@bsv/expo-wallet-toolbox 0.3.1 → 0.5.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 +311 -0
- package/README.md +52 -1
- package/assets/sounds/vault-deposit.wav +0 -0
- package/assets/sounds/vault-withdraw.wav +0 -0
- package/core/config.tsx +21 -18
- package/core/context/VaultContext.tsx +8 -11
- package/core/context/WalletConnectionContext.tsx +137 -52
- package/core/context/WalletContext.tsx +413 -23
- package/core/hooks/useConfirmationSound.ts +14 -8
- package/core/i18n/translations.tsx +3368 -952
- package/core/index.ts +107 -14
- package/core/localpay/build.ts +674 -37
- package/core/localpay/codec.ts +68 -5
- package/core/localpay/pending.ts +240 -22
- package/core/localpay/settlementAck.ts +149 -0
- package/core/localpay/types.ts +14 -1
- package/core/localpay/verify.ts +118 -69
- package/core/mandala/abortGuard.ts +134 -0
- package/core/mandala/basketMigration.ts +166 -0
- package/core/mandala/bundle.ts +244 -0
- package/core/mandala/createRuntime.ts +2437 -0
- package/core/mandala/drain.ts +670 -0
- package/core/mandala/permissionModule.ts +642 -0
- package/core/mandala/resendTransfer.ts +175 -0
- package/core/mandala/runtime.ts +357 -0
- package/core/mandala/settlementStore.ts +412 -0
- package/core/mandala/types.ts +290 -0
- package/core/offline/cancelParked.ts +94 -1
- package/core/offline/payerHold.ts +152 -12
- package/core/offline/tokenFrames.ts +197 -0
- package/core/parsePeerPayURI.ts +70 -17
- package/core/pay/rails/address.ts +51 -3
- package/core/pay/rails/handle.ts +88 -9
- package/core/pay/rails/index.ts +16 -6
- package/core/pay/rails/nearby.ts +114 -4
- package/core/services/capWalletArgs.ts +8 -9
- package/core/services/externalOrigin.ts +39 -0
- package/core/services/vault/VaultKeyService.ts +912 -251
- package/core/services/vault/ceremony.ts +435 -367
- package/core/services/vault/ceremonyHost.ts +27 -21
- package/core/services/vault/devMock.ts +30 -7
- package/core/services/vault/driver.ts +95 -41
- package/core/services/vault/guard.ts +514 -56
- package/core/services/vault/hardwareLease.ts +22 -0
- package/core/services/vault/mockYubiKey.ts +258 -90
- package/core/services/vault/pivReset.ts +145 -0
- package/core/services/vault/r1comb.ts +976 -0
- package/core/services/vault/session.ts +93 -26
- package/core/services/vault/transfers.ts +2617 -747
- package/core/services/vault/types.ts +100 -43
- package/core/services/vault/vaultStore.ts +991 -74
- package/core/services/walletConnectionValidation.ts +293 -0
- package/core/services/walletServiceConfig.ts +19 -24
- package/core/storage/StorageExpoSQLite.ts +382 -56
- package/core/storage/dbImage.ts +48 -0
- package/core/storage/methods/findSql.ts +0 -54
- package/core/storage/methods/listOutputsSql.ts +7 -3
- package/core/storage/methods/offlineActions.ts +15 -0
- package/core/storage/methods/processOfflineActions.ts +263 -6
- package/core/storage/methods/walletBalanceSql.ts +16 -4
- package/core/storage/schema/createTables.ts +123 -0
- package/core/storage/sqlUpdateValue.ts +24 -0
- package/core/toolboxConfig.ts +240 -0
- package/core/walletRepair/runWalletCheck.ts +19 -2
- package/package.json +25 -24
- package/ui/components/QRScanner.tsx +1 -1
- package/ui/components/pay/AdmissionNotice.tsx +99 -0
- package/ui/components/pay/AssetPicker.tsx +184 -0
- package/ui/components/pay/AvailableBalance.tsx +33 -2
- package/ui/components/pay/HandleReceive.tsx +213 -50
- package/ui/components/pay/NearbyFlow.tsx +616 -69
- package/ui/components/pay/PayForm.tsx +73 -8
- package/ui/components/pay/PaymentSuccessOverlay.tsx +43 -2
- package/ui/components/pay/RecipientField.tsx +49 -4
- package/ui/components/pay/RequestHub.tsx +68 -8
- package/ui/components/pay/ResultBanner.tsx +41 -4
- package/ui/components/pay/UniversalSend.tsx +534 -30
- package/ui/components/pay/tokenSendCopy.ts +116 -0
- package/ui/components/pay/useRecipientInput.ts +36 -7
- package/ui/components/ui/PermissionSheet.tsx +65 -4
- package/ui/components/ui/Sheet.tsx +9 -2
- package/ui/components/vault/EnrollWizard.tsx +1432 -488
- package/ui/components/vault/KeyChooser.tsx +96 -0
- package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
- package/ui/components/vault/vaultErrorCopy.ts +145 -0
- package/ui/components/wallet/ActivityRow.tsx +101 -17
- package/ui/components/wallet/AmountInput.tsx +77 -25
- package/ui/components/wallet/AssetAmount.tsx +95 -0
- package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
- package/ui/components/wallet/tokenEviction.ts +65 -0
- package/ui/hooks/useExportWalletData.ts +39 -0
- package/ui/hooks/useMandala.ts +303 -0
- package/ui/hooks/useVaultBalance.ts +105 -7
- package/ui/hooks/useVaultCoverage.ts +52 -0
- package/ui/importDatabases.ts +7 -3
- package/ui/index.ts +50 -7
- package/ui/screens/ConnectionsScreen.tsx +46 -29
- package/ui/screens/PairScreen.tsx +12 -12
- package/ui/screens/PayScreen.tsx +130 -10
- package/ui/screens/SettingsScreen.tsx +18 -9
- package/ui/screens/VaultScreen.tsx +925 -171
- package/ui/screens/VaultTransferScreen.tsx +376 -123
- package/ui/screens/WalletCheckScreen.tsx +10 -1
- package/ui/screens/WalletConfigScreen.tsx +42 -20
- package/ui/screens/WalletHomeScreen.tsx +417 -86
- package/ui/screens/homeBadges.ts +9 -1
- package/ui/screens/tokenRowTitle.ts +68 -0
- package/ui/tokenFormat.ts +108 -0
- package/ui/tokenSeen.ts +75 -0
- package/ui/tokenStatus.ts +79 -0
- package/assets/sounds/vault-close.wav +0 -0
- package/assets/sounds/vault-open.wav +0 -0
- package/core/services/vault/k1.ts +0 -75
- package/core/services/vault/sealing.ts +0 -84
- package/core/services/vault/vaultDerivation.ts +0 -152
- package/core/services/vault/vaultPassphrase.ts +0 -287
- package/ui/components/vault/PassphraseField.tsx +0 -306
- package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
- package/ui/screens/VaultRecoverScreen.tsx +0 -226
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turning the frames this device already holds durably into drain sources.
|
|
3
|
+
*
|
|
4
|
+
* This is the supply side of FIX G and FIX I. `processOfflineActions` calls
|
|
5
|
+
* `token.frames()` at the start of every pass and hands the result to
|
|
6
|
+
* `reconcileSettlements`, which re-derives the evidence cache and any missing
|
|
7
|
+
* `token_settlements` row. The two durable stores have very different shapes,
|
|
8
|
+
* so each gets its own reader:
|
|
9
|
+
*
|
|
10
|
+
* · `localpay_pending` (receiver) holds the frame ALREADY DECODED, so nothing
|
|
11
|
+
* is needed but the queue entries.
|
|
12
|
+
* · `offline_actions.framePayload` (payer) holds the SEALED `bsvpayf1:` QR
|
|
13
|
+
* string. Opening it needs the session pre-shared key, which the drain does
|
|
14
|
+
* not hold and should not — so the decoder is injected by whoever still has
|
|
15
|
+
* the session, and a row that cannot be opened is simply skipped. The payer
|
|
16
|
+
* losing its own settlement row is survivable in a way the recipient's is
|
|
17
|
+
* not: the recipient submits (rule 3), and the payer's optional submit
|
|
18
|
+
* (rule 6) is a race it is always safe to lose.
|
|
19
|
+
*
|
|
20
|
+
* **Deliberately NOT filtered by `MAX_PENDING_ATTEMPTS` (FIX I).** That ceiling
|
|
21
|
+
* governs `localpay_pending`'s own BSV-shaped internalize retry loop and burns
|
|
22
|
+
* an attempt on any failure, including a transient
|
|
23
|
+
* `Block header not found for height N` from a fresh-block BUMP this device has
|
|
24
|
+
* not caught up on. A token payment's state of record is `token_settlements`,
|
|
25
|
+
* not the pending queue — so an exhausted queue entry still contributes its
|
|
26
|
+
* frame here, the settlement row stays alive, and the row is abandoned only by
|
|
27
|
+
* an explicit `refused`/`orphaned` verdict from the overlay.
|
|
28
|
+
*/
|
|
29
|
+
import { Beef, Transaction } from '@bsv/sdk'
|
|
30
|
+
import { MandalaToken } from '@bsv/templates'
|
|
31
|
+
import type { EvidenceFrame, TokenFrameSource } from '../mandala/drain'
|
|
32
|
+
import type { OfflineActionRow } from '../storage/methods/offlineActions'
|
|
33
|
+
import { frameBytesFromQr, unsealFrame } from '../localpay/codec'
|
|
34
|
+
|
|
35
|
+
/** Structurally satisfied by `localpay/pending`'s `PendingPayment`. */
|
|
36
|
+
export interface PendingLike {
|
|
37
|
+
frame: EvidenceFrame
|
|
38
|
+
status?: string
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The subject txid of an AtomicBEEF — the same txid `internalizeAction` used
|
|
43
|
+
* internally, and therefore the one a `token_settlements` row is keyed by.
|
|
44
|
+
*/
|
|
45
|
+
/**
|
|
46
|
+
* The token figure a frame moves: the amount in the PAYEE output's own script.
|
|
47
|
+
*
|
|
48
|
+
* Read off the atomic transaction rather than trusted from any body, and off
|
|
49
|
+
* `outputIndex` (0 when the frame does not say — the nearby build never
|
|
50
|
+
* randomises outputs) so the payer's own frame answers the payee's figure and
|
|
51
|
+
* never the change. `undefined` for anything that is not a readable token
|
|
52
|
+
* output: the settlement row then has no amount, which the activity list says
|
|
53
|
+
* out loud rather than inventing a number.
|
|
54
|
+
*/
|
|
55
|
+
export function frameTokenAmount(frame: EvidenceFrame): number | undefined {
|
|
56
|
+
try {
|
|
57
|
+
const tx = Transaction.fromAtomicBEEF(Array.from(frame.transaction))
|
|
58
|
+
const script = tx.outputs[frame.outputIndex ?? 0]?.lockingScript
|
|
59
|
+
if (!script) return undefined
|
|
60
|
+
const amount = MandalaToken.decode(script).amount
|
|
61
|
+
return Number.isFinite(amount) && amount >= 0 ? amount : undefined
|
|
62
|
+
} catch {
|
|
63
|
+
return undefined
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function frameTxid(frame: EvidenceFrame): string | undefined {
|
|
68
|
+
try {
|
|
69
|
+
return Beef.fromBinary(frame.transaction).atomicTxid
|
|
70
|
+
} catch {
|
|
71
|
+
return undefined
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Receiver-side sources. Every non-completed entry with a token block, whether
|
|
77
|
+
* or not the pending queue has given up on it.
|
|
78
|
+
*/
|
|
79
|
+
export function tokenFrameSourcesFromPending(entries: readonly PendingLike[]): TokenFrameSource[] {
|
|
80
|
+
const sources: TokenFrameSource[] = []
|
|
81
|
+
for (const entry of entries) {
|
|
82
|
+
if (!entry.frame?.token) continue
|
|
83
|
+
const txid = frameTxid(entry.frame)
|
|
84
|
+
if (!txid) continue
|
|
85
|
+
const amountBaseUnits = frameTokenAmount(entry.frame)
|
|
86
|
+
sources.push({
|
|
87
|
+
txid,
|
|
88
|
+
role: 'received',
|
|
89
|
+
frame: entry.frame,
|
|
90
|
+
...(amountBaseUnits !== undefined ? { amountBaseUnits } : {})
|
|
91
|
+
})
|
|
92
|
+
}
|
|
93
|
+
return sources
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Payer-side sources, for the rows whose sealed `framePayload` the caller can
|
|
98
|
+
* open. A row this device cannot decode contributes nothing rather than
|
|
99
|
+
* throwing: the drain must reach every other row in the same pass.
|
|
100
|
+
*/
|
|
101
|
+
export function tokenFrameSourcesFromOfflineActions(
|
|
102
|
+
rows: readonly OfflineActionRow[],
|
|
103
|
+
decode: (framePayload: string) => EvidenceFrame | undefined
|
|
104
|
+
): TokenFrameSource[] {
|
|
105
|
+
const sources: TokenFrameSource[] = []
|
|
106
|
+
for (const row of rows) {
|
|
107
|
+
if (!row.framePayload) continue
|
|
108
|
+
let frame: EvidenceFrame | undefined
|
|
109
|
+
try {
|
|
110
|
+
frame = decode(row.framePayload)
|
|
111
|
+
} catch {
|
|
112
|
+
continue
|
|
113
|
+
}
|
|
114
|
+
if (!frame?.token) continue
|
|
115
|
+
const amountBaseUnits = frameTokenAmount(frame)
|
|
116
|
+
sources.push({
|
|
117
|
+
txid: row.txid,
|
|
118
|
+
role: row.role,
|
|
119
|
+
frame,
|
|
120
|
+
// A parked row must keep its own state: it is the user's, not the
|
|
121
|
+
// drain's, and reconciliation may not promote it to a submittable one.
|
|
122
|
+
state: row.status === 'parked' ? 'parked' : undefined,
|
|
123
|
+
...(amountBaseUnits !== undefined ? { amountBaseUnits } : {})
|
|
124
|
+
})
|
|
125
|
+
}
|
|
126
|
+
return sources
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// ───────────────────── the payer's sealed-frame decoder ─────────────────────
|
|
130
|
+
//
|
|
131
|
+
// `offline_actions.framePayload` is the `bsvpayf1:` envelope around a frame
|
|
132
|
+
// SEALED with the nearby session's pre-shared key. The drain holds no session
|
|
133
|
+
// and should not: the PSK is a hand-over secret, not durable wallet state. So
|
|
134
|
+
// the keys of the sessions this process has actually taken part in are kept
|
|
135
|
+
// here, in memory only, and the decoder tries each of them.
|
|
136
|
+
//
|
|
137
|
+
// What "in memory only" costs is bounded and known: a payer that restarts
|
|
138
|
+
// before its own optional submit (rule 6) loses the ability to re-derive its
|
|
139
|
+
// `token_settlements` row from the frame. That is the race it is always safe
|
|
140
|
+
// to lose — the RECIPIENT submits (rule 3), and the payer's submit only makes
|
|
141
|
+
// its own change spendable sooner. What it buys is that a durable copy of the
|
|
142
|
+
// key that opens every stored frame is never written to disk.
|
|
143
|
+
|
|
144
|
+
/** How many session keys are remembered. Well past any plausible number of live hand-overs. */
|
|
145
|
+
export const MAX_REMEMBERED_SESSION_KEYS = 32
|
|
146
|
+
|
|
147
|
+
const sessionKeys: Uint8Array[] = []
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Remember a nearby session's PSK for this process.
|
|
151
|
+
*
|
|
152
|
+
* Called by whoever mints or scans a session (the nearby flow), not by the
|
|
153
|
+
* drain. Idempotent per key, and bounded: the oldest key is dropped once the
|
|
154
|
+
* ring is full, which is correct because a hand-over's frame is reconciled on
|
|
155
|
+
* the very next online tick.
|
|
156
|
+
*/
|
|
157
|
+
export function rememberSessionPsk(psk: Uint8Array): void {
|
|
158
|
+
if (!(psk instanceof Uint8Array) || psk.length !== 32) return
|
|
159
|
+
const already = sessionKeys.some(known => known.length === psk.length && known.every((b, i) => b === psk[i]))
|
|
160
|
+
if (already) return
|
|
161
|
+
sessionKeys.push(new Uint8Array(psk))
|
|
162
|
+
while (sessionKeys.length > MAX_REMEMBERED_SESSION_KEYS) sessionKeys.shift()
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Drop every remembered key. Logout, network switch, and the tests. */
|
|
166
|
+
export function forgetSessionPsks(): void {
|
|
167
|
+
sessionKeys.length = 0
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* A decoder for `tokenFrameSourcesFromOfflineActions`.
|
|
172
|
+
*
|
|
173
|
+
* Tries each remembered session key in turn and returns the first frame that
|
|
174
|
+
* opens. Undefined — never a throw — for a truncated row, a foreign string, or
|
|
175
|
+
* a frame from a session this process no longer holds the key for: the drain
|
|
176
|
+
* must reach every other row in the same pass.
|
|
177
|
+
*/
|
|
178
|
+
export function sealedFramePayloadDecoder(
|
|
179
|
+
keys: () => readonly Uint8Array[] = () => sessionKeys
|
|
180
|
+
): (framePayload: string) => EvidenceFrame | undefined {
|
|
181
|
+
return framePayload => {
|
|
182
|
+
let bytes: Uint8Array
|
|
183
|
+
try {
|
|
184
|
+
bytes = frameBytesFromQr(framePayload)
|
|
185
|
+
} catch {
|
|
186
|
+
return undefined
|
|
187
|
+
}
|
|
188
|
+
for (const psk of keys()) {
|
|
189
|
+
try {
|
|
190
|
+
return unsealFrame(bytes, psk)
|
|
191
|
+
} catch {
|
|
192
|
+
// Wrong key for this frame (a GCM tag mismatch). Try the next.
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
return undefined
|
|
196
|
+
}
|
|
197
|
+
}
|
package/core/parsePeerPayURI.ts
CHANGED
|
@@ -3,8 +3,17 @@ import { PublicKey } from '@bsv/sdk'
|
|
|
3
3
|
/**
|
|
4
4
|
* BRC-125 PeerPay URI (https://bsv.brc.dev/payments/0125).
|
|
5
5
|
*
|
|
6
|
-
* peerpay-URI
|
|
7
|
-
* sats-param
|
|
6
|
+
* peerpay-URI = "peerpay:" identity-key [ "?" query ]
|
|
7
|
+
* sats-param = "sats=" 1*DIGIT
|
|
8
|
+
* asset-param = "asset=" 64HEXDIG "." 1*DIGIT ; the asset's genesis outpoint
|
|
9
|
+
* amount-param = "amount=" 1*DIGIT ; BASE UNITS of that asset
|
|
10
|
+
*
|
|
11
|
+
* `sats` is the BSV selector. `asset` names a token by its genesis outpoint —
|
|
12
|
+
* the one identifier every issuer's asset already has — and `amount` is a
|
|
13
|
+
* figure in that token's own base units, so it only means anything beside an
|
|
14
|
+
* `asset`. Both are optional: `asset` alone is an open token request, where
|
|
15
|
+
* the payer chooses the figure. A link mixing `sats` with either is refused
|
|
16
|
+
* rather than read in one money or the other (maintainer decision, 2026-09-15).
|
|
8
17
|
*
|
|
9
18
|
* Plus one extension parameter this app emits and reads: `url`, the payee's
|
|
10
19
|
* message-box host, so a payer can skip the overlay lookup. Per BRC-125 an extension that does not parse
|
|
@@ -15,6 +24,10 @@ import { PublicKey } from '@bsv/sdk'
|
|
|
15
24
|
export interface PeerPayParams {
|
|
16
25
|
identityKey: string
|
|
17
26
|
sats?: number
|
|
27
|
+
/** The token's genesis outpoint, `txid.vout`, lowercased. */
|
|
28
|
+
asset?: string
|
|
29
|
+
/** Base units of `asset`. Never present without it. */
|
|
30
|
+
amount?: number
|
|
18
31
|
messageBoxUrl?: string
|
|
19
32
|
}
|
|
20
33
|
|
|
@@ -22,16 +35,29 @@ export interface PeerPayValidationResult {
|
|
|
22
35
|
isPeerPay: boolean
|
|
23
36
|
identityKey?: string
|
|
24
37
|
sats?: number
|
|
38
|
+
asset?: string
|
|
39
|
+
amount?: number
|
|
25
40
|
/** Present only when the link carried a usable https `url` extension. */
|
|
26
41
|
messageBoxUrl?: string
|
|
27
42
|
errors: {
|
|
28
43
|
identityKey?: string
|
|
29
44
|
sats?: string
|
|
45
|
+
asset?: string
|
|
46
|
+
amount?: string
|
|
30
47
|
}
|
|
31
48
|
}
|
|
32
49
|
|
|
50
|
+
/** Any error at all — the one test every consumer of a validation result makes. */
|
|
51
|
+
export function peerPayHasErrors(result: PeerPayValidationResult): boolean {
|
|
52
|
+
return Object.values(result.errors).some(Boolean)
|
|
53
|
+
}
|
|
54
|
+
|
|
33
55
|
const PEERPAY_SCHEME = 'peerpay:'
|
|
34
56
|
const COMPRESSED_PUBLIC_KEY_REGEX = /^0[23][0-9a-fA-F]{64}$/
|
|
57
|
+
/** A genesis outpoint: 32-byte txid in hex, a dot, a decimal output index. */
|
|
58
|
+
const ASSET_OUTPOINT_REGEX = /^[0-9a-fA-F]{64}\.(0|[1-9][0-9]*)$/
|
|
59
|
+
/** A whole non-negative figure with no sign, point or leading zero. */
|
|
60
|
+
const WHOLE_FIGURE_REGEX = /^(0|[1-9][0-9]*)$/
|
|
35
61
|
/**
|
|
36
62
|
* https, a host, then an optional path/query/fragment with no whitespace. The
|
|
37
63
|
* authority chunk excludes `@` and `\` so a `mb.trusted.example@evil.example`
|
|
@@ -41,10 +67,12 @@ const MESSAGE_BOX_URL_REGEX = /^https:\/\/[^\s/?#@\\]+(?:[/?#]\S*)?$/i
|
|
|
41
67
|
|
|
42
68
|
export function parsePeerPayURI(uri: string): PeerPayParams | null {
|
|
43
69
|
const result = validatePeerPayURI(uri)
|
|
44
|
-
if (!result.isPeerPay || !result.identityKey || result
|
|
70
|
+
if (!result.isPeerPay || !result.identityKey || peerPayHasErrors(result)) return null
|
|
45
71
|
return {
|
|
46
72
|
identityKey: result.identityKey,
|
|
47
|
-
sats: result.sats,
|
|
73
|
+
...(result.sats !== undefined ? { sats: result.sats } : {}),
|
|
74
|
+
...(result.asset !== undefined ? { asset: result.asset } : {}),
|
|
75
|
+
...(result.amount !== undefined ? { amount: result.amount } : {}),
|
|
48
76
|
...(result.messageBoxUrl ? { messageBoxUrl: result.messageBoxUrl } : {})
|
|
49
77
|
}
|
|
50
78
|
}
|
|
@@ -70,36 +98,61 @@ export function validatePeerPayURI(uri: string): PeerPayValidationResult {
|
|
|
70
98
|
}
|
|
71
99
|
|
|
72
100
|
let sats: number | undefined
|
|
101
|
+
let asset: string | undefined
|
|
102
|
+
let amount: number | undefined
|
|
73
103
|
let messageBoxUrl: string | undefined
|
|
74
104
|
if (queryPart) {
|
|
75
105
|
const params = new URLSearchParams(queryPart)
|
|
76
106
|
if (params.has('sats')) {
|
|
77
|
-
const
|
|
78
|
-
if (
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
107
|
+
const figure = wholeFigure(params.get('sats') ?? '')
|
|
108
|
+
if (figure === null) errors.sats = 'PeerPay link contains an invalid sats amount'
|
|
109
|
+
else if (figure > 0) sats = figure
|
|
110
|
+
}
|
|
111
|
+
if (params.has('asset')) {
|
|
112
|
+
const raw = (params.get('asset') ?? '').trim()
|
|
113
|
+
if (ASSET_OUTPOINT_REGEX.test(raw)) asset = raw.toLowerCase()
|
|
114
|
+
else errors.asset = 'PeerPay link names an invalid asset'
|
|
115
|
+
}
|
|
116
|
+
if (params.has('amount')) {
|
|
117
|
+
const figure = wholeFigure(params.get('amount') ?? '')
|
|
118
|
+
if (figure === null) errors.amount = 'PeerPay link contains an invalid amount'
|
|
119
|
+
else if (!params.has('asset')) errors.amount = 'PeerPay link names an amount without an asset'
|
|
120
|
+
else if (figure > 0) amount = figure
|
|
121
|
+
}
|
|
122
|
+
// Two selectors for two different monies: refused, never read as either.
|
|
123
|
+
if (params.has('sats') && (params.has('asset') || params.has('amount'))) {
|
|
124
|
+
errors.sats = 'PeerPay link mixes sats with a token request'
|
|
88
125
|
}
|
|
89
126
|
const url = (params.get('url') ?? '').trim().replace(/\/+$/, '')
|
|
90
127
|
if (url && MESSAGE_BOX_URL_REGEX.test(url)) messageBoxUrl = url
|
|
91
128
|
}
|
|
92
129
|
|
|
93
|
-
return {
|
|
130
|
+
return {
|
|
131
|
+
isPeerPay: true,
|
|
132
|
+
identityKey,
|
|
133
|
+
sats,
|
|
134
|
+
...(asset !== undefined ? { asset } : {}),
|
|
135
|
+
...(amount !== undefined ? { amount } : {}),
|
|
136
|
+
...(messageBoxUrl ? { messageBoxUrl } : {}),
|
|
137
|
+
errors
|
|
138
|
+
}
|
|
94
139
|
}
|
|
95
140
|
|
|
96
141
|
/** The human-readable problem with a peerpay link, or null when there is none. */
|
|
97
142
|
export function peerPayValidationMessage(result: PeerPayValidationResult | null): string | null {
|
|
98
143
|
if (!result || !result.isPeerPay) return null
|
|
99
|
-
const
|
|
144
|
+
const { identityKey, sats, asset, amount } = result.errors
|
|
145
|
+
const messages = [identityKey, sats, asset, amount].filter(Boolean)
|
|
100
146
|
return messages.length ? messages.join('. ') : null
|
|
101
147
|
}
|
|
102
148
|
|
|
149
|
+
/** A whole safe integer from a query value, or null for anything else. */
|
|
150
|
+
function wholeFigure(text: string): number | null {
|
|
151
|
+
if (!WHOLE_FIGURE_REGEX.test(text)) return null
|
|
152
|
+
const parsed = Number(text)
|
|
153
|
+
return Number.isSafeInteger(parsed) ? parsed : null
|
|
154
|
+
}
|
|
155
|
+
|
|
103
156
|
/**
|
|
104
157
|
* A 33-byte compressed secp256k1 key in hex, either case, on the curve. Round-trips through
|
|
105
158
|
* PublicKey because the SDK reduces an out-of-range x mod p instead of throwing — parse success
|
|
@@ -27,6 +27,46 @@ import { isValidBsvAddress } from './index'
|
|
|
27
27
|
|
|
28
28
|
export const BRC29_PROTOCOL_ID: WalletProtocol = [2, '3241645161d8']
|
|
29
29
|
|
|
30
|
+
/** Whether the address rail can carry a particular payment, and why not when it cannot. */
|
|
31
|
+
export type AddressRailAvailability = { kind: 'available' } | { kind: 'unavailable'; reason: string }
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* D4: the address rail cannot carry a Mandala token, ever.
|
|
35
|
+
*
|
|
36
|
+
* Not a policy and not a UI opinion — a protocol fact. A token output's owner
|
|
37
|
+
* key is ECDH-derived against the recipient's IDENTITY key
|
|
38
|
+
* (`MandalaToken.lockBRC29`), and the issuer's overlay refuses a transaction
|
|
39
|
+
* carrying an FT output whose owner it cannot name from a linkage. A base58
|
|
40
|
+
* address names a hash, not an identity, so there is nothing to derive against
|
|
41
|
+
* and nothing to reveal — the transaction would be refused if it were ever
|
|
42
|
+
* built, and the money would be locked to a script no one can spend if it
|
|
43
|
+
* were not.
|
|
44
|
+
*
|
|
45
|
+
* The reason text comes from the runtime (`recipientRefusal`, which is the
|
|
46
|
+
* lib's own `guardTokenRecipient`) rather than from a string here, so the
|
|
47
|
+
* wallet and the lib cannot come to say two different things about the same
|
|
48
|
+
* refusal. A caller with no runtime still gets a correct refusal, just a
|
|
49
|
+
* shorter one.
|
|
50
|
+
*/
|
|
51
|
+
export function addressRailAvailability(args: {
|
|
52
|
+
address: string
|
|
53
|
+
/** Set when the payment is denominated in a token rather than in satoshis. */
|
|
54
|
+
assetId?: string
|
|
55
|
+
/** `MandalaRuntime.recipientRefusal`. */
|
|
56
|
+
recipientRefusal?: (recipient: string) => string | null
|
|
57
|
+
}): AddressRailAvailability {
|
|
58
|
+
if (args.assetId === undefined || args.assetId === '') {
|
|
59
|
+
return isValidBsvAddress(args.address) ? { kind: 'available' } : { kind: 'unavailable', reason: 'Invalid BSV address' }
|
|
60
|
+
}
|
|
61
|
+
const reason = args.recipientRefusal?.(args.address)
|
|
62
|
+
return {
|
|
63
|
+
kind: 'unavailable',
|
|
64
|
+
reason:
|
|
65
|
+
reason ??
|
|
66
|
+
'Mandala tokens can only be sent to an identity key, not to an address — the token output is derived against the recipient identity and the overlay refuses anything else'
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
30
70
|
export const LEGACY_DERIVATION_SUFFIX = Utils.toBase64(Utils.toArray('legacy', 'utf8'))
|
|
31
71
|
|
|
32
72
|
/**
|
|
@@ -339,8 +379,15 @@ export async function sendToAddress(args: {
|
|
|
339
379
|
adminOriginator: string
|
|
340
380
|
address: string
|
|
341
381
|
satoshis: number
|
|
382
|
+
/**
|
|
383
|
+
* The sender's own note for this outbound send. There is no counterparty
|
|
384
|
+
* channel on this rail — an address names no one to notify — so this is
|
|
385
|
+
* purely the payer's own record: it replaces the abbreviated-address
|
|
386
|
+
* description in their own activity list, nothing more.
|
|
387
|
+
*/
|
|
388
|
+
note?: string
|
|
342
389
|
}): Promise<{ paidSatoshis: number }> {
|
|
343
|
-
const { wallet, adminOriginator, address, satoshis } = args
|
|
390
|
+
const { wallet, adminOriginator, address, satoshis, note } = args
|
|
344
391
|
const sats = Math.round(Number(satoshis))
|
|
345
392
|
if (!Number.isFinite(sats) || sats <= 0) throw new Error('Invalid amount')
|
|
346
393
|
if (!isValidBsvAddress(address)) throw new Error('Invalid BSV address')
|
|
@@ -352,8 +399,9 @@ export async function sendToAddress(args: {
|
|
|
352
399
|
const result = (await wallet.createAction(
|
|
353
400
|
{
|
|
354
401
|
// The recipient's address is the description so the activity list has a
|
|
355
|
-
// name for the row without a lookup; the to: label is what lets it draw
|
|
356
|
-
|
|
402
|
+
// name for the row without a lookup; the to: label is what lets it draw
|
|
403
|
+
// a face. A sender's own note overrides it, same as the other rails.
|
|
404
|
+
description: note?.trim() || abbreviateKey(address),
|
|
357
405
|
outputs: [{ lockingScript, satoshis: sats, outputDescription: 'BSV for recipient address' }],
|
|
358
406
|
labels: ['legacy', 'outbound', addressLabel(TO_ADDRESS_LABEL_PREFIX, address)],
|
|
359
407
|
...(isSendMax ? { options: { randomizeOutputs: false } } : {})
|
package/core/pay/rails/handle.ts
CHANGED
|
@@ -23,6 +23,7 @@ import type { CreditFailureKind } from '../creditErrors'
|
|
|
23
23
|
import { abbreviateKey } from '../counterparty'
|
|
24
24
|
import { isDuplicateMessageError, sendControlMessage, type ResendReason } from '../../peerpay/control'
|
|
25
25
|
import { TaskDrainOutbox } from '../../monitor/TaskDrainOutbox'
|
|
26
|
+
import type { MandalaRuntime, TokenSendResult } from '../../mandala/runtime'
|
|
26
27
|
|
|
27
28
|
export const MESSAGE_BOX_URL_KEY = 'message_box_url'
|
|
28
29
|
export const DEFAULT_MESSAGE_BOX_URL = 'https://gmb.bsvblockchain.tech'
|
|
@@ -66,17 +67,31 @@ interface InternalizingWallet {
|
|
|
66
67
|
/**
|
|
67
68
|
* A shareable BRC-125 payment link for a handle.
|
|
68
69
|
*
|
|
69
|
-
* `peerpay:<key>[?sats=<n>][&url=<host>]
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
*
|
|
73
|
-
*
|
|
74
|
-
*
|
|
70
|
+
* `peerpay:<key>[?sats=<n>][&url=<host>]` for BSV, or
|
|
71
|
+
* `peerpay:<key>?asset=<txid.vout>[&amount=<base units>][&url=<host>]` for a
|
|
72
|
+
* token — the same forms the app parses (parsePeerPayURI.ts) and routes
|
|
73
|
+
* (+native-intent.ts in the host app). A non-positive figure emits no
|
|
74
|
+
* `sats`/`amount` — a zero would be an invalid link, and an open request is
|
|
75
|
+
* exactly the absence of a figure. A token request never carries `sats`: the
|
|
76
|
+
* two are different money, and the parser refuses a link that names both.
|
|
77
|
+
* `url` is this app's extension: the payee's message-box host, so the payer
|
|
78
|
+
* can skip the overlay lookup. Omitted for the no-server sentinel and for blank.
|
|
75
79
|
*/
|
|
76
|
-
export function peerPayLinkFor(
|
|
80
|
+
export function peerPayLinkFor(
|
|
81
|
+
identityKey: string,
|
|
82
|
+
sats?: number,
|
|
83
|
+
messageBoxUrl?: string,
|
|
84
|
+
token?: { assetId: string; baseUnits?: number }
|
|
85
|
+
): string {
|
|
77
86
|
const params: string[] = []
|
|
78
|
-
|
|
79
|
-
|
|
87
|
+
if (token) {
|
|
88
|
+
params.push(`asset=${token.assetId.toLowerCase()}`)
|
|
89
|
+
const units = token.baseUnits !== undefined ? Math.round(Number(token.baseUnits)) : NaN
|
|
90
|
+
if (Number.isFinite(units) && units > 0) params.push(`amount=${units}`)
|
|
91
|
+
} else {
|
|
92
|
+
const amount = sats !== undefined ? Math.round(Number(sats)) : NaN
|
|
93
|
+
if (Number.isFinite(amount) && amount > 0) params.push(`sats=${amount}`)
|
|
94
|
+
}
|
|
80
95
|
const host = (messageBoxUrl ?? '').trim().replace(/\/+$/, '')
|
|
81
96
|
if (host && host !== NO_MESSAGE_BOX) params.push(`url=${encodeURIComponent(host)}`)
|
|
82
97
|
const base = `peerpay:${identityKey.toLowerCase()}`
|
|
@@ -567,6 +582,70 @@ export async function cancelOutboxPayment(args: {
|
|
|
567
582
|
return { aborted }
|
|
568
583
|
}
|
|
569
584
|
|
|
585
|
+
// ── The token half of the handle rail (offline-settlement spec §4.5) ──
|
|
586
|
+
//
|
|
587
|
+
// Same rail, different pipeline. A satoshi payment is minted here and delivered
|
|
588
|
+
// through the `payment_inbox` PeerPay box; a Mandala token payment is minted by
|
|
589
|
+
// `@bsv/mandala`'s own overlay-first transfer and delivered through the
|
|
590
|
+
// `'mandala-payments'` box — and unlike the nearby rail, the handle rail's
|
|
591
|
+
// SENDER is online by construction, so it submits before it notifies and can
|
|
592
|
+
// forward the tip's own σ_I in the body. That is why `TokenSendResult` carries
|
|
593
|
+
// `settled`: it is the difference between "sent · settling" and "sent · settled
|
|
594
|
+
// with {{issuer}}" on the payer's screen, decided by evidence rather than hope.
|
|
595
|
+
//
|
|
596
|
+
// Neither function reaches into the runtime's internals: both take the
|
|
597
|
+
// narrowest slice of `MandalaRuntime` they need, so this module keeps knowing
|
|
598
|
+
// nothing about overlays, baskets or settlement rows.
|
|
599
|
+
|
|
600
|
+
/** The slice of `MandalaRuntime` the handle rail uses. */
|
|
601
|
+
export type HandleTokenRuntime = Pick<
|
|
602
|
+
MandalaRuntime,
|
|
603
|
+
'available' | 'recipientRefusal' | 'sendToHandle' | 'receiveFromInbox'
|
|
604
|
+
>
|
|
605
|
+
|
|
606
|
+
/**
|
|
607
|
+
* Send tokens to a handle.
|
|
608
|
+
*
|
|
609
|
+
* Every refusal this function can make itself is made BEFORE the runtime is
|
|
610
|
+
* touched — no runtime, wrong network, a recipient that is not an identity key
|
|
611
|
+
* — because each of those is a fact about the request, not about the overlay,
|
|
612
|
+
* and an overlay round-trip cannot change any of them.
|
|
613
|
+
*/
|
|
614
|
+
export async function sendTokenViaHandle(args: {
|
|
615
|
+
runtime: HandleTokenRuntime | undefined
|
|
616
|
+
recipient: string
|
|
617
|
+
assetId: string
|
|
618
|
+
baseUnits: number
|
|
619
|
+
}): Promise<TokenSendResult> {
|
|
620
|
+
const { runtime, recipient, assetId, baseUnits } = args
|
|
621
|
+
if (!runtime?.available) {
|
|
622
|
+
return { kind: 'unavailable', message: 'Stablecoins are not available on this network' }
|
|
623
|
+
}
|
|
624
|
+
const refusal = runtime.recipientRefusal(recipient)
|
|
625
|
+
if (refusal) return { kind: 'refused', code: 'ERR_RECIPIENT', message: refusal }
|
|
626
|
+
return await runtime.sendToHandle({ assetId, recipientIdentityKey: recipient, baseUnits })
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/**
|
|
630
|
+
* The Mandala half of the handle rail's receive drain.
|
|
631
|
+
*
|
|
632
|
+
* Called beside `creditInboxOnce` on the same tick: the two inboxes are
|
|
633
|
+
* different message boxes on the same server, and a wallet that drained only
|
|
634
|
+
* one would leave real money sitting in the other. Never throws — a MessageBox
|
|
635
|
+
* that is down must not take the satoshi inbox down with it.
|
|
636
|
+
*/
|
|
637
|
+
export async function drainMandalaInbox(
|
|
638
|
+
runtime: HandleTokenRuntime | undefined
|
|
639
|
+
): Promise<{ credited: number; failed: number }> {
|
|
640
|
+
if (!runtime?.available) return { credited: 0, failed: 0 }
|
|
641
|
+
try {
|
|
642
|
+
return await runtime.receiveFromInbox()
|
|
643
|
+
} catch (e) {
|
|
644
|
+
console.warn('[mandala] the token inbox drain failed:', e instanceof Error ? e.message : String(e))
|
|
645
|
+
return { credited: 0, failed: 0 }
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
|
|
570
649
|
/**
|
|
571
650
|
* Whether an error from the handle rail means "the message box server could not
|
|
572
651
|
* be reached" rather than anything about the payment itself. The raw shapes —
|
package/core/pay/rails/index.ts
CHANGED
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
validatePeerPayURI,
|
|
14
14
|
type PeerPayValidationResult,
|
|
15
15
|
peerPayValidationMessage,
|
|
16
|
+
peerPayHasErrors,
|
|
16
17
|
isCompressedPublicKey
|
|
17
18
|
} from '../../parsePeerPayURI'
|
|
18
19
|
|
|
@@ -21,10 +22,15 @@ export { isCompressedPublicKey }
|
|
|
21
22
|
|
|
22
23
|
export type RailId = 'nearby' | 'handle' | 'address'
|
|
23
24
|
|
|
24
|
-
/**
|
|
25
|
+
/**
|
|
26
|
+
* How a counterparty was identified. Each variant carries only what its rail
|
|
27
|
+
* needs. A handle may carry a figure in exactly one money: `sats` (BSV), or
|
|
28
|
+
* `asset` (a token's genesis outpoint) with `amount` in its base units —
|
|
29
|
+
* `asset` alone is an open token request.
|
|
30
|
+
*/
|
|
25
31
|
export type PayTarget =
|
|
26
32
|
| { kind: 'nearby'; session: Session }
|
|
27
|
-
| { kind: 'handle'; identityKey: string; sats?: number; messageBoxUrl?: string }
|
|
33
|
+
| { kind: 'handle'; identityKey: string; sats?: number; asset?: string; amount?: number; messageBoxUrl?: string }
|
|
28
34
|
| { kind: 'address'; address: string; sats?: number }
|
|
29
35
|
|
|
30
36
|
/** Six cell names. Since the universal input, `pay-*` are deep-link aliases that all open the send form; `get-*` open one receive method directly. */
|
|
@@ -98,18 +104,20 @@ export type RecipientInput =
|
|
|
98
104
|
| { kind: 'empty' }
|
|
99
105
|
| { kind: 'address'; address: string }
|
|
100
106
|
| { kind: 'invalid_address' }
|
|
101
|
-
| { kind: 'handle'; identityKey: string; sats?: number; messageBoxUrl?: string }
|
|
107
|
+
| { kind: 'handle'; identityKey: string; sats?: number; asset?: string; amount?: number; messageBoxUrl?: string }
|
|
102
108
|
| { kind: 'invalid_link'; message: string }
|
|
103
109
|
| { kind: 'search'; query: string }
|
|
104
110
|
|
|
105
111
|
function handleFromPeerPay(result: PeerPayValidationResult): RecipientInput {
|
|
106
|
-
if (!result.identityKey || result
|
|
112
|
+
if (!result.identityKey || peerPayHasErrors(result)) {
|
|
107
113
|
return { kind: 'invalid_link', message: peerPayValidationMessage(result) ?? 'Invalid peerpay link' }
|
|
108
114
|
}
|
|
109
115
|
return {
|
|
110
116
|
kind: 'handle',
|
|
111
117
|
identityKey: result.identityKey,
|
|
112
118
|
...(result.sats !== undefined ? { sats: result.sats } : {}),
|
|
119
|
+
...(result.asset !== undefined ? { asset: result.asset } : {}),
|
|
120
|
+
...(result.amount !== undefined ? { amount: result.amount } : {}),
|
|
113
121
|
...(result.messageBoxUrl ? { messageBoxUrl: result.messageBoxUrl } : {})
|
|
114
122
|
}
|
|
115
123
|
}
|
|
@@ -151,11 +159,13 @@ export function classifyScan(raw: string): PayTarget | null {
|
|
|
151
159
|
|
|
152
160
|
if (text.toLowerCase().startsWith('peerpay:')) {
|
|
153
161
|
const result = validatePeerPayURI(text)
|
|
154
|
-
if (!result.identityKey || result
|
|
162
|
+
if (!result.identityKey || peerPayHasErrors(result)) return null
|
|
155
163
|
return {
|
|
156
164
|
kind: 'handle',
|
|
157
165
|
identityKey: result.identityKey,
|
|
158
|
-
sats: result.sats,
|
|
166
|
+
...(result.sats !== undefined ? { sats: result.sats } : {}),
|
|
167
|
+
...(result.asset !== undefined ? { asset: result.asset } : {}),
|
|
168
|
+
...(result.amount !== undefined ? { amount: result.amount } : {}),
|
|
159
169
|
...(result.messageBoxUrl ? { messageBoxUrl: result.messageBoxUrl } : {})
|
|
160
170
|
}
|
|
161
171
|
}
|