@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,330 @@
|
|
|
1
|
+
// Safe locale detection for React Native
|
|
2
|
+
const getLocaleDefault = (): string => {
|
|
3
|
+
try {
|
|
4
|
+
// Try to get locale using Intl API if available
|
|
5
|
+
return Intl.NumberFormat().resolvedOptions().locale?.split('-u-')[0] || 'en-US'
|
|
6
|
+
} catch {
|
|
7
|
+
// Fallback to en-US if Intl is not fully supported
|
|
8
|
+
return 'en-US'
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const localeDefault = getLocaleDefault()
|
|
13
|
+
|
|
14
|
+
const SATS_PER_BSV = 100_000_000
|
|
15
|
+
const CENT_THRESHOLD = 0.01
|
|
16
|
+
|
|
17
|
+
export type UsdToFiat = Record<string, number>
|
|
18
|
+
|
|
19
|
+
export type AmountFormatOptions = {
|
|
20
|
+
showPlus?: boolean
|
|
21
|
+
abbreviate?: boolean
|
|
22
|
+
showFiatAsInteger?: boolean
|
|
23
|
+
usdToFiat?: UsdToFiat
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export const isFiatCurrency = (currency: string): boolean => Boolean(currency) && currency !== 'BSV'
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Satoshis per 1 unit of `currency`. USD is the WhatsOnChain rate; other fiat
|
|
30
|
+
* is that rate divided by the USD→fiat cross (1 USD = `usdToFiat[code]` units).
|
|
31
|
+
*/
|
|
32
|
+
export const satoshisPerFiatUnit = (
|
|
33
|
+
currency: string,
|
|
34
|
+
satoshisPerUSD: number,
|
|
35
|
+
usdToFiat: UsdToFiat = {}
|
|
36
|
+
): number => {
|
|
37
|
+
if (currency === 'USD') return satoshisPerUSD
|
|
38
|
+
const fx = usdToFiat[currency]
|
|
39
|
+
if (!(satoshisPerUSD > 0) || !(fx > 0)) return 0
|
|
40
|
+
return satoshisPerUSD / fx
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export const fiatFractionDigits = (currency: string): number => {
|
|
44
|
+
try {
|
|
45
|
+
const digits = new Intl.NumberFormat(localeDefault, {
|
|
46
|
+
style: 'currency',
|
|
47
|
+
currency
|
|
48
|
+
}).resolvedOptions().maximumFractionDigits
|
|
49
|
+
return typeof digits === 'number' ? digits : 2
|
|
50
|
+
} catch {
|
|
51
|
+
return 2
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Format number as currency with fallback for platforms where Intl is not fully supported
|
|
56
|
+
const formatCurrency = (
|
|
57
|
+
value: number,
|
|
58
|
+
locale: string,
|
|
59
|
+
currency: string,
|
|
60
|
+
minDigits: number,
|
|
61
|
+
maxDigits?: number
|
|
62
|
+
): string => {
|
|
63
|
+
const abs = Math.abs(value)
|
|
64
|
+
let formatted: string
|
|
65
|
+
try {
|
|
66
|
+
const options: Intl.NumberFormatOptions = {
|
|
67
|
+
currency,
|
|
68
|
+
style: 'currency',
|
|
69
|
+
minimumFractionDigits: minDigits
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (maxDigits !== undefined) {
|
|
73
|
+
options.maximumFractionDigits = maxDigits
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const formatter = new Intl.NumberFormat(locale, options)
|
|
77
|
+
formatted = formatter.format(abs)
|
|
78
|
+
} catch {
|
|
79
|
+
formatted = `${currency} ${abs.toFixed(minDigits)}`
|
|
80
|
+
}
|
|
81
|
+
return value < 0 ? `(${formatted})` : formatted
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Format a satoshi amount as a locale-aware integer string with grouping separators.
|
|
86
|
+
* E.g. 1234567 -> "1,234,567" (en-US) or "1.234.567" (de-DE)
|
|
87
|
+
*/
|
|
88
|
+
const formatSatoshisLocale = (satoshis: number): string => {
|
|
89
|
+
try {
|
|
90
|
+
return new Intl.NumberFormat(localeDefault, {
|
|
91
|
+
maximumFractionDigits: 0,
|
|
92
|
+
useGrouping: true
|
|
93
|
+
}).format(satoshis)
|
|
94
|
+
} catch {
|
|
95
|
+
return Math.abs(satoshis).toLocaleString()
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Format a BSV decimal amount with locale-aware separators.
|
|
101
|
+
* Shows up to 8 decimal places, trimming trailing zeros.
|
|
102
|
+
*/
|
|
103
|
+
const formatBsvLocale = (bsvValue: number): string => {
|
|
104
|
+
try {
|
|
105
|
+
return new Intl.NumberFormat(localeDefault, {
|
|
106
|
+
minimumFractionDigits: 0,
|
|
107
|
+
maximumFractionDigits: 8,
|
|
108
|
+
useGrouping: true
|
|
109
|
+
}).format(bsvValue)
|
|
110
|
+
} catch {
|
|
111
|
+
// Fallback: trim trailing zeros from toFixed(8)
|
|
112
|
+
return parseFloat(bsvValue.toFixed(8)).toString()
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Format a sub-cent USD value as cents (¢).
|
|
118
|
+
* Dynamically adjusts decimal precision based on magnitude.
|
|
119
|
+
*/
|
|
120
|
+
const formatCents = (cents: number): string => {
|
|
121
|
+
const absCents = Math.abs(cents)
|
|
122
|
+
let maxDigits = 2
|
|
123
|
+
if (absCents < 0.01) maxDigits = 4
|
|
124
|
+
else if (absCents < 0.1) maxDigits = 3
|
|
125
|
+
|
|
126
|
+
try {
|
|
127
|
+
const formatted = new Intl.NumberFormat(localeDefault, {
|
|
128
|
+
minimumFractionDigits: 0,
|
|
129
|
+
maximumFractionDigits: maxDigits,
|
|
130
|
+
useGrouping: true
|
|
131
|
+
}).format(cents)
|
|
132
|
+
return `${formatted}¢`
|
|
133
|
+
} catch {
|
|
134
|
+
return `${parseFloat(cents.toFixed(maxDigits))}¢`
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Format a satoshi amount as fiat using satoshis-per-unit of that currency.
|
|
140
|
+
* Values below one minor unit (1 cent, 1 yen, …) display as "< {smallest}".
|
|
141
|
+
* Otherwise rounds up to the currency's minor unit.
|
|
142
|
+
*/
|
|
143
|
+
export const formatSatoshisAsFiat = (
|
|
144
|
+
satoshis: number,
|
|
145
|
+
satoshisPerUnit: number,
|
|
146
|
+
showFiatAsInteger = false,
|
|
147
|
+
currency = 'USD'
|
|
148
|
+
): string => {
|
|
149
|
+
if (!Number.isInteger(Number(satoshis)) || !satoshisPerUnit || satoshisPerUnit <= 0) {
|
|
150
|
+
return '...'
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const raw = satoshis / satoshisPerUnit
|
|
154
|
+
if (isNaN(raw)) return '...'
|
|
155
|
+
|
|
156
|
+
const v = Math.abs(raw)
|
|
157
|
+
const digits = showFiatAsInteger ? 0 : fiatFractionDigits(currency)
|
|
158
|
+
const factor = 10 ** digits
|
|
159
|
+
const threshold = digits === 0 ? 1 : 1 / factor
|
|
160
|
+
|
|
161
|
+
if (v > 0 && v < threshold && !showFiatAsInteger) {
|
|
162
|
+
const smallest = formatCurrency(threshold, localeDefault, currency, digits, digits)
|
|
163
|
+
return raw < 0 ? `< (${smallest})` : `< ${smallest}`
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const sign = raw < 0 ? -1 : 1
|
|
167
|
+
const rounded = (sign * Math.ceil(Math.abs(raw) * factor)) / factor
|
|
168
|
+
|
|
169
|
+
const minDigits = showFiatAsInteger ? 0 : digits
|
|
170
|
+
const maxDigits = showFiatAsInteger ? 0 : digits
|
|
171
|
+
|
|
172
|
+
return formatCurrency(rounded, localeDefault, currency, minDigits, maxDigits)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Format a satoshi amount in BSV mode with smart threshold:
|
|
177
|
+
* - < 100,000,000 sats (< 1 BSV): display as satoshis with grouping (e.g., "50,000 satoshis")
|
|
178
|
+
* - >= 100,000,000 sats (>= 1 BSV): display as BSV with decimals (e.g., "1.5 BSV")
|
|
179
|
+
*
|
|
180
|
+
* All formatting is locale-aware.
|
|
181
|
+
*/
|
|
182
|
+
export const formatSatoshisAsBsv = (satoshis: number, showPlus = false, abbreviate = false): string => {
|
|
183
|
+
const numValue = Number(satoshis)
|
|
184
|
+
if (!Number.isInteger(numValue)) return '---'
|
|
185
|
+
|
|
186
|
+
const sign = numValue < 0 ? '-' : showPlus ? '+' : ''
|
|
187
|
+
const absValue = Math.abs(numValue)
|
|
188
|
+
|
|
189
|
+
if (absValue >= SATS_PER_BSV) {
|
|
190
|
+
// Display as BSV
|
|
191
|
+
const bsvValue = absValue / SATS_PER_BSV
|
|
192
|
+
return `${sign}${formatBsvLocale(bsvValue)} BSV`
|
|
193
|
+
} else {
|
|
194
|
+
// Display as satoshis
|
|
195
|
+
const label = abbreviate ? 'sats' : 'satoshis'
|
|
196
|
+
return `${sign}${formatSatoshisLocale(absValue)} ${label}`
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Smart format function: formats a satoshi amount based on the currency setting.
|
|
202
|
+
* - fiat codes: convert using WhatsOnChain USD and optional USD→fiat crosses
|
|
203
|
+
* - 'BSV' (default): smart threshold (satoshis for < 1 BSV, BSV for >= 1 BSV)
|
|
204
|
+
*/
|
|
205
|
+
export const formatAmount = (
|
|
206
|
+
satoshis: number,
|
|
207
|
+
currency: string = 'BSV',
|
|
208
|
+
satoshisPerUSD: number = 0,
|
|
209
|
+
options: AmountFormatOptions = {}
|
|
210
|
+
): string => {
|
|
211
|
+
const { showPlus = false, abbreviate = false, showFiatAsInteger = false, usdToFiat = {} } = options
|
|
212
|
+
|
|
213
|
+
if (isFiatCurrency(currency)) {
|
|
214
|
+
const per = satoshisPerFiatUnit(currency, satoshisPerUSD, usdToFiat)
|
|
215
|
+
return formatSatoshisAsFiat(satoshis, per, showFiatAsInteger, currency)
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
return formatSatoshisAsBsv(satoshis, showPlus, abbreviate)
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Format satoshis as a plain BSV decimal, with no unit appended.
|
|
223
|
+
* E.g. 729948 -> "0.00729948". For the context line under a balance, where the
|
|
224
|
+
* unit is written out separately.
|
|
225
|
+
*/
|
|
226
|
+
export const formatSatoshisAsBsvDecimal = (satoshis: number): string =>
|
|
227
|
+
formatBsvLocale(Math.abs(Number(satoshis)) / SATS_PER_BSV)
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Split a formatted amount into its figure and its unit, so the two can be set
|
|
231
|
+
* at different sizes — the figure is the thing being read, the unit is a label
|
|
232
|
+
* hanging off it. In USD mode the symbol is part of the figure, so `unit` is
|
|
233
|
+
* empty rather than fabricated.
|
|
234
|
+
*/
|
|
235
|
+
export const formatAmountParts = (
|
|
236
|
+
satoshis: number,
|
|
237
|
+
currency: string = 'BSV',
|
|
238
|
+
satoshisPerUSD: number = 0,
|
|
239
|
+
options: AmountFormatOptions = {}
|
|
240
|
+
): { value: string; unit: string } => {
|
|
241
|
+
const text = formatAmount(satoshis, currency, satoshisPerUSD, options)
|
|
242
|
+
if (isFiatCurrency(currency)) return { value: text, unit: '' }
|
|
243
|
+
const split = text.lastIndexOf(' ')
|
|
244
|
+
if (split < 0) return { value: text, unit: '' }
|
|
245
|
+
return { value: text.slice(0, split), unit: text.slice(split + 1) }
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* The spendable figure in the unit AmountInput is asking for RIGHT NOW, with
|
|
250
|
+
* no symbol and no unit word: the input's own suffix already says "satoshis"
|
|
251
|
+
* or "EUR", and repeating it beside the balance reads twice. BSV mode never
|
|
252
|
+
* switches to whole BSV for this reason — the field beside it takes satoshis.
|
|
253
|
+
* Empty when there is nothing honest to show (no rate in fiat mode, NaN).
|
|
254
|
+
*/
|
|
255
|
+
export const formatAmountInInputUnit = (
|
|
256
|
+
satoshis: number,
|
|
257
|
+
currency: string,
|
|
258
|
+
satoshisPerUSD: number,
|
|
259
|
+
usdToFiat: UsdToFiat = {}
|
|
260
|
+
): string => {
|
|
261
|
+
const n = Number(satoshis)
|
|
262
|
+
if (!Number.isFinite(n)) return ''
|
|
263
|
+
if (isFiatCurrency(currency)) {
|
|
264
|
+
const per = satoshisPerFiatUnit(currency, satoshisPerUSD, usdToFiat)
|
|
265
|
+
if (!(per > 0)) return ''
|
|
266
|
+
const amount = Math.abs(n) / per
|
|
267
|
+
const digits = fiatFractionDigits(currency)
|
|
268
|
+
try {
|
|
269
|
+
return new Intl.NumberFormat(localeDefault, {
|
|
270
|
+
minimumFractionDigits: digits,
|
|
271
|
+
maximumFractionDigits: digits
|
|
272
|
+
}).format(amount)
|
|
273
|
+
} catch {
|
|
274
|
+
return amount.toFixed(digits)
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
return formatSatoshisLocale(Math.abs(Math.round(n)))
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Convert a user-entered display value back to integer satoshis.
|
|
282
|
+
* - BSV mode: input is satoshi integers, passthrough
|
|
283
|
+
* - fiat mode: input is a decimal amount in that currency
|
|
284
|
+
*/
|
|
285
|
+
export const parseDisplayToSatoshis = (
|
|
286
|
+
displayValue: string,
|
|
287
|
+
currency: string,
|
|
288
|
+
satoshisPerUSD: number,
|
|
289
|
+
usdToFiat: UsdToFiat = {}
|
|
290
|
+
): number => {
|
|
291
|
+
const cleaned = displayValue.trim()
|
|
292
|
+
if (!cleaned) return 0
|
|
293
|
+
|
|
294
|
+
if (isFiatCurrency(currency)) {
|
|
295
|
+
const amount = parseFloat(cleaned)
|
|
296
|
+
if (isNaN(amount)) return 0
|
|
297
|
+
const per = satoshisPerFiatUnit(currency, satoshisPerUSD, usdToFiat)
|
|
298
|
+
if (!(per > 0)) return 0
|
|
299
|
+
return Math.round(amount * per)
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// BSV mode: input is always integer satoshis
|
|
303
|
+
const sats = parseInt(cleaned, 10)
|
|
304
|
+
return isNaN(sats) ? 0 : sats
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Get the appropriate unit label for display.
|
|
309
|
+
* In BSV mode, the label depends on the amount (satoshis vs BSV).
|
|
310
|
+
* If no satoshi value is provided, returns "satoshis" (the input label for BSV mode).
|
|
311
|
+
*/
|
|
312
|
+
export const getUnitLabel = (currency: string, satoshis?: number, abbreviate = false, satoshisPerUSD?: number): string => {
|
|
313
|
+
if (isFiatCurrency(currency)) {
|
|
314
|
+
if (currency === 'USD' && satoshis !== undefined && satoshisPerUSD && satoshisPerUSD > 0) {
|
|
315
|
+
const usd = Math.abs(satoshis / satoshisPerUSD)
|
|
316
|
+
if (usd > 0 && usd < CENT_THRESHOLD) return '¢'
|
|
317
|
+
}
|
|
318
|
+
return currency
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// BSV mode: if an amount is provided, use threshold to pick label
|
|
322
|
+
if (satoshis !== undefined && Math.abs(satoshis) >= SATS_PER_BSV) {
|
|
323
|
+
return 'BSV'
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
return abbreviate ? 'sats' : 'satoshis'
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// Keep legacy exports for backward compatibility during migration
|
|
330
|
+
export const formatSatoshis = formatSatoshisAsBsv
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Restore side of the backup log.
|
|
3
|
+
*
|
|
4
|
+
* `WalletStorageSyncReader` is a two-method interface, and that is the entire restore
|
|
5
|
+
* contract — so replaying an encrypted log into a fresh database needs no changes to the
|
|
6
|
+
* toolbox at all. `WalletStorageManager.syncFromReader` drives this exactly as it would
|
|
7
|
+
* drive a live remote storage provider.
|
|
8
|
+
*/
|
|
9
|
+
import type { CompletedProtoWallet } from '@bsv/sdk'
|
|
10
|
+
import type {
|
|
11
|
+
RequestSyncChunkArgs,
|
|
12
|
+
SyncChunk
|
|
13
|
+
} from '@bsv/wallet-toolbox-mobile/out/src/sdk/WalletStorage.interfaces'
|
|
14
|
+
import type { TableSettings } from '@bsv/wallet-toolbox-mobile/out/src/storage/schema/tables'
|
|
15
|
+
import type { BackupClient, LogEntry } from './client'
|
|
16
|
+
import { decodeChunk, emptyChunk } from './codec'
|
|
17
|
+
import type { BackupChain } from './constants'
|
|
18
|
+
|
|
19
|
+
export class BackupChainError extends Error {
|
|
20
|
+
constructor (message: string) {
|
|
21
|
+
super(message)
|
|
22
|
+
this.name = 'BackupChainError'
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export class RemoteSyncReader {
|
|
27
|
+
private entries: LogEntry[] | null = null
|
|
28
|
+
private next = 0
|
|
29
|
+
|
|
30
|
+
constructor (
|
|
31
|
+
private readonly client: BackupClient,
|
|
32
|
+
private readonly wallet: CompletedProtoWallet,
|
|
33
|
+
private readonly chain: BackupChain,
|
|
34
|
+
private readonly deviceId: string,
|
|
35
|
+
private readonly generation: number,
|
|
36
|
+
private readonly settings: TableSettings
|
|
37
|
+
) {}
|
|
38
|
+
|
|
39
|
+
/** Settings for the storage being restored into. */
|
|
40
|
+
async makeAvailable (): Promise<TableSettings> {
|
|
41
|
+
return this.settings
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Return the next chunk in sequence.
|
|
46
|
+
*
|
|
47
|
+
* `args` is ignored deliberately: a live reader would honour `since` and `offsets`, but a
|
|
48
|
+
* log is an ordered recording of chunks that were already produced against those very
|
|
49
|
+
* arguments. Replaying them in order reproduces the original stream exactly, and second
|
|
50
|
+
* -guessing it would risk skipping records.
|
|
51
|
+
*/
|
|
52
|
+
async getSyncChunk (_args: RequestSyncChunkArgs): Promise<SyncChunk> {
|
|
53
|
+
if (this.entries == null) {
|
|
54
|
+
this.entries = await this.client.index(this.deviceId, this.generation)
|
|
55
|
+
this.verifyChain(this.entries)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (this.next >= this.entries.length) {
|
|
59
|
+
// All twelve arrays present and empty: the completion sentinel.
|
|
60
|
+
return emptyChunk(this.deviceId, this.settings.storageIdentityKey, '')
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const entry = this.entries[this.next++]
|
|
64
|
+
const ciphertext = await this.client.blob(this.deviceId, this.generation, entry.seq)
|
|
65
|
+
return await decodeChunk(this.wallet, Array.from(ciphertext), this.chain)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Number of chunks in this generation, once the index has been read. */
|
|
69
|
+
get length (): number {
|
|
70
|
+
return this.entries?.length ?? 0
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Reject a log with a gap or a fork before any of it is replayed.
|
|
75
|
+
*
|
|
76
|
+
* A restore that silently stops halfway is worse than one that fails: the wallet would
|
|
77
|
+
* look healthy while missing the outputs it needs to spend.
|
|
78
|
+
*/
|
|
79
|
+
private verifyChain (entries: LogEntry[]): void {
|
|
80
|
+
for (let i = 0; i < entries.length; i++) {
|
|
81
|
+
const expectedSeq = i + 1
|
|
82
|
+
if (entries[i].seq !== expectedSeq) {
|
|
83
|
+
throw new BackupChainError(
|
|
84
|
+
`backup chain has a gap: expected sequence ${expectedSeq}, found ${entries[i].seq}`
|
|
85
|
+
)
|
|
86
|
+
}
|
|
87
|
+
if (i > 0 && entries[i].prevSha256 !== entries[i - 1].sha256) {
|
|
88
|
+
throw new BackupChainError(
|
|
89
|
+
`backup chain is forked at sequence ${entries[i].seq}: previous hash does not match`
|
|
90
|
+
)
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* App-side adapter over `@bsv/backup-cache-client`.
|
|
3
|
+
*
|
|
4
|
+
* The wire client lives in the npm package (published from
|
|
5
|
+
* go-private-backup-cache/ts-client) and speaks the server's stateless
|
|
6
|
+
* per-request auth-proof protocol: one signed header per request, no
|
|
7
|
+
* handshake, no session, so uploads and downloads stream end to end and the
|
|
8
|
+
* server's blob cap is what GET /v1/limits says (200 MiB after the
|
|
9
|
+
* transaction-storage-capacity work) rather than a constant baked in here.
|
|
10
|
+
*
|
|
11
|
+
* This module keeps the two app-specific decisions out of the package:
|
|
12
|
+
*
|
|
13
|
+
* - IDENTITY. Requests authenticate as the backup pseudonym derived from the
|
|
14
|
+
* wallet's m/0'/0' key, never the wallet's identity key. The constructor
|
|
15
|
+
* takes the primary key and derives the wallet itself so no call site can
|
|
16
|
+
* accidentally hand the client the real identity.
|
|
17
|
+
*
|
|
18
|
+
* - TIMEOUTS. The monitor awaits its tasks, so a request that never answers
|
|
19
|
+
* holds the task pending indefinitely — observed on device as BackupPush
|
|
20
|
+
* passes running past 100 seconds. Every request is bounded here; a backup
|
|
21
|
+
* is never urgent, and giving up until the next pass is strictly better
|
|
22
|
+
* than occupying the monitor.
|
|
23
|
+
*/
|
|
24
|
+
import {
|
|
25
|
+
BackupCacheClient,
|
|
26
|
+
BackupHttpError,
|
|
27
|
+
ERR_BLOB_TOO_LARGE,
|
|
28
|
+
ERR_SEQ_CONFLICT,
|
|
29
|
+
type DeviceSummary,
|
|
30
|
+
type Limits,
|
|
31
|
+
type LogEntry
|
|
32
|
+
} from '@bsv/backup-cache-client'
|
|
33
|
+
import type { BackupChain } from './constants'
|
|
34
|
+
import { deriveBackupWallet } from './derive'
|
|
35
|
+
|
|
36
|
+
export { BackupHttpError, ERR_BLOB_TOO_LARGE, ERR_SEQ_CONFLICT }
|
|
37
|
+
export type { DeviceSummary, Limits, LogEntry }
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Ceiling on any single backup request.
|
|
41
|
+
*
|
|
42
|
+
* Applies per HTTP request. The stateless proof protocol needs exactly one
|
|
43
|
+
* request per operation (the old BRC-103 handshake needed two), so this now
|
|
44
|
+
* bounds each operation outright.
|
|
45
|
+
*/
|
|
46
|
+
export const BACKUP_REQUEST_TIMEOUT_MS = 30_000
|
|
47
|
+
|
|
48
|
+
export class BackupClient extends BackupCacheClient {
|
|
49
|
+
/**
|
|
50
|
+
* @param baseUrl origin of the backup service, no trailing slash or path
|
|
51
|
+
* prefix — the request URI is signed into every proof, so a prefix the
|
|
52
|
+
* server does not see identically would fail all of them.
|
|
53
|
+
* @param primaryKey the wallet's m/0'/0' key, from which the pseudonym is derived.
|
|
54
|
+
* @param chain the network this client serves. Each chain derives a different
|
|
55
|
+
* pseudonym, so each network's log lives in its own server account.
|
|
56
|
+
* @param fetchImpl injectable transport for tests; defaults to global fetch.
|
|
57
|
+
*/
|
|
58
|
+
constructor (baseUrl: string, primaryKey: number[], chain: BackupChain, fetchImpl?: typeof fetch) {
|
|
59
|
+
super({
|
|
60
|
+
baseUrl,
|
|
61
|
+
wallet: deriveBackupWallet(primaryKey, chain),
|
|
62
|
+
fetch: withTimeout(fetchImpl ?? ((input, init) => fetch(input, init)))
|
|
63
|
+
})
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Append a chunk. Accepts the codec's `number[]` ciphertext alongside the
|
|
68
|
+
* package's own body shapes, so encodeChunk's output flows straight through.
|
|
69
|
+
*/
|
|
70
|
+
override async append (
|
|
71
|
+
deviceId: string,
|
|
72
|
+
generation: number,
|
|
73
|
+
seq: number,
|
|
74
|
+
prevSha256: string | undefined,
|
|
75
|
+
body: Uint8Array | Blob | number[]
|
|
76
|
+
): Promise<{ seq: number, sha256: string, size: number }> {
|
|
77
|
+
const bytes = Array.isArray(body) ? new Uint8Array(body) : body
|
|
78
|
+
return await super.append(deviceId, generation, seq, prevSha256, bytes)
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Bound every request the client makes.
|
|
84
|
+
*
|
|
85
|
+
* A race rather than an AbortController, kept from the previous client: losing
|
|
86
|
+
* the race abandons the in-flight promise, which is acceptable because the
|
|
87
|
+
* caller retries the whole pass and nothing downstream depends on the
|
|
88
|
+
* abandoned result.
|
|
89
|
+
*/
|
|
90
|
+
function withTimeout (transport: typeof fetch): typeof fetch {
|
|
91
|
+
return async (input, init) => {
|
|
92
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
93
|
+
try {
|
|
94
|
+
return await Promise.race([
|
|
95
|
+
transport(input, init),
|
|
96
|
+
new Promise<never>((_resolve, reject) => {
|
|
97
|
+
timer = setTimeout(
|
|
98
|
+
() =>
|
|
99
|
+
reject(
|
|
100
|
+
new Error(`Backup request timed out after ${BACKUP_REQUEST_TIMEOUT_MS}ms: ${String(input)}`)
|
|
101
|
+
),
|
|
102
|
+
BACKUP_REQUEST_TIMEOUT_MS
|
|
103
|
+
)
|
|
104
|
+
;(timer as { unref?: () => void }).unref?.()
|
|
105
|
+
})
|
|
106
|
+
])
|
|
107
|
+
} finally {
|
|
108
|
+
if (timer != null) clearTimeout(timer)
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|