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

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 (229) 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 +484 -0
  4. package/build/cjs/src/clients/v2/__tests__/editCancel.spec.js +260 -0
  5. package/build/cjs/src/clients/v2/__tests__/errors.spec.js +263 -0
  6. package/build/cjs/src/clients/v2/__tests__/increase.spec.js +777 -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 +135 -0
  10. package/build/cjs/src/clients/v2/index.js +171 -27
  11. package/build/cjs/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +48 -0
  12. package/build/cjs/src/codegen/prebuilt/hashedMarketConfigKeys.json +1082 -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/api.js +17 -5
  16. package/build/cjs/src/configs/chains.js +11 -1
  17. package/build/cjs/src/configs/contracts.js +7 -7
  18. package/build/cjs/src/configs/markets.js +43 -1
  19. package/build/cjs/src/configs/tokens.js +63 -132
  20. package/build/cjs/src/test/mock.js +1 -1
  21. package/build/cjs/src/utils/__tests__/markets.spec.js +10 -0
  22. package/build/cjs/src/utils/__tests__/orderTransactions/decreaseOrders.spec.js +2 -0
  23. package/build/cjs/src/utils/__tests__/orderTransactions/increaseOrders.spec.js +2 -0
  24. package/build/cjs/src/utils/__tests__/orderTransactions/swapOrders.spec.js +1 -0
  25. package/build/cjs/src/utils/__tests__/positions.spec.js +59 -7
  26. package/build/cjs/src/utils/__tests__/uiFeeReceiver.spec.js +34 -0
  27. package/build/cjs/src/utils/balances/api.js +63 -0
  28. package/build/cjs/src/utils/buyback/api.js +7 -0
  29. package/build/cjs/src/utils/buyback/types.js +2 -0
  30. package/build/cjs/src/utils/errors/index.js +1 -0
  31. package/build/cjs/src/utils/errors/isIgnoredEstimateGasError.js +23 -0
  32. package/build/cjs/src/utils/express/index.js +18 -0
  33. package/build/cjs/src/utils/express/types.js +2 -0
  34. package/build/cjs/src/utils/express/utils/batchOrderUtils.js +218 -0
  35. package/build/cjs/src/utils/express/utils/bridgeOutUtils.js +73 -0
  36. package/build/cjs/src/utils/express/utils/estimateExpressParams.js +243 -0
  37. package/build/cjs/src/utils/express/utils/expressParamsUtils.js +22 -0
  38. package/build/cjs/src/utils/express/utils/fetchGelatoGasTankBalance.js +13 -0
  39. package/build/cjs/src/utils/express/utils/gelatoRelayUtils.js +77 -0
  40. package/build/cjs/src/utils/express/utils/globalExpressParams.js +40 -0
  41. package/build/cjs/src/utils/express/utils/index.js +27 -0
  42. package/build/cjs/src/utils/express/utils/oracleParamsUtils.js +49 -0
  43. package/build/cjs/src/utils/express/utils/referralUtils.js +35 -0
  44. package/build/cjs/src/utils/express/utils/relayParamsUtils.js +201 -0
  45. package/build/cjs/src/utils/fees/executionFee.js +8 -1
  46. package/build/cjs/src/utils/fees/priceImpact.js +1 -2
  47. package/build/cjs/src/utils/http/http.js +86 -13
  48. package/build/cjs/src/utils/http/httpFallback.js +65 -0
  49. package/build/cjs/src/utils/markets/__tests__/mockMarkets.js +4 -0
  50. package/build/cjs/src/utils/markets/hashKeys.js +16 -0
  51. package/build/cjs/src/utils/markets/multicall.js +20 -0
  52. package/build/cjs/src/utils/markets/utils.js +8 -0
  53. package/build/cjs/src/utils/metrics/index.js +7 -0
  54. package/build/cjs/src/utils/numbers/utils.js +29 -27
  55. package/build/cjs/src/utils/orderTransactions/api.js +88 -0
  56. package/build/cjs/src/utils/orderTransactions/index.js +1 -0
  57. package/build/cjs/src/utils/orderTransactions/utils.js +4 -1
  58. package/build/cjs/src/utils/orderTransactions/validateTypedData.js +89 -0
  59. package/build/cjs/src/utils/positions/utils.js +5 -19
  60. package/build/cjs/src/utils/rpc/createViemRpc.js +39 -0
  61. package/build/cjs/src/utils/rpc/index.js +5 -0
  62. package/build/cjs/src/utils/signer/index.js +5 -0
  63. package/build/cjs/src/utils/signer/privateKeySigner.js +42 -0
  64. package/build/cjs/src/utils/subaccount/api.js +22 -0
  65. package/build/cjs/src/utils/subaccount/generateSubaccount.js +19 -0
  66. package/build/cjs/src/utils/subaccount/getEmptySubaccountApproval.js +24 -0
  67. package/build/cjs/src/utils/subaccount/getSubaccountApprovalTypedData.js +46 -0
  68. package/build/cjs/src/utils/subaccount/hashSubaccountApproval.js +28 -0
  69. package/build/cjs/src/utils/subaccount/index.js +30 -0
  70. package/build/cjs/src/utils/subaccount/types.js +2 -0
  71. package/build/cjs/src/utils/swap/__tests__/mockRouting.spec.js +49 -0
  72. package/build/cjs/src/utils/swap/__tests__/swapStats.spec.js +63 -0
  73. package/build/cjs/src/utils/swap/buildSwapStrategy.js +10 -2
  74. package/build/cjs/src/utils/swap/swapRouting.js +7 -2
  75. package/build/cjs/src/utils/swap/swapStats.js +90 -6
  76. package/build/cjs/src/utils/swap/swapValues.js +8 -2
  77. package/build/cjs/src/utils/trade/increase.js +7 -1
  78. package/build/cjs/src/utils/trade/types.js +1 -1
  79. package/build/cjs/src/utils/tradeHistory/utils.js +14 -28
  80. package/build/cjs/src/utils/twap/index.js +4 -1
  81. package/build/cjs/src/utils/twap/uiFeeReceiver.js +23 -7
  82. package/build/esm/scripts/subsquid-codegen.js +1 -1
  83. package/build/esm/src/clients/v2/__tests__/data.spec.js +83 -0
  84. package/build/esm/src/clients/v2/__tests__/decrease.spec.js +482 -0
  85. package/build/esm/src/clients/v2/__tests__/editCancel.spec.js +258 -0
  86. package/build/esm/src/clients/v2/__tests__/errors.spec.js +261 -0
  87. package/build/esm/src/clients/v2/__tests__/increase.spec.js +775 -0
  88. package/build/esm/src/clients/v2/__tests__/subaccount.spec.js +72 -0
  89. package/build/esm/src/clients/v2/__tests__/swap.spec.js +190 -0
  90. package/build/esm/src/clients/v2/__tests__/testUtil.js +123 -0
  91. package/build/esm/src/clients/v2/index.js +145 -5
  92. package/build/esm/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +48 -0
  93. package/build/esm/src/codegen/prebuilt/hashedMarketConfigKeys.json +1082 -0
  94. package/build/esm/src/codegen/prebuilt/hashedMarketValuesKeys.json +90 -0
  95. package/build/esm/src/codegen/subsquid.js +321 -0
  96. package/build/esm/src/configs/api.js +15 -4
  97. package/build/esm/src/configs/chains.js +11 -1
  98. package/build/esm/src/configs/contracts.js +7 -7
  99. package/build/esm/src/configs/markets.js +43 -1
  100. package/build/esm/src/configs/tokens.js +62 -130
  101. package/build/esm/src/test/mock.js +1 -1
  102. package/build/esm/src/utils/__tests__/markets.spec.js +10 -0
  103. package/build/esm/src/utils/__tests__/orderTransactions/decreaseOrders.spec.js +2 -0
  104. package/build/esm/src/utils/__tests__/orderTransactions/increaseOrders.spec.js +2 -0
  105. package/build/esm/src/utils/__tests__/orderTransactions/swapOrders.spec.js +1 -0
  106. package/build/esm/src/utils/__tests__/positions.spec.js +60 -8
  107. package/build/esm/src/utils/__tests__/uiFeeReceiver.spec.js +35 -1
  108. package/build/esm/src/utils/balances/api.js +54 -0
  109. package/build/esm/src/utils/buyback/api.js +3 -0
  110. package/build/esm/src/utils/buyback/types.js +1 -0
  111. package/build/esm/src/utils/errors/index.js +1 -0
  112. package/build/esm/src/utils/errors/isIgnoredEstimateGasError.js +19 -0
  113. package/build/esm/src/utils/express/index.js +2 -0
  114. package/build/esm/src/utils/express/types.js +1 -0
  115. package/build/esm/src/utils/express/utils/batchOrderUtils.js +210 -0
  116. package/build/esm/src/utils/express/utils/bridgeOutUtils.js +69 -0
  117. package/build/esm/src/utils/express/utils/estimateExpressParams.js +237 -0
  118. package/build/esm/src/utils/express/utils/expressParamsUtils.js +16 -0
  119. package/build/esm/src/utils/express/utils/fetchGelatoGasTankBalance.js +9 -0
  120. package/build/esm/src/utils/express/utils/gelatoRelayUtils.js +71 -0
  121. package/build/esm/src/utils/express/utils/globalExpressParams.js +36 -0
  122. package/build/esm/src/utils/express/utils/index.js +11 -0
  123. package/build/esm/src/utils/express/utils/oracleParamsUtils.js +42 -0
  124. package/build/esm/src/utils/express/utils/referralUtils.js +30 -0
  125. package/build/esm/src/utils/express/utils/relayParamsUtils.js +192 -0
  126. package/build/esm/src/utils/fees/executionFee.js +6 -0
  127. package/build/esm/src/utils/fees/priceImpact.js +1 -2
  128. package/build/esm/src/utils/http/http.js +84 -12
  129. package/build/esm/src/utils/http/httpFallback.js +61 -0
  130. package/build/esm/src/utils/markets/__tests__/mockMarkets.js +4 -0
  131. package/build/esm/src/utils/markets/hashKeys.js +17 -1
  132. package/build/esm/src/utils/markets/multicall.js +20 -0
  133. package/build/esm/src/utils/markets/utils.js +8 -0
  134. package/build/esm/src/utils/metrics/index.js +4 -0
  135. package/build/esm/src/utils/numbers/utils.js +25 -24
  136. package/build/esm/src/utils/orderTransactions/api.js +77 -0
  137. package/build/esm/src/utils/orderTransactions/index.js +1 -0
  138. package/build/esm/src/utils/orderTransactions/utils.js +4 -1
  139. package/build/esm/src/utils/orderTransactions/validateTypedData.js +84 -0
  140. package/build/esm/src/utils/positions/utils.js +5 -19
  141. package/build/esm/src/utils/rpc/createViemRpc.js +35 -0
  142. package/build/esm/src/utils/rpc/index.js +1 -0
  143. package/build/esm/src/utils/signer/index.js +1 -0
  144. package/build/esm/src/utils/signer/privateKeySigner.js +38 -0
  145. package/build/esm/src/utils/subaccount/api.js +16 -0
  146. package/build/esm/src/utils/subaccount/generateSubaccount.js +15 -0
  147. package/build/esm/src/utils/subaccount/getEmptySubaccountApproval.js +20 -0
  148. package/build/esm/src/utils/subaccount/getSubaccountApprovalTypedData.js +42 -0
  149. package/build/esm/src/utils/subaccount/hashSubaccountApproval.js +24 -0
  150. package/build/esm/src/utils/subaccount/index.js +6 -0
  151. package/build/esm/src/utils/subaccount/types.js +1 -0
  152. package/build/esm/src/utils/swap/__tests__/mockRouting.spec.js +49 -0
  153. package/build/esm/src/utils/swap/__tests__/swapStats.spec.js +64 -1
  154. package/build/esm/src/utils/swap/buildSwapStrategy.js +10 -2
  155. package/build/esm/src/utils/swap/swapRouting.js +7 -2
  156. package/build/esm/src/utils/swap/swapStats.js +90 -7
  157. package/build/esm/src/utils/swap/swapValues.js +8 -2
  158. package/build/esm/src/utils/trade/increase.js +7 -1
  159. package/build/esm/src/utils/trade/types.js +1 -1
  160. package/build/esm/src/utils/tradeHistory/utils.js +13 -26
  161. package/build/esm/src/utils/twap/index.js +1 -0
  162. package/build/esm/src/utils/twap/uiFeeReceiver.js +20 -6
  163. package/build/types/src/clients/v2/__tests__/data.spec.d.ts +1 -0
  164. package/build/types/src/clients/v2/__tests__/decrease.spec.d.ts +1 -0
  165. package/build/types/src/clients/v2/__tests__/editCancel.spec.d.ts +1 -0
  166. package/build/types/src/clients/v2/__tests__/errors.spec.d.ts +1 -0
  167. package/build/types/src/clients/v2/__tests__/increase.spec.d.ts +1 -0
  168. package/build/types/src/clients/v2/__tests__/subaccount.spec.d.ts +1 -0
  169. package/build/types/src/clients/v2/__tests__/swap.spec.d.ts +1 -0
  170. package/build/types/src/clients/v2/__tests__/testUtil.d.ts +24 -0
  171. package/build/types/src/clients/v2/index.d.ts +62 -1
  172. package/build/types/src/codegen/prebuilt/index.d.ts +1220 -0
  173. package/build/types/src/codegen/subsquid.d.ts +1276 -44
  174. package/build/types/src/configs/api.d.ts +1 -0
  175. package/build/types/src/configs/chains.d.ts +10 -1
  176. package/build/types/src/configs/contracts.d.ts +6 -6
  177. package/build/types/src/configs/tokens.d.ts +6 -1
  178. package/build/types/src/utils/balances/api.d.ts +39 -0
  179. package/build/types/src/utils/buyback/api.d.ts +5 -0
  180. package/build/types/src/utils/buyback/types.d.ts +15 -0
  181. package/build/types/src/utils/chains/types.d.ts +1 -0
  182. package/build/types/src/utils/errors/index.d.ts +1 -0
  183. package/build/types/src/utils/errors/isIgnoredEstimateGasError.d.ts +2 -0
  184. package/build/types/src/utils/express/index.d.ts +2 -0
  185. package/build/types/src/utils/express/types.d.ts +95 -0
  186. package/build/types/src/utils/express/utils/batchOrderUtils.d.ts +98 -0
  187. package/build/types/src/utils/express/utils/bridgeOutUtils.d.ts +21 -0
  188. package/build/types/src/utils/express/utils/estimateExpressParams.d.ts +37 -0
  189. package/build/types/src/utils/express/utils/expressParamsUtils.d.ts +19 -0
  190. package/build/types/src/utils/express/utils/fetchGelatoGasTankBalance.d.ts +5 -0
  191. package/build/types/src/utils/express/utils/gelatoRelayUtils.d.ts +25 -0
  192. package/build/types/src/utils/express/utils/globalExpressParams.d.ts +31 -0
  193. package/build/types/src/utils/express/utils/index.d.ts +11 -0
  194. package/build/types/src/utils/express/utils/oracleParamsUtils.d.ts +10 -0
  195. package/build/types/src/utils/express/utils/referralUtils.d.ts +17 -0
  196. package/build/types/src/utils/express/utils/relayParamsUtils.d.ts +49 -0
  197. package/build/types/src/utils/fees/executionFee.d.ts +1 -0
  198. package/build/types/src/utils/http/http.d.ts +16 -1
  199. package/build/types/src/utils/http/httpFallback.d.ts +18 -0
  200. package/build/types/src/utils/http/types.d.ts +3 -0
  201. package/build/types/src/utils/markets/types.d.ts +5 -1
  202. package/build/types/src/utils/metrics/index.d.ts +4 -0
  203. package/build/types/src/utils/numbers/utils.d.ts +2 -5
  204. package/build/types/src/utils/orderTransactions/api.d.ts +158 -0
  205. package/build/types/src/utils/orderTransactions/index.d.ts +1 -0
  206. package/build/types/src/utils/orderTransactions/validateTypedData.d.ts +6 -0
  207. package/build/types/src/utils/positions/utils.d.ts +1 -9
  208. package/build/types/src/utils/rpc/createViemRpc.d.ts +3 -0
  209. package/build/types/src/utils/rpc/index.d.ts +26 -0
  210. package/build/types/src/utils/signer/index.d.ts +23 -0
  211. package/build/types/src/utils/signer/privateKeySigner.d.ts +19 -0
  212. package/build/types/src/utils/subaccount/api.d.ts +51 -0
  213. package/build/types/src/utils/subaccount/generateSubaccount.d.ts +8 -0
  214. package/build/types/src/utils/subaccount/getEmptySubaccountApproval.d.ts +9 -0
  215. package/build/types/src/utils/subaccount/getSubaccountApprovalTypedData.d.ts +24 -0
  216. package/build/types/src/utils/subaccount/hashSubaccountApproval.d.ts +1 -0
  217. package/build/types/src/utils/subaccount/index.d.ts +7 -0
  218. package/build/types/src/utils/subaccount/types.d.ts +55 -0
  219. package/build/types/src/utils/swap/buildSwapStrategy.d.ts +6 -2
  220. package/build/types/src/utils/swap/swapStats.d.ts +14 -0
  221. package/build/types/src/utils/swap/swapValues.d.ts +4 -0
  222. package/build/types/src/utils/tokens/types.d.ts +0 -1
  223. package/build/types/src/utils/trade/increase.d.ts +2 -0
  224. package/build/types/src/utils/trade/types.d.ts +2 -1
  225. package/build/types/src/utils/tradeHistory/utils.d.ts +0 -1
  226. package/build/types/src/utils/twap/index.d.ts +1 -0
  227. package/build/types/src/utils/twap/types.d.ts +2 -0
  228. package/build/types/src/utils/twap/uiFeeReceiver.d.ts +10 -2
  229. package/package.json +40 -3
@@ -0,0 +1,237 @@
1
+ import { size } from "viem";
2
+ import { BASIS_POINTS_DIVISOR_BIGINT } from "../../../configs/factors";
3
+ import { NATIVE_TOKEN_ADDRESS } from "../../../configs/tokens";
4
+ import { bigMath } from "../../bigmath";
5
+ import { extendError, isIgnoredEstimateGasError } from "../../errors";
6
+ import { applyGasBuffer, approximateL1GasBuffer, estimateRelayerGasLimit } from "../../fees/executionFee";
7
+ import { noopMetrics } from "../../metrics";
8
+ import { applyFactor } from "../../numbers";
9
+ import { nowInSeconds } from "../../time";
10
+ import { ExpressEstimationError, ExpressEstimationInsufficientGasPaymentTokenBalanceError, getIsValidExpressParams, } from "./expressParamsUtils";
11
+ import { getExpressContractAddress, getRawRelayerParams, getRelayerFeeParams } from "./relayParamsUtils";
12
+ export function getNeedTokenApprove(tokenAllowanceData, tokenAddress, amountToSpend, permits) {
13
+ if (tokenAddress === NATIVE_TOKEN_ADDRESS || amountToSpend === undefined || amountToSpend <= 0n) {
14
+ return false;
15
+ }
16
+ if (!tokenAllowanceData || !tokenAddress || tokenAllowanceData[tokenAddress] === undefined) {
17
+ return true;
18
+ }
19
+ const shouldApprove = amountToSpend > tokenAllowanceData[tokenAddress];
20
+ const signedPermit = permits.find((permit) => permit.token === tokenAddress && BigInt(permit.value) >= amountToSpend && Number(permit.deadline) > nowInSeconds());
21
+ return shouldApprove && !signedPermit;
22
+ }
23
+ export function getGasPaymentValidations({ gasPaymentToken, gasPaymentTokenAmount, gasPaymentTokenAsCollateralAmount, gasPaymentAllowanceData, tokenPermits, isGmxAccount, }) {
24
+ const gasTokenAmountWithBuffer = bigMath.mulDiv(gasPaymentTokenAmount, 13n, 10n);
25
+ const totalGasPaymentTokenAmount = gasPaymentTokenAsCollateralAmount + gasTokenAmountWithBuffer;
26
+ const tokenBalance = isGmxAccount ? gasPaymentToken.gmxAccountBalance : gasPaymentToken.walletBalance;
27
+ const isOutGasTokenBalance = tokenBalance === undefined || totalGasPaymentTokenAmount > tokenBalance;
28
+ const needGasPaymentTokenApproval = isGmxAccount
29
+ ? false
30
+ : getNeedTokenApprove(gasPaymentAllowanceData, gasPaymentToken.address, totalGasPaymentTokenAmount, tokenPermits);
31
+ return {
32
+ isOutGasTokenBalance,
33
+ needGasPaymentTokenApproval,
34
+ isValid: !isOutGasTokenBalance && !needGasPaymentTokenApproval,
35
+ };
36
+ }
37
+ export async function estimateExpressParams({ chainId, isGmxAccount, transactionParams, globalExpressParams, estimationMethod = "approximate", requireValidations = true, subaccount: rawSubaccount, throwOnInvalid = false, overrideGasLimit, rpc, simulationOrigin, stateOverride, metrics = noopMetrics, gasPaymentAllowanceData, getSubaccountValidations, }) {
38
+ if (requireValidations && !transactionParams.isValid) {
39
+ if (throwOnInvalid) {
40
+ throw new ExpressEstimationError("transactionParams is invalid");
41
+ }
42
+ return undefined;
43
+ }
44
+ const { findFeeSwapPath, gasLimits, gasPaymentToken, relayerFeeToken, l1Reference, tokenPermits: rawTokenPermits, gasPrice, bufferBps, } = globalExpressParams;
45
+ const { expressTransactionBuilder, gasPaymentTokenAsCollateralAmount, executionFeeAmount, executionGasLimit, transactionPayloadGasLimit, transactionExternalCalls, subaccountActions, account, } = transactionParams;
46
+ const subaccountRouterAddress = rawSubaccount
47
+ ? getExpressContractAddress(chainId, {
48
+ isSubaccount: true,
49
+ isMultichain: isGmxAccount,
50
+ scope: "subaccount",
51
+ })
52
+ : undefined;
53
+ const subaccountValidations = rawSubaccount && getSubaccountValidations && subaccountRouterAddress
54
+ ? getSubaccountValidations({
55
+ requiredActions: subaccountActions,
56
+ subaccount: rawSubaccount,
57
+ subaccountRouterAddress,
58
+ })
59
+ : undefined;
60
+ const subaccount = subaccountValidations?.isValid ? rawSubaccount : undefined;
61
+ const tokenPermits = isGmxAccount ? [] : rawTokenPermits;
62
+ // --- Pass 1: base estimate with assumed feeSwapsCount=1, oraclePriceCount=2 ---
63
+ const baseRelayerGasLimit = overrideGasLimit ??
64
+ estimateRelayerGasLimit({
65
+ gasLimits,
66
+ tokenPermitsCount: tokenPermits.length,
67
+ feeSwapsCount: 1,
68
+ feeExternalCallsGasLimit: 0n,
69
+ oraclePriceCount: 2,
70
+ l1GasLimit: l1Reference?.gasLimit ?? 0n,
71
+ transactionPayloadGasLimit,
72
+ });
73
+ const baseRelayerFeeAmount = baseRelayerGasLimit * gasPrice;
74
+ const baseTotalRelayerFeeTokenAmount = baseRelayerFeeAmount + executionFeeAmount;
75
+ const baseRelayFeeParams = getRelayerFeeParams({
76
+ chainId,
77
+ account,
78
+ gasPaymentToken,
79
+ relayerFeeToken,
80
+ relayerFeeAmount: baseRelayerFeeAmount,
81
+ totalRelayerFeeTokenAmount: baseTotalRelayerFeeTokenAmount,
82
+ gasPaymentTokenAsCollateralAmount,
83
+ transactionExternalCalls,
84
+ feeExternalSwapQuote: undefined,
85
+ findFeeSwapPath,
86
+ });
87
+ if (!baseRelayFeeParams) {
88
+ if (throwOnInvalid) {
89
+ throw new ExpressEstimationError("baseRelayFeeParams is undefined");
90
+ }
91
+ return undefined;
92
+ }
93
+ const baseRelayParams = getRawRelayerParams({
94
+ chainId,
95
+ gasPaymentTokenAddress: gasPaymentToken.address,
96
+ relayerFeeTokenAddress: relayerFeeToken.address,
97
+ feeParams: baseRelayFeeParams.feeParams,
98
+ externalCalls: baseRelayFeeParams.externalCalls,
99
+ tokenPermits,
100
+ });
101
+ // Build txn to measure calldata size for L1 gas buffer
102
+ const baseTxn = await expressTransactionBuilder({
103
+ relayParams: baseRelayParams,
104
+ gasPaymentParams: baseRelayFeeParams.gasPaymentParams,
105
+ subaccount,
106
+ });
107
+ const l1GasLimit = l1Reference
108
+ ? approximateL1GasBuffer({
109
+ l1Reference,
110
+ sizeOfData: BigInt(size(baseTxn.txnData.callData)),
111
+ })
112
+ : 0n;
113
+ // --- Determine gas limit ---
114
+ let gasLimit;
115
+ if (overrideGasLimit !== undefined) {
116
+ gasLimit = overrideGasLimit;
117
+ }
118
+ else if (estimationMethod === "estimateGas") {
119
+ if (!rpc || !simulationOrigin) {
120
+ throw new ExpressEstimationError("rpc and simulationOrigin are required for estimateGas mode");
121
+ }
122
+ const baseGasPaymentValidations = getGasPaymentValidations({
123
+ gasPaymentToken,
124
+ gasPaymentTokenAsCollateralAmount,
125
+ gasPaymentTokenAmount: baseRelayFeeParams.gasPaymentParams.gasPaymentTokenAmount,
126
+ gasPaymentAllowanceData,
127
+ isGmxAccount,
128
+ tokenPermits,
129
+ });
130
+ if (baseGasPaymentValidations.isOutGasTokenBalance ||
131
+ baseGasPaymentValidations.needGasPaymentTokenApproval ||
132
+ !transactionParams.isValid) {
133
+ if (throwOnInvalid) {
134
+ throw new ExpressEstimationInsufficientGasPaymentTokenBalanceError({
135
+ balance: isGmxAccount ? gasPaymentToken.gmxAccountBalance : gasPaymentToken.walletBalance,
136
+ requiredAmount: baseRelayFeeParams.gasPaymentParams.gasPaymentTokenAmount,
137
+ });
138
+ }
139
+ return undefined;
140
+ }
141
+ try {
142
+ const estimated = await rpc.estimateGas({
143
+ from: simulationOrigin,
144
+ to: baseTxn.txnData.to,
145
+ data: baseTxn.txnData.callData,
146
+ value: 0n,
147
+ stateOverride,
148
+ });
149
+ gasLimit = applyGasBuffer(estimated);
150
+ }
151
+ catch (error) {
152
+ if (!isIgnoredEstimateGasError(error)) {
153
+ metrics.pushError(extendError(error, { data: { estimationMethod } }), "expressOrders.estimateGas");
154
+ }
155
+ if (throwOnInvalid) {
156
+ throw new ExpressEstimationError("gas limit estimation failed");
157
+ }
158
+ return undefined;
159
+ }
160
+ }
161
+ else {
162
+ // approximate mode
163
+ gasLimit = estimateRelayerGasLimit({
164
+ gasLimits,
165
+ tokenPermitsCount: tokenPermits.length,
166
+ feeSwapsCount: baseRelayFeeParams.feeParams.feeSwapPath.length,
167
+ feeExternalCallsGasLimit: baseRelayFeeParams.feeExternalSwapGasLimit,
168
+ oraclePriceCount: baseRelayParams.oracleParams.tokens.length,
169
+ l1GasLimit,
170
+ transactionPayloadGasLimit,
171
+ });
172
+ }
173
+ // --- Pass 2: final fee calculation with actual gas limit ---
174
+ let relayerFeeAmount = applyFactor(gasLimit * gasPrice, gasLimits.gelatoRelayFeeMultiplierFactor);
175
+ const buffer = bigMath.mulDiv(relayerFeeAmount, BigInt(bufferBps), BASIS_POINTS_DIVISOR_BIGINT);
176
+ relayerFeeAmount += buffer;
177
+ const totalRelayerFeeTokenAmount = relayerFeeAmount + executionFeeAmount;
178
+ const finalRelayFeeParams = getRelayerFeeParams({
179
+ chainId,
180
+ account,
181
+ gasPaymentToken,
182
+ relayerFeeToken,
183
+ relayerFeeAmount,
184
+ totalRelayerFeeTokenAmount,
185
+ gasPaymentTokenAsCollateralAmount,
186
+ transactionExternalCalls,
187
+ feeExternalSwapQuote: undefined,
188
+ findFeeSwapPath,
189
+ });
190
+ if (!finalRelayFeeParams) {
191
+ if (throwOnInvalid) {
192
+ throw new ExpressEstimationError("finalRelayFeeParams is undefined");
193
+ }
194
+ return undefined;
195
+ }
196
+ const finalRelayParams = getRawRelayerParams({
197
+ chainId,
198
+ gasPaymentTokenAddress: gasPaymentToken.address,
199
+ relayerFeeTokenAddress: relayerFeeToken.address,
200
+ feeParams: finalRelayFeeParams.feeParams,
201
+ externalCalls: finalRelayFeeParams.externalCalls,
202
+ tokenPermits,
203
+ });
204
+ // --- Validations ---
205
+ const gasPaymentValidations = getGasPaymentValidations({
206
+ gasPaymentToken,
207
+ gasPaymentTokenAmount: finalRelayFeeParams.gasPaymentParams.gasPaymentTokenAmount,
208
+ gasPaymentTokenAsCollateralAmount,
209
+ gasPaymentAllowanceData,
210
+ isGmxAccount,
211
+ tokenPermits,
212
+ });
213
+ if (requireValidations && !getIsValidExpressParams({ chainId, gasPaymentValidations })) {
214
+ if (throwOnInvalid) {
215
+ throw new ExpressEstimationInsufficientGasPaymentTokenBalanceError({
216
+ balance: isGmxAccount ? gasPaymentToken.gmxAccountBalance : gasPaymentToken.walletBalance,
217
+ requiredAmount: finalRelayFeeParams.gasPaymentParams.gasPaymentTokenAmount,
218
+ });
219
+ }
220
+ return undefined;
221
+ }
222
+ return {
223
+ chainId,
224
+ subaccount,
225
+ relayParamsPayload: finalRelayParams,
226
+ gasPaymentParams: finalRelayFeeParams.gasPaymentParams,
227
+ executionFeeAmount,
228
+ executionGasLimit,
229
+ estimationMethod: estimationMethod ?? "approximate",
230
+ gasLimit,
231
+ l1GasLimit,
232
+ gasPrice,
233
+ subaccountValidations,
234
+ gasPaymentValidations,
235
+ isGmxAccount,
236
+ };
237
+ }
@@ -0,0 +1,16 @@
1
+ export class ExpressEstimationError extends Error {
2
+ constructor() {
3
+ super(...arguments);
4
+ this.name = "ExpressEstimationError";
5
+ }
6
+ }
7
+ export class ExpressEstimationInsufficientGasPaymentTokenBalanceError extends ExpressEstimationError {
8
+ constructor(params) {
9
+ super();
10
+ this.params = params;
11
+ this.name = "ExpressEstimationInsufficientGasPaymentTokenBalanceError";
12
+ }
13
+ }
14
+ export function getIsValidExpressParams({ gasPaymentValidations, }) {
15
+ return gasPaymentValidations.isValid;
16
+ }
@@ -0,0 +1,9 @@
1
+ import { GELATO_API_KEYS } from "../../../configs/express";
2
+ import { getGelatoRelayerClient } from "../../gelatoRelay";
3
+ export async function fetchGelatoGasTankBalance(chainId) {
4
+ const apiKey = GELATO_API_KEYS[chainId];
5
+ if (!apiKey)
6
+ return undefined;
7
+ const relayer = getGelatoRelayerClient(apiKey);
8
+ return relayer.getBalance();
9
+ }
@@ -0,0 +1,71 @@
1
+ import { TransactionRevertedError, TransactionRejectedError } from "@gelatocloud/gasless";
2
+ import { encodePacked } from "viem";
3
+ import { GELATO_API_KEYS } from "../../../configs/express";
4
+ import { getGelatoRelayerClient, StatusCode } from "../../gelatoRelay/utils";
5
+ export class GelatoRelayError extends Error {
6
+ constructor(message, cause) {
7
+ super(message);
8
+ this.cause = cause;
9
+ this.name = "GelatoRelayError";
10
+ }
11
+ }
12
+ export async function sendToGelatoRelay({ chainId, txnData, }) {
13
+ const data = encodePacked(["bytes", "address", "address", "uint256"], [txnData.callData, txnData.to, txnData.feeToken, txnData.feeAmount]);
14
+ const apiKey = GELATO_API_KEYS[chainId];
15
+ if (!apiKey) {
16
+ throw new GelatoRelayError(`Gelato API key not configured for chain ${chainId}`);
17
+ }
18
+ const relayerClient = getGelatoRelayerClient(apiKey);
19
+ let taskId;
20
+ try {
21
+ taskId = await relayerClient.sendTransaction({
22
+ chainId,
23
+ to: txnData.to,
24
+ data,
25
+ });
26
+ }
27
+ catch (e) {
28
+ throw new GelatoRelayError(`Gelato relay failed: ${e?.message ?? String(e)}`, e);
29
+ }
30
+ if (!taskId) {
31
+ throw new GelatoRelayError("Gelato relay returned no taskId");
32
+ }
33
+ return { taskId, relayerClient };
34
+ }
35
+ export async function waitForGelatoTask(relayerClient, taskId, options) {
36
+ try {
37
+ const receipt = await relayerClient.waitForReceipt({
38
+ id: taskId,
39
+ timeout: options?.timeout ?? 120000,
40
+ pollingInterval: options?.pollingInterval ?? 1000,
41
+ throwOnReverted: true,
42
+ });
43
+ return {
44
+ transactionHash: receipt.transactionHash,
45
+ blockNumber: Number(receipt.blockNumber),
46
+ status: "success",
47
+ statusCode: StatusCode.Success,
48
+ };
49
+ }
50
+ catch (error) {
51
+ if (error instanceof TransactionRevertedError) {
52
+ return {
53
+ transactionHash: error.receipt.transactionHash,
54
+ blockNumber: undefined,
55
+ status: "failed",
56
+ statusCode: StatusCode.Reverted,
57
+ message: error.errorMessage,
58
+ };
59
+ }
60
+ if (error instanceof TransactionRejectedError) {
61
+ return {
62
+ transactionHash: undefined,
63
+ blockNumber: undefined,
64
+ status: "failed",
65
+ statusCode: StatusCode.Rejected,
66
+ message: error.errorMessage,
67
+ };
68
+ }
69
+ throw error;
70
+ }
71
+ }
@@ -0,0 +1,36 @@
1
+ import { EXPRESS_EXTRA_EXECUTION_FEE_BUFFER_BPS, getDefaultGasPaymentToken, getRelayerFeeToken } from "../../../configs/express";
2
+ import { SwapPricingType } from "../../orders/types";
3
+ import { createFindSwapPath } from "../../swap/swapPath";
4
+ export function buildGlobalExpressParams({ chainId, gasLimits, gasPrice, tokensData, marketsInfoData, gasPaymentTokenAddress, tokenPermits = [], l1Reference, bufferBps = EXPRESS_EXTRA_EXECUTION_FEE_BUFFER_BPS, }) {
5
+ const resolvedGasPaymentTokenAddress = gasPaymentTokenAddress ?? getDefaultGasPaymentToken(chainId);
6
+ const relayerFeeToken = getRelayerFeeToken(chainId);
7
+ const findFeeSwapPath = createFindSwapPath({
8
+ chainId,
9
+ fromTokenAddress: resolvedGasPaymentTokenAddress,
10
+ toTokenAddress: relayerFeeToken.address,
11
+ marketsInfoData,
12
+ gasEstimationParams: {
13
+ gasPrice,
14
+ gasLimits,
15
+ tokensData,
16
+ },
17
+ swapPricingType: SwapPricingType.AtomicSwap,
18
+ });
19
+ const gasPaymentToken = tokensData[resolvedGasPaymentTokenAddress];
20
+ const resolvedRelayerFeeToken = tokensData[relayerFeeToken.address];
21
+ return {
22
+ chainId,
23
+ gasLimits,
24
+ gasPrice,
25
+ tokensData,
26
+ marketsInfoData,
27
+ gasPaymentTokenAddress: resolvedGasPaymentTokenAddress,
28
+ relayerFeeTokenAddress: relayerFeeToken.address,
29
+ gasPaymentToken,
30
+ relayerFeeToken: resolvedRelayerFeeToken,
31
+ tokenPermits,
32
+ l1Reference,
33
+ bufferBps,
34
+ findFeeSwapPath,
35
+ };
36
+ }
@@ -0,0 +1,11 @@
1
+ export * from "../types";
2
+ export * from "./oracleParamsUtils";
3
+ export * from "./relayParamsUtils";
4
+ export * from "./batchOrderUtils";
5
+ export * from "./gelatoRelayUtils";
6
+ export * from "./globalExpressParams";
7
+ export * from "./expressParamsUtils";
8
+ export * from "./estimateExpressParams";
9
+ export * from "./fetchGelatoGasTankBalance";
10
+ export * from "./bridgeOutUtils";
11
+ export * from "./referralUtils";
@@ -0,0 +1,42 @@
1
+ import uniq from "lodash/uniq";
2
+ import { getContract } from "../../../configs/contracts";
3
+ import { MARKETS } from "../../../configs/markets";
4
+ import { convertTokenAddress } from "../../../configs/tokens";
5
+ import { getOppositeCollateralFromConfig } from "../../markets";
6
+ function getOracleParams({ chainId, tokenAddresses }) {
7
+ const uniqTokenAddresses = uniq(tokenAddresses.map((tokenAddress) => convertTokenAddress(chainId, tokenAddress, "wrapped")));
8
+ const chainLinkPriceFeedProvider = getContract(chainId, "ChainlinkPriceFeedProvider");
9
+ return {
10
+ tokens: uniqTokenAddresses,
11
+ providers: Array(uniqTokenAddresses.length).fill(chainLinkPriceFeedProvider),
12
+ data: Array(uniqTokenAddresses.length).fill("0x"),
13
+ };
14
+ }
15
+ export function getOracleParamsForRelayParams({ chainId, gasPaymentTokenAddress, relayerFeeTokenAddress, feeSwapPath, externalCalls, }) {
16
+ const tokenAddresses = [gasPaymentTokenAddress, relayerFeeTokenAddress];
17
+ if (externalCalls) {
18
+ tokenAddresses.push(...externalCalls.sendTokens);
19
+ }
20
+ if (feeSwapPath.length) {
21
+ tokenAddresses.push(...getSwapPathOracleTokens({
22
+ chainId,
23
+ initialCollateralAddress: gasPaymentTokenAddress,
24
+ swapPath: feeSwapPath,
25
+ }));
26
+ }
27
+ return getOracleParams({ chainId, tokenAddresses });
28
+ }
29
+ function getSwapPathOracleTokens({ chainId, initialCollateralAddress, swapPath, }) {
30
+ let currentToken = initialCollateralAddress;
31
+ const tokenAddresses = [initialCollateralAddress];
32
+ for (const marketAddress of swapPath) {
33
+ const marketConfig = MARKETS[chainId]?.[marketAddress];
34
+ if (!marketConfig) {
35
+ throw new Error(`Market not found for oracle params: ${marketAddress}`);
36
+ }
37
+ const tokenOut = getOppositeCollateralFromConfig(marketConfig, currentToken);
38
+ currentToken = tokenOut;
39
+ tokenAddresses.push(currentToken, marketConfig.indexTokenAddress);
40
+ }
41
+ return tokenAddresses;
42
+ }
@@ -0,0 +1,30 @@
1
+ import { getContract } from "../../../configs/contracts";
2
+ import { getGelatoRelayRouterDomain, hashRelayParams } from "./relayParamsUtils";
3
+ export async function signSetTraderReferralCode({ signer, relayParams, referralCode, chainId, srcChainId, }) {
4
+ const types = {
5
+ SetTraderReferralCode: [
6
+ { name: "referralCode", type: "bytes32" },
7
+ { name: "relayParams", type: "bytes32" },
8
+ ],
9
+ };
10
+ const domain = getGelatoRelayRouterDomain(srcChainId ?? chainId, getContract(chainId, "MultichainOrderRouter"));
11
+ const typedData = {
12
+ referralCode: referralCode,
13
+ relayParams: hashRelayParams(relayParams),
14
+ };
15
+ return signer.signTypedData(domain, types, typedData);
16
+ }
17
+ export async function signRegisterCode({ signer, relayParams, referralCode, chainId, srcChainId, }) {
18
+ const types = {
19
+ RegisterCode: [
20
+ { name: "referralCode", type: "bytes32" },
21
+ { name: "relayParams", type: "bytes32" },
22
+ ],
23
+ };
24
+ const domain = getGelatoRelayRouterDomain(srcChainId ?? chainId, getContract(chainId, "MultichainOrderRouter"));
25
+ const typedData = {
26
+ referralCode: referralCode,
27
+ relayParams: hashRelayParams(relayParams),
28
+ };
29
+ return signer.signTypedData(domain, types, typedData);
30
+ }
@@ -0,0 +1,192 @@
1
+ import { encodeAbiParameters, keccak256 } from "viem";
2
+ import { abis } from "../../../abis";
3
+ import { getContract } from "../../../configs/contracts";
4
+ import { SwapPricingType } from "../../orders/types";
5
+ import { combineExternalCalls, getEmptyExternalCallsPayload, getExternalCallsPayload, } from "../../orderTransactions";
6
+ import { getSwapAmountsByToValue } from "../../swap";
7
+ import { nowInSeconds } from "../../time";
8
+ import { getOracleParamsForRelayParams } from "./oracleParamsUtils";
9
+ export function getExpressContractAddress(chainId, { isSubaccount, isMultichain, scope, }) {
10
+ let contractName;
11
+ if (isMultichain) {
12
+ switch (scope) {
13
+ case "claims":
14
+ contractName = "MultichainClaimsRouter";
15
+ break;
16
+ case "order":
17
+ contractName = "MultichainOrderRouter";
18
+ break;
19
+ case "subaccount":
20
+ contractName = "MultichainSubaccountRouter";
21
+ break;
22
+ case "glv":
23
+ contractName = "MultichainGlvRouter";
24
+ break;
25
+ case "gm":
26
+ contractName = "MultichainGmRouter";
27
+ break;
28
+ case "transfer":
29
+ contractName = "MultichainTransferRouter";
30
+ break;
31
+ default:
32
+ throw new Error(`Invalid scope: ${scope}`);
33
+ }
34
+ }
35
+ else {
36
+ if (isSubaccount) {
37
+ contractName = "SubaccountGelatoRelayRouter";
38
+ }
39
+ else {
40
+ contractName = "GelatoRelayRouter";
41
+ }
42
+ }
43
+ return getContract(chainId, contractName);
44
+ }
45
+ export function getGelatoRelayRouterDomain(chainId, relayRouterAddress) {
46
+ return {
47
+ name: "GmxBaseGelatoRelayRouter",
48
+ version: "1",
49
+ chainId,
50
+ verifyingContract: relayRouterAddress,
51
+ };
52
+ }
53
+ export function getRelayerFeeParams({ chainId, account, gasPaymentToken, relayerFeeToken, relayerFeeAmount, totalRelayerFeeTokenAmount, gasPaymentTokenAsCollateralAmount, transactionExternalCalls, feeExternalSwapQuote, findFeeSwapPath, }) {
54
+ const gasPaymentParams = {
55
+ gasPaymentToken: gasPaymentToken,
56
+ relayFeeToken: relayerFeeToken,
57
+ gasPaymentTokenAddress: gasPaymentToken.address,
58
+ relayerFeeTokenAddress: relayerFeeToken.address,
59
+ relayerFeeAmount,
60
+ totalRelayerFeeTokenAmount,
61
+ gasPaymentTokenAmount: 0n,
62
+ gasPaymentTokenAsCollateralAmount,
63
+ };
64
+ let feeParams;
65
+ let externalCalls = transactionExternalCalls ?? getEmptyExternalCallsPayload();
66
+ let feeExternalSwapGasLimit = 0n;
67
+ if (relayerFeeToken.address === gasPaymentToken.address) {
68
+ feeParams = {
69
+ feeToken: relayerFeeToken.address,
70
+ feeAmount: totalRelayerFeeTokenAmount,
71
+ feeSwapPath: [],
72
+ };
73
+ gasPaymentParams.gasPaymentTokenAmount = totalRelayerFeeTokenAmount;
74
+ }
75
+ else {
76
+ let feeSwapAmounts;
77
+ if (findFeeSwapPath) {
78
+ feeSwapAmounts = getSwapAmountsByToValue({
79
+ tokenIn: gasPaymentToken,
80
+ tokenOut: relayerFeeToken,
81
+ amountOut: totalRelayerFeeTokenAmount,
82
+ isLimit: false,
83
+ findSwapPath: findFeeSwapPath,
84
+ swapOptimizationOrder: ["length"],
85
+ uiFeeFactor: 0n,
86
+ marketsInfoData: undefined,
87
+ chainId,
88
+ externalSwapQuoteParams: undefined,
89
+ allowSameTokenSwap: false,
90
+ swapPricingType: SwapPricingType.AtomicSwap,
91
+ });
92
+ }
93
+ const bestFeeSwapStrategy = getBestFeeSwapStrategy(feeSwapAmounts, feeExternalSwapQuote);
94
+ if (bestFeeSwapStrategy?.swapPath) {
95
+ feeParams = {
96
+ feeToken: gasPaymentToken.address,
97
+ feeAmount: bestFeeSwapStrategy.amountIn,
98
+ feeSwapPath: bestFeeSwapStrategy.swapPath,
99
+ };
100
+ gasPaymentParams.gasPaymentTokenAmount = bestFeeSwapStrategy.amountIn;
101
+ gasPaymentParams.totalRelayerFeeTokenAmount = bestFeeSwapStrategy.amountOut;
102
+ }
103
+ else if (bestFeeSwapStrategy?.externalSwapQuote) {
104
+ externalCalls = combineExternalCalls([
105
+ externalCalls,
106
+ getExternalCallsPayload({
107
+ chainId,
108
+ account,
109
+ quote: bestFeeSwapStrategy.externalSwapQuote,
110
+ }),
111
+ ]);
112
+ feeExternalSwapGasLimit = bestFeeSwapStrategy.externalSwapQuote.txnData.estimatedGas;
113
+ feeParams = {
114
+ feeToken: relayerFeeToken.address,
115
+ feeAmount: 0n,
116
+ feeSwapPath: [],
117
+ };
118
+ gasPaymentParams.gasPaymentTokenAmount = bestFeeSwapStrategy.externalSwapQuote.amountIn;
119
+ gasPaymentParams.totalRelayerFeeTokenAmount = bestFeeSwapStrategy.externalSwapQuote.amountOut;
120
+ }
121
+ else {
122
+ return undefined;
123
+ }
124
+ }
125
+ return {
126
+ feeParams,
127
+ externalCalls,
128
+ feeExternalSwapGasLimit,
129
+ gasPaymentParams,
130
+ };
131
+ }
132
+ export function getBestFeeSwapStrategy(internalSwapAmounts, externalSwapQuote) {
133
+ if (externalSwapQuote && externalSwapQuote.usdOut > (internalSwapAmounts?.swapStrategy.swapPathStats?.usdOut ?? 0n)) {
134
+ return {
135
+ amountIn: externalSwapQuote.amountIn,
136
+ amountOut: externalSwapQuote.amountOut,
137
+ externalSwapQuote,
138
+ };
139
+ }
140
+ else if (internalSwapAmounts?.swapStrategy.swapPathStats) {
141
+ return {
142
+ amountIn: internalSwapAmounts.amountIn,
143
+ amountOut: internalSwapAmounts.amountOut,
144
+ swapPath: internalSwapAmounts.swapStrategy.swapPathStats.swapPath,
145
+ };
146
+ }
147
+ return undefined;
148
+ }
149
+ export function getRawRelayerParams({ chainId, gasPaymentTokenAddress, relayerFeeTokenAddress, feeParams, externalCalls, tokenPermits, }) {
150
+ const oracleParams = getOracleParamsForRelayParams({
151
+ chainId,
152
+ externalCalls,
153
+ feeSwapPath: feeParams.feeSwapPath,
154
+ gasPaymentTokenAddress,
155
+ relayerFeeTokenAddress,
156
+ });
157
+ return {
158
+ oracleParams,
159
+ tokenPermits,
160
+ externalCalls,
161
+ fee: feeParams,
162
+ desChainId: BigInt(chainId),
163
+ userNonce: BigInt(nowInSeconds()),
164
+ };
165
+ }
166
+ export function hashRelayParams(relayParams) {
167
+ const encoded = encodeAbiParameters(abis.RelayParams, [
168
+ {
169
+ tokens: relayParams.oracleParams.tokens,
170
+ providers: relayParams.oracleParams.providers,
171
+ data: relayParams.oracleParams.data,
172
+ },
173
+ {
174
+ sendTokens: relayParams.externalCalls.sendTokens,
175
+ sendAmounts: relayParams.externalCalls.sendAmounts,
176
+ externalCallTargets: relayParams.externalCalls.externalCallTargets,
177
+ externalCallDataList: relayParams.externalCalls.externalCallDataList,
178
+ refundTokens: relayParams.externalCalls.refundTokens,
179
+ refundReceivers: relayParams.externalCalls.refundReceivers,
180
+ },
181
+ relayParams.tokenPermits,
182
+ {
183
+ feeToken: relayParams.fee.feeToken,
184
+ feeAmount: relayParams.fee.feeAmount,
185
+ feeSwapPath: relayParams.fee.feeSwapPath,
186
+ },
187
+ relayParams.userNonce,
188
+ relayParams.deadline,
189
+ relayParams.desChainId,
190
+ ]);
191
+ return keccak256(encoded);
192
+ }
@@ -50,6 +50,12 @@ export function estimateRelayerGasLimit({ gasLimits, tokenPermitsCount, feeSwaps
50
50
  const relayParamsGasLimit = feeSwapsGasLimit + oraclePricesGasLimit + tokenPermitsGasLimit + feeExternalCallsGasLimit;
51
51
  return relayParamsGasLimit + transactionPayloadGasLimit + l1GasLimit;
52
52
  }
53
+ const MIN_GAS_LIMIT = 22000n;
54
+ const GAS_BUFFER_BPS = 1000n; // 10%
55
+ export function applyGasBuffer(gasLimit) {
56
+ const clamped = gasLimit < MIN_GAS_LIMIT ? MIN_GAS_LIMIT : gasLimit;
57
+ return clamped + (clamped * GAS_BUFFER_BPS) / 10000n;
58
+ }
53
59
  export function approximateL1GasBuffer({ l1Reference, sizeOfData, }) {
54
60
  const evaluated = Math.round((Number(l1Reference.gasLimit) * Math.log(Number(sizeOfData))) / Math.log(Number(l1Reference.sizeOfData)));
55
61
  const l1GasLimit = Math.abs(evaluated) < Infinity ? BigInt(evaluated) : l1Reference.gasLimit;