@bsv/expo-wallet-toolbox 0.4.0 → 0.7.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 (182) hide show
  1. package/CHANGELOG.md +547 -0
  2. package/README.md +19 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/amountFormatHelpers.ts +238 -34
  6. package/core/backup/RemoteSyncReader.ts +2 -5
  7. package/core/backup/codec.ts +2 -2
  8. package/core/backup/push.ts +1 -1
  9. package/core/config.tsx +16 -1
  10. package/core/contacts/contactActivity.ts +153 -0
  11. package/core/contacts/contactCache.ts +41 -0
  12. package/core/contacts/contactsStore.ts +183 -0
  13. package/core/context/VaultContext.tsx +8 -11
  14. package/core/context/WalletConnectionContext.tsx +137 -52
  15. package/core/context/WalletContext.tsx +464 -30
  16. package/core/demo/demoAssets.ts +60 -0
  17. package/core/demo/demoLedger.ts +240 -0
  18. package/core/demo/demoMandalaRuntime.ts +96 -0
  19. package/core/demo/demoMode.ts +38 -0
  20. package/core/demo/demoWallet.ts +25 -0
  21. package/core/demo/index.ts +26 -0
  22. package/core/demo/useDemo.ts +59 -0
  23. package/core/headers/OfflineFirstChaintracks.ts +52 -14
  24. package/core/headers/headerStore.ts +7 -10
  25. package/core/hooks/useConfirmationSound.ts +14 -8
  26. package/core/i18n/translations.tsx +4562 -986
  27. package/core/identity/contactLink.ts +36 -0
  28. package/core/identity/handleRegistry/client.ts +285 -0
  29. package/core/identity/handleRegistry/profileCert.ts +254 -0
  30. package/core/identity/handleRegistry/registration.ts +559 -0
  31. package/core/identity/handleRegistry/resolver.ts +247 -0
  32. package/core/identity/handleRegistry/rules.ts +104 -0
  33. package/core/index.ts +116 -15
  34. package/core/localpay/build.ts +674 -37
  35. package/core/localpay/codec.ts +68 -5
  36. package/core/localpay/pending.ts +240 -22
  37. package/core/localpay/pendingAborts.ts +5 -1
  38. package/core/localpay/settlementAck.ts +149 -0
  39. package/core/localpay/types.ts +14 -1
  40. package/core/localpay/verify.ts +118 -69
  41. package/core/mandala/abortGuard.ts +134 -0
  42. package/core/mandala/basketMigration.ts +166 -0
  43. package/core/mandala/bundle.ts +244 -0
  44. package/core/mandala/createRuntime.ts +2437 -0
  45. package/core/mandala/drain.ts +670 -0
  46. package/core/mandala/permissionModule.ts +642 -0
  47. package/core/mandala/resendTransfer.ts +175 -0
  48. package/core/mandala/runtime.ts +357 -0
  49. package/core/mandala/settlementStore.ts +412 -0
  50. package/core/mandala/types.ts +290 -0
  51. package/core/monitor/MonitorSupervisor.ts +121 -0
  52. package/core/monitor/TaskBackupPush.ts +1 -1
  53. package/core/monitor/TaskCreditInbox.ts +1 -1
  54. package/core/monitor/TaskDrainOutbox.ts +1 -1
  55. package/core/monitor/TaskSendOffline.ts +1 -1
  56. package/core/net/online.ts +49 -0
  57. package/core/numberFormat.ts +19 -0
  58. package/core/offline/cancelParked.ts +94 -1
  59. package/core/offline/payerHold.ts +152 -12
  60. package/core/offline/plan.ts +1 -1
  61. package/core/offline/tokenFrames.ts +197 -0
  62. package/core/parsePeerPayURI.ts +70 -17
  63. package/core/pay/rails/address.ts +51 -3
  64. package/core/pay/rails/handle.ts +88 -9
  65. package/core/pay/rails/index.ts +16 -6
  66. package/core/pay/rails/nearby.ts +114 -4
  67. package/core/pay/recordProof.ts +2 -6
  68. package/core/services/arcadeBroadcastProvider.ts +1 -4
  69. package/core/services/capWalletArgs.ts +8 -9
  70. package/core/services/exchangeRate.ts +1 -1
  71. package/core/services/externalOrigin.ts +42 -0
  72. package/core/services/vault/VaultKeyService.ts +912 -251
  73. package/core/services/vault/ceremony.ts +435 -367
  74. package/core/services/vault/ceremonyHost.ts +27 -21
  75. package/core/services/vault/devMock.ts +30 -7
  76. package/core/services/vault/driver.ts +95 -41
  77. package/core/services/vault/guard.ts +514 -56
  78. package/core/services/vault/hardwareLease.ts +22 -0
  79. package/core/services/vault/mockYubiKey.ts +258 -90
  80. package/core/services/vault/pivReset.ts +145 -0
  81. package/core/services/vault/r1comb.ts +976 -0
  82. package/core/services/vault/session.ts +93 -26
  83. package/core/services/vault/transfers.ts +2617 -747
  84. package/core/services/vault/types.ts +100 -43
  85. package/core/services/vault/vaultStore.ts +991 -74
  86. package/core/services/walletConnectionValidation.ts +293 -0
  87. package/core/services/walletServiceConfig.ts +31 -20
  88. package/core/storage/StorageExpoSQLite.ts +420 -87
  89. package/core/storage/dbImage.ts +48 -0
  90. package/core/storage/methods/findSql.ts +3 -54
  91. package/core/storage/methods/listActionsSql.ts +8 -5
  92. package/core/storage/methods/listOutputsSql.ts +9 -5
  93. package/core/storage/methods/offlineActions.ts +15 -0
  94. package/core/storage/methods/processOfflineActions.ts +265 -9
  95. package/core/storage/methods/reviewStatusSql.ts +7 -2
  96. package/core/storage/methods/walletBalanceSql.ts +16 -4
  97. package/core/storage/schema/createTables.ts +152 -0
  98. package/core/storage/sqlUpdateValue.ts +24 -0
  99. package/core/toolboxConfig.ts +182 -1
  100. package/core/toolboxTypes.ts +40 -0
  101. package/core/userAvatar.ts +79 -0
  102. package/core/walletMonitor.ts +8 -3
  103. package/core/walletRepair/runWalletCheck.ts +19 -2
  104. package/package.json +31 -30
  105. package/ui/activityFilter.ts +115 -0
  106. package/ui/components/QRScanner.tsx +1 -1
  107. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  108. package/ui/components/pay/AssetPicker.tsx +184 -0
  109. package/ui/components/pay/AvailableBalance.tsx +33 -2
  110. package/ui/components/pay/HandleReceive.tsx +213 -50
  111. package/ui/components/pay/NearbyFlow.tsx +616 -69
  112. package/ui/components/pay/PayForm.tsx +73 -8
  113. package/ui/components/pay/PaymentSuccessOverlay.tsx +89 -8
  114. package/ui/components/pay/RecipientField.tsx +132 -73
  115. package/ui/components/pay/RequestHub.tsx +68 -8
  116. package/ui/components/pay/ResultBanner.tsx +41 -4
  117. package/ui/components/pay/StepBar.tsx +32 -0
  118. package/ui/components/pay/UniversalSend.tsx +1118 -86
  119. package/ui/components/pay/tokenSendCopy.ts +116 -0
  120. package/ui/components/pay/useRecipientInput.ts +36 -7
  121. package/ui/components/ui/PencilEditField.tsx +109 -0
  122. package/ui/components/ui/PermissionSheet.tsx +65 -4
  123. package/ui/components/ui/Sheet.tsx +9 -2
  124. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  125. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  126. package/ui/components/vault/KeyChooser.tsx +96 -0
  127. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  128. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  129. package/ui/components/wallet/ActivityRow.tsx +283 -97
  130. package/ui/components/wallet/AmountInput.tsx +92 -28
  131. package/ui/components/wallet/AssetAmount.tsx +95 -0
  132. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  133. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  134. package/ui/components/wallet/ContactSigil.tsx +49 -0
  135. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  136. package/ui/components/wallet/FitAmount.tsx +148 -0
  137. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  138. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  139. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  140. package/ui/components/wallet/ProfileButton.tsx +62 -0
  141. package/ui/components/wallet/UserAvatar.tsx +85 -0
  142. package/ui/components/wallet/avatarIcons.ts +122 -0
  143. package/ui/components/wallet/tokenEviction.ts +65 -0
  144. package/ui/hooks/useContactsStore.ts +10 -0
  145. package/ui/hooks/useExportWalletData.ts +39 -0
  146. package/ui/hooks/useMandala.ts +320 -0
  147. package/ui/hooks/useOnline.ts +65 -20
  148. package/ui/hooks/useVaultBalance.ts +105 -7
  149. package/ui/hooks/useVaultCoverage.ts +52 -0
  150. package/ui/importDatabases.ts +7 -3
  151. package/ui/index.ts +75 -7
  152. package/ui/screens/ConnectionsScreen.tsx +46 -29
  153. package/ui/screens/ContactScreen.tsx +289 -0
  154. package/ui/screens/ContactsScreen.tsx +373 -0
  155. package/ui/screens/IdentifierScreen.tsx +234 -0
  156. package/ui/screens/NewContactScreen.tsx +362 -0
  157. package/ui/screens/PairScreen.tsx +12 -12
  158. package/ui/screens/PayScreen.tsx +145 -12
  159. package/ui/screens/ProfileScreen.tsx +783 -0
  160. package/ui/screens/SettingsScreen.tsx +18 -9
  161. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  162. package/ui/screens/TrustScreen.tsx +1 -1
  163. package/ui/screens/VaultScreen.tsx +925 -171
  164. package/ui/screens/VaultTransferScreen.tsx +376 -123
  165. package/ui/screens/WalletCheckScreen.tsx +10 -1
  166. package/ui/screens/WalletConfigScreen.tsx +80 -16
  167. package/ui/screens/WalletHomeScreen.tsx +915 -139
  168. package/ui/screens/homeBadges.ts +9 -1
  169. package/ui/screens/tokenRowTitle.ts +68 -0
  170. package/ui/tokenFormat.ts +108 -0
  171. package/ui/tokenSeen.ts +75 -0
  172. package/ui/tokenStatus.ts +100 -0
  173. package/ui/txStatus.ts +43 -5
  174. package/assets/sounds/vault-close.wav +0 -0
  175. package/assets/sounds/vault-open.wav +0 -0
  176. package/core/services/vault/k1.ts +0 -75
  177. package/core/services/vault/sealing.ts +0 -84
  178. package/core/services/vault/vaultDerivation.ts +0 -152
  179. package/core/services/vault/vaultPassphrase.ts +0 -287
  180. package/ui/components/vault/PassphraseField.tsx +0 -306
  181. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  182. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -0,0 +1,116 @@
1
+ /**
2
+ * What a failed token send SAYS — pure, so it can be argued about in a test
3
+ * rather than on a phone.
4
+ *
5
+ * Two rules from the design decide every line here, and they are the reason
6
+ * this is a lookup rather than a string concatenation at the call site:
7
+ *
8
+ * 1. The guarantee is separate from the guess. "Nothing was sent and your
9
+ * balance is unchanged" is attached ONLY to an explicit refusal, where the
10
+ * runtime has already aborted the action and the inputs are provably
11
+ * released. A narrowed reason on top of that ("…because it is paused") is a
12
+ * hint, and a wrong hint on a true guarantee is survivable.
13
+ * 2. A LOCAL failure is not a refusal either, but since the hand-over-first
14
+ * decision it is the only non-refusal a send can have: nothing on this
15
+ * rail contacts the overlay, so there is no lost response to reconcile and
16
+ * no reason to hedge. That branch names the local reason and says plainly
17
+ * that nothing left the wallet — see `tokenUnavailableCopy`.
18
+ *
19
+ * When the issuer cannot be named, `{{issuer}}` becomes "the issuer" rather
20
+ * than a key or a hex string: the overlay-unreachable case in particular must
21
+ * not attribute an outage to a party that may not be the one that was down.
22
+ */
23
+ import type { TokenSendResult } from '../../../core/mandala/runtime'
24
+
25
+ export interface TokenSendCopy {
26
+ /** i18n key. */
27
+ key: string
28
+ /** Interpolation values; always carries `ticker` and `issuer`. */
29
+ values: Record<string, string>
30
+ /** The one inline affordance the note may carry. */
31
+ action?: 'get-bsv' | 'check-again'
32
+ }
33
+
34
+ export interface TokenSendContext {
35
+ ticker: string
36
+ /** Already resolved to a name, or undefined when the issuer cannot be named. */
37
+ issuer?: string
38
+ /** The fallback noun for an unnamed issuer, translated by the caller. */
39
+ issuerFallback: string
40
+ /** The fallback phrase for a failure that came with no message, translated by the caller. */
41
+ reasonFallback?: string
42
+ }
43
+
44
+ const has = (haystack: string, ...needles: string[]) => needles.some(n => haystack.includes(n))
45
+
46
+ /**
47
+ * A refusal code or an error message, narrowed to the sentence the holder gets.
48
+ * Matching is by substring because the code space spans two overlay engines and
49
+ * the lib's own throws; an unmatched code lands on the plain refusal, which is
50
+ * true for every one of them.
51
+ */
52
+ export function tokenRefusalCopy(code: string, ctx: TokenSendContext): TokenSendCopy {
53
+ const values = { ticker: ctx.ticker, issuer: ctx.issuer || ctx.issuerFallback }
54
+ const c = code.toLowerCase()
55
+
56
+ if (has(c, 'pause')) return { key: 'token_err_refused_paused', values }
57
+ if (has(c, 'frozen', 'freeze', 'evicted')) return { key: 'token_err_refused_frozen', values }
58
+ if (has(c, 'recipient', 'allowlist', 'not_allowed', 'blocked', 'registry', 'membership', 'sanction'))
59
+ return { key: 'token_err_refused_recipient', values }
60
+ if (has(c, 'insufficient')) return { key: 'token_err_balance_changed', values }
61
+ if (has(c, 'busy', 'already in flight', 'in flight'))
62
+ return { key: 'token_err_busy', values }
63
+ if (has(c, 'fund', 'insufficient funds', 'not enough satoshis'))
64
+ return { key: 'pay_asset_needs_bsv', values, action: 'get-bsv' }
65
+ return { key: 'token_err_refused', values }
66
+ }
67
+
68
+ /**
69
+ * Everything that is not a refusal.
70
+ *
71
+ * Since the 2026-09-15 hand-over-first decision (§4.5 / wire contract §9.13)
72
+ * this branch no longer covers "the overlay could not be reached": SENDING
73
+ * CONTACTS NO OVERLAY AT ALL, so the only ways a send can fail here are local
74
+ * — the MessageBox would not open, the wallet could not build or sign, coin
75
+ * selection came up short. Every one of those is provable and reversible on
76
+ * this device, which changes the copy twice over:
77
+ *
78
+ * · it may now promise "nothing left your wallet", because nothing did; and
79
+ * · it must NOT name the issuer, who was never involved and may be perfectly
80
+ * healthy — attributing a local fault to them is simply a lie.
81
+ *
82
+ * "Check again" goes with the old sentence for the same reason: there is no
83
+ * lost response to reconcile, so there is nothing to check.
84
+ */
85
+ export function tokenUnavailableCopy(message: string, ctx: TokenSendContext): TokenSendCopy {
86
+ const values = { ticker: ctx.ticker, issuer: ctx.issuer || ctx.issuerFallback }
87
+ const m = message.toLowerCase()
88
+ // A funding throw is a local, provable fact and keeps its own sentence even
89
+ // when it surfaces through the unavailable channel.
90
+ if (has(m, 'fund', 'not enough satoshis')) return { key: 'pay_asset_needs_bsv', values, action: 'get-bsv' }
91
+ if (has(m, 'busy', 'in flight')) return { key: 'token_err_busy', values }
92
+ // `reasonFallback` is the caller's translated noun for "we have no detail";
93
+ // an un-interpolated `{{reason}}` would read as a missing sentence.
94
+ return {
95
+ key: 'token_err_send_failed',
96
+ values: { ...values, reason: message.trim() || ctx.reasonFallback || 'unknown error' }
97
+ }
98
+ }
99
+
100
+ /** The runtime's own result, mapped to copy. `sent` has no copy — it succeeded. */
101
+ export function tokenSendCopy(result: TokenSendResult, ctx: TokenSendContext): TokenSendCopy | null {
102
+ if (result.kind === 'sent') return null
103
+ if (result.kind === 'refused') return tokenRefusalCopy(result.code || result.message || '', ctx)
104
+ return tokenUnavailableCopy(result.message || '', ctx)
105
+ }
106
+
107
+ /** A thrown error from the send path, mapped the same way. */
108
+ export function tokenThrowCopy(error: unknown, ctx: TokenSendContext): TokenSendCopy {
109
+ const message = error instanceof Error ? error.message : String(error ?? '')
110
+ const m = message.toLowerCase()
111
+ // The one string the lib throws that IS a provable refusal: the facilitator
112
+ // came back with zero admitted outputs and the action was aborted.
113
+ if (has(m, 'overlay rejected')) return tokenRefusalCopy(message, ctx)
114
+ if (has(m, 'insufficient token balance')) return tokenRefusalCopy('insufficient', ctx)
115
+ return tokenUnavailableCopy(message, ctx)
116
+ }
@@ -45,14 +45,41 @@ export interface UseRecipientInputOptions {
45
45
  * Compared by content; a new object with the same fields does not re-adopt.
46
46
  */
47
47
  initialTarget?: RecipientTarget
48
- /** A link or code named an amount too. */
49
- onPeerPayAmount?: (sats: number) => void
48
+ /**
49
+ * A link or code named a money, and maybe a figure: `sats` is a BSV
50
+ * request; `asset` is a token request (its genesis outpoint), with `amount`
51
+ * in that token's base units or absent for an open request.
52
+ */
53
+ onPeerPayRequest?: (request: PeerPayRequest) => void
50
54
  /** A peerpay link that did not validate; the message is the validator's. */
51
55
  onPeerPayError?: (message: string) => void
52
56
  /** A nearby-session code was scanned: this form is the wrong surface for it. */
53
57
  onNearbySession?: (session: Session) => void
54
58
  }
55
59
 
60
+ /**
61
+ * What a peerpay link asked for, in exactly one money — and for WHOM: a
62
+ * request that has to wait (holdings not known yet) is applied only if the
63
+ * recipient is still the one the link named.
64
+ */
65
+ export type PeerPayRequest = { identityKey: string; sats?: number; asset?: string; amount?: number }
66
+
67
+ /** The request a classified handle carries, or null when it named no money at all. */
68
+ function requestOf(input: {
69
+ identityKey: string
70
+ sats?: number
71
+ asset?: string
72
+ amount?: number
73
+ }): PeerPayRequest | null {
74
+ if (input.sats === undefined && input.asset === undefined) return null
75
+ return {
76
+ identityKey: input.identityKey,
77
+ ...(input.sats !== undefined ? { sats: input.sats } : {}),
78
+ ...(input.asset !== undefined ? { asset: input.asset } : {}),
79
+ ...(input.amount !== undefined ? { amount: input.amount } : {})
80
+ }
81
+ }
82
+
56
83
  const SEARCH_DEBOUNCE_MS = 400
57
84
 
58
85
  function textFor(target: RecipientTarget): string {
@@ -63,7 +90,7 @@ export function useRecipientInput({
63
90
  wallet,
64
91
  adminOriginator,
65
92
  initialTarget,
66
- onPeerPayAmount,
93
+ onPeerPayRequest,
67
94
  onPeerPayError,
68
95
  onNearbySession
69
96
  }: UseRecipientInputOptions) {
@@ -135,7 +162,8 @@ export function useRecipientInput({
135
162
  identityKey: input.identityKey,
136
163
  ...(input.messageBoxUrl ? { messageBoxUrl: input.messageBoxUrl } : {})
137
164
  })
138
- if (input.sats !== undefined) onPeerPayAmount?.(input.sats)
165
+ const request = requestOf(input)
166
+ if (request) onPeerPayRequest?.(request)
139
167
  return
140
168
  case 'invalid_link':
141
169
  stopSearch()
@@ -164,7 +192,7 @@ export function useRecipientInput({
164
192
  return
165
193
  }
166
194
  },
167
- [onPeerPayAmount, onPeerPayError, stopSearch]
195
+ [onPeerPayRequest, onPeerPayError, stopSearch]
168
196
  )
169
197
 
170
198
  const selectIdentity = useCallback(
@@ -242,12 +270,13 @@ export function useRecipientInput({
242
270
  identityKey: scanned.identityKey,
243
271
  ...(scanned.messageBoxUrl ? { messageBoxUrl: scanned.messageBoxUrl } : {})
244
272
  })
245
- if (scanned.sats !== undefined) onPeerPayAmount?.(scanned.sats)
273
+ const request = requestOf(scanned)
274
+ if (request) onPeerPayRequest?.(request)
246
275
  return
247
276
  }
248
277
  setDirectTarget({ kind: 'address', address: scanned.address })
249
278
  },
250
- [onNearbySession, onPeerPayAmount, onPeerPayError, setDirectTarget]
279
+ [onNearbySession, onPeerPayRequest, onPeerPayError, setDirectTarget]
251
280
  )
252
281
 
253
282
  return {
@@ -0,0 +1,109 @@
1
+ /**
2
+ * An editable label row for a grouped card (contact name, profile display
3
+ * name): the field is always a live text input, a pencil sits at rest in the
4
+ * leading slot, and once the text has actually changed that slot becomes a
5
+ * filled confirm button (2026-09-17 design ruling). Tapping the pencil only
6
+ * focuses the field; nothing is saved until the check is tapped or the
7
+ * keyboard's return key is pressed with a real change.
8
+ */
9
+ import React, { useEffect, useRef, useState } from 'react'
10
+ import { StyleSheet, TextInput, View, type StyleProp, type TextStyle } from 'react-native'
11
+ import { useTheme, spacing, typography } from '@bsv/expo-wallet-toolbox'
12
+ import PressableScale from './PressableScale'
13
+
14
+ type IoniconsComponent = typeof import('@expo/vector-icons').Ionicons
15
+ let ioniconsComponent: IoniconsComponent | undefined
16
+ function loadIonicons(): IoniconsComponent {
17
+ if (!ioniconsComponent) {
18
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
19
+ ioniconsComponent = require('@expo/vector-icons').Ionicons as IoniconsComponent
20
+ }
21
+ return ioniconsComponent
22
+ }
23
+
24
+ export interface PencilEditFieldProps {
25
+ value: string
26
+ onSave: (next: string) => void | Promise<void>
27
+ placeholder?: string
28
+ textStyle?: StyleProp<TextStyle>
29
+ editAccessibilityLabel: string
30
+ saveAccessibilityLabel: string
31
+ autoCapitalize?: 'none' | 'sentences' | 'words' | 'characters'
32
+ maxLength?: number
33
+ }
34
+
35
+ export function PencilEditField({
36
+ value,
37
+ onSave,
38
+ placeholder,
39
+ textStyle,
40
+ editAccessibilityLabel,
41
+ saveAccessibilityLabel,
42
+ autoCapitalize = 'words',
43
+ maxLength
44
+ }: PencilEditFieldProps) {
45
+ const { colors } = useTheme()
46
+ const Ionicons = loadIonicons()
47
+ const inputRef = useRef<TextInput>(null)
48
+ const [text, setText] = useState(value)
49
+ // A save that lands from outside (a cache refresh, the parent reloading)
50
+ // re-seeds the field; an in-progress edit is never clobbered, because the
51
+ // parent's value only changes once our own save has gone through.
52
+ useEffect(() => setText(value), [value])
53
+ const changed = text.trim() !== '' && text.trim() !== value.trim()
54
+
55
+ const save = async () => {
56
+ if (!changed) return
57
+ await onSave(text.trim())
58
+ inputRef.current?.blur()
59
+ }
60
+
61
+ return (
62
+ <View style={styles.row}>
63
+ {changed ? (
64
+ <PressableScale
65
+ onPress={save}
66
+ haptic="confirm"
67
+ style={styles.leading}
68
+ accessibilityRole="button"
69
+ accessibilityLabel={saveAccessibilityLabel}
70
+ >
71
+ <View style={[styles.confirmDisc, { backgroundColor: colors.accent }]}>
72
+ <Ionicons name="checkmark" size={16} color={colors.textOnAccent} />
73
+ </View>
74
+ </PressableScale>
75
+ ) : (
76
+ <PressableScale
77
+ onPress={() => inputRef.current?.focus()}
78
+ style={styles.leading}
79
+ accessibilityRole="button"
80
+ accessibilityLabel={editAccessibilityLabel}
81
+ >
82
+ <Ionicons name="pencil-outline" size={17} color={colors.textSecondary} />
83
+ </PressableScale>
84
+ )}
85
+ <TextInput
86
+ ref={inputRef}
87
+ value={text}
88
+ onChangeText={setText}
89
+ placeholder={placeholder}
90
+ placeholderTextColor={colors.textTertiary}
91
+ autoCapitalize={autoCapitalize}
92
+ autoCorrect={false}
93
+ maxLength={maxLength}
94
+ returnKeyType="done"
95
+ onSubmitEditing={save}
96
+ style={[styles.input, { color: colors.textPrimary }, textStyle]}
97
+ />
98
+ </View>
99
+ )
100
+ }
101
+
102
+ const styles = StyleSheet.create({
103
+ row: { flexDirection: 'row', alignItems: 'center', minHeight: 52, paddingLeft: spacing.xs, paddingRight: spacing.lg },
104
+ // A 44pt target around a 17pt glyph / 28pt disc, flush with the card's
105
+ // left padding once the disc's own inset is counted.
106
+ leading: { width: 44, height: 44, alignItems: 'center', justifyContent: 'center' },
107
+ confirmDisc: { width: 28, height: 28, borderRadius: 14, alignItems: 'center', justifyContent: 'center' },
108
+ input: { ...typography.body, flex: 1, minWidth: 0, paddingVertical: spacing.md, paddingHorizontal: 0 }
109
+ })
@@ -42,7 +42,7 @@ function loadIonicons(): IoniconsComponent {
42
42
  // Types
43
43
  // ---------------------------------------------------------------------------
44
44
 
45
- type PermissionKind = 'protocol' | 'basket' | 'certificate' | 'spending' | 'group' | 'btms'
45
+ type PermissionKind = 'protocol' | 'basket' | 'certificate' | 'spending' | 'group' | 'btms' | 'mandala'
46
46
 
47
47
  interface GroupProtocol {
48
48
  protocolID: [number, string]
@@ -105,6 +105,7 @@ function deriveActive(
105
105
  certificateRequests: any[]
106
106
  spendingRequests: any[]
107
107
  btmsRequests: any[]
108
+ mandalaRequests: any[]
108
109
  protocolAccessModalOpen: boolean
109
110
  basketAccessModalOpen: boolean
110
111
  certificateAccessModalOpen: boolean
@@ -134,8 +135,8 @@ function deriveActive(
134
135
  }
135
136
  }
136
137
 
137
- // Priority: spending > certificate > protocol > basket > btms (spending is most
138
- // time-sensitive). We show only one at a time — exactly like the originals.
138
+ // Priority: spending > certificate > protocol > basket > btms > mandala (spending
139
+ // is most time-sensitive). We show only one at a time — exactly like the originals.
139
140
 
140
141
  if (ctx.spendingAuthorizationModalOpen && ctx.spendingRequests.length > 0) {
141
142
  const r = ctx.spendingRequests[0]
@@ -258,6 +259,55 @@ function deriveActive(
258
259
  }
259
260
  }
260
261
 
262
+ // mandala: same shape as btms above — driven purely by queue length, resolved via advanceMandalaQueue
263
+ if (ctx.mandalaRequests.length > 0) {
264
+ const r = ctx.mandalaRequests[0]
265
+ let promptData: {
266
+ type?: string
267
+ action?: string
268
+ assetId?: string
269
+ tokenName?: string
270
+ sendAmount?: number
271
+ changeAmount?: number
272
+ creditAmount?: number
273
+ } = {}
274
+ try {
275
+ promptData = JSON.parse(r.message)
276
+ } catch {
277
+ // message not valid JSON — ignore, use defaults
278
+ }
279
+
280
+ let description: string
281
+ if (promptData.type === 'mandala_spend' && promptData.sendAmount != null) {
282
+ description = `wants to spend ${promptData.sendAmount} ${promptData.tokenName || 'Mandala tokens'}`
283
+ } else if (promptData.type === 'mandala_credit' && promptData.creditAmount != null) {
284
+ description = `wants to credit ${promptData.creditAmount} ${promptData.tokenName || 'Mandala tokens'} to your wallet`
285
+ } else if (promptData.type === 'mandala_access' && promptData.action === 'relinquishOutput') {
286
+ description = 'wants to remove a Mandala token holding from your wallet'
287
+ } else if (promptData.type === 'mandala_access') {
288
+ description = 'wants to see your Mandala token balance'
289
+ } else {
290
+ description = 'wants to access Mandala tokens'
291
+ }
292
+
293
+ const details: { label: string; value: string }[] = []
294
+ if (promptData.tokenName) details.push({ label: 'Token', value: promptData.tokenName })
295
+ if (promptData.sendAmount != null) details.push({ label: 'Send amount', value: String(promptData.sendAmount) })
296
+ if (promptData.changeAmount != null) details.push({ label: 'Change', value: String(promptData.changeAmount) })
297
+ if (promptData.creditAmount != null) details.push({ label: 'Credit amount', value: String(promptData.creditAmount) })
298
+ if (promptData.assetId) details.push({ label: 'Asset ID', value: truncate(promptData.assetId, 28) })
299
+
300
+ return {
301
+ kind: 'mandala',
302
+ // mandala requests are resolved via advanceMandalaQueue, not permissionsManager — use a sentinel requestID
303
+ requestID: '',
304
+ originator: r.originator || 'Unknown app',
305
+ title: 'Token Spend Request',
306
+ description,
307
+ details
308
+ }
309
+ }
310
+
261
311
  return null
262
312
  }
263
313
 
@@ -283,11 +333,13 @@ const PermissionSheet: React.FC = () => {
283
333
  certificateRequests,
284
334
  spendingRequests,
285
335
  btmsRequests,
336
+ mandalaRequests,
286
337
  advanceProtocolQueue,
287
338
  advanceBasketQueue,
288
339
  advanceCertificateQueue,
289
340
  advanceSpendingQueue,
290
341
  advanceBtmsQueue,
342
+ advanceMandalaQueue,
291
343
  managers,
292
344
  settings
293
345
  } = useContext(WalletContext)
@@ -341,6 +393,7 @@ const PermissionSheet: React.FC = () => {
341
393
  certificateRequests,
342
394
  spendingRequests,
343
395
  btmsRequests,
396
+ mandalaRequests,
344
397
  protocolAccessModalOpen,
345
398
  basketAccessModalOpen,
346
399
  certificateAccessModalOpen,
@@ -354,6 +407,7 @@ const PermissionSheet: React.FC = () => {
354
407
  certificateRequests,
355
408
  spendingRequests,
356
409
  btmsRequests,
410
+ mandalaRequests,
357
411
  protocolAccessModalOpen,
358
412
  basketAccessModalOpen,
359
413
  certificateAccessModalOpen,
@@ -399,6 +453,9 @@ const PermissionSheet: React.FC = () => {
399
453
  if (active.kind === 'btms') {
400
454
  // BTMS uses its own promise-based resolution — no permissionsManager.denyPermission
401
455
  advanceBtmsQueue(false)
456
+ } else if (active.kind === 'mandala') {
457
+ // Mandala uses its own promise-based resolution too — no permissionsManager.denyPermission
458
+ advanceMandalaQueue(false)
402
459
  } else {
403
460
  try {
404
461
  await managers.permissionsManager?.denyPermission(active.requestID)
@@ -434,6 +491,7 @@ const PermissionSheet: React.FC = () => {
434
491
  advanceCertificateQueue,
435
492
  advanceSpendingQueue,
436
493
  advanceBtmsQueue,
494
+ advanceMandalaQueue,
437
495
  setProtocolAccessModalOpen,
438
496
  setBasketAccessModalOpen,
439
497
  setCertificateAccessModalOpen,
@@ -451,6 +509,8 @@ const PermissionSheet: React.FC = () => {
451
509
 
452
510
  if (request.kind === 'btms') {
453
511
  advanceBtmsQueue(true)
512
+ } else if (request.kind === 'mandala') {
513
+ advanceMandalaQueue(true)
454
514
  } else if (request.kind === 'spending') {
455
515
  managers.permissionsManager?.grantPermission({
456
516
  requestID: request.requestID,
@@ -479,7 +539,7 @@ const PermissionSheet: React.FC = () => {
479
539
  }
480
540
  }
481
541
  setDetailsExpanded(false)
482
- // Reset granted so that consecutive BTMS requests (sharing sentinel requestID '')
542
+ // Reset granted so that consecutive BTMS/Mandala requests (sharing sentinel requestID '')
483
543
  // don't leave the sheet permanently in granted state / deadlocked.
484
544
  setGranted(false)
485
545
  }, [
@@ -489,6 +549,7 @@ const PermissionSheet: React.FC = () => {
489
549
  advanceCertificateQueue,
490
550
  advanceSpendingQueue,
491
551
  advanceBtmsQueue,
552
+ advanceMandalaQueue,
492
553
  setProtocolAccessModalOpen,
493
554
  setBasketAccessModalOpen,
494
555
  setCertificateAccessModalOpen,
@@ -32,6 +32,10 @@ interface SheetProps {
32
32
  fullPage?: boolean
33
33
  /** When true the sheet sizes to its content (up to heightPercent max). */
34
34
  fitContent?: boolean
35
+ /** Fires once the open spring settles. Use this (not a fixed timeout) to
36
+ * focus a field inside the sheet — focusing before the sheet has finished
37
+ * moving into place drops the first keystroke typed into it. */
38
+ onOpenComplete?: () => void
35
39
  children?: React.ReactNode
36
40
  }
37
41
 
@@ -52,6 +56,7 @@ const Sheet: React.FC<SheetProps> = ({
52
56
  heightPercent = 0.75,
53
57
  fullPage = false,
54
58
  fitContent = false,
59
+ onOpenComplete,
55
60
  children
56
61
  }) => {
57
62
  const { colors } = useTheme()
@@ -81,7 +86,9 @@ const Sheet: React.FC<SheetProps> = ({
81
86
  setRendered(true)
82
87
  if (!wasVisibleRef.current) {
83
88
  translateY.value = sheetHeight
84
- translateY.value = withSpring(0, { mass: 1, stiffness: 280, damping: 32 })
89
+ translateY.value = withSpring(0, { mass: 1, stiffness: 280, damping: 32 }, finished => {
90
+ if (finished && onOpenComplete) runOnJS(onOpenComplete)()
91
+ })
85
92
  }
86
93
  } else {
87
94
  translateY.value = withSpring(sheetHeight, { mass: 1, stiffness: 400, damping: 38 }, finished => {
@@ -305,7 +312,7 @@ const styles = StyleSheet.create({
305
312
  shadowRadius: 30
306
313
  },
307
314
  backdrop: {
308
- ...StyleSheet.absoluteFillObject,
315
+ ...StyleSheet.absoluteFill,
309
316
  zIndex: 10
310
317
  },
311
318
  handleArea: {
@@ -0,0 +1,86 @@
1
+ /**
2
+ * A full-screen surface that arrives from the right and leaves to the right —
3
+ * the push/pop a native stack gives you, for a view presented inside a screen
4
+ * rather than routed to.
5
+ *
6
+ * React Native's `Modal` animates only vertically (`animationType="slide"`
7
+ * comes up from the bottom), which reads as a sheet, not a push. So the
8
+ * transform is ours, and per the motion rules it runs on the UI thread via
9
+ * Reanimated and decelerates on `easings.out` — never a JS timer.
10
+ *
11
+ * Reduced motion collapses the translation to a crossfade rather than removing
12
+ * the transition: the surface still needs to read as arriving.
13
+ */
14
+ import React, { useEffect, useState } from 'react'
15
+ import { StyleSheet, useWindowDimensions, View } from 'react-native'
16
+ import Animated, {
17
+ runOnJS,
18
+ useAnimatedStyle,
19
+ useReducedMotion,
20
+ useSharedValue,
21
+ withTiming
22
+ } from 'react-native-reanimated'
23
+ import { durations, easings } from '@bsv/expo-wallet-toolbox'
24
+
25
+ export default function SlideOverFromRight({
26
+ visible,
27
+ onClosed,
28
+ children
29
+ }: {
30
+ visible: boolean
31
+ /** Fired once the surface has finished leaving, so the caller can drop its content. */
32
+ onClosed?: () => void
33
+ children: React.ReactNode
34
+ }) {
35
+ const { width } = useWindowDimensions()
36
+ const reduced = useReducedMotion()
37
+ // Mounted for as long as anything is on screen — through the close animation,
38
+ // not just while `visible` is true.
39
+ const [mounted, setMounted] = useState(visible)
40
+ const progress = useSharedValue(visible ? 1 : 0)
41
+
42
+ // Adjusting own state during render, which React sanctions for "derive from
43
+ // a prop that just changed" — an effect would mount one frame late and the
44
+ // surface would jump in already half-arrived.
45
+ if (visible && !mounted) setMounted(true)
46
+
47
+ useEffect(() => {
48
+ const done = (finished?: boolean) => {
49
+ 'worklet'
50
+ if (finished && !visible) {
51
+ runOnJS(setMounted)(false)
52
+ if (onClosed) runOnJS(onClosed)()
53
+ }
54
+ }
55
+ progress.value = withTiming(
56
+ visible ? 1 : 0,
57
+ { duration: visible ? durations.moderate : durations.quick, easing: easings.out },
58
+ done
59
+ )
60
+ // `onClosed` is deliberately absent: an inline callback from the caller
61
+ // would re-run this effect on every render and restart the animation.
62
+ // eslint-disable-next-line react-hooks/exhaustive-deps
63
+ }, [visible, progress])
64
+
65
+ const style = useAnimatedStyle(() =>
66
+ reduced
67
+ ? { opacity: progress.value, transform: [{ translateX: 0 }] }
68
+ : { opacity: 1, transform: [{ translateX: (1 - progress.value) * width }] }
69
+ )
70
+
71
+ if (!mounted) return null
72
+
73
+ return (
74
+ <View style={[StyleSheet.absoluteFill, styles.above]} pointerEvents="box-none">
75
+ <Animated.View style={[StyleSheet.absoluteFill, style]}>{children}</Animated.View>
76
+ </View>
77
+ )
78
+ }
79
+
80
+ const styles = StyleSheet.create({
81
+ // A full-screen surface has to cover the screen it arrives over, including
82
+ // that screen's own lifted chrome. The list's top ScrollFade carries
83
+ // zIndex 1, and being a later sibling is not enough to beat it — without
84
+ // this the fade's 24pt band paints straight across the arriving surface.
85
+ above: { zIndex: 10 }
86
+ })