@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,454 @@
|
|
|
1
|
+
import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
|
|
2
|
+
import { AppState } from 'react-native'
|
|
3
|
+
import * as SecureStore from 'expo-secure-store'
|
|
4
|
+
import { WalletClient, PrivateKey, ProtoWallet, Utils } from '@bsv/sdk'
|
|
5
|
+
import type { WalletProtocol } from '@bsv/sdk'
|
|
6
|
+
import connectionStore from '../stores/ConnectionStore'
|
|
7
|
+
import type { Connection } from '../stores/ConnectionStore'
|
|
8
|
+
|
|
9
|
+
// ── Constants ─────────────────────────────────────────────────────────────────
|
|
10
|
+
|
|
11
|
+
export const IMPLEMENTED_METHODS = new Set([
|
|
12
|
+
'getPublicKey', 'listOutputs', 'listCertificates', 'createAction', 'signAction',
|
|
13
|
+
'listActions', 'internalizeAction', 'acquireCertificate',
|
|
14
|
+
'relinquishCertificate', 'revealCounterpartyKeyLinkage', 'createHmac', 'verifyHmac',
|
|
15
|
+
'encrypt', 'decrypt', 'createSignature', 'verifySignature',
|
|
16
|
+
])
|
|
17
|
+
|
|
18
|
+
const NAV_TIMEOUT_MS = 5 * 60 * 1000 // 5 min — navigated away from pair screen
|
|
19
|
+
const APP_STATE_TIMEOUT_MS = 12 * 60 * 1000 // 12 min — app backgrounded
|
|
20
|
+
|
|
21
|
+
export const lastSeqKey = (topic: string) => `wallet_pairing_lastseq_${topic}`
|
|
22
|
+
|
|
23
|
+
// ── Types ─────────────────────────────────────────────────────────────────────
|
|
24
|
+
|
|
25
|
+
export type ConnectionStatus = 'idle' | 'connecting' | 'connected' | 'disconnected' | 'error'
|
|
26
|
+
|
|
27
|
+
type RpcRequest = { id: string; seq: number; method: string; params: unknown }
|
|
28
|
+
type RpcResponse = { id: string; seq: number; result?: unknown; error?: { code: number; message: string } }
|
|
29
|
+
type WireEnvelope = { topic: string; ciphertext: string; mobileIdentityKey?: string }
|
|
30
|
+
|
|
31
|
+
export interface SessionMeta {
|
|
32
|
+
topic: string
|
|
33
|
+
origin: string
|
|
34
|
+
relay: string
|
|
35
|
+
backendIdentityKey: string
|
|
36
|
+
mobileIdentityKey: string
|
|
37
|
+
protocolID: WalletProtocol
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface ConnectParams {
|
|
41
|
+
topic: string
|
|
42
|
+
backendIdentityKey: string
|
|
43
|
+
protocolID: string // JSON-encoded WalletProtocol
|
|
44
|
+
origin: string
|
|
45
|
+
expiry?: string // Unix seconds — required for signature verification
|
|
46
|
+
sig?: string // base64url DER ECDSA signature
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
interface WalletConnectionContextValue {
|
|
50
|
+
status: ConnectionStatus
|
|
51
|
+
sessionMeta: SessionMeta | null
|
|
52
|
+
errorMsg: string | null
|
|
53
|
+
connect: (params: ConnectParams, wallet: WalletClient) => Promise<void>
|
|
54
|
+
reconnect: (connection: Connection, wallet: WalletClient) => Promise<void>
|
|
55
|
+
disconnect: () => void
|
|
56
|
+
startNavTimer: () => void
|
|
57
|
+
cancelNavTimer: () => void
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// ── Helpers ───────────────────────────────────────────────────────────────────
|
|
61
|
+
|
|
62
|
+
async function encryptPayload(
|
|
63
|
+
wallet: WalletClient,
|
|
64
|
+
protocolID: WalletProtocol,
|
|
65
|
+
keyID: string,
|
|
66
|
+
counterparty: string,
|
|
67
|
+
payload: string,
|
|
68
|
+
): Promise<string> {
|
|
69
|
+
const plaintext = Array.from(new TextEncoder().encode(payload))
|
|
70
|
+
const { ciphertext } = await wallet.encrypt({ protocolID, keyID, counterparty, plaintext })
|
|
71
|
+
return Buffer.from(ciphertext).toString('base64url')
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function decryptPayload(
|
|
75
|
+
wallet: WalletClient,
|
|
76
|
+
protocolID: WalletProtocol,
|
|
77
|
+
keyID: string,
|
|
78
|
+
counterparty: string,
|
|
79
|
+
ciphertextB64: string,
|
|
80
|
+
): Promise<string> {
|
|
81
|
+
const ciphertext = Array.from(Buffer.from(ciphertextB64, 'base64url'))
|
|
82
|
+
const { plaintext } = await wallet.decrypt({ protocolID, keyID, counterparty, ciphertext })
|
|
83
|
+
return new TextDecoder().decode(new Uint8Array(plaintext))
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function verifyQrSignature(params: ConnectParams): Promise<void> {
|
|
87
|
+
if (!params.sig) throw new Error('QR code is not signed — do not connect')
|
|
88
|
+
const anyoneWallet = new ProtoWallet(new PrivateKey(1))
|
|
89
|
+
const payload = Array.from(new TextEncoder().encode(
|
|
90
|
+
`${params.topic}|${params.backendIdentityKey}|${params.origin}|${params.expiry}`
|
|
91
|
+
))
|
|
92
|
+
const signature = Utils.toArray(params.sig.replace(/-/g, '+').replace(/_/g, '/'), 'base64') as number[]
|
|
93
|
+
const { valid } = await anyoneWallet.verifySignature({
|
|
94
|
+
data: payload,
|
|
95
|
+
signature,
|
|
96
|
+
protocolID: [0, 'qr pairing'],
|
|
97
|
+
keyID: params.topic,
|
|
98
|
+
counterparty: params.backendIdentityKey,
|
|
99
|
+
})
|
|
100
|
+
if (!valid) throw new Error('QR code signature is invalid — do not connect')
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function fetchRelay(origin: string, topic: string): Promise<string> {
|
|
104
|
+
const res = await fetch(`${origin}/api/session/${topic}`)
|
|
105
|
+
if (!res.ok) throw new Error(`Could not fetch session from origin: HTTP ${res.status}`)
|
|
106
|
+
const data = await res.json() as { relay?: string }
|
|
107
|
+
if (!data.relay) throw new Error('Origin server did not return a relay URL')
|
|
108
|
+
return data.relay
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// ── Context ───────────────────────────────────────────────────────────────────
|
|
112
|
+
|
|
113
|
+
const WalletConnectionContext = createContext<WalletConnectionContextValue | null>(null)
|
|
114
|
+
|
|
115
|
+
export function useWalletConnection() {
|
|
116
|
+
const ctx = useContext(WalletConnectionContext)
|
|
117
|
+
if (!ctx) throw new Error('useWalletConnection must be used within WalletConnectionProvider')
|
|
118
|
+
return ctx
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
interface WalletConnectionProviderProps {
|
|
122
|
+
children: React.ReactNode
|
|
123
|
+
/** Sent to the desktop session as `walletMeta.name` during pairing. Host
|
|
124
|
+
* apps should pass their own display name (see UserContext's `appName`
|
|
125
|
+
* for the equivalent pattern) — defaults to a generic value so this
|
|
126
|
+
* package makes no assumption about which app is embedding it. */
|
|
127
|
+
walletName?: string
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export function WalletConnectionProvider({ children, walletName = 'App' }: WalletConnectionProviderProps) {
|
|
131
|
+
const [status, setStatus] = useState<ConnectionStatus>('idle')
|
|
132
|
+
const [sessionMeta, setSessionMeta] = useState<SessionMeta | null>(null)
|
|
133
|
+
const [errorMsg, setErrorMsg] = useState<string | null>(null)
|
|
134
|
+
|
|
135
|
+
// Internal refs — changes here don't trigger re-renders
|
|
136
|
+
const wsRef = useRef<WebSocket | null>(null)
|
|
137
|
+
const lastSeqRef = useRef(0)
|
|
138
|
+
const navTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
|
139
|
+
const appStateTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
|
140
|
+
const intentionalCloseRef = useRef(false)
|
|
141
|
+
// Snapshot of sessionMeta for use inside async WS callbacks
|
|
142
|
+
const sessionMetaRef = useRef<SessionMeta | null>(null)
|
|
143
|
+
useEffect(() => { sessionMetaRef.current = sessionMeta }, [sessionMeta])
|
|
144
|
+
|
|
145
|
+
// ── Disconnect ─────────────────────────────────────────────────────────────
|
|
146
|
+
|
|
147
|
+
const disconnect = useCallback(() => {
|
|
148
|
+
const topic = sessionMetaRef.current?.topic
|
|
149
|
+
if (topic) {
|
|
150
|
+
void SecureStore.setItemAsync(lastSeqKey(topic), String(lastSeqRef.current))
|
|
151
|
+
connectionStore.setStatus(topic, 'disconnected')
|
|
152
|
+
}
|
|
153
|
+
intentionalCloseRef.current = true
|
|
154
|
+
const ws = wsRef.current
|
|
155
|
+
wsRef.current = null
|
|
156
|
+
ws?.close()
|
|
157
|
+
if (navTimerRef.current) { clearTimeout(navTimerRef.current); navTimerRef.current = null }
|
|
158
|
+
if (appStateTimerRef.current) { clearTimeout(appStateTimerRef.current); appStateTimerRef.current = null }
|
|
159
|
+
setSessionMeta(null)
|
|
160
|
+
setStatus('idle')
|
|
161
|
+
}, [])
|
|
162
|
+
|
|
163
|
+
// ── Nav timer (pair screen lifecycle) ─────────────────────────────────────
|
|
164
|
+
|
|
165
|
+
const startNavTimer = useCallback(() => {
|
|
166
|
+
if (navTimerRef.current) clearTimeout(navTimerRef.current)
|
|
167
|
+
navTimerRef.current = setTimeout(() => {
|
|
168
|
+
navTimerRef.current = null
|
|
169
|
+
if (wsRef.current) disconnect()
|
|
170
|
+
}, NAV_TIMEOUT_MS)
|
|
171
|
+
}, [disconnect])
|
|
172
|
+
|
|
173
|
+
const cancelNavTimer = useCallback(() => {
|
|
174
|
+
if (navTimerRef.current) { clearTimeout(navTimerRef.current); navTimerRef.current = null }
|
|
175
|
+
}, [])
|
|
176
|
+
|
|
177
|
+
// ── AppState timer (app backgrounded) ────────────────────────────────────
|
|
178
|
+
|
|
179
|
+
useEffect(() => {
|
|
180
|
+
const sub = AppState.addEventListener('change', nextState => {
|
|
181
|
+
if (nextState === 'background' || nextState === 'inactive') {
|
|
182
|
+
if (appStateTimerRef.current) clearTimeout(appStateTimerRef.current)
|
|
183
|
+
appStateTimerRef.current = setTimeout(() => {
|
|
184
|
+
appStateTimerRef.current = null
|
|
185
|
+
if (wsRef.current) disconnect()
|
|
186
|
+
}, APP_STATE_TIMEOUT_MS)
|
|
187
|
+
} else if (nextState === 'active') {
|
|
188
|
+
if (appStateTimerRef.current) { clearTimeout(appStateTimerRef.current); appStateTimerRef.current = null }
|
|
189
|
+
}
|
|
190
|
+
})
|
|
191
|
+
return () => sub.remove()
|
|
192
|
+
}, [disconnect])
|
|
193
|
+
|
|
194
|
+
// ── RPC dispatch ──────────────────────────────────────────────────────────
|
|
195
|
+
|
|
196
|
+
async function handleRpc(
|
|
197
|
+
request: RpcRequest,
|
|
198
|
+
meta: SessionMeta,
|
|
199
|
+
ws: WebSocket,
|
|
200
|
+
wallet: WalletClient,
|
|
201
|
+
): Promise<void> {
|
|
202
|
+
const sendResponse = async (response: RpcResponse) => {
|
|
203
|
+
try {
|
|
204
|
+
const ciphertext = await encryptPayload(
|
|
205
|
+
wallet, meta.protocolID, meta.topic, meta.backendIdentityKey, JSON.stringify(response),
|
|
206
|
+
)
|
|
207
|
+
ws.send(JSON.stringify({ topic: meta.topic, ciphertext } satisfies WireEnvelope))
|
|
208
|
+
} catch (err) {
|
|
209
|
+
console.warn('[WalletConnection] sendResponse failed:', err)
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
if (!IMPLEMENTED_METHODS.has(request.method)) {
|
|
214
|
+
await sendResponse({ id: request.id, seq: request.seq,
|
|
215
|
+
error: { code: 501, message: `Method "${request.method}" is not implemented` } })
|
|
216
|
+
return
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Call wallet method directly — WalletPermissionsManager handles all
|
|
220
|
+
// permission prompts (spending, protocol, basket, certificate) via its
|
|
221
|
+
// own callbacks and the existing wallet permission modals.
|
|
222
|
+
let result: unknown
|
|
223
|
+
let error: { code: number; message: string } | undefined
|
|
224
|
+
try {
|
|
225
|
+
type WFn = (p: unknown) => Promise<unknown>
|
|
226
|
+
result = await (wallet as unknown as Record<string, WFn>)[request.method](request.params)
|
|
227
|
+
} catch (err) {
|
|
228
|
+
const message = err instanceof Error ? err.message : 'Wallet error'
|
|
229
|
+
// WalletPermissionsManager throws when user denies — surface as rejection
|
|
230
|
+
const code = message.includes('denied') || message.includes('rejected') ? 4001 : 500
|
|
231
|
+
error = { code, message }
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
await sendResponse(error
|
|
235
|
+
? { id: request.id, seq: request.seq, error }
|
|
236
|
+
: { id: request.id, seq: request.seq, result },
|
|
237
|
+
)
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// ── Shared WS message / event wiring ─────────────────────────────────────
|
|
241
|
+
|
|
242
|
+
function wireSocket(
|
|
243
|
+
ws: WebSocket,
|
|
244
|
+
wallet: WalletClient,
|
|
245
|
+
meta: SessionMeta,
|
|
246
|
+
initialSeq: number,
|
|
247
|
+
onFirstMessage: () => void,
|
|
248
|
+
) {
|
|
249
|
+
wsRef.current = ws
|
|
250
|
+
lastSeqRef.current = initialSeq
|
|
251
|
+
let firstMessageFired = false
|
|
252
|
+
|
|
253
|
+
ws.onmessage = async event => {
|
|
254
|
+
try {
|
|
255
|
+
const envelope = JSON.parse(event.data as string) as WireEnvelope
|
|
256
|
+
if (!envelope.ciphertext) return
|
|
257
|
+
|
|
258
|
+
let plaintext: string
|
|
259
|
+
try {
|
|
260
|
+
plaintext = await decryptPayload(
|
|
261
|
+
wallet, meta.protocolID, meta.topic, meta.backendIdentityKey, envelope.ciphertext,
|
|
262
|
+
)
|
|
263
|
+
} catch (err) {
|
|
264
|
+
console.warn('[WalletConnection] decryptPayload failed:', err)
|
|
265
|
+
return
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
const msg = JSON.parse(plaintext) as RpcRequest | RpcResponse
|
|
269
|
+
if (typeof msg.seq !== 'number' || msg.seq <= lastSeqRef.current) {
|
|
270
|
+
console.warn('[WalletConnection] dropping message: seq', msg.seq, '<= lastSeq', lastSeqRef.current)
|
|
271
|
+
return
|
|
272
|
+
}
|
|
273
|
+
lastSeqRef.current = msg.seq
|
|
274
|
+
|
|
275
|
+
if (!firstMessageFired) {
|
|
276
|
+
firstMessageFired = true
|
|
277
|
+
onFirstMessage()
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
if ('method' in msg && msg.method === 'pairing_ack') return
|
|
281
|
+
if ('method' in msg && msg.id) {
|
|
282
|
+
void handleRpc(msg as RpcRequest, meta, ws, wallet)
|
|
283
|
+
}
|
|
284
|
+
} catch {
|
|
285
|
+
// malformed outer envelope — drop silently
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
ws.onerror = () => {
|
|
290
|
+
setErrorMsg('WebSocket connection failed')
|
|
291
|
+
setStatus('error')
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
ws.onclose = () => {
|
|
295
|
+
const wasIntentional = intentionalCloseRef.current
|
|
296
|
+
intentionalCloseRef.current = false
|
|
297
|
+
|
|
298
|
+
// Don't change the state if this is not the current ws
|
|
299
|
+
if (!wasIntentional && wsRef.current !== null && wsRef.current !== ws) {
|
|
300
|
+
return
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
if (!wasIntentional) {
|
|
304
|
+
const topic = sessionMetaRef.current?.topic
|
|
305
|
+
if (topic) {
|
|
306
|
+
void SecureStore.setItemAsync(lastSeqKey(topic), String(lastSeqRef.current))
|
|
307
|
+
connectionStore.setStatus(topic, 'disconnected')
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
wsRef.current = null
|
|
311
|
+
lastSeqRef.current = 0
|
|
312
|
+
if (navTimerRef.current) { clearTimeout(navTimerRef.current); navTimerRef.current = null }
|
|
313
|
+
if (appStateTimerRef.current) { clearTimeout(appStateTimerRef.current); appStateTimerRef.current = null }
|
|
314
|
+
setSessionMeta(null)
|
|
315
|
+
// Don't override the 'idle' status that disconnect() already set
|
|
316
|
+
if (!wasIntentional) {
|
|
317
|
+
if (firstMessageFired) {
|
|
318
|
+
setErrorMsg('Connection closed — the desktop session ended')
|
|
319
|
+
setStatus('disconnected')
|
|
320
|
+
} else {
|
|
321
|
+
setErrorMsg('Could not reach the desktop — check that the browser tab is still open')
|
|
322
|
+
setStatus('error')
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// ── connect (fresh pairing) ───────────────────────────────────────────────
|
|
329
|
+
|
|
330
|
+
const connect = useCallback(async (params: ConnectParams, wallet: WalletClient) => {
|
|
331
|
+
setStatus('connecting')
|
|
332
|
+
setErrorMsg(null)
|
|
333
|
+
|
|
334
|
+
let relay: string
|
|
335
|
+
try {
|
|
336
|
+
// Verify QR signature before trusting the origin or opening any connection
|
|
337
|
+
await verifyQrSignature(params)
|
|
338
|
+
|
|
339
|
+
// Fetch relay URL from origin over HTTPS — TLS cert is the trust anchor
|
|
340
|
+
relay = await fetchRelay(params.origin, params.topic)
|
|
341
|
+
} catch (err) {
|
|
342
|
+
setErrorMsg(err instanceof Error ? err.message : 'Connection failed')
|
|
343
|
+
setStatus('error')
|
|
344
|
+
throw err
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
const protocolID = JSON.parse(params.protocolID) as WalletProtocol
|
|
348
|
+
const { publicKey: mobileIdentityKey } = await wallet.getPublicKey({ identityKey: true })
|
|
349
|
+
|
|
350
|
+
const meta: SessionMeta = {
|
|
351
|
+
topic: params.topic, origin: params.origin, relay,
|
|
352
|
+
backendIdentityKey: params.backendIdentityKey, mobileIdentityKey,
|
|
353
|
+
protocolID,
|
|
354
|
+
}
|
|
355
|
+
setSessionMeta(meta)
|
|
356
|
+
|
|
357
|
+
const ws = new WebSocket(`${relay}/ws?topic=${params.topic}&role=mobile`)
|
|
358
|
+
|
|
359
|
+
ws.onopen = async () => {
|
|
360
|
+
try {
|
|
361
|
+
const payload = JSON.stringify({
|
|
362
|
+
id: crypto.randomUUID(), seq: 1, method: 'pairing_approved',
|
|
363
|
+
params: {
|
|
364
|
+
mobileIdentityKey,
|
|
365
|
+
walletMeta: { name: walletName, platform: 'mobile' },
|
|
366
|
+
permissions: Array.from(IMPLEMENTED_METHODS),
|
|
367
|
+
},
|
|
368
|
+
})
|
|
369
|
+
const ciphertext = await encryptPayload(wallet, protocolID, params.topic, params.backendIdentityKey, payload)
|
|
370
|
+
ws.send(JSON.stringify({ topic: params.topic, mobileIdentityKey, ciphertext } satisfies WireEnvelope))
|
|
371
|
+
} catch {
|
|
372
|
+
setErrorMsg('Failed to send pairing message')
|
|
373
|
+
setStatus('error')
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
wireSocket(ws, wallet, meta, 0, () => {
|
|
378
|
+
connectionStore.add({
|
|
379
|
+
sessionId: params.topic, origin: params.origin, relay,
|
|
380
|
+
backendIdentityKey: params.backendIdentityKey, mobileIdentityKey,
|
|
381
|
+
protocolID: params.protocolID,
|
|
382
|
+
connectedAt: Date.now(), status: 'active',
|
|
383
|
+
})
|
|
384
|
+
setStatus('connected')
|
|
385
|
+
})
|
|
386
|
+
}, [walletName]) // eslint-disable-line react-hooks/exhaustive-deps
|
|
387
|
+
|
|
388
|
+
// ── reconnect (resume from stored session) ────────────────────────────────
|
|
389
|
+
|
|
390
|
+
const reconnect = useCallback(async (connection: Connection, wallet: WalletClient) => {
|
|
391
|
+
setStatus('connecting')
|
|
392
|
+
setErrorMsg(null)
|
|
393
|
+
|
|
394
|
+
// Fetch relay URL from origin over HTTPS — relay may have moved since last connection
|
|
395
|
+
const relay = await fetchRelay(connection.origin, connection.sessionId)
|
|
396
|
+
|
|
397
|
+
const protocolID = JSON.parse(connection.protocolID) as WalletProtocol
|
|
398
|
+
const storedSeq = await SecureStore.getItemAsync(lastSeqKey(connection.sessionId))
|
|
399
|
+
const initialSeq = storedSeq ? Number(storedSeq) : 0
|
|
400
|
+
|
|
401
|
+
const meta: SessionMeta = {
|
|
402
|
+
topic: connection.sessionId, origin: connection.origin, relay,
|
|
403
|
+
backendIdentityKey: connection.backendIdentityKey,
|
|
404
|
+
mobileIdentityKey: connection.mobileIdentityKey,
|
|
405
|
+
protocolID,
|
|
406
|
+
}
|
|
407
|
+
setSessionMeta(meta)
|
|
408
|
+
|
|
409
|
+
const ws = new WebSocket(`${relay}/ws?topic=${connection.sessionId}&role=mobile`)
|
|
410
|
+
|
|
411
|
+
ws.onopen = async () => {
|
|
412
|
+
try {
|
|
413
|
+
const payload = JSON.stringify({
|
|
414
|
+
id: crypto.randomUUID(), seq: initialSeq + 1, method: 'pairing_approved',
|
|
415
|
+
params: {
|
|
416
|
+
mobileIdentityKey: connection.mobileIdentityKey,
|
|
417
|
+
walletMeta: { name: walletName, platform: 'mobile' },
|
|
418
|
+
permissions: Array.from(IMPLEMENTED_METHODS),
|
|
419
|
+
},
|
|
420
|
+
})
|
|
421
|
+
const ciphertext = await encryptPayload(
|
|
422
|
+
wallet, protocolID, connection.sessionId, connection.backendIdentityKey, payload,
|
|
423
|
+
)
|
|
424
|
+
ws.send(JSON.stringify({
|
|
425
|
+
topic: connection.sessionId,
|
|
426
|
+
mobileIdentityKey: connection.mobileIdentityKey,
|
|
427
|
+
ciphertext,
|
|
428
|
+
} satisfies WireEnvelope))
|
|
429
|
+
} catch {
|
|
430
|
+
setErrorMsg('Failed to send reconnect message')
|
|
431
|
+
setStatus('error')
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
wireSocket(ws, wallet, meta, initialSeq, () => {
|
|
436
|
+
connectionStore.setStatus(connection.sessionId, 'active')
|
|
437
|
+
setStatus('connected')
|
|
438
|
+
})
|
|
439
|
+
}, [walletName]) // eslint-disable-line react-hooks/exhaustive-deps
|
|
440
|
+
|
|
441
|
+
// ── Provider ──────────────────────────────────────────────────────────────
|
|
442
|
+
|
|
443
|
+
const value = useMemo<WalletConnectionContextValue>(() => ({
|
|
444
|
+
status, sessionMeta, errorMsg,
|
|
445
|
+
connect, reconnect, disconnect,
|
|
446
|
+
startNavTimer, cancelNavTimer,
|
|
447
|
+
}), [status, sessionMeta, errorMsg, connect, reconnect, disconnect, startNavTimer, cancelNavTimer])
|
|
448
|
+
|
|
449
|
+
return (
|
|
450
|
+
<WalletConnectionContext.Provider value={value}>
|
|
451
|
+
{children}
|
|
452
|
+
</WalletConnectionContext.Provider>
|
|
453
|
+
)
|
|
454
|
+
}
|