@kaleidorg/rgb-lib-wasm 0.0.0-stage → 1.0.0-ks.1

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/README.md CHANGED
@@ -1,3 +1,389 @@
1
- # Temporary Holding Version
1
+ # rgb-lib-wasm
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A WebAssembly port of [rgb-lib](https://github.com/UTEXO-Protocol/rgb-lib) for managing RGB protocol wallets in the browser.
4
+
5
+ > **Beta Software** — This library is under active development and has not been audited.
6
+ > APIs may change without notice between versions. Use at your own risk.
7
+
8
+ ## What it does
9
+
10
+ rgb-lib-wasm lets you issue, send, and receive RGB assets from a web browser. It replaces the native Rust dependencies (filesystem, SQLite, TCP sockets) with browser-compatible alternatives:
11
+
12
+ - **In-memory database** with IndexedDB persistence
13
+ - **Esplora indexer** over HTTP
14
+ - **Encrypted backup** to a local file or a remote VSS server
15
+
16
+ Supported asset types:
17
+ - **NIA** (Non-Inflatable Asset)
18
+ - **IFA** (Inflatable Fungible Asset).
19
+
20
+ ## Prerequisites
21
+
22
+ - Rust 1.85.0+ with the `wasm32-unknown-unknown` target
23
+ - [wasm-pack](https://rustwasm.github.io/wasm-pack/) 0.14+
24
+
25
+ ```bash
26
+ rustup target add wasm32-unknown-unknown
27
+ cargo install wasm-pack@0.14.0
28
+ ```
29
+
30
+ ## Building
31
+
32
+ ```bash
33
+ cd bindings/wasm
34
+ ./build.sh
35
+ ```
36
+
37
+ This produces the `pkg/` directory containing an npm-ready package (`rgb_lib_wasm.js`, `.d.ts` types, and the `.wasm` binary).
38
+
39
+ ### Trying the examples
40
+
41
+ ```bash
42
+ cd bindings/wasm
43
+ python3 -m http.server 8000
44
+ # Open http://localhost:8000/examples/index.html
45
+ ```
46
+
47
+ The `examples/` folder contains interactive pages that cover the full API, split by topic:
48
+
49
+ | Page | Description |
50
+ |------|-------------|
51
+ | [`index.html`](bindings/wasm/examples/index.html) | Quick start guide + automated "Run All" flow |
52
+ | [`wallet.html`](bindings/wasm/examples/wallet.html) | Key management, wallet creation, go online, fund, create UTXOs, wallet state queries, fee estimation |
53
+ | [`bitcoin.html`](bindings/wasm/examples/bitcoin.html) | Send BTC, drain wallet, PSBT sign/finalize utilities |
54
+ | [`rgb.html`](bindings/wasm/examples/rgb.html) | Issue NIA/IFA, blind/witness receive, send RGB, inflate IFA, refresh/fail/delete transfers |
55
+ | [`backup.html`](bindings/wasm/examples/backup.html) | Local encrypted backup, VSS cloud backup, check proxy URL, error handling tests |
56
+
57
+ All pages share `examples/lib/shared.js` (WASM init, helpers, regtest utilities). Each page is self-contained with its own wallet setup section. Online operations (funding, sending, etc.) require the regtest Docker services — see [DEV-ENVIRONMENT.md](DEV-ENVIRONMENT.md) for setup.
58
+
59
+ ## Usage
60
+
61
+ ```javascript
62
+ import init, {
63
+ generateKeys, restoreKeys, checkProxyUrl,
64
+ validateConsignmentOffchain,
65
+ WasmWallet, WasmInvoice,
66
+ } from './pkg/rgb_lib_wasm.js';
67
+
68
+ await init();
69
+ ```
70
+
71
+ ### Key generation
72
+
73
+ ```javascript
74
+ const keys = generateKeys('Regtest');
75
+ // keys: { mnemonic, accountXpubVanilla, accountXpubColored, masterFingerprint }
76
+
77
+ const restored = restoreKeys('Regtest', keys.mnemonic);
78
+ ```
79
+
80
+ ### Creating a wallet
81
+
82
+ ```javascript
83
+ const walletData = {
84
+ dataDir: ':memory:',
85
+ bitcoinNetwork: 'Regtest',
86
+ databaseType: 'Sqlite',
87
+ maxAllocationsPerUtxo: 5,
88
+ accountXpubVanilla: keys.accountXpubVanilla,
89
+ accountXpubColored: keys.accountXpubColored,
90
+ mnemonic: keys.mnemonic,
91
+ masterFingerprint: keys.masterFingerprint,
92
+ vanillaKeychain: null,
93
+ supportedSchemas: ['Nia', 'Ifa'],
94
+ };
95
+
96
+ // create() restores state from IndexedDB if available
97
+ const wallet = await WasmWallet.create(JSON.stringify(walletData));
98
+
99
+ // Await durable IndexedDB commit before persisting dependent application state.
100
+ await wallet.flush();
101
+ ```
102
+
103
+ ### Persistence ordering
104
+
105
+ `WasmWallet.create()` and Rust `Wallet::restore()` finish IndexedDB restoration
106
+ before returning. They return an error instead of silently starting from fresh
107
+ state when a stored snapshot cannot be read or decoded.
108
+
109
+ Rust `Wallet::flush()` and JavaScript `wallet.flush()` resolve only after the
110
+ IndexedDB read-write transaction commits. Persist dependent application state,
111
+ acknowledge accepted RGB funding, or broadcast a transaction that depends on an
112
+ RGB mutation only after the flush succeeds. A failed flush leaves the current
113
+ in-memory wallet state intact and can be retried. Snapshots carry a monotonic
114
+ sequence, and IndexedDB rejects stale writes so an earlier automatic save cannot
115
+ overwrite a later explicit flush.
116
+
117
+ Lightning-specific `consume_fascia`, `color_psbt_and_consume`, and
118
+ `accept_transfer` operations await this durable commit before returning
119
+ success.
120
+
121
+ ### Going online
122
+
123
+ ```javascript
124
+ const online = await wallet.goOnline(true, 'http://localhost:8094/regtest/api');
125
+ await wallet.sync(online);
126
+ ```
127
+
128
+ ### Creating UTXOs
129
+
130
+ RGB allocations live on UTXOs. Before issuing or receiving assets you need colored UTXOs:
131
+
132
+ ```javascript
133
+ const unsignedPsbt = await wallet.createUtxosBegin(online, true, 5, 1000, 1n, false);
134
+ const signedPsbt = wallet.signPsbt(unsignedPsbt);
135
+ const count = await wallet.createUtxosEnd(online, signedPsbt, false);
136
+ ```
137
+
138
+ ### Issuing assets
139
+
140
+ ```javascript
141
+ // NIA (fixed supply)
142
+ const nia = wallet.issueAssetNia('TICK', 'My Token', 0, [1000]);
143
+
144
+ // IFA (inflatable supply)
145
+ const ifa = wallet.issueAssetIfa('IFAT', 'Inflatable', 0, [1000], [500], undefined);
146
+ ```
147
+
148
+ ### Sending RGB assets
149
+
150
+ All send operations follow a three-step PSBT workflow: **begin** (build unsigned PSBT) → **sign** → **end** (broadcast).
151
+
152
+ ```javascript
153
+ const recipientMap = {
154
+ [assetId]: [{
155
+ recipientId: invoiceString,
156
+ witnessData: { amountSat: 1000, blinding: null },
157
+ amount: 100,
158
+ transportEndpoints: ['rpc://localhost:3000/json-rpc'],
159
+ }]
160
+ };
161
+ const psbt = await wallet.sendBegin(online, recipientMap, false, 1n, 1);
162
+ const signed = wallet.signPsbt(psbt);
163
+ const result = await wallet.sendEnd(online, signed, false);
164
+ // result: { txid, batchTransferIdx }
165
+ ```
166
+
167
+ ### Sending BTC
168
+
169
+ ```javascript
170
+ const psbt = await wallet.sendBtcBegin(online, address, 50000n, 1n, false);
171
+ const signed = wallet.signPsbt(psbt);
172
+ const txid = await wallet.sendBtcEnd(online, signed, false);
173
+ ```
174
+
175
+ ### Receiving assets
176
+
177
+ ```javascript
178
+ // Blind receive (UTXO-based)
179
+ const blind = wallet.blindReceive(null, 'Any', null, ['rpc://localhost:3000/json-rpc'], 1);
180
+ // blind: { invoice, recipientId, expirationTimestamp, ... }
181
+
182
+ // Witness receive (address-based)
183
+ const witness = wallet.witnessReceive(null, { Fungible: 100 }, null, ['rpc://localhost:3000/json-rpc'], 1);
184
+ ```
185
+
186
+ ### Parsing invoices
187
+
188
+ ```javascript
189
+ const invoice = new WasmInvoice(invoiceString);
190
+ const data = invoice.invoiceData();
191
+ // data: { recipientId, assetSchema, assetId, assignment, network, expirationTimestamp, transportEndpoints }
192
+ const str = invoice.invoiceString(); // original string
193
+ ```
194
+
195
+ ### Querying wallet state
196
+
197
+ ```javascript
198
+ const btcBalance = wallet.getBtcBalance();
199
+ const assetBalance = wallet.getAssetBalance(assetId);
200
+ const metadata = wallet.getAssetMetadata(assetId);
201
+ // metadata: { assetSchema, name, ticker, precision, initialSupply, maxSupply, knownCirculatingSupply, timestamp, ... }
202
+ const assets = wallet.listAssets([]); // all schemas
203
+ const transfers = wallet.listTransfers(null); // all assets
204
+ const unspents = wallet.listUnspents(false);
205
+ const transactions = wallet.listTransactions();
206
+ const address = wallet.getAddress();
207
+ ```
208
+
209
+ ### Fee estimation
210
+
211
+ ```javascript
212
+ const feeRate = await wallet.getFeeEstimation(online, 6); // target 6 blocks
213
+ ```
214
+
215
+ ### Draining the wallet
216
+
217
+ ```javascript
218
+ const psbt = await wallet.drainToBegin(online, destinationAddress, true, 1n);
219
+ const signed = wallet.signPsbt(psbt);
220
+ const txid = await wallet.drainToEnd(online, signed);
221
+ ```
222
+
223
+ ### Inflating an IFA asset
224
+
225
+ ```javascript
226
+ const psbt = await wallet.inflateBegin(online, assetId, [200], 1n, 1);
227
+ const signed = wallet.signPsbt(psbt);
228
+ const result = await wallet.inflateEnd(online, signed);
229
+ ```
230
+
231
+ ### Local encrypted backup
232
+
233
+ Wallet state is encrypted with Scrypt + XChaCha20Poly1305 and returned as bytes:
234
+
235
+ ```javascript
236
+ // Backup
237
+ const bytes = wallet.backup('my-password');
238
+ // bytes is a Uint8Array — save it as a file download
239
+
240
+ // Check if backup is needed
241
+ const needed = wallet.backupInfo(); // true if wallet changed since last backup
242
+
243
+ // Restore (wallet must be created first with the same mnemonic)
244
+ wallet.restoreBackup(backupBytes, 'my-password');
245
+ ```
246
+
247
+ ### VSS cloud backup
248
+
249
+ [VSS](https://github.com/lightningdevkit/vss-server) (Versioned Storage Service) provides cloud backup with optimistic locking:
250
+
251
+ ```javascript
252
+ // Configure (signing key is a 32-byte hex-encoded secp256k1 secret key)
253
+ wallet.configureVssBackup('http://vss-server:8082/vss', 'my-store-id', signingKeyHex);
254
+
255
+ // Upload
256
+ const version = await wallet.vssBackup();
257
+
258
+ // Check status
259
+ const info = await wallet.vssBackupInfo();
260
+ // info: { backupExists, serverVersion, backupRequired }
261
+
262
+ // Restore
263
+ await wallet.vssRestoreBackup();
264
+
265
+ // Disable
266
+ wallet.disableVssBackup();
267
+ ```
268
+
269
+ ### Transfer management
270
+
271
+ ```javascript
272
+ const refreshResult = await wallet.refresh(online, null, [], false);
273
+ const failed = await wallet.failTransfers(online, null, false, false);
274
+ const deleted = wallet.deleteTransfers(null, false);
275
+ ```
276
+
277
+ ### Utilities
278
+
279
+ ```javascript
280
+ // Validate an RGB proxy server
281
+ await checkProxyUrl('http://localhost:3000/json-rpc');
282
+
283
+ // Validate an RGB consignment offchain (before TX is broadcast)
284
+ // consignmentBytes is a Uint8Array of the strict-encoded consignment
285
+ const result = validateConsignmentOffchain(consignmentBytes, txid, 'Regtest');
286
+ // result: { valid: true, warnings: [...] }
287
+ // result: { valid: false, error: "invalid", details: "..." }
288
+
289
+ // PSBT signing and finalization (standalone)
290
+ const signed = wallet.signPsbt(unsignedPsbtBase64);
291
+ const finalized = wallet.finalizePsbt(signedPsbtBase64);
292
+ ```
293
+
294
+ ## API reference
295
+
296
+ ### Standalone functions
297
+
298
+ | Function | Description |
299
+ |----------|-------------|
300
+ | `generateKeys(network)` | Generate a new BIP39 mnemonic and derive xpubs |
301
+ | `restoreKeys(network, mnemonic)` | Restore xpubs from a mnemonic |
302
+ | `checkProxyUrl(url)` | Validate an RGB proxy server URL |
303
+ | `validateConsignmentOffchain(bytes, txid, network)` | Validate an RGB consignment using bundled witness data |
304
+
305
+ ### `WasmInvoice`
306
+
307
+ | Method | Description |
308
+ |--------|-------------|
309
+ | `new(invoiceString)` | Parse and validate an RGB invoice string |
310
+ | `invoiceData()` | Return parsed `InvoiceData` as a JS object |
311
+ | `invoiceString()` | Return the original invoice string |
312
+
313
+ ### `WasmWallet` methods
314
+
315
+ | Method | Async | Description |
316
+ |--------|-------|-------------|
317
+ | `new(walletDataJson)` | no | Create wallet (no IndexedDB restore) |
318
+ | `create(walletDataJson)` | yes | Create wallet with IndexedDB restore; fails if restore fails |
319
+ | `flush()` | yes | Durably commit current wallet state to IndexedDB |
320
+ | `getWalletData()` | no | Return WalletData as JS object |
321
+ | `getAddress()` | no | Get a new Bitcoin address |
322
+ | `getBtcBalance()` | no | Get BTC balance |
323
+ | `getAssetBalance(assetId)` | no | Get balance for an RGB asset |
324
+ | `getAssetMetadata(assetId)` | no | Get metadata for an RGB asset (name, ticker, precision, supply, etc.) |
325
+ | `listAssets(schemas)` | no | List known RGB assets |
326
+ | `listTransfers(assetId?)` | no | List RGB transfers |
327
+ | `listUnspents(settledOnly)` | no | List unspent outputs with RGB allocations |
328
+ | `listTransactions()` | no | List Bitcoin transactions |
329
+ | `goOnline(skipCheck, indexerUrl)` | yes | Connect to an Esplora indexer |
330
+ | `sync(online)` | yes | Sync wallet with indexer |
331
+ | `createUtxosBegin(...)` | yes | Prepare PSBT to create colored UTXOs |
332
+ | `createUtxosEnd(online, psbt, skipSync)` | yes | Broadcast UTXO creation PSBT |
333
+ | `issueAssetNia(ticker, name, precision, amounts)` | no | Issue a Non-Inflatable Asset |
334
+ | `issueAssetIfa(...)` | no | Issue an Inflatable Fungible Asset |
335
+ | `blindReceive(...)` | no | Create a blind receive invoice |
336
+ | `witnessReceive(...)` | no | Create a witness receive invoice |
337
+ | `sendBegin(...)` | yes | Prepare RGB send PSBT |
338
+ | `sendEnd(online, psbt, skipSync)` | yes | Broadcast RGB send PSBT |
339
+ | `sendBtcBegin(...)` | yes | Prepare BTC send PSBT |
340
+ | `sendBtcEnd(online, psbt, skipSync)` | yes | Broadcast BTC send PSBT |
341
+ | `getFeeEstimation(online, blocks)` | yes | Estimate fee rate for target blocks |
342
+ | `drainToBegin(online, addr, destroyAssets, feeRate)` | yes | Prepare drain PSBT |
343
+ | `drainToEnd(online, psbt)` | yes | Broadcast drain PSBT |
344
+ | `inflateBegin(...)` | yes | Prepare IFA inflation PSBT |
345
+ | `inflateEnd(online, psbt)` | yes | Broadcast IFA inflation PSBT |
346
+ | `listUnspentsVanilla(online, minConf, skipSync)` | yes | List non-colored UTXOs |
347
+ | `refresh(online, assetId?, filter, skipSync)` | yes | Refresh pending transfers |
348
+ | `failTransfers(online, batchIdx?, noAssetOnly, skipSync)` | yes | Fail pending transfers |
349
+ | `deleteTransfers(batchIdx?, noAssetOnly)` | no | Delete failed transfers |
350
+ | `signPsbt(psbt)` | no | Sign a PSBT |
351
+ | `finalizePsbt(psbt)` | no | Finalize a signed PSBT |
352
+ | `backup(password)` | no | Create encrypted backup (returns bytes) |
353
+ | `restoreBackup(bytes, password)` | no | Restore from encrypted backup |
354
+ | `backupInfo()` | no | Check if backup is needed |
355
+ | `configureVssBackup(url, storeId, keyHex)` | no | Configure VSS cloud backup |
356
+ | `disableVssBackup()` | no | Disable VSS cloud backup |
357
+ | `vssBackup()` | yes | Upload backup to VSS server |
358
+ | `vssRestoreBackup()` | yes | Restore from VSS server |
359
+ | `vssBackupInfo()` | yes | Query VSS backup status |
360
+
361
+ ## Cargo features
362
+
363
+ | Feature | Default | Description |
364
+ |---------|---------|-------------|
365
+ | `esplora` | yes | Online operations via Esplora HTTP indexer |
366
+ | `camel_case` | yes | camelCase JSON serialization for all types |
367
+
368
+
369
+ ## Running tests
370
+
371
+ ```bash
372
+ # Native unit tests (94 tests)
373
+ cargo test --lib
374
+
375
+ # WASM unit tests (headless Firefox)
376
+ wasm-pack test --headless --firefox --release -- --test keys_wasm
377
+ wasm-pack test --headless --firefox --release -- --test wallet_wasm
378
+
379
+ # Integration tests (requires regtest Docker services)
380
+ cd tests && bash regtest.sh start
381
+ cd .. && wasm-pack test --headless --firefox --release -- --test integration_wasm
382
+ cd tests && bash regtest.sh stop
383
+ ```
384
+
385
+ See [DEV-ENVIRONMENT.md](DEV-ENVIRONMENT.md) for the full regtest infrastructure setup, CI configuration, Docker Compose details, and troubleshooting.
386
+
387
+ ## License
388
+
389
+ MIT
package/package.json CHANGED
@@ -1,6 +1,20 @@
1
1
  {
2
2
  "name": "@kaleidorg/rgb-lib-wasm",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "type": "module",
4
+ "description": "RGB wallet library WASM bindings for browsers",
5
+ "version": "1.0.0-ks.1",
6
+ "files": [
7
+ "rgb_lib_wasm_bindings_bg.wasm",
8
+ "rgb_lib_wasm_bindings.js",
9
+ "rgb_lib_wasm_bindings.d.ts"
10
+ ],
11
+ "main": "rgb_lib_wasm_bindings.js",
12
+ "types": "rgb_lib_wasm_bindings.d.ts",
13
+ "sideEffects": [
14
+ "./snippets/*"
15
+ ],
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "https://github.com/kaleidoswap/rgb-lib-wasm.git"
19
+ }
6
20
  }