Skip to content

fix: support upgraded Hyperliquid TWAP orders(OK-59156) - #12849

Open
Minnzen wants to merge 19 commits into
release/v6.5.0from
codex/OK-59156-twap-hot-update
Open

fix: support upgraded Hyperliquid TWAP orders(OK-59156)#12849
Minnzen wants to merge 19 commits into
release/v6.5.0from
codex/OK-59156-twap-hot-update

Conversation

@Minnzen

@Minnzen Minnzen commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

OK-59156


Summary

  • Upgrade @nktkas/hyperliquid from 0.32.2 to 0.33.3 on the release/v6.5.0 hot-update branch.
  • Add TWAP trigger/stop details, seven-day duration, and the new waiting/stopped lifecycle states.
  • Remove fixed 30-second slice estimates and validate only the 100 USDC total notional minimum.

Intent & Context

OK-59156 needs to ship through the 6.5.0 hot-update path instead of waiting for the next normal release. SDK 0.33.3 is the first published version that provides the required TWAP details, state fields, and history statuses.

SDK Upgrade

  • Bump @nktkas/hyperliquid from 0.32.2 to 0.33.3 and update its transitive dependencies.
  • Adapt the ESM-only package and rews v4 WebSocket transport changes; serialize latency pings per client.
  • Adapt WebData2, outcome spot balances, nullable agent expiry, and user abstraction types.
  • Resolve the SDK's @noble/hashes ^2.2.0 dependency to the reviewed 2.2.0 release so the hot update does not float to a package below the seven-day supply-chain threshold.
  • Delete the broad 0.32.2 TWAP backport patch and obsolete rews 2 patch.
  • Keep one minimal 0.33.3 patch that changes only the SDK duration bound from 1440 to 10080 minutes; upstream 0.33.3 already owns all other TWAP schemas.

TWAP Changes

  • Add trigger price and buy upper/sell lower stop price fields to form, confirmation, signing, active-order, and history flows.
  • Clear a stop price when the side changes; validate trigger/stop boundaries against the same Hyperliquid wire-formatted prices in main and background runtimes.
  • Use the market-wide mark price for TWAP form and size calculations, with the account mark as a consistent fallback while either feed is loading.
  • Use mark price consistently for perp TWAP size conversion, slider sizing, confirmation, minimum notional, and background submission.
  • Add a 7d preset and accept durations up to 10080 minutes.
  • Display trigger/stop prices and support waitingForTrigger / stopped; pending orders do not advance elapsed time or progress before activation.
  • Remove child-order count/value estimates and the client-side 10 USDC slice check.

Risk Assessment

  • Risk Level: Medium-high because 0.33.x contains explicit breaking changes.
  • Affected Platforms: Extension / Mobile / Desktop / Web.
  • Runtime Scope: main owns form validation and display; bg owns SDK transport, signing, validation, and submission. On iOS, Android, and extension they run in isolated, version-locked JS runtimes and initialize independently; desktop and web are single-runtime.
  • Native Resources: no database schema, native code, or shared native singleton changes. The WebSocket transport remains bg-owned at the service boundary.
  • Known Follow-up: remove the 10080-minute patch when the SDK publishes the server's seven-day bound.

Test Plan

  • yarn install --immutable; verify the 0.33.3 patch applies.
  • Verify the patch applies to a pristine 0.33.3 package.
  • Run targeted SDK, TWAP, portfolio, and subscription Jest suites (5 suites / 54 tests).
  • Run TypeScript validation and yarn agent:check --profile commit.
  • Run the full repository yarn lint suite.
  • Run the minimum-release-age diff check (4 packages pass, 0 too young).
  • Build the Android native background Metro bundle with the ESM-only SDK.
  • Smoke-test a signed seven-day TWAP request with trigger and stop details.
  • Place immediate, trigger-above, and trigger-below TWAP orders on testnet.
  • Verify buy maximum/sell minimum price termination on testnet.
  • Verify a seven-day duration and waiting/stopped list states on testnet.

Comment thread packages/kit/src/states/jotai/contexts/hyperliquid/actions.ts Outdated
@sidmorizon

Copy link
Copy Markdown
Contributor

@codex review

@sidmorizon

Copy link
Copy Markdown
Contributor

@codex security review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1bd948b2d7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/shared/src/utils/hyperliquidTwapUtils.ts Outdated
@chatgpt-codex-connector

Copy link
Copy Markdown

Security review completed. No security issues were found in this pull request.

Reviewed commit: 1bd948b2d7

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

Comment thread packages/shared/src/utils/hyperliquidTwapUtils.ts
Comment thread packages/kit/src/views/Perp/components/OrderInfoPanel/List/PerpTwapList.tsx Outdated
Comment thread packages/shared/src/utils/hyperliquidTwapUtils.ts Outdated
@Minnzen

Minnzen commented Aug 12, 2026

Copy link
Copy Markdown
Contributor Author

已处理 automated review 的两个 blocking issue,并随 SDK 升级提交 83501874ee 推送:

  • P1:切换买卖方向时清空 twapStopPrice;main 确认、action 提交和 bg exchange 三层都按方向、mark price 与 trigger boundary 校验最高/最低价。
  • P2:perp TWAP 的表单金额换算、slider size、确认金额、100 USDC 校验和后台提交统一使用 mark price;spot 仍使用 mid price。

另外已补齐原 PR 缺失的真实 SDK 升级:@nktkas/hyperliquid 0.32.2 → 0.33.3,删除旧版 TWAP 大 patch 和 rews 2 patch,仅保留 0.33.3 的 7 天 duration 上限最小 patch。

验证:4 suites / 49 tests、TypeScript、commit profile、pristine patch check、Android background Metro bundle、7 天 TWAP 签名烟测均通过。该 review 是 issue comment,GitHub 没有单独的 resolve 状态;对应问题已经由本提交关闭。

@socket-security

socket-security Bot commented Aug 12, 2026

Copy link
Copy Markdown

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

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License
Updated@​nktkas/​hyperliquid@​0.32.2 ⏵ 0.33.310010010095 +1100

View full report

Comment thread packages/kit/src/states/jotai/contexts/hyperliquid/actions.ts
@Minnzen

Minnzen commented Aug 12, 2026

Copy link
Copy Markdown
Contributor Author

CI follow-up:

  • Supply Chain - Minimum Release Age initially failed because the SDK's @noble/hashes ^2.2.0 floated to 2.3.0, which was only 6 days old. Commit c3b440be49 adds a range-specific resolution to the reviewed 2.2.0 release. The exact diff check reports 4 packages OK / 0 too young.
  • Full lint then identified an obsolete IHyperliquidFrontendOrder[] assertion after the 0.33.3 type narrowing. Commit 49369a1d61 removes only that assertion.
  • Review identified that main validated raw TWAP boundary prices while bg validated wire-formatted prices. Commit ae79df4542 makes button, confirmation, main, and bg validation use the same Hyperliquid wire price before submission and adds the truncation-boundary regression case.

Latest HEAD ae79df4542 is green: 17 checks passed, 0 failed, 0 pending. All review threads are resolved. Local commit checks and the targeted TWAP test also pass; PR readiness is waiting only for the repository's required human approval.

@Minnzen Minnzen added the release-ready This PR should be included in the next release label Aug 12, 2026
@Minnzen Minnzen removed the release-ready This PR should be included in the next release label Aug 12, 2026
Comment thread packages/kit/src/views/Perp/components/TradingPanel/panels/PerpTradingForm.tsx Outdated
Comment thread packages/shared/src/utils/hyperliquidTwapUtils.ts Outdated
@originalix

originalix commented Aug 13, 2026

Copy link
Copy Markdown
Collaborator

Automated code review found blocking issues

@Minnzen

Reviewed commit a32f28fc4f50. This report always reflects the latest reviewed changes.

Review summary

This PR upgrades the Hyperliquid integration boundary to SDK 0.33.3 and threads the expanded TWAP contract through shared validation helpers, background exchange/subscription services, foreground Jotai state, and Perps UI surfaces. It adds trigger/stop-aware TWAP configuration, seven-day durations, and runtime-status display while keeping bg responsible for transport, account ingestion, and caches and main responsible for copied presentation state. The main correctness gap is that widened spot-balance responses without a token identifier are still filtered out before live atoms and cached display totals are written, so affected accounts can under-report holdings even though the snapshot path now marks itself degraded.

What needs attention: Confirm how positive spot balances without token identifiers should flow through background valuation, cached display totals, and degraded-state UX instead of disappearing.

Issues to address

  • P1 · Outcome spot balances disappear from live state and cached totals
    • Impact: Hyperliquid 0.33.3 can return positive spot-balance variants without a token field. The live ingest now filters those records before writing spotBalancesAtom and perpsSpotBalancesAtom, and snapshot assembly repeats the filtering before spotTotalUsd is derived. That means an account can still hold positive value while the balances UI and persisted display snapshot publish a smaller total without any live degraded-state guard.
    • Suggested action: Preserve the widened balance variant through the live state/cache boundary, or explicitly mark the result degraded and avoid writing a misleading total until that balance can be represented safely.

Validation gaps

  • Targeted Jest reruns were blocked in this workspace because Yarn could not find the node_modules state file.
  • The upgraded websocket transport path uses private SDK internals and was not exercised against a live installed runtime here.
  • No runtime capture was available for an account holding the widened tokenless spot-balance variant.

Comment thread patches/@nktkas+rews+2.0.2.patch Outdated
Comment thread packages/kit/src/views/Perp/components/TradingPanel/panels/PerpTradingForm.tsx Outdated
Comment thread packages/kit/src/views/Perp/components/TradingPanel/panels/PerpTradingForm.tsx Outdated

@originalix originalix left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@Minnzen

Automated code review found blocking issues

Reviewed commit 96405115bf62.

  • P1 · TWAP confirmation still shows pre-normalized trigger/stop prices
  • P1 · TWAP submit guards still ignore the new mark-price fallback

View the full review report

@Minnzen

Minnzen commented Aug 13, 2026

Copy link
Copy Markdown
Contributor Author

已处理 automated review 的两个 P1,随 commit 2bc551da51 推送:

  • P1(确认页价格未归一化):OrderConfirmModal 的 TWAP trigger/stop 预览改为复用提交路径同一个 formatTwapPriceForOrder() 的输出,用户确认的价格即实际发出的 wire 价格。
  • P1(提交守卫缺 mark-price fallback):新增 useTwapReferencePrice() 共享 hook,统一按 activeAssetCtx.ctx.markPrice ?? activeAssetData.markPx(spot 用 mid)推导参考价,PerpTradingFormTradingButtonGroupuseOrderConfirm 三处复用;submitOrder action 同链路 fallback。冷启动/重连期间表单、CTA 校验与提交不再互相矛盾。

顺带:hook 底层用新增的 perpsActiveAssetCtxMarkPriceAtom 计算 selector(对齐现有 midPrice selector 模式),三个组件不再订阅整个 ctx 快照,缓解每 tick 重绘问题。已回复并 resolve sidmorizon 的 4 条线程(其中 rews patch 与 transport.close 两条经查证 SDK 源码后说明不需要改动)。

验证:hyperliquidTwapUtils / useTradingCalculationsForSide / useTwapReferencePrice(新增 4 例)/ ServiceHyperLiquid 共 15 suites 105 tests 通过;yarn agent:check --profile commit 通过。

@originalix originalix left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@Minnzen

Automated code review found blocking issues

Reviewed commit 2bc551da512a.

  • P1 · Outcome spot balances disappear from UI and cached totals
  • P2 · Plain TWAP orders now always send the optional details wrapper

View the full review report

@Minnzen

Minnzen commented Aug 13, 2026

Copy link
Copy Markdown
Contributor Author

针对 automated review 最新一轮(reviewed 2bc551da512a),随 commit b6becfd4a0 推送:

P2(plain TWAP 恒发 details wrapper)— 已修复。 details 改为仅在配置了 trigger/stop 时构造,否则整个省略。已用 SDK 的 parse + canonicalize 实测:省略 key 时 canonical action 不含 details(与 0.33 之前生产验证过的 wire 形状一致);此前的 {t: null, s: null} 确实会原样上 wire。注意不能传 details: undefined(canonicalize 会保留该 key),因此用条件展开。

P1(outcome spot 余额被过滤)— 说明后维持现状,建议 follow-up。 分析如下:

  1. Portfolio 聚合路径(hyperliquidPortfolioUtils.ts aggregate 内)已经对被过滤且 total > 0 的 outcome 条目置 degraded = true,并非静默丢弃;spotHasPositiveBalance 也未过滤 outcome 条目。
  2. App 全链路没有 outcome market 支持:无订阅、无价格源(outcome 代币不在 spot universe/allMids 内)。若把它们放进 calculateSpotBalancesTotalUsd,会永久落入 missingPriceCoins 分支,导致 spot 总额长期卡在 fallback/partial 状态——比排除更糟。
  3. "degraded-but-visible" 需要决定 +N/oN 条目的展示文案与估值语义(entryNtl 是入场名义价值,不是现值,结算后可能偏差极大),且 ISpotBalance 契约(token: number)被 mappings/转账等下游依赖——属于 feature 级改动,不适合热更分支。
    建议为 outcome-token 展示单开 ticket 在常规版本处理。

另外修复了 CI lint 的两个格式错误(useTwapReferencePrice.ts import 分组)。定向测试:ServiceHyperLiquid 12 suites / 86 tests 通过,yarn agent:check --profile commit 通过。

@originalix originalix left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@Minnzen

Automated code review found blocking issues

Reviewed commit b6becfd4a04a.

  • P1 · Outcome spot balances disappear from live state and cached totals

View the full review report

@Minnzen

Minnzen commented Aug 13, 2026

Copy link
Copy Markdown
Contributor Author

回应 automated reviewb6becfd4a04a 的复审(仅剩 P1 outcome 余额一项):

产品结论不变——热更分支不引入 outcome 代币展示(无价格源、无 UI 语义、ISpotBalance 契约下游依赖广),完整理由见上一条回复

针对本轮指出的"WS 路径完全静默",随 commit 已推送最小改善:updateSpotBalances 在过滤掉正余额 outcome 条目时输出 warn 日志(与该文件现有日志风格一致),使遗漏在日志/排障中可见。Portfolio 快照路径维持既有 degraded = true 标记。outcome 代币的可见化处理建议单开 ticket 在常规版本评估。

@originalix originalix left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@Minnzen

Automated code review found blocking issues

Reviewed commit 764fbe781ba4.

  • P1 · Outcome spot balances disappear from live state and cached totals

View the full review report

@originalix originalix left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@Minnzen

Automated code review found blocking issues

Reviewed commit b11d55b4c6bf.

  • P1 · Outcome spot balances disappear from live state and cached totals

View the full review report

Comment thread packages/kit/src/views/Perp/hooks/useTradingCalculationsForSide.ts

@originalix originalix left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@Minnzen

Automated code review found blocking issues

Reviewed commit a32f28fc4f50.

  • P1 · Outcome spot balances disappear from live state and cached totals

View the full review report

@sidmorizon

Copy link
Copy Markdown
Contributor

@cursoragent review

@cursor

cursor Bot commented Aug 18, 2026

Copy link
Copy Markdown

Taking a look!

Open in Web Open in Cursor 

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.

3 participants