@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
@@ -32,8 +32,7 @@ import {
32
32
  type PostOutcome
33
33
  } from '../../offline/plan'
34
34
  import { descendantsOf, type OrderableTx } from '../../offline/order'
35
- import { postTokenStep, reconcileSettlements, type TokenFrameSource } from '../../mandala/drain'
36
- import type { AdmissionVerifier, CoverFn, SettlementStore, SubmitFn, TokenSettlementRow } from '../../mandala/types'
35
+ import { txHasColorOutput } from '../../mandala/colorGuard'
37
36
  import { devLog } from '../../logging'
38
37
  import { getOnline } from '../../net/online'
39
38
 
@@ -80,78 +79,15 @@ interface HeldAction {
80
79
  api: TableProvenTxReq
81
80
  }
82
81
 
83
- /**
84
- * Everything the Mandala settlement drain needs that this module cannot do
85
- * itself. Absent for a wallet with no token payments — then not one line of
86
- * behaviour below changes.
87
- *
88
- * `cover` and `submit` are injected rather than imported because one is a pure
89
- * verifier over local evidence and the other is a network call; keeping both
90
- * out of here is what leaves this file a database-and-ordering module.
91
- */
92
- export interface OfflineTokenDeps {
93
- store: SettlementStore
94
- cover: CoverFn
95
- submit: SubmitFn
96
- /**
97
- * FIX H / wire contract §9.10. THIS WALLET's configured overlay identity key
98
- * and the σ_I verifier that checks against it — the only thing that may let a
99
- * cached admission skip a `/submit`, and the filter on what the evidence
100
- * cache is allowed to keep at all. Absent and nothing is trusted: every
101
- * ancestor is submitted, which is free and always correct.
102
- */
103
- overlayIdentityKey?: string
104
- verifyAdmission?: AdmissionVerifier
105
- /**
106
- * Clear `@bsv/mandala`'s tx-journal entry for a tip this pass really
107
- * broadcast. See `TokenStepDeps.journalRemove`; passed straight through so
108
- * the drain's own broadcast is the only thing that can clear one.
109
- */
110
- journalRemove?: (txid: string) => Promise<void>
111
- /**
112
- * FIX G: every durable token frame this device holds, re-read each pass so
113
- * the evidence tables and the settlement rows are re-derived idempotently
114
- * before anything is decided. Supplied by the caller because only it can
115
- * open a payer-side sealed `framePayload`.
116
- */
117
- frames?: () => Promise<TokenFrameSource[]>
118
- }
119
-
120
82
  export async function processOfflineActions(args: {
121
83
  storage: StorageExpoSQLite
122
84
  /** Injected so tests can supply a missing ancestor without hitting the network. */
123
85
  refetchBeef?: (txid: string) => Promise<number[] | undefined>
124
- /** Mandala settlement. Omit entirely and the drain behaves exactly as before. */
125
- token?: OfflineTokenDeps
126
86
  }): Promise<ProcessOfflineActionsResult> {
127
- const { storage, refetchBeef, token } = args
87
+ const { storage, refetchBeef } = args
128
88
  const db = storage.sqliteDb
129
89
  if (!db) return { sent: 0, rejected: 0, stopped: true, stalledOn: 'the database is not open' }
130
90
 
131
- // Before anything is read or decided: re-derive the settlement evidence from
132
- // the frame bytes that are already durable (FIX G). Purely local, so it runs
133
- // even on a pass that turns out to be offline, and it is allowed to fail —
134
- // it is a cache-population step, and the next tick repeats it.
135
- if (token?.frames) {
136
- try {
137
- const r = await reconcileSettlements({
138
- store: token.store,
139
- sources: await token.frames(),
140
- overlayIdentityKey: token.overlayIdentityKey,
141
- verifyAdmission: token.verifyAdmission
142
- })
143
- if (r.errors.length > 0) devLog('[processOfflineActions] evidence reconciliation reported:', r.errors)
144
- if (r.dropped > 0) {
145
- // FIX H: counterparty-supplied σ_I that did not verify against this
146
- // wallet's configured overlay key. Not an error and not a decline —
147
- // the ancestors are simply submitted rather than skipped.
148
- devLog(`[processOfflineActions] dropped ${r.dropped} unverifiable admission(s) from frame evidence`)
149
- }
150
- } catch (e) {
151
- devLog('[processOfflineActions] could not reconcile token settlements:', e)
152
- }
153
- }
154
-
155
91
  // XQ-009 remainder: a row this device once honestly marked 'sent' (real
156
92
  // proof, or a real broadcast) can still have its backing request later
157
93
  // reclaimed by the toolbox's own proof-timeout machinery
@@ -191,7 +127,6 @@ export async function processOfflineActions(args: {
191
127
  if (api && outcomeFromReqStatus(api.status) === 'success') {
192
128
  devLog(`[processOfflineActions] storage already records '${api.status}' for ${row.txid}; closing its queue row`)
193
129
  await updateOfflineAction(db, row.txid, { status: 'sent' })
194
- if (token) await closeSettlementAsBroadcast(token.store, row.txid)
195
130
  sent++
196
131
  } else {
197
132
  rows.push(row)
@@ -294,36 +229,21 @@ export async function processOfflineActions(args: {
294
229
  }
295
230
  if (action) await updateOfflineAction(db, step.txid, { status: 'posting' })
296
231
 
297
- // The ONE token branch. A transaction with a `token_settlements` row may
298
- // not be broadcast until the issuer's overlay has admitted it and every
299
- // unadmitted token ancestor it spends — so the ordinary post becomes
300
- // `postTokenStep`'s injected `broadcast`, reached only after `/submit`
301
- // says yes. Everything after this line — applyOutcome, the cascade, the
302
- // requeue — is unchanged, because `postTokenStep` returns the same
303
- // `PostOutcome` shape a BSV post does.
304
- const read = token ? await readSettlement(token.store, step.txid) : { ok: true as const, row: undefined }
305
- const broadcast = async () =>
306
- action ? await postOwned(storage, action.api) : await postForeign(storage, merged, step.txid)
307
- const outcome = !read.ok
308
- ? // The read failed, so this step does not know whether it is a token
309
- // transaction. Stall it: `serviceError` leaves every row where it was
310
- // and retries the whole prefix next pass.
311
- ('serviceError' as PostOutcome)
312
- : read.row
313
- ? await postTokenStep(
314
- {
315
- store: token!.store,
316
- cover: token!.cover,
317
- submit: token!.submit,
318
- overlayIdentityKey: token!.overlayIdentityKey,
319
- verifyAdmission: token!.verifyAdmission,
320
- journalRemove: token!.journalRemove,
321
- broadcast
322
- },
323
- read.row,
324
- step
325
- )
326
- : await broadcast()
232
+ // The ONE color branch (plan 07 W1, IC §8.2). A transaction with a 1Color
233
+ // output is broadcast only once its `color_transfers` row reads `settled`:
234
+ // the color module's `settle` got a verified admission from the Mandala
235
+ // overlay, which itself broadcasts what it admits. Until then the step is a
236
+ // `serviceError` — its row stays queued and its subtree waits — exactly
237
+ // like a step that found no network. A read fault does the same: "I could
238
+ // not tell" never resolves to "go ahead". Everything after this line —
239
+ // applyOutcome, the cascade, the requeue — is unchanged.
240
+ const hold = await colorHold(storage, merged, txs, step.txid, action?.api.rawTx)
241
+ const outcome: PostOutcome =
242
+ hold !== 'release'
243
+ ? 'serviceError'
244
+ : action
245
+ ? await postOwned(storage, action.api)
246
+ : await postForeign(storage, merged, step.txid)
327
247
  // A cascade needs to see what spends the refused transaction, and beefs only
328
248
  // reach backwards, so the graph the queue built cannot contain a spender that
329
249
  // is not itself queued. Widened only when a cascade is actually about to run,
@@ -372,31 +292,66 @@ export async function processOfflineActions(args: {
372
292
  }
373
293
 
374
294
  /**
375
- * Whether this txid has a settlement row — or whether the question could not be
376
- * answered at all.
295
+ * Whether one step of the release plan may be posted now.
296
+ *
297
+ * · `release` — the tx carries no 1Color output (answered from its bytes, so a
298
+ * plain BSV step never touches the journal), this wallet's token custody is
299
+ * not in it (a decoy 1Color output on someone else's tx), or its
300
+ * `color_transfers` row reads `settled`.
301
+ * · `hold` — an unsettled 1Color tx of this wallet's custody (the hold's
302
+ * predicate, `colorHeldTxids`): a missing row holds a receipt the host
303
+ * ledger recorded and nothing has admitted yet.
304
+ * · `fault` — a custody read failed. The caller treats it exactly like
305
+ * `hold`; it is distinct only for the log.
377
306
  *
378
- * The three outcomes are deliberately distinct, and the third is the fix. A
379
- * thrown read (a locked database, a schema without these tables, a corrupt
380
- * page) USED to fall back to `undefined`, which the caller cannot tell from
381
- * "this is an ordinary BSV transaction" — so a read fault sent an unadmitted
382
- * token tip straight to `broadcast()`, defeating the whole §4.3 gate on exactly
383
- * the kind of transient fault the drain is built to survive. "I could not tell"
384
- * must never resolve to "go ahead": the caller turns it into `serviceError`,
385
- * the rows stay where they are, and the next pass asks again.
307
+ * A FOREIGN step (an ancestor that arrived inside a counterparty's BEEF, no
308
+ * request of ours) carries no custody of its own: the journal and the host
309
+ * ledger record this wallet's own sends and receipts, keyed by their tips. So
310
+ * a foreign 1Color step is held exactly while it is an unadmitted link in a
311
+ * chain this wallet holds: when some descendant of it in this graph is held
312
+ * by the predicate. Posting it then would put an unadmitted token tx under
313
+ * our pending receipt on chain. Once no descendant is held (each is settled,
314
+ * or not ours at all), it is released: a settled descendant was admitted and
315
+ * broadcast by the overlay, which it cannot do without its ancestors already
316
+ * on the network, and a decoy-only chain is not ours to hold. A foreign step
317
+ * that is itself custodial keeps the earlier rule: released when some 1Color
318
+ * descendant is not held.
386
319
  *
387
- * The token guard in `StorageExpoSQLite.attemptToPostReqsToNetwork` reads the
388
- * same table and would usually catch the same case — but it is reached only
389
- * from `shareReqsWithWorld`, and `postForeign` does not go through it at all.
390
- * Two independent barriers are worth having; one of them failing open is not.
320
+ * Bytes: an owned step uses its request's raw tx, a foreign one the merged
321
+ * graph's. A step with no bytes is held (`colorHeldTxids`).
391
322
  */
392
- type SettlementRead = { ok: true; row: TokenSettlementRow | undefined } | { ok: false }
323
+ type ColorHold = 'release' | 'hold' | 'fault'
393
324
 
394
- async function readSettlement(store: SettlementStore, txid: string): Promise<SettlementRead> {
325
+ async function colorHold(
326
+ storage: StorageExpoSQLite,
327
+ merged: Beef,
328
+ txs: OrderableTx[],
329
+ txid: string,
330
+ ownedRawTx: number[] | undefined
331
+ ): Promise<ColorHold> {
332
+ const owned = ownedRawTx !== undefined
333
+ const rawTx = ownedRawTx ?? merged.findTxid(txid)?.tx?.toBinary()
334
+ if (rawTx && rawTx.length > 0 && !txHasColorOutput(rawTx)) return 'release'
395
335
  try {
396
- return { ok: true, row: await store.getSettlement(txid) }
336
+ const held = await storage.colorHeldTxids([{ txid, rawTx }])
337
+ if (owned) return held.has(txid) ? 'hold' : 'release'
338
+
339
+ const colorDescendants: { txid: string; rawTx: number[] }[] = []
340
+ for (const d of descendantsOf(txid, txs)) {
341
+ const bytes = merged.findTxid(d)?.tx?.toBinary()
342
+ if (bytes && txHasColorOutput(bytes)) colorDescendants.push({ txid: d, rawTx: bytes })
343
+ }
344
+ const heldDescendants =
345
+ colorDescendants.length === 0 ? new Set<string>() : await storage.colorHeldTxids(colorDescendants)
346
+ if (!held.has(txid)) {
347
+ // Not ours by itself: held only under a chain of ours that is still held.
348
+ return colorDescendants.some(d => heldDescendants.has(d.txid)) ? 'hold' : 'release'
349
+ }
350
+ if (colorDescendants.length === 0) return 'hold'
351
+ return colorDescendants.some(d => !heldDescendants.has(d.txid)) ? 'release' : 'hold'
397
352
  } catch (e) {
398
- devLog(`[processOfflineActions] could not read the settlement row for ${txid}:`, e)
399
- return { ok: false }
353
+ devLog(`[processOfflineActions] could not read color_transfers for ${txid}; holding it:`, e)
354
+ return 'fault'
400
355
  }
401
356
  }
402
357
 
@@ -643,13 +598,17 @@ async function postOwned(storage: StorageExpoSQLite, api: TableProvenTxReq): Pro
643
598
  /**
644
599
  * `postOwned` for ONE txid, for a caller outside the queue loop.
645
600
  *
646
- * The Mandala runtime's `settleNow` needs a broadcast to hand `postTokenStep`
647
- * the moment a hand-over lands, and it must be the SAME broadcast the drain
648
- * uses — status transitions, history notes, `markStaleInputsAsSpent`, the
649
- * re-hold on a service error, and the "storage is the witness, not the reported
650
- * status" rule all live in `postOwned` and must not be reimplemented beside it.
651
- * So this is the whole of the new surface: find the request, post it, report
652
- * the same `PostOutcome`.
601
+ * The Mandala runtime may need to post one settled tx the moment it settles,
602
+ * and it must be the SAME broadcast the drain uses — status transitions,
603
+ * history notes, `markStaleInputsAsSpent`, the re-hold on a service error, and
604
+ * the "storage is the witness, not the reported status" rule all live in
605
+ * `postOwned` and must not be reimplemented beside it. So this is the whole of
606
+ * the new surface: find the request, post it, report the same `PostOutcome`.
607
+ *
608
+ * It carries the color hold itself. `postOwned` calls the toolbox's
609
+ * module-level post, past the `StorageExpoSQLite` override, so without the
610
+ * same check here this would be a way around the guard: an unsettled 1Color tx
611
+ * (or an unanswerable journal read) comes back `'serviceError'`, unposted.
653
612
  *
654
613
  * A txid with no request of this wallet's own comes back `'serviceError'`
655
614
  * rather than being posted some other way. That is deliberate: a FOREIGN
@@ -665,6 +624,10 @@ export async function postOwnedByTxid(storage: StorageExpoSQLite, txid: string):
665
624
  devLog(`[processOfflineActions] no request of our own for ${txid}; leaving its broadcast to the drain`)
666
625
  return 'serviceError'
667
626
  }
627
+ if ((await colorHold(storage, new Beef(), [], txid, api.rawTx)) !== 'release') {
628
+ devLog(`[processOfflineActions] ${txid} is an unsettled 1Color tx (or unreadable); not posting it`)
629
+ return 'serviceError'
630
+ }
668
631
  return await postOwned(storage, api)
669
632
  }
670
633
 
@@ -737,19 +700,6 @@ async function recordDeliveredElsewhere(storage: StorageExpoSQLite, api: TablePr
737
700
  }
738
701
  }
739
702
 
740
- /**
741
- * The settlement twin of closing a queue row on a recorded delivery: the same
742
- * advance `broadcastAdmittedTip` makes after a real post. Best-effort — the
743
- * queue row is the durable fact, and `reconcileSettlements` re-derives rows.
744
- */
745
- async function closeSettlementAsBroadcast(store: SettlementStore, txid: string): Promise<void> {
746
- try {
747
- await store.advanceSettlement(txid, ['admitted', 'submitting', 'held', 'handed_over'], 'broadcast')
748
- } catch (e) {
749
- devLog(`[processOfflineActions] could not close the settlement row of ${txid} as broadcast:`, e)
750
- }
751
- }
752
-
753
703
  /**
754
704
  * Post a foreign ancestor that arrived inside someone's BEEF.
755
705
  *
@@ -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
- }
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.22.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",
@@ -32,13 +32,14 @@
32
32
  "@bsv/air-gap": "^0.1.3",
33
33
  "@bsv/backup-cache-client": "^0.1.0",
34
34
  "@bsv/btms-permission-module": "^1.2.1",
35
- "@bsv/mandala": "^0.4.1",
35
+ "@bsv/color-permission-module": "^0.2.0",
36
+ "@bsv/mandala": "^0.5.0",
36
37
  "@bsv/message-box-client": "^2.5.3",
37
38
  "@bsv/react-native-localpay-transport": "*",
38
- "@bsv/sdk": "^2.8.11",
39
- "@bsv/templates": "^2.0.0",
39
+ "@bsv/sdk": "^4.0.0",
40
+ "@bsv/templates": "^2.2.0",
41
+ "@bsv/wallet-toolbox-mobile": "^2.15.0",
40
42
  "@bsv/webrtpay": "^0.2.1",
41
- "@bsv/wallet-toolbox-mobile": "^2.14.9",
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",
@@ -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 }),