@bsv/expo-wallet-toolbox 0.21.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/CHANGELOG.md +222 -0
  2. package/README.md +82 -13
  3. package/core/bridge/BrowserBridgeProvider.tsx +273 -0
  4. package/core/bridge/bindings.ts +459 -0
  5. package/core/bridge/conformance.ts +222 -0
  6. package/core/bridge/consent.ts +494 -0
  7. package/core/bridge/consentSheetSource.ts +98 -0
  8. package/core/bridge/dispatcher.ts +621 -0
  9. package/core/bridge/inbox.ts +464 -0
  10. package/core/bridge/index.ts +48 -0
  11. package/core/bridge/loopback/cors.ts +57 -0
  12. package/core/bridge/loopback/endpoints.ts +11 -0
  13. package/core/bridge/loopback/hostCheck.ts +25 -0
  14. package/core/bridge/loopback/index.ts +7 -0
  15. package/core/bridge/loopback/launchProof.ts +166 -0
  16. package/core/bridge/loopback/router.ts +770 -0
  17. package/core/bridge/loopback/routerTypes.ts +115 -0
  18. package/core/bridge/loopback/status.ts +52 -0
  19. package/core/bridge/memoryInboxStore.ts +222 -0
  20. package/core/bridge/permissionPolicy.ts +247 -0
  21. package/core/bridge/policy.ts +72 -0
  22. package/core/bridge/protocol/base64url.ts +64 -0
  23. package/core/bridge/protocol/connectionError.ts +79 -0
  24. package/core/bridge/protocol/constants.ts +21 -0
  25. package/core/bridge/protocol/continuity.ts +21 -0
  26. package/core/bridge/protocol/descriptor.ts +395 -0
  27. package/core/bridge/protocol/envelopes.ts +188 -0
  28. package/core/bridge/protocol/errorCodec.ts +164 -0
  29. package/core/bridge/protocol/json.ts +237 -0
  30. package/core/bridge/protocol/limits.ts +43 -0
  31. package/core/bridge/protocol/methods.ts +55 -0
  32. package/core/bridge/protocol/origin.ts +130 -0
  33. package/core/bridge/runtime.ts +642 -0
  34. package/core/bridge/runtimeFlags.ts +34 -0
  35. package/core/bridge/testing/conformanceCases.ts +149 -0
  36. package/core/bridge/testing/pageClient.ts +44 -0
  37. package/core/bridge/unverifiedManager.ts +97 -0
  38. package/core/bridge/unverifiedOriginator.ts +79 -0
  39. package/core/config.tsx +1 -16
  40. package/core/contacts/contactActivity.ts +48 -28
  41. package/core/contacts/contactsStore.ts +2 -2
  42. package/core/context/WalletConnectionContext.tsx +7 -1
  43. package/core/context/WalletContext.tsx +420 -348
  44. package/core/context/sessionTeardown.ts +46 -0
  45. package/core/demo/demoAssets.ts +8 -10
  46. package/core/demo/demoLedger.ts +32 -38
  47. package/core/demo/demoMandalaRuntime.ts +67 -49
  48. package/core/demo/index.ts +1 -1
  49. package/core/hooks/usePermissionQueue.ts +89 -34
  50. package/core/i18n/translations.tsx +983 -12
  51. package/core/index.ts +70 -37
  52. package/core/localpay/build.ts +110 -569
  53. package/core/localpay/codec.ts +190 -93
  54. package/core/localpay/pending.ts +217 -202
  55. package/core/localpay/session.ts +99 -25
  56. package/core/localpay/types.ts +6 -5
  57. package/core/localpay/verify.ts +118 -173
  58. package/core/mandala/abortGuard.ts +97 -120
  59. package/core/mandala/accessPolicy.ts +133 -0
  60. package/core/mandala/assets.ts +370 -0
  61. package/core/mandala/colorGuard.ts +178 -0
  62. package/core/mandala/colorModule.ts +82 -0
  63. package/core/mandala/createRuntime.ts +483 -2392
  64. package/core/mandala/handle.ts +694 -0
  65. package/core/mandala/kvStore.ts +105 -0
  66. package/core/mandala/nearby.ts +185 -0
  67. package/core/mandala/receipt.ts +121 -0
  68. package/core/mandala/runtime.ts +166 -312
  69. package/core/mandala/settle.ts +540 -0
  70. package/core/mandala/transferJournal.ts +395 -0
  71. package/core/mandala/types.ts +61 -311
  72. package/core/networks.ts +5 -5
  73. package/core/offline/cancelParked.ts +80 -63
  74. package/core/offline/payerHold.ts +52 -118
  75. package/core/parsePeerPayURI.ts +25 -12
  76. package/core/pay/rails/handle.ts +15 -14
  77. package/core/pay/rails/index.ts +5 -3
  78. package/core/pay/rails/nearby.ts +25 -87
  79. package/core/profiles/assertProfileEmpty.ts +19 -10
  80. package/core/services/autoApprovePolicy.ts +7 -1
  81. package/core/services/capWalletArgs.ts +2 -1
  82. package/core/services/permissionPrompts.ts +132 -0
  83. package/core/services/signingPermissionPolicy.ts +230 -2
  84. package/core/services/vault/guard.ts +15 -4
  85. package/core/services/walletArgLimits.ts +17 -2
  86. package/core/storage/StorageExpoSQLite.ts +93 -229
  87. package/core/storage/encryptedDbImage.ts +325 -0
  88. package/core/storage/methods/processOfflineActions.ts +86 -136
  89. package/core/storage/schema/createTables.ts +9 -184
  90. package/core/toolboxConfig.ts +18 -1
  91. package/package.json +9 -8
  92. package/ui/bridgeSheet/ContextRelay.tsx +86 -0
  93. package/ui/bridgeSheet/relayedContexts.ts +21 -0
  94. package/ui/components/pay/AssetPicker.tsx +2 -2
  95. package/ui/components/pay/HandleReceive.tsx +4 -4
  96. package/ui/components/pay/NearbyFlow.tsx +324 -239
  97. package/ui/components/pay/RequestHub.tsx +10 -0
  98. package/ui/components/pay/UniversalSend.tsx +31 -28
  99. package/ui/components/pay/useRecipientInput.ts +2 -2
  100. package/ui/components/ui/PermissionSheet.tsx +625 -315
  101. package/ui/components/ui/Sheet.tsx +59 -7
  102. package/ui/components/ui/colorPrompt.ts +236 -0
  103. package/ui/components/ui/sheetResumeSignal.ts +19 -0
  104. package/ui/components/wallet/AmountInput.tsx +9 -6
  105. package/ui/components/wallet/AssetAmount.tsx +6 -6
  106. package/ui/components/wallet/AssetSwitcherDropdown.tsx +26 -7
  107. package/ui/components/wallet/Balance.tsx +3 -1
  108. package/ui/components/wallet/ContactActivityList.tsx +10 -13
  109. package/ui/components/wallet/tokenEviction.ts +9 -9
  110. package/ui/exportDatabases.ts +94 -5
  111. package/ui/hooks/useExportWalletData.ts +37 -24
  112. package/ui/hooks/useMandala.ts +6 -6
  113. package/ui/hooks/useSpendableBalance.ts +3 -1
  114. package/ui/importDatabases.ts +124 -29
  115. package/ui/index.ts +4 -0
  116. package/ui/screens/PayScreen.tsx +14 -20
  117. package/ui/screens/SettingsScreen.tsx +3 -1
  118. package/ui/screens/WalletCheckScreen.tsx +7 -2
  119. package/ui/screens/WalletConfigScreen.tsx +13 -1
  120. package/ui/screens/WalletHomeScreen.tsx +40 -14
  121. package/ui/screens/tokenRowTitle.ts +28 -15
  122. package/ui/tokenFormat.ts +133 -69
  123. package/ui/tokenStatus.ts +5 -8
  124. package/core/localpay/settlementAck.ts +0 -155
  125. package/core/mandala/basketMigration.ts +0 -166
  126. package/core/mandala/bundle.ts +0 -244
  127. package/core/mandala/drain.ts +0 -754
  128. package/core/mandala/inboxPrehold.ts +0 -193
  129. package/core/mandala/permissionModule.ts +0 -931
  130. package/core/mandala/resendTransfer.ts +0 -178
  131. package/core/mandala/settlementStore.ts +0 -434
  132. package/core/mandala/token.ts +0 -45
  133. package/core/offline/tokenFrames.ts +0 -197
@@ -1,6 +1,6 @@
1
1
  import type { SQLiteDatabase } from 'expo-sqlite'
2
2
  import type { BindValue } from '../methods/offlineActions'
3
- import { devLog } from '../../logging'
3
+ import { COLOR_TRANSFERS_DDL, migrateMandalaToColor } from '../../mandala/transferJournal'
4
4
 
5
5
  /**
6
6
  * SQL statements to create all wallet storage tables
@@ -162,7 +162,7 @@ export async function createTables(db: SQLiteDatabase): Promise<void> {
162
162
  // ALTER does (ensureTransactionsColumns, defined below — hoisted). Called
163
163
  // here, inside createTables, rather than only from StorageExpoSQLite.migrate,
164
164
  // so every direct createTables() caller (this schema file's own tests
165
- // included) gets these columns too, exactly like ensureTokenSettlementColumns
165
+ // included) gets these columns too, exactly like ensureContactsColumns
166
166
  // below.
167
167
  await ensureTransactionsColumns(db)
168
168
 
@@ -398,109 +398,13 @@ export async function createTables(db: SQLiteDatabase): Promise<void> {
398
398
  // with defaults, so an existing row reads back not-favourite and present.
399
399
  await ensureContactsColumns(db)
400
400
 
401
- await createMandalaSettlementTables(db)
402
- }
403
-
404
- /**
405
- * The four Mandala settlement tables (offline-settlement spec §4.1).
406
- *
407
- * Additive only: nothing in `offline_actions`, `proven_tx_reqs` or the
408
- * toolbox's own schema changes shape. `CREATE TABLE IF NOT EXISTS` is the whole
409
- * migration — a device upgrading into this feature gets the tables empty on its
410
- * next boot, and every row in them is re-derivable from frame bytes that are
411
- * already durable elsewhere (FIX G), so there is nothing to backfill.
412
- *
413
- * Split into its own exported function so the settlement store's tests can
414
- * stand the schema up without the rest of the wallet, and so a future migration
415
- * runner has one named unit to call.
416
- */
417
- export async function createMandalaSettlementTables(
418
- db: Pick<SQLiteDatabase, 'execAsync' | 'getAllAsync'>
419
- ): Promise<void> {
420
- // One row per token transaction this wallet has ever built, received, or
421
- // forwarded evidence for — THE single owner of "what state is this token
422
- // payment in" (spec §5). The `state` CHECK is deliberately the whole state
423
- // machine: a state this file does not list is a bug that must fail at the
424
- // write, not survive as an unreachable row nothing drains.
425
- await db.execAsync(`
426
- CREATE TABLE IF NOT EXISTS token_settlements (
427
- txid TEXT PRIMARY KEY,
428
- role TEXT NOT NULL CHECK (role IN ('sent','received')),
429
- assetId TEXT NOT NULL,
430
- state TEXT NOT NULL CHECK (state IN (
431
- 'built','parked','handed_over','held',
432
- 'submitting','admitted','broadcast','refused','orphaned')),
433
- counterpartyKey TEXT,
434
- amountBaseUnits INTEGER,
435
- overlayUrl TEXT NOT NULL,
436
- overlayIdentityKey TEXT NOT NULL,
437
- admissionOutputsJson TEXT,
438
- admissionSignatureHex TEXT,
439
- relevantVout INTEGER,
440
- refusedCode TEXT,
441
- refusedPayloadHash TEXT,
442
- poisonedByTxid TEXT,
443
- reference TEXT,
444
- createdAt TEXT NOT NULL,
445
- updatedAt TEXT NOT NULL
446
- );
447
- CREATE INDEX IF NOT EXISTS idx_token_settlements_state ON token_settlements(state);
448
- CREATE INDEX IF NOT EXISTS idx_token_settlements_role ON token_settlements(role);
449
- CREATE INDEX IF NOT EXISTS idx_token_settlements_createdAt ON token_settlements(createdAt);
450
- `)
451
-
452
- // A device that created these tables before `reference` existed keeps them;
453
- // CREATE TABLE IF NOT EXISTS cannot add the column, so the guarded ALTER does.
454
- await ensureTokenSettlementColumns(db)
455
- await db.execAsync(`CREATE INDEX IF NOT EXISTS idx_token_settlements_reference ON token_settlements(reference);`)
456
- // Drives a contact's activity pane (core/contacts/contactActivity.ts):
457
- // every token transfer with this counterparty, in one indexed lookup.
458
- await db.execAsync(
459
- `CREATE INDEX IF NOT EXISTS idx_token_settlements_counterpartyKey ON token_settlements(counterpartyKey);`
460
- )
461
-
462
- // Cached mirror of the AdmissionEntry values this device has SEEN. Purely a
463
- // derivable cache (FIX G) — never a precondition for anything.
464
- await db.execAsync(`
465
- CREATE TABLE IF NOT EXISTS token_admissions (
466
- txid TEXT PRIMARY KEY,
467
- outputsToAdmitJson TEXT NOT NULL,
468
- signatureHex TEXT NOT NULL,
469
- signerKey TEXT NOT NULL,
470
- source TEXT NOT NULL CHECK (source IN ('minted','bundle','submitted','fetched')),
471
- obtainedAt TEXT NOT NULL
472
- );
473
- CREATE INDEX IF NOT EXISTS idx_token_admissions_signerKey ON token_admissions(signerKey);
474
- `)
475
-
476
- // Edge index for the recursive COVER walk, so coverage is a local SQL query
477
- // rather than a re-parse of a whole BEEF on every pass. Token inputs only
478
- // (FIX K): a plain BSV change input funding the fee is not a token ancestor.
479
- await db.execAsync(`
480
- CREATE TABLE IF NOT EXISTS token_admission_edges (
481
- childTxid TEXT NOT NULL,
482
- parentTxid TEXT NOT NULL,
483
- parentVout INTEGER NOT NULL,
484
- PRIMARY KEY (childTxid, parentTxid, parentVout)
485
- );
486
- CREATE INDEX IF NOT EXISTS idx_token_admission_edges_child ON token_admission_edges(childTxid);
487
- CREATE INDEX IF NOT EXISTS idx_token_admission_edges_parent ON token_admission_edges(parentTxid);
488
- `)
489
-
490
- // Off-chain linkage payloads for UNADMITTED chain transactions: the exact
491
- // bytes a downstream submitter needs to build the /submit body for a txid
492
- // nobody has σ_I for yet. Carried verbatim hop by hop — this device can never
493
- // decrypt one, only forward it.
494
- await db.execAsync(`
495
- CREATE TABLE IF NOT EXISTS token_linkage_payloads (
496
- txid TEXT PRIMARY KEY,
497
- payloadBytes BLOB NOT NULL,
498
- overlayUrl TEXT NOT NULL,
499
- overlayIdentityKey TEXT NOT NULL,
500
- source TEXT NOT NULL CHECK (source IN ('minted','forwarded')),
501
- createdAt TEXT NOT NULL
502
- );
503
- `)
401
+ // 1Color: the one-time, marker-guarded drop of the four Mandala settlement
402
+ // tables and the old lib's KV journals, then the `color_transfers` journal.
403
+ // Runs on every boot before the runtime or `@bsv/mandala` exist, so no new
404
+ // lib journal can be written before the wipe and none is wiped after it.
405
+ // The table is created again unconditionally, so a re-run is harmless.
406
+ await migrateMandalaToColor(db)
407
+ await db.execAsync(COLOR_TRANSFERS_DDL)
504
408
  }
505
409
 
506
410
  /**
@@ -604,82 +508,3 @@ export async function ensureTransactionsColumns(db: {
604
508
  if (!have.has(col.name)) await db.execAsync(col.ddl)
605
509
  }
606
510
  }
607
-
608
- /**
609
- * The same doctrine for `token_settlements`, which shipped before it had a
610
- * `reference` column and cannot be re-created over live rows.
611
- *
612
- * A nullable column with no default: every existing row reads back
613
- * `reference === undefined`, which the abort guard treats as "unknown
614
- * reference" and therefore never blocks on. The wallet re-derives these rows
615
- * every drain tick (FIX G) but only from frame bytes, which do not carry a
616
- * wallet action reference — so the backfill is simply the next hand-over.
617
- */
618
- const TOKEN_SETTLEMENT_COLUMNS: { name: string; ddl: string }[] = [
619
- { name: 'reference', ddl: 'ALTER TABLE token_settlements ADD COLUMN reference TEXT' },
620
- // XR-038: the wallet-relevant output index, so a cached admission for some
621
- // OTHER output of the same txid can never stand in for this one. Nullable,
622
- // no default — an existing row reads back `relevantVout === undefined`,
623
- // which `postTokenStep` reads as 0 (the payee's-output convention), exactly
624
- // as it always has for every row written before this column existed.
625
- { name: 'relevantVout', ddl: 'ALTER TABLE token_settlements ADD COLUMN relevantVout INTEGER' }
626
- ]
627
-
628
- export async function ensureTokenSettlementColumns(db: {
629
- getAllAsync(sql: string, params: BindValue[]): Promise<unknown[]>
630
- execAsync(sql: string): Promise<unknown>
631
- }): Promise<void> {
632
- const info = (await db.getAllAsync('PRAGMA table_info(token_settlements)', [])) as { name: string }[]
633
- const have = new Set(info.map(c => c.name))
634
- for (const col of TOKEN_SETTLEMENT_COLUMNS) {
635
- if (have.has(col.name)) continue
636
- await db.execAsync(col.ddl)
637
- // XR-033: this ALTER just gave every existing row a NULL `reference`, and
638
- // the abort guard's primary check (`getSettlementByReference`) can never
639
- // match a NULL one against any reference — so backfill it now, in the
640
- // same migration step, rather than leaving it to "the next hand-over"
641
- // (which never comes for a row already stuck in a blocked state).
642
- if (col.name === 'reference') await backfillLegacyTokenSettlementReferences(db)
643
- }
644
- }
645
-
646
- /**
647
- * XR-033: resolves each pre-migration row's `reference` from `transactions`,
648
- * the SAME table `abortAction({reference})` itself matches a reference
649
- * against (`findTransactions({partial:{reference}})`) — so this backfills
650
- * from the one mapping that is already authoritative, rather than guessing.
651
- *
652
- * Scoped to rows that both need it and can be resolved: still blocked (the
653
- * same states `abortGuard.ts`'s `ABORT_BLOCKED_SETTLEMENT_STATES` lists —
654
- * duplicated here, not imported, for the reason `settlementStore.ts` gives:
655
- * this schema file is statements, not cross-module logic) and whose
656
- * transaction row still exists to resolve from. A row that cannot be
657
- * resolved (its transaction is gone) is left NULL; the abort guard's own
658
- * second, coarser check (`hasUnresolvedLegacyBlockedRows`) covers that case
659
- * without this migration needing to.
660
- *
661
- * Never throws: this runs inside the ADD COLUMN step of the wallet's whole
662
- * migration ladder, and `transactions` — always present in the real app,
663
- * created earlier in this same `createTables` — is not guaranteed by this
664
- * function's own narrow signature. A device where the backfill itself cannot
665
- * run is exactly what `hasUnresolvedLegacyBlockedRows` exists to catch at
666
- * `abortAction` time instead, so a failure here costs that coarser refusal,
667
- * never a broken migration.
668
- */
669
- async function backfillLegacyTokenSettlementReferences(db: {
670
- execAsync(sql: string): Promise<unknown>
671
- }): Promise<void> {
672
- try {
673
- await db.execAsync(`
674
- UPDATE token_settlements
675
- SET reference = (
676
- SELECT reference FROM transactions WHERE transactions.txid = token_settlements.txid
677
- )
678
- WHERE reference IS NULL
679
- AND state IN ('held','handed_over','submitting','admitted','broadcast')
680
- AND EXISTS (SELECT 1 FROM transactions WHERE transactions.txid = token_settlements.txid)
681
- `)
682
- } catch (e) {
683
- devLog('[createTables] could not backfill legacy token_settlements references:', e)
684
- }
685
- }
@@ -2,6 +2,7 @@ import type { AppChain } from './config'
2
2
  import type { PushAdapter } from './push/types'
3
3
  import { trimTrailingSlashes } from './net/trimTrailingSlashes'
4
4
  import { isRelayUrl, isStunUrl } from './directpay/settings'
5
+ import type { PermissionPolicyOverride } from './bridge/permissionPolicy'
5
6
 
6
7
  /**
7
8
  * Service endpoints and API keys for one chain.
@@ -165,8 +166,17 @@ export interface ToolboxConfig {
165
166
  * change.
166
167
  */
167
168
  directPay?: DirectPayHostConfig
169
+ /**
170
+ * The browser bridge (BRC-185). Optional; a host that omits it gets the built-in policy.
171
+ * `allowLocalhostHttp` lets a development build accept `http://localhost` origins.
172
+ * `permissionPolicy` states this build's default prompt settings for verified and
173
+ * unverified origins; the user's own stored policy wins over it.
174
+ */
175
+ browserBridge?: { allowLocalhostHttp?: boolean; permissionPolicy?: PermissionPolicyOverride }
168
176
  }
169
177
 
178
+ export type BrowserBridgeHostConfig = NonNullable<ToolboxConfig['browserBridge']>
179
+
170
180
  interface ResolvedConfig {
171
181
  backupUrl: string
172
182
  services: Partial<Record<AppChain, ToolboxServiceConfig>>
@@ -176,6 +186,7 @@ interface ResolvedConfig {
176
186
  vaultEnabled: boolean
177
187
  push: PushAdapter | undefined
178
188
  directPay: DirectPayHostConfig | undefined
189
+ browserBridge: BrowserBridgeHostConfig | undefined
179
190
  }
180
191
 
181
192
  let current: ResolvedConfig | null = null
@@ -271,7 +282,8 @@ export function configureToolbox(config: ToolboxConfig): void {
271
282
  handleMinLength: config.handleMinLength === 1 || config.handleMinLength === 2 ? config.handleMinLength : 3,
272
283
  vaultEnabled: config.vaultEnabled === true,
273
284
  push: config.push,
274
- directPay: config.directPay
285
+ directPay: config.directPay,
286
+ browserBridge: config.browserBridge
275
287
  }
276
288
  }
277
289
 
@@ -444,6 +456,11 @@ export function getDirectPayConfig(): DirectPayHostConfig | undefined {
444
456
  return current?.directPay
445
457
  }
446
458
 
459
+ /** What the host stated about the browser bridge; `{}` when it stated nothing. Never throws. */
460
+ export function getBrowserBridgeConfig(): BrowserBridgeHostConfig {
461
+ return current?.browserBridge ?? {}
462
+ }
463
+
447
464
  /**
448
465
  * Whether the vault may be used on this network.
449
466
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bsv/expo-wallet-toolbox",
3
- "version": "0.21.0",
3
+ "version": "0.23.0",
4
4
  "private": false,
5
5
  "description": "Wallet screens and P2P local-payment backend for Expo/React Native apps, extracted from BSV Wallet.",
6
6
  "license": "SEE LICENSE IN LICENSE.txt",
@@ -31,14 +31,15 @@
31
31
  "peerDependencies": {
32
32
  "@bsv/air-gap": "^0.1.3",
33
33
  "@bsv/backup-cache-client": "^0.1.0",
34
- "@bsv/btms-permission-module": "^1.2.1",
35
- "@bsv/mandala": "^0.4.1",
36
- "@bsv/message-box-client": "^2.5.3",
34
+ "@bsv/btms-permission-module": "^1.2.4",
35
+ "@bsv/color-permission-module": "^0.2.0",
36
+ "@bsv/mandala": "^0.5.0",
37
+ "@bsv/message-box-client": "^2.7.0",
37
38
  "@bsv/react-native-localpay-transport": "*",
38
- "@bsv/sdk": "^2.8.11",
39
- "@bsv/templates": "^2.0.0",
40
- "@bsv/webrtpay": "^0.2.1",
41
- "@bsv/wallet-toolbox-mobile": "^2.14.9",
39
+ "@bsv/sdk": "^4.0.1",
40
+ "@bsv/templates": "^2.2.0",
41
+ "@bsv/wallet-toolbox-mobile": "^2.15.1",
42
+ "@bsv/webrtpay": "^0.2.3",
42
43
  "@expo/vector-icons": "^15.0.3",
43
44
  "@noble/curves": "^2.3.0",
44
45
  "@react-native-async-storage/async-storage": "^2.2.0",
@@ -0,0 +1,86 @@
1
+ import React, { useContext, useLayoutEffect, useSyncExternalStore } from 'react'
2
+ import { RELAYED_CONTEXTS } from './relayedContexts'
3
+
4
+ /**
5
+ * Feeds a second React root the contexts of the first (spec 7.4, 10). `ContextRelayPublisher` is rendered inside
6
+ * the first root's providers and writes each relayed context's current value into a module-level store;
7
+ * `ContextRelaySubscriber` is the second root's top and re-provides those values to its children. Both roots live
8
+ * in one JS runtime, so the store is shared by module identity and a value change (a theme switch, a wallet state
9
+ * update) reaches the subscriber without remounting it.
10
+ *
11
+ * The subscriber renders nothing until every entry has been published once: a child must never read a context
12
+ * default (the default of `WalletContext` is a wallet that is not there).
13
+ */
14
+
15
+ type Snapshot = { readonly values: ReadonlyArray<unknown>; readonly published: ReadonlyArray<boolean> }
16
+
17
+ const EMPTY: Snapshot = {
18
+ values: RELAYED_CONTEXTS.map(() => undefined),
19
+ published: RELAYED_CONTEXTS.map(() => false)
20
+ }
21
+
22
+ let snapshot: Snapshot = EMPTY
23
+ const listeners = new Set<() => void>()
24
+
25
+ function emit(): void {
26
+ for (const fn of [...listeners]) fn()
27
+ }
28
+
29
+ function subscribe(fn: () => void): () => void {
30
+ listeners.add(fn)
31
+ return () => {
32
+ listeners.delete(fn)
33
+ }
34
+ }
35
+
36
+ function getSnapshot(): Snapshot {
37
+ return snapshot
38
+ }
39
+
40
+ function publish(values: ReadonlyArray<unknown>): void {
41
+ const changed = values.some((v, i) => !snapshot.published[i] || !Object.is(v, snapshot.values[i]))
42
+ if (!changed) return
43
+ snapshot = { values: [...values], published: values.map(() => true) }
44
+ emit()
45
+ }
46
+
47
+ /** Publishes one entry only; tests use it to prove the subscriber waits for every entry. Not exported from the barrel. */
48
+ export function publishRelayedContextForTest(name: string, value: unknown): void {
49
+ const i = RELAYED_CONTEXTS.findIndex(e => e.name === name)
50
+ if (i < 0) throw new Error(`not a relayed context: ${name}`)
51
+ const values = [...snapshot.values]
52
+ const published = [...snapshot.published]
53
+ values[i] = value
54
+ published[i] = true
55
+ snapshot = { values, published }
56
+ emit()
57
+ }
58
+
59
+ /** Clears the store: tests, and sign-out (a later sheet must not render a signed-out wallet's values). */
60
+ export function resetContextRelay(): void {
61
+ snapshot = EMPTY
62
+ emit()
63
+ }
64
+
65
+ /** Rendered once inside the first root's providers. Renders nothing. */
66
+ export const ContextRelayPublisher: React.FC = () => {
67
+ // The list is a module constant, so the number of hooks never changes between renders.
68
+ const values = RELAYED_CONTEXTS.map(entry => useContext(entry.context)) // eslint-disable-line react-hooks/rules-of-hooks
69
+ // Layout effect: the second root learns the value before the next paint, so a theme switch never shows one frame
70
+ // of mixed colours across the two roots.
71
+ useLayoutEffect(() => {
72
+ publish(values)
73
+ })
74
+ return null
75
+ }
76
+
77
+ /** The second root's top: re-provides each relayed context with the live value. */
78
+ export const ContextRelaySubscriber: React.FC<{ children: React.ReactNode }> = ({ children }) => {
79
+ const snap = useSyncExternalStore(subscribe, getSnapshot, getSnapshot)
80
+ if (!snap.published.every(Boolean)) return null
81
+ // The nesting is stable (same order, same types), so a value change updates providers in place and never remounts.
82
+ return RELAYED_CONTEXTS.reduceRight<React.ReactNode>(
83
+ (inner, entry, i) => <entry.context.Provider value={snap.values[i]}>{inner}</entry.context.Provider>,
84
+ children
85
+ ) as React.ReactElement
86
+ }
@@ -0,0 +1,21 @@
1
+ import type React from 'react'
2
+ import { ThemeContext } from '../../core/theme/ThemeContext'
3
+ import { WalletContext } from '../../core/context/WalletContext'
4
+ import { ExchangeRateContext } from '../../core/context/ExchangeRateContext'
5
+ import { UserContext } from '../../core/context/UserContext'
6
+
7
+ /**
8
+ * The React contexts `PermissionSheet` (and the cards it renders) read. The Android bridge sheet runs on a second
9
+ * React root of the same React host (spec 7.4), and a second root does not see the first root's providers, so each
10
+ * context listed here is copied across by `ContextRelay`. A context the sheet reads that is not listed here would
11
+ * silently fall back to its default value on the second root: `relayedContexts.test.tsx` scans the sheet's import
12
+ * closure and fails until the new context is added.
13
+ *
14
+ * Language is intentionally not listed: i18n is a module singleton and `useTranslation` reads it without a provider.
15
+ */
16
+ export const RELAYED_CONTEXTS: ReadonlyArray<{ name: string; context: React.Context<any> }> = [
17
+ { name: 'ThemeContext', context: ThemeContext },
18
+ { name: 'WalletContext', context: WalletContext },
19
+ { name: 'ExchangeRateContext', context: ExchangeRateContext },
20
+ { name: 'UserContext', context: UserContext }
21
+ ]
@@ -78,7 +78,7 @@ export default function AssetPicker({
78
78
 
79
79
  const current = balances.find(b => b.asset.assetId === selected) ?? null
80
80
  const currentLabel = current ? current.asset.label || current.asset.ticker : BSV_LABEL
81
- const currentFigure = current ? formatTokenAmountWithUnit(current.baseUnits, current.asset) : bsvBalanceText
81
+ const currentFigure = current ? formatTokenAmountWithUnit(current.units, current.asset) : bsvBalanceText
82
82
 
83
83
  const choose = (assetId: string | null) => {
84
84
  onSelect(assetId)
@@ -117,7 +117,7 @@ export default function AssetPicker({
117
117
  label={b.asset.label || b.asset.ticker}
118
118
  issuerName={b.asset.issuerName}
119
119
  fingerprint={shortAssetId(b.asset.assetId)}
120
- figure={showFigures ? formatTokenAmountWithUnit(b.baseUnits, b.asset) : null}
120
+ figure={showFigures ? formatTokenAmountWithUnit(b.units, b.asset) : null}
121
121
  selected={selected === b.asset.assetId}
122
122
  onPress={() => choose(b.asset.assetId)}
123
123
  />
@@ -374,7 +374,7 @@ export interface HandleReceiveProps {
374
374
  */
375
375
  asset?: { assetId: string; ticker: string; issuerName?: string } | null
376
376
  /** The figure the code asks for, in the asset's base units. Absent for an open request. */
377
- requestedBaseUnits?: number
377
+ requestedUnits?: bigint
378
378
  /** The same figure, in the asset's own units, already formatted for the screen. */
379
379
  requestedAmountText?: string
380
380
  /**
@@ -401,7 +401,7 @@ export interface HandleReceiveProps {
401
401
  export default function HandleReceive({
402
402
  initialSats,
403
403
  asset = null,
404
- requestedBaseUnits,
404
+ requestedUnits,
405
405
  requestedAmountText,
406
406
  admissionRefusal,
407
407
  assetMessageBoxUrl = null,
@@ -530,7 +530,7 @@ export default function HandleReceive({
530
530
  identityKey,
531
531
  asset ? undefined : initialSats,
532
532
  isConfigured ? messageBoxUrl : undefined,
533
- asset ? { assetId: asset.assetId, baseUnits: requestedBaseUnits } : undefined
533
+ asset ? { assetId: asset.assetId, units: requestedUnits } : undefined
534
534
  )
535
535
  : ''
536
536
 
@@ -695,7 +695,7 @@ export default function HandleReceive({
695
695
  const firstHold = !seen.includes(arrival.asset.assetId)
696
696
  if (firstHold) await markSeen(SEEN_ASSETS_KEY, arrival.asset.assetId)
697
697
  setTokenReceived({
698
- amountText: formatTokenAmountWithUnit(arrival.baseUnits, arrival.asset, { showPlus: true }) ?? '',
698
+ amountText: formatTokenAmountWithUnit(arrival.units, arrival.asset, { showPlus: true }) ?? '',
699
699
  // Credited and spendable, and not yet confirmed — both true, and the
700
700
  // receipt says both rather than claiming a settlement nobody has.
701
701
  statusNote: arrival.status === 'settled' ? undefined : t('local_pay_token_not_cleared', { issuer }),