@gmx-io/sdk 2.4.0 → 2.6.0-next.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.
Files changed (159) hide show
  1. package/build/cjs/scripts/generate-synthetics-abis.js +17 -2
  2. package/build/cjs/src/abis/CustomErrors.js +98 -0
  3. package/build/cjs/src/abis/CustomErrorsV2_2_1.js +5565 -0
  4. package/build/cjs/src/abis/ExchangeRouterV2_2_1.js +1462 -0
  5. package/build/cjs/src/abis/GelatoRelayRouterV2_2_1.js +1945 -0
  6. package/build/cjs/src/abis/GlvReaderV2_2_1.js +1681 -0
  7. package/build/cjs/src/abis/MultichainClaimsRouterV2_2_1.js +1281 -0
  8. package/build/cjs/src/abis/MultichainGlvRouterV2_2_1.js +1176 -0
  9. package/build/cjs/src/abis/MultichainGmRouterV2_2_1.js +1480 -0
  10. package/build/cjs/src/abis/MultichainOrderRouterV2_2_1.js +2065 -0
  11. package/build/cjs/src/abis/MultichainSubaccountRouterV2_2_1.js +2160 -0
  12. package/build/cjs/src/abis/MultichainTransferRouterV2_2_1.js +1033 -0
  13. package/build/cjs/src/abis/RelayParamsV2_2_1.js +56 -0
  14. package/build/cjs/src/abis/RewardRouterV3.js +675 -0
  15. package/build/cjs/src/abis/SubaccountGelatoRelayRouterV2_2_1.js +2502 -0
  16. package/build/cjs/src/abis/SyntheticsReaderV2_2_1.js +5279 -0
  17. package/build/cjs/src/abis/__tests__/fixtures/arbitrumSepoliaReaders.json +8 -0
  18. package/build/cjs/src/abis/__tests__/getAbi.spec.js +84 -0
  19. package/build/cjs/src/abis/getAbi.js +42 -0
  20. package/build/cjs/src/abis/index.js +4 -1
  21. package/build/cjs/src/clients/v1/modules/orders/orders.js +5 -3
  22. package/build/cjs/src/clients/v1/modules/orders/transactions/createIncreaseOrderTxn.js +3 -1
  23. package/build/cjs/src/clients/v1/modules/orders/transactions/updateOrderTxn.js +21 -25
  24. package/build/cjs/src/clients/v1/modules/orders/utils.js +6 -7
  25. package/build/cjs/src/clients/v1/modules/trades/trades.js +4 -3
  26. package/build/cjs/src/clients/v1/multicall.js +2 -1
  27. package/build/cjs/src/clients/v2/__tests__/decrease.spec.js +0 -2
  28. package/build/cjs/src/clients/v2/__tests__/editCancel.spec.js +0 -3
  29. package/build/cjs/src/clients/v2/__tests__/globalCleanup.js +0 -1
  30. package/build/cjs/src/clients/v2/__tests__/increase.spec.js +0 -2
  31. package/build/cjs/src/clients/v2/__tests__/subaccountLifecycle.spec.js +0 -1
  32. package/build/cjs/src/clients/v2/__tests__/testUtil.js +0 -1
  33. package/build/cjs/src/configs/__tests__/markets.spec.js +8 -1
  34. package/build/cjs/src/configs/chains.js +3 -0
  35. package/build/cjs/src/configs/contracts.js +27 -18
  36. package/build/cjs/src/configs/dataStore.js +13 -3
  37. package/build/cjs/src/utils/__tests__/address.spec.js +50 -0
  38. package/build/cjs/src/utils/__tests__/orderTransactions/exchangeRouterMulticall.spec.js +41 -4
  39. package/build/cjs/src/utils/__tests__/orderTransactions/updateOrder.spec.js +4 -0
  40. package/build/cjs/src/utils/__tests__/referrals.spec.js +36 -4
  41. package/build/cjs/src/utils/address/index.js +17 -0
  42. package/build/cjs/src/utils/address/utils.js +32 -0
  43. package/build/cjs/src/utils/errors/transactionsErrors.js +17 -0
  44. package/build/cjs/src/utils/express/utils/batchOrderUtils.js +14 -9
  45. package/build/cjs/src/utils/express/utils/bridgeOutUtils.js +52 -17
  46. package/build/cjs/src/utils/express/utils/referralUtils.js +38 -25
  47. package/build/cjs/src/utils/express/utils/relayParamsUtils.js +11 -3
  48. package/build/cjs/src/utils/multichain/api.js +17 -8
  49. package/build/cjs/src/utils/orderTransactions/api.js +3 -4
  50. package/build/cjs/src/utils/orderTransactions/utils.js +8 -7
  51. package/build/cjs/src/utils/referrals/utils.js +24 -15
  52. package/build/cjs/src/utils/subaccount/getEmptySubaccountApproval.js +2 -0
  53. package/build/cjs/src/utils/subaccount/getSubaccountApprovalTypedData.js +37 -15
  54. package/build/cjs/src/utils/subaccount/hashSubaccountApproval.js +32 -18
  55. package/build/cjs/src/utils/subaccount/index.js +4 -1
  56. package/build/cjs/src/utils/subaccount/sdkClient.js +1 -1
  57. package/build/cjs/src/utils/subaccount/state.js +10 -1
  58. package/build/cjs/src/utils/tradeHistory/utils.js +6 -6
  59. package/build/esm/scripts/generate-synthetics-abis.js +17 -2
  60. package/build/esm/src/abis/CustomErrors.js +98 -0
  61. package/build/esm/src/abis/CustomErrorsV2_2_1.js +5563 -0
  62. package/build/esm/src/abis/ExchangeRouterV2_2_1.js +1460 -0
  63. package/build/esm/src/abis/GelatoRelayRouterV2_2_1.js +1943 -0
  64. package/build/esm/src/abis/GlvReaderV2_2_1.js +1679 -0
  65. package/build/esm/src/abis/MultichainClaimsRouterV2_2_1.js +1279 -0
  66. package/build/esm/src/abis/MultichainGlvRouterV2_2_1.js +1174 -0
  67. package/build/esm/src/abis/MultichainGmRouterV2_2_1.js +1478 -0
  68. package/build/esm/src/abis/MultichainOrderRouterV2_2_1.js +2063 -0
  69. package/build/esm/src/abis/MultichainSubaccountRouterV2_2_1.js +2158 -0
  70. package/build/esm/src/abis/MultichainTransferRouterV2_2_1.js +1031 -0
  71. package/build/esm/src/abis/RelayParamsV2_2_1.js +54 -0
  72. package/build/esm/src/abis/RewardRouterV3.js +673 -0
  73. package/build/esm/src/abis/SubaccountGelatoRelayRouterV2_2_1.js +2500 -0
  74. package/build/esm/src/abis/SyntheticsReaderV2_2_1.js +5277 -0
  75. package/build/esm/src/abis/__tests__/fixtures/arbitrumSepoliaReaders.json +8 -0
  76. package/build/esm/src/abis/__tests__/getAbi.spec.js +79 -0
  77. package/build/esm/src/abis/getAbi.js +35 -0
  78. package/build/esm/src/abis/index.js +4 -1
  79. package/build/esm/src/clients/v1/modules/orders/orders.js +5 -3
  80. package/build/esm/src/clients/v1/modules/orders/transactions/createIncreaseOrderTxn.js +3 -1
  81. package/build/esm/src/clients/v1/modules/orders/transactions/updateOrderTxn.js +21 -25
  82. package/build/esm/src/clients/v1/modules/orders/utils.js +6 -7
  83. package/build/esm/src/clients/v1/modules/trades/trades.js +4 -3
  84. package/build/esm/src/clients/v1/multicall.js +2 -1
  85. package/build/esm/src/clients/v2/__tests__/decrease.spec.js +0 -2
  86. package/build/esm/src/clients/v2/__tests__/editCancel.spec.js +0 -3
  87. package/build/esm/src/clients/v2/__tests__/globalCleanup.js +0 -1
  88. package/build/esm/src/clients/v2/__tests__/increase.spec.js +0 -2
  89. package/build/esm/src/clients/v2/__tests__/subaccountLifecycle.spec.js +0 -1
  90. package/build/esm/src/clients/v2/__tests__/testUtil.js +0 -1
  91. package/build/esm/src/configs/__tests__/markets.spec.js +9 -2
  92. package/build/esm/src/configs/chains.js +3 -0
  93. package/build/esm/src/configs/contracts.js +25 -17
  94. package/build/esm/src/configs/dataStore.js +8 -0
  95. package/build/esm/src/utils/__tests__/address.spec.js +48 -0
  96. package/build/esm/src/utils/__tests__/orderTransactions/exchangeRouterMulticall.spec.js +43 -6
  97. package/build/esm/src/utils/__tests__/orderTransactions/updateOrder.spec.js +5 -1
  98. package/build/esm/src/utils/__tests__/referrals.spec.js +37 -5
  99. package/build/esm/src/utils/address/index.js +1 -0
  100. package/build/esm/src/utils/address/utils.js +25 -0
  101. package/build/esm/src/utils/errors/transactionsErrors.js +17 -0
  102. package/build/esm/src/utils/express/utils/batchOrderUtils.js +14 -9
  103. package/build/esm/src/utils/express/utils/bridgeOutUtils.js +53 -18
  104. package/build/esm/src/utils/express/utils/referralUtils.js +37 -25
  105. package/build/esm/src/utils/express/utils/relayParamsUtils.js +10 -5
  106. package/build/esm/src/utils/multichain/api.js +15 -7
  107. package/build/esm/src/utils/orderTransactions/api.js +3 -4
  108. package/build/esm/src/utils/orderTransactions/utils.js +9 -8
  109. package/build/esm/src/utils/referrals/utils.js +23 -15
  110. package/build/esm/src/utils/subaccount/getEmptySubaccountApproval.js +2 -0
  111. package/build/esm/src/utils/subaccount/getSubaccountApprovalTypedData.js +36 -14
  112. package/build/esm/src/utils/subaccount/hashSubaccountApproval.js +32 -18
  113. package/build/esm/src/utils/subaccount/index.js +2 -2
  114. package/build/esm/src/utils/subaccount/sdkClient.js +2 -2
  115. package/build/esm/src/utils/subaccount/state.js +8 -0
  116. package/build/esm/src/utils/tradeHistory/utils.js +6 -6
  117. package/build/tsconfig.tsbuildinfo +1 -1
  118. package/build/types/scripts/generate-synthetics-abis.d.ts +6 -0
  119. package/build/types/src/abis/CustomErrors.d.ts +160 -0
  120. package/build/types/src/abis/CustomErrorsV2_2_1.d.ts +4174 -0
  121. package/build/types/src/abis/ExchangeRouterV2_2_1.d.ts +1128 -0
  122. package/build/types/src/abis/GelatoRelayRouterV2_2_1.d.ts +1508 -0
  123. package/build/types/src/abis/GlvReaderV2_2_1.d.ts +1293 -0
  124. package/build/types/src/abis/MultichainClaimsRouterV2_2_1.d.ts +985 -0
  125. package/build/types/src/abis/MultichainGlvRouterV2_2_1.d.ts +906 -0
  126. package/build/types/src/abis/MultichainGmRouterV2_2_1.d.ts +1142 -0
  127. package/build/types/src/abis/MultichainOrderRouterV2_2_1.d.ts +1601 -0
  128. package/build/types/src/abis/MultichainSubaccountRouterV2_2_1.d.ts +1678 -0
  129. package/build/types/src/abis/MultichainTransferRouterV2_2_1.d.ts +793 -0
  130. package/build/types/src/abis/RelayParamsV2_2_1.d.ts +118 -0
  131. package/build/types/src/abis/RewardRouterV3.d.ts +1129 -0
  132. package/build/types/src/abis/SubaccountGelatoRelayRouterV2_2_1.d.ts +1946 -0
  133. package/build/types/src/abis/SyntheticsReaderV2_2_1.d.ts +4075 -0
  134. package/build/types/src/abis/__tests__/getAbi.spec.d.ts +1 -0
  135. package/build/types/src/abis/getAbi.d.ts +17051 -0
  136. package/build/types/src/abis/index.d.ts +6700 -4744
  137. package/build/types/src/clients/v1/modules/orders/transactions/createIncreaseOrderTxn.d.ts +2 -1
  138. package/build/types/src/clients/v1/modules/orders/transactions/updateOrderTxn.d.ts +8 -3
  139. package/build/types/src/configs/contracts.d.ts +6 -0
  140. package/build/types/src/configs/dataStore.d.ts +4 -0
  141. package/build/types/src/utils/__tests__/address.spec.d.ts +1 -0
  142. package/build/types/src/utils/address/index.d.ts +1 -0
  143. package/build/types/src/utils/address/utils.d.ts +11 -0
  144. package/build/types/src/utils/errors/transactionsErrors.d.ts +18 -1
  145. package/build/types/src/utils/express/types.d.ts +1 -0
  146. package/build/types/src/utils/express/utils/batchOrderUtils.d.ts +4 -3
  147. package/build/types/src/utils/express/utils/bridgeOutUtils.d.ts +8 -2
  148. package/build/types/src/utils/express/utils/referralUtils.d.ts +21 -0
  149. package/build/types/src/utils/multichain/api.d.ts +8 -0
  150. package/build/types/src/utils/orderTransactions/api.d.ts +0 -3
  151. package/build/types/src/utils/orderTransactions/utils.d.ts +5 -2
  152. package/build/types/src/utils/referrals/utils.d.ts +7 -1
  153. package/build/types/src/utils/subaccount/api.d.ts +1 -0
  154. package/build/types/src/utils/subaccount/getSubaccountApprovalTypedData.d.ts +4 -0
  155. package/build/types/src/utils/subaccount/hashSubaccountApproval.d.ts +2 -1
  156. package/build/types/src/utils/subaccount/index.d.ts +2 -2
  157. package/build/types/src/utils/subaccount/state.d.ts +2 -1
  158. package/build/types/src/utils/subaccount/types.d.ts +3 -1
  159. package/package.json +1 -1
@@ -1,6 +1,7 @@
1
- import { encodeAbiParameters, keccak256 } from "viem";
1
+ import { encodeAbiParameters, keccak256, zeroHash } from "viem";
2
2
  import { abis } from "../../../abis";
3
- import { getContract } from "../../../configs/contracts";
3
+ import RelayParamsV2_2_1 from "../../../abis/RelayParamsV2_2_1";
4
+ import { getContract, isContractsV2_2_1 } from "../../../configs/contracts";
4
5
  import { SwapPricingType } from "../../orders/types";
5
6
  import { combineExternalCalls, getEmptyExternalCallsPayload, getExternalCallsPayload, } from "../../orderTransactions";
6
7
  import { getSwapAmountsByToValue } from "../../swap";
@@ -160,10 +161,11 @@ export function getRawRelayerParams({ chainId, gasPaymentTokenAddress, relayerFe
160
161
  fee: feeParams,
161
162
  desChainId: BigInt(chainId),
162
163
  userNonce: BigInt(nowInSeconds()),
164
+ eip6492SignatureWrapperHash: zeroHash,
163
165
  };
164
166
  }
165
167
  export function hashRelayParams(relayParams) {
166
- const encoded = encodeAbiParameters(abis.RelayParams, [
168
+ const values = [
167
169
  {
168
170
  tokens: relayParams.oracleParams.tokens,
169
171
  providers: relayParams.oracleParams.providers,
@@ -186,6 +188,9 @@ export function hashRelayParams(relayParams) {
186
188
  relayParams.userNonce,
187
189
  relayParams.deadline,
188
190
  relayParams.desChainId,
189
- ]);
190
- return keccak256(encoded);
191
+ ];
192
+ if (isContractsV2_2_1(Number(relayParams.desChainId))) {
193
+ return keccak256(encodeAbiParameters(RelayParamsV2_2_1, [...values, relayParams.eip6492SignatureWrapperHash]));
194
+ }
195
+ return keccak256(encodeAbiParameters(abis.RelayParams, values));
191
196
  }
@@ -1,5 +1,5 @@
1
1
  import { encodeAbiParameters, encodeFunctionData, zeroAddress } from "viem";
2
- import { abis } from "../../abis";
2
+ import { getAbi } from "../../abis/getAbi";
3
3
  import { getContract } from "../../configs/contracts";
4
4
  import { getLayerZeroEndpointId } from "../../configs/multichain";
5
5
  import { getToken } from "../../configs/tokens";
@@ -21,25 +21,25 @@ export function buildSameChainDepositTxn(request) {
21
21
  }
22
22
  depositTokenAddress = wrappedAddress;
23
23
  sendCall = encodeFunctionData({
24
- abi: abis.MultichainTransferRouter,
24
+ abi: getAbi(chainId, "MultichainTransferRouter"),
25
25
  functionName: "sendWnt",
26
26
  args: [multichainVault, amount],
27
27
  });
28
28
  }
29
29
  else {
30
30
  sendCall = encodeFunctionData({
31
- abi: abis.MultichainTransferRouter,
31
+ abi: getAbi(chainId, "MultichainTransferRouter"),
32
32
  functionName: "sendTokens",
33
33
  args: [tokenAddress, multichainVault, amount],
34
34
  });
35
35
  }
36
36
  const bridgeInCall = encodeFunctionData({
37
- abi: abis.MultichainTransferRouter,
37
+ abi: getAbi(chainId, "MultichainTransferRouter"),
38
38
  functionName: "bridgeIn",
39
39
  args: [account, depositTokenAddress],
40
40
  });
41
41
  const data = encodeFunctionData({
42
- abi: abis.MultichainTransferRouter,
42
+ abi: getAbi(chainId, "MultichainTransferRouter"),
43
43
  functionName: "multicall",
44
44
  args: [[sendCall, bridgeInCall]],
45
45
  });
@@ -49,6 +49,14 @@ export function buildSameChainDepositTxn(request) {
49
49
  value: isNative ? amount : 0n,
50
50
  };
51
51
  }
52
+ export function getEmptyBridgeFeeParams() {
53
+ return {
54
+ feeToken: zeroAddress,
55
+ feeAmount: 0n,
56
+ feeSwapPath: [],
57
+ minOutputAmount: 0n,
58
+ };
59
+ }
52
60
  export function buildSameChainWithdrawBridgeOutParams(params) {
53
61
  return {
54
62
  token: params.tokenAddress,
@@ -65,9 +73,9 @@ export function buildSameChainWithdrawTxn(request) {
65
73
  const { chainId, bridgeOutParams } = request;
66
74
  const router = getContract(chainId, "MultichainTransferRouter");
67
75
  const data = encodeFunctionData({
68
- abi: abis.MultichainTransferRouter,
76
+ abi: getAbi(chainId, "MultichainTransferRouter"),
69
77
  functionName: "transferOut",
70
- args: [bridgeOutParams],
78
+ args: [{ ...bridgeOutParams, bridgeFee: bridgeOutParams.bridgeFee ?? getEmptyBridgeFeeParams() }],
71
79
  });
72
80
  return { to: router, data, value: 0n };
73
81
  }
@@ -175,7 +175,7 @@ function parsePrepareResponse(raw) {
175
175
  }
176
176
  // the express chain stays on the origin that served it: prepare and submit pin that origin by request id, submit and status reuse it
177
177
  function chainKeys(prepared) {
178
- return [prepared.requestId, prepared.idempotencyKey];
178
+ return [prepared.requestId];
179
179
  }
180
180
  export async function prepareOrder(ctx, request) {
181
181
  return postJsonPinning(ctx.api, "/v1/orders/txns/prepare", request, chainKeys, {
@@ -183,7 +183,7 @@ export async function prepareOrder(ctx, request) {
183
183
  });
184
184
  }
185
185
  export async function submitOrder(ctx, request) {
186
- return postJsonPinned(ctx.api, [request.requestId, request.idempotencyKey], "/v1/orders/txns/submit", request);
186
+ return postJsonPinned(ctx.api, [request.requestId], "/v1/orders/txns/submit", request);
187
187
  }
188
188
  export async function prepareEditOrder(ctx, request) {
189
189
  return postJsonPinning(ctx.api, "/v1/orders/txns/edit/prepare", request, chainKeys, {
@@ -201,7 +201,7 @@ export async function prepareCollateral(ctx, request) {
201
201
  });
202
202
  }
203
203
  export async function fetchOrderStatus(ctx, request) {
204
- return postJsonPinned(ctx.api, [request.requestId, request.idempotencyKey], "/v1/orders/txns/status", request);
204
+ return postJsonPinned(ctx.api, [request.requestId], "/v1/orders/txns/status", request);
205
205
  }
206
206
  export async function signPreparedOrder(prepared, signer, chainId, accountAddress) {
207
207
  if (prepared.payloadType !== "typed-data") {
@@ -228,7 +228,6 @@ export async function executeExpressOrder(ctx, request, signer, accountAddress)
228
228
  requestId: prepared.requestId,
229
229
  signature,
230
230
  from: accountAddress ?? signer.address,
231
- idempotencyKey: prepared.idempotencyKey,
232
231
  eip712Data: {
233
232
  batchParams: prepared.payload.batchParams,
234
233
  relayParams: prepared.payload.relayParams,
@@ -1,10 +1,9 @@
1
1
  import uniq from "lodash/uniq";
2
2
  import { encodeFunctionData, zeroAddress, zeroHash } from "viem";
3
- import ExchangeRouterAbi from "../../abis/ExchangeRouter";
4
- import { abis } from "../../abis/index";
3
+ import { getAbi } from "../../abis/getAbi";
5
4
  import ERC20ABI from "../../abis/Token";
6
5
  import { getExcessiveExecutionFee, getExecutionFeePriorityFeeAllowance, getHighExecutionFee, } from "../../configs/chains";
7
- import { getContract } from "../../configs/contracts";
6
+ import { getContract, isContractsV2_2_1 } from "../../configs/contracts";
8
7
  import { convertTokenAddress, getToken, getWrappedToken, NATIVE_TOKEN_ADDRESS } from "../../configs/tokens";
9
8
  import { bigMath } from "../bigmath";
10
9
  import { expandDecimals, MaxUint256, USD_DECIMALS } from "../numbers";
@@ -283,6 +282,7 @@ export function buildUpdateOrderPayload(p) {
283
282
  minOutputAmount: p.minOutputAmount,
284
283
  autoCancel: p.autoCancel,
285
284
  validFromTime: 0n,
285
+ decreasePositionSwapType: p.decreasePositionSwapType,
286
286
  executionFeeTopUp: p.executionFeeTopUp,
287
287
  },
288
288
  };
@@ -544,7 +544,7 @@ function combineTransfers(tokenTransfers) {
544
544
  }
545
545
  return { tokenTransfers: Object.values(transfersMap), value };
546
546
  }
547
- export function getBatchOrderMulticallPayload({ params }) {
547
+ export function getBatchOrderMulticallPayload({ chainId, params, }) {
548
548
  const { createOrderParams, updateOrderParams, cancelOrderParams } = params;
549
549
  const multicall = [];
550
550
  let value = 0n;
@@ -563,7 +563,7 @@ export function getBatchOrderMulticallPayload({ params }) {
563
563
  multicall.push(...cancelMulticall);
564
564
  value += cancelValue;
565
565
  }
566
- const { encodedMulticall, callData } = encodeExchangeRouterMulticall(multicall);
566
+ const { encodedMulticall, callData } = encodeExchangeRouterMulticall(chainId, multicall);
567
567
  return { multicall, value, encodedMulticall, callData };
568
568
  }
569
569
  export function buildCreateOrderMulticall(params) {
@@ -615,6 +615,7 @@ export function buildUpdateOrderMulticall(updateTxn) {
615
615
  updatePayload.triggerPrice,
616
616
  updatePayload.minOutputAmount,
617
617
  0n,
618
+ ...(isContractsV2_2_1(chainId) ? [updatePayload.decreasePositionSwapType] : []),
618
619
  updatePayload.autoCancel,
619
620
  ],
620
621
  });
@@ -635,14 +636,14 @@ export function buildCancelOrderMulticall({ params }) {
635
636
  value: 0n,
636
637
  };
637
638
  }
638
- export function encodeExchangeRouterMulticall(multicall) {
639
+ export function encodeExchangeRouterMulticall(chainId, multicall) {
639
640
  const encodedMulticall = multicall.map((call) => encodeFunctionData({
640
- abi: abis.ExchangeRouter,
641
+ abi: getAbi(chainId, "ExchangeRouter"),
641
642
  functionName: call.method,
642
643
  args: call.params,
643
644
  }));
644
645
  const callData = encodeFunctionData({
645
- abi: ExchangeRouterAbi,
646
+ abi: getAbi(chainId, "ExchangeRouter"),
646
647
  functionName: "multicall",
647
648
  args: [encodedMulticall],
648
649
  });
@@ -1,26 +1,34 @@
1
1
  export const MAX_REFERRAL_CODE_LENGTH = 20;
2
2
  import { padHex, stringToHex, zeroHash } from "viem";
3
- import { bytesToString, hexToBytes } from "viem/utils";
3
+ import { hexToBytes } from "viem/utils";
4
+ export const REFERRAL_CODE_REGEX = /^\w+$/;
5
+ const BYTES32_HEX_REGEX = /^0x[0-9a-fA-F]{64}$/;
6
+ export function isReferralCodeHex(value) {
7
+ return typeof value === "string" && BYTES32_HEX_REGEX.test(value);
8
+ }
9
+ /**
10
+ * Codes registered through the UI are letters, digits and `_` right-padded with zeros. The contract accepts any
11
+ * bytes32, so anything else (e.g. left-padded addresses, hashes, other text) is returned as the original hex.
12
+ */
4
13
  export function decodeReferralCode(hexCode) {
5
- if (!hexCode || hexCode === zeroHash) {
14
+ if (!hexCode || !isReferralCodeHex(hexCode) || hexCode === zeroHash) {
6
15
  return "";
7
16
  }
8
- try {
9
- const bytes = hexToBytes(hexCode);
10
- if (bytes.length !== 32)
11
- throw new Error();
12
- return bytesToString(bytes).replace(/\0+$/, "");
13
- }
14
- catch (ex) {
15
- let code = "";
16
- const cleaned = hexCode.substring(2);
17
- for (let i = 0; i < 32; i++) {
18
- code += String.fromCharCode(parseInt(cleaned.substring(i * 2, i * 2 + 2), 16));
19
- }
20
- return code.trim();
17
+ const bytes = hexToBytes(hexCode);
18
+ const firstZeroIndex = bytes.indexOf(0);
19
+ const textLength = firstZeroIndex === -1 ? bytes.length : firstZeroIndex;
20
+ const text = String.fromCharCode(...bytes.subarray(0, textLength));
21
+ // only the characters `encodeReferralCode` keeps, so the text never points to a different code
22
+ if (!REFERRAL_CODE_REGEX.test(text) || bytes.subarray(textLength).some((byte) => byte !== 0)) {
23
+ return hexCode;
21
24
  }
25
+ return text;
22
26
  }
23
27
  export function encodeReferralCode(code) {
28
+ if (isReferralCodeHex(code)) {
29
+ // not an address, so no checksum casing; lowercase matches what chain and subgraph return
30
+ return code.toLowerCase();
31
+ }
24
32
  let final = code.replace(/[^\w_]/g, ""); // replace everything other than numbers, string and underscor to ''
25
33
  if (final.length > MAX_REFERRAL_CODE_LENGTH) {
26
34
  return zeroHash;
@@ -15,6 +15,8 @@ export function getEmptySubaccountApproval(chainId, subaccountAddress) {
15
15
  desChainId: BigInt(chainId),
16
16
  deadline: 0n,
17
17
  integrationId: zeroHash,
18
+ revocationCounter: 0n,
19
+ eip6492SignatureWrapperHash: zeroHash,
18
20
  signature: "0x",
19
21
  };
20
22
  }
@@ -1,27 +1,46 @@
1
1
  import { zeroHash } from "viem";
2
+ import { isContractsV2_2_1 } from "../../configs/contracts";
2
3
  import { SUBACCOUNT_ORDER_ACTION } from "../../configs/dataStore";
3
4
  import { getExpressContractAddress, getGelatoRelayRouterDomain } from "../express";
5
+ export const SUBACCOUNT_APPROVAL_TYPES = {
6
+ SubaccountApproval: [
7
+ { name: "subaccount", type: "address" },
8
+ { name: "shouldAdd", type: "bool" },
9
+ { name: "expiresAt", type: "uint256" },
10
+ { name: "maxAllowedCount", type: "uint256" },
11
+ { name: "actionType", type: "bytes32" },
12
+ { name: "nonce", type: "uint256" },
13
+ { name: "desChainId", type: "uint256" },
14
+ { name: "deadline", type: "uint256" },
15
+ { name: "integrationId", type: "bytes32" },
16
+ ],
17
+ };
18
+ export const SUBACCOUNT_APPROVAL_TYPES_V2_2_1 = {
19
+ SubaccountApproval: [
20
+ { name: "account", type: "address" },
21
+ { name: "subaccount", type: "address" },
22
+ { name: "shouldAdd", type: "bool" },
23
+ { name: "expiresAt", type: "uint256" },
24
+ { name: "maxAllowedCount", type: "uint256" },
25
+ { name: "actionType", type: "bytes32" },
26
+ { name: "nonce", type: "uint256" },
27
+ { name: "desChainId", type: "uint256" },
28
+ { name: "deadline", type: "uint256" },
29
+ { name: "integrationId", type: "bytes32" },
30
+ { name: "revocationCounter", type: "uint256" },
31
+ { name: "eip6492SignatureWrapperHash", type: "bytes32" },
32
+ ],
33
+ };
4
34
  export function getSubaccountApprovalTypedData(params) {
5
- const { chainId, subaccountAddress, shouldAdd, expiresAt, maxAllowedCount, nonce, signingChainId } = params;
35
+ const { chainId, subaccountAddress, shouldAdd, expiresAt, maxAllowedCount, nonce, account, revocationCounter, signingChainId, } = params;
36
+ const isV2_2_1 = isContractsV2_2_1(chainId);
6
37
  const relayRouterAddress = getExpressContractAddress(chainId, {
7
38
  isSubaccount: true,
8
39
  isMultichain: false,
9
40
  scope: "subaccount",
10
41
  });
11
42
  const domain = getGelatoRelayRouterDomain((signingChainId ?? chainId), relayRouterAddress);
12
- const types = {
13
- SubaccountApproval: [
14
- { name: "subaccount", type: "address" },
15
- { name: "shouldAdd", type: "bool" },
16
- { name: "expiresAt", type: "uint256" },
17
- { name: "maxAllowedCount", type: "uint256" },
18
- { name: "actionType", type: "bytes32" },
19
- { name: "nonce", type: "uint256" },
20
- { name: "desChainId", type: "uint256" },
21
- { name: "deadline", type: "uint256" },
22
- { name: "integrationId", type: "bytes32" },
23
- ],
24
- };
43
+ const types = isV2_2_1 ? SUBACCOUNT_APPROVAL_TYPES_V2_2_1 : SUBACCOUNT_APPROVAL_TYPES;
25
44
  const message = {
26
45
  subaccount: subaccountAddress,
27
46
  shouldAdd,
@@ -32,6 +51,9 @@ export function getSubaccountApprovalTypedData(params) {
32
51
  desChainId: chainId.toString(),
33
52
  deadline: expiresAt.toString(),
34
53
  integrationId: zeroHash,
54
+ ...(isV2_2_1
55
+ ? { account, revocationCounter: revocationCounter.toString(), eip6492SignatureWrapperHash: zeroHash }
56
+ : {}),
35
57
  };
36
58
  return {
37
59
  domain,
@@ -1,24 +1,38 @@
1
1
  import { encodeAbiParameters, keccak256, zeroHash } from "viem";
2
- export function hashSubaccountApproval(approval) {
2
+ import { isContractsV2_2_1 } from "../../configs/contracts";
3
+ const SUBACCOUNT_APPROVAL_COMPONENTS = [
4
+ { name: "subaccount", type: "address" },
5
+ { name: "shouldAdd", type: "bool" },
6
+ { name: "expiresAt", type: "uint256" },
7
+ { name: "maxAllowedCount", type: "uint256" },
8
+ { name: "actionType", type: "bytes32" },
9
+ { name: "nonce", type: "uint256" },
10
+ { name: "desChainId", type: "uint256" },
11
+ { name: "deadline", type: "uint256" },
12
+ { name: "integrationId", type: "bytes32" },
13
+ { name: "signature", type: "bytes" },
14
+ ];
15
+ const SUBACCOUNT_APPROVAL_COMPONENTS_V2_2_1 = [
16
+ { name: "subaccount", type: "address" },
17
+ { name: "shouldAdd", type: "bool" },
18
+ { name: "expiresAt", type: "uint256" },
19
+ { name: "maxAllowedCount", type: "uint256" },
20
+ { name: "actionType", type: "bytes32" },
21
+ { name: "nonce", type: "uint256" },
22
+ { name: "desChainId", type: "uint256" },
23
+ { name: "deadline", type: "uint256" },
24
+ { name: "integrationId", type: "bytes32" },
25
+ { name: "revocationCounter", type: "uint256" },
26
+ { name: "eip6492SignatureWrapperHash", type: "bytes32" },
27
+ { name: "signature", type: "bytes" },
28
+ ];
29
+ export function hashSubaccountApproval(chainId, approval) {
3
30
  if (!approval || !approval.subaccount) {
4
31
  return zeroHash;
5
32
  }
6
- const encodedData = encodeAbiParameters([
7
- {
8
- type: "tuple",
9
- components: [
10
- { name: "subaccount", type: "address" },
11
- { name: "shouldAdd", type: "bool" },
12
- { name: "expiresAt", type: "uint256" },
13
- { name: "maxAllowedCount", type: "uint256" },
14
- { name: "actionType", type: "bytes32" },
15
- { name: "nonce", type: "uint256" },
16
- { name: "desChainId", type: "uint256" },
17
- { name: "deadline", type: "uint256" },
18
- { name: "integrationId", type: "bytes32" },
19
- { name: "signature", type: "bytes" },
20
- ],
21
- },
22
- ], [approval]);
33
+ const components = isContractsV2_2_1(chainId)
34
+ ? SUBACCOUNT_APPROVAL_COMPONENTS_V2_2_1
35
+ : SUBACCOUNT_APPROVAL_COMPONENTS;
36
+ const encodedData = encodeAbiParameters([{ type: "tuple", components }], [approval]);
23
37
  return keccak256(encodedData);
24
38
  }
@@ -2,6 +2,6 @@ export * from "./types";
2
2
  export { generateSubaccount, decryptSubaccountPrivateKey, createSubaccountSignerFromConfig, } from "./generateSubaccount";
3
3
  export { hashSubaccountApproval } from "./hashSubaccountApproval";
4
4
  export { getEmptySubaccountApproval } from "./getEmptySubaccountApproval";
5
- export { getSubaccountApprovalTypedData } from "./getSubaccountApprovalTypedData";
6
- export { isEmptySubaccountApproval, isSameSubaccountApproval, isSubaccountApprovalExpired, isSubaccountApprovalNonceExpired, isSubaccountApprovalSynced, isSubaccountStatusUsable, parseSubaccountStatus, shouldRefreshExplicitSubaccountApproval, toSignedSubaccountApproval, } from "./state";
5
+ export { getSubaccountApprovalTypedData, SUBACCOUNT_APPROVAL_TYPES, SUBACCOUNT_APPROVAL_TYPES_V2_2_1, } from "./getSubaccountApprovalTypedData";
6
+ export { isEmptySubaccountApproval, isSameSubaccountApproval, isSubaccountApprovalExpired, isSubaccountApprovalNonceExpired, isSubaccountApprovalRevoked, isSubaccountApprovalSynced, isSubaccountStatusUsable, parseSubaccountStatus, shouldRefreshExplicitSubaccountApproval, toSignedSubaccountApproval, } from "./state";
7
7
  export { fetchSubaccountStatus, prepareSubaccountApproval, signSubaccountApproval } from "./api";
@@ -4,7 +4,7 @@ import { nowInSeconds } from "../time";
4
4
  import { fetchSubaccountStatus, prepareSubaccountApproval, signSubaccountApproval } from "./api";
5
5
  import { generateSubaccount } from "./generateSubaccount";
6
6
  import { getEmptySubaccountApproval } from "./getEmptySubaccountApproval";
7
- import { isEmptySubaccountApproval, isSameSubaccountApproval, isSubaccountApprovalExpired, isSubaccountApprovalNonceExpired, isSubaccountApprovalSynced, isSubaccountStatusUsable, parseSubaccountStatus, shouldRefreshExplicitSubaccountApproval, toSignedSubaccountApproval, } from "./state";
7
+ import { isEmptySubaccountApproval, isSameSubaccountApproval, isSubaccountApprovalExpired, isSubaccountApprovalNonceExpired, isSubaccountApprovalRevoked, isSubaccountApprovalSynced, isSubaccountStatusUsable, parseSubaccountStatus, shouldRefreshExplicitSubaccountApproval, toSignedSubaccountApproval, } from "./state";
8
8
  const sdkSubaccountSigners = new WeakMap();
9
9
  const MAX_PREPARED_SUBACCOUNT_APPROVALS = 100;
10
10
  const SUBACCOUNT_STATUS_CACHE_TTL_MS = 15000;
@@ -133,6 +133,7 @@ export function reconcileSdkSubaccountApproval(subaccount) {
133
133
  }
134
134
  if (isSubaccountApprovalSynced(approval, status) ||
135
135
  isSubaccountApprovalNonceExpired(approval, status) ||
136
+ isSubaccountApprovalRevoked(approval, status.revocationCounter) ||
136
137
  isSubaccountApprovalExpired(approval)) {
137
138
  subaccount.approval = undefined;
138
139
  }
@@ -339,7 +340,6 @@ export async function executeExpressOrderWithSubaccount(client, request, signer)
339
340
  requestId: prepared.requestId,
340
341
  signature,
341
342
  from: isSubaccountOrder ? request.from : signer.address,
342
- idempotencyKey: prepared.idempotencyKey,
343
343
  eip712Data: {
344
344
  batchParams: prepared.payload.batchParams,
345
345
  relayParams: prepared.payload.relayParams,
@@ -1,3 +1,4 @@
1
+ import { zeroHash } from "viem";
1
2
  import { toBigInt } from "../numbers";
2
3
  import { nowInSeconds } from "../time";
3
4
  export function parseSubaccountStatus(status) {
@@ -10,6 +11,7 @@ export function parseSubaccountStatus(status) {
10
11
  approvalNonce: toBigInt(status.approvalNonce) ?? 0n,
11
12
  multichainApprovalNonce: toBigInt(status.multichainApprovalNonce) ?? 0n,
12
13
  integrationId: status.integrationId ?? undefined,
14
+ revocationCounter: toBigInt(status.revocationCounter) ?? 0n,
13
15
  };
14
16
  }
15
17
  export function isSubaccountStatusUsable(status) {
@@ -31,11 +33,15 @@ export function shouldRefreshExplicitSubaccountApproval(approval, status, pendin
31
33
  return (status !== undefined &&
32
34
  (isSubaccountApprovalSynced(approval, status) ||
33
35
  isSubaccountApprovalNonceExpired(approval, status) ||
36
+ isSubaccountApprovalRevoked(approval, status.revocationCounter) ||
34
37
  isSubaccountApprovalExpired(approval)));
35
38
  }
36
39
  export function isSubaccountApprovalNonceExpired(approval, status) {
37
40
  return toBigInt(approval.nonce) !== status.approvalNonce;
38
41
  }
42
+ export function isSubaccountApprovalRevoked(approval, revocationCounter) {
43
+ return (toBigInt(approval.revocationCounter) ?? 0n) < revocationCounter;
44
+ }
39
45
  export function isSubaccountApprovalSynced(approval, status) {
40
46
  return (status.active &&
41
47
  status.maxAllowedCount === toBigInt(approval.maxAllowedCount) &&
@@ -56,6 +62,8 @@ export function toSignedSubaccountApproval(prepared, signature) {
56
62
  desChainId: toBigInt(prepared.message.desChainId) ?? 0n,
57
63
  deadline: toBigInt(prepared.message.deadline) ?? 0n,
58
64
  integrationId: prepared.message.integrationId,
65
+ revocationCounter: toBigInt(prepared.message.revocationCounter) ?? 0n,
66
+ eip6492SignatureWrapperHash: prepared.message.eip6492SignatureWrapperHash ?? zeroHash,
59
67
  signature,
60
68
  signedAt: Date.now(),
61
69
  signatureChainId: prepared.domain.chainId,
@@ -1,4 +1,4 @@
1
- import { getAddress } from "viem";
1
+ import { normalizeAddress } from "../address";
2
2
  import { toBigInt } from "../numbers";
3
3
  import { getByKey } from "../objects";
4
4
  import { isIncreaseOrderType, isSwapOrderType } from "../orders";
@@ -8,8 +8,8 @@ export function createRawTradeActionTransformer(marketsInfoData, wrappedToken, t
8
8
  return (rawAction) => {
9
9
  const orderType = Number(rawAction.orderType);
10
10
  if (isSwapOrderType(orderType)) {
11
- const initialCollateralTokenAddress = getAddress(rawAction.initialCollateralTokenAddress);
12
- const swapPath = rawAction.swapPath.map((address) => getAddress(address));
11
+ const initialCollateralTokenAddress = normalizeAddress(rawAction.initialCollateralTokenAddress);
12
+ const swapPath = rawAction.swapPath.map((address) => normalizeAddress(address));
13
13
  const swapPathOutputAddresses = getSwapPathOutputAddresses({
14
14
  marketsInfoData,
15
15
  swapPath,
@@ -55,11 +55,11 @@ export function createRawTradeActionTransformer(marketsInfoData, wrappedToken, t
55
55
  return tradeAction;
56
56
  }
57
57
  else {
58
- const marketAddress = getAddress(rawAction.marketAddress);
58
+ const marketAddress = normalizeAddress(rawAction.marketAddress);
59
59
  const marketInfo = getByKey(marketsInfoData, marketAddress);
60
60
  const indexToken = marketInfo?.indexToken;
61
- const initialCollateralTokenAddress = getAddress(rawAction.initialCollateralTokenAddress);
62
- const swapPath = rawAction.swapPath.map((address) => getAddress(address));
61
+ const initialCollateralTokenAddress = normalizeAddress(rawAction.initialCollateralTokenAddress);
62
+ const swapPath = rawAction.swapPath.map((address) => normalizeAddress(address));
63
63
  const swapPathOutputAddresses = getSwapPathOutputAddresses({
64
64
  marketsInfoData,
65
65
  swapPath,