@bsv/expo-wallet-toolbox 0.20.0 → 0.22.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 +147 -0
- package/README.md +78 -13
- package/core/contacts/contactActivity.ts +48 -28
- package/core/contacts/contactsStore.ts +2 -2
- package/core/context/WalletContext.tsx +166 -219
- 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/directpay/DirectPayManager.ts +148 -29
- package/core/directpay/DirectPayProvider.tsx +11 -2
- package/core/directpay/payFlow.ts +10 -1
- package/core/directpay/settings.ts +56 -9
- package/core/directpay/types.ts +11 -2
- package/core/directpay/webrtpay.ts +4 -0
- package/core/i18n/translations.tsx +185 -84
- package/core/index.ts +55 -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/direct.ts +6 -2
- 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/vault/guard.ts +5 -4
- package/core/storage/StorageExpoSQLite.ts +93 -229
- package/core/storage/methods/processOfflineActions.ts +86 -136
- package/core/storage/schema/createTables.ts +9 -184
- package/package.json +6 -5
- package/ui/components/pay/AssetPicker.tsx +2 -2
- package/ui/components/pay/HandleReceive.tsx +10 -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 +94 -160
- package/ui/components/ui/colorPrompt.ts +236 -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/hooks/useMandala.ts +6 -6
- package/ui/hooks/useSpendableBalance.ts +3 -1
- package/ui/importDatabases.ts +1 -1
- package/ui/screens/PayScreen.tsx +14 -20
- package/ui/screens/SettingsScreen.tsx +3 -1
- package/ui/screens/WalletCheckScreen.tsx +7 -2
- 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
|
@@ -1,178 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Resend for a TOKEN transfer, whatever rail it first went out on.
|
|
3
|
-
*
|
|
4
|
-
* "The counterparty says they never got it" has one honest answer for a
|
|
5
|
-
* stablecoin: deliver the transfer notification again, over the message box,
|
|
6
|
-
* because that is the one rail that confirms delivery and the one inbox every
|
|
7
|
-
* recipient wallet drains. A nearby hand-over whose code was never scanned, a
|
|
8
|
-
* handle-rail transfer whose notify failed and fell out of the lib's journal —
|
|
9
|
-
* both end here with the SAME body `transferTokens` sends at transfer time, so
|
|
10
|
-
* the recipient's `receiveTokens` needs nothing new to credit it (it acks by
|
|
11
|
-
* messageId and treats an already-internalized output as a no-op).
|
|
12
|
-
*
|
|
13
|
-
* Everything the body needs is already on the payer's device, on both rails:
|
|
14
|
-
*
|
|
15
|
-
* · recipient, the blinded sender A′ and the keyID — the lib's blinding
|
|
16
|
-
* journal, written by `transferTokens` (`blindingPut`) and by the nearby
|
|
17
|
-
* build (`blindingReserve` + `commitBlinding`). Fallback: the payee output's
|
|
18
|
-
* own `recipientCustomInstructions` marker, which both rails write too;
|
|
19
|
-
* · which output is the payee's — that same marker, because the handle rail
|
|
20
|
-
* randomises output order;
|
|
21
|
-
* · the transaction — the existing network-first / local-second resend lookup;
|
|
22
|
-
* · assetId and amount — DECODED from the output's script, never a stored claim;
|
|
23
|
-
* · a cached σ_I when this device holds one, so the recipient can credit
|
|
24
|
-
* without waiting on its own overlay round-trip (§4.5). Optional by design.
|
|
25
|
-
*
|
|
26
|
-
* Nothing here contacts the overlay, decides settlement, or touches the
|
|
27
|
-
* transaction's own status: a resend is a delivery, not a payment.
|
|
28
|
-
*/
|
|
29
|
-
import { Transaction } from '@bsv/sdk'
|
|
30
|
-
import { MandalaToken } from './token'
|
|
31
|
-
import { isDuplicateMessageError } from '../peerpay/control'
|
|
32
|
-
|
|
33
|
-
/** The recipient-side inbox `receiveTokens` drains (`@bsv/mandala` `MESSAGEBOX`). */
|
|
34
|
-
export const MANDALA_MESSAGE_BOX = 'mandala-payments'
|
|
35
|
-
|
|
36
|
-
/** The FT derivation protocol, as the lib's `FT_PROTOCOL`. */
|
|
37
|
-
const FT_PROTOCOL: [number, string] = [2, 'p mandala token']
|
|
38
|
-
|
|
39
|
-
export type TokenResendFailure = 'no_record' | 'no_transaction'
|
|
40
|
-
export type TokenResendOutcome = { ok: true } | { ok: false; reason: TokenResendFailure }
|
|
41
|
-
|
|
42
|
-
/** What the payer remembers about who the payment was for and how it was locked. */
|
|
43
|
-
export interface TokenResendRecord {
|
|
44
|
-
recipient: string
|
|
45
|
-
/** A′ — what went on the wire as the sender; the recipient derives against it. */
|
|
46
|
-
senderBlinded: string
|
|
47
|
-
keyID: string
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export interface TokenResendAction {
|
|
51
|
-
labels?: string[]
|
|
52
|
-
outputs?: { outputIndex?: number; customInstructions?: string }[]
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
export interface PendingTokenNotification {
|
|
56
|
-
txid: string
|
|
57
|
-
recipient: string
|
|
58
|
-
messageBox: string
|
|
59
|
-
body: object
|
|
60
|
-
at: number
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
export interface TokenResendDeps {
|
|
64
|
-
/** The lib's blinding journal, by txid. */
|
|
65
|
-
blindingRecord: (txid: string) => Promise<TokenResendRecord | undefined>
|
|
66
|
-
/** The `mandala`-labelled wallet action for the txid, with its outputs. */
|
|
67
|
-
listAction: (txid: string) => Promise<TokenResendAction | undefined>
|
|
68
|
-
/** AtomicBEEF for the txid — `makeResendBeef` in production. */
|
|
69
|
-
refetch: (txid: string) => Promise<number[] | undefined>
|
|
70
|
-
/** This device's cached σ_I for the txid, if any. */
|
|
71
|
-
admission: (
|
|
72
|
-
txid: string
|
|
73
|
-
) => Promise<{ outputsToAdmit: number[]; signatureHex: string; signerKey: string } | undefined>
|
|
74
|
-
/** The lib's notification journal: `notifyPut` / `notifyRemove`. */
|
|
75
|
-
journal: { put(entry: PendingTokenNotification): Promise<void>; remove(txid: string): Promise<void> }
|
|
76
|
-
sendMessage: (args: { recipient: string; messageBox: string; body: object }) => Promise<unknown>
|
|
77
|
-
/** Unwraps metadata the permissions manager encrypted on its way to storage. */
|
|
78
|
-
decryptMetadata?: (value: string) => Promise<string>
|
|
79
|
-
now?: () => number
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
interface Marker extends Partial<TokenResendRecord> {
|
|
83
|
-
outputIndex: number
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/** The payee output's `recipientCustomInstructions`, and which output carried it. */
|
|
87
|
-
async function findMarker(
|
|
88
|
-
action: TokenResendAction | undefined,
|
|
89
|
-
decrypt?: (v: string) => Promise<string>
|
|
90
|
-
): Promise<Marker | undefined> {
|
|
91
|
-
for (const output of action?.outputs ?? []) {
|
|
92
|
-
const raw = output.customInstructions
|
|
93
|
-
if (typeof raw !== 'string' || raw === '') continue
|
|
94
|
-
let text = raw
|
|
95
|
-
if (decrypt) {
|
|
96
|
-
try {
|
|
97
|
-
text = await decrypt(raw)
|
|
98
|
-
} catch {
|
|
99
|
-
// Not encrypted, or not ours to read — try it as it is.
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
let parsed: Record<string, unknown>
|
|
103
|
-
try {
|
|
104
|
-
parsed = JSON.parse(text) as Record<string, unknown>
|
|
105
|
-
} catch {
|
|
106
|
-
continue
|
|
107
|
-
}
|
|
108
|
-
if (typeof parsed.senderBlinded !== 'string') continue
|
|
109
|
-
return {
|
|
110
|
-
outputIndex: typeof output.outputIndex === 'number' ? output.outputIndex : 0,
|
|
111
|
-
recipient: typeof parsed.recipient === 'string' ? parsed.recipient : undefined,
|
|
112
|
-
senderBlinded: parsed.senderBlinded,
|
|
113
|
-
keyID: typeof parsed.keyID === 'string' ? parsed.keyID : undefined
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
return undefined
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
export async function resendTokenTransfer(txid: string, deps: TokenResendDeps): Promise<TokenResendOutcome> {
|
|
120
|
-
const [journaled, action] = await Promise.all([deps.blindingRecord(txid), deps.listAction(txid)])
|
|
121
|
-
const marker = await findMarker(action, deps.decryptMetadata)
|
|
122
|
-
|
|
123
|
-
const recipient = journaled?.recipient ?? marker?.recipient
|
|
124
|
-
const senderBlinded = journaled?.senderBlinded ?? marker?.senderBlinded
|
|
125
|
-
const keyID = journaled?.keyID ?? marker?.keyID
|
|
126
|
-
if (!recipient || !senderBlinded || !keyID) return { ok: false, reason: 'no_record' }
|
|
127
|
-
// The nearby build never randomises outputs, so a record with no marker
|
|
128
|
-
// (an older action whose instructions did not survive) still names index 0.
|
|
129
|
-
const outputIndex = marker?.outputIndex ?? 0
|
|
130
|
-
|
|
131
|
-
const transaction = await deps.refetch(txid)
|
|
132
|
-
if (!transaction) return { ok: false, reason: 'no_transaction' }
|
|
133
|
-
let assetId: string
|
|
134
|
-
let amount: number
|
|
135
|
-
try {
|
|
136
|
-
const script = Transaction.fromAtomicBEEF(transaction).outputs[outputIndex]?.lockingScript
|
|
137
|
-
if (!script) return { ok: false, reason: 'no_transaction' }
|
|
138
|
-
;({ assetId, amount } = MandalaToken.decode(script))
|
|
139
|
-
} catch {
|
|
140
|
-
return { ok: false, reason: 'no_transaction' }
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
const cached = await deps.admission(txid)
|
|
144
|
-
const body = {
|
|
145
|
-
assetId,
|
|
146
|
-
amount: String(amount),
|
|
147
|
-
transaction,
|
|
148
|
-
keyID,
|
|
149
|
-
outputIndex,
|
|
150
|
-
protocolID: FT_PROTOCOL,
|
|
151
|
-
sender: senderBlinded,
|
|
152
|
-
senderMode: 'blinded' as const,
|
|
153
|
-
...(cached
|
|
154
|
-
? {
|
|
155
|
-
admission: {
|
|
156
|
-
txid,
|
|
157
|
-
outputsToAdmit: cached.outputsToAdmit,
|
|
158
|
-
signature: cached.signatureHex,
|
|
159
|
-
signerKey: cached.signerKey
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
: {})
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
// Journal FIRST, exactly as `transferTokens` does: a send that fails after
|
|
166
|
-
// this is retried by `reconcileNotifications` on the next drain tick, and a
|
|
167
|
-
// duplicate delivery is safe on the receiving side.
|
|
168
|
-
await deps.journal.put({ txid, recipient, messageBox: MANDALA_MESSAGE_BOX, body, at: (deps.now ?? Date.now)() })
|
|
169
|
-
try {
|
|
170
|
-
await deps.sendMessage({ recipient, messageBox: MANDALA_MESSAGE_BOX, body })
|
|
171
|
-
} catch (e) {
|
|
172
|
-
// The box already holds this exact message: the recipient has what the
|
|
173
|
-
// resend was trying to give them, which is the wanted end state.
|
|
174
|
-
if (!isDuplicateMessageError(e)) throw e
|
|
175
|
-
}
|
|
176
|
-
await deps.journal.remove(txid)
|
|
177
|
-
return { ok: true }
|
|
178
|
-
}
|
|
@@ -1,434 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* `SettlementStore` over the toolbox's own SQLite connection.
|
|
3
|
-
*
|
|
4
|
-
* Deliberately logic-free, in the same spirit as `storage/methods/offlineActions.ts`:
|
|
5
|
-
* every decision about WHEN a row may move lives in `mandala/drain.ts`, which is
|
|
6
|
-
* unit-tested against a real in-memory SQLite. What is here is statements.
|
|
7
|
-
*
|
|
8
|
-
* Two rules the SQL itself enforces, because a convention would not survive a
|
|
9
|
-
* crash or a second drain tick:
|
|
10
|
-
*
|
|
11
|
-
* 1. **`state` belongs to `advanceSettlement` alone.** `upsertSettlement` is
|
|
12
|
-
* the re-derivation path (FIX G — the drain re-runs it on every pass from
|
|
13
|
-
* the durable frame bytes), so if it wrote `state` it would drag an
|
|
14
|
-
* `admitted` row back to `held` every tick and re-submit forever. It
|
|
15
|
-
* therefore sets `state` only on the INSERT, and on conflict updates the
|
|
16
|
-
* descriptive columns alone.
|
|
17
|
-
* 2. **`advanceSettlement` is one guarded UPDATE.** `... WHERE txid = ? AND
|
|
18
|
-
* state IN (...)` plus a changes-count check is a compare-and-swap: two
|
|
19
|
-
* interleaved drains cannot both believe they claimed the same row, and a
|
|
20
|
-
* row someone else already moved to a terminal state is never resurrected.
|
|
21
|
-
* There is no read-then-write anywhere in this file for that reason.
|
|
22
|
-
*
|
|
23
|
-
* Access pattern matches `StorageExpoSQLite`'s own use of `offline_actions`:
|
|
24
|
-
* the caller hands in `storage.sqliteDb` and this module only ever issues
|
|
25
|
-
* parameterised statements against it.
|
|
26
|
-
*/
|
|
27
|
-
import type {
|
|
28
|
-
SettlementStore,
|
|
29
|
-
TokenAdmissionEdge,
|
|
30
|
-
TokenAdmissionRow,
|
|
31
|
-
TokenLinkageRow,
|
|
32
|
-
TokenSettlementRole,
|
|
33
|
-
TokenSettlementRow,
|
|
34
|
-
TokenSettlementState
|
|
35
|
-
} from './types'
|
|
36
|
-
|
|
37
|
-
/** Everything these statements bind. BLOB columns are why `Uint8Array` is here. */
|
|
38
|
-
export type SettlementBindValue = string | number | null | Uint8Array
|
|
39
|
-
|
|
40
|
-
/**
|
|
41
|
-
* Structurally satisfied by expo-sqlite's `SQLiteDatabase` and by the
|
|
42
|
-
* `node:sqlite` adapter the tests use. `runAsync` is narrowed to its result's
|
|
43
|
-
* `changes` because `advanceSettlement`'s whole contract depends on it.
|
|
44
|
-
*/
|
|
45
|
-
export interface SettlementDb {
|
|
46
|
-
runAsync(sql: string, params: SettlementBindValue[]): Promise<{ changes: number }>
|
|
47
|
-
getAllAsync(sql: string, params: SettlementBindValue[]): Promise<unknown[]>
|
|
48
|
-
getFirstAsync(sql: string, params: SettlementBindValue[]): Promise<unknown>
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/** The store, plus the one batch question the storage guard needs to ask. */
|
|
52
|
-
export interface SqlSettlementStore extends SettlementStore {
|
|
53
|
-
/**
|
|
54
|
-
* Which of `txids` have a `token_settlements` row. One statement, because the
|
|
55
|
-
* caller (`attemptToPostReqsToNetwork`'s token guard) asks this on the hot
|
|
56
|
-
* path of every broadcast.
|
|
57
|
-
*/
|
|
58
|
-
settlementTxidsIn(txids: string[]): Promise<Set<string>>
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
interface SettlementDbRow {
|
|
62
|
-
txid: string
|
|
63
|
-
role: string
|
|
64
|
-
assetId: string
|
|
65
|
-
state: string
|
|
66
|
-
counterpartyKey: string | null
|
|
67
|
-
amountBaseUnits: number | null
|
|
68
|
-
overlayUrl: string
|
|
69
|
-
overlayIdentityKey: string
|
|
70
|
-
admissionOutputsJson: string | null
|
|
71
|
-
admissionSignatureHex: string | null
|
|
72
|
-
relevantVout: number | null
|
|
73
|
-
refusedCode: string | null
|
|
74
|
-
refusedPayloadHash: string | null
|
|
75
|
-
poisonedByTxid: string | null
|
|
76
|
-
reference: string | null
|
|
77
|
-
createdAt: string
|
|
78
|
-
updatedAt: string
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
/** A JSON array column that will not throw the caller's drain pass for one bad row. */
|
|
82
|
-
function readNumberArray(json: string | null): number[] | undefined {
|
|
83
|
-
if (!json) return undefined
|
|
84
|
-
try {
|
|
85
|
-
const parsed = JSON.parse(json) as unknown
|
|
86
|
-
if (!Array.isArray(parsed)) return undefined
|
|
87
|
-
return parsed.filter((n): n is number => typeof n === 'number')
|
|
88
|
-
} catch {
|
|
89
|
-
return undefined
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
function toSettlement(row: SettlementDbRow): TokenSettlementRow {
|
|
94
|
-
return {
|
|
95
|
-
txid: row.txid,
|
|
96
|
-
role: row.role as TokenSettlementRole,
|
|
97
|
-
assetId: row.assetId,
|
|
98
|
-
state: row.state as TokenSettlementState,
|
|
99
|
-
counterpartyKey: row.counterpartyKey ?? undefined,
|
|
100
|
-
amountBaseUnits: row.amountBaseUnits ?? undefined,
|
|
101
|
-
overlayUrl: row.overlayUrl,
|
|
102
|
-
overlayIdentityKey: row.overlayIdentityKey,
|
|
103
|
-
admissionOutputs: readNumberArray(row.admissionOutputsJson),
|
|
104
|
-
admissionSignatureHex: row.admissionSignatureHex ?? undefined,
|
|
105
|
-
relevantVout: row.relevantVout ?? undefined,
|
|
106
|
-
refusedCode: row.refusedCode ?? undefined,
|
|
107
|
-
refusedPayloadHash: row.refusedPayloadHash ?? undefined,
|
|
108
|
-
poisonedByTxid: row.poisonedByTxid ?? undefined,
|
|
109
|
-
reference: row.reference ?? undefined,
|
|
110
|
-
createdAt: row.createdAt,
|
|
111
|
-
updatedAt: row.updatedAt
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
/**
|
|
116
|
-
* `payloadBytes` comes back from expo-sqlite as a `Uint8Array` and from
|
|
117
|
-
* `node:sqlite` the same way, but a driver that hands back an ArrayBuffer or a
|
|
118
|
-
* number[] must not silently become an empty payload — these bytes are the only
|
|
119
|
-
* thing that lets a downstream device submit this txid at all.
|
|
120
|
-
*
|
|
121
|
-
* A TEXT value is the 2026-09-16 incident's residue: `putLinkage` was handed a
|
|
122
|
-
* JSON-rehydrated payload (an index-keyed object, not a `Uint8Array`), and
|
|
123
|
-
* expo-sqlite's Android binding stringified it as a java `Map` — `{0=1.0,
|
|
124
|
-
* 2=250.0, 1=2.0}`, hash-ordered, Double-valued. Rows like that are on devices
|
|
125
|
-
* and `INSERT OR IGNORE` would have kept them forever, so they are read back
|
|
126
|
-
* into the bytes they always meant. Anything else that is not bytes still
|
|
127
|
-
* throws, never becomes an empty payload.
|
|
128
|
-
*/
|
|
129
|
-
function toBytes(value: unknown): Uint8Array {
|
|
130
|
-
if (value instanceof Uint8Array) return value
|
|
131
|
-
if (value instanceof ArrayBuffer) return new Uint8Array(value)
|
|
132
|
-
if (Array.isArray(value)) return new Uint8Array(value as number[])
|
|
133
|
-
if (typeof value === 'string') {
|
|
134
|
-
const recovered = bytesFromJavaMapString(value)
|
|
135
|
-
if (recovered) return recovered
|
|
136
|
-
}
|
|
137
|
-
throw new Error('token_linkage_payloads.payloadBytes is not readable as bytes')
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
function bytesFromJavaMapString(text: string): Uint8Array | undefined {
|
|
141
|
-
const braced = /^\{(.*)\}$/s.exec(text.trim())
|
|
142
|
-
if (!braced) return undefined
|
|
143
|
-
const body = braced[1].trim()
|
|
144
|
-
if (body === '') return new Uint8Array(0)
|
|
145
|
-
const pairs = body.split(',')
|
|
146
|
-
const out = new Uint8Array(pairs.length)
|
|
147
|
-
const seen = new Set<number>()
|
|
148
|
-
for (const pair of pairs) {
|
|
149
|
-
const kv = /^\s*(\d+)=(\d+)(?:\.0+)?\s*$/.exec(pair)
|
|
150
|
-
if (!kv) return undefined
|
|
151
|
-
const index = Number(kv[1])
|
|
152
|
-
const byte = Number(kv[2])
|
|
153
|
-
if (index >= out.length || seen.has(index) || byte > 255) return undefined
|
|
154
|
-
seen.add(index)
|
|
155
|
-
out[index] = byte
|
|
156
|
-
}
|
|
157
|
-
return out
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
/** Columns `advanceSettlement` and `upsertSettlement` may write, and their SQL names. */
|
|
161
|
-
const PATCHABLE: { key: keyof TokenSettlementRow; column: string }[] = [
|
|
162
|
-
{ key: 'counterpartyKey', column: 'counterpartyKey' },
|
|
163
|
-
{ key: 'amountBaseUnits', column: 'amountBaseUnits' },
|
|
164
|
-
{ key: 'admissionOutputs', column: 'admissionOutputsJson' },
|
|
165
|
-
{ key: 'admissionSignatureHex', column: 'admissionSignatureHex' },
|
|
166
|
-
{ key: 'refusedCode', column: 'refusedCode' },
|
|
167
|
-
{ key: 'refusedPayloadHash', column: 'refusedPayloadHash' },
|
|
168
|
-
{ key: 'poisonedByTxid', column: 'poisonedByTxid' },
|
|
169
|
-
{ key: 'reference', column: 'reference' }
|
|
170
|
-
]
|
|
171
|
-
|
|
172
|
-
function patchValue(key: keyof TokenSettlementRow, value: unknown): SettlementBindValue {
|
|
173
|
-
if (value === undefined || value === null) return null
|
|
174
|
-
if (key === 'admissionOutputs') return JSON.stringify(value)
|
|
175
|
-
return value as SettlementBindValue
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
export function createSettlementStore(db: SettlementDb): SqlSettlementStore {
|
|
179
|
-
return {
|
|
180
|
-
async getSettlement(txid: string): Promise<TokenSettlementRow | undefined> {
|
|
181
|
-
const row = (await db.getFirstAsync('SELECT * FROM token_settlements WHERE txid = ?', [
|
|
182
|
-
txid
|
|
183
|
-
])) as SettlementDbRow | null
|
|
184
|
-
return row ? toSettlement(row) : undefined
|
|
185
|
-
},
|
|
186
|
-
|
|
187
|
-
/**
|
|
188
|
-
* One indexed lookup (`idx_token_settlements_reference`), because this is
|
|
189
|
-
* asked before EVERY `abortAction` the wallet makes — the overwhelming
|
|
190
|
-
* majority of which are plain BSV actions with no row here at all. An empty
|
|
191
|
-
* or absent reference can never match a row and is refused a query.
|
|
192
|
-
*/
|
|
193
|
-
async getSettlementByReference(reference: string): Promise<TokenSettlementRow | undefined> {
|
|
194
|
-
if (!reference) return undefined
|
|
195
|
-
const row = (await db.getFirstAsync('SELECT * FROM token_settlements WHERE reference = ?', [
|
|
196
|
-
reference
|
|
197
|
-
])) as SettlementDbRow | null
|
|
198
|
-
return row ? toSettlement(row) : undefined
|
|
199
|
-
},
|
|
200
|
-
|
|
201
|
-
/**
|
|
202
|
-
* XR-033: the coarse fallback `getSettlementByReference` cannot offer for
|
|
203
|
-
* a row with no reference at all. `state` names the same set
|
|
204
|
-
* `abortGuard.ts`'s `ABORT_BLOCKED_SETTLEMENT_STATES` does — duplicated
|
|
205
|
-
* rather than imported, in keeping with this file's own rule that it is
|
|
206
|
-
* statements only, with no cross-module logic.
|
|
207
|
-
*/
|
|
208
|
-
async hasUnresolvedLegacyBlockedRows(): Promise<boolean> {
|
|
209
|
-
const row = (await db.getFirstAsync(
|
|
210
|
-
`SELECT 1 FROM token_settlements
|
|
211
|
-
WHERE reference IS NULL
|
|
212
|
-
AND state IN ('held','handed_over','submitting','admitted','broadcast')
|
|
213
|
-
LIMIT 1`,
|
|
214
|
-
[]
|
|
215
|
-
)) as unknown
|
|
216
|
-
return row != null
|
|
217
|
-
},
|
|
218
|
-
|
|
219
|
-
async listSettlements(filter = {}): Promise<TokenSettlementRow[]> {
|
|
220
|
-
const where: string[] = []
|
|
221
|
-
const params: SettlementBindValue[] = []
|
|
222
|
-
if (filter.state && filter.state.length > 0) {
|
|
223
|
-
where.push(`state IN (${filter.state.map(() => '?').join(',')})`)
|
|
224
|
-
params.push(...filter.state)
|
|
225
|
-
}
|
|
226
|
-
if (filter.role !== undefined) {
|
|
227
|
-
where.push('role = ?')
|
|
228
|
-
params.push(filter.role)
|
|
229
|
-
}
|
|
230
|
-
const sql =
|
|
231
|
-
'SELECT * FROM token_settlements' +
|
|
232
|
-
(where.length ? ` WHERE ${where.join(' AND ')}` : '') +
|
|
233
|
-
' ORDER BY createdAt ASC, txid ASC'
|
|
234
|
-
return ((await db.getAllAsync(sql, params)) as SettlementDbRow[]).map(toSettlement)
|
|
235
|
-
},
|
|
236
|
-
|
|
237
|
-
/**
|
|
238
|
-
* Insert the row, or refresh only what a re-derivation can legitimately
|
|
239
|
-
* know. `state`, `role` and the two terminal-verdict columns are never
|
|
240
|
-
* touched on conflict — see rule 1 at the top of this file.
|
|
241
|
-
*/
|
|
242
|
-
async upsertSettlement(row): Promise<void> {
|
|
243
|
-
const now = new Date().toISOString()
|
|
244
|
-
const createdAt = row.createdAt ?? now
|
|
245
|
-
await db.runAsync(
|
|
246
|
-
`INSERT INTO token_settlements
|
|
247
|
-
(txid, role, assetId, state, counterpartyKey, amountBaseUnits, overlayUrl, overlayIdentityKey,
|
|
248
|
-
admissionOutputsJson, admissionSignatureHex, relevantVout, refusedCode, refusedPayloadHash, poisonedByTxid,
|
|
249
|
-
reference, createdAt, updatedAt)
|
|
250
|
-
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
|
251
|
-
ON CONFLICT(txid) DO UPDATE SET
|
|
252
|
-
assetId = excluded.assetId,
|
|
253
|
-
counterpartyKey = COALESCE(excluded.counterpartyKey, token_settlements.counterpartyKey),
|
|
254
|
-
amountBaseUnits = COALESCE(excluded.amountBaseUnits, token_settlements.amountBaseUnits),
|
|
255
|
-
overlayUrl = excluded.overlayUrl,
|
|
256
|
-
overlayIdentityKey = excluded.overlayIdentityKey,
|
|
257
|
-
admissionOutputsJson = COALESCE(excluded.admissionOutputsJson, token_settlements.admissionOutputsJson),
|
|
258
|
-
admissionSignatureHex = COALESCE(excluded.admissionSignatureHex, token_settlements.admissionSignatureHex),
|
|
259
|
-
relevantVout = COALESCE(excluded.relevantVout, token_settlements.relevantVout),
|
|
260
|
-
reference = COALESCE(excluded.reference, token_settlements.reference),
|
|
261
|
-
updatedAt = excluded.updatedAt`,
|
|
262
|
-
[
|
|
263
|
-
row.txid,
|
|
264
|
-
row.role,
|
|
265
|
-
row.assetId,
|
|
266
|
-
row.state,
|
|
267
|
-
row.counterpartyKey ?? null,
|
|
268
|
-
row.amountBaseUnits ?? null,
|
|
269
|
-
row.overlayUrl,
|
|
270
|
-
row.overlayIdentityKey,
|
|
271
|
-
row.admissionOutputs ? JSON.stringify(row.admissionOutputs) : null,
|
|
272
|
-
row.admissionSignatureHex ?? null,
|
|
273
|
-
row.relevantVout ?? null,
|
|
274
|
-
row.refusedCode ?? null,
|
|
275
|
-
row.refusedPayloadHash ?? null,
|
|
276
|
-
row.poisonedByTxid ?? null,
|
|
277
|
-
row.reference ?? null,
|
|
278
|
-
createdAt,
|
|
279
|
-
now
|
|
280
|
-
]
|
|
281
|
-
)
|
|
282
|
-
},
|
|
283
|
-
|
|
284
|
-
/**
|
|
285
|
-
* One statement, compare-and-swap on `state`. False means the row was not
|
|
286
|
-
* in one of `from` — either someone else moved it, or it does not exist —
|
|
287
|
-
* and NOTHING was written, so a caller may treat false as "not mine to
|
|
288
|
-
* advance" without a compensating read.
|
|
289
|
-
*/
|
|
290
|
-
async advanceSettlement(
|
|
291
|
-
txid: string,
|
|
292
|
-
from: TokenSettlementState[],
|
|
293
|
-
to: TokenSettlementState,
|
|
294
|
-
patch: Partial<TokenSettlementRow> = {}
|
|
295
|
-
): Promise<boolean> {
|
|
296
|
-
const sets = ['state = ?', 'updatedAt = ?']
|
|
297
|
-
const params: SettlementBindValue[] = [to, new Date().toISOString()]
|
|
298
|
-
for (const { key, column } of PATCHABLE) {
|
|
299
|
-
if (patch[key] === undefined) continue
|
|
300
|
-
sets.push(`${column} = ?`)
|
|
301
|
-
params.push(patchValue(key, patch[key]))
|
|
302
|
-
}
|
|
303
|
-
params.push(txid, ...from)
|
|
304
|
-
const placeholders = from.length > 0 ? from.map(() => '?').join(',') : `''`
|
|
305
|
-
const result = await db.runAsync(
|
|
306
|
-
`UPDATE token_settlements SET ${sets.join(', ')} WHERE txid = ? AND state IN (${placeholders})`,
|
|
307
|
-
params
|
|
308
|
-
)
|
|
309
|
-
return (result?.changes ?? 0) > 0
|
|
310
|
-
},
|
|
311
|
-
|
|
312
|
-
async settlementTxidsIn(txids: string[]): Promise<Set<string>> {
|
|
313
|
-
if (txids.length === 0) return new Set()
|
|
314
|
-
const rows = (await db.getAllAsync(
|
|
315
|
-
`SELECT txid FROM token_settlements WHERE txid IN (${txids.map(() => '?').join(',')})`,
|
|
316
|
-
txids
|
|
317
|
-
)) as { txid: string }[]
|
|
318
|
-
return new Set(rows.map(r => r.txid))
|
|
319
|
-
},
|
|
320
|
-
|
|
321
|
-
async getAdmission(txid: string): Promise<TokenAdmissionRow | undefined> {
|
|
322
|
-
const row = (await db.getFirstAsync('SELECT * FROM token_admissions WHERE txid = ?', [txid])) as {
|
|
323
|
-
txid: string
|
|
324
|
-
outputsToAdmitJson: string
|
|
325
|
-
signatureHex: string
|
|
326
|
-
signerKey: string
|
|
327
|
-
source: TokenAdmissionRow['source']
|
|
328
|
-
obtainedAt: string
|
|
329
|
-
} | null
|
|
330
|
-
if (!row) return undefined
|
|
331
|
-
return {
|
|
332
|
-
txid: row.txid,
|
|
333
|
-
outputsToAdmit: readNumberArray(row.outputsToAdmitJson) ?? [],
|
|
334
|
-
signatureHex: row.signatureHex,
|
|
335
|
-
signerKey: row.signerKey,
|
|
336
|
-
source: row.source,
|
|
337
|
-
obtainedAt: row.obtainedAt
|
|
338
|
-
}
|
|
339
|
-
},
|
|
340
|
-
|
|
341
|
-
/**
|
|
342
|
-
* Idempotent, and asymmetric on purpose: first-hand evidence (this device
|
|
343
|
-
* submitted, or fetched `GET /admin/admission/:txid` itself) replaces a
|
|
344
|
-
* cached bundle entry, but a counterparty-supplied bundle NEVER overwrites
|
|
345
|
-
* anything already on record. For a `bundle`/`minted` source against an
|
|
346
|
-
* existing row the `WHERE` makes this exactly an `INSERT OR IGNORE`, which
|
|
347
|
-
* is what the FIX G re-derivation pass needs.
|
|
348
|
-
*/
|
|
349
|
-
async putAdmission(row: TokenAdmissionRow): Promise<void> {
|
|
350
|
-
await db.runAsync(
|
|
351
|
-
`INSERT INTO token_admissions (txid, outputsToAdmitJson, signatureHex, signerKey, source, obtainedAt)
|
|
352
|
-
VALUES (?,?,?,?,?,?)
|
|
353
|
-
ON CONFLICT(txid) DO UPDATE SET
|
|
354
|
-
outputsToAdmitJson = excluded.outputsToAdmitJson,
|
|
355
|
-
signatureHex = excluded.signatureHex,
|
|
356
|
-
signerKey = excluded.signerKey,
|
|
357
|
-
source = excluded.source,
|
|
358
|
-
obtainedAt = excluded.obtainedAt
|
|
359
|
-
WHERE excluded.source IN ('submitted','fetched')`,
|
|
360
|
-
[row.txid, JSON.stringify(row.outputsToAdmit), row.signatureHex, row.signerKey, row.source, row.obtainedAt]
|
|
361
|
-
)
|
|
362
|
-
},
|
|
363
|
-
|
|
364
|
-
async putEdges(edges: TokenAdmissionEdge[]): Promise<void> {
|
|
365
|
-
for (const e of edges) {
|
|
366
|
-
await db.runAsync(
|
|
367
|
-
'INSERT OR IGNORE INTO token_admission_edges (childTxid, parentTxid, parentVout) VALUES (?,?,?)',
|
|
368
|
-
[e.childTxid, e.parentTxid, e.parentVout]
|
|
369
|
-
)
|
|
370
|
-
}
|
|
371
|
-
},
|
|
372
|
-
|
|
373
|
-
async parentsOf(childTxid: string): Promise<TokenAdmissionEdge[]> {
|
|
374
|
-
const rows = (await db.getAllAsync(
|
|
375
|
-
`SELECT childTxid, parentTxid, parentVout FROM token_admission_edges
|
|
376
|
-
WHERE childTxid = ? ORDER BY parentTxid ASC, parentVout ASC`,
|
|
377
|
-
[childTxid]
|
|
378
|
-
)) as TokenAdmissionEdge[]
|
|
379
|
-
return rows.map(r => ({ childTxid: r.childTxid, parentTxid: r.parentTxid, parentVout: r.parentVout }))
|
|
380
|
-
},
|
|
381
|
-
|
|
382
|
-
async getLinkage(txid: string): Promise<TokenLinkageRow | undefined> {
|
|
383
|
-
const row = (await db.getFirstAsync('SELECT * FROM token_linkage_payloads WHERE txid = ?', [txid])) as {
|
|
384
|
-
txid: string
|
|
385
|
-
payloadBytes: unknown
|
|
386
|
-
overlayUrl: string
|
|
387
|
-
overlayIdentityKey: string
|
|
388
|
-
source: TokenLinkageRow['source']
|
|
389
|
-
createdAt: string
|
|
390
|
-
} | null
|
|
391
|
-
if (!row) return undefined
|
|
392
|
-
return {
|
|
393
|
-
txid: row.txid,
|
|
394
|
-
payloadBytes: toBytes(row.payloadBytes),
|
|
395
|
-
overlayUrl: row.overlayUrl,
|
|
396
|
-
overlayIdentityKey: row.overlayIdentityKey,
|
|
397
|
-
source: row.source,
|
|
398
|
-
createdAt: row.createdAt
|
|
399
|
-
}
|
|
400
|
-
},
|
|
401
|
-
|
|
402
|
-
/**
|
|
403
|
-
* Insert-or-ignore in effect: the payload for a txid is whatever its issuer
|
|
404
|
-
* minted, forwarded verbatim. A second copy arriving on a later hop is by
|
|
405
|
-
* construction the same bytes, and a *different* copy is a counterparty
|
|
406
|
-
* trying to rewrite evidence this device already holds — so an existing
|
|
407
|
-
* BLOB is never touched. The one row a new copy may replace is one that
|
|
408
|
-
* holds no evidence at all — not a blob (see `toBytes`), or an empty one:
|
|
409
|
-
* a driver stringifying a value this store should have refused, which it
|
|
410
|
-
* now does, and an empty payload is likewise refused here because an
|
|
411
|
-
* overlay cannot verify nothing and every reader already treats it as
|
|
412
|
-
* "nothing held".
|
|
413
|
-
*/
|
|
414
|
-
async putLinkage(row: TokenLinkageRow): Promise<void> {
|
|
415
|
-
if (!(row.payloadBytes instanceof Uint8Array) || row.payloadBytes.length === 0) {
|
|
416
|
-
throw new Error('token_linkage_payloads.payloadBytes must be a non-empty Uint8Array')
|
|
417
|
-
}
|
|
418
|
-
await db.runAsync(
|
|
419
|
-
`INSERT INTO token_linkage_payloads
|
|
420
|
-
(txid, payloadBytes, overlayUrl, overlayIdentityKey, source, createdAt)
|
|
421
|
-
VALUES (?,?,?,?,?,?)
|
|
422
|
-
ON CONFLICT(txid) DO UPDATE SET
|
|
423
|
-
payloadBytes = excluded.payloadBytes,
|
|
424
|
-
overlayUrl = excluded.overlayUrl,
|
|
425
|
-
overlayIdentityKey = excluded.overlayIdentityKey,
|
|
426
|
-
source = excluded.source,
|
|
427
|
-
createdAt = excluded.createdAt
|
|
428
|
-
WHERE typeof(token_linkage_payloads.payloadBytes) <> 'blob'
|
|
429
|
-
OR length(token_linkage_payloads.payloadBytes) = 0`,
|
|
430
|
-
[row.txid, row.payloadBytes, row.overlayUrl, row.overlayIdentityKey, row.source, row.createdAt]
|
|
431
|
-
)
|
|
432
|
-
}
|
|
433
|
-
}
|
|
434
|
-
}
|
package/core/mandala/token.ts
DELETED
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* BRC-162 token-script boundary for the wallet.
|
|
3
|
-
*
|
|
4
|
-
* A drop-in for the old `MandalaToken` (8-chunk PushDrop) from `@bsv/templates`
|
|
5
|
-
* 1.x, over `Bsv21Binary` from `@bsv/templates` 2.x. `decode` yields
|
|
6
|
-
* `{ assetId, amount, pubKeyHash }` for a VALUE-role output only (deploy and
|
|
7
|
-
* authority outputs are not coins) and throws on anything else, exactly as the
|
|
8
|
-
* old decoder did, so every call site keeps its `try/catch` shape.
|
|
9
|
-
*/
|
|
10
|
-
import { LockingScript, type WalletCounterparty, type WalletInterface, type WalletProtocol } from '@bsv/sdk'
|
|
11
|
-
import { Bsv21Binary, tokenIdToString } from '@bsv/templates'
|
|
12
|
-
|
|
13
|
-
export class MandalaToken {
|
|
14
|
-
private readonly inner: Bsv21Binary
|
|
15
|
-
|
|
16
|
-
constructor(wallet?: WalletInterface, originator?: string) {
|
|
17
|
-
this.inner = new Bsv21Binary(wallet, originator)
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
static decode(script: LockingScript | string): { assetId: string; amount: number; pubKeyHash: number[] } {
|
|
21
|
-
const ls = LockingScript.fromHex(typeof script === 'string' ? script : script.toHex())
|
|
22
|
-
const d = Bsv21Binary.decode(ls)
|
|
23
|
-
if (d.role !== 'value' || d.tokenId == null) throw new Error(`not a BRC-162 value output (role ${d.role})`)
|
|
24
|
-
if (d.restPubKeyHash == null) throw new Error('BRC-162 output is not P2PKH-locked')
|
|
25
|
-
if (d.amount > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error('BRC-162 amount exceeds 2^53-1')
|
|
26
|
-
return { assetId: tokenIdToString(d.tokenId), amount: Number(d.amount), pubKeyHash: d.restPubKeyHash }
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
/** A value coin of `assetId` locked to `pubKeyHash`. */
|
|
30
|
-
lock(assetId: string, amount: number, pubKeyHash: readonly number[]): LockingScript {
|
|
31
|
-
return LockingScript.fromHex(this.inner.lock(assetId, BigInt(amount), pubKeyHash).toHex())
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
/** A value coin locked to hash160 of the wallet-derived (BRC-29 style) key. */
|
|
35
|
-
async lockBRC29(
|
|
36
|
-
assetId: string,
|
|
37
|
-
amount: number,
|
|
38
|
-
protocolID: WalletProtocol,
|
|
39
|
-
keyID: string,
|
|
40
|
-
counterparty: WalletCounterparty
|
|
41
|
-
): Promise<LockingScript> {
|
|
42
|
-
const s = await this.inner.lockBRC29(assetId, BigInt(amount), protocolID, keyID, counterparty)
|
|
43
|
-
return LockingScript.fromHex(s.toHex())
|
|
44
|
-
}
|
|
45
|
-
}
|