@metamask-previews/perps-controller 24.1.0-preview-4ba073b3a → 25.0.0-preview-e1d02b2

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 (42) hide show
  1. package/CHANGELOG.md +13 -3
  2. package/dist/PerpsController.d.ts.map +1 -1
  3. package/dist/PerpsController.js +44 -6
  4. package/dist/PerpsController.js.map +1 -1
  5. package/dist/constants/hyperLiquidConfig.d.ts +1 -0
  6. package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
  7. package/dist/constants/hyperLiquidConfig.js +3 -0
  8. package/dist/constants/hyperLiquidConfig.js.map +1 -1
  9. package/dist/providers/HyperLiquidProvider.d.ts +3 -6
  10. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  11. package/dist/providers/HyperLiquidProvider.js +404 -196
  12. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  13. package/dist/providers/LighterProvider.d.ts.map +1 -1
  14. package/dist/providers/LighterProvider.js +38 -6
  15. package/dist/providers/LighterProvider.js.map +1 -1
  16. package/dist/services/HyperLiquidClientService.d.ts +3 -1
  17. package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
  18. package/dist/services/HyperLiquidClientService.js +3 -2
  19. package/dist/services/HyperLiquidClientService.js.map +1 -1
  20. package/dist/services/TradingService.d.ts +4 -0
  21. package/dist/services/TradingService.d.ts.map +1 -1
  22. package/dist/services/TradingService.js +7 -2
  23. package/dist/services/TradingService.js.map +1 -1
  24. package/dist/types/index.d.ts +5 -0
  25. package/dist/types/index.d.ts.map +1 -1
  26. package/dist/types/index.js.map +1 -1
  27. package/dist/utils/cancelOrders.d.ts.map +1 -1
  28. package/dist/utils/cancelOrders.js +30 -0
  29. package/dist/utils/cancelOrders.js.map +1 -1
  30. package/dist/utils/errorUtils.d.ts +10 -0
  31. package/dist/utils/errorUtils.d.ts.map +1 -1
  32. package/dist/utils/errorUtils.js +33 -3
  33. package/dist/utils/errorUtils.js.map +1 -1
  34. package/dist/utils/guardedHyperLiquidClient.d.ts +10 -1
  35. package/dist/utils/guardedHyperLiquidClient.d.ts.map +1 -1
  36. package/dist/utils/guardedHyperLiquidClient.js +37 -3
  37. package/dist/utils/guardedHyperLiquidClient.js.map +1 -1
  38. package/dist/utils/hyperLiquidValidation.d.ts.map +1 -1
  39. package/dist/utils/hyperLiquidValidation.js +4 -2
  40. package/dist/utils/hyperLiquidValidation.js.map +1 -1
  41. package/docs/tpsl.md +2 -2
  42. package/package.json +6 -5
@@ -3,8 +3,8 @@ import { HyperliquidError } from '@nktkas/hyperliquid';
3
3
  import { BigNumber } from 'bignumber.js';
4
4
  import { v4 as uuidv4 } from 'uuid';
5
5
  import { PERPS_EVENT_PROPERTY, PERPS_EVENT_VALUE, } from '../constants/eventNames.js';
6
- import { BASIS_POINTS_DIVISOR, BUILDER_FEE_CONFIG, canonicalizeHyperLiquidDexes, FEE_RATES, HYPERLIQUID_ORDER_CAPABILITIES, getBridgeInfo, getChainId, HIP3_ASSET_MARKET_TYPES, HIP3_FEE_CONFIG, HIP3_MARGIN_CONFIG, HYPERLIQUID_ASSET_NAMES, HYPERLIQUID_CONFIG, HYPERLIQUID_WITHDRAWAL_MINUTES, isUnrestrictedMarginMode, REFERRAL_CONFIG, TRADING_DEFAULTS, USDC_DECIMALS, USDC_SYMBOL, } from '../constants/hyperLiquidConfig.js';
7
- import { DETAILED_ORDER_TYPES } from '../constants/orderTypes.js';
6
+ import { BASIS_POINTS_DIVISOR, BUILDER_FEE_CONFIG, canonicalizeHyperLiquidDexes, FEE_RATES, HYPERLIQUID_ORDER_CAPABILITIES, getBridgeInfo, getChainId, HIP3_ASSET_MARKET_TYPES, HIP3_FEE_CONFIG, HIP3_MARGIN_CONFIG, HYPERLIQUID_ACCOUNT_SUPPORT_RECHECK_MS, HYPERLIQUID_ASSET_NAMES, HYPERLIQUID_CONFIG, HYPERLIQUID_WITHDRAWAL_MINUTES, isUnrestrictedMarginMode, REFERRAL_CONFIG, TRADING_DEFAULTS, USDC_DECIMALS, USDC_SYMBOL, } from '../constants/hyperLiquidConfig.js';
7
+ import { DETAILED_ORDER_TYPES, isTPSLOrder } from '../constants/orderTypes.js';
8
8
  import { CHASE_ORDER_CONFIG, CHASE_ORDER_STATUS, DECIMAL_PRECISION_CONFIG, HYPERLIQUID_TWAP_LIMITS, ORDER_SLIPPAGE_CONFIG, PERFORMANCE_CONFIG, PERPS_CONSTANTS, PROVIDER_CONFIG, SUBSCRIPTION_CLOID_CONFIG, TP_SL_CONFIG, WITHDRAWAL_CONSTANTS, } from '../constants/perpsConfig.js';
9
9
  import { PERPS_TRANSACTIONS_HISTORY_CONSTANTS } from '../constants/transactionsHistoryConfig.js';
10
10
  import { OrderDiscoveryError, PerpsControllerError } from '../errors.js';
@@ -23,7 +23,7 @@ import { boundTwapExecution, isChaseOrderRunning, reconcileTwapExecution, supers
23
23
  import { isValidCapabilitySymbol } from '../utils/capabilitySymbols.js';
24
24
  import { resolveCloseSelection } from '../utils/closePositions.js';
25
25
  import { PERPS_ERROR_ACTION, PERPS_ERROR_COMPONENT, PERPS_ERROR_OPERATION, attachProviderErrorCause, createPerpsErrorContext, } from '../utils/errorContext.js';
26
- import { ensureError, isHyperLiquidMultiSigRequiredError, isHyperLiquidUserNotFoundError, isKeyringLockedError, normalizeHyperLiquidError, } from '../utils/errorUtils.js';
26
+ import { ensureError, getHyperLiquidWriteGuardCode, isHyperLiquidMultiSigRequiredError, isHyperLiquidUserNotFoundError, isKeyringLockedError, normalizeHyperLiquidError, } from '../utils/errorUtils.js';
27
27
  import { shouldDeferUnifiedAccountSetup } from '../utils/hyperLiquidAbstraction.js';
28
28
  import { adaptAccountStateFromSDK, adaptHyperLiquidLedgerUpdateToUserHistoryItem, adaptMarketFromSDK, adaptOrderFromSDK, adaptPositionFromSDK, adaptPositionTriggerOrderFromSDK, adaptPublicTradesFromHyperLiquid, adaptTpslLinkageToGrouping, buildAssetMapping, buildHyperLiquidFillId, formatHyperLiquidPrice, formatHyperLiquidSize, HYPERLIQUID_SCALE_CLOID_MARKER, parseAssetName, readScaleGroupId, } from '../utils/hyperLiquidAdapter.js';
29
29
  import { estimateCrossLiquidationPrice, estimateCrossMaintenanceMargin, previewHyperLiquidIsolatedPositionModify, resolveHyperLiquidMarginTiers, } from '../utils/hyperLiquidPositionPreview.js';
@@ -782,6 +782,9 @@ export class HyperLiquidProvider {
782
782
  // Session-scoped, account/network-keyed support probes. Provider instances
783
783
  // are discarded on reconnect; rejected probes are not retained.
784
784
  #accountSupportByContext = new Map();
785
+ // Expiry for probe-derived entries in #accountSupportByContext. Venue
786
+ // rejections recorded by #recordAccountSupport have no expiry.
787
+ #accountSupportExpiresAt = new Map();
785
788
  // Session cache for builder fee approval state (cleared on disconnect/reconnect)
786
789
  // Key: `network:userAddress`, Value: true if builder fee is approved
787
790
  #builderFeeCheckCache = new Map();
@@ -892,6 +895,7 @@ export class HyperLiquidProvider {
892
895
  // venue answer. A "Must deposit" answer is attributed from it, so only to
893
896
  // the agent that signed that request.
894
897
  #agentSignatureByAnswer = new WeakMap();
898
+ #getCurrentIsTestnet;
895
899
  #onAgentRejected;
896
900
  // Promise-based lock to prevent race conditions in concurrent initialization
897
901
  #initializationPromise = null;
@@ -917,6 +921,7 @@ export class HyperLiquidProvider {
917
921
  options.subscriptionBuilderAddressMainnet;
918
922
  this.#getAgentSigner = options.getAgentSigner;
919
923
  this.#onAgentRejected = options.onAgentRejected;
924
+ this.#getCurrentIsTestnet = options.getCurrentIsTestnet;
920
925
  this.#onChaseOrderMaxDistanceReached =
921
926
  options.onChaseOrderMaxDistanceReached;
922
927
  this.#priceDeviationLimit =
@@ -1782,8 +1787,19 @@ export class HyperLiquidProvider {
1782
1787
  #getAccountSupportCacheKey(network, userAddress) {
1783
1788
  return `${network}:${userAddress.toLowerCase()}`;
1784
1789
  }
1785
- #recordAccountSupport(network, userAddress, support) {
1786
- this.#accountSupportByContext.set(this.#getAccountSupportCacheKey(network, userAddress), Promise.resolve(support));
1790
+ #recordUnsupportedAccount(network, userAddress) {
1791
+ const cacheKey = this.#getAccountSupportCacheKey(network, userAddress);
1792
+ this.#accountSupportByContext.set(cacheKey, Promise.resolve({ isSupported: false, reason: 'multi_sig_account' }));
1793
+ this.#accountSupportExpiresAt.delete(cacheKey);
1794
+ }
1795
+ #assertCachedAccountWritable(cacheKey, support) {
1796
+ // A nonexpiring entry is a refusal recorded while a write can be
1797
+ // awaiting a probe or checking that the captured account is still active.
1798
+ const hasRecordedRefusal = this.#accountSupportByContext.has(cacheKey) &&
1799
+ !this.#accountSupportExpiresAt.has(cacheKey);
1800
+ if (support?.isSupported === false || hasRecordedRefusal) {
1801
+ throw new Error(PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED);
1802
+ }
1787
1803
  }
1788
1804
  /**
1789
1805
  * Replace an optimistic support result after the venue authoritatively
@@ -1797,15 +1813,10 @@ export class HyperLiquidProvider {
1797
1813
  * @returns Whether the rejection requires Hyperliquid multi-signature.
1798
1814
  */
1799
1815
  #recordUnsupportedAccountFromError(error, accountContext) {
1800
- const isMultiSigRequired = isHyperLiquidMultiSigRequiredError(error) ||
1801
- ensureError(error, 'HyperLiquidProvider.recordUnsupportedAccountFromError').message === PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED;
1802
- if (!isMultiSigRequired) {
1816
+ if (!isHyperLiquidMultiSigRequiredError(error)) {
1803
1817
  return false;
1804
1818
  }
1805
- this.#recordAccountSupport(accountContext.network, accountContext.userAddress, {
1806
- isSupported: false,
1807
- reason: 'multi_sig_account',
1808
- });
1819
+ this.#recordUnsupportedAccount(accountContext.network, accountContext.userAddress);
1809
1820
  return true;
1810
1821
  }
1811
1822
  /**
@@ -1821,16 +1832,41 @@ export class HyperLiquidProvider {
1821
1832
  typeof status.error === 'string' &&
1822
1833
  this.#recordUnsupportedAccountFromError(createStatusError(status.error, answer), accountContext));
1823
1834
  }
1835
+ /**
1836
+ * Record venue refusals before the SDK releases the wallet's signing lock.
1837
+ *
1838
+ * @param outcome - Exchange transport response or thrown error.
1839
+ * @param accountContext - Captured account that issued the request.
1840
+ */
1841
+ #recordUnsupportedAccountFromExchangeOutcome(outcome, accountContext) {
1842
+ if ('error' in outcome) {
1843
+ this.#recordUnsupportedAccountFromError(outcome.error, accountContext);
1844
+ }
1845
+ const answer = 'answer' in outcome ? outcome.answer : getVenueAnswer(outcome.error);
1846
+ if (isStatusObject(answer)) {
1847
+ const { response } = answer;
1848
+ if (answer.status === 'err' && typeof response === 'string') {
1849
+ this.#recordUnsupportedAccountFromError(response, accountContext);
1850
+ }
1851
+ else if (isStatusObject(response) && isStatusObject(response.data)) {
1852
+ const { status, statuses } = response.data;
1853
+ this.#recordUnsupportedAccountFromStatuses(Array.isArray(statuses) ? statuses : [status], answer, accountContext);
1854
+ }
1855
+ }
1856
+ }
1824
1857
  /**
1825
1858
  * Read support for an account context without initializing the provider.
1826
- * Successful results are stable for the provider session and coalesced by
1827
- * account and network. Failed probes fail open and remain retryable.
1859
+ * Results are coalesced by account and network. Unsupported results stay for
1860
+ * the provider session; supported ones are re-probed after
1861
+ * HYPERLIQUID_ACCOUNT_SUPPORT_RECHECK_MS so write-time checks see a signer
1862
+ * change. Failed probes fail open and remain retryable.
1828
1863
  *
1829
1864
  * @param context - An operation-scoped account context. Defaults to the
1830
1865
  * currently active account and network.
1866
+ * @param refreshPositiveSupport - Recheck even a current positive decision.
1831
1867
  * @returns Whether the account can submit Hyperliquid actions.
1832
1868
  */
1833
- async #getAccountSupportForContext(context) {
1869
+ async #getAccountSupportForContext(context, refreshPositiveSupport = false) {
1834
1870
  const userAddress = context?.userAddress ??
1835
1871
  (await this.#walletService.getUserAddressWithDefault());
1836
1872
  const network = context?.network ??
@@ -1838,22 +1874,39 @@ export class HyperLiquidProvider {
1838
1874
  const cacheKey = this.#getAccountSupportCacheKey(network, userAddress);
1839
1875
  const cachedSupport = this.#accountSupportByContext.get(cacheKey);
1840
1876
  if (cachedSupport) {
1841
- return cachedSupport;
1877
+ const expiresAt = this.#accountSupportExpiresAt.get(cacheKey);
1878
+ if (expiresAt === undefined ||
1879
+ (!refreshPositiveSupport && Date.now() < expiresAt)) {
1880
+ return cachedSupport;
1881
+ }
1882
+ const cachedResult = await cachedSupport;
1883
+ if (this.#accountSupportByContext.get(cacheKey) !== cachedSupport) {
1884
+ // Replaced while awaiting (venue rejection or a concurrent re-probe).
1885
+ return await this.#getAccountSupportForContext({ userAddress, network, infoClient: context?.infoClient }, refreshPositiveSupport);
1886
+ }
1887
+ if (!cachedResult.isSupported) {
1888
+ return cachedResult;
1889
+ }
1890
+ this.#accountSupportByContext.delete(cacheKey);
1891
+ this.#accountSupportExpiresAt.delete(cacheKey);
1842
1892
  }
1843
1893
  const probe = this.#isHyperliquidMultiSigAccount(userAddress, context?.infoClient);
1844
1894
  const support = probe.then((isMultiSig) => isMultiSig
1845
1895
  ? { isSupported: false, reason: 'multi_sig_account' }
1846
1896
  : { isSupported: true }, () => ({ isSupported: true }));
1847
1897
  this.#accountSupportByContext.set(cacheKey, support);
1898
+ this.#accountSupportExpiresAt.set(cacheKey, Date.now() + HYPERLIQUID_ACCOUNT_SUPPORT_RECHECK_MS);
1848
1899
  probe
1849
1900
  .then((isMultiSig) => {
1850
1901
  if (isMultiSig === undefined &&
1851
1902
  this.#accountSupportByContext.get(cacheKey) === support) {
1852
1903
  this.#accountSupportByContext.delete(cacheKey);
1904
+ this.#accountSupportExpiresAt.delete(cacheKey);
1853
1905
  }
1854
1906
  }, () => {
1855
1907
  if (this.#accountSupportByContext.get(cacheKey) === support) {
1856
1908
  this.#accountSupportByContext.delete(cacheKey);
1909
+ this.#accountSupportExpiresAt.delete(cacheKey);
1857
1910
  }
1858
1911
  })
1859
1912
  .catch(() => undefined);
@@ -1874,11 +1927,11 @@ export class HyperLiquidProvider {
1874
1927
  const currentAddress = await this.#walletService
1875
1928
  .getUserAddressWithDefault()
1876
1929
  .catch(() => undefined);
1877
- const currentNetwork = this.#clientService.isTestnetMode()
1878
- ? 'testnet'
1879
- : 'mainnet';
1930
+ const isTestnet = this.#clientService.isTestnetMode();
1931
+ const currentNetwork = isTestnet ? 'testnet' : 'mainnet';
1880
1932
  if (currentAddress?.toLowerCase() !== context.userAddress.toLowerCase() ||
1881
- currentNetwork !== context.network) {
1933
+ currentNetwork !== context.network ||
1934
+ (this.#getCurrentIsTestnet?.() ?? isTestnet) !== isTestnet) {
1882
1935
  throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
1883
1936
  }
1884
1937
  }
@@ -1890,40 +1943,96 @@ export class HyperLiquidProvider {
1890
1943
  */
1891
1944
  async #assertRollbackAccountWritable(context) {
1892
1945
  await this.#assertAccountIdentityCurrent(context);
1893
- const cachedSupport = this.#accountSupportByContext.get(this.#getAccountSupportCacheKey(context.network, context.userAddress));
1894
- const support = cachedSupport ? await cachedSupport : undefined;
1946
+ const cacheKey = this.#getAccountSupportCacheKey(context.network, context.userAddress);
1947
+ const support = await this.#accountSupportByContext.get(cacheKey);
1895
1948
  await this.#assertAccountIdentityCurrent(context);
1896
- if (support && !support.isSupported) {
1897
- throw new Error(PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED);
1898
- }
1949
+ this.#assertCachedAccountWritable(cacheKey, support);
1899
1950
  }
1900
1951
  /**
1901
1952
  * Block an action when another step has authoritatively corrected support
1902
- * for its captured account. A missing cache entry remains fail-open: this
1903
- * fence must not turn a transient probe failure into another network probe.
1953
+ * for its captured account. Refresh a positive result when it expires.
1954
+ * A retained client can retry a missing cache entry on its next write after
1955
+ * a transient probe failure.
1904
1956
  *
1905
1957
  * @param context - The account, network, and lifecycle captured by the action.
1906
1958
  * @param operation - Operation name included in lifecycle diagnostics.
1907
- */
1908
- async #assertNoKnownUnsupportedAccount(context, operation) {
1909
- await this.#assertAccountContextCurrent(context, operation);
1910
- const cachedSupport = this.#accountSupportByContext.get(this.#getAccountSupportCacheKey(context.network, context.userAddress));
1911
- const support = cachedSupport ? await cachedSupport : undefined;
1912
- await this.#assertAccountContextCurrent(context, operation);
1913
- if (support && !support.isSupported) {
1914
- throw new Error(PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED);
1915
- }
1959
+ * @param options - Requirements for the captured write.
1960
+ * @param options.retryMissingSupport - Retry a missing support decision.
1961
+ * @param options.requireVerifiedSupport - Refuse writes if support is unavailable.
1962
+ * @param options.refreshPositiveSupport - Recheck support after signing even before expiry.
1963
+ * @param options.rollbackInfoClient - Captured HTTP reader for cleanup after teardown.
1964
+ */
1965
+ async #assertNoKnownUnsupportedAccount(context, operation, options = {}) {
1966
+ const { requireVerifiedSupport, retryMissingSupport, refreshPositiveSupport, rollbackInfoClient, } = options;
1967
+ const assertScope = rollbackInfoClient
1968
+ ? async () => await this.#assertAccountIdentityCurrent(context)
1969
+ : async () => await this.#assertAccountContextCurrent(context, operation);
1970
+ await assertScope();
1971
+ const cacheKey = this.#getAccountSupportCacheKey(context.network, context.userAddress);
1972
+ const supportContext = { ...context, infoClient: rollbackInfoClient };
1973
+ if (refreshPositiveSupport ||
1974
+ ((retryMissingSupport || requireVerifiedSupport) &&
1975
+ !this.#accountSupportByContext.has(cacheKey))) {
1976
+ await this.#getAccountSupportForContext(supportContext, refreshPositiveSupport);
1977
+ }
1978
+ let supportRequest;
1979
+ let expiresAt = this.#accountSupportExpiresAt.get(cacheKey);
1980
+ do {
1981
+ if (expiresAt !== undefined && Date.now() >= expiresAt) {
1982
+ await this.#getAccountSupportForContext(supportContext);
1983
+ }
1984
+ supportRequest = this.#accountSupportByContext.get(cacheKey);
1985
+ const support = await supportRequest;
1986
+ await assertScope();
1987
+ this.#assertCachedAccountWritable(cacheKey, support);
1988
+ if (requireVerifiedSupport &&
1989
+ !this.#accountSupportByContext.has(cacheKey)) {
1990
+ throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);
1991
+ }
1992
+ // The decision can expire or be replaced during the identity lookup.
1993
+ expiresAt = this.#accountSupportExpiresAt.get(cacheKey);
1994
+ } while (this.#accountSupportByContext.get(cacheKey) !== supportRequest ||
1995
+ (expiresAt !== undefined && Date.now() >= expiresAt));
1916
1996
  }
1917
1997
  /**
1918
1998
  * Create an operation-local exchange client that revalidates its captured
1919
- * account after signing and immediately before transport dispatch.
1999
+ * account before signing and again immediately before transport dispatch.
1920
2000
  *
1921
2001
  * @param context - Account, network, and lifecycle authorized for the write.
1922
2002
  * @param operation - Operation name included in lifecycle diagnostics.
1923
2003
  * @returns An exchange client fenced to the captured account context.
1924
2004
  */
1925
2005
  #getAccountGuardedExchangeClient(context, operation) {
1926
- return this.#clientService.getExchangeClient(async () => await this.#assertNoKnownUnsupportedAccount(context, operation));
2006
+ const assertWritable = async () => await this.#assertNoKnownUnsupportedAccount(context, operation);
2007
+ return this.#clientService.getExchangeClient(assertWritable, {
2008
+ beforeSign: assertWritable,
2009
+ });
2010
+ }
2011
+ /**
2012
+ * Capture a cleanup client before placement so it can retract orders after
2013
+ * teardown, provided the issuing account is still selected on that network.
2014
+ *
2015
+ * @param accountContext - Owner of the placement and rollback.
2016
+ * @returns The exchange client for compensating cancellation.
2017
+ */
2018
+ #getRollbackExchangeClient(accountContext) {
2019
+ // The HTTP reader remains usable after disconnect clears the SDK clients.
2020
+ const infoClient = this.#clientService.getInfoClient({ useHttp: true });
2021
+ const assertWritable = async () => await this.#assertNoKnownUnsupportedAccount(accountContext, 'Rollback', {
2022
+ requireVerifiedSupport: true,
2023
+ rollbackInfoClient: infoClient,
2024
+ });
2025
+ return this.#clientService.getExchangeClient(assertWritable, {
2026
+ beforeSign: assertWritable,
2027
+ onExchangeResult: (outcome) => this.#recordUnsupportedAccountFromExchangeOutcome(outcome, accountContext),
2028
+ });
2029
+ }
2030
+ async #captureAccountContext() {
2031
+ return {
2032
+ lifecycleGeneration: this.#lifecycleGeneration,
2033
+ network: this.#clientService.isTestnetMode() ? 'testnet' : 'mainnet',
2034
+ userAddress: await this.#walletService.getUserAddressWithDefault(),
2035
+ };
1927
2036
  }
1928
2037
  /**
1929
2038
  * Stop an action before signing when Hyperliquid reports a native multi-sig
@@ -1934,17 +2043,11 @@ export class HyperLiquidProvider {
1934
2043
  * @returns The account context whose support was checked.
1935
2044
  */
1936
2045
  async #assertAccountSupported(expectedContext) {
1937
- const context = expectedContext ??
1938
- {
1939
- lifecycleGeneration: this.#lifecycleGeneration,
1940
- network: this.#clientService.isTestnetMode() ? 'testnet' : 'mainnet',
1941
- userAddress: await this.#walletService.getUserAddressWithDefault(),
1942
- };
2046
+ const context = expectedContext ?? (await this.#captureAccountContext());
1943
2047
  const support = await this.#getAccountSupportForContext(context);
1944
2048
  await this.#assertAccountContextCurrent(context, 'Account support check');
1945
- if (!support.isSupported) {
1946
- throw new Error(PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED);
1947
- }
2049
+ const cacheKey = this.#getAccountSupportCacheKey(context.network, context.userAddress);
2050
+ this.#assertCachedAccountWritable(cacheKey, support);
1948
2051
  return context;
1949
2052
  }
1950
2053
  /**
@@ -2134,9 +2237,9 @@ export class HyperLiquidProvider {
2134
2237
  if (accountContext) {
2135
2238
  await this.#assertNoKnownUnsupportedAccount(accountContext, 'Unified account migration');
2136
2239
  }
2137
- const exchangeClient = this.#clientService.getExchangeClient(accountContext
2138
- ? async () => await this.#assertNoKnownUnsupportedAccount(accountContext, 'Unified account migration dispatch')
2139
- : undefined);
2240
+ const exchangeClient = accountContext
2241
+ ? this.#getAccountGuardedExchangeClient(accountContext, 'Unified account migration dispatch')
2242
+ : this.#clientService.getExchangeClient();
2140
2243
  await exchangeClient.agentSetAbstraction({
2141
2244
  abstraction: HL_ABSTRACTION_WIRE.unifiedAccount,
2142
2245
  });
@@ -2192,10 +2295,7 @@ export class HyperLiquidProvider {
2192
2295
  // account-shape condition, not a failure worth reporting or retrying.
2193
2296
  if (isHyperLiquidMultiSigRequiredError(error)) {
2194
2297
  this.#deps.debugLogger.log('[ensureUnifiedAccountEnabled] Multi-sig account (race/probe fallback), skipping unified account migration', { user: userAddress, network, mode: currentMode });
2195
- this.#recordAccountSupport(network, userAddress, {
2196
- isSupported: false,
2197
- reason: 'multi_sig_account',
2198
- });
2298
+ this.#recordUnsupportedAccount(network, userAddress);
2199
2299
  this.#deps.metrics.trackPerpsEvent(PerpsAnalyticsEvent.AccountSetup, {
2200
2300
  ...(currentMode && {
2201
2301
  [PERPS_EVENT_PROPERTY.PREVIOUS_ABSTRACTION_MODE]: currentMode,
@@ -2229,8 +2329,8 @@ export class HyperLiquidProvider {
2229
2329
  return;
2230
2330
  }
2231
2331
  if (accountContext &&
2232
- ensureError(error, 'HyperLiquidProvider.ensureUnifiedAccountEnabled')
2233
- .message === PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE) {
2332
+ getHyperLiquidWriteGuardCode(error) ===
2333
+ PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE) {
2234
2334
  completeInFlight();
2235
2335
  throw error;
2236
2336
  }
@@ -2776,8 +2876,16 @@ export class HyperLiquidProvider {
2776
2876
  if (!this.#hip3Enabled) {
2777
2877
  return [null];
2778
2878
  }
2779
- if (this.#dexDiscoveryCache.state?.validated) {
2780
- return this.#dexDiscoveryCache.state.validated;
2879
+ const isComplete = (dexs) => Array.isArray(dexs) &&
2880
+ dexs[0] === null &&
2881
+ dexs
2882
+ .slice(1)
2883
+ .every((dex) => isStatusObject(dex) &&
2884
+ typeof dex.name === 'string' &&
2885
+ dex.name.trim().length > 0);
2886
+ const cached = this.#dexDiscoveryCache.state;
2887
+ if (cached && isComplete(cached.raw)) {
2888
+ return cached.validated;
2781
2889
  }
2782
2890
  const lifecycleGeneration = this.#lifecycleGeneration;
2783
2891
  const infoClient = this.#clientService.getInfoClient({ useHttp: true });
@@ -2788,7 +2896,7 @@ export class HyperLiquidProvider {
2788
2896
  catch {
2789
2897
  throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);
2790
2898
  }
2791
- if (!Array.isArray(allDexs)) {
2899
+ if (!isComplete(allDexs)) {
2792
2900
  throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);
2793
2901
  }
2794
2902
  this.#assertCacheWriteLifecycleCurrent(lifecycleGeneration, 'Strict DEX discovery cache write');
@@ -3702,8 +3810,8 @@ export class HyperLiquidProvider {
3702
3810
  }
3703
3811
  catch (error) {
3704
3812
  this.#recordUnsupportedAccountFromError(error, supportContext);
3705
- if (ensureError(error, 'HyperLiquidProvider.ensureBuilderFeeApproval')
3706
- .message === PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE) {
3813
+ if (getHyperLiquidWriteGuardCode(error) ===
3814
+ PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE) {
3707
3815
  completeInFlight();
3708
3816
  return;
3709
3817
  }
@@ -3780,11 +3888,23 @@ export class HyperLiquidProvider {
3780
3888
  this.#approvedBuilderAddresses.add(key);
3781
3889
  return;
3782
3890
  }
3783
- const exchangeClient = this.#clientService.getExchangeClient();
3784
- await exchangeClient.approveBuilderFee({
3785
- builder: builderAddress,
3786
- maxFeeRate: BUILDER_FEE_CONFIG.MaxFeeRate,
3891
+ // Pin support to the account the approval was keyed for.
3892
+ const accountContext = await this.#assertAccountSupported({
3893
+ lifecycleGeneration: this.#lifecycleGeneration,
3894
+ network,
3895
+ userAddress,
3787
3896
  });
3897
+ const exchangeClient = this.#getAccountGuardedExchangeClient(accountContext, 'Subscription builder approval');
3898
+ try {
3899
+ await exchangeClient.approveBuilderFee({
3900
+ builder: builderAddress,
3901
+ maxFeeRate: BUILDER_FEE_CONFIG.MaxFeeRate,
3902
+ });
3903
+ }
3904
+ catch (error) {
3905
+ this.#recordUnsupportedAccountFromError(error, accountContext);
3906
+ throw error;
3907
+ }
3788
3908
  if (approvalEpoch !== this.#subscriptionBuilderApprovalEpoch) {
3789
3909
  return;
3790
3910
  }
@@ -5330,7 +5450,8 @@ export class HyperLiquidProvider {
5330
5450
  durationMinutes > HYPERLIQUID_TWAP_LIMITS.MaxDurationMinutes) {
5331
5451
  throw new Error(PERPS_ERROR_CODES.ORDER_TWAP_DURATION_INVALID);
5332
5452
  }
5333
- const exchangeClient = this.#clientService.getExchangeClient();
5453
+ const exchangeClient = this.#getAccountGuardedExchangeClient(accountContext, 'TWAP order dispatch');
5454
+ const rollbackClient = this.#getRollbackExchangeClient(accountContext);
5334
5455
  this.#deps.debugLogger.log('Submitting TWAP order', {
5335
5456
  symbol: params.symbol,
5336
5457
  assetId,
@@ -5369,7 +5490,7 @@ export class HyperLiquidProvider {
5369
5490
  let remainsLive = true;
5370
5491
  try {
5371
5492
  await this.#assertRollbackAccountWritable(accountContext);
5372
- const cancelResult = await exchangeClient.twapCancel({
5493
+ const cancelResult = await rollbackClient.twapCancel({
5373
5494
  a: assetId,
5374
5495
  t: running.twapId,
5375
5496
  });
@@ -5453,7 +5574,8 @@ export class HyperLiquidProvider {
5453
5574
  prices: orders.map((order) => order.p),
5454
5575
  sizes,
5455
5576
  });
5456
- const exchangeClient = this.#clientService.getExchangeClient();
5577
+ const exchangeClient = this.#getAccountGuardedExchangeClient(accountContext, 'Scale order dispatch');
5578
+ const rollbackClient = this.#getRollbackExchangeClient(accountContext);
5457
5579
  let result;
5458
5580
  let thrownBulkOrderError;
5459
5581
  try {
@@ -5541,11 +5663,11 @@ export class HyperLiquidProvider {
5541
5663
  };
5542
5664
  }
5543
5665
  const [orderIds, pendingClientOrderIds] = await Promise.all([
5544
- this.#cancelOrderRequests(exchangeClient, restingChildOrderIds.map((orderId) => ({
5666
+ this.#cancelOrderRequests(rollbackClient, restingChildOrderIds.map((orderId) => ({
5545
5667
  a: assetId,
5546
5668
  o: Number(orderId),
5547
5669
  }))),
5548
- this.#cancelOrderCloidRequests(exchangeClient, cleanupClientOrderIds.map((clientOrderId) => ({
5670
+ this.#cancelOrderCloidRequests(rollbackClient, cleanupClientOrderIds.map((clientOrderId) => ({
5549
5671
  asset: assetId,
5550
5672
  cloid: clientOrderId,
5551
5673
  }))),
@@ -5683,12 +5805,11 @@ export class HyperLiquidProvider {
5683
5805
  if (generation !== this.#strategyGeneration) {
5684
5806
  throw new Error(PERPS_ERROR_CODES.ORDER_CHASE_ABANDONED);
5685
5807
  }
5686
- // Held onto rather than looked up again after the submission returns.
5687
- // `disconnect` drops the service's client reference synchronously, so a
5688
- // retraction that asked for a client after the fact would be refused one
5689
- // and leave the order resting under the account that placed it. This
5690
- // instance signed the order and can still cancel it as that account.
5691
- const placingClient = this.#clientService.getExchangeClient();
5808
+ const placingClient = this.#getAccountGuardedExchangeClient(accountContext, 'Chase initial placement dispatch');
5809
+ // Capture the cleanup client now because disconnect drops the service's
5810
+ // client reference. Its fence can retract the order after teardown if the
5811
+ // same account and network are still selected.
5812
+ const rollbackClient = this.#getRollbackExchangeClient(accountContext);
5692
5813
  let orderId;
5693
5814
  for (let attempt = 1; attempt <= CHASE_ORDER_CONFIG.InitialPlacementAttempts; attempt += 1) {
5694
5815
  try {
@@ -5773,11 +5894,8 @@ export class HyperLiquidProvider {
5773
5894
  // would have invalidated, and the exchange id is only usable for as long as
5774
5895
  // the provider stays pointed at the account that placed it — a disconnect
5775
5896
  // is usually followed by an account or network switch, after which handing
5776
- // the id back is no remedy at all. So it is cancelled here, through the
5777
- // client that signed it. The held client remains usable after teardown,
5778
- // but its adapter resolves the selected account again for each signature,
5779
- // so rollback validates the captured identity before cancellation. The
5780
- // failure is then true of the venue as well as of this provider.
5897
+ // the id back is no remedy at all. The captured rollback client remains
5898
+ // usable after teardown and checks the signing identity before cancellation.
5781
5899
  // Best-effort still: a context change or closing transport falls back to
5782
5900
  // reporting the live id.
5783
5901
  if (generation !== this.#strategyGeneration) {
@@ -5785,7 +5903,7 @@ export class HyperLiquidProvider {
5785
5903
  orderId,
5786
5904
  restingPrice: quotePrice,
5787
5905
  });
5788
- const outcome = await this.#retractOrphanedChaseOrder(session, placingClient);
5906
+ const outcome = await this.#retractOrphanedChaseOrder(session, rollbackClient);
5789
5907
  return createErrorResult(new Error(PERPS_ERROR_CODES.ORDER_CHASE_ABANDONED), {
5790
5908
  success: false,
5791
5909
  // Reported only when the retraction did not take. Naming an order
@@ -5870,16 +5988,13 @@ export class HyperLiquidProvider {
5870
5988
  * @param params.marksSubscriptionCloid - Whether to mark the cloid, captured
5871
5989
  * when the session started. Passed explicitly rather than read live: a
5872
5990
  * replacement runs long after the fee resolution behind it was cleared.
5873
- * @param params.exchangeClient - Client to submit through. Passed in rather
5874
- * than looked up here so a first placement can keep the instance it signed
5875
- * with, which is the only one that can take the order back once `disconnect`
5876
- * has dropped the service's reference.
5991
+ * @param params.exchangeClient - Guarded client for this placement.
5877
5992
  * @param params.accountContext - Account/network/lifecycle captured by the
5878
5993
  * action that owns the chase.
5879
5994
  * @returns The resting order's exchange ID.
5880
5995
  */
5881
5996
  async #restChaseOrder(params) {
5882
- await this.#assertNoKnownUnsupportedAccount(params.accountContext, 'Chase order submission');
5997
+ await this.#assertAccountSupported(params.accountContext);
5883
5998
  const result = await params.exchangeClient.order({
5884
5999
  orders: this.#applySubscriptionCloid([
5885
6000
  {
@@ -6341,7 +6456,7 @@ export class HyperLiquidProvider {
6341
6456
  builder: session.builder,
6342
6457
  marksSubscriptionCloid: session.marksSubscriptionCloid,
6343
6458
  accountContext: session.accountContext,
6344
- exchangeClient: this.#clientService.getExchangeClient(),
6459
+ exchangeClient: this.#getAccountGuardedExchangeClient(session.accountContext, 'Chase replacement dispatch'),
6345
6460
  });
6346
6461
  session.size = size;
6347
6462
  session.replacementRefusals = 0;
@@ -6567,9 +6682,10 @@ export class HyperLiquidProvider {
6567
6682
  await this.#assertRollbackAccountWritable(session.accountContext);
6568
6683
  }
6569
6684
  else {
6570
- await this.#assertNoKnownUnsupportedAccount(session.accountContext, 'Chase cancellation');
6685
+ await this.#assertAccountSupported(session.accountContext);
6571
6686
  }
6572
- const exchangeClient = placingClient ?? this.#clientService.getExchangeClient();
6687
+ const exchangeClient = placingClient ??
6688
+ this.#getAccountGuardedExchangeClient(session.accountContext, 'Chase cancellation dispatch');
6573
6689
  let result;
6574
6690
  try {
6575
6691
  result = await exchangeClient.cancel({
@@ -7118,7 +7234,7 @@ export class HyperLiquidProvider {
7118
7234
  await this.#assertNoKnownUnsupportedAccount(accountContext, 'TWAP cancellation');
7119
7235
  let result;
7120
7236
  try {
7121
- result = await this.#clientService.getExchangeClient().twapCancel({
7237
+ result = await this.#getAccountGuardedExchangeClient(accountContext, 'TWAP cancellation dispatch').twapCancel({
7122
7238
  a: assetId,
7123
7239
  t: twapId,
7124
7240
  });
@@ -7162,7 +7278,7 @@ export class HyperLiquidProvider {
7162
7278
  symbol: group.symbol,
7163
7279
  dexName: parseAssetName(group.symbol).dex,
7164
7280
  });
7165
- const exchangeClient = this.#clientService.getExchangeClient();
7281
+ const exchangeClient = this.#getAccountGuardedExchangeClient(accountContext, 'Scale cancellation dispatch');
7166
7282
  const cancelRequests = group.orderIds.map((orderId) => ({
7167
7283
  a: assetId,
7168
7284
  o: Number(orderId),
@@ -8023,7 +8139,7 @@ export class HyperLiquidProvider {
8023
8139
  // the fill fan-out a reduction applied to an order that paid nothing.
8024
8140
  // The replacement inherits the resting order's own attribution.
8025
8141
  await this.#assertNoKnownUnsupportedAccount(accountContext, 'Order modification');
8026
- const exchangeClient = this.#clientService.getExchangeClient();
8142
+ const exchangeClient = this.#getAccountGuardedExchangeClient(accountContext, 'Order modification dispatch');
8027
8143
  try {
8028
8144
  const result = await exchangeClient.modify({
8029
8145
  oid: typeof params.orderId === 'string'
@@ -8123,7 +8239,7 @@ export class HyperLiquidProvider {
8123
8239
  dexName: parseAssetName(params.symbol).dex,
8124
8240
  });
8125
8241
  await this.#assertNoKnownUnsupportedAccount(accountContext, 'Order cancellation');
8126
- const exchangeClient = this.#clientService.getExchangeClient();
8242
+ const exchangeClient = this.#getAccountGuardedExchangeClient(accountContext, 'Order cancellation dispatch');
8127
8243
  const result = await exchangeClient.cancel({
8128
8244
  cancels: [
8129
8245
  {
@@ -8204,6 +8320,8 @@ export class HyperLiquidProvider {
8204
8320
  });
8205
8321
  const chaseIndexes = new Set(chaseRoutes.map(({ index }) => index));
8206
8322
  try {
8323
+ const issuedAccount = await this.#captureAccountContext();
8324
+ await this.#assertAccountContextCurrent(issuedAccount, 'Batch order cancellation');
8207
8325
  for (const handle of new Set(chaseRoutes.map((route) => route.handle))) {
8208
8326
  this.#stopChaseSession(handle);
8209
8327
  }
@@ -8229,6 +8347,7 @@ export class HyperLiquidProvider {
8229
8347
  // fee approval that the action cannot use.
8230
8348
  const { accountContext } = await this.#ensureReadyForTrading({
8231
8349
  requiresBuilderFee: false,
8350
+ accountContext: issuedAccount,
8232
8351
  });
8233
8352
  const cancelRequests = await Promise.all(ordinaryOrders.map(async ({ order }) => {
8234
8353
  const asset = await this.#getAssetIdWithRepair({
@@ -8241,7 +8360,7 @@ export class HyperLiquidProvider {
8241
8360
  };
8242
8361
  }));
8243
8362
  await this.#assertNoKnownUnsupportedAccount(accountContext, 'Batch order cancellation');
8244
- const exchangeClient = this.#clientService.getExchangeClient();
8363
+ const exchangeClient = this.#getAccountGuardedExchangeClient(accountContext, 'Batch order cancellation dispatch');
8245
8364
  let statuses;
8246
8365
  let answer;
8247
8366
  try {
@@ -8536,7 +8655,7 @@ export class HyperLiquidProvider {
8536
8655
  }
8537
8656
  // Single batch API call
8538
8657
  await this.#assertNoKnownUnsupportedAccount(accountContext, 'Batch close submission');
8539
- const exchangeClient = this.#clientService.getExchangeClient();
8658
+ const exchangeClient = this.#getAccountGuardedExchangeClient(accountContext, 'Batch close submission dispatch');
8540
8659
  const result = await exchangeClient.order({
8541
8660
  orders: this.#applySubscriptionCloid(orders),
8542
8661
  grouping: 'na',
@@ -8759,26 +8878,32 @@ export class HyperLiquidProvider {
8759
8878
  params.stopLossSize === undefined))) {
8760
8879
  throw new Error('Hyperliquid partial pair linkage requires an independently sized TP/SL pair');
8761
8880
  }
8762
- const lifecycle = this.#lifecycleGeneration;
8763
- const isTestnet = this.#clientService.isTestnetMode();
8764
- const userAddress = await this.#walletService.getUserAddressWithDefault();
8765
- const accountContext = {
8766
- lifecycleGeneration: lifecycle,
8767
- network: isTestnet ? 'testnet' : 'mainnet',
8768
- userAddress,
8769
- };
8770
- const assertScope = async () => {
8771
- const current = await this.#walletService.getUserAddressWithDefault();
8772
- this.#assertProviderLifecycleCurrent(lifecycle, operationName);
8773
- if (current.toLowerCase() !== userAddress.toLowerCase() ||
8774
- this.#clientService.isTestnetMode() !== isTestnet) {
8775
- throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
8776
- }
8777
- };
8881
+ const accountContext = await this.#captureAccountContext();
8882
+ const { userAddress } = accountContext;
8883
+ const assertScope = async () => await this.#assertAccountContextCurrent(accountContext, operationName);
8778
8884
  await assertScope();
8779
8885
  this.#deps.debugLogger.log('Updating position TP/SL:', params);
8780
8886
  const { symbol, takeProfitPrice, stopLossPrice, takeProfitSize, stopLossSize, position: livePosition, } = params;
8781
8887
  const isPartialTpsl = takeProfitSize !== undefined || stopLossSize !== undefined;
8888
+ // The price each leg fills at once triggered; undefined executes at
8889
+ // market. A whole-position update fills TP as a limit at its trigger and
8890
+ // SL at market. A leg replace fills at its limit price, else at market.
8891
+ const takeProfitFillPrice = legScope
8892
+ ? legScope.limitPrice
8893
+ : takeProfitPrice;
8894
+ const stopLossFillPrice = legScope?.limitPrice;
8895
+ const usesSlippageCap = !isPartialTpsl &&
8896
+ ((Boolean(takeProfitPrice) && takeProfitFillPrice === undefined) ||
8897
+ (Boolean(stopLossPrice) && stopLossFillPrice === undefined));
8898
+ const maxSlippageBps = usesSlippageCap
8899
+ ? (legScope?.maxSlippageBps ?? params.maxSlippageBps)
8900
+ : undefined;
8901
+ if (maxSlippageBps !== undefined &&
8902
+ (!Number.isFinite(maxSlippageBps) ||
8903
+ maxSlippageBps < 0 ||
8904
+ maxSlippageBps >= BASIS_POINTS_DIVISOR)) {
8905
+ return { success: false, error: PERPS_ERROR_CODES.SLIPPAGE_EXCEEDED };
8906
+ }
8782
8907
  // Basic initialization only. The trading setup that can prompt a hardware
8783
8908
  // wallet and write the referral / builder-fee approvals is deferred until
8784
8909
  // every validation below has passed, so a rejected update leaves nothing
@@ -8889,13 +9014,6 @@ export class HyperLiquidProvider {
8889
9014
  // HyperLiquid accepts one builder context for the whole TP/SL action.
8890
9015
  // Position TP/SL has no parent policy to inherit, so resolve every
8891
9016
  // included trigger and charge the batch when any child policy charges.
8892
- // The price each leg fills at once triggered; undefined executes at
8893
- // market. A whole-position update fills TP as a limit at its trigger and
8894
- // SL at market. A leg replace fills at its limit price, else at market.
8895
- const takeProfitFillPrice = legScope
8896
- ? legScope.limitPrice
8897
- : takeProfitPrice;
8898
- const stopLossFillPrice = legScope?.limitPrice;
8899
9017
  const feePolicyContexts = [
8900
9018
  ...(takeProfitPrice
8901
9019
  ? [
@@ -9086,39 +9204,47 @@ export class HyperLiquidProvider {
9086
9204
  }
9087
9205
  // Build orders array for TP/SL
9088
9206
  const orders = [];
9089
- // The limit HyperLiquid fills a leg at once triggered. A replaced market
9090
- // leg is capped like any market trigger: its trigger moved against the
9091
- // closing side by the slippage tolerance. A whole-position update keeps
9092
- // its existing prices.
9093
- const legOrderPrice = (orderType, triggerPrice, fillPrice) => legScope && fillPrice === undefined
9094
- ? calculateOrderPriceAndSize({
9095
- orderType,
9096
- isBuy: !isLong,
9097
- finalPositionSize: 0,
9098
- currentPrice: 0,
9099
- triggerPrice,
9100
- maxSlippageBps: legScope.maxSlippageBps,
9101
- szDecimals: assetInfo.szDecimals,
9102
- }).formattedPrice
9103
- : formatHyperLiquidPrice({
9104
- price: parseFloat(fillPrice ?? triggerPrice),
9105
- szDecimals: assetInfo.szDecimals,
9106
- });
9207
+ const formatLegPrice = (price) => formatHyperLiquidPrice({
9208
+ price,
9209
+ szDecimals: assetInfo.szDecimals,
9210
+ });
9211
+ const legOrderPrice = (triggerPx, fillPrice) => {
9212
+ // Standalone partial triggers retain their trigger as the fill price.
9213
+ if (fillPrice !== undefined) {
9214
+ return formatLegPrice(fillPrice);
9215
+ }
9216
+ if (isPartialTpsl) {
9217
+ return triggerPx;
9218
+ }
9219
+ // Derive the cap from the wire trigger and round toward it so the
9220
+ // submitted limit cannot widen the chosen tolerance. Integers are
9221
+ // always valid prices, even when the significant-figure grid is wider.
9222
+ const tolerance = new BigNumber(maxSlippageBps ?? ORDER_SLIPPAGE_CONFIG.DefaultTpslSlippageBps).times(1 / BASIS_POINTS_DIVISOR);
9223
+ const boundary = new BigNumber(triggerPx).times(isLong ? tolerance.negated().plus(1) : tolerance.plus(1));
9224
+ // Use the decimal exponent so a boundary just below a power of ten
9225
+ // keeps its tick. A floating-point conversion can round it up.
9226
+ const priceDecimals = Math.max(0, Math.min(DECIMAL_PRECISION_CONFIG.MaxPriceDecimals - assetInfo.szDecimals, DECIMAL_PRECISION_CONFIG.MaxSignificantFigures -
9227
+ 1 -
9228
+ (boundary.e ?? 0)));
9229
+ return boundary
9230
+ .shiftedBy(priceDecimals)
9231
+ .integerValue(isLong ? BigNumber.ROUND_CEIL : BigNumber.ROUND_FLOOR)
9232
+ .shiftedBy(-priceDecimals)
9233
+ .toFixed();
9234
+ };
9107
9235
  // Take Profit order
9108
9236
  if (takeProfitPrice) {
9237
+ const triggerPx = formatLegPrice(takeProfitPrice);
9109
9238
  const tpOrder = {
9110
9239
  a: assetId,
9111
9240
  b: !isLong, // Opposite side to close position
9112
- p: legOrderPrice('take_profit_market', takeProfitPrice, takeProfitFillPrice),
9241
+ p: legOrderPrice(triggerPx, takeProfitFillPrice),
9113
9242
  s: resolveTpslSize(takeProfitSize),
9114
9243
  r: true, // Always reduce-only for position TP
9115
9244
  t: {
9116
9245
  trigger: {
9117
9246
  isMarket: takeProfitFillPrice === undefined,
9118
- triggerPx: formatHyperLiquidPrice({
9119
- price: parseFloat(takeProfitPrice),
9120
- szDecimals: assetInfo.szDecimals,
9121
- }),
9247
+ triggerPx,
9122
9248
  tpsl: 'tp',
9123
9249
  },
9124
9250
  },
@@ -9127,25 +9253,32 @@ export class HyperLiquidProvider {
9127
9253
  }
9128
9254
  // Stop Loss order
9129
9255
  if (stopLossPrice) {
9256
+ const triggerPx = formatLegPrice(stopLossPrice);
9130
9257
  const slOrder = {
9131
9258
  a: assetId,
9132
9259
  b: !isLong, // Opposite side to close position
9133
- p: legOrderPrice('stop_market', stopLossPrice, stopLossFillPrice),
9260
+ p: legOrderPrice(triggerPx, stopLossFillPrice),
9134
9261
  s: resolveTpslSize(stopLossSize),
9135
9262
  r: true, // Always reduce-only for position SL
9136
9263
  t: {
9137
9264
  trigger: {
9138
9265
  isMarket: stopLossFillPrice === undefined,
9139
- triggerPx: formatHyperLiquidPrice({
9140
- price: parseFloat(stopLossPrice),
9141
- szDecimals: assetInfo.szDecimals,
9142
- }),
9266
+ triggerPx,
9143
9267
  tpsl: 'sl',
9144
9268
  },
9145
9269
  },
9146
9270
  };
9147
9271
  orders.push(slOrder);
9148
9272
  }
9273
+ for (const order of orders) {
9274
+ const price = Number(order.p);
9275
+ if (!(Number.isFinite(price) && price > 0)) {
9276
+ return {
9277
+ success: false,
9278
+ error: PERPS_ERROR_CODES.ORDER_PRICE_POSITIVE,
9279
+ };
9280
+ }
9281
+ }
9149
9282
  const generatedCloids = new Set();
9150
9283
  for (const order of orders) {
9151
9284
  order.c = createUnmarkedProtectionCloid(generatedCloids);
@@ -9168,35 +9301,51 @@ export class HyperLiquidProvider {
9168
9301
  }
9169
9302
  };
9170
9303
  await assertCurrentPosition();
9171
- // These operation-local reads run inside the SDK signing semaphore.
9172
- // The extra round trips deliberately serialize with the signed write,
9173
- // preventing stale account-shape/position dispatch after wallet prompts.
9174
- const assertWritableScope = async () => {
9175
- await assertScope();
9176
- const isMultiSig = await this.#isHyperliquidMultiSigAccount(userAddress, infoClient);
9177
- await assertScope();
9178
- if (isMultiSig) {
9179
- throw new Error(PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED);
9304
+ const assertWritableScope = async (refreshPositiveSupport = false) => await this.#assertNoKnownUnsupportedAccount(accountContext, operationName, { requireVerifiedSupport: true, refreshPositiveSupport });
9305
+ const assertWritablePosition = async (refreshPositiveSupport = false) => {
9306
+ await assertWritableScope(refreshPositiveSupport);
9307
+ await assertCurrentPosition();
9308
+ if (expectedPosition) {
9309
+ // The position read can outlive a positive account-support decision.
9310
+ await assertWritableScope();
9180
9311
  }
9181
9312
  };
9313
+ const recordOutcome = (outcome) => this.#recordUnsupportedAccountFromExchangeOutcome(outcome, accountContext);
9182
9314
  let cancelGuardFailure;
9183
- const exchangeClient = this.#clientService.getExchangeClient(async () => {
9315
+ const assertCanCancel = async (refreshPositiveSupport = false) => {
9184
9316
  try {
9185
- await assertWritableScope();
9186
- await assertCurrentPosition();
9317
+ await assertWritablePosition(refreshPositiveSupport);
9187
9318
  }
9188
9319
  catch (error) {
9189
9320
  cancelGuardFailure = error;
9190
9321
  throw error;
9191
9322
  }
9323
+ };
9324
+ const exchangeClient = this.#clientService.getExchangeClient(async () => await assertCanCancel(true), { beforeSign: assertCanCancel, onExchangeResult: recordOutcome });
9325
+ // Restoration belongs to the same account and network, but does not use
9326
+ // the requested replacement's position precondition.
9327
+ const assertRestorationWritable = async (refreshPositiveSupport = false) => {
9328
+ try {
9329
+ await assertWritableScope(refreshPositiveSupport);
9330
+ }
9331
+ catch (error) {
9332
+ if (!(error instanceof Error) ||
9333
+ error.message !== PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE) {
9334
+ throw error;
9335
+ }
9336
+ // Retry the read before restoring confirmed cancellations.
9337
+ await assertWritableScope(refreshPositiveSupport);
9338
+ }
9339
+ };
9340
+ const recoveryExchangeClient = this.#clientService.getExchangeClient(async () => await assertRestorationWritable(true), {
9341
+ beforeSign: assertRestorationWritable,
9342
+ onExchangeResult: recordOutcome,
9192
9343
  });
9193
- const recoveryExchangeClient = this.#clientService.getExchangeClient(assertWritableScope);
9194
9344
  let replacementMayHaveDispatched = false;
9195
9345
  const replacementExchangeClient = this.#clientService.getExchangeClient(async () => {
9196
- await assertWritableScope();
9197
- await assertCurrentPosition();
9346
+ await assertWritablePosition(true);
9198
9347
  replacementMayHaveDispatched = true;
9199
- });
9348
+ }, { beforeSign: assertWritablePosition, onExchangeResult: recordOutcome });
9200
9349
  const rollbackRequiresBuilderFee = [
9201
9350
  ...restorablePositionTpslOrders,
9202
9351
  ...restorableStandaloneTpslOrders,
@@ -9249,9 +9398,7 @@ export class HyperLiquidProvider {
9249
9398
  let statuses;
9250
9399
  let restorationFailure;
9251
9400
  try {
9252
- // Restore the exact pre-call reduce-only intent. Scope and account
9253
- // shape are still probed after signing, but the requested new
9254
- // protection's position precondition does not apply to rollback.
9401
+ // Restore the exact pre-call reduce-only intent.
9255
9402
  await assertScope();
9256
9403
  const result = await recoveryExchangeClient.order({
9257
9404
  orders: sentRestorationOrders,
@@ -9812,7 +9959,7 @@ export class HyperLiquidProvider {
9812
9959
  }
9813
9960
  // Call SDK to update isolated margin
9814
9961
  await this.#assertNoKnownUnsupportedAccount(accountContext, 'Margin update');
9815
- const exchangeClient = this.#clientService.getExchangeClient();
9962
+ const exchangeClient = this.#getAccountGuardedExchangeClient(accountContext, 'Margin update dispatch');
9816
9963
  const result = await exchangeClient.updateIsolatedMargin({
9817
9964
  asset: assetId,
9818
9965
  isBuy,
@@ -10551,6 +10698,7 @@ export class HyperLiquidProvider {
10551
10698
  * @returns A promise that resolves to the result.
10552
10699
  */
10553
10700
  async getOpenOrders(params) {
10701
+ const strict = params?.throwOnUnavailable === true;
10554
10702
  const generation = this.#lifecycleGeneration;
10555
10703
  try {
10556
10704
  // Path 0: Standalone mode for lightweight open order queries
@@ -10586,10 +10734,10 @@ export class HyperLiquidProvider {
10586
10734
  return orders;
10587
10735
  }
10588
10736
  const userAddress = await this.#walletService.getUserAddressWithDefault(params?.accountId);
10589
- if (!params?.skipCache && params?.accountId === undefined) {
10737
+ if (!strict && !params?.skipCache && params?.accountId === undefined) {
10590
10738
  const cachedOrders = this.#subscriptionService.getOrdersCacheIfInitialized(true, {
10591
10739
  userAddress,
10592
- requirePositionSizes: !params?.throwOnUnavailable,
10740
+ requirePositionSizes: true,
10593
10741
  });
10594
10742
  if (cachedOrders !== null) {
10595
10743
  this.#assertCacheWriteLifecycleCurrent(generation, 'Get open orders');
@@ -10605,10 +10753,30 @@ export class HyperLiquidProvider {
10605
10753
  // Read-only operation: only need client initialization
10606
10754
  await this.#ensureClientsInitialized();
10607
10755
  this.#clientService.ensureInitialized();
10608
- const infoClient = this.#clientService.getInfoClient();
10609
- const dexs = await this.#getValidatedDexsStrict();
10610
- const { results: orderResults, failedDexs } = await this.#queryUserDataAcrossDexs({ user: userAddress }, (userParam) => infoClient.frontendOpenOrders(userParam), dexs);
10611
- if (failedDexs.length > 0 && !params?.throwOnUnavailable) {
10756
+ const infoClient = strict
10757
+ ? this.#clientService.getInfoClient({ useHttp: true })
10758
+ : this.#clientService.getInfoClient();
10759
+ // Query orders across all enabled DEXs in parallel
10760
+ const { results: orderResults, failedDexs } = await this.#queryUserDataAcrossDexs({ user: userAddress }, async (userParam) => {
10761
+ const orders = await infoClient.frontendOpenOrders(userParam);
10762
+ if (strict) {
10763
+ const knownTypes = Object.values(DETAILED_ORDER_TYPES);
10764
+ if (!Array.isArray(orders) ||
10765
+ orders.some((order) => !order ||
10766
+ typeof order.coin !== 'string' ||
10767
+ !order.coin.trim() ||
10768
+ !Number.isSafeInteger(order.oid) ||
10769
+ order.oid < 0 ||
10770
+ !knownTypes.includes(order.orderType) ||
10771
+ order.isTrigger !== isTPSLOrder(order.orderType) ||
10772
+ (order.isPositionTpsl && !order.isTrigger) ||
10773
+ typeof order.reduceOnly !== 'boolean')) {
10774
+ throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);
10775
+ }
10776
+ }
10777
+ return orders;
10778
+ }, await this.#getValidatedDexsStrict());
10779
+ if (failedDexs.length > 0 && !strict) {
10612
10780
  throw failedDexs[0].error;
10613
10781
  }
10614
10782
  const rawOrders = orderResults.flatMap((result) => result.data);
@@ -10626,7 +10794,7 @@ export class HyperLiquidProvider {
10626
10794
  positions = await this.#fetchPositionContext(infoClient, userAddress, protectionDexs);
10627
10795
  }
10628
10796
  catch (error) {
10629
- if (!params?.throwOnUnavailable) {
10797
+ if (!strict) {
10630
10798
  throw error;
10631
10799
  }
10632
10800
  // Cancellation discovery only needs the IDs and symbols.
@@ -10660,7 +10828,7 @@ export class HyperLiquidProvider {
10660
10828
  return orders;
10661
10829
  }
10662
10830
  catch (error) {
10663
- if (params?.throwOnUnavailable) {
10831
+ if (strict) {
10664
10832
  throw error;
10665
10833
  }
10666
10834
  this.#deps.debugLogger.log('Error getting currently open orders:', error);
@@ -11632,6 +11800,37 @@ export class HyperLiquidProvider {
11632
11800
  if (!basicValidation.isValid) {
11633
11801
  return basicValidation;
11634
11802
  }
11803
+ if (params.currentPrice !== undefined &&
11804
+ !Number.isFinite(params.currentPrice)) {
11805
+ return {
11806
+ isValid: false,
11807
+ error: PERPS_ERROR_CODES.ORDER_PRICE_POSITIVE,
11808
+ };
11809
+ }
11810
+ // Leverage 0 and NaN are falsy, so they must be refused explicitly
11811
+ // rather than skipping the range check below.
11812
+ if (params.leverage !== undefined &&
11813
+ !(Number.isFinite(params.leverage) && params.leverage >= 1)) {
11814
+ return {
11815
+ isValid: false,
11816
+ error: PERPS_ERROR_CODES.ORDER_LEVERAGE_INVALID,
11817
+ };
11818
+ }
11819
+ const coinSize = params.size ? parseFloat(params.size) : undefined;
11820
+ const usdSize = params.usdAmount
11821
+ ? parseFloat(params.usdAmount)
11822
+ : undefined;
11823
+ // USD sizing still consumes the caller's coin size as a reduce-only cap.
11824
+ if ((usdSize !== undefined &&
11825
+ !(Number.isFinite(usdSize) && usdSize >= 0)) ||
11826
+ (coinSize !== undefined &&
11827
+ !(Number.isFinite(coinSize) && coinSize >= 0)) ||
11828
+ (params.reduceOnly === true &&
11829
+ usdSize !== undefined &&
11830
+ usdSize > 0 &&
11831
+ coinSize === 0)) {
11832
+ return { isValid: false, error: PERPS_ERROR_CODES.ORDER_SIZE_POSITIVE };
11833
+ }
11635
11834
  if (params.marginMode !== undefined) {
11636
11835
  if (params.marginMode !== 'cross' && params.marginMode !== 'isolated') {
11637
11836
  return {
@@ -11711,6 +11910,12 @@ export class HyperLiquidProvider {
11711
11910
  minimumRequired: minimumOrderSize,
11712
11911
  });
11713
11912
  }
11913
+ if (!Number.isFinite(orderValueUSD)) {
11914
+ return {
11915
+ isValid: false,
11916
+ error: PERPS_ERROR_CODES.ORDER_MAX_VALUE_EXCEEDED,
11917
+ };
11918
+ }
11714
11919
  // Validate minimum order size
11715
11920
  if (orderValueUSD < minimumOrderSize) {
11716
11921
  return {
@@ -11729,7 +11934,7 @@ export class HyperLiquidProvider {
11729
11934
  }
11730
11935
  }
11731
11936
  // Asset-specific leverage validation
11732
- if (params.leverage && params.symbol) {
11937
+ if (params.leverage !== undefined) {
11733
11938
  try {
11734
11939
  const maxLeverage = await this.getMaxLeverage(params.symbol);
11735
11940
  if (params.leverage < 1 || params.leverage > maxLeverage) {
@@ -12158,9 +12363,9 @@ export class HyperLiquidProvider {
12158
12363
  else {
12159
12364
  await this.#assertNoKnownUnsupportedAccount(accountContext, 'DEX transfer');
12160
12365
  }
12161
- const exchangeClient = this.#clientService.getExchangeClient(allowStaleLifecycle
12162
- ? async () => await this.#assertRollbackAccountWritable(transferAccountContext)
12163
- : async () => await this.#assertNoKnownUnsupportedAccount(transferAccountContext, 'DEX transfer dispatch'));
12366
+ const exchangeClient = allowStaleLifecycle
12367
+ ? this.#getRollbackExchangeClient(transferAccountContext)
12368
+ : this.#getAccountGuardedExchangeClient(transferAccountContext, 'DEX transfer dispatch');
12164
12369
  const result = await exchangeClient.sendAsset({
12165
12370
  destination: userAddress,
12166
12371
  sourceDex: params.sourceDex,
@@ -12643,7 +12848,7 @@ export class HyperLiquidProvider {
12643
12848
  }
12644
12849
  const caughtError = ensureError(error, 'HyperLiquidProvider.prepareTradingWallet');
12645
12850
  const normalizedError = normalizeHyperLiquidError(caughtError);
12646
- if (caughtError.message === PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE) {
12851
+ if (normalizedError.errorCode === PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE) {
12647
12852
  this.#deps.debugLogger.log('[prepareTradingWallet] Provider replaced during preparation');
12648
12853
  }
12649
12854
  else if (caughtError.message === PERPS_ERROR_CODES.NO_ACCOUNT_SELECTED) {
@@ -13310,18 +13515,19 @@ export class HyperLiquidProvider {
13310
13515
  }
13311
13516
  }
13312
13517
  /**
13313
- * Escape hatch for agentic validation flows and test harnesses that drive
13314
- * HL mutations directly. NOT part of the PerpsProvider interface.
13315
- * Production code paths must go through the provider's own methods.
13518
+ * Provide fixture flows an SDK client fenced to the selected account.
13316
13519
  *
13317
- * @returns A promise resolving to the underlying HyperLiquid SDK
13318
- * ExchangeClient. Promise shape matches the existing agentic flows
13319
- * (hl-provision-fixture) that chain `.then` on the result.
13520
+ * @returns A promise resolving to a guarded HyperLiquid SDK ExchangeClient.
13320
13521
  */
13321
13522
  async getExchangeClient() {
13322
- // Initialized here so the client signs through this provider's wallet.
13523
+ const accountContext = await this.#captureAccountContext();
13323
13524
  await this.#ensureClientsInitialized();
13324
- return this.#clientService.getExchangeClient();
13525
+ await this.#assertAccountSupported(accountContext);
13526
+ const assertWritable = async () => await this.#assertNoKnownUnsupportedAccount(accountContext, 'SDK exchange write', { retryMissingSupport: true });
13527
+ return this.#clientService.getExchangeClient(assertWritable, {
13528
+ beforeSign: assertWritable,
13529
+ onExchangeResult: (outcome) => this.#recordUnsupportedAccountFromExchangeOutcome(outcome, accountContext),
13530
+ });
13325
13531
  }
13326
13532
  /**
13327
13533
  * Disconnect provider
@@ -13385,6 +13591,7 @@ export class HyperLiquidProvider {
13385
13591
  // generation above to discard any old response that resolves later.
13386
13592
  this.clearFeeCache();
13387
13593
  this.#accountSupportByContext.clear();
13594
+ this.#accountSupportExpiresAt.clear();
13388
13595
  this.#referralCheckCache.clear();
13389
13596
  this.#builderFeeCheckCache.clear();
13390
13597
  this.#builderFeeRefusals.clear();
@@ -13760,7 +13967,7 @@ export class HyperLiquidProvider {
13760
13967
  return;
13761
13968
  }
13762
13969
  if (accountContext &&
13763
- ensureError(error, 'HyperLiquidProvider.ensureReferralSet').message ===
13970
+ getHyperLiquidWriteGuardCode(error) ===
13764
13971
  PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE) {
13765
13972
  completeInFlight();
13766
13973
  throw error;
@@ -13865,12 +14072,11 @@ export class HyperLiquidProvider {
13865
14072
  */
13866
14073
  async #setReferralCode(accountContext) {
13867
14074
  try {
13868
- if (accountContext) {
13869
- await this.#assertNoKnownUnsupportedAccount(accountContext, 'Referral setup');
13870
- }
13871
- const exchangeClient = accountContext
13872
- ? this.#getAccountGuardedExchangeClient(accountContext, 'Referral setup dispatch')
13873
- : this.#clientService.getExchangeClient();
14075
+ // Without a captured action context, check the current account before
14076
+ // signing so the write is still fenced.
14077
+ const writeContext = accountContext ?? (await this.#assertAccountSupported());
14078
+ await this.#assertNoKnownUnsupportedAccount(writeContext, 'Referral setup');
14079
+ const exchangeClient = this.#getAccountGuardedExchangeClient(writeContext, 'Referral setup dispatch');
13874
14080
  const referralCode = this.#getReferralCode(this.#clientService.isTestnetMode());
13875
14081
  this.#deps.debugLogger.log('[setReferralCode] Setting referral code', {
13876
14082
  code: referralCode,
@@ -13890,7 +14096,9 @@ export class HyperLiquidProvider {
13890
14096
  }
13891
14097
  catch (error) {
13892
14098
  if (accountContext &&
13893
- this.#recordUnsupportedAccountFromError(error, accountContext)) {
14099
+ (getHyperLiquidWriteGuardCode(error) ===
14100
+ PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE ||
14101
+ this.#recordUnsupportedAccountFromError(error, accountContext))) {
13894
14102
  throw error;
13895
14103
  }
13896
14104
  // Retryable (a locked keyring, an unavailable agent, or one the venue