@bsv/expo-wallet-toolbox 0.25.0 → 0.26.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.
Files changed (50) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/core/context/WalletContext.tsx +11 -15
  3. package/core/i18n/translations.tsx +221 -36
  4. package/core/identity/handleRegistry/client.ts +110 -16
  5. package/core/identity/handleRegistry/registration.ts +115 -17
  6. package/core/index.ts +8 -0
  7. package/core/net/wocLimiter.ts +133 -0
  8. package/core/pay/beefRepair.ts +3 -1
  9. package/core/pay/rails/address.ts +2 -2
  10. package/core/profiles/profileStore.ts +4 -1
  11. package/core/services/arcadeBroadcastProvider.ts +6 -0
  12. package/core/services/exchangeRate.ts +8 -1
  13. package/core/services/groupSpendingLimit.ts +26 -0
  14. package/core/services/signingPermissionPolicy.ts +14 -8
  15. package/core/services/vault/ceremony.ts +13 -0
  16. package/core/services/vault/ceremonyHost.ts +58 -0
  17. package/core/services/vault/failedVaultSpend.ts +40 -0
  18. package/core/services/vault/outputAuthority.ts +13 -6
  19. package/core/services/vault/transfers.ts +56 -12
  20. package/core/services/vault/wocLookup.ts +5 -2
  21. package/core/storage/encryptedDbImage.ts +11 -2
  22. package/core/theme/tokens.ts +26 -12
  23. package/package.json +2 -1
  24. package/ui/components/QRScanner.tsx +24 -22
  25. package/ui/components/pay/MessageBoxConfig.tsx +10 -16
  26. package/ui/components/pay/NearbyAdvisoryModal.tsx +6 -13
  27. package/ui/components/pay/NearbyFlow.tsx +72 -35
  28. package/ui/components/pay/PayForm.tsx +27 -19
  29. package/ui/components/pay/PaymentSuccessOverlay.tsx +8 -6
  30. package/ui/components/pay/UniversalSend.tsx +4 -1
  31. package/ui/components/ui/AlertCard.tsx +3 -2
  32. package/ui/components/ui/BalancedText.tsx +117 -0
  33. package/ui/components/ui/ErrorBoundary.tsx +31 -14
  34. package/ui/components/ui/GroupedList.tsx +28 -22
  35. package/ui/components/ui/ListRow.tsx +126 -35
  36. package/ui/components/ui/PermissionSheet.tsx +31 -24
  37. package/ui/components/ui/PresenceRow.tsx +15 -23
  38. package/ui/components/ui/Sheet.tsx +11 -17
  39. package/ui/components/ui/Toast.tsx +13 -17
  40. package/ui/components/vault/EnrollWizard.tsx +446 -196
  41. package/ui/components/vault/KeyChooser.tsx +7 -20
  42. package/ui/components/vault/VaultCeremonySheet.tsx +44 -36
  43. package/ui/components/wallet/AmountInput.tsx +11 -17
  44. package/ui/components/wallet/BiometricAdvisoryModal.tsx +13 -17
  45. package/ui/index.ts +1 -1
  46. package/ui/screens/TrustScreen.tsx +49 -61
  47. package/ui/screens/VaultScreen.tsx +99 -60
  48. package/ui/screens/VaultTransferScreen.tsx +34 -27
  49. package/ui/screens/WalletCheckScreen.tsx +25 -24
  50. package/ui/screens/WalletConfigScreen.tsx +66 -72
@@ -35,6 +35,18 @@ export type AvailabilityResult =
35
35
  | { kind: 'failed' }
36
36
 
37
37
  /** `rejected` is the server answering no; `failed` is not having an answer. */
38
+ /**
39
+ * The App Store or Google Play subscription that pays for a custom handle, as
40
+ * the registry verifies it: `token` is the StoreKit 2 signed transaction or
41
+ * Google's purchase token.
42
+ */
43
+ export interface StorePurchase {
44
+ store: 'app-store' | 'google-play'
45
+ productId: string
46
+ transactionId: string
47
+ token: string | null
48
+ }
49
+
38
50
  export type PutResult =
39
51
  | { kind: 'created' }
40
52
  | { kind: 'ok' }
@@ -50,13 +62,42 @@ export type PutResult =
50
62
  */
51
63
  export type ProfileLookup = { kind: 'found'; profile: RegistryProfile } | { kind: 'none' } | { kind: 'failed' }
52
64
 
65
+ /** A profile as `search` returns it. */
66
+ export type HandleProfile = RegistryProfile
67
+
68
+ /**
69
+ * What a complete address resolves to, against the key this device pinned for
70
+ * it. `changed` is a valid certificate under another key: the pin does not move
71
+ * until `acceptKey`. `failed` is not having an answer, `none` is the registry
72
+ * saying nobody holds the handle.
73
+ */
74
+ export type ResolveResult =
75
+ | { kind: 'found'; profile: HandleProfile }
76
+ | { kind: 'changed'; profile: HandleProfile; pinnedKey: string }
77
+ | { kind: 'none' }
78
+ | { kind: 'failed' }
79
+
53
80
  export interface HandleRegistryClient {
54
81
  /** The pinned domain: what a bare handle is registered under. */
55
82
  readonly domain: string
56
83
  checkAvailability(handle: string): Promise<AvailabilityResult>
57
- putCertificate(cert: ProfileCertJson): Promise<PutResult>
58
- /** Throws on transport failure — the contract `searchIdentities` already has. */
59
- search(query: string): Promise<RegistryProfile[]>
84
+ /**
85
+ * `purchase` pays for a custom handle; it goes as `{certificate, purchase}`.
86
+ * `fallback` is the certificate of the generated handle the wallet becomes
87
+ * when the subscription lapses; it goes as a third member, and only with a
88
+ * purchase (the registry ignores it on a free claim).
89
+ */
90
+ putCertificate(cert: ProfileCertJson, purchase?: StorePurchase, fallback?: ProfileCertJson): Promise<PutResult>
91
+ /**
92
+ * Throws on transport failure — the contract `searchIdentities` already has.
93
+ * A complete address whose key differs from the pin comes back with
94
+ * `changedFrom` (the pinned key); a partial query still drops that row.
95
+ */
96
+ search(query: string): Promise<Array<HandleProfile & { changedFrom?: string }>>
97
+ /** Never throws. One complete address, checked against this device's key pin. */
98
+ resolveHandle(paymail: string): Promise<ResolveResult>
99
+ /** Replaces the pin for `paymail`: the payer has accepted its new key. */
100
+ acceptKey(paymail: string, identityKey: string): Promise<void>
60
101
  /** Never throws. The full verdict, for callers that cache the answer. */
61
102
  lookupProfile(identityKey: string, domain?: string): Promise<ProfileLookup>
62
103
  /** Never throws — the contract `resolveIdentity` already has. */
@@ -108,13 +149,17 @@ export function createHandleRegistryClient(args: {
108
149
  * is indistinguishable from a compromised or malicious registry redirecting
109
150
  * the paymail to an attacker.
110
151
  */
111
- async function pinnedOrNull(profile: RegistryProfile): Promise<RegistryProfile | null> {
152
+ async function checkPin(profile: RegistryProfile): Promise<{ kind: 'match' } | { kind: 'mismatch'; pinnedKey: string }> {
112
153
  const known = await pinStore.get(profile.paymail)
113
154
  if (known === null) {
114
155
  await pinStore.set(profile.paymail, profile.identityKey)
115
- return profile
156
+ return { kind: 'match' }
116
157
  }
117
- return known.toLowerCase() === profile.identityKey.toLowerCase() ? profile : null
158
+ return known.toLowerCase() === profile.identityKey.toLowerCase() ? { kind: 'match' } : { kind: 'mismatch', pinnedKey: known }
159
+ }
160
+
161
+ async function pinnedOrNull(profile: RegistryProfile): Promise<RegistryProfile | null> {
162
+ return (await checkPin(profile)).kind === 'match' ? profile : null
118
163
  }
119
164
 
120
165
  /** Only ever from the registry we write to: a foreign host's clock is not
@@ -167,6 +212,13 @@ export function createHandleRegistryClient(args: {
167
212
  if (at < 0) return isRoutableSearchQuery(text) ? { domain, query: text } : null
168
213
  const local = text.slice(0, at)
169
214
  const typed = text.slice(at + 1)
215
+ // A one-character handle is a real, exact address: `r@domain` asks the
216
+ // registry for that one handle. Anything shorter than a search query is
217
+ // read this way only when the domain is finished; typed as a fragment it
218
+ // is still nothing to ask about.
219
+ if (/^[a-z0-9]$/.test(local) && (typed === domain || looksLikeDomain(typed))) {
220
+ return { domain: typed, query: local, paymail: `${local}@${typed}` }
221
+ }
170
222
  if (local.length < SEARCH_MIN_QUERY_LENGTH || !isRoutableSearchQuery(local)) return null
171
223
  // A domain still being typed is a prefix of ours: still our registry, and
172
224
  // still a fragment — the user has not finished naming anybody yet.
@@ -242,14 +294,18 @@ export function createHandleRegistryClient(args: {
242
294
  }
243
295
  },
244
296
 
245
- async putCertificate(cert) {
246
- let res: Response
247
- try {
248
- res = await fetchWithTimeout(fetchImpl, `${origin}/api/handle`, {
297
+ async putCertificate(cert, purchase, fallback) {
298
+ const put = (body: unknown) =>
299
+ fetchWithTimeout(fetchImpl, `${origin}/api/handle`, {
249
300
  method: 'PUT',
250
301
  headers: { 'content-type': 'application/json' },
251
- body: JSON.stringify(cert)
302
+ body: JSON.stringify(body)
252
303
  })
304
+ let res: Response
305
+ try {
306
+ res = await put(purchase ? { certificate: cert, purchase, ...(fallback ? { fallback } : {}) } : cert)
307
+ // No bare retry after ERR_INVALID_CERTIFICATE: the registry verifies
308
+ // purchases now, and a bare certificate would claim a paid handle free.
253
309
  } catch (e) {
254
310
  return { kind: 'failed', message: e instanceof Error ? e.message : String(e) }
255
311
  }
@@ -296,11 +352,49 @@ export function createHandleRegistryClient(args: {
296
352
  )
297
353
  const certified = verified.filter((profile): profile is RegistryProfile => profile !== null)
298
354
  // Each row is checked against this device's own key-pin history
299
- // (XR-071) — a row whose certificate verifies but whose key contradicts
300
- // one already accepted for that paymail is dropped like any other row
301
- // that failed verification.
302
- const pinned = await Promise.all(certified.map(profile => pinnedOrNull(profile)))
303
- return pinned.filter((profile): profile is RegistryProfile => profile !== null)
355
+ // (XR-071). A row whose certificate verifies but whose key contradicts
356
+ // one already accepted for that paymail is dropped from a partial query;
357
+ // for a complete address it is the answer, flagged with the pinned key,
358
+ // so the caller can warn instead of showing nobody.
359
+ const rows = await Promise.all(
360
+ certified.map(async (profile): Promise<(HandleProfile & { changedFrom?: string }) | null> => {
361
+ const pin = await checkPin(profile)
362
+ if (pin.kind === 'mismatch') return route.paymail ? { ...profile, changedFrom: pin.pinnedKey } : null
363
+ return profile
364
+ })
365
+ )
366
+ return rows.filter((profile): profile is HandleProfile & { changedFrom?: string } => profile !== null)
367
+ },
368
+
369
+ async resolveHandle(paymail) {
370
+ try {
371
+ const route = routeFor(paymail)
372
+ if (!route?.paymail) return { kind: 'none' }
373
+ const endpoints = await resolver.resolve(route.domain)
374
+ if (!endpoints) return { kind: 'failed' }
375
+ const res = await fetchWithTimeout(fetchImpl, endpoints.search(route.query), {
376
+ headers: { accept: 'application/json' }
377
+ })
378
+ if (endpoints.pinned) notePinnedSkew(res)
379
+ if (res.status === 404) return { kind: 'none' }
380
+ if (!res.ok) return { kind: 'failed' }
381
+ const body = (await res.json()) as unknown
382
+ if (!Array.isArray(body)) return { kind: 'none' }
383
+ for (const row of body.slice(0, MAX_SEARCH_RESULTS)) {
384
+ const profile = await verifyProfileCertificate(row, { domain: route.domain, paymail: route.paymail })
385
+ if (!profile) continue
386
+ const pin = await checkPin(profile)
387
+ if (pin.kind === 'mismatch') return { kind: 'changed', profile, pinnedKey: pin.pinnedKey }
388
+ return { kind: 'found', profile }
389
+ }
390
+ return { kind: 'none' }
391
+ } catch {
392
+ return { kind: 'failed' }
393
+ }
394
+ },
395
+
396
+ async acceptKey(paymail, identityKey) {
397
+ await pinStore.set(paymail.trim().toLowerCase(), identityKey)
304
398
  },
305
399
 
306
400
  lookupProfile,
@@ -17,7 +17,7 @@
17
17
  */
18
18
  import { parsePaymail } from './rules'
19
19
  import { buildProfileCertificate, type ProfileCertJson, type ProfileSigner } from './profileCert'
20
- import type { HandleRegistryClient } from './client'
20
+ import type { HandleRegistryClient, StorePurchase } from './client'
21
21
 
22
22
  /** The in-flight journal. One at a time; a second intent replaces it. */
23
23
  export const PENDING_JOURNAL_KEY = 'profile_handle_pending'
@@ -30,6 +30,9 @@ export const ISSUED_AT_KV_KEY = 'profile_handle_issued_at'
30
30
  */
31
31
  export const MAX_ISSUED_AT_LEAD_MS = 240_000
32
32
 
33
+ /** The registry's refusal of a fallback handle that is taken or too similar. */
34
+ const FALLBACK_UNAVAILABLE = 'ERR_FALLBACK_UNAVAILABLE'
35
+
33
36
  /** Structurally satisfied by `StorageExpoSQLite`. */
34
37
  export interface RegistrationStorage {
35
38
  getKeyValue(key: string): Promise<string | undefined>
@@ -42,6 +45,10 @@ export interface PendingStep {
42
45
  kind: 'release' | 'claim'
43
46
  paymail: string
44
47
  cert: ProfileCertJson
48
+ /** the store subscription a paid claim is sent with */
49
+ purchase?: StorePurchase
50
+ /** the generated handle's certificate a paid claim reserves, signed after the claim */
51
+ fallback?: ProfileCertJson
45
52
  }
46
53
 
47
54
  /**
@@ -69,15 +76,21 @@ export interface PendingJournal {
69
76
  export type RegistrationFailureCode = 'invalid_handle' | 'wrong_domain' | 'same_handle' | 'clock_ahead'
70
77
 
71
78
  export type RegistrationResult =
72
- | { kind: 'registered'; paymail: string }
79
+ /** `fallback`: the bare free handle the claim reserved, when it went with one */
80
+ | { kind: 'registered'; paymail: string; fallback?: string }
73
81
  | { kind: 'updated'; paymail: string }
74
- | { kind: 'changed'; paymail: string }
82
+ | { kind: 'changed'; paymail: string; fallback?: string }
75
83
  /** The handle was tombstoned and nothing was claimed in its place. */
76
84
  | { kind: 'released'; paymail: string }
77
85
  /** `attempted` is the handle that was lost; `paymail` is the one kept. */
78
86
  | { kind: 'rolled_back'; paymail: string; attempted?: string }
79
87
  | { kind: 'pending' }
80
- | { kind: 'rejected'; code: string; description: string }
88
+ /**
89
+ * `notRestored`: a change's claim was refused AND the reclaim of the old
90
+ * handle (`notRestored`, handle@domain) was refused too, so the wallet holds
91
+ * no handle. `code` and `description` are then the reclaim's.
92
+ */
93
+ | { kind: 'rejected'; code: string; description: string; notRestored?: string }
81
94
  | { kind: 'failed'; message: string; code?: RegistrationFailureCode }
82
95
  | { kind: 'unavailable' }
83
96
  | { kind: 'idle' }
@@ -236,12 +249,63 @@ async function alreadyApplied(
236
249
  return mine === null || mine.paymail !== step.paymail
237
250
  }
238
251
 
252
+ /**
253
+ * The fallback's certificate for a paid claim, dated strictly after `after`
254
+ * (the claim, or in a change the later of the release and the claim). Null
255
+ * with no purchase: the registry reads `fallback` on a paid claim only.
256
+ */
257
+ async function buildFallback(
258
+ deps: RegistrationDeps,
259
+ client: HandleRegistryClient,
260
+ args: { purchase?: StorePurchase; fallbackHandle?: string },
261
+ after: Date
262
+ ): Promise<ProfileCertJson | null> {
263
+ if (!args.purchase || !args.fallbackHandle) return null
264
+ const paymail = `${args.fallbackHandle.trim().toLowerCase()}@${client.domain}`
265
+ if (!parsePaymail(paymail)) throw new InvalidFallback(args.fallbackHandle)
266
+ const issuedAt = await nextIssuedAt(deps, client, after)
267
+ // The ceiling can leave no room above the claim; a fallback dated at or
268
+ // before it would be refused as stale after the claim had been paid for.
269
+ if (issuedAt.getTime() <= after.getTime()) throw new ClockAhead()
270
+ return await buildProfileCertificate({ signer: deps.signer, paymail, issuedAt })
271
+ }
272
+
273
+ class InvalidFallback extends Error {
274
+ constructor(handle: string) {
275
+ super(`handleRegistry: not a valid fallback handle: ${handle}`)
276
+ }
277
+ }
278
+
279
+ class ClockAhead extends Error {
280
+ constructor() {
281
+ super('handleRegistry: the clock is too far ahead to reserve a fallback handle yet')
282
+ }
283
+ }
284
+
285
+ /** A failure this module reached on its own, in the shape callers read. */
286
+ function failureOf(e: unknown): RegistrationResult {
287
+ if (e instanceof InvalidFallback) return { kind: 'failed', code: 'invalid_handle', message: e.message }
288
+ if (e instanceof ClockAhead) return { kind: 'failed', code: 'clock_ahead', message: e.message }
289
+ return { kind: 'failed', message: messageOf(e) }
290
+ }
291
+
239
292
  /** The `issuedAt` a step was minted with, as the journal carries it. */
240
293
  function issuedAtOf(step: PendingStep | undefined): Date | undefined {
241
294
  const ms = Date.parse(step?.cert.fields.issuedAt ?? '')
242
295
  return Number.isFinite(ms) ? new Date(ms) : undefined
243
296
  }
244
297
 
298
+ /** The bare handle a claim step reserved as its fallback, when it had one. */
299
+ function fallbackOf(step: PendingStep | undefined): string | undefined {
300
+ const paymail = step?.fallback?.fields.paymail
301
+ return typeof paymail === 'string' ? paymail.split('@')[0] : undefined
302
+ }
303
+
304
+ /** A reclaim the registry refused: the old handle is not back. */
305
+ function notRestored(back: RegistrationResult, paymail: string): RegistrationResult {
306
+ return back.kind === 'rejected' ? { ...back, notRestored: paymail } : back
307
+ }
308
+
245
309
  /**
246
310
  * The handle to put the user back on, when the step the registry just refused
247
311
  * is the claim of a change that has already tombstoned the old one.
@@ -271,7 +335,7 @@ async function runJournal(
271
335
  ): Promise<RegistrationResult> {
272
336
  for (let i = 0; i < journal.steps.length; i++) {
273
337
  const step = journal.steps[i]
274
- const outcome = await client.putCertificate(step.cert)
338
+ const outcome = await client.putCertificate(step.cert, step.purchase, step.fallback)
275
339
  if (outcome.kind === 'created' || outcome.kind === 'ok') continue
276
340
  // No answer: the journal stays, and the next mount or an explicit retry
277
341
  // re-sends the same bytes.
@@ -290,14 +354,27 @@ async function runJournal(
290
354
  // their tombstone ahead of ours — any device a few minutes fast does —
291
355
  // and is the same hazard as the handle being taken. Replaying cannot
292
356
  // win, but the reclaim still can.
293
- if (reclaim) return await rollBack(deps, client, reclaim.paymail, reclaim.releasedAt, reclaim.attempted)
357
+ if (reclaim) return notRestored(await rollBack(deps, client, reclaim.paymail, reclaim.releasedAt, reclaim.attempted), reclaim.paymail)
294
358
  // Replaying a certificate the registry calls stale can never win, so
295
359
  // keeping the journal would only retry it on every mount, forever.
296
360
  await clearJournal(deps.storage)
297
361
  return { kind: 'failed', message: outcome.description }
298
362
  }
299
- if (reclaim) return await rollBack(deps, client, reclaim.paymail, reclaim.releasedAt, reclaim.attempted)
363
+ if (reclaim) {
364
+ const back = await rollBack(deps, client, reclaim.paymail, reclaim.releasedAt, reclaim.attempted)
365
+ // The reserve failed before anything was claimed, so the caller has to
366
+ // see that code to pick another fallback: the old handle is back, and
367
+ // the refusal is what is reported.
368
+ if (outcome.code === FALLBACK_UNAVAILABLE && back.kind === 'rolled_back') {
369
+ return { kind: 'rejected', code: outcome.code, description: outcome.description }
370
+ }
371
+ return notRestored(back, reclaim.paymail)
372
+ }
300
373
  await clearJournal(deps.storage)
374
+ // a rollback journal resumed on a later start: its one step reclaims the old handle
375
+ if (journal.intent === 'change' && journal.steps.length === 1 && journal.previousPaymail === step.paymail) {
376
+ return { kind: 'rejected', code: outcome.code, description: outcome.description, notRestored: step.paymail }
377
+ }
301
378
  return { kind: 'rejected', code: outcome.code, description: outcome.description }
302
379
  }
303
380
  await clearJournal(deps.storage)
@@ -313,10 +390,12 @@ async function runJournal(
313
390
  ...(journal.attemptedPaymail ? { attempted: journal.attemptedPaymail } : {})
314
391
  }
315
392
  }
393
+ // the fallback is the journal's, which may not be the one the caller of this run chose
394
+ const fallback = fallbackOf(journal.steps[journal.steps.length - 1])
316
395
  if (journal.intent === 'update') return { kind: 'updated', paymail }
317
- if (journal.intent === 'change') return { kind: 'changed', paymail }
396
+ if (journal.intent === 'change') return { kind: 'changed', paymail, ...(fallback ? { fallback } : {}) }
318
397
  if (journal.intent === 'release') return { kind: 'released', paymail }
319
- return { kind: 'registered', paymail }
398
+ return { kind: 'registered', paymail, ...(fallback ? { fallback } : {}) }
320
399
  }
321
400
 
322
401
  /**
@@ -398,9 +477,9 @@ async function finishOutstanding(
398
477
 
399
478
  export function registerHandle(
400
479
  deps: RegistrationDeps,
401
- args: { handle: string; displayName?: string }
480
+ args: { handle: string; displayName?: string; purchase?: StorePurchase; fallbackHandle?: string }
402
481
  ): Promise<RegistrationResult> {
403
- return share(`register:${args.handle.trim().toLowerCase()}:${args.displayName?.trim() ?? ''}`, async () => {
482
+ return share(`register:${args.handle.trim().toLowerCase()}:${args.displayName?.trim() ?? ''}:${args.fallbackHandle ?? ''}`, async () => {
404
483
  const client = deps.client
405
484
  if (!client) return { kind: 'unavailable' }
406
485
  try {
@@ -416,16 +495,25 @@ export function registerHandle(
416
495
  issuedAt,
417
496
  displayName: args.displayName
418
497
  })
498
+ const fallback = await buildFallback(deps, client, args, issuedAt)
419
499
  const journal: PendingJournal = {
420
500
  v: 1,
421
501
  intent: 'register',
422
- steps: [{ kind: 'claim', paymail, cert }],
502
+ steps: [
503
+ {
504
+ kind: 'claim',
505
+ paymail,
506
+ cert,
507
+ ...(args.purchase ? { purchase: args.purchase } : {}),
508
+ ...(fallback ? { fallback } : {})
509
+ }
510
+ ],
423
511
  startedAt: issuedAt.toISOString()
424
512
  }
425
513
  await writeJournal(deps.storage, journal)
426
514
  return await runJournal(deps, client, journal)
427
515
  } catch (e) {
428
- return { kind: 'failed', message: messageOf(e) }
516
+ return failureOf(e)
429
517
  }
430
518
  })
431
519
  }
@@ -472,9 +560,9 @@ export function updateProfile(
472
560
 
473
561
  export function changeHandle(
474
562
  deps: RegistrationDeps,
475
- args: { previousPaymail: string; handle: string; displayName?: string }
563
+ args: { previousPaymail: string; handle: string; displayName?: string; purchase?: StorePurchase; fallbackHandle?: string }
476
564
  ): Promise<RegistrationResult> {
477
- const key = `change:${args.previousPaymail.trim().toLowerCase()}:${args.handle.trim().toLowerCase()}:${args.displayName?.trim() ?? ''}`
565
+ const key = `change:${args.previousPaymail.trim().toLowerCase()}:${args.handle.trim().toLowerCase()}:${args.displayName?.trim() ?? ''}:${args.fallbackHandle ?? ''}`
478
566
  return share(key, async () => {
479
567
  const client = deps.client
480
568
  if (!client) return { kind: 'unavailable' }
@@ -530,12 +618,22 @@ export function changeHandle(
530
618
  issuedAt: claimAt,
531
619
  displayName: args.displayName
532
620
  })
621
+ // dated after the release and the claim both, so it beats the tombstone
622
+ // of a fallback handle that is the one being released
623
+ const fallback = await buildFallback(deps, client, args, claimAt)
533
624
  const journal: PendingJournal = {
534
625
  v: 1,
535
626
  intent: 'change',
536
627
  steps: [
537
628
  { kind: 'release', paymail: previousPaymail, cert: release },
538
- { kind: 'claim', paymail, cert: claim }
629
+ // the new handle's subscription and its fallback go with its claim; a release needs neither
630
+ {
631
+ kind: 'claim',
632
+ paymail,
633
+ cert: claim,
634
+ ...(args.purchase ? { purchase: args.purchase } : {}),
635
+ ...(fallback ? { fallback } : {})
636
+ }
539
637
  ],
540
638
  previousPaymail,
541
639
  startedAt: releaseAt.toISOString()
@@ -543,7 +641,7 @@ export function changeHandle(
543
641
  await writeJournal(deps.storage, journal)
544
642
  return await runJournal(deps, client, journal)
545
643
  } catch (e) {
546
- return { kind: 'failed', message: messageOf(e) }
644
+ return failureOf(e)
547
645
  }
548
646
  })
549
647
  }
package/core/index.ts CHANGED
@@ -37,6 +37,14 @@ export { TaskCreditInbox } from './monitor/TaskCreditInbox'
37
37
  export { TaskDrainOutbox, drainUnsentEntries } from './monitor/TaskDrainOutbox'
38
38
  export { getOnline, subscribeOnline, probeOnline } from './net/online'
39
39
  export { validateArcUrl } from './net/validateArcUrl'
40
+ export {
41
+ configureWocLimiter,
42
+ resetWocLimiter,
43
+ wocLimitedFetch,
44
+ WOC_ANON_INTERVAL_MS,
45
+ WOC_RATE_LIMIT_PAUSE_MS,
46
+ type WocLimiterOptions
47
+ } from './net/wocLimiter'
40
48
  export * from './logging'
41
49
  export * from './diskSpace'
42
50
  export type { AppChain, WalletChain } from './config'
@@ -0,0 +1,133 @@
1
+ /**
2
+ * One request pacer for every WhatsOnChain call in the app.
3
+ *
4
+ * WhatsOnChain answers more than 3 requests per second from one client with no
5
+ * API key with HTTP 429. Before this module, each feature paced itself or not at
6
+ * all: the Vault chain scan sent 3 history requests per index back to back, so
7
+ * an empty gap of 20 indices was 60 requests with no pause, and a sweep,
8
+ * a proof refresh or a broadcast at the same time added to the same quota.
9
+ *
10
+ * Every WhatsOnChain request now takes a slot from a lane before it is sent. A
11
+ * lane is one API origin, for requests with no key. The slot is reserved
12
+ * synchronously, before any await, so callers that start at the same moment
13
+ * queue behind each other instead of passing together. The first request on an
14
+ * idle lane goes at once.
15
+ *
16
+ * A request that carries a `woc-api-key` header uses a lane of its own: it
17
+ * counts against the key's quota, not the anonymous one. That lane has the same
18
+ * spacing by default, because the tier of a key is not known here; a host with
19
+ * a paid key can lower `keyedIntervalMs`. A 429 on any lane pushes that lane's
20
+ * next slot out by `pauseMs`.
21
+ */
22
+
23
+ /** Spacing of requests with no key: 2.5 per second, under the limit of 3 with room for network jitter. */
24
+ export const WOC_ANON_INTERVAL_MS = 400
25
+ /** Extra pause on a lane after WhatsOnChain answers 429. */
26
+ export const WOC_RATE_LIMIT_PAUSE_MS = 1500
27
+ /** The header WhatsOnChain reads an API key from. */
28
+ export const WOC_KEY_HEADER = 'woc-api-key'
29
+
30
+ export interface WocLimiterOptions {
31
+ /** Spacing of requests with no key. */
32
+ intervalMs: number
33
+ /** Spacing of requests with a key. */
34
+ keyedIntervalMs: number
35
+ /** Extra pause after a 429. */
36
+ pauseMs: number
37
+ now: () => number
38
+ sleep: (ms: number) => Promise<void>
39
+ }
40
+
41
+ const defaults = (): WocLimiterOptions => ({
42
+ intervalMs: WOC_ANON_INTERVAL_MS,
43
+ keyedIntervalMs: WOC_ANON_INTERVAL_MS,
44
+ pauseMs: WOC_RATE_LIMIT_PAUSE_MS,
45
+ now: () => Date.now(),
46
+ sleep: ms => new Promise(resolve => setTimeout(resolve, ms))
47
+ })
48
+
49
+ let options: WocLimiterOptions = defaults()
50
+ /** Lane name to the earliest time its next request may go. */
51
+ const nextSlot = new Map<string, number>()
52
+
53
+ /** Change the limiter's spacing or clock (tests, or a host with a paid key). Clears every lane. */
54
+ export function configureWocLimiter(over: Partial<WocLimiterOptions>): void {
55
+ options = { ...options, ...over }
56
+ nextSlot.clear()
57
+ }
58
+
59
+ /** Back to the default spacing and clock, with every lane idle. */
60
+ export function resetWocLimiter(): void {
61
+ options = defaults()
62
+ nextSlot.clear()
63
+ }
64
+
65
+ function originOf(url: string): string {
66
+ const match = /^[a-z][a-z0-9+.-]*:\/\/[^/?#]+/i.exec(url)
67
+ return match ? match[0].toLowerCase() : url
68
+ }
69
+
70
+ function hasKey(headers: HeadersInit | undefined): boolean {
71
+ if (!headers) return false
72
+ if (Array.isArray(headers)) return headers.some(([name, value]) => name.toLowerCase() === WOC_KEY_HEADER && !!value)
73
+ if (typeof (headers as Headers).get === 'function') return !!(headers as Headers).get(WOC_KEY_HEADER)
74
+ return Object.entries(headers as Record<string, string>).some(
75
+ ([name, value]) => name.toLowerCase() === WOC_KEY_HEADER && !!value
76
+ )
77
+ }
78
+
79
+ function laneFor(url: string, keyed: boolean): string {
80
+ return `${originOf(url)}|${keyed ? 'key' : 'anon'}`
81
+ }
82
+
83
+ /**
84
+ * Reserve this request's slot and return how long to wait for it (0 on an
85
+ * idle lane). The reservation is synchronous, so the order of calls is the
86
+ * order of requests.
87
+ */
88
+ export function reserveWocSlot(url: string, keyed = false): number {
89
+ const lane = laneFor(url, keyed)
90
+ const now = options.now()
91
+ const at = Math.max(now, nextSlot.get(lane) ?? 0)
92
+ nextSlot.set(lane, at + (keyed ? options.keyedIntervalMs : options.intervalMs))
93
+ return at - now
94
+ }
95
+
96
+ /** Wait the time that `reserveWocSlot` returned. Resolves at once for 0. */
97
+ export function waitWocSlot(ms: number): Promise<void> {
98
+ return ms > 0 ? options.sleep(ms) : Promise.resolve()
99
+ }
100
+
101
+ /** Reserve this request's slot and wait for it. */
102
+ export function wocSlot(url: string, keyed = false): Promise<void> {
103
+ return waitWocSlot(reserveWocSlot(url, keyed))
104
+ }
105
+
106
+ /** Record a 429 on a lane: its next slot moves out by `pauseMs`. */
107
+ export function wocRateLimited(url: string, keyed = false): void {
108
+ const lane = laneFor(url, keyed)
109
+ const until = options.now() + options.pauseMs
110
+ nextSlot.set(lane, Math.max(nextSlot.get(lane) ?? 0, until))
111
+ }
112
+
113
+ type FetchLike = (url: string, init?: RequestInit) => Promise<Response>
114
+
115
+ /**
116
+ * `fetch` for WhatsOnChain, paced by the shared limiter. A GET or HEAD that
117
+ * gets 429 is sent once more, after the lane's pause; the second answer is
118
+ * returned as it is, so a caller still sees a 429 that lasts.
119
+ */
120
+ export async function wocLimitedFetch(url: string, init?: RequestInit, fetchImpl?: FetchLike): Promise<Response> {
121
+ const doFetch: FetchLike = fetchImpl ?? ((u, i) => (i ? fetch(u, i) : fetch(u)))
122
+ const keyed = hasKey(init?.headers)
123
+ const method = (init?.method ?? 'GET').toUpperCase()
124
+ const retryable = method === 'GET' || method === 'HEAD'
125
+ for (let attempt = 0; ; attempt++) {
126
+ const wait = reserveWocSlot(url, keyed)
127
+ if (wait > 0) await waitWocSlot(wait)
128
+ const response = await doFetch(url, init)
129
+ if (response.status !== 429) return response
130
+ wocRateLimited(url, keyed)
131
+ if (!retryable || attempt >= 1) return response
132
+ }
133
+ }
@@ -24,6 +24,7 @@
24
24
  */
25
25
  import { Beef, Utils } from '@bsv/sdk'
26
26
  import { MAX_HEX_RESPONSE_CHARS, wocRequestInit, type WocConfig } from './rails/address'
27
+ import { wocLimitedFetch } from '../net/wocLimiter'
27
28
 
28
29
  /** Injectable for tests; production uses global fetch. */
29
30
  export type FetchLike = (
@@ -45,7 +46,8 @@ export async function refetchAtomicBeef(args: {
45
46
  fetchImpl?: FetchLike
46
47
  }): Promise<number[] | undefined> {
47
48
  const { woc, txid } = args
48
- const doFetch = args.fetchImpl ?? (globalThis.fetch as unknown as FetchLike)
49
+ // An injected fetch is used as it is; the default goes through the shared WhatsOnChain limiter.
50
+ const doFetch = args.fetchImpl ?? (wocLimitedFetch as unknown as FetchLike)
49
51
 
50
52
  let bytes: number[]
51
53
  try {
@@ -26,6 +26,7 @@ import { abbreviateKey, addressLabel, FROM_ADDRESS_LABEL_PREFIX, TO_ADDRESS_LABE
26
26
  import { addressNetwork, isValidBsvAddress } from './index'
27
27
 
28
28
  import { BRC29_PROTOCOL_ID } from '../../peerpay/brc29'
29
+ import { wocLimitedFetch } from '../../net/wocLimiter'
29
30
  export { BRC29_PROTOCOL_ID } from '../../peerpay/brc29'
30
31
 
31
32
  /** Whether the address rail can carry a particular payment, and why not when it cannot. */
@@ -183,8 +184,7 @@ export function wocRequestInit(woc: WocConfig): { headers: Record<string, string
183
184
 
184
185
  /** A WhatsOnChain GET that turns a 429 into WocRateLimited. Shared with pay/rails/sweep.ts. */
185
186
  export async function wocFetch(woc: WocConfig, url: string): Promise<Response> {
186
- const init = wocRequestInit(woc)
187
- const response = init ? await fetch(url, init) : await fetch(url)
187
+ const response = await wocLimitedFetch(url, wocRequestInit(woc))
188
188
  if (response.status === 429) throw new WocRateLimited()
189
189
  return response
190
190
  }
@@ -79,7 +79,10 @@ export function normalizeRestorePending(raw: unknown): AppChain[] | undefined {
79
79
  }
80
80
 
81
81
  export function defaultProfilesState(): ProfilesState {
82
- return { active: 0, profiles: [{ index: 0, network: e2eSafeChain(DEFAULT_CHAIN) }] }
82
+ // E2E builds set this before the toolbox loads (index.js). A fresh install
83
+ // then starts on testnet. Production never sets it, so the default stays main.
84
+ const network = (globalThis as { __BSV_E2E_CHAIN?: string }).__BSV_E2E_CHAIN === 'test' ? 'test' : DEFAULT_CHAIN
85
+ return { active: 0, profiles: [{ index: 0, network: e2eSafeChain(network) }] }
83
86
  }
84
87
 
85
88
  /** Trim and cap a profile name; undefined when nothing is left (the default label applies). */
@@ -1,6 +1,7 @@
1
1
  import { Beef, Transaction } from '@bsv/sdk'
2
2
  import type { NetworkProfile, WocEndpoints } from '../networks'
3
3
  import { trimTrailingSlashes } from '../net/trimTrailingSlashes'
4
+ import { reserveWocSlot, waitWocSlot, wocRateLimited } from '../net/wocLimiter'
4
5
  import type { PostBeefResult, PostTxResultForTxid } from '../toolboxTypes'
5
6
 
6
7
  const BROADCAST_TIMEOUT_MS = 30_000
@@ -483,6 +484,10 @@ export function createWocBroadcastService(woc: WocEndpoints, apiKey?: string) {
483
484
  Accept: 'text/plain'
484
485
  }
485
486
  if (apiKey) headers['woc-api-key'] = apiKey
487
+ // The limiter wait comes before the deadline starts, so time in the
488
+ // queue never counts against this request's timeout.
489
+ const wait = reserveWocSlot(baseUrl, !!apiKey)
490
+ if (wait > 0) await waitWocSlot(wait)
486
491
  const response = await fetchWithBodyDeadline(
487
492
  `${baseUrl}/tx/raw`,
488
493
  {
@@ -492,6 +497,7 @@ export function createWocBroadcastService(woc: WocEndpoints, apiKey?: string) {
492
497
  },
493
498
  timeoutMs
494
499
  )
500
+ if (response.status === 429) wocRateLimited(baseUrl, !!apiKey)
495
501
  const body = await response.text()
496
502
  console.log(`[${name}] POST /tx/raw ${response.status}`, loggableSnippet(body))
497
503
  const txResult: PostTxResultForTxid = {