Skip to content

feat(perps): add e2e validation scripts for HyperLiquid API testing#8893

Open
abretonc7s wants to merge 11 commits into
mainfrom
feat/perps-e2e-validation
Open

feat(perps): add e2e validation scripts for HyperLiquid API testing#8893
abretonc7s wants to merge 11 commits into
mainfrom
feat/perps-e2e-validation

Conversation

@abretonc7s
Copy link
Copy Markdown
Contributor

@abretonc7s abretonc7s commented May 25, 2026

Explanation

The perps controller (migrated in #8871, tests in #8840) currently has 58 unit test files — all mocked. Zero coverage against real HyperLiquid APIs. This PR adds standalone e2e validation scripts that call the live HyperLiquid API.

Read-only scenarios (no wallet needed)

  1. market-data — meta, metaAndAssetCtxs, allMids, spotMeta structure and sanity
  2. account-state — clearinghouseState and frontendOpenOrders response shapes
  3. order-validation — constants, slippage config, error codes against live market metadata
  4. subscription-stream — real allMids WebSocket stream, price update structure
  5. error-codes — PERPS_ERROR_CODES structure and API edge-case behavior

Trading scenarios (testnet wallet, parameterized)

  1. trading-lifecycle — open position → verify → set TP/SL → close → verify flat
  2. limit-orders — place limit → verify resting → cancel → verify removed

All trading scripts accept CLI params (--coin, --size, --leverage, --side, --tp-pct, --sl-pct, --offset-pct) so recipes can invoke the same script with different scenarios.

Each script uses createStandaloneInfoClient (read-only) or ExchangeClient + viem privateKeyToAccount (trading), outputs structured JSON, and exits 0/1.

See e2e/README.md for full usage.

References

Checklist

  • I've updated the test suite for new or updated code as appropriate
  • I've updated documentation (JSDoc, Markdown, etc.) for new or updated code as appropriate
  • I've communicated my changes to consumers by updating changelogs for packages I've changed
  • I've introduced breaking changes in this PR and have prepared draft pull requests for clients and consumer packages to resolve them

Note

Low Risk
Changes are isolated to new e2e scripts, docs, and dev dependencies; production controller code is not modified. Trading scripts only run with an explicit testnet private key env var.

Overview
Adds a new packages/perps-controller/e2e suite of standalone tsx scripts that hit live HyperLiquid (no mocks), with shared E2ERunner JSON pass/fail output and e2e/README.md usage docs.

Read-only scripts use createStandaloneInfoClient for market data, account shapes, order-validation constants vs live meta, WebSocket allMids, and error-code/API edge checks. Trading scripts use ExchangeClient + viem privateKeyToAccount via HL_E2E_PRIVATE_KEY (testnet by default), with CLI flags for trading-lifecycle (open → optional TP/SL → close) and limit-orders (rest → cancel).

Build/tooling: tsconfig.json includes ./e2e, viem is added as a devDependency (lockfile bumps viem/ox/ws).

Reviewed by Cursor Bugbot for commit 8ceeb88. Bugbot is set up for automated code reviews on this repo. Configure here.

@abretonc7s abretonc7s requested a review from a team as a code owner May 25, 2026 23:47
@abretonc7s abretonc7s requested a review from a team as a code owner May 26, 2026 00:29
@socket-security
Copy link
Copy Markdown

socket-security Bot commented May 26, 2026

Review the following changes in direct dependencies. Learn more about Socket for GitHub.

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License
Updatedviem@​2.48.4 ⏵ 2.50.498 +1100100 +198100

View full report

@socket-security
Copy link
Copy Markdown

socket-security Bot commented May 26, 2026

Warning

MetaMask internal reviewing guidelines:

  • Do not ignore-all
  • Each alert has instructions on how to review if you don't know what it means. If lost, ask your Security Liaison or the supply-chain group
  • Copy-paste ignore lines for specific packages or a group of one kind with a note on what research you did to deem it safe.
    @SocketSecurity ignore npm/PACKAGE@VERSION
Action Severity Alert  (click "▶" to expand/collapse)
Warn Low
Potential code anomaly (AI signal): npm ox is 100.0% likely to have a medium risk anomaly

Notes: This dependency is a cross-platform worker harness that executes embedded WebAssembly to perform a “salt mining” computation and returns progress/results to the caller via message passing. In this file, there is no clear evidence of classic malware behaviors such as network exfiltration, credential theft, or filesystem/system sabotage. The most notable supply-chain/security concerns are dynamic code execution patterns (Node Worker with eval:true and browser Blob URL worker scripts) and the potential for CPU-intensive abuse (computational mining-like workload) if invoked in an unauthorized context or with adversarial parameters. Overall: moderate security risk driven by execution surface and availability impact rather than direct data-stealing.

Confidence: 1.00

Severity: 0.60

From: ?npm/viem@2.50.4npm/ox@0.14.22

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/ox@0.14.22. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm ox is 100.0% likely to have a medium risk anomaly

Notes: This module implements parallel WebAssembly computation using Node worker_threads and browser Web Workers, including dynamic worker script execution (Node eval:true and browser Blob URL). It communicates only via postMessage and does not show network exfiltration, credential theft, or persistence within this snippet. The main risks are supply-chain/execution boundary concerns from dynamic worker code and potential CPU/DoS impact if the mining parameters are attacker-influenced. Overall: likely intended for compute work, but should be reviewed and guarded with strict input controls and hardened worker creation.

Confidence: 1.00

Severity: 0.60

From: ?npm/viem@2.50.4npm/ox@0.14.22

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/ox@0.14.22. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm ox is 100.0% likely to have a medium risk anomaly

Notes: This fragment is primarily a CPU-intensive proof-of-work/salt-mining implementation using worker-thread parallelism plus an async fallback. It includes input validation, structured error propagation, and abort handling, and it does not show classic malware behaviors (no network/file/process/persistence or dynamic execution in the snippet). The dominant security concern is potential resource-exhaustion/DoS if untrusted callers can control workerCount/count/chunkSize, and secondary concern is leakage of progress/rate metrics into application callbacks/logging. Overall: likely intended PoW functionality but potentially abuse-prone in the wrong threat model.

Confidence: 1.00

Severity: 0.60

From: ?npm/viem@2.50.4npm/ox@0.14.22

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/ox@0.14.22. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm ox is 100.0% likely to have a medium risk anomaly

Notes: This dependency is a worker-based “salt mining”/proof-of-work compute engine that loads an embedded WebAssembly payload and runs a CPU-intensive loop in Node worker_threads or browser Web Workers, communicating progress and results via postMessage. There is no direct evidence in this fragment of network exfiltration, credential access, persistence, or system modification. The main security concerns are (1) dynamic worker code execution (Node worker eval:true and browser Blob URL execution) and (2) cryptomining-like resource consumption that can be abused for CPU exhaustion. The embedded WASM module itself should be reviewed to confirm it contains only the expected computation and no hidden side effects.

Confidence: 1.00

Severity: 0.60

From: ?npm/viem@2.50.4npm/ox@0.14.22

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/ox@0.14.22. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm viem is 100.0% likely to have a medium risk anomaly

Notes: The code implements a cross-chain deposit flow with proper validations, artifact reads, and on-chain interactions. There is no evidence of hidden backdoors, data exfiltration, or malware. The main security considerations relate to token approval logic and correct configuration of flags to avoid granting excessive allowances. Overall, the module appears legitimate for a bridge deposit flow, with moderate risk primarily around configuration of approvals and correct handling of gas/fees.

Confidence: 1.00

Severity: 0.60

From: packages/perps-controller/package.jsonnpm/viem@2.50.4

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/viem@2.50.4. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm ws is 100.0% likely to have a medium risk anomaly

Notes: The code implements a standard EventTarget-like mixin for wrapping event listeners and dispatching events to user callbacks. There are no suspicious patterns such as dynamic code execution, hardcoded secrets, or network activity. The risk is contingent on what the consumer does inside their handlers; the snippet itself does not introduce malware or data leakage mechanisms beyond normal event dispatch. Overall security risk is low in isolation.

Confidence: 1.00

Severity: 0.60

From: ?npm/@myx-trade/sdk@0.1.265npm/viem@2.50.4npm/jest-environment-jsdom@29.7.0npm/ws@8.20.1

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/ws@8.20.1. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Low
Potential code anomaly (AI signal): npm ws is 100.0% likely to have a medium risk anomaly

Notes: The analyzed code segment represents a robust, standards-aligned WebSocket receiver. It correctly handles frame parsing, masking, fragmentation, and optional compression via PerMessageDeflate, with appropriate validation and error signaling. There is no evidence of malicious intent or backdoors within this module; the security posture is solid for a protocol parser, with typical risks mitigated by payload size checks and UTF-8 validation. Overall, the code is appropriate for integration in a WebSocket client/server library, with moderate security risk primarily tied to how downstream consumers handle emitted data and potential resource usage under edge cases.

Confidence: 1.00

Severity: 0.60

From: ?npm/@myx-trade/sdk@0.1.265npm/viem@2.50.4npm/jest-environment-jsdom@29.7.0npm/ws@8.20.1

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/ws@8.20.1. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

View full report

Comment thread packages/perps-controller/e2e/trading-lifecycle.ts
Comment thread packages/perps-controller/e2e/trading-lifecycle.ts Outdated
…efore close

- Change TP/SL order grouping from 'na' to 'positionTpsl' so HyperLiquid
  properly associates trigger orders with the open position.
- Re-fetch mid price immediately before computing close order price to avoid
  stale price from script start causing IOC close to not fill.
@abretonc7s
Copy link
Copy Markdown
Contributor Author

Automated pr-complete run — #8893

Metric Value
Run 6051ea71
Duration ?
Model claude/opus
Nudges 0
Worker report

PR #8893 — Comments Report

PR Comments/Checks Addressed

cursor[bot] Review Comments (2 issues)

1. TP/SL orders use wrong grouping value (Medium Severity)

  • File: packages/perps-controller/e2e/trading-lifecycle.ts:213
  • Issue: TP/SL orders used grouping: 'na' instead of grouping: 'positionTpsl'. HyperLiquid requires positionTpsl grouping to associate trigger orders with an existing position.
  • Fix: Changed grouping: 'na'grouping: 'positionTpsl' on the TP/SL order call.

2. Close order uses stale price from script start (Medium Severity)

  • File: packages/perps-controller/e2e/trading-lifecycle.ts:225
  • Issue: Close order derived slippage price from midPrice fetched at script start (step 1), but the close happens much later (step 6). If the market moves >3% during the window, the IOC close order won't fill.
  • Fix: Added a fresh info.allMids() call immediately before computing closePrice.

Bot Comments (not actionable)

  • socket-security[bot]: Dependency audit — informational only (viem update), no action needed.

CI Checks

  • Check changelog: FAILURE — pre-existing; e2e scripts in e2e/ do not require changelog entries (not published).
  • All lint, build, test, and security checks: SUCCESS.

Files Changed

File Change
packages/perps-controller/e2e/trading-lifecycle.ts Fixed TP/SL grouping (napositionTpsl); re-fetch mid price before close order

Downstream Compatibility Assessment

No impact. Changes are limited to e2e/trading-lifecycle.ts, which is an e2e test script outside the published src/ directory. No public API changes, no type changes, no exports affected. Mobile and Extension clients are not impacted.

Validation Results

  • Unit tests: 58 suites, 1725 passed, 40 skipped — all green.
  • Build: Pre-existing TS6305 errors from unbuilt dependency outputs (not related to this change).
  • Recipe: No inherited recipe artifact present; skipped.

@abretonc7s abretonc7s enabled auto-merge May 27, 2026 03:47
Copy link
Copy Markdown

@cursor cursor Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 8ceeb88. Configure here.

runner.assertGt(`${params.coin} mid price > 0`, midPrice, 0);

const isBuy = params.side === 'long';
const limitPrice = midPrice * (1 + params.offsetPct / 100);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Default offset causes immediate fill for short orders

Medium Severity

The limitPrice calculation applies offsetPct uniformly regardless of order side: midPrice * (1 + offsetPct / 100). The default offsetPct is -2, which places the price 2% below market. For a buy (long) order this correctly rests on the book, but for a sell (short) order, placing 2% below market causes immediate fill against existing bids. Running --side short without explicitly setting --offset-pct to a positive value produces an order that fills instantly, failing the 'order is resting' assertion in a confusing way.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 8ceeb88. Configure here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant