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

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 (46) hide show
  1. package/build/cjs/src/clients/v2/__tests__/decrease.spec.js +14 -0
  2. package/build/cjs/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +24 -0
  3. package/build/cjs/src/codegen/prebuilt/hashedMarketConfigKeys.json +183 -0
  4. package/build/cjs/src/codegen/prebuilt/hashedMarketValuesKeys.json +45 -0
  5. package/build/cjs/src/configs/api.js +9 -9
  6. package/build/cjs/src/configs/marketHours.js +27 -0
  7. package/build/cjs/src/configs/markets.js +21 -0
  8. package/build/cjs/src/configs/tokens.js +32 -0
  9. package/build/cjs/src/utils/__tests__/markets.spec.js +44 -9
  10. package/build/cjs/src/utils/markets/utils.js +19 -12
  11. package/build/cjs/src/utils/orderTransactions/api.js +15 -10
  12. package/build/cjs/src/utils/orderTransactions/utils.js +2 -2
  13. package/build/cjs/src/utils/orderTransactions/validateTypedData.js +7 -0
  14. package/build/cjs/src/utils/positions/utils.js +1 -1
  15. package/build/cjs/src/utils/subaccount/generateSubaccount.js +20 -2
  16. package/build/cjs/src/utils/subaccount/index.js +3 -1
  17. package/build/cjs/src/utils/swap/__tests__/swapRouting.spec.js +1 -1
  18. package/build/cjs/src/utils/trade/trade.js +7 -0
  19. package/build/cjs/src/utils/twap/index.js +10 -4
  20. package/build/esm/src/clients/v2/__tests__/decrease.spec.js +14 -0
  21. package/build/esm/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +24 -0
  22. package/build/esm/src/codegen/prebuilt/hashedMarketConfigKeys.json +183 -0
  23. package/build/esm/src/codegen/prebuilt/hashedMarketValuesKeys.json +45 -0
  24. package/build/esm/src/configs/api.js +9 -9
  25. package/build/esm/src/configs/marketHours.js +24 -0
  26. package/build/esm/src/configs/markets.js +21 -0
  27. package/build/esm/src/configs/tokens.js +32 -0
  28. package/build/esm/src/utils/__tests__/markets.spec.js +45 -10
  29. package/build/esm/src/utils/markets/utils.js +19 -12
  30. package/build/esm/src/utils/orderTransactions/api.js +15 -10
  31. package/build/esm/src/utils/orderTransactions/utils.js +2 -2
  32. package/build/esm/src/utils/orderTransactions/validateTypedData.js +7 -0
  33. package/build/esm/src/utils/positions/utils.js +1 -1
  34. package/build/esm/src/utils/subaccount/generateSubaccount.js +14 -1
  35. package/build/esm/src/utils/subaccount/index.js +1 -1
  36. package/build/esm/src/utils/swap/__tests__/swapRouting.spec.js +1 -1
  37. package/build/esm/src/utils/trade/trade.js +7 -0
  38. package/build/esm/src/utils/twap/index.js +10 -4
  39. package/build/types/src/codegen/prebuilt/index.d.ts +252 -0
  40. package/build/types/src/configs/marketHours.d.ts +7 -0
  41. package/build/types/src/configs/tokens.d.ts +1 -39
  42. package/build/types/src/utils/markets/utils.d.ts +1 -1
  43. package/build/types/src/utils/subaccount/generateSubaccount.d.ts +3 -0
  44. package/build/types/src/utils/subaccount/index.d.ts +1 -1
  45. package/build/types/src/utils/tokens/types.d.ts +2 -0
  46. package/package.json +1 -1
@@ -2043,6 +2043,51 @@
2043
2043
  "longInterestInTokensUsingShortToken": "0xd893c4fcc594e9a0ce0ab93d266e4e70414b4cd26b53cb0163e7062a5eb685f9",
2044
2044
  "shortInterestInTokensUsingLongToken": "0x44b4ead85e88e64c9d33a4d1536e7a88dbdd358c34493b750b307e71bd30c389",
2045
2045
  "shortInterestInTokensUsingShortToken": "0x2b0d7675116aaba49bd90b5bab02e516d56e17c58bc9094856584ef539cbaeab"
2046
+ },
2047
+ "0xda81cdd397210C08cFc567f93982E148A3aac8a6": {
2048
+ "longPoolAmount": "0xa623b2ef3b0cbe188cd0a6a7f66ab11ff4097d13d5c91d5bc890a14ef7014fb2",
2049
+ "shortPoolAmount": "0xfbf08274e17ac1ac55834da4dc313d4719268cb10576e2f55816326a0abccd18",
2050
+ "positionImpactPoolAmount": "0x6196f1f685c07c510baaf44af1778099371cd0b09e7775654bf6e4a6fc7fd574",
2051
+ "swapImpactPoolAmountLong": "0x619360f4a669b67b737be8ed17e588ce75df8ebc74784241104c52bbd26a1b4e",
2052
+ "swapImpactPoolAmountShort": "0xc6d1d060ece19603561b09c3f499db24a460eb7439020b9ecc0dce5d1db4007e",
2053
+ "longInterestUsingLongToken": "0x62f5cd8ce2d4c0fa7a7feb9561c85a031b663deceaf3cd14d390a84a0f102702",
2054
+ "longInterestUsingShortToken": "0xd118e405922d9f76977b26d001d9e0d017f1664c2c2501947733e436221eaff3",
2055
+ "shortInterestUsingLongToken": "0xbeb8ea99ac439f5cf0c09b33f460800abfdb2e5a304160defbc3d7b0bba807ad",
2056
+ "shortInterestUsingShortToken": "0x8baabff8869decb43b5438a4531a433c0964f0d72111460628ad4df61ee4e251",
2057
+ "longInterestInTokensUsingLongToken": "0xea6a68fda1c1e0643dedbeffabd16c14c096231f14d7a1b7b26cab333c29f5ca",
2058
+ "longInterestInTokensUsingShortToken": "0x36288838d6485d0e6ab9fe998405ad3b5a614bed06207face6cc08e3a910358b",
2059
+ "shortInterestInTokensUsingLongToken": "0x585315fb32db672be38177229edfeeee2435eac1ba61724a000eca920da364c5",
2060
+ "shortInterestInTokensUsingShortToken": "0x2594d3cdf50fa51cdfc4d521017759e70695d4a4c3d02607c3396ef00456f87a"
2061
+ },
2062
+ "0x6F287D071800BfA847B4a7a7104BE33F87Ce9E74": {
2063
+ "longPoolAmount": "0xffe4f5141fa56213c7a4503e906e8b78d14c8f45d554b239ec665a4dc59da992",
2064
+ "shortPoolAmount": "0x84dfdde24a9488ad7a160b52eae17c165d9e65704ec2fd51cc1cd31722317cb0",
2065
+ "positionImpactPoolAmount": "0xe4d42e78bd6cc4fbe977ff9582bb3d30a63c3e8e1c91058a5cee5809a83a8063",
2066
+ "swapImpactPoolAmountLong": "0x631ae2ecd66309a4f22523c4174101b5fd24373ee65bdfe5e92958c1c6d4af81",
2067
+ "swapImpactPoolAmountShort": "0x3cfdcff765e146b85cd62580516e6106f754a32f8c1b959dabf339d4b772266e",
2068
+ "longInterestUsingLongToken": "0x0a9ac749f1651357200b4524b525a7920e1294dfa3f4c132e1ffffa89c11c71e",
2069
+ "longInterestUsingShortToken": "0x2b4ab8502b07948a316c2d2fb0281900156815e09e56af0c6db1f6c04dd92053",
2070
+ "shortInterestUsingLongToken": "0x2bbb0f05a9a9dcdbe868292fd4cf60b5492e82152a03d50e603e3ece144ceb9a",
2071
+ "shortInterestUsingShortToken": "0xcb8451da9c5259dbe0be3a67aabbc798caa8590ee95195f628c95021fa448175",
2072
+ "longInterestInTokensUsingLongToken": "0x3ba80188520b08938ec084c527df3573fd612a30e15509ac8528d106fc0c5b2f",
2073
+ "longInterestInTokensUsingShortToken": "0x6b077b72d8987e5e1e91701460f816550467f3509961418cea5ff582a6f1de14",
2074
+ "shortInterestInTokensUsingLongToken": "0x5b3c85e631d365e17e9a26781b391f96c805603bc9980fcffd6fbc16f9e63d68",
2075
+ "shortInterestInTokensUsingShortToken": "0xb28e17120d8673905d243b23f0fbd4af7eccbe2462c26091faed611cd4c3fcfd"
2076
+ },
2077
+ "0x2Ce2bc8B0f9d000f359d756a5816C125474Bb39b": {
2078
+ "longPoolAmount": "0x0aa370bd4f4cb71230e4dfedd31a584f0cf5b74534a540655da5ae43508d0194",
2079
+ "shortPoolAmount": "0x0594ea921b3a3c25474baad01a129c89b1b4bce5e97cb77f114dac27e9d98ba7",
2080
+ "positionImpactPoolAmount": "0xd48f22400dc15fffe3d57af129244c75a05bd6c316f752647480fa40302ba44e",
2081
+ "swapImpactPoolAmountLong": "0x0766f80043596ab996995415283da0071d8daa85f33db0eed147e7f211fedc10",
2082
+ "swapImpactPoolAmountShort": "0xd61775b7c0987cd87fd06904569a03ea2d28cc1ca52180146dd88ff2306bb63d",
2083
+ "longInterestUsingLongToken": "0xefab48a072d02232e61d878dcc7dc31b0897511be212ea86b7e8504a97d08be0",
2084
+ "longInterestUsingShortToken": "0xa7ce1cd08babdcd3cbba098eaaea1f0bb62d60eec4ff42c6108cefe17d5eab75",
2085
+ "shortInterestUsingLongToken": "0x3358ebdffc9da33dfe5811ea2a24e9e8cd46c78b7d4d6bbe89b80a1f2ce5ebac",
2086
+ "shortInterestUsingShortToken": "0x764a71125a505ed36dd3e449394fb0dc3bcd52fd39ea77804c7f43fe6084f641",
2087
+ "longInterestInTokensUsingLongToken": "0x660deee197e25d7ec0983a4228890535c632bbb8b9e4cb9c3131fb84caa2a932",
2088
+ "longInterestInTokensUsingShortToken": "0x5cabb84debcb7263087ca7ef71e167a8048527739991483f2793bb6079554a50",
2089
+ "shortInterestInTokensUsingLongToken": "0xccb072d4c5cf74a4a1d0e6f80b7628dba861d6c95037409fc42800e72a935d7c",
2090
+ "shortInterestInTokensUsingShortToken": "0x3e1a9a944352a0080a281988fbf04a6b9c44a82767c10d16eb11ad80b1fb5d65"
2046
2091
  }
2047
2092
  },
2048
2093
  "43113": {
@@ -1,19 +1,19 @@
1
1
  import { ARBITRUM, ARBITRUM_SEPOLIA, AVALANCHE, AVALANCHE_FUJI, BOTANIX, MEGAETH } from "./chains";
2
2
  const API_URLS = {
3
- [ARBITRUM]: "https://arbitrum.gmxapi.io/api/v1",
4
- [AVALANCHE]: "https://avalanche.gmxapi.io/api/v1",
3
+ [ARBITRUM]: "https://arbitrum.gmxapi.io/v1",
4
+ [AVALANCHE]: "https://avalanche.gmxapi.io/v1",
5
5
  [AVALANCHE_FUJI]: undefined,
6
- [BOTANIX]: "https://botanix.gmxapi.io/api/v1",
7
- [ARBITRUM_SEPOLIA]: "https://gmx-api-arbitrum-sepolia-yp6pp.ondigitalocean.app/api/v1",
8
- [MEGAETH]: "https://megaeth.gmxapi.io/api/v1",
6
+ [BOTANIX]: "https://botanix.gmxapi.io/v1",
7
+ [ARBITRUM_SEPOLIA]: "https://gmx-api-arbitrum-sepolia-yp6pp.ondigitalocean.app/v1",
8
+ [MEGAETH]: "https://megaeth.gmxapi.io/v1",
9
9
  };
10
10
  const API_FALLBACK_URLS = {
11
- [ARBITRUM]: ["https://arbitrum.gmxapi.ai/api/v1"],
12
- [AVALANCHE]: ["https://avalanche.gmxapi.ai/api/v1"],
11
+ [ARBITRUM]: ["https://arbitrum.gmxapi.ai/v1"],
12
+ [AVALANCHE]: ["https://avalanche.gmxapi.ai/v1"],
13
13
  [AVALANCHE_FUJI]: [],
14
- [BOTANIX]: ["https://botanix.gmxapi.ai/api/v1"],
14
+ [BOTANIX]: ["https://botanix.gmxapi.ai/v1"],
15
15
  [ARBITRUM_SEPOLIA]: [],
16
- [MEGAETH]: ["https://megaeth.gmxapi.ai/api/v1"],
16
+ [MEGAETH]: ["https://megaeth.gmxapi.ai/v1"],
17
17
  };
18
18
  export function getApiUrl(chainId) {
19
19
  return API_URLS[chainId];
@@ -0,0 +1,24 @@
1
+ // Per-market UI leverage caps keyed off the contract's `minCollateralFactor`.
2
+ // The contracts team runs a cron (see Linear ENG-54) that toggles each market's
3
+ // MCF between its on-hours and off-hours value. Matching either sentinel here
4
+ // lets the UI apply the correct cap without knowing the session schedule.
5
+ const GOLD_SILVER_CFG = {
6
+ onHoursMcf: 9n * 10n ** 27n,
7
+ onHoursMaxLeverage: 100,
8
+ offHoursMcf: 35n * 10n ** 27n,
9
+ offHoursMaxLeverage: 25,
10
+ };
11
+ export const MARKET_HOURS_MARKETS = {
12
+ // Arbitrum
13
+ "0x0Df2BE76F517BCF0000AbfFcB6344B3b2aC4Cc4f": GOLD_SILVER_CFG, // GOLD/USD
14
+ "0x448Fa722717df299ee197E2F6d8EB7911EFF6cEc": GOLD_SILVER_CFG, // SILVER/USD
15
+ "0xda81cdd397210C08cFc567f93982E148A3aac8a6": GOLD_SILVER_CFG, // WTIOIL/USD
16
+ "0x6F287D071800BfA847B4a7a7104BE33F87Ce9E74": GOLD_SILVER_CFG, // BRENTOIL/USD
17
+ "0x2Ce2bc8B0f9d000f359d756a5816C125474Bb39b": {
18
+ // NATGAS/USD
19
+ onHoursMcf: 22n * 10n ** 27n,
20
+ onHoursMaxLeverage: 40,
21
+ offHoursMcf: 40n * 10n ** 27n,
22
+ offHoursMaxLeverage: 20,
23
+ },
24
+ };
@@ -915,6 +915,27 @@ export const MARKETS = {
915
915
  longTokenAddress: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
916
916
  shortTokenAddress: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
917
917
  },
918
+ // WTIOIL/USD [WETH-USDC]
919
+ "0xda81cdd397210C08cFc567f93982E148A3aac8a6": {
920
+ marketTokenAddress: "0xda81cdd397210C08cFc567f93982E148A3aac8a6",
921
+ indexTokenAddress: "0xa8Ffb545d5cBF1F44E3eBA123D60372cD267D73c",
922
+ longTokenAddress: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
923
+ shortTokenAddress: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
924
+ },
925
+ // BRENTOIL/USD [WETH-USDC]
926
+ "0x6F287D071800BfA847B4a7a7104BE33F87Ce9E74": {
927
+ marketTokenAddress: "0x6F287D071800BfA847B4a7a7104BE33F87Ce9E74",
928
+ indexTokenAddress: "0x9C5C4b9BA1fEBA72186f50d8Ae7C58b1D7f0B12F",
929
+ longTokenAddress: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
930
+ shortTokenAddress: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
931
+ },
932
+ // NATGAS/USD [WETH-USDC]
933
+ "0x2Ce2bc8B0f9d000f359d756a5816C125474Bb39b": {
934
+ marketTokenAddress: "0x2Ce2bc8B0f9d000f359d756a5816C125474Bb39b",
935
+ indexTokenAddress: "0x620aC65BE29066Bb9D1E92C65b35B9fD321Fb963",
936
+ longTokenAddress: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
937
+ shortTokenAddress: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
938
+ },
918
939
  },
919
940
  [AVALANCHE]: {
920
941
  // BTC/USD [BTC-USDC]
@@ -1197,6 +1197,38 @@ export const TOKENS = {
1197
1197
  imageUrl: "https://s2.coinmarketcap.com/static/img/coins/64x64/39343.png",
1198
1198
  explorerUrl: "https://arbiscan.io/token/0xE41902f9aD379A8CC34A34efa00F5c3EE5112bC8",
1199
1199
  },
1200
+ {
1201
+ name: "WTI Crude Oil",
1202
+ symbol: "WTIOIL",
1203
+ address: "0xa8Ffb545d5cBF1F44E3eBA123D60372cD267D73c",
1204
+ isSynthetic: true,
1205
+ decimals: 18,
1206
+ categories: ["rwa"],
1207
+ searchAliases: ["CL"],
1208
+ imageUrl: "https://s2.coinmarketcap.com/static/img/coins/64x64/39487.png",
1209
+ explorerUrl: "https://arbiscan.io/token/0xa8Ffb545d5cBF1F44E3eBA123D60372cD267D73c",
1210
+ },
1211
+ {
1212
+ name: "Brent Crude Oil",
1213
+ symbol: "BRENTOIL",
1214
+ address: "0x9C5C4b9BA1fEBA72186f50d8Ae7C58b1D7f0B12F",
1215
+ isSynthetic: true,
1216
+ decimals: 18,
1217
+ categories: ["rwa"],
1218
+ searchAliases: ["BZ"],
1219
+ imageUrl: "https://s2.coinmarketcap.com/static/img/coins/64x64/39804.png",
1220
+ explorerUrl: "https://arbiscan.io/token/0x9C5C4b9BA1fEBA72186f50d8Ae7C58b1D7f0B12F",
1221
+ },
1222
+ {
1223
+ name: "Natural Gas",
1224
+ symbol: "NATGAS",
1225
+ address: "0x620aC65BE29066Bb9D1E92C65b35B9fD321Fb963",
1226
+ isSynthetic: true,
1227
+ decimals: 18,
1228
+ categories: ["rwa"],
1229
+ imageUrl: "https://s2.coinmarketcap.com/static/img/coins/64x64/39464.png",
1230
+ explorerUrl: "https://arbiscan.io/token/0x620aC65BE29066Bb9D1E92C65b35B9fD321Fb963",
1231
+ },
1200
1232
  ],
1201
1233
  [AVALANCHE]: [
1202
1234
  {
@@ -1,8 +1,9 @@
1
1
  import { describe, expect, it } from "vitest";
2
2
  import { ARBITRUM } from "../../configs/chains";
3
+ import { BASIS_POINTS_DIVISOR } from "../../configs/factors";
3
4
  import { TOKENS } from "../../configs/tokens";
4
5
  import { getMarketFullName, getMarketIndexName, getMarketPoolName, getContractMarketPrices, getTokenPoolType, getPoolUsdWithoutPnl, getCappedPoolPnl, getMaxLeverageByMinCollateralFactor, getMaxAllowedLeverageByMinCollateralFactor, getOppositeCollateral, getAvailableUsdLiquidityForCollateral, getReservedUsd, getMarketDivisor, getMarketPnl, getOpenInterestUsd, getOpenInterestInTokens, getPriceForPnl, } from "../markets";
5
- import { expandDecimals } from "../numbers";
6
+ import { expandDecimals, numberToBigint, PRECISION_DECIMALS } from "../numbers";
6
7
  function getToken(symbol) {
7
8
  return TOKENS[ARBITRUM].find((token) => token.symbol === symbol);
8
9
  }
@@ -140,18 +141,52 @@ describe("getMaxLeverageByMinCollateralFactor", () => {
140
141
  });
141
142
  });
142
143
  describe("getMaxAllowedLeverageByMinCollateralFactor", () => {
143
- it("returns half of max leverage", () => {
144
- expect(getMaxAllowedLeverageByMinCollateralFactor(1000000000000000000n)).toBe(5000000000000000);
145
- });
146
- it("returns 100x for on-hours MCF (0.009 → 110x contract max)", () => {
147
- // MCF 0.009 = 9e27 → maxLeverage 110x → allowed 100x
144
+ const GOLD_MARKET = "0x0Df2BE76F517BCF0000AbfFcB6344B3b2aC4Cc4f";
145
+ const SILVER_MARKET = "0x448Fa722717df299ee197E2F6d8EB7911EFF6cEc";
146
+ const WTIOIL_MARKET = "0xda81cdd397210C08cFc567f93982E148A3aac8a6";
147
+ const BRENTOIL_MARKET = "0x6F287D071800BfA847B4a7a7104BE33F87Ce9E74";
148
+ const NATGAS_MARKET = "0x2Ce2bc8B0f9d000f359d756a5816C125474Bb39b";
149
+ const NON_MARKET_HOURS_MARKET = "0x1234567890abcdef1234567890abcdef12345678";
150
+ it("returns half of max leverage when no market address is provided", () => {
151
+ expect(getMaxAllowedLeverageByMinCollateralFactor(1000000000000000000n, undefined)).toBe(5000000000000000);
152
+ });
153
+ it("returns half of max leverage for a regular market", () => {
154
+ expect(getMaxAllowedLeverageByMinCollateralFactor(1000000000000000000n, NON_MARKET_HOURS_MARKET)).toBe(5000000000000000);
155
+ });
156
+ it("returns 100x for GOLD on on-hours MCF (0.009 → 110x contract max)", () => {
148
157
  const onHoursFactor = 9n * 10n ** 27n;
149
- expect(getMaxAllowedLeverageByMinCollateralFactor(onHoursFactor)).toBe(100 * 10000);
158
+ expect(getMaxAllowedLeverageByMinCollateralFactor(onHoursFactor, GOLD_MARKET)).toBe(100 * BASIS_POINTS_DIVISOR);
150
159
  });
151
- it("returns 25x for off-hours MCF (0.035 → 30x contract max)", () => {
152
- // MCF 0.035 = 35e27 → maxLeverage 30x → allowed 25x
160
+ it("returns 25x for GOLD on off-hours MCF (0.035 → 30x contract max)", () => {
153
161
  const offHoursFactor = 35n * 10n ** 27n;
154
- expect(getMaxAllowedLeverageByMinCollateralFactor(offHoursFactor)).toBe(25 * 10000);
162
+ expect(getMaxAllowedLeverageByMinCollateralFactor(offHoursFactor, GOLD_MARKET)).toBe(25 * BASIS_POINTS_DIVISOR);
163
+ });
164
+ it("returns 100x / 25x for SILVER with the same GOLD MCFs", () => {
165
+ expect(getMaxAllowedLeverageByMinCollateralFactor(9n * 10n ** 27n, SILVER_MARKET)).toBe(100 * BASIS_POINTS_DIVISOR);
166
+ expect(getMaxAllowedLeverageByMinCollateralFactor(35n * 10n ** 27n, SILVER_MARKET)).toBe(25 * BASIS_POINTS_DIVISOR);
167
+ });
168
+ it("returns 100x for WTIOIL on-hours MCF and 25x for off-hours MCF", () => {
169
+ expect(getMaxAllowedLeverageByMinCollateralFactor(9n * 10n ** 27n, WTIOIL_MARKET)).toBe(100 * BASIS_POINTS_DIVISOR);
170
+ expect(getMaxAllowedLeverageByMinCollateralFactor(35n * 10n ** 27n, WTIOIL_MARKET)).toBe(25 * BASIS_POINTS_DIVISOR);
171
+ });
172
+ it("returns 100x for BRENTOIL on-hours MCF and 25x for off-hours MCF", () => {
173
+ expect(getMaxAllowedLeverageByMinCollateralFactor(9n * 10n ** 27n, BRENTOIL_MARKET)).toBe(100 * BASIS_POINTS_DIVISOR);
174
+ expect(getMaxAllowedLeverageByMinCollateralFactor(35n * 10n ** 27n, BRENTOIL_MARKET)).toBe(25 * BASIS_POINTS_DIVISOR);
175
+ });
176
+ it("returns 40x for NATGAS on-hours MCF and 20x for off-hours MCF", () => {
177
+ expect(getMaxAllowedLeverageByMinCollateralFactor(22n * 10n ** 27n, NATGAS_MARKET)).toBe(40 * BASIS_POINTS_DIVISOR);
178
+ expect(getMaxAllowedLeverageByMinCollateralFactor(40n * 10n ** 27n, NATGAS_MARKET)).toBe(20 * BASIS_POINTS_DIVISOR);
179
+ });
180
+ it("does not apply market-hours overrides to other markets with same MCF", () => {
181
+ const onHoursFactor = 9n * 10n ** 27n;
182
+ const offHoursFactor = 35n * 10n ** 27n;
183
+ expect(getMaxAllowedLeverageByMinCollateralFactor(onHoursFactor, NON_MARKET_HOURS_MARKET)).toBe(55.5 * BASIS_POINTS_DIVISOR);
184
+ expect(getMaxAllowedLeverageByMinCollateralFactor(offHoursFactor, NON_MARKET_HOURS_MARKET)).toBe(14.5 * BASIS_POINTS_DIVISOR);
185
+ });
186
+ it("rounds allowed leverage to nearest .0 or .5", () => {
187
+ expect(getMaxAllowedLeverageByMinCollateralFactor(numberToBigint(1 / 24, PRECISION_DECIMALS), undefined)).toBe(12 * BASIS_POINTS_DIVISOR);
188
+ expect(getMaxAllowedLeverageByMinCollateralFactor(numberToBigint(1 / 25, PRECISION_DECIMALS), undefined)).toBe(12.5 * BASIS_POINTS_DIVISOR);
189
+ expect(getMaxAllowedLeverageByMinCollateralFactor(numberToBigint(1 / 50, PRECISION_DECIMALS), undefined)).toBe(25 * BASIS_POINTS_DIVISOR);
155
190
  });
156
191
  });
157
192
  describe("getOppositeCollateral", () => {
@@ -1,6 +1,8 @@
1
1
  import { zeroAddress } from "viem";
2
2
  import { BASIS_POINTS_DIVISOR, BASIS_POINTS_DIVISOR_BIGINT } from "../../configs/factors";
3
+ import { MARKET_HOURS_MARKETS } from "../../configs/marketHours";
3
4
  import { convertTokenAddress, getTokenVisualMultiplier, NATIVE_TOKEN_ADDRESS } from "../../configs/tokens";
5
+ import { bigMath } from "../bigmath";
4
6
  import { getBorrowingFactorPerPeriod, getFundingFactorPerPeriod } from "../fees";
5
7
  import { applyFactor, PRECISION } from "../numbers";
6
8
  import { getByKey } from "../objects";
@@ -82,24 +84,29 @@ export function getCappedPoolPnl(p) {
82
84
  const maxPnl = applyFactor(poolUsd, maxPnlFactor);
83
85
  return poolPnl > maxPnl ? maxPnl : poolPnl;
84
86
  }
87
+ /**
88
+ * Rounds to nearest .0 leverage, so that getMaxAllowedLeverageByMinCollateralFactor can get .0 or .5 leverage.
89
+ */
90
+ const ROUNDING_VALUE = 10000;
85
91
  export function getMaxLeverageByMinCollateralFactor(minCollateralFactor) {
86
92
  if (minCollateralFactor === undefined)
87
93
  return 100 * BASIS_POINTS_DIVISOR;
88
94
  if (minCollateralFactor === 0n)
89
95
  return 100 * BASIS_POINTS_DIVISOR;
90
- const x = Number(PRECISION / minCollateralFactor);
91
- const rounded = Math.round(x / 10) * 10;
92
- return rounded * BASIS_POINTS_DIVISOR;
96
+ const x = bigMath.mulDiv(PRECISION, BASIS_POINTS_DIVISOR_BIGINT, minCollateralFactor);
97
+ const rounded = Math.round(Number(x) / ROUNDING_VALUE) * ROUNDING_VALUE;
98
+ return rounded;
93
99
  }
94
- // GOLD/SILVER on-hours: MCF 0.009 (9e27) → 100x UI
95
- const MCF_ON_HOURS = 9n * 10n ** 27n;
96
- // GOLD/SILVER off-hours: MCF 0.035 (35e27) → 25x UI
97
- const MCF_OFF_HOURS = 35n * 10n ** 27n;
98
- export function getMaxAllowedLeverageByMinCollateralFactor(minCollateralFactor) {
99
- if (minCollateralFactor === MCF_ON_HOURS)
100
- return 100 * BASIS_POINTS_DIVISOR;
101
- if (minCollateralFactor === MCF_OFF_HOURS)
102
- return 25 * BASIS_POINTS_DIVISOR;
100
+ export function getMaxAllowedLeverageByMinCollateralFactor(minCollateralFactor, marketAddress) {
101
+ if (marketAddress) {
102
+ const cfg = MARKET_HOURS_MARKETS[marketAddress];
103
+ if (cfg) {
104
+ if (minCollateralFactor === cfg.onHoursMcf)
105
+ return cfg.onHoursMaxLeverage * BASIS_POINTS_DIVISOR;
106
+ if (minCollateralFactor === cfg.offHoursMcf)
107
+ return cfg.offHoursMaxLeverage * BASIS_POINTS_DIVISOR;
108
+ }
109
+ }
103
110
  return getMaxLeverageByMinCollateralFactor(minCollateralFactor) / 2;
104
111
  }
105
112
  export function getOppositeCollateral(marketInfo, tokenAddress) {
@@ -2,16 +2,21 @@ import { validateOrderTypedData } from "./validateTypedData";
2
2
  function parseEstimates(raw) {
3
3
  if (!raw)
4
4
  return undefined;
5
- return {
6
- positionPriceImpactDeltaUsd: BigInt(raw.positionPriceImpactDeltaUsd),
7
- swapPriceImpactDeltaUsd: BigInt(raw.swapPriceImpactDeltaUsd),
8
- executionFeeAmount: BigInt(raw.executionFeeAmount),
9
- acceptablePrice: BigInt(raw.acceptablePrice),
10
- sizeDeltaUsd: BigInt(raw.sizeDeltaUsd),
11
- positionFeeUsd: BigInt(raw.positionFeeUsd),
12
- borrowingFeeUsd: BigInt(raw.borrowingFeeUsd),
13
- fundingFeeUsd: BigInt(raw.fundingFeeUsd),
14
- };
5
+ try {
6
+ return {
7
+ positionPriceImpactDeltaUsd: BigInt(raw.positionPriceImpactDeltaUsd ?? "0"),
8
+ swapPriceImpactDeltaUsd: BigInt(raw.swapPriceImpactDeltaUsd ?? "0"),
9
+ executionFeeAmount: BigInt(raw.executionFeeAmount ?? "0"),
10
+ acceptablePrice: BigInt(raw.acceptablePrice ?? "0"),
11
+ sizeDeltaUsd: BigInt(raw.sizeDeltaUsd ?? "0"),
12
+ positionFeeUsd: BigInt(raw.positionFeeUsd ?? "0"),
13
+ borrowingFeeUsd: BigInt(raw.borrowingFeeUsd ?? "0"),
14
+ fundingFeeUsd: BigInt(raw.fundingFeeUsd ?? "0"),
15
+ };
16
+ }
17
+ catch (e) {
18
+ throw new Error(`Failed to parse order estimates: ${e instanceof Error ? e.message : e}`);
19
+ }
15
20
  }
16
21
  function parsePrepareResponse(raw) {
17
22
  return { ...raw, estimates: parseEstimates(raw.estimates) };
@@ -158,8 +158,8 @@ export function buildDecreaseOrderPayload(p) {
158
158
  };
159
159
  }
160
160
  export function buildTwapOrdersPayloads(p, twapParams) {
161
- if (!twapParams.numberOfParts || twapParams.numberOfParts <= 0) {
162
- throw new Error(`TWAP numberOfParts must be > 0, got ${twapParams.numberOfParts}`);
161
+ if (!twapParams.numberOfParts || twapParams.numberOfParts < 2) {
162
+ throw new Error(`TWAP numberOfParts must be >= 2, got ${twapParams.numberOfParts}`);
163
163
  }
164
164
  const uiFeeReceiver = createTwapUiFeeReceiver({ numberOfParts: twapParams.numberOfParts, source: twapParams.source });
165
165
  if (isSwapOrderType(p.orderType)) {
@@ -67,6 +67,13 @@ accountAddress) {
67
67
  throw new Error(`Order receiver "${receiver}" does not match signer "${signerAddress}". Possible malicious typed data.`);
68
68
  }
69
69
  }
70
+ const cancellationReceiver = order?.addresses?.cancellationReceiver;
71
+ if (cancellationReceiver) {
72
+ const checksummedCancellationReceiver = getAddress(cancellationReceiver);
73
+ if (checksummedCancellationReceiver !== ZERO_ADDRESS && !allowedReceivers.has(checksummedCancellationReceiver)) {
74
+ throw new Error(`Order cancellationReceiver "${cancellationReceiver}" does not match signer "${signerAddress}". Possible malicious typed data.`);
75
+ }
76
+ }
70
77
  }
71
78
  }
72
79
  }
@@ -329,7 +329,7 @@ export function getPositionInfo(p) {
329
329
  pendingFundingFeesUsd,
330
330
  pnl: undefined,
331
331
  });
332
- const maxAllowedLeverage = getMaxAllowedLeverageByMinCollateralFactor(marketInfo.minCollateralFactor);
332
+ const maxAllowedLeverage = getMaxAllowedLeverageByMinCollateralFactor(marketInfo.minCollateralFactor, marketInfo.marketTokenAddress);
333
333
  const hasLowCollateral = (leverage !== undefined && leverage > maxAllowedLeverage) || false;
334
334
  const liquidationPrice = getLiquidationPrice({
335
335
  marketInfo,
@@ -1,3 +1,4 @@
1
+ import cryptoJs from "crypto-js";
1
2
  import { keccak256 } from "viem";
2
3
  import { privateKeyToAccount } from "viem/accounts";
3
4
  import { SUBACCOUNT_MESSAGE } from "../../configs/express";
@@ -7,9 +8,21 @@ export async function generateSubaccount(mainSigner) {
7
8
  const pk = keccak256(signature);
8
9
  const account = privateKeyToAccount(pk);
9
10
  const signer = new PrivateKeySigner(pk);
11
+ const encryptedPrivateKey = cryptoJs.AES.encrypt(pk, mainSigner.address).toString();
10
12
  return {
11
13
  address: account.address,
12
14
  signer,
13
- privateKey: pk,
15
+ privateKey: encryptedPrivateKey,
14
16
  };
15
17
  }
18
+ export function decryptSubaccountPrivateKey(encryptedPrivateKey, mainAccountAddress) {
19
+ const decrypted = cryptoJs.AES.decrypt(encryptedPrivateKey, mainAccountAddress).toString(cryptoJs.enc.Utf8);
20
+ if (!decrypted) {
21
+ throw new Error("Failed to decrypt subaccount private key");
22
+ }
23
+ return decrypted;
24
+ }
25
+ export function createSubaccountSignerFromConfig(encryptedPrivateKey, mainAccountAddress) {
26
+ const pk = decryptSubaccountPrivateKey(encryptedPrivateKey, mainAccountAddress);
27
+ return new PrivateKeySigner(pk);
28
+ }
@@ -1,5 +1,5 @@
1
1
  export * from "./types";
2
- export { generateSubaccount } from "./generateSubaccount";
2
+ export { generateSubaccount, decryptSubaccountPrivateKey, createSubaccountSignerFromConfig, } from "./generateSubaccount";
3
3
  export { hashSubaccountApproval } from "./hashSubaccountApproval";
4
4
  export { getEmptySubaccountApproval } from "./getEmptySubaccountApproval";
5
5
  export { getSubaccountApprovalTypedData, } from "./getSubaccountApprovalTypedData";
@@ -293,7 +293,7 @@ describe("getBestSwapPath", () => {
293
293
  it("should handle routes with zero output", () => {
294
294
  const routes = createTestRoutes();
295
295
  const result = getBestSwapPath({ routes, usdIn: 100n * dollar, estimator: () => ({ usdOut: 0n }) });
296
- expect(result).toEqual(routes[0]);
296
+ expect(result).toBeUndefined();
297
297
  });
298
298
  it("should skip routes that throw errors", () => {
299
299
  const routes = createTestRoutes();
@@ -3,7 +3,11 @@ import { bigMath } from "../bigmath";
3
3
  import { DecreasePositionSwapType } from "../orders/types";
4
4
  import { getShouldUseMaxPrice } from "../prices";
5
5
  import { TradeMode, TradeType, } from "./types";
6
+ const MAX_ALLOWED_SLIPPAGE = 5000; // 50%
6
7
  export function applySlippageToPrice(allowedSlippage, price, isIncrease, isLong) {
8
+ if (allowedSlippage < 0 || allowedSlippage > MAX_ALLOWED_SLIPPAGE) {
9
+ throw new Error(`allowedSlippage must be between 0 and ${MAX_ALLOWED_SLIPPAGE} bps, got ${allowedSlippage}`);
10
+ }
7
11
  const shouldIncreasePrice = getShouldUseMaxPrice(isIncrease, isLong);
8
12
  const slippageBasisPoints = shouldIncreasePrice
9
13
  ? BASIS_POINTS_DIVISOR + allowedSlippage
@@ -11,6 +15,9 @@ export function applySlippageToPrice(allowedSlippage, price, isIncrease, isLong)
11
15
  return bigMath.mulDiv(price, BigInt(slippageBasisPoints), BASIS_POINTS_DIVISOR_BIGINT);
12
16
  }
13
17
  export function applySlippageToMinOut(allowedSlippage, minOutputAmount) {
18
+ if (allowedSlippage < 0 || allowedSlippage > MAX_ALLOWED_SLIPPAGE) {
19
+ throw new Error(`allowedSlippage must be between 0 and ${MAX_ALLOWED_SLIPPAGE} bps, got ${allowedSlippage}`);
20
+ }
14
21
  const slippageBasisPoints = BASIS_POINTS_DIVISOR - allowedSlippage;
15
22
  return bigMath.mulDiv(minOutputAmount, BigInt(slippageBasisPoints), BASIS_POINTS_DIVISOR_BIGINT);
16
23
  }
@@ -12,10 +12,13 @@ export function getTwapDurationInSeconds(duration) {
12
12
  return duration.hours * 60 * 60 + duration.minutes * 60;
13
13
  }
14
14
  export function getTwapValidFromTime(duration, numberOfParts, partIndex) {
15
+ if (numberOfParts < 2) {
16
+ throw new Error(`TWAP numberOfParts must be >= 2, got ${numberOfParts}`);
17
+ }
15
18
  const durationMinutes = duration.hours * 60 + duration.minutes;
16
- const durationMs = durationMinutes * 60;
19
+ const durationSeconds = durationMinutes * 60;
17
20
  const startTime = Math.ceil(Date.now() / 1000);
18
- return BigInt(Math.floor(startTime + (durationMs / (numberOfParts - 1)) * partIndex));
21
+ return BigInt(Math.floor(startTime + (durationSeconds / (numberOfParts - 1)) * partIndex));
19
22
  }
20
23
  export function changeTwapNumberOfPartsValue(value) {
21
24
  if (value < MIN_TWAP_NUMBER_OF_PARTS) {
@@ -37,10 +40,13 @@ export function getTwapOrderKey({ twapId, orderType, pool, isLong, collateralTok
37
40
  return `${twapId}-${type}-${pool}-${collateralTokenSymbol}`;
38
41
  }
39
42
  export function makeTwapValidFromTimeGetter(duration, numberOfParts) {
43
+ if (numberOfParts < 2) {
44
+ throw new Error(`TWAP numberOfParts must be >= 2, got ${numberOfParts}`);
45
+ }
40
46
  const durationMinutes = duration.hours * 60 + duration.minutes;
41
- const durationMs = durationMinutes * 60;
47
+ const durationSeconds = durationMinutes * 60;
42
48
  const startTime = Math.ceil(Date.now() / 1000);
43
49
  return (part) => {
44
- return BigInt(Math.floor(startTime + (durationMs / (numberOfParts - 1)) * part));
50
+ return BigInt(Math.floor(startTime + (durationSeconds / (numberOfParts - 1)) * part));
45
51
  };
46
52
  }