@bsv/expo-wallet-toolbox 0.21.0 → 0.22.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 (78) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/README.md +78 -13
  3. package/core/contacts/contactActivity.ts +48 -28
  4. package/core/contacts/contactsStore.ts +2 -2
  5. package/core/context/WalletContext.tsx +166 -219
  6. package/core/demo/demoAssets.ts +8 -10
  7. package/core/demo/demoLedger.ts +32 -38
  8. package/core/demo/demoMandalaRuntime.ts +67 -49
  9. package/core/demo/index.ts +1 -1
  10. package/core/i18n/translations.tsx +72 -0
  11. package/core/index.ts +55 -37
  12. package/core/localpay/build.ts +110 -569
  13. package/core/localpay/codec.ts +190 -93
  14. package/core/localpay/pending.ts +217 -202
  15. package/core/localpay/session.ts +99 -25
  16. package/core/localpay/types.ts +6 -5
  17. package/core/localpay/verify.ts +118 -173
  18. package/core/mandala/abortGuard.ts +97 -120
  19. package/core/mandala/accessPolicy.ts +133 -0
  20. package/core/mandala/assets.ts +370 -0
  21. package/core/mandala/colorGuard.ts +178 -0
  22. package/core/mandala/colorModule.ts +82 -0
  23. package/core/mandala/createRuntime.ts +483 -2392
  24. package/core/mandala/handle.ts +694 -0
  25. package/core/mandala/kvStore.ts +105 -0
  26. package/core/mandala/nearby.ts +185 -0
  27. package/core/mandala/receipt.ts +121 -0
  28. package/core/mandala/runtime.ts +166 -312
  29. package/core/mandala/settle.ts +540 -0
  30. package/core/mandala/transferJournal.ts +395 -0
  31. package/core/mandala/types.ts +61 -311
  32. package/core/networks.ts +5 -5
  33. package/core/offline/cancelParked.ts +80 -63
  34. package/core/offline/payerHold.ts +52 -118
  35. package/core/parsePeerPayURI.ts +25 -12
  36. package/core/pay/rails/handle.ts +15 -14
  37. package/core/pay/rails/index.ts +5 -3
  38. package/core/pay/rails/nearby.ts +25 -87
  39. package/core/profiles/assertProfileEmpty.ts +19 -10
  40. package/core/services/vault/guard.ts +5 -4
  41. package/core/storage/StorageExpoSQLite.ts +93 -229
  42. package/core/storage/methods/processOfflineActions.ts +86 -136
  43. package/core/storage/schema/createTables.ts +9 -184
  44. package/package.json +6 -5
  45. package/ui/components/pay/AssetPicker.tsx +2 -2
  46. package/ui/components/pay/HandleReceive.tsx +4 -4
  47. package/ui/components/pay/NearbyFlow.tsx +324 -239
  48. package/ui/components/pay/RequestHub.tsx +10 -0
  49. package/ui/components/pay/UniversalSend.tsx +31 -28
  50. package/ui/components/pay/useRecipientInput.ts +2 -2
  51. package/ui/components/ui/PermissionSheet.tsx +94 -160
  52. package/ui/components/ui/colorPrompt.ts +236 -0
  53. package/ui/components/wallet/AmountInput.tsx +9 -6
  54. package/ui/components/wallet/AssetAmount.tsx +6 -6
  55. package/ui/components/wallet/AssetSwitcherDropdown.tsx +26 -7
  56. package/ui/components/wallet/Balance.tsx +3 -1
  57. package/ui/components/wallet/ContactActivityList.tsx +10 -13
  58. package/ui/components/wallet/tokenEviction.ts +9 -9
  59. package/ui/hooks/useMandala.ts +6 -6
  60. package/ui/hooks/useSpendableBalance.ts +3 -1
  61. package/ui/importDatabases.ts +1 -1
  62. package/ui/screens/PayScreen.tsx +14 -20
  63. package/ui/screens/SettingsScreen.tsx +3 -1
  64. package/ui/screens/WalletCheckScreen.tsx +7 -2
  65. package/ui/screens/WalletHomeScreen.tsx +40 -14
  66. package/ui/screens/tokenRowTitle.ts +28 -15
  67. package/ui/tokenFormat.ts +133 -69
  68. package/ui/tokenStatus.ts +5 -8
  69. package/core/localpay/settlementAck.ts +0 -155
  70. package/core/mandala/basketMigration.ts +0 -166
  71. package/core/mandala/bundle.ts +0 -244
  72. package/core/mandala/drain.ts +0 -754
  73. package/core/mandala/inboxPrehold.ts +0 -193
  74. package/core/mandala/permissionModule.ts +0 -931
  75. package/core/mandala/resendTransfer.ts +0 -178
  76. package/core/mandala/settlementStore.ts +0 -434
  77. package/core/mandala/token.ts +0 -45
  78. package/core/offline/tokenFrames.ts +0 -197
@@ -110,34 +110,22 @@ function loadQuietEventSourceClass(): EventSourceCtor {
110
110
  }
111
111
 
112
112
  /**
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.
113
+ * Dispose this build's color module and drop it from the ref. Sync,
114
+ * idempotent and never throws: it runs at the head of every teardown, before
115
+ * the storage under the module's store is destroyed, so an in-flight
116
+ * `settle()` resolves but no new overlay submit starts against a closing
117
+ * database (IC §2.3 `dispose`).
121
118
  */
122
- async function resolveMandalaAssetMetadata(assetId: string): Promise<MandalaAssetMetadata | null> {
119
+ function disposeColorModule(ref: { current: BuiltColorModule | undefined }): void {
120
+ const built = ref.current
121
+ ref.current = undefined
123
122
  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
123
+ built?.module.dispose()
124
+ } catch (error) {
125
+ console.warn('[WalletContext] color module dispose failed:', error)
129
126
  }
130
127
  }
131
128
 
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
129
  import type { AppChain } from '../config'
142
130
  import { DEFAULT_STORAGE_URL, DEFAULT_CHAIN, ADMIN_ORIGINATOR, toWalletChain } from '../config'
143
131
  import { NETWORKS, isAppChain } from '../networks'
@@ -157,17 +145,11 @@ import AsyncStorage from '@react-native-async-storage/async-storage'
157
145
  import { UserContext } from './UserContext'
158
146
  import { useLocalStorage } from './LocalStorageProvider'
159
147
  import { usePermissionQueue } from '../hooks/usePermissionQueue'
160
- import { configureMandala, resolveAssetMetadata } from '@bsv/mandala'
148
+ import { configureMandala } from '@bsv/mandala'
161
149
  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
150
  import { wrapAbortActionForSettlements } from '../mandala/abortGuard'
170
- import { migrateMandalaBasketName } from '../mandala/basketMigration'
151
+ import { createColorAccessPolicy } from '../mandala/accessPolicy'
152
+ import { buildColorModule, type BuiltColorModule } from '../mandala/colorModule'
171
153
  import {
172
154
  bindOriginator,
173
155
  createMandalaKvStorage,
@@ -175,10 +157,8 @@ import {
175
157
  type MandalaMessageBox
176
158
  } from '../mandala/createRuntime'
177
159
  import type { MandalaRuntime } from '../mandala/runtime'
178
- import { MANDALA_BASKET } from '../mandala/types'
179
160
  import { mandalaSettlementDeps, type CancelParkedSettlementDeps } from '../offline/cancelParked'
180
161
  import { drainMandalaInbox } from '../pay/rails/handle'
181
- import { forgetSessionPsks, sealedFramePayloadDecoder } from '../offline/tokenFrames'
182
162
  import { disconnectActivePairedSession } from './WalletConnectionContext'
183
163
  import connectionStore from '../stores/ConnectionStore'
184
164
  import { loadUserAvatarIcon } from '../userAvatar'
@@ -198,7 +178,7 @@ import {
198
178
  createWocBroadcastService
199
179
  } from '../services/arcadeBroadcastProvider'
200
180
  import { getExchangeRate } from '../services/exchangeRate'
201
- import { logWithTimestamp } from '../logging'
181
+ import { devLog, logWithTimestamp } from '../logging'
202
182
  import { recoverMnemonicWallet } from '../mnemonicWallet'
203
183
  import { backupProbe, discoverProfiles, registerDiscoveredProfile } from '../profiles/discovery'
204
184
  import {
@@ -741,13 +721,27 @@ type BtmsRequest = {
741
721
  resolve: (approved: boolean) => void
742
722
  }
743
723
 
744
- /** Same shape as BtmsRequest — MandalaTokenModule's requestTokenAccess queue item. */
724
+ /** Same shape as BtmsRequest — the color module's consent queue item (via createColorAccessPolicy). */
725
+ /**
726
+ * Waits on a foreground or reconnect `settleAll()` (single-flight with the
727
+ * drain tick's own settle). A row that settled releases its held tx on the
728
+ * drain's next pass, so that pass is asked for now. Never rejects: a settle
729
+ * that fails leaves every row as it was, for the next tick.
730
+ */
731
+ async function releaseAfterTokenSettle(settling: Promise<number> | undefined, when: string): Promise<void> {
732
+ try {
733
+ if (((await settling) ?? 0) > 0) TaskSendOffline.requestNow()
734
+ } catch (e) {
735
+ devLog(`[WalletContext] ${when} token settle failed:`, e)
736
+ }
737
+ }
738
+
745
739
  type MandalaRequest = {
746
- /** The originator (dApp domain) requesting Mandala token access */
740
+ /** The originator (dApp domain) requesting token access */
747
741
  originator: string
748
- /** The raw message from MandalaTokenModule (JSON-encoded promptData) */
742
+ /** The raw consent message from the color module (JSON, IC §2.5) */
749
743
  message: string
750
- /** Resolve the pending Promise from MandalaTokenModule — true = approved */
744
+ /** Resolve the pending consent Promise — true = approved */
751
745
  resolve: (approved: boolean) => void
752
746
  }
753
747
 
@@ -841,6 +835,13 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
841
835
  */
842
836
  const [mandala, setMandala] = useState<MandalaRuntime | undefined>(undefined)
843
837
  const mandalaRef = useRef<MandalaRuntime | undefined>(undefined)
838
+ /**
839
+ * This build's BRC-207 color module (with its provider and store), or
840
+ * undefined on a chain with no Mandala endpoints, before a build, or when
841
+ * the module could not be built. The runtime and the drain tick read it
842
+ * here; teardown disposes it.
843
+ */
844
+ const colorRef = useRef<BuiltColorModule | undefined>(undefined)
844
845
  const appStateRef = useRef<AppStateStatus>(AppState.currentState)
845
846
  const monitorSupervisorRef = useRef<MonitorSupervisor | null>(null)
846
847
  const monitorRef = useRef<Monitor | null>(null)
@@ -1917,32 +1918,17 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1917
1918
  }
1918
1919
  }
1919
1920
 
1920
- let migrationUserId: number | undefined
1921
1921
  try {
1922
1922
  const auth = await storageManager.getAuth()
1923
1923
  setWalletUserId(auth.userId ?? null)
1924
- migrationUserId = auth.userId ?? undefined
1925
1924
  } catch {
1926
1925
  // Scoping is a filter, not a gate: with no id the queue reads fall
1927
1926
  // back to unscoped, which is today's behaviour.
1928
1927
  setWalletUserId(null)
1929
1928
  }
1930
1929
 
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.
1930
+ // Hand `@bsv/mandala` this deployment's endpoints and a DURABLE
1931
+ // journal store — before any lib call can run.
1946
1932
  //
1947
1933
  // The storage adapter is the load-bearing half. The lib's journals
1948
1934
  // are its recovery contract: an overlay-accepted, not-yet-broadcast
@@ -1952,17 +1938,15 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1952
1938
  // process-lifetime Map — i.e. no crash recovery at all — and the
1953
1939
  // failure is silent. See lib/src/storage.ts.
1954
1940
  //
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).
1941
+ // Token custody is no longer the lib's: value outputs live in the
1942
+ // color module's `p color <assetTag>` baskets (registered below), so
1943
+ // no basket is configured here.
1959
1944
  if (mandalaEndpoints) {
1960
1945
  try {
1961
1946
  configureMandala({
1962
1947
  overlayUrl: mandalaEndpoints.overlayUrl,
1963
1948
  overlayIdentityKey: mandalaEndpoints.overlayIdentityKey,
1964
1949
  messageBoxUrl: mandalaEndpoints.messageBoxUrl,
1965
- basket: MANDALA_BASKET,
1966
1950
  storage: createMandalaKvStorage(phoneStorage)
1967
1951
  })
1968
1952
  } catch (error) {
@@ -1976,72 +1960,53 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1976
1960
  // "p btms" operations surface a UI modal rather than silently denying.
1977
1961
  const btmsModule = loadBtmsPermissionModule().createBtmsModule({ wallet, promptHandler: btmsPromptHandler })
1978
1962
 
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.
1963
+ // The BRC-207 color module (plan 07 Task 10): all token custody and
1964
+ // evidence, registered below as `permissionModules.color`, so every
1965
+ // `p color` basket, label and protocol call — from any originator —
1966
+ // goes through it. Built over the UNDERLYING `wallet`, never the
1967
+ // manager: the module derives and signs on it directly.
1985
1968
  //
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
- )
2032
-
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
- })
1969
+ // Only with endpoints AND this device's storage: the module's
1970
+ // evidence store is the wallet's key_value_store. Otherwise, and when
1971
+ // the build throws (a malformed overlay key or url), there is no
1972
+ // `color` key at all, so `p color` calls fail closed with
1973
+ // "Unsupported P-module scheme" (S5). The broadcast hold and the abort
1974
+ // refusal do not depend on the module: they key on the journal and on
1975
+ // `mandalaEndpoints`, so a missing module still holds every token tx.
1976
+ //
1977
+ // Consent goes through createColorAccessPolicy (W2): the wallet's own
1978
+ // screens are approved without a prompt, external originators queue on
1979
+ // the permission sheet. A fresh policy per build, so a read grant never
1980
+ // outlives the wallet that gave it.
1981
+ //
1982
+ // A previous build's module is disposed first (teardown normally has
1983
+ // already): two live modules would each hold selections and settle
1984
+ // latches over the same store.
1985
+ //
1986
+ // Only while this build is still the wanted one. A switch that
1987
+ // overtook it has already torn down and may have started the next
1988
+ // build, whose LIVE module the ref now holds: disposing that would
1989
+ // leave it routing `p color` calls that can never settle again. A
1990
+ // stale build touches neither the ref nor a module (it is discarded
1991
+ // before publishing, below). The check and the assignment are one
1992
+ // synchronous step, so no build can interleave between them.
1993
+ let colorModule: BuiltColorModule['module'] | undefined
1994
+ if (stillWanted()) {
1995
+ disposeColorModule(colorRef)
1996
+ if (mandalaEndpoints && phoneStorage) {
1997
+ try {
1998
+ colorRef.current = buildColorModule({
1999
+ wallet,
2000
+ endpoints: mandalaEndpoints,
2001
+ kv: phoneStorage,
2002
+ requestTokenAccess: createColorAccessPolicy({ adminOriginator, prompt: mandalaPromptHandler })
2003
+ })
2004
+ } catch (error) {
2005
+ console.error('[WalletContext] could not build the color module; p color calls will be refused:', error)
2006
+ }
2007
+ }
2008
+ colorModule = colorRef.current?.module
2009
+ }
2045
2010
 
2046
2011
  // Setup permissions with provided callbacks and BTMS module.
2047
2012
  const permissionsManager = new SigningPolicyPermissionsManager(wallet, adminOriginator, {
@@ -2074,7 +2039,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2074
2039
  // signing is exempt (SigningPolicyPermissionsManager).
2075
2040
  seekProtocolPermissionsForSigning: true,
2076
2041
  seekSpendingPermissions: true,
2077
- permissionModules: { btms: btmsModule, mandala: mandalaModule }
2042
+ permissionModules: colorModule ? { btms: btmsModule, color: colorModule } : { btms: btmsModule }
2078
2043
  } as any)
2079
2044
 
2080
2045
  if (protocolPermissionCallback) {
@@ -2098,42 +2063,32 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2098
2063
  // SQLite storage; with no local storage those external calls are
2099
2064
  // refused rather than let through.
2100
2065
  //
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.
2066
+ // `wrapAbortActionForSettlements` wraps the result-conforming manager
2067
+ // and guardVaultAccess is applied to ITS result (never the other way
2068
+ // around), so the published object stays the one the guard's own
2069
+ // re-wrap dedup recognises — several screens rely on that
2070
+ // (`guardVaultAccess(managers.permissionsManager, ADMIN_ORIGINATOR)`
2071
+ // again). It is the last line of defence for the 2026-09-15 incident —
2072
+ // an `abortAction` against a token payment the payee or the overlay
2073
+ // may already have releases inputs that are spent on chain. It reads
2074
+ // the `color_transfers` journal LATE, off `mandalaRef`, because the
2075
+ // runtime is built below this line and replaced on every rebuild.
2114
2076
  //
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.
2077
+ // No createAction input wrapper sits here any more. The color module
2078
+ // is reached through `p color` plan labels and baskets, and a `p color`
2079
+ // input can only be unlocked through the module's signature-envelope
2080
+ // path (a bare digest under a `p color` key is refused, A.13), so a
2081
+ // spend that names no plan cannot move tokens around it.
2123
2082
  //
2124
2083
  // XR-034: `mandalaEndpoints` (above, static for this build) is the
2125
2084
  // guard's ONLY "token settlement provably not in use" signal — never
2126
2085
  // `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.
2086
+ // threw or is mid-rebuild, both of which can leave real journal rows
2087
+ // unreadable rather than absent.
2129
2088
  newManagers.permissionsManager = guardVaultAccess(
2130
2089
  wrapAbortActionForSettlements(
2131
- wrapCreateActionForTokenInputs(
2132
- conformWalletResults(adminOriginator, permissionsManager),
2133
- listMandalaTokenOutpoints,
2134
- adminOriginator
2135
- ),
2136
- () => mandalaRef.current?.store,
2090
+ conformWalletResults(adminOriginator, permissionsManager),
2091
+ () => mandalaRef.current?.journal,
2137
2092
  () => mandalaEndpoints !== undefined
2138
2093
  ),
2139
2094
  adminOriginator,
@@ -2156,6 +2111,17 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2156
2111
  storage: phoneStorage,
2157
2112
  chain,
2158
2113
  endpoints: mandalaEndpoints,
2114
+ // The module registered above for THIS build (undefined without
2115
+ // endpoints, or when its build failed): its host-only
2116
+ // `markSettled`, the overlay provider and the host ledger all
2117
+ // come from it. Without it the runtime is unavailable rather
2118
+ // than half-wired.
2119
+ color: colorRef.current?.module,
2120
+ provider: colorRef.current?.provider,
2121
+ ledger: colorRef.current?.ledger,
2122
+ // The UNDERLYING wallet the module was built over (B7): hand-over
2123
+ // envelopes are built from its custody, never through the manager.
2124
+ hostWallet: colorRef.current ? (wallet as never) : undefined,
2159
2125
  // Lazy: constructing a runtime must do no I/O, and a wallet that
2160
2126
  // never touches stablecoins never opens a MessageBox connection.
2161
2127
  messageBox: mandalaEndpoints
@@ -2175,17 +2141,12 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2175
2141
  chain
2176
2142
  ) as unknown as MandalaMessageBox
2177
2143
  : 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
2144
  // The one thing `settleNow` asks about connectivity: whether a
2183
2145
  // hand-over that just landed should be followed by this device's
2184
2146
  // own submit now, or left to the drain. The runtime deliberately
2185
2147
  // has no NetInfo dependency of its own, so the app-wide probe is
2186
2148
  // handed to it here.
2187
- isOnline: getOnline,
2188
- refetchBeef: makeBeefRepair({ woc: wocConfigFor(chain), online: getOnline })
2149
+ isOnline: getOnline
2189
2150
  })
2190
2151
  mandalaRef.current = runtime.available ? runtime : undefined
2191
2152
  setMandala(runtime.available ? runtime : undefined)
@@ -2259,49 +2220,28 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2259
2220
  if (phoneStorage) {
2260
2221
  monitor.addTask(
2261
2222
  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()
2223
+ // The color runtime's own pass first: redeliver undelivered
2224
+ // hand-overs, the module settle, and the held-receipt
2225
+ // reconcile (`MandalaRuntime.tick`, never throws). It runs
2226
+ // AHEAD of the release pass on purpose — `processOfflineActions`
2227
+ // posts a held 1Color tx only once its `color_transfers` row
2228
+ // reads `settled`, so a row this settles goes out in the SAME
2229
+ // pass. Read from the ref, not captured: a rebuild replaces the
2230
+ // runtime under a task that was registered once, and a
2231
+ // torn-down wallet's ref is undefined, so it drains nothing.
2232
+ await mandalaRef.current?.tick()
2292
2233
  const r = await processOfflineActions({
2293
2234
  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
2235
+ refetchBeef: makeBeefRepair({ woc: wocConfigFor(chain), online: getOnline })
2304
2236
  })
2237
+ // The handle rail's `mandala-color` box, on the drain's cadence
2238
+ // too: a hand-over credited here is journaled `held` and the
2239
+ // next tick settles it. The credit-inbox task drains the same
2240
+ // box (its `incomplete` flag feeds the profile removal check);
2241
+ // both coalesce on the runtime's receive single flight. Never
2242
+ // throws (see drainMandalaInbox).
2243
+ const drained = await drainMandalaInbox(mandalaRef.current)
2244
+ if (drained.credited > 0) setTxStatusVersion(v => v + 1)
2305
2245
  // The drain writes transaction statuses directly, below the
2306
2246
  // monitor's onTransactionStatusChanged callback — bump the
2307
2247
  // version ourselves so the transactions screen re-fetches.
@@ -2464,9 +2404,11 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2464
2404
  if (sendWaiting?.processUnsent) {
2465
2405
  const orig = sendWaiting.processUnsent.bind(sendWaiting)
2466
2406
  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.
2407
+ // Guard #2 for this path: an unsettled 1Color request (its
2408
+ // `color_transfers` row is missing or not `settled`, see
2409
+ // `colorHeldTxids`) is the drain's to release once the module
2410
+ // settles it, never the monitor's. Held here and dropped from
2411
+ // this pass.
2470
2412
  const heldTokenTxids = await phoneStorage.holdTokenReqsForDrain(allReqApis as never)
2471
2413
  const reqApis =
2472
2414
  heldTokenTxids.size > 0 ? allReqApis.filter(r => !heldTokenTxids.has(r.txid)) : allReqApis
@@ -3103,6 +3045,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3103
3045
  // signer/listing already in flight can resume against the departing wallet.
3104
3046
  vaultStore.clearScope()
3105
3047
  vaultCeremony.cancel()
3048
+ // Same reason for the color module: no new token submit may start once
3049
+ // teardown has begun, and its store is about to be destroyed below.
3050
+ disposeColorModule(colorRef)
3106
3051
 
3107
3052
  // Push listeners and the registration sync belong to the wallet being
3108
3053
  // torn down; nothing may fire them against it from here on.
@@ -3144,7 +3089,6 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3144
3089
  // task or a screen draining the departed wallet's tables.
3145
3090
  mandalaRef.current = undefined
3146
3091
  setMandala(undefined)
3147
- forgetSessionPsks()
3148
3092
 
3149
3093
  // Tear down current wallet state (but keep mnemonic / config)
3150
3094
  vaultStore.clearScope()
@@ -3609,18 +3553,14 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3609
3553
  storage,
3610
3554
  adminOriginator,
3611
3555
  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
3556
+ // How a TOKEN frame's receipt settled, for the `color_transfers`
3557
+ // journal (held / settled / refused), and the lib's recipient path
3558
+ // that verifies and credits it (B7). Read off the ref on every pass:
3559
+ // the runtime is rebuilt with the wallet. The journal hook's own
3560
+ // failure is never the payment's, and until a row lands the missing
3561
+ // row holds the tx from broadcast (W1).
3562
+ mandalaRef.current?.nearby.onReceived,
3563
+ mandalaRef.current?.nearby.accept
3624
3564
  )
3625
3565
  const successes = results.filter(r => r.success)
3626
3566
  if (successes.length > 0) {
@@ -3840,6 +3780,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3840
3780
  TaskCreditInbox.noteConnectivity(online)
3841
3781
  TaskDrainOutbox.noteConnectivity(online)
3842
3782
  TaskBackupPush.noteConnectivity(online)
3783
+ // Back online: the module settles what was credited or handed over
3784
+ // offline (single-flight with the drain tick), and a row that settled
3785
+ // releases its held tx on the drain's next pass.
3786
+ if (online) void releaseAfterTokenSettle(mandalaRef.current?.settleAll(), 'reconnect')
3843
3787
  })
3844
3788
  }, [walletBuilt])
3845
3789
 
@@ -3879,6 +3823,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3879
3823
  const isNowForeground = nextAppState === 'active'
3880
3824
 
3881
3825
  if (wasBackground && isNowForeground) {
3826
+ void releaseAfterTokenSettle(mandalaRef.current?.settleAll(), 'foreground')
3882
3827
  // The loop's timers were frozen with the app; the gap is the OS's, not
3883
3828
  // the monitor's. Without this the first watchdog check after a long
3884
3829
  // background would restart a healthy loop.
@@ -3969,6 +3914,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3969
3914
  // hardware session before monitor or storage teardown yields.
3970
3915
  vaultStore.clearScope()
3971
3916
  vaultCeremony.cancel()
3917
+ // And stop the color module starting any new token submit; its store is
3918
+ // the database destroyed below.
3919
+ disposeColorModule(colorRef)
3972
3920
  // XR-018: a live paired RPC socket otherwise outlives logout/wallet
3973
3921
  // deletion — the peer would keep dispatching allowlisted BRC-100 methods
3974
3922
  // against a wallet the user believes they've logged out of.
@@ -4055,7 +4003,6 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
4055
4003
  setStorage(null)
4056
4004
  mandalaRef.current = undefined
4057
4005
  setMandala(undefined)
4058
- forgetSessionPsks()
4059
4006
 
4060
4007
  vaultStore.clearScope()
4061
4008
  updateManagers({})
@@ -13,8 +13,8 @@
13
13
  import type { TokenAssetInfo } from '../mandala/runtime'
14
14
 
15
15
  /** Demo overlay identity — 66 hex chars, the length a real one has. */
16
- const DEMO_OVERLAY_KEY = '02' + 'de'.repeat(32)
17
- const DEMO_OVERLAY_URL = 'https://overlay.demo.invalid'
16
+ export const DEMO_OVERLAY_KEY = '02' + 'de'.repeat(32)
17
+ export const DEMO_OVERLAY_URL = 'https://overlay.demo.invalid'
18
18
 
19
19
  export const DEMO_USD: TokenAssetInfo = {
20
20
  assetId: 'd0'.repeat(32) + '_0',
@@ -22,8 +22,7 @@ export const DEMO_USD: TokenAssetInfo = {
22
22
  ticker: 'USDX',
23
23
  decimals: 2,
24
24
  issuerName: 'Acme Bank',
25
- overlayUrl: DEMO_OVERLAY_URL,
26
- overlayIdentityKey: DEMO_OVERLAY_KEY
25
+ resolved: true
27
26
  }
28
27
 
29
28
  export const DEMO_CHF: TokenAssetInfo = {
@@ -32,8 +31,7 @@ export const DEMO_CHF: TokenAssetInfo = {
32
31
  ticker: 'CHFX',
33
32
  decimals: 2,
34
33
  issuerName: 'Helvetia Bank',
35
- overlayIdentityKey: DEMO_OVERLAY_KEY,
36
- overlayUrl: DEMO_OVERLAY_URL
34
+ resolved: true
37
35
  }
38
36
 
39
37
  export const DEMO_ASSETS: TokenAssetInfo[] = [DEMO_USD, DEMO_CHF]
@@ -45,10 +43,10 @@ export function demoAssetById(assetId: string): TokenAssetInfo | undefined {
45
43
  /** Opening BSV balance, in satoshis. 0.25 BSV — enough to read as funded. */
46
44
  export const DEMO_OPENING_SATS = 25_000_000
47
45
 
48
- /** Opening token balances, in base units (2 dp): 1,240.00 USDX / 860.50 CHFX. */
49
- export const DEMO_OPENING_TOKEN_BASE_UNITS: Record<string, number> = {
50
- [DEMO_USD.assetId]: 124_000,
51
- [DEMO_CHF.assetId]: 86_050
46
+ /** Opening token balances, in exact token units (2 dp): 1,240.00 USDX / 860.50 CHFX. */
47
+ export const DEMO_OPENING_TOKEN_UNITS: Record<string, bigint> = {
48
+ [DEMO_USD.assetId]: 124_000n,
49
+ [DEMO_CHF.assetId]: 86_050n
52
50
  }
53
51
 
54
52
  /** Counterparties the demo history is transacted against. */