@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
@@ -17,6 +17,11 @@ import { KeyDeriver, PrivateKey, MerklePath, Transaction, Utils } from '@bsv/sdk
17
17
  import { DEFAULT_SETTINGS } from './defaultWalletSettings'
18
18
  import { conformWalletResults } from '../services/conformWalletResults'
19
19
  import { SigningPolicyPermissionsManager } from '../services/signingPermissionPolicy'
20
+ import {
21
+ guardTokenPromptHandlers,
22
+ handleSpendingPrompt,
23
+ withdrawPrompts as withdrawPromptsFrom
24
+ } from '../services/permissionPrompts'
20
25
  import { VAULT_RETENTION_MS, ceremony as vaultCeremony } from '../services/vault/ceremonyHost'
21
26
  import { getVaultDriver } from '../services/vault/driver'
22
27
  import { backupAttestation } from '../services/vault/backupAttestation'
@@ -110,35 +115,27 @@ function loadQuietEventSourceClass(): EventSourceCtor {
110
115
  }
111
116
 
112
117
  /**
113
- * `MandalaTokenModuleDeps.resolveAssetMetadata`, over the lib's own registry
114
- * lookup (`@bsv/mandala`'s `resolveAssetMetadata` — overlay lookup,
115
- * SPV-verified genesis, memoized). Only ever affects the display (name AND,
116
- * per adversarial-review finding 4, decimal formatting) in a permission
117
- * prompt, never a decision to prompt or to grant, so a failure is null and
118
- * the prompt falls back to the raw assetId in base units — including on a
119
- * build where `configureMandala` has not run, where the lib throws rather
120
- * than pretending the asset has no name.
118
+ * Dispose this build's color module and drop it from the ref. Sync,
119
+ * idempotent and never throws: it runs at the head of every teardown, before
120
+ * the storage under the module's store is destroyed, so an in-flight
121
+ * `settle()` resolves but no new overlay submit starts against a closing
122
+ * database (IC §2.3 `dispose`).
121
123
  */
122
- async function resolveMandalaAssetMetadata(assetId: string): Promise<MandalaAssetMetadata | null> {
124
+ function disposeColorModule(ref: { current: BuiltColorModule | undefined }): void {
125
+ const built = ref.current
126
+ ref.current = undefined
123
127
  try {
124
- const meta = await resolveAssetMetadata(assetId)
125
- if (!meta) return null
126
- return { label: meta.label, ticker: meta.ticker, decimals: meta.decimals }
127
- } catch {
128
- return null
128
+ built?.module.dispose()
129
+ } catch (error) {
130
+ console.warn('[WalletContext] color module dispose failed:', error)
129
131
  }
130
132
  }
131
133
 
132
- // XR-039: same paging discipline as `core/localpay/build.ts`'s
133
- // `listTokenBasket` and `core/mandala/createRuntime.ts`'s `listTokenOutputs`
134
- // -- a page size generous enough that any realistic basket is one round
135
- // trip, and a hard page ceiling so a wallet that reports a `totalOutputs` it
136
- // never actually serves (or repeats a page forever) cannot spin
137
- // `listMandalaTokenOutpoints` into an infinite loop.
138
- const MANDALA_OUTPOINT_LIST_PAGE = 1000
139
- const MANDALA_OUTPOINT_LIST_MAX_PAGES = 1000
140
-
141
134
  import type { AppChain } from '../config'
135
+ import { effectiveUnverified, loadStoredPolicy, resolvePermissionPolicy } from '../bridge/permissionPolicy'
136
+ import { notifyPromptRaised } from '../bridge/runtime'
137
+ import { hasUnattestedTransport, onUnattestedTransportChange } from '../bridge/runtimeFlags'
138
+ import { buildUnverifiedPermissionsManager } from '../bridge/unverifiedManager'
142
139
  import { DEFAULT_STORAGE_URL, DEFAULT_CHAIN, ADMIN_ORIGINATOR, toWalletChain } from '../config'
143
140
  import { NETWORKS, isAppChain } from '../networks'
144
141
  import { getBackupUrl, getHandleRegistryConfig, getMandalaEndpoints, getPushAdapter } from '../toolboxConfig'
@@ -157,17 +154,11 @@ import AsyncStorage from '@react-native-async-storage/async-storage'
157
154
  import { UserContext } from './UserContext'
158
155
  import { useLocalStorage } from './LocalStorageProvider'
159
156
  import { usePermissionQueue } from '../hooks/usePermissionQueue'
160
- import { configureMandala, resolveAssetMetadata } from '@bsv/mandala'
157
+ import { configureMandala } from '@bsv/mandala'
161
158
  import { MessageBoxClient } from '@bsv/message-box-client'
162
- import {
163
- MandalaTokenModule,
164
- wrapCreateActionForTokenInputs,
165
- listAllOutpoints,
166
- resolveMandalaOutput,
167
- type MandalaAssetMetadata
168
- } from '../mandala/permissionModule'
169
159
  import { wrapAbortActionForSettlements } from '../mandala/abortGuard'
170
- import { migrateMandalaBasketName } from '../mandala/basketMigration'
160
+ import { createColorAccessPolicy } from '../mandala/accessPolicy'
161
+ import { buildColorModule, type BuiltColorModule } from '../mandala/colorModule'
171
162
  import {
172
163
  bindOriginator,
173
164
  createMandalaKvStorage,
@@ -175,11 +166,9 @@ import {
175
166
  type MandalaMessageBox
176
167
  } from '../mandala/createRuntime'
177
168
  import type { MandalaRuntime } from '../mandala/runtime'
178
- import { MANDALA_BASKET } from '../mandala/types'
179
169
  import { mandalaSettlementDeps, type CancelParkedSettlementDeps } from '../offline/cancelParked'
180
170
  import { drainMandalaInbox } from '../pay/rails/handle'
181
- import { forgetSessionPsks, sealedFramePayloadDecoder } from '../offline/tokenFrames'
182
- import { disconnectActivePairedSession } from './WalletConnectionContext'
171
+ import { runSessionTeardown } from './sessionTeardown'
183
172
  import connectionStore from '../stores/ConnectionStore'
184
173
  import { loadUserAvatarIcon } from '../userAvatar'
185
174
  import { createServices, chaintracksUrlFor } from '../services/walletServiceConfig'
@@ -198,7 +187,7 @@ import {
198
187
  createWocBroadcastService
199
188
  } from '../services/arcadeBroadcastProvider'
200
189
  import { getExchangeRate } from '../services/exchangeRate'
201
- import { logWithTimestamp } from '../logging'
190
+ import { devLog, logWithTimestamp } from '../logging'
202
191
  import { recoverMnemonicWallet } from '../mnemonicWallet'
203
192
  import { backupProbe, discoverProfiles, registerDiscoveredProfile } from '../profiles/discovery'
204
193
  import {
@@ -391,6 +380,15 @@ const profilePurgeIo: PurgeProfileIo = {
391
380
  interface ManagerState {
392
381
  walletManager?: SimpleWalletManager
393
382
  permissionsManager?: WalletPermissionsManager
383
+ /** The attested manager itself, before the guard and conformance wrappers
384
+ * `permissionsManager` carries. What `withdrawPrompts` retires. */
385
+ signingPermissionsManager?: SigningPolicyPermissionsManager
386
+ /** The manager for unverified (unattested) browser origins, behind the same wrapper stack as
387
+ * `permissionsManager`. Present only when a transport that can deliver unattested calls was
388
+ * registered when the wallet was built (spec 6.5). */
389
+ unverifiedPermissionsManager?: WalletPermissionsManager
390
+ /** The unverified manager itself, before its wrappers. What `withdrawPrompts` retires. */
391
+ unverifiedSigningPermissionsManager?: SigningPolicyPermissionsManager
394
392
  settingsManager?: WalletSettingsManager
395
393
  }
396
394
 
@@ -461,13 +459,23 @@ export interface WalletContextValue {
461
459
  groupRequests: GroupPermissionRequest[]
462
460
  btmsRequests: BtmsRequest[]
463
461
  mandalaRequests: MandalaRequest[]
464
- advanceBasketQueue: () => void
465
- advanceCertificateQueue: () => void
466
- advanceProtocolQueue: () => void
467
- advanceSpendingQueue: () => void
468
- advanceGroupQueue: () => void
462
+ advanceBasketQueue: (requestID?: string) => void
463
+ advanceCertificateQueue: (requestID?: string) => void
464
+ advanceProtocolQueue: (requestID?: string) => void
465
+ advanceSpendingQueue: (requestID?: string) => void
466
+ advanceGroupQueue: (requestID?: string) => void
469
467
  advanceBtmsQueue: (approved: boolean) => void
470
468
  advanceMandalaQueue: (approved: boolean) => void
469
+ /**
470
+ * Retires the given (replaced) managers, denies what they still hold and
471
+ * empties every permission queue. Idempotent. Runs by itself on every
472
+ * teardown the context performs; the bridge runtime calls it for a wallet it
473
+ * sees replaced some other way.
474
+ */
475
+ withdrawPrompts: (oldManagers: SigningPolicyPermissionsManager[]) => void
476
+ /** Registers something else to clear on a withdrawal (pending connection
477
+ * requests). Returns the unregister function. */
478
+ registerPromptWithdrawal: (clear: () => void) => () => void
471
479
  finalizeConfig: (wabConfig: WABConfig) => boolean
472
480
  setConfigStatus: (status: ConfigStatus) => void
473
481
  configStatus: ConfigStatus
@@ -607,6 +615,8 @@ export const WalletContext = createContext<WalletContextValue>({
607
615
  advanceGroupQueue: () => {},
608
616
  advanceBtmsQueue: () => {},
609
617
  advanceMandalaQueue: () => {},
618
+ withdrawPrompts: () => {},
619
+ registerPromptWithdrawal: () => () => {},
610
620
  finalizeConfig: () => false,
611
621
  setConfigStatus: () => {},
612
622
  configStatus: 'initial',
@@ -673,7 +683,12 @@ export const useWalletManagers = (): WalletManagersSlice => useContext(WalletMan
673
683
 
674
684
  type PermissionType = 'identity' | 'protocol' | 'renewal' | 'basket'
675
685
 
676
- type BasketAccessRequest = {
686
+ /** Each prompt callback is bound per manager and each queue item records the
687
+ * manager that raised it; the sheet answers that manager, never whichever one
688
+ * is current, so a stale answer cannot reach a replacement. */
689
+ type RaisedBy = { manager?: SigningPolicyPermissionsManager }
690
+
691
+ type BasketAccessRequest = RaisedBy & {
677
692
  requestID: string
678
693
  basket?: string
679
694
  originator: string
@@ -681,7 +696,7 @@ type BasketAccessRequest = {
681
696
  renewal?: boolean
682
697
  }
683
698
 
684
- type CertificateAccessRequest = {
699
+ type CertificateAccessRequest = RaisedBy & {
685
700
  requestID: string
686
701
  certificate?: {
687
702
  certType?: string
@@ -693,7 +708,7 @@ type CertificateAccessRequest = {
693
708
  renewal?: boolean
694
709
  }
695
710
 
696
- type ProtocolAccessRequest = {
711
+ type ProtocolAccessRequest = RaisedBy & {
697
712
  requestID: string
698
713
  protocolSecurityLevel: number
699
714
  protocolID: string
@@ -707,7 +722,7 @@ type ProtocolAccessRequest = {
707
722
  type?: PermissionType
708
723
  }
709
724
 
710
- type SpendingRequest = {
725
+ type SpendingRequest = RaisedBy & {
711
726
  requestID: string
712
727
  originator: string
713
728
  description?: string
@@ -721,7 +736,7 @@ type SpendingRequest = {
721
736
 
722
737
  /** A site's grouped permission request, from its manifest's
723
738
  * `metanet.groupPermissions` (WalletPermissionsManager.waitForAuthentication). */
724
- export type GroupPermissionRequest = {
739
+ export type GroupPermissionRequest = RaisedBy & {
725
740
  requestID: string
726
741
  originator: string
727
742
  permissions: {
@@ -741,13 +756,27 @@ type BtmsRequest = {
741
756
  resolve: (approved: boolean) => void
742
757
  }
743
758
 
744
- /** Same shape as BtmsRequest — MandalaTokenModule's requestTokenAccess queue item. */
759
+ /** Same shape as BtmsRequest — the color module's consent queue item (via createColorAccessPolicy). */
760
+ /**
761
+ * Waits on a foreground or reconnect `settleAll()` (single-flight with the
762
+ * drain tick's own settle). A row that settled releases its held tx on the
763
+ * drain's next pass, so that pass is asked for now. Never rejects: a settle
764
+ * that fails leaves every row as it was, for the next tick.
765
+ */
766
+ async function releaseAfterTokenSettle(settling: Promise<number> | undefined, when: string): Promise<void> {
767
+ try {
768
+ if (((await settling) ?? 0) > 0) TaskSendOffline.requestNow()
769
+ } catch (e) {
770
+ devLog(`[WalletContext] ${when} token settle failed:`, e)
771
+ }
772
+ }
773
+
745
774
  type MandalaRequest = {
746
- /** The originator (dApp domain) requesting Mandala token access */
775
+ /** The originator (dApp domain) requesting token access */
747
776
  originator: string
748
- /** The raw message from MandalaTokenModule (JSON-encoded promptData) */
777
+ /** The raw consent message from the color module (JSON, IC §2.5) */
749
778
  message: string
750
- /** Resolve the pending Promise from MandalaTokenModule — true = approved */
779
+ /** Resolve the pending consent Promise — true = approved */
751
780
  resolve: (approved: boolean) => void
752
781
  }
753
782
 
@@ -841,6 +870,13 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
841
870
  */
842
871
  const [mandala, setMandala] = useState<MandalaRuntime | undefined>(undefined)
843
872
  const mandalaRef = useRef<MandalaRuntime | undefined>(undefined)
873
+ /**
874
+ * This build's BRC-207 color module (with its provider and store), or
875
+ * undefined on a chain with no Mandala endpoints, before a build, or when
876
+ * the module could not be built. The runtime and the drain tick read it
877
+ * here; teardown disposes it.
878
+ */
879
+ const colorRef = useRef<BuiltColorModule | undefined>(undefined)
844
880
  const appStateRef = useRef<AppStateStatus>(AppState.currentState)
845
881
  const monitorSupervisorRef = useRef<MonitorSupervisor | null>(null)
846
882
  const monitorRef = useRef<Monitor | null>(null)
@@ -1100,7 +1136,13 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1100
1136
  setSpendingAuthorizationModalOpen
1101
1137
  } = useContext(UserContext)
1102
1138
 
1103
- const focusOpts = { isFocused, onFocusRequested, onFocusRelinquished }
1139
+ // A prompt raised for a connected site while the app is in the background must pull the user to
1140
+ // the sheet; the bridge decides whether that applies (live binding of this originator, not active).
1141
+ const notePromptRaised = useCallback((item: unknown) => {
1142
+ const originator = (item as { originator?: unknown } | null)?.originator
1143
+ if (typeof originator === 'string') notifyPromptRaised(originator)
1144
+ }, [])
1145
+ const focusOpts = { isFocused, onFocusRequested, onFocusRelinquished, onEnqueue: notePromptRaised }
1104
1146
 
1105
1147
  const basketQueue = usePermissionQueue<BasketAccessRequest>({
1106
1148
  ...focusOpts,
@@ -1159,6 +1201,70 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1159
1201
  [mandalaQueue.enqueue]
1160
1202
  )
1161
1203
 
1204
+ // The five manager-backed queues answer by identity: with a requestID only
1205
+ // that item is removed, and nothing if it is no longer queued (a withdrawal
1206
+ // emptied the queue while the user's answer was on its way).
1207
+ const advanceBasketQueue = useCallback(
1208
+ (requestID?: string) => basketQueue.advance(undefined, requestID),
1209
+ [basketQueue.advance]
1210
+ )
1211
+ const advanceCertificateQueue = useCallback(
1212
+ (requestID?: string) => certificateQueue.advance(undefined, requestID),
1213
+ [certificateQueue.advance]
1214
+ )
1215
+ const advanceProtocolQueue = useCallback(
1216
+ (requestID?: string) => protocolQueue.advance(undefined, requestID),
1217
+ [protocolQueue.advance]
1218
+ )
1219
+ const advanceSpendingQueue = useCallback(
1220
+ (requestID?: string) => spendingQueue.advance(undefined, requestID),
1221
+ [spendingQueue.advance]
1222
+ )
1223
+ const advanceGroupQueue = useCallback(
1224
+ (requestID?: string) => groupQueue.advance(undefined, requestID),
1225
+ [groupQueue.advance]
1226
+ )
1227
+
1228
+ const promptWithdrawalsRef = useRef(new Set<() => void>())
1229
+ const registerPromptWithdrawal = useCallback((clear: () => void) => {
1230
+ promptWithdrawalsRef.current.add(clear)
1231
+ return () => {
1232
+ promptWithdrawalsRef.current.delete(clear)
1233
+ }
1234
+ }, [])
1235
+ const withdrawPrompts = useCallback(
1236
+ (oldManagers: SigningPolicyPermissionsManager[]) => {
1237
+ withdrawPromptsFrom(oldManagers, {
1238
+ managerQueues: [basketQueue, certificateQueue, protocolQueue, spendingQueue, groupQueue],
1239
+ tokenQueues: [btmsQueue, mandalaQueue],
1240
+ others: [...promptWithdrawalsRef.current]
1241
+ })
1242
+ },
1243
+ [
1244
+ basketQueue.clear,
1245
+ certificateQueue.clear,
1246
+ protocolQueue.clear,
1247
+ spendingQueue.clear,
1248
+ groupQueue.clear,
1249
+ btmsQueue.clear,
1250
+ mandalaQueue.clear
1251
+ ]
1252
+ )
1253
+ // Teardown paths are declared far from here and must not re-create on every
1254
+ // queue change, so they reach the current function through a ref.
1255
+ const withdrawPromptsRef = useRef(withdrawPrompts)
1256
+ withdrawPromptsRef.current = withdrawPrompts
1257
+ /** Withdraws the prompts of the managers currently published, before the
1258
+ * wallet they belong to is torn down. */
1259
+ const withdrawCurrentPrompts = useCallback(() => {
1260
+ const { signingPermissionsManager, unverifiedSigningPermissionsManager } = managersRef.current
1261
+ withdrawPromptsRef.current(
1262
+ [signingPermissionsManager, unverifiedSigningPermissionsManager].filter(
1263
+ (m): m is SigningPolicyPermissionsManager => m !== undefined
1264
+ )
1265
+ )
1266
+ }, [])
1267
+
1162
1268
  const updateSettings = useCallback(
1163
1269
  async (newSettings: WalletSettings) => {
1164
1270
  setSettings(newSettings)
@@ -1175,7 +1281,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1175
1281
  originator: string
1176
1282
  reason?: string
1177
1283
  renewal?: boolean
1178
- }
1284
+ },
1285
+ manager?: SigningPolicyPermissionsManager
1179
1286
  ) => {
1180
1287
  if (incomingRequest?.requestID) {
1181
1288
  basketQueue.enqueue({
@@ -1183,7 +1290,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1183
1290
  basket: incomingRequest.basket,
1184
1291
  originator: incomingRequest.originator,
1185
1292
  reason: incomingRequest.reason,
1186
- renewal: incomingRequest.renewal
1293
+ renewal: incomingRequest.renewal,
1294
+ manager
1187
1295
  })
1188
1296
  }
1189
1297
  },
@@ -1202,7 +1310,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1202
1310
  originator: string
1203
1311
  reason?: string
1204
1312
  renewal?: boolean
1205
- }
1313
+ },
1314
+ manager?: SigningPolicyPermissionsManager
1206
1315
  ) => {
1207
1316
  if (incomingRequest?.requestID) {
1208
1317
  const certificate = incomingRequest.certificate as any
@@ -1213,7 +1322,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1213
1322
  certificateType: certificate?.certType || '',
1214
1323
  fieldsArray: certificate?.fields || [],
1215
1324
  description: incomingRequest.reason,
1216
- renewal: incomingRequest.renewal
1325
+ renewal: incomingRequest.renewal,
1326
+ manager
1217
1327
  } as any)
1218
1328
  }
1219
1329
  },
@@ -1221,7 +1331,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1221
1331
  )
1222
1332
 
1223
1333
  const protocolPermissionCallback = useCallback(
1224
- (args: PermissionRequest & { requestID: string }): Promise<void> => {
1334
+ (args: PermissionRequest & { requestID: string }, manager?: SigningPolicyPermissionsManager): Promise<void> => {
1225
1335
  const { requestID, counterparty, originator, reason, renewal, protocolID } = args
1226
1336
  const keyID = (args as { keyID?: unknown }).keyID
1227
1337
  if (!requestID || !protocolID) return Promise.resolve()
@@ -1242,7 +1352,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1242
1352
  originator,
1243
1353
  description: reason,
1244
1354
  renewal,
1245
- type: permissionType
1355
+ type: permissionType,
1356
+ manager
1246
1357
  })
1247
1358
  return Promise.resolve()
1248
1359
  },
@@ -1250,67 +1361,46 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1250
1361
  )
1251
1362
 
1252
1363
  const spendingAuthorizationCallback = useCallback(
1253
- async (args: PermissionRequest & { requestID: string }): Promise<void> => {
1254
- const { requestID, originator, reason, renewal, spending } = args
1255
- if (!requestID || !spending) return
1256
-
1364
+ async (
1365
+ args: PermissionRequest & { requestID: string },
1366
+ manager?: SigningPolicyPermissionsManager
1367
+ ): Promise<void> => {
1257
1368
  // Auto-approve small transactions if within threshold, per-originator
1258
1369
  // cooldown, and the global rolling 24h cap (misc-p2-04) — accounting
1259
1370
  // lives in autoApprovePolicy.ts. Read the persisted threshold fresh on
1260
1371
  // every request so a change made in wallet-config takes effect
1261
1372
  // immediately (the mount-time ref read alone left the old value live
1262
1373
  // until app restart — felt like auto-approve was "stuck on").
1263
- try {
1264
- const stored = await AsyncStorage.getItem(profileScopedKey(AUTO_APPROVE_STORAGE_KEY))
1265
- // Unset means this profile never chose one: the default, never another profile's.
1266
- autoApproveThresholdRef.current = stored !== null ? Number(stored) || 0 : DEFAULT_AUTO_APPROVE_THRESHOLD
1267
- } catch {}
1268
- const threshold = autoApproveThresholdRef.current
1269
- autoApproveThresholdSnapshot = threshold
1270
- // Logging gated behind __DEV__: an unconditional console.log here flushes
1271
- // over the JS↔native bridge on every spend request — i.e. on the payment
1272
- // hot path — and shows up as jank under any burst of micropayments.
1273
- const autoApproveDecision = autoApprovePolicy.shouldAutoApprove({
1274
- originator,
1275
- satoshis: spending.satoshis
1276
- })
1277
- if (autoApproveDecision.approve) {
1278
- autoApprovePolicy.record({ originator, satoshis: spending.satoshis, at: Date.now() })
1279
- persistAutoApproveLedger()
1280
- if (__DEV__) console.log(`[spend-auth] AUTO-APPROVING requestID=${requestID} sats=${spending.satoshis}`)
1281
- managersRef.current.permissionsManager?.grantPermission({
1282
- requestID,
1283
- ephemeral: true,
1284
- amount: spending.satoshis
1285
- })
1286
- return
1287
- }
1288
- if (__DEV__) {
1289
- console.log(
1290
- `[spend-auth] not eligible (${autoApproveDecision.reason}) → manual modal requestID=${requestID} sats=${spending.satoshis} threshold=${threshold}`
1291
- )
1292
- }
1293
-
1294
- spendingQueue.enqueue({
1295
- requestID,
1296
- originator,
1297
- description: reason,
1298
- transactionAmount: 0,
1299
- totalPastSpending: 0,
1300
- amountPreviouslyAuthorized: 0,
1301
- authorizationAmount: spending.satoshis,
1302
- renewal,
1303
- lineItems: spending.lineItems || []
1374
+ // The flow itself (including what a withdrawal during that read means)
1375
+ // is handleSpendingPrompt's.
1376
+ await handleSpendingPrompt<SpendingRequest>(args as never, manager, {
1377
+ loadThreshold: async () => {
1378
+ try {
1379
+ const stored = await AsyncStorage.getItem(profileScopedKey(AUTO_APPROVE_STORAGE_KEY))
1380
+ // Unset means this profile never chose one: the default, never another profile's.
1381
+ autoApproveThresholdRef.current = stored !== null ? Number(stored) || 0 : DEFAULT_AUTO_APPROVE_THRESHOLD
1382
+ } catch {}
1383
+ },
1384
+ decide: (originator, satoshis) => {
1385
+ autoApproveThresholdSnapshot = autoApproveThresholdRef.current
1386
+ return autoApprovePolicy.shouldAutoApprove({ originator, satoshis })
1387
+ },
1388
+ recordAutoApproved: (originator, satoshis) => {
1389
+ autoApprovePolicy.record({ originator, satoshis, at: Date.now() })
1390
+ persistAutoApproveLedger()
1391
+ },
1392
+ enqueue: spendingQueue.enqueue,
1393
+ currentManager: () => managersRef.current.signingPermissionsManager
1304
1394
  })
1305
1395
  },
1306
1396
  [spendingQueue.enqueue]
1307
1397
  )
1308
1398
 
1309
1399
  const groupedPermissionCallback = useCallback(
1310
- async (args: GroupPermissionRequest): Promise<void> => {
1400
+ async (args: GroupPermissionRequest, manager?: SigningPolicyPermissionsManager): Promise<void> => {
1311
1401
  const { requestID, originator, permissions } = args ?? ({} as GroupPermissionRequest)
1312
1402
  if (!requestID || !permissions) return
1313
- groupQueue.enqueue({ requestID, originator, permissions })
1403
+ groupQueue.enqueue({ requestID, originator, permissions, manager })
1314
1404
  },
1315
1405
  [groupQueue.enqueue]
1316
1406
  )
@@ -1917,32 +2007,17 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1917
2007
  }
1918
2008
  }
1919
2009
 
1920
- let migrationUserId: number | undefined
1921
2010
  try {
1922
2011
  const auth = await storageManager.getAuth()
1923
2012
  setWalletUserId(auth.userId ?? null)
1924
- migrationUserId = auth.userId ?? undefined
1925
2013
  } catch {
1926
2014
  // Scoping is a filter, not a gate: with no id the queue reads fall
1927
2015
  // back to unscoped, which is today's behaviour.
1928
2016
  setWalletUserId(null)
1929
2017
  }
1930
2018
 
1931
- // One-time basket rename ('mandala-tokens' -> MANDALA_BASKET), run
1932
- // after storage is attached (and any backup restore above has had
1933
- // its chance to write old-named rows) so a restored device's rows
1934
- // are migrated too, not just a freshly-created wallet's. Guarded
1935
- // internally by its own key_value_store marker; the per-user pass
1936
- // still runs on every build so a restored backup's old-named rows
1937
- // are caught even after the marker is set. See offline-settlement-final.md §8.3.
1938
- try {
1939
- await migrateMandalaBasketName(phoneStorage, migrationUserId)
1940
- } catch (error) {
1941
- console.error('[WalletContext] Mandala basket migration failed:', error)
1942
- }
1943
-
1944
- // Hand `@bsv/mandala` this deployment's endpoints, this wallet's
1945
- // basket, and a DURABLE journal store — before any lib call can run.
2019
+ // Hand `@bsv/mandala` this deployment's endpoints and a DURABLE
2020
+ // journal store — before any lib call can run.
1946
2021
  //
1947
2022
  // The storage adapter is the load-bearing half. The lib's journals
1948
2023
  // are its recovery contract: an overlay-accepted, not-yet-broadcast
@@ -1952,17 +2027,15 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1952
2027
  // process-lifetime Map — i.e. no crash recovery at all — and the
1953
2028
  // failure is silent. See lib/src/storage.ts.
1954
2029
  //
1955
- // `basket` is the wallet's own deviation from the lib default
1956
- // ('mandala-tokens'): 'p mandala' is BRC-99 P-routed, which is what
1957
- // puts every listOutputs/createAction/internalizeAction against it
1958
- // through MandalaTokenModule regardless of originator (spec §8.3).
2030
+ // Token custody is no longer the lib's: value outputs live in the
2031
+ // color module's `p color <assetTag>` baskets (registered below), so
2032
+ // no basket is configured here.
1959
2033
  if (mandalaEndpoints) {
1960
2034
  try {
1961
2035
  configureMandala({
1962
2036
  overlayUrl: mandalaEndpoints.overlayUrl,
1963
2037
  overlayIdentityKey: mandalaEndpoints.overlayIdentityKey,
1964
2038
  messageBoxUrl: mandalaEndpoints.messageBoxUrl,
1965
- basket: MANDALA_BASKET,
1966
2039
  storage: createMandalaKvStorage(phoneStorage)
1967
2040
  })
1968
2041
  } catch (error) {
@@ -1974,122 +2047,98 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1974
2047
 
1975
2048
  // Create BTMS permission module, wiring in the prompt handler so that
1976
2049
  // "p btms" operations surface a UI modal rather than silently denying.
1977
- const btmsModule = loadBtmsPermissionModule().createBtmsModule({ wallet, promptHandler: btmsPromptHandler })
1978
-
1979
- // Adversarial-review finding (2): every outpoint this wallet holds in
1980
- // MANDALA_BASKET, via the ADMIN-originator wallet -- i.e. this call
1981
- // itself passes through MandalaTokenModule with zero prompts (the
1982
- // module's own admin pass-through branch). Shared by the module's
1983
- // deps below AND by wrapCreateActionForTokenInputs's wrapper further
1984
- // down, so both use the exact same listing.
2050
+ // Both token-module prompt functions are tied to this build: once its
2051
+ // manager is retired (the wallet was replaced) they resolve false
2052
+ // without enqueueing. The manager below retires them with itself.
2053
+ const buildPrompts = guardTokenPromptHandlers({ btms: btmsPromptHandler, mandala: mandalaPromptHandler })
2054
+ const btmsModule = loadBtmsPermissionModule().createBtmsModule({ wallet, promptHandler: buildPrompts.btms })
2055
+
2056
+ // The BRC-207 color module (plan 07 Task 10): all token custody and
2057
+ // evidence, registered below as `permissionModules.color`, so every
2058
+ // `p color` basket, label and protocol call — from any originator —
2059
+ // goes through it. Built over the UNDERLYING `wallet`, never the
2060
+ // manager: the module derives and signs on it directly.
1985
2061
  //
1986
- // XR-039: paginated to completion via `listAllOutpoints` (a single
1987
- // 10,000-row page silently truncated a larger basket, and a spend of
1988
- // an input past that page read as "not a token input" -- the same
1989
- // balance-truncation bug `core/localpay/build.ts`'s `listTokenBasket`
1990
- // and `createRuntime.ts`'s `listTokenOutputs` were already fixed
1991
- // for), and a genuine listing fault now PROPAGATES instead of being
1992
- // swallowed into an authoritative-looking empty Set -- an empty Set
1993
- // here reads as "confirmed no token inputs" to every caller, which a
1994
- // storage fault or a wallet with no Mandala basket are not
1995
- // distinguishable from without this throwing. The two callers
1996
- // (`injectMandalaLabelIfTokenInputsPresent`, `anyInputIsTokenCoin`)
1997
- // are exactly what now fails closed on that throw.
1998
- const listMandalaTokenOutpoints = (): Promise<Set<string>> =>
1999
- listAllOutpoints(
2000
- async (limit, offset) =>
2001
- await wallet.listOutputs(
2002
- { basket: MANDALA_BASKET, includeCustomInstructions: false, limit, offset } as never,
2003
- adminOriginator
2004
- ),
2005
- MANDALA_OUTPOINT_LIST_PAGE,
2006
- MANDALA_OUTPOINT_LIST_MAX_PAGES
2007
- )
2008
-
2009
- // XR-041: resolves ONE outpoint named on a `relinquishOutput` call to
2010
- // its decoded `{assetId, amount}`, from this device's OWN current
2011
- // MANDALA_BASKET listing — `include: 'locking scripts'` is the one
2012
- // difference from `listMandalaTokenOutpoints` above, since naming the
2013
- // holding needs the script, not just the outpoint. Same admin-
2014
- // originator, zero-prompt listing; same to-completion paging.
2015
- const resolveMandalaOutputForRelinquish = (outpoint: string) =>
2016
- resolveMandalaOutput(
2017
- async (limit, offset) =>
2018
- await wallet.listOutputs(
2019
- {
2020
- basket: MANDALA_BASKET,
2021
- include: 'locking scripts',
2022
- includeCustomInstructions: false,
2023
- limit,
2024
- offset
2025
- } as never,
2026
- adminOriginator
2027
- ),
2028
- outpoint,
2029
- MANDALA_OUTPOINT_LIST_PAGE,
2030
- MANDALA_OUTPOINT_LIST_MAX_PAGES
2031
- )
2062
+ // Only with endpoints AND this device's storage: the module's
2063
+ // evidence store is the wallet's key_value_store. Otherwise, and when
2064
+ // the build throws (a malformed overlay key or url), there is no
2065
+ // `color` key at all, so `p color` calls fail closed with
2066
+ // "Unsupported P-module scheme" (S5). The broadcast hold and the abort
2067
+ // refusal do not depend on the module: they key on the journal and on
2068
+ // `mandalaEndpoints`, so a missing module still holds every token tx.
2069
+ //
2070
+ // Consent goes through createColorAccessPolicy (W2): the wallet's own
2071
+ // screens are approved without a prompt, external originators queue on
2072
+ // the permission sheet. A fresh policy per build, so a read grant never
2073
+ // outlives the wallet that gave it.
2074
+ //
2075
+ // A previous build's module is disposed first (teardown normally has
2076
+ // already): two live modules would each hold selections and settle
2077
+ // latches over the same store.
2078
+ //
2079
+ // Only while this build is still the wanted one. A switch that
2080
+ // overtook it has already torn down and may have started the next
2081
+ // build, whose LIVE module the ref now holds: disposing that would
2082
+ // leave it routing `p color` calls that can never settle again. A
2083
+ // stale build touches neither the ref nor a module (it is discarded
2084
+ // before publishing, below). The check and the assignment are one
2085
+ // synchronous step, so no build can interleave between them.
2086
+ let colorModule: BuiltColorModule['module'] | undefined
2087
+ if (stillWanted()) {
2088
+ disposeColorModule(colorRef)
2089
+ if (mandalaEndpoints && phoneStorage) {
2090
+ try {
2091
+ colorRef.current = buildColorModule({
2092
+ wallet,
2093
+ endpoints: mandalaEndpoints,
2094
+ kv: phoneStorage,
2095
+ requestTokenAccess: createColorAccessPolicy({ adminOriginator, prompt: buildPrompts.mandala })
2096
+ })
2097
+ } catch (error) {
2098
+ console.error('[WalletContext] could not build the color module; p color calls will be refused:', error)
2099
+ }
2100
+ }
2101
+ colorModule = colorRef.current?.module
2102
+ }
2032
2103
 
2033
- // Mandala's own P-module (schemeID 'mandala', basket MANDALA_BASKET =
2034
- // 'p mandala') -- same routing mechanism as BTMS above
2035
- // (WalletPermissionsManager delegates by basket prefix regardless of
2036
- // originator), but decodes Mandala's own script layout rather than
2037
- // BTMS's PushDrop. See offline-settlement-final.md §8.
2038
- const mandalaModule = new MandalaTokenModule({
2039
- adminOriginator,
2040
- requestTokenAccess: mandalaPromptHandler,
2041
- resolveAssetMetadata: resolveMandalaAssetMetadata,
2042
- listTokenOutpoints: listMandalaTokenOutpoints,
2043
- resolveMandalaOutput: resolveMandalaOutputForRelinquish
2044
- })
2104
+ // The user's stored prompt policy for this profile (spec 6.5), authenticated by the admin
2105
+ // key. It applies from this build on; absent or not authentic means the defaults.
2106
+ const builtPolicy = resolvePermissionPolicy(
2107
+ await loadStoredPolicy(profileScopedKey(''), wallet as never, adminOriginator)
2108
+ )
2045
2109
 
2046
2110
  // Setup permissions with provided callbacks and BTMS module.
2047
2111
  const permissionsManager = new SigningPolicyPermissionsManager(wallet, adminOriginator, {
2048
2112
  differentiatePrivilegedOperations: true,
2049
- seekBasketInsertionPermissions: false,
2050
- seekBasketListingPermissions: false,
2051
- seekBasketRemovalPermissions: false,
2052
- seekCertificateAcquisitionPermissions: false,
2053
- seekCertificateDisclosurePermissions: false,
2054
- seekCertificateRelinquishmentPermissions: false,
2055
- seekCertificateListingPermissions: false,
2056
- // A site whose manifest declares metanet.groupPermissions is asked
2057
- // for them all in one sheet during waitForAuthentication. The request
2058
- // holds that origin's permission lock until answered, so it MUST be
2059
- // handled (onGroupedPermissionRequested, below) or the site hangs.
2060
- seekGroupedPermission: true,
2061
- seekPermissionsForIdentityKeyRevelation: false,
2062
- seekPermissionsForIdentityResolution: false,
2063
- seekPermissionsForKeyLinkageRevelation: false,
2064
- seekPermissionsForPublicKeyRevelation: false,
2065
- seekPermissionWhenApplyingActionLabels: false,
2066
- seekPermissionWhenListingActionsByLabel: false,
2067
- seekProtocolPermissionsForEncrypting: false,
2068
- seekProtocolPermissionsForHMAC: false,
2069
- // On, unlike Metanet Desktop: the vault guard no longer refuses
2070
- // external BRC-29 ([2,'3241645161d8']) signing outright, and that
2071
- // namespace also derives this wallet's own address-rail keys
2072
- // (counterparty 'anyone'), so a site signing under it must be
2073
- // asked first -- for BRC-29, on every signature. BRC-103/104 auth
2074
- // signing is exempt (SigningPolicyPermissionsManager).
2075
- seekProtocolPermissionsForSigning: true,
2076
- seekSpendingPermissions: true,
2077
- permissionModules: { btms: btmsModule, mandala: mandalaModule }
2113
+ // The prompt settings live in core/bridge/permissionPolicy.ts (default: exactly the
2114
+ // configuration this literal used to hold).
2115
+ ...builtPolicy.verified,
2116
+ permissionModules: colorModule ? { btms: btmsModule, color: colorModule } : { btms: btmsModule }
2078
2117
  } as any)
2079
2118
 
2080
- if (protocolPermissionCallback) {
2081
- permissionsManager.bindCallback('onProtocolPermissionRequested', protocolPermissionCallback)
2082
- }
2083
- if (basketAccessCallback) {
2084
- permissionsManager.bindCallback('onBasketAccessRequested', basketAccessCallback)
2085
- }
2086
- if (spendingAuthorizationCallback) {
2087
- permissionsManager.bindCallback('onSpendingAuthorizationRequested', spendingAuthorizationCallback)
2088
- }
2089
- permissionsManager.bindCallback('onGroupedPermissionRequested', groupedPermissionCallback as any)
2090
- if (certificateAccessCallback) {
2091
- permissionsManager.bindCallback('onCertificateAccessRequested', certificateAccessCallback)
2119
+ permissionsManager.onRetire(buildPrompts.retire)
2120
+
2121
+ const bindPromptCallbacks = (mgr: SigningPolicyPermissionsManager) => {
2122
+ // Bound per manager: each queue item records the manager that raised
2123
+ // it, and the sheet answers that one (see RaisedBy).
2124
+ if (protocolPermissionCallback) {
2125
+ mgr.bindCallback('onProtocolPermissionRequested', (args: any) => protocolPermissionCallback(args, mgr))
2126
+ }
2127
+ if (basketAccessCallback) {
2128
+ mgr.bindCallback('onBasketAccessRequested', (args: any) => basketAccessCallback(args, mgr))
2129
+ }
2130
+ if (spendingAuthorizationCallback) {
2131
+ mgr.bindCallback('onSpendingAuthorizationRequested', (args: any) =>
2132
+ spendingAuthorizationCallback(args, mgr)
2133
+ )
2134
+ }
2135
+ mgr.bindCallback('onGroupedPermissionRequested', ((args: any) => groupedPermissionCallback(args, mgr)) as any)
2136
+ if (certificateAccessCallback) {
2137
+ mgr.bindCallback('onCertificateAccessRequested', (args: any) => certificateAccessCallback(args, mgr))
2138
+ }
2092
2139
  }
2140
+ bindPromptCallbacks(permissionsManager)
2141
+ newManagers.signingPermissionsManager = permissionsManager
2093
2142
 
2094
2143
  // Publish one idempotently guarded manager for both trusted in-app
2095
2144
  // Vault calls and external WalletClient calls; external call sites may
@@ -2098,47 +2147,51 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2098
2147
  // SQLite storage; with no local storage those external calls are
2099
2148
  // refused rather than let through.
2100
2149
  //
2101
- // wrapCreateActionForTokenInputs wraps the RAW permissionsManager
2102
- // FIRST, and guardVaultAccess is applied to ITS result (never the
2103
- // other way around) -- adversarial-review finding (2):
2104
- // WalletPermissionsManager only P-routes a createAction call whose
2105
- // OUTPUTS or LABELS name a 'p ' scheme, never its inputs, so a
2106
- // createAction that spends 'p mandala' inputs with no basketed/
2107
- // decodable change output would otherwise reach
2108
- // MandalaTokenModule.onRequest for exactly zero callers of this
2109
- // manager. Wrapping outside-in (guard around this wrapper) would
2110
- // instead break guardVaultAccess's own re-wrap dedup, which several
2111
- // screens rely on (`guardVaultAccess(managers.permissionsManager,
2112
- // ADMIN_ORIGINATOR)` again) -- see permissionModule.ts's wrapper doc
2113
- // for the full mechanism.
2150
+ // `wrapAbortActionForSettlements` wraps the result-conforming manager
2151
+ // and guardVaultAccess is applied to ITS result (never the other way
2152
+ // around), so the published object stays the one the guard's own
2153
+ // re-wrap dedup recognises — several screens rely on that
2154
+ // (`guardVaultAccess(managers.permissionsManager, ADMIN_ORIGINATOR)`
2155
+ // again). It is the last line of defence for the 2026-09-15 incident —
2156
+ // an `abortAction` against a token payment the payee or the overlay
2157
+ // may already have releases inputs that are spent on chain. It reads
2158
+ // the `color_transfers` journal LATE, off `mandalaRef`, because the
2159
+ // runtime is built below this line and replaced on every rebuild.
2114
2160
  //
2115
- // `wrapAbortActionForSettlements` goes on the same stack, for the same
2116
- // reason and in the same place: inside `guardVaultAccess`, so the
2117
- // published object stays the one the guard's dedup recognises. It is
2118
- // the last line of defence for the 2026-09-15 incident — an
2119
- // `abortAction` against a token payment the overlay has already
2120
- // admitted (and therefore broadcast) releases inputs that are spent on
2121
- // chain. It reads the settlement store LATE, off `mandalaRef`, because
2122
- // the runtime is built below this line and replaced on every rebuild.
2161
+ // No createAction input wrapper sits here any more. The color module
2162
+ // is reached through `p color` plan labels and baskets, and a `p color`
2163
+ // input can only be unlocked through the module's signature-envelope
2164
+ // path (a bare digest under a `p color` key is refused, A.13), so a
2165
+ // spend that names no plan cannot move tokens around it.
2123
2166
  //
2124
2167
  // XR-034: `mandalaEndpoints` (above, static for this build) is the
2125
2168
  // guard's ONLY "token settlement provably not in use" signal — never
2126
2169
  // `mandalaRef.current`, whose `undefined` also covers a runtime that
2127
- // threw or is mid-rebuild, both of which can leave real settlement
2128
- // rows unreadable rather than absent.
2129
- newManagers.permissionsManager = guardVaultAccess(
2130
- wrapAbortActionForSettlements(
2131
- wrapCreateActionForTokenInputs(
2132
- conformWalletResults(adminOriginator, permissionsManager),
2133
- listMandalaTokenOutpoints,
2134
- adminOriginator
2170
+ // threw or is mid-rebuild, both of which can leave real journal rows
2171
+ // unreadable rather than absent.
2172
+ // The unverified manager gets the same stack (spec 6.5).
2173
+ const guardedStack = (mgr: SigningPolicyPermissionsManager) =>
2174
+ guardVaultAccess(
2175
+ wrapAbortActionForSettlements(
2176
+ conformWalletResults(adminOriginator, mgr),
2177
+ () => mandalaRef.current?.journal,
2178
+ () => mandalaEndpoints !== undefined
2135
2179
  ),
2136
- () => mandalaRef.current?.store,
2137
- () => mandalaEndpoints !== undefined
2138
- ),
2139
- adminOriginator,
2140
- { lookup: phoneStorage }
2141
- )
2180
+ adminOriginator,
2181
+ { lookup: phoneStorage }
2182
+ )
2183
+ newManagers.permissionsManager = guardedStack(permissionsManager)
2184
+
2185
+ if (hasUnattestedTransport()) {
2186
+ const unverified = buildUnverifiedPermissionsManager(
2187
+ wallet,
2188
+ adminOriginator,
2189
+ effectiveUnverified(builtPolicy)
2190
+ )
2191
+ bindPromptCallbacks(unverified)
2192
+ newManagers.unverifiedSigningPermissionsManager = unverified
2193
+ newManagers.unverifiedPermissionsManager = guardedStack(unverified)
2194
+ }
2142
2195
 
2143
2196
  // THE MANDALA RUNTIME'S ONE CONSTRUCTION SITE.
2144
2197
  //
@@ -2156,6 +2209,17 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2156
2209
  storage: phoneStorage,
2157
2210
  chain,
2158
2211
  endpoints: mandalaEndpoints,
2212
+ // The module registered above for THIS build (undefined without
2213
+ // endpoints, or when its build failed): its host-only
2214
+ // `markSettled`, the overlay provider and the host ledger all
2215
+ // come from it. Without it the runtime is unavailable rather
2216
+ // than half-wired.
2217
+ color: colorRef.current?.module,
2218
+ provider: colorRef.current?.provider,
2219
+ ledger: colorRef.current?.ledger,
2220
+ // The UNDERLYING wallet the module was built over (B7): hand-over
2221
+ // envelopes are built from its custody, never through the manager.
2222
+ hostWallet: colorRef.current ? (wallet as never) : undefined,
2159
2223
  // Lazy: constructing a runtime must do no I/O, and a wallet that
2160
2224
  // never touches stablecoins never opens a MessageBox connection.
2161
2225
  messageBox: mandalaEndpoints
@@ -2175,17 +2239,12 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2175
2239
  chain
2176
2240
  ) as unknown as MandalaMessageBox
2177
2241
  : undefined,
2178
- // The payer's own frames are sealed with a nearby session PSK the
2179
- // drain never persists; this opens the ones whose session this
2180
- // process still holds. See offline/tokenFrames.ts.
2181
- decodeSealedFrame: sealedFramePayloadDecoder(),
2182
2242
  // The one thing `settleNow` asks about connectivity: whether a
2183
2243
  // hand-over that just landed should be followed by this device's
2184
2244
  // own submit now, or left to the drain. The runtime deliberately
2185
2245
  // has no NetInfo dependency of its own, so the app-wide probe is
2186
2246
  // handed to it here.
2187
- isOnline: getOnline,
2188
- refetchBeef: makeBeefRepair({ woc: wocConfigFor(chain), online: getOnline })
2247
+ isOnline: getOnline
2189
2248
  })
2190
2249
  mandalaRef.current = runtime.available ? runtime : undefined
2191
2250
  setMandala(runtime.available ? runtime : undefined)
@@ -2259,49 +2318,28 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2259
2318
  if (phoneStorage) {
2260
2319
  monitor.addTask(
2261
2320
  new TaskSendOffline(monitor, async () => {
2262
- // FIX C recovery and the nearby-blinding reservation sweep ride
2263
- // this same tick, ahead of the submit-then-broadcast pass below
2264
- // so a row this recovers to `admitted` can broadcast in the
2265
- // SAME pass rather than waiting for the next one. Read from the
2266
- // ref for the same reason `token: mandalaRef.current?.tokenDeps`
2267
- // is below — a rebuild replaces the runtime under a task
2268
- // registered once. Both are best-effort and never throw.
2269
- await mandalaRef.current?.recoverStaleAdmissions()
2270
- // The 2026-09-15 repair: a settlement row that says the overlay
2271
- // has the transaction, beside a wallet that failed it and
2272
- // released its input coin as spendable although it is spent on
2273
- // chain. Ahead of the release pass on purpose — a coin this
2274
- // re-marks spent must not be planned into a send below.
2275
- await mandalaRef.current?.repairAdmittedAborted()
2276
- // The LIB's own journals, on the same tick and with the same
2277
- // ref discipline: an overlay-accepted transfer whose broadcast
2278
- // never went out, a liftable refusal still holding its inputs,
2279
- // and the recipient notification a committed transfer owes its
2280
- // payee. Nothing else in this wallet drives them — the
2281
- // settlement drain below only knows `token_settlements` rows,
2282
- // and the handle rail writes none of these entries. Never
2283
- // throws (see `reconcileJournals`).
2284
- await mandalaRef.current?.reconcileJournals()
2285
- // The payer's handle-rail rows: no queue row exists for them,
2286
- // so the release pass below would never step them. Each one
2287
- // takes its `settleNow` step here instead (2026-09-15).
2288
- await mandalaRef.current?.settlePendingSends()
2289
- // Every held coin's σ_I on device, for the next offline hand-over.
2290
- await mandalaRef.current?.ensureAdmissionsForHoldings()
2291
- await mandalaRef.current?.pruneBlindingReservations()
2321
+ // The color runtime's own pass first: redeliver undelivered
2322
+ // hand-overs, the module settle, and the held-receipt
2323
+ // reconcile (`MandalaRuntime.tick`, never throws). It runs
2324
+ // AHEAD of the release pass on purpose — `processOfflineActions`
2325
+ // posts a held 1Color tx only once its `color_transfers` row
2326
+ // reads `settled`, so a row this settles goes out in the SAME
2327
+ // pass. Read from the ref, not captured: a rebuild replaces the
2328
+ // runtime under a task that was registered once, and a
2329
+ // torn-down wallet's ref is undefined, so it drains nothing.
2330
+ await mandalaRef.current?.tick()
2292
2331
  const r = await processOfflineActions({
2293
2332
  storage: phoneStorage!,
2294
- refetchBeef: makeBeefRepair({ woc: wocConfigFor(chain), online: getOnline }),
2295
- // The settlement drain, on the same cadence and in the same
2296
- // pass as the BSV release. That is the whole of §4.3: a token
2297
- // transaction takes the ordinary plan's place in dependency
2298
- // order and simply has `/submit` in front of its broadcast,
2299
- // so the recipient's `held` rows and the payer's
2300
- // `handed_over` rows both settle on every online tick.
2301
- // Read from the ref, not captured: a rebuild replaces the
2302
- // runtime under a task that was registered once.
2303
- token: mandalaRef.current?.tokenDeps
2333
+ refetchBeef: makeBeefRepair({ woc: wocConfigFor(chain), online: getOnline })
2304
2334
  })
2335
+ // The handle rail's `mandala-color` box, on the drain's cadence
2336
+ // too: a hand-over credited here is journaled `held` and the
2337
+ // next tick settles it. The credit-inbox task drains the same
2338
+ // box (its `incomplete` flag feeds the profile removal check);
2339
+ // both coalesce on the runtime's receive single flight. Never
2340
+ // throws (see drainMandalaInbox).
2341
+ const drained = await drainMandalaInbox(mandalaRef.current)
2342
+ if (drained.credited > 0) setTxStatusVersion(v => v + 1)
2305
2343
  // The drain writes transaction statuses directly, below the
2306
2344
  // monitor's onTransactionStatusChanged callback — bump the
2307
2345
  // version ourselves so the transactions screen re-fetches.
@@ -2464,9 +2502,11 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2464
2502
  if (sendWaiting?.processUnsent) {
2465
2503
  const orig = sendWaiting.processUnsent.bind(sendWaiting)
2466
2504
  sendWaiting.processUnsent = async (allReqApis, indent) => {
2467
- // Guard #2 for this path: a request with a `token_settlements`
2468
- // row is the settlement drain's to broadcast, after `/submit`,
2469
- // never the monitor's. Held here and dropped from this pass.
2505
+ // Guard #2 for this path: an unsettled 1Color request (its
2506
+ // `color_transfers` row is missing or not `settled`, see
2507
+ // `colorHeldTxids`) is the drain's to release once the module
2508
+ // settles it, never the monitor's. Held here and dropped from
2509
+ // this pass.
2470
2510
  const heldTokenTxids = await phoneStorage.holdTokenReqsForDrain(allReqApis as never)
2471
2511
  const reqApis =
2472
2512
  heldTokenTxids.size > 0 ? allReqApis.filter(r => !heldTokenTxids.has(r.txid)) : allReqApis
@@ -3099,10 +3139,17 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3099
3139
  * anything can resume against the departing wallet.
3100
3140
  */
3101
3141
  const teardownBuiltWallet = useCallback(async () => {
3142
+ // Prompts raised by the departing wallet are withdrawn, and its managers
3143
+ // retired, before anything yields: otherwise a sheet for it survives the
3144
+ // switch and answering it throws on the new manager.
3145
+ withdrawCurrentPrompts()
3102
3146
  // Invalidate Vault operations before the first teardown await. Otherwise a
3103
3147
  // signer/listing already in flight can resume against the departing wallet.
3104
3148
  vaultStore.clearScope()
3105
3149
  vaultCeremony.cancel()
3150
+ // Same reason for the color module: no new token submit may start once
3151
+ // teardown has begun, and its store is about to be destroyed below.
3152
+ disposeColorModule(colorRef)
3106
3153
 
3107
3154
  // Push listeners and the registration sync belong to the wallet being
3108
3155
  // torn down; nothing may fire them against it from here on.
@@ -3144,7 +3191,6 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3144
3191
  // task or a screen draining the departed wallet's tables.
3145
3192
  mandalaRef.current = undefined
3146
3193
  setMandala(undefined)
3147
- forgetSessionPsks()
3148
3194
 
3149
3195
  // Tear down current wallet state (but keep mnemonic / config)
3150
3196
  vaultStore.clearScope()
@@ -3168,6 +3214,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3168
3214
  reviewImportedCoinsRef.current = opts?.reviewImportedCoins === true
3169
3215
  // Any build already in flight belongs to the configuration being replaced.
3170
3216
  const token = buildGenRef.current.bump()
3217
+ // The bridge's bindings and published managers belong to the wallet being torn down: close
3218
+ // and drop them before anything yields (spec G9), not when the next build publishes.
3219
+ runSessionTeardown('rebuild')
3171
3220
  await teardownBuiltWallet()
3172
3221
 
3173
3222
  // Re-finalize with current config — triggers auto-build effect
@@ -3189,6 +3238,20 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3189
3238
  [selectedNetwork, teardownBuiltWallet, finalizeConfig, waitForRebuild]
3190
3239
  )
3191
3240
 
3241
+ // A transport that can deliver unattested calls registered after this wallet was built: the
3242
+ // unverified manager is made in the build, so build again to get it (spec 6.5). Normally the
3243
+ // provider registers before the first build and this never fires.
3244
+ const rebuildWalletRef = useRef(rebuildWallet)
3245
+ rebuildWalletRef.current = rebuildWallet
3246
+ useEffect(
3247
+ () =>
3248
+ onUnattestedTransportChange(present => {
3249
+ if (!present || !walletBuiltRef.current || managersRef.current.unverifiedPermissionsManager) return
3250
+ void rebuildWalletRef.current().catch(() => {})
3251
+ }),
3252
+ []
3253
+ )
3254
+
3192
3255
  // Switch network: tear down wallet, update config, and rebuild on new chain.
3193
3256
  // The network belongs to the active profile, so this changes that profile's.
3194
3257
  //
@@ -3201,6 +3264,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3201
3264
  // The ref, not the state: the fallback below runs inside the same call.
3202
3265
  const from = selectedNetworkRef.current
3203
3266
  if (network === from || switchInFlightRef.current) return
3267
+ runSessionTeardown('network')
3204
3268
  logWithTimestamp(F, `Switching network from ${from} to ${network}`)
3205
3269
  const token = buildGenRef.current.bump()
3206
3270
  // Same hold-off as switchProfile: no build may start on the old network
@@ -3282,7 +3346,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3282
3346
  let __tBuild = 0
3283
3347
  try {
3284
3348
  // Pairings belong to the departing identity.
3285
- disconnectActivePairedSession()
3349
+ runSessionTeardown('profile')
3286
3350
  profileTransitionRef.current = true
3287
3351
  try {
3288
3352
  await teardownBuiltWallet()
@@ -3609,18 +3673,14 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3609
3673
  storage,
3610
3674
  adminOriginator,
3611
3675
  undefined,
3612
- // A credited TOKEN frame is the moment this device becomes
3613
- // responsible for submitting its chain (settlement rule 3), so the
3614
- // row and the evidence the frame carried are written here — not
3615
- // inside the queue, which knows nothing about settlement. Its own
3616
- // failure is never the payment's: the coin is already credited, and
3617
- // the drain re-derives what this missed on the next online tick.
3618
- mandalaRef.current?.onTokenCredited,
3619
- // The same facts, written BEFORE the internalize — which is the only
3620
- // ordering the unadmitted-broadcast guard can actually read
3621
- // (§4.3 guard #2). This one IS allowed to refuse the credit: the
3622
- // frame stays durable in the queue and the next tick retries it.
3623
- mandalaRef.current?.onTokenHeld
3676
+ // How a TOKEN frame's receipt settled, for the `color_transfers`
3677
+ // journal (held / settled / refused), and the lib's recipient path
3678
+ // that verifies and credits it (B7). Read off the ref on every pass:
3679
+ // the runtime is rebuilt with the wallet. The journal hook's own
3680
+ // failure is never the payment's, and until a row lands the missing
3681
+ // row holds the tx from broadcast (W1).
3682
+ mandalaRef.current?.nearby.onReceived,
3683
+ mandalaRef.current?.nearby.accept
3624
3684
  )
3625
3685
  const successes = results.filter(r => r.success)
3626
3686
  if (successes.length > 0) {
@@ -3840,6 +3900,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3840
3900
  TaskCreditInbox.noteConnectivity(online)
3841
3901
  TaskDrainOutbox.noteConnectivity(online)
3842
3902
  TaskBackupPush.noteConnectivity(online)
3903
+ // Back online: the module settles what was credited or handed over
3904
+ // offline (single-flight with the drain tick), and a row that settled
3905
+ // releases its held tx on the drain's next pass.
3906
+ if (online) void releaseAfterTokenSettle(mandalaRef.current?.settleAll(), 'reconnect')
3843
3907
  })
3844
3908
  }, [walletBuilt])
3845
3909
 
@@ -3879,6 +3943,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3879
3943
  const isNowForeground = nextAppState === 'active'
3880
3944
 
3881
3945
  if (wasBackground && isNowForeground) {
3946
+ void releaseAfterTokenSettle(mandalaRef.current?.settleAll(), 'foreground')
3882
3947
  // The loop's timers were frozen with the app; the gap is the OS's, not
3883
3948
  // the monitor's. Without this the first watchdog check after a long
3884
3949
  // background would restart a healthy loop.
@@ -3969,10 +4034,14 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3969
4034
  // hardware session before monitor or storage teardown yields.
3970
4035
  vaultStore.clearScope()
3971
4036
  vaultCeremony.cancel()
4037
+ // And stop the color module starting any new token submit; its store is
4038
+ // the database destroyed below.
4039
+ disposeColorModule(colorRef)
3972
4040
  // XR-018: a live paired RPC socket otherwise outlives logout/wallet
3973
4041
  // deletion — the peer would keep dispatching allowlisted BRC-100 methods
3974
4042
  // against a wallet the user believes they've logged out of.
3975
- disconnectActivePairedSession()
4043
+ runSessionTeardown('logout')
4044
+ withdrawCurrentPrompts()
3976
4045
  // The IIFE's promise IS returned (unlike the old fire-and-forget version):
3977
4046
  // XR-107 needs the caller to await the verified outcome of the secret
3978
4047
  // erasure below, not just the synchronous kickoff. This does not
@@ -4055,7 +4124,6 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
4055
4124
  setStorage(null)
4056
4125
  mandalaRef.current = undefined
4057
4126
  setMandala(undefined)
4058
- forgetSessionPsks()
4059
4127
 
4060
4128
  vaultStore.clearScope()
4061
4129
  updateManagers({})
@@ -4642,13 +4710,15 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
4642
4710
  groupRequests: groupQueue.requests,
4643
4711
  btmsRequests: btmsQueue.requests,
4644
4712
  mandalaRequests: mandalaQueue.requests,
4645
- advanceBasketQueue: basketQueue.advance,
4646
- advanceCertificateQueue: certificateQueue.advance,
4647
- advanceProtocolQueue: protocolQueue.advance,
4648
- advanceSpendingQueue: spendingQueue.advance,
4649
- advanceGroupQueue: groupQueue.advance,
4713
+ advanceBasketQueue,
4714
+ advanceCertificateQueue,
4715
+ advanceProtocolQueue,
4716
+ advanceSpendingQueue,
4717
+ advanceGroupQueue,
4650
4718
  advanceBtmsQueue,
4651
4719
  advanceMandalaQueue,
4720
+ withdrawPrompts,
4721
+ registerPromptWithdrawal,
4652
4722
  finalizeConfig,
4653
4723
  setConfigStatus,
4654
4724
  configStatus,
@@ -4702,13 +4772,15 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
4702
4772
  groupQueue.requests,
4703
4773
  btmsQueue.requests,
4704
4774
  mandalaQueue.requests,
4705
- basketQueue.advance,
4706
- certificateQueue.advance,
4707
- protocolQueue.advance,
4708
- spendingQueue.advance,
4709
- groupQueue.advance,
4775
+ advanceBasketQueue,
4776
+ advanceCertificateQueue,
4777
+ advanceProtocolQueue,
4778
+ advanceSpendingQueue,
4779
+ advanceGroupQueue,
4710
4780
  advanceBtmsQueue,
4711
4781
  advanceMandalaQueue,
4782
+ withdrawPrompts,
4783
+ registerPromptWithdrawal,
4712
4784
  finalizeConfig,
4713
4785
  setConfigStatus,
4714
4786
  configStatus,
@@ -4813,11 +4885,11 @@ export interface WalletQueuesSlice {
4813
4885
  groupRequests: GroupPermissionRequest[]
4814
4886
  btmsRequests: BtmsRequest[]
4815
4887
  mandalaRequests: MandalaRequest[]
4816
- advanceBasketQueue: () => void
4817
- advanceCertificateQueue: () => void
4818
- advanceProtocolQueue: () => void
4819
- advanceSpendingQueue: () => void
4820
- advanceGroupQueue: () => void
4888
+ advanceBasketQueue: (requestID?: string) => void
4889
+ advanceCertificateQueue: (requestID?: string) => void
4890
+ advanceProtocolQueue: (requestID?: string) => void
4891
+ advanceSpendingQueue: (requestID?: string) => void
4892
+ advanceGroupQueue: (requestID?: string) => void
4821
4893
  advanceBtmsQueue: (approved: boolean) => void
4822
4894
  advanceMandalaQueue: (approved: boolean) => void
4823
4895
  }