Skip to content

feat(perps): support explicit HyperLiquid margin mode - #10136

Merged
abretonc7s merged 6 commits into
mainfrom
TAT-3519-feat-cross-margin-controller
Sep 9, 2026
Merged

abretonc7s merged 6 commits into
mainfrom
TAT-3519-feat-cross-margin-controller

Conversation

@abretonc7s

@abretonc7s abretonc7s commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Explanation

HyperLiquid order preparation currently always sends isCross: false when applying leverage. Add optional OrderParams.marginMode: 'cross' | 'isolated' and pass the explicit mode to standard and strategy order preparation. Callers that omit mode retain existing isolated behavior.

Explicit requests require integer leverage and are checked before signing. Cross is rejected on isolated-only/restricted markets and HIP-3 markets while their collateral-transfer path assumes isolated margin. Fresh position/order reads reject changing an occupied asset's mode; matching-mode orders remain allowed. Lighter rejects explicit mode until it supports this contract. MarketInfo.marginMode preserves venue capability and new error codes let clients explain rejections.

This is the controller prerequisite for a bounded Mobile position-display change, not completion of the TAT-3519 epic. Pro selection, account health/balance semantics, account-wide refresh, analytics and rollout remain follow-ups. No package version is preselected; a release containing this PR must be published before Mobile consumes it.

Validation: full Core build and scoped ESLint passed; 692 tests passed across HyperLiquid advanced/strategy, Lighter and adapter suites, including coverage for explicit Cross, explicit isolated, omitted mode and rejection before signatures across trigger/TWAP/scale/chase orders. Scoped formatting and changelog validation passed. Standalone test-inclusive typecheck fails on project-reference/declaration resolution; it is not counted as passing. A fresh yalc build was linked into Mobile; its typecheck and 169 affected tests passed. On selected HyperLiquid testnet dev1, the Mobile controller opened real Cross ETH long/null and short/numeric liquidation positions. Pro/Lite recipes passed, including a recorded 37/37-action run. Both test positions were closed and ETH restored to isolated 3x. No mainnet mutation occurred.

Independent cross-review completed after three rounds on c99b20455291ff3247ff08b3cefd9fa6d0440fc4: both reviewers approve with no remaining actionable nits. No new runtime validation bypass or omitted-mode regression was found. Keep this PR draft for operator review; release publication and consumer adoption remain separate steps.

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

Breaking type change: adding ORDER_MARGIN_MODE_INVALID, ORDER_MARGIN_MODE_UNSUPPORTED, ORDER_MARGIN_MODE_POSITION_OPEN, and ORDER_MARGIN_MODE_ORDER_OPEN expands PerpsErrorCode. Mobile and Extension consumers using exhaustive error maps must add all four entries when upgrading. The dependent Mobile draft includes these mappings; any other exhaustive consumers must migrate during release adoption. Runtime behavior for callers that omit marginMode is preserved. The checkbox remains unchecked because consumer migration beyond the prepared Mobile draft has not been completed.


Note

Medium Risk
Changes HyperLiquid order preparation (leverage/margin mode) and adds venue-dependent validation on the signing path, plus a breaking expansion of PerpsErrorCode for consumers with exhaustive error maps.

Overview
Adds optional OrderParams.marginMode ('cross' | 'isolated', requires integer leverage) and exports MarginMode. Callers that omit marginMode keep prior isolated-leverage behavior; explicit requests run new pre-sign checks on HyperLiquid.

HyperLiquid forwards the chosen mode to updateLeverage (isCross) for standard and strategy orders, exposes venue restriction on MarketInfo.marginMode, and validates unsupported Cross (isolated-only / restricted markets, HIP-3), open positions, resting orders, and active native TWAP schedules (including pre-first-fill) via fresh venue reads—failing closed when those reads fail.

Breaking: four new PerpsErrorCode values for invalid/unsupported margin mode and blocked mode changes; exhaustive client error maps must add them. Lighter rejects any explicit marginMode with ORDER_MARGIN_MODE_UNSUPPORTED in validate and place paths.

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

@abretonc7s abretonc7s self-assigned this Sep 8, 2026
@abretonc7s
abretonc7s marked this pull request as ready for review September 8, 2026 07:39
@abretonc7s
abretonc7s requested review from a team as code owners September 8, 2026 07:39
@abretonc7s
abretonc7s enabled auto-merge September 8, 2026 07:39

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

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 c99b204. Configure here.

@Bigshmow Bigshmow left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

@abretonc7s
abretonc7s added this pull request to the merge queue Sep 9, 2026
Merged via the queue into main with commit 30e02f2 Sep 9, 2026
46 checks passed
@abretonc7s
abretonc7s deleted the TAT-3519-feat-cross-margin-controller branch September 9, 2026 00:49
@abretonc7s abretonc7s mentioned this pull request Sep 9, 2026
3 of 4 tasks
pull Bot pushed a commit to Reality2byte/core that referenced this pull request Sep 9, 2026
## Explanation

Publishes `@metamask/perps-controller@16.2.0`. No other workspace
packages are version-bumped.

This is a minor, not a major. Expanding `PerpsErrorCode` with the
margin-mode codes is additive; clients should handle unknown codes in a
catch-all rather than an exhaustive map. Optional
`OrderParams.marginMode` and `MarketInfo.marginMode` keep existing
callers on the isolated-leverage path.

Also includes the HyperLiquid TWAP terminal-record fix and Lighter
account/market/log fixes.

## References

- MetaMask#10136
- MetaMask#10122
- MetaMask#10119
- MetaMask#10110

## Checklist

- [x] I've updated the test suite for new or updated code as appropriate
- [x] I've updated documentation (JSDoc, Markdown, etc.) for new or
updated code as appropriate
- [x] I've communicated my changes to consumers by [updating changelogs
for packages I've
changed](https://github.com/MetaMask/core/tree/main/docs/processes/updating-changelogs.md)
- [ ] I've introduced [breaking
changes](https://github.com/MetaMask/core/tree/main/docs/processes/breaking-changes.md)
in this PR and have prepared draft pull requests for clients and
consumer packages to resolve them

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> This PR only bumps versions and edits changelog/README/JSDoc; trading
behavior ships in the referenced feature PRs, not in this diff.
> 
> **Overview**
> Cuts **release 1245.0.0**, publishing
**`@metamask/perps-controller@16.2.0`** (monorepo root version bump
only; no other workspace packages change).
> 
> The diff is mostly release bookkeeping: **`package.json` versions**, a
new **`[16.2.0]` changelog** section (margin-mode error codes and
HyperLiquid `marginMode` API, TWAP terminal-record fix, Lighter
account/market/logging fixes — already merged via linked PRs), and
**consumer guidance** updates.
> 
> **Policy clarification:** new **`PerpsErrorCode` values (including the
four margin-mode codes) are documented as additive minors**, not
breaking — the changelog drops the prior **BREAKING** wording.
**`README.md`** adds an **Error codes** section and
**`perpsErrorCodes.ts`** JSDoc now tells clients to use a **catch-all**
for unknown codes instead of an exhaustive `Record<PerpsErrorCode, …>`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
add8f2d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
pull Bot pushed a commit to Reality2byte/metamask-mobile that referenced this pull request Sep 10, 2026
<!--
Please submit this PR as a draft initially.

Do not mark it as "Ready for review" until this PR meets the canonical
Definition of Ready For Review in `docs/readme/ready-for-review.md`.

In short: the template must be materially complete (not just section
titles
present), all status checks must be currently passing, and the only
expected
follow-up commits must be reviewer-driven.
-->
<!--
mms-check directive vocabulary — read by
.github/scripts/shared/pr-template-checks.ts
at module load to build the validation plan. Directives are invisible in
rendered
markdown and must NOT be removed or edited without updating the
validator registry.

  type=text           Section must contain non-placeholder prose.
  type=changelog      Section must have a valid CHANGELOG entry: line.
type=issue-link Section must have a Fixes:/Closes:/Refs: line with a
value.
type=manual-testing Section must have real testing steps or an explicit
N/A.
type=screenshot Section must have evidence (image/URL) or an explicit
N/A.
type=checklist Section must have all checkboxes consciously checked.
required=true|false Whether a missing/invalid section runs the validator
at all.
blocking=true|false Whether a failure of this check fails the CI
workflow.
Default: false — failures are shown as warnings in the sticky
                      comment but do not block the PR.

Sections without a directive are checked for structural presence only.
-->

## **Description**

<!-- mms-check: type=text required=true -->

Bumps `@metamask/perps-controller` from 16.1.0 to 16.2.0 (Core release
1245.0.0).

16.2.0 adds optional HyperLiquid `OrderParams.marginMode`, four
`ORDER_MARGIN_MODE_*` error codes, a TWAP terminal-record fix, and
Lighter account/market fixes. Callers that omit `marginMode` stay on
isolated.

Mobile maps `PerpsErrorCode` exhaustively, so this PR adds the four new
codes to `ERROR_CODE_TO_I18N_KEY`, English copy, and
`translatePerpsErrorCoverage.test.ts`. It does not ship Pro cross-margin
UI (that is MetaMask#35831).

### Recipe validation

Verdict: pass

Proved:
- AC1: lockfile resolves `@metamask/perps-controller@16.2.0`
- AC2: bundled `perps.smoke` opened Perps Testnet, read positions/orders
(empty, no mutation), and `perps-market-list` was present

Gaps:
- iOS Runway only (`mm-1`). Android not run.
- First recipe run failed on Login/CDP after restart; relaunch +
fixtures recovered. Passing run is the proof.

## **Changelog**

<!-- mms-check: type=changelog required=true blocking=true -->

CHANGELOG entry: Added Perps error messages for invalid, unsupported,
and occupied-position/order margin modes

## **Related issues**

<!-- mms-check: type=issue-link required=true -->

Refs: MetaMask/core#10136
Jira: https://consensyssoftware.atlassian.net/browse/TAT-3519

## **Manual testing steps**

<!-- mms-check: type=manual-testing required=true -->

```gherkin
Feature: Perps controller 16.2.0 smoke

  Scenario: Perps market list still loads after the bump
    Given a Runway iOS build on mm-1 with the wallet fixture unlocked
    And @metamask/perps-controller is 16.2.0

    When the bundled perps.smoke recipe runs
    Then the wallet unlocks if needed
    And the Perps market list is present
    And live positions and orders can be read without placing or cancelling anything
```

Platform: iOS simulator `mm-1`. Build: Runway expo-dev-client. Fixture:
existing 4-entry wallet. Perps testnet enabled.

## **Screenshots/Recordings**

<table>
<tr><td colspan="2"><strong>Recipe visual
evidence</strong><br/>Screenshots are grouped for quick reviewer
comparison.</td></tr>
<tr>
<td align="center" width="50%"><strong>Perps Testnet home after 16.2.0
smoke</strong><br/><img
src="https://raw.githubusercontent.com/abretonc7s/mm-mobile-artifacts/main/evidence/dev-update-perps-controller-smoke-2221/01-ui-screenshot-screenshot.png"
alt="Perps Testnet home after 16.2.0 smoke" width="400" /></td>
<td width="50%"></td>
</tr>
</table>

### **Before**

N/A. Dependency bump, no UI redesign.

### **After**

Perps Testnet home after the 16.2.0 smoke (recipe-backed).

## **Pre-merge author checklist**

<!-- mms-check: type=checklist required=true -->

- [x] I've followed [MetaMask Contributor
Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask Mobile
Coding
Standards](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/CODING_GUIDELINES.md).
- [x] I've completed the PR template to the best of my ability
- [x] I've included tests if applicable
- [x] I've documented my code using [JSDoc](https://jsdoc.app/) format
if applicable
- [x] I've applied the right labels on the PR (see [labeling
guidelines](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/LABELING_GUIDELINES.md)).
Not required for external contributors.

#### Performance checks (if applicable)

- [x] I've tested on Android
  - Considered; iOS Runway only for this bump
- [x] I've tested with a power user scenario
  - Considered; not applicable (fixture wallet, non-mutating smoke)
- [x] I've instrumented key operations with Sentry traces for production
performance metrics
  - Considered; not applicable (no new product operations)

For performance guidelines and tooling, see the [Performance
Guide](https://consensyssoftware.atlassian.net/wiki/spaces/TL1/pages/400085549067/Performance+Guide+for+Engineers).

## **Pre-merge reviewer checklist**

- [ ] I've manually tested the PR (e.g. pull and build branch, run the
app, test code being changed).
- [ ] I confirm that this PR addresses all acceptance criteria described
in the ticket it closes and includes the necessary testing evidence such
as recordings and or screenshots.
pull Bot pushed a commit to Reality2byte/metamask-mobile that referenced this pull request Sep 16, 2026
<!--
Please submit this PR as a draft initially.

Do not mark it as "Ready for review" until this PR meets the canonical
Definition of Ready For Review in `docs/readme/ready-for-review.md`.

In short: the template must be materially complete (not just section
titles
present), all status checks must be currently passing, and the only
expected
follow-up commits must be reviewer-driven.
-->
<!--
mms-check directive vocabulary — read by
.github/scripts/shared/pr-template-checks.ts
at module load to build the validation plan. Directives are invisible in
rendered
markdown and must NOT be removed or edited without updating the
validator registry.

  type=text           Section must contain non-placeholder prose.
  type=changelog      Section must have a valid CHANGELOG entry: line.
type=issue-link Section must have a Fixes:/Closes:/Refs: line with a
value.
type=manual-testing Section must have real testing steps or an explicit
N/A.
type=screenshot Section must have evidence (image/URL) or an explicit
N/A.
type=checklist Section must have all checkboxes consciously checked.
required=true|false Whether a missing/invalid section runs the validator
at all.
blocking=true|false Whether a failure of this check fails the CI
workflow.
Default: false — failures are shown as warnings in the sticky
                      comment but do not block the PR.

Sections without a directive are checked for structural presence only.
-->

## **Description**

Existing Cross positions now show an explicit "No liquidation price"
state when Hyperliquid supplies null, and a shared-collateral
explanation for both null and numeric prices. Lite and compact position
cards gain a Cross badge, while detailed cards label collateral
"Position margin used" and suppress margin editing.

### What changes on screen

Perpetual positions can use **isolated** margin (collateral committed to
that one position) or **cross** margin (collateral shared across all
cross positions). Before this PR, existing Cross positions were rendered
with isolated-position assumptions, which produced two concrete
problems:

1. **A null liquidation price rendered as an empty or misleading
value.** Hyperliquid legitimately returns `liquidationPrice: null` for a
cross position when, at the current account value, no liquidation price
exists. That is meaningful information, not missing data.
2. **Margin appeared editable on positions where editing does not
apply.** Add/remove margin is an isolated-position operation; a cross
position's collateral is the shared account balance.

This PR makes both explicit:

| | Isolated position | Cross position (this PR) |
|---|---|---|
| Collateral label | "Margin" | **"Position margin used"** with a
`Cross` badge |
| Margin edit control | Tappable, opens add/remove margin | **Absent** —
`marginPress = isCross ? undefined : onMarginPress` |
| Liquidation, venue value present | Price | Price **+ ⓘ** → "Cross
liquidation price" explanation |
| Liquidation, venue value null | n/a | **"No liquidation price" + ⓘ** →
explanation of why |

Both explanations state that a liquidation can affect the **entire cross
balance**, which is the risk that distinguishes cross from isolated.

**Scope note:** this is the *existing-position display* slice of
TAT-3519. The Pro margin-mode picker stays disabled, so there is no
user-facing Cross/isolated selector in this PR — the difference shipped
here is how an already-open Cross position reads. Mixed-book grouping,
compact rows and privacy masking are covered by component tests.

[Core PR MetaMask#10136](MetaMask/core#10136) adds
explicit `OrderParams.marginMode`, validates venue capability and
existing positions/orders before signing, and passes Cross to
`updateLeverage`. **That dependency is now resolved:** it merged and
shipped in `@metamask/perps-controller@16.2.0`, `main` picked up the
bump, and Mobile typecheck is clean against the released package — no
yalc or file dependency is committed.

<!-- mms-check: type=text required=true -->

<!--
Write a short description of the changes included in this pull request,
also include relevant motivation and context. Have in mind the following
questions:
1. What is the reason for the change?
2. What is the improvement/solution?
-->

### Feature flag

Gated behind **`perpsCrossMarginEnabled`** (LaunchDarkly:
`perps-cross-margin-enabled`), version-gated
via `validatedVersionGatedFeatureFlag` and **defaulting to `false`**,
consistent with the other perps
flags. There is no equivalent gate at the controller level, so the gate
lives in the client.

Required in all three components that branch on Cross, alongside the
position type:

```ts
const isCrossMarginEnabled = useSelector(selectPerpsCrossMarginEnabledFlag);
const isCross = isCrossMarginEnabled && position.leverage.type === 'cross';
```

With the flag **off**, a Cross position renders exactly as it did before
this PR — no badge, no
liquidation explanation, no "Position margin used" label, and margin
editing restored on the Lite card. Covered
by a dedicated flag-off test in both the Pro and Lite card suites.

This matters because `PerpsPositionCard` / `PerpsCard` are the
**Lite/shared** cards, not Pro-only:
without their own flag they would have inherited just `perpsEnabled` and
changed behaviour for
everyone on the existing Perps rollout, with no independent rollback.

## **Changelog**

<!-- mms-check: type=changelog required=true blocking=true -->

<!--
If this PR is not End-User-Facing and should not show up in the
CHANGELOG, you can choose to either:
1. Write `CHANGELOG entry: null`
2. Label with `no-changelog`

If this PR is End-User-Facing, please write a short User-Facing
description in the past tense like:
`CHANGELOG entry: Added a new tab for users to see their NFTs`
`CHANGELOG entry: Fixed a bug that was causing some NFTs to flicker`

(This helps the Release Engineer do their job more quickly and
accurately)
-->

CHANGELOG entry: Improved Cross position badges, liquidation
explanations and margin labels.

## **Related issues**

<!-- mms-check: type=issue-link required=true -->

Refs: https://consensyssoftware.atlassian.net/browse/TAT-3519

## **Manual testing steps**

<!-- mms-check: type=manual-testing required=true -->

```gherkin
Feature: Existing Cross position display
  Scenario Outline: Inspect a genuine Cross ETH position
    Given the selected testnet account holds exactly one Cross ETH position
    And the venue liquidation price is <price>
    When I inspect the position in Pro and Lite
    Then the position is labelled Cross and Position margin used
    And the liquidation value displays <display>
    And the margin edit control is absent
    When I press the liquidation information button
    Then the explanation states that liquidation can affect the entire cross balance

    Examples:
      | price             | display              |
      | null              | No liquidation price |
      | current venue USD | formatted venue USD  |
```

Use current venue values for replay; funding can change numeric
liquidation. Privacy masking, compact rows and isolated controls are
covered by component tests. Android, mixed-book grouping and
account-wide refresh were not exercised by this recipe.

## **Screenshots/Recordings**

Live Hyperliquid testnet Cross ETH position (0.0051 @ 2394.1,
leverage.type=cross, venue liquidationPx null) on dev1. Recipe passed
41/41 against the review-fix commit b111177, proving the renamed
position-scoped label, the Cross badge, the explicit no-liquidation
state and the shared-collateral explanation in both Pro and Lite. No
before screenshot is claimed.

<table>
<tr><td align="center" valign="top" width="50%"><strong>Pro Cross
position: 'Position margin used' with Cross badge and 'No liquidation
price'</strong><br/><img
src="https://raw.githubusercontent.com/abretonc7s/mm-mobile-farm-artifacts/main/fixes/35831/recipe-run/screenshots/cross-summary-pro.png?sha=fe4a708045e40fb7"
alt="Pro Cross position: 'Position margin used' with Cross badge and 'No
liquidation price'" width="320" /><br/><sub>caption confidence: LOW —
generic filename — no state-specific suffix</sub></td><td align="center"
valign="top" width="50%"><strong>Pro liquidation value and Cross
information affordance</strong><br/><img
src="https://raw.githubusercontent.com/abretonc7s/mm-mobile-farm-artifacts/main/fixes/35831/recipe-run/screenshots/cross-position-pro.png?sha=7cae73157236be98"
alt="Pro liquidation value and Cross information affordance" width="320"
/><br/><sub>caption confidence: LOW — generic filename — no
state-specific suffix</sub></td></tr>
<tr><td align="center" valign="top" width="50%"><strong>Pro
shared-collateral explanation: liquidation can affect the entire cross
balance</strong><br/><img
src="https://raw.githubusercontent.com/abretonc7s/mm-mobile-farm-artifacts/main/fixes/35831/recipe-run/screenshots/cross-explanation-pro.png?sha=b638cc3039d0abfd"
alt="Pro shared-collateral explanation: liquidation can affect the
entire cross balance" width="320" /><br/><sub>caption confidence: LOW —
generic filename — no state-specific suffix</sub></td><td align="center"
valign="top" width="50%"><strong>Lite Cross position summary after badge
and label assertions</strong><br/><img
src="https://raw.githubusercontent.com/abretonc7s/mm-mobile-farm-artifacts/main/fixes/35831/recipe-run/screenshots/cross-summary-lite.png?sha=376067b521cce427"
alt="Lite Cross position summary after badge and label assertions"
width="320" /><br/><sub>caption confidence: LOW — generic filename — no
state-specific suffix</sub></td></tr>
<tr><td align="center" valign="top" width="50%"><strong>Lite liquidation
value with no margin edit control</strong><br/><img
src="https://raw.githubusercontent.com/abretonc7s/mm-mobile-farm-artifacts/main/fixes/35831/recipe-run/screenshots/cross-position-lite.png?sha=423e1b79bc96baad"
alt="Lite liquidation value with no margin edit control" width="320"
/><br/><sub>caption confidence: LOW — generic filename — no
state-specific suffix</sub></td><td align="center" valign="top"
width="50%"><strong>Lite shared-collateral explanation</strong><br/><img
src="https://raw.githubusercontent.com/abretonc7s/mm-mobile-farm-artifacts/main/fixes/35831/recipe-run/screenshots/cross-explanation-lite.png?sha=a0430e24bfa95f2c"
alt="Lite shared-collateral explanation" width="320" /><br/><sub>caption
confidence: LOW — generic filename — no state-specific
suffix</sub></td></tr>
</table>

## **Validation Recipe**

<details><summary>recipe.json, 42 nodes; validates live Cross display in
Pro and Lite</summary>

```json
{
  "$schema": "https://farmslot.io/schemas/recipe-v1.schema.json",
  "title": "Existing cross-position display in Lite and Pro",
  "description": "Requires exactly one real cross position on the selected account, so shared Pro selectors cannot match another market. Run separately for null and numeric liquidation fixtures. Asserts badges, venue liquidation display, explanation and non-editable Position margin used in Lite and Pro. No trades are created. Mixed-book, compact-row and privacy behavior require the later component tests; the remaining epic stays open. The null branch requires an existing falsy JSON field, excluding empty string, zero and false, because this pinned runner cannot express literal null in an atomic assertion.",
  "paramsSchema": {
    "type": "object",
    "additionalProperties": false,
    "properties": {
      "market": {
        "type": "string",
        "default": "ETH"
      },
      "accountAddress": {
        "type": "string",
        "default": "0x8dc623e964475d4d669da601fd15ea9125469003"
      },
      "liquidationPrice": {
        "type": "string",
        "default": "",
        "description": "Raw venue liquidation price; required to match the position when priceKind is numeric."
      },
      "displayValue": {
        "type": "string",
        "default": "No liquidation price",
        "description": "The formatted venue price without distance, or No liquidation price. Pro matches the price within its distance-suffixed display; Lite matches exactly."
      },
      "explanation": {
        "type": "string",
        "default": "At the current account value, this position has no liquidation price. This can change as the value of your other cross positions changes. A liquidation can affect your entire cross balance.",
        "description": "Exact localized tooltip copy for priceKind; supply the numeric explanation for numeric runs."
      },
      "priceKind": {
        "type": "string",
        "enum": [
          "null",
          "numeric"
        ],
        "default": "null"
      }
    }
  },
  "workflow": {
    "entry": "wallet",
    "nodes": {
      "wallet": {
        "action": "metamask.wallet.read_state",
        "intent": "Verify the selected account before inspecting its positions",
        "next": "account"
      },
      "account": {
        "action": "assert_output",
        "intent": "Require the intended account; never substitute another wallet",
        "source": "wallet",
        "assert": {
          "path": "$.account.address",
          "operator": "eq",
          "value": "{{params.accountAddress}}"
        },
        "next": "unlock"
      },
      "unlock": {
        "action": "metamask.wallet.ensure_unlocked",
        "intent": "Unlock the selected fixture wallet through its supported flow",
        "unlock_timeout_ms": 90000,
        "next": "environment"
      },
      "positions": {
        "action": "command",
        "intent": "Read full live controller positions and compare their mode and liquidation price against the venue; the bundled read action omits these fields",
        "timeout_ms": 30000,
        "next": "require-cross"
      },
      "require-cross": {
        "action": "assert_json",
        "intent": "Require exactly one live position so shared value selectors cannot match another market",
        "assert": {
          "path": "$.positions",
          "operator": "length_eq",
          "value": 1
        },
        "next": "require-cross-mode",
      },
      "pro-open": {
        "action": "ui.navigate",
        "intent": "Open the cross market in pro mode",
        "page": "perps-market",
        "market": "{{params.market}}",
        "mode": "pro",
        "next": "pro-scroll"
      },
      "pro-scroll": {
        "action": "ui.scroll",
        "intent": "Make the shared-collateral classification and margin amount visible for review",
        "test_id": "cross-margin-tag-pro-{{params.market}}",
        "scroll_into_view": true,
        "timeout_ms": 15000,
        "next": "pro-tag"
      },
      "pro-tag": {
        "action": "ui.wait_for",
        "intent": "Require the cross margin badge in pro",
        "test_id": "cross-margin-tag-pro-{{params.market}}",
        "expected": "visible",
        "timeout_ms": 5000,
        "next": "pro-margin"
      },
      "pro-price": {
        "action": "ui.wait_for",
        "intent": "Require the expected visible venue price or explicit no-price state",
        "text": "{{params.displayValue}}",
        "text_match": "contains",
        "expected": "visible",
        "timeout_ms": 5000,
        "next": "pro-position-capture",
        "test_id": "perps-pro-market-position-liq-price"
      },
      "pro-margin": {
        "action": "ui.wait_for",
        "intent": "Require the position-scoped cross collateral label",
        "text": "Position margin used",
        "text_match": "contains",
        "expected": "visible",
        "timeout_ms": 5000,
        "next": "pro-no-edit"
      },
      "pro-info": {
        "action": "ui.press",
        "intent": "Open the cross liquidation explanation",
        "test_id": "cross-liquidation-info-pro-{{params.market}}",
        "next": "pro-explanation"
      },
      "pro-explanation": {
        "action": "ui.wait_for",
        "intent": "Require the shared-collateral explanation",
        "text": "{{params.explanation}}",
        "text_match": "exact",
        "expected": "visible",
        "timeout_ms": 5000,
        "next": "pro-capture",
        "test_id": "perps-bottom-sheet-tooltip-content"
      },
      "pro-capture": {
        "action": "ui.screenshot",
        "intent": "Preserve the explanation that liquidation can affect the entire cross balance",
        "next": "pro-dismiss"
      },
      "pro-dismiss": {
        "action": "ui.press",
        "intent": "Dismiss the explanation through its visible action",
        "test_id": "perps-bottom-sheet-tooltip-got-it-button",
        "next": "lite-open"
      },
      "lite-open": {
        "action": "ui.navigate",
        "intent": "Open the cross market in lite mode",
        "page": "perps-market",
        "market": "{{params.market}}",
        "mode": "lite",
        "next": "lite-scroll"
      },
      "lite-scroll": {
        "action": "ui.scroll",
        "intent": "Make the shared-collateral classification and margin amount visible for review",
        "test_id": "cross-margin-tag-lite-{{params.market}}",
        "scroll_into_view": true,
        "timeout_ms": 15000,
        "next": "lite-tag"
      },
      "lite-tag": {
        "action": "ui.wait_for",
        "intent": "Require the cross margin badge in lite",
        "test_id": "cross-margin-tag-lite-{{params.market}}",
        "expected": "visible",
        "timeout_ms": 5000,
        "next": "lite-margin"
      },
      "lite-price": {
        "action": "ui.wait_for",
        "intent": "Require the expected visible venue price or explicit no-price state",
        "text": "{{params.displayValue}}",
        "text_match": "exact",
        "expected": "visible",
        "timeout_ms": 5000,
        "next": "lite-position-capture",
        "test_id": "position-card-liquidation-price-value"
      },
      "lite-margin": {
        "action": "ui.wait_for",
        "intent": "Require the position-scoped cross collateral label",
        "text": "Position margin used",
        "text_match": "contains",
        "expected": "visible",
        "timeout_ms": 5000,
        "next": "lite-no-edit"
      },
      "lite-no-edit": {
        "action": "ui.wait_for",
        "intent": "Require the cross margin edit control to be absent from this single-position view",
        "test_id": "position-card-margin-chevron",
        "expected": "absent",
        "timeout_ms": 5000,
        "next": "lite-summary-capture"
      },
      "lite-info": {
        "action": "ui.press",
        "intent": "Open the cross liquidation explanation",
        "test_id": "cross-liquidation-info-lite-{{params.market}}",
        "next": "lite-explanation"
      },
      "lite-explanation": {
        "action": "ui.wait_for",
        "intent": "Require the shared-collateral explanation",
        "text": "{{params.explanation}}",
        "text_match": "exact",
        "expected": "visible",
        "timeout_ms": 5000,
        "next": "lite-capture",
        "test_id": "perps-bottom-sheet-tooltip-content"
      },
      "lite-capture": {
        "action": "ui.screenshot",
        "intent": "Preserve the explanation that liquidation can affect the entire cross balance",
        "next": "lite-dismiss"
      },
      "lite-dismiss": {
        "action": "ui.press",
        "intent": "Dismiss the explanation through its visible action",
        "test_id": "perps-bottom-sheet-tooltip-got-it-button",
        "next": "done"
      },
      "done": {
        "action": "end",
        "status": "pass"
      },
      "price-kind": {
        "action": "switch",
        "intent": "Choose the explicit no-price case or the supplied numeric venue-price case",
        "value": "{{params.priceKind}}",
        "equals": "null",
        "cases": {
          "match": "require-null-price"
        },
        "default": "require-numeric-price"
      },
      "require-null-price": {
        "action": "assert_json",
        "intent": "Require the venue liquidation field to be present",
        "assert": {
          "path": "$.positions[0].liquidationPrice",
          "operator": "exists"
        },
        "next": "require-null-falsy",
      },
      "require-numeric-price": {
        "action": "assert_json",
        "intent": "Require the expected venue liquidation value before comparing its UI rendering",
        "assert": {
          "path": "$.positions[0].liquidationPrice",
          "operator": "eq",
          "value": "{{params.liquidationPrice}}"
        },
        "next": "pro-open",
      },
      "pro-no-edit": {
        "action": "ui.wait_for",
        "intent": "Require the cross margin edit control to be absent from this single-position view",
        "test_id": "perps-pro-market-position-edit-margin",
        "expected": "absent",
        "timeout_ms": 5000,
        "next": "pro-summary-capture"
      },
      "pro-scroll-price": {
        "action": "ui.scroll",
        "intent": "Make the liquidation value visible alongside its shared-collateral explanation control",
        "test_id": "cross-liquidation-info-pro-{{params.market}}",
        "scroll_into_view": true,
        "timeout_ms": 15000,
        "next": "pro-price"
      },
      "pro-position-capture": {
        "action": "ui.screenshot",
        "intent": "Preserve the visible liquidation value and cross information affordance after their assertions",
        "next": "pro-info"
      },
      "lite-scroll-price": {
        "action": "ui.scroll",
        "intent": "Make the liquidation value visible alongside its shared-collateral explanation control",
        "test_id": "cross-liquidation-info-lite-{{params.market}}",
        "scroll_into_view": true,
        "timeout_ms": 15000,
        "next": "lite-price"
      },
      "lite-position-capture": {
        "action": "ui.screenshot",
        "intent": "Preserve the visible liquidation value and cross information affordance after their assertions",
        "next": "lite-info"
      },
      "require-cross-mode": {
        "action": "assert_json",
        "intent": "Require shared collateral on the live position",
        "assert": {
          "path": "$.positions[0].leverage.type",
          "operator": "eq",
          "value": "cross"
        },
        "next": "require-cross-market",
      },
      "require-cross-market": {
        "action": "assert_json",
        "intent": "Require the live position to belong to the intended market",
        "assert": {
          "path": "$.positions[0].symbol",
          "operator": "eq",
          "value": "{{params.market}}"
        },
        "next": "price-kind",
      },
      "require-null-falsy": {
        "action": "assert_json",
        "intent": "Require an empty-valued liquidation field before ruling out non-null JSON values",
        "assert": {
          "path": "$.positions[0].liquidationPrice",
          "operator": "falsy"
        },
        "next": "require-null-not-string",
      },
      "require-null-not-string": {
        "action": "assert_json",
        "intent": "Reject an empty price string as a substitute for venue null",
        "assert": {
          "path": "$.positions[0].liquidationPrice",
          "operator": "ne",
          "value": ""
        },
        "next": "require-null-not-zero",
      },
      "require-null-not-zero": {
        "action": "assert_json",
        "intent": "Reject numeric zero as a substitute for venue null",
        "assert": {
          "path": "$.positions[0].liquidationPrice",
          "operator": "ne",
          "value": 0
        },
        "next": "require-null-not-false",
      },
      "require-null-not-false": {
        "action": "assert_json",
        "intent": "Reject boolean false so only literal venue null passes",
        "assert": {
          "path": "$.positions[0].liquidationPrice",
          "operator": "ne",
          "value": false
        },
        "next": "pro-open",
      },
      "environment": {
        "action": "command",
        "intent": "Verify dev1, Hyperliquid and testnet before reading the real Cross fixture",
        "timeout_ms": 30000,
        "next": "positions"
      },
      "pro-summary-capture": {
        "action": "ui.screenshot",
        "intent": "Preserve the visible Cross badge and Position margin used label after their assertions",
        "next": "pro-scroll-price"
      },
      "lite-summary-capture": {
        "action": "ui.screenshot",
        "intent": "Preserve the visible Cross badge and Position margin used label after their assertions",
        "next": "lite-scroll-price"
      }
    }
  }
}
```
</details>

## **Validation Logs**

Re-validated on the rebased branch (`origin/main` @ `9e21342485`). Both
inherited fixtures were
re-established as real testnet positions, because the recipe gates on
one live Cross position and the
original validation closed its positions on completion.

| Fixture | Order | Position | `leverage.type` | Venue `liquidationPx` |
Recipe result |
|---|---|---|---|---|---|
| null | `59791500698` | +0.005 ETH long @ $2,425.7 | `cross` | `null` |
**41/41 pass** |
| numeric | `59791614653` | −0.005 ETH short @ $2,424.8 | `cross` |
`125774.0984313725` | **37/37 pass** |

Cleanup: both closed (`59791593595`, `59791798948`), leverage restored
to the `isolated 3x` baseline.
Final inspect confirms **0 open positions**.

```bash
mm-harness run recipe.json --adapter mobile --slot macpro-mm-2 --json
mm-harness run recipe.json priceKind=numeric 'liquidationPrice="125774.0984313725"' \
  'displayValue=$125,774' explanation='...' --adapter mobile --record-video=full-run --json
```

**Local gate (post-rebase):** scoped ESLint `--max-warnings=0` clean ·
`lint:tsc` exit 0 ·
`format:check` clean · working tree clean · Jest **5/5 suites, 110/110
tests**.

`lint:tsc` passing is the direct evidence the Core dependency is
resolved: it is the first clean
typecheck since `main` bumped `@metamask/perps-controller` to `^16.2.0`,
which supplies the four
`ORDER_MARGIN_MODE_*` constants that previously failed at
`translatePerpsError.ts:77/79/81/83`.

**Not covered:** Android, mixed-book grouping, account-wide refresh, and
the Pro margin-mode picker
(disabled in this slice).

## **Pre-merge author checklist**

<!-- mms-check: type=checklist required=true -->

<!--
Every checklist item must be consciously assessed before marking this PR
as
"Ready for review". A checked box means you deliberately considered that
responsibility, not that you literally performed every action listed.

Unchecked boxes are ambiguous: they are not an implicit "N/A" and they
are not
a silent "skip". See `docs/readme/ready-for-review.md` for the full
checklist
semantics.
-->

- [x] I've followed [MetaMask Contributor
Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask Mobile
Coding
Standards](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/CODING_GUIDELINES.md).
- [x] I've completed the PR template to the best of my ability
- [x] I've included tests if applicable
- [x] I've documented my code using [JSDoc](https://jsdoc.app/) format
if applicable
- [x] I've applied the right labels on the PR (see [labeling
guidelines](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/LABELING_GUIDELINES.md)).
Not required for external contributors.

The performance items below were considered. This is an iOS
display/controller prerequisite validation; Android and power-user
performance profiling were not run, and no performance claim or new
tracing was added. Draft status is retained pending Core
release/dependency integration and operator review.

#### Performance checks (if applicable)

- [x] I've tested on Android
  - Ideally on a mid-range device; emulator is acceptable
- [x] I've tested with a power user scenario
- Use these [power-user
SRPs](https://consensyssoftware.atlassian.net/wiki/spaces/TL1/pages/edit-v2/401401446401?draftShareId=9d77e1e1-4bdc-4be1-9ebb-ccd916988d93)
to import wallets with many accounts and tokens
- [x] I've instrumented key operations with Sentry traces for production
performance metrics
- See [`trace()`](/app/util/trace.ts) for usage and
[`addToken`](/app/components/Views/AddAsset/components/AddCustomToken/AddCustomToken.tsx#L274)
for an example

For performance guidelines and tooling, see the [Performance
Guide](https://consensyssoftware.atlassian.net/wiki/spaces/TL1/pages/400085549067/Performance+Guide+for+Engineers).

## **Pre-merge reviewer checklist**

<!--
Reviewer checklist items follow the same semantics as the author
checklist: an
unchecked box is ambiguous, a checked box means the reviewer consciously
assessed that responsibility. See `docs/readme/ready-for-review.md`.
-->

- [ ] I've manually tested the PR (e.g. pull and build branch, run the
app, test code being changed).
- [ ] I confirm that this PR addresses all acceptance criteria described
in the ticket it closes and includes the necessary testing evidence such
as recordings and or screenshots.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> User-facing perps risk and margin copy changes when the flag is on;
rollout is gated and display-only, but incorrect liquidation messaging
could mislead traders.
> 
> **Overview**
> Adds **Cross margin display** for open cross positions behind the
**`perpsCrossMarginEnabled`** flag (defaults off). When the flag and
`leverage.type === 'cross'` align, Lite (`PerpsPositionCard`), Pro
(`PerpsProPositionCard`), and compact rows (`PerpsCard`) show a
**Cross** badge, relabel collateral as **Position margin used**, and
**hide margin edit** controls.
> 
> **Liquidation** handling changes for cross positions: a null venue
price shows **No liquidation price** instead of the generic fallback,
and a new **`PerpsCrossMarginInfoButton`** opens bottom-sheet copy
explaining shared cross collateral (with/without a numeric liquidation
price). Tooltip keys, i18n, and stable test IDs (`cross-margin-tag-*`,
`cross-liquidation-info-*`) support automation.
> 
> Flag-off behavior is unchanged (isolated presentation). Tests and
mocks cover cross vs isolated, privacy masking, and compact rows.
Margin-mode validation error strings in `en.json` are clarified.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
322be6a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants