@reyaxyz/sdk 0.132.5 → 0.133.0

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.
package/README.md CHANGED
@@ -6,5 +6,5 @@
6
6
 
7
7
  | Statements | Branches | Functions | Lines |
8
8
  | --------------------------- | ----------------------- | ------------------------- | ----------------- |
9
- | ![Statements](https://img.shields.io/badge/statements-8.24%25-red.svg?style=flat) | ![Branches](https://img.shields.io/badge/branches-4.3%25-red.svg?style=flat) | ![Functions](https://img.shields.io/badge/functions-3.84%25-red.svg?style=flat) | ![Lines](https://img.shields.io/badge/lines-7.91%25-red.svg?style=flat) |
9
+ | ![Statements](https://img.shields.io/badge/statements-9.16%25-red.svg?style=flat) | ![Branches](https://img.shields.io/badge/branches-5.75%25-red.svg?style=flat) | ![Functions](https://img.shields.io/badge/functions-4.1%25-red.svg?style=flat) | ![Lines](https://img.shields.io/badge/lines-8.81%25-red.svg?style=flat) |
10
10
 
@@ -40,7 +40,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
40
40
  };
41
41
  Object.defineProperty(exports, "__esModule", { value: true });
42
42
  exports.closeOrder = exports.matchOrder = void 0;
43
- var encode_1 = require("./encode");
44
43
  var signAndBroadcastTransaction_1 = require("../signAndBroadcastTransaction");
45
44
  var common_1 = require("@reyaxyz/common");
46
45
  var bignumber_js_1 = __importDefault(require("bignumber.js"));
@@ -89,66 +88,7 @@ var executeMarketOrderViaOrdersGateway = function (params) { return __awaiter(vo
89
88
  }
90
89
  });
91
90
  }); };
92
- var matchOrderV1 = function (params) { return __awaiter(void 0, void 0, void 0, function () {
93
- var snappedAmount, orderBaseE18, slippageFactor, orderPriceLimitE18, chainId, _a, data, eip712Payload, eip712Signature, result;
94
- var _b, _c, _d, _e, _f, _g;
95
- return __generator(this, function (_h) {
96
- switch (_h.label) {
97
- case 0:
98
- console.log('match order execution v1');
99
- if (params.amountInBase === 0) {
100
- throw new Error('Order cannot be of size zero.');
101
- }
102
- snappedAmount = (0, bignumber_js_1.default)(params.amountInBase)
103
- .abs()
104
- .dividedBy(params.market.baseSpacing)
105
- .integerValue(bignumber_js_1.default.ROUND_FLOOR)
106
- .multipliedBy(params.market.baseSpacing)
107
- .toNumber();
108
- if (params.amountInBase < 0) {
109
- snappedAmount = -snappedAmount;
110
- }
111
- if (Math.abs(snappedAmount) < params.market.minOrderSizeBase) {
112
- console.error("Minimum trade amount ".concat(params.market.minOrderSizeBase, ". Entered amount ").concat(snappedAmount, ", ").concat(params.amountInBase));
113
- throw new Error("Minimum trade amount ".concat(params.market.minOrderSizeBase));
114
- }
115
- orderBaseE18 = (0, common_3.scale)(18)(snappedAmount);
116
- slippageFactor = 40;
117
- orderPriceLimitE18 = (0, common_1.calculatePriceLimitForTrade)(params.market.currentPrice, snappedAmount, slippageFactor);
118
- chainId = (0, network_1.getReyaNetwork)();
119
- return [4 /*yield*/, (0, encode_1.encodeMatchOrder)(params.signer, chainId, params.owner.coreSigNonce, params.marginAccountId, orderBaseE18, orderPriceLimitE18, params.market.counterpartyAccountIds, params.market.id, params.market.exchangeId)];
120
- case 1:
121
- _a = _h.sent(), data = _a.calldata, eip712Payload = _a.payload, eip712Signature = _a.signature;
122
- return [4 /*yield*/, (0, signAndBroadcastTransaction_1.signAndBroadcastTransaction)(data, chainId, common_2.ContractType.PERIPHERY_PROXY, {
123
- action: 'matchOrder',
124
- accountId: params.marginAccountId,
125
- marketId: params.market.id,
126
- tradeSource: params.tradeSource,
127
- matchOrder: {
128
- userEIP712Signature: eip712Signature,
129
- eip712Payload: eip712Payload,
130
- },
131
- })];
132
- case 2:
133
- result = _h.sent();
134
- return [2 /*return*/, {
135
- transactionHash: (result === null || result === void 0 ? void 0 : result.txHash) || null,
136
- coreSigNonce: Number(result === null || result === void 0 ? void 0 : result.coreSigNonce) || null,
137
- xpBoost: ((_b = result.miscellaneous) === null || _b === void 0 ? void 0 : _b.tradeXpBoost) || 0,
138
- lotteryXpBoost: ((_c = result.miscellaneous) === null || _c === void 0 ? void 0 : _c.lotteryXpBoost) || 0,
139
- isNftWon: ((_d = result.miscellaneous) === null || _d === void 0 ? void 0 : _d.xpNftAwarded) || false,
140
- marginAccountId: params.marginAccountId,
141
- xpEarned: ((_e = result.miscellaneous) === null || _e === void 0 ? void 0 : _e.xpEarned) || 0,
142
- executionPrice: ((_f = result.tradeDetails) === null || _f === void 0 ? void 0 : _f.executionPrice) || 0,
143
- base: ((_g = result.tradeDetails) === null || _g === void 0 ? void 0 : _g.base) || 0,
144
- positions: result.positions,
145
- orders: result.orders,
146
- accounts: result.accounts,
147
- }];
148
- }
149
- });
150
- }); };
151
- var matchOrderV2 = function (params) { return __awaiter(void 0, void 0, void 0, function () {
91
+ var matchOrder = function (params) { return __awaiter(void 0, void 0, void 0, function () {
152
92
  var snappedAmount, orderBaseE18, slippageFactor, orderPriceLimitE18, result;
153
93
  var _a, _b, _c, _d, _e, _f;
154
94
  return __generator(this, function (_g) {
@@ -206,75 +146,8 @@ var matchOrderV2 = function (params) { return __awaiter(void 0, void 0, void 0,
206
146
  }
207
147
  });
208
148
  }); };
209
- var matchOrder = function (params) { return __awaiter(void 0, void 0, void 0, function () {
210
- var isMatchOrderV2;
211
- return __generator(this, function (_a) {
212
- isMatchOrderV2 = process.env.MATCH_ORDER_VIA_ORDERS_GATEWAY_ENABLED === 'true' || false;
213
- if (isMatchOrderV2) {
214
- return [2 /*return*/, matchOrderV2(params)];
215
- }
216
- return [2 /*return*/, matchOrderV1(params)];
217
- });
218
- }); };
219
149
  exports.matchOrder = matchOrder;
220
- var closeOrderV1 = function (params) { return __awaiter(void 0, void 0, void 0, function () {
221
- var closingBase, slippageFactor, orderPriceLimitE18, chainId, _a, data, eip712Payload, eip712Signature, result;
222
- var _b, _c, _d, _e, _f, _g;
223
- return __generator(this, function (_h) {
224
- switch (_h.label) {
225
- case 0:
226
- console.log('close order execution v1');
227
- if (params.orderBase === 0) {
228
- throw new Error('Position is already closed.');
229
- }
230
- closingBase = 0;
231
- if (params.type === 'full') {
232
- closingBase = params.orderBase;
233
- }
234
- else {
235
- closingBase = params.closingOrderBase;
236
- if (closingBase === 0) {
237
- throw new Error('Specified base to close is zero.');
238
- }
239
- if (closingBase * params.orderBase < 0) {
240
- throw new Error('Specified base to close is in different direction that the actual order.');
241
- }
242
- if (Math.abs(closingBase) > Math.abs(params.orderBase)) {
243
- throw new Error('Specified base to close is larger than the actual order.');
244
- }
245
- }
246
- slippageFactor = 40;
247
- orderPriceLimitE18 = (0, common_1.calculatePriceLimitForTrade)(params.market.currentPrice, -closingBase, slippageFactor);
248
- chainId = (0, network_1.getReyaNetwork)();
249
- return [4 /*yield*/, (0, encode_1.encodeMatchOrder)(params.signer, chainId, params.owner.coreSigNonce, params.marginAccountId, -(0, common_3.scale)(18)(closingBase), orderPriceLimitE18, params.market.counterpartyAccountIds, params.market.id, params.market.exchangeId)];
250
- case 1:
251
- _a = _h.sent(), data = _a.calldata, eip712Payload = _a.payload, eip712Signature = _a.signature;
252
- return [4 /*yield*/, (0, signAndBroadcastTransaction_1.signAndBroadcastTransaction)(data, chainId, common_2.ContractType.PERIPHERY_PROXY, {
253
- action: 'closeOrder',
254
- accountId: params.marginAccountId,
255
- marketId: params.market.id,
256
- matchOrder: {
257
- userEIP712Signature: eip712Signature,
258
- eip712Payload: eip712Payload,
259
- },
260
- })];
261
- case 2:
262
- result = _h.sent();
263
- return [2 /*return*/, {
264
- transactionHash: (result === null || result === void 0 ? void 0 : result.txHash) || null,
265
- coreSigNonce: Number(result === null || result === void 0 ? void 0 : result.coreSigNonce) || null,
266
- xpBoost: ((_b = result.miscellaneous) === null || _b === void 0 ? void 0 : _b.tradeXpBoost) || 0,
267
- lotteryXpBoost: ((_c = result.miscellaneous) === null || _c === void 0 ? void 0 : _c.lotteryXpBoost) || 0,
268
- isNftWon: ((_d = result.miscellaneous) === null || _d === void 0 ? void 0 : _d.xpNftAwarded) || false,
269
- marginAccountId: params.marginAccountId,
270
- xpEarned: ((_e = result.miscellaneous) === null || _e === void 0 ? void 0 : _e.xpEarned) || 0,
271
- executionPrice: ((_f = result.tradeDetails) === null || _f === void 0 ? void 0 : _f.executionPrice) || 0,
272
- base: ((_g = result.tradeDetails) === null || _g === void 0 ? void 0 : _g.base) || 0,
273
- }];
274
- }
275
- });
276
- }); };
277
- var closeOrderV2 = function (params) { return __awaiter(void 0, void 0, void 0, function () {
150
+ var closeOrder = function (params) { return __awaiter(void 0, void 0, void 0, function () {
278
151
  var closingBase, slippageFactor, orderPriceLimit, result;
279
152
  var _a, _b, _c, _d, _e, _f;
280
153
  return __generator(this, function (_g) {
@@ -330,15 +203,5 @@ var closeOrderV2 = function (params) { return __awaiter(void 0, void 0, void 0,
330
203
  }
331
204
  });
332
205
  }); };
333
- var closeOrder = function (params) { return __awaiter(void 0, void 0, void 0, function () {
334
- var isCloseOrderV2;
335
- return __generator(this, function (_a) {
336
- isCloseOrderV2 = process.env.CLOSE_ORDER_VIA_ORDERS_GATEWAY_ENABLED === 'true' || false;
337
- if (isCloseOrderV2) {
338
- return [2 /*return*/, closeOrderV2(params)];
339
- }
340
- return [2 /*return*/, closeOrderV1(params)];
341
- });
342
- }); };
343
206
  exports.closeOrder = closeOrder;
344
207
  //# sourceMappingURL=order.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"order.js","sourceRoot":"/","sources":["services/orders/order.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,mCAA4C;AAC5C,8EAA6E;AAC7E,0CAOyB;AACzB,8DAAqC;AACrC,0CAA+C;AAC/C,0CAAwC;AACxC,+CAAqD;AACrD,iCAA6C;AAE7C,IAAM,kCAAkC,GAAG,UACzC,MAAsC;;;;;gBAEhC,MAAM,GAAG,iBAAQ,CAAC,eAAe,EAAE,CAAC,MAAM,CAC9C,CAAC,QAAQ,EAAE,SAAS,CAAC,EACrB,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,MAAM,CAAC,KAAK,CAAC,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M,CAAC,eAAe;wBACvC,QAAQ,EAAE,CAAA,MAAA,MAAM,CAAC,aAAa,0CAAE,QAAQ,KAAI,CAAC;wBAC7C,cAAc,EAAE,CAAA,MAAA,MAAM,CAAC,YAAY,0CAAE,cAAc,KAAI,CAAC;wBACxD,IAAI,EAAE,CAAA,MAAA,MAAM,CAAC,YAAY,0CAAE,IAAI,KAAI,CAAC;qBACrC,EAAC;;;KACH,CAAC;AAEK,IAAM,UAAU,GAAG,UACxB,MAAwB;;;QAElB,cAAc,GAClB,OAAO,CAAC,GAAG,CAAC,sCAAsC,KAAK,MAAM,IAAI,KAAK,CAAC;QAEzE,IAAI,cAAc,EAAE,CAAC;YACnB,sBAAO,YAAY,CAAC,MAAM,CAAC,EAAC;QAC9B,CAAC;QAED,sBAAO,YAAY,CAAC,MAAM,CAAC,EAAC;;KAC7B,CAAC;AAXW,QAAA,UAAU,cAWrB","sourcesContent":["import {\n CloseOrderParams,\n CloseOrderResult,\n MatchOrderParams,\n MatchOrderResult,\n OrdersGatewayMarketOrderParams,\n} from './types';\nimport { encodeMatchOrder } from './encode';\nimport { signAndBroadcastTransaction } from '../signAndBroadcastTransaction';\nimport {\n calculatePriceLimitForTrade,\n ORDERS_GATEWAY_DEADLINE_IN_SECONDS,\n OrdersGatewayAbi,\n OrdersGatewayOrderType,\n signOrdersGatewayOrder,\n TransactionExecutionOutput,\n} from '@reyaxyz/common';\nimport BigNumber from 'bignumber.js';\nimport { ContractType } from '@reyaxyz/common';\nimport { scale } from '@reyaxyz/common';\nimport { getReyaNetwork } from '../../utils/network';\nimport { AbiCoder, Interface } from 'ethers';\n\nconst executeMarketOrderViaOrdersGateway = async (\n params: OrdersGatewayMarketOrderParams,\n): Promise<TransactionExecutionOutput> => {\n const inputs = AbiCoder.defaultAbiCoder().encode(\n ['int256', 'uint256'],\n [params.order.baseE18, params.order.priceLimitE18],\n );\n\n const reyaChainId = getReyaNetwork();\n const creationTimestampMs = Date.now();\n const creationTimestampSeconds = Math.floor(creationTimestampMs / 1000);\n\n const { signature, nonce } = await signOrdersGatewayOrder(\n params.signer,\n reyaChainId,\n params.marginAccountId,\n params.marketId,\n params.exchangeId,\n params.counterpartyAccountIds,\n params.order.type,\n inputs,\n creationTimestampSeconds + ORDERS_GATEWAY_DEADLINE_IN_SECONDS,\n creationTimestampMs,\n );\n\n const fnSig = 'execute';\n const fnArgs = [\n [\n params.marginAccountId,\n params.marketId,\n params.exchangeId,\n params.counterpartyAccountIds,\n params.order.type,\n inputs,\n await params.signer.getAddress(),\n nonce,\n ],\n [signature.v, signature.r, signature.s, signature.deadline],\n ];\n\n const ogInterface = new Interface(OrdersGatewayAbi);\n const data = ogInterface.encodeFunctionData(fnSig, fnArgs);\n\n const result = await signAndBroadcastTransaction(\n data,\n reyaChainId,\n ContractType.ORDERS_GATEWAY_PROXY,\n {\n accountId: params.marginAccountId,\n marketId: params.marketId,\n tradeSource: params.tradeSource,\n },\n );\n\n return result;\n};\n\nconst matchOrderV1 = async (\n params: MatchOrderParams,\n): Promise<MatchOrderResult> => {\n console.log('match order execution v1');\n\n if (params.amountInBase === 0) {\n throw new Error('Order cannot be of size zero.');\n }\n\n let snappedAmount = BigNumber(params.amountInBase)\n .abs()\n .dividedBy(params.market.baseSpacing)\n .integerValue(BigNumber.ROUND_FLOOR)\n .multipliedBy(params.market.baseSpacing)\n .toNumber();\n\n if (params.amountInBase < 0) {\n snappedAmount = -snappedAmount;\n }\n\n if (Math.abs(snappedAmount) < params.market.minOrderSizeBase) {\n console.error(\n `Minimum trade amount ${params.market.minOrderSizeBase}. Entered amount ${snappedAmount}, ${params.amountInBase}`,\n );\n throw new Error(`Minimum trade amount ${params.market.minOrderSizeBase}`);\n }\n\n const orderBaseE18 = scale(18)(snappedAmount);\n const slippageFactor = 40; // 2.5%\n const orderPriceLimitE18 = calculatePriceLimitForTrade(\n params.market.currentPrice,\n snappedAmount,\n slippageFactor,\n );\n\n const chainId = getReyaNetwork();\n\n const {\n calldata: data,\n payload: eip712Payload,\n signature: eip712Signature,\n } = await encodeMatchOrder(\n params.signer,\n chainId,\n params.owner.coreSigNonce,\n params.marginAccountId,\n orderBaseE18,\n orderPriceLimitE18,\n params.market.counterpartyAccountIds,\n params.market.id,\n params.market.exchangeId,\n );\n\n const result = await signAndBroadcastTransaction(\n data,\n chainId,\n ContractType.PERIPHERY_PROXY,\n {\n action: 'matchOrder',\n accountId: params.marginAccountId,\n marketId: params.market.id,\n tradeSource: params.tradeSource,\n matchOrder: {\n userEIP712Signature: eip712Signature,\n eip712Payload,\n },\n },\n );\n\n return {\n transactionHash: result?.txHash || null,\n coreSigNonce: Number(result?.coreSigNonce) || null,\n xpBoost: result.miscellaneous?.tradeXpBoost || 0,\n lotteryXpBoost: result.miscellaneous?.lotteryXpBoost || 0,\n isNftWon: result.miscellaneous?.xpNftAwarded || false,\n marginAccountId: params.marginAccountId,\n xpEarned: result.miscellaneous?.xpEarned || 0,\n executionPrice: result.tradeDetails?.executionPrice || 0,\n base: result.tradeDetails?.base || 0,\n positions: result.positions,\n orders: result.orders,\n accounts: result.accounts,\n };\n};\n\nconst matchOrderV2 = async (\n params: MatchOrderParams,\n): Promise<MatchOrderResult> => {\n console.log('match order execution v2');\n\n if (params.amountInBase === 0) {\n throw new Error('Order cannot be of size zero.');\n }\n\n let snappedAmount = BigNumber(params.amountInBase)\n .abs()\n .dividedBy(params.market.baseSpacing)\n .integerValue(BigNumber.ROUND_FLOOR)\n .multipliedBy(params.market.baseSpacing)\n .toNumber();\n\n if (params.amountInBase < 0) {\n snappedAmount = -snappedAmount;\n }\n\n if (Math.abs(snappedAmount) < params.market.minOrderSizeBase) {\n console.error(\n `Minimum trade amount ${params.market.minOrderSizeBase}. Entered amount ${snappedAmount}, ${params.amountInBase}`,\n );\n throw new Error(`Minimum trade amount ${params.market.minOrderSizeBase}`);\n }\n\n const orderBaseE18 = scale(18)(snappedAmount);\n const slippageFactor = 40; // 2.5%\n const orderPriceLimitE18 = calculatePriceLimitForTrade(\n params.market.currentPrice,\n snappedAmount,\n slippageFactor,\n );\n\n const result = await executeMarketOrderViaOrdersGateway({\n signer: params.signer,\n marginAccountId: params.marginAccountId,\n counterpartyAccountIds: params.market.counterpartyAccountIds,\n marketId: params.market.id,\n exchangeId: params.market.exchangeId,\n tradeSource: params.tradeSource,\n order: {\n baseE18: orderBaseE18,\n priceLimitE18: orderPriceLimitE18,\n type: OrdersGatewayOrderType.MARKET_ORDER,\n },\n });\n\n return {\n transactionHash: result?.txHash || null,\n coreSigNonce: Number(result?.coreSigNonce) || null,\n xpBoost: result.miscellaneous?.tradeXpBoost || 0,\n lotteryXpBoost: result.miscellaneous?.lotteryXpBoost || 0,\n isNftWon: result.miscellaneous?.xpNftAwarded || false,\n marginAccountId: params.marginAccountId,\n xpEarned: result.miscellaneous?.xpEarned || 0,\n executionPrice: result.tradeDetails?.executionPrice || 0,\n base: result.tradeDetails?.base || 0,\n positions: result.positions,\n orders: result.orders,\n accounts: result.accounts,\n };\n};\n\nexport const matchOrder = async (\n params: MatchOrderParams,\n): Promise<MatchOrderResult> => {\n const isMatchOrderV2 =\n process.env.MATCH_ORDER_VIA_ORDERS_GATEWAY_ENABLED === 'true' || false;\n\n if (isMatchOrderV2) {\n return matchOrderV2(params);\n }\n\n return matchOrderV1(params);\n};\n\nconst closeOrderV1 = async (\n params: CloseOrderParams,\n): Promise<CloseOrderResult> => {\n console.log('close order execution v1');\n\n if (params.orderBase === 0) {\n throw new Error('Position is already closed.');\n }\n\n let closingBase: number = 0;\n if (params.type === 'full') {\n closingBase = params.orderBase;\n } else {\n closingBase = params.closingOrderBase;\n\n if (closingBase === 0) {\n throw new Error('Specified base to close is zero.');\n }\n\n if (closingBase * params.orderBase < 0) {\n throw new Error(\n 'Specified base to close is in different direction that the actual order.',\n );\n }\n\n if (Math.abs(closingBase) > Math.abs(params.orderBase)) {\n throw new Error(\n 'Specified base to close is larger than the actual order.',\n );\n }\n }\n\n const slippageFactor = 40; // 2.5%\n const orderPriceLimitE18 = calculatePriceLimitForTrade(\n params.market.currentPrice,\n -closingBase,\n slippageFactor,\n );\n\n const chainId = getReyaNetwork();\n const {\n calldata: data,\n payload: eip712Payload,\n signature: eip712Signature,\n } = await encodeMatchOrder(\n params.signer,\n chainId,\n params.owner.coreSigNonce,\n params.marginAccountId,\n -scale(18)(closingBase),\n orderPriceLimitE18,\n params.market.counterpartyAccountIds,\n params.market.id,\n params.market.exchangeId,\n );\n\n const result = await signAndBroadcastTransaction(\n data,\n chainId,\n ContractType.PERIPHERY_PROXY,\n {\n action: 'closeOrder',\n accountId: params.marginAccountId,\n marketId: params.market.id,\n matchOrder: {\n userEIP712Signature: eip712Signature,\n eip712Payload,\n },\n },\n );\n\n return {\n transactionHash: result?.txHash || null,\n coreSigNonce: Number(result?.coreSigNonce) || null,\n xpBoost: result.miscellaneous?.tradeXpBoost || 0,\n lotteryXpBoost: result.miscellaneous?.lotteryXpBoost || 0,\n isNftWon: result.miscellaneous?.xpNftAwarded || false,\n marginAccountId: params.marginAccountId,\n xpEarned: result.miscellaneous?.xpEarned || 0,\n executionPrice: result.tradeDetails?.executionPrice || 0,\n base: result.tradeDetails?.base || 0,\n };\n};\n\nconst closeOrderV2 = async (\n params: CloseOrderParams,\n): Promise<CloseOrderResult> => {\n console.log('close order execution v2');\n\n if (params.orderBase === 0) {\n throw new Error('Position is already closed.');\n }\n\n let closingBase: number = 0;\n if (params.type === 'full') {\n closingBase = params.orderBase;\n } else {\n closingBase = params.closingOrderBase;\n\n if (closingBase === 0) {\n throw new Error('Specified base to close is zero.');\n }\n\n if (closingBase * params.orderBase < 0) {\n throw new Error(\n 'Specified base to close is in different direction that the actual order.',\n );\n }\n\n if (Math.abs(closingBase) > Math.abs(params.orderBase)) {\n throw new Error(\n 'Specified base to close is larger than the actual order.',\n );\n }\n }\n\n const slippageFactor = 40; // 2.5%\n const orderPriceLimit = calculatePriceLimitForTrade(\n params.market.currentPrice,\n -closingBase,\n slippageFactor,\n );\n\n const result = await executeMarketOrderViaOrdersGateway({\n signer: params.signer,\n marginAccountId: params.marginAccountId,\n counterpartyAccountIds: params.market.counterpartyAccountIds,\n marketId: params.market.id,\n exchangeId: params.market.exchangeId,\n order: {\n baseE18: -scale(18)(closingBase),\n priceLimitE18: orderPriceLimit,\n type: OrdersGatewayOrderType.REDUCE_ONLY_MARKET_ORDER,\n },\n });\n\n return {\n transactionHash: result?.txHash || null,\n coreSigNonce: Number(result?.coreSigNonce) || null,\n xpBoost: result.miscellaneous?.tradeXpBoost || 0,\n lotteryXpBoost: result.miscellaneous?.lotteryXpBoost || 0,\n isNftWon: result.miscellaneous?.xpNftAwarded || false,\n marginAccountId: params.marginAccountId,\n xpEarned: result.miscellaneous?.xpEarned || 0,\n executionPrice: result.tradeDetails?.executionPrice || 0,\n base: result.tradeDetails?.base || 0,\n };\n};\n\nexport const closeOrder = async (\n params: CloseOrderParams,\n): Promise<CloseOrderResult> => {\n const isCloseOrderV2 =\n process.env.CLOSE_ORDER_VIA_ORDERS_GATEWAY_ENABLED === 'true' || false;\n\n if (isCloseOrderV2) {\n return closeOrderV2(params);\n }\n\n return closeOrderV1(params);\n};\n"]}
1
+ {"version":3,"file":"order.js","sourceRoot":"/","sources":["services/orders/order.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,8EAA6E;AAC7E,0CAOyB;AACzB,8DAAqC;AACrC,0CAA+C;AAC/C,0CAAwC;AACxC,+CAAqD;AACrD,iCAA6C;AAE7C,IAAM,kCAAkC,GAAG,UACzC,MAAsC;;;;;gBAEhC,MAAM,GAAG,iBAAQ,CAAC,eAAe,EAAE,CAAC,MAAM,CAC9C,CAAC,QAAQ,EAAE,SAAS,CAAC,EACrB,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,MAAM,CAAC,KAAK,CAAC,aAAa,CAAC,CACnD,CAAC;gBAEI,WAAW,GAAG,IAAA,wBAAc,GAAE,CAAC;gBAC/B,mBAAmB,GAAG,IAAI,CAAC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M,CAAC,UAAU;wBACpC,KAAK,EAAE;4BACL,OAAO,EAAE,CAAC,IAAA,cAAK,EAAC,EAAE,CAAC,CAAC,WAAW,CAAC;4BAChC,aAAa,EAAE,eAAe;4BAC9B,IAAI,EAAE,+BAAsB,CAAC,wBAAwB;yBACtD;qBACF,CAAC,EAAA;;gBAXI,MAAM,GAAG,SAWb;gBAEF,sBAAO;wBACL,eAAe,EAAE,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,MAAM,KAAI,IAAI;wBACvC,YAAY,EAAE,MAAM,CAAC,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,YAAY,CAAC,IAAI,IAAI;wBAClD,OAAO,EAAE,CAAA,MAAA,MAAM,CAAC,aAAa,0CAAE,YAAY,KAAI,CAAC;wBAChD,cAAc,EAAE,CAAA,MAAA,MAAM,CAAC,aAAa,0CAAE,cAAc,KAAI,CAAC;wBACzD,QAAQ,EAAE,CAAA,MAAA,MAAM,CAAC,aAAa,0CAAE,YAAY,KAAI,KAAK;wBACrD,eAAe,EAAE,MAAM,CAAC,eAAe;wBACvC,QAAQ,EAAE,CAAA,MAAA,MAAM,CAAC,aAAa,0CAAE,QAAQ,KAAI,CAAC;wBAC7C,cAAc,EAAE,CAAA,MAAA,MAAM,CAAC,YAAY,0CAAE,cAAc,KAAI,CAAC;wBACxD,IAAI,EAAE,CAAA,MAAA,MAAM,CAAC,YAAY,0CAAE,IAAI,KAAI,CAAC;qBACrC,EAAC;;;KACH,CAAC;AA/DW,QAAA,UAAU,cA+DrB","sourcesContent":["import {\n CloseOrderParams,\n CloseOrderResult,\n MatchOrderParams,\n MatchOrderResult,\n OrdersGatewayMarketOrderParams,\n} from './types';\nimport { signAndBroadcastTransaction } from '../signAndBroadcastTransaction';\nimport {\n calculatePriceLimitForTrade,\n ORDERS_GATEWAY_DEADLINE_IN_SECONDS,\n OrdersGatewayAbi,\n OrdersGatewayOrderType,\n signOrdersGatewayOrder,\n TransactionExecutionOutput,\n} from '@reyaxyz/common';\nimport BigNumber from 'bignumber.js';\nimport { ContractType } from '@reyaxyz/common';\nimport { scale } from '@reyaxyz/common';\nimport { getReyaNetwork } from '../../utils/network';\nimport { AbiCoder, Interface } from 'ethers';\n\nconst executeMarketOrderViaOrdersGateway = async (\n params: OrdersGatewayMarketOrderParams,\n): Promise<TransactionExecutionOutput> => {\n const inputs = AbiCoder.defaultAbiCoder().encode(\n ['int256', 'uint256'],\n [params.order.baseE18, params.order.priceLimitE18],\n );\n\n const reyaChainId = getReyaNetwork();\n const creationTimestampMs = Date.now();\n const creationTimestampSeconds = Math.floor(creationTimestampMs / 1000);\n\n const { signature, nonce } = await signOrdersGatewayOrder(\n params.signer,\n reyaChainId,\n params.marginAccountId,\n params.marketId,\n params.exchangeId,\n params.counterpartyAccountIds,\n params.order.type,\n inputs,\n creationTimestampSeconds + ORDERS_GATEWAY_DEADLINE_IN_SECONDS,\n creationTimestampMs,\n );\n\n const fnSig = 'execute';\n const fnArgs = [\n [\n params.marginAccountId,\n params.marketId,\n params.exchangeId,\n params.counterpartyAccountIds,\n params.order.type,\n inputs,\n await params.signer.getAddress(),\n nonce,\n ],\n [signature.v, signature.r, signature.s, signature.deadline],\n ];\n\n const ogInterface = new Interface(OrdersGatewayAbi);\n const data = ogInterface.encodeFunctionData(fnSig, fnArgs);\n\n const result = await signAndBroadcastTransaction(\n data,\n reyaChainId,\n ContractType.ORDERS_GATEWAY_PROXY,\n {\n accountId: params.marginAccountId,\n marketId: params.marketId,\n tradeSource: params.tradeSource,\n },\n );\n\n return result;\n};\n\nexport const matchOrder = async (\n params: MatchOrderParams,\n): Promise<MatchOrderResult> => {\n console.log('match order execution v2');\n\n if (params.amountInBase === 0) {\n throw new Error('Order cannot be of size zero.');\n }\n\n let snappedAmount = BigNumber(params.amountInBase)\n .abs()\n .dividedBy(params.market.baseSpacing)\n .integerValue(BigNumber.ROUND_FLOOR)\n .multipliedBy(params.market.baseSpacing)\n .toNumber();\n\n if (params.amountInBase < 0) {\n snappedAmount = -snappedAmount;\n }\n\n if (Math.abs(snappedAmount) < params.market.minOrderSizeBase) {\n console.error(\n `Minimum trade amount ${params.market.minOrderSizeBase}. Entered amount ${snappedAmount}, ${params.amountInBase}`,\n );\n throw new Error(`Minimum trade amount ${params.market.minOrderSizeBase}`);\n }\n\n const orderBaseE18 = scale(18)(snappedAmount);\n const slippageFactor = 40; // 2.5%\n const orderPriceLimitE18 = calculatePriceLimitForTrade(\n params.market.currentPrice,\n snappedAmount,\n slippageFactor,\n );\n\n const result = await executeMarketOrderViaOrdersGateway({\n signer: params.signer,\n marginAccountId: params.marginAccountId,\n counterpartyAccountIds: params.market.counterpartyAccountIds,\n marketId: params.market.id,\n exchangeId: params.market.exchangeId,\n tradeSource: params.tradeSource,\n order: {\n baseE18: orderBaseE18,\n priceLimitE18: orderPriceLimitE18,\n type: OrdersGatewayOrderType.MARKET_ORDER,\n },\n });\n\n return {\n transactionHash: result?.txHash || null,\n coreSigNonce: Number(result?.coreSigNonce) || null,\n xpBoost: result.miscellaneous?.tradeXpBoost || 0,\n lotteryXpBoost: result.miscellaneous?.lotteryXpBoost || 0,\n isNftWon: result.miscellaneous?.xpNftAwarded || false,\n marginAccountId: params.marginAccountId,\n xpEarned: result.miscellaneous?.xpEarned || 0,\n executionPrice: result.tradeDetails?.executionPrice || 0,\n base: result.tradeDetails?.base || 0,\n positions: result.positions,\n orders: result.orders,\n accounts: result.accounts,\n };\n};\n\nexport const closeOrder = async (\n params: CloseOrderParams,\n): Promise<CloseOrderResult> => {\n console.log('close order execution v2');\n\n if (params.orderBase === 0) {\n throw new Error('Position is already closed.');\n }\n\n let closingBase: number = 0;\n if (params.type === 'full') {\n closingBase = params.orderBase;\n } else {\n closingBase = params.closingOrderBase;\n\n if (closingBase === 0) {\n throw new Error('Specified base to close is zero.');\n }\n\n if (closingBase * params.orderBase < 0) {\n throw new Error(\n 'Specified base to close is in different direction that the actual order.',\n );\n }\n\n if (Math.abs(closingBase) > Math.abs(params.orderBase)) {\n throw new Error(\n 'Specified base to close is larger than the actual order.',\n );\n }\n }\n\n const slippageFactor = 40; // 2.5%\n const orderPriceLimit = calculatePriceLimitForTrade(\n params.market.currentPrice,\n -closingBase,\n slippageFactor,\n );\n\n const result = await executeMarketOrderViaOrdersGateway({\n signer: params.signer,\n marginAccountId: params.marginAccountId,\n counterpartyAccountIds: params.market.counterpartyAccountIds,\n marketId: params.market.id,\n exchangeId: params.market.exchangeId,\n order: {\n baseE18: -scale(18)(closingBase),\n priceLimitE18: orderPriceLimit,\n type: OrdersGatewayOrderType.REDUCE_ONLY_MARKET_ORDER,\n },\n });\n\n return {\n transactionHash: result?.txHash || null,\n coreSigNonce: Number(result?.coreSigNonce) || null,\n xpBoost: result.miscellaneous?.tradeXpBoost || 0,\n lotteryXpBoost: result.miscellaneous?.lotteryXpBoost || 0,\n isNftWon: result.miscellaneous?.xpNftAwarded || false,\n marginAccountId: params.marginAccountId,\n xpEarned: result.miscellaneous?.xpEarned || 0,\n executionPrice: result.tradeDetails?.executionPrice || 0,\n base: result.tradeDetails?.base || 0,\n };\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"order.d.ts","sourceRoot":"/","sources":["services/orders/order.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAEjB,MAAM,SAAS,CAAC;AAgOjB,eAAO,MAAM,UAAU,WACb,gBAAgB,KACvB,QAAQ,gBAAgB,CAS1B,CAAC;AAuJF,eAAO,MAAM,UAAU,WACb,gBAAgB,KACvB,QAAQ,gBAAgB,CAS1B,CAAC"}
1
+ {"version":3,"file":"order.d.ts","sourceRoot":"/","sources":["services/orders/order.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAEjB,MAAM,SAAS,CAAC;AAyEjB,eAAO,MAAM,UAAU,WACb,gBAAgB,KACvB,QAAQ,gBAAgB,CA6D1B,CAAC;AAEF,eAAO,MAAM,UAAU,WACb,gBAAgB,KACvB,QAAQ,gBAAgB,CA6D1B,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reyaxyz/sdk",
3
- "version": "0.132.5",
3
+ "version": "0.133.0",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "registry": "https://registry.npmjs.org"
@@ -35,5 +35,5 @@
35
35
  "ethers": "6.9.0"
36
36
  },
37
37
  "packageManager": "pnpm@8.3.1",
38
- "gitHead": "6e76e8b709722c3ebee4c6eb81abead9e22fdfe4"
38
+ "gitHead": "53d7a2716e941f32487aecdd03e3d57fbaea5d97"
39
39
  }
@@ -5,7 +5,6 @@ import {
5
5
  MatchOrderResult,
6
6
  OrdersGatewayMarketOrderParams,
7
7
  } from './types';
8
- import { encodeMatchOrder } from './encode';
9
8
  import { signAndBroadcastTransaction } from '../signAndBroadcastTransaction';
10
9
  import {
11
10
  calculatePriceLimitForTrade,
@@ -78,92 +77,7 @@ const executeMarketOrderViaOrdersGateway = async (
78
77
  return result;
79
78
  };
80
79
 
81
- const matchOrderV1 = async (
82
- params: MatchOrderParams,
83
- ): Promise<MatchOrderResult> => {
84
- console.log('match order execution v1');
85
-
86
- if (params.amountInBase === 0) {
87
- throw new Error('Order cannot be of size zero.');
88
- }
89
-
90
- let snappedAmount = BigNumber(params.amountInBase)
91
- .abs()
92
- .dividedBy(params.market.baseSpacing)
93
- .integerValue(BigNumber.ROUND_FLOOR)
94
- .multipliedBy(params.market.baseSpacing)
95
- .toNumber();
96
-
97
- if (params.amountInBase < 0) {
98
- snappedAmount = -snappedAmount;
99
- }
100
-
101
- if (Math.abs(snappedAmount) < params.market.minOrderSizeBase) {
102
- console.error(
103
- `Minimum trade amount ${params.market.minOrderSizeBase}. Entered amount ${snappedAmount}, ${params.amountInBase}`,
104
- );
105
- throw new Error(`Minimum trade amount ${params.market.minOrderSizeBase}`);
106
- }
107
-
108
- const orderBaseE18 = scale(18)(snappedAmount);
109
- const slippageFactor = 40; // 2.5%
110
- const orderPriceLimitE18 = calculatePriceLimitForTrade(
111
- params.market.currentPrice,
112
- snappedAmount,
113
- slippageFactor,
114
- );
115
-
116
- const chainId = getReyaNetwork();
117
-
118
- const {
119
- calldata: data,
120
- payload: eip712Payload,
121
- signature: eip712Signature,
122
- } = await encodeMatchOrder(
123
- params.signer,
124
- chainId,
125
- params.owner.coreSigNonce,
126
- params.marginAccountId,
127
- orderBaseE18,
128
- orderPriceLimitE18,
129
- params.market.counterpartyAccountIds,
130
- params.market.id,
131
- params.market.exchangeId,
132
- );
133
-
134
- const result = await signAndBroadcastTransaction(
135
- data,
136
- chainId,
137
- ContractType.PERIPHERY_PROXY,
138
- {
139
- action: 'matchOrder',
140
- accountId: params.marginAccountId,
141
- marketId: params.market.id,
142
- tradeSource: params.tradeSource,
143
- matchOrder: {
144
- userEIP712Signature: eip712Signature,
145
- eip712Payload,
146
- },
147
- },
148
- );
149
-
150
- return {
151
- transactionHash: result?.txHash || null,
152
- coreSigNonce: Number(result?.coreSigNonce) || null,
153
- xpBoost: result.miscellaneous?.tradeXpBoost || 0,
154
- lotteryXpBoost: result.miscellaneous?.lotteryXpBoost || 0,
155
- isNftWon: result.miscellaneous?.xpNftAwarded || false,
156
- marginAccountId: params.marginAccountId,
157
- xpEarned: result.miscellaneous?.xpEarned || 0,
158
- executionPrice: result.tradeDetails?.executionPrice || 0,
159
- base: result.tradeDetails?.base || 0,
160
- positions: result.positions,
161
- orders: result.orders,
162
- accounts: result.accounts,
163
- };
164
- };
165
-
166
- const matchOrderV2 = async (
80
+ export const matchOrder = async (
167
81
  params: MatchOrderParams,
168
82
  ): Promise<MatchOrderResult> => {
169
83
  console.log('match order execution v2');
@@ -228,104 +142,7 @@ const matchOrderV2 = async (
228
142
  };
229
143
  };
230
144
 
231
- export const matchOrder = async (
232
- params: MatchOrderParams,
233
- ): Promise<MatchOrderResult> => {
234
- const isMatchOrderV2 =
235
- process.env.MATCH_ORDER_VIA_ORDERS_GATEWAY_ENABLED === 'true' || false;
236
-
237
- if (isMatchOrderV2) {
238
- return matchOrderV2(params);
239
- }
240
-
241
- return matchOrderV1(params);
242
- };
243
-
244
- const closeOrderV1 = async (
245
- params: CloseOrderParams,
246
- ): Promise<CloseOrderResult> => {
247
- console.log('close order execution v1');
248
-
249
- if (params.orderBase === 0) {
250
- throw new Error('Position is already closed.');
251
- }
252
-
253
- let closingBase: number = 0;
254
- if (params.type === 'full') {
255
- closingBase = params.orderBase;
256
- } else {
257
- closingBase = params.closingOrderBase;
258
-
259
- if (closingBase === 0) {
260
- throw new Error('Specified base to close is zero.');
261
- }
262
-
263
- if (closingBase * params.orderBase < 0) {
264
- throw new Error(
265
- 'Specified base to close is in different direction that the actual order.',
266
- );
267
- }
268
-
269
- if (Math.abs(closingBase) > Math.abs(params.orderBase)) {
270
- throw new Error(
271
- 'Specified base to close is larger than the actual order.',
272
- );
273
- }
274
- }
275
-
276
- const slippageFactor = 40; // 2.5%
277
- const orderPriceLimitE18 = calculatePriceLimitForTrade(
278
- params.market.currentPrice,
279
- -closingBase,
280
- slippageFactor,
281
- );
282
-
283
- const chainId = getReyaNetwork();
284
- const {
285
- calldata: data,
286
- payload: eip712Payload,
287
- signature: eip712Signature,
288
- } = await encodeMatchOrder(
289
- params.signer,
290
- chainId,
291
- params.owner.coreSigNonce,
292
- params.marginAccountId,
293
- -scale(18)(closingBase),
294
- orderPriceLimitE18,
295
- params.market.counterpartyAccountIds,
296
- params.market.id,
297
- params.market.exchangeId,
298
- );
299
-
300
- const result = await signAndBroadcastTransaction(
301
- data,
302
- chainId,
303
- ContractType.PERIPHERY_PROXY,
304
- {
305
- action: 'closeOrder',
306
- accountId: params.marginAccountId,
307
- marketId: params.market.id,
308
- matchOrder: {
309
- userEIP712Signature: eip712Signature,
310
- eip712Payload,
311
- },
312
- },
313
- );
314
-
315
- return {
316
- transactionHash: result?.txHash || null,
317
- coreSigNonce: Number(result?.coreSigNonce) || null,
318
- xpBoost: result.miscellaneous?.tradeXpBoost || 0,
319
- lotteryXpBoost: result.miscellaneous?.lotteryXpBoost || 0,
320
- isNftWon: result.miscellaneous?.xpNftAwarded || false,
321
- marginAccountId: params.marginAccountId,
322
- xpEarned: result.miscellaneous?.xpEarned || 0,
323
- executionPrice: result.tradeDetails?.executionPrice || 0,
324
- base: result.tradeDetails?.base || 0,
325
- };
326
- };
327
-
328
- const closeOrderV2 = async (
145
+ export const closeOrder = async (
329
146
  params: CloseOrderParams,
330
147
  ): Promise<CloseOrderResult> => {
331
148
  console.log('close order execution v2');
@@ -389,16 +206,3 @@ const closeOrderV2 = async (
389
206
  base: result.tradeDetails?.base || 0,
390
207
  };
391
208
  };
392
-
393
- export const closeOrder = async (
394
- params: CloseOrderParams,
395
- ): Promise<CloseOrderResult> => {
396
- const isCloseOrderV2 =
397
- process.env.CLOSE_ORDER_VIA_ORDERS_GATEWAY_ENABLED === 'true' || false;
398
-
399
- if (isCloseOrderV2) {
400
- return closeOrderV2(params);
401
- }
402
-
403
- return closeOrderV1(params);
404
- };
@@ -1,74 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.encodeMatchOrder = void 0;
40
- var common_1 = require("@reyaxyz/common");
41
- var encode_1 = require("../encode");
42
- var common_2 = require("@reyaxyz/common");
43
- var common_3 = require("@reyaxyz/common");
44
- var common_4 = require("@reyaxyz/common");
45
- var ethers_1 = require("ethers");
46
- var ethers_2 = require("ethers");
47
- var encodeMatchOrder = function (signer, chainId, coreSigNonce, accountId, orderBase, orderPriceLimit, counterpartyAccountIds, marketId, exchangeId) { return __awaiter(void 0, void 0, void 0, function () {
48
- var multiAction, _a, eip712Signature, eip712Payload, value, functionSignature, parameters, INTERFACE, calldata;
49
- return __generator(this, function (_b) {
50
- switch (_b.label) {
51
- case 0:
52
- multiAction = new common_1.MultiAction();
53
- (0, encode_1.encodeSingleTrade)(counterpartyAccountIds, orderBase, orderPriceLimit, marketId, exchangeId, multiAction);
54
- return [4 /*yield*/, (0, common_2.signCoreCommands)(signer, chainId, (0, common_3.getAddress)(chainId, common_3.ContractType.PERIPHERY_PROXY), accountId, multiAction.commands, coreSigNonce + 1, (0, common_3.getCurrentTimestampInSeconds)() + common_4.CORE_DEADLINE_IN_SECONDS, ethers_2.ethers.AbiCoder.defaultAbiCoder().encode([], []))];
55
- case 1:
56
- _a = _b.sent(), eip712Signature = _a.signature, eip712Payload = _a.payload;
57
- value = BigInt(0);
58
- functionSignature = 'execute';
59
- parameters = [
60
- { accountId: accountId, commands: multiAction.commands, sig: eip712Signature },
61
- ];
62
- INTERFACE = new ethers_1.Interface(common_1.PeripheryAbi);
63
- calldata = INTERFACE.encodeFunctionData(functionSignature, parameters);
64
- return [2 /*return*/, {
65
- calldata: calldata,
66
- value: BigInt(value).toString(10),
67
- signature: eip712Signature,
68
- payload: eip712Payload,
69
- }];
70
- }
71
- });
72
- }); };
73
- exports.encodeMatchOrder = encodeMatchOrder;
74
- //# sourceMappingURL=encode.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"encode.js","sourceRoot":"/","sources":["services/orders/encode.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0CAAmE;AACnE,oCAA8C;AAC9C,0CAAmD;AACnD,0CAIyB;AACzB,0CAA2D;AAC3D,iCAA2C;AAC3C,iCAAgC;AAGzB,IAAM,gBAAgB,GAAG,UAC9B,MAAc,EACd,OAAe,EACf,YAAoB,EACpB,SAAiB,EACjB,SAAiB,EACjB,eAAuB,EACvB,sBAAgC,EAChC,QAAgB,EAChB,UAAkB;;;;;gBAEZ,WAAW,GAAG,IAAI,oBAAW,EAAE,CAAC;gBAEtC,IAAA,0BAAiB,EACf,sBAAsB,EACtB,SAAS,EACT,eAAe,EACf,QAAQ,EACR,UAAU,EACV,WAAW,CACZ,CAAC;gBAGA,qBAAM,IAAA,yBAAgB,EACpB,MAAM,EACN,OAAO,EACP,IAAA,mBAAU,EAAC,OAAO,EAAE,qBAAY,CAAC,eAAe,CAAC,EACjD,SAAS,EACT,WAAW,CAAC,QAAQ,EACpB,YAAY,GAAG,CAAC,EAChB,IAAA,qCAA4B,GAAE,GAAG,iCAAwB,EACzD,eAAM,CAAC,QAAQ,CAAC,eAAe,EAAE,CAAC,MAAM,CAAC,EAAE,EAAE,EAAE,CAAC,CACjD,EAAA;;gBAVG,KACJ,SASC,EAVgB,eAAe,eAAA,EAAW,aAAa,aAAA;gBAYpD,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;gBAElB,iBAAiB,GAAG,SAAS,CAAC;gBAC9B,UAAU,GAAG;oBACjB,EAAE,SAAS,WAAA,EAAE,QAAQ,EAAE,WAAW,CAAC,QAAQ,EAAE,GAAG,EAAE,eAAe,EAAE;iBACpE,CAAC;gBAEI,SAAS,GAAG,IAAI,kBAAS,CAAC,qBAAG,CAAC,CAAC;gBAC/B,QAAQ,GAAG,SAAS,CAAC,kBAAkB,CAAC,iBAAiB,EAAE,UAAU,CAAC,CAAC;gBAC7E,sBAAO;wBACL,QAAQ,EAAE,QAAQ;wBAClB,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC;wBACjC,SAAS,EAAE,eAAe;wBAC1B,OAAO,EAAE,aAAa;qBACvB,EAAC;;;KACH,CAAC;AAjDW,QAAA,gBAAgB,oBAiD3B","sourcesContent":["import { MultiAction, PeripheryAbi as abi } from '@reyaxyz/common';\nimport { encodeSingleTrade } from '../encode';\nimport { signCoreCommands } from '@reyaxyz/common';\nimport {\n getCurrentTimestampInSeconds,\n ContractType,\n getAddress,\n} from '@reyaxyz/common';\nimport { CORE_DEADLINE_IN_SECONDS } from '@reyaxyz/common';\nimport { Interface, Signer } from 'ethers';\nimport { ethers } from 'ethers';\nimport { MethodParametersAndEIP712Payload } from './types';\n\nexport const encodeMatchOrder = async (\n signer: Signer,\n chainId: number,\n coreSigNonce: number,\n accountId: number,\n orderBase: bigint,\n orderPriceLimit: bigint,\n counterpartyAccountIds: number[],\n marketId: number,\n exchangeId: number,\n): Promise<MethodParametersAndEIP712Payload> => {\n const multiAction = new MultiAction();\n\n encodeSingleTrade(\n counterpartyAccountIds,\n orderBase,\n orderPriceLimit,\n marketId,\n exchangeId,\n multiAction,\n );\n\n const { signature: eip712Signature, payload: eip712Payload } =\n await signCoreCommands(\n signer,\n chainId,\n getAddress(chainId, ContractType.PERIPHERY_PROXY),\n accountId,\n multiAction.commands,\n coreSigNonce + 1,\n getCurrentTimestampInSeconds() + CORE_DEADLINE_IN_SECONDS,\n ethers.AbiCoder.defaultAbiCoder().encode([], []),\n );\n\n const value = BigInt(0);\n\n const functionSignature = 'execute';\n const parameters = [\n { accountId, commands: multiAction.commands, sig: eip712Signature },\n ];\n\n const INTERFACE = new Interface(abi);\n const calldata = INTERFACE.encodeFunctionData(functionSignature, parameters);\n return {\n calldata: calldata,\n value: BigInt(value).toString(10),\n signature: eip712Signature,\n payload: eip712Payload,\n };\n};\n"]}
@@ -1,4 +0,0 @@
1
- import { Signer } from 'ethers';
2
- import { MethodParametersAndEIP712Payload } from './types';
3
- export declare const encodeMatchOrder: (signer: Signer, chainId: number, coreSigNonce: number, accountId: number, orderBase: bigint, orderPriceLimit: bigint, counterpartyAccountIds: number[], marketId: number, exchangeId: number) => Promise<MethodParametersAndEIP712Payload>;
4
- //# sourceMappingURL=encode.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"encode.d.ts","sourceRoot":"/","sources":["services/orders/encode.ts"],"names":[],"mappings":"AASA,OAAO,EAAa,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE3C,OAAO,EAAE,gCAAgC,EAAE,MAAM,SAAS,CAAC;AAE3D,eAAO,MAAM,gBAAgB,WACnB,MAAM,WACL,MAAM,gBACD,MAAM,aACT,MAAM,aACN,MAAM,mBACA,MAAM,0BACC,MAAM,EAAE,YACtB,MAAM,cACJ,MAAM,KACjB,QAAQ,gCAAgC,CAuC1C,CAAC"}
@@ -1,63 +0,0 @@
1
- import { MultiAction, PeripheryAbi as abi } from '@reyaxyz/common';
2
- import { encodeSingleTrade } from '../encode';
3
- import { signCoreCommands } from '@reyaxyz/common';
4
- import {
5
- getCurrentTimestampInSeconds,
6
- ContractType,
7
- getAddress,
8
- } from '@reyaxyz/common';
9
- import { CORE_DEADLINE_IN_SECONDS } from '@reyaxyz/common';
10
- import { Interface, Signer } from 'ethers';
11
- import { ethers } from 'ethers';
12
- import { MethodParametersAndEIP712Payload } from './types';
13
-
14
- export const encodeMatchOrder = async (
15
- signer: Signer,
16
- chainId: number,
17
- coreSigNonce: number,
18
- accountId: number,
19
- orderBase: bigint,
20
- orderPriceLimit: bigint,
21
- counterpartyAccountIds: number[],
22
- marketId: number,
23
- exchangeId: number,
24
- ): Promise<MethodParametersAndEIP712Payload> => {
25
- const multiAction = new MultiAction();
26
-
27
- encodeSingleTrade(
28
- counterpartyAccountIds,
29
- orderBase,
30
- orderPriceLimit,
31
- marketId,
32
- exchangeId,
33
- multiAction,
34
- );
35
-
36
- const { signature: eip712Signature, payload: eip712Payload } =
37
- await signCoreCommands(
38
- signer,
39
- chainId,
40
- getAddress(chainId, ContractType.PERIPHERY_PROXY),
41
- accountId,
42
- multiAction.commands,
43
- coreSigNonce + 1,
44
- getCurrentTimestampInSeconds() + CORE_DEADLINE_IN_SECONDS,
45
- ethers.AbiCoder.defaultAbiCoder().encode([], []),
46
- );
47
-
48
- const value = BigInt(0);
49
-
50
- const functionSignature = 'execute';
51
- const parameters = [
52
- { accountId, commands: multiAction.commands, sig: eip712Signature },
53
- ];
54
-
55
- const INTERFACE = new Interface(abi);
56
- const calldata = INTERFACE.encodeFunctionData(functionSignature, parameters);
57
- return {
58
- calldata: calldata,
59
- value: BigInt(value).toString(10),
60
- signature: eip712Signature,
61
- payload: eip712Payload,
62
- };
63
- };