Repository navigation
perf(walletconnect): sign relay auth JWTs with native ed25519 - #38839
Conversation
WalletConnect signs a relay auth JWT on every relayer connect (unlock, foreground, network changes) and derives its client public key with @walletconnect/relay-auth's bundled pure-JS ed25519. A Hermes profile right after unlock on a Galaxy Z Fold4 showed 506 ms of JS thread in that code (precompute tables and scalar multiplication), inside a 928 ms JS lag. Metro now resolves @walletconnect/relay-auth to a shim that re-exports the package and replaces generateKeyPair and signJWT with react-native-quick-crypto (OpenSSL) calls. ed25519 is deterministic, so keys and JWTs are byte-identical (covered by equivalence tests against the JS implementation); on any native failure the shim falls back to the JS implementation for the session. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
CLA Signature Action: All authors have signed the CLA. You may need to manually re-run the blocking PR check if it doesn't pass in a few minutes. |
PR template — items to address before "Ready for review"Warnings — informational, address before merging:
See docs/readme/ready-for-review.md for the full Definition of Ready for Review. |
Smart E2E Test SelectionSelected E2E tagsSmokeMMConnect AI Confidence: 78 E2E reasoningExpand to readThis PR introduces a new WalletConnect relay-auth shim ( Why these tags:
Why not ALL tags: The shim is specifically scoped to WalletConnect relay authentication (key generation and JWT signing for relay connections). It has a JS fallback, making it unlikely to break non-WalletConnect flows. The change doesn't touch transaction signing, account management, swap/bridge, staking, or other wallet flows. Risk assessment: Medium — the change intercepts a critical cryptographic path at the Metro bundler level (affecting all WalletConnect relay auth calls), but includes a robust JS fallback mechanism. The metro.config.js change is critical infrastructure but the resolver logic is well-scoped to only |
Before/after on a deviceMeasured with the internal perf session (in-app sampler with Hermes sampling profiles at about 100 Hz, symbolicated with the build's source map). Device: Galaxy Z Fold4 (SM-F936B, 120 Hz), main-exp 8.19.0 (4532), same wallet. Each run was a cold start, then a biometric unlock, then 20 s on WalletView.
Caveat: total JS-thread busy time over the 10 s after unlock is noisy run to run (before 3.38–3.66 s, after 2.67–3.81 s). With this sample size it can't confirm the ~0.5 s saving at the thread level; the function-level profile above is the reliable signal. The worst JS lag after unlock is unchanged (median 568 ms), because other startup work (lazy module loads, Perps and Predict preloads) now accounts for it. That work is a separate follow-up. 🤖 Generated with Claude Code |
With only this PR appliedSame device and method as above: Galaxy Z Fold4, main-exp, cold start, then biometric unlock, then 20 s on WalletView. This time the build is the perf-session branch plus only this PR's commit (
🤖 Generated with Claude Code |
Use @metamask/native-utils getPublicKeyEd25519, the same synchronous native library shimPerf.js uses for secp256k1, for the public key. Signing stays on react-native-quick-crypto because native-utils has no ed25519 signing. Each native call now falls back to JS on its own, so a failure in one library doesn't turn off the other. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
After moving the public key to
|
| Baseline | This PR, quick-crypto only (run 41836379965) | This PR, native-utils key + quick-crypto signature | |
|---|---|---|---|
JS time in relay-auth's ed25519 (wNAF / getPrecomputes / multiply) |
median 505 ms | 0 ms (4 of 4 unlocks) | 0 ms (4 of 4 unlocks) |
- No curve frames from relay-auth in any profile.
- The one relay-auth sample seen (11 ms, once) is
ht, an encoding helper the shim reuses on purpose for the JWT format. @metamask/native-utilsdoesn't show up at all, because its call finishes faster than one 10 ms sample.- WalletConnect core still runs (
@walletconnect/coreframes), so the native path ran and didn't fall back to JS. A fallback would cost the ~250 ms precompute again.
🤖 Generated with Claude Code
…ask#38837) ## **Description** <!-- mms-check: type=text required=true --> **Problem.** Every unlock blocks the Android main thread for about 400 ms, even for users who never use Lighter. `LighterSignerWebView` mounts as soon as the wallet unlocks and passes `wasm-wrapper.standalone.html` (10.3 MB, the Go/WASM signer as base64) as `source.html`. **Evidence.** An always-on perf session ran on a Galaxy Z Fold4 with the exp build 8.19.0 (4532). About 2.5 s after `WalletView` first appeared, it recorded two UI-thread stalls, both inside `RNCWebViewManager.onAfterUpdateTransaction` ← `ViewManager.createViewInstance` (Fabric `preallocateView` / `createView`): - 145 ms in `ReadableNativeMap.importValues`: copying the 10 MB prop across JNI. - 259 ms in `WebView.loadDataWithBaseURL`: loading the inline document on the main thread. The only other inline-HTML WebView in `Root` is `SnapsExecutionWebView`, and it mounts before Engine init, not at unlock. **Fix.** Mount the signer page only when a Lighter call needs it: - `lighterSignerBridge` now records a request (`requestLighterSigner`) when client setup starts or a WASM call is made. `LighterSignerWebView` subscribes to it with `useSyncExternalStore`, and mounts only when the wallet is unlocked **and** a request exists. - Callers already wait behind the bridge's readiness promise (90 s deadline), so the first call queues until the page reports `ready`. Client setup requests the page before reading the keychain, so both happen in parallel. - Key discovery (`getStoredKeyIndices`, `getRecoverableKeyIndices`) doesn't need the page, so it doesn't trigger a load. - Locking still unmounts the page, and now also forgets the request. The next unlock waits for the next call. The security properties are unchanged: same `https://localhost` origin, navigation filter, file-access flags, message validation and lock lifecycle. Only the moment the page mounts changes. **Risk.** The first Lighter call in a session waits for the page to load (hundreds of ms to a few seconds on low-end devices), which used to happen at unlock. Users who never use Lighter never pay it. **Follow-up (not in this PR).** The 10 MB document is still inlined into the JS bundle and copied over JNI when it does mount. Shipping it as a native asset and loading it by URL would remove both the copy and the bundle weight. That needs care with the origin and `onShouldStartLoadWithRequest`, so it's left for a separate change. **Verification.** Measured with the perf session on a Galaxy Z Fold4 over 4–5 cold unlocks per build. Main-thread stalls with the Lighter WebView on the stack went from a median of 323 ms per unlock to 0 ms, both [with MetaMask#38839](MetaMask#38837 (comment)) and [with only this PR applied](MetaMask#38837 (comment)). The test wallet uses Hyperliquid, so for Lighter users the cost moves to their first trading action rather than disappearing. ## **Changelog** <!-- mms-check: type=changelog required=true blocking=true --> CHANGELOG entry: Improved unlock responsiveness on Android by loading the Lighter signer only when it is needed ## **Related issues** <!-- mms-check: type=issue-link required=true --> Refs: MetaMask#38554 (perf session POC that found this) ## **Manual testing steps** <!-- mms-check: type=manual-testing required=true --> ```gherkin Feature: Lighter signer loads on demand Scenario: unlock without using Lighter Given a build with MM_PERPS_LIGHTER_PROVIDER_ENABLED=true When user unlocks the wallet and stays on the wallet home Then no hidden Lighter WebView is created (no lighter-signer-webview in the view tree) And no loadDataWithBaseURL stall appears at unlock Scenario: first Lighter action Given the wallet is unlocked and Lighter has not been used yet When user starts a Lighter flow that needs the signer (client setup / placing an order) Then the signer page loads and the action completes Scenario: lock and unlock Given the signer page is loaded When user locks and unlocks the wallet Then the page is gone after lock and only loads again on the next Lighter action ``` ## **Screenshots/Recordings** <!-- mms-check: type=screenshot required=true --> ### **Before** N/A (no UI change). Perf-session evidence above; before/after numbers are in the comments linked under Verification. ### **After** N/A (no UI change). ## **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 - Ideally on a mid-range device; emulator is acceptable - [ ] 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 - [ ] 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** - [ ] 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. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes wallet-lock coordination and when the key-holding WebView mounts, but signing semantics and isolation are unchanged; the main product risk is first-use latency for Lighter users. > > **Overview** > **Defers loading the ~10 MB Lighter WASM WebView** so it no longer mounts on every wallet unlock (which blocked the Android main thread for hundreds of ms). The hidden signer page now mounts only when the wallet is unlocked **and** a bridge call actually needs it. > > The bridge gains a small **demand signal** (`requestLighterSigner` / `clearLighterSignerRequest` + `useSyncExternalStore` in `LighterSignerWebView`). **`createClient`** and **`execute`** set the request before keychain read / WASM work; **key discovery** does not. Pending calls still wait on the existing readiness promise, so the first Lighter action pays the load cost instead of unlock. > > **Lock handling** moves partly to the always-mounted host: on `KeyringController:lock` it clears the demand flag and marks the bridge unavailable even when no WebView is mounted; on unlock it revives the bridge without reloading until the next request. Tests add a **lazy mounting** suite and adjust lock/unlock expectations (e.g. batched lock+unlock no longer auto-remounts the page). > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 91feb61. 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.5 <noreply@anthropic.com> Co-authored-by: Cursor <cursoragent@cursor.com>
Manual test evidence: iOS simulator + Galaxy Z Fold4Tested head
Cold first call: relay-auth JS vs native shim (
|
| Device | relay-auth JS | Native shim | Same JWT |
|---|---|---|---|
| Fold4, fresh process before unlock | 559.2 ms (550.6 + 8.6) | 8.1 ms (0.7 + 7.4) | yes |
| iOS simulator, same process | 329.3 ms (320.2 + 9.1) | 96.6 ms (6.9 + 89.7) | yes |
Steady state on the Fold4: native signJWT ≈ 0.9 ms vs ≈ 7 ms warm JS; native generateKeyPair ≈ 0.1 ms.
The JS curve is never touched on unlock. After unlocking with saved WalletConnect sessions (WC init, getClientId and a relay connect with signJWT all done), the first call into relay-auth's JS generateKeyPair still paid the full precompute: 447 ms then 2.4 ms on the Fold4 after a real kill and reopen, and 310.7 ms then 1.7 ms on iOS after a JS reload.
iOS checks (skulk session 20261106-164654-868c)
| Check | Verdict | Evidence |
|---|---|---|
| Shim bundled, native path active | PASS | Metro's module table: the shim (7846) next to the real relay-auth (7847). Every importer (@walletconnect/core, utils, and the copies nested under @reown/walletkit) depends on the shim; only the shim imports the real package. |
| Native output byte-identical to JS on device | PASS | 5 fixed seeds: public key, secret key and full JWT identical; verifyJWT accepts each native JWT. Real OpenSSL and native-utils, not Jest mocks. |
| Pair a new dApp over WC v2 | PASS | The app opened wss://relay.walletconnect.org?auth=<JWT> and the relay accepted it; the dApp got session.approved. |
| Signing request reaches the wallet | PASS | The personal_sign sheet showed the exact message; Cancel sent 4001 User rejected the request. back to the dApp. |
| Kill + relaunch + unlock keeps the session | UNVERIFIED | skulk's relaunch deletes persistStore, mmkv and AsyncStorage before launch (fresh fixture wallet), so the harness wiped the session. Covered on Android. |
| JS reload with a saved session: requests reach the UI | UNVERIFIED | The relay reconnected and both requests reached WalletKit, but the reload re-read skulk's fixture state, which dropped the dApp's permission. Harness, not the PR. Covered on Android. |
| Unlock with saved sessions reconnects using native only | PASS | A new relay socket was accepted after unlock, sessions were restored, the native flag stayed on, the JS curve was still cold, and a dApp request arrived. |
Android checks (Fold4, Metro from the PR branch)
MetaMask sets FLAG_SECURE on Android, so screenshots are blocked. Evidence is the app's own state read over Metro's CDP inspector, plus the test dApp's log.
| Check | Result | Evidence |
|---|---|---|
| Shim wired into every caller | PASS | All four WC importers resolve to the shim; native flag on. |
| Pair a new dApp | PASS | wallet_requestPermissions approval shown; after Connect the dApp got session.approved; relay connected. |
| Signing request reaches the wallet | PASS | A personal_sign approval appeared; Cancel sent 4001 back to the dApp. |
| Kill, reopen, unlock with a saved session | PASS | am force-stop, cold launch (new pid), WC not initialized before unlock. After unlock: relay reconnected in 6.7 s, session restored, native flag on, JS curve still cold (447 ms → 2.4 ms). |
| Requests still arrive after reopen | PASS | A new personal_sign surfaced as an approval; Cancel sent 4001 back. |
| Native output byte-identical to JS | PASS | 5 seeds identical; verifyJWT true. |
The test dApp was a Node script using @walletconnect/sign-client on the public relay. Every signature was rejected, never approved.
Notes for the author
- "Every user pays it, with or without a WalletConnect connection" doesn't seem to hold for
signJWTon core 2.23.4.Relayer.transportOpen()returns early with "Starting WS connection skipped because the client has no topics to work with." On a wallet with no pairings, WalletConnect was initialized after unlock withconnected: false, 0 topics and no relay socket. SosignJWTat unlock only runs for wallets with a pairing or session. I didn't establish whethergetClientId(→generateKeyPair) still runs at unlock without topics: the app builds the core withnew Core(), notCore.init(), which is what callsgetClientId. Worth tightening the description, or confirming with a profile on a wallet with no sessions. - No fallback seen.
isNativeEd25519ActiveForTests()stayedtrueon both platforms through every pairing, signature and reconnect. - quick-crypto first-call cost. The first native
signJWTin a process took 89.7 ms on the iOS simulator and 7.4 ms on the Fold4; later calls take under 1 ms. Still a clear net win, but worth checking on real iOS hardware.
Caveats
- Both platforms ran CI's dev client from
main(run 42229069816) with this PR's JS from Metro. The PR has no native changes, and the native libraries it calls already ship in that client. - The Android bundle came from a local worktree whose
node_modulesbelongs to another checkout. The packages this change touches match the PR's lockfile:@walletconnect/core2.23.4, relay-auth 1.1.0,@metamask/native-utils0.8.0,react-native-quick-crypto1.1.9. The iOS bundle used skulk's own clean install of the PR (bundle6f610e4c…). - In-app reads used
eval/ CDPRuntime.evaluate; skulk's ledger records them (20 evals, no mock rules or flag overrides).
…shim The shim and its test import the copy of relay-auth that @walletconnect/core resolves, on purpose, so the shim follows core's version. Declaring it as a direct dependency could pin a different copy. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…gning key - Report the first fallback of each native call through Logger.error (Sentry), so a broken native library doesn't silently bring back the ~500 ms of JS ed25519. The report carries the call name only, no key material. - Send a secret key of the wrong length to the JS implementation without turning native signing off for the session, like generateKeyPair already does for the seed. - Test that the lockfile holds a single @walletconnect/relay-auth, which is what lets the shim wrap the same copy @walletconnect/core uses, and reword the comment that claimed it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|



Description
Problem. WalletConnect signs a relay auth JWT every time its relayer connects. That happens in
core.crypto.signJWT, called fromrelayer.createProviderat unlock, on foreground and on network changes. It also derives the client's public key ingetClientId. Both go through@walletconnect/relay-auth, which bundles a pure-JS ed25519 (@noble/curves). On Hermes the first call in a process costs about half a second of JS thread: it builds precompute tables, then runs two scalar multiplications.Who pays it: every wallet with a WalletConnect pairing or session.
Relayer.init()in@walletconnect/core2.23.4 ends withthis.transportOpen()→createProvider()→core.crypto.signJWT().transportOpen()returns early when the subscriber has no topics ("Starting WS connection skipped because the client has no topics to work with."), so the relay connect and its JWT only happen for wallets that have one.WC2Manager.initruns at every unlock (initializeSDKServices,app/store/sagas/index.ts:83), so those wallets pay the ~500 ms on the JS thread at every unlock, and again when the network comes back (subscribeToNetworkChange→transportOpen). A wallet that has never connected to a dApp skips the relay connect at unlock. Whether it still derives the client key at unlock (getClientId→generateKeyPair) is not established: the app builds the core withnew Core(), andCore.init()is what callsgetClientId.Evidence. From the always-on perf session (#38554) on a Galaxy Z Fold4 at 120 Hz, exp build 8.19.0 (4532), right after unlock: JS lag was 928 ms with the JS thread at 85.7%. The Hermes profile covering that moment (symbolicated with the build's source map) has this hottest path:
Fix. Metro resolves
@walletconnect/relay-authtoapp/shims/walletconnect-relay-auth.ts. That shim re-exports the package unchanged and replaces only two functions,generateKeyPairandsignJWT, with native libraries the app already ships:getPublicKeyEd25519(seed)from@metamask/native-utils, the same synchronous Nitro libraryshimPerf.jsalready uses for secp256k1 (seedocs/performance/native-crypto.md).new Ed('ed25519').signSync(data, seed)fromreact-native-quick-crypto(OpenSSL).@metamask/native-utils0.8.0 has no ed25519 signing. If it gains one, this can move there too.Logger.error(Sentry, tagoperation:relay_auth_native_ed25519) with the call name only, so a broken native library shows up instead of silently costing the ~500 ms again. A secret key of the wrong length goes to JS without turning native signing off.The JWT header, payload and encoding still come from relay-auth's own helpers (
encodeIss,encodeData,encodeJWT). ed25519 is deterministic, so keys and JWTs are byte-identical to the JS implementation.Why a Metro shim and not a patch, or a
shimPerf.js-style mutation. relay-auth pins@noble/curves1.8.0 exactly, while the app uses 1.9.7. So mutating the app's@noble/curvesthe wayshimPerf.jsdoes would never reach relay-auth's copy: that's the single-copy invariant indocs/performance/native-crypto.md. relay-auth's dist is also a minified bundle that inlines noble, so patching it would be fragile. The redirect follows the existingreact-native-safe-area-contextshim pattern inmetro.config.js. The shim imports the copy of relay-auth that core resolves, so it follows core's version. Jest doesn't remap the package, so unit tests keep using the real JS implementation.Risks.
verifyJWTon the shim's output. They back quick-crypto with Node's OpenSSL ed25519.EdKeyPairandKeyObjectHandleare registered on both iOS and Android (OpenSSL 3.6.2 on both).Follow-up, not in this PR. Defer
WC2Manager.init(app/store/sagas/index.ts:83,initializeSDKServices) until after the homepage's first content. The relayer connect would then leave the unlock path entirely.Changelog
CHANGELOG entry: Improved app responsiveness right after unlock by signing WalletConnect relay authentication natively
Related issues
Refs: #38554 (perf session that found it)
Manual testing steps
Verification: before/after over cold unlocks on a device is in the PR comments: relay-auth JS time went from a median of 505 ms to 0 ms. A run with only this change applied is in progress.
Manual test evidence on an iOS simulator and a Galaxy Z Fold4 (pairing, signing requests, kill + reopen + unlock with a saved session, on-device equivalence and cold timings: 559 ms JS vs 8 ms native on the Fold4): #38839 (comment)
Screenshots/Recordings
N/A: no UI change. The before/after Hermes profiles will be attached in the verification comment.
Before
N/A
After
N/A
Pre-merge author checklist
Performance checks (if applicable)
trace()for usage andaddTokenfor an exampleFor performance guidelines and tooling, see the Performance Guide.
Pre-merge reviewer checklist
🤖 Generated with Claude Code
Note
Medium Risk
Touches cryptographic signing for WalletConnect relayers; correctness and native dependency availability need vigilance though JS fallbacks exist.
Overview
Adds a Metro redirect so WalletConnect loads
app/shims/walletconnect-relay-auth.ts, which wraps@walletconnect/relay-authto derive keys and sign relay-auth JWTs with@metamask/native-utilsandreact-native-quick-crypto, falling back to the bundled JS implementation per native call on error while re-exporting the rest of relay-auth.The companion Jest suite asserts byte-for-byte parity with the JS path, exercises every fallback scenario, and guards that only one lockfile copy exists;
.depcheckrc.ymlnow whitelists@walletconnect/relay-authbecause the shim imports that transitive package directly.Reviewed by Cursor Bugbot for commit 9375cbd. Bugbot is set up for automated code reviews on this repo. Configure here.