@bsv/expo-wallet-toolbox 0.21.0 → 0.23.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 +222 -0
- package/README.md +82 -13
- package/core/bridge/BrowserBridgeProvider.tsx +273 -0
- package/core/bridge/bindings.ts +459 -0
- package/core/bridge/conformance.ts +222 -0
- package/core/bridge/consent.ts +494 -0
- package/core/bridge/consentSheetSource.ts +98 -0
- package/core/bridge/dispatcher.ts +621 -0
- package/core/bridge/inbox.ts +464 -0
- package/core/bridge/index.ts +48 -0
- package/core/bridge/loopback/cors.ts +57 -0
- package/core/bridge/loopback/endpoints.ts +11 -0
- package/core/bridge/loopback/hostCheck.ts +25 -0
- package/core/bridge/loopback/index.ts +7 -0
- package/core/bridge/loopback/launchProof.ts +166 -0
- package/core/bridge/loopback/router.ts +770 -0
- package/core/bridge/loopback/routerTypes.ts +115 -0
- package/core/bridge/loopback/status.ts +52 -0
- package/core/bridge/memoryInboxStore.ts +222 -0
- package/core/bridge/permissionPolicy.ts +247 -0
- package/core/bridge/policy.ts +72 -0
- package/core/bridge/protocol/base64url.ts +64 -0
- package/core/bridge/protocol/connectionError.ts +79 -0
- package/core/bridge/protocol/constants.ts +21 -0
- package/core/bridge/protocol/continuity.ts +21 -0
- package/core/bridge/protocol/descriptor.ts +395 -0
- package/core/bridge/protocol/envelopes.ts +188 -0
- package/core/bridge/protocol/errorCodec.ts +164 -0
- package/core/bridge/protocol/json.ts +237 -0
- package/core/bridge/protocol/limits.ts +43 -0
- package/core/bridge/protocol/methods.ts +55 -0
- package/core/bridge/protocol/origin.ts +130 -0
- package/core/bridge/runtime.ts +642 -0
- package/core/bridge/runtimeFlags.ts +34 -0
- package/core/bridge/testing/conformanceCases.ts +149 -0
- package/core/bridge/testing/pageClient.ts +44 -0
- package/core/bridge/unverifiedManager.ts +97 -0
- package/core/bridge/unverifiedOriginator.ts +79 -0
- package/core/config.tsx +1 -16
- package/core/contacts/contactActivity.ts +48 -28
- package/core/contacts/contactsStore.ts +2 -2
- package/core/context/WalletConnectionContext.tsx +7 -1
- package/core/context/WalletContext.tsx +420 -348
- package/core/context/sessionTeardown.ts +46 -0
- package/core/demo/demoAssets.ts +8 -10
- package/core/demo/demoLedger.ts +32 -38
- package/core/demo/demoMandalaRuntime.ts +67 -49
- package/core/demo/index.ts +1 -1
- package/core/hooks/usePermissionQueue.ts +89 -34
- package/core/i18n/translations.tsx +983 -12
- package/core/index.ts +70 -37
- package/core/localpay/build.ts +110 -569
- package/core/localpay/codec.ts +190 -93
- package/core/localpay/pending.ts +217 -202
- package/core/localpay/session.ts +99 -25
- package/core/localpay/types.ts +6 -5
- package/core/localpay/verify.ts +118 -173
- package/core/mandala/abortGuard.ts +97 -120
- package/core/mandala/accessPolicy.ts +133 -0
- package/core/mandala/assets.ts +370 -0
- package/core/mandala/colorGuard.ts +178 -0
- package/core/mandala/colorModule.ts +82 -0
- package/core/mandala/createRuntime.ts +483 -2392
- package/core/mandala/handle.ts +694 -0
- package/core/mandala/kvStore.ts +105 -0
- package/core/mandala/nearby.ts +185 -0
- package/core/mandala/receipt.ts +121 -0
- package/core/mandala/runtime.ts +166 -312
- package/core/mandala/settle.ts +540 -0
- package/core/mandala/transferJournal.ts +395 -0
- package/core/mandala/types.ts +61 -311
- package/core/networks.ts +5 -5
- package/core/offline/cancelParked.ts +80 -63
- package/core/offline/payerHold.ts +52 -118
- package/core/parsePeerPayURI.ts +25 -12
- package/core/pay/rails/handle.ts +15 -14
- package/core/pay/rails/index.ts +5 -3
- package/core/pay/rails/nearby.ts +25 -87
- package/core/profiles/assertProfileEmpty.ts +19 -10
- package/core/services/autoApprovePolicy.ts +7 -1
- package/core/services/capWalletArgs.ts +2 -1
- package/core/services/permissionPrompts.ts +132 -0
- package/core/services/signingPermissionPolicy.ts +230 -2
- package/core/services/vault/guard.ts +15 -4
- package/core/services/walletArgLimits.ts +17 -2
- package/core/storage/StorageExpoSQLite.ts +93 -229
- package/core/storage/encryptedDbImage.ts +325 -0
- package/core/storage/methods/processOfflineActions.ts +86 -136
- package/core/storage/schema/createTables.ts +9 -184
- package/core/toolboxConfig.ts +18 -1
- package/package.json +9 -8
- package/ui/bridgeSheet/ContextRelay.tsx +86 -0
- package/ui/bridgeSheet/relayedContexts.ts +21 -0
- package/ui/components/pay/AssetPicker.tsx +2 -2
- package/ui/components/pay/HandleReceive.tsx +4 -4
- package/ui/components/pay/NearbyFlow.tsx +324 -239
- package/ui/components/pay/RequestHub.tsx +10 -0
- package/ui/components/pay/UniversalSend.tsx +31 -28
- package/ui/components/pay/useRecipientInput.ts +2 -2
- package/ui/components/ui/PermissionSheet.tsx +625 -315
- package/ui/components/ui/Sheet.tsx +59 -7
- package/ui/components/ui/colorPrompt.ts +236 -0
- package/ui/components/ui/sheetResumeSignal.ts +19 -0
- package/ui/components/wallet/AmountInput.tsx +9 -6
- package/ui/components/wallet/AssetAmount.tsx +6 -6
- package/ui/components/wallet/AssetSwitcherDropdown.tsx +26 -7
- package/ui/components/wallet/Balance.tsx +3 -1
- package/ui/components/wallet/ContactActivityList.tsx +10 -13
- package/ui/components/wallet/tokenEviction.ts +9 -9
- package/ui/exportDatabases.ts +94 -5
- package/ui/hooks/useExportWalletData.ts +37 -24
- package/ui/hooks/useMandala.ts +6 -6
- package/ui/hooks/useSpendableBalance.ts +3 -1
- package/ui/importDatabases.ts +124 -29
- package/ui/index.ts +4 -0
- package/ui/screens/PayScreen.tsx +14 -20
- package/ui/screens/SettingsScreen.tsx +3 -1
- package/ui/screens/WalletCheckScreen.tsx +7 -2
- package/ui/screens/WalletConfigScreen.tsx +13 -1
- package/ui/screens/WalletHomeScreen.tsx +40 -14
- package/ui/screens/tokenRowTitle.ts +28 -15
- package/ui/tokenFormat.ts +133 -69
- package/ui/tokenStatus.ts +5 -8
- package/core/localpay/settlementAck.ts +0 -155
- package/core/mandala/basketMigration.ts +0 -166
- package/core/mandala/bundle.ts +0 -244
- package/core/mandala/drain.ts +0 -754
- package/core/mandala/inboxPrehold.ts +0 -193
- package/core/mandala/permissionModule.ts +0 -931
- package/core/mandala/resendTransfer.ts +0 -178
- package/core/mandala/settlementStore.ts +0 -434
- package/core/mandala/token.ts +0 -45
- package/core/offline/tokenFrames.ts +0 -197
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Key-value adapters over `StorageExpoSQLite`'s `key_value_store`.
|
|
3
|
+
*
|
|
4
|
+
* Two durable stores share the wallet's one KV table:
|
|
5
|
+
* - `createMandalaKvStorage` — the `@bsv/mandala` lib's `MandalaStorage`;
|
|
6
|
+
* - `createColorModuleStore` — the color permission module's
|
|
7
|
+
* `ColorModuleStore` (IC §2.1). The module owns every `color.v1.` key and
|
|
8
|
+
* its layout is internal to it: the wallet never reads those keys and
|
|
9
|
+
* calls the module's host-only `markSettled(txid)` instead.
|
|
10
|
+
*
|
|
11
|
+
* The same `createMandalaKvStorage` also backs the Mandala host ledger
|
|
12
|
+
* (`mandala.host.v1.record.*`, design §9 B7), which no BRC-100 caller reaches.
|
|
13
|
+
*
|
|
14
|
+
* Get/set go through the storage's own `getKeyValue`/`setKeyValue` (an atomic
|
|
15
|
+
* per-key upsert). Delete and prefix listing go straight to SQL because the
|
|
16
|
+
* storage exposes neither, and both are hard failures when the database is
|
|
17
|
+
* closed rather than silent no-ops: a delete that quietly did nothing would
|
|
18
|
+
* leave a completed record behind forever, and an empty listing would read
|
|
19
|
+
* as "nothing outstanding" when work is in fact pending.
|
|
20
|
+
*/
|
|
21
|
+
import type { ColorModuleStore } from '@bsv/color-permission-module'
|
|
22
|
+
import type { MandalaStorage } from '@bsv/mandala'
|
|
23
|
+
|
|
24
|
+
/** What the adapters need: the toolbox's own key/value table, plus raw SQL for the two verbs it lacks. */
|
|
25
|
+
export interface WalletKv {
|
|
26
|
+
getKeyValue(key: string): Promise<string | undefined>
|
|
27
|
+
setKeyValue(key: string, value: string): Promise<void>
|
|
28
|
+
readonly sqliteDb?: {
|
|
29
|
+
runAsync(sql: string, params: (string | number | null)[]): Promise<{ changes: number }>
|
|
30
|
+
getAllAsync(sql: string, params: (string | number | null)[]): Promise<unknown[]>
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
type SqlHandle = NonNullable<WalletKv['sqliteDb']>
|
|
35
|
+
|
|
36
|
+
/** LIKE treats these as wildcards; a prefix containing one must still match literally. */
|
|
37
|
+
function escapeLike(prefix: string): string {
|
|
38
|
+
return prefix.replace(/[\\%_]/g, c => `\\${c}`)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function sqlHandle(kv: WalletKv, owner: string): SqlHandle {
|
|
42
|
+
const handle = kv.sqliteDb
|
|
43
|
+
if (!handle) throw new Error(`${owner}: the wallet database is not open`)
|
|
44
|
+
return handle
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function deleteKey(db: SqlHandle, key: string): Promise<void> {
|
|
48
|
+
await db.runAsync('DELETE FROM key_value_store WHERE key = ?', [key])
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Every stored key that starts with `prefix`, compared exactly.
|
|
53
|
+
*
|
|
54
|
+
* The escaped `LIKE` narrows in SQL, but SQLite's `LIKE` is ASCII
|
|
55
|
+
* case-insensitive by default, so its result is a superset: the
|
|
56
|
+
* `startsWith` filter makes the match literal and case-sensitive.
|
|
57
|
+
*/
|
|
58
|
+
async function keysWithPrefix(db: SqlHandle, prefix: string): Promise<string[]> {
|
|
59
|
+
const rows = (await db.getAllAsync(`SELECT key FROM key_value_store WHERE key LIKE ? ESCAPE '\\'`, [
|
|
60
|
+
`${escapeLike(prefix)}%`
|
|
61
|
+
])) as { key: string }[]
|
|
62
|
+
return rows.map(r => r.key).filter(key => key.startsWith(prefix))
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* `MandalaStorage` over `StorageExpoSQLite`'s `key_value_store` (D3c).
|
|
67
|
+
*
|
|
68
|
+
* React Native has no `localStorage`, so without this adapter the lib
|
|
69
|
+
* silently falls back to a process-lifetime Map and anything it journals
|
|
70
|
+
* dies with the process.
|
|
71
|
+
*/
|
|
72
|
+
export function createMandalaKvStorage(kv: WalletKv): MandalaStorage {
|
|
73
|
+
const db = (): SqlHandle => sqlHandle(kv, 'Mandala journal storage')
|
|
74
|
+
return {
|
|
75
|
+
getItem: async key => (await kv.getKeyValue(key)) ?? null,
|
|
76
|
+
setItem: async (key, value) => {
|
|
77
|
+
await kv.setKeyValue(key, value)
|
|
78
|
+
},
|
|
79
|
+
removeItem: async key => {
|
|
80
|
+
await deleteKey(db(), key)
|
|
81
|
+
},
|
|
82
|
+
keys: async prefix => keysWithPrefix(db(), prefix)
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The color module's durable store (IC §2.1) over `key_value_store`.
|
|
88
|
+
*
|
|
89
|
+
* The module's settlement records live here; losing a write would leave a
|
|
90
|
+
* settled coin reading `color_offline`, so every failure propagates to the
|
|
91
|
+
* module rather than being swallowed.
|
|
92
|
+
*/
|
|
93
|
+
export function createColorModuleStore(kv: WalletKv): ColorModuleStore {
|
|
94
|
+
const db = (): SqlHandle => sqlHandle(kv, 'Color module store')
|
|
95
|
+
return {
|
|
96
|
+
get: async key => kv.getKeyValue(key),
|
|
97
|
+
set: async (key, value) => {
|
|
98
|
+
await kv.setKeyValue(key, value)
|
|
99
|
+
},
|
|
100
|
+
delete: async key => {
|
|
101
|
+
await deleteKey(db(), key)
|
|
102
|
+
},
|
|
103
|
+
keys: async prefix => keysWithPrefix(db(), prefix)
|
|
104
|
+
}
|
|
105
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The nearby rail's PAYER half of the token runtime (plan 07 Task 15).
|
|
3
|
+
*
|
|
4
|
+
* The color module funds and signs the hand-over inside lib `sendHandover`,
|
|
5
|
+
* which also builds the envelope from the host wallet's custody and records
|
|
6
|
+
* the hand-over `pending` in the host ledger (B7); localpay only frames its
|
|
7
|
+
* v4 body. What lives here is the wallet's own record of it, the kept body
|
|
8
|
+
* and `color_transfers` (W1), which the broadcast hold and the abort refusal
|
|
9
|
+
* both read.
|
|
10
|
+
*
|
|
11
|
+
* `handover`, in this order (stability mandate):
|
|
12
|
+
* 1. Refuse what the request alone decides (amount domain, recipient).
|
|
13
|
+
* 2. `sendHandover` with the SESSION's own remittance strings (a contract
|
|
14
|
+
* extension of IC §8.1: both or neither, ≤ 48 bytes, used verbatim), so
|
|
15
|
+
* the payee's output is derived from the nonces the payee minted.
|
|
16
|
+
* 3. Check the result is bound to that request: the receipt carries the
|
|
17
|
+
* same asset and strings, and the payee output is index 0 (the frame
|
|
18
|
+
* names it). Anything else is released, never journaled.
|
|
19
|
+
* 4. Keep the v4 body (a handle-rail resend of this payment needs it), then
|
|
20
|
+
* journal `built`, rail `nearby`, with the receipt custody. Nobody has
|
|
21
|
+
* the bytes yet, so a body or journal fault (or a txid already journaled
|
|
22
|
+
* for another transfer) is answered by releasing the action, never by
|
|
23
|
+
* returning bytes the journal does not know.
|
|
24
|
+
*
|
|
25
|
+
* `onHandedOver` moves the row forward only: built → parked → handed_over.
|
|
26
|
+
* A repeat, or a request for a state the row is already past, succeeds
|
|
27
|
+
* without writing, because the handle rail's resend also hands a parked row
|
|
28
|
+
* over and the payer's own release then confirms it. A cancelled, refused or
|
|
29
|
+
* missing row is a failure: `payerHold` reads a failure as "not journaled"
|
|
30
|
+
* and keeps the queue row parked.
|
|
31
|
+
*/
|
|
32
|
+
import type { WalletInterface } from '@bsv/sdk'
|
|
33
|
+
import { MAX_UINT64, sendHandover, type HandoverResult, type HostLedger } from '@bsv/mandala'
|
|
34
|
+
import { devLog } from '../logging'
|
|
35
|
+
import { releaseUnseenHandover, type HandoverBodies } from './handle'
|
|
36
|
+
import type { NearbyTokenDeps } from './runtime'
|
|
37
|
+
import type { TransferJournal } from './transferJournal'
|
|
38
|
+
import type { ColorTransferState } from './types'
|
|
39
|
+
|
|
40
|
+
export interface NearbyPayerDeps {
|
|
41
|
+
/** The PUBLISHED manager, bound to the admin originator. */
|
|
42
|
+
wallet: WalletInterface
|
|
43
|
+
identityKey: () => Promise<string>
|
|
44
|
+
journal: TransferJournal
|
|
45
|
+
/** The host's UNDERLYING wallet (the envelope is built from its custody). */
|
|
46
|
+
hostWallet: WalletInterface
|
|
47
|
+
/** The host ledger shared with the issuer-v1 handler. */
|
|
48
|
+
ledger: HostLedger
|
|
49
|
+
/** Where the v4 body is kept for a later resend. */
|
|
50
|
+
bodies: HandoverBodies
|
|
51
|
+
/** Plain reason a recipient cannot receive tokens, or null. */
|
|
52
|
+
recipientRefusal: (recipient: string) => string | null
|
|
53
|
+
/** Journal state changed. */
|
|
54
|
+
onChange?: () => void
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export type NearbyPayer = Pick<NearbyTokenDeps, 'handover' | 'onHandedOver'>
|
|
58
|
+
|
|
59
|
+
/** States each `onHandedOver` target may be reached from. */
|
|
60
|
+
const ADVANCE_FROM: Record<'parked' | 'handed_over', readonly ColorTransferState[]> = {
|
|
61
|
+
parked: ['built'],
|
|
62
|
+
handed_over: ['built', 'parked']
|
|
63
|
+
}
|
|
64
|
+
/** States that already satisfy each target: the row is there or further on. */
|
|
65
|
+
const ALREADY_AT: Record<'parked' | 'handed_over', readonly ColorTransferState[]> = {
|
|
66
|
+
parked: ['parked', 'handed_over', 'settled'],
|
|
67
|
+
handed_over: ['handed_over', 'settled']
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const messageOf = (e: unknown): string => (e instanceof Error ? e.message : String(e))
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Why `h` is not the hand-over this request asked for, or null when it is.
|
|
74
|
+
* Shared by the runtime (before journaling) and the frame builder (before
|
|
75
|
+
* framing), so the two can never disagree about what "bound" means.
|
|
76
|
+
*/
|
|
77
|
+
export function handoverMismatch(
|
|
78
|
+
h: Pick<HandoverResult, 'outputIndex' | 'receipt'>,
|
|
79
|
+
want: { assetId: string; derivationPrefix: string; derivationSuffix: string }
|
|
80
|
+
): string | null {
|
|
81
|
+
if (h.outputIndex !== 0) return `the hand-over pays output ${String(h.outputIndex)}, not output 0`
|
|
82
|
+
if (h.receipt?.assetId !== want.assetId) return 'the hand-over is for another asset'
|
|
83
|
+
if (h.receipt.derivationPrefix !== want.derivationPrefix || h.receipt.derivationSuffix !== want.derivationSuffix) {
|
|
84
|
+
return 'the hand-over does not carry this session’s remittance'
|
|
85
|
+
}
|
|
86
|
+
return null
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function createNearbyPayer(d: NearbyPayerDeps): NearbyPayer {
|
|
90
|
+
const notify = (): void => {
|
|
91
|
+
try {
|
|
92
|
+
d.onChange?.()
|
|
93
|
+
} catch (e) {
|
|
94
|
+
devLog('[mandala] nearby: a change listener threw:', e)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const handover: NearbyPayer['handover'] = async a => {
|
|
99
|
+
const units = a.units
|
|
100
|
+
if (typeof units !== 'bigint' || units < 1n || units > MAX_UINT64) {
|
|
101
|
+
throw new Error('A token amount must be a whole number from 1 to 18446744073709551615 base units')
|
|
102
|
+
}
|
|
103
|
+
const refusal = d.recipientRefusal(a.recipientKey)
|
|
104
|
+
if (refusal !== null) throw new Error(refusal)
|
|
105
|
+
const recipientKey = a.recipientKey.trim().toLowerCase()
|
|
106
|
+
const note = a.note !== undefined && a.note.trim() !== '' ? a.note.trim() : undefined
|
|
107
|
+
const identityKey = await d.identityKey()
|
|
108
|
+
|
|
109
|
+
// A lib throw is passed through untouched: its `.name` is the refusal
|
|
110
|
+
// class the screen maps (IC D22), and nothing was signed.
|
|
111
|
+
const h = await sendHandover({
|
|
112
|
+
wallet: d.wallet,
|
|
113
|
+
identityKey,
|
|
114
|
+
assetId: a.assetId,
|
|
115
|
+
amount: units,
|
|
116
|
+
recipientKey,
|
|
117
|
+
derivationPrefix: a.derivationPrefix,
|
|
118
|
+
derivationSuffix: a.derivationSuffix,
|
|
119
|
+
...(note !== undefined ? { note } : {}),
|
|
120
|
+
hostWallet: d.hostWallet,
|
|
121
|
+
ledger: d.ledger,
|
|
122
|
+
// The journal row below, the kept body and the host ledger own
|
|
123
|
+
// durability; see the handle rail's `sendToHandle` for why the lib's
|
|
124
|
+
// txJournal stays off.
|
|
125
|
+
journal: false
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
// Signed. From here every exit either journals it or releases it.
|
|
129
|
+
const mismatch = handoverMismatch(h, a)
|
|
130
|
+
if (mismatch !== null) {
|
|
131
|
+
await releaseUnseenHandover(d, h)
|
|
132
|
+
throw new Error(mismatch)
|
|
133
|
+
}
|
|
134
|
+
try {
|
|
135
|
+
await d.bodies.put(h.txid, h.body)
|
|
136
|
+
const wrote = await d.journal.insert({
|
|
137
|
+
txid: h.txid,
|
|
138
|
+
role: 'sent',
|
|
139
|
+
state: 'built',
|
|
140
|
+
delivered: false,
|
|
141
|
+
reference: h.reference,
|
|
142
|
+
rail: 'nearby',
|
|
143
|
+
units,
|
|
144
|
+
counterpartyKey: recipientKey,
|
|
145
|
+
outputIndex: h.outputIndex,
|
|
146
|
+
assetId: a.assetId,
|
|
147
|
+
...(note !== undefined ? { note } : {}),
|
|
148
|
+
derivationPrefix: h.receipt.derivationPrefix,
|
|
149
|
+
derivationSuffix: h.receipt.derivationSuffix,
|
|
150
|
+
senderIdentityKey: h.receipt.senderIdentityKey
|
|
151
|
+
})
|
|
152
|
+
if (!wrote) {
|
|
153
|
+
const existing = await d.journal.get(h.txid)
|
|
154
|
+
if (existing?.role !== 'sent' || existing.reference !== h.reference) {
|
|
155
|
+
throw new Error(`color_transfers already holds ${h.txid} for another transfer`)
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
} catch (e) {
|
|
159
|
+
devLog(`[mandala] nearby: journaling the hand-over ${h.txid} failed; releasing it unframed:`, messageOf(e))
|
|
160
|
+
await releaseUnseenHandover(d, h)
|
|
161
|
+
throw e
|
|
162
|
+
}
|
|
163
|
+
notify()
|
|
164
|
+
return h
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const onHandedOver: NearbyPayer['onHandedOver'] = async (txid, to) => {
|
|
168
|
+
const patch = to === 'handed_over' ? { delivered: true } : undefined
|
|
169
|
+
if (await d.journal.advance(txid, ADVANCE_FROM[to], to, patch)) {
|
|
170
|
+
notify()
|
|
171
|
+
return
|
|
172
|
+
}
|
|
173
|
+
const row = await d.journal.get(txid)
|
|
174
|
+
if (row?.role !== 'sent') throw new Error(`color_transfers has no sent row for ${txid}`)
|
|
175
|
+
if (!ALREADY_AT[to].includes(row.state)) {
|
|
176
|
+
throw new Error(`the hand-over ${txid} is ${row.state}; it cannot be marked ${to}`)
|
|
177
|
+
}
|
|
178
|
+
if (to === 'handed_over' && row.state === 'handed_over' && !row.delivered) {
|
|
179
|
+
await d.journal.setDelivered(txid, true)
|
|
180
|
+
notify()
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
return { handover, onHandedOver }
|
|
185
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The token half of a nearby (localpay) frame, as the v4 hand-over body the
|
|
3
|
+
* lib reads, and how a failed receipt is classified (design §9 B7, IC §7.3).
|
|
4
|
+
*
|
|
5
|
+
* A FRAME_VERSION 7 token frame carries exactly the §7.2 body members (minus
|
|
6
|
+
* `v`/`kind`, which the frame version replaces): the frame's own sender key,
|
|
7
|
+
* remittance strings, output index, note and AtomicBEEF, plus the token
|
|
8
|
+
* block's asset id, decimal amount, sender mode and the σ / envelope evidence.
|
|
9
|
+
* The payee rebuilds the body here and runs the lib's own recipient path on it
|
|
10
|
+
* (`parseHandoverBody` → `acceptHandover`: online submit or offline COVER,
|
|
11
|
+
* host ledger record, then the plain BRC-207 receipt internalize). The
|
|
12
|
+
* receipt itself is the 5-member custody JSON (IC §7.1); no evidence ever
|
|
13
|
+
* travels in `customInstructions`.
|
|
14
|
+
*
|
|
15
|
+
* Pure: no wallet, no storage, no network.
|
|
16
|
+
*/
|
|
17
|
+
import { Utils } from '@bsv/sdk'
|
|
18
|
+
import { classifyReceiveError, type HandoverBodyV4, type HandoverResult } from '@bsv/mandala'
|
|
19
|
+
import type { PaymentFrame, TokenPayment } from '../localpay/codec'
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The v4 hand-over body a token frame stands for. Throws a TypeError for a
|
|
23
|
+
* BSV frame (the codec refuses a token kind without its block; this is the
|
|
24
|
+
* second wall). Members are copied verbatim: `parseHandoverBody` is the one
|
|
25
|
+
* strict check, so this never "repairs" anything a sender put on the wire.
|
|
26
|
+
*/
|
|
27
|
+
export function bodyFromFrame(frame: PaymentFrame): HandoverBodyV4 {
|
|
28
|
+
if (frame.kind !== 'token' || frame.token === undefined) {
|
|
29
|
+
throw new TypeError('a v4 hand-over body is built from a token frame')
|
|
30
|
+
}
|
|
31
|
+
const t = frame.token
|
|
32
|
+
return {
|
|
33
|
+
v: 4,
|
|
34
|
+
kind: 'handover',
|
|
35
|
+
assetId: t.assetId,
|
|
36
|
+
amount: t.amount,
|
|
37
|
+
derivationPrefix: frame.derivationPrefix,
|
|
38
|
+
derivationSuffix: frame.derivationSuffix,
|
|
39
|
+
senderIdentityKey: frame.senderIdentityKey,
|
|
40
|
+
senderMode: t.senderMode,
|
|
41
|
+
transaction: Utils.toHex(Array.from(frame.transaction)),
|
|
42
|
+
outputIndex: frame.outputIndex,
|
|
43
|
+
...(t.admission !== undefined ? { admission: t.admission } : {}),
|
|
44
|
+
admissions: t.admissions,
|
|
45
|
+
linkage: t.linkage,
|
|
46
|
+
...(frame.note !== undefined && frame.note !== '' ? { note: frame.note } : {})
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The frame's token block for a signed hand-over: the evidence members of its v4 body. */
|
|
51
|
+
export function tokenPaymentOfHandover(h: Pick<HandoverResult, 'body'>): TokenPayment {
|
|
52
|
+
const b = h.body
|
|
53
|
+
return {
|
|
54
|
+
assetId: b.assetId,
|
|
55
|
+
amount: b.amount,
|
|
56
|
+
senderMode: b.senderMode,
|
|
57
|
+
...(b.admission !== undefined ? { admission: b.admission } : {}),
|
|
58
|
+
admissions: b.admissions,
|
|
59
|
+
linkage: b.linkage,
|
|
60
|
+
certificates: []
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** `(ERR_X)` or `(ERR_X, retryable)`, the lib/overlay message tag. */
|
|
65
|
+
const CODE_TAG = /\((ERR_[A-Z0-9_]+)(, retryable)?\)/
|
|
66
|
+
|
|
67
|
+
function nameOf(e: unknown): string {
|
|
68
|
+
const n = (e as { name?: unknown } | null)?.name
|
|
69
|
+
return typeof n === 'string' ? n : ''
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function messageOf(e: unknown): string {
|
|
73
|
+
const m = (e as { message?: unknown } | null)?.message
|
|
74
|
+
return typeof m === 'string' ? m : String(e)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Module refusals of the asset itself (its `req` names a profile this wallet
|
|
79
|
+
* does not support, or no overlay is configured for its issuer key): final for
|
|
80
|
+
* this wallet's configuration, whatever the lib's generic classifier says.
|
|
81
|
+
*/
|
|
82
|
+
const FINAL_MODULE_ERRORS = ['UnsupportedProfileError', 'ProfileParamsError'] as const
|
|
83
|
+
|
|
84
|
+
const isNamed = (e: unknown, name: string): boolean => nameOf(e) === name || messageOf(e).includes(`[${name}] `)
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Whether a failed receipt is worth retrying, by the lib's own receive
|
|
88
|
+
* classifier (`classifyReceiveError`): `retry` (a transport fault, a
|
|
89
|
+
* retryable verdict, `ERR_NOT_COVERED`, `ERR_BODY_UNREADABLE`, anything
|
|
90
|
+
* unrecognised) is retriable; `ack` (a malformed or contradicting body, a
|
|
91
|
+
* refused hop, a final overlay verdict, `ProfileDataError`) and `declined`
|
|
92
|
+
* (the user's own "no") are final, and so are the module's refusals of the
|
|
93
|
+
* asset itself (`FINAL_MODULE_ERRORS`). An unanswerable "is it final?" stays
|
|
94
|
+
* retriable: a payment is never journaled refused on a guess.
|
|
95
|
+
*/
|
|
96
|
+
export function isRetriableReceiptFailure(e: unknown): boolean {
|
|
97
|
+
if (FINAL_MODULE_ERRORS.some(n => isNamed(e, n))) return false
|
|
98
|
+
return classifyReceiveError(e).disposition === 'retry'
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** True for a transport-level overlay failure (no typed verdict): the attempt is not counted. */
|
|
102
|
+
export function isTransportReceiptFailure(e: unknown): boolean {
|
|
103
|
+
const code = (e as { code?: unknown } | null)?.code
|
|
104
|
+
if (code === 'ERR_UNAVAILABLE') return true
|
|
105
|
+
return CODE_TAG.exec(messageOf(e))?.[1] === 'ERR_UNAVAILABLE'
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* The refusal code journaled for a failed receipt: the lib/overlay `ERR_*`
|
|
110
|
+
* code when there is one, else the error class, else `ERR_RECEIPT`.
|
|
111
|
+
*/
|
|
112
|
+
export function receiptFailureCode(e: unknown): string {
|
|
113
|
+
const c = classifyReceiveError(e)
|
|
114
|
+
if (c.code !== undefined) return c.code
|
|
115
|
+
if (c.disposition === 'declined') return 'ColorConsentDeclinedError'
|
|
116
|
+
for (const n of FINAL_MODULE_ERRORS) if (isNamed(e, n)) return n
|
|
117
|
+
const name = nameOf(e)
|
|
118
|
+
if (name !== '' && name !== 'Error') return name
|
|
119
|
+
const bracket = /^\[([A-Za-z]+Error)\] /.exec(messageOf(e))?.[1]
|
|
120
|
+
return bracket ?? 'ERR_RECEIPT'
|
|
121
|
+
}
|