@bsv/expo-wallet-toolbox 0.21.0 → 0.23.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 (133) hide show
  1. package/CHANGELOG.md +222 -0
  2. package/README.md +82 -13
  3. package/core/bridge/BrowserBridgeProvider.tsx +273 -0
  4. package/core/bridge/bindings.ts +459 -0
  5. package/core/bridge/conformance.ts +222 -0
  6. package/core/bridge/consent.ts +494 -0
  7. package/core/bridge/consentSheetSource.ts +98 -0
  8. package/core/bridge/dispatcher.ts +621 -0
  9. package/core/bridge/inbox.ts +464 -0
  10. package/core/bridge/index.ts +48 -0
  11. package/core/bridge/loopback/cors.ts +57 -0
  12. package/core/bridge/loopback/endpoints.ts +11 -0
  13. package/core/bridge/loopback/hostCheck.ts +25 -0
  14. package/core/bridge/loopback/index.ts +7 -0
  15. package/core/bridge/loopback/launchProof.ts +166 -0
  16. package/core/bridge/loopback/router.ts +770 -0
  17. package/core/bridge/loopback/routerTypes.ts +115 -0
  18. package/core/bridge/loopback/status.ts +52 -0
  19. package/core/bridge/memoryInboxStore.ts +222 -0
  20. package/core/bridge/permissionPolicy.ts +247 -0
  21. package/core/bridge/policy.ts +72 -0
  22. package/core/bridge/protocol/base64url.ts +64 -0
  23. package/core/bridge/protocol/connectionError.ts +79 -0
  24. package/core/bridge/protocol/constants.ts +21 -0
  25. package/core/bridge/protocol/continuity.ts +21 -0
  26. package/core/bridge/protocol/descriptor.ts +395 -0
  27. package/core/bridge/protocol/envelopes.ts +188 -0
  28. package/core/bridge/protocol/errorCodec.ts +164 -0
  29. package/core/bridge/protocol/json.ts +237 -0
  30. package/core/bridge/protocol/limits.ts +43 -0
  31. package/core/bridge/protocol/methods.ts +55 -0
  32. package/core/bridge/protocol/origin.ts +130 -0
  33. package/core/bridge/runtime.ts +642 -0
  34. package/core/bridge/runtimeFlags.ts +34 -0
  35. package/core/bridge/testing/conformanceCases.ts +149 -0
  36. package/core/bridge/testing/pageClient.ts +44 -0
  37. package/core/bridge/unverifiedManager.ts +97 -0
  38. package/core/bridge/unverifiedOriginator.ts +79 -0
  39. package/core/config.tsx +1 -16
  40. package/core/contacts/contactActivity.ts +48 -28
  41. package/core/contacts/contactsStore.ts +2 -2
  42. package/core/context/WalletConnectionContext.tsx +7 -1
  43. package/core/context/WalletContext.tsx +420 -348
  44. package/core/context/sessionTeardown.ts +46 -0
  45. package/core/demo/demoAssets.ts +8 -10
  46. package/core/demo/demoLedger.ts +32 -38
  47. package/core/demo/demoMandalaRuntime.ts +67 -49
  48. package/core/demo/index.ts +1 -1
  49. package/core/hooks/usePermissionQueue.ts +89 -34
  50. package/core/i18n/translations.tsx +983 -12
  51. package/core/index.ts +70 -37
  52. package/core/localpay/build.ts +110 -569
  53. package/core/localpay/codec.ts +190 -93
  54. package/core/localpay/pending.ts +217 -202
  55. package/core/localpay/session.ts +99 -25
  56. package/core/localpay/types.ts +6 -5
  57. package/core/localpay/verify.ts +118 -173
  58. package/core/mandala/abortGuard.ts +97 -120
  59. package/core/mandala/accessPolicy.ts +133 -0
  60. package/core/mandala/assets.ts +370 -0
  61. package/core/mandala/colorGuard.ts +178 -0
  62. package/core/mandala/colorModule.ts +82 -0
  63. package/core/mandala/createRuntime.ts +483 -2392
  64. package/core/mandala/handle.ts +694 -0
  65. package/core/mandala/kvStore.ts +105 -0
  66. package/core/mandala/nearby.ts +185 -0
  67. package/core/mandala/receipt.ts +121 -0
  68. package/core/mandala/runtime.ts +166 -312
  69. package/core/mandala/settle.ts +540 -0
  70. package/core/mandala/transferJournal.ts +395 -0
  71. package/core/mandala/types.ts +61 -311
  72. package/core/networks.ts +5 -5
  73. package/core/offline/cancelParked.ts +80 -63
  74. package/core/offline/payerHold.ts +52 -118
  75. package/core/parsePeerPayURI.ts +25 -12
  76. package/core/pay/rails/handle.ts +15 -14
  77. package/core/pay/rails/index.ts +5 -3
  78. package/core/pay/rails/nearby.ts +25 -87
  79. package/core/profiles/assertProfileEmpty.ts +19 -10
  80. package/core/services/autoApprovePolicy.ts +7 -1
  81. package/core/services/capWalletArgs.ts +2 -1
  82. package/core/services/permissionPrompts.ts +132 -0
  83. package/core/services/signingPermissionPolicy.ts +230 -2
  84. package/core/services/vault/guard.ts +15 -4
  85. package/core/services/walletArgLimits.ts +17 -2
  86. package/core/storage/StorageExpoSQLite.ts +93 -229
  87. package/core/storage/encryptedDbImage.ts +325 -0
  88. package/core/storage/methods/processOfflineActions.ts +86 -136
  89. package/core/storage/schema/createTables.ts +9 -184
  90. package/core/toolboxConfig.ts +18 -1
  91. package/package.json +9 -8
  92. package/ui/bridgeSheet/ContextRelay.tsx +86 -0
  93. package/ui/bridgeSheet/relayedContexts.ts +21 -0
  94. package/ui/components/pay/AssetPicker.tsx +2 -2
  95. package/ui/components/pay/HandleReceive.tsx +4 -4
  96. package/ui/components/pay/NearbyFlow.tsx +324 -239
  97. package/ui/components/pay/RequestHub.tsx +10 -0
  98. package/ui/components/pay/UniversalSend.tsx +31 -28
  99. package/ui/components/pay/useRecipientInput.ts +2 -2
  100. package/ui/components/ui/PermissionSheet.tsx +625 -315
  101. package/ui/components/ui/Sheet.tsx +59 -7
  102. package/ui/components/ui/colorPrompt.ts +236 -0
  103. package/ui/components/ui/sheetResumeSignal.ts +19 -0
  104. package/ui/components/wallet/AmountInput.tsx +9 -6
  105. package/ui/components/wallet/AssetAmount.tsx +6 -6
  106. package/ui/components/wallet/AssetSwitcherDropdown.tsx +26 -7
  107. package/ui/components/wallet/Balance.tsx +3 -1
  108. package/ui/components/wallet/ContactActivityList.tsx +10 -13
  109. package/ui/components/wallet/tokenEviction.ts +9 -9
  110. package/ui/exportDatabases.ts +94 -5
  111. package/ui/hooks/useExportWalletData.ts +37 -24
  112. package/ui/hooks/useMandala.ts +6 -6
  113. package/ui/hooks/useSpendableBalance.ts +3 -1
  114. package/ui/importDatabases.ts +124 -29
  115. package/ui/index.ts +4 -0
  116. package/ui/screens/PayScreen.tsx +14 -20
  117. package/ui/screens/SettingsScreen.tsx +3 -1
  118. package/ui/screens/WalletCheckScreen.tsx +7 -2
  119. package/ui/screens/WalletConfigScreen.tsx +13 -1
  120. package/ui/screens/WalletHomeScreen.tsx +40 -14
  121. package/ui/screens/tokenRowTitle.ts +28 -15
  122. package/ui/tokenFormat.ts +133 -69
  123. package/ui/tokenStatus.ts +5 -8
  124. package/core/localpay/settlementAck.ts +0 -155
  125. package/core/mandala/basketMigration.ts +0 -166
  126. package/core/mandala/bundle.ts +0 -244
  127. package/core/mandala/drain.ts +0 -754
  128. package/core/mandala/inboxPrehold.ts +0 -193
  129. package/core/mandala/permissionModule.ts +0 -931
  130. package/core/mandala/resendTransfer.ts +0 -178
  131. package/core/mandala/settlementStore.ts +0 -434
  132. package/core/mandala/token.ts +0 -45
  133. package/core/offline/tokenFrames.ts +0 -197
@@ -1,931 +0,0 @@
1
- /**
2
- * MandalaTokenModule — the `WalletPermissionsManager` P-module for the
3
- * `'p mandala'` basket (schemeID `'mandala'`).
4
- *
5
- * Mirrors `@bsv/btms-permission-module`'s `BasicTokenModule` shape and file
6
- * organization exactly (admin pass-through, a 60s session-authorization
7
- * cache keyed by originator, a JSON-encoded prompt message, a generic
8
- * fallback that never throws on a decode failure) — but decodes Mandala's
9
- * own script layout, `<36B assetId><scriptnum amount> OP_2DROP <P2PKH tail>`,
10
- * via `MandalaToken.decode` from `@bsv/templates`, NOT BTMS's `PushDrop.decode`:
11
- * the two token formats are unrelated.
12
- *
13
- * Mandala's FT protocol is `[2, 'p mandala token']` (@bsv/mandala 0.4.0), so
14
- * `WalletPermissionsManager` also routes every wallet call keyed on that
15
- * protocol here, the same way BTMS's `[0, 'p btms']` reaches
16
- * `BasicTokenModule`. For a connected app:
17
- * - `getPublicKey`/`verifySignature` pass through. A public key cannot
18
- * spend, and issuing or sending to yourself needs keys toward `self`/
19
- * your own identity key.
20
- * - `createSignature` passes only when the digest it signs is the BIP-143
21
- * sighash of an input of a transaction this module saw the user approve
22
- * (the `createAction` response, captured in `onResponse`). Any other
23
- * signature gets its own prompt and never grants a session.
24
- * - `encrypt`/`decrypt`/`createHmac`/`verifyHmac` are refused: nothing in
25
- * the Mandala lib uses them under the token protocol.
26
- *
27
- * Source of truth: offline-settlement-final.md §8.3, plus a set of
28
- * adversarial-review findings closed here (see the inline notes tagged
29
- * "adversarial-review finding" throughout this file):
30
- * 1. [critical] listOutputs used to withhold `customInstructions`
31
- * (keyID/counterparty/blinding derivation data), because knowing a
32
- * coin's derivation was enough to sign a spend of it. Reverted: the
33
- * Mandala lib finds admin assets and spendable coins by those
34
- * instructions, so withholding them broke issuing and sending from a
35
- * connected app, and `createSignature` is now bound to approved
36
- * transactions (see above), so the derivation alone no longer spends.
37
- * 2. [medium/high] createAction that only SPENDS `'p mandala'` INPUTS (no
38
- * basketed change output) is now gated too — see `anyInputIsTokenCoin`
39
- * and the `wrapCreateActionForTokenInputs` wrapper below.
40
- * 3. [medium] listActions is now routed the same as listOutputs.
41
- * 4. [medium] Prompt amounts are grouped by assetId and decimal-formatted.
42
- * 5. [low] relinquishOutput is its own authorization class.
43
- */
44
- import { Hash, LockingScript, Transaction, Utils } from '@bsv/sdk'
45
- import type { PermissionsModule } from '@bsv/wallet-toolbox-mobile'
46
- import { MandalaToken } from './token'
47
- import { MANDALA_BASKET } from './types'
48
-
49
- const SESSION_TIMEOUT_MS = 60_000
50
- const SESSION_CLEANUP_INTERVAL_MS = 30_000
51
- /** Approved transactions remembered per originator. A token send signs right
52
- * after its createAction, so a handful covers any honest app; the cap keeps
53
- * a looping one from growing the map without bound. */
54
- const MAX_AUTHORIZED_TRANSACTIONS_PER_ORIGINATOR = 8
55
-
56
- /** Token-protocol methods the Mandala lib never calls: refused outright. */
57
- const REFUSED_KEY_METHODS = new Set(['encrypt', 'decrypt', 'createHmac', 'verifyHmac'])
58
-
59
- /**
60
- * The digest a `createSignature` call will actually sign: `hashToDirectlySign`
61
- * as given, otherwise SHA-256 of `data` (what ProtoWallet does). Undefined
62
- * for anything malformed, which the caller then refuses.
63
- */
64
- export function signedDigestHex(args: unknown): string | undefined {
65
- if (args === null || typeof args !== 'object') return undefined
66
- const { hashToDirectlySign, data } = args as { hashToDirectlySign?: unknown; data?: unknown }
67
- const bytes = (value: unknown): number[] | undefined => {
68
- if (!Array.isArray(value) && !(value instanceof Uint8Array)) return undefined
69
- const out = Array.from(value as ArrayLike<unknown>)
70
- return out.every(b => Number.isInteger(b) && (b as number) >= 0 && (b as number) <= 255)
71
- ? (out as number[])
72
- : undefined
73
- }
74
- if (hashToDirectlySign !== undefined) {
75
- const hash = bytes(hashToDirectlySign)
76
- return hash !== undefined && hash.length === 32 ? Utils.toHex(hash) : undefined
77
- }
78
- const payload = bytes(data)
79
- return payload !== undefined ? Utils.toHex(Hash.sha256(payload)) : undefined
80
- }
81
-
82
- /**
83
- * The BIP-143 sighash (SIGHASH_ALL|FORKID, what `walletMandalaUnlock` signs
84
- * by default) of every input of a signable transaction. An input whose
85
- * source is not in the BEEF cannot be hashed and is skipped: it is not one
86
- * the wallet can be asked to sign for anyway.
87
- */
88
- export function authorizedSighashes(atomicBEEF: number[] | Uint8Array): Set<string> {
89
- const tx = Transaction.fromAtomicBEEF(Array.from(atomicBEEF))
90
- const digests = new Set<string>()
91
- for (let i = 0; i < tx.inputs.length; i++) {
92
- try {
93
- digests.add(Utils.toHex(Hash.hash256(tx.preimage(i))))
94
- } catch {
95
- // No source transaction for this input.
96
- }
97
- }
98
- return digests
99
- }
100
-
101
- /**
102
- * Normalises an outpoint the same way the SDK's own `Number(...)` coercion
103
- * of a vout would (mirrors `services/vault/guard.ts`'s own
104
- * `canonicalOutpoint`, kept as a separate small copy rather than a shared
105
- * import so Mandala's permission gate does not depend on Vault's module).
106
- *
107
- * XR-039: `listMandalaTokenOutpoints`'s Set and an input's own `outpoint`
108
- * string have to agree on ONE spelling of the same outpoint, or an alternate
109
- * spelling ("00", "0e0", a differently-cased txid) lets a real token input
110
- * slip past the `.has()` check unmatched. `undefined` for anything that is
111
- * not a well-formed `<64-hex-txid>.<vout>` — callers then never match it
112
- * against anything, which is the safe default.
113
- */
114
- export function canonicalOutpoint(value: string | undefined): string | undefined {
115
- if (typeof value !== 'string') return undefined
116
- const parts = value.split('.')
117
- if (parts.length !== 2 || !/^[0-9a-fA-F]{64}$/.test(parts[0])) return undefined
118
- const vout = Number(parts[1])
119
- if (!Number.isSafeInteger(vout) || vout < 0) return undefined
120
- return `${parts[0].toLowerCase()}.${vout}`
121
- }
122
-
123
- /** One `listOutputs`-shaped page, as `listAllOutpoints` needs to see it. */
124
- export interface OutpointListPage {
125
- outputs: { outpoint: string }[]
126
- totalOutputs?: number
127
- }
128
-
129
- /**
130
- * Every outpoint a paged listing reports, to completion, canonicalized.
131
- *
132
- * XR-039: `listMandalaTokenOutpoints` (WalletContext.tsx) used to read a
133
- * single capped page and call that the whole basket — a spend of an input
134
- * past that page read as "not a token input" to every caller of the Set this
135
- * builds, exactly the same balance-truncation bug `core/localpay/build.ts`'s
136
- * `listTokenBasket` and `core/mandala/createRuntime.ts`'s `listTokenOutputs`
137
- * were already fixed for. Same paging discipline here: the wallet's own
138
- * `totalOutputs` ends the loop when it reports one, a short/empty page ends
139
- * it otherwise, and `maxPages` is the hard stop against a wallet that ignores
140
- * `offset` or reports a total it never actually serves.
141
- *
142
- * A pure function over an injected `list` rather than a method on the wallet
143
- * itself so this loop — the actual security-relevant logic, not just glue —
144
- * is unit-testable without a real wallet/storage stack.
145
- */
146
- export async function listAllOutpoints(
147
- list: (limit: number, offset: number) => Promise<OutpointListPage>,
148
- pageSize = 1000,
149
- maxPages = 1000
150
- ): Promise<Set<string>> {
151
- const outpoints = new Set<string>()
152
- let offset = 0
153
- for (let page = 0; page < maxPages; page++) {
154
- const { outputs, totalOutputs } = await list(pageSize, offset)
155
- for (const o of outputs) {
156
- const canonical = canonicalOutpoint(o.outpoint)
157
- if (canonical !== undefined) outpoints.add(canonical)
158
- }
159
- // An empty page always ends it — that, plus the page ceiling, is what
160
- // keeps a wallet that ignores `offset` from looping forever.
161
- if (outputs.length === 0) break
162
- offset += outputs.length
163
- if (typeof totalOutputs === 'number') {
164
- // The wallet's own count is authoritative when it reports one. A SHORT
165
- // page must not end the loop here: a wallet may cap `limit` below what
166
- // was asked for, and treating that cap as "end of basket" would
167
- // re-introduce the truncation this loop exists to remove.
168
- if (offset >= totalOutputs) break
169
- } else if (outputs.length < pageSize) {
170
- break
171
- }
172
- }
173
- return outpoints
174
- }
175
-
176
- export interface MandalaAssetMetadata {
177
- label?: string
178
- ticker?: string
179
- /** Base-10 display decimals (e.g. 2 for cents-style tokens). Absent/non-numeric
180
- * means "unknown" — every amount display falls back to raw base units. */
181
- decimals?: number
182
- }
183
-
184
- export interface MandalaTokenModuleDeps {
185
- /** Our own app's originator — calls carrying it pass through with zero prompts. */
186
- adminOriginator: string
187
- /** Same shape as BTMS's requestTokenAccess: app id + JSON message -> approved? */
188
- requestTokenAccess: (app: string, message: string) => Promise<boolean>
189
- /** Optional friendly name/ticker/decimals for the prompt copy. Never gates anything —
190
- * a throwing or null-returning resolver just means the raw assetId (in base units) is shown. */
191
- resolveAssetMetadata: (assetId: string) => Promise<MandalaAssetMetadata | null>
192
- /**
193
- * Adversarial-review finding (2): every outpoint (`'txid.vout'`) this
194
- * wallet currently holds in `MANDALA_BASKET`, via the admin-originator
195
- * wallet's own `listOutputs({basket: MANDALA_BASKET, ...})` — i.e. a call
196
- * that itself passes through this module with zero prompts (see the
197
- * admin pass-through branch in `onRequest`). Used to detect a
198
- * `createAction` that spends token coins purely through `inputs`, which
199
- * `WalletPermissionsManager`'s basket-routing (keyed on OUTPUTS only,
200
- * `collectNonPBaskets`) would otherwise miss entirely. A throwing
201
- * implementation is treated as "no token inputs found" — this dep can
202
- * only ever ADD a prompt, never remove one that would otherwise fire from
203
- * the output-side checks, so a fault here fails toward "no extra info",
204
- * not toward "silently allow".
205
- */
206
- listTokenOutpoints: () => Promise<Set<string>>
207
- /**
208
- * XR-041: resolves ONE currently-held `MANDALA_BASKET` outpoint to its
209
- * decoded `{assetId, amount}`, via the admin-originator wallet's own
210
- * listing — never from anything a caller claims. `null` for an outpoint
211
- * this device does not currently hold as a Mandala coin (already spent,
212
- * never was one, or an unresolvable/malformed one) — `promptForRelinquish`
213
- * fails CLOSED on `null` rather than falling back to unlabeled copy: an
214
- * app must not be able to get an unnamed holding removed.
215
- */
216
- resolveMandalaOutput: (outpoint: string) => Promise<DecodedMandalaOutput | null>
217
- }
218
-
219
- /** The slice of `CreateActionOutput` this module reads. Structural, not the
220
- * full SDK type, so a test can pass a plain object. */
221
- interface MandalaCreateActionOutputLike {
222
- lockingScript?: string
223
- basket?: string
224
- customInstructions?: string
225
- }
226
-
227
- /** True for an output the Mandala lib marks as the payment itself
228
- * (customInstructions `direction: 'sent'`). In a send to yourself that
229
- * output stays in the basket, so the basket alone would show it as change. */
230
- function isMarkedSent(output: MandalaCreateActionOutputLike): boolean {
231
- if (typeof output?.customInstructions !== 'string') return false
232
- try {
233
- return (JSON.parse(output.customInstructions) as { direction?: unknown })?.direction === 'sent'
234
- } catch {
235
- return false
236
- }
237
- }
238
- /** The slice of `RelinquishOutputArgs` this module reads. */
239
- interface MandalaRelinquishOutputArgsLike {
240
- basket?: string
241
- output?: string
242
- }
243
- /** The slice of `CreateActionInput` this module reads. */
244
- interface MandalaCreateActionInputLike {
245
- outpoint?: string
246
- }
247
- interface MandalaCreateActionArgsLike {
248
- outputs?: MandalaCreateActionOutputLike[]
249
- inputs?: MandalaCreateActionInputLike[]
250
- }
251
-
252
- interface MandalaInternalizeOutputLike {
253
- outputIndex: number
254
- protocol?: string
255
- insertionRemittance?: { basket?: string }
256
- }
257
- interface MandalaInternalizeActionArgsLike {
258
- /** AtomicBEEF — the SDK type allows either representation; both feed
259
- * `Transaction.fromAtomicBEEF` directly. */
260
- tx?: number[] | Uint8Array
261
- outputs?: MandalaInternalizeOutputLike[]
262
- }
263
-
264
- export interface DecodedMandalaOutput {
265
- assetId: string
266
- amount: number
267
- }
268
-
269
- /** One asset's send/change totals for a createAction spend prompt. */
270
- export interface MandalaSpendLine {
271
- assetId: string
272
- sendAmount: number
273
- changeAmount: number
274
- tokenName?: string
275
- decimals?: number
276
- /** Decimal-formatted, e.g. "25.00 USDX"; base units + a short assetId when
277
- * decimals could not be resolved. */
278
- display: string
279
- }
280
-
281
- /** One asset's credited total for an internalizeAction credit prompt. */
282
- export interface MandalaCreditLine {
283
- assetId: string
284
- creditAmount: number
285
- tokenName?: string
286
- decimals?: number
287
- display: string
288
- }
289
-
290
- /**
291
- * Decodes one output's locking script as a Mandala token. Never throws:
292
- * `MandalaToken.decode` throws on anything that isn't its exact 8-chunk
293
- * shape, and every caller here treats "not a Mandala output" the same way
294
- * whether the script is empty, foreign, or simply malformed.
295
- */
296
- export function tryDecodeMandalaOutput(lockingScriptHex: string | undefined): DecodedMandalaOutput | null {
297
- if (!lockingScriptHex) return null
298
- try {
299
- const script = LockingScript.fromHex(lockingScriptHex)
300
- const decoded = MandalaToken.decode(script)
301
- return { assetId: decoded.assetId, amount: decoded.amount }
302
- } catch {
303
- return null
304
- }
305
- }
306
-
307
- /** One `listOutputs`-shaped page carrying locking scripts, as `resolveMandalaOutput` needs them. */
308
- export interface ScriptedOutputPage {
309
- outputs: { outpoint: string; lockingScript?: string }[]
310
- totalOutputs?: number
311
- }
312
-
313
- /**
314
- * Finds ONE currently-held outpoint in a paged listing, to completion, and
315
- * decodes its Mandala token script.
316
- *
317
- * XR-041: `promptForRelinquish` used to authorize removing a holding with no
318
- * more than the bare action name — "wants to remove a Mandala token holding
319
- * from your wallet" — never which one. This is what lets it name the target:
320
- * `assetId`/`amount` resolved from the wallet's OWN current listing, never
321
- * from anything the caller claims. `null` — not found (already spent, never
322
- * held, or `target` malformed), or the page ceiling was hit without a match —
323
- * is the caller's signal to fail closed rather than approve an unlabeled
324
- * removal; same truncation discipline as `listAllOutpoints` (XR-039), because
325
- * a holding on page two must be just as nameable as one on page one.
326
- */
327
- export async function resolveMandalaOutput(
328
- list: (limit: number, offset: number) => Promise<ScriptedOutputPage>,
329
- target: string,
330
- pageSize = 1000,
331
- maxPages = 1000
332
- ): Promise<DecodedMandalaOutput | null> {
333
- const canonicalTarget = canonicalOutpoint(target)
334
- if (canonicalTarget === undefined) return null
335
- let offset = 0
336
- for (let page = 0; page < maxPages; page++) {
337
- const { outputs, totalOutputs } = await list(pageSize, offset)
338
- for (const o of outputs) {
339
- if (canonicalOutpoint(o.outpoint) === canonicalTarget) return tryDecodeMandalaOutput(o.lockingScript)
340
- }
341
- // An empty page always ends it — that, plus the page ceiling, is what
342
- // keeps a wallet that ignores `offset` from looping forever.
343
- if (outputs.length === 0) break
344
- offset += outputs.length
345
- if (typeof totalOutputs === 'number') {
346
- // The wallet's own count is authoritative when it reports one. A SHORT
347
- // page must not end the loop here: a wallet may cap `limit` below what
348
- // was asked for, and treating that cap as "end of basket" would
349
- // re-introduce the truncation this loop exists to remove.
350
- if (offset >= totalOutputs) break
351
- } else if (outputs.length < pageSize) {
352
- break
353
- }
354
- }
355
- return null
356
- }
357
-
358
- /** A short, human-scannable form of a long `'<64-hex>.<vout>'` assetId. */
359
- function shortAssetId(assetId: string): string {
360
- if (!assetId || assetId.length <= 16) return assetId
361
- return `${assetId.slice(0, 8)}…${assetId.slice(-6)}`
362
- }
363
-
364
- /**
365
- * "25.00 USDX" when decimals are known (clamped to a sane 0-18 range,
366
- * mirroring common token-decimals conventions); "2500000 a1b2c3d4…ef01.0"
367
- * (raw base units + a short assetId form) when they are not — adversarial-
368
- * review finding (4): never show raw base units next to a resolved ticker,
369
- * and never guess a decimals value we were not actually given.
370
- */
371
- function formatTokenAmount(
372
- baseUnits: number,
373
- decimals: number | undefined,
374
- tokenName: string | undefined,
375
- assetId: string
376
- ): string {
377
- if (typeof decimals === 'number' && Number.isInteger(decimals) && decimals >= 0 && decimals <= 18) {
378
- const scaled = baseUnits / 10 ** decimals
379
- const unit = tokenName || shortAssetId(assetId)
380
- return `${scaled.toFixed(decimals)} ${unit}`
381
- }
382
- return `${baseUnits} ${shortAssetId(assetId)}`
383
- }
384
-
385
- /**
386
- * Adversarial-review finding (2): the P-label `WalletPermissionsManager`'s
387
- * `listActions`/`createAction` label-routing keys on. Two independent uses:
388
- * - `wrapCreateActionForTokenInputs` (below) injects it onto a createAction
389
- * call whose INPUTS spend `'p mandala'` coins but whose outputs carry no
390
- * `'p mandala'`-basket output — the manager's own basket-only routing
391
- * would otherwise never call `onRequest` for such a call at all.
392
- * - It also then persists as a real label on the resulting action, so it
393
- * doubles as the "Mandala action" label finding (3) calls for: apps that
394
- * build Mandala createAction calls directly (rather than through the
395
- * wrapper) should add this same label so `listActions({labels:[...]})`
396
- * P-routes to this module too — label-routing is `listActions`' ONLY
397
- * signal, `MANDALA_BASKET` alone does not make a listActions call route
398
- * here. This module cannot enforce that from inside `onRequest` (it never
399
- * sees the call before the manager decides whether to route it at all);
400
- * it is a wiring requirement on every Mandala action-creation call site.
401
- */
402
- export const MANDALA_ACTION_LABEL = 'p mandala token-spend'
403
-
404
- export class MandalaTokenModule implements PermissionsModule {
405
- private readonly deps: MandalaTokenModuleDeps
406
-
407
- /**
408
- * Session-authorization cache — same shape as BasicTokenModule's: a
409
- * time-limited (60s) grant per originator, refreshed by every prompt this
410
- * module shows (spend/credit/access alike), consulted only by the
411
- * once-per-session access checks (`listOutputs`/`listActions`).
412
- * `relinquishOutput` deliberately does NOT read or write this cache —
413
- * adversarial-review finding (5): it is its own authorization class.
414
- */
415
- private readonly sessionAuthorizations: Map<string, number> = new Map()
416
- /** Per originator: the input sighashes of each transaction the user
417
- * approved through `promptForSpend`/`promptGeneric`, newest last. */
418
- private readonly authorizedTransactions: Map<string, { digests: Set<string>; timestamp: number }[]> = new Map()
419
- private readonly cleanupTimer: ReturnType<typeof setInterval>
420
-
421
- constructor(deps: MandalaTokenModuleDeps) {
422
- if (!deps || typeof deps.requestTokenAccess !== 'function') {
423
- throw new Error('requestTokenAccess callback is required')
424
- }
425
- if (!deps.adminOriginator || typeof deps.adminOriginator !== 'string') {
426
- throw new Error('adminOriginator is required')
427
- }
428
- this.deps = deps
429
- this.cleanupTimer = setInterval(() => this.cleanupExpiredSessions(), SESSION_CLEANUP_INTERVAL_MS)
430
- // Never keep a test runner or RN's timer host alive just for this sweep.
431
- ;(this.cleanupTimer as unknown as { unref?: () => void }).unref?.()
432
- }
433
-
434
- private cleanupExpiredSessions(): void {
435
- const now = Date.now()
436
- for (const [originator, timestamp] of this.sessionAuthorizations.entries()) {
437
- if (now - timestamp > SESSION_TIMEOUT_MS) {
438
- this.sessionAuthorizations.delete(originator)
439
- }
440
- }
441
- for (const originator of this.authorizedTransactions.keys()) this.liveAuthorizedTransactions(originator)
442
- }
443
-
444
- /** This originator's unexpired approved transactions; prunes the rest. */
445
- private liveAuthorizedTransactions(originator: string): { digests: Set<string>; timestamp: number }[] {
446
- const now = Date.now()
447
- const live = (this.authorizedTransactions.get(originator) ?? []).filter(
448
- t => now - t.timestamp <= SESSION_TIMEOUT_MS
449
- )
450
- if (live.length === 0) this.authorizedTransactions.delete(originator)
451
- else this.authorizedTransactions.set(originator, live)
452
- return live
453
- }
454
-
455
- private hasSessionAuthorization(originator: string): boolean {
456
- const timestamp = this.sessionAuthorizations.get(originator)
457
- if (!timestamp) return false
458
- if (Date.now() - timestamp > SESSION_TIMEOUT_MS) {
459
- this.sessionAuthorizations.delete(originator)
460
- return false
461
- }
462
- return true
463
- }
464
-
465
- private grantSessionAuthorization(originator: string): void {
466
- this.sessionAuthorizations.set(originator, Date.now())
467
- }
468
-
469
- /**
470
- * THE ONLY MANDALA-SPECIFIC LINE (per spec §8.3): our own app's lib calls
471
- * always carry `adminOriginator` (the wallet's `withAdminOriginator`
472
- * wrapper) — auto-approve them with no prompt, preserving "no review
473
- * screen, the CTA is the confirmation". Everyone else is a paired external
474
- * caller and is prompted, exactly like BTMS.
475
- */
476
- async onRequest(req: { method: string; args: object; originator: string }): Promise<{ args: object }> {
477
- const { method, args, originator } = req
478
-
479
- if (!method || typeof method !== 'string') throw new Error('Invalid method')
480
- if (!originator || typeof originator !== 'string') throw new Error('Invalid originator')
481
- if (!args || typeof args !== 'object') throw new Error('Invalid args')
482
-
483
- if (originator === this.deps.adminOriginator) {
484
- return { args }
485
- }
486
-
487
- switch (method) {
488
- case 'listOutputs': {
489
- // customInstructions come back when asked for: see finding (1).
490
- await this.promptOnceForAccess(originator, 'listOutputs')
491
- break
492
- }
493
- case 'listActions':
494
- // Adversarial-review finding (3): same once-per-session gate as
495
- // listOutputs. Reaching this handler at all depends on the calling
496
- // action carrying a 'p mandala ...' label — see MANDALA_ACTION_LABEL's
497
- // doc above.
498
- await this.promptOnceForAccess(originator, 'listActions')
499
- break
500
- case 'relinquishOutput':
501
- await this.promptForRelinquish(args as MandalaRelinquishOutputArgsLike, originator)
502
- break
503
- case 'createAction':
504
- await this.promptForSpend(args as MandalaCreateActionArgsLike, originator)
505
- break
506
- case 'internalizeAction':
507
- await this.promptForCredit(args as MandalaInternalizeActionArgsLike, originator)
508
- break
509
- case 'createSignature':
510
- await this.authorizeSignature(args, originator)
511
- break
512
- default:
513
- if (REFUSED_KEY_METHODS.has(method)) {
514
- throw new Error(`Mandala token keys cannot be used for ${method}`)
515
- }
516
- // getPublicKey/verifySignature, and any method a future manager
517
- // version routes here, pass through.
518
- break
519
- }
520
-
521
- return { args }
522
- }
523
-
524
- /**
525
- * After an approved `createAction` (`onRequest` threw otherwise), remembers
526
- * the input sighashes of the transaction the wallet built, so the app's
527
- * `createSignature` calls for exactly that transaction need no second
528
- * prompt. A response that cannot be hashed is passed on unchanged and
529
- * simply leaves those signatures to `authorizeSignature`'s own prompt.
530
- */
531
- async onResponse(res: unknown, context: { method: string; originator: string }): Promise<unknown> {
532
- if (context.method !== 'createAction' || context.originator === this.deps.adminOriginator) return res
533
- const tx = (res as { signableTransaction?: { tx?: number[] | Uint8Array } } | null)?.signableTransaction?.tx
534
- if (tx === undefined) return res
535
- let digests: Set<string>
536
- try {
537
- digests = authorizedSighashes(tx)
538
- } catch {
539
- return res
540
- }
541
- const live = this.liveAuthorizedTransactions(context.originator)
542
- live.push({ digests, timestamp: Date.now() })
543
- this.authorizedTransactions.set(context.originator, live.slice(-MAX_AUTHORIZED_TRANSACTIONS_PER_ORIGINATOR))
544
- return res
545
- }
546
-
547
- /**
548
- * `createSignature` under the token protocol from a connected app. Signing
549
- * an input of a transaction the user just approved goes ahead; anything
550
- * else (an unrouted createAction, an expired approval, a digest that is not
551
- * one of that transaction's) is asked about on its own. The prompt never
552
- * grants a session: one approval is one signature.
553
- */
554
- private async authorizeSignature(args: object, originator: string): Promise<void> {
555
- const digest = signedDigestHex(args)
556
- if (digest === undefined) throw new Error('Invalid createSignature args')
557
- if (this.liveAuthorizedTransactions(originator).some(t => t.digests.has(digest))) return
558
- const approved = await this.deps.requestTokenAccess(originator, JSON.stringify({ type: 'mandala_signature' }))
559
- if (!approved) {
560
- throw new Error('User denied permission to sign with a Mandala token key')
561
- }
562
- }
563
-
564
- /** listOutputs / listActions — once per 60s session, like BTMS's promptForBTMSAccess. */
565
- private async promptOnceForAccess(originator: string, action: 'listOutputs' | 'listActions'): Promise<void> {
566
- if (this.hasSessionAuthorization(originator)) return
567
-
568
- const message = JSON.stringify({ type: 'mandala_access', action })
569
- const approved = await this.deps.requestTokenAccess(originator, message)
570
- if (!approved) {
571
- throw new Error('User denied permission to access Mandala tokens')
572
- }
573
- this.grantSessionAuthorization(originator)
574
- }
575
-
576
- /**
577
- * Adversarial-review finding (5): relinquishOutput is its own
578
- * authorization class. It is never satisfied by an existing
579
- * spend/credit/access session (no `hasSessionAuthorization` check), and it
580
- * never grants one either (no `grantSessionAuthorization` call) — removing
581
- * a holding from the wallet is consequential enough that every call must
582
- * show its own prompt, and approving it must not silently unlock
583
- * listOutputs/listActions for the rest of the session window.
584
- *
585
- * XR-041: the prompt used to say only "wants to remove a Mandala token
586
- * holding from your wallet" — never which one, or how much. `args.output`
587
- * is resolved against this device's OWN current listing (never trusted
588
- * from the caller) into `{assetId, amount}` before anything is shown, and
589
- * an unresolved target fails the whole call closed — a consequential,
590
- * irreversible-feeling removal must never be approved uninformed.
591
- */
592
- private async promptForRelinquish(args: MandalaRelinquishOutputArgsLike, originator: string): Promise<void> {
593
- const outpoint = typeof args?.output === 'string' ? args.output : undefined
594
- let resolved: DecodedMandalaOutput | null = null
595
- if (outpoint) {
596
- try {
597
- resolved = await this.deps.resolveMandalaOutput(outpoint)
598
- } catch {
599
- resolved = null
600
- }
601
- }
602
- if (!resolved) {
603
- throw new Error('Could not identify the Mandala holding to be removed')
604
- }
605
- const { tokenName, decimals } = await this.resolveAssetDisplay(resolved.assetId)
606
- const message = JSON.stringify({
607
- type: 'mandala_access',
608
- action: 'relinquishOutput',
609
- assetId: resolved.assetId,
610
- tokenName,
611
- amount: resolved.amount,
612
- display: formatTokenAmount(resolved.amount, decimals, tokenName, resolved.assetId),
613
- outpoint
614
- })
615
- const approved = await this.deps.requestTokenAccess(originator, message)
616
- if (!approved) {
617
- throw new Error('User denied permission to access Mandala tokens')
618
- }
619
- }
620
-
621
- /**
622
- * createAction with an output in `'p mandala'` — always prompts (mirrors
623
- * BTMS's `handleCreateAction`, which never skips on an existing session;
624
- * only the access checks above do that), then refreshes the session so a
625
- * following listOutputs/listActions within the window does not re-prompt.
626
- *
627
- * Adversarial-review finding (2): also gates on INPUTS. Basket-routing
628
- * only ever reaches this method via a `'p mandala'`-basketed/decodable
629
- * OUTPUT (see `extractOutputAmountsByAsset`) or the `MANDALA_ACTION_LABEL`
630
- * the `wrapCreateActionForTokenInputs` wrapper injects — a spend with no
631
- * such output (e.g. a full-balance spend with no change) could otherwise
632
- * decode to zero here even once routed. `anyInputIsTokenCoin` is a second,
633
- * independent signal so this method still emits a `'mandala_spend'`
634
- * prompt (never the fully-generic fallback) whenever any input is a known
635
- * token coin, even if no output tells us how much.
636
- */
637
- private async promptForSpend(args: MandalaCreateActionArgsLike, originator: string): Promise<void> {
638
- const totals = this.extractOutputAmountsByAsset(args?.outputs)
639
-
640
- if (totals.size === 0 && !(await this.anyInputIsTokenCoin(args?.inputs))) {
641
- // Nothing decodable (every output failed to decode, or none present)
642
- // and no input is a known token coin either — fall back to a generic
643
- // prompt rather than guessing. Mirrors BasicTokenModule's
644
- // promptForGenericAuthorization fallback.
645
- await this.promptGeneric(originator, 'spend')
646
- return
647
- }
648
-
649
- const lines = await this.buildSpendLines(totals)
650
- // Back-compat top-level fields mirror the FIRST/primary asset (today's
651
- // single-asset behavior, unchanged); `lines` carries the full,
652
- // decimal-formatted, one-entry-per-asset breakdown (finding 4).
653
- // `JSON.stringify` drops `undefined` values, so an empty `lines` array
654
- // (token-input-only, nothing decodable) naturally omits them.
655
- const primary = lines[0]
656
- const message = JSON.stringify({
657
- type: 'mandala_spend',
658
- sendAmount: primary?.sendAmount,
659
- changeAmount: primary?.changeAmount,
660
- assetId: primary?.assetId,
661
- tokenName: primary?.tokenName,
662
- lines
663
- })
664
- const approved = await this.deps.requestTokenAccess(originator, message)
665
- if (!approved) {
666
- // Exact BTMS wording (spec §8.6): denial "throws the same shape as
667
- // BTMS ('User denied permission to spend tokens')".
668
- throw new Error('User denied permission to spend tokens')
669
- }
670
- this.grantSessionAuthorization(originator)
671
- }
672
-
673
- /** internalizeAction inserting into `'p mandala'` — an app crediting ITSELF. */
674
- private async promptForCredit(args: MandalaInternalizeActionArgsLike, originator: string): Promise<void> {
675
- const insertions = (args?.outputs ?? []).filter(
676
- o => o?.protocol === 'basket insertion' && o?.insertionRemittance?.basket === MANDALA_BASKET
677
- )
678
-
679
- const totals = new Map<string, number>()
680
- if (insertions.length > 0 && args?.tx) {
681
- try {
682
- const tx = Transaction.fromAtomicBEEF(args.tx)
683
- for (const insertion of insertions) {
684
- const output = tx.outputs[insertion.outputIndex]
685
- const decoded = output?.lockingScript ? tryDecodeMandalaOutput(output.lockingScript.toHex()) : null
686
- if (decoded) {
687
- totals.set(decoded.assetId, (totals.get(decoded.assetId) ?? 0) + decoded.amount)
688
- }
689
- }
690
- } catch {
691
- // Unparseable AtomicBEEF -- fall through to the zero-amount branch
692
- // below rather than throw; a decode failure is never fatal here.
693
- }
694
- }
695
-
696
- if (totals.size === 0) {
697
- await this.promptGeneric(originator, 'credit')
698
- return
699
- }
700
-
701
- const lines = await this.buildCreditLines(totals)
702
- const primary = lines[0]
703
- const message = JSON.stringify({
704
- type: 'mandala_credit',
705
- creditAmount: primary?.creditAmount,
706
- assetId: primary?.assetId,
707
- tokenName: primary?.tokenName,
708
- lines
709
- })
710
- const approved = await this.deps.requestTokenAccess(originator, message)
711
- if (!approved) {
712
- throw new Error('User denied permission to credit Mandala tokens')
713
- }
714
- this.grantSessionAuthorization(originator)
715
- }
716
-
717
- private async promptGeneric(originator: string, context: 'spend' | 'credit'): Promise<void> {
718
- const message = JSON.stringify({ type: 'mandala_generic', context })
719
- const approved = await this.deps.requestTokenAccess(originator, message)
720
- if (!approved) {
721
- throw new Error('User denied permission to spend Mandala tokens')
722
- }
723
- this.grantSessionAuthorization(originator)
724
- }
725
-
726
- /**
727
- * Sums send vs. change over every Mandala-decodable output, GROUPED BY
728
- * assetId (adversarial-review finding 4 — a createAction touching more
729
- * than one asset previously collapsed every asset's amounts into one
730
- * running total under whichever assetId was seen first). An output that
731
- * carries the `'p mandala'` basket is change (stays with us) unless the lib
732
- * marks it as the payment (a send to yourself); one that does not is the
733
- * recipient's (Mandala payer outputs are otherwise never basketed).
734
- * A script that fails to decode is silently skipped, not fatal —
735
- * `tryDecodeMandalaOutput` never throws.
736
- */
737
- private extractOutputAmountsByAsset(
738
- outputs: MandalaCreateActionOutputLike[] | undefined
739
- ): Map<string, { sendAmount: number; changeAmount: number }> {
740
- const totals = new Map<string, { sendAmount: number; changeAmount: number }>()
741
-
742
- for (const output of outputs ?? []) {
743
- const decoded = tryDecodeMandalaOutput(output?.lockingScript)
744
- if (!decoded) continue
745
- const entry = totals.get(decoded.assetId) ?? { sendAmount: 0, changeAmount: 0 }
746
- // An app can only make the prompt show MORE as sent this way, never less:
747
- // an unbasketed output always counts as sent.
748
- if (output.basket === MANDALA_BASKET && !isMarkedSent(output)) {
749
- entry.changeAmount += decoded.amount
750
- } else {
751
- entry.sendAmount += decoded.amount
752
- }
753
- totals.set(decoded.assetId, entry)
754
- }
755
-
756
- return totals
757
- }
758
-
759
- /**
760
- * Adversarial-review finding (2): resolves each input outpoint against
761
- * `deps.listTokenOutpoints()` (the admin-originator wallet's own
762
- * `'p mandala'`-basket listing) and reports whether any of them is a
763
- * token coin this wallet holds. A throwing/failing `listTokenOutpoints`
764
- * is treated as "no token inputs found" — this is a pure ADD-a-prompt
765
- * signal on top of the output-side checks, so failing open here never
766
- * removes a prompt the output side would otherwise have shown.
767
- */
768
- private async anyInputIsTokenCoin(inputs: MandalaCreateActionInputLike[] | undefined): Promise<boolean> {
769
- if (!inputs || inputs.length === 0) return false
770
- let tokenOutpoints: Set<string>
771
- try {
772
- tokenOutpoints = await this.deps.listTokenOutpoints()
773
- } catch {
774
- return false
775
- }
776
- return inputs.some(input => {
777
- const outpoint = canonicalOutpoint(input?.outpoint)
778
- return outpoint !== undefined && tokenOutpoints.has(outpoint)
779
- })
780
- }
781
-
782
- private async buildSpendLines(
783
- totals: Map<string, { sendAmount: number; changeAmount: number }>
784
- ): Promise<MandalaSpendLine[]> {
785
- const lines: MandalaSpendLine[] = []
786
- for (const [assetId, { sendAmount, changeAmount }] of totals) {
787
- const { tokenName, decimals } = await this.resolveAssetDisplay(assetId)
788
- lines.push({
789
- assetId,
790
- sendAmount,
791
- changeAmount,
792
- tokenName,
793
- decimals,
794
- display: formatTokenAmount(sendAmount, decimals, tokenName, assetId)
795
- })
796
- }
797
- return lines
798
- }
799
-
800
- private async buildCreditLines(totals: Map<string, number>): Promise<MandalaCreditLine[]> {
801
- const lines: MandalaCreditLine[] = []
802
- for (const [assetId, creditAmount] of totals) {
803
- const { tokenName, decimals } = await this.resolveAssetDisplay(assetId)
804
- lines.push({
805
- assetId,
806
- creditAmount,
807
- tokenName,
808
- decimals,
809
- display: formatTokenAmount(creditAmount, decimals, tokenName, assetId)
810
- })
811
- }
812
- return lines
813
- }
814
-
815
- private async resolveAssetDisplay(assetId: string | undefined): Promise<{ tokenName?: string; decimals?: number }> {
816
- if (!assetId) return {}
817
- try {
818
- const meta = await this.deps.resolveAssetMetadata(assetId)
819
- return {
820
- tokenName: meta?.ticker || meta?.label || undefined,
821
- decimals: typeof meta?.decimals === 'number' ? meta.decimals : undefined
822
- }
823
- } catch {
824
- // resolveAssetMetadata is caller-injected and may be a stub or may
825
- // fail (network, missing registry entry) — never let that block or
826
- // fail a permission prompt; the assetId alone is still shown.
827
- return {}
828
- }
829
- }
830
- }
831
-
832
- /**
833
- * Adversarial-review finding (2), second half: `WalletPermissionsManager`
834
- * only ever routes a `createAction` call through a P-module when the call's
835
- * OUTPUTS or LABELS name a `'p '`-scheme (`collectNonPBaskets`/
836
- * `splitLabelsByPermissionModule`, confirmed against
837
- * `@bsv/wallet-toolbox-mobile`'s `WalletPermissionsManager.js`) — INPUTS are
838
- * never scanned. A createAction that spends `'p mandala'` inputs with no
839
- * basketed/decodable Mandala output (e.g. a full-balance spend with no
840
- * change) therefore never reaches `MandalaTokenModule.onRequest` at all, no
841
- * matter what that method does internally.
842
- *
843
- * This wraps the PUBLISHED `WalletPermissionsManager` (or anything
844
- * shaped like it) so that a `createAction` call whose inputs reference a
845
- * known `'p mandala'` outpoint gets `MANDALA_ACTION_LABEL` injected into its
846
- * `labels` BEFORE the manager's own routing decision runs — which makes the
847
- * manager's label-routing pick up the module exactly as if the caller had
848
- * labeled the action itself (see `MANDALA_ACTION_LABEL`'s doc). Every other
849
- * method/property passes through untouched. `adminOriginator` calls are
850
- * short-circuited with zero work: the module already grants those a
851
- * zero-prompt pass-through unconditionally (see the class doc), so injecting
852
- * the label there would only add a `listTokenOutpoints()` round-trip to
853
- * EVERY admin createAction call — including the app's own everyday,
854
- * non-Mandala spends — for no gating benefit at all.
855
- *
856
- * WIRING: wrap the RAW `permissionsManager` with this FIRST, THEN apply
857
- * `guardVaultAccess` around the result — never the other way around.
858
- * `guardVaultAccess` has its own idempotent-re-wrap dedup
859
- * (`GUARD_TARGETS`/`GUARDED_PROXIES` in `services/vault/guard.ts`), which
860
- * several screens rely on (`guardVaultAccess(managers.permissionsManager,
861
- * ADMIN_ORIGINATOR)` again in e.g. `PairScreen.tsx`/`ConnectionsScreen.tsx`)
862
- * to avoid creating a second guard runtime around the same wallet. That
863
- * dedup only recognizes an object IT previously wrapped — putting this
864
- * wrapper's Proxy on the OUTSIDE (wrapping an already-guarded manager) would
865
- * make every such re-application invisible to the dedup and silently
866
- * double-guard the wallet with a second runtime that has no storage lookup
867
- * (so it refuses every external call naming an outpoint) and its own
868
- * listActions queue. Wrapping the raw manager first, then guarding the
869
- * result, keeps the publicly published value exactly what `guardVaultAccess`
870
- * itself produced and expects to see again — in this app that is
871
- * `WalletContext.tsx`'s
872
- * `newManagers.permissionsManager = guardVaultAccess(
873
- * wrapCreateActionForTokenInputs(permissionsManager, listMandalaTokenOutpoints,
874
- * adminOriginator), adminOriginator)`. A manager constructed anywhere else
875
- * (a test double, a future second entry point) that skips this wrapper
876
- * reopens exactly the gap described above.
877
- */
878
- export function wrapCreateActionForTokenInputs<
879
- T extends { createAction: (args: any, originator: string) => Promise<unknown> }
880
- >(manager: T, listTokenOutpoints: () => Promise<Set<string>>, adminOriginator?: string): T {
881
- return new Proxy(manager, {
882
- get(target, prop, receiver) {
883
- if (prop === 'createAction') {
884
- return async (args: MandalaCreateActionArgsLike & { labels?: string[] }, originator: string) => {
885
- const routedArgs =
886
- originator === adminOriginator
887
- ? args
888
- : await injectMandalaLabelIfTokenInputsPresent(args, listTokenOutpoints)
889
- return target.createAction(routedArgs, originator)
890
- }
891
- }
892
- const value = Reflect.get(target, prop, receiver)
893
- return typeof value === 'function' ? value.bind(target) : value
894
- }
895
- }) as T
896
- }
897
-
898
- async function injectMandalaLabelIfTokenInputsPresent(
899
- args: MandalaCreateActionArgsLike & { labels?: string[] },
900
- listTokenOutpoints: () => Promise<Set<string>>
901
- ): Promise<MandalaCreateActionArgsLike & { labels?: string[] }> {
902
- const inputs = args?.inputs
903
- if (!Array.isArray(inputs) || inputs.length === 0) return args
904
-
905
- const labels = Array.isArray(args.labels) ? args.labels : []
906
- if (labels.includes(MANDALA_ACTION_LABEL)) return args
907
-
908
- let tokenOutpoints: Set<string>
909
- try {
910
- tokenOutpoints = await listTokenOutpoints()
911
- } catch {
912
- // XR-039: forwarding `args` UNCHANGED here is how a full-balance (no
913
- // basketed change) Mandala spend hit by a transient listing fault used to
914
- // reach the manager's generic, no-token-amount-awareness review instead
915
- // of this module's own. `MANDALA_ACTION_LABEL` is the ONLY thing that
916
- // routes an input-only Mandala spend to `MandalaTokenModule.onRequest` at
917
- // all — with no reliable read on whether these inputs spend a token coin,
918
- // fail closed and force it, same as a confirmed match below. Worst case
919
- // (a plain, non-Mandala action) still resolves to `promptForSpend`'s own
920
- // generic fallback, which is a real, interactive approval — never a
921
- // silent one.
922
- return { ...args, labels: [...labels, MANDALA_ACTION_LABEL] }
923
- }
924
-
925
- const spendsTokenInput = inputs.some(input => {
926
- const outpoint = canonicalOutpoint(input?.outpoint)
927
- return outpoint !== undefined && tokenOutpoints.has(outpoint)
928
- })
929
- if (!spendsTokenInput) return args
930
- return { ...args, labels: [...labels, MANDALA_ACTION_LABEL] }
931
- }