@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.
- package/CHANGELOG.md +159 -0
- package/core/backup/erase.ts +7 -1
- package/core/backup/preference.ts +12 -4
- package/core/backup/push.ts +8 -1
- package/core/backup/status.ts +6 -2
- package/core/config.tsx +1 -1
- package/core/context/WalletContext.tsx +904 -184
- package/core/i18n/translations.tsx +496 -12
- package/core/identity/handleRegistry/registration.ts +57 -3
- package/core/index.ts +26 -1
- package/core/mandala/createRuntime.ts +3 -3
- package/core/mandala/runtime.ts +7 -2
- package/core/mnemonicWallet.ts +46 -40
- package/core/monitor/MonitorSupervisor.ts +35 -1
- package/core/monitor/TaskCreditInbox.ts +24 -0
- package/core/pay/beefRepair.ts +8 -3
- package/core/pay/rails/address.ts +43 -3
- package/core/pay/rails/handle.ts +5 -3
- package/core/pay/sweeper.ts +39 -4
- package/core/peerpay/outbox.ts +11 -1
- package/core/profiles/assertProfileEmpty.ts +287 -0
- package/core/profiles/discovery.ts +84 -0
- package/core/profiles/profileLabel.ts +13 -0
- package/core/profiles/profileStore.ts +265 -0
- package/core/profiles/purgeProfile.ts +76 -0
- package/core/profiles/removeProfile.ts +257 -0
- package/core/push/events.ts +189 -0
- package/core/push/identities.ts +55 -0
- package/core/push/profilePush.ts +143 -0
- package/core/push/pushAdvisory.ts +33 -0
- package/core/push/registration.ts +391 -0
- package/core/push/types.ts +35 -0
- package/core/services/arcTokenStorage.ts +17 -2
- package/core/services/vault/transfers.ts +6 -1
- package/core/services/vault/vaultStore.ts +16 -3
- package/core/stores/ConnectionStore.ts +11 -7
- package/core/toolboxConfig.ts +31 -4
- package/core/userAvatar.ts +12 -5
- package/core/walletDbRegistry.ts +73 -0
- package/package.json +1 -1
- package/ui/backupShares.ts +2 -3
- package/ui/components/pay/HandleReceive.tsx +141 -16
- package/ui/components/pay/MessageBoxConfig.tsx +6 -5
- package/ui/components/pay/NotificationAdvisoryModal.tsx +124 -0
- package/ui/components/ui/PencilEditField.tsx +5 -2
- package/ui/components/wallet/Balance.tsx +3 -1
- package/ui/components/wallet/ProfileButton.tsx +92 -18
- package/ui/components/wallet/ProfileSwitcherPopover.tsx +247 -0
- package/ui/hooks/useOfflineNoticeActions.ts +2 -1
- package/ui/hooks/useSpendableBalance.ts +3 -1
- package/ui/index.ts +1 -0
- package/ui/printRecoveryShares.ts +6 -7
- package/ui/screens/PairScreen.tsx +2 -1
- package/ui/screens/PayScreen.tsx +53 -0
- package/ui/screens/ProfileScreen.tsx +195 -4
- package/ui/screens/SettingsScreen.tsx +80 -6
- package/ui/screens/VaultScreen.tsx +31 -2
- package/ui/screens/VaultTransferScreen.tsx +25 -2
- package/ui/screens/WalletCheckScreen.tsx +2 -1
- package/ui/screens/WalletConfigScreen.tsx +51 -21
- package/ui/screens/WalletHomeScreen.tsx +6 -3
- 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 {
|
|
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
|
package/core/mandala/runtime.ts
CHANGED
|
@@ -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
|
-
/**
|
|
173
|
-
|
|
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. */
|
package/core/mnemonicWallet.ts
CHANGED
|
@@ -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
|
|
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
|
-
*
|
|
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
|
|
26
|
-
|
|
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
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
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
|
-
|
|
48
|
-
|
|
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
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
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
|
-
//
|
|
56
|
-
|
|
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
|
-
|
|
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 {
|
package/core/pay/beefRepair.ts
CHANGED
|
@@ -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 = (
|
|
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
|
|
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
|
|
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
|
|
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
|
}
|
package/core/pay/rails/handle.ts
CHANGED
|
@@ -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://
|
|
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
|
-
|
|
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
|
|
package/core/pay/sweeper.ts
CHANGED
|
@@ -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
|
-
/**
|
|
17
|
-
|
|
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
|
}
|
package/core/peerpay/outbox.ts
CHANGED
|
@@ -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.
|