@bsv/expo-wallet-toolbox 0.1.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.
- package/LICENSE.txt +28 -0
- package/README.md +512 -0
- package/assets/sounds/payment-receive.wav +0 -0
- package/assets/sounds/payment-send.wav +0 -0
- package/assets/sounds/vault-close.wav +0 -0
- package/assets/sounds/vault-open.wav +0 -0
- package/core/amountFormatHelpers.ts +330 -0
- package/core/backup/RemoteSyncReader.ts +94 -0
- package/core/backup/client.ts +111 -0
- package/core/backup/codec.ts +218 -0
- package/core/backup/constants.ts +88 -0
- package/core/backup/cursor.ts +138 -0
- package/core/backup/derive.ts +46 -0
- package/core/backup/deviceId.ts +33 -0
- package/core/backup/erase.ts +67 -0
- package/core/backup/preference.ts +33 -0
- package/core/backup/push.ts +295 -0
- package/core/backup/restore.ts +152 -0
- package/core/backup/restoreOnImport.ts +119 -0
- package/core/backup/status.ts +46 -0
- package/core/config.tsx +47 -0
- package/core/constants.ts +35 -0
- package/core/context/ExchangeRateContext.tsx +69 -0
- package/core/context/LocalStorageProvider.tsx +225 -0
- package/core/context/UserContext.tsx +129 -0
- package/core/context/VaultContext.tsx +79 -0
- package/core/context/WalletConnectionContext.tsx +454 -0
- package/core/context/WalletContext.tsx +2938 -0
- package/core/context/buildGeneration.ts +37 -0
- package/core/deviceTier.ts +89 -0
- package/core/diskSpace.ts +62 -0
- package/core/displayCurrencies.ts +56 -0
- package/core/headers/OfflineFirstChaintracks.ts +176 -0
- package/core/headers/checkpoints.ts +39 -0
- package/core/headers/fs.ts +119 -0
- package/core/headers/headerStore.ts +333 -0
- package/core/headers/prewarm.ts +36 -0
- package/core/headers/syncHeaders.ts +73 -0
- package/core/hooks/useConfirmationSound.ts +135 -0
- package/core/hooks/useHaptics.ts +51 -0
- package/core/hooks/usePermissionQueue.ts +69 -0
- package/core/i18n/translations.tsx +6692 -0
- package/core/index.ts +295 -0
- package/core/localpay/blePermissions.ts +32 -0
- package/core/localpay/build.ts +392 -0
- package/core/localpay/codec.ts +338 -0
- package/core/localpay/deviceCaps.ts +175 -0
- package/core/localpay/nearbyAdvisory.ts +32 -0
- package/core/localpay/nearbyPermissions.ts +34 -0
- package/core/localpay/pending.ts +385 -0
- package/core/localpay/pendingAborts.ts +67 -0
- package/core/localpay/qr.ts +16 -0
- package/core/localpay/session.ts +277 -0
- package/core/localpay/sessionPolicy.ts +5 -0
- package/core/localpay/transport/awdl.ts +11 -0
- package/core/localpay/transport/ble.ts +159 -0
- package/core/localpay/transport/nearby.ts +12 -0
- package/core/localpay/transport/race.ts +110 -0
- package/core/localpay/transport/select.ts +128 -0
- package/core/localpay/transport/socket.ts +244 -0
- package/core/localpay/types.ts +82 -0
- package/core/localpay/verify.ts +204 -0
- package/core/logging.config.ts +10 -0
- package/core/logging.ts +77 -0
- package/core/mnemonicWallet.ts +180 -0
- package/core/monitor/TaskBackupPush.ts +168 -0
- package/core/monitor/TaskCreditInbox.ts +116 -0
- package/core/monitor/TaskDrainOutbox.ts +122 -0
- package/core/monitor/TaskSendOffline.ts +123 -0
- package/core/monitor/unfailRetry.ts +116 -0
- package/core/net/chainMatch.ts +34 -0
- package/core/net/online.ts +34 -0
- package/core/offline/cancelParked.ts +56 -0
- package/core/offline/hold.ts +127 -0
- package/core/offline/order.ts +109 -0
- package/core/offline/payerHold.ts +144 -0
- package/core/offline/plan.ts +264 -0
- package/core/offline/queueGrace.ts +52 -0
- package/core/parsePeerPayURI.ts +119 -0
- package/core/pay/beefRepair.ts +106 -0
- package/core/pay/creditErrors.ts +46 -0
- package/core/pay/creditInbox.ts +202 -0
- package/core/pay/damagedInbox.ts +64 -0
- package/core/pay/proofNudge.ts +23 -0
- package/core/pay/provenTxFromBump.ts +31 -0
- package/core/pay/rails/address.ts +329 -0
- package/core/pay/rails/handle.ts +617 -0
- package/core/pay/rails/index.ts +197 -0
- package/core/pay/rails/nearby.ts +79 -0
- package/core/pay/receiveFocus.ts +13 -0
- package/core/pay/recordProof.ts +91 -0
- package/core/pay/refreshProofGuard.ts +34 -0
- package/core/pay/sweeper.ts +75 -0
- package/core/pay/tokenAmount.ts +18 -0
- package/core/pay/userError.ts +18 -0
- package/core/pay/watchlist.ts +126 -0
- package/core/peerpay/control.ts +122 -0
- package/core/peerpay/handleResendRequests.ts +475 -0
- package/core/peerpay/inboxAttempts.ts +33 -0
- package/core/peerpay/metadataDecryptor.ts +42 -0
- package/core/peerpay/offlineNacks.ts +96 -0
- package/core/peerpay/outbox.ts +209 -0
- package/core/peerpay/rebuildToken.ts +76 -0
- package/core/peerpay/resendBeef.ts +115 -0
- package/core/services/arcadeBroadcastProvider.ts +214 -0
- package/core/services/capWalletArgs.ts +99 -0
- package/core/services/exchangeRate.ts +63 -0
- package/core/services/secrets/envelope.ts +102 -0
- package/core/services/secrets/hkdf.ts +37 -0
- package/core/services/secrets/index.ts +63 -0
- package/core/services/secrets/kek.ts +274 -0
- package/core/services/secrets/migration.ts +188 -0
- package/core/services/secrets/policy.ts +120 -0
- package/core/services/secrets/storage.ts +54 -0
- package/core/services/secrets/store.ts +125 -0
- package/core/services/secrets/types.ts +85 -0
- package/core/services/usdFxRates.ts +101 -0
- package/core/services/vault/VaultKeyService.ts +312 -0
- package/core/services/vault/backupAttestation.ts +136 -0
- package/core/services/vault/ceremony.ts +972 -0
- package/core/services/vault/ceremonyHost.ts +46 -0
- package/core/services/vault/devMock.ts +22 -0
- package/core/services/vault/driver.ts +197 -0
- package/core/services/vault/guard.ts +90 -0
- package/core/services/vault/k1.ts +75 -0
- package/core/services/vault/mockYubiKey.ts +217 -0
- package/core/services/vault/random.ts +20 -0
- package/core/services/vault/sealing.ts +84 -0
- package/core/services/vault/session.ts +59 -0
- package/core/services/vault/transfers.ts +1151 -0
- package/core/services/vault/types.ts +109 -0
- package/core/services/vault/vaultDerivation.ts +152 -0
- package/core/services/vault/vaultPassphrase.ts +287 -0
- package/core/services/vault/vaultStore.ts +104 -0
- package/core/services/walletArgLimits.ts +234 -0
- package/core/services/walletServiceConfig.ts +170 -0
- package/core/storage/LocalStorageAdapter.ts +58 -0
- package/core/storage/README.md +391 -0
- package/core/storage/StorageExpoSQLite.ts +2008 -0
- package/core/storage/errors.ts +73 -0
- package/core/storage/index.ts +3 -0
- package/core/storage/methods/findSql.ts +286 -0
- package/core/storage/methods/historyNotes.ts +61 -0
- package/core/storage/methods/listActionsSql.ts +212 -0
- package/core/storage/methods/listOutputsSql.ts +211 -0
- package/core/storage/methods/offlineActions.ts +156 -0
- package/core/storage/methods/processOfflineActions.ts +503 -0
- package/core/storage/methods/reclaim.ts +135 -0
- package/core/storage/methods/reviewStatusSql.ts +167 -0
- package/core/storage/methods/unprovenWithoutReqSql.ts +26 -0
- package/core/storage/methods/walletBalanceSql.ts +55 -0
- package/core/storage/schema/createTables.ts +385 -0
- package/core/storage/skipQueuedAncestors.ts +29 -0
- package/core/storage/sqlUpdateValue.ts +12 -0
- package/core/stores/ConnectionStore.ts +71 -0
- package/core/theme/ThemeContext.tsx +182 -0
- package/core/theme/assertThemeContrast.ts +109 -0
- package/core/theme/motion.ts +50 -0
- package/core/theme/tokens.ts +232 -0
- package/core/theme/useThemeStyles.tsx +156 -0
- package/core/walletDbRegistry.ts +110 -0
- package/core/walletMonitor.ts +149 -0
- package/core/walletRepair/runWalletCheck.ts +195 -0
- package/core/walletRepair/shouldReleaseUtxo.ts +18 -0
- package/package.json +86 -0
- package/ui/backupShares.ts +367 -0
- package/ui/components/QRScanner.tsx +353 -0
- package/ui/components/pay/AddressReceive.tsx +507 -0
- package/ui/components/pay/AvailableBalance.tsx +61 -0
- package/ui/components/pay/HandleReceive.tsx +896 -0
- package/ui/components/pay/MessageBoxConfig.tsx +256 -0
- package/ui/components/pay/NearbyAdvisoryModal.tsx +111 -0
- package/ui/components/pay/NearbyFlow.tsx +2542 -0
- package/ui/components/pay/OfflineNotice.tsx +337 -0
- package/ui/components/pay/PayCellRow.tsx +101 -0
- package/ui/components/pay/PayForm.tsx +223 -0
- package/ui/components/pay/PaymentQrDisplay.tsx +105 -0
- package/ui/components/pay/PaymentSuccessOverlay.tsx +266 -0
- package/ui/components/pay/RecipientField.tsx +308 -0
- package/ui/components/pay/RequestHub.tsx +75 -0
- package/ui/components/pay/ResultBanner.tsx +69 -0
- package/ui/components/pay/UniversalSend.tsx +687 -0
- package/ui/components/pay/useRecipientInput.ts +270 -0
- package/ui/components/security/WalletLockNotice.tsx +138 -0
- package/ui/components/ui/AlertCard.tsx +223 -0
- package/ui/components/ui/AppLogo.tsx +166 -0
- package/ui/components/ui/BlurChrome.tsx +72 -0
- package/ui/components/ui/Celebration.tsx +84 -0
- package/ui/components/ui/ChoiceSheet.ts +69 -0
- package/ui/components/ui/CustomSafeArea.tsx +74 -0
- package/ui/components/ui/ErrorBoundary.tsx +154 -0
- package/ui/components/ui/GroupedList.tsx +125 -0
- package/ui/components/ui/IconButton.tsx +105 -0
- package/ui/components/ui/ListRow.tsx +197 -0
- package/ui/components/ui/PermissionSheet.tsx +920 -0
- package/ui/components/ui/PresenceRow.tsx +215 -0
- package/ui/components/ui/PressableScale.tsx +105 -0
- package/ui/components/ui/ScreenGradient.tsx +47 -0
- package/ui/components/ui/ScrollFade.tsx +76 -0
- package/ui/components/ui/Sheet.tsx +342 -0
- package/ui/components/ui/Toast.tsx +142 -0
- package/ui/components/ui/index.ts +8 -0
- package/ui/components/vault/EnrollWizard.tsx +627 -0
- package/ui/components/vault/PassphraseField.tsx +306 -0
- package/ui/components/vault/PhraseBackupSheet.tsx +227 -0
- package/ui/components/vault/VaultBackdrop.tsx +354 -0
- package/ui/components/vault/VaultCeremonySheet.tsx +327 -0
- package/ui/components/wallet/ActivityRow.tsx +408 -0
- package/ui/components/wallet/AmountDisplay.tsx +48 -0
- package/ui/components/wallet/AmountInput.tsx +256 -0
- package/ui/components/wallet/BackupReminderSheet.tsx +168 -0
- package/ui/components/wallet/Balance.tsx +144 -0
- package/ui/components/wallet/BiometricAdvisoryModal.tsx +133 -0
- package/ui/components/wallet/ImportFromBackupPrompt.tsx +93 -0
- package/ui/exportDatabases.ts +122 -0
- package/ui/exportTransactions.ts +129 -0
- package/ui/hooks/useOfflineNoticeActions.ts +136 -0
- package/ui/hooks/useOnline.ts +70 -0
- package/ui/hooks/useSpendableBalance.ts +58 -0
- package/ui/hooks/useVaultBalance.ts +50 -0
- package/ui/importDatabases.ts +170 -0
- package/ui/index.ts +136 -0
- package/ui/isImageUrl.ts +10 -0
- package/ui/printRecoveryShares.ts +93 -0
- package/ui/resolveIdentity.ts +125 -0
- package/ui/screens/ConnectionsScreen.tsx +438 -0
- package/ui/screens/LogsScreen.tsx +432 -0
- package/ui/screens/PairScreen.tsx +288 -0
- package/ui/screens/PayScreen.tsx +479 -0
- package/ui/screens/SettingsScreen.tsx +180 -0
- package/ui/screens/TrustScreen.tsx +831 -0
- package/ui/screens/VaultRecoverScreen.tsx +226 -0
- package/ui/screens/VaultScreen.tsx +423 -0
- package/ui/screens/VaultTransferScreen.tsx +293 -0
- package/ui/screens/WalletCheckScreen.tsx +539 -0
- package/ui/screens/WalletConfigScreen.tsx +1095 -0
- package/ui/screens/WalletHomeScreen.tsx +1597 -0
- package/ui/screens/homeBadges.ts +18 -0
- package/ui/txStatus.ts +79 -0
- package/ui/validateTrust.ts +44 -0
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A validated window of block headers, on disk, plus an in-memory merkle-root
|
|
3
|
+
* index.
|
|
4
|
+
*
|
|
5
|
+
* WHY THIS EXISTS: `Beef.verify` needs exactly one thing — a merkle root for a
|
|
6
|
+
* block height (@bsv/sdk Beef.js:702-707). Everything else about offline
|
|
7
|
+
* payments follows from being able to answer that with no network.
|
|
8
|
+
*
|
|
9
|
+
* SHAPE: `<chain>.bin` holds contiguous 80-byte headers starting at
|
|
10
|
+
* `anchor.height + 1`; `<chain>.json` holds the metadata; `<chain>-extra.json`
|
|
11
|
+
* holds roots resolved below the window while online. On open, one pass over
|
|
12
|
+
* the .bin builds a packed Uint8Array of 32-byte roots — ~1.7 MB for a year,
|
|
13
|
+
* versus ~3.4 MB if they were kept as hex strings — so a lookup is an array
|
|
14
|
+
* slice and a hex encode rather than file I/O.
|
|
15
|
+
*
|
|
16
|
+
* VALIDATION is a single pass per appended chunk: link each header to the
|
|
17
|
+
* previous hash, hash it once, check that hash against the target its own bits
|
|
18
|
+
* declare, and keep the root. Doing it here rather than calling the toolbox's
|
|
19
|
+
* `validateBufferOfHeaders` avoids hashing every header twice, since that
|
|
20
|
+
* helper checks linkage but not difficulty.
|
|
21
|
+
*/
|
|
22
|
+
import { Utils } from '@bsv/sdk'
|
|
23
|
+
import {
|
|
24
|
+
blockHash,
|
|
25
|
+
deserializeBaseBlockHeader,
|
|
26
|
+
validateHeaderDifficulty
|
|
27
|
+
} from '@bsv/wallet-toolbox-mobile/out/src/services/chaintracker/chaintracks/util/blockHeaderUtilities'
|
|
28
|
+
import type { HeaderCheckpoint } from './checkpoints'
|
|
29
|
+
import type { HeaderFs } from './fs'
|
|
30
|
+
|
|
31
|
+
const HEADER_BYTES = 80
|
|
32
|
+
const ROOT_BYTES = 32
|
|
33
|
+
|
|
34
|
+
interface StoredMeta {
|
|
35
|
+
chain: string
|
|
36
|
+
anchorHeight: number
|
|
37
|
+
anchorHash: string
|
|
38
|
+
count: number
|
|
39
|
+
tipHash: string
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export class HeaderStore {
|
|
43
|
+
/** Headers validated per JS-thread slice before `append` yields. ~140ms on the device that produced 2.8s stalls. */
|
|
44
|
+
static readonly DEFAULT_YIELD_EVERY = 100
|
|
45
|
+
yieldEvery = HeaderStore.DEFAULT_YIELD_EVERY
|
|
46
|
+
|
|
47
|
+
private roots: Uint8Array
|
|
48
|
+
private extra: Record<string, string>
|
|
49
|
+
private constructor(
|
|
50
|
+
private readonly fs: HeaderFs,
|
|
51
|
+
readonly chain: string,
|
|
52
|
+
readonly anchor: HeaderCheckpoint,
|
|
53
|
+
private headerCount: number,
|
|
54
|
+
private currentTipHash: string,
|
|
55
|
+
roots: Uint8Array,
|
|
56
|
+
extra: Record<string, string>
|
|
57
|
+
) {
|
|
58
|
+
this.roots = roots
|
|
59
|
+
this.extra = extra
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
private get binPath(): string {
|
|
63
|
+
return `${this.chain}.bin`
|
|
64
|
+
}
|
|
65
|
+
private get metaPath(): string {
|
|
66
|
+
return `${this.chain}.json`
|
|
67
|
+
}
|
|
68
|
+
private get extraPath(): string {
|
|
69
|
+
return `${this.chain}-extra.json`
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** First height held by the window. */
|
|
73
|
+
get baseHeight(): number {
|
|
74
|
+
return this.anchor.height + 1
|
|
75
|
+
}
|
|
76
|
+
get count(): number {
|
|
77
|
+
return this.headerCount
|
|
78
|
+
}
|
|
79
|
+
/** Highest validated height, or the anchor height when the window is empty. */
|
|
80
|
+
get tipHeight(): number {
|
|
81
|
+
return this.anchor.height + this.headerCount
|
|
82
|
+
}
|
|
83
|
+
/** Hash of the highest validated header, or the anchor hash when empty. */
|
|
84
|
+
get tipHash(): string {
|
|
85
|
+
return this.currentTipHash
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
static async open(fs: HeaderFs, chain: string, anchor: HeaderCheckpoint): Promise<HeaderStore> {
|
|
89
|
+
const extraRaw = await fs.readText(`${chain}-extra.json`)
|
|
90
|
+
let extra: Record<string, string> = {}
|
|
91
|
+
if (extraRaw) {
|
|
92
|
+
try {
|
|
93
|
+
const parsed = JSON.parse(extraRaw) as unknown
|
|
94
|
+
if (parsed && typeof parsed === 'object') extra = parsed as Record<string, string>
|
|
95
|
+
} catch {
|
|
96
|
+
// A corrupt cache of roots is a cache miss, never a load failure.
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const metaRaw = await fs.readText(`${chain}.json`)
|
|
101
|
+
let meta: StoredMeta | undefined
|
|
102
|
+
if (metaRaw) {
|
|
103
|
+
try {
|
|
104
|
+
meta = JSON.parse(metaRaw) as StoredMeta
|
|
105
|
+
} catch {
|
|
106
|
+
meta = undefined
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const empty = new HeaderStore(fs, chain, anchor, 0, anchor.hash, new Uint8Array(0), extra)
|
|
111
|
+
|
|
112
|
+
// A shipped checkpoint that moved (app update) invalidates the window: its
|
|
113
|
+
// first header no longer links to anything we trust. Start over rather than
|
|
114
|
+
// keep headers we can no longer justify.
|
|
115
|
+
if (
|
|
116
|
+
!meta ||
|
|
117
|
+
meta.chain !== chain ||
|
|
118
|
+
meta.anchorHeight !== anchor.height ||
|
|
119
|
+
meta.anchorHash !== anchor.hash ||
|
|
120
|
+
meta.count <= 0
|
|
121
|
+
) {
|
|
122
|
+
await empty.reset()
|
|
123
|
+
return empty
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
let bin = await fs.readBytes(`${chain}.bin`)
|
|
127
|
+
const expected = meta.count * HEADER_BYTES
|
|
128
|
+
if (!bin || bin.length < expected) {
|
|
129
|
+
await empty.reset()
|
|
130
|
+
return empty
|
|
131
|
+
}
|
|
132
|
+
// Crash-mid-append: extra bytes past meta.count are not indexed and would
|
|
133
|
+
// sit in front of the next append. Truncate to the committed prefix.
|
|
134
|
+
if (bin.length > expected) {
|
|
135
|
+
bin = bin.subarray(0, expected)
|
|
136
|
+
await fs.writeBytes(`${chain}.bin`, bin)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const roots = new Uint8Array(meta.count * ROOT_BYTES)
|
|
140
|
+
for (let i = 0; i < meta.count; i++) {
|
|
141
|
+
// Merkle root occupies bytes 36..68 of a header, little-endian on the
|
|
142
|
+
// wire and display order reversed.
|
|
143
|
+
const src = bin.subarray(i * HEADER_BYTES + 36, i * HEADER_BYTES + 68)
|
|
144
|
+
const display = src.slice().reverse()
|
|
145
|
+
roots.set(display, i * ROOT_BYTES)
|
|
146
|
+
}
|
|
147
|
+
return new HeaderStore(fs, chain, anchor, meta.count, meta.tipHash, roots, extra)
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
rootForHeight(height: number): string | undefined {
|
|
151
|
+
// A heal written to extra is the value to consult, even for a height the
|
|
152
|
+
// window also covers — otherwise a logged heal is stored and then ignored.
|
|
153
|
+
const extra = this.extra[String(height)]
|
|
154
|
+
if (extra !== undefined) return extra
|
|
155
|
+
const index = height - this.baseHeight
|
|
156
|
+
if (index >= 0 && index < this.headerCount) {
|
|
157
|
+
return Utils.toHex(Array.from(this.roots.subarray(index * ROOT_BYTES, (index + 1) * ROOT_BYTES)))
|
|
158
|
+
}
|
|
159
|
+
return undefined
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Validates and appends a chunk. Returns the number of headers added.
|
|
164
|
+
*
|
|
165
|
+
* Throws without mutating anything if the chunk is misaligned, starts at the
|
|
166
|
+
* wrong height, fails to link, or contains a header whose hash does not meet
|
|
167
|
+
* its declared target.
|
|
168
|
+
*/
|
|
169
|
+
async append(bytes: Uint8Array, firstHeight: number): Promise<number> {
|
|
170
|
+
if (bytes.length === 0) return 0
|
|
171
|
+
if (bytes.length % HEADER_BYTES !== 0) {
|
|
172
|
+
throw new Error(`header chunk must be a multiple of 80 bytes, got ${bytes.length}`)
|
|
173
|
+
}
|
|
174
|
+
if (firstHeight !== this.tipHeight + 1) {
|
|
175
|
+
throw new Error(`header chunk starts at height ${firstHeight}, expected ${this.tipHeight + 1}`)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const added = bytes.length / HEADER_BYTES
|
|
179
|
+
const newRoots = new Uint8Array(added * ROOT_BYTES)
|
|
180
|
+
let prev = this.currentTipHash
|
|
181
|
+
|
|
182
|
+
for (let i = 0; i < added; i++) {
|
|
183
|
+
// Two SHA-256 passes and a difficulty check per header, on the JS thread.
|
|
184
|
+
// A 2,000-header chunk was ~2.8s of solid JS on a mid-range Android and a
|
|
185
|
+
// first-launch sync repeats that ~30 times; nothing else — a nearby
|
|
186
|
+
// payment's ack, a tap — could run. Hand the loop back periodically.
|
|
187
|
+
if (i > 0 && i % this.yieldEvery === 0) await yieldToEventLoop()
|
|
188
|
+
const offset = i * HEADER_BYTES
|
|
189
|
+
const header = bytes.slice(offset, offset + HEADER_BYTES)
|
|
190
|
+
const parsed = deserializeBaseBlockHeader(bytes, offset)
|
|
191
|
+
if (parsed.previousHash !== prev) {
|
|
192
|
+
throw new Error(
|
|
193
|
+
`header at height ${firstHeight + i} names previous hash ${parsed.previousHash}, expected ${prev}`
|
|
194
|
+
)
|
|
195
|
+
}
|
|
196
|
+
const hash = blockHash(header)
|
|
197
|
+
// Throws on failure — a header that does not meet its own target is not a
|
|
198
|
+
// header, and accepting it would let anyone mint merkle roots.
|
|
199
|
+
// The upstream .d.ts types `hash` as Buffer, but the implementation only
|
|
200
|
+
// ever does `asArray(hash)`, which accepts a display-order hex string
|
|
201
|
+
// (what blockHash returns) identically to a Buffer — hence the cast.
|
|
202
|
+
validateHeaderDifficulty(hash as unknown as Buffer, parsed.bits)
|
|
203
|
+
newRoots.set(new Uint8Array(Utils.toArray(parsed.merkleRoot, 'hex')), i * ROOT_BYTES)
|
|
204
|
+
prev = hash
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
await this.fs.appendBytes(this.binPath, bytes)
|
|
208
|
+
const merged = new Uint8Array(this.roots.length + newRoots.length)
|
|
209
|
+
merged.set(this.roots, 0)
|
|
210
|
+
merged.set(newRoots, this.roots.length)
|
|
211
|
+
this.roots = merged
|
|
212
|
+
this.headerCount += added
|
|
213
|
+
this.currentTipHash = prev
|
|
214
|
+
await this.writeMeta()
|
|
215
|
+
return added
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Drops headers after `count`. Rewinds an orphaned tip so the next canonical
|
|
220
|
+
* header can link. Rebuilds the on-disk `.bin` and the in-memory root index.
|
|
221
|
+
*/
|
|
222
|
+
async truncateToCount(count: number): Promise<void> {
|
|
223
|
+
if (count === this.headerCount) return
|
|
224
|
+
if (count < 0 || count > this.headerCount) {
|
|
225
|
+
throw new Error(`truncateToCount(${count}) out of range 0..${this.headerCount}`)
|
|
226
|
+
}
|
|
227
|
+
if (count === 0) {
|
|
228
|
+
await this.reset()
|
|
229
|
+
return
|
|
230
|
+
}
|
|
231
|
+
const keep = count * HEADER_BYTES
|
|
232
|
+
const bin = await this.fs.readBytes(this.binPath)
|
|
233
|
+
if (!bin || bin.length < keep) {
|
|
234
|
+
await this.reset()
|
|
235
|
+
return
|
|
236
|
+
}
|
|
237
|
+
const sliced = bin.subarray(0, keep)
|
|
238
|
+
await this.fs.writeBytes(this.binPath, sliced)
|
|
239
|
+
this.roots = new Uint8Array(this.roots.subarray(0, count * ROOT_BYTES))
|
|
240
|
+
this.headerCount = count
|
|
241
|
+
this.currentTipHash = blockHash(sliced.subarray(keep - HEADER_BYTES, keep))
|
|
242
|
+
await this.writeMeta()
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async putExtraRoot(height: number, root: string): Promise<void> {
|
|
246
|
+
if (this.inReorgWindow(height)) return
|
|
247
|
+
if (this.extra[String(height)] === root) return
|
|
248
|
+
this.extra = { ...this.extra, [String(height)]: root }
|
|
249
|
+
await this.fs.writeText(this.extraPath, JSON.stringify(this.extra))
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Batch form of `putExtraRoot`. Merges every entry into the in-memory
|
|
254
|
+
* `extra` map and writes the JSON file once, rather than once per entry —
|
|
255
|
+
* `putExtraRoot` re-serializes and rewrites the whole file on every call,
|
|
256
|
+
* so seeding it row-by-row from a proven_txs table is O(n) file writes for
|
|
257
|
+
* n rows. Callers that resolve one miss at a time (OfflineFirstChaintracks)
|
|
258
|
+
* should keep using `putExtraRoot`; callers seeding many roots at once
|
|
259
|
+
* (prewarmOwnRoots) should use this instead. Returns how many entries were
|
|
260
|
+
* newly added (i.e. not already present in the store with the same root).
|
|
261
|
+
*/
|
|
262
|
+
async putExtraRoots(entries: { height: number; root: string }[]): Promise<number> {
|
|
263
|
+
if (entries.length === 0) return 0
|
|
264
|
+
const merged = { ...this.extra }
|
|
265
|
+
let added = 0
|
|
266
|
+
for (const { height, root } of entries) {
|
|
267
|
+
if (this.inReorgWindow(height)) continue
|
|
268
|
+
const key = String(height)
|
|
269
|
+
if (merged[key] === root) continue
|
|
270
|
+
merged[key] = root
|
|
271
|
+
added++
|
|
272
|
+
}
|
|
273
|
+
if (added === 0) return 0
|
|
274
|
+
this.extra = merged
|
|
275
|
+
await this.fs.writeText(this.extraPath, JSON.stringify(this.extra))
|
|
276
|
+
return added
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Throws away the stored window and records an empty one.
|
|
281
|
+
*
|
|
282
|
+
* The `.bin` is DELETED, not merely forgotten. `HeaderFs.appendBytes` appends,
|
|
283
|
+
* so leaving the old bytes on disk puts them in front of whatever the next sync
|
|
284
|
+
* writes: `meta.count` then counts only the new headers while `open()` rebuilds
|
|
285
|
+
* the root index from the FIRST `count * 80` bytes — the discarded anchor's —
|
|
286
|
+
* and every height in the window is served the wrong merkle root. The
|
|
287
|
+
* `bin.length < count * HEADER_BYTES` guard cannot catch that, because the file
|
|
288
|
+
* is too long rather than too short, and nothing else notices. After a single
|
|
289
|
+
* checkpoint bump every upgrading install would refuse every offline payment,
|
|
290
|
+
* for good. Safe in direction — a root that does not match returns false, it
|
|
291
|
+
* never accepts a forgery — but silent and permanent, which is why the delete
|
|
292
|
+
* has to happen here rather than being left to a future rotation.
|
|
293
|
+
*
|
|
294
|
+
* A delete that genuinely fails is left to throw. `open()`'s caller treats an
|
|
295
|
+
* unavailable header store as "no offline verification this launch" and tries
|
|
296
|
+
* again on the next one, which self-heals; serving wrong roots would not.
|
|
297
|
+
*
|
|
298
|
+
* `<chain>-extra.json` is deliberately kept: those entries are height ->
|
|
299
|
+
* merkle root facts, true whichever checkpoint the window happens to be
|
|
300
|
+
* anchored to, and re-earning them costs a full prewarm over `proven_txs`.
|
|
301
|
+
*
|
|
302
|
+
* Public so a sync that cannot rewind onto the remote chain (cap 144) can
|
|
303
|
+
* start over from the checkpoint.
|
|
304
|
+
*/
|
|
305
|
+
async reset(): Promise<void> {
|
|
306
|
+
await this.fs.deleteFile(this.binPath)
|
|
307
|
+
this.roots = new Uint8Array(0)
|
|
308
|
+
this.headerCount = 0
|
|
309
|
+
this.currentTipHash = this.anchor.hash
|
|
310
|
+
await this.writeMeta()
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** Last 6 stored heights can reorg; an extra root there would hide the window. */
|
|
314
|
+
private inReorgWindow(height: number): boolean {
|
|
315
|
+
return height <= this.tipHeight && height > this.tipHeight - 6
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
private async writeMeta(): Promise<void> {
|
|
319
|
+
const meta: StoredMeta = {
|
|
320
|
+
chain: this.chain,
|
|
321
|
+
anchorHeight: this.anchor.height,
|
|
322
|
+
anchorHash: this.anchor.hash,
|
|
323
|
+
count: this.headerCount,
|
|
324
|
+
tipHash: this.currentTipHash
|
|
325
|
+
}
|
|
326
|
+
await this.fs.writeText(this.metaPath, JSON.stringify(meta))
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** One macrotask turn, so timers, touches and native callbacks get a slice. */
|
|
331
|
+
function yieldToEventLoop(): Promise<void> {
|
|
332
|
+
return new Promise(resolve => setTimeout(resolve, 0))
|
|
333
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Seeds the header store with roots this wallet has already had validated.
|
|
3
|
+
*
|
|
4
|
+
* `proven_txs` rows are written only after `TaskCheckForProofs` has confirmed
|
|
5
|
+
* the proof against chaintracks, so their `merkleRoot` values are not the
|
|
6
|
+
* server's unverified word — they are our own past verifications. Copying them
|
|
7
|
+
* costs no network and covers exactly the heights a counterparty's BEEF will
|
|
8
|
+
* reference, because our outputs become their inputs.
|
|
9
|
+
*/
|
|
10
|
+
import type { HeaderStore } from './headerStore'
|
|
11
|
+
|
|
12
|
+
export interface ProvenTxRootRow {
|
|
13
|
+
height: number
|
|
14
|
+
merkleRoot: string
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export async function prewarmOwnRoots(args: { rows: ProvenTxRootRow[]; store: HeaderStore }): Promise<number> {
|
|
18
|
+
const { rows, store } = args
|
|
19
|
+
// Filter and dedup entirely in memory, then write once via putExtraRoots.
|
|
20
|
+
// Calling putExtraRoot per row would rewrite the whole extra-roots file on
|
|
21
|
+
// every iteration — O(n) file writes for n rows, which is invisible at the
|
|
22
|
+
// tens-of-rows scale but costs whole seconds of JS-thread time at the
|
|
23
|
+
// thousands-of-rows scale a long-lived wallet can reach.
|
|
24
|
+
const seenHeights = new Set<number>()
|
|
25
|
+
const toAdd: { height: number; root: string }[] = []
|
|
26
|
+
for (const row of rows) {
|
|
27
|
+
if (!Number.isInteger(row.height) || row.height <= 0) continue
|
|
28
|
+
if (typeof row.merkleRoot !== 'string' || row.merkleRoot.length !== 64) continue
|
|
29
|
+
if (seenHeights.has(row.height)) continue
|
|
30
|
+
if (store.rootForHeight(row.height) !== undefined) continue
|
|
31
|
+
seenHeights.add(row.height)
|
|
32
|
+
toAdd.push({ height: row.height, root: row.merkleRoot })
|
|
33
|
+
}
|
|
34
|
+
if (toAdd.length === 0) return 0
|
|
35
|
+
return store.putExtraRoots(toAdd)
|
|
36
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pulls headers from a chaintracks deployment into the local window.
|
|
3
|
+
*
|
|
4
|
+
* `getHeaders(height, count)` returns hex of concatenated 80-byte headers and is
|
|
5
|
+
* the only header source that works on every chain we ship — there is no bulk
|
|
6
|
+
* header CDN for teratest. Verified against both deployments on 2026-07-28.
|
|
7
|
+
*
|
|
8
|
+
* The default chunk of 2,000 headers is 320 KB of response body: about 26
|
|
9
|
+
* requests per year of mainnet headers, small enough that a dropped connection
|
|
10
|
+
* costs almost nothing and progress moves visibly.
|
|
11
|
+
*/
|
|
12
|
+
import { Utils } from '@bsv/sdk'
|
|
13
|
+
import type { HeaderStore } from './headerStore'
|
|
14
|
+
|
|
15
|
+
export interface HeaderSource {
|
|
16
|
+
getHeaders(height: number, count: number): Promise<string>
|
|
17
|
+
getPresentHeight(): Promise<number>
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface SyncHeadersResult {
|
|
21
|
+
added: number
|
|
22
|
+
tipHeight: number
|
|
23
|
+
presentHeight: number
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Walk back at most this many headers before giving up and resetting. */
|
|
27
|
+
const REWIND_CAP = 144
|
|
28
|
+
|
|
29
|
+
function isFirstHeaderPrevHashError(err: unknown, firstHeight: number): boolean {
|
|
30
|
+
const msg = err instanceof Error ? err.message : String(err)
|
|
31
|
+
return /previous hash/i.test(msg) && msg.includes(`header at height ${firstHeight} `)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function syncHeaders(args: {
|
|
35
|
+
store: HeaderStore
|
|
36
|
+
client: HeaderSource
|
|
37
|
+
chunkSize?: number
|
|
38
|
+
onProgress?: (tipHeight: number, presentHeight: number) => void
|
|
39
|
+
shouldStop?: () => boolean
|
|
40
|
+
}): Promise<SyncHeadersResult> {
|
|
41
|
+
const { store, client, chunkSize = 2000, onProgress, shouldStop } = args
|
|
42
|
+
const presentHeight = await client.getPresentHeight()
|
|
43
|
+
let added = 0
|
|
44
|
+
let rewinds = 0
|
|
45
|
+
|
|
46
|
+
while (store.tipHeight < presentHeight) {
|
|
47
|
+
if (shouldStop?.()) break
|
|
48
|
+
const from = store.tipHeight + 1
|
|
49
|
+
const want = Math.min(chunkSize, presentHeight - store.tipHeight)
|
|
50
|
+
const hex = await client.getHeaders(from, want)
|
|
51
|
+
if (!hex) break
|
|
52
|
+
const bytes = new Uint8Array(Utils.toArray(hex, 'hex'))
|
|
53
|
+
if (bytes.length === 0) break
|
|
54
|
+
try {
|
|
55
|
+
added += await store.append(bytes, from)
|
|
56
|
+
onProgress?.(store.tipHeight, presentHeight)
|
|
57
|
+
} catch (err) {
|
|
58
|
+
// First-header previous-hash miss is a tip reorg: drop the orphan and
|
|
59
|
+
// refetch. A later header in the chunk, or any other validation failure,
|
|
60
|
+
// still propagates — a silent truncated window would look complete.
|
|
61
|
+
if (!isFirstHeaderPrevHashError(err, from)) throw err
|
|
62
|
+
if (store.count > 0 && rewinds < REWIND_CAP) {
|
|
63
|
+
await store.truncateToCount(store.count - 1)
|
|
64
|
+
rewinds++
|
|
65
|
+
continue
|
|
66
|
+
}
|
|
67
|
+
await store.reset()
|
|
68
|
+
throw err
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return { added, tipHeight: store.tipHeight, presentHeight }
|
|
73
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The app's tiny sound palette — the audible half of key money/security moments.
|
|
3
|
+
*
|
|
4
|
+
* Companion to `hooks/useHaptics.ts`, deliberately the same shape: a plain
|
|
5
|
+
* module object you can import anywhere, plus a hook alias for symmetry inside
|
|
6
|
+
* components. Fire-and-forget, and it never throws.
|
|
7
|
+
*
|
|
8
|
+
* Three rules, all non-negotiable, because these play in public:
|
|
9
|
+
*
|
|
10
|
+
* 1. RESPECT THE SILENT SWITCH. `playsInSilentMode: false` — a phone set to
|
|
11
|
+
* silent stays silent. An app that overrides the ringer switch for its own
|
|
12
|
+
* receipt noise is an app people mute permanently.
|
|
13
|
+
* 2. NEVER MIX BADLY. `interruptionMode: 'mixWithOthers'` — these are sub-1s
|
|
14
|
+
* blips, not a media session. Ducking or pausing someone's music to
|
|
15
|
+
* announce a payment is rude and, on iOS, sticky.
|
|
16
|
+
* 3. NEVER BLOCK, NEVER THROW. Every call site is `void`; every failure — no
|
|
17
|
+
* native module, an audio session another app owns, a decode error — is
|
|
18
|
+
* swallowed to a single dev warning. A silent success is still a success.
|
|
19
|
+
*
|
|
20
|
+
* expo-audio is required lazily on first play, so a build missing the native
|
|
21
|
+
* module degrades to silence at the one moment it is used rather than taking
|
|
22
|
+
* the module graph down at startup.
|
|
23
|
+
*
|
|
24
|
+
* Pairing rules (each tone pairs with exactly one haptic; never fire both a
|
|
25
|
+
* tone's partner haptic AND the tone's own — Toast/Celebration already own
|
|
26
|
+
* haptics.success for their moments):
|
|
27
|
+
* paymentReceive ↔ haptics.success (money landed)
|
|
28
|
+
* paymentSend ↔ haptics.success (money sent)
|
|
29
|
+
* vaultOpen ↔ haptics.success (vault unlocked after the ceremony)
|
|
30
|
+
* vaultClose ↔ haptics.confirm (vault relocked: timeout / unplug / manual)
|
|
31
|
+
*/
|
|
32
|
+
import { useMemo } from 'react'
|
|
33
|
+
|
|
34
|
+
// Bundled tones. Static requires, not imports: Metro resolves these to asset
|
|
35
|
+
// ids at build time, which is exactly the `number` shape expo-audio accepts.
|
|
36
|
+
const TONES = {
|
|
37
|
+
paymentReceive: require('../../assets/sounds/payment-receive.wav'),
|
|
38
|
+
paymentSend: require('../../assets/sounds/payment-send.wav'),
|
|
39
|
+
vaultOpen: require('../../assets/sounds/vault-open.wav'),
|
|
40
|
+
vaultClose: require('../../assets/sounds/vault-close.wav'),
|
|
41
|
+
} as const
|
|
42
|
+
|
|
43
|
+
type ToneName = keyof typeof TONES
|
|
44
|
+
|
|
45
|
+
/** Minimal structural view of the bits of expo-audio this module touches. */
|
|
46
|
+
interface Player {
|
|
47
|
+
play(): void
|
|
48
|
+
seekTo(seconds: number): Promise<void>
|
|
49
|
+
remove(): void
|
|
50
|
+
}
|
|
51
|
+
interface AudioModule {
|
|
52
|
+
createAudioPlayer(source: unknown): Player
|
|
53
|
+
setAudioModeAsync(mode: Record<string, unknown>): Promise<void>
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
let audio: AudioModule | null | undefined
|
|
57
|
+
let modeSet = false
|
|
58
|
+
const players: Partial<Record<ToneName, Player>> = {}
|
|
59
|
+
|
|
60
|
+
function warn(e: unknown): void {
|
|
61
|
+
if (__DEV__) console.warn('[sound] tone unavailable:', e instanceof Error ? e.message : String(e))
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function load(): AudioModule | null {
|
|
65
|
+
if (audio !== undefined) return audio
|
|
66
|
+
try {
|
|
67
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
68
|
+
audio = require('expo-audio') as AudioModule
|
|
69
|
+
} catch (e) {
|
|
70
|
+
warn(e)
|
|
71
|
+
audio = null
|
|
72
|
+
}
|
|
73
|
+
return audio
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Plays a tone, if the device is willing. Returns immediately; the audio-session
|
|
78
|
+
* configuration is awaited *inside* the fire-and-forget promise so nothing on a
|
|
79
|
+
* user-facing path ever waits on CoreAudio. One reused player per tone.
|
|
80
|
+
*/
|
|
81
|
+
function playTone(name: ToneName): void {
|
|
82
|
+
const mod = load()
|
|
83
|
+
if (!mod) return
|
|
84
|
+
void (async () => {
|
|
85
|
+
try {
|
|
86
|
+
if (!modeSet) {
|
|
87
|
+
await mod.setAudioModeAsync({
|
|
88
|
+
playsInSilentMode: false,
|
|
89
|
+
interruptionMode: 'mixWithOthers',
|
|
90
|
+
shouldPlayInBackground: false,
|
|
91
|
+
allowsRecording: false,
|
|
92
|
+
})
|
|
93
|
+
modeSet = true
|
|
94
|
+
}
|
|
95
|
+
let player = players[name]
|
|
96
|
+
if (!player) {
|
|
97
|
+
player = mod.createAudioPlayer(TONES[name])
|
|
98
|
+
players[name] = player
|
|
99
|
+
}
|
|
100
|
+
await player.seekTo(0)
|
|
101
|
+
player.play()
|
|
102
|
+
} catch (e) {
|
|
103
|
+
warn(e)
|
|
104
|
+
}
|
|
105
|
+
})()
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Releases every shared player. Optional — call when the last screen that can
|
|
109
|
+
* play a tone unmounts, to hand native objects back early. */
|
|
110
|
+
function releaseAll(): void {
|
|
111
|
+
for (const key of Object.keys(players) as ToneName[]) {
|
|
112
|
+
const p = players[key]
|
|
113
|
+
delete players[key]
|
|
114
|
+
try {
|
|
115
|
+
p?.remove()
|
|
116
|
+
} catch (e) {
|
|
117
|
+
warn(e)
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
modeSet = false
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export const sounds = {
|
|
124
|
+
/** The money landed. Pairs with `haptics.success()`. */
|
|
125
|
+
paymentReceive: () => playTone('paymentReceive'),
|
|
126
|
+
/** The money was sent. Pairs with `haptics.success()`. */
|
|
127
|
+
paymentSend: () => playTone('paymentSend'),
|
|
128
|
+
/** The vault unlocked after a successful ceremony. Pairs with `haptics.success()`. */
|
|
129
|
+
vaultOpen: () => playTone('vaultOpen'),
|
|
130
|
+
/** The vault relocked (timeout, unplug, or manual). Pairs with `haptics.confirm()`. */
|
|
131
|
+
vaultClose: () => playTone('vaultClose'),
|
|
132
|
+
release: releaseAll,
|
|
133
|
+
} as const
|
|
134
|
+
|
|
135
|
+
export const useConfirmationSound = () => useMemo(() => sounds, [])
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Semantic haptic vocabulary (spec Part 1). Import `haptics` directly in
|
|
3
|
+
* plain modules; use `useHaptics()` in components for symmetry with other
|
|
4
|
+
* hooks. All calls are fire-and-forget and never throw.
|
|
5
|
+
*
|
|
6
|
+
* | semantic | iOS | Android |
|
|
7
|
+
* |----------|-----------------------------|---------|
|
|
8
|
+
* | tap | selectionAsync | no-op |
|
|
9
|
+
* | confirm | impactAsync(Light) | no-op |
|
|
10
|
+
* | success | notificationAsync(Success) | vibrate |
|
|
11
|
+
* | warning | notificationAsync(Warning) | vibrate |
|
|
12
|
+
* | error | notificationAsync(Error) | vibrate |
|
|
13
|
+
*
|
|
14
|
+
* expo-haptics is required lazily, on first call, rather than imported
|
|
15
|
+
* statically — this file is barrel-exported from the package root, and a
|
|
16
|
+
* static top-level `import` of a native module gets eagerly evaluated for
|
|
17
|
+
* every consumer of the barrel (breaking non-native/test hosts that never
|
|
18
|
+
* call a haptic), the same class of issue documented on
|
|
19
|
+
* services/vault/driver.ts and random.ts's lazy native requires.
|
|
20
|
+
*/
|
|
21
|
+
import { Platform } from 'react-native'
|
|
22
|
+
|
|
23
|
+
type HapticsModule = typeof import('expo-haptics')
|
|
24
|
+
|
|
25
|
+
let mod: HapticsModule | null | undefined
|
|
26
|
+
|
|
27
|
+
function load(): HapticsModule | null {
|
|
28
|
+
if (mod !== undefined) return mod
|
|
29
|
+
try {
|
|
30
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
31
|
+
mod = require('expo-haptics') as HapticsModule
|
|
32
|
+
} catch {
|
|
33
|
+
mod = null
|
|
34
|
+
}
|
|
35
|
+
return mod
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const swallow = (p: Promise<void>) => { p.catch(() => {}) }
|
|
39
|
+
const isIOS = () => Platform.OS === 'ios'
|
|
40
|
+
|
|
41
|
+
export const haptics = {
|
|
42
|
+
tap: () => { const h = load(); if (h && isIOS()) swallow(h.selectionAsync()) },
|
|
43
|
+
confirm: () => { const h = load(); if (h && isIOS()) swallow(h.impactAsync(h.ImpactFeedbackStyle.Light)) },
|
|
44
|
+
success: () => { const h = load(); if (h) swallow(h.notificationAsync(h.NotificationFeedbackType.Success)) },
|
|
45
|
+
warning: () => { const h = load(); if (h) swallow(h.notificationAsync(h.NotificationFeedbackType.Warning)) },
|
|
46
|
+
error: () => { const h = load(); if (h) swallow(h.notificationAsync(h.NotificationFeedbackType.Error)) },
|
|
47
|
+
} as const
|
|
48
|
+
|
|
49
|
+
export type HapticName = keyof typeof haptics
|
|
50
|
+
|
|
51
|
+
export const useHaptics = () => haptics
|