@bsv/expo-wallet-toolbox 0.11.8 → 0.13.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 (62) hide show
  1. package/CHANGELOG.md +159 -0
  2. package/core/backup/erase.ts +7 -1
  3. package/core/backup/preference.ts +12 -4
  4. package/core/backup/push.ts +8 -1
  5. package/core/backup/status.ts +6 -2
  6. package/core/config.tsx +1 -1
  7. package/core/context/WalletContext.tsx +904 -184
  8. package/core/i18n/translations.tsx +496 -12
  9. package/core/identity/handleRegistry/registration.ts +57 -3
  10. package/core/index.ts +26 -1
  11. package/core/mandala/createRuntime.ts +3 -3
  12. package/core/mandala/runtime.ts +7 -2
  13. package/core/mnemonicWallet.ts +46 -40
  14. package/core/monitor/MonitorSupervisor.ts +35 -1
  15. package/core/monitor/TaskCreditInbox.ts +24 -0
  16. package/core/pay/beefRepair.ts +8 -3
  17. package/core/pay/rails/address.ts +43 -3
  18. package/core/pay/rails/handle.ts +5 -3
  19. package/core/pay/sweeper.ts +39 -4
  20. package/core/peerpay/outbox.ts +11 -1
  21. package/core/profiles/assertProfileEmpty.ts +287 -0
  22. package/core/profiles/discovery.ts +84 -0
  23. package/core/profiles/profileLabel.ts +13 -0
  24. package/core/profiles/profileStore.ts +265 -0
  25. package/core/profiles/purgeProfile.ts +76 -0
  26. package/core/profiles/removeProfile.ts +257 -0
  27. package/core/push/events.ts +189 -0
  28. package/core/push/identities.ts +55 -0
  29. package/core/push/profilePush.ts +143 -0
  30. package/core/push/pushAdvisory.ts +33 -0
  31. package/core/push/registration.ts +391 -0
  32. package/core/push/types.ts +35 -0
  33. package/core/services/arcTokenStorage.ts +17 -2
  34. package/core/services/vault/transfers.ts +6 -1
  35. package/core/services/vault/vaultStore.ts +16 -3
  36. package/core/stores/ConnectionStore.ts +11 -7
  37. package/core/toolboxConfig.ts +31 -4
  38. package/core/userAvatar.ts +12 -5
  39. package/core/walletDbRegistry.ts +73 -0
  40. package/package.json +1 -1
  41. package/ui/backupShares.ts +2 -3
  42. package/ui/components/pay/HandleReceive.tsx +141 -16
  43. package/ui/components/pay/MessageBoxConfig.tsx +6 -5
  44. package/ui/components/pay/NotificationAdvisoryModal.tsx +124 -0
  45. package/ui/components/ui/PencilEditField.tsx +5 -2
  46. package/ui/components/wallet/Balance.tsx +3 -1
  47. package/ui/components/wallet/ProfileButton.tsx +92 -18
  48. package/ui/components/wallet/ProfileSwitcherPopover.tsx +247 -0
  49. package/ui/hooks/useOfflineNoticeActions.ts +2 -1
  50. package/ui/hooks/useSpendableBalance.ts +3 -1
  51. package/ui/index.ts +1 -0
  52. package/ui/printRecoveryShares.ts +6 -7
  53. package/ui/screens/PairScreen.tsx +2 -1
  54. package/ui/screens/PayScreen.tsx +53 -0
  55. package/ui/screens/ProfileScreen.tsx +195 -4
  56. package/ui/screens/SettingsScreen.tsx +80 -6
  57. package/ui/screens/VaultScreen.tsx +31 -2
  58. package/ui/screens/VaultTransferScreen.tsx +25 -2
  59. package/ui/screens/WalletCheckScreen.tsx +2 -1
  60. package/ui/screens/WalletConfigScreen.tsx +51 -21
  61. package/ui/screens/WalletHomeScreen.tsx +6 -3
  62. package/ui/tokenSeen.ts +13 -9
@@ -36,7 +36,7 @@ export interface RegistrationStorage {
36
36
  setKeyValue(key: string, value: string): Promise<void>
37
37
  }
38
38
 
39
- export type RegistrationIntent = 'register' | 'update' | 'change'
39
+ export type RegistrationIntent = 'register' | 'update' | 'change' | 'release'
40
40
 
41
41
  export interface PendingStep {
42
42
  kind: 'release' | 'claim'
@@ -46,8 +46,8 @@ export interface PendingStep {
46
46
 
47
47
  /**
48
48
  * `intent` is not in the design's journal shape. `resumePending` runs a journal
49
- * it did not start and still has to say which of registered/updated/changed
50
- * happened, and no combination of the other fields tells those apart.
49
+ * it did not start and still has to say which of registered/updated/changed/
50
+ * released happened, and no combination of the other fields tells those apart.
51
51
  * `attemptedPaymail` is there for the same reason: a rollback resumed on a
52
52
  * later mount has to name the handle that was lost, and its one step is the
53
53
  * reclaim. Nothing has shipped, so the version stays 1.
@@ -72,6 +72,8 @@ export type RegistrationResult =
72
72
  | { kind: 'registered'; paymail: string }
73
73
  | { kind: 'updated'; paymail: string }
74
74
  | { kind: 'changed'; paymail: string }
75
+ /** The handle was tombstoned and nothing was claimed in its place. */
76
+ | { kind: 'released'; paymail: string }
75
77
  /** `attempted` is the handle that was lost; `paymail` is the one kept. */
76
78
  | { kind: 'rolled_back'; paymail: string; attempted?: string }
77
79
  | { kind: 'pending' }
@@ -313,6 +315,7 @@ async function runJournal(
313
315
  }
314
316
  if (journal.intent === 'update') return { kind: 'updated', paymail }
315
317
  if (journal.intent === 'change') return { kind: 'changed', paymail }
318
+ if (journal.intent === 'release') return { kind: 'released', paymail }
316
319
  return { kind: 'registered', paymail }
317
320
  }
318
321
 
@@ -545,6 +548,57 @@ export function changeHandle(
545
548
  })
546
549
  }
547
550
 
551
+ /**
552
+ * Tombstone a handle and claim nothing in its place — what removing a profile
553
+ * does to the name that points at it.
554
+ *
555
+ * The same journal discipline as every other write, and the same shape as the
556
+ * first step of `changeHandle`: a `released: true` certificate, signed by the
557
+ * live wallet and dated after everything this device has minted, written down
558
+ * before the request so a lost answer is replayed rather than re-minted. The
559
+ * registry holds the name for its cooldown afterwards; only the same key may
560
+ * reclaim it until then.
561
+ *
562
+ * Whether the registry shows a handle for this identity at all is the caller's
563
+ * question, asked before this: this releases the paymail it is handed.
564
+ *
565
+ * Anything but `released` means the handle may still be held, and that includes
566
+ * `registered`, `updated` and `changed`: an unfinished journal of any kind is
567
+ * finished first and its answer is what comes back, so a caller must read only
568
+ * `released` as done.
569
+ */
570
+ export function releaseHandle(deps: RegistrationDeps, args: { paymail: string }): Promise<RegistrationResult> {
571
+ return share(`release:${args.paymail.trim().toLowerCase()}`, async () => {
572
+ const client = deps.client
573
+ if (!client) return { kind: 'unavailable' }
574
+ try {
575
+ const outstanding = await finishOutstanding(deps, client)
576
+ if (outstanding) return outstanding
577
+ const parsed = parsePaymail(args.paymail)
578
+ if (!parsed || parsed.domain !== client.domain) {
579
+ return {
580
+ kind: 'failed',
581
+ code: 'wrong_domain',
582
+ message: `handleRegistry: not this registry's paymail: ${args.paymail}`
583
+ }
584
+ }
585
+ const paymail = `${parsed.handle}@${parsed.domain}`
586
+ const issuedAt = await nextIssuedAt(deps, client)
587
+ const cert = await buildProfileCertificate({ signer: deps.signer, paymail, issuedAt, released: true })
588
+ const journal: PendingJournal = {
589
+ v: 1,
590
+ intent: 'release',
591
+ steps: [{ kind: 'release', paymail, cert }],
592
+ startedAt: issuedAt.toISOString()
593
+ }
594
+ await writeJournal(deps.storage, journal)
595
+ return await runJournal(deps, client, journal)
596
+ } catch (e) {
597
+ return { kind: 'failed', message: messageOf(e) }
598
+ }
599
+ })
600
+ }
601
+
548
602
  /** Called on every Profile mount. Nothing journalled is the common case. */
549
603
  export function resumePending(deps: RegistrationDeps): Promise<RegistrationResult> {
550
604
  return share('resume', async () => {
package/core/index.ts CHANGED
@@ -1,6 +1,29 @@
1
1
  export const CANARY = 'core'
2
2
 
3
- export { recoverMnemonicWallet, generateMnemonicWallet, validateMnemonic } from './mnemonicWallet'
3
+ export {
4
+ recoverMnemonicWallet,
5
+ generateMnemonicWallet,
6
+ validateMnemonic,
7
+ deriveProfileKeys,
8
+ hdFromMnemonic,
9
+ profilePaths
10
+ } from './mnemonicWallet'
11
+ export {
12
+ PROFILES_STORAGE_KEY,
13
+ getActiveProfile,
14
+ getActiveProfileIndex,
15
+ getProfilesState,
16
+ liveProfiles,
17
+ profileScopedKey,
18
+ subscribeProfiles,
19
+ useActiveProfileIndex,
20
+ useProfiles,
21
+ type ProfileRecord,
22
+ type ProfilesState
23
+ } from './profiles/profileStore'
24
+ export { profileLabel } from './profiles/profileLabel'
25
+ export type { RemovalBlocker } from './profiles/assertProfileEmpty'
26
+ export type { ProfileRemovalCheck, RemoveProfileResult, RemoveRefusal } from './profiles/removeProfile'
4
27
  export {
5
28
  getRegisteredDbs,
6
29
  registerDb,
@@ -35,6 +58,7 @@ export {
35
58
  getServiceConfig,
36
59
  getMandalaEndpoints,
37
60
  getHandleRegistryConfig,
61
+ getPushAdapter,
38
62
  isAllowedServiceOrigin,
39
63
  isMandalaAvailable,
40
64
  isVaultEnabled,
@@ -42,6 +66,7 @@ export {
42
66
  resetToolboxConfig
43
67
  } from './toolboxConfig'
44
68
  export type { ToolboxConfig, ToolboxServiceConfig, MandalaEndpointConfig, HandleRegistryConfig } from './toolboxConfig'
69
+ export type { PushAdapter, PushPermission, PushOpenedEvent } from './push/types'
45
70
 
46
71
  // Theme tokens and providers
47
72
  export { ThemeProvider, useTheme } from './theme/ThemeContext'
@@ -2477,14 +2477,14 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
2477
2477
  }
2478
2478
  },
2479
2479
 
2480
- async receiveFromInbox(): Promise<{ credited: number; failed: number }> {
2480
+ async receiveFromInbox(): Promise<{ credited: number; failed: number; incomplete?: true }> {
2481
2481
  if (!available) return { credited: 0, failed: 0 }
2482
2482
  let box: MandalaMessageBox
2483
2483
  try {
2484
2484
  box = await messageBox()
2485
2485
  } catch (e) {
2486
2486
  devLog('[mandala] no MessageBox client for the inbox drain:', e)
2487
- return { credited: 0, failed: 0 }
2487
+ return { credited: 0, failed: 0, incomplete: true }
2488
2488
  }
2489
2489
 
2490
2490
  // P1-4: for every hand-over message this pass can decode, write its
@@ -2520,7 +2520,7 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
2520
2520
  // filter with — skip the whole receive rather than let a hand-over
2521
2521
  // credit run against receiveTokens with no guard in front of it.
2522
2522
  devLog('[mandala] inbox pre-hold pass failed; skipping this receive pass:', e)
2523
- return { credited: 0, failed: 0 }
2523
+ return { credited: 0, failed: 0, incomplete: true }
2524
2524
  }
2525
2525
  // A message whose pre-hold write failed is kept out of THIS
2526
2526
  // receiveTokens call only (`processed` is the library's own message
@@ -169,8 +169,13 @@ export interface MandalaRuntime {
169
169
  * place of the lib's fixed "Receive N of assetId" wording. */
170
170
  note?: string
171
171
  }): Promise<TokenSendResult>
172
- /** Handle rail: drain the MessageBox inbox (lib receiveTokens), credit, journal. */
173
- receiveFromInbox(): Promise<{ credited: number; failed: number }>
172
+ /**
173
+ * Handle rail: drain the MessageBox inbox (lib receiveTokens), credit, journal.
174
+ * `incomplete` is set when the drain could not run at all (the MessageBox could
175
+ * not be opened or read), which is not the same as an inbox with nothing in it:
176
+ * what was waiting there is still waiting.
177
+ */
178
+ receiveFromInbox(): Promise<{ credited: number; failed: number; incomplete?: true }>
174
179
  /** Nearby rail: the blinded payee lock the localpay token build needs (lib prepareBlindedPayment). */
175
180
  lockToPayee: LockToPayee
176
181
  /** Pure COVER verifier over local evidence (lib cover), for verify.ts at hand-over. */
@@ -10,57 +10,62 @@ export interface MnemonicWalletConfig {
10
10
  mnemonic?: string // Optional: provide existing mnemonic
11
11
  passphrase?: string // Optional BIP39 passphrase
12
12
  language?: 'en' | 'es' | 'fr' | 'it' | 'ja' | 'ko' | 'zh_CN' | 'zh_TW' // Default: 'en'
13
+ /** Which wallet profile to derive. Default 0. See profilePaths. */
14
+ profileIndex?: number
13
15
  }
14
16
 
15
- export interface MnemonicWalletResult {
17
+ export interface ProfileKeys {
18
+ privilegedKey: PrivateKey // Derived key at m/1'/n' for the privileged key manager
19
+ primaryKey: number[] // Derived key at m/0'/n' for wallet
20
+ identityKey: string // Public key hex of the primary key
21
+ }
22
+
23
+ export interface MnemonicWalletResult extends ProfileKeys {
16
24
  mnemonic: string
17
- rootKey: PrivateKey
18
- primaryKey: number[] // Derived key at m/0'/0' for wallet
19
- identityKey: string // Public key hex
20
25
  }
21
26
 
22
27
  /**
23
- * Generate a new mnemonic-based wallet
28
+ * The two hardened paths profile `n` derives from the shared seed. Every profile
29
+ * is a separate wallet (its own identity, storage, backup account) yet one
30
+ * mnemonic backs them all up. The privileged key sits on its own branch so no
31
+ * profile ever shares key material with another, and none uses the BIP32 master.
24
32
  */
25
- export function generateMnemonicWallet(config: MnemonicWalletConfig = {}): MnemonicWalletResult {
26
- const { passphrase = '' } = config
27
-
28
- // Generate new mnemonic or use provided one
29
- let mnemonicInstance: Mnemonic
30
- if (config.mnemonic) {
31
- // Validate and use existing mnemonic
32
- mnemonicInstance = Mnemonic.fromString(config.mnemonic)
33
- } else {
34
- // Generate new random mnemonic (128 bits = 12 words by default)
35
- mnemonicInstance = Mnemonic.fromRandom()
33
+ export function profilePaths(n: number): { primary: string; privileged: string } {
34
+ if (!Number.isInteger(n) || n < 0 || n >= 2 ** 31) {
35
+ throw new Error(`Invalid profile index: ${n}`)
36
36
  }
37
+ return { primary: `m/0'/${n}'`, privileged: `m/1'/${n}'` }
38
+ }
37
39
 
38
- // Get mnemonic as string
39
- const mnemonicString = mnemonicInstance.toString()
40
-
41
- // Derive seed from mnemonic
42
- const seed = mnemonicInstance.toSeed(passphrase)
43
-
44
- // Create HD key from seed
45
- const hdKey = HD.fromSeed(seed)
40
+ /** BIP39 seed → BIP32 root. The expensive step (PBKDF2): build once, derive many profiles. */
41
+ export function hdFromMnemonic(mnemonic: string, passphrase: string = ''): HD {
42
+ return HD.fromSeed(Mnemonic.fromString(mnemonic).toSeed(passphrase))
43
+ }
46
44
 
47
- // Get root key
48
- const rootKey = hdKey.privKey
45
+ /** Profile `n`'s keys from an already-built root. */
46
+ export function deriveProfileKeys(hdKey: HD, n: number): ProfileKeys {
47
+ const paths = profilePaths(n)
48
+ const primary = hdKey.derive(paths.primary).privKey
49
+ return {
50
+ privilegedKey: hdKey.derive(paths.privileged).privKey,
51
+ primaryKey: primary.toArray(),
52
+ identityKey: primary.toPublicKey().toString()
53
+ }
54
+ }
49
55
 
50
- // Derive primary key at path m/0'/0' (hardened derivation)
51
- // This is the key used as the wallet's primary key
52
- const derivedHdKey = hdKey.derive("m/0'/0'")
53
- const primaryKey = derivedHdKey.privKey.toArray()
56
+ /**
57
+ * Generate a new mnemonic-based wallet
58
+ */
59
+ export function generateMnemonicWallet(config: MnemonicWalletConfig = {}): MnemonicWalletResult {
60
+ const { passphrase = '', profileIndex = 0 } = config
54
61
 
55
- // Get identity key (public key) for the derived key
56
- const identityKey = derivedHdKey.privKey.toPublicKey().toString()
62
+ // Validate and use the provided mnemonic, or generate a new random one
63
+ // (128 bits = 12 words by default)
64
+ const mnemonicInstance = config.mnemonic ? Mnemonic.fromString(config.mnemonic) : Mnemonic.fromRandom()
65
+ const mnemonicString = mnemonicInstance.toString()
66
+ const hdKey = HD.fromSeed(mnemonicInstance.toSeed(passphrase))
57
67
 
58
- return {
59
- mnemonic: mnemonicString,
60
- rootKey,
61
- primaryKey,
62
- identityKey
63
- }
68
+ return { mnemonic: mnemonicString, ...deriveProfileKeys(hdKey, profileIndex) }
64
69
  }
65
70
 
66
71
  /**
@@ -68,9 +73,10 @@ export function generateMnemonicWallet(config: MnemonicWalletConfig = {}): Mnemo
68
73
  */
69
74
  export function recoverMnemonicWallet(
70
75
  mnemonic: string,
71
- passphrase: string = ''
76
+ passphrase: string = '',
77
+ profileIndex: number = 0
72
78
  ): MnemonicWalletResult {
73
- return generateMnemonicWallet({ mnemonic, passphrase })
79
+ return generateMnemonicWallet({ mnemonic, passphrase, profileIndex })
74
80
  }
75
81
 
76
82
  /**
@@ -47,6 +47,8 @@ export class MonitorSupervisor {
47
47
  restarts = 0
48
48
  private generation = 0
49
49
  private monitor: Monitor | undefined
50
+ /** Resolvers for inter-pass sleeps in progress, so `stop` can cut them short. */
51
+ private readonly sleeping = new Set<() => void>()
50
52
 
51
53
  constructor(
52
54
  private readonly now: () => number = () => Date.now(),
@@ -78,6 +80,25 @@ export class MonitorSupervisor {
78
80
  this.lastPassAt = this.now()
79
81
  }
80
82
 
83
+ /**
84
+ * Stop the loop and wake it if it is sleeping between passes, so a drain
85
+ * (stopMonitorAndDrain) waits only for a pass actually in flight — not the
86
+ * rest of the inter-pass interval. The toolbox's own `stopTasks()` only clears
87
+ * the flag the loop checks AFTER its sleep, which left every teardown (rebuild,
88
+ * network or profile switch, logout) waiting up to `taskRunWaitMsecs` for
89
+ * nothing.
90
+ */
91
+ stop(): void {
92
+ this.monitor?.stopTasks()
93
+ this.wake()
94
+ }
95
+
96
+ /** Cut short any inter-pass sleep. A loop whose monitor is still running just
97
+ * starts its next pass early; a stopped one exits and resolves its drain. */
98
+ wake(): void {
99
+ for (const wake of [...this.sleeping]) wake()
100
+ }
101
+
81
102
  isStalled(stallMs: number = MONITOR_STALL_MS): boolean {
82
103
  const state = this.monitor as unknown as LoopState | undefined
83
104
  if (!state?._tasksRunning) return false
@@ -98,6 +119,18 @@ export class MonitorSupervisor {
98
119
  return true
99
120
  }
100
121
 
122
+ /** `wait`, but `stop` can end it early. */
123
+ private sleep(ms: number): Promise<void> {
124
+ return new Promise<void>(resolve => {
125
+ const wake = () => {
126
+ this.sleeping.delete(wake)
127
+ resolve()
128
+ }
129
+ this.sleeping.add(wake)
130
+ void this.wait(ms).then(wake, wake)
131
+ })
132
+ }
133
+
101
134
  private async loop(state: LoopState, generation: number): Promise<void> {
102
135
  while (state._tasksRunning && generation === this.generation) {
103
136
  try {
@@ -109,7 +142,8 @@ export class MonitorSupervisor {
109
142
  }
110
143
  if (generation !== this.generation) return
111
144
  this.lastPassAt = this.now()
112
- await this.wait(state.options.taskRunWaitMsecs)
145
+ if (!state._tasksRunning) break
146
+ await this.sleep(state.options.taskRunWaitMsecs)
113
147
  }
114
148
  // Only the live generation may report completion: an abandoned one waking
115
149
  // up late must not resolve a drain that belongs to its successor.
@@ -18,6 +18,30 @@ export interface CreditInboxTaskResult {
18
18
  accepted: number
19
19
  attention: number
20
20
  pending?: boolean
21
+ /**
22
+ * Part of the pass could not run at all (the token box could not be read). What
23
+ * is waiting there is unknown rather than absent: the monitor retries it as
24
+ * `pending`, and the profile removal refuses to read it as an empty inbox.
25
+ */
26
+ incomplete?: boolean
27
+ }
28
+
29
+ /**
30
+ * The satoshi inbox's pass and the token inbox's drain as one result. A token
31
+ * message that failed to credit, or a token box that could not be read, is work
32
+ * left in the inbox: `pending`, so the monitor tries again and the removal check
33
+ * does not take the inbox for empty.
34
+ */
35
+ export function mergeInboxResults(
36
+ satoshis: { accepted: number; attentionCount: number; pending: boolean },
37
+ tokens: { credited: number; failed: number; incomplete?: boolean }
38
+ ): CreditInboxTaskResult {
39
+ return {
40
+ accepted: satoshis.accepted + tokens.credited,
41
+ attention: satoshis.attentionCount,
42
+ pending: satoshis.pending || tokens.failed > 0 || tokens.incomplete === true,
43
+ ...(tokens.incomplete ? { incomplete: true } : {})
44
+ }
21
45
  }
22
46
 
23
47
  export class TaskCreditInbox extends WalletMonitorTask {
@@ -23,10 +23,13 @@
23
23
  * and `makeBeefRepair` declines rather than burning an attempt on it.
24
24
  */
25
25
  import { Beef, Utils } from '@bsv/sdk'
26
- import { MAX_HEX_RESPONSE_CHARS, type WocConfig } from './rails/address'
26
+ import { MAX_HEX_RESPONSE_CHARS, wocRequestInit, type WocConfig } from './rails/address'
27
27
 
28
28
  /** Injectable for tests; production uses global fetch. */
29
- export type FetchLike = (url: string) => Promise<{ ok: boolean; status: number; text: () => Promise<string> }>
29
+ export type FetchLike = (
30
+ url: string,
31
+ init?: { headers?: Record<string, string> }
32
+ ) => Promise<{ ok: boolean; status: number; text: () => Promise<string> }>
30
33
 
31
34
  /**
32
35
  * The current AtomicBEEF for `txid`, or undefined if the network cannot supply
@@ -46,7 +49,9 @@ export async function refetchAtomicBeef(args: {
46
49
 
47
50
  let bytes: number[]
48
51
  try {
49
- const resp = await doFetch(`${woc.apiBase}/v1/bsv/${woc.segment}/tx/${txid}/beef`)
52
+ const url = `${woc.apiBase}/v1/bsv/${woc.segment}/tx/${txid}/beef`
53
+ const init = wocRequestInit(woc)
54
+ const resp = init ? await doFetch(url, init) : await doFetch(url)
50
55
  // Checked, because the body of a 404 is prose. `Utils.toArray(prose, 'hex')`
51
56
  // throws "Invalid hex string", and an empty body parses to a Beef whose
52
57
  // magic check fails — both of which would surface as a confusing error from
@@ -137,6 +137,14 @@ export interface WocConfig {
137
137
  apiBase: string
138
138
  segment: string
139
139
  network: 'mainnet' | 'testnet'
140
+ /**
141
+ * A WhatsOnChain key, sent only as the `woc-api-key` header (see
142
+ * `wocRequestInit`); never logged. `wocConfigFor` does not set it: the
143
+ * host's app-wide key is shared with broadcast, and a 5 s sweep across the
144
+ * whole fleet would drain that quota. A caller with a key of its own may set
145
+ * it explicitly.
146
+ */
147
+ apiKey?: string
140
148
  }
141
149
 
142
150
  export function wocConfigFor(network: AppChain): WocConfig {
@@ -147,6 +155,35 @@ export function wocConfigFor(network: AppChain): WocConfig {
147
155
  }[network]
148
156
  }
149
157
 
158
+ /**
159
+ * HTTP 429 from WhatsOnChain. A type of its own because it is the one failure
160
+ * of these fetches the caller must not treat like the rest: the sweep polls
161
+ * every 5 s, so "try again next tick" is exactly the behaviour that keeps a
162
+ * rate limit alive. It lets the sweep stop the pass and back off instead.
163
+ */
164
+ export class WocRateLimited extends Error {
165
+ constructor() {
166
+ super('WhatsOnChain rate limit reached')
167
+ this.name = 'WocRateLimited'
168
+ }
169
+ }
170
+
171
+ /**
172
+ * The request options carrying the WhatsOnChain key, or undefined when the
173
+ * config has none — so that a config without a key sends the same bare request
174
+ * it always did.
175
+ */
176
+ export function wocRequestInit(woc: WocConfig): { headers: Record<string, string> } | undefined {
177
+ return woc.apiKey ? { headers: { 'woc-api-key': woc.apiKey } } : undefined
178
+ }
179
+
180
+ async function wocFetch(woc: WocConfig, url: string): Promise<Response> {
181
+ const init = wocRequestInit(woc)
182
+ const response = init ? await fetch(url, init) : await fetch(url)
183
+ if (response.status === 429) throw new WocRateLimited()
184
+ return response
185
+ }
186
+
150
187
  export interface AddressDerivingWallet {
151
188
  getPublicKey(args: unknown, originator?: string): Promise<{ publicKey: string }>
152
189
  }
@@ -201,7 +238,7 @@ export const MAX_UTXO_LISTING_ROWS = 2000
201
238
  export const MAX_HEX_RESPONSE_CHARS = 8_000_000
202
239
 
203
240
  export async function getUtxosForAddress(woc: WocConfig, address: string): Promise<Utxo[]> {
204
- const response = await fetch(`${woc.apiBase}/v1/bsv/${woc.segment}/address/${address}/unspent/all`)
241
+ const response = await wocFetch(woc, `${woc.apiBase}/v1/bsv/${woc.segment}/address/${address}/unspent/all`)
205
242
  const rp = await response.json()
206
243
  // A live receive address never legitimately carries anywhere near this many
207
244
  // UTXOs; sweepAddress fetches one BEEF per distinct txid in the result, so
@@ -396,7 +433,7 @@ export async function sweepAddress(args: {
396
433
  for (const txid of txids) {
397
434
  const relevant = byTxid.get(txid) as Utxo[]
398
435
  try {
399
- const resp = await fetch(`${woc.apiBase}/v1/bsv/${woc.segment}/tx/${txid}/beef`)
436
+ const resp = await wocFetch(woc, `${woc.apiBase}/v1/bsv/${woc.segment}/tx/${txid}/beef`)
400
437
  const bytes = parseWocBeefBody({ ok: resp.ok, text: await resp.text() })
401
438
  if (!bytes) {
402
439
  failureCount++
@@ -450,7 +487,10 @@ export async function sweepAddress(args: {
450
487
  if (response?.accepted) {
451
488
  importedSatoshis += verified.reduce((sum, o) => sum + (tx.outputs[o.vout]?.satoshis ?? 0), 0)
452
489
  } else failureCount++
453
- } catch {
490
+ } catch (error) {
491
+ // A rate limit is not this payment's failure: the rest of the pass would
492
+ // only be refused the same way, so let it stop the sweep (see runSweep).
493
+ if (error instanceof WocRateLimited) throw error
454
494
  failureCount++
455
495
  }
456
496
  }
@@ -26,7 +26,7 @@ import { TaskDrainOutbox } from '../../monitor/TaskDrainOutbox'
26
26
  import type { MandalaRuntime, TokenSendResult } from '../../mandala/runtime'
27
27
 
28
28
  export const MESSAGE_BOX_URL_KEY = 'message_box_url'
29
- export const DEFAULT_MESSAGE_BOX_URL = 'https://gmb.bsvblockchain.tech'
29
+ export const DEFAULT_MESSAGE_BOX_URL = 'https://messagebox.bsvblockchain.tech'
30
30
  /** The previous default. A saved preference equal to it is treated as "use the
31
31
  * default", so existing installs follow the default forward. */
32
32
  export const LEGACY_MESSAGE_BOX_URL = 'https://messagebox.babbage.systems'
@@ -711,13 +711,15 @@ export async function sendTokenViaHandle(args: {
711
711
  */
712
712
  export async function drainMandalaInbox(
713
713
  runtime: HandleTokenRuntime | undefined
714
- ): Promise<{ credited: number; failed: number }> {
714
+ ): Promise<{ credited: number; failed: number; incomplete?: true }> {
715
715
  if (!runtime?.available) return { credited: 0, failed: 0 }
716
716
  try {
717
717
  return await runtime.receiveFromInbox()
718
718
  } catch (e) {
719
719
  console.warn('[mandala] the token inbox drain failed:', e instanceof Error ? e.message : String(e))
720
- return { credited: 0, failed: 0 }
720
+ // Not `{ 0, 0 }` alone: that reads as an inbox with nothing in it, and a
721
+ // caller that must know (the profile removal) has to be able to tell.
722
+ return { credited: 0, failed: 0, incomplete: true }
721
723
  }
722
724
  }
723
725
 
@@ -10,11 +10,43 @@
10
10
  * Every bound is deliberate and tested: see shouldSweepNow for when a pass may
11
11
  * run at all, and pay/watchlist.ts for which addresses it may touch.
12
12
  */
13
- import { sweepAddress, type AddressRailWallet, type WocConfig } from './rails/address'
13
+ import { sweepAddress, WocRateLimited, type AddressRailWallet, type WocConfig } from './rails/address'
14
14
  import { getWatchlist, touchWatched, type KVStorage } from './watchlist'
15
15
 
16
- /** One poll every 30s — an order of magnitude cheaper than the 3s screen poll it replaces. */
17
- export const SWEEP_INTERVAL_MS = 30_000
16
+ /**
17
+ * One poll every 5s, foreground only (shouldSweepNow refuses in the background).
18
+ *
19
+ * An address payment announces itself to no one: unlike the handle and nearby
20
+ * rails there is no MessageBox message to push, so the only way this wallet
21
+ * learns of one is to look. 5s is what makes "show the address, money appears"
22
+ * feel immediate to a user watching the screen. The cost is up to ~1.6 WhatsOnChain
23
+ * requests/s on a device with the full 8 watched addresses. The requests carry
24
+ * no API key on purpose: the host's app-wide key is shared with broadcast, and
25
+ * a fleet polling at 5s would drain its quota. So the sweep runs on WhatsOnChain's
26
+ * anonymous limit, and a 429 backs it off (SWEEP_BACKOFF_TICKS) rather than
27
+ * being retried on the next tick.
28
+ */
29
+ export const SWEEP_INTERVAL_MS = 5_000
30
+
31
+ /** Ticks to sit out after a WhatsOnChain 429: 30s at SWEEP_INTERVAL_MS. */
32
+ export const SWEEP_BACKOFF_TICKS = 6
33
+
34
+ /**
35
+ * Spend one tick of a pending backoff. Pure so the caller's counter (a plain
36
+ * variable in the sweep effect's closure) is tested here rather than through a
37
+ * provider.
38
+ */
39
+ export function consumeBackoff(remaining: number): { skip: boolean; remaining: number } {
40
+ return remaining > 0 ? { skip: true, remaining: remaining - 1 } : { skip: false, remaining: 0 }
41
+ }
42
+
43
+ /**
44
+ * The backoff after a failed pass: a full SWEEP_BACKOFF_TICKS for a rate limit,
45
+ * unchanged for anything else (those stay best-effort — the next tick retries).
46
+ */
47
+ export function backoffAfterSweepError(error: unknown, remaining: number): number {
48
+ return error instanceof WocRateLimited ? SWEEP_BACKOFF_TICKS : remaining
49
+ }
18
50
 
19
51
  export interface SweepOutcome {
20
52
  address: string
@@ -61,7 +93,10 @@ export async function runSweep(args: {
61
93
  // rather than retiring it the moment it pays out. A funded address whose
62
94
  // import failed must stay watched too, or a bad BEEF fetch TTL-drops it.
63
95
  if (importedSatoshis > 0 || foundOnChain) await touchWatched(storage, watched.address)
64
- } catch {
96
+ } catch (error) {
97
+ // A rate limit is the one failure that does stop the pass: the other
98
+ // addresses would be refused the same way and only deepen the limit.
99
+ if (error instanceof WocRateLimited) throw error
65
100
  // A dead WoC host or a locked wallet must not stop the rest of the pass.
66
101
  // The entry stays watched and the next pass retries it.
67
102
  }
@@ -108,7 +108,7 @@ function withOutboxLock<T>(storage: StorageLike, fn: () => Promise<T>): Promise<
108
108
  return run
109
109
  }
110
110
 
111
- async function readEntries(storage: StorageLike): Promise<OutboxEntry[]> {
111
+ async function readEntries(storage: Pick<StorageLike, 'getKeyValue'>): Promise<OutboxEntry[]> {
112
112
  // Mutations must fail closed: treating an unreadable queue as empty would
113
113
  // erase persisted tokens when the subsequent write succeeds.
114
114
  const raw = await storage.getKeyValue(OUTBOX_KEY)
@@ -136,6 +136,16 @@ export async function getOutboxEntries(storage: StorageLike): Promise<OutboxEntr
136
136
  }
137
137
  }
138
138
 
139
+ /**
140
+ * Every outbox entry, or a throw when the queue cannot be read.
141
+ *
142
+ * For a caller that must not mistake "could not read" for "nothing owed" —
143
+ * removing a profile deletes the database this queue lives in.
144
+ */
145
+ export async function getOutboxEntriesStrict(storage: Pick<StorageLike, 'getKeyValue'>): Promise<OutboxEntry[]> {
146
+ return readEntries(storage)
147
+ }
148
+
139
149
  /**
140
150
  * Persist a new outbound payment token to the outbox before delivery is attempted.
141
151
  * Returns the generated entry ID.