@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,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rail identity.
|
|
3
|
+
*
|
|
4
|
+
* A rail is never chosen by the user. It is inferred from what they typed or
|
|
5
|
+
* scanned: a nearby-session code, an identity key or peerpay link, or a
|
|
6
|
+
* base58check address. Free text that is none of those is an identity search.
|
|
7
|
+
* Everything in this file is pure — no wallet, no network — so the
|
|
8
|
+
* classification a payment depends on is testable in isolation.
|
|
9
|
+
*/
|
|
10
|
+
import { Utils } from '@bsv/sdk'
|
|
11
|
+
import { decodeSession, type Session } from '../../localpay/session'
|
|
12
|
+
import {
|
|
13
|
+
validatePeerPayURI,
|
|
14
|
+
type PeerPayValidationResult,
|
|
15
|
+
peerPayValidationMessage,
|
|
16
|
+
isCompressedPublicKey
|
|
17
|
+
} from '../../parsePeerPayURI'
|
|
18
|
+
|
|
19
|
+
/** One definition of a valid compressed key serves both the bare-key path and the link parser. */
|
|
20
|
+
export { isCompressedPublicKey }
|
|
21
|
+
|
|
22
|
+
export type RailId = 'nearby' | 'handle' | 'address'
|
|
23
|
+
|
|
24
|
+
/** How a counterparty was identified. Each variant carries only what its rail needs. */
|
|
25
|
+
export type PayTarget =
|
|
26
|
+
| { kind: 'nearby'; session: Session }
|
|
27
|
+
| { kind: 'handle'; identityKey: string; sats?: number; messageBoxUrl?: string }
|
|
28
|
+
| { kind: 'address'; address: string; sats?: number }
|
|
29
|
+
|
|
30
|
+
/** Six cell names. Since the universal input, `pay-*` are deep-link aliases that all open the send form; `get-*` open one receive method directly. */
|
|
31
|
+
export type PayCell = 'pay-nearby' | 'pay-handle' | 'pay-address' | 'get-nearby' | 'get-handle' | 'get-address'
|
|
32
|
+
|
|
33
|
+
export const PAY_CELLS: readonly PayCell[] = [
|
|
34
|
+
'pay-nearby',
|
|
35
|
+
'pay-handle',
|
|
36
|
+
'pay-address',
|
|
37
|
+
'get-nearby',
|
|
38
|
+
'get-handle',
|
|
39
|
+
'get-address'
|
|
40
|
+
] as const
|
|
41
|
+
|
|
42
|
+
export function isPayCell(value: string | undefined): value is PayCell {
|
|
43
|
+
return !!value && (PAY_CELLS as readonly string[]).includes(value)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Pure. Derived from how the counterparty was identified, never from a user choosing a transport. */
|
|
47
|
+
export function inferRail(target: PayTarget): RailId {
|
|
48
|
+
return target.kind
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** What the user must already have for a rail to be possible. */
|
|
52
|
+
export const PRECONDITION_KEYS: Record<RailId, string> = {
|
|
53
|
+
nearby: 'pay_pre_nearby',
|
|
54
|
+
handle: 'pay_pre_handle',
|
|
55
|
+
address: 'pay_pre_address'
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* What happens after they tap Pay. The address line is the one that must never
|
|
60
|
+
* be implicit: a user who pastes an address expecting messaging-style delivery
|
|
61
|
+
* has effectively posted cash.
|
|
62
|
+
*/
|
|
63
|
+
export const CONSEQUENCE_KEYS: Record<RailId, string> = {
|
|
64
|
+
nearby: 'pay_conseq_nearby',
|
|
65
|
+
handle: 'pay_conseq_handle',
|
|
66
|
+
address: 'pay_conseq_address'
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Strips a `bitcoin:` scheme and any query string, leaving a bare address candidate. */
|
|
70
|
+
export function normalizeAddressInput(raw: string): string {
|
|
71
|
+
return raw
|
|
72
|
+
.replace(/^bitcoin:/i, '')
|
|
73
|
+
.split('?')[0]
|
|
74
|
+
.trim()
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function isValidBsvAddress(text: string): boolean {
|
|
78
|
+
if (!text) return false
|
|
79
|
+
try {
|
|
80
|
+
Utils.fromBase58Check(text)
|
|
81
|
+
return true
|
|
82
|
+
} catch {
|
|
83
|
+
return false
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Base58 alphabet (no 0, O, I, l), 25–35 chars: the shape of a P2PKH address on
|
|
89
|
+
* either network — mainnet `1`, testnet `m`/`n`. P2SH `3` is deliberately
|
|
90
|
+
* absent: the address rail pays with a P2PKH lock. Anything this matches is
|
|
91
|
+
* either an address or a mis-paste — never a search query — so a checksum
|
|
92
|
+
* failure is reported, not searched.
|
|
93
|
+
*/
|
|
94
|
+
const ADDRESS_CANDIDATE_REGEX = /^[1mn][1-9A-HJ-NP-Za-km-z]{24,34}$/
|
|
95
|
+
|
|
96
|
+
/** What the recipient field has been given, as typed. */
|
|
97
|
+
export type RecipientInput =
|
|
98
|
+
| { kind: 'empty' }
|
|
99
|
+
| { kind: 'address'; address: string }
|
|
100
|
+
| { kind: 'invalid_address' }
|
|
101
|
+
| { kind: 'handle'; identityKey: string; sats?: number; messageBoxUrl?: string }
|
|
102
|
+
| { kind: 'invalid_link'; message: string }
|
|
103
|
+
| { kind: 'search'; query: string }
|
|
104
|
+
|
|
105
|
+
function handleFromPeerPay(result: PeerPayValidationResult): RecipientInput {
|
|
106
|
+
if (!result.identityKey || result.errors.identityKey || result.errors.sats) {
|
|
107
|
+
return { kind: 'invalid_link', message: peerPayValidationMessage(result) ?? 'Invalid peerpay link' }
|
|
108
|
+
}
|
|
109
|
+
return {
|
|
110
|
+
kind: 'handle',
|
|
111
|
+
identityKey: result.identityKey,
|
|
112
|
+
...(result.sats !== undefined ? { sats: result.sats } : {}),
|
|
113
|
+
...(result.messageBoxUrl ? { messageBoxUrl: result.messageBoxUrl } : {})
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* The one place typed text becomes a recipient kind. Order matters: schemed
|
|
119
|
+
* forms first, then the address shape (which alone can produce an inline
|
|
120
|
+
* error), then a bare key, then search for everything else.
|
|
121
|
+
*/
|
|
122
|
+
export function classifyRecipientInput(raw: string): RecipientInput {
|
|
123
|
+
const text = raw.trim()
|
|
124
|
+
if (!text) return { kind: 'empty' }
|
|
125
|
+
|
|
126
|
+
if (text.toLowerCase().startsWith('peerpay:')) return handleFromPeerPay(validatePeerPayURI(text))
|
|
127
|
+
|
|
128
|
+
const isBitcoinUri = /^bitcoin:/i.test(text)
|
|
129
|
+
const candidate = isBitcoinUri ? normalizeAddressInput(text) : text
|
|
130
|
+
if (isBitcoinUri || ADDRESS_CANDIDATE_REGEX.test(candidate)) {
|
|
131
|
+
return isValidBsvAddress(candidate) ? { kind: 'address', address: candidate } : { kind: 'invalid_address' }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (isCompressedPublicKey(text)) return { kind: 'handle', identityKey: text.toLowerCase() }
|
|
135
|
+
|
|
136
|
+
return { kind: 'search', query: text }
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* The one place a scanned or pasted string becomes a rail.
|
|
141
|
+
*
|
|
142
|
+
* Order matters: the two schemed forms are unambiguous and go first, then the
|
|
143
|
+
* localpay session envelope, then the two bare forms. A string that matches
|
|
144
|
+
* nothing returns null — the caller shows "not recognised" rather than
|
|
145
|
+
* guessing a rail, because guessing wrong on this input sends money the wrong
|
|
146
|
+
* way.
|
|
147
|
+
*/
|
|
148
|
+
export function classifyScan(raw: string): PayTarget | null {
|
|
149
|
+
const text = raw.trim()
|
|
150
|
+
if (!text) return null
|
|
151
|
+
|
|
152
|
+
if (text.toLowerCase().startsWith('peerpay:')) {
|
|
153
|
+
const result = validatePeerPayURI(text)
|
|
154
|
+
if (!result.identityKey || result.errors.identityKey || result.errors.sats) return null
|
|
155
|
+
return {
|
|
156
|
+
kind: 'handle',
|
|
157
|
+
identityKey: result.identityKey,
|
|
158
|
+
sats: result.sats,
|
|
159
|
+
...(result.messageBoxUrl ? { messageBoxUrl: result.messageBoxUrl } : {})
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
if (/^bitcoin:/i.test(text)) {
|
|
164
|
+
const address = normalizeAddressInput(text)
|
|
165
|
+
return isValidBsvAddress(address) ? { kind: 'address', address } : null
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
try {
|
|
169
|
+
return { kind: 'nearby', session: decodeSession(text) }
|
|
170
|
+
} catch {
|
|
171
|
+
// Not a session envelope. Fall through to the bare forms.
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
if (isCompressedPublicKey(text)) return { kind: 'handle', identityKey: text.toLowerCase() }
|
|
175
|
+
if (isValidBsvAddress(text)) return { kind: 'address', address: text }
|
|
176
|
+
return null
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Where an old route sends the user now.
|
|
181
|
+
*
|
|
182
|
+
* `/payments` carried the only external deep link in the app (`peerpay:` via
|
|
183
|
+
* +native-intent), so its params are forwarded verbatim; the other two never
|
|
184
|
+
* took params.
|
|
185
|
+
*/
|
|
186
|
+
export function legacyRedirectTarget(
|
|
187
|
+
route: 'payments' | 'legacy-payments' | 'local-payments',
|
|
188
|
+
params: Record<string, string | undefined>
|
|
189
|
+
): { pathname: '/pay'; params: Record<string, string> } {
|
|
190
|
+
const cell: PayCell = route === 'payments' ? 'pay-handle' : route === 'legacy-payments' ? 'get-address' : 'get-nearby'
|
|
191
|
+
const forwarded: Record<string, string> = { cell }
|
|
192
|
+
for (const key of ['peerpay', 'identityKey', 'sats'] as const) {
|
|
193
|
+
const value = params[key]
|
|
194
|
+
if (value !== undefined) forwarded[key] = value
|
|
195
|
+
}
|
|
196
|
+
return { pathname: '/pay', params: forwarded }
|
|
197
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The nearby rail — in-person, device-to-device over AWDL, Nearby, BLE or QR.
|
|
3
|
+
*
|
|
4
|
+
* A pass-through, on purpose. localpay/* is device-proven with 210 tests
|
|
5
|
+
* behind it and its money-safety invariants were verified line by line, so this
|
|
6
|
+
* rail adds NOTHING: no wrappers, no defaults, no convenience. Its only job is
|
|
7
|
+
* to be the single import site for nearby, so a future change cannot quietly
|
|
8
|
+
* grow a second implementation between the screen and the transport.
|
|
9
|
+
*
|
|
10
|
+
* If you find yourself wanting to add a function here, add it to the caller
|
|
11
|
+
* instead.
|
|
12
|
+
*/
|
|
13
|
+
export { decodeSession, encodeSession, mintSession, type Session } from '../../localpay/session'
|
|
14
|
+
export {
|
|
15
|
+
FRAME_BLOCK_BYTES,
|
|
16
|
+
SEAL_VERSION,
|
|
17
|
+
frameBytesFromQr,
|
|
18
|
+
frameToQr,
|
|
19
|
+
sealedToQr,
|
|
20
|
+
sealFrame,
|
|
21
|
+
unsealFrame,
|
|
22
|
+
type PaymentFrame
|
|
23
|
+
} from '../../localpay/codec'
|
|
24
|
+
/**
|
|
25
|
+
* The animated-QR transport is `@bsv/air-gap` (BRC-141), not app code. It was
|
|
26
|
+
* grown here first and upstreamed; the published library adds what a local
|
|
27
|
+
* copy could not justify carrying — a wire version byte, per-stream session
|
|
28
|
+
* ids with switch hysteresis so one stray frame cannot erase a scan in
|
|
29
|
+
* progress, and explicit decoder resource budgets. Display cadence stays with
|
|
30
|
+
* the renderer, because the library deliberately has no opinion on it.
|
|
31
|
+
*/
|
|
32
|
+
export {
|
|
33
|
+
AIR_GAP_PREFIX,
|
|
34
|
+
AirGapDecoder,
|
|
35
|
+
AirGapEncoder,
|
|
36
|
+
MAX_MESSAGE_BYTES,
|
|
37
|
+
estimatePartCharLength,
|
|
38
|
+
isAirGapPart
|
|
39
|
+
} from '@bsv/air-gap'
|
|
40
|
+
export {
|
|
41
|
+
isSessionSpent,
|
|
42
|
+
markSessionSpent,
|
|
43
|
+
processPending,
|
|
44
|
+
savePending,
|
|
45
|
+
type PendingPayment
|
|
46
|
+
} from '../../localpay/pending'
|
|
47
|
+
export { buildPaymentFrame, finalizeDelivery } from '../../localpay/build'
|
|
48
|
+
export {
|
|
49
|
+
FrameVerifyError,
|
|
50
|
+
verifyFramePayment,
|
|
51
|
+
type DerivingWallet,
|
|
52
|
+
type FrameVerifyKind
|
|
53
|
+
} from '../../localpay/verify'
|
|
54
|
+
export { holdSentPaymentOffline } from '../../offline/payerHold'
|
|
55
|
+
export { awdlTransport } from '../../localpay/transport/awdl'
|
|
56
|
+
export { nearbyTransport } from '../../localpay/transport/nearby'
|
|
57
|
+
export { bleTransport } from '../../localpay/transport/ble'
|
|
58
|
+
export { raceReceivers, type RaceWinner, type RadioKind } from '../../localpay/transport/race'
|
|
59
|
+
export {
|
|
60
|
+
describeFloor,
|
|
61
|
+
localSupportsAwdl,
|
|
62
|
+
localSupportsBle,
|
|
63
|
+
localSupportsNearby,
|
|
64
|
+
selectTransport,
|
|
65
|
+
type FloorReason,
|
|
66
|
+
type TransportKind
|
|
67
|
+
} from '../../localpay/transport/select'
|
|
68
|
+
export { requestNearbyPermissions } from '../../localpay/nearbyPermissions'
|
|
69
|
+
export { requestBlePermissions } from '../../localpay/blePermissions'
|
|
70
|
+
export {
|
|
71
|
+
capsFromProbe,
|
|
72
|
+
prepareBle,
|
|
73
|
+
probeDeviceCaps,
|
|
74
|
+
readBluetoothState,
|
|
75
|
+
type BluetoothState,
|
|
76
|
+
type DeviceProbe
|
|
77
|
+
} from '../../localpay/deviceCaps'
|
|
78
|
+
export { isDeclineReason, type Ack, type ConfirmDelivery, type DeclineReason } from '../../localpay/types'
|
|
79
|
+
export { CAP_BLE, CAP_NEARBY } from '../../localpay/session'
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether HandleReceive is the focused screen. Background credit uses this so
|
|
3
|
+
* it does not toast over the overlay that screen already owns.
|
|
4
|
+
*/
|
|
5
|
+
let receiveInboxFocused = false
|
|
6
|
+
|
|
7
|
+
export function setReceiveInboxFocused(focused: boolean): void {
|
|
8
|
+
receiveInboxFocused = focused
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function isReceiveInboxFocused(): boolean {
|
|
12
|
+
return receiveInboxFocused
|
|
13
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Record a merkle proof the wallet fetched itself.
|
|
3
|
+
*
|
|
4
|
+
* The toolbox's own route (`updateProvenTxReqWithNewProvenTx`) needs a
|
|
5
|
+
* proven_tx_req to hang the proof on, and normally every unproven transaction
|
|
6
|
+
* has one. A payment whose first `internalizeAction` failed half-way and was
|
|
7
|
+
* then retried down the toolbox's merge path does not: the merge adds the
|
|
8
|
+
* output but never creates a req (toolbox 2.4.3, `mergedInternalize`). Such a
|
|
9
|
+
* row is invisible to TaskCheckForProofs and used to make Refresh throw. With
|
|
10
|
+
* no req, the proof is written directly: a proven_tx row (the toolbox's own
|
|
11
|
+
* `findOrInsertProvenTx` shape) and the transaction promoted to `completed`.
|
|
12
|
+
*/
|
|
13
|
+
import type {
|
|
14
|
+
TableProvenTx,
|
|
15
|
+
TableProvenTxReq,
|
|
16
|
+
TableTransaction
|
|
17
|
+
} from '@bsv/wallet-toolbox-mobile/out/src/storage/schema/tables'
|
|
18
|
+
import type { UpdateProvenTxReqWithNewProvenTxArgs } from '@bsv/wallet-toolbox-mobile/out/src/sdk/WalletStorage.interfaces'
|
|
19
|
+
|
|
20
|
+
export interface ProofStorage {
|
|
21
|
+
findProvenTxReqs(args: {
|
|
22
|
+
partial: { txid: string }
|
|
23
|
+
}): Promise<Pick<TableProvenTxReq, 'provenTxReqId' | 'status' | 'attempts' | 'history'>[]>
|
|
24
|
+
updateProvenTxReqWithNewProvenTx(args: UpdateProvenTxReqWithNewProvenTxArgs): Promise<unknown>
|
|
25
|
+
findTransactions(args: {
|
|
26
|
+
partial: { txid: string }
|
|
27
|
+
noRawTx?: boolean
|
|
28
|
+
}): Promise<Pick<TableTransaction, 'transactionId' | 'status'>[]>
|
|
29
|
+
findProvenTxs(args: { partial: { txid: string } }): Promise<Pick<TableProvenTx, 'provenTxId'>[]>
|
|
30
|
+
insertProvenTx(tx: TableProvenTx): Promise<number>
|
|
31
|
+
updateTransaction(id: number, update: Partial<TableTransaction>): Promise<number>
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The proven_tx columns a BUMP yields — see `provenTxFromBump`. */
|
|
35
|
+
export interface ProofFields {
|
|
36
|
+
index: number
|
|
37
|
+
height: number
|
|
38
|
+
blockHash: string
|
|
39
|
+
merklePath: number[]
|
|
40
|
+
merkleRoot: string
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export type RecordProofOutcome = 'via-req' | 'direct'
|
|
44
|
+
|
|
45
|
+
export async function recordProof(
|
|
46
|
+
storage: ProofStorage,
|
|
47
|
+
args: {
|
|
48
|
+
txid: string
|
|
49
|
+
proof: ProofFields
|
|
50
|
+
/** Only called on the direct path: the proven_tx row needs the raw bytes and an internalized row may hold none. */
|
|
51
|
+
fetchRawTx: () => Promise<number[]>
|
|
52
|
+
}
|
|
53
|
+
): Promise<RecordProofOutcome> {
|
|
54
|
+
const { txid, proof } = args
|
|
55
|
+
const reqs = await storage.findProvenTxReqs({ partial: { txid } })
|
|
56
|
+
if (reqs.length > 0) {
|
|
57
|
+
const req = reqs[0]
|
|
58
|
+
await storage.updateProvenTxReqWithNewProvenTx({
|
|
59
|
+
provenTxReqId: req.provenTxReqId,
|
|
60
|
+
status: req.status,
|
|
61
|
+
txid,
|
|
62
|
+
attempts: req.attempts,
|
|
63
|
+
history: req.history,
|
|
64
|
+
...proof
|
|
65
|
+
})
|
|
66
|
+
return 'via-req'
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const txs = await storage.findTransactions({ partial: { txid }, noRawTx: true })
|
|
70
|
+
if (txs.length === 0) throw new Error('No record found for this transaction')
|
|
71
|
+
|
|
72
|
+
const pending = txs.filter(t => t.status !== 'completed')
|
|
73
|
+
if (pending.length === 0) return 'direct'
|
|
74
|
+
|
|
75
|
+
let provenTxId = (await storage.findProvenTxs({ partial: { txid } }))[0]?.provenTxId
|
|
76
|
+
if (provenTxId === undefined) {
|
|
77
|
+
const now = new Date()
|
|
78
|
+
provenTxId = await storage.insertProvenTx({
|
|
79
|
+
created_at: now,
|
|
80
|
+
updated_at: now,
|
|
81
|
+
provenTxId: 0,
|
|
82
|
+
txid,
|
|
83
|
+
rawTx: await args.fetchRawTx(),
|
|
84
|
+
...proof
|
|
85
|
+
})
|
|
86
|
+
}
|
|
87
|
+
for (const tx of pending) {
|
|
88
|
+
await storage.updateTransaction(tx.transactionId, { status: 'completed', provenTxId })
|
|
89
|
+
}
|
|
90
|
+
return 'direct'
|
|
91
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure gate for refreshProof's "not on chain → mark failed" path.
|
|
3
|
+
* Offline-queued payments must not be failed: that releases inputs the
|
|
4
|
+
* payee still holds and can double-spend the person we just paid.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
const IN_FLIGHT = new Set(['sending', 'unproven', 'nosend', 'unprocessed', 'unsigned', 'nonfinal'])
|
|
8
|
+
|
|
9
|
+
/** Matches the monitor's abandonedMsecs. */
|
|
10
|
+
const STUCK_AFTER_MS = 5 * 60 * 1000
|
|
11
|
+
|
|
12
|
+
export type OfflineRefreshStatus =
|
|
13
|
+
| 'queued'
|
|
14
|
+
| 'posting'
|
|
15
|
+
| 'sent'
|
|
16
|
+
| 'rejected'
|
|
17
|
+
| 'acknowledged'
|
|
18
|
+
// Held back deliberately, never released for broadcast. Like queued and
|
|
19
|
+
// posting, a Refresh must not decide such a transaction has failed.
|
|
20
|
+
| 'parked'
|
|
21
|
+
|
|
22
|
+
export function shouldFailUnprovenTx(args: {
|
|
23
|
+
offlineStatus?: OfflineRefreshStatus
|
|
24
|
+
txStatus: string
|
|
25
|
+
updatedAtMs: number
|
|
26
|
+
nowMs: number
|
|
27
|
+
}): 'pending' | 'failed' {
|
|
28
|
+
if (args.offlineStatus === 'queued' || args.offlineStatus === 'posting' || args.offlineStatus === 'parked') {
|
|
29
|
+
return 'pending'
|
|
30
|
+
}
|
|
31
|
+
if (!IN_FLIGHT.has(args.txStatus)) return 'pending'
|
|
32
|
+
if (args.updatedAtMs && args.nowMs - args.updatedAtMs < STUCK_AFTER_MS) return 'pending'
|
|
33
|
+
return 'failed'
|
|
34
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The background address sweep.
|
|
3
|
+
*
|
|
4
|
+
* "Get paid → a conventional wallet" is: show the address, and money appears.
|
|
5
|
+
* That means the sweep cannot live in a screen — the screen is exactly what the
|
|
6
|
+
* user no longer has to visit — so this module is the callable pass and
|
|
7
|
+
* WalletContext owns its lifecycle, beside the localpay retry loop that already
|
|
8
|
+
* runs there.
|
|
9
|
+
*
|
|
10
|
+
* Every bound is deliberate and tested: see shouldSweepNow for when a pass may
|
|
11
|
+
* run at all, and pay/watchlist.ts for which addresses it may touch.
|
|
12
|
+
*/
|
|
13
|
+
import { sweepAddress, type AddressRailWallet, type WocConfig } from './rails/address'
|
|
14
|
+
import { getWatchlist, touchWatched, type KVStorage } from './watchlist'
|
|
15
|
+
|
|
16
|
+
/** One poll every 30s — an order of magnitude cheaper than the 3s screen poll it replaces. */
|
|
17
|
+
export const SWEEP_INTERVAL_MS = 30_000
|
|
18
|
+
|
|
19
|
+
export interface SweepOutcome {
|
|
20
|
+
address: string
|
|
21
|
+
importedSatoshis: number
|
|
22
|
+
failureCount: number
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Whether a pass may run right now.
|
|
27
|
+
*
|
|
28
|
+
* Pure so the four conditions are stated in one place and tested: no polling
|
|
29
|
+
* before the wallet exists, none in the background, none offline, and never two
|
|
30
|
+
* at once (each pass writes to the wallet).
|
|
31
|
+
*/
|
|
32
|
+
export function shouldSweepNow(state: {
|
|
33
|
+
walletBuilt: boolean
|
|
34
|
+
appActive: boolean
|
|
35
|
+
online: boolean
|
|
36
|
+
inFlight: boolean
|
|
37
|
+
}): boolean {
|
|
38
|
+
return state.walletBuilt && state.appActive && state.online && !state.inFlight
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export async function runSweep(args: {
|
|
42
|
+
wallet: AddressRailWallet
|
|
43
|
+
storage: KVStorage
|
|
44
|
+
adminOriginator: string
|
|
45
|
+
woc: WocConfig
|
|
46
|
+
}): Promise<SweepOutcome[]> {
|
|
47
|
+
const { wallet, storage, adminOriginator, woc } = args
|
|
48
|
+
const outcomes: SweepOutcome[] = []
|
|
49
|
+
|
|
50
|
+
for (const watched of await getWatchlist(storage)) {
|
|
51
|
+
try {
|
|
52
|
+
const { importedSatoshis, failureCount, foundOnChain } = await sweepAddress({
|
|
53
|
+
wallet,
|
|
54
|
+
adminOriginator,
|
|
55
|
+
woc,
|
|
56
|
+
address: watched.address,
|
|
57
|
+
derivationPrefix: watched.derivationPrefix
|
|
58
|
+
})
|
|
59
|
+
outcomes.push({ address: watched.address, importedSatoshis, failureCount })
|
|
60
|
+
// Money arrived here once, so it may again: keep this address alive
|
|
61
|
+
// rather than retiring it the moment it pays out. A funded address whose
|
|
62
|
+
// import failed must stay watched too, or a bad BEEF fetch TTL-drops it.
|
|
63
|
+
if (importedSatoshis > 0 || foundOnChain) await touchWatched(storage, watched.address)
|
|
64
|
+
} catch {
|
|
65
|
+
// A dead WoC host or a locked wallet must not stop the rest of the pass.
|
|
66
|
+
// The entry stays watched and the next pass retries it.
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
return outcomes
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function sweptTotal(outcomes: SweepOutcome[]): number {
|
|
74
|
+
return outcomes.reduce((sum, o) => sum + o.importedSatoshis, 0)
|
|
75
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { Transaction } from '@bsv/sdk'
|
|
2
|
+
|
|
3
|
+
export function satoshisFromToken(token: {
|
|
4
|
+
transaction: number[]
|
|
5
|
+
outputIndex?: number
|
|
6
|
+
amount?: number
|
|
7
|
+
}): { satoshis: number; claimedAgrees: boolean } | undefined {
|
|
8
|
+
try {
|
|
9
|
+
const tx = Transaction.fromAtomicBEEF(token.transaction)
|
|
10
|
+
const satoshis = tx.outputs[token.outputIndex ?? 0]?.satoshis
|
|
11
|
+
if (typeof satoshis !== 'number' || satoshis < 0) return undefined
|
|
12
|
+
const claimed = token.amount
|
|
13
|
+
const claimedAgrees = typeof claimed !== 'number' || !Number.isFinite(claimed) || claimed === satoshis
|
|
14
|
+
return { satoshis, claimedAgrees }
|
|
15
|
+
} catch {
|
|
16
|
+
return undefined
|
|
17
|
+
}
|
|
18
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Map a wallet/engine error onto a user-facing i18n key.
|
|
3
|
+
*
|
|
4
|
+
* `WERR_REVIEW_ACTIONS` means a stuck reservation or invalid-change record —
|
|
5
|
+
* Check Wallet is the repair, not retrying the send.
|
|
6
|
+
*/
|
|
7
|
+
export function userFacingPayError(e: unknown): { key: string; offerWalletCheck: boolean } {
|
|
8
|
+
const message =
|
|
9
|
+
e instanceof Error
|
|
10
|
+
? e.message
|
|
11
|
+
: typeof e === 'string'
|
|
12
|
+
? e
|
|
13
|
+
: String((e as { message?: unknown } | undefined)?.message ?? e ?? '')
|
|
14
|
+
if (/WERR_REVIEW_ACTIONS|review actions/i.test(message)) {
|
|
15
|
+
return { key: 'error_review_actions', offerWalletCheck: true }
|
|
16
|
+
}
|
|
17
|
+
return { key: 'unknown_error', offerWalletCheck: false }
|
|
18
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which addresses the background sweeper is allowed to poll.
|
|
3
|
+
*
|
|
4
|
+
* The sweeper never derives an address on its own initiative: it polls exactly
|
|
5
|
+
* the addresses this app has put in front of a user, because those are the only
|
|
6
|
+
* ones anyone could have been asked to pay. That is what makes the background
|
|
7
|
+
* work bounded — an unbounded look-back would be a WoC request per day per
|
|
8
|
+
* poll, for money that was never requested.
|
|
9
|
+
*
|
|
10
|
+
* Bounds (spec open question 5):
|
|
11
|
+
* · at most MAX_WATCHED addresses, most-recently-active kept
|
|
12
|
+
* · never-swept addresses live WATCH_UNSWEPT_TTL_MS (MAX_WATCH_DAYS)
|
|
13
|
+
* · WATCH_TTL_MS still names the 24h imported-activity window
|
|
14
|
+
* · never older than MAX_WATCH_DAYS by its issue date
|
|
15
|
+
*
|
|
16
|
+
* A dropped address is not lost money: the Get paid → conventional wallet view
|
|
17
|
+
* re-registers today's address every time it is opened, and the earlier-day
|
|
18
|
+
* recovery stepper can reach back MAX_RECOVERY_DAYS and sweep by hand.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
export const WATCHLIST_KEY = 'pay_address_watchlist'
|
|
22
|
+
export const MAX_WATCHED = 8
|
|
23
|
+
export const WATCH_TTL_MS = 86_400_000
|
|
24
|
+
export const MAX_WATCH_DAYS = 7
|
|
25
|
+
export const WATCH_UNSWEPT_TTL_MS = MAX_WATCH_DAYS * 86_400_000
|
|
26
|
+
|
|
27
|
+
export interface WatchedAddress {
|
|
28
|
+
address: string
|
|
29
|
+
/** The YYYY-MM-DD the address was derived for. */
|
|
30
|
+
date: string
|
|
31
|
+
/** base64 of `date` — carried so a sweep needs no re-derivation. */
|
|
32
|
+
derivationPrefix: string
|
|
33
|
+
/** ISO 8601. The later of issue and last successful sweep. */
|
|
34
|
+
lastActivityAt: string
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface KVStorage {
|
|
38
|
+
getKeyValue(k: string): Promise<string | undefined>
|
|
39
|
+
setKeyValue(k: string, v: string): Promise<void>
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Same discipline as localpay/pending.ts: every read-modify-write on the
|
|
43
|
+
// single storage key runs through one chain, or a write built from a stale read
|
|
44
|
+
// silently drops entries.
|
|
45
|
+
let queueLock: Promise<unknown> = Promise.resolve()
|
|
46
|
+
|
|
47
|
+
function withQueueLock<T>(fn: () => Promise<T>): Promise<T> {
|
|
48
|
+
const run = queueLock.then(fn, fn)
|
|
49
|
+
queueLock = run.catch(() => undefined)
|
|
50
|
+
return run
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const DAY_MS = 86_400_000
|
|
54
|
+
|
|
55
|
+
export function pruneWatchlist(list: WatchedAddress[], nowMs: number): WatchedAddress[] {
|
|
56
|
+
// The date cap is a CALENDAR-day comparison, not a rolling MAX_WATCH_DAYS ×
|
|
57
|
+
// 24h window. `date` is a midnight-UTC day stamp while nowMs carries a time
|
|
58
|
+
// of day, so a naive `nowMs - MAX_WATCH_DAYS * DAY_MS` lands part-way
|
|
59
|
+
// through day 7 and drops an address issued that morning — money issued
|
|
60
|
+
// inside the advertised look-back would stop being swept. Floor now to its
|
|
61
|
+
// own UTC midnight first, so an address dated exactly MAX_WATCH_DAYS ago is
|
|
62
|
+
// still swept for the whole of that day.
|
|
63
|
+
const todayStart = Math.floor(nowMs / DAY_MS) * DAY_MS
|
|
64
|
+
const oldestAllowed = todayStart - MAX_WATCH_DAYS * DAY_MS
|
|
65
|
+
return list
|
|
66
|
+
.filter(e => {
|
|
67
|
+
const activity = Date.parse(e.lastActivityAt)
|
|
68
|
+
if (!Number.isFinite(activity) || nowMs - activity > WATCH_UNSWEPT_TTL_MS) return false
|
|
69
|
+
const issued = Date.parse(`${e.date}T00:00:00Z`)
|
|
70
|
+
if (!Number.isFinite(issued) || issued < oldestAllowed) return false
|
|
71
|
+
return true
|
|
72
|
+
})
|
|
73
|
+
.sort((a, b) => Date.parse(b.lastActivityAt) - Date.parse(a.lastActivityAt))
|
|
74
|
+
.slice(0, MAX_WATCHED)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async function readAll(storage: KVStorage): Promise<WatchedAddress[]> {
|
|
78
|
+
const raw = await storage.getKeyValue(WATCHLIST_KEY)
|
|
79
|
+
if (!raw) return []
|
|
80
|
+
try {
|
|
81
|
+
const parsed = JSON.parse(raw) as unknown
|
|
82
|
+
return Array.isArray(parsed) ? (parsed as WatchedAddress[]) : []
|
|
83
|
+
} catch {
|
|
84
|
+
return []
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function writeAll(storage: KVStorage, list: WatchedAddress[]): Promise<void> {
|
|
89
|
+
await storage.setKeyValue(WATCHLIST_KEY, JSON.stringify(list))
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Register (or refresh) an address the user has just been shown. */
|
|
93
|
+
export async function watchAddress(storage: KVStorage, entry: Omit<WatchedAddress, 'lastActivityAt'>): Promise<void> {
|
|
94
|
+
return withQueueLock(async () => {
|
|
95
|
+
const now = Date.now()
|
|
96
|
+
const existing = (await readAll(storage)).filter(e => e.address !== entry.address)
|
|
97
|
+
const next = pruneWatchlist([{ ...entry, lastActivityAt: new Date(now).toISOString() }, ...existing], now)
|
|
98
|
+
await writeAll(storage, next)
|
|
99
|
+
})
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The addresses the sweeper may poll right now. Prunes as a side effect of reading. */
|
|
103
|
+
export async function getWatchlist(storage: KVStorage): Promise<WatchedAddress[]> {
|
|
104
|
+
return pruneWatchlist(await readAll(storage), Date.now())
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Extend an address's life — called after a successful sweep, so more can arrive. */
|
|
108
|
+
export async function touchWatched(storage: KVStorage, address: string): Promise<void> {
|
|
109
|
+
return withQueueLock(async () => {
|
|
110
|
+
const all = await readAll(storage)
|
|
111
|
+
if (!all.some(e => e.address === address)) return
|
|
112
|
+
const now = Date.now()
|
|
113
|
+
const next = all.map(e => (e.address === address ? { ...e, lastActivityAt: new Date(now).toISOString() } : e))
|
|
114
|
+
await writeAll(storage, pruneWatchlist(next, now))
|
|
115
|
+
})
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export async function unwatchAddress(storage: KVStorage, address: string): Promise<void> {
|
|
119
|
+
return withQueueLock(async () => {
|
|
120
|
+
const all = await readAll(storage)
|
|
121
|
+
await writeAll(
|
|
122
|
+
storage,
|
|
123
|
+
all.filter(e => e.address !== address)
|
|
124
|
+
)
|
|
125
|
+
})
|
|
126
|
+
}
|