@bsv/expo-wallet-toolbox 0.21.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 +114 -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/i18n/translations.tsx +72 -0
- 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/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 +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 +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
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Token reads: inventory, exact balances and asset display metadata (plan 07
|
|
3
|
+
* Task 11).
|
|
4
|
+
*
|
|
5
|
+
* Everything here reads the color module's read-only `listOutputs` views
|
|
6
|
+
* (0207:606-697) through the published manager, as the admin originator:
|
|
7
|
+
*
|
|
8
|
+
* · `p color assets` — the inventory. Ordinary output records for real
|
|
9
|
+
* outpoints, each with exactly one wallet-authored state tag
|
|
10
|
+
* (`color_state_available|reserved|pending|restricted`) and, for an
|
|
11
|
+
* offline credit, the additional `color_offline` tag (0207:396-404).
|
|
12
|
+
* · `p color balance <assetTag>` — the exact available sum of one asset, as
|
|
13
|
+
* a canonical decimal string with no uint64 ceiling (BRC-112).
|
|
14
|
+
*
|
|
15
|
+
* Every read is exact or a throw. A partial page, a non-canonical amount or a
|
|
16
|
+
* record that does not decode is an error, never a smaller number: a balance
|
|
17
|
+
* screen that shows less than the truth invites a second payment, and one that
|
|
18
|
+
* shows offline value as settled hides settlement risk (W10, Review Focus 4).
|
|
19
|
+
*
|
|
20
|
+
* Display metadata (label, ticker, decimals) comes from the asset's deploy tx
|
|
21
|
+
* through lib `readDeploy` (W7). It is untrusted display data, but it is
|
|
22
|
+
* hash-bound: a deploy tx is only ever filed under the asset id derived from
|
|
23
|
+
* its own txid, so no counterparty can rename somebody else's asset.
|
|
24
|
+
*/
|
|
25
|
+
import { Transaction, type WalletInterface } from '@bsv/sdk'
|
|
26
|
+
import { COLOR_OFFLINE_TAG, type ColorOverlayProvider } from '@bsv/color-permission-module'
|
|
27
|
+
import { assetTag, decodeToken, readDeploy } from '@bsv/mandala'
|
|
28
|
+
import type { WalletKv } from './kvStore'
|
|
29
|
+
import type { TokenAssetInfo } from './runtime'
|
|
30
|
+
import { devLog } from '../logging'
|
|
31
|
+
|
|
32
|
+
/** The inventory selector (0207:612). A query, never a storage basket. */
|
|
33
|
+
export const ASSETS_VIEW = 'p color assets'
|
|
34
|
+
/** The available-state tag every spendable inventory record carries (0207:643-646). */
|
|
35
|
+
export const STATE_AVAILABLE_TAG = 'color_state_available'
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* One inventory page, and the hard stop on paging. A thousand is one round
|
|
39
|
+
* trip for any realistic wallet; the page ceiling stops a wallet that reports
|
|
40
|
+
* a count it never serves from spinning a balance read, and it throws rather
|
|
41
|
+
* than truncating (0207:663-664).
|
|
42
|
+
*/
|
|
43
|
+
const INVENTORY_PAGE = 1000
|
|
44
|
+
const INVENTORY_MAX_PAGES = 1000
|
|
45
|
+
|
|
46
|
+
const CANONICAL_UNITS = /^(0|[1-9][0-9]*)$/
|
|
47
|
+
const ASSET_ID = /^[0-9a-f]{64}_(0|[1-9][0-9]{0,9})$/
|
|
48
|
+
const OUTPOINT = /^([0-9a-f]{64})\.(0|[1-9][0-9]{0,9})$/
|
|
49
|
+
/** IC §4: a deploy's `dec` is 0..18. */
|
|
50
|
+
const MAX_DECIMALS = 18
|
|
51
|
+
|
|
52
|
+
export interface InventoryRecord {
|
|
53
|
+
/** `<txid>.<vout>` (IC §0). */
|
|
54
|
+
outpoint: string
|
|
55
|
+
/** `<64 lowercase hex>_<vout>`. */
|
|
56
|
+
assetId: string
|
|
57
|
+
role: 'value' | 'authority'
|
|
58
|
+
/** Exact token units of this output. Zero for an authority record. */
|
|
59
|
+
units: bigint
|
|
60
|
+
/** Wallet-authored tags as the module reported them (state tag, `color_offline`). */
|
|
61
|
+
tags: string[]
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function inventoryError(detail: string): Error {
|
|
65
|
+
return new Error(`p color assets inventory: ${detail}`)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** One inventory output record decoded from its own locking script, or a throw. */
|
|
69
|
+
function decodeRecord(output: unknown): InventoryRecord {
|
|
70
|
+
const o = output as { outpoint?: unknown; lockingScript?: unknown; tags?: unknown }
|
|
71
|
+
const m = typeof o?.outpoint === 'string' ? OUTPOINT.exec(o.outpoint) : null
|
|
72
|
+
if (m == null) throw inventoryError(`record with an invalid outpoint ${JSON.stringify(o?.outpoint)}`)
|
|
73
|
+
const outpoint = o.outpoint as string
|
|
74
|
+
if (typeof o.lockingScript !== 'string' || o.lockingScript === '') {
|
|
75
|
+
throw inventoryError(`record ${outpoint} has no locking script`)
|
|
76
|
+
}
|
|
77
|
+
const tags = o.tags ?? []
|
|
78
|
+
if (!Array.isArray(tags) || !tags.every(t => typeof t === 'string')) {
|
|
79
|
+
throw inventoryError(`record ${outpoint} has invalid tags`)
|
|
80
|
+
}
|
|
81
|
+
// vout is an output index, not a token amount: Number() is exact here.
|
|
82
|
+
const decoded = decodeToken(o.lockingScript, m[1], Number(m[2]))
|
|
83
|
+
if (decoded == null || decoded.assetId == null || !ASSET_ID.test(decoded.assetId)) {
|
|
84
|
+
throw inventoryError(`record ${outpoint} is not a 1Color token output`)
|
|
85
|
+
}
|
|
86
|
+
// A deploy output holds the new asset itself: its supply is value (deploy-fixed),
|
|
87
|
+
// and a zero-amount deploy is the asset's authority (deploy-authority).
|
|
88
|
+
const role: 'value' | 'authority' =
|
|
89
|
+
decoded.role === 'value' || (decoded.role === 'deploy' && decoded.amount > 0n) ? 'value' : 'authority'
|
|
90
|
+
return {
|
|
91
|
+
outpoint,
|
|
92
|
+
assetId: decoded.assetId,
|
|
93
|
+
role,
|
|
94
|
+
units: role === 'value' ? decoded.amount : 0n,
|
|
95
|
+
tags: [...(tags as string[])]
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Every record of the `p color assets` inventory, decoded, paged to completion.
|
|
101
|
+
*
|
|
102
|
+
* `totalOutputs` drives the paging (a short page is not the end: a wallet may
|
|
103
|
+
* cap `limit`). An empty page ends it, which also stops a wallet that ignores
|
|
104
|
+
* `offset`. Pages are separate snapshots (0207:657-660), so a record that
|
|
105
|
+
* shows again on a later page is the same outpoint, never more value: records
|
|
106
|
+
* are de-duplicated by outpoint.
|
|
107
|
+
*/
|
|
108
|
+
export async function readInventory(wallet: WalletInterface, originator: string): Promise<InventoryRecord[]> {
|
|
109
|
+
const byOutpoint = new Map<string, InventoryRecord>()
|
|
110
|
+
let offset = 0
|
|
111
|
+
for (let page = 0; page < INVENTORY_MAX_PAGES; page++) {
|
|
112
|
+
const chunk = (await wallet.listOutputs(
|
|
113
|
+
{ basket: ASSETS_VIEW, include: 'locking scripts', includeTags: true, limit: INVENTORY_PAGE, offset },
|
|
114
|
+
originator
|
|
115
|
+
)) as { totalOutputs?: unknown; outputs?: unknown }
|
|
116
|
+
const total = chunk.totalOutputs
|
|
117
|
+
if (typeof total !== 'number' || !Number.isSafeInteger(total) || total < 0) {
|
|
118
|
+
throw inventoryError(`invalid totalOutputs ${JSON.stringify(total)}`)
|
|
119
|
+
}
|
|
120
|
+
if (!Array.isArray(chunk.outputs)) throw inventoryError('page has no outputs array')
|
|
121
|
+
for (const output of chunk.outputs) {
|
|
122
|
+
const record = decodeRecord(output)
|
|
123
|
+
if (!byOutpoint.has(record.outpoint)) byOutpoint.set(record.outpoint, record)
|
|
124
|
+
}
|
|
125
|
+
if (chunk.outputs.length === 0) return [...byOutpoint.values()]
|
|
126
|
+
offset += chunk.outputs.length
|
|
127
|
+
if (offset >= total) return [...byOutpoint.values()]
|
|
128
|
+
}
|
|
129
|
+
throw inventoryError(`more than ${INVENTORY_MAX_PAGES} pages; refusing to truncate`)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* The exact available units of `assetId`: the `p color balance <assetTag>`
|
|
134
|
+
* view's `totalOutputs`, which must be a canonical decimal string (BRC-112).
|
|
135
|
+
* A JSON number, a leading zero or anything else is a thrown error — a number
|
|
136
|
+
* would already have lost precision above 2^53.
|
|
137
|
+
*/
|
|
138
|
+
export async function readAvailable(wallet: WalletInterface, originator: string, assetId: string): Promise<bigint> {
|
|
139
|
+
return await readBalanceView(wallet, originator, assetId)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* The pending (offline-credited, not yet settled) units of `assetId`: the
|
|
144
|
+
* same balance view filtered to `color_offline` (B7 API: "Pending balance").
|
|
145
|
+
* A subset of `readAvailable`, never added to it.
|
|
146
|
+
*/
|
|
147
|
+
export async function readPending(wallet: WalletInterface, originator: string, assetId: string): Promise<bigint> {
|
|
148
|
+
return await readBalanceView(wallet, originator, assetId, [COLOR_OFFLINE_TAG])
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function readBalanceView(
|
|
152
|
+
wallet: WalletInterface,
|
|
153
|
+
originator: string,
|
|
154
|
+
assetId: string,
|
|
155
|
+
tags?: string[]
|
|
156
|
+
): Promise<bigint> {
|
|
157
|
+
const basket = `p color balance ${assetTag(assetId)}`
|
|
158
|
+
const r = (await wallet.listOutputs(tags ? { basket, tags } : { basket }, originator)) as { totalOutputs?: unknown }
|
|
159
|
+
const total = r?.totalOutputs
|
|
160
|
+
if (typeof total !== 'string' || !CANONICAL_UNITS.test(total)) {
|
|
161
|
+
throw new Error(`${basket}${tags ? ` [${tags.join(',')}]` : ''}: non-canonical balance ${JSON.stringify(total)}`)
|
|
162
|
+
}
|
|
163
|
+
return BigInt(total)
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* The offline (not yet overlay-settled) part of `assetId`'s available units:
|
|
168
|
+
* value records that carry BOTH `color_state_available` and `color_offline`.
|
|
169
|
+
* A reserved or pending record is not available and is not counted, whatever
|
|
170
|
+
* else it carries (0207:396-404).
|
|
171
|
+
*/
|
|
172
|
+
export function offlineUnitsOf(records: readonly InventoryRecord[], assetId: string): bigint {
|
|
173
|
+
let sum = 0n
|
|
174
|
+
for (const r of records) {
|
|
175
|
+
if (r.assetId !== assetId || r.role !== 'value') continue
|
|
176
|
+
if (r.tags.includes(STATE_AVAILABLE_TAG) && r.tags.includes(COLOR_OFFLINE_TAG)) sum += r.units
|
|
177
|
+
}
|
|
178
|
+
return sum
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// ─────────────────────────────── metadata ───────────────────────────────
|
|
182
|
+
|
|
183
|
+
/** The label an asset with no readable deploy shows. The full id is always available beside it. */
|
|
184
|
+
export function shortAssetId(assetId: string): string {
|
|
185
|
+
return `${assetId.slice(0, 20)}…`
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** KV key of an asset's cached deploy metadata (W7). */
|
|
189
|
+
export function assetMetadataKey(assetId: string): string {
|
|
190
|
+
return `bsvwallet.color.asset.${assetId}`
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
interface CachedDeploy {
|
|
194
|
+
v: 1
|
|
195
|
+
sym?: string
|
|
196
|
+
dec: number
|
|
197
|
+
label?: string
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** How long an UNRESOLVED answer is reused before the overlay is asked again. */
|
|
201
|
+
const UNRESOLVED_TTL_MS = 10_000
|
|
202
|
+
|
|
203
|
+
function unresolved(assetId: string): TokenAssetInfo {
|
|
204
|
+
return { assetId, label: shortAssetId(assetId), ticker: '', decimals: 0, resolved: false }
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function fromDeploy(assetId: string, d: CachedDeploy): TokenAssetInfo {
|
|
208
|
+
return {
|
|
209
|
+
assetId,
|
|
210
|
+
label: d.label !== undefined && d.label !== '' ? d.label : shortAssetId(assetId),
|
|
211
|
+
ticker: d.sym ?? '',
|
|
212
|
+
decimals: d.dec,
|
|
213
|
+
resolved: true
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function parseCached(text: string): CachedDeploy | undefined {
|
|
218
|
+
try {
|
|
219
|
+
const v = JSON.parse(text) as Partial<CachedDeploy>
|
|
220
|
+
if (v?.v !== 1 || typeof v.dec !== 'number' || !Number.isInteger(v.dec) || v.dec < 0 || v.dec > MAX_DECIMALS) {
|
|
221
|
+
return undefined
|
|
222
|
+
}
|
|
223
|
+
if (v.sym !== undefined && typeof v.sym !== 'string') return undefined
|
|
224
|
+
if (v.label !== undefined && typeof v.label !== 'string') return undefined
|
|
225
|
+
return {
|
|
226
|
+
v: 1,
|
|
227
|
+
dec: v.dec,
|
|
228
|
+
...(v.sym !== undefined ? { sym: v.sym } : {}),
|
|
229
|
+
...(v.label !== undefined ? { label: v.label } : {})
|
|
230
|
+
}
|
|
231
|
+
} catch {
|
|
232
|
+
return undefined
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* The deploy metadata of `tx`, filed under the asset id its OWN txid names, or
|
|
238
|
+
* undefined. Only a deploy whose `req` is exactly `mandalaReq(K)` for this
|
|
239
|
+
* wallet's overlay key resolves: any other asset fails closed against the
|
|
240
|
+
* Mandala overlay anyway (W3), and is shown by its short id.
|
|
241
|
+
*/
|
|
242
|
+
function deployOf(tx: Transaction, overlayIdentityKey: string): { assetId: string; cached: CachedDeploy } | undefined {
|
|
243
|
+
const txid = tx.id('hex')
|
|
244
|
+
const script = tx.outputs[0]?.lockingScript
|
|
245
|
+
if (script == null) return undefined
|
|
246
|
+
const d = readDeploy(script, txid)
|
|
247
|
+
if (d == null || d.assetId !== `${txid}_0` || d.mandalaKey !== overlayIdentityKey) return undefined
|
|
248
|
+
if (!Number.isInteger(d.dec) || d.dec < 0 || d.dec > MAX_DECIMALS) return undefined
|
|
249
|
+
return {
|
|
250
|
+
assetId: d.assetId,
|
|
251
|
+
cached: {
|
|
252
|
+
v: 1,
|
|
253
|
+
dec: d.dec,
|
|
254
|
+
...(d.sym !== undefined ? { sym: d.sym } : {}),
|
|
255
|
+
...(d.label !== undefined ? { label: d.label } : {})
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* The deploy tx of `assetId` from the overlay's `color-admission` answer for
|
|
262
|
+
* `<txid>.0`, checked the way the module checks it: valid BEEF, the named
|
|
263
|
+
* output exists, and the tx's own id is the asset's txid.
|
|
264
|
+
*/
|
|
265
|
+
async function deployFromProvider(provider: ColorOverlayProvider, assetId: string): Promise<Transaction | undefined> {
|
|
266
|
+
const txid = assetId.slice(0, 64)
|
|
267
|
+
const answer = await provider.admission(assetId, [`${txid}.0`])
|
|
268
|
+
if (answer?.type !== 'output-list' || !Array.isArray(answer.outputs)) return undefined
|
|
269
|
+
for (const item of answer.outputs) {
|
|
270
|
+
if (item.outputIndex !== 0) continue
|
|
271
|
+
let tx: Transaction
|
|
272
|
+
try {
|
|
273
|
+
tx = Transaction.fromBEEF(item.beef, item.txid)
|
|
274
|
+
} catch {
|
|
275
|
+
continue
|
|
276
|
+
}
|
|
277
|
+
if (tx.id('hex') === txid) return tx
|
|
278
|
+
}
|
|
279
|
+
return undefined
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Display metadata for assets, from a cached deploy first and the
|
|
284
|
+
* overlay's deploy answer second (W7).
|
|
285
|
+
*
|
|
286
|
+
* · `remember(hex)` files a deploy tx under the asset id of its own txid
|
|
287
|
+
* (receipts carry no deploy since B7). It never throws:
|
|
288
|
+
* a bad hex string or a non-deploy is ignored.
|
|
289
|
+
* · `info(assetId)` answers from memory, then the KV cache, then
|
|
290
|
+
* `provider.admission`. A resolved answer is cached for good (it is a pure
|
|
291
|
+
* function of the hash-bound deploy). An unresolved one is reused only for
|
|
292
|
+
* ~10 s, so a read made offline does not pin "unknown" until a restart.
|
|
293
|
+
* Concurrent reads of one asset share one lookup.
|
|
294
|
+
*/
|
|
295
|
+
export function createAssetMetadata(
|
|
296
|
+
kv: WalletKv,
|
|
297
|
+
provider: ColorOverlayProvider | undefined,
|
|
298
|
+
overlayIdentityKey: string,
|
|
299
|
+
opts: { now?: () => number } = {}
|
|
300
|
+
): { info(assetId: string): Promise<TokenAssetInfo>; remember(declarationTxHex: string): Promise<void> } {
|
|
301
|
+
const now = opts.now ?? (() => Date.now())
|
|
302
|
+
const resolvedMemo = new Map<string, TokenAssetInfo>()
|
|
303
|
+
const unresolvedMemo = new Map<string, number>()
|
|
304
|
+
const inFlight = new Map<string, Promise<TokenAssetInfo>>()
|
|
305
|
+
|
|
306
|
+
const store = async (assetId: string, cached: CachedDeploy): Promise<void> => {
|
|
307
|
+
resolvedMemo.set(assetId, fromDeploy(assetId, cached))
|
|
308
|
+
unresolvedMemo.delete(assetId)
|
|
309
|
+
try {
|
|
310
|
+
await kv.setKeyValue(assetMetadataKey(assetId), JSON.stringify(cached))
|
|
311
|
+
} catch (e) {
|
|
312
|
+
// Display data only: the in-memory answer still serves this session.
|
|
313
|
+
devLog(`[mandala] could not cache metadata for ${assetId}:`, e)
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
const lookup = async (assetId: string): Promise<TokenAssetInfo> => {
|
|
318
|
+
try {
|
|
319
|
+
const text = await kv.getKeyValue(assetMetadataKey(assetId))
|
|
320
|
+
const cached = text === undefined ? undefined : parseCached(text)
|
|
321
|
+
if (cached !== undefined) {
|
|
322
|
+
const info = fromDeploy(assetId, cached)
|
|
323
|
+
resolvedMemo.set(assetId, info)
|
|
324
|
+
return info
|
|
325
|
+
}
|
|
326
|
+
} catch (e) {
|
|
327
|
+
devLog(`[mandala] could not read cached metadata for ${assetId}:`, e)
|
|
328
|
+
}
|
|
329
|
+
if (provider !== undefined) {
|
|
330
|
+
try {
|
|
331
|
+
const tx = await deployFromProvider(provider, assetId)
|
|
332
|
+
const d = tx === undefined ? undefined : deployOf(tx, overlayIdentityKey)
|
|
333
|
+
if (d !== undefined && d.assetId === assetId) {
|
|
334
|
+
await store(assetId, d.cached)
|
|
335
|
+
return resolvedMemo.get(assetId) as TokenAssetInfo
|
|
336
|
+
}
|
|
337
|
+
} catch (e) {
|
|
338
|
+
devLog(`[mandala] could not resolve the deploy of ${assetId}:`, e)
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
unresolvedMemo.set(assetId, now())
|
|
342
|
+
return unresolved(assetId)
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
return {
|
|
346
|
+
async info(assetId) {
|
|
347
|
+
const hit = resolvedMemo.get(assetId)
|
|
348
|
+
if (hit !== undefined) return hit
|
|
349
|
+
const at = unresolvedMemo.get(assetId)
|
|
350
|
+
if (at !== undefined && now() - at < UNRESOLVED_TTL_MS) return unresolved(assetId)
|
|
351
|
+
if (!ASSET_ID.test(assetId)) return unresolved(assetId)
|
|
352
|
+
let p = inFlight.get(assetId)
|
|
353
|
+
if (p === undefined) {
|
|
354
|
+
p = lookup(assetId).finally(() => inFlight.delete(assetId))
|
|
355
|
+
inFlight.set(assetId, p)
|
|
356
|
+
}
|
|
357
|
+
return await p
|
|
358
|
+
},
|
|
359
|
+
|
|
360
|
+
async remember(declarationTxHex) {
|
|
361
|
+
try {
|
|
362
|
+
if (typeof declarationTxHex !== 'string' || !/^([0-9a-f]{2})+$/.test(declarationTxHex)) return
|
|
363
|
+
const d = deployOf(Transaction.fromHex(declarationTxHex), overlayIdentityKey)
|
|
364
|
+
if (d !== undefined) await store(d.assetId, d.cached)
|
|
365
|
+
} catch (e) {
|
|
366
|
+
devLog('[mandala] ignored a declarationTx that is not a readable deploy:', e)
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The broadcast hold's predicate: which transactions the wallet must not post.
|
|
3
|
+
*
|
|
4
|
+
* IC §8.2 (host broadcast guard): a host holds the toolbox's broadcast of a
|
|
5
|
+
* 1Color transaction until it is settled, and a receipt's `internalizeAction`
|
|
6
|
+
* must not reach the network before a verified admission. Plan 07 W1 keys
|
|
7
|
+
* "settled" on the wallet's own journal, `color_transfers`, and never on the
|
|
8
|
+
* module's `color.v1.*` keys (IC §2.1 says that layout is module-internal).
|
|
9
|
+
*
|
|
10
|
+
* The hold applies only where THIS wallet's token custody is involved. A
|
|
11
|
+
* 1Color output alone proves nothing: anyone can add a 1-sat 1Color output to
|
|
12
|
+
* a payment, and a payer who could make the payee's wallet hold a BSV credit
|
|
13
|
+
* (instead of broadcasting it) would keep the payment unconfirmed while
|
|
14
|
+
* staying free to double-spend its inputs (the decoy-output finding, every
|
|
15
|
+
* rail: handle/MessageBox, direct, nearby, address). So a 1Color tx is held
|
|
16
|
+
* when any of these says the wallet's custody is in it:
|
|
17
|
+
* - a `color_transfers` row (this wallet built or received it as a token
|
|
18
|
+
* transfer);
|
|
19
|
+
* - a Mandala host-ledger record (B7: written BEFORE the receipt is
|
|
20
|
+
* internalized by the lib's receive path and by the issuer-v1 handler's
|
|
21
|
+
* own admission, and before `sendHandover` returns). The toolbox
|
|
22
|
+
* broadcasts inside `internalizeAction` BEFORE it stores the receipt's
|
|
23
|
+
* outputs in their `p color` basket, so the basket cannot be read at hold
|
|
24
|
+
* time; the ledger can;
|
|
25
|
+
* - an input it spends from one of this wallet's `p color` baskets (marked
|
|
26
|
+
* spent before any broadcast attempt, both by `createAction` and by
|
|
27
|
+
* `internalizeAction`): a token send from any originator.
|
|
28
|
+
* Such a tx is held unless its journal row reads `settled`.
|
|
29
|
+
*
|
|
30
|
+
* Every other arm fails closed:
|
|
31
|
+
* - Bytes that will not parse cannot be shown to be anything; they are
|
|
32
|
+
* held. A req with no bytes at all is held for the same reason.
|
|
33
|
+
* - A journal, ledger or input read fault propagates. Every caller already
|
|
34
|
+
* turns a throw into "hold the whole batch" or "stall this step";
|
|
35
|
+
* answering an empty set here would read as "nothing to hold" and post.
|
|
36
|
+
*
|
|
37
|
+
* Plain BSV never touches the journal: a batch with no 1Color tx is answered
|
|
38
|
+
* from the bytes alone.
|
|
39
|
+
*/
|
|
40
|
+
import { Transaction, type LockingScript } from '@bsv/sdk'
|
|
41
|
+
import { OneColor } from '@bsv/templates'
|
|
42
|
+
import { decodeToken } from '@bsv/mandala/brc162'
|
|
43
|
+
import type { TransferJournal } from './transferJournal'
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* What the hold reads besides the bytes. `custodyOf` answers, for txids that
|
|
47
|
+
* have no journal row, which ones this wallet's custody is involved in
|
|
48
|
+
* through the host ledger or its own `p color` inputs. Without it, every
|
|
49
|
+
* 1Color tx counts as custodial (the pre-scoping rule: hold all).
|
|
50
|
+
*/
|
|
51
|
+
export interface ColorCustody extends Pick<TransferJournal, 'statesOf'> {
|
|
52
|
+
custodyOf?: (txids: readonly string[]) => Promise<ReadonlySet<string>>
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The key prefix of `@bsv/mandala`'s host-ledger records (`hostLedger.ts`,
|
|
57
|
+
* `mandala.host.v1.record.<txid>`). Read raw by the hold: a record that is
|
|
58
|
+
* present but unreadable still counts as custody (fail closed), where the
|
|
59
|
+
* lib's own `get` would read it as absent.
|
|
60
|
+
*/
|
|
61
|
+
export const HOST_LEDGER_RECORD_PREFIX = 'mandala.host.v1.record.'
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Of `txids`, the ones whose transaction spends an output of this wallet's
|
|
65
|
+
* `p color` baskets, by SQL over the toolbox's own tables (`outputs.spentBy`
|
|
66
|
+
* is set before any broadcast attempt). Chunked under SQLite's bound-parameter
|
|
67
|
+
* limit. Faults propagate.
|
|
68
|
+
*/
|
|
69
|
+
export async function txidsSpendingColorOutputs(
|
|
70
|
+
db: { getAllAsync(sql: string, params: (string | number | null)[]): Promise<unknown[]> },
|
|
71
|
+
txids: readonly string[]
|
|
72
|
+
): Promise<Set<string>> {
|
|
73
|
+
const out = new Set<string>()
|
|
74
|
+
for (let i = 0; i < txids.length; i += 500) {
|
|
75
|
+
const chunk = txids.slice(i, i + 500)
|
|
76
|
+
const rows = await db.getAllAsync(
|
|
77
|
+
`SELECT DISTINCT t.txid AS txid FROM transactions t
|
|
78
|
+
JOIN outputs o ON o.spentBy = t.transactionId
|
|
79
|
+
JOIN output_baskets b ON b.basketId = o.basketId
|
|
80
|
+
WHERE b.name LIKE 'p color %' AND t.txid IN (${chunk.map(() => '?').join(',')})`,
|
|
81
|
+
chunk
|
|
82
|
+
)
|
|
83
|
+
for (const r of rows as { txid?: unknown }[]) if (typeof r.txid === 'string') out.add(r.txid)
|
|
84
|
+
}
|
|
85
|
+
return out
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* True when any output of `rawTx` is a BRC-162 1Color output, and when the
|
|
90
|
+
* bytes cannot be parsed at all (fail closed). A precondition of the hold,
|
|
91
|
+
* never the hold itself (see `colorHeldTxids`).
|
|
92
|
+
*
|
|
93
|
+
* `decodeToken` (the lib's codec boundary) recognises a 1Color output locked
|
|
94
|
+
* to a P2PKH remainder, which is every output a Mandala holder builds. A
|
|
95
|
+
* 1Color envelope over any other remainder is still a BRC-162 token output
|
|
96
|
+
* (0162 lockRemainder), so it is held too: `OneColor.decode` accepting the
|
|
97
|
+
* script is enough.
|
|
98
|
+
*/
|
|
99
|
+
export function txHasColorOutput(rawTx: readonly number[] | Uint8Array): boolean {
|
|
100
|
+
let tx: Transaction
|
|
101
|
+
try {
|
|
102
|
+
tx = Transaction.fromBinary(Array.from(rawTx))
|
|
103
|
+
} catch {
|
|
104
|
+
return true
|
|
105
|
+
}
|
|
106
|
+
return transactionHasColorOutput(tx)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* The same predicate over an already-parsed transaction: true when any output
|
|
111
|
+
* is a 1Color output by the rule above.
|
|
112
|
+
*
|
|
113
|
+
* Shared by the hold and by `processOfflineActions`, so the two cannot drift
|
|
114
|
+
* on what a 1Color output is.
|
|
115
|
+
*/
|
|
116
|
+
export function transactionHasColorOutput(tx: Pick<Transaction, 'outputs'>): boolean {
|
|
117
|
+
return tx.outputs.some(o => isColorScript(o.lockingScript))
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function isColorScript(script: LockingScript | undefined): boolean {
|
|
121
|
+
if (script == null) return false
|
|
122
|
+
if (decodeToken(script) !== null) return true
|
|
123
|
+
try {
|
|
124
|
+
OneColor.decode(script)
|
|
125
|
+
return true
|
|
126
|
+
} catch {
|
|
127
|
+
return false
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Of `reqs`, the txids the toolbox must not broadcast now.
|
|
133
|
+
*
|
|
134
|
+
* held ⇔ no bytes ∨ unparseable bytes ∨ (a 1Color output ∧ custody ∧ journal
|
|
135
|
+
* state ≠ `settled`), where custody is a journal row, or `custodyOf` naming
|
|
136
|
+
* the txid (host ledger, own `p color` inputs). One `statesOf` read and at
|
|
137
|
+
* most one `custodyOf` read cover the batch. Faults propagate.
|
|
138
|
+
*/
|
|
139
|
+
export async function colorHeldTxids(
|
|
140
|
+
reqs: readonly { txid: string; rawTx?: readonly number[] | Uint8Array }[],
|
|
141
|
+
custody: ColorCustody
|
|
142
|
+
): Promise<Set<string>> {
|
|
143
|
+
const held = new Set<string>()
|
|
144
|
+
const color = new Set<string>()
|
|
145
|
+
for (const r of reqs) {
|
|
146
|
+
if (r.rawTx == null) {
|
|
147
|
+
held.add(r.txid)
|
|
148
|
+
continue
|
|
149
|
+
}
|
|
150
|
+
let tx: Transaction
|
|
151
|
+
try {
|
|
152
|
+
tx = Transaction.fromBinary(Array.from(r.rawTx))
|
|
153
|
+
} catch {
|
|
154
|
+
held.add(r.txid)
|
|
155
|
+
continue
|
|
156
|
+
}
|
|
157
|
+
if (transactionHasColorOutput(tx)) color.add(r.txid)
|
|
158
|
+
}
|
|
159
|
+
for (const txid of held) color.delete(txid)
|
|
160
|
+
if (color.size === 0) return held
|
|
161
|
+
const states = await custody.statesOf([...color])
|
|
162
|
+
const unjournaled = [...color].filter(txid => !states.has(txid))
|
|
163
|
+
const custodial =
|
|
164
|
+
unjournaled.length === 0
|
|
165
|
+
? new Set<string>()
|
|
166
|
+
: custody.custodyOf
|
|
167
|
+
? await custody.custodyOf(unjournaled)
|
|
168
|
+
: new Set(unjournaled)
|
|
169
|
+
for (const txid of color) {
|
|
170
|
+
const state = states.get(txid)
|
|
171
|
+
if (state !== undefined) {
|
|
172
|
+
if (state !== 'settled') held.add(txid)
|
|
173
|
+
} else if (custodial.has(txid)) {
|
|
174
|
+
held.add(txid)
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return held
|
|
178
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The wallet's one assembly of the BRC-207 color module (plan 07 Task 10).
|
|
3
|
+
*
|
|
4
|
+
* The module holds all token custody (B7: no history evidence). It is registered in the
|
|
5
|
+
* permissions manager as `permissionModules.color`, so every `p color` basket,
|
|
6
|
+
* label and protocol call — from any originator — passes through it.
|
|
7
|
+
*
|
|
8
|
+
* Registration (IC §8.2, Revision 3 / design §9 B7):
|
|
9
|
+
* · `wallet` is the UNDERLYING wallet, never the permissions manager. The
|
|
10
|
+
* module derives keys and signs on it directly; handing it the manager would
|
|
11
|
+
* route the module's own calls back into itself.
|
|
12
|
+
* · profiles: the Mandala issuer-v1 profile only (B7: no attested profile),
|
|
13
|
+
* whose one configured overlay is this chain's (overlayUrl, K). An asset
|
|
14
|
+
* naming any other K has no provider and fails closed (S5).
|
|
15
|
+
* · ledger: the Mandala HOST LEDGER (`createHostLedger`) over the wallet's
|
|
16
|
+
* `key_value_store` (`mandala.host.v1.record.*`). One object, shared by the
|
|
17
|
+
* issuer-v1 handler (it credits a receipt only from it, or after its own
|
|
18
|
+
* verified submit) and the runtime's send, receive and settle paths. It is
|
|
19
|
+
* in-process only: no BRC-100 method reaches it, so no app can make the
|
|
20
|
+
* handler credit anything.
|
|
21
|
+
* · provider (W3): the default provider is the plain Mandala overlay provider
|
|
22
|
+
* for this chain. This is a Mandala wallet: a profile-free 1Color asset is
|
|
23
|
+
* checked against the Mandala overlay and fails closed there.
|
|
24
|
+
* · store: the module's durable `color.v1.` records over the wallet's
|
|
25
|
+
* `key_value_store`. The wallet never reads those keys (IC §2.1); it calls
|
|
26
|
+
* the host-only `module.markSettled(txid)` instead.
|
|
27
|
+
*
|
|
28
|
+
* Construction does no I/O. Every throw here (a malformed overlay key or url)
|
|
29
|
+
* means no module: the caller then registers no `color` key, so `p color`
|
|
30
|
+
* calls fail closed with "Unsupported P-module scheme".
|
|
31
|
+
*/
|
|
32
|
+
import {
|
|
33
|
+
createColorModule,
|
|
34
|
+
type ColorModuleStore,
|
|
35
|
+
type ColorOverlayProvider,
|
|
36
|
+
type ColorPermissionModule,
|
|
37
|
+
type ColorTokenAccessHandler
|
|
38
|
+
} from '@bsv/color-permission-module'
|
|
39
|
+
import { createHostLedger, type HostLedger } from '@bsv/mandala'
|
|
40
|
+
import { MANDALA_PROFILE_ID, createMandalaOverlayProvider, createMandalaProfile } from '@bsv/mandala/profile'
|
|
41
|
+
import type { WalletInterface } from '@bsv/sdk'
|
|
42
|
+
import type { MandalaEndpointConfig } from '../toolboxConfig'
|
|
43
|
+
import { createColorModuleStore, createMandalaKvStorage, type WalletKv } from './kvStore'
|
|
44
|
+
|
|
45
|
+
export interface BuildColorModuleArgs {
|
|
46
|
+
/** The UNDERLYING wallet, never the permissions manager. */
|
|
47
|
+
wallet: WalletInterface
|
|
48
|
+
endpoints: MandalaEndpointConfig
|
|
49
|
+
kv: WalletKv
|
|
50
|
+
requestTokenAccess: ColorTokenAccessHandler
|
|
51
|
+
fetch?: typeof fetch
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface BuiltColorModule {
|
|
55
|
+
module: ColorPermissionModule
|
|
56
|
+
provider: ColorOverlayProvider & { readonly url: string; readonly identityKey: string }
|
|
57
|
+
store: ColorModuleStore
|
|
58
|
+
/** The host ledger the issuer-v1 handler credits from (shared with the runtime). */
|
|
59
|
+
ledger: HostLedger
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function buildColorModule(a: BuildColorModuleArgs): BuiltColorModule {
|
|
63
|
+
const { overlayUrl, overlayIdentityKey } = a.endpoints
|
|
64
|
+
const fetchOption = a.fetch === undefined ? {} : { fetch: a.fetch }
|
|
65
|
+
const provider = createMandalaOverlayProvider({ url: overlayUrl, identityKey: overlayIdentityKey, ...fetchOption })
|
|
66
|
+
const store = createColorModuleStore(a.kv)
|
|
67
|
+
const ledger = createHostLedger(createMandalaKvStorage(a.kv))
|
|
68
|
+
const module = createColorModule({
|
|
69
|
+
wallet: a.wallet,
|
|
70
|
+
provider,
|
|
71
|
+
requestTokenAccess: a.requestTokenAccess,
|
|
72
|
+
store,
|
|
73
|
+
profiles: {
|
|
74
|
+
[MANDALA_PROFILE_ID]: createMandalaProfile({
|
|
75
|
+
overlays: [{ identityKey: overlayIdentityKey, url: overlayUrl }],
|
|
76
|
+
ledger,
|
|
77
|
+
...fetchOption
|
|
78
|
+
})
|
|
79
|
+
}
|
|
80
|
+
})
|
|
81
|
+
return { module, provider, store, ledger }
|
|
82
|
+
}
|