Skip to content

Update README.md - #80

Merged
estebanmino merged 5 commits into
masterfrom
update-readme
Aug 28, 2018
Merged

estebanmino merged 5 commits into
masterfrom
update-readme

Conversation

@brunobar79

@brunobar79 brunobar79 commented Aug 22, 2018 •

Copy link
Copy Markdown
Contributor
  • Remove todo from README (now we have github issues for each topic)
  • Added CircleCi build badge
  • Removed TravisCI badge

@estebanmino
estebanmino merged commit 8ffb1a5 into master Aug 28, 2018
@brunobar79
brunobar79 deleted the update-readme branch February 11, 2019 21:41
sethkfman pushed a commit that referenced this pull request Sep 3, 2021
The README release instructions have been updated to account for the
new release actions we're now using.
rickycodes pushed a commit that referenced this pull request Jan 31, 2022
* Update README.md

* addedd CircleCI badge

* Remove travis badge

* Use shield style badge for CircleCi

* Fix typo
weitingsun pushed a commit to Poovarasan-Sandhanam/metamask-mobile that referenced this pull request Nov 6, 2026
…@metamask/device-mcp 0.7.0 (MetaMask#38594)

## **Description**

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

Upgrades the visual testing workflow (`tests/llm-workflow`, the `yarn
mm` CLI) to `@metamask/client-mcp-core` **0.13.1** ([release PR
MetaMask#82](MetaMask/client-mcp-core#82); 0.13.0
([MetaMask#80](MetaMask/client-mcp-core#80)) was not
published, 0.13.1 is the same code) and `@metamask/device-mcp`
**0.7.0**, and adapts the mobile consumer to the core changes. Only dev
tooling changes; no app code is touched.

**Changes (one commit each):**

| Commit | Change |
| --- | --- |
| device-mcp ^0.5.0 + Origin in the iOS liveness probe | Metro rejects
Hermes CDP connections without an `Origin` header. `verifyJsLiveness`
now sends the same `Origin` that device-mcp uses, so the launch health
check stops falling back to target-presence-only. |
| Drop the knowledge store | Core 0.13.x removes the knowledge store.
The daemon no longer creates one, and the provider writes `session.json`
with `writeSessionMetadata` to
`<artifactsDir>/<sessionId>/session.json`. |
| Report only known app state fields | Core no longer puts app state in
observations, and the mobile driver no longer guesses wallet fields. The
state snapshot capability reports `isLoaded`, `extensionId` and `source:
'stub'`, plus `currentScreen` only when a known testId identifies it.
Note: on mobile, core (0.13.x and 0.9.0) returns the driver's state
directly and does not call this capability, so `get-state` never shows
`currentScreen`. |
| Use device-mcp Android snapshots | device-mcp's ADB backend ships its
own signer-verified snapshot helper (`helper-first`), so the local
`agent-device` snapshot wrapper (~770 lines) is removed.
`DEVICE_MCP_ADB_SNAPSHOT` still overrides the mode. |
| device-mcp ^0.6.0 → ^0.7.0 | 0.6.0 brings `helper-first` and the
nested idb format. 0.7.0 adds session-scoped idb companion teardown and
fixes idb recovery error reporting. |
| Dispose the iOS driver in adapter cleanup | On a failed launch, core
cannot see the driver, so its private idb companion leaked.
`IOSPlatformAdapter.cleanup()` now disposes it (idempotent with core's
own disposal). |
| Call `node_modules/.bin/mm` directly (docs) | Skips Yarn startup,
about 0.4–0.5 s per call. |
| client-mcp-core ^0.13.0 → ^0.13.1 | Version bump, README version notes
and `yarn.lock` (client-mcp-core 0.13.1, one `@metamask/device-mcp`
0.7.0). |

**What agents see from core 0.13.x:** one-line JSON output by default
(`--pretty` to indent), a per-call `--observe none|diff|full`,
observations only for mutating and batch tools, no app state in
observations, `meta.timing` on every response, cancelled timed-out
calls, a flat mobile a11y tree without status/nav bars and the dev
overlay, `run-steps` `observe` instead of `includeObservations`, and
`batchTimeoutMs` capped at 30 s. The matching skill update is
MetaMask/skills#211 (`testing/mobile-visual-testing`).

## **Changelog**

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

CHANGELOG entry: null

## **Related issues**

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

Refs: MetaMask/client-mcp-core#80,
MetaMask/client-mcp-core#82

## **Manual testing steps**

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

```gherkin
Feature: mm CLI visual testing workflow with client-mcp-core 0.13.1

  Background:
    And an iOS Simulator is booted with a MetaMask dev build installed
    And Metro is running from this branch on port 8085

  Scenario: launch and observe on iOS
    When I run "yarn mm:doctor"
    Then every iOS prerequisite passes
    When I run "node_modules/.bin/mm launch --platform ios --metro-port 8085"
    Then the launch succeeds and "state" is {"isLoaded":true,"extensionId":"io.metamask.MetaMask","source":"stub"}
    When I run "node_modules/.bin/mm describe-screen"
    Then the output is one line of JSON with "a11y.nodes", "testIds" and "meta.timing"
    When I click an a11y ref with "--observe full"
    Then the response has "observations" with only "a11y" and "testIds"
    When I run "node_modules/.bin/mm knowledge-search send"
    Then the CLI reports "unknown command 'knowledge-search'"
    When I run "node_modules/.bin/mm cleanup"
    Then the response is {"cleanedUp":true, ...}
```

## **Screenshots/Recordings**

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

### **Before**

N/A (dev tooling only)

### **After**

N/A (dev tooling only). Validation with client-mcp-core 0.13.0 (yalc
from `release/0.13.0`, before publish) and re-checked with **0.13.1 and
device-mcp 0.7.0 from npm**, with Metro from this branch:

- `yarn test:unit:llm-workflow`: 16 suites, 219 tests passed (0.13.0 via
yalc and 0.13.1 from npm).
- `yarn install --immutable` and `yarn dedupe --check`: pass with
0.13.1.
- Smoke with 0.13.1 from npm, iOS and Android: launch, unlock, wallet
home, `click --observe full` (observation has only `a11y` and
`testIds`), account picker, Send opened and closed (nothing sent or
signed), `cdp` `isUnlocked()` = `true`, `cleanup`.
- `tsc --noEmit` and ESLint on the changed files: clean.
- `yarn mm:doctor`: all iOS prerequisites passed.

**Live sessions** (existing wallet, unlock screen; no transactions):

| Check | iOS (iPhone 17 Pro sim, main dev build 8.20.0) | Android
(emulator-5554, API 36, Metro-attached dev build) |
| --- | --- | --- |
| `launch --metro-port 8085` | ✅ `state` = `{isLoaded, extensionId,
source: "stub"}` | ✅ |
| `describe-screen` (flat a11y tree, testIds, `meta.timing`) | ✅ unlock
screen testIds found | ✅ unlock screen testIds found; no status/nav bar
nodes |
| `get-state` (partial, no guessed wallet fields) | ✅ | ✅ |
| `type --testid` → diff observation | ✅ | ✅ |
| `get-text` (read → no observation) | ✅ | ✅ |
| `click --observe none` / `--observe full` | ✅ / ✅ (64 nodes) | ✅ / ✅ |
| `run-steps` with `observe: "none"`, `batchTimeoutMs: 20000` | ✅
`summary.ok` | ✅ `summary.ok` |
| `includeObservations` rejected; `batchTimeoutMs` > 30000 rejected | ✅
| ✅ |
| `--pretty`, one-line JSON by default | ✅ | ✅ |
| `wait-for` timeout | ✅ cancelled with error | — |
| `press-button back` | — | ✅ |
| `cdp` / `hermes-targets` with `--metro-port 8085` | ✅ | ✅ |
| `screenshot`, `list-testids`, `accessibility-snapshot` | ✅ | ✅ |
| `knowledge-*` | ✅ `unknown command` | ✅ |
| `cleanup` | ✅ | ✅ |

**Unlocked flows** (existing wallet, read-only: nothing was sent or
signed; Send was only opened and closed):

| Step | iOS (iPhone 17 Pro sim, iOS 27, dev build 8.20.0) | Android
(emulator-5554, API 36, dev build 8.20.0 + Metro JS from this branch) |
| --- | --- | --- |
| Type password and unlock | ✅ `type`, then `click --testid Done`
(keyboard return submits) | ✅ `type`, `press-button back`, `click
--testid log-in-button` |
| Wallet home (`wait-for --testid wallet-screen`, `describe-screen`) | ✅
| ✅ |
| Account picker opens, back to home | ✅ `click --testid account-picker`
| ❌ `click --testid account-picker` and `click <ref>` open the profile
screen (see 6 below). ✅ `tap-coordinates` at the center of
`account-picker` opens Accounts |
| Open Send, back to home | ✅ with `tap-coordinates` (see 2 below) | ✅
`click --testid wallet-send-button` |
| `cdp` `KeyringController.isUnlocked()` | ✅ `true` | ✅ `true` |
| `cleanup` | ✅ | ✅ |

Known behavior (not a regression, the same with client-mcp-core 0.9.0 /
earlier device-mcp versions). The skill PR documents each one; fixes are
tracked for a later client-mcp-core / device-mcp release, not this PR:

1. `mm cdp` / `hermes-targets` do not reuse the launch's `--metro-port`
and default to 8081. Pass `--metro-port` on each call when Metro runs on
another port.
2. iOS 18+: device-mcp reads the tree with idb `--api axbridge`, which
merges the wallet home balance and the Buy / Swap / Send / Receive row
into one unlabelled container. `wallet-send-button` is missing, so
`click --testid wallet-send-button` times out. `--api ax` lists it.
Workaround: `tap-coordinates`. Fix: MetaMask/device-mcp#52.
3. iOS: `mm dismiss-keyboard` fails because idb rejects `idb ui key
RETURN`. Workaround: `click --testid Done`. Fix: MetaMask/device-mcp#48.
4. Mobile `get-state` has no `currentScreen` (see the table of changes
above).
5. After a tap that opens a slow screen (the first Send of a session on
Android), the observation can still show the previous screen. `wait-for`
on a testId of the new screen confirms the navigation.
6. Test ID match is substring-based (device-mcp `findElement` →
`fuzzyMatch` returns the first element whose identifier *contains* the
query, in tree order). On the Android wallet home,
`account-picker-avatar` (inside `profile-button`, earlier in the tree)
matches `account-picker`, so the tap lands on the profile avatar (85,
138) instead of the account picker (384, 136). An a11y ref resolves to
the same testId query, so it fails the same way. iOS passes only because
its tree has no `account-picker-avatar`. Workaround: `tap-coordinates`.
Fix: MetaMask/device-mcp#52 (exact match first).

## **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.

#### 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]
> **Low Risk**
> Changes are confined to LLM workflow dev dependencies and tests under
`tests/llm-workflow`; production mobile app behavior is unaffected.
> 
> **Overview**
> Upgrades the **`yarn mm` / `tests/llm-workflow`** dev tooling to
**`@metamask/client-mcp-core` 0.13.1** and **`@metamask/device-mcp`
0.7.0**. No application code under `app/` is changed.
> 
> **Core 0.13.x alignment:** The daemon no longer registers a
**`KnowledgeStore`**; session metadata is written with
**`writeSessionMetadata`** into
`<artifactsDir>/<sessionId>/session.json` (default
**`test-artifacts`**). The state snapshot capability returns a minimal
stub when there is no driver and **drops `currentScreen`** unless a
known testId maps to a screen.
> 
> **Android snapshots:** The local **`agent-device` snapshot wrapper**
(`snapshot-backend`, helper ADB executor, and their tests) is removed.
The Android adapter passes **`device-mcp`'s `AdbBackend` through
unchanged** for **`helper-first`** snapshots and
**`DEVICE_MCP_ADB_SNAPSHOT`** overrides; README documents the new helper
package and modes.
> 
> **iOS Hermes / cleanup:** **`verifyJsLiveness`** sends Metro's
expected **`Origin`** header (via **`debuggerOrigin`** or
**`HERMES_CDP_ORIGIN`**). **`IOSPlatformAdapter.cleanup`** disposes the
driver/backend after closing the app so failed launches do not leak idb
companions.
> 
> Docs note calling **`node_modules/.bin/mm`** directly; Babel excludes
**`hermes-health.ts`** for runtime env; **`tsconfig`** drops the
**`agent-device`** path mapping.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b508bf7. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
darkwing pushed a commit to darkwing/metamask-mobile that referenced this pull request Nov 13, 2026
…o-phase signed reads (PRED-1372) (MetaMask#39353)

## **Description**

PredictNext signing rework (PRED-1372): signed venue profiles
(ADR-0004), exact-byte order commit, and two-phase signed reads for the
Kalshi venue on mobile.

**Why.** The Predict API used to sign every Kalshi account request
itself, with one server-held demo key. The consequence was that the
phone's signature decided nothing about *which* account was read: every
device showed the same balance. This PR is the mobile half of removing
that key — the phone now signs each account operation with its device
key, and the backend only relays.

**What changed**

- **Signing primitives** (`auth/signing/`, `auth/venue-profiles/`):
ES256 device signatures over canonicalized operations; the phone sends
the venue profile *reference* (`profile {id: "kalshi-demo-signing",
version: 2}`) and the server resolves its bundled document;
approved-intent ledger for replay protection; profile schema and
template validation.
- **Two-phase signed reads** (`adapters/remote/signedVenueCall.ts`):
phase 1 is bearer-only and the route answers 200 `sign_required` naming
the one venue GET it needs; phase 2 re-issues the read with the phone's
signature over those exact coordinates. A route that answers with a
different `sign_required` is signed again — the phone signs at most
twice per read, and one renewal is allowed on 403
`venue_authorization_invalid` / 409 `venue_signature_expired`. Exceeding
the bound surfaces the distinct `VenueReadBudgetExhaustedError`, which
is classified as **sent** (`requestSent: true`) because the signature
budget was spent mid-flight.
- **Distinct dispatch failures**: `PredictRequestNotSentError` (nothing
crossed the wire) and `PredictSigningError` (the request was sent) are
no longer flattened into `INVALID_RESPONSE`; signing refusal maps to
`VENUE_SIGNING_REFUSED` and signing unavailability to `UNAUTHENTICATED`.
- **Exact-byte order commit**: the adapter signs the exact bytes the
relay forwards. The confirm path itself already ships
(`PredictOrderFlowSheet` → `service.commitPreview`), and this PR adds
the signing around it: the sheet pins the idempotency key and the
amount/contracts at quote time, so a Commit signs what the user was
quoted even if the inputs drift afterwards.
- **Honest outcomes**: `venue_preview_mismatch` maps to
`ORDER_PREVIEW_MISMATCH` ("The signed order does not match this quote.
Refresh and review it again.") and stays pre-relay, so it is never shown
as a region block. `operation_not_found` maps to `ORDER_OUTCOME_UNKNOWN`
("Order outcome could not be confirmed. Check your activity or contact
support."), and any non-unsent commit failure is wrapped the same way,
so an unknown outcome is never presented as a definite negative. Order
notifications have explicit `needs_manual_review` and `not_filled`
cases, with an exhaustive `never` check instead of a silent default.
- **Lock/reset revoke in-flight signatures**: the approved-intent ledger
re-checks a generation counter after every read and write, and the
service compares a session snapshot (generation, binding identity,
in-flight resets, enabled/unlocked, canonical profile) before signing
and after the crypto completes. `reset()` drops the active session and
device key synchronously before awaiting the ledger clear and slot
deletes, so a later unlock cannot authorize work captured before the
revocation.
- **Durable recovery after relaunch**: a credential-free dispatch
journal (`predict-next:order-dispatches:v1`) is written before the
commit POST, so an order whose response was lost still has a reference
after the app closes. `bindOrderRecoveryLifecycle` resumes discovery and
signed observation on authenticated startup/foreground/reconnect,
generation-fenced, backed by the API's unresolved-operation listing. The
portfolio surfaces this through `PortfolioRecoveryPanel`. Recovery
observes; it never POSTs.
- **`VENUE_ACCOUNT_NOT_ENABLED` error code** and adapter 403 mapping, so
the temporary demo onboarding gate can reopen on that 403.
`useVenueAccountNotEnabled` is wired into `KalshiDemoOnboardingGate`.
- **`venue_authorization_required` → `UNAUTHENTICATED`**: the backend
refuses an account read it cannot verify against the device signature.
That code previously fell through to the generic 403 branch and became
`GEO_BLOCKED`, telling users their region was unsupported when the real
problem was authorization.
- **Order preview rows**: `Maximum cost (signed)` for buys and `Proceeds
if fully filled (signed)` for sells, so the bound the user is signing is
visible before they sign.
- **Profile version gate**: `venue_profile_update_required` maps to
`APP_UPDATE_REQUIRED` ("Update MetaMask to continue trading with this
venue.") and `venue_profile_not_ready` to `VENUE_UNAVAILABLE`, so a
store build is told to update rather than failing opaquely. Profile
version 2 adds `reduce_only` (`true` for sells, `false` for buys).
- **View layer no longer builds signing inputs**:
`auth/previewOperation.ts`, `auth/signing/orderCommit.ts` (+ test) and
`adapters/remote/createKalshiTradingAdapter.ts` are deleted. Signing
previews live on `KalshiRemoteAdapter.previewOperation` and
`PredictDeviceAuthService.previewOperation`, with the signing helpers in
`adapters/remote/kalshiOrderSigning.ts`.
- **API error contract check**: the mobile fixture
`contracts/v1/fixtures/api-errors.v1.json` mirrors the API inventory,
and `KalshiRemoteAdapter.error-contract.test.ts` drives every emitted
code/status/phase. The cross-repo gate compares the consumer copy
semantically, so formatter differences cannot mask a missing code.

**Fixes found while bringing the flow up on device**

- **Sign operation was never wired into the engine**
(`core/Engine/controllers/predict-service-init.ts`,
`core/Engine/messengers/predict-order-service-messenger.ts`).
`signOperation` and `invalidateSigningSession` were absent from both the
init-time messenger registration and the action union, so the order
client's handler resolved `undefined`; the client refuses to send
without it, and every Approve & Submit failed before a request left the
device. Both actions are now registered. The same file wires the
dispatch journal and the recovery lifecycle binding.

ADR-0004
(`app/components/UI/PredictNext/docs/adr/0004-signed-venue-profiles.md`)
added; ADR-0003 superseded.

The Kalshi demo onboarding UI (`onboarding/`) is temporary and will be
replaced by Universal KYC. This PR changes
`KalshiDemoOnboardingGate.tsx` (+ test) to consume
`useVenueAccountNotEnabled`, which previously existed but was never
imported.

**Counterpart.** The API-side removal of the server-held credential is
`va-mmcx-predict-api` PR MetaMask#80 on branch
`feat/predictnext-signing-rework`. That change makes this one
load-bearing: without a device signature the backend now refuses the
read with 403 `venue_authorization_required` instead of serving a shared
account. The two PRs must ship together: MetaMask#80 requires the v4
`idempotencyKey` this branch sends.

## Test layer placement

Unit tests for the request/error surface, plus focused integration for
the recovery seam. The behaviour under change is deterministic request
construction, error mapping, and durable recovery — all exercised at the
boundary responsible for it:

- `signedVenueCall.test.ts` — proposal chaining, the two-signature
bound, and the sent-vs-unsent budget classification.
- `deviceRequestSigner.test.ts`, `kalshiOrderSigning.test.ts`,
`approvedIntentLedger.test.ts`, `profileTemplates.test.ts`,
`venueAuthorization.test.ts`, `venueSigningProfiles.test.ts` — signing
primitives, path normalization, and replay revocation.
- `PredictApiReadClient.test.ts`, `PredictOrderService.test.ts`,
`KalshiRemoteAdapter.test.ts` — client and adapter contract, including
the 403 mapping and preview-mismatch regressions.
- `KalshiRemoteAdapter.error-contract.test.ts` — every emitted API
code/status/phase against the mirrored contract.
- `PredictOrderService.recovery.test.ts` (unit) and
`PredictOrderService.integration.test.ts` (Engine seam) — pre-dispatch
journaling, relaunch resume, and lock-during-write. Component-view is
not the right layer: recovery state is driven by the service and
AppState/NetInfo, not by a new screen, and the preview rows are already
covered through `OrderPreviewRows.test.tsx`.
- Appium is not justified: nothing here depends on a device/native
boundary beyond key custody, which the unit-level signer tests isolate
with a fake key. The full device journey is a manual step below.

Verified locally at this commit: `jest app/components/UI/PredictNext` —
**162 suites / 2355 tests passing**. Earlier full-suite figures in this
description (`157 suites / 2163 tests`) were measured on `2271ef0bcc7`
and are superseded.

## **Changelog**

CHANGELOG entry: Fixed Predict order previews reporting signing failures
as an unsupported region, added signed maximum-cost and proceeds rows to
the preview, and resumed unresolved order observation after relaunch

## **Related issues**

Refs: PRED-1372

## **Manual testing steps**

```gherkin
Feature: device-signed Predict account reads

  Background:
    Given the app is built against a Predict API that holds no venue account credential
    And the wallet completed Predict venue onboarding so a device signing key exists

  Scenario: a signed portfolio read resolves the device's own account
    Given the Predict portfolio loaded successfully at least once
    When the user opens the Predict tab and the portfolio refreshes
    Then the displayed balance belongs to the signed-in wallet's own venue account
    And every portfolio request carries a device signature, not a server credential

  Scenario: an unverifiable account read is reported as an authorization problem
    Given the device signing key is missing or the venue rejects it
    When the user opens the Predict portfolio
    Then the app reports an authentication problem
    And it does not report the region as unsupported

  Scenario: order preview shows the signed bounds
    Given a market is selected in the Predict order flow
    When the user previews a buy order
    Then the preview shows "Maximum cost (signed)"
    When the user previews a sell order
    Then the preview shows "Proceeds if fully filled (signed)"

  Scenario: an unresolved order is observed after relaunch
    Given a commit was dispatched and the response was lost
    When the app is killed, relaunched and unlocked
    Then the portfolio shows the order as being observed
    And recovery never sends a second commit
```

Setup: point `MM_PREDICT_API_URL` at a local stack, reset the app cache,
then complete Predict onboarding. A wallet with no Kalshi account should
reach the demo onboarding gate via `venue_account_not_enabled`.

## **Screenshots/Recordings**

First paired-runtime run executed on the iOS simulator against this
branch's local API. Tool: `skulk`, session `20261112-112920-5913`;
mobile `320fa0f63d126b430fc30f85ecce8c1609b30579`, API branch
`feat/predictnext-signing-rework` on `:3333` behind a logging proxy.
Report: `skulk report 20261112-112920-5913 --json` -> **4 checks: 3 PASS
/ 0 FAIL / 0 SKIPPED / 1 UNVERIFIED**.

| Scenario | Verdict | Decisive evidence |
| --- | --- | --- |
| Unverifiable account read reported as an authorization problem, not a
region block | PASS | Bearer-only `GET /v1/venues/kalshi/balance` -> 200
`kind:sign_required`; signed re-call with `venue-read` +
`venue-authorization` -> 403 `venue_account_not_enabled` (Kalshi cause
`permission_denied`). App surfaced `VENUE_ACCOUNT_NOT_ENABLED` and the
onboarding CTA, never `GEO_BLOCKED`. Shot `shots/2541.png`. |
| Order preview shows the signed bounds | PASS |
`PredictOrderService:requestQuote` returned `limitPrice 0.5600`,
`estimatedContracts 12`, `requestedAmount 7.00`, `totalDebit 6.96`,
expiry set, fees `0.12 venue + 0.12 metamask`; `reviewPreview` returned
`maxCost 6.96` / `contracts 12.00`. Backend `POST
/v1/venues/kalshi/orders/preview` -> 201. Shot `shots/2580.png`. |
| Unresolved order observed after relaunch without a second commit |
PASS | Commit POSTed exactly once and failed closed as
`ORDER_OUTCOME_UNKNOWN` (`phase:commit`, `mutationRelay:unknown`).
`getRecovery` returned `[{previewId: e0df30f0-..., status: 'checking'}]`
both before and after `relaunch`. Every post-relaunch request for that
preview was a GET; no second `POST /commit` and no re-preview. Shot
`shots/3699.png`. |
| Signed portfolio read resolves the wallet's own account | UNVERIFIED |
Both phases execute (phase 1 `sign_required`, phase 2 signed with a
1552-byte envelope), so the two-phase protocol is proven, but **no
portfolio page was ever read**: the fixture's Kalshi demo account has no
enrolled device credential, so Kalshi answers `403 permission_denied`
after the API verifies and relays. Closing this needs demo onboarding
completed for the session wallet, which requires an email code to a real
inbox on the shared demo account. Shot `shots/3747.png`. |

Raw artifacts:
`~/.skulk/sessions/20261112-112920-5913/report/report.md`,
`report.json`, and `shots/`. Not claimed: an accepted commit against a
funded venue account, an exact-byte signature accepted by Kalshi, or any
Android run. The unread portfolio page is the only scenario not proven
on device, and its prerequisite is external to this branch.

## **Pre-merge author checklist**

- [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
  - 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).

<!--
Assessment notes, so each checked box above is unambiguous:
- Android: assessed as not applicable for this PR — the work was
exercised on the iOS simulator only. No Android device or emulator run
has happened.
- Power-user scenario: assessed as not applicable — the change touches
signing and error mapping, not wallet scale, and no multi-account import
was run.
- Sentry traces: assessed as not applicable — the added work is request
signing and error mapping; no new user-facing operation was
instrumented, and adding traces to the signing path was deliberately out
of scope.
- Tests: `jest app/components/UI/PredictNext` — 162 suites / 2355 tests
passing at this commit.
- Labels: `size-XL` plus the team label applied by CI.
-->

## **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.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Changes authentication, cryptographic signing, order placement, and
error semantics on the trading path; incorrect dispatch or mapping could
mislead users about order outcomes or authorization.
> 
> **Overview**
> Mobile PredictNext now **device-signs** Kalshi account reads and order
commits instead of relying on bearer-only API calls.
**`PredictApiReadClient`** uses a two-phase flow (bearer
`sign_required`, then re-call with `Venue-Authorization` and pinned
venue GET coordinates), signs **`commitOrder`** as exact body bytes to
`.../orders/{previewId}/commit`, and adds **`observeOrder`** and
**`listUnresolvedOrders`**. Signing refusal vs. post-dispatch failure is
split via **`PredictRequestNotSentError`**, **`PredictSigningError`**,
and **`PredictReadBudgetExhaustedError`**.
> 
> **`KalshiRemoteAdapter`** pins previews (idempotency, quote snapshot,
auth generation), exposes **`reviewOrder`** / **`invalidatePreviews`**,
requires explicit **`user-approved`** commit, and forwards signed inputs
from **`kalshiOrderSigning`**. Portfolio summary is **composed** from
holdings totals plus a separate balance read. Errors map canonical API
body codes first (including auth 403s → **`UNAUTHENTICATED`**, not
**`GEO_BLOCKED`**), with phase metadata from **`predictErrorEvidence`**.
> 
> Supporting pieces: **`signedVenueCall`** (renew-on-stale signature/A2T
with bounded read budget), **`approvedIntentLedger`** (confirmation +
replay limits), stricter **P-256 key** lifecycle on delete/clear races,
removal of **`createKalshiTradingAdapter`**, and contract tests for
every emitted API error at the adapter boundary.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6c1771f. 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 <noreply@anthropic.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
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.

2 participants