@utexo/rgb-sdk 1.0.4 → 1.0.5

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.
Files changed (37) hide show
  1. package/Readme.md +261 -299
  2. package/cli/README.md +348 -0
  3. package/cli/commands/address.mjs +16 -0
  4. package/cli/commands/blindreceive.mjs +15 -0
  5. package/cli/commands/btcbalance.mjs +11 -0
  6. package/cli/commands/createlightninginvoice.mjs +14 -0
  7. package/cli/commands/createutxos.mjs +13 -0
  8. package/cli/commands/decodergbinvoice.mjs +9 -0
  9. package/cli/commands/generate_keys.mjs +35 -0
  10. package/cli/commands/getlightningreceiverequest.mjs +10 -0
  11. package/cli/commands/getlightningsendrequest.mjs +10 -0
  12. package/cli/commands/getonchainsendstatus.mjs +20 -0
  13. package/cli/commands/listassets.mjs +11 -0
  14. package/cli/commands/listtransfers.mjs +10 -0
  15. package/cli/commands/listunspents.mjs +10 -0
  16. package/cli/commands/onchainreceive.mjs +16 -0
  17. package/cli/commands/onchainsend.mjs +11 -0
  18. package/cli/commands/onchainsendbegin.mjs +9 -0
  19. package/cli/commands/onchainsendend.mjs +9 -0
  20. package/cli/commands/paylightninginvoice.mjs +11 -0
  21. package/cli/commands/paylightninginvoicebegin.mjs +10 -0
  22. package/cli/commands/paylightninginvoiceend.mjs +9 -0
  23. package/cli/commands/refresh.mjs +9 -0
  24. package/cli/commands/send.mjs +31 -0
  25. package/cli/commands/sign-psbt.mjs +12 -0
  26. package/cli/commands/signpsbt.mjs +10 -0
  27. package/cli/commands/witnessreceive.mjs +15 -0
  28. package/cli/generate_keys.mjs +66 -0
  29. package/cli/run.mjs +291 -0
  30. package/cli/utils.mjs +220 -0
  31. package/dist/index.cjs +1606 -121
  32. package/dist/index.cjs.map +1 -1
  33. package/dist/index.d.mts +1235 -145
  34. package/dist/index.d.ts +1235 -145
  35. package/dist/index.mjs +1592 -116
  36. package/dist/index.mjs.map +1 -1
  37. package/package.json +21 -7
package/Readme.md CHANGED
@@ -1,11 +1,13 @@
1
1
  # @utexo/rgb-sdk Overview
2
2
 
3
+ > **Beta notice:** This package is currently in beta. Please test thoroughly in development environments before using in production.
4
+
3
5
  This is the underlying SDK used by RGB client applications. It provides a complete set of TypeScript/Node.js bindings for managing RGB-based transfers using **rgb-protocol libraries**
4
6
 
5
7
  ⚠️ **Security Notice**
6
8
  If you're migrating from the legacy `rgb-sdk` (which relied on a remote RGB Node server), be aware that wallet metadata such as xpubs may have been exposed and this cannot be undone.
7
9
 
8
- If you're upgrading from `rgb-sdk` to `@utexo/rgb-sdk`, see the **[Migration Guide](./README.md#migration-guide-rgb-sdk--utexorgb-sdk)** for step-by-step instructions on moving your wallet state to local storage.
10
+ If you're upgrading from `rgb-sdk` to `@utexo/rgb-sdk`, see the **[Migration Guide](./MIGRATION.md)** for step-by-step instructions on moving your wallet state to local storage.
9
11
 
10
12
  For full details on security implications and recommended actions, please read **[SECURITY.md](./SECURITY.md)**.
11
13
 
@@ -24,54 +26,84 @@ With this SDK, developers can:
24
26
 
25
27
  ---
26
28
 
27
- ## ⚙️ Capabilities of `@utexo/rgb-sdk` (via `WalletManager`)
28
-
29
- | Method | Description |
30
- |--------|-------------|
31
- | `generateKeys(network?)` | Generate new wallet keys (mnemonic, xpubs, master fingerprint) - top-level function |
32
- | `restoreFromBackup(params)` | High-level function to restore wallet from backup - top-level function |
33
- | `deriveKeysFromMnemonic(network, mnemonic)` | Derive wallet keys (xpub/xpriv) from existing mnemonic |
34
- | `deriveKeysFromSeed(network, seed)` | Derive wallet keys (xpub/xpriv) directly from a BIP39 seed |
35
- | `registerWallet()` | Register wallet (synchronous) |
36
- | `getBtcBalance()` | Get on-chain BTC balance (synchronous) |
37
- | `getAddress()` | Get a derived deposit address (synchronous) |
29
+ ## ⚙️ Capabilities of `@utexo/rgb-sdk` (via `UTEXOWallet`)
30
+
31
+ The primary wallet class is **`UTEXOWallet`**: initialize with a mnemonic (or seed) and optional `{ network, dataDir }`, then call `await wallet.initialize()` before use. It combines standard RGB operations with UTEXO features (Lightning, on-chain deposit/withdrawal).
32
+
33
+ | Method / Function | Description |
34
+ |-------------------|-------------|
35
+ | `generateKeys(network?)` | Generate new wallet keys (mnemonic, xpubs, master fingerprint) top-level function |
36
+ | `restoreUtxoWalletFromBackup({ backupPath, password, targetDir })` | Restore UTEXO wallet from file backup (layer1 + utexo) top-level function |
37
+ | `restoreUtxoWalletFromVss({ mnemonic, targetDir, config?, vssServerUrl? })` | Restore UTEXO wallet from VSS cloud backup – top-level function |
38
+ | `deriveKeysFromMnemonic(network, mnemonic)` | Derive wallet keys from existing mnemonic |
39
+ | `deriveKeysFromSeed(network, seed)` | Derive wallet keys from BIP39 seed |
40
+ | `getAddress()` | Get deposit address (async) |
41
+ | `getBtcBalance()` | Get on-chain BTC balance (async) |
42
+ | `getXpub()` | Get vanilla and colored xpubs |
43
+ | `getNetwork()` | Get current network |
38
44
  | `listUnspents()` | List unspent UTXOs |
39
- | `listAssets()` | List RGB assets held (synchronous) |
45
+ | `listAssets()` | List RGB assets held |
40
46
  | `getAssetBalance(assetId)` | Get balance for a specific asset |
41
- | `createUtxosBegin({ upTo, num, size, feeRate })` | Start creating new UTXOs |
42
- | `createUtxosEnd({ signedPsbt, skipSync? })` | Finalize UTXO creation with a signed PSBT |
47
+ | `createUtxos({ num?, size?, upTo? })` | Create UTXOs (async; combines begin, sign, end; feeRate defaults to 1) |
48
+ | `createUtxosBegin({ upTo?, num?, size? })` | Start creating UTXOs (returns unsigned PSBT) |
49
+ | `createUtxosEnd({ signedPsbt, skipSync? })` | Finalize UTXO creation with signed PSBT |
43
50
  | `blindReceive({ assetId, amount, minConfirmations?, durationSeconds? })` | Generate blinded UTXO for receiving |
44
51
  | `witnessReceive({ assetId, amount, minConfirmations?, durationSeconds? })` | Generate witness UTXO for receiving |
45
- | `issueAssetNia({...})` | Issue a new Non-Inflationary Asset |
46
- | `signPsbt(psbt, mnemonic?)` | Sign PSBT using mnemonic and BDK (async) |
47
- | `signMessage(message, options?)` | Produce a Schnorr signature for an arbitrary message |
48
- | `verifyMessage(message, signature, options?)` | Verify Schnorr message signatures using wallet keys or provided public key |
52
+ | `issueAssetNia({ ticker, name, amounts, precision })` | Issue a new Non-Inflationary Asset |
53
+ | `send({ invoice, assetId, amount, witnessData? })` | Complete send (begin sign end; use `witnessData` for witness invoices; feeRate defaults to 1) |
54
+ | `sendBegin({ invoice, assetId, amount, witnessData?, ... })` | Prepare transfer (returns unsigned PSBT) |
55
+ | `sendEnd({ signedPsbt, skipSync? })` | Complete transfer with signed PSBT |
56
+ | `signPsbt(psbt, mnemonic?)` | Sign PSBT using wallet mnemonic (async) |
49
57
  | `refreshWallet()` | Sync and refresh wallet state |
50
- | `syncWallet()` | Trigger wallet sync without additional refresh logic |
51
- | `listTransactions()` | List BTC-level transactions (synchronous) |
52
- | `listTransfers(assetId?)` | List RGB transfer history for asset (synchronous) |
58
+ | `syncWallet()` | Trigger wallet sync |
59
+ | `listTransactions()` | List BTC-level transactions |
60
+ | `listTransfers(assetId?)` | List RGB transfer history for asset |
53
61
  | `failTransfers(params)` | Mark waiting transfers as failed |
54
- | `deleteTransfers(params)` | Delete transfers from wallet |
55
- | `sendBegin(...)` | Prepare a transfer (build unsigned PSBT) |
56
- | `sendEnd({ signedPsbt, skipSync? })` | Submit signed PSBT to complete transfer |
57
- | `sendBtcBegin(params)` | Begin Bitcoin send operation (returns PSBT) |
58
- | `sendBtcEnd(params)` | Complete Bitcoin send operation with signed PSBT |
59
- | `send(...)` | Complete send operation: begin sign → end |
60
- | `createBackup({ backupPath, password })` | Create an encrypted wallet backup (backupPath required, filename includes master fingerprint) |
61
- | `restoreFromBackup({ backupFilePath, password, dataDir })` | Restore wallet state from a backup file (top-level function, call before creating wallet) |
62
+ | `createBackup({ backupPath, password })` | Create encrypted backup (layer1 + utexo in one folder) |
63
+ | `vssBackup(config?, mnemonic?)` | Backup to VSS (config optional; built from mnemonic + default server URL) |
64
+ | `vssBackupInfo(config?, mnemonic?)` | Get VSS backup info |
65
+ | *On-chain* | |
66
+ | `onchainReceive(params)` | Generate invoice for depositing from mainnet to UTEXO |
67
+ | `onchainSendBegin(params)` | Start on-chain withdraw (returns unsigned PSBT) |
68
+ | `onchainSendEnd(params)` | Finalize on-chain withdraw with signed PSBT |
69
+ | `onchainSend(params, mnemonic?)` | Complete on-chain withdraw (begin sign end) |
70
+ | `getOnchainSendStatus(invoice)` | Get status of on-chain withdraw |
71
+ | *Lightning* | |
72
+ | `createLightningInvoice(params)` | Create Lightning invoice for receiving |
73
+ | `payLightningInvoiceBegin(params)` | Start Lightning payment (returns unsigned PSBT) |
74
+ | `payLightningInvoiceEnd(params)` | Finalize Lightning payment with signed PSBT |
75
+ | `payLightningInvoice(params, mnemonic?)` | Complete Lightning payment (begin → sign → end) |
76
+ | `getLightningSendRequest(lnInvoice)` | Get status of Lightning send |
77
+ | `getLightningReceiveRequest(lnInvoice)` | Get status of Lightning receive |
78
+ | `listLightningPayments()` | List Lightning payments |
79
+
80
+ **Examples:** [examples/](./examples/). **CLI (dev tools):** [cli/](./cli/).
81
+
82
+ ```javascript
83
+ const { UTEXOWallet } = require('@utexo/rgb-sdk');
84
+
85
+ const wallet = new UTEXOWallet('your twelve word mnemonic phrase here ...', { network: 'testnet' });
86
+ await wallet.initialize();
87
+
88
+ const address = await wallet.getAddress();
89
+ const balance = await wallet.getBtcBalance();
90
+ const assets = await wallet.listAssets();
91
+ // ... onchainReceive(), onchainSend(), createLightningInvoice(), payLightningInvoice(), etc.
92
+
93
+ await wallet.dispose();
94
+ ```
62
95
 
63
96
  ---
64
97
 
65
98
  ## 🧩 Notes for Custom Integration
66
99
 
67
- - All RGB operations are handled locally using the `RGBLibClient` class, which wraps the native `rgb-lib` library.
68
- - The `signPsbt` method demonstrates how to integrate a signing flow using `bdk-wasm`. This can be replaced with your own HSM or hardware wallet integration if needed.
69
- - By using this SDK, developers have full control over:
70
- - Transfer orchestration
71
- - UTXO selection
100
+ - All RGB operations are handled locally; `RGBLibClient` wraps the native `rgb-lib` library via internal clients.
101
+ - The `signPsbt` method uses the wallet mnemonic for signing; it can be replaced with your own HSM or hardware wallet flow if needed.
102
+ - By using this SDK with `UTEXOWallet`, you have full control over:
103
+ - Transfer orchestration (send, witnessReceive, blindReceive)
104
+ - UTXO creation and sync
72
105
  - Invoice lifecycle
73
- - Signing policy
74
- - Wallet data storage (via `dataDir` parameter)
106
+ - Wallet data storage (via `dataDir` in options)
75
107
 
76
108
  This pattern enables advanced use cases, such as:
77
109
 
@@ -92,19 +124,23 @@ This SDK uses `rgb-protocol libraries`. All operations are performed locally.
92
124
 
93
125
  The SDK uses default endpoints for RGB transport and Bitcoin indexing. These are automatically used if not specified:
94
126
 
95
- **Transport Endpoint** (RGB protocol communication):
127
+ **Transport Endpoints** (RGB protocol communication):
96
128
 
97
- - Default: `rpcs://proxy.iriswallet.com/0.2/json-rpc`
129
+ - **Mainnet**: `rpcs://rgb-proxy-mainnet.utexo.com/json-rpc`
130
+ - **Testnet**: `rpcs://rgb-proxy-testnet3.utexo.com/json-rpc`
131
+ - **Testnet4**: `rpcs://proxy.iriswallet.com/0.2/json-rpc`
132
+ - **Signet**: `rpcs://rgb-proxy-utexo.utexo.com/json-rpc`
133
+ - **Regtest**: `rpcs://proxy.iriswallet.com/0.2/json-rpc`
98
134
 
99
135
  **Indexer URLs** (Bitcoin blockchain data):
100
136
 
101
137
  - **Mainnet**: `ssl://electrum.iriswallet.com:50003`
102
138
  - **Testnet**: `ssl://electrum.iriswallet.com:50013`
103
139
  - **Testnet4**: `ssl://electrum.iriswallet.com:50053`
104
- - **Signet**: `tcp://46.224.75.237:50001`
140
+ - **Signet**: `https://esplora-api.utexo.com`
105
141
  - **Regtest**: `tcp://regtest.thunderstack.org:50001`
106
142
 
107
- These defaults can be overridden by providing `transportEndpoint` and `indexerUrl` parameters when initializing `WalletManager`.
143
+ UTEXOWallet uses network (`testnet` / `mainnet`) that define indexer and transport endpoints internally.
108
144
 
109
145
  ### Installation
110
146
 
@@ -112,141 +148,30 @@ These defaults can be overridden by providing `transportEndpoint` and `indexerUr
112
148
  npm install @utexo/rgb-sdk
113
149
  ```
114
150
 
115
- ### Browser Compatibility
116
-
117
- This SDK is browser-compatible but requires polyfills for Node.js built-in modules. The SDK uses WebAssembly modules and dynamically loads dependencies based on the environment.
118
-
119
- #### Required Polyfills
120
-
121
- For React/Next.js applications, you'll need to configure webpack to polyfill Node.js modules. Install the required polyfills:
122
-
123
- ```bash
124
- npm install --save-dev crypto-browserify stream-browserify buffer process path-browserify
125
- ```
126
-
127
- #### CRACO Configuration (React with Create React App)
128
-
129
- If you're using Create React App with CRACO, create a `craco.config.js` file:
130
-
131
- ```javascript
132
- const path = require('path');
133
- const webpack = require('webpack');
134
-
135
- module.exports = {
136
- webpack: {
137
- alias: {
138
- "@": path.resolve(__dirname, "src/"),
139
- },
140
- configure: (webpackConfig) => {
141
- webpackConfig.resolve = webpackConfig.resolve || {};
142
- webpackConfig.resolve.fallback = {
143
- ...(webpackConfig.resolve.fallback || {}),
144
- crypto: require.resolve('crypto-browserify'),
145
- 'node:crypto': require.resolve('crypto-browserify'),
146
- stream: require.resolve('stream-browserify'),
147
- buffer: require.resolve('buffer'),
148
- process: require.resolve('process/browser'),
149
- path: require.resolve('path-browserify'),
150
- 'node:path': require.resolve('path-browserify'),
151
- fs: false,
152
- module: false,
153
- };
154
-
155
- // WASM rule for .wasm files
156
- const wasmRule = { test: /\.wasm$/, type: 'webassembly/sync' };
157
- const oneOf = webpackConfig.module?.rules?.find(r => Array.isArray(r.oneOf))?.oneOf;
158
- if (oneOf) {
159
- const assetIdx = oneOf.findIndex(r => r.type === 'asset/resource');
160
- if (assetIdx >= 0) oneOf.splice(assetIdx, 0, wasmRule);
161
- else oneOf.unshift(wasmRule);
162
- } else {
163
- webpackConfig.module = webpackConfig.module || {};
164
- webpackConfig.module.rules = [wasmRule, ...(webpackConfig.module.rules || [])];
165
- }
166
-
167
- webpackConfig.experiments = {
168
- ...webpackConfig.experiments,
169
- asyncWebAssembly: true,
170
- topLevelAwait: true,
171
- syncWebAssembly: true,
172
- layers: true,
173
- };
174
-
175
- webpackConfig.plugins = (webpackConfig.plugins || []).concat([
176
- new webpack.ProvidePlugin({
177
- Buffer: ['buffer', 'Buffer'],
178
- process: ['process'],
179
- }),
180
- ]);
181
-
182
- return webpackConfig;
183
- },
184
- },
185
- };
186
- ```
187
-
188
- #### Dynamic Import in Browser
189
-
190
- Use dynamic import to ensure WASM modules load correctly in browser environments:
191
-
192
- ```javascript
193
- // Dynamic import ensures the WASM/glue load together
194
- const sdk = await import('@utexo/rgb-sdk');
195
-
196
- const { WalletManager, generateKeys } = sdk;
197
-
198
- // Use the SDK normally
199
- const keys = generateKeys('testnet');
200
- const wallet = new WalletManager({
201
- xpubVan: keys.accountXpubVanilla,
202
- xpubCol: keys.accountXpubColored,
203
- masterFingerprint: keys.masterFingerprint,
204
- mnemonic: keys.mnemonic,
205
- network: 'testnet',
206
- transportEndpoint: 'rpcs://proxy.iriswallet.com/0.2/json-rpc',
207
- indexerUrl: 'ssl://electrum.iriswallet.com:50013'
208
- });
209
- ```
210
-
211
- ### Important: WASM Module Support
151
+ ### Node.js only
212
152
 
213
- This SDK uses WebAssembly modules for cryptographic operations. When running scripts, you may need to use the `--experimental-wasm-modules` flag:
214
-
215
- ```bash
216
- node --experimental-wasm-modules your-script.js
217
- ```
218
-
219
- **Note**: All npm scripts in this project already include this flag automatically. For browser environments, see the Browser Compatibility section above.
153
+ This SDK is designed for **Node.js** and is not browser-compatible. Use it in Node.js applications, scripts, and backends.
220
154
 
221
155
  ### Basic Usage
222
156
 
223
157
  ```javascript
224
- const { WalletManager, generateKeys } = require('@utexo/rgb-sdk');
158
+ const { UTEXOWallet, generateKeys } = require('@utexo/rgb-sdk');
225
159
 
226
- // 1. Generate wallet keys (synchronous)
227
- const keys = generateKeys('testnet');
228
- console.log('Master Fingerprint:', keys.masterFingerprint);
160
+ // 1. Generate wallet keys (async)
161
+ const keys = await generateKeys('testnet');
229
162
  console.log('Mnemonic:', keys.mnemonic); // Store securely!
230
163
 
231
- // 2. Initialize wallet (constructor-based)
232
- const wallet = new WalletManager({
233
- xpubVan: keys.accountXpubVanilla,
234
- xpubCol: keys.accountXpubColored,
235
- masterFingerprint: keys.masterFingerprint,
236
- mnemonic: keys.mnemonic,
237
- network: 'testnet',
238
- transportEndpoint: 'rpcs://proxy.iriswallet.com/0.2/json-rpc',
239
- indexerUrl: 'ssl://electrum.iriswallet.com:50013',
240
- dataDir: './wallet-data' // Optional: defaults to temp directory
241
- });
164
+ // 2. Create and initialize UTEXO wallet
165
+ const wallet = new UTEXOWallet(keys.mnemonic, { network: 'testnet' });
166
+ await wallet.initialize();
242
167
 
243
- // 3. Register wallet (synchronous)
244
- const { address } = wallet.registerWallet();
168
+ // 3. Get address and balance
169
+ const address = await wallet.getAddress();
245
170
  console.log('Wallet address:', address);
171
+ const balance = await wallet.getBtcBalance();
172
+ console.log('BTC balance:', balance);
246
173
 
247
- // 4. Check balance (synchronous)
248
- const balance = wallet.getBtcBalance();
249
- console.log('BTC Balance:', balance);
174
+ await wallet.dispose();
250
175
  ```
251
176
 
252
177
  ---
@@ -256,61 +181,50 @@ console.log('BTC Balance:', balance);
256
181
  ### Wallet Initialization
257
182
 
258
183
  ```javascript
259
- const { WalletManager, generateKeys, restoreFromBackup } = require('@utexo/rgb-sdk');
184
+ const { UTEXOWallet, generateKeys, restoreUtxoWalletFromBackup, restoreUtxoWalletFromVss } = require('@utexo/rgb-sdk');
260
185
 
261
- // Generate new wallet keys (synchronous)
262
- const keys = generateKeys('testnet');
186
+ // Generate new wallet keys (async)
187
+ const keys = await generateKeys('testnet');
263
188
 
264
- // Initialize wallet with keys (constructor-based - recommended)
265
- const wallet = new WalletManager({
266
- xpubVan: keys.accountXpubVanilla,
267
- xpubCol: keys.accountXpubColored,
268
- masterFingerprint: keys.masterFingerprint,
269
- mnemonic: keys.mnemonic,
270
- network: 'testnet', // 'mainnet', 'testnet', 'signet', or 'regtest'
271
- transportEndpoint: 'rpcs://proxy.iriswallet.com/0.2/json-rpc',
272
- indexerUrl: 'ssl://electrum.iriswallet.com:50013',
273
- dataDir: './wallet-data' // Optional: defaults to temp directory
274
- });
189
+ // Initialize UTEXO wallet with mnemonic
190
+ const wallet = new UTEXOWallet(keys.mnemonic, { network: 'testnet' });
191
+ await wallet.initialize();
275
192
 
276
- // Register wallet (synchronous)
277
- wallet.registerWallet();
193
+ // Optional: use dataDir for persistent storage (same layout as restore)
194
+ const walletWithDir = new UTEXOWallet(keys.mnemonic, { network: 'testnet', dataDir: './wallet-data' });
195
+ await walletWithDir.initialize();
278
196
 
279
- // Alternative: Restore wallet from backup (must be called before creating wallet)
280
- restoreFromBackup({
281
- backupFilePath: './backup/abc123.backup',
197
+ // Restore from file backup (layer1 + utexo in one folder)
198
+ const { targetDir } = restoreUtxoWalletFromBackup({
199
+ backupPath: './backup-folder',
282
200
  password: 'your-password',
283
- dataDir: './restored-wallet-data'
201
+ targetDir: './restored-wallet',
284
202
  });
203
+ const restoredWallet = new UTEXOWallet(keys.mnemonic, { dataDir: targetDir, network: 'testnet' });
204
+ await restoredWallet.initialize();
285
205
 
286
- // Then create wallet pointing to restored directory
287
- const restoredWallet = new WalletManager({
288
- xpubVan: keys.accountXpubVanilla,
289
- xpubCol: keys.accountXpubColored,
290
- masterFingerprint: keys.masterFingerprint,
206
+ // Restore from VSS (mnemonic required; vssServerUrl optional, uses default)
207
+ const { targetDir: vssDir } = await restoreUtxoWalletFromVss({
291
208
  mnemonic: keys.mnemonic,
292
- network: 'testnet',
293
- dataDir: './restored-wallet-data' // Point to restored directory
209
+ targetDir: './restored-from-vss',
294
210
  });
211
+ const fromVss = new UTEXOWallet(keys.mnemonic, { dataDir: vssDir, network: 'testnet' });
212
+ await fromVss.initialize();
295
213
  ```
296
214
 
297
215
  ### UTXO Management
298
216
 
299
217
  ```javascript
300
- // Step 1: Begin UTXO creation
301
- const psbt = wallet.createUtxosBegin({
302
- upTo: true,
303
- num: 5,
304
- size: 1000,
305
- feeRate: 1
306
- });
218
+ // Option 1: Create UTXOs in one call (begin → sign → end)
219
+ const count = await wallet.createUtxos({ num: 5, size: 1000 });
220
+ await wallet.syncWallet();
221
+ console.log(`Created ${count} UTXOs`);
307
222
 
308
- // Step 2: Sign the PSBT (async operation)
223
+ // Option 2: Begin/end flow for custom signing
224
+ const psbt = await wallet.createUtxosBegin({ num: 5, size: 1000 });
309
225
  const signedPsbt = await wallet.signPsbt(psbt);
310
-
311
- // Step 3: Finalize UTXO creation
312
- const utxosCreated = wallet.createUtxosEnd({ signedPsbt });
313
- console.log(`Created ${utxosCreated} UTXOs`);
226
+ const utxosCreated = await wallet.createUtxosEnd({ signedPsbt });
227
+ await wallet.syncWallet();
314
228
  ```
315
229
 
316
230
  ### Asset Issuance
@@ -330,62 +244,125 @@ console.log('Asset issued:', asset.asset?.assetId);
330
244
  ### Asset Transfers
331
245
 
332
246
  ```javascript
333
- // Create blind receive for receiving wallet
247
+ // Receiver: create blind or witness invoice
334
248
  const receiveData = receiverWallet.blindReceive({
335
249
  assetId: assetId,
336
250
  amount: 100,
337
- minConfirmations: 3, // Optional, default: 3
338
- durationSeconds: 2000 // Optional, default: 2000
251
+ minConfirmations: 3,
252
+ durationSeconds: 2000
339
253
  });
254
+ // For witness invoices, sender must pass witnessData when sending
255
+ const witnessData = await receiverWallet.witnessReceive({ assetId, amount: 50 });
340
256
 
341
- // Step 1: Begin asset transfer
342
- const sendPsbt = senderWallet.sendBegin({
257
+ // Sender: Option 1 complete send in one call
258
+ const sendResult = await senderWallet.send({
343
259
  invoice: receiveData.invoice,
344
- feeRate: 1,
345
- minConfirmations: 1
260
+ assetId,
261
+ amount: 100
262
+ });
263
+ // For witness invoice:
264
+ await senderWallet.send({
265
+ invoice: witnessData.invoice,
266
+ assetId,
267
+ amount: 50,
268
+ witnessData: { amountSat: 1000 }
346
269
  });
347
270
 
348
- // Step 2: Sign the PSBT (async operation)
271
+ // Sender: Option 2 begin/end flow for custom signing
272
+ const sendPsbt = await senderWallet.sendBegin({
273
+ invoice: receiveData.invoice,
274
+ assetId,
275
+ amount: 100
276
+ });
349
277
  const signedSendPsbt = await senderWallet.signPsbt(sendPsbt);
278
+ await senderWallet.sendEnd({ signedPsbt: signedSendPsbt });
350
279
 
351
- // Step 3: Finalize transfer
352
- const sendResult = senderWallet.sendEnd({
353
- signedPsbt: signedSendPsbt,
354
- skipSync: false // Optional, default: false
355
- });
280
+ // Refresh both wallets and list transfers
281
+ await senderWallet.refreshWallet();
282
+ await receiverWallet.refreshWallet();
283
+ const transfers = await receiverWallet.listTransfers(assetId);
284
+ ```
356
285
 
357
- // Alternative: Complete send in one call
358
- const sendResult2 = await senderWallet.send({
359
- invoice: receiveData.invoice,
360
- feeRate: 1,
361
- minConfirmations: 1
286
+ ### On-chain receive/send
287
+
288
+ ```javascript
289
+ const { UTEXOWallet } = require('@utexo/rgb-sdk');
290
+
291
+ const sender = new UTEXOWallet("test mnemonic sender", { network: 'testnet' });
292
+ const receiver = new UTEXOWallet("test mnemonic receiver", { network: 'testnet' });
293
+ await sender.initialize();
294
+ await receiver.initialize();
295
+
296
+ // 1) Receiver: onchainReceive – create mainnet invoice for deposit
297
+ const { invoice } = await receiver.onchainReceive({
298
+ assetId: "rgb:WPRv95Nj-icdrgPp-zpQhIp_-2TyJ~Ge-k~FvuMZ-~vVnkA0",
299
+ amount: 5,
300
+ });
301
+
302
+ // 2) Sender: onchainSend – pay that mainnet invoice from UTEXO
303
+ const sendResult = await sender.onchainSend({ invoice });
304
+ console.log('Onchain send result:', sendResult);
305
+
306
+ await receiver.refreshWallet()
307
+ await sender.refreshWallet()
308
+
309
+ // wait 3 confirmation blocks
310
+
311
+ await receiver.refreshWallet()
312
+ await sender.refreshWallet()
313
+
314
+ const status = await receiver.getOnchainSendStatus(invoice)
315
+ console.log(status)
316
+
317
+ ```
318
+
319
+ ### Lightning receive/send
320
+
321
+ ```javascript
322
+ const { UTEXOWallet } = require('@utexo/rgb-sdk');
323
+
324
+ const sender = new UTEXOWallet("test mnemonic sender", { network: 'testnet' });
325
+ const receiver = new UTEXOWallet("test mnemonic receiver", { network: 'testnet' });
326
+ await sender.initialize();
327
+ await receiver.initialize();
328
+
329
+ // 1) Receiver: createLightningInvoice – create Lightning invoice for receiving
330
+ const assetId = "rgb:WPRv95Nj-icdrgPp-zpQhIp_-2TyJ~Ge-k~FvuMZ-~vVnkA0";
331
+ const { lnInvoice } = await receiver.createLightningInvoice({
332
+ asset: { assetId, amount: 5 },
362
333
  });
363
334
 
364
- // Refresh both wallets to sync the transfer
365
- senderWallet.refreshWallet();
366
- receiverWallet.refreshWallet();
335
+ // 2) Sender: payLightningInvoice pay that Lightning invoice from UTEXO
336
+ const sendResult = await sender.payLightningInvoice({ lnInvoice, assetId, amount: 5 });
337
+ console.log('Lightning send result:', sendResult);
338
+
339
+ await receiver.refreshWallet();
340
+ await sender.refreshWallet();
341
+
342
+ const status = await sender.getLightningSendRequest(lnInvoice);
343
+ console.log(status);
367
344
  ```
368
345
 
369
346
  ### Balance and Asset Management
370
347
 
371
348
  ```javascript
372
- // Get BTC balance (synchronous)
373
- const btcBalance = wallet.getBtcBalance();
349
+ // Get BTC balance (async)
350
+ const btcBalance = await wallet.getBtcBalance();
374
351
 
375
- // List all assets (synchronous)
376
- const assets = wallet.listAssets();
352
+ // List all assets
353
+ const assets = await wallet.listAssets();
377
354
 
378
355
  // Get specific asset balance
379
- const assetBalance = wallet.getAssetBalance(assetId);
356
+ const assetBalance = await wallet.getAssetBalance(assetId);
380
357
 
381
358
  // List unspent UTXOs
382
- const unspents = wallet.listUnspents();
359
+ const unspents = await wallet.listUnspents();
383
360
 
384
- // List transactions (synchronous)
385
- const transactions = wallet.listTransactions();
361
+ // List transactions
362
+ const transactions = await wallet.listTransactions();
386
363
 
387
- // List transfers for specific asset (synchronous)
388
- const transfers = wallet.listTransfers(assetId);
364
+ // List transfers for specific asset
365
+ const transfers = await wallet.listTransfers(assetId);
389
366
  ```
390
367
 
391
368
  ---
@@ -393,50 +370,31 @@ const transfers = wallet.listTransfers(assetId);
393
370
  ## Setup wallet and issue asset
394
371
 
395
372
  ```javascript
396
- const { WalletManager, generateKeys } = require('@utexo/rgb-sdk');
373
+ const { UTEXOWallet, generateKeys } = require('@utexo/rgb-sdk');
397
374
 
398
375
  async function demo() {
399
- // 1. Generate and initialize wallet
400
- const keys = generateKeys('testnet');
401
- const wallet = new WalletManager({
402
- xpubVan: keys.accountXpubVanilla,
403
- xpubCol: keys.accountXpubColored,
404
- masterFingerprint: keys.masterFingerprint,
405
- mnemonic: keys.mnemonic,
406
- network: 'testnet',
407
- transportEndpoint: 'rpcs://proxy.iriswallet.com/0.2/json-rpc',
408
- indexerUrl: 'ssl://electrum.iriswallet.com:50013'
409
- });
376
+ const keys = await generateKeys('testnet');
377
+ const wallet = new UTEXOWallet(keys.mnemonic, { network: 'testnet' });
378
+ await wallet.initialize();
410
379
 
411
- // 2. Register wallet (synchronous)
412
- const { address } = wallet.registerWallet();
380
+ const address = await wallet.getAddress();
381
+ const balance = await wallet.getBtcBalance();
413
382
 
414
- // TODO: Send some BTC to this address for fees and UTXO creation
415
- const balance = wallet.getBtcBalance();
416
-
417
- // 4. Create UTXOs
418
- const psbt = wallet.createUtxosBegin({
419
- upTo: true,
420
- num: 5,
421
- size: 1000,
422
- feeRate: 1
423
- });
424
- const signedPsbt = await wallet.signPsbt(psbt); // Async operation
425
- const utxosCreated = wallet.createUtxosEnd({ signedPsbt });
383
+ // Create UTXOs and issue asset
384
+ const count = await wallet.createUtxos({ num: 5, size: 1000 });
385
+ await wallet.syncWallet();
426
386
 
427
- // 5. Issue asset
428
387
  const asset = await wallet.issueAssetNia({
429
- ticker: "DEMO",
430
- name: "Demo Token",
388
+ ticker: 'DEMO',
389
+ name: 'Demo Token',
431
390
  amounts: [1000],
432
391
  precision: 2
433
392
  });
434
393
 
435
- // 6. List assets and balances (synchronous)
436
- const assets = wallet.listAssets();
437
- const assetBalance = wallet.getAssetBalance(asset.asset?.assetId);
394
+ const assets = await wallet.listAssets();
395
+ const assetBalance = await wallet.getAssetBalance(asset.assetId);
438
396
 
439
- // Wallet is ready to send/receive RGB assets
397
+ await wallet.dispose();
440
398
  }
441
399
  ```
442
400
 
@@ -449,8 +407,8 @@ async function demo() {
449
407
  ```javascript
450
408
  const { generateKeys, deriveKeysFromMnemonic } = require('@utexo/rgb-sdk');
451
409
 
452
- // Generate new wallet keys (synchronous)
453
- const keys = generateKeys('testnet');
410
+ // Generate new wallet keys (async)
411
+ const keys = await generateKeys('testnet');
454
412
  const mnemonic = keys.mnemonic; // Sensitive - protect at rest
455
413
 
456
414
  // Store mnemonic securely for later restoration
@@ -477,41 +435,39 @@ const isValid = await verifyMessage({
477
435
 
478
436
  ### Backup and Restore
479
437
 
438
+ > **Backup modes:** UTEXOWallet supports **local (file) backups** (encrypted files on disk) and **VSS backups** (state persisted to a remote Versioned Storage Service). The recommended strategy is to use VSS and invoke `vssBackup()` after any state-changing operation (e.g. UTXO creation, asset issuance, transfers) to ensure the latest state is recoverable;
439
+ >
440
+ > **Concurrency constraint:** Do **not** run restores while any wallet instance is online. At most one instance of a given wallet should ever be connected to the indexer/VSS; before calling any restore function, ensure all instances for that wallet are offline.
441
+
480
442
  ```javascript
481
- const { WalletManager, restoreFromBackup, generateKeys } = require('@utexo/rgb-sdk');
482
-
483
- // Create backup
484
- const keys = generateKeys('testnet');
485
- const wallet = new WalletManager({
486
- xpubVan: keys.accountXpubVanilla,
487
- xpubCol: keys.accountXpubColored,
488
- masterFingerprint: keys.masterFingerprint,
489
- mnemonic: keys.mnemonic,
490
- network: 'testnet'
491
- });
443
+ const { UTEXOWallet, restoreUtxoWalletFromBackup, restoreUtxoWalletFromVss, generateKeys } = require('@utexo/rgb-sdk');
444
+
445
+ const keys = await generateKeys('testnet');
446
+ const wallet = new UTEXOWallet(keys.mnemonic, { network: 'testnet' });
447
+ await wallet.initialize();
492
448
 
493
- // Create backup (filename will be <masterFingerprint>.backup)
494
- const backup = wallet.createBackup({
495
- backupPath: './backups', // Directory must exist
449
+ // File backup (layer1 + utexo in one folder: wallet_<fp>_layer1.backup, wallet_<fp>_utexo.backup)
450
+ const backup = await wallet.createBackup({
451
+ backupPath: './backups',
496
452
  password: 'secure-password'
497
453
  });
498
- console.log('Backup created at:', backup.backupPath);
454
+ console.log('Backup created:', backup.layer1BackupPath, backup.utexoBackupPath);
499
455
 
500
- // Restore wallet from backup (must be called before creating wallet)
501
- restoreFromBackup({
502
- backupFilePath: './backups/abc123.backup',
456
+ // Restore from file backup
457
+ const { targetDir } = restoreUtxoWalletFromBackup({
458
+ backupPath: './backups',
503
459
  password: 'secure-password',
504
- dataDir: './restored-wallet'
460
+ targetDir: './restored-wallet'
505
461
  });
462
+ const restoredWallet = new UTEXOWallet(keys.mnemonic, { dataDir: targetDir, network: 'testnet' });
463
+ await restoredWallet.initialize();
506
464
 
507
- // Create wallet pointing to restored directory
508
- const restoredWallet = new WalletManager({
509
- xpubVan: keys.accountXpubVanilla,
510
- xpubCol: keys.accountXpubColored,
511
- masterFingerprint: keys.masterFingerprint,
465
+ // VSS backup (config optional; built from mnemonic + DEFAULT_VSS_SERVER_URL)
466
+ await wallet.vssBackup();
467
+ // Restore from VSS
468
+ const { targetDir: vssDir } = await restoreUtxoWalletFromVss({
512
469
  mnemonic: keys.mnemonic,
513
- network: 'testnet',
514
- dataDir: './restored-wallet'
470
+ targetDir: './restored-from-vss'
515
471
  });
516
472
  ```
517
473
 
@@ -519,7 +475,13 @@ const restoredWallet = new WalletManager({
519
475
 
520
476
  ## Full Examples
521
477
 
522
- For complete working examples demonstrating all features, see:
478
+ - [new-wallet](examples/new-wallet.mjs) Generate keys and create a new UTEXO wallet
479
+ - [read-wallet](examples/read-wallet.mjs) – Initialize by mnemonic and call getXpub, getNetwork, getAddress, getBtcBalance, listAssets
480
+ - [create-utxos-asset](examples/create-utxos-asset.mjs) – Create UTXOs and issue a NIA asset
481
+ - [transfer](examples/transfer.mjs) – Two wallets: witness + blind receive, refresh, listTransfers (requires ASSET_ID and funded wallets)
482
+ - [onchain-flow](examples/onchain-flow.mjs) – On-chain transfer: receive + send
483
+ - [lightning-flow](examples/lightning-flow.mjs) – Lightning transfer: createLightningInvoice + payLightningInvoice
484
+ - [utexo-vss-backup-restore](examples/utexo-vss-backup-restore.mjs) – VSS backup and restore
485
+ - [utexo-file-backup-restore](examples/utexo-file-backup-restore.mjs) – File backup and restore
523
486
 
524
- - `example-flow.js` - Complete RGB wallet workflow with two wallets, asset issuance, and transfers
525
- - `example-basic-usage.js` - Basic wallet operations and asset management
487
+ See [examples/README.md](examples/README.md) for run commands. CLI: [cli/](cli/).