@bsv/expo-wallet-toolbox 0.19.0 → 0.21.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 (141) hide show
  1. package/CHANGELOG.md +154 -30
  2. package/README.md +79 -79
  3. package/core/backup/RemoteSyncReader.ts +26 -24
  4. package/core/backup/appData.ts +9 -8
  5. package/core/backup/codec.ts +21 -18
  6. package/core/backup/constants.ts +5 -5
  7. package/core/backup/contactsBackup.ts +8 -8
  8. package/core/backup/cursor.ts +12 -7
  9. package/core/backup/derive.ts +3 -3
  10. package/core/backup/deviceId.ts +2 -2
  11. package/core/backup/erase.ts +2 -2
  12. package/core/backup/preference.ts +2 -2
  13. package/core/backup/push.ts +10 -12
  14. package/core/backup/restore.ts +22 -14
  15. package/core/backup/restoreOnImport.ts +3 -2
  16. package/core/config.tsx +17 -13
  17. package/core/constants.ts +34 -11
  18. package/core/contacts/contactsStore.ts +4 -3
  19. package/core/context/WalletConnectionContext.tsx +294 -212
  20. package/core/context/WalletContext.tsx +132 -97
  21. package/core/context/defaultWalletSettings.ts +4 -2
  22. package/core/demo/demoLedger.ts +1 -5
  23. package/core/directpay/DirectPayManager.ts +148 -29
  24. package/core/directpay/DirectPayProvider.tsx +26 -26
  25. package/core/directpay/payFlow.ts +10 -1
  26. package/core/directpay/receive.ts +2 -1
  27. package/core/directpay/settings.ts +56 -9
  28. package/core/directpay/types.ts +11 -2
  29. package/core/directpay/webrtpay.ts +4 -0
  30. package/core/headers/checkpoints.ts +10 -1
  31. package/core/headers/headerStore.ts +13 -2
  32. package/core/hooks/useConfirmationSound.ts +3 -3
  33. package/core/hooks/useHaptics.ts +23 -6
  34. package/core/i18n/translations.tsx +382 -209
  35. package/core/index.ts +2 -0
  36. package/core/localpay/codec.ts +12 -6
  37. package/core/localpay/deviceCaps.ts +4 -14
  38. package/core/localpay/pending.ts +2 -1
  39. package/core/localpay/qr.ts +1 -1
  40. package/core/localpay/settlementAck.ts +1 -4
  41. package/core/localpay/transport/ble.ts +2 -2
  42. package/core/localpay/transport/socket.ts +1 -1
  43. package/core/mandala/abortGuard.ts +1 -1
  44. package/core/mandala/drain.ts +3 -0
  45. package/core/mandala/permissionModule.ts +3 -2
  46. package/core/mandala/resendTransfer.ts +4 -1
  47. package/core/mandala/runtime.ts +4 -4
  48. package/core/monitor/TaskBackupPush.ts +10 -13
  49. package/core/net/chainMatch.ts +8 -5
  50. package/core/networks.ts +145 -0
  51. package/core/parsePeerPayURI.ts +4 -1
  52. package/core/pay/beefRepair.ts +6 -3
  53. package/core/pay/creditErrors.ts +37 -1
  54. package/core/pay/rails/address.ts +10 -6
  55. package/core/pay/rails/direct.ts +6 -2
  56. package/core/pay/rails/handle.ts +84 -11
  57. package/core/pay/rails/index.ts +18 -2
  58. package/core/pay/receiveHistory.ts +8 -8
  59. package/core/peerpay/handleResendRequests.ts +11 -18
  60. package/core/peerpay/inboxAttempts.ts +1 -4
  61. package/core/peerpay/rebuildToken.ts +12 -9
  62. package/core/profiles/profileStore.ts +2 -1
  63. package/core/profiles/removalProblems.ts +3 -1
  64. package/core/services/arcTokenStorage.ts +2 -1
  65. package/core/services/arcadeBroadcastProvider.ts +7 -17
  66. package/core/services/secrets/envelope.ts +1 -6
  67. package/core/services/secrets/hkdf.ts +1 -6
  68. package/core/services/secrets/index.ts +3 -22
  69. package/core/services/usdFxRates.ts +1 -4
  70. package/core/services/vault/VaultKeyService.ts +2 -1
  71. package/core/services/vault/chainRecovery.ts +48 -21
  72. package/core/services/vault/metaAuthority.ts +4 -1
  73. package/core/services/vault/r1comb.ts +113 -51
  74. package/core/services/vault/session.ts +5 -1
  75. package/core/services/vault/transfers.ts +699 -576
  76. package/core/services/vault/vaultStore.ts +12 -10
  77. package/core/services/walletArgLimits.ts +1 -2
  78. package/core/services/walletConnectionValidation.ts +44 -28
  79. package/core/services/walletServiceConfig.ts +9 -40
  80. package/core/storage/StorageExpoSQLite.ts +7 -21
  81. package/core/storage/methods/listActionsSql.ts +81 -67
  82. package/core/storage/methods/listOutputsSql.ts +21 -16
  83. package/core/storage/methods/reviewStatusSql.ts +1 -4
  84. package/core/stores/ConnectionStore.ts +1 -1
  85. package/core/theme/ThemeContext.tsx +12 -16
  86. package/core/theme/motion.ts +3 -3
  87. package/core/theme/tokens.ts +6 -6
  88. package/core/toolboxConfig.ts +23 -0
  89. package/core/walletDbRegistry.ts +7 -5
  90. package/core/walletRepair/runWalletCheck.ts +1 -4
  91. package/package.json +2 -2
  92. package/ui/components/pay/AddressReceive.tsx +3 -3
  93. package/ui/components/pay/HandleReceive.tsx +21 -15
  94. package/ui/components/pay/MessageBoxConfig.tsx +46 -20
  95. package/ui/components/pay/NearbyFlow.tsx +575 -507
  96. package/ui/components/pay/OfflineNotice.tsx +1 -3
  97. package/ui/components/pay/PayCellRow.tsx +1 -4
  98. package/ui/components/pay/PayForm.tsx +1 -3
  99. package/ui/components/pay/RequestHub.tsx +14 -6
  100. package/ui/components/pay/UniversalSend.tsx +79 -27
  101. package/ui/components/pay/tokenSendCopy.ts +1 -2
  102. package/ui/components/pay/useRecipientInput.ts +2 -2
  103. package/ui/components/security/WalletLockNotice.tsx +1 -3
  104. package/ui/components/ui/AlertCard.tsx +44 -45
  105. package/ui/components/ui/BlurChrome.tsx +4 -15
  106. package/ui/components/ui/Celebration.tsx +3 -3
  107. package/ui/components/ui/ChoiceSheet.ts +1 -3
  108. package/ui/components/ui/ErrorBoundary.tsx +2 -6
  109. package/ui/components/ui/GroupedList.tsx +13 -31
  110. package/ui/components/ui/IconButton.tsx +6 -9
  111. package/ui/components/ui/ListRow.tsx +19 -25
  112. package/ui/components/ui/PresenceRow.tsx +4 -4
  113. package/ui/components/ui/PressableScale.tsx +24 -20
  114. package/ui/components/ui/Toast.tsx +23 -16
  115. package/ui/components/vault/KeyChooser.tsx +9 -6
  116. package/ui/components/vault/VaultBackdrop.tsx +1 -8
  117. package/ui/components/vault/VaultCeremonySheet.tsx +5 -5
  118. package/ui/components/wallet/ActivityRow.tsx +3 -2
  119. package/ui/components/wallet/BackupReminderSheet.tsx +1 -5
  120. package/ui/components/wallet/Balance.tsx +4 -1
  121. package/ui/components/wallet/ContactActivityList.tsx +7 -7
  122. package/ui/components/wallet/IconPickerSheet.tsx +1 -5
  123. package/ui/components/wallet/ProfileSwitcherPopover.tsx +6 -1
  124. package/ui/components/wallet/tokenEviction.ts +4 -1
  125. package/ui/hooks/useMandala.ts +1 -7
  126. package/ui/hooks/useOfflineNoticeActions.ts +21 -27
  127. package/ui/hooks/useSpendableBalance.ts +2 -2
  128. package/ui/hooks/useVaultCoverage.ts +7 -1
  129. package/ui/index.ts +9 -1
  130. package/ui/resolveIdentity.ts +20 -8
  131. package/ui/screens/ConnectionsScreen.tsx +44 -18
  132. package/ui/screens/LogsScreen.tsx +24 -22
  133. package/ui/screens/PairScreen.tsx +85 -54
  134. package/ui/screens/PayScreen.tsx +5 -1
  135. package/ui/screens/ProfileScreen.tsx +0 -3
  136. package/ui/screens/TrustScreen.tsx +125 -80
  137. package/ui/screens/VaultScreen.tsx +19 -7
  138. package/ui/screens/VaultTransferScreen.tsx +5 -1
  139. package/ui/screens/WalletCheckScreen.tsx +14 -17
  140. package/ui/screens/WalletConfigScreen.tsx +414 -376
  141. package/ui/screens/WalletHomeScreen.tsx +47 -42
package/core/index.ts CHANGED
@@ -40,6 +40,8 @@ export { validateArcUrl } from './net/validateArcUrl'
40
40
  export * from './logging'
41
41
  export * from './diskSpace'
42
42
  export type { AppChain, WalletChain } from './config'
43
+ export { APP_CHAINS, NETWORKS, isAppChain, hasOverlay } from './networks'
44
+ export type { NetworkProfile, OverlayPreset, WocEndpoints } from './networks'
43
45
  export {
44
46
  toWalletChain,
45
47
  DEFAULT_WAB_URL,
@@ -13,10 +13,10 @@ export class CodecError extends Error {
13
13
  export type FrameKind = 'bsv' | 'token'
14
14
 
15
15
  export interface TokenPayment {
16
- assetId: string // "<64-hex txid>.<vout>"
16
+ assetId: string // "<64-hex txid>.<vout>"
17
17
  overlayUrl: string
18
- overlayIdentityKey: string // 66-hex compressed pubkey
19
- certificates: Uint8Array[] // opaque serialized VerifiableCertificates
18
+ overlayIdentityKey: string // 66-hex compressed pubkey
19
+ certificates: Uint8Array[] // opaque serialized VerifiableCertificates
20
20
  linkage: Array<{ txid: string; payload: Uint8Array }> // per-txid MandalaLinkagePayload bytes, whole chain
21
21
  /**
22
22
  * σ_I evidence for the ancestors this frame's chain bottoms out at — the
@@ -183,7 +183,8 @@ export function encodeFrame(f: PaymentFrame): Uint8Array {
183
183
  }
184
184
  putVarint(out, t.admissions.length)
185
185
  for (const entry of t.admissions) {
186
- if (entry.txid.length !== 64) throw new CodecError(`admission txid must be 64 hex chars, got ${entry.txid.length}`)
186
+ if (entry.txid.length !== 64)
187
+ throw new CodecError(`admission txid must be 64 hex chars, got ${entry.txid.length}`)
187
188
  // Same shape check the overlay key already gets: a signerKey that is not
188
189
  // a 33-byte compressed point can never verify, and one that is silently
189
190
  // truncated on the wire would verify against a DIFFERENT key on the far
@@ -258,10 +259,15 @@ export function decodeFrame(b: Uint8Array): PaymentFrame {
258
259
  const transaction = getBytes(b, pos)
259
260
  if (pos.i !== b.length) throw new CodecError('trailing bytes after frame')
260
261
  return {
261
- version, kind, senderIdentityKey, outputIndex, derivationPrefix, derivationSuffix,
262
+ version,
263
+ kind,
264
+ senderIdentityKey,
265
+ outputIndex,
266
+ derivationPrefix,
267
+ derivationSuffix,
262
268
  ...(token === undefined ? {} : { token }),
263
269
  ...(note ? { note } : {}),
264
- transaction,
270
+ transaction
265
271
  }
266
272
  }
267
273
 
@@ -19,15 +19,7 @@
19
19
  import { Platform } from 'react-native'
20
20
  import NetInfo, { type NetInfoState } from '@react-native-community/netinfo'
21
21
  import { getLocalPayBleTransport } from '@bsv/react-native-localpay-transport'
22
- import {
23
- HINT_BT,
24
- HINT_NET,
25
- HINT_NFC,
26
- HINT_ONLINE,
27
- HINT_ONLINE_KNOWN,
28
- HINT_WIFI,
29
- RUNG_MASK,
30
- } from './session'
22
+ import { HINT_BT, HINT_NET, HINT_NFC, HINT_ONLINE, HINT_ONLINE_KNOWN, HINT_WIFI, RUNG_MASK } from './session'
31
23
 
32
24
  /** Mirrors LocalPayBleTransport.bluetoothState(); anything else coerces to 'unknown'. */
33
25
  export type BluetoothState = 'poweredOn' | 'poweredOff' | 'unauthorized' | 'unsupported' | 'unknown'
@@ -58,7 +50,7 @@ const BLUETOOTH_STATES: readonly BluetoothState[] = [
58
50
  'poweredOff',
59
51
  'unauthorized',
60
52
  'unsupported',
61
- 'unknown',
53
+ 'unknown'
62
54
  ]
63
55
 
64
56
  /**
@@ -145,15 +137,13 @@ function readNfcAvailable(): boolean {
145
137
  */
146
138
  export async function probeDeviceCaps(opts?: { netBudgetMs?: number }): Promise<DeviceProbe> {
147
139
  const net = await fetchNetWithinBudget(opts?.netBudgetMs ?? DEFAULT_NET_BUDGET_MS)
148
- const wifi =
149
- net !== null &&
150
- (Platform.OS === 'android' ? net.isWifiEnabled === true : net.type === 'wifi')
140
+ const wifi = net !== null && (Platform.OS === 'android' ? net.isWifiEnabled === true : net.type === 'wifi')
151
141
  return {
152
142
  online: net === null ? null : net.isInternetReachable,
153
143
  connected: net === null ? null : net.isConnected,
154
144
  wifi,
155
145
  bluetooth: readBluetoothState(),
156
- nfc: readNfcAvailable(),
146
+ nfc: readNfcAvailable()
157
147
  }
158
148
  }
159
149
 
@@ -8,6 +8,7 @@ import { MANDALA_ACTION_LABEL, MANDALA_BASKET } from '../mandala/bundle'
8
8
  import { MANDALA_ACTION_LABEL as MANDALA_TOKEN_SPEND_LABEL } from '../mandala/permissionModule'
9
9
  import type { AdmissionEntryWire } from '../mandala/types'
10
10
  import { isRetriableInternalizeFailure } from '../mandala/drain'
11
+ import { failedPostReason } from '../pay/creditErrors'
11
12
 
12
13
  export const PENDING_KEY = 'localpay_pending'
13
14
  /**
@@ -665,7 +666,7 @@ export async function processPending(
665
666
  }
666
667
  }
667
668
  } catch (e) {
668
- const error = e instanceof Error ? e.message : String(e)
669
+ const error = failedPostReason(e) ?? (e instanceof Error ? e.message : String(e))
669
670
  await updateStatus(storage, p.id, 'failed', error)
670
671
  results.push({ id: p.id, success: false, error })
671
672
  }
@@ -12,5 +12,5 @@ export const qrTransport: LocalPaymentTransport = {
12
12
  },
13
13
  send() {
14
14
  return Promise.reject(new QrHandoffRequired())
15
- },
15
+ }
16
16
  }
@@ -46,10 +46,7 @@ export interface SettlementAck {
46
46
  * signed it. Injected: the σ_I digest is the overlay's own and lives in
47
47
  * `@bsv/mandala`, so wallet and overlay cannot disagree about what is signed.
48
48
  */
49
- export type VerifyAdmissionFn = (
50
- entry: AdmissionEntryWire,
51
- overlayIdentityKey: string
52
- ) => boolean | Promise<boolean>
49
+ export type VerifyAdmissionFn = (entry: AdmissionEntryWire, overlayIdentityKey: string) => boolean | Promise<boolean>
53
50
 
54
51
  export function encodeSettlementAck(ack: SettlementAck): string {
55
52
  return SETTLEMENT_ACK_PREFIX + JSON.stringify(ack)
@@ -116,7 +116,7 @@ export function makeBleTransport(
116
116
  toBase64(session.psk),
117
117
  toBase64(sealFrame(frame, session.psk)),
118
118
  SEND_TIMEOUT_MS,
119
- connectTimeoutMs,
119
+ connectTimeoutMs
120
120
  ] as const
121
121
  } catch (e) {
122
122
  settled = true
@@ -146,7 +146,7 @@ export function makeBleTransport(
146
146
  }
147
147
  )
148
148
  })
149
- },
149
+ }
150
150
  }
151
151
  }
152
152
 
@@ -297,6 +297,6 @@ export function makeSocketTransport(
297
297
  }
298
298
  )
299
299
  })
300
- },
300
+ }
301
301
  }
302
302
  }
@@ -183,7 +183,7 @@ export function wrapAbortActionForSettlements<T extends AbortableManager>(
183
183
  return { aborted: false }
184
184
  }
185
185
  } catch (e) {
186
- console.warn('[mandala] refusing to abort: could not read this action\'s settlement state:', e)
186
+ console.warn("[mandala] refusing to abort: could not read this action's settlement state:", e)
187
187
  return { aborted: false }
188
188
  }
189
189
  return await target.abortAction(args, originator)
@@ -711,6 +711,9 @@ const RETRIABLE_INTERNALIZE_PATTERNS: readonly RegExp[] = [
711
711
  /network request failed/i,
712
712
  /timed? ?out/i,
713
713
  /econnreset|econnrefused|enotfound|fetch failed/i,
714
+ // internalizeAction posts an unproven payment itself (wallet-toolbox-mobile
715
+ // 2.14.7+); when no broadcaster answered, `failedPostReason` says so.
716
+ /no broadcaster could be reached/i,
714
717
  // `processPending`'s own pre-internalize settlement write (§4.2/§4.3 guard
715
718
  // #2). A failure there is a local storage fault, not a bad frame: the money
716
719
  // is real, the frame is durable, and the next tick tries the same write
@@ -444,7 +444,9 @@ export class MandalaTokenModule implements PermissionsModule {
444
444
  /** This originator's unexpired approved transactions; prunes the rest. */
445
445
  private liveAuthorizedTransactions(originator: string): { digests: Set<string>; timestamp: number }[] {
446
446
  const now = Date.now()
447
- const live = (this.authorizedTransactions.get(originator) ?? []).filter(t => now - t.timestamp <= SESSION_TIMEOUT_MS)
447
+ const live = (this.authorizedTransactions.get(originator) ?? []).filter(
448
+ t => now - t.timestamp <= SESSION_TIMEOUT_MS
449
+ )
448
450
  if (live.length === 0) this.authorizedTransactions.delete(originator)
449
451
  else this.authorizedTransactions.set(originator, live)
450
452
  return live
@@ -616,7 +618,6 @@ export class MandalaTokenModule implements PermissionsModule {
616
618
  }
617
619
  }
618
620
 
619
-
620
621
  /**
621
622
  * createAction with an output in `'p mandala'` — always prompts (mirrors
622
623
  * BTMS's `handleCreateAction`, which never skips on an existing session;
@@ -84,7 +84,10 @@ interface Marker extends Partial<TokenResendRecord> {
84
84
  }
85
85
 
86
86
  /** The payee output's `recipientCustomInstructions`, and which output carried it. */
87
- async function findMarker(action: TokenResendAction | undefined, decrypt?: (v: string) => Promise<string>): Promise<Marker | undefined> {
87
+ async function findMarker(
88
+ action: TokenResendAction | undefined,
89
+ decrypt?: (v: string) => Promise<string>
90
+ ): Promise<Marker | undefined> {
88
91
  for (const output of action?.outputs ?? []) {
89
92
  const raw = output.customInstructions
90
93
  if (typeof raw !== 'string' || raw === '') continue
@@ -55,10 +55,10 @@ export interface TokenAssetStatus {
55
55
 
56
56
  export interface TokenAssetInfo {
57
57
  assetId: string
58
- label: string // e.g. "Acme Dollar"
59
- ticker: string // e.g. "USDX"
58
+ label: string // e.g. "Acme Dollar"
59
+ ticker: string // e.g. "USDX"
60
60
  decimals: number
61
- issuerName?: string // e.g. "Acme Bank" — used in every failure/settling copy
61
+ issuerName?: string // e.g. "Acme Bank" — used in every failure/settling copy
62
62
  overlayUrl: string
63
63
  overlayIdentityKey: string
64
64
  }
@@ -87,7 +87,7 @@ export interface TokenActivityRow {
87
87
  baseUnits: number
88
88
  counterpartyKey?: string
89
89
  status: TokenActivityStatus
90
- at: string // ISO
90
+ at: string // ISO
91
91
  refusedCode?: string
92
92
  /** `payloadHash` of the linkage bytes this refusal was recorded against (amendment §9.1/§9.3). */
93
93
  refusedPayloadHash?: string
@@ -56,7 +56,7 @@ export class TaskBackupPush extends WalletMonitorTask {
56
56
  * backup log (XR-105; same pattern as TaskDrainOutbox.running). */
57
57
  static running = false
58
58
 
59
- static noteConnectivity (online: boolean): void {
59
+ static noteConnectivity(online: boolean): void {
60
60
  TaskBackupPush.onlineNow = online
61
61
  if (online) {
62
62
  TaskBackupPush.checkNow = true
@@ -66,32 +66,29 @@ export class TaskBackupPush extends WalletMonitorTask {
66
66
  }
67
67
 
68
68
  /** New wallet activity. Cheap to over-call: one idle pass clears the flag. */
69
- static noteChanged (): void {
69
+ static noteChanged(): void {
70
70
  TaskBackupPush.hasChanges = true
71
71
  }
72
72
 
73
73
  /** User asked for an immediate backup. */
74
- static requestNow (): void {
74
+ static requestNow(): void {
75
75
  TaskBackupPush.checkNow = true
76
76
  TaskBackupPush.backoffMs = TaskBackupPush.BASE_BACKOFF_MS
77
77
  TaskBackupPush.nextDueAt = 0
78
78
  }
79
79
 
80
- static noteRan (at: number): void {
80
+ static noteRan(at: number): void {
81
81
  TaskBackupPush.nextDueAt = at + MIN_PUSH_INTERVAL_MS
82
82
  TaskBackupPush.lastRunAt = at
83
83
  }
84
84
 
85
- static noteFailure (at: number): void {
85
+ static noteFailure(at: number): void {
86
86
  TaskBackupPush.nextDueAt = at + TaskBackupPush.backoffMs
87
- TaskBackupPush.backoffMs = Math.min(
88
- TaskBackupPush.backoffMs * 2,
89
- TaskBackupPush.MAX_BACKOFF_MS
90
- )
87
+ TaskBackupPush.backoffMs = Math.min(TaskBackupPush.backoffMs * 2, TaskBackupPush.MAX_BACKOFF_MS)
91
88
  }
92
89
 
93
90
  /** Test seam; also used when the user signs out. */
94
- static reset (): void {
91
+ static reset(): void {
95
92
  TaskBackupPush.onlineNow = false
96
93
  TaskBackupPush.hasChanges = false
97
94
  TaskBackupPush.checkNow = false
@@ -103,14 +100,14 @@ export class TaskBackupPush extends WalletMonitorTask {
103
100
  TaskBackupPush.running = false
104
101
  }
105
102
 
106
- constructor (
103
+ constructor(
107
104
  monitor: Monitor,
108
105
  private readonly push: () => Promise<PushResult>
109
106
  ) {
110
107
  super(monitor, TaskBackupPush.taskName)
111
108
  }
112
109
 
113
- trigger (nowMsecsSinceEpoch: number): { run: boolean } {
110
+ trigger(nowMsecsSinceEpoch: number): { run: boolean } {
114
111
  if (!TaskBackupPush.onlineNow) return { run: false }
115
112
  if (TaskBackupPush.checkNow) return { run: true }
116
113
  if (TaskBackupPush.hasChanges) {
@@ -120,7 +117,7 @@ export class TaskBackupPush extends WalletMonitorTask {
120
117
  return { run: nowMsecsSinceEpoch >= TaskBackupPush.lastRunAt + TaskBackupPush.IDLE_RECHECK_MS }
121
118
  }
122
119
 
123
- async runTask (): Promise<string> {
120
+ async runTask(): Promise<string> {
124
121
  // A watchdog restart can spawn a new generation's runOnce() while an old
125
122
  // generation's own runOnce() is still executing (it is not cancelled,
126
123
  // only stopped from looping again). Without this guard both could
@@ -8,16 +8,19 @@
8
8
  * past — which is how a testnet wallet came to display a mainnet balance and a
9
9
  * mainnet list of payments.
10
10
  *
11
- * The app's chain names and the toolbox's do not match ('teratest' is 'ttn' to
12
- * the toolbox, and both testnets share the 'test' storage chain), so the
11
+ * The app's chain names and the toolbox's do not match ('teratest' is 'ttn' and
12
+ * 'scaletest' is 'regtest' to the toolbox), and storage records the toolbox's
13
+ * name — it is built with `createStorageBaseOptions(walletChain)` — so the
13
14
  * comparison goes through the same mapping the wallet build uses.
14
15
  */
15
16
 
16
- export type AppChain = 'main' | 'test' | 'teratest'
17
+ import { NETWORKS, isAppChain, type AppChain } from '../networks'
18
+
19
+ export type { AppChain } from '../networks'
17
20
 
18
21
  /** The storage chain an app-level network is expected to be backed by. */
19
- export function storageChainFor(network: AppChain | string): string {
20
- return network === 'main' ? 'main' : 'test'
22
+ export function storageChainFor(network: AppChain | string): string | undefined {
23
+ return isAppChain(network) ? NETWORKS[network].walletChain : undefined
21
24
  }
22
25
 
23
26
  /**
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Per-network facts, in one table.
3
+ *
4
+ * Every place that used to branch on the network with a ternary (`main ? … :
5
+ * test ? … : <teratest>`) reads it from here instead. The ternaries silently
6
+ * sent any network they did not name to the last branch, which was harmless
7
+ * while there were three and wrong the moment a fourth arrived: the scaling
8
+ * teratestnet would have broadcast to teratest's Arcade and opened teratest's
9
+ * database. A `Record<AppChain, …>` makes a missing network a type error.
10
+ *
11
+ * App ids vs toolbox ids: the app persists and displays its own names
12
+ * (`'teratest'`, `'scaletest'` — AsyncStorage keys, database filenames, env var
13
+ * names, the backup log), and the toolbox identifies the same chains as `'ttn'`
14
+ * and `'regtest'`. Convert only at toolbox boundaries, with `toWalletChain`.
15
+ *
16
+ * This module is a leaf: it imports nothing, so `config.tsx`, `chainMatch.ts`
17
+ * and the vault/backup modules can all depend on it without a cycle.
18
+ */
19
+
20
+ export const APP_CHAINS = ['main', 'test', 'teratest', 'scaletest'] as const
21
+ export type AppChain = (typeof APP_CHAINS)[number]
22
+
23
+ /**
24
+ * The wallet-toolbox `Chain` values this app uses.
25
+ *
26
+ * `'regtest'` is the chain the scaling teratestnet actually runs: Teranode
27
+ * regtest parameters (regtest genesis, proof-of-work limit 0x207fffff), which
28
+ * is not the toolbox's `'tstn'` (go-chaincfg TeraScalingTestNetParams, real
29
+ * proof of work). The toolbox gains `'regtest'` in @bsv/wallet-toolbox 2.15.0
30
+ * (bsv-blockchain/ts-stack#819); `toWalletChain` bridges the type until then.
31
+ */
32
+ export type WalletChain = 'main' | 'test' | 'ttn' | 'regtest'
33
+
34
+ /** The overlay preset `@bsv/sdk`'s LookupResolver and the MessageBox client accept. */
35
+ export type OverlayPreset = 'mainnet' | 'testnet' | 'teratestnet' | 'local'
36
+
37
+ /** WhatsOnChain-compatible API for a network that has one. */
38
+ export interface WocEndpoints {
39
+ /** API origin, no trailing slash. Requests go to `${apiBase}/v1/bsv/${segment}/…`. */
40
+ apiBase: string
41
+ /** The path segment: WoC serves teratest under `test`, too. */
42
+ segment: 'main' | 'test'
43
+ /** Explorer origin for transaction links. */
44
+ explorerBase: string
45
+ }
46
+
47
+ export interface NetworkProfile {
48
+ walletChain: WalletChain
49
+ /**
50
+ * Whether the network may be chosen in the picker. A network that is not
51
+ * available keeps its whole configuration so it can be switched on in one
52
+ * place, but no new wallet can be put on it.
53
+ */
54
+ available: boolean
55
+ /** Default Arcade origin (broadcast, SSE, and `/chaintracks/v1`). */
56
+ arcadeUrl: string
57
+ /** Default MessageBox origin. Each network has its own server. */
58
+ messageBoxUrl: string
59
+ /** Undefined on a network with no WhatsOnChain: address rails, WoC proofs and explorer links are off. */
60
+ woc?: WocEndpoints
61
+ /** TAAL ARC broadcast fallback, where TAAL runs one. */
62
+ taalArcUrl?: string
63
+ /** GorillaPool ARC broadcast fallback, where GorillaPool runs one. */
64
+ gorillaPoolArcUrl?: string
65
+ /** Whether Bitails (the toolbox's built-in provider) serves this network. */
66
+ bitails: boolean
67
+ /**
68
+ * The overlay preset for MessageBox / identity lookups.
69
+ *
70
+ * `'local'` marks a network with no overlay at all: nothing can be looked up
71
+ * or advertised, so identity search is skipped and MessageBox routes only to
72
+ * its configured host.
73
+ */
74
+ overlayPreset: OverlayPreset
75
+ /** Whether the MessageBox server for this network sends push notifications. */
76
+ push: boolean
77
+ }
78
+
79
+ export const NETWORKS: Record<AppChain, NetworkProfile> = {
80
+ main: {
81
+ available: true,
82
+ walletChain: 'main',
83
+ arcadeUrl: 'https://arcade-v2-us-1.bsvblockchain.tech',
84
+ messageBoxUrl: 'https://messagebox.bsvblockchain.tech',
85
+ woc: { apiBase: 'https://api.whatsonchain.com', segment: 'main', explorerBase: 'https://whatsonchain.com' },
86
+ taalArcUrl: 'https://arc.taal.com',
87
+ gorillaPoolArcUrl: 'https://arc.gorillapool.io',
88
+ bitails: true,
89
+ overlayPreset: 'mainnet',
90
+ push: true
91
+ },
92
+ test: {
93
+ available: true,
94
+ walletChain: 'test',
95
+ arcadeUrl: 'https://arcade-v2-testnet-us-1.bsvblockchain.tech',
96
+ messageBoxUrl: 'https://messagebox-testnet.bsvblockchain.tech',
97
+ woc: { apiBase: 'https://api.whatsonchain.com', segment: 'test', explorerBase: 'https://test.whatsonchain.com' },
98
+ taalArcUrl: 'https://arc-test.taal.com',
99
+ bitails: true,
100
+ overlayPreset: 'testnet',
101
+ push: false
102
+ },
103
+ teratest: {
104
+ available: true,
105
+ walletChain: 'ttn',
106
+ arcadeUrl: 'https://arcade-v2-ttn-us-1.bsvblockchain.tech',
107
+ messageBoxUrl: 'https://messagebox-ttn.bsvblockchain.tech',
108
+ woc: {
109
+ apiBase: 'https://api.woc-ttn.bsvblockchain.tech',
110
+ segment: 'test',
111
+ explorerBase: 'https://woc-ttn.bsvblockchain.tech'
112
+ },
113
+ bitails: false,
114
+ overlayPreset: 'teratestnet',
115
+ push: false
116
+ },
117
+ // The scaling teratestnet. Arcade, chaintracks and MessageBox only: there is
118
+ // no WhatsOnChain, explorer or overlay for it.
119
+ //
120
+ // Not available yet. The deployed chain runs Teranode regtest parameters
121
+ // (regtest genesis 0f9188f1…, bits 0x207fffff; its chaintracks reports
122
+ // 'regtest'), so the toolbox chain is 'regtest', not 'tstn'. The installed
123
+ // @bsv/wallet-toolbox-mobile 2.14.x has no 'regtest' chain and rejects every
124
+ // header above the mainnet proof-of-work limit, so nothing on it can be
125
+ // verified. Switch it on once the dependency is 2.15.0 or later
126
+ // (bsv-blockchain/ts-stack#819).
127
+ scaletest: {
128
+ walletChain: 'regtest',
129
+ available: false,
130
+ arcadeUrl: 'https://arcade-tstn-us-1.bsvblockchain.tech',
131
+ messageBoxUrl: 'https://messagebox-tstn.bsvblockchain.tech',
132
+ bitails: false,
133
+ overlayPreset: 'local',
134
+ push: false
135
+ }
136
+ }
137
+
138
+ export function isAppChain(value: unknown): value is AppChain {
139
+ return typeof value === 'string' && (APP_CHAINS as readonly string[]).includes(value)
140
+ }
141
+
142
+ /** Whether the network has any overlay to look identities up in. */
143
+ export function hasOverlay(chain: AppChain): boolean {
144
+ return NETWORKS[chain].overlayPreset !== 'local'
145
+ }
@@ -32,7 +32,10 @@ export const PEERPAY_NOTE_MAX = 120
32
32
  /** A note as a link may carry it: plain, single-line text, or nothing. */
33
33
  export function cleanPeerPayNote(raw: string | null | undefined): string | undefined {
34
34
  // eslint-disable-next-line no-control-regex
35
- const text = (raw ?? '').replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, ' ').replace(/\s+/g, ' ').trim()
35
+ const text = (raw ?? '')
36
+ .replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, ' ')
37
+ .replace(/\s+/g, ' ')
38
+ .trim()
36
39
  return text ? Array.from(text).slice(0, PEERPAY_NOTE_MAX).join('') : undefined
37
40
  }
38
41
 
@@ -102,14 +102,17 @@ export async function refetchAtomicBeef(args: {
102
102
  *
103
103
  * `online` is consulted first so an offline device declines instead of
104
104
  * attempting a fetch that must fail — see the note at the top of this file.
105
+ * A network with no WhatsOnChain (`woc` undefined) has nowhere to refetch
106
+ * from, so it always declines.
105
107
  */
106
108
  export function makeBeefRepair(args: {
107
- woc: WocConfig
109
+ woc: WocConfig | undefined
108
110
  online: () => Promise<boolean>
109
111
  fetchImpl?: FetchLike
110
112
  }): (txid: string) => Promise<number[] | undefined> {
113
+ const woc = args.woc
111
114
  return async (txid: string) => {
112
- if (!(await args.online())) return undefined
113
- return refetchAtomicBeef({ woc: args.woc, txid, fetchImpl: args.fetchImpl })
115
+ if (!woc || !(await args.online())) return undefined
116
+ return refetchAtomicBeef({ woc, txid, fetchImpl: args.fetchImpl })
114
117
  }
115
118
  }
@@ -8,10 +8,46 @@
8
8
  */
9
9
  export type CreditFailureKind = 'environmental' | 'double_spend' | 'structural'
10
10
 
11
+ /**
12
+ * internalizeAction (wallet-toolbox-mobile 2.14.7 and later) posts an unproven payment
13
+ * itself and throws WERR_REVIEW_ACTIONS, crediting nothing, when the post fails. Its
14
+ * `reviewActionResults` say why: a double spend, an invalid transaction, or, when every
15
+ * result is a service error, no broadcaster could be reached.
16
+ */
17
+ function classifyFailedPost(e: unknown): CreditFailureKind | undefined {
18
+ const review = e as { name?: unknown; reviewActionResults?: unknown } | null
19
+ if (review?.name !== 'WERR_REVIEW_ACTIONS' || !Array.isArray(review.reviewActionResults)) return undefined
20
+ const statuses = review.reviewActionResults.map(r => (r as { status?: unknown } | null)?.status)
21
+ if (statuses.length === 0) return undefined
22
+ if (statuses.includes('doubleSpend')) return 'double_spend'
23
+ if (statuses.every(s => s === 'serviceError')) return 'environmental'
24
+ return 'structural'
25
+ }
26
+
27
+ /**
28
+ * Why internalizeAction's post of a payment failed, in words, for callers that
29
+ * keep only a message: WERR_REVIEW_ACTIONS's own message does not say. The
30
+ * environmental wording is matched by `isRetriableInternalizeFailure`.
31
+ */
32
+ export function failedPostReason(e: unknown): string | undefined {
33
+ switch (classifyFailedPost(e)) {
34
+ case 'environmental':
35
+ return 'The payment could not be broadcast: no broadcaster could be reached'
36
+ case 'double_spend':
37
+ return 'The payment could not be broadcast: the network reported a double spend'
38
+ case 'structural':
39
+ return 'The payment could not be broadcast: the network rejected the transaction'
40
+ default:
41
+ return undefined
42
+ }
43
+ }
44
+
11
45
  export function classifyCreditError(
12
46
  e: unknown,
13
47
  ctx?: { lastMissHeight?: number; offline?: boolean }
14
48
  ): CreditFailureKind {
49
+ const failedPost = classifyFailedPost(e)
50
+ if (failedPost) return failedPost
15
51
  const message = e instanceof Error ? e.message : typeof e === 'string' ? e : ''
16
52
  if (/invalid status failed|doubleSpend|double.?spend/i.test(message)) return 'double_spend'
17
53
  // Headers behind or the device offline: any credit failure is treated as
@@ -21,7 +57,7 @@ export function classifyCreditError(
21
57
  if (ctx?.offline) return 'environmental'
22
58
  if (ctx?.lastMissHeight != null) return 'environmental'
23
59
  if (
24
- /network request failed|timed? ?out|chaintracks|database is locked|database table is locked|database-locked|failed to retrieve messages|not found on refresh/i.test(
60
+ /network request failed|timed? ?out|chaintracks|database is locked|database table is locked|database-locked|failed to retrieve messages|not found on refresh|no broadcaster could be reached/i.test(
25
61
  message
26
62
  )
27
63
  )
@@ -22,6 +22,7 @@ import {
22
22
  type WalletProtocol
23
23
  } from '@bsv/sdk'
24
24
  import type { AppChain } from '../../config'
25
+ import { NETWORKS } from '../../networks'
25
26
  import { abbreviateKey, addressLabel, FROM_ADDRESS_LABEL_PREFIX, TO_ADDRESS_LABEL_PREFIX } from '../counterparty'
26
27
  import { addressNetwork, isValidBsvAddress } from './index'
27
28
 
@@ -147,12 +148,15 @@ export interface WocConfig {
147
148
  apiKey?: string
148
149
  }
149
150
 
150
- export function wocConfigFor(network: AppChain): WocConfig {
151
- return {
152
- main: { apiBase: 'https://api.whatsonchain.com', segment: 'main', network: 'mainnet' as const },
153
- test: { apiBase: 'https://api.whatsonchain.com', segment: 'test', network: 'testnet' as const },
154
- teratest: { apiBase: 'https://api.woc-ttn.bsvblockchain.tech', segment: 'test', network: 'testnet' as const }
155
- }[network]
151
+ /**
152
+ * The WhatsOnChain API for a network, or undefined on a network that has none
153
+ * (the scaling teratestnet). Without it there is nothing to look an address up
154
+ * in, so the address rail, sweeps and BEEF repair are all off there.
155
+ */
156
+ export function wocConfigFor(network: AppChain): WocConfig | undefined {
157
+ const woc = NETWORKS[network].woc
158
+ if (!woc) return undefined
159
+ return { apiBase: woc.apiBase, segment: woc.segment, network: network === 'main' ? 'mainnet' : 'testnet' }
156
160
  }
157
161
 
158
162
  /**
@@ -57,6 +57,7 @@ import { markOutboxSent, saveOutboxEntry, updateOutboxEntry } from '../../peerpa
57
57
  import { TaskDrainOutbox } from '../../monitor/TaskDrainOutbox'
58
58
  import { NotSentError } from '../../directpay/payFlow'
59
59
  import { dialFailure } from '../../directpay/dialFailure'
60
+ import { MAX_LIVE_TRANSACTION_BYTES } from '../../directpay/settings'
60
61
  import type { DirectPayClientLike, DirectPaymentAck, DirectPeer, WebRTPayModule } from '../../directpay/webrtpay'
61
62
 
62
63
  interface StorageLike {
@@ -246,10 +247,13 @@ function whyNotDeliverable(
246
247
  ): NotSentError | undefined {
247
248
  if (signal?.aborted) return new NotSentError('Cancelled', '', 'aborted')
248
249
  const bytes = token.transaction.length
249
- if (bytes > webrtpay.MAX_DIRECT_TRANSACTION_BYTES) {
250
+ // Live payments carry at most 1 MB (MAX_LIVE_TRANSACTION_BYTES), below the package's own cap.
251
+ const limit = Math.min(MAX_LIVE_TRANSACTION_BYTES, webrtpay.MAX_DIRECT_TRANSACTION_BYTES)
252
+ if (bytes > limit) {
250
253
  return new NotSentError(
251
254
  'This payment is too large to deliver directly',
252
- `${bytes} bytes; at most ${webrtpay.MAX_DIRECT_TRANSACTION_BYTES} can go over the link`
255
+ `${bytes} bytes; at most ${limit} can go over the link`,
256
+ 'too_large'
253
257
  )
254
258
  }
255
259
  try {