@bsv/expo-wallet-toolbox 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +255 -0
- package/README.md +19 -0
- package/core/amountFormatHelpers.ts +238 -34
- package/core/backup/RemoteSyncReader.ts +2 -5
- package/core/backup/codec.ts +2 -2
- package/core/backup/push.ts +1 -1
- package/core/config.tsx +12 -5
- package/core/contacts/contactActivity.ts +153 -0
- package/core/contacts/contactCache.ts +41 -0
- package/core/contacts/contactsStore.ts +183 -0
- package/core/context/WalletContext.tsx +55 -10
- package/core/demo/demoAssets.ts +60 -0
- package/core/demo/demoLedger.ts +240 -0
- package/core/demo/demoMandalaRuntime.ts +96 -0
- package/core/demo/demoMode.ts +38 -0
- package/core/demo/demoWallet.ts +25 -0
- package/core/demo/index.ts +26 -0
- package/core/demo/useDemo.ts +59 -0
- package/core/headers/OfflineFirstChaintracks.ts +52 -14
- package/core/headers/headerStore.ts +7 -10
- package/core/i18n/translations.tsx +1234 -74
- package/core/identity/contactLink.ts +36 -0
- package/core/identity/handleRegistry/client.ts +285 -0
- package/core/identity/handleRegistry/profileCert.ts +254 -0
- package/core/identity/handleRegistry/registration.ts +559 -0
- package/core/identity/handleRegistry/resolver.ts +247 -0
- package/core/identity/handleRegistry/rules.ts +104 -0
- package/core/index.ts +20 -2
- package/core/localpay/pendingAborts.ts +5 -1
- package/core/monitor/MonitorSupervisor.ts +121 -0
- package/core/monitor/TaskBackupPush.ts +1 -1
- package/core/monitor/TaskCreditInbox.ts +1 -1
- package/core/monitor/TaskDrainOutbox.ts +1 -1
- package/core/monitor/TaskSendOffline.ts +1 -1
- package/core/net/online.ts +49 -0
- package/core/numberFormat.ts +19 -0
- package/core/offline/plan.ts +1 -1
- package/core/pay/recordProof.ts +2 -6
- package/core/services/arcadeBroadcastProvider.ts +1 -4
- package/core/services/exchangeRate.ts +1 -1
- package/core/services/externalOrigin.ts +5 -2
- package/core/services/vault/transfers.ts +2 -2
- package/core/services/walletServiceConfig.ts +31 -20
- package/core/storage/StorageExpoSQLite.ts +41 -34
- package/core/storage/methods/findSql.ts +3 -0
- package/core/storage/methods/listActionsSql.ts +8 -5
- package/core/storage/methods/listOutputsSql.ts +2 -2
- package/core/storage/methods/processOfflineActions.ts +2 -3
- package/core/storage/methods/reviewStatusSql.ts +7 -2
- package/core/storage/schema/createTables.ts +29 -0
- package/core/toolboxConfig.ts +70 -0
- package/core/toolboxTypes.ts +40 -0
- package/core/userAvatar.ts +79 -0
- package/core/walletMonitor.ts +8 -3
- package/package.json +7 -7
- package/ui/activityFilter.ts +115 -0
- package/ui/components/pay/PaymentSuccessOverlay.tsx +46 -6
- package/ui/components/pay/RecipientField.tsx +84 -70
- package/ui/components/pay/StepBar.tsx +32 -0
- package/ui/components/pay/UniversalSend.tsx +677 -149
- package/ui/components/ui/PencilEditField.tsx +109 -0
- package/ui/components/ui/SlideOverFromRight.tsx +86 -0
- package/ui/components/wallet/ActivityRow.tsx +222 -120
- package/ui/components/wallet/AmountInput.tsx +18 -6
- package/ui/components/wallet/ContactActivityList.tsx +149 -0
- package/ui/components/wallet/ContactSigil.tsx +49 -0
- package/ui/components/wallet/EditPictureSheet.tsx +99 -0
- package/ui/components/wallet/FitAmount.tsx +148 -0
- package/ui/components/wallet/IconPickerSheet.tsx +168 -0
- package/ui/components/wallet/IdentifierRow.tsx +69 -0
- package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
- package/ui/components/wallet/ProfileButton.tsx +62 -0
- package/ui/components/wallet/UserAvatar.tsx +85 -0
- package/ui/components/wallet/avatarIcons.ts +122 -0
- package/ui/hooks/useContactsStore.ts +10 -0
- package/ui/hooks/useMandala.ts +18 -1
- package/ui/hooks/useOnline.ts +65 -20
- package/ui/index.ts +26 -1
- package/ui/screens/ContactScreen.tsx +289 -0
- package/ui/screens/ContactsScreen.tsx +373 -0
- package/ui/screens/IdentifierScreen.tsx +234 -0
- package/ui/screens/NewContactScreen.tsx +362 -0
- package/ui/screens/PayScreen.tsx +20 -7
- package/ui/screens/ProfileScreen.tsx +783 -0
- package/ui/screens/TransactionDetailScreen.tsx +419 -0
- package/ui/screens/TrustScreen.tsx +1 -1
- package/ui/screens/WalletConfigScreen.tsx +42 -0
- package/ui/screens/WalletHomeScreen.tsx +528 -83
- package/ui/tokenStatus.ts +21 -0
- package/ui/txStatus.ts +43 -5
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `ContactsStore` over the toolbox's own SQLite connection.
|
|
3
|
+
*
|
|
4
|
+
* Deliberately logic-free, same spirit as `mandala/settlementStore.ts`: every
|
|
5
|
+
* decision (what counts as a match, how activity is aggregated) lives in the
|
|
6
|
+
* callers of this module. What is here is statements.
|
|
7
|
+
*
|
|
8
|
+
* `name` is the one column this store treats as sacred: it is the user's own
|
|
9
|
+
* label for the counterparty, and no method here ever overwrites it except
|
|
10
|
+
* `renameContact`, which exists for exactly that. A background identity
|
|
11
|
+
* refresh calls `refreshContactCache` instead, which never touches `name`.
|
|
12
|
+
*
|
|
13
|
+
* Access pattern matches `settlementStore.ts`: the caller hands in
|
|
14
|
+
* `storage.sqliteDb` and this module only ever issues parameterised statements
|
|
15
|
+
* against it.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** Everything these statements bind. */
|
|
19
|
+
export type ContactsBindValue = string | number | null
|
|
20
|
+
|
|
21
|
+
/** Structurally satisfied by expo-sqlite's `SQLiteDatabase` and by the
|
|
22
|
+
* `node:sqlite` adapter the tests use. */
|
|
23
|
+
export interface ContactsDb {
|
|
24
|
+
runAsync(sql: string, params: ContactsBindValue[]): Promise<{ changes: number }>
|
|
25
|
+
getAllAsync(sql: string, params: ContactsBindValue[]): Promise<unknown[]>
|
|
26
|
+
getFirstAsync(sql: string, params: ContactsBindValue[]): Promise<unknown>
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** How a contact entered the address book. */
|
|
30
|
+
export type ContactSource = 'manual' | 'qr' | 'pay' | 'search'
|
|
31
|
+
|
|
32
|
+
export interface ContactRow {
|
|
33
|
+
contactId: number
|
|
34
|
+
userId: number
|
|
35
|
+
identityKey: string
|
|
36
|
+
/** The user's own label. Never overwritten by a cache refresh. */
|
|
37
|
+
name: string
|
|
38
|
+
cachedHandle?: string
|
|
39
|
+
cachedAvatarUrl?: string
|
|
40
|
+
cachedCertifier?: string
|
|
41
|
+
source: ContactSource
|
|
42
|
+
createdAt: string
|
|
43
|
+
updatedAt: string
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
interface ContactDbRow {
|
|
47
|
+
contactId: number
|
|
48
|
+
userId: number
|
|
49
|
+
identityKey: string
|
|
50
|
+
name: string
|
|
51
|
+
cachedHandle: string | null
|
|
52
|
+
cachedAvatarUrl: string | null
|
|
53
|
+
cachedCertifier: string | null
|
|
54
|
+
source: string
|
|
55
|
+
created_at: string
|
|
56
|
+
updated_at: string
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function toContact(row: ContactDbRow): ContactRow {
|
|
60
|
+
return {
|
|
61
|
+
contactId: row.contactId,
|
|
62
|
+
userId: row.userId,
|
|
63
|
+
identityKey: row.identityKey,
|
|
64
|
+
name: row.name,
|
|
65
|
+
cachedHandle: row.cachedHandle ?? undefined,
|
|
66
|
+
cachedAvatarUrl: row.cachedAvatarUrl ?? undefined,
|
|
67
|
+
cachedCertifier: row.cachedCertifier ?? undefined,
|
|
68
|
+
source: row.source as ContactSource,
|
|
69
|
+
createdAt: row.created_at,
|
|
70
|
+
updatedAt: row.updated_at
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export interface ContactsStore {
|
|
75
|
+
listContacts(userId: number): Promise<ContactRow[]>
|
|
76
|
+
/** Case-insensitive substring match on `name` and `cachedHandle`. Forgiving,
|
|
77
|
+
* not scored — "fuzzy" in the design sense, not a ranked fuzzy algorithm. */
|
|
78
|
+
searchContacts(userId: number, query: string): Promise<ContactRow[]>
|
|
79
|
+
getContact(userId: number, identityKey: string): Promise<ContactRow | undefined>
|
|
80
|
+
/** Throws on a duplicate (userId, identityKey) — callers check `getContact` first when they need "already a contact" as a non-throwing fact. */
|
|
81
|
+
createContact(args: {
|
|
82
|
+
userId: number
|
|
83
|
+
identityKey: string
|
|
84
|
+
name: string
|
|
85
|
+
cachedHandle?: string
|
|
86
|
+
cachedAvatarUrl?: string
|
|
87
|
+
cachedCertifier?: string
|
|
88
|
+
source: ContactSource
|
|
89
|
+
}): Promise<ContactRow>
|
|
90
|
+
/** The user's own edit. The only method that may change `name`. */
|
|
91
|
+
renameContact(userId: number, identityKey: string, name: string): Promise<void>
|
|
92
|
+
/** A background identity refresh. Never touches `name`. */
|
|
93
|
+
refreshContactCache(
|
|
94
|
+
userId: number,
|
|
95
|
+
identityKey: string,
|
|
96
|
+
cache: { cachedHandle?: string; cachedAvatarUrl?: string; cachedCertifier?: string }
|
|
97
|
+
): Promise<void>
|
|
98
|
+
deleteContact(userId: number, identityKey: string): Promise<void>
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function createContactsStore(db: ContactsDb): ContactsStore {
|
|
102
|
+
return {
|
|
103
|
+
async listContacts(userId) {
|
|
104
|
+
const rows = (await db.getAllAsync('SELECT * FROM contacts WHERE userId = ? ORDER BY name COLLATE NOCASE ASC', [
|
|
105
|
+
userId
|
|
106
|
+
])) as ContactDbRow[]
|
|
107
|
+
return rows.map(toContact)
|
|
108
|
+
},
|
|
109
|
+
|
|
110
|
+
async searchContacts(userId, query) {
|
|
111
|
+
const needle = `%${query.trim().toLowerCase()}%`
|
|
112
|
+
if (query.trim() === '') return createContactsStore(db).listContacts(userId)
|
|
113
|
+
const rows = (await db.getAllAsync(
|
|
114
|
+
`SELECT * FROM contacts
|
|
115
|
+
WHERE userId = ?
|
|
116
|
+
AND (lower(name) LIKE ? OR lower(coalesce(cachedHandle, '')) LIKE ?)
|
|
117
|
+
ORDER BY name COLLATE NOCASE ASC`,
|
|
118
|
+
[userId, needle, needle]
|
|
119
|
+
)) as ContactDbRow[]
|
|
120
|
+
return rows.map(toContact)
|
|
121
|
+
},
|
|
122
|
+
|
|
123
|
+
async getContact(userId, identityKey) {
|
|
124
|
+
const row = (await db.getFirstAsync('SELECT * FROM contacts WHERE userId = ? AND identityKey = ?', [
|
|
125
|
+
userId,
|
|
126
|
+
identityKey
|
|
127
|
+
])) as ContactDbRow | null
|
|
128
|
+
return row ? toContact(row) : undefined
|
|
129
|
+
},
|
|
130
|
+
|
|
131
|
+
async createContact(args) {
|
|
132
|
+
const now = new Date().toISOString()
|
|
133
|
+
await db.runAsync(
|
|
134
|
+
`INSERT INTO contacts
|
|
135
|
+
(created_at, updated_at, userId, identityKey, name, cachedHandle, cachedAvatarUrl, cachedCertifier, source)
|
|
136
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
137
|
+
[
|
|
138
|
+
now,
|
|
139
|
+
now,
|
|
140
|
+
args.userId,
|
|
141
|
+
args.identityKey,
|
|
142
|
+
args.name,
|
|
143
|
+
args.cachedHandle ?? null,
|
|
144
|
+
args.cachedAvatarUrl ?? null,
|
|
145
|
+
args.cachedCertifier ?? null,
|
|
146
|
+
args.source
|
|
147
|
+
]
|
|
148
|
+
)
|
|
149
|
+
const created = await createContactsStore(db).getContact(args.userId, args.identityKey)
|
|
150
|
+
if (!created) throw new Error('contacts: insert did not persist')
|
|
151
|
+
return created
|
|
152
|
+
},
|
|
153
|
+
|
|
154
|
+
async renameContact(userId, identityKey, name) {
|
|
155
|
+
await db.runAsync('UPDATE contacts SET name = ?, updated_at = ? WHERE userId = ? AND identityKey = ?', [
|
|
156
|
+
name,
|
|
157
|
+
new Date().toISOString(),
|
|
158
|
+
userId,
|
|
159
|
+
identityKey
|
|
160
|
+
])
|
|
161
|
+
},
|
|
162
|
+
|
|
163
|
+
async refreshContactCache(userId, identityKey, cache) {
|
|
164
|
+
await db.runAsync(
|
|
165
|
+
`UPDATE contacts
|
|
166
|
+
SET cachedHandle = ?, cachedAvatarUrl = ?, cachedCertifier = ?, updated_at = ?
|
|
167
|
+
WHERE userId = ? AND identityKey = ?`,
|
|
168
|
+
[
|
|
169
|
+
cache.cachedHandle ?? null,
|
|
170
|
+
cache.cachedAvatarUrl ?? null,
|
|
171
|
+
cache.cachedCertifier ?? null,
|
|
172
|
+
new Date().toISOString(),
|
|
173
|
+
userId,
|
|
174
|
+
identityKey
|
|
175
|
+
]
|
|
176
|
+
)
|
|
177
|
+
},
|
|
178
|
+
|
|
179
|
+
async deleteContact(userId, identityKey) {
|
|
180
|
+
await db.runAsync('DELETE FROM contacts WHERE userId = ? AND identityKey = ?', [userId, identityKey])
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
@@ -9,17 +9,15 @@ import {
|
|
|
9
9
|
WalletSigner,
|
|
10
10
|
PermissionRequest,
|
|
11
11
|
SimpleWalletManager,
|
|
12
|
-
Monitor
|
|
12
|
+
Monitor,
|
|
13
|
+
DEFAULT_SETTINGS as LIB_DEFAULT_SETTINGS,
|
|
14
|
+
WalletSettings,
|
|
15
|
+
WalletSettingsManager
|
|
13
16
|
} from '@bsv/wallet-toolbox-mobile'
|
|
14
17
|
import { KeyDeriver, PrivateKey, MerklePath, Transaction, Utils } from '@bsv/sdk'
|
|
15
18
|
import { VAULT_RETENTION_MS, ceremony as vaultCeremony } from '../services/vault/ceremonyHost'
|
|
16
19
|
import { getVaultDriver } from '../services/vault/driver'
|
|
17
20
|
import { backupAttestation } from '../services/vault/backupAttestation'
|
|
18
|
-
import {
|
|
19
|
-
DEFAULT_SETTINGS as LIB_DEFAULT_SETTINGS,
|
|
20
|
-
WalletSettings,
|
|
21
|
-
WalletSettingsManager
|
|
22
|
-
} from '@bsv/wallet-toolbox-mobile/out/src/WalletSettingsManager'
|
|
23
21
|
|
|
24
22
|
/** App-level defaults: library defaults + additional certifiers */
|
|
25
23
|
/**
|
|
@@ -202,6 +200,7 @@ import { getOnline, subscribeOnline } from '../net/online'
|
|
|
202
200
|
import { canInternalizePending, processPending } from '../localpay/pending'
|
|
203
201
|
import { replayPendingAborts } from '../localpay/pendingAborts'
|
|
204
202
|
import { TaskSendOffline } from '../monitor/TaskSendOffline'
|
|
203
|
+
import { MONITOR_STALL_MS, MonitorSupervisor } from '../monitor/MonitorSupervisor'
|
|
205
204
|
import { TaskCreditInbox } from '../monitor/TaskCreditInbox'
|
|
206
205
|
import { drainUnsentEntries, TaskDrainOutbox } from '../monitor/TaskDrainOutbox'
|
|
207
206
|
import { TaskBackupPush } from '../monitor/TaskBackupPush'
|
|
@@ -598,6 +597,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
598
597
|
const [mandala, setMandala] = useState<MandalaRuntime | undefined>(undefined)
|
|
599
598
|
const mandalaRef = useRef<MandalaRuntime | undefined>(undefined)
|
|
600
599
|
const appStateRef = useRef<AppStateStatus>(AppState.currentState)
|
|
600
|
+
const monitorSupervisorRef = useRef<MonitorSupervisor | null>(null)
|
|
601
601
|
const monitorRef = useRef<Monitor | null>(null)
|
|
602
602
|
// The offline-first chain tracker and the header store it wraps. Populated
|
|
603
603
|
// in buildWallet (tracker synchronously, store once the background open
|
|
@@ -1098,7 +1098,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
1098
1098
|
// the single source of truth for these URLs — createServiceOptions
|
|
1099
1099
|
// calls the same function, so there is exactly one table to edit.
|
|
1100
1100
|
const remoteChaintracks = new ChaintracksServiceClient(walletChain, chaintracksUrlFor(chain))
|
|
1101
|
-
const offlineChaintracks = new OfflineFirstChaintracks(remoteChaintracks, getOnline)
|
|
1101
|
+
const offlineChaintracks = new OfflineFirstChaintracks(remoteChaintracks, getOnline, walletChain)
|
|
1102
1102
|
offlineChaintracksRef.current = offlineChaintracks
|
|
1103
1103
|
|
|
1104
1104
|
// Passing offlineChaintracks here does two things, and createServices
|
|
@@ -1121,7 +1121,12 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
1121
1121
|
|
|
1122
1122
|
// Replace all default broadcast providers with EF/rawtx-only services.
|
|
1123
1123
|
// Order: Arcade → Taal → GorillaPool → WoC → Bitails. UntilSuccess stops at first success.
|
|
1124
|
+
// 'ArcadeBeef' is the toolbox's own Arcade broadcaster, registered
|
|
1125
|
+
// because serviceOptions now carries arcadeUrl (needed for Arcade-first
|
|
1126
|
+
// proofs and SSE). Our createArcadeBroadcastService replaces it here so
|
|
1127
|
+
// the same tx is not posted to Arcade twice with two header sets.
|
|
1124
1128
|
const bitailsService = (services as any).bitails
|
|
1129
|
+
services.postBeefServices.remove('ArcadeBeef')
|
|
1125
1130
|
services.postBeefServices.remove('GorillaPoolArcBeef')
|
|
1126
1131
|
services.postBeefServices.remove('TaalArcBeef')
|
|
1127
1132
|
services.postBeefServices.remove('Bitails')
|
|
@@ -1143,7 +1148,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
1143
1148
|
}
|
|
1144
1149
|
|
|
1145
1150
|
// Replace WoC getMerklePath with BUMP endpoint — no TSC→BUMP conversion needed.
|
|
1146
|
-
//
|
|
1151
|
+
// The toolbox's 'Arcade' provider stays where Services put it: first.
|
|
1152
|
+
// Every tx this wallet sends goes through Arcade, so GET /v1/tx/{txid}
|
|
1153
|
+
// there is the one lookup that can answer as soon as it is mined. WoC
|
|
1154
|
+
// BUMP and Bitails are re-added after it as fallbacks, in that order.
|
|
1147
1155
|
const wocBumpBase =
|
|
1148
1156
|
chain === 'main'
|
|
1149
1157
|
? 'https://api.whatsonchain.com/v1/bsv/main'
|
|
@@ -1997,8 +2005,12 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
1997
2005
|
// otherwise "stop" a not-yet-started monitor and this callback
|
|
1998
2006
|
// would then start an unstoppable zombie nothing references.
|
|
1999
2007
|
if (monitorRef.current !== monitor) return
|
|
2000
|
-
// startTasks
|
|
2001
|
-
|
|
2008
|
+
// Not monitor.startTasks(): the supervisor drives the same pass
|
|
2009
|
+
// loop, but survives a throwing pass and can be restarted by the
|
|
2010
|
+
// watchdog below when a pass hangs. See MonitorSupervisor.
|
|
2011
|
+
const supervisor = new MonitorSupervisor()
|
|
2012
|
+
monitorSupervisorRef.current = supervisor
|
|
2013
|
+
supervisor.start(monitor)
|
|
2002
2014
|
})
|
|
2003
2015
|
logWithTimestamp(F, 'Monitor scheduled (ARC SSE) after interactions')
|
|
2004
2016
|
} catch (error: any) {
|
|
@@ -2612,6 +2624,35 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
2612
2624
|
})
|
|
2613
2625
|
}, [walletBuilt])
|
|
2614
2626
|
|
|
2627
|
+
// Monitor watchdog. A pass loop that stops — a task's await that never
|
|
2628
|
+
// resolves, or a throw out of runOnce's own logging — leaves every unsent
|
|
2629
|
+
// request at 'sending' with nothing else in the app able to broadcast it
|
|
2630
|
+
// (2026-09-18: two BSV sends stuck until a force-quit). No completed pass
|
|
2631
|
+
// for MONITOR_STALL_MS while the app is active means the loop is gone;
|
|
2632
|
+
// restart it on the same monitor. 2 min, not 1: a healthy pass is ~5 s
|
|
2633
|
+
// apart but a slow network task can legitimately hold one for a while, and
|
|
2634
|
+
// restarting a healthy loop is the one thing this must never do.
|
|
2635
|
+
useEffect(() => {
|
|
2636
|
+
if (!walletBuilt) return
|
|
2637
|
+
const check = () => {
|
|
2638
|
+
if (AppState.currentState !== 'active') return
|
|
2639
|
+
const supervisor = monitorSupervisorRef.current
|
|
2640
|
+
if (!supervisor || monitorRef.current === null) return
|
|
2641
|
+
if (!supervisor.isStalled(MONITOR_STALL_MS)) return
|
|
2642
|
+
const stalledForMs = Date.now() - supervisor.lastPassAt
|
|
2643
|
+
console.warn(`[WalletContext] monitor loop stalled for ${Math.round(stalledForMs / 1000)}s; restarting it`)
|
|
2644
|
+
if (supervisor.restart()) {
|
|
2645
|
+
// Best-effort: the stalled pass may be holding the very connection this
|
|
2646
|
+
// writes to. Never awaited, never allowed to throw.
|
|
2647
|
+
monitorRef.current
|
|
2648
|
+
?.logEvent('Watchdog', `restarted monitor loop after ${Math.round(stalledForMs / 1000)}s without a pass`)
|
|
2649
|
+
.catch(() => {})
|
|
2650
|
+
}
|
|
2651
|
+
}
|
|
2652
|
+
const interval = setInterval(check, 30_000)
|
|
2653
|
+
return () => clearInterval(interval)
|
|
2654
|
+
}, [walletBuilt])
|
|
2655
|
+
|
|
2615
2656
|
// Fetch Arcade status events when app returns to foreground
|
|
2616
2657
|
useEffect(() => {
|
|
2617
2658
|
const subscription = AppState.addEventListener('change', (nextAppState: AppStateStatus) => {
|
|
@@ -2619,6 +2660,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
2619
2660
|
const isNowForeground = nextAppState === 'active'
|
|
2620
2661
|
|
|
2621
2662
|
if (wasBackground && isNowForeground) {
|
|
2663
|
+
// The loop's timers were frozen with the app; the gap is the OS's, not
|
|
2664
|
+
// the monitor's. Without this the first watchdog check after a long
|
|
2665
|
+
// background would restart a healthy loop.
|
|
2666
|
+
monitorSupervisorRef.current?.touch()
|
|
2622
2667
|
const monitor = monitorRef.current
|
|
2623
2668
|
if (monitor) {
|
|
2624
2669
|
monitor.fetchSSEEvents().then(count => {
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The two stablecoins demo mode holds, plus the BSV opening balance.
|
|
3
|
+
*
|
|
4
|
+
* DEV-ONLY. Nothing here describes a real issuer, a real overlay or a real
|
|
5
|
+
* asset: the genesis outpoints are obviously-fake repeated bytes so that a
|
|
6
|
+
* figure from this file can never be mistaken for one from an overlay, and
|
|
7
|
+
* the overlay URLs point at `.invalid`, which by RFC 2606 can never resolve.
|
|
8
|
+
*
|
|
9
|
+
* Naming follows the stablecoin UX spec, which uses `USDX` / "Acme Dollar" /
|
|
10
|
+
* "Acme Bank" throughout; the CHF asset copies that shape rather than
|
|
11
|
+
* inventing a second convention.
|
|
12
|
+
*/
|
|
13
|
+
import type { TokenAssetInfo } from '../mandala/runtime'
|
|
14
|
+
|
|
15
|
+
/** Demo overlay identity — 66 hex chars, the length a real one has. */
|
|
16
|
+
const DEMO_OVERLAY_KEY = '02' + 'de'.repeat(32)
|
|
17
|
+
const DEMO_OVERLAY_URL = 'https://overlay.demo.invalid'
|
|
18
|
+
|
|
19
|
+
export const DEMO_USD: TokenAssetInfo = {
|
|
20
|
+
assetId: 'd0'.repeat(32) + '.0',
|
|
21
|
+
label: 'Acme Dollar',
|
|
22
|
+
ticker: 'USDX',
|
|
23
|
+
decimals: 2,
|
|
24
|
+
issuerName: 'Acme Bank',
|
|
25
|
+
overlayUrl: DEMO_OVERLAY_URL,
|
|
26
|
+
overlayIdentityKey: DEMO_OVERLAY_KEY
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const DEMO_CHF: TokenAssetInfo = {
|
|
30
|
+
assetId: 'cf'.repeat(32) + '.0',
|
|
31
|
+
label: 'Helvetia Franc',
|
|
32
|
+
ticker: 'CHFX',
|
|
33
|
+
decimals: 2,
|
|
34
|
+
issuerName: 'Helvetia Bank',
|
|
35
|
+
overlayIdentityKey: DEMO_OVERLAY_KEY,
|
|
36
|
+
overlayUrl: DEMO_OVERLAY_URL
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export const DEMO_ASSETS: TokenAssetInfo[] = [DEMO_USD, DEMO_CHF]
|
|
40
|
+
|
|
41
|
+
export function demoAssetById(assetId: string): TokenAssetInfo | undefined {
|
|
42
|
+
return DEMO_ASSETS.find(a => a.assetId === assetId)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Opening BSV balance, in satoshis. 0.25 BSV — enough to read as funded. */
|
|
46
|
+
export const DEMO_OPENING_SATS = 25_000_000
|
|
47
|
+
|
|
48
|
+
/** Opening token balances, in base units (2 dp): 1,240.00 USDX / 860.50 CHFX. */
|
|
49
|
+
export const DEMO_OPENING_TOKEN_BASE_UNITS: Record<string, number> = {
|
|
50
|
+
[DEMO_USD.assetId]: 124_000,
|
|
51
|
+
[DEMO_CHF.assetId]: 86_050
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Counterparties the demo history is transacted against. */
|
|
55
|
+
export const DEMO_COUNTERPARTIES = [
|
|
56
|
+
{ name: 'Sofia Berger', key: '02' + 'a1'.repeat(32) },
|
|
57
|
+
{ name: 'Marco Ferrari', key: '02' + 'b2'.repeat(32) },
|
|
58
|
+
{ name: 'Lena Vogt', key: '02' + 'c3'.repeat(32) },
|
|
59
|
+
{ name: 'Corner Store', key: '02' + 'd4'.repeat(32) }
|
|
60
|
+
]
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The demo wallet's whole world: one mutable, in-memory ledger.
|
|
3
|
+
*
|
|
4
|
+
* DEV-ONLY. Holds a BSV balance with its action history and a base-unit
|
|
5
|
+
* balance per demo stablecoin with its settlement history, and mutates both
|
|
6
|
+
* when the UI "sends". Nothing here touches SQLite, the keychain, an overlay
|
|
7
|
+
* or the network, so a demo send can never become a real one — and everything
|
|
8
|
+
* is gone at reload, which is what makes the mode safe to hand to someone.
|
|
9
|
+
*
|
|
10
|
+
* Figures are integers throughout (satoshis, token base units) for the same
|
|
11
|
+
* reason `ui/tokenFormat.ts` is: a float balance prints money that is not
|
|
12
|
+
* owned.
|
|
13
|
+
*/
|
|
14
|
+
import type { TokenActivityRow, TokenActivityStatus } from '../mandala/runtime'
|
|
15
|
+
import type { WalletAction } from '@bsv/sdk'
|
|
16
|
+
import {
|
|
17
|
+
DEMO_CHF,
|
|
18
|
+
DEMO_COUNTERPARTIES,
|
|
19
|
+
DEMO_OPENING_SATS,
|
|
20
|
+
DEMO_OPENING_TOKEN_BASE_UNITS,
|
|
21
|
+
DEMO_USD,
|
|
22
|
+
demoAssetById
|
|
23
|
+
} from './demoAssets'
|
|
24
|
+
|
|
25
|
+
/** `ActivityAction` without importing the UI layer from core. */
|
|
26
|
+
export type DemoAction = WalletAction & {
|
|
27
|
+
reference?: string
|
|
28
|
+
created_at?: string | number | Date
|
|
29
|
+
senderIdentityKey?: string
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
interface DemoState {
|
|
33
|
+
satoshis: number
|
|
34
|
+
actions: DemoAction[]
|
|
35
|
+
tokenBaseUnits: Record<string, number>
|
|
36
|
+
tokenActivity: TokenActivityRow[]
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const listeners = new Set<() => void>()
|
|
40
|
+
|
|
41
|
+
/** Deterministic 64-hex txid, so a demo row looks like a row and never collides. */
|
|
42
|
+
let txidCounter = 0
|
|
43
|
+
function demoTxid(): string {
|
|
44
|
+
txidCounter += 1
|
|
45
|
+
return txidCounter.toString(16).padStart(8, '0').repeat(8)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function daysAgo(n: number, hour = 12): string {
|
|
49
|
+
const d = new Date()
|
|
50
|
+
d.setDate(d.getDate() - n)
|
|
51
|
+
d.setHours(hour, (n * 7) % 60, 0, 0)
|
|
52
|
+
return d.toISOString()
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function bsvAction(over: Partial<DemoAction> & { satoshis: number; description: string }): DemoAction {
|
|
56
|
+
return {
|
|
57
|
+
txid: demoTxid(),
|
|
58
|
+
status: 'completed',
|
|
59
|
+
isOutgoing: over.satoshis < 0,
|
|
60
|
+
labels: [],
|
|
61
|
+
version: 1,
|
|
62
|
+
lockTime: 0,
|
|
63
|
+
...over,
|
|
64
|
+
// `satoshis` on a WalletAction is the signed delta to the balance, which
|
|
65
|
+
// is what the row renders; keep the caller's sign.
|
|
66
|
+
satoshis: over.satoshis
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function tokenRow(
|
|
71
|
+
assetId: string,
|
|
72
|
+
role: 'sent' | 'received',
|
|
73
|
+
baseUnits: number,
|
|
74
|
+
at: string,
|
|
75
|
+
counterpartyKey?: string,
|
|
76
|
+
status: TokenActivityStatus = 'settled'
|
|
77
|
+
): TokenActivityRow {
|
|
78
|
+
const asset = demoAssetById(assetId)
|
|
79
|
+
if (!asset) throw new Error(`demo: unknown assetId ${assetId}`)
|
|
80
|
+
return { txid: demoTxid(), role, asset, baseUnits, counterpartyKey, status, at }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The opening history: money in and out, on all three rails, spread over the
|
|
85
|
+
* last three weeks so the home list has day headers to group under.
|
|
86
|
+
*/
|
|
87
|
+
function seed(): DemoState {
|
|
88
|
+
const [sofia, marco, lena, store] = DEMO_COUNTERPARTIES
|
|
89
|
+
txidCounter = 0
|
|
90
|
+
return {
|
|
91
|
+
satoshis: DEMO_OPENING_SATS,
|
|
92
|
+
actions: [
|
|
93
|
+
bsvAction({ satoshis: 12_000_000, description: 'Salary — October', created_at: daysAgo(18, 9) }),
|
|
94
|
+
bsvAction({ satoshis: -2_400_000, description: `Paid ${store.name}`, created_at: daysAgo(14, 18) }),
|
|
95
|
+
bsvAction({ satoshis: 6_500_000, description: `From ${sofia.name}`, created_at: daysAgo(11, 10) }),
|
|
96
|
+
bsvAction({ satoshis: -850_000, description: 'Coffee', created_at: daysAgo(7, 8) }),
|
|
97
|
+
bsvAction({ satoshis: -3_250_000, description: `Paid ${marco.name}`, created_at: daysAgo(4, 16) }),
|
|
98
|
+
bsvAction({ satoshis: 15_000_000, description: `From ${lena.name}`, created_at: daysAgo(2, 13) }),
|
|
99
|
+
bsvAction({ satoshis: -1_000_000, description: 'Lunch', created_at: daysAgo(0, 12) })
|
|
100
|
+
],
|
|
101
|
+
tokenBaseUnits: { ...DEMO_OPENING_TOKEN_BASE_UNITS },
|
|
102
|
+
tokenActivity: [
|
|
103
|
+
tokenRow(DEMO_USD.assetId, 'received', 50_000, daysAgo(16, 11), sofia.key),
|
|
104
|
+
tokenRow(DEMO_CHF.assetId, 'received', 40_000, daysAgo(13, 15), lena.key),
|
|
105
|
+
tokenRow(DEMO_USD.assetId, 'sent', 12_500, daysAgo(9, 19), store.key),
|
|
106
|
+
tokenRow(DEMO_CHF.assetId, 'sent', 7_450, daysAgo(6, 12), marco.key),
|
|
107
|
+
tokenRow(DEMO_USD.assetId, 'received', 86_500, daysAgo(3, 14), marco.key),
|
|
108
|
+
tokenRow(DEMO_CHF.assetId, 'received', 53_500, daysAgo(1, 17), sofia.key),
|
|
109
|
+
// One row mid-flight, so the "settling" copy has something to render.
|
|
110
|
+
tokenRow(DEMO_USD.assetId, 'sent', 2_000, daysAgo(0, 11), lena.key, 'settling')
|
|
111
|
+
]
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Initialised here rather than beside `listeners` above: `seed()` assigns
|
|
117
|
+
* `txidCounter`, so calling it any earlier reads that binding inside its
|
|
118
|
+
* temporal dead zone and throws on import.
|
|
119
|
+
*/
|
|
120
|
+
let state: DemoState = seed()
|
|
121
|
+
|
|
122
|
+
function notify(): void {
|
|
123
|
+
listeners.forEach(l => l())
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function subscribeDemoLedger(listener: () => void): () => void {
|
|
127
|
+
listeners.add(listener)
|
|
128
|
+
return () => {
|
|
129
|
+
listeners.delete(listener)
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// ── reads ──────────────────────────────────────────────────────────────
|
|
134
|
+
|
|
135
|
+
export function demoSatoshis(): number {
|
|
136
|
+
return state.satoshis
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Newest first — the order the activity list renders in. */
|
|
140
|
+
export function demoActions(limit?: number, offset = 0): DemoAction[] {
|
|
141
|
+
const sorted = [...state.actions].sort(
|
|
142
|
+
(a, b) => new Date(b.created_at ?? 0).getTime() - new Date(a.created_at ?? 0).getTime()
|
|
143
|
+
)
|
|
144
|
+
return limit == null ? sorted.slice(offset) : sorted.slice(offset, offset + limit)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function demoTotalActions(): number {
|
|
148
|
+
return state.actions.length
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export function demoTokenBaseUnits(assetId: string): number {
|
|
152
|
+
return state.tokenBaseUnits[assetId] ?? 0
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export function demoTokenActivity(limit?: number): TokenActivityRow[] {
|
|
156
|
+
const sorted = [...state.tokenActivity].sort((a, b) => new Date(b.at).getTime() - new Date(a.at).getTime())
|
|
157
|
+
return limit == null ? sorted : sorted.slice(0, limit)
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Base units awaiting settlement — what the UI shows as not-yet-final. */
|
|
161
|
+
export function demoUnsettledBaseUnits(assetId: string): number {
|
|
162
|
+
return state.tokenActivity
|
|
163
|
+
.filter(r => r.asset.assetId === assetId && r.role === 'received' && r.status === 'settling')
|
|
164
|
+
.reduce((sum, r) => sum + r.baseUnits, 0)
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// ── writes ─────────────────────────────────────────────────────────────
|
|
168
|
+
|
|
169
|
+
/** Spend BSV. Returns the new row, or null when the balance cannot cover it. */
|
|
170
|
+
export function demoSendBsv(satoshis: number, description: string): DemoAction | null {
|
|
171
|
+
if (!Number.isFinite(satoshis) || satoshis <= 0) return null
|
|
172
|
+
if (satoshis > state.satoshis) return null
|
|
173
|
+
const action = bsvAction({
|
|
174
|
+
satoshis: -Math.round(satoshis),
|
|
175
|
+
description: description || 'Demo payment',
|
|
176
|
+
created_at: new Date().toISOString()
|
|
177
|
+
})
|
|
178
|
+
state = { ...state, satoshis: state.satoshis - Math.round(satoshis), actions: [...state.actions, action] }
|
|
179
|
+
notify()
|
|
180
|
+
return action
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Receive BSV — for demonstrating an incoming payment on cue. */
|
|
184
|
+
export function demoReceiveBsv(satoshis: number, description: string): DemoAction | null {
|
|
185
|
+
if (!Number.isFinite(satoshis) || satoshis <= 0) return null
|
|
186
|
+
const action = bsvAction({
|
|
187
|
+
satoshis: Math.round(satoshis),
|
|
188
|
+
description: description || 'Demo receipt',
|
|
189
|
+
created_at: new Date().toISOString()
|
|
190
|
+
})
|
|
191
|
+
state = { ...state, satoshis: state.satoshis + Math.round(satoshis), actions: [...state.actions, action] }
|
|
192
|
+
notify()
|
|
193
|
+
return action
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Spend a token. Returns the new row, or null when the balance cannot cover it. */
|
|
197
|
+
export function demoSendToken(
|
|
198
|
+
assetId: string,
|
|
199
|
+
baseUnits: number,
|
|
200
|
+
counterpartyKey?: string
|
|
201
|
+
): TokenActivityRow | null {
|
|
202
|
+
if (!demoAssetById(assetId)) return null
|
|
203
|
+
if (!Number.isFinite(baseUnits) || baseUnits <= 0) return null
|
|
204
|
+
const held = demoTokenBaseUnits(assetId)
|
|
205
|
+
const amount = Math.round(baseUnits)
|
|
206
|
+
if (amount > held) return null
|
|
207
|
+
const row = tokenRow(assetId, 'sent', amount, new Date().toISOString(), counterpartyKey, 'settled')
|
|
208
|
+
state = {
|
|
209
|
+
...state,
|
|
210
|
+
tokenBaseUnits: { ...state.tokenBaseUnits, [assetId]: held - amount },
|
|
211
|
+
tokenActivity: [...state.tokenActivity, row]
|
|
212
|
+
}
|
|
213
|
+
notify()
|
|
214
|
+
return row
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Receive a token — for demonstrating an incoming payment on cue. */
|
|
218
|
+
export function demoReceiveToken(
|
|
219
|
+
assetId: string,
|
|
220
|
+
baseUnits: number,
|
|
221
|
+
counterpartyKey?: string
|
|
222
|
+
): TokenActivityRow | null {
|
|
223
|
+
if (!demoAssetById(assetId)) return null
|
|
224
|
+
if (!Number.isFinite(baseUnits) || baseUnits <= 0) return null
|
|
225
|
+
const amount = Math.round(baseUnits)
|
|
226
|
+
const row = tokenRow(assetId, 'received', amount, new Date().toISOString(), counterpartyKey, 'settled')
|
|
227
|
+
state = {
|
|
228
|
+
...state,
|
|
229
|
+
tokenBaseUnits: { ...state.tokenBaseUnits, [assetId]: demoTokenBaseUnits(assetId) + amount },
|
|
230
|
+
tokenActivity: [...state.tokenActivity, row]
|
|
231
|
+
}
|
|
232
|
+
notify()
|
|
233
|
+
return row
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Back to the opening position, without a reload. */
|
|
237
|
+
export function resetDemoLedger(): void {
|
|
238
|
+
state = seed()
|
|
239
|
+
notify()
|
|
240
|
+
}
|