@qntx/wallet-engine 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +1057 -20
  2. package/dist/apps-fiat24.d.mts +202 -0
  3. package/dist/apps-fiat24.mjs +1378 -0
  4. package/dist/apps-fiat24.mjs.map +1 -0
  5. package/dist/apps-hyperliquid.d.mts +549 -0
  6. package/dist/apps-hyperliquid.mjs +2742 -0
  7. package/dist/apps-hyperliquid.mjs.map +1 -0
  8. package/dist/apps-polymarket.d.mts +729 -0
  9. package/dist/apps-polymarket.mjs +3786 -0
  10. package/dist/apps-polymarket.mjs.map +1 -0
  11. package/dist/apps.d.mts +136 -0
  12. package/dist/apps.mjs +535 -0
  13. package/dist/apps.mjs.map +1 -0
  14. package/dist/connect-BY1C5ZRI.mjs +210 -0
  15. package/dist/connect-BY1C5ZRI.mjs.map +1 -0
  16. package/dist/connect.d.mts +17 -9
  17. package/dist/connect.mjs +3 -185
  18. package/dist/controller-DpNVHVsj.d.mts +2295 -0
  19. package/dist/controller-rMnaxKAH.mjs +46 -0
  20. package/dist/controller-rMnaxKAH.mjs.map +1 -0
  21. package/dist/decimal-COJ4g8qy.mjs +38 -0
  22. package/dist/decimal-COJ4g8qy.mjs.map +1 -0
  23. package/dist/eligibility-BfM9ybYZ.mjs +48 -0
  24. package/dist/eligibility-BfM9ybYZ.mjs.map +1 -0
  25. package/dist/engine-Dic_kkEr.d.mts +1829 -0
  26. package/dist/errors-B8W-hoYW.d.mts +7 -0
  27. package/dist/errors-horUy5k1.mjs +24 -0
  28. package/dist/errors-horUy5k1.mjs.map +1 -0
  29. package/dist/gateway-contract.d.mts +3 -362
  30. package/dist/gateway-contract.mjs +1531 -81
  31. package/dist/gateway-contract.mjs.map +1 -1
  32. package/dist/idb.d.mts +5 -0
  33. package/dist/idb.mjs +122 -46
  34. package/dist/idb.mjs.map +1 -1
  35. package/dist/index-vBgfOFIh.d.mts +2227 -0
  36. package/dist/index.d.mts +58 -515
  37. package/dist/index.mjs +22314 -4901
  38. package/dist/index.mjs.map +1 -1
  39. package/dist/json-BDwV38cj.mjs +15 -0
  40. package/dist/json-BDwV38cj.mjs.map +1 -0
  41. package/dist/link-Ceq8Dggp.mjs +139 -0
  42. package/dist/link-Ceq8Dggp.mjs.map +1 -0
  43. package/dist/primitives-DbSHLZKq.mjs +31 -0
  44. package/dist/primitives-DbSHLZKq.mjs.map +1 -0
  45. package/dist/push-message-AQuzoNFY.d.mts +84 -0
  46. package/dist/push-message-kbnH1A5w.mjs +142 -0
  47. package/dist/push-message-kbnH1A5w.mjs.map +1 -0
  48. package/dist/push.d.mts +13 -0
  49. package/dist/push.mjs +70 -0
  50. package/dist/push.mjs.map +1 -0
  51. package/dist/qr.d.mts +292 -0
  52. package/dist/qr.mjs +1725 -0
  53. package/dist/qr.mjs.map +1 -0
  54. package/dist/registry-CbtwcxkX.mjs +374 -0
  55. package/dist/registry-CbtwcxkX.mjs.map +1 -0
  56. package/dist/risk-DyABgg4W.mjs +757 -0
  57. package/dist/risk-DyABgg4W.mjs.map +1 -0
  58. package/dist/session-CNJFLarP.mjs +18 -0
  59. package/dist/session-CNJFLarP.mjs.map +1 -0
  60. package/dist/socket-ChG9JRT_.mjs +110 -0
  61. package/dist/socket-ChG9JRT_.mjs.map +1 -0
  62. package/dist/spi-BrTw5s98.d.mts +3 -0
  63. package/dist/timer-Cdk5rGM2.mjs +43 -0
  64. package/dist/timer-Cdk5rGM2.mjs.map +1 -0
  65. package/dist/types-BpvioFGo.d.mts +258 -0
  66. package/dist/types-DbftVZ3I.mjs +90 -0
  67. package/dist/types-DbftVZ3I.mjs.map +1 -0
  68. package/dist/walletconnect.d.mts +86 -0
  69. package/dist/walletconnect.mjs +1507 -0
  70. package/dist/walletconnect.mjs.map +1 -0
  71. package/dist/webln-BgrtPXpG.mjs +2593 -0
  72. package/dist/webln-BgrtPXpG.mjs.map +1 -0
  73. package/dist/webln-Bllk_xJ2.d.mts +666 -0
  74. package/package.json +94 -19
  75. package/dist/connect.mjs.map +0 -1
  76. package/dist/errors-DpkJneDe.d.mts +0 -1696
  77. package/dist/registry-Deo5WQe1.d.mts +0 -25
  78. package/dist/registry-wYrcuFNc.mjs +0 -99
  79. package/dist/registry-wYrcuFNc.mjs.map +0 -1
  80. package/dist/webln-DzsI7jVb.mjs +0 -3629
  81. package/dist/webln-DzsI7jVb.mjs.map +0 -1
package/README.md CHANGED
@@ -2,30 +2,40 @@
2
2
 
3
3
  App-side controllers over a [`@qntx/wallet`](https://www.npmjs.com/package/@qntx/wallet) `Wallet`:
4
4
  the account tree, Spark payments, zaps, encrypted metadata sync and cloud backup. Controllers
5
- expose Zustand stores; every I/O dependency (`fetch`, randomness, clock, storage, relays, cloud)
6
- is injected. The engine never holds signing keys — every wallet-owned outflow goes through the
7
- enclave's per-operation approval.
5
+ expose read-only Zustand stores; every I/O dependency (`fetch`, randomness, clock, storage,
6
+ relays, cloud) is injected. The engine never holds signing keys — every wallet-owned outflow goes
7
+ through the enclave's per-operation approval.
8
8
 
9
- Peer dependencies: the exact `@qntx/wallet` release, `@qntx/spark` `^0.5.0` and
10
- `@qntx/nostr` `^0.15.0`.
9
+ Peer dependencies: `@qntx/wallet` (the exact release — engine and wallet must agree on the
10
+ protocol), `@qntx/wallet-chains` (exact), `@qntx/spark` and `@qntx/nostr`. The exact ranges are
11
+ this package's `peerDependencies`.
11
12
 
12
13
  ```bash
13
- npm install @qntx/wallet-engine @qntx/wallet @qntx/wallet-worker @qntx/spark @qntx/nostr
14
+ npm install @qntx/wallet-engine @qntx/wallet @qntx/wallet-worker @qntx/wallet-chains @qntx/spark @qntx/nostr
14
15
  ```
15
16
 
16
17
  ```ts
18
+ import { verifyEvent } from "@qntx/nostr";
19
+ import type { Wallet } from "@qntx/wallet";
17
20
  import { createWalletEngine } from "@qntx/wallet-engine";
18
21
  // in-app-browser provider injection and the WebView bridge:
19
22
  import { injectedScript, createBrowserBridge } from "@qntx/wallet-engine/connect";
20
- import { openIndexedDbEngineStore } from "@qntx/wallet-engine/idb";
23
+ import { openIndexedDbEngineStore, openIndexedDbPublicStore } from "@qntx/wallet-engine/idb";
24
+
25
+ // From your wallet setup — createWebWallet / createNodeWallet / createNativeWallet.
26
+ declare const wallet: Wallet;
27
+ declare const showCallsSheet: (origin: string, txIds: ReadonlyArray<string>) => void;
21
28
 
22
29
  const random = (n: number) => crypto.getRandomValues(new Uint8Array(n));
23
30
  const engine = createWalletEngine({
24
31
  wallet, // from createWebWallet / createNodeWallet / createNativeWallet
32
+ verifyEvent, // the host's native verifier, the same one given to the wallet
25
33
  sparkNetwork: "mainnet",
26
34
  fetch: globalThis.fetch.bind(globalThis),
27
35
  random,
28
36
  now: () => Date.now(),
37
+ weblnAlias: "Example",
38
+ lightningMaxFee: (amountSats) => Math.max(10, Math.floor(amountSats / 100)),
29
39
  logger: { warn: (message, error) => console.warn(message, error) },
30
40
  openStore: async () =>
31
41
  openIndexedDbEngineStore({
@@ -33,28 +43,1042 @@ const engine = createWalletEngine({
33
43
  dataKey: await wallet.dataKeys.get("wallet-db"),
34
44
  random,
35
45
  }),
46
+ showCallsStatus: ({ origin, txIds }) => showCallsSheet(origin, txIds),
47
+ publicStore: await openIndexedDbPublicStore({ name: "app-public" }),
36
48
  });
37
49
  ```
38
50
 
51
+ `EngineOptions.gateway: { url }` is the wallet gateway: tried first for RPC and Esplora on the
52
+ networks it serves, and the only source of prices, swap and bridge quotes and EVM history. The
53
+ engine sends it a fresh `x-client-id` per session and per scope.
54
+
39
55
  The engine follows the wallet's lock state: unlocking opens the encrypted `EngineStore` and starts
40
- the selected account group; locking flushes pending writes, closes every Spark client and clears
41
- in-memory state.
56
+ the selected account group; locking flushes pending writes, closes every Spark client, stops
57
+ polling, and ignores late results from the old session. Transaction and request state stays
58
+ readable until the next unlock reloads it.
42
59
 
43
60
  ## Surface
44
61
 
45
- - `engine.accounts` — `AccountTreeController`: wallets and account groups, selection, names,
62
+ Each controller member is a `HostController<…>` facade: the host methods listed for it plus a
63
+ read-only `store` (`getState`, `getInitialState`, `subscribe` — use it with zustand's `useStore`).
64
+ Lifecycle, wiring between controllers and `setState` stay inside the engine. Name a member's type
65
+ as `WalletEngine["spark"]`; every type in these signatures (`AccountRef`, `TrackedTransaction`,
66
+ `PrepareParams`, `RequestResult`, the request displays, `SparkTokenBalance`, …) is exported from
67
+ the package root.
68
+
69
+ - `engine.networks` — configured chain networks (`enabled`, `info`, `endpoints`), their read
70
+ clients (`client`, `solanaRpc`, `esplora`) and custom RPC endpoints (`addRpc`).
71
+ - `engine.assets` — token and balance reads per account. A Bitcoin balance counts outputs
72
+ protected as possible inscription or rune carriers in `protected`, apart from `native`; user
73
+ freezes are not part of the balance (a frozen coin still counts in `native`).
74
+ - `engine.prices` — fiat spot prices and valuations, display-only.
75
+ `setVisible` gates polling on app visibility; `setCurrency` switches the persisted quote
76
+ currency and refetches.
77
+ - `engine.portfolio` — `portfolio.group({ walletId, groupIndex })` values one account group:
78
+ a `Valuation` with an exact decimal `total`, a `stale` flag and the `unpriced` holding count.
79
+ - `engine.transactions` — tracked transactions (`store`, `txById`) and coin control; it builds,
80
+ signs and records nothing itself — sends, replacements and dApp signatures go through
81
+ `requests`. A broadcast whose outcome is unknown resolves `submitted` and the engine
82
+ rebroadcasts the same signed bytes — never re-send it. Inclusion is not finality: a
83
+ transaction in a block carries `block` (hash and height — EVM block number, Bitcoin height,
84
+ Solana slot) and stays tracked at a low frequency until `final` — EVM `finalized` tag, six
85
+ Bitcoin confirmations, Solana `finalized` commitment. A reorg returns it to `submitted`
86
+ (polling and rebroadcast resume) and a `final` transaction is never polled again. Coin
87
+ control: `setUtxosFrozen` / `frozenUtxos` persist per-account freezes, and `inputs` on a
88
+ send picks the outpoints (naming a UTXO protected as a possible inscription carrier is the
89
+ opt-in to spend it).
90
+ - `engine.requests` — every wallet-owned outflow becomes a request here (`prepare`, `approve`,
91
+ `reject`, `outcome`, the sign log).
92
+ `approve(id, method, { verify, acknowledged })` — `requiredAcknowledgement(request)` returns
93
+ the `danger` findings and checks the host must have shown; approving without them throws
94
+ `AcknowledgementRequiredError`. If a re-simulation changes the outcome at approval it throws
95
+ `SimulationChangedError` and the request stays approvable. A blind request throws
96
+ `BlindSigningDisabledError` — enable `wallet.vault.setBlindSigning` and approve it again.
97
+ Every recipient a decoded intent names — outflows, the settlement terms
98
+ (`minimumReceived`, bridge refunds, Hyperliquid deposits, staking withdrawals and
99
+ delegations), typed-data order/consideration/Safe/Hyperliquid destinations and any
100
+ nested calls — is assessed against the contacts and paid history, except the signer
101
+ itself: an unseen recipient warns `first-recipient`, a lookalike of a known address
102
+ raises `address-poisoning`.
103
+ - `engine.history` — one newest-first activity list per account group
104
+ (state keyed `${walletId}:${groupIndex}`). `load`/`loadMore` page backwards while `hasMore`;
105
+ entries carry `verified`, `origin` and `flags`; `truncated` lists the networks whose provider
106
+ left unpagable gaps.
107
+ - `engine.approvals` — the standing-authority inventory (`load`, `unload`, `refresh`,
108
+ `setVisible`, `exposure`) and revocations (`revoke`, `revokeBatch`); see
109
+ [Approvals](#approvals).
110
+ - `engine.nfts` — an owner's NFT inventory on one network from the gateway (`load`/`loadMore`
111
+ page it, `refresh` re-reads the loaded pages, `detail`/`collection`/`floor` answer one item,
112
+ collection or its marketplace floors). Inventory data is display-only — a send never builds
113
+ from it. Media are `NftMedia` descriptors with an `active` flag: render them as images or in a
114
+ sandbox that runs no script, never as documents. Flagged items (`spam` non-empty) are `hidden`
115
+ by default; `setHidden(network, id, "hidden" | "shown" | undefined)` persists the override.
116
+ `inscriptions(group, network)` lists the Bitcoin UTXOs the spend path already protects as
117
+ possible inscription carriers — read-only. NFT sends go through `requests`: `evm-nft-send`
118
+ takes `{ contract, items: [{ tokenId, amount? }], to }` — one entry for ERC-721, up to
119
+ `EVM_BATCH_LIMIT` distinct ids for one ERC-1155 batch — and `solana-nft-send` takes
120
+ `{ asset, to }` where `asset` is a Metaplex Core asset or an SPL NFT mint. Preparation
121
+ re-reads ownership from chain and a refusal throws `NftTransferError` with a `reason`
122
+ (`not-nft`, `not-owned`, `insufficient-balance`, `programmable`, `frozen`, `not-found`).
123
+ - `engine.addressBook` — contacts, synced through `metaSync`.
124
+ - `engine.connections` — dApp sessions and trusted origins; pass it to `createBrowserBridge`
125
+ (`checkOrigin`, `invalidateOrigin`).
126
+ - `engine.eip1193`, `engine.nip07`, `engine.webln`, `engine.solanaWallet`,
127
+ `engine.bitcoinWallet`, `engine.tronWallet` — the injected provider handlers for each wallet
128
+ standard (`handle`, and `subscribe` where the standard has events).
129
+ - `engine.phishing` — the phishing list (`check`, `sync`, `trust`, `untrust`); its lifecycle is
130
+ independent of the lock state.
131
+ - `engine.spark` — Spark reads and receives, with token balances (`SparkAccountState.tokens`); it
132
+ has no send method — every payment, token sends included, goes through `requests`. Token sends
133
+ are `pay` with `token` and resolve `"token"`. Every payment is recorded before it is sent; a
134
+ `pending` result carries that record (`SparkPaymentRecord`) when the commit response was lost —
135
+ show it in flight, never failed, and never pay again. The engine reconciles open records against
136
+ the Spark operator (after unlock, then on a backed-off poll) and lists them in
137
+ `SparkAccountState.payments` and in `engine.history` until they settle or fail. Cooperative
138
+ exits take `amountSats` (what arrives at the Bitcoin address, the debit adds the quoted fee)
139
+ and require `maxFeeSats`.
140
+ - `engine.accounts` — wallets and account groups, selection, names,
46
141
  hidden groups, Spark group discovery and social identity bindings.
47
- - `engine.spark` — `SparkController`: balances, history, sends, Lightning receives and
48
- cooperative exits for the selected group.
49
- - `engine.payments` — `parse` (pure, never throws), `resolve` (LNURL lookups) and `pay`, which
50
- routes a parsed option to Spark, Lightning or a Bitcoin withdrawal after validation and before
51
- approval. Typed `PayResult` per payment kind.
52
- - `engine.zaps` — `prepare` signs the NIP-57 request with any `NostrSigner` and fetches the
53
- invoice; `pay` pays it from the built-in Spark wallet. External wallets may pay
54
- `prepared.invoice` themselves and validate the receipt against `receiptPubkey`.
142
+ - `engine.watch` — watch-only accounts: `add`, `rename`, `remove`, `list` and per-network
143
+ `assets`.
55
144
  - `engine.metaSync` — NIP-78 (kind 30078) metadata documents, NIP-44 encrypted to the wallet's
56
- group-0 Nostr identity; pull before publish, per-entry last-writer-wins.
57
- - `engine.backup` — `BackupController` over an injected `CloudStore`.
145
+ group-0 Nostr identity; pull before publish. Merge is not plain per-entry LWW: a record's
146
+ identity is immutable, deletes are terminal, and remote stamps too far in the future are
147
+ refused.
148
+ - `engine.backup` — cloud backup over an injected `CloudStore`. The backup password is
149
+ Argon2id-stretched, needs at least 12 characters and must reach zxcvbn's top score — rate a
150
+ draft with `backupPasswordStrength(password)`, a refused one throws `weak-password`. A
151
+ restore adopts the file's backup key only on a React Native kernel passkey restore; every
152
+ other restore leaves backup off until it is enabled again.
153
+ - `engine.zaps` — `prepare` only: signs the NIP-57 request with any `NostrSigner` and fetches the
154
+ invoice; the invoice itself is paid through `requests` like any other outflow.
155
+ - `engine.names` — `resolve` forward-resolves an ENS name for a send on a network.
156
+ - `engine.delegation` — an account's EIP-7702 delegation state on a network.
157
+ - `engine.bridges` — gateway Across bridge `quote`/`status`, display-only; `quote` requires
158
+ `maxFeeBps`, the relay-fee ceiling in basis points of the input amount.
159
+ - `engine.keys` — imported single private keys held in the vault; passthrough to `wallet.keys`.
160
+ - `engine.swaps` — gateway swap quotes (0x on EVM, Jupiter on Solana), display-only.
161
+ - `engine.lido` — Lido liquid staking on Ethereum mainnet: stETH position and withdrawal
162
+ requests.
163
+ - `engine.staking` — Solana stake positions and the current validator set.
164
+ - `engine.payments` — `parse` (pure, never throws), `resolve` (LNURL lookups) and
165
+ `withdrawLnurl`.
166
+ - `engine.unsubscribe` — stops listening to the wallet and the phishing-list refresh.
167
+
168
+ Transaction tracking: a send whose outcome is unknown is never declared `dropped` by a timer.
169
+ On EVM a transaction ends on its own receipt, on its nonce being consumed without its receipt
170
+ (cross-checked against the host endpoint), or on a replacement; on Bitcoin only on inclusion or
171
+ on one of its inputs being spent by another confirmed transaction. When no endpoint has known a
172
+ transaction for thirty minutes the row turns `stuck: true` — still `submitted`, still holding its
173
+ nonce or inputs, polled at the finality interval — and the host should offer `speed-up` /
174
+ `cancel`. A row recovered from a broadcast whose outcome never settled carries
175
+ `rebroadcast: false`: watched, never resent. TRON and Solana keep proof-based expiry (chain
176
+ expiration, blockhash / durable-nonce validity), and neither trusts one upstream's word for an
177
+ absence: every read of a poll is pinned to a single upstream (the gateway is pinned to one
178
+ provider once it answers), and `dropped` is reached only when a configured host endpoint's own
179
+ pinned client proves the same drop, or — without one — after three consecutive matching polls.
180
+ On Solana the streak must span more than one blockhash processing age (~60 seconds): a
181
+ blockhash transaction is `dropped` only when its blockhash is past its last valid height, the
182
+ status ledger holds no entry, and the status bank is no older than the reads that expired it;
183
+ a durable-nonce transaction only when the nonce account has provably moved past the submitted
184
+ nonce (a status bank behind the nonce read proves nothing) and the account's signature
185
+ history covers the window since submission without listing the transaction — a trimmed
186
+ ledger can make a landed send read absent.
187
+
188
+ Chain binding on the gateway path: when the gateway serves a TRON or Solana network, the value
189
+ that binds the signed bytes to the chain — TRON's reference block, Solana's recent blockhash —
190
+ must be confirmed by a host endpoint, and the answering node must report the configured
191
+ network's genesis. A gateway-only testnet send is refused rather than signed on one
192
+ party's word — a binding taken from the mainnet would produce a signature valid on the
193
+ mainnet — while a gateway-only mainnet send builds flagged `reads-unverified`: a wrong-chain
194
+ binding makes the signature invalid on the mainnet and nothing of more value can move.
195
+
196
+ L1 data fees on OP Stack and Scroll move with the L1's own fee market, so the `l1Data` amount an
197
+ intent displays is a bound, not the raw oracle read: the read plus three L1 price updates of at
198
+ most ×9/8 (two for the inclusion window, one of review headroom). Approval re-reads the oracle
199
+ before signing, and broadcast re-reads it again whenever the signature took longer than one
200
+ 12 s L1 slot; when the current price outgrows what the shown maximum covers the request ends
201
+ (`the L1 data fee rose — start over`) — the host re-prepares and the user approves the new bound.
202
+
203
+ The engine store from `@qntx/wallet-engine/idb` names rows by a keyed hash of the collection and
204
+ key, authenticates every value it reads back (a row that fails authentication reads as absent),
205
+ and rebuilds a database keyed by another data key empty.
206
+
207
+ ## TRON
208
+
209
+ The engine serves TRON mainnet (`tron:728126428`) and the Shasta (`tron:2494104990`) and Nile
210
+ (`tron:3448148188`) testnets: TRX, TRC-10 and TRC-20 sends, staking operations, TRC-20
211
+ approvals, balances and resources, fiat prices, and history.
212
+
213
+ Host `rpc` entries are full-node HTTP base URLs — the engine appends the `/wallet/*` and
214
+ `/walletsolidity/*` paths itself and reads both heads on the same base:
215
+
216
+ ```text
217
+ createWalletEngine({
218
+ // …
219
+ rpc: {
220
+ "tron:728126428": ["https://api.trongrid.io"],
221
+ "tron:3448148188": ["https://nile.trongrid.io"],
222
+ },
223
+ });
224
+ ```
225
+
226
+ When the gateway serves the network it is tried first (route `POST /v1/tron/:caip2/*`, an
227
+ allow-list of node-API paths plus the TronGrid indexer feeds); every decisive read is still
228
+ cross-checked against a second provider before anything is built or signed, and a
229
+ `reads-unverified` flag marks a prepare whose cross-check could not run. Two reads are binding
230
+ rather than flaggable: the reference block — what binds the signed bytes to the chain — must be
231
+ confirmed by a host endpoint when the gateway serves the network — on a testnet a gateway-only
232
+ TRON send is refused, on a mainnet it proceeds flagged `reads-unverified`; and the answering
233
+ node itself must report the network's genesis block, so a gateway provider on another chain is
234
+ refused before anything is signed.
235
+
236
+ Request methods are `send`, `tron-stake` and `tron-approve`. A TRON `send` takes the token as a
237
+ TRC-10 decimal id or a TRC-20 `T…` address and an optional `memo` (1–256 UTF-8 bytes, no line
238
+ breaks or hidden characters — it becomes `raw_data.data` and costs the chain's flat memo fee,
239
+ quoted as `tronFee.memo`); `tron-stake` carries one action — `freeze`,
240
+ `unfreeze`, `withdraw-expired`, `cancel-unfreeze`, `delegate` (with an optional `lockBlocks`),
241
+ `undelegate`, `vote` or `claim-rewards` — checked against the java-tron actuator rules before
242
+ signing; `tron-approve` builds the TRC-20 `approve` call (amount `0n` revokes). A pending request
243
+ carries `tronFee`, a `TronFeeQuote` with the expected and maximum burn, the bandwidth source
244
+ (`staked`/`free`/`burn`/`activation-staked`/`activation-fee`), energy details for contract
245
+ calls, the activation charge for a first send to an absent account, and warnings
246
+ (`recipient-not-activated`, `token-recipient-empty`).
247
+
248
+ A built TRON request is fresh for 20 seconds before its `expiration`: approve with less left — or
249
+ after the reference block left the solidified chain — and the route rebuilds the same contract on
250
+ a fresh head before signing, never signing stale bytes; a rebuild whose fee bound grows is refused
251
+ instead. DApp-built transactions get no rebuild: under 20 seconds they are refused and the dApp
252
+ must build again.
253
+
254
+ The in-app browser gets the TronLink surface — `window.tron`, `window.tronLink` and
255
+ `window.tronWeb`, installed immutable in the top frame only and announced over TIP-6963.
256
+ `tronWeb` covers what real dApps call: `defaultAddress`, `ready`, `trx.sign`,
257
+ `trx.signMessageV2`, `_signTypedData`/`signTypedData`, `trx.sendRawTransaction`,
258
+ `getBlockByNumber(0)` (the network genesis), `addressChanged` and the node setters as no-ops;
259
+ every other member — `transactionBuilder`, `utils`, `event`, `plugin`, the rest of `trx` — is a
260
+ refusal that rejects with code `4200` rather than a wrong answer, and there are no `isTronLink`
261
+ flags. `trx.sign` on a hex string is refused: a digest is signed with `signMessageV2`, and
262
+ multi-signature is not offered.
263
+
264
+ A dApp transaction is signed only when it can be shown exactly: `raw_data` must bind the session's
265
+ own account as owner, a single modeled contract, `Permission_id` 0, an `expiration` between 20
266
+ seconds and 24 hours out, and a reference block proven on the chain (full node or, within its
267
+ head, the solidity node, cross-checked against the independent endpoint when one is configured);
268
+ the page's `txID` must be sha256 of `raw_data` and a supplied `raw_data` JSON must re-encode to the
269
+ same bytes. The wallet never broadcasts a dApp transaction itself — approve creates a `submitted`
270
+ entry carrying `tron.dappSignature` and no `raw`, so the poll can only observe: when the dApp's
271
+ broadcast lands the entry goes `confirmed`/`final`, and if the head passes `expiration` with no
272
+ inclusion it is `dropped`. `trx.sendRawTransaction` hands the wallet-signed bytes back through
273
+ `submitDappTron` — the signature must match the observed entry's — for the one wallet broadcast.
274
+ `tron_signMessageV2` signs TIP-191 bytes, `tron_signTypedData` a TIP-712 document the page
275
+ supplies as `domain`/`types`/`message`, and `wallet_watchAsset` accepts TRC-20 only.
276
+
277
+ Tracking follows the chain's own rule: the signed bytes bind to the solidified head and stay
278
+ `submitted` — rebroadcast as needed — until the solidified node reports them (solidified
279
+ inclusion is `final`, a failed receipt is `failed`) or its timestamp passes the transaction's
280
+ `expiration`, which is `dropped`. A poll never trusts one upstream's word for an absence: every
281
+ read of a poll is pinned to a single upstream (the gateway is pinned to one provider once it
282
+ answers), and `dropped` or `reorged` is reached only when a configured host endpoint agrees, or
283
+ — without one — after three consecutive matching polls spanning more than one solidification
284
+ period (~57 seconds). Broadcast answers the node does not classify are never guessed: only a
285
+ definite refusal fails a request.
286
+
287
+ History is display-only indexer data: the gateway's TronGrid feeds, verified entry by entry on
288
+ the node (the raw data hash must equal the txid and every claimed leg must decode to the claim)
289
+ — an entry the node contradicts is flagged `chain-mismatch`, one it cannot prove stays
290
+ unverified.
291
+
292
+ Not offered: `AccountPermissionUpdate` (multi-sig/permission changes).
293
+
294
+ ## Approvals
295
+
296
+ `engine.approvals.load(account, network)` returns a view key; `ApprovalsState.views[key]` is one
297
+ `ApprovalsView` — every standing authority the account holds over that network, as rows:
298
+
299
+ - EVM: ERC-20 allowances, Permit2 allowances (amount and expiration), ERC-721 and ERC-1155
300
+ operators, ERC-721 single-token approvals, and the account's own EIP-7702 delegation.
301
+ - Solana: SPL delegates, foreign close authorities, mint freeze authorities and Token-2022
302
+ permanent delegates, and stake account authorities.
303
+ - TRON: TRC-20 allowances and the account's permission keys.
304
+
305
+ Kernel session keys that may sign for the owner are linked in `view.sessions`, not listed as
306
+ rows — a session key is revoked through the app that owns it, not through `revoke`.
307
+
308
+ **Trust.** A row is never shown on a discovery source's word. Sources — the gateway's
309
+ `POST /v1/approvals/:caip2` (an EVM `eth_getLogs` scan; a TRON indexer where one exists) and the
310
+ engine's own recorded transactions — yield candidate keys only. Every candidate is then read on
311
+ chain at `view.at.height` on the primary endpoint and cross-checked on the independent one: a
312
+ candidate the chain does not confirm is `dropped`, a disagreement between the endpoints hides the
313
+ row and counts it in `disputed`, a candidate that could not be read is `unread`, and a row
314
+ confirmed on only one upstream carries `verified: false`. `view.sources` lists each source's
315
+ status and the height it answered at. `view.exhaustive` names the kinds the chain itself
316
+ enumerates (the EVM delegation, Solana token-account delegates, close and mint authorities, TRON
317
+ permissions); every other kind is a _known_ approval — indexers can miss a spender, so label those
318
+ lists accordingly. Discovered candidate keys persist in the session store (collection
319
+ `approvals`), so an approval outlives the source that found it; keys no longer confirmed on chain
320
+ are pruned.
321
+
322
+ **Risk and exposure.** Rows carry `risk` flags — `unlimited`, `eoa-spender`, `spender-no-code`,
323
+ `address-poisoning`, `foreign-delegation` — and an `exposure` naming what the spender can take
324
+ right now. `engine.approvals.exposure(key)` values the view's exposures at current quotes. Both
325
+ are display-only; nothing about them changes what a request may do.
326
+
327
+ **Freshness.** A loaded view re-reads every `APPROVALS_POLL_MS` while `setVisible(true)` — gate it
328
+ on the approvals screen being shown — on `refresh(key)`, and after a transaction carrying an
329
+ approval intent confirms on the network; that re-read answers at the confirming block or later,
330
+ never from before it.
331
+
332
+ **Revoking.** `engine.approvals.revoke(key, rowId, fee?)` prepares an ordinary request through the
333
+ request pipeline — approve it like any other. The request's display intent describes a revocation
334
+ (an allowance set to 0, a Permit2 lockdown, an operator cleared, a delegation removed), never a
335
+ grant, and the builder re-reads the chain before building: when nothing is left to revoke the
336
+ prepare is refused. `revokeBatch(key, rowIds, fee?)` puts several rows in one transaction — EVM
337
+ rows (`erc20`, `permit2`, `operator`, `nft`; up to `EVM_BATCH_LIMIT`) only on an account already
338
+ delegated to the wallet's delegator, the batch a single self-call with no authorization, or
339
+ several `spl-delegate` rows (up to 10). Rows with `revoke: "none"` — a foreign close authority, a
340
+ mint authority, a stake authority, a TRON permission key — cannot be removed from this wallet.
341
+ Prepare one revocation request at a time: nonces are reserved at commit, so a second prepared
342
+ request would go stale. A row is never removed optimistically; it disappears when the chain read
343
+ after inclusion no longer shows it. Authorities an app's venue holds outside the approvals
344
+ inventory — the Hyperliquid builder-fee approval on HyperCore — are listed by
345
+ `AppsController.authorities` (see [Writing an app provider](#writing-an-app-provider)).
346
+
347
+ ## Writing an app provider
348
+
349
+ An app provider is an `AppDefinition<Id, Api, D>`: a small factory the host lists in
350
+ `createApps({ apps: […] })`. `tests/migration/app-provider.ts` is a complete example — a
351
+ `"example-notes"` provider that registers a per-group handle — importing only the public
352
+ package entries.
353
+
354
+ ```text
355
+ export const exampleNotes = (
356
+ config,
357
+ ): AppDefinition<"example-notes", ExampleNotesApi, ExampleNotesDetail> => ({
358
+ id: "example-notes", // ^[a-z][a-z0-9-]{1,31}$
359
+ enableWhen: ["available"],
360
+ create: (context) => ({ api, provider }),
361
+ });
362
+ ```
363
+
364
+ - `id` is validated at `createApps` — it must match `^[a-z][a-z0-9-]{1,31}$` — and so is
365
+ `enableWhen`: the eligibility answers under which `enable`/`renew` may start. `"blocked"` is
366
+ never allowed, and an unknown, error or absent answer refuses too (eligibility fails closed).
367
+ - `create(context)` runs once per `createApps` and returns `{ api, provider, unlock?, lock?,
368
+ close? }`. `api` is whatever the host calls (`apps["example-notes"]`); `provider` is the
369
+ lifecycle contract below; the hooks fire on vault unlock, lock and teardown.
370
+
371
+ **Group state.** The controller owns `AppGroupBase` — `status`, `termsAcknowledged`,
372
+ `requestId`, `error` — and merges the app's detail `D` flat on top:
373
+ `AppGroupState<D> = AppGroupBase & Partial<D>`. `D` must satisfy `AppDetail`: a detail key may
374
+ not redefine a controller field. A `flow.write({ … })` patch may carry `undefined` to clear a
375
+ field; `termsAcknowledged` is the host's alone — providers cannot write it. The controller
376
+ persists only that flag per group and never reads detail; the eligibility overlay rewrites
377
+ `disabled` ↔ `unavailable` only, so an enabled group stays enabled when a region blocks.
378
+
379
+ **Provider.** `{ error, groups, reconcile, enable, renew, disable, cancel }`:
380
+
381
+ - `error(category, message)` maps the controller's categories (`"unavailable"`,
382
+ `"unlock-required"`, `"busy"`, `"invalid-input"`) to the app's own error class.
383
+ - `groups` lists the groups that may hold state (usually `context.storage.groups`).
384
+ - `reconcile(group, flow)` derives status from app storage after unlock — it owns what a reload
385
+ cannot prove.
386
+ - `enable(group, flow)`/`renew` run the enabling flow under `enableWhen`;
387
+ `disable(group, options, flow)` (`options.revoke` for server-side revocation) and
388
+ `cancel(group, flow)` (reject a pending `requestId`, then reconcile) are never gated.
389
+ - Every provider method receives an `AppFlow<D>`: `flow.current()` is the live group state,
390
+ `flow.write(patch)` merges it, `flow.stale()` reports the flow lost the group. Only one flow
391
+ per group + app runs at a time — a second call throws `busy` — and a lock or a newer flow
392
+ silently drops a stale write.
393
+
394
+ **Context.** `create` receives an `AppContext<D>` with injected I/O — `requests`, `networks`,
395
+ `fetch`, `now`, `setTimer`, `random`, `logger`, `socket`, `storage` — so a provider touches no
396
+ globals. Requests it opens are stamped `{ kind: "app", id }`; an app cannot choose its origin.
397
+ `storage` is the `apps.<id>` collection of the store the host supplies: group-scoped keys
398
+ (`get`/`put`/`delete(group, name)`), closed while the vault is locked, pruned with deleted
399
+ wallets. `context.availability()` is the app's value under the last ready eligibility answer —
400
+ it outlives a lock, so market views keep working — `context.groupState(group)` is the live
401
+ `AppGroupState<D>` (`undefined` while locked or absent), and `context.flow(group, run)` runs an
402
+ api action under the same unlock and busy guards the provider methods get.
403
+
404
+ **Signing.** An app signs only through the request pipeline — requests attributed to it with
405
+ origin `{ kind: "app", id }`, approved by the user and decoded by the kernel — or through a
406
+ kernel session scheme; it never holds a private key. Credentials that cannot authorize moving
407
+ value (API keys, HMAC secrets, bearer tokens) may live in `storage`.
408
+
409
+ **Inside this repo** providers live under `src/apps/<app>/` and may import only
410
+ `src/apps/spi.ts` — enforced by the check-boundaries `app-provider-spi` rule, type-only edges
411
+ included. Every runtime value the SPI re-exports is also a public export of
412
+ `@qntx/wallet-engine` or `@qntx/wallet-engine/apps`, so an external provider loses nothing;
413
+ `createAppSocketCore` is the one exception and stays in-tree until the providers leave the
414
+ package.
415
+
416
+ A provider may also expose `authorities(group)`: the standing authorities its venue holds over
417
+ the group's funds outside the kernel's session keys — the Hyperliquid builder-fee approval on
418
+ HyperCore, Polymarket's trading approvals on the deposit wallet, Fiat24's owner-EOA allowances.
419
+ `AppsController.authorities(group)` collects every app's rows — display-only, one
420
+ `{ app, error }` row per failed read.
421
+
422
+ ## Hyperliquid
423
+
424
+ `@qntx/wallet-engine/apps` is a separate entry point: the `AppsController` and the composition
425
+ host apps build on. Each provider ships in its own sub-entry —
426
+ `@qntx/wallet-engine/apps/hyperliquid`, `@qntx/wallet-engine/apps/polymarket` — so a host bundles
427
+ only the apps it lists.
428
+
429
+ ```ts
430
+ import type { Wallet } from "@qntx/wallet";
431
+ import type { WalletEngine } from "@qntx/wallet-engine";
432
+ import { createApps } from "@qntx/wallet-engine/apps";
433
+ import type { AppSocket } from "@qntx/wallet-engine/apps";
434
+ import { hyperliquid } from "@qntx/wallet-engine/apps/hyperliquid";
435
+ import { polymarket } from "@qntx/wallet-engine/apps/polymarket";
436
+ import type { PolymarketBuilder } from "@qntx/wallet-engine/apps/polymarket";
437
+ import { openIndexedDbEngineStore } from "@qntx/wallet-engine/idb";
438
+
439
+ // The engine and wallet from the examples above; the sign oracle is your server endpoint.
440
+ declare const engine: WalletEngine;
441
+ declare const wallet: Wallet;
442
+ declare const random: (length: number) => Uint8Array;
443
+ declare const myBuilderEndpoint: PolymarketBuilder["sign"];
444
+
445
+ const dataKey = await wallet.dataKeys.get("app-apps");
446
+ const apps = await createApps({
447
+ wallet, // the same Wallet the engine was built on
448
+ account: engine.signers.apis.account, // the one signing seam — every custody answers it
449
+ requests: engine.requests, // user-signed actions open approval requests here
450
+ networks: engine.networks, // chain reads (the Hyperliquid CCTP deposit's allowance/burn limit)
451
+ fetch: globalThis.fetch.bind(globalThis),
452
+ now: () => Date.now(),
453
+ setTimer: (ms, fn) => {
454
+ const id = setTimeout(fn, ms);
455
+ return () => clearTimeout(id);
456
+ },
457
+ random,
458
+ logger: { warn: (m, e) => console.warn(m, e) },
459
+ openStore: async () => openIndexedDbEngineStore({ name: "app-apps", dataKey, random }),
460
+ // a separate EngineStore from the engine's own
461
+ socket: (url) => new WebSocket(url) as AppSocket, // browser, RN or Node ≥ 22 — one socket for all views
462
+ gateway: { url: "https://api.example.com" },
463
+ // the wallet gateway — /v1/eligibility is fetched here
464
+ apps: [
465
+ hyperliquid({
466
+ network: "Mainnet", // or "Testnet"
467
+ agentName: "my-app", // ^[A-Za-z0-9._-]{1,16}$ — part of the kernel's agent binding
468
+ builder: { address: "0x…", feeRateTenthsBps: 10 }, // optional builder fee — see below
469
+ }),
470
+ polymarket({
471
+ builder: { code: "0x…", sign: myBuilderEndpoint }, // Remote Builder Signing — see below
472
+ }),
473
+ ],
474
+ });
475
+ await apps.destroy();
476
+ ```
477
+
478
+ `apps.controller` is a `HostController<AppsState>` (the usual `store` facade) with
479
+ `acknowledgeTerms`, `enable`, `renew`, `disable`, `cancel` and
480
+ `refreshEligibility`; the providers are `apps.hyperliquid` and `apps.polymarket`. A group's
481
+ entry in the controller's `groups` map is typed by the listed app —
482
+ `HyperliquidGroupState` for Hyperliquid, `PolymarketGroupState` for Polymarket. The full
483
+ composition — engine, apps, approvals, orders, live views — is in `tests/migration/hyperliquid.ts`
484
+ and `tests/migration/polymarket.ts`.
485
+
486
+ ### Enabling
487
+
488
+ Each account group enables the app once: `acknowledgeTerms(group, "hyperliquid")` records the
489
+ terms acknowledgement, then `enable(group, "hyperliquid")` creates a kernel-held agent key and
490
+ opens an `ApproveAgent` approval request on `engine.requests`. The group's
491
+ `HyperliquidGroupState` tells the host what to show:
492
+
493
+ - `status: "enabling"` — a flow is running; `step` narrows it
494
+ (`"approve-agent"`, `"verify"`, `"approve-builder"`) and `requestId` names the request to render.
495
+ A flow interrupted by a lock or a reload resumes where it stopped on the next unlock.
496
+ - `status: "enabled"` — trades sign with `agent` (address, `validUntil`); `renewalDue`, written
497
+ once the group is enabled, is true when the 180-day validity window is close enough that a
498
+ host should offer `renew`.
499
+ - `status: "needs-reauthorization"` — the agent is gone, expired or rejected by Hyperliquid;
500
+ `renew` re-authorizes.
501
+ - `status: "unavailable"` — eligibility says the app is blocked in this jurisdiction. The
502
+ overlay only ever covers `disabled`; an enabled group stays enabled so the user can still
503
+ disable it.
504
+ - `status: "disabled"` — nothing enabled.
505
+
506
+ `enable` and `renew` throw `HyperliquidError("unavailable")` unless the gateway's eligibility
507
+ answer is `ready` and reports the app `available` — an unanswered or malformed check refuses too.
508
+ `disable` (delete the agent, `revoke: true` to also unapprove it on Hyperliquid) and `cancel`
509
+ (abort a running flow) are never gated. Call `apps.controller.refreshEligibility()` on foreground;
510
+ unlock already refreshes.
511
+
512
+ On iOS the agent's limits are approved on the kernel's secure-input view — Face ID shows no text —
513
+ so the host must mount `SecureInput` (`@qntx/wallet-native/secure-input`) wherever `enable`,
514
+ `renew`, a `sessions.open` reopen or `disable({ revoke: true })` can run; without one the calls
515
+ answer `unsupported`.
516
+
517
+ **Eligibility is display-only — it is not a security boundary.** The platforms enforce their own
518
+ restrictions; the gateway answer only decides what the UI offers.
519
+
520
+ ### Trading
521
+
522
+ `apps.hyperliquid` is platform-neutral: `markets` (meta, mids, perp/spot asset lookup),
523
+ `account` (clearinghouse, spot, orders, fills), `quote` (price/size rounding and previews),
524
+ `clock` (the skew/nonce clock), `trade` (signed L1 actions), `fund` and `transfer` (user-signed),
525
+ `live` (WebSocket views).
526
+
527
+ - `quote.limit`/`quote.market` build a preview — wire price, size, notional, minimum-check. For a
528
+ market order the preview's price is the slippage cap the exchange will fill against;
529
+ `trade.place` requires `slippageBps` (there is no default — the host must show the computed
530
+ cap it is about to sign).
531
+ - `trade.place`/`close` answer `{ outcomes, price }`; each outcome is `resting`, `filled`,
532
+ `rejected` or `unknown` per cloid. `unknown` means the POST's result is unknowable and the
533
+ action may have committed — the engine reconciles it by cloid and **nothing is ever
534
+ re-sent**. Give every order a stable `cloid` so reconciliation can find it.
535
+ - `unknown` is never proven "not placed": no documented consistency between an info read and
536
+ L1 state means an `unknownOid` answer cannot rule out a committed order. `trade.corrections`
537
+ is the follow-up channel — `subscribe` gets `{ group, cloid, outcome }` every time a pending
538
+ cloid is proven later: by `orderStatus` re-asks for ten minutes after the call returned
539
+ (every 10 s, bounded set of 64), or by live user-view frames — an `openOrders` frame carrying
540
+ the cloid corrects to `resting` immediately, a `fills` frame carrying it triggers an
541
+ immediate `orderStatus` check (a fill alone cannot prove a full fill). Locking the vault
542
+ drops the pending set.
543
+ - `trade.modify`/`batchModify`/`cancel`/`cancelByCloid`/`cancelAll`/`twapCancel`/`setLeverage`/
544
+ `adjustMargin`/`close` round out the action set.
545
+
546
+ ### Live views
547
+
548
+ `live.book`, `live.trades`, `live.candles` for markets and `live.account`, `live.spotState`,
549
+ `live.openOrders`, `live.fills` for a group (resolved to its owner, closed on lock). A view's
550
+ `LiveState` is `{ status: "connecting" | "live" | "stale", data, updatedAt }`: data only renders
551
+ as `live` after a post-confirmation snapshot; any disconnect flips to `stale` — keep the data
552
+ visible but marked, never as live.
553
+
554
+ ### Funding
555
+
556
+ `fund.deposit(group, { amount, fee, dex? })` prepares the CCTP deposit — a USDC
557
+ `depositForBurnWithHook` on Arbitrum's TokenMessengerV2 that Circle's CctpForwarder mints on
558
+ HyperEVM into the Hyperliquid account (destination domain 19, confirmed finality;
559
+ `HYPERLIQUID_DEPOSIT` has the contracts per network and `dex` defaults to `"perps"`). The
560
+ provider reads the Circle forward fee from Iris and refuses a deposit the fee would consume or
561
+ that exceeds the on-chain per-message burn limit. It is a two-call flow: when the messenger's
562
+ USDC allowance is short the result is `approval-required` carrying only an exact-amount approve
563
+ request (the burn call cannot be prepared while the approval is unmined — its `eth_estimateGas`
564
+ reverts); the host approves it and calls `deposit` again, and the re-read allowance then yields
565
+ the `deposit` variant carrying the burn request.
566
+ `transfer.{toPerp,toSpot}` move USDC between the owner's spot and perp accounts, `usdSend`/
567
+ `spotSend` send to another address and `withdraw` sends USDC back to the owner's Arbitrum
568
+ address. Every one opens an approval request: the returned `HyperliquidPendingAction` carries
569
+ the `requestId` to render and an `outcome` promise (`ok`, or `unknown` — may have committed).
570
+
571
+ ### Builder fees
572
+
573
+ An optional `hyperliquid({ builder })` attaches `{ b, f }` to signed order actions — but only
574
+ after the user approved it on Hyperliquid (`approveBuilderFee` runs inside enable when configured)
575
+ and this session confirmed `maxBuilderFee` still covers it. Declining the approval still finishes
576
+ `enabled` with `builder: "declined"` (orders carry no builder); the decline persists across
577
+ unlock, renew and re-enable until `apps.hyperliquid.approveBuilder(group)` obtains an
578
+ approval. There is no default fee, the attached rate is never above the approved one, and
579
+ `feeRateTenthsBps` is 1–100 (tenths of a basis point, 0.1–10 bp).
580
+
581
+ ### Scope
582
+
583
+ Sub-accounts, vaults and referral codes are out of scope for this phase: the kernel's agent
584
+ signature allow-list covers only the owner account's actions.
585
+
586
+ ### Security
587
+
588
+ > An unlocked agent and a compromised main runtime can place, modify and cancel any order,
589
+ > change leverage, adjust isolated margin and trade for sub-accounts or
590
+ > vaults — including filling against an attacker's resting orders at extreme prices in an
591
+ > illiquid market, which "trades" funds to the attacker; it can attach a builder fee up to the
592
+ > rate the main account approved. It cannot withdraw, transfer or deposit into vaults: the
593
+ > kernel does not sign those actions. The window is the unlocked period plus at most 60 seconds —
594
+ > each agent signature carries an `expiresAfter` at most 60 s after it was made and Hyperliquid
595
+ > rejects the action afterwards. Both bounds are on the device clock (the kernel has no trusted
596
+ > time): `assertClock()` refuses to sign when the device is more than 5 s off Hyperliquid's server
597
+ > time, but a compromised main runtime can skip that check, so a device clock running S ahead
598
+ > stretches the window by S (Hyperliquid accepts nonces up to a day ahead); actions already submitted keep their effects (resting
599
+ > orders); deleting the local agent does not revoke it on Hyperliquid (it stays
600
+ > valid until `validUntil`), but nothing can sign with it again.
601
+
602
+ ## Polymarket
603
+
604
+ Polymarket support lives under `apps.polymarket` when `createApps` lists `polymarket(config)` from
605
+ `@qntx/wallet-engine/apps/polymarket`. The provider trades from the account's **deposit wallet** —
606
+ a Polymarket smart contract wallet the relayer deploys to a deterministic CREATE2 address derived
607
+ from the group's `evm.bip44` signer. Everything else is discovered, not persisted: credentials
608
+ live in the engine's encrypted apps store, deployment is proven on-chain (relayer answers are
609
+ hints only), approvals from the Data API.
610
+
611
+ ```text
612
+ const apps = createApps({
613
+ wallet,
614
+ requests,
615
+ networks,
616
+ fetch,
617
+ now,
618
+ setTimer,
619
+ random,
620
+ logger,
621
+ openStore,
622
+ socket,
623
+ gateway: { url },
624
+ apps: [
625
+ polymarket({
626
+ // The host's Remote Builder Signing oracle — see "Builder signing" below.
627
+ builder: {
628
+ code: "0x…", // optional attribution written into orders; absent = zero code
629
+ sign: async ({ method, path, body }) => postToYourBuilderEndpoint({ method, path, body }),
630
+ },
631
+ }),
632
+ ],
633
+ });
634
+ ```
635
+
636
+ ### Account model
637
+
638
+ Enablement resolves exactly one wallet per group: the beacon or UUPS deposit-wallet candidate,
639
+ preferring a deployed one. An account that only ever had the legacy Polymarket **Safe** reports
640
+ `needs-migration` — it is displayed read-only and no trading path runs for it (the Safe cannot be
641
+ upgraded by the relayer). Trading directly from the owner EOA is not offered: Polymarket allows
642
+ EOA orders only for allow-listed accounts, and the deposit wallet covers everyone else.
643
+
644
+ `account.locate(group)` returns `{ signer, wallet, kind, deployed, legacySafe? }`; a deposit wallet
645
+ that coexists with a deployed Safe surfaces `legacySafe` for display.
646
+
647
+ `locate` never trusts the unauthenticated relayer's `/deployed` answer: it reads `eth_getCode` on
648
+ all three CREATE2 candidates over the Polygon RPC — cross-checked byte-for-byte against the host
649
+ endpoint when the gateway serves the network — requires a deposit wallet's code to equal the
650
+ template's expected runtime exactly (the Safe's CREATE2 address already commits to its init-code
651
+ hash, so any code proves it), and then insists every relayer hint agree. Any disagreement, or a
652
+ deposit-wallet-shaped candidate carrying other code, is `PolymarketError("deployment-mismatch")`
653
+ and nothing is chosen; a host endpoint that cannot answer fails closed with `unavailable`. A
654
+ deposit — or any trading path — therefore never targets a wallet the chain does not prove.
655
+
656
+ ### What works without a builder
657
+
658
+ | Capability | Without a builder | Why |
659
+ | ------------------------------------------------------------------------------------ | ---------------------------------------------------- | --------------------------------------------------------------------------------- |
660
+ | Market data, search, book, history, positions/trades/value (Gamma/CLOB/Data, public) | works | no authentication |
661
+ | Locating an existing deposit wallet (derivations + `eth_getCode`, relayer as hint) | works | public reads |
662
+ | Deploying the deposit wallet | `builder-required` | relayer `WALLET-CREATE` only accepts builder credentials |
663
+ | `ClobAuth` → L2 credentials | works | the CLOB does not require a builder |
664
+ | The 8-call approvals batch, withdraw, future redeems | `builder-required` | all are relayer `WALLET` transactions |
665
+ | Placing/cancelling orders | works when the wallet is already deployed + approved | the CLOB needs only L2 + the order signature; `builder` field zero = unattributed |
666
+ | Deposit (EOA → deposit-wallet pUSD) | works | an ordinary Polygon transaction, user pays POL gas |
667
+
668
+ ### Builder signing
669
+
670
+ Relayer submissions are HMAC'd by a builder API key **the app never holds**: `builder.sign`
671
+ receives `{ method, path, body }` and must return the four `POLY_BUILDER_API_KEY /
672
+ POLY_BUILDER_PASSPHRASE / POLY_BUILDER_SIGNATURE / POLY_BUILDER_TIMESTAMP` headers — the engine
673
+ sends the exact `body` string it signed. The host endpoint must authenticate its caller and should
674
+ restrict `path` to `/submit`. Builder secrets belong on the host's server — never in the app, and
675
+ never proxied through the gateway.
676
+
677
+ ### Enablement
678
+
679
+ `enable` runs five steps — `locate-wallet` → `deploy-wallet` (only when undeployed; builder
680
+ required) → `credentials` (one `ClobAuth` typed-data signature serves `POST /auth/api-key` and, if
681
+ needed, `GET /auth/derive-api-key`) → `approvals` (only the rows the Data API reports missing from
682
+ a fixed 8-call table, signed as one `DepositWallet` `Batch` and submitted through the relayer) →
683
+ `verify` — each writing `{ step, requestId, error }` so a lock or crash resumes without repeating
684
+ finished work. Statuses: `disabled`, `enabling`, `enabled`, `needs-reauthorization`,
685
+ `needs-migration`, `unavailable`. `renew` does not apply — CLOB credentials do not expire.
686
+ `disable({ revoke: true })` asks the CLOB to `DELETE /auth/api-key` first and then drops the
687
+ stored credential record; a local delete alone is **not** a revoke — the same wallet re-derives the same credentials,
688
+ so always use `revoke: true` to cut the key off server-side.
689
+
690
+ Eligibility: `enable` accepts `available` **and** `close-only` jurisdictions (close-only users need
691
+ credentials to sell and withdraw); `blocked` and unknown/error answers fail closed with
692
+ `PolymarketError("blocked")`.
693
+
694
+ ### Credential custody
695
+
696
+ The `apiKey`/`secret`/`passphrase` the CLOB answers are written into the app's encrypted
697
+ collection on the session store (`apps.polymarket`, key `<walletId>/<groupIndex>/eip155:137`,
698
+ encrypted under the data key the host's `openStore` holds) — unavailable while locked, pruned when
699
+ the wallet is deleted, cleared on `disable`, and never surfaced in controller state, snapshots,
700
+ logs, or error strings. Every later authenticated request is HMAC'd by the engine itself
701
+ (`l2Headers`) with a ±30 s timestamp window, after checking the stored `owner` still equals the
702
+ group's `evm.bip44` signer. The authenticated `/ws/user` channel receives the same credentials in
703
+ its subscription frame for live order/trade events. Residual risk: a compromised main runtime
704
+ while the wallet is unlocked can read the CLOB credentials: it can cancel orders and read private
705
+ CLOB data (orders, trades) until the user disables Polymarket with revoke (server-side
706
+ `DELETE /auth/api-key`). It cannot place orders — every order needs a signature the kernel decodes
707
+ and the user approves — and cannot move funds (no CLOB path withdraws or transfers).
708
+
709
+ ### Trading
710
+
711
+ `trade.place` covers limit `GTC`/`GTD` (with `postOnly`) and market `FOK`/`FAK` orders. Rounding is
712
+ directional — price to the tick in the user's favour, size down to the 2-decimal grid — so the
713
+ signed order is never worse than the requested limit, and a market quote's shown worst-price bound
714
+ is the signed bound. GTD `expiration` and the displayed fee fields are **unsigned** (the V2 struct
715
+ has no such fields) and shown as such. `orderId` is the order's EIP-712 hash, known before
716
+ approval.
717
+
718
+ Outcomes: `resting`, `matched`, `delayed`, `unmatched`, `rejected` (classified reason), `canceled`,
719
+ and `unknown`. An `unknown` — timeout, network error, 5xx, or an answer that cannot be tied to the
720
+ hash — is reconciled by reads at 0/+2 s/+5 s and **never re-posted**: a V2 order has no expiry, so
721
+ a lost-but-valid order could still be submitted by whoever holds it. An order no reconcile read
722
+ saw is **not** proven absent, so the engine attempts `DELETE /order` by id before resolving — the
723
+ attempt's result rides the outcome as `cancel` — and registers the id for the late reconcile:
724
+ `trade.corrections` re-asks `order` every 10 s for 10 minutes and emits the eventual status once.
725
+ `unknown` means the order may or may not exist — it MUST NOT be blindly re-placed, because a
726
+ later-landing first order plus the retry is a duplicate position. A `canceled` outcome or
727
+ correction carries `making`, the row's `size_matched`: `making` > "0" is a partial fill taken
728
+ before the cancel landed, so only the unfilled remainder is free to re-place — and
729
+ `unknown.cancel.kind === "canceled"` only says the defensive DELETE removed the _remaining_ size,
730
+ never that nothing filled. Cancels
731
+ (`cancel`, `cancelMany` ≤ 500, `cancelAll`, `cancelMarket`) are never eligibility-gated.
732
+
733
+ ### Close-only
734
+
735
+ BUY orders — and BUY quotes — are refused (`close-only`) when the gateway reports the app
736
+ `close-only`/`blocked`, when eligibility is unknown, or when the account's own `closed_only` flag
737
+ is set (a failed check fails closed). SELLs, cancels and withdrawals are always allowed.
738
+
739
+ ### Funding
740
+
741
+ `fund.deposit(group, { amount, fee })` prepares a pUSD `send` from the owner EOA to the located
742
+ **deployed** deposit wallet — it is not eligibility-gated (a deposit opens nothing).
743
+ `fund.withdraw(group, { amount })` submits a one-call relayer `Batch`, `pUSD.transfer(owner)`, so
744
+ the destination is always the owner's own address; a lost submit resolves `unknown` and is never
745
+ auto-resubmitted. Only pUSD moves through this lane this round: USDC/USDC.e wrapping and
746
+ cross-chain bridging are not offered because Polymarket's collateral is pUSD on Polygon and
747
+ wrapping paths belong to the swap/bridge lanes, not this app.
748
+
749
+ ### Live views
750
+
751
+ `live.book(assetId)` streams the public market channel (`custom_feature_enabled` for
752
+ best-bid/ask and resolution events): a `book` snapshot turns the view `live`, `price_change`
753
+ deltas apply only on top of it (size `"0"` removes the level), and every disconnect marks the view
754
+ `stale` while keeping the last data. `live.account(group)` streams the authenticated user channel
755
+ (`/ws/user`): the group's credentials go out as the first frame, order events upsert/remove the
756
+ open-orders list and trade events debounce into a REST re-read. A disconnect keeps the data as
757
+ `stale` and falls back to a 10 s REST poll (`source: "poll"`) until the socket reconnects and the
758
+ view returns to `live`/`stream`; a lock or a missing-credential stop closes the view for good.
759
+
760
+ ## Fiat24
761
+
762
+ Fiat24 support lives under `apps.fiat24` when `createApps` lists `fiat24(config)` from
763
+ `@qntx/wallet-engine/apps/fiat24`. The provider is built on the `@qntx/fiat24` SDK (Arbitrum One
764
+ only): the account read and the resumable flows run over a viem client built from
765
+ `engine.networks` — with an independent endpoint configured every pinned read must agree on both
766
+ sides, and the SDK's own deployment check stays on, so a drifted deployment reports the typed
767
+ status `contract-changed` rather than signing against unexpected code. The REST API is optional:
768
+ `fiat24({ fetch })` is for `api.fiat24.com` only.
769
+
770
+ ```text
771
+ import { fiat24 } from "@qntx/wallet-engine/apps/fiat24";
772
+
773
+ const apps = createApps({
774
+ /* … the same options as above … */
775
+ apps: [fiat24({ fetch: fiat24Fetch })], // see "The REST api" — omit for a chain-only build
776
+ });
777
+ ```
778
+
779
+ - `account(group)` reads the group's account once: `no-account`, an `AccountStatus` (or `stale`
780
+ for a failed read), or `contract-changed`. `live(group)` is the same read as a store facade,
781
+ polled every 15 s (`FIAT24_POLL_MS`) while `setVisible(true)` and unlocked.
782
+ - `flows` is `start` / `advance` / `list` / `discard` / `payoutSettlement` over the SDK's
783
+ resumable transfer, exchange, payout, top-up, onboarding and card flows. Advances are
784
+ serialised per group, `start` refuses `flow-unresolved` while another flow could still send,
785
+ and an entry that no longer decodes lists as `{ id, invalid: true }` — `discard` is the only
786
+ way out of it, so have the user check the account's activity first.
787
+ - `session(group)` is the secured reads (`profile`, `cards`, `cardDisplayToken`,
788
+ `transactions`) through a lazy SDK session. `api` is the unauthenticated reads (`rates`,
789
+ `paymentPurposes`, `countries`, `countryCities`, `banks`, `bankByIban`, `kycUrl`).
790
+
791
+ **Every SDK write is exactly one `{ kind: "app", id: "fiat24" }` request** on `engine.requests`:
792
+ transactions are `evm-sign` `evm.transaction` requests at the SDK-chosen nonce (the engine pins
793
+ it — `prepare` fails with `NonceConflictError` if the sender's next nonce moved on), and session
794
+ grants are `evm.fiat24-session` requests. A `Fiat24Flow.refusal` on a returned entry says why a
795
+ send did not happen. Reconcile — on unlock and every 15 s while visible — only ever advances
796
+ records in `sending`/`submitted`/`unknown`, which the SDK resolves by polling receipts and
797
+ nonces; it can never sign or broadcast.
798
+
799
+ **Persistence.** Flow states persist as `encodeFlowState` text in the app's EngineStore
800
+ collection — pseudonymous chain fields only, no PII. Payout drafts hold unverified payee data
801
+ and stay in memory. Session grants are bearer credentials held only in memory; lock, disable and
802
+ wallet removal end them (disable also rejects the group's still-open requests).
803
+
804
+ **Jurisdiction.** `enable` needs an eligibility answer of `available` or `close-only` — a
805
+ restricted jurisdiction still gets the read surface to wind positions down — and onboarding and
806
+ top-up refuse when the chain reports the feature `unavailable`.
807
+
808
+ ### The REST api
809
+
810
+ `api.fiat24.com` sends no CORS headers and the gateway does not proxy it, so the host owns the
811
+ transport:
812
+
813
+ - **React Native:** inject the platform `fetch`, uninstrumented — exclude `api.fiat24.com` from
814
+ logging/Sentry interceptors, disable its HTTP cache, and note RN's fetch follows redirects
815
+ whatever `redirect` says; inject one that does not if that matters.
816
+ - **Web:** inject a `fetch` that sends the request to a host proxy for `https://api.fiat24.com`.
817
+ The proxy sees the session grant headers, which are a bearer credential for the account until
818
+ their deadline — treat them accordingly.
819
+
820
+ Without `fetch` the chain flows still work — transfers, exchanges, top-ups, payouts to a saved
821
+ contact, and onboarding up to KYC — while the secured and public REST reads, a bank or Swiss-QR
822
+ payout draft's verify step, a card flow's API write, and the onboarding `tourist`/`kyc` steps
823
+ throw `Fiat24AppError("api-unavailable")`.
824
+
825
+ ### Security
826
+
827
+ Residual risks a host must state, from the SDK's README: exact-in FX and top-up have no on-chain
828
+ minimum output (the issuer's rate can move between the flow's quote check and inclusion); a
829
+ payout's payee is bound off-chain — the signed transaction carries only the contact id and
830
+ reference, and Fiat24 resolves the recipient; and a single EOA owns the ProxyAdmin of every
831
+ Fiat24 proxy (it can pause, re-wire and upgrade the deployment, which is why writes fail closed
832
+ with `contract-changed`). See the [SDK README](https://github.com/qntx/fiat24#residual-risks) for
833
+ the full list.
834
+
835
+ ## WalletConnect
836
+
837
+ `@qntx/wallet-engine/walletconnect` is a separate entry point: the wallet side of WalletConnect
838
+ v2 (Reown WalletKit + the sign client). It needs four optional peer dependencies — install them
839
+ yourself: `@reown/walletkit`, `@walletconnect/core`, `@walletconnect/types`,
840
+ `@walletconnect/utils` (exact pins in `peerDependencies`). No other entry imports them, so a
841
+ host that never pairs pays nothing — the SDK and its relay transport live only in this entry's
842
+ bundle.
843
+
844
+ All four packages are under the **WalletConnect Community License Agreement** (Reown, Inc.,
845
+ release date 20 August 2025 — see `LICENSE.md` in each installed package). Reading the license:
846
+ downloading, installing, integrating or using the packages makes you a Licensee bound by it.
847
+ Use for education/non-commercial research and for developing your own apps and wallets is
848
+ royalty-free, subject to the limited-commercial-use rule: above **500 monthly active users or
849
+ 2,500,000 monthly RPC calls** you must pay for a commercial licence. Modifications are allowed
850
+ but every modification or derivative work is assigned to Reown (you keep a licence to use it
851
+ only in conjunction with the packages while the licence is in effect, must mark changed files,
852
+ and must hand Reown the source/binary on request); your own app stays yours. Distribution
853
+ requires the notice "Portions © 2025 Reown, Inc. All Rights Reserved" and a copy of the
854
+ licence, and as a material condition all use must connect to the proprietary Reown gateway
855
+ infrastructure and the WalletConnect messaging protocol.
856
+
857
+ WalletConnect peers are ordinary dApp origins
858
+ keyed `walletconnect:<session topic>`: their sessions live in `engine.connections` alongside
859
+ browser sessions, and every `session_request` runs through the same handlers and request pipeline
860
+ the in-app browser uses, so the approval UI and risk checks are unchanged.
861
+
862
+ ```ts
863
+ import type { Wallet } from "@qntx/wallet";
864
+ import type { WalletEngine } from "@qntx/wallet-engine";
865
+ import { createWalletConnect } from "@qntx/wallet-engine/walletconnect";
866
+ import type { WalletConnectStorage } from "@qntx/wallet-engine/walletconnect";
867
+
868
+ declare const projectId: string;
869
+ declare const storage: WalletConnectStorage;
870
+ declare const wallet: Wallet;
871
+ declare const engine: WalletEngine;
872
+
873
+ const walletConnect = await createWalletConnect({
874
+ projectId, // from the Reown dashboard — see the checklist below
875
+ metadata: {
876
+ name: "my wallet",
877
+ description: "…",
878
+ url: "https://wallet.example",
879
+ icons: ["https://wallet.example/icon.png"],
880
+ redirect: { native: "mywallet://", universal: "https://wallet.example/wc" },
881
+ },
882
+ storage, // WalletConnectStorage — a host-provided key-value store, required
883
+ wallet, // the same Wallet the engine was built on
884
+ engine, // the WalletEngine
885
+ now: () => Date.now(),
886
+ logger: { warn: (m, e) => console.warn(m, e) },
887
+ });
888
+ await walletConnect.dispose();
889
+ ```
890
+
891
+ `walletConnect.getState().proposals` lists open proposals (peer name/url — self-declared, display
892
+ only — Verify status, risk findings, offerable networks). `approve(id, { networks, acknowledged })`
893
+ grants a subset of the offered networks and returns the `ConnectionSession`; `reject(id)` answers
894
+ USER_REJECTED. Danger findings must be passed back in `acknowledged` or `approve` throws
895
+ `"unacknowledged"`. `pair(uri)` accepts a `wc:` URI; `dispose()` tears down the relay connection —
896
+ sessions persist in the engine's connection store, not in WalletConnect's.
897
+
898
+ ### Storage
899
+
900
+ `storage` is mandatory (`WalletConnectStorage`: `getKeys`/`getEntries`/`getItem`/`setItem`/
901
+ `removeItem`, JSON values). The SDK persists sessions, pairings, keys and pending requests there;
902
+ give it durable storage or every restart loses the pairings.
903
+
904
+ - **Web:** an IndexedDB-backed key-value store the host provides (a `localStorage` JSON shim works
905
+ for a playground, not for production).
906
+ - **React Native:** `import "@walletconnect/react-native-compat"` as the **first** import of the
907
+ app entry — before anything that transitively loads the SDK. Its peer dependencies:
908
+ `@react-native-async-storage/async-storage`, `@react-native-community/netinfo`,
909
+ `react-native-get-random-values`, `expo-application`. Back `storage` with AsyncStorage.
910
+
911
+ ### Globals WalletKit needs
912
+
913
+ | Global | Web | React Native |
914
+ | -------------------------------------------------------- | ------------------------------------------------------ | ------------------------- |
915
+ | `WebSocket` (captured once at module load) | built-in | built-in |
916
+ | `fetch` (Verify, telemetry off, Echo only if registered) | built-in | built-in |
917
+ | `crypto.getRandomValues`, `crypto.randomUUID` | built-in | via `react-native-compat` |
918
+ | `TextEncoder`/`TextDecoder`, `atob`/`btoa` | built-in | via `react-native-compat` |
919
+ | `URL` | built-in | via `react-native-compat` |
920
+ | `navigator.product`, `NetInfo` | n/a | via `react-native-compat` |
921
+ | `window`/`document`/`localStorage` | dApp-side branches only — the wallet never enters them | n/a |
922
+
923
+ ### Deep links
924
+
925
+ A scanned QR or pasted `wc:` URI goes `engine.payments.parse(text)` → `{ kind: "walletconnect",
926
+ uri }` → `walletConnect.pair(uri)` — parse only pairs the `walletconnect` result. On mobile,
927
+ register the app's universal link (iOS) / scheme (Android) for `wc:` URIs and set
928
+ `metadata.redirect` so dApps can return to the wallet.
929
+
930
+ ### Namespaces and methods
931
+
932
+ | Namespace | Methods | Events |
933
+ | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
934
+ | `eip155` | `personal_sign`, `eth_signTypedData_v4`, `eth_sendTransaction`, `wallet_sendCalls`, `wallet_getCallsStatus`, `wallet_showCallsStatus`, `wallet_getCapabilities`, `wallet_watchAsset`, `wallet_switchEthereumChain`, `wallet_addEthereumChain` | `accountsChanged`, `chainChanged` |
935
+ | `solana` | `solana_signMessage`, `solana_signTransaction`, `solana_signAllTransactions`, `solana_signAndSendTransaction` | `accountsChanged`, `chainChanged` |
936
+ | `bip122` | `getAccountAddresses`, `signMessage`, `signPsbt`, `sendTransfer` | `accountsChanged`, `chainChanged`, `bip122_addressesChanged` |
937
+
938
+ Limits: `eth_sign`/`eth_signTypedData`(v1/v3)/`eth_signTransaction` are never approved (the
939
+ injected provider refuses them too); BIP-322 is the only `signMessage` protocol (`ecdsa`/absent →
940
+ 4200); `sendTransfer` refuses `memo` (no OP_RETURN); `solana_signAndSendTransaction` ignores
941
+ `sendOptions` — the engine broadcasts with its own settings; bip122 sessions advertise only the
942
+ payment address (the ordinal address comes back from `getAccountAddresses`). A proposal's embedded
943
+ `requests.authentication`/`requests.walletPay` are ignored — approval proceeds without them.
944
+
945
+ ### Verify, phishing, lifecycle
946
+
947
+ Each proposal carries a WalletConnect Verify result plus the engine's phishing check on the
948
+ peer's metadata origin: `isScam` and `INVALID` are `danger` findings (`verify-threat`,
949
+ `verify-mismatch`) that block approval unless acknowledged; `UNKNOWN` is neutral. A peer on the
950
+ phishing deny list is rejected outright.
951
+
952
+ A proposal that arrives while the vault is locked is held and judged on unlock; an expired one is
953
+ dropped. Session requests requeue on a mid-approval lock, except one-click auth, which is refused.
954
+ Pending requests, sessions and pairings survive restarts via `storage`. Sessions expire with the
955
+ WalletConnect TTL and reconcile against the connection store; revoking the origin or a dApp
956
+ disconnect deletes both.
957
+
958
+ ### One-click auth
959
+
960
+ `session_authenticate` requests are validated (peer URL, domain = peer host, SIWE URI = peer
961
+ origin, every recap chain on the session's network), signed as a SIWE `personal-message` through
962
+ the ordinary `evm-sign` pipeline — the existing sign-in parse and risk display apply — and settled
963
+ as a Cacao. When the recap carries eip155 methods the auth also creates the session; without
964
+ methods it stays an auth.
965
+
966
+ ### One instance
967
+
968
+ One `createWalletConnect` per JS runtime: Core keeps a global singleton keyed by storage prefix
969
+ (`DISABLE_GLOBAL_CORE` opts out). Telemetry is always off.
970
+
971
+ ### Host checklist
972
+
973
+ - `projectId` from the [Reown dashboard](https://dashboard.reown.com) — not a secret, but configure
974
+ the project's allowed domains/bundle ids there.
975
+ - **License:** WalletConnect is under the WalletConnect Community License — Reown's relay is
976
+ mandatory and the free tier covers ≤ 500 MAU and ≤ 2.5 M relay RPC calls/month. Take a
977
+ commercial licence before a public release above that, and never patch or fork the SDK (§1c).
978
+ - Register the deep link / universal link and set `metadata.redirect`.
979
+ - On RN, `react-native-compat` must be the first import.
980
+ - Upgrade `@reown/walletkit` only together with the `@walletconnect/*` packages — WalletKit pins
981
+ core/utils/types exactly.
982
+
983
+ ## QR signer
984
+
985
+ `@qntx/wallet-engine/qr` is a separate entry: the wallet side of UR QR signing. Two roles share
986
+ the entry — a phone wallet **answers** the sign requests a watch-only wallet displays as animated
987
+ QR frames, and our Web wallet **asks**: it holds no keys and emits the requests the phone signs.
988
+ The whole exchange is UR over frames: `qrFrames` emits the fountain parts, `createQrScanner`
989
+ receives them inside byte/frame/deadline bounds.
990
+
991
+ ### Signing for a watch-only wallet
992
+
993
+ The flow is: scan the counterpart's frames into `createQrScanner({ kind: "request" })` (its
994
+ progress ratio is the UI's progress) → `readQrRequest` decodes the payload and re-checks it →
995
+ `qrSigner({ engine, wallet }).prepare(request, account)` binds it and opens an ordinary engine
996
+ request at `awaiting-approval` → the user verifies the decoded intent and approves →
997
+ `respond(id)` waits for the pipeline outcome and encodes the signature as the UR response → the
998
+ host shows `qrFrames(payload)` until the desktop has the parts. `prepare` and `respond` belong to
999
+ one `qrSigner` instance — `respond` refuses a request another instance prepared.
1000
+
1001
+ A QR request is one more origin in the existing pipeline — the account's own backend signs: a
1002
+ vault key in the kernel, or a hardware wallet through `EngineOptions.devices` (the device
1003
+ exchanges inside `signing` are the tap cadence; nothing signs before approval, and the
1004
+ counterpart is never told which kind of signer answered). Cancellation and timeout exist at
1005
+ every hop: a frame budget and scan deadline in the scanner, rejection or expiry in the pipeline,
1006
+ abort through the device io's signal. A lost device mid-flow ends `failed` with no payload and
1007
+ nothing half-signed.
1008
+
1009
+ ### The watch-only side
1010
+
1011
+ `readQrExport` reads the phone's `crypto-multi-accounts` export into `QrLink`s (one per family,
1012
+ strict path shapes, a bitcoin account by its xpub); `watch.add({ ..., qr })` stores a watch
1013
+ account pinned to that fingerprint/path/xpub — it signs only through frames and never reaches an
1014
+ `AccountRef`. `qrSignRequest` writes the request our own `readQrRequest` accepts and `prepare`
1015
+ binds, refusing what the phone would refuse with the same codes (no EIP-7702, no contract
1016
+ creation, a solana message whose required signers exclude the link, a PSBT with no input under
1017
+ the link).
1018
+ `readQrSignature` verifies the answer cryptographically — sender recovery for EVM/TRON, ed25519
1019
+ for Solana, same-content plus a new under-link signature for a PSBT — before handing it back.
1020
+
1021
+ The scanned export is the trust root of the whole exchange: a malicious export replaces every
1022
+ address the watch wallet will ever show, so the user must compare the first receive address the
1023
+ watch wallet derives against the phone's own account screen before trusting anything it signs
1024
+ for.
1025
+
1026
+ ### Counterparts
1027
+
1028
+ | Counterpart | Export | Request | Response | Verified |
1029
+ | ------------------------------ | ---------------------------- | --------------------- | ------------------- | --------------------------------------------------------------------------------------------- |
1030
+ | MetaMask / Rabby | crypto-hdkey, crypto-account | eth-sign-request | eth-signature | Differential against the keyring's `@keystonehq/*` codecs; not verified against the app |
1031
+ | BlueWallet / Sparrow / Nunchuk | crypto-account | crypto-psbt | crypto-psbt | Differential at BlueWallet's exact codec pin; Sparrow is source-read only; Nunchuk unverified |
1032
+ | Keystone-compatible JS | crypto-multi-accounts | sol/tron-sign-request | sol/tron-signature | Differential against Keystone Rust 1.0.9 and firmware goldens |
1033
+ | qntx Web wallet | crypto-multi-accounts | all families above | matching signatures | End to end in Node: two wallets exchanging only frames |
1034
+
1035
+ ### Binding
1036
+
1037
+ A request signs only when it binds to the account and to an enabled network:
1038
+
1039
+ - EVM: the chain id of the transaction or the typed-data domain must be an enabled network;
1040
+ EIP-7702, contract creation and self-calls are refused; nonce and fee are signed as sent and
1041
+ the recovered signer is re-checked on the response.
1042
+ - Solana: the request carries no cluster — it binds to the first enabled cluster whose blockhash
1043
+ check accepts the message (mainnet first), else refused.
1044
+ - TRON: the TaPoS reference block must prove out on an enabled network, else refused.
1045
+ - Bitcoin: coin type picks mainnet or the single enabled testnet; single-sig templates only —
1046
+ multisig (witnessScript, redeemScript, taproot-leaf scripts) is refused.
1047
+
1048
+ The account must also match: fingerprint, keypath and — where the type carries it — the address
1049
+ must equal the pinned account (EVM case-insensitive, TRON/Solana exact), else `account-mismatch`.
1050
+ Solana and Bitcoin QR requests are sign-only: `send` is refused and broadcasting stays with the
1051
+ watch wallet — every response is a signature or an envelope/PSBT the counterpart broadcasts.
1052
+ A sign-in message over QR carries no verifiable page domain: where a dApp claiming a foreign
1053
+ domain is refused, the QR path prepares with a `qr-sign-in-unverified` danger finding the host
1054
+ must surface and the user must acknowledge to approve.
1055
+
1056
+ ### Export and inspection
1057
+
1058
+ `qrSigner.exportAccount` reports what a form `discloses` (`evm-all-addresses`,
1059
+ `account-addresses`, `single-addresses`) — the UI should say so before showing the QR.
1060
+ `inspectQrRequest(request)` decodes the display intent and the digests a signing device would
1061
+ show; it proves what the scanned bytes mean, not that the desktop sent the same bytes to the
1062
+ device — compare the digest on the device. Only digests a primary source says the device
1063
+ renders carry a `shownBy` label (Ledger app-ethereum ≥ 1.14 the transaction hash, ≥ 1.18 the
1064
+ EIP-712 domain and message hashes; Ledger app-solana the message hash) — a digest with no
1065
+ source is still listed, unlabelled, as the protocol value.
1066
+ `inspectQrRequest` reports `displays`: one decoded intent per output encoding the request
1067
+ permits, each labelled by the networks that encoding serves. A PSBT carries no declared
1068
+ network, so its derivations' coin types decide — `0'` is mainnet; `1'` is ambiguous between the
1069
+ `tb1…` test networks (testnet and signet share the prefix — one display, labelled by both) and
1070
+ regtest's `bcrt1…`, so it yields two displays; mixed or missing coin types fail with
1071
+ `network-ambiguous`, the same refusal `bindQrRequest` raises, rather than show outputs on a
1072
+ guessed network.
1073
+
1074
+ ### Limits
1075
+
1076
+ - A phone is not an air-gapped device: it is online; the QR path removes the cable and the
1077
+ pairing, not the attack surface.
1078
+ - Multisig is not supported — single-sig PSBT templates only.
1079
+ - Device digests: `shownBy` lists which device's screen actually displays each digest
1080
+ (`ledger-ethereum`, `ledger-solana`); `tron-txid`, `tron-message-digest` and the digests on
1081
+ the bitcoin path ship `shownBy: []` — unverified, treat them as display-only.
58
1082
 
59
1083
  ## React Native hosts
60
1084
 
@@ -77,6 +1101,19 @@ What the host must provide:
77
1101
  A host that already calls `install()` from `react-native-quick-crypto` (as Meowl does) also works;
78
1102
  the same smoke passes with those globals installed.
79
1103
 
1104
+ ### In-app browser
1105
+
1106
+ `createBrowserBridge` attributes every page message to the origin of the URL the host passes as
1107
+ `topUrl`, and drops it unless that origin is the current top-level page. The host must therefore
1108
+ pass the URL of the frame that sent the message, never the top-level URL, or a cross-origin frame
1109
+ inside a connected dApp (an ad, a widget) could request accounts and signatures under the dApp's
1110
+ origin. Use react-native-webview 13.13.5 or later, which reports the sending frame in
1111
+ `nativeEvent.url` (the message's `frameInfo` on iOS, the `WebMessageListener` source origin on
1112
+ Android). On an Android system WebView without `WEB_MESSAGE_LISTENER`, react-native-webview falls
1113
+ back to `addJavascriptInterface`, which reaches every frame and reports the top-level URL; the
1114
+ in-app browser is not safe there. The injected provider installs itself only in the top-level
1115
+ document.
1116
+
80
1117
  ## License
81
1118
 
82
1119
  MIT OR Apache-2.0