@gmx-io/sdk 1.5.0-alpha-9 → 1.5.0-alpha-10

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 (201) hide show
  1. package/build/cjs/scripts/subsquid-codegen.js +1 -1
  2. package/build/cjs/src/clients/v2/__tests__/data.spec.js +85 -0
  3. package/build/cjs/src/clients/v2/__tests__/decrease.spec.js +471 -0
  4. package/build/cjs/src/clients/v2/__tests__/editCancel.spec.js +259 -0
  5. package/build/cjs/src/clients/v2/__tests__/errors.spec.js +261 -0
  6. package/build/cjs/src/clients/v2/__tests__/increase.spec.js +764 -0
  7. package/build/cjs/src/clients/v2/__tests__/subaccount.spec.js +74 -0
  8. package/build/cjs/src/clients/v2/__tests__/swap.spec.js +192 -0
  9. package/build/cjs/src/clients/v2/__tests__/testUtil.js +136 -0
  10. package/build/cjs/src/clients/v2/index.js +162 -27
  11. package/build/cjs/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +48 -0
  12. package/build/cjs/src/codegen/prebuilt/hashedMarketConfigKeys.json +342 -0
  13. package/build/cjs/src/codegen/prebuilt/hashedMarketValuesKeys.json +90 -0
  14. package/build/cjs/src/codegen/subsquid.js +323 -1
  15. package/build/cjs/src/configs/chains.js +11 -1
  16. package/build/cjs/src/configs/contracts.js +7 -7
  17. package/build/cjs/src/configs/markets.js +56 -2
  18. package/build/cjs/src/configs/tokens.js +63 -132
  19. package/build/cjs/src/test/mock.js +1 -1
  20. package/build/cjs/src/utils/__tests__/markets.spec.js +10 -0
  21. package/build/cjs/src/utils/__tests__/orderTransactions/decreaseOrders.spec.js +2 -0
  22. package/build/cjs/src/utils/__tests__/orderTransactions/increaseOrders.spec.js +2 -0
  23. package/build/cjs/src/utils/__tests__/orderTransactions/swapOrders.spec.js +1 -0
  24. package/build/cjs/src/utils/__tests__/positions.spec.js +59 -7
  25. package/build/cjs/src/utils/__tests__/uiFeeReceiver.spec.js +34 -0
  26. package/build/cjs/src/utils/balances/api.js +65 -0
  27. package/build/cjs/src/utils/buyback/api.js +7 -0
  28. package/build/cjs/src/utils/buyback/types.js +2 -0
  29. package/build/cjs/src/utils/errors/index.js +1 -0
  30. package/build/cjs/src/utils/errors/isIgnoredEstimateGasError.js +23 -0
  31. package/build/cjs/src/utils/express/index.js +18 -0
  32. package/build/cjs/src/utils/express/types.js +2 -0
  33. package/build/cjs/src/utils/express/utils/batchOrderUtils.js +218 -0
  34. package/build/cjs/src/utils/express/utils/bridgeOutUtils.js +73 -0
  35. package/build/cjs/src/utils/express/utils/estimateExpressParams.js +244 -0
  36. package/build/cjs/src/utils/express/utils/expressParamsUtils.js +22 -0
  37. package/build/cjs/src/utils/express/utils/fetchGelatoGasTankBalance.js +13 -0
  38. package/build/cjs/src/utils/express/utils/gelatoRelayUtils.js +77 -0
  39. package/build/cjs/src/utils/express/utils/globalExpressParams.js +40 -0
  40. package/build/cjs/src/utils/express/utils/index.js +27 -0
  41. package/build/cjs/src/utils/express/utils/oracleParamsUtils.js +49 -0
  42. package/build/cjs/src/utils/express/utils/referralUtils.js +35 -0
  43. package/build/cjs/src/utils/express/utils/relayParamsUtils.js +208 -0
  44. package/build/cjs/src/utils/fees/priceImpact.js +1 -2
  45. package/build/cjs/src/utils/http/http.js +86 -13
  46. package/build/cjs/src/utils/markets/utils.js +8 -0
  47. package/build/cjs/src/utils/metrics/index.js +7 -0
  48. package/build/cjs/src/utils/numbers/utils.js +29 -27
  49. package/build/cjs/src/utils/orderTransactions/api.js +88 -0
  50. package/build/cjs/src/utils/orderTransactions/index.js +2 -0
  51. package/build/cjs/src/utils/orderTransactions/simulation.js +141 -0
  52. package/build/cjs/src/utils/orderTransactions/utils.js +4 -1
  53. package/build/cjs/src/utils/orderTransactions/validateTypedData.js +100 -0
  54. package/build/cjs/src/utils/positions/utils.js +5 -19
  55. package/build/cjs/src/utils/rpc/createViemRpc.js +39 -0
  56. package/build/cjs/src/utils/rpc/index.js +5 -0
  57. package/build/cjs/src/utils/signer/index.js +5 -0
  58. package/build/cjs/src/utils/signer/privateKeySigner.js +42 -0
  59. package/build/cjs/src/utils/subaccount/api.js +22 -0
  60. package/build/cjs/src/utils/subaccount/generateSubaccount.js +19 -0
  61. package/build/cjs/src/utils/subaccount/getEmptySubaccountApproval.js +24 -0
  62. package/build/cjs/src/utils/subaccount/getSubaccountApprovalTypedData.js +51 -0
  63. package/build/cjs/src/utils/subaccount/hashSubaccountApproval.js +28 -0
  64. package/build/cjs/src/utils/subaccount/index.js +30 -0
  65. package/build/cjs/src/utils/subaccount/types.js +2 -0
  66. package/build/cjs/src/utils/swap/swapPath.js +4 -1
  67. package/build/cjs/src/utils/trade/types.js +1 -1
  68. package/build/cjs/src/utils/tradeHistory/utils.js +14 -28
  69. package/build/cjs/src/utils/twap/index.js +4 -1
  70. package/build/cjs/src/utils/twap/uiFeeReceiver.js +23 -7
  71. package/build/esm/scripts/subsquid-codegen.js +1 -1
  72. package/build/esm/src/clients/v2/__tests__/data.spec.js +83 -0
  73. package/build/esm/src/clients/v2/__tests__/decrease.spec.js +469 -0
  74. package/build/esm/src/clients/v2/__tests__/editCancel.spec.js +257 -0
  75. package/build/esm/src/clients/v2/__tests__/errors.spec.js +259 -0
  76. package/build/esm/src/clients/v2/__tests__/increase.spec.js +762 -0
  77. package/build/esm/src/clients/v2/__tests__/subaccount.spec.js +72 -0
  78. package/build/esm/src/clients/v2/__tests__/swap.spec.js +190 -0
  79. package/build/esm/src/clients/v2/__tests__/testUtil.js +124 -0
  80. package/build/esm/src/clients/v2/index.js +136 -4
  81. package/build/esm/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +48 -0
  82. package/build/esm/src/codegen/prebuilt/hashedMarketConfigKeys.json +342 -0
  83. package/build/esm/src/codegen/prebuilt/hashedMarketValuesKeys.json +90 -0
  84. package/build/esm/src/codegen/subsquid.js +321 -0
  85. package/build/esm/src/configs/chains.js +11 -1
  86. package/build/esm/src/configs/contracts.js +7 -7
  87. package/build/esm/src/configs/markets.js +55 -1
  88. package/build/esm/src/configs/tokens.js +62 -130
  89. package/build/esm/src/test/mock.js +1 -1
  90. package/build/esm/src/utils/__tests__/markets.spec.js +10 -0
  91. package/build/esm/src/utils/__tests__/orderTransactions/decreaseOrders.spec.js +2 -0
  92. package/build/esm/src/utils/__tests__/orderTransactions/increaseOrders.spec.js +2 -0
  93. package/build/esm/src/utils/__tests__/orderTransactions/swapOrders.spec.js +1 -0
  94. package/build/esm/src/utils/__tests__/positions.spec.js +60 -8
  95. package/build/esm/src/utils/__tests__/uiFeeReceiver.spec.js +35 -1
  96. package/build/esm/src/utils/balances/api.js +56 -0
  97. package/build/esm/src/utils/buyback/api.js +3 -0
  98. package/build/esm/src/utils/buyback/types.js +1 -0
  99. package/build/esm/src/utils/errors/index.js +1 -0
  100. package/build/esm/src/utils/errors/isIgnoredEstimateGasError.js +19 -0
  101. package/build/esm/src/utils/express/index.js +2 -0
  102. package/build/esm/src/utils/express/types.js +1 -0
  103. package/build/esm/src/utils/express/utils/batchOrderUtils.js +210 -0
  104. package/build/esm/src/utils/express/utils/bridgeOutUtils.js +69 -0
  105. package/build/esm/src/utils/express/utils/estimateExpressParams.js +238 -0
  106. package/build/esm/src/utils/express/utils/expressParamsUtils.js +16 -0
  107. package/build/esm/src/utils/express/utils/fetchGelatoGasTankBalance.js +9 -0
  108. package/build/esm/src/utils/express/utils/gelatoRelayUtils.js +71 -0
  109. package/build/esm/src/utils/express/utils/globalExpressParams.js +36 -0
  110. package/build/esm/src/utils/express/utils/index.js +11 -0
  111. package/build/esm/src/utils/express/utils/oracleParamsUtils.js +42 -0
  112. package/build/esm/src/utils/express/utils/referralUtils.js +30 -0
  113. package/build/esm/src/utils/express/utils/relayParamsUtils.js +198 -0
  114. package/build/esm/src/utils/fees/priceImpact.js +1 -2
  115. package/build/esm/src/utils/http/http.js +84 -12
  116. package/build/esm/src/utils/markets/utils.js +8 -0
  117. package/build/esm/src/utils/metrics/index.js +4 -0
  118. package/build/esm/src/utils/numbers/utils.js +25 -24
  119. package/build/esm/src/utils/orderTransactions/api.js +77 -0
  120. package/build/esm/src/utils/orderTransactions/index.js +2 -0
  121. package/build/esm/src/utils/orderTransactions/simulation.js +136 -0
  122. package/build/esm/src/utils/orderTransactions/utils.js +4 -1
  123. package/build/esm/src/utils/orderTransactions/validateTypedData.js +95 -0
  124. package/build/esm/src/utils/positions/utils.js +5 -19
  125. package/build/esm/src/utils/rpc/createViemRpc.js +35 -0
  126. package/build/esm/src/utils/rpc/index.js +1 -0
  127. package/build/esm/src/utils/signer/index.js +1 -0
  128. package/build/esm/src/utils/signer/privateKeySigner.js +38 -0
  129. package/build/esm/src/utils/subaccount/api.js +16 -0
  130. package/build/esm/src/utils/subaccount/generateSubaccount.js +15 -0
  131. package/build/esm/src/utils/subaccount/getEmptySubaccountApproval.js +20 -0
  132. package/build/esm/src/utils/subaccount/getSubaccountApprovalTypedData.js +47 -0
  133. package/build/esm/src/utils/subaccount/hashSubaccountApproval.js +24 -0
  134. package/build/esm/src/utils/subaccount/index.js +6 -0
  135. package/build/esm/src/utils/subaccount/types.js +1 -0
  136. package/build/esm/src/utils/swap/swapPath.js +5 -2
  137. package/build/esm/src/utils/trade/types.js +1 -1
  138. package/build/esm/src/utils/tradeHistory/utils.js +13 -26
  139. package/build/esm/src/utils/twap/index.js +1 -0
  140. package/build/esm/src/utils/twap/uiFeeReceiver.js +20 -6
  141. package/build/types/src/clients/v2/__tests__/data.spec.d.ts +1 -0
  142. package/build/types/src/clients/v2/__tests__/decrease.spec.d.ts +1 -0
  143. package/build/types/src/clients/v2/__tests__/editCancel.spec.d.ts +1 -0
  144. package/build/types/src/clients/v2/__tests__/errors.spec.d.ts +1 -0
  145. package/build/types/src/clients/v2/__tests__/increase.spec.d.ts +1 -0
  146. package/build/types/src/clients/v2/__tests__/subaccount.spec.d.ts +1 -0
  147. package/build/types/src/clients/v2/__tests__/swap.spec.d.ts +1 -0
  148. package/build/types/src/clients/v2/__tests__/testUtil.d.ts +25 -0
  149. package/build/types/src/clients/v2/index.d.ts +59 -1
  150. package/build/types/src/codegen/prebuilt/index.d.ts +480 -0
  151. package/build/types/src/codegen/subsquid.d.ts +1276 -44
  152. package/build/types/src/configs/chains.d.ts +10 -1
  153. package/build/types/src/configs/contracts.d.ts +6 -6
  154. package/build/types/src/configs/markets.d.ts +5 -0
  155. package/build/types/src/configs/tokens.d.ts +6 -1
  156. package/build/types/src/utils/balances/api.d.ts +39 -0
  157. package/build/types/src/utils/buyback/api.d.ts +5 -0
  158. package/build/types/src/utils/buyback/types.d.ts +15 -0
  159. package/build/types/src/utils/chains/types.d.ts +1 -0
  160. package/build/types/src/utils/errors/index.d.ts +1 -0
  161. package/build/types/src/utils/errors/isIgnoredEstimateGasError.d.ts +2 -0
  162. package/build/types/src/utils/express/index.d.ts +2 -0
  163. package/build/types/src/utils/express/types.d.ts +95 -0
  164. package/build/types/src/utils/express/utils/batchOrderUtils.d.ts +98 -0
  165. package/build/types/src/utils/express/utils/bridgeOutUtils.d.ts +21 -0
  166. package/build/types/src/utils/express/utils/estimateExpressParams.d.ts +37 -0
  167. package/build/types/src/utils/express/utils/expressParamsUtils.d.ts +19 -0
  168. package/build/types/src/utils/express/utils/fetchGelatoGasTankBalance.d.ts +5 -0
  169. package/build/types/src/utils/express/utils/gelatoRelayUtils.d.ts +25 -0
  170. package/build/types/src/utils/express/utils/globalExpressParams.d.ts +31 -0
  171. package/build/types/src/utils/express/utils/index.d.ts +11 -0
  172. package/build/types/src/utils/express/utils/oracleParamsUtils.d.ts +10 -0
  173. package/build/types/src/utils/express/utils/referralUtils.d.ts +17 -0
  174. package/build/types/src/utils/express/utils/relayParamsUtils.d.ts +63 -0
  175. package/build/types/src/utils/http/http.d.ts +16 -1
  176. package/build/types/src/utils/http/types.d.ts +3 -0
  177. package/build/types/src/utils/metrics/index.d.ts +4 -0
  178. package/build/types/src/utils/numbers/utils.d.ts +2 -5
  179. package/build/types/src/utils/orderTransactions/api.d.ts +158 -0
  180. package/build/types/src/utils/orderTransactions/index.d.ts +2 -0
  181. package/build/types/src/utils/orderTransactions/simulation.d.ts +26 -0
  182. package/build/types/src/utils/orderTransactions/validateTypedData.d.ts +6 -0
  183. package/build/types/src/utils/positions/utils.d.ts +1 -9
  184. package/build/types/src/utils/rpc/createViemRpc.d.ts +3 -0
  185. package/build/types/src/utils/rpc/index.d.ts +26 -0
  186. package/build/types/src/utils/signer/index.d.ts +23 -0
  187. package/build/types/src/utils/signer/privateKeySigner.d.ts +19 -0
  188. package/build/types/src/utils/subaccount/api.d.ts +50 -0
  189. package/build/types/src/utils/subaccount/generateSubaccount.d.ts +8 -0
  190. package/build/types/src/utils/subaccount/getEmptySubaccountApproval.d.ts +9 -0
  191. package/build/types/src/utils/subaccount/getSubaccountApprovalTypedData.d.ts +24 -0
  192. package/build/types/src/utils/subaccount/hashSubaccountApproval.d.ts +1 -0
  193. package/build/types/src/utils/subaccount/index.d.ts +7 -0
  194. package/build/types/src/utils/subaccount/types.d.ts +55 -0
  195. package/build/types/src/utils/tokens/types.d.ts +0 -1
  196. package/build/types/src/utils/trade/types.d.ts +1 -1
  197. package/build/types/src/utils/tradeHistory/utils.d.ts +0 -1
  198. package/build/types/src/utils/twap/index.d.ts +1 -0
  199. package/build/types/src/utils/twap/types.d.ts +2 -0
  200. package/build/types/src/utils/twap/uiFeeReceiver.d.ts +10 -2
  201. package/package.json +40 -3
@@ -0,0 +1,208 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.hashRelayParams = exports.getRawRelayerParams = exports.getBestInternalSwapStrategy = exports.getBestSwapStrategy = exports.getRelayerFeeParams = exports.getGelatoRelayRouterDomain = exports.getExpressContractAddress = void 0;
4
+ const viem_1 = require("viem");
5
+ const abis_1 = require("../../../abis");
6
+ const contracts_1 = require("../../../configs/contracts");
7
+ const types_1 = require("../../orders/types");
8
+ const orderTransactions_1 = require("../../orderTransactions");
9
+ const swap_1 = require("../../swap");
10
+ const time_1 = require("../../time");
11
+ const oracleParamsUtils_1 = require("./oracleParamsUtils");
12
+ function getExpressContractAddress(chainId, { isSubaccount, isMultichain, scope, }) {
13
+ let contractName;
14
+ if (isMultichain) {
15
+ switch (scope) {
16
+ case "claims":
17
+ contractName = "MultichainClaimsRouter";
18
+ break;
19
+ case "order":
20
+ contractName = "MultichainOrderRouter";
21
+ break;
22
+ case "subaccount":
23
+ contractName = "MultichainSubaccountRouter";
24
+ break;
25
+ case "glv":
26
+ contractName = "MultichainGlvRouter";
27
+ break;
28
+ case "gm":
29
+ contractName = "MultichainGmRouter";
30
+ break;
31
+ case "transfer":
32
+ contractName = "MultichainTransferRouter";
33
+ break;
34
+ default:
35
+ throw new Error(`Invalid scope: ${scope}`);
36
+ }
37
+ }
38
+ else {
39
+ if (isSubaccount) {
40
+ contractName = "SubaccountGelatoRelayRouter";
41
+ }
42
+ else {
43
+ contractName = "GelatoRelayRouter";
44
+ }
45
+ }
46
+ return (0, contracts_1.getContract)(chainId, contractName);
47
+ }
48
+ exports.getExpressContractAddress = getExpressContractAddress;
49
+ function getGelatoRelayRouterDomain(chainId, relayRouterAddress) {
50
+ return {
51
+ name: "GmxBaseGelatoRelayRouter",
52
+ version: "1",
53
+ chainId,
54
+ verifyingContract: relayRouterAddress,
55
+ };
56
+ }
57
+ exports.getGelatoRelayRouterDomain = getGelatoRelayRouterDomain;
58
+ function getRelayerFeeParams({ chainId, account, gasPaymentToken, relayerFeeToken, relayerFeeAmount, totalRelayerFeeTokenAmount, gasPaymentTokenAsCollateralAmount, transactionExternalCalls, feeExternalSwapQuote, findFeeSwapPath, }) {
59
+ const gasPaymentParams = {
60
+ gasPaymentToken: gasPaymentToken,
61
+ relayFeeToken: relayerFeeToken,
62
+ gasPaymentTokenAddress: gasPaymentToken.address,
63
+ relayerFeeTokenAddress: relayerFeeToken.address,
64
+ relayerFeeAmount,
65
+ totalRelayerFeeTokenAmount,
66
+ gasPaymentTokenAmount: 0n,
67
+ gasPaymentTokenAsCollateralAmount,
68
+ };
69
+ let feeParams;
70
+ let externalCalls = transactionExternalCalls ?? (0, orderTransactions_1.getEmptyExternalCallsPayload)();
71
+ let feeExternalSwapGasLimit = 0n;
72
+ if (relayerFeeToken.address === gasPaymentToken.address) {
73
+ feeParams = {
74
+ feeToken: relayerFeeToken.address,
75
+ feeAmount: totalRelayerFeeTokenAmount,
76
+ feeSwapPath: [],
77
+ };
78
+ gasPaymentParams.gasPaymentTokenAmount = totalRelayerFeeTokenAmount;
79
+ }
80
+ else {
81
+ let feeSwapAmounts;
82
+ if (findFeeSwapPath) {
83
+ feeSwapAmounts = (0, swap_1.getSwapAmountsByToValue)({
84
+ tokenIn: gasPaymentToken,
85
+ tokenOut: relayerFeeToken,
86
+ amountOut: totalRelayerFeeTokenAmount,
87
+ isLimit: false,
88
+ findSwapPath: findFeeSwapPath,
89
+ swapOptimizationOrder: ["length"],
90
+ uiFeeFactor: 0n,
91
+ marketsInfoData: undefined,
92
+ chainId,
93
+ externalSwapQuoteParams: undefined,
94
+ allowSameTokenSwap: false,
95
+ swapPricingType: types_1.SwapPricingType.AtomicSwap,
96
+ });
97
+ }
98
+ const bestFeeSwapStrategy = getBestSwapStrategy({
99
+ internalSwapAmounts: feeSwapAmounts,
100
+ externalSwapQuote: feeExternalSwapQuote,
101
+ });
102
+ if (bestFeeSwapStrategy?.swapPath) {
103
+ feeParams = {
104
+ feeToken: gasPaymentToken.address,
105
+ feeAmount: bestFeeSwapStrategy.amountIn,
106
+ feeSwapPath: bestFeeSwapStrategy.swapPath,
107
+ };
108
+ gasPaymentParams.gasPaymentTokenAmount = bestFeeSwapStrategy.amountIn;
109
+ gasPaymentParams.totalRelayerFeeTokenAmount = bestFeeSwapStrategy.amountOut;
110
+ }
111
+ else if (bestFeeSwapStrategy?.externalSwapQuote) {
112
+ externalCalls = (0, orderTransactions_1.combineExternalCalls)([
113
+ externalCalls,
114
+ (0, orderTransactions_1.getExternalCallsPayload)({
115
+ chainId,
116
+ account,
117
+ quote: bestFeeSwapStrategy.externalSwapQuote,
118
+ }),
119
+ ]);
120
+ feeExternalSwapGasLimit = bestFeeSwapStrategy.externalSwapQuote.txnData.estimatedGas;
121
+ feeParams = {
122
+ feeToken: relayerFeeToken.address,
123
+ feeAmount: 0n,
124
+ feeSwapPath: [],
125
+ };
126
+ gasPaymentParams.gasPaymentTokenAmount = bestFeeSwapStrategy.externalSwapQuote.amountIn;
127
+ gasPaymentParams.totalRelayerFeeTokenAmount = bestFeeSwapStrategy.externalSwapQuote.amountOut;
128
+ }
129
+ else {
130
+ return undefined;
131
+ }
132
+ }
133
+ return {
134
+ feeParams,
135
+ externalCalls,
136
+ feeExternalSwapGasLimit,
137
+ gasPaymentParams,
138
+ };
139
+ }
140
+ exports.getRelayerFeeParams = getRelayerFeeParams;
141
+ function getBestSwapStrategy({ internalSwapAmounts, externalSwapQuote, }) {
142
+ return getBestInternalSwapStrategy(internalSwapAmounts, externalSwapQuote);
143
+ }
144
+ exports.getBestSwapStrategy = getBestSwapStrategy;
145
+ function getBestInternalSwapStrategy(internalSwapAmounts, externalSwapQuote) {
146
+ if (externalSwapQuote && externalSwapQuote.usdOut > (internalSwapAmounts?.swapStrategy.swapPathStats?.usdOut ?? 0n)) {
147
+ return {
148
+ amountIn: externalSwapQuote.amountIn,
149
+ amountOut: externalSwapQuote.amountOut,
150
+ externalSwapQuote,
151
+ };
152
+ }
153
+ else if (internalSwapAmounts?.swapStrategy.swapPathStats) {
154
+ return {
155
+ amountIn: internalSwapAmounts.amountIn,
156
+ amountOut: internalSwapAmounts.amountOut,
157
+ swapPath: internalSwapAmounts.swapStrategy.swapPathStats.swapPath,
158
+ };
159
+ }
160
+ return undefined;
161
+ }
162
+ exports.getBestInternalSwapStrategy = getBestInternalSwapStrategy;
163
+ function getRawRelayerParams({ chainId, gasPaymentTokenAddress, relayerFeeTokenAddress, feeParams, externalCalls, tokenPermits, }) {
164
+ const oracleParams = (0, oracleParamsUtils_1.getOracleParamsForRelayParams)({
165
+ chainId,
166
+ externalCalls,
167
+ feeSwapPath: feeParams.feeSwapPath,
168
+ gasPaymentTokenAddress,
169
+ relayerFeeTokenAddress,
170
+ });
171
+ return {
172
+ oracleParams,
173
+ tokenPermits,
174
+ externalCalls,
175
+ fee: feeParams,
176
+ desChainId: BigInt(chainId),
177
+ userNonce: BigInt((0, time_1.nowInSeconds)()),
178
+ };
179
+ }
180
+ exports.getRawRelayerParams = getRawRelayerParams;
181
+ function hashRelayParams(relayParams) {
182
+ const encoded = (0, viem_1.encodeAbiParameters)(abis_1.abis.RelayParams, [
183
+ {
184
+ tokens: relayParams.oracleParams.tokens,
185
+ providers: relayParams.oracleParams.providers,
186
+ data: relayParams.oracleParams.data,
187
+ },
188
+ {
189
+ sendTokens: relayParams.externalCalls.sendTokens,
190
+ sendAmounts: relayParams.externalCalls.sendAmounts,
191
+ externalCallTargets: relayParams.externalCalls.externalCallTargets,
192
+ externalCallDataList: relayParams.externalCalls.externalCallDataList,
193
+ refundTokens: relayParams.externalCalls.refundTokens,
194
+ refundReceivers: relayParams.externalCalls.refundReceivers,
195
+ },
196
+ relayParams.tokenPermits,
197
+ {
198
+ feeToken: relayParams.fee.feeToken,
199
+ feeAmount: relayParams.fee.feeAmount,
200
+ feeSwapPath: relayParams.fee.feeSwapPath,
201
+ },
202
+ relayParams.userNonce,
203
+ relayParams.deadline,
204
+ relayParams.desChainId,
205
+ ]);
206
+ return (0, viem_1.keccak256)(encoded);
207
+ }
208
+ exports.hashRelayParams = hashRelayParams;
@@ -5,7 +5,6 @@ const bigmath_1 = require("../bigmath");
5
5
  const markets_1 = require("../markets");
6
6
  const numbers_1 = require("../numbers");
7
7
  const tokens_1 = require("../tokens");
8
- const tradeHistory_1 = require("../tradeHistory");
9
8
  function getPriceImpactByAcceptablePrice(p) {
10
9
  const { sizeDeltaUsd, acceptablePrice, indexPrice: markPrice, isLong, isIncrease } = p;
11
10
  const shouldFlipPriceDiff = isIncrease ? !isLong : isLong;
@@ -362,7 +361,7 @@ function applyImpactFactor(diff, factor, exponent) {
362
361
  if (!isFinite(powered) || isNaN(powered)) {
363
362
  return 0n;
364
363
  }
365
- let result = (0, tradeHistory_1.bigNumberify)(BigInt(Math.round(powered)));
364
+ let result = BigInt(Math.round(powered));
366
365
  result = (result * factor) / (0, numbers_1.expandDecimals)(1, 30);
367
366
  return result;
368
367
  }
@@ -3,31 +3,104 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.HttpClient = void 0;
6
+ exports.HttpClient = exports.HttpError = void 0;
7
7
  const cross_fetch_1 = __importDefault(require("cross-fetch"));
8
8
  const buildUrl_1 = require("../buildUrl");
9
+ const DEFAULT_TIMEOUT_MS = 30000;
10
+ function bigIntReplacer(_key, value) {
11
+ return typeof value === "bigint" ? value.toString() : value;
12
+ }
13
+ class HttpError extends Error {
14
+ constructor(statusCode, message, body) {
15
+ super(message);
16
+ this.name = "HttpError";
17
+ this.statusCode = statusCode;
18
+ this.code = body?.code ?? body?.error?.code;
19
+ this.traceId = body?.traceId;
20
+ this.body = body;
21
+ }
22
+ }
23
+ exports.HttpError = HttpError;
24
+ function throwHttpError(statusCode, statusText, errorBody) {
25
+ let errorMessage = `HTTP ${statusCode}: ${statusText}`;
26
+ if (errorBody?.message) {
27
+ const msg = typeof errorBody.message === "string" ? errorBody.message : JSON.stringify(errorBody.message);
28
+ errorMessage = `HTTP ${statusCode}: ${msg}`;
29
+ }
30
+ throw new HttpError(statusCode, errorMessage, errorBody);
31
+ }
9
32
  class HttpClient {
10
- constructor(url) {
33
+ constructor(url, timeoutMs = DEFAULT_TIMEOUT_MS) {
11
34
  this.url = url;
35
+ this.timeoutMs = timeoutMs;
12
36
  }
13
37
  async fetchJson(path, opts) {
14
38
  const query = opts?.query
15
39
  ? Object.fromEntries(Object.entries(opts.query).filter(([, value]) => value !== undefined && value !== null))
16
40
  : undefined;
17
41
  const url = (0, buildUrl_1.buildUrl)(this.url, path, query);
18
- const response = await (0, cross_fetch_1.default)(url, {
19
- headers: {
20
- Accept: "application/json",
21
- },
22
- });
23
- if (!response.ok) {
24
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
42
+ const controller = new AbortController();
43
+ const timeoutId = setTimeout(() => controller.abort(), this.timeoutMs);
44
+ try {
45
+ const response = await (0, cross_fetch_1.default)(url, {
46
+ headers: {
47
+ Accept: "application/json",
48
+ },
49
+ signal: controller.signal,
50
+ });
51
+ if (!response.ok) {
52
+ let errorBody;
53
+ try {
54
+ errorBody = await response.json();
55
+ }
56
+ catch {
57
+ // ignore parse errors
58
+ }
59
+ throwHttpError(response.status, response.statusText, errorBody);
60
+ }
61
+ const json = await response.json();
62
+ if (opts?.transform) {
63
+ return opts.transform(json);
64
+ }
65
+ return json;
66
+ }
67
+ finally {
68
+ clearTimeout(timeoutId);
69
+ }
70
+ }
71
+ async postJson(path, body, opts) {
72
+ const url = (0, buildUrl_1.buildUrl)(this.url, path);
73
+ const controller = new AbortController();
74
+ const timeoutId = setTimeout(() => controller.abort(), this.timeoutMs);
75
+ try {
76
+ const response = await (0, cross_fetch_1.default)(url, {
77
+ method: "POST",
78
+ headers: {
79
+ "Content-Type": "application/json",
80
+ Accept: "application/json",
81
+ },
82
+ body: JSON.stringify(body, bigIntReplacer),
83
+ signal: controller.signal,
84
+ });
85
+ if (!response.ok) {
86
+ let errorBody;
87
+ try {
88
+ errorBody = await response.json();
89
+ }
90
+ catch {
91
+ // ignore parse errors
92
+ }
93
+ throwHttpError(response.status, response.statusText, errorBody);
94
+ }
95
+ const json = await response.json();
96
+ if (opts?.transform) {
97
+ return opts.transform(json);
98
+ }
99
+ return json;
25
100
  }
26
- const json = await response.json();
27
- if (opts?.transform) {
28
- return opts.transform(json);
101
+ finally {
102
+ clearTimeout(timeoutId);
29
103
  }
30
- return json;
31
104
  }
32
105
  }
33
106
  exports.HttpClient = HttpClient;
@@ -103,7 +103,15 @@ function getMaxLeverageByMinCollateralFactor(minCollateralFactor) {
103
103
  return rounded * factors_1.BASIS_POINTS_DIVISOR;
104
104
  }
105
105
  exports.getMaxLeverageByMinCollateralFactor = getMaxLeverageByMinCollateralFactor;
106
+ // GOLD/SILVER on-hours: MCF 0.009 (9e27) → 100x UI
107
+ const MCF_ON_HOURS = 9n * 10n ** 27n;
108
+ // GOLD/SILVER off-hours: MCF 0.035 (35e27) → 25x UI
109
+ const MCF_OFF_HOURS = 35n * 10n ** 27n;
106
110
  function getMaxAllowedLeverageByMinCollateralFactor(minCollateralFactor) {
111
+ if (minCollateralFactor === MCF_ON_HOURS)
112
+ return 100 * factors_1.BASIS_POINTS_DIVISOR;
113
+ if (minCollateralFactor === MCF_OFF_HOURS)
114
+ return 25 * factors_1.BASIS_POINTS_DIVISOR;
107
115
  return getMaxLeverageByMinCollateralFactor(minCollateralFactor) / 2;
108
116
  }
109
117
  exports.getMaxAllowedLeverageByMinCollateralFactor = getMaxAllowedLeverageByMinCollateralFactor;
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.noopMetrics = void 0;
4
+ exports.noopMetrics = {
5
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
6
+ pushError() { },
7
+ };
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.toBigNumberWithDecimals = exports.roundWithDecimals = exports.getPlusOrMinusSymbol = exports.padDecimals = exports.limitDecimals = exports.getLimitedDisplay = exports.formatAmountFree = exports.formatArrayAmount = exports.formatKeyAmount = exports.formatAmount = exports.numberWithCommas = exports.formatFactor = exports.formatBalanceAmount = exports.formatAmountHuman = exports.formatPercentageDisplay = exports.formatUsdPrice = exports.formatRatePercentage = exports.formatTokenAmountWithUsd = exports.formatTokenAmount = exports.formatPercentage = exports.formatDeltaUsd = exports.formatBigUsd = exports.formatUsd = exports.adjustForDecimals = exports.bigintToNumber = exports.trimZeroDecimals = exports.numberToBigint = exports.applyFactor = exports.roundUpMagnitudeDivision = exports.getBasisPoints = exports.basisPointsToFloat = exports.expandDecimals = exports.safeDivide = exports.isNonZero = exports.TRIGGER_PREFIX_BELOW = exports.TRIGGER_PREFIX_ABOVE = exports.PERCENT_PRECISION_DECIMALS = exports.MaxInt256 = exports.MaxUint256 = exports.BN_NEGATIVE_ONE = exports.BN_ONE = exports.BN_ZERO = exports.FLOAT_PRECISION_SQRT = exports.FLOAT_PRECISION_SQRT_DECIMALS = exports.PRECISION = exports.PRECISION_DECIMALS = exports.BASIS_POINTS_DECIMALS = exports.BASIS_POINTS_DIVISOR_BIGINT = exports.BASIS_POINTS_DIVISOR = exports.USD_DECIMALS = void 0;
4
- exports.absDiffBps = exports.clamp = exports.calculateDisplayDecimals = exports.deserializeBigIntsInObject = exports.serializeBigIntsInObject = exports.removeTrailingZeros = exports.maxbigint = exports.minBigNumber = exports.roundBigIntToDecimals = exports.roundToOrder = exports.roundToTwoDecimals = exports.roundUpDivision = exports.parseValue = exports.bigNumberify = void 0;
3
+ exports.getPlusOrMinusSymbol = exports.padDecimals = exports.limitDecimals = exports.getLimitedDisplay = exports.formatAmountFree = exports.formatArrayAmount = exports.formatKeyAmount = exports.formatAmount = exports.numberWithCommas = exports.formatFactor = exports.formatBalanceAmount = exports.formatAmountHuman = exports.formatNumberHuman = exports.formatPercentageDisplay = exports.formatUsdPrice = exports.formatRatePercentage = exports.formatTokenAmountWithUsd = exports.formatTokenAmount = exports.formatPercentage = exports.formatDeltaUsd = exports.formatBigUsd = exports.formatUsd = exports.adjustForDecimals = exports.bigintToNumber = exports.trimZeroDecimals = exports.numberToBigint = exports.applyFactor = exports.roundUpMagnitudeDivision = exports.getBasisPoints = exports.basisPointsToFloat = exports.toBigInt = exports.expandDecimals = exports.safeDivide = exports.isNonZero = exports.TRIGGER_PREFIX_BELOW = exports.TRIGGER_PREFIX_ABOVE = exports.PERCENT_PRECISION_DECIMALS = exports.MaxInt256 = exports.MaxUint256 = exports.BN_NEGATIVE_ONE = exports.BN_ONE = exports.BN_ZERO = exports.FLOAT_PRECISION_SQRT = exports.FLOAT_PRECISION_SQRT_DECIMALS = exports.PRECISION = exports.PRECISION_DECIMALS = exports.BASIS_POINTS_DECIMALS = exports.BASIS_POINTS_DIVISOR_BIGINT = exports.BASIS_POINTS_DIVISOR = exports.USD_DECIMALS = void 0;
4
+ exports.absDiffBps = exports.clamp = exports.calculateDisplayDecimals = exports.deserializeBigIntsInObject = exports.serializeBigIntsInObject = exports.removeTrailingZeros = exports.maxbigint = exports.minBigNumber = exports.roundBigIntToDecimals = exports.roundToOrder = exports.roundToTwoDecimals = exports.roundUpDivision = exports.parseValue = exports.toBigNumberWithDecimals = exports.roundWithDecimals = void 0;
5
5
  const viem_1 = require("viem");
6
6
  const bigmath_1 = require("../bigmath");
7
7
  exports.USD_DECIMALS = 30;
@@ -34,6 +34,23 @@ function expandDecimals(n, decimals) {
34
34
  return BigInt(n) * 10n ** BigInt(decimals);
35
35
  }
36
36
  exports.expandDecimals = expandDecimals;
37
+ function toBigInt(value) {
38
+ try {
39
+ if (value === undefined || value === null) {
40
+ return undefined;
41
+ }
42
+ if (typeof value === "bigint") {
43
+ return value;
44
+ }
45
+ return BigInt(value);
46
+ }
47
+ catch (e) {
48
+ // eslint-disable-next-line no-console
49
+ console.error("toBigInt error", e);
50
+ return undefined;
51
+ }
52
+ }
53
+ exports.toBigInt = toBigInt;
37
54
  function basisPointsToFloat(basisPoints) {
38
55
  return (basisPoints * exports.PRECISION) / exports.BASIS_POINTS_DIVISOR_BIGINT;
39
56
  }
@@ -274,11 +291,7 @@ function formatPercentageDisplay(percentage, hideThreshold) {
274
291
  return `${percentage}%`;
275
292
  }
276
293
  exports.formatPercentageDisplay = formatPercentageDisplay;
277
- function formatAmountHuman(amount, tokenDecimals, showDollar = false, displayDecimals = 1) {
278
- if (amount === undefined) {
279
- return "...";
280
- }
281
- let n = Number((0, exports.formatAmount)(amount, tokenDecimals));
294
+ function formatNumberHuman(n, showDollar = false, displayDecimals = 1) {
282
295
  // For large numbers, we can neglect the decimals to avoid decimals in cases like 9999999.99999
283
296
  if (n >= 1000000) {
284
297
  n = Math.round(n);
@@ -297,6 +310,14 @@ function formatAmountHuman(amount, tokenDecimals, showDollar = false, displayDec
297
310
  }
298
311
  return `${isNegative ? "-" : ""}${sign}${absN.toFixed(displayDecimals)}`;
299
312
  }
313
+ exports.formatNumberHuman = formatNumberHuman;
314
+ function formatAmountHuman(amount, tokenDecimals, showDollar = false, displayDecimals = 1) {
315
+ if (amount === undefined) {
316
+ return "...";
317
+ }
318
+ let n = Number((0, exports.formatAmount)(amount, tokenDecimals));
319
+ return formatNumberHuman(n, showDollar, displayDecimals);
320
+ }
300
321
  exports.formatAmountHuman = formatAmountHuman;
301
322
  function formatBalanceAmount(amount, tokenDecimals, tokenSymbol, { showZero = false, toExponential = true, isStable = false, signed = false, } = {}) {
302
323
  if (amount === undefined)
@@ -526,25 +547,6 @@ function toBigNumberWithDecimals(value, decimals) {
526
547
  }
527
548
  }
528
549
  exports.toBigNumberWithDecimals = toBigNumberWithDecimals;
529
- /**
530
- *
531
- * @deprecated Use BigInt instead
532
- */
533
- function bigNumberify(n) {
534
- try {
535
- if (n === undefined)
536
- throw new Error("n is undefined");
537
- if (n === null)
538
- throw new Error("n is null");
539
- return BigInt(n);
540
- }
541
- catch (e) {
542
- // eslint-disable-next-line no-console
543
- console.error("bigNumberify error", e);
544
- return undefined;
545
- }
546
- }
547
- exports.bigNumberify = bigNumberify;
548
550
  const parseValue = (value, tokenDecimals) => {
549
551
  const pValue = parseFloat(value);
550
552
  if (isNaN(pValue) || !isFinite(pValue)) {
@@ -557,7 +559,7 @@ const parseValue = (value, tokenDecimals) => {
557
559
  if (amount > MAX_ALLOWED || amount < -MAX_ALLOWED) {
558
560
  return undefined;
559
561
  }
560
- return bigNumberify(amount);
562
+ return toBigInt(amount);
561
563
  };
562
564
  exports.parseValue = parseValue;
563
565
  function roundUpDivision(a, b) {
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.executeExpressOrder = exports.signPreparedOrder = exports.fetchOrderStatus = exports.prepareCollateral = exports.prepareCancelOrder = exports.prepareEditOrder = exports.submitOrder = exports.prepareOrder = void 0;
4
+ const validateTypedData_1 = require("./validateTypedData");
5
+ function parseEstimates(raw) {
6
+ if (!raw)
7
+ return undefined;
8
+ return {
9
+ positionPriceImpactDeltaUsd: BigInt(raw.positionPriceImpactDeltaUsd),
10
+ swapPriceImpactDeltaUsd: BigInt(raw.swapPriceImpactDeltaUsd),
11
+ executionFeeAmount: BigInt(raw.executionFeeAmount),
12
+ acceptablePrice: BigInt(raw.acceptablePrice),
13
+ sizeDeltaUsd: BigInt(raw.sizeDeltaUsd),
14
+ positionFeeUsd: BigInt(raw.positionFeeUsd),
15
+ borrowingFeeUsd: BigInt(raw.borrowingFeeUsd),
16
+ fundingFeeUsd: BigInt(raw.fundingFeeUsd),
17
+ };
18
+ }
19
+ function parsePrepareResponse(raw) {
20
+ return { ...raw, estimates: parseEstimates(raw.estimates) };
21
+ }
22
+ async function prepareOrder(ctx, request) {
23
+ return ctx.api.postJson("/orders/txns/prepare", request, {
24
+ transform: parsePrepareResponse,
25
+ });
26
+ }
27
+ exports.prepareOrder = prepareOrder;
28
+ async function submitOrder(ctx, request) {
29
+ return ctx.api.postJson("/orders/txns/submit", request);
30
+ }
31
+ exports.submitOrder = submitOrder;
32
+ async function prepareEditOrder(ctx, request) {
33
+ return ctx.api.postJson("/orders/txns/edit/prepare", request, {
34
+ transform: parsePrepareResponse,
35
+ });
36
+ }
37
+ exports.prepareEditOrder = prepareEditOrder;
38
+ async function prepareCancelOrder(ctx, request) {
39
+ return ctx.api.postJson("/orders/txns/cancel/prepare", request, {
40
+ transform: parsePrepareResponse,
41
+ });
42
+ }
43
+ exports.prepareCancelOrder = prepareCancelOrder;
44
+ async function prepareCollateral(ctx, request) {
45
+ return ctx.api.postJson("/orders/txns/collateral/prepare", request, {
46
+ transform: parsePrepareResponse,
47
+ });
48
+ }
49
+ exports.prepareCollateral = prepareCollateral;
50
+ async function fetchOrderStatus(ctx, request) {
51
+ return ctx.api.postJson("/orders/txns/status", request);
52
+ }
53
+ exports.fetchOrderStatus = fetchOrderStatus;
54
+ async function signPreparedOrder(prepared, signer, chainId, accountAddress) {
55
+ if (prepared.payloadType !== "typed-data") {
56
+ throw new Error(`Cannot sign payloadType "${prepared.payloadType}" with signTypedData. ` +
57
+ `Classic transactions must be signed and sent by the wallet directly.`);
58
+ }
59
+ const typedData = prepared.payload.typedData;
60
+ if (!typedData) {
61
+ throw new Error("Missing typedData in prepare response payload");
62
+ }
63
+ const domain = typedData.domain;
64
+ const types = typedData.types;
65
+ const message = typedData.message;
66
+ if (chainId !== undefined) {
67
+ (0, validateTypedData_1.validateOrderTypedData)(domain, types, message, chainId, signer.address, accountAddress);
68
+ }
69
+ return signer.signTypedData(domain, types, message);
70
+ }
71
+ exports.signPreparedOrder = signPreparedOrder;
72
+ async function executeExpressOrder(ctx, request, signer, accountAddress) {
73
+ const prepared = await prepareOrder(ctx, request);
74
+ const signature = await signPreparedOrder(prepared, signer, ctx.chainId, accountAddress);
75
+ return submitOrder(ctx, {
76
+ mode: prepared.mode,
77
+ requestId: prepared.requestId,
78
+ signature,
79
+ from: accountAddress ?? signer.address,
80
+ idempotencyKey: prepared.idempotencyKey,
81
+ eip712Data: {
82
+ batchParams: prepared.payload.batchParams,
83
+ relayParams: prepared.payload.relayParams,
84
+ subaccountApproval: request.subaccountApproval,
85
+ },
86
+ });
87
+ }
88
+ exports.executeExpressOrder = executeExpressOrder;
@@ -15,3 +15,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./utils"), exports);
18
+ __exportStar(require("./api"), exports);
19
+ __exportStar(require("./simulation"), exports);