@utexo/rgb-sdk 1.0.0-beta.8

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 (40) hide show
  1. package/LICENCE +201 -0
  2. package/Readme.md +480 -0
  3. package/cli/README.md +348 -0
  4. package/cli/commands/address.mjs +16 -0
  5. package/cli/commands/blindreceive.mjs +15 -0
  6. package/cli/commands/btcbalance.mjs +11 -0
  7. package/cli/commands/createlightninginvoice.mjs +14 -0
  8. package/cli/commands/createutxos.mjs +13 -0
  9. package/cli/commands/decodergbinvoice.mjs +9 -0
  10. package/cli/commands/generate_keys.mjs +35 -0
  11. package/cli/commands/getlightningreceiverequest.mjs +10 -0
  12. package/cli/commands/getlightningsendrequest.mjs +10 -0
  13. package/cli/commands/getonchainsendstatus.mjs +20 -0
  14. package/cli/commands/listassets.mjs +11 -0
  15. package/cli/commands/listtransfers.mjs +10 -0
  16. package/cli/commands/listunspents.mjs +10 -0
  17. package/cli/commands/onchainreceive.mjs +16 -0
  18. package/cli/commands/onchainsend.mjs +11 -0
  19. package/cli/commands/onchainsendbegin.mjs +9 -0
  20. package/cli/commands/onchainsendend.mjs +9 -0
  21. package/cli/commands/paylightninginvoice.mjs +11 -0
  22. package/cli/commands/paylightninginvoicebegin.mjs +10 -0
  23. package/cli/commands/paylightninginvoiceend.mjs +9 -0
  24. package/cli/commands/refresh.mjs +9 -0
  25. package/cli/commands/send.mjs +31 -0
  26. package/cli/commands/sign-psbt.mjs +12 -0
  27. package/cli/commands/signpsbt.mjs +10 -0
  28. package/cli/commands/witnessreceive.mjs +15 -0
  29. package/cli/data/stage2-receiver.example.json +11 -0
  30. package/cli/data/stage2-sender.example.json +11 -0
  31. package/cli/generate_keys.mjs +66 -0
  32. package/cli/run.mjs +308 -0
  33. package/cli/utils.mjs +220 -0
  34. package/dist/index.cjs +1282 -0
  35. package/dist/index.cjs.map +1 -0
  36. package/dist/index.d.mts +163 -0
  37. package/dist/index.d.ts +163 -0
  38. package/dist/index.mjs +1018 -0
  39. package/dist/index.mjs.map +1 -0
  40. package/package.json +124 -0
package/LICENCE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/Readme.md ADDED
@@ -0,0 +1,480 @@
1
+ # @utexo/rgb-sdk Overview
2
+
3
+ > **Beta notice:** This package is currently in beta. Please test thoroughly in development environments before using in production.
4
+
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**
6
+
7
+ **RGB Protocol**: This SDK uses the [`rgb-lib`](https://github.com/RGB-Tools/rgb-lib) binding library to interact with the RGB protocol. All operations are performed locally, providing full control over wallet data and operations.
8
+
9
+ ---
10
+
11
+ ## 🧰 What You Can Do with This Library
12
+
13
+ With this SDK, developers can:
14
+
15
+ - Generate RGB invoices
16
+ - Create and manage UTXOs
17
+ - Sign PSBTs using local private keys or hardware signing flows
18
+ - Fetch asset balances, transfer status, and other RGB-related state
19
+
20
+ ---
21
+
22
+ ## ⚙️ Capabilities of `@utexo/rgb-sdk` (via `UTEXOWallet`)
23
+
24
+ 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).
25
+
26
+ | Method / Function | Description |
27
+ |-------------------|-------------|
28
+ | `generateKeys(network?)` | Generate new wallet keys (mnemonic, xpubs, master fingerprint) – top-level function |
29
+ | `restoreUtxoWalletFromBackup({ backupPath, password, targetDir })` | Restore UTEXO wallet from file backup (layer1 + utexo) – top-level function |
30
+ | `restoreUtxoWalletFromVss({ mnemonic, targetDir, config?, vssServerUrl? })` | Restore UTEXO wallet from VSS cloud backup – top-level function |
31
+ | `deriveKeysFromMnemonic(network, mnemonic)` | Derive wallet keys from existing mnemonic |
32
+ | `deriveKeysFromSeed(network, seed)` | Derive wallet keys from BIP39 seed |
33
+ | `getAddress()` | Get deposit address (async) |
34
+ | `getBtcBalance()` | Get on-chain BTC balance (async) |
35
+ | `getXpub()` | Get vanilla and colored xpubs |
36
+ | `getNetwork()` | Get current network |
37
+ | `listUnspents()` | List unspent UTXOs |
38
+ | `listAssets()` | List RGB assets held |
39
+ | `getAssetBalance(assetId)` | Get balance for a specific asset |
40
+ | `createUtxos({ num?, size?, upTo? })` | Create UTXOs (async; combines begin, sign, end; feeRate defaults to 1) |
41
+ | `createUtxosBegin({ upTo?, num?, size? })` | Start creating UTXOs (returns unsigned PSBT) |
42
+ | `createUtxosEnd({ signedPsbt, skipSync? })` | Finalize UTXO creation with signed PSBT |
43
+ | `blindReceive({ assetId, amount, minConfirmations?, durationSeconds? })` | Generate blinded UTXO for receiving |
44
+ | `witnessReceive({ assetId, amount, minConfirmations?, durationSeconds? })` | Generate witness UTXO for receiving |
45
+ | `issueAssetNia({ ticker, name, amounts, precision })` | Issue a new Non-Inflationary Asset |
46
+ | `send({ invoice, assetId, amount, witnessData? })` | Complete send (begin → sign → end; use `witnessData` for witness invoices; feeRate defaults to 1) |
47
+ | `sendBegin({ invoice, assetId, amount, witnessData?, ... })` | Prepare transfer (returns unsigned PSBT) |
48
+ | `sendEnd({ signedPsbt, skipSync? })` | Complete transfer with signed PSBT |
49
+ | `signPsbt(psbt, mnemonic?)` | Sign PSBT using wallet mnemonic (async) |
50
+ | `refreshWallet()` | Sync and refresh wallet state |
51
+ | `syncWallet()` | Trigger wallet sync |
52
+ | `listTransactions()` | List BTC-level transactions |
53
+ | `listTransfers(assetId?)` | List RGB transfer history for asset |
54
+ | `failTransfers(params)` | Mark waiting transfers as failed |
55
+ | `createBackup({ backupPath, password })` | Create encrypted backup (layer1 + utexo in one folder) |
56
+ | `vssBackup(config?, mnemonic?)` | Backup to VSS (config optional; built from mnemonic + default server URL) |
57
+ | `vssBackupInfo(config?, mnemonic?)` | Get VSS backup info |
58
+ | *On-chain* | |
59
+ | `onchainReceive(params)` | Generate invoice for depositing from mainnet to UTEXO |
60
+ | `onchainSendBegin(params)` | Start on-chain withdraw (returns unsigned PSBT) |
61
+ | `onchainSendEnd(params)` | Finalize on-chain withdraw with signed PSBT |
62
+ | `onchainSend(params, mnemonic?)` | Complete on-chain withdraw (begin → sign → end) |
63
+ | `getOnchainSendStatus(invoice)` | Get status of on-chain withdraw |
64
+ | *Lightning* | |
65
+ | `createLightningInvoice(params)` | Create Lightning invoice for receiving |
66
+ | `payLightningInvoiceBegin(params)` | Start Lightning payment (returns unsigned PSBT) |
67
+ | `payLightningInvoiceEnd(params)` | Finalize Lightning payment with signed PSBT |
68
+ | `payLightningInvoice(params, mnemonic?)` | Complete Lightning payment (begin → sign → end) |
69
+ | `getLightningSendRequest(lnInvoice)` | Get status of Lightning send |
70
+ | `getLightningReceiveRequest(lnInvoice)` | Get status of Lightning receive |
71
+ | `listLightningPayments()` | List Lightning payments |
72
+
73
+ **Examples:** [examples/](./examples/). **CLI (dev tools):** [cli/](./cli/).
74
+
75
+ ```javascript
76
+ const { UTEXOWallet } = require('@utexo/rgb-sdk');
77
+
78
+ const wallet = new UTEXOWallet('your twelve word mnemonic phrase here ...', { network: 'testnet' });
79
+ await wallet.initialize();
80
+
81
+ const address = await wallet.getAddress();
82
+ const balance = await wallet.getBtcBalance();
83
+ const assets = await wallet.listAssets();
84
+ // ... onchainReceive(), onchainSend(), createLightningInvoice(), payLightningInvoice(), etc.
85
+
86
+ await wallet.dispose();
87
+ ```
88
+
89
+ ---
90
+
91
+ ## 🧩 Notes for Custom Integration
92
+
93
+ - All RGB operations are handled locally; `RGBLibClient` wraps the native `rgb-lib` library via internal clients.
94
+ - The `signPsbt` method uses the wallet mnemonic for signing; it can be replaced with your own HSM or hardware wallet flow if needed.
95
+ - By using this SDK with `UTEXOWallet`, you have full control over:
96
+ - Transfer orchestration (send, witnessReceive, blindReceive)
97
+ - UTXO creation and sync
98
+ - Invoice lifecycle
99
+ - Wallet data storage (via `dataDir` in options)
100
+
101
+ This pattern enables advanced use cases, such as:
102
+
103
+ - Integrating with third-party identity/auth layers
104
+ - Applying custom fee logic or batching
105
+ - Implementing compliance and audit tracking
106
+ - Full local wallet management without external server dependencies
107
+
108
+ ---
109
+
110
+ ## Getting Started
111
+
112
+ ### Prerequisites
113
+
114
+ This SDK uses `rgb-protocol libraries`. All operations are performed locally.
115
+
116
+ ### Default Endpoints
117
+
118
+ The SDK uses default endpoints for RGB transport and Bitcoin indexing. These are automatically used if not specified:
119
+
120
+ **Transport Endpoints** (RGB protocol communication):
121
+
122
+ - **UTEXO**: `rpcs://rgb-proxy-utexo.utexo.com/json-rpc`
123
+ - **Mainnet**: `rpcs://rgb-proxy-mainnet.utexo.com/json-rpc`
124
+ - **Testnet**: `rpcs://rgb-proxy-testnet3.utexo.com/json-rpc`
125
+ - **Testnet4**: `rpcs://proxy.iriswallet.com/0.2/json-rpc`
126
+ - **Signet**: `rpcs://proxy.iriswallet.com/0.2/json-rpc`
127
+ - **Regtest**: `rpcs://proxy.iriswallet.com/0.2/json-rpc`
128
+
129
+ **Indexer URLs** (Bitcoin blockchain data):
130
+
131
+ - **UTEXO**: `https://esplora-api.utexo.com`
132
+ - **Mainnet**: `ssl://electrum.iriswallet.com:50003`
133
+ - **Testnet**: `ssl://electrum.iriswallet.com:50013`
134
+ - **Testnet4**: `ssl://electrum.iriswallet.com:50053`
135
+ - **Signet**: `ssl://electrum.iriswallet.com:50033`
136
+ - **Regtest**: `tcp://regtest.thunderstack.org:50001`
137
+
138
+ UTEXOWallet uses network (`testnet` / `mainnet`) that define indexer and transport endpoints internally.
139
+
140
+ ### Installation
141
+
142
+ ```bash
143
+ npm install @utexo/rgb-sdk
144
+ ```
145
+
146
+ ### Node.js only
147
+
148
+ This SDK is designed for **Node.js** and is not browser-compatible. Use it in Node.js applications, scripts, and backends.
149
+
150
+ ### Basic Usage
151
+
152
+ ```javascript
153
+ const { UTEXOWallet, generateKeys } = require('@utexo/rgb-sdk');
154
+
155
+ // 1. Generate wallet keys (async)
156
+ const keys = await generateKeys('testnet');
157
+ console.log('Mnemonic:', keys.mnemonic); // Store securely!
158
+
159
+ // 2. Create and initialize UTEXO wallet
160
+ const wallet = new UTEXOWallet(keys.mnemonic, { network: 'testnet' });
161
+ await wallet.initialize();
162
+
163
+ // 3. Get address and balance
164
+ const address = await wallet.getAddress();
165
+ console.log('Wallet address:', address);
166
+ const balance = await wallet.getBtcBalance();
167
+ console.log('BTC balance:', balance);
168
+
169
+ await wallet.dispose();
170
+ ```
171
+
172
+ ## Core Workflows
173
+
174
+ ### Wallet Initialization
175
+
176
+ ```javascript
177
+ const { UTEXOWallet, generateKeys, restoreUtxoWalletFromBackup, restoreUtxoWalletFromVss } = require('@utexo/rgb-sdk');
178
+
179
+ // Generate new wallet keys (async)
180
+ const keys = await generateKeys('testnet');
181
+
182
+ // Initialize UTEXO wallet with mnemonic
183
+ const wallet = new UTEXOWallet(keys.mnemonic, { network: 'testnet' });
184
+ await wallet.initialize();
185
+
186
+ // Optional: use dataDir for persistent storage (same layout as restore)
187
+ const walletWithDir = new UTEXOWallet(keys.mnemonic, { network: 'testnet', dataDir: './wallet-data' });
188
+ await walletWithDir.initialize();
189
+
190
+ // Restore from file backup (layer1 + utexo in one folder)
191
+ const { targetDir } = restoreUtxoWalletFromBackup({
192
+ backupPath: './backup-folder',
193
+ password: 'your-password',
194
+ targetDir: './restored-wallet',
195
+ });
196
+ const restoredWallet = new UTEXOWallet(keys.mnemonic, { dataDir: targetDir, network: 'testnet' });
197
+ await restoredWallet.initialize();
198
+
199
+ // Restore from VSS (mnemonic required; vssServerUrl optional, uses default)
200
+ const { targetDir: vssDir } = await restoreUtxoWalletFromVss({
201
+ mnemonic: keys.mnemonic,
202
+ targetDir: './restored-from-vss',
203
+ });
204
+ const fromVss = new UTEXOWallet(keys.mnemonic, { dataDir: vssDir, network: 'testnet' });
205
+ await fromVss.initialize();
206
+ ```
207
+
208
+ ### UTXO Management
209
+
210
+ ```javascript
211
+ // Option 1: Create UTXOs in one call (begin → sign → end)
212
+ const count = await wallet.createUtxos({ num: 5, size: 1000 });
213
+ await wallet.syncWallet();
214
+ console.log(`Created ${count} UTXOs`);
215
+
216
+ // Option 2: Begin/end flow for custom signing
217
+ const psbt = await wallet.createUtxosBegin({ num: 5, size: 1000 });
218
+ const signedPsbt = await wallet.signPsbt(psbt);
219
+ const utxosCreated = await wallet.createUtxosEnd({ signedPsbt });
220
+ await wallet.syncWallet();
221
+ ```
222
+
223
+ ### Asset Issuance
224
+
225
+ ```javascript
226
+ // Issue a new NIA
227
+ const asset = await wallet.issueAssetNia({
228
+ ticker: "USDT",
229
+ name: "Tether USD",
230
+ amounts: [1000, 500],
231
+ precision: 6
232
+ });
233
+
234
+ console.log('Asset issued:', asset.asset?.assetId);
235
+ ```
236
+
237
+ ### Asset Transfers
238
+
239
+ ```javascript
240
+ // Receiver: create blind or witness invoice
241
+ const receiveData = receiverWallet.blindReceive({
242
+ assetId: assetId,
243
+ amount: 100,
244
+ minConfirmations: 3,
245
+ durationSeconds: 2000
246
+ });
247
+ // For witness invoices, sender must pass witnessData when sending
248
+ const witnessData = await receiverWallet.witnessReceive({ assetId, amount: 50 });
249
+
250
+ // Sender: Option 1 – complete send in one call
251
+ const sendResult = await senderWallet.send({
252
+ invoice: receiveData.invoice,
253
+ assetId,
254
+ amount: 100
255
+ });
256
+ // For witness invoice:
257
+ await senderWallet.send({
258
+ invoice: witnessData.invoice,
259
+ assetId,
260
+ amount: 50,
261
+ witnessData: { amountSat: 1000 }
262
+ });
263
+
264
+ // Sender: Option 2 – begin/end flow for custom signing
265
+ const sendPsbt = await senderWallet.sendBegin({
266
+ invoice: receiveData.invoice,
267
+ assetId,
268
+ amount: 100
269
+ });
270
+ const signedSendPsbt = await senderWallet.signPsbt(sendPsbt);
271
+ await senderWallet.sendEnd({ signedPsbt: signedSendPsbt });
272
+
273
+ // Refresh both wallets and list transfers
274
+ await senderWallet.refreshWallet();
275
+ await receiverWallet.refreshWallet();
276
+ const transfers = await receiverWallet.listTransfers(assetId);
277
+ ```
278
+
279
+ ### On-chain receive/send
280
+
281
+ ```javascript
282
+ const { UTEXOWallet } = require('@utexo/rgb-sdk');
283
+
284
+ const sender = new UTEXOWallet("test mnemonic sender", { network: 'testnet' });
285
+ const receiver = new UTEXOWallet("test mnemonic receiver", { network: 'testnet' });
286
+ await sender.initialize();
287
+ await receiver.initialize();
288
+
289
+ // 1) Receiver: onchainReceive – create mainnet invoice for deposit
290
+ const { invoice } = await receiver.onchainReceive({
291
+ assetId: "rgb:WPRv95Nj-icdrgPp-zpQhIp_-2TyJ~Ge-k~FvuMZ-~vVnkA0",
292
+ amount: 5,
293
+ });
294
+
295
+ // 2) Sender: onchainSend – pay that mainnet invoice from UTEXO
296
+ const sendResult = await sender.onchainSend({ invoice });
297
+ console.log('Onchain send result:', sendResult);
298
+
299
+ await receiver.refreshWallet()
300
+ await sender.refreshWallet()
301
+
302
+ // wait 3 confirmation blocks
303
+
304
+ await receiver.refreshWallet()
305
+ await sender.refreshWallet()
306
+
307
+ const status = await receiver.getOnchainSendStatus(invoice)
308
+ console.log(status)
309
+
310
+ ```
311
+
312
+ ### Lightning receive/send
313
+
314
+ ```javascript
315
+ const { UTEXOWallet } = require('@utexo/rgb-sdk');
316
+
317
+ const sender = new UTEXOWallet("test mnemonic sender", { network: 'testnet' });
318
+ const receiver = new UTEXOWallet("test mnemonic receiver", { network: 'testnet' });
319
+ await sender.initialize();
320
+ await receiver.initialize();
321
+
322
+ // 1) Receiver: createLightningInvoice – create Lightning invoice for receiving
323
+ const assetId = "rgb:WPRv95Nj-icdrgPp-zpQhIp_-2TyJ~Ge-k~FvuMZ-~vVnkA0";
324
+ const { lnInvoice } = await receiver.createLightningInvoice({
325
+ asset: { assetId, amount: 5 },
326
+ });
327
+
328
+ // 2) Sender: payLightningInvoice – pay that Lightning invoice from UTEXO
329
+ const sendResult = await sender.payLightningInvoice({ lnInvoice, assetId, amount: 5 });
330
+ console.log('Lightning send result:', sendResult);
331
+
332
+ await receiver.refreshWallet();
333
+ await sender.refreshWallet();
334
+
335
+ const status = await sender.getLightningSendRequest(lnInvoice);
336
+ console.log(status);
337
+ ```
338
+
339
+ ### Balance and Asset Management
340
+
341
+ ```javascript
342
+ // Get BTC balance (async)
343
+ const btcBalance = await wallet.getBtcBalance();
344
+
345
+ // List all assets
346
+ const assets = await wallet.listAssets();
347
+
348
+ // Get specific asset balance
349
+ const assetBalance = await wallet.getAssetBalance(assetId);
350
+
351
+ // List unspent UTXOs
352
+ const unspents = await wallet.listUnspents();
353
+
354
+ // List transactions
355
+ const transactions = await wallet.listTransactions();
356
+
357
+ // List transfers for specific asset
358
+ const transfers = await wallet.listTransfers(assetId);
359
+ ```
360
+
361
+ ---
362
+
363
+ ## Setup wallet and issue asset
364
+
365
+ ```javascript
366
+ const { UTEXOWallet, generateKeys } = require('@utexo/rgb-sdk');
367
+
368
+ async function demo() {
369
+ const keys = await generateKeys('testnet');
370
+ const wallet = new UTEXOWallet(keys.mnemonic, { network: 'testnet' });
371
+ await wallet.initialize();
372
+
373
+ const address = await wallet.getAddress();
374
+ const balance = await wallet.getBtcBalance();
375
+
376
+ // Create UTXOs and issue asset
377
+ const count = await wallet.createUtxos({ num: 5, size: 1000 });
378
+ await wallet.syncWallet();
379
+
380
+ const asset = await wallet.issueAssetNia({
381
+ ticker: 'DEMO',
382
+ name: 'Demo Token',
383
+ amounts: [1000],
384
+ precision: 2
385
+ });
386
+
387
+ const assets = await wallet.listAssets();
388
+ const assetBalance = await wallet.getAssetBalance(asset.assetId);
389
+
390
+ await wallet.dispose();
391
+ }
392
+ ```
393
+
394
+ ---
395
+
396
+ ## Security
397
+
398
+ ### Key Management
399
+
400
+ ```javascript
401
+ const { generateKeys, deriveKeysFromMnemonic } = require('@utexo/rgb-sdk');
402
+
403
+ // Generate new wallet keys (async)
404
+ const keys = await generateKeys('testnet');
405
+ const mnemonic = keys.mnemonic; // Sensitive - protect at rest
406
+
407
+ // Store mnemonic securely for later restoration
408
+ // Use environment variables for production
409
+ const storedMnemonic = process.env.WALLET_MNEMONIC;
410
+
411
+ // Restore keys from mnemonic
412
+ const restoredKeys = await deriveKeysFromMnemonic('testnet', storedMnemonic);
413
+
414
+ // Sign and verify arbitrary messages (Schnorr signatures)
415
+ const seedHex = process.env.WALLET_SEED_HEX; // 64-byte hex string
416
+ const { signature, accountXpub } = await signMessage({
417
+ message: 'Hello RGB!',
418
+ seed: seedHex,
419
+ network: 'testnet',
420
+ });
421
+ const isValid = await verifyMessage({
422
+ message: 'Hello RGB!',
423
+ signature,
424
+ accountXpub,
425
+ network: 'testnet',
426
+ });
427
+ ```
428
+
429
+ ### Backup and Restore
430
+
431
+ > **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;
432
+ >
433
+ > **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.
434
+
435
+ ```javascript
436
+ const { UTEXOWallet, restoreUtxoWalletFromBackup, restoreUtxoWalletFromVss, generateKeys } = require('@utexo/rgb-sdk');
437
+
438
+ const keys = await generateKeys('testnet');
439
+ const wallet = new UTEXOWallet(keys.mnemonic, { network: 'testnet' });
440
+ await wallet.initialize();
441
+
442
+ // File backup (layer1 + utexo in one folder: wallet_<fp>_layer1.backup, wallet_<fp>_utexo.backup)
443
+ const backup = await wallet.createBackup({
444
+ backupPath: './backups',
445
+ password: 'secure-password'
446
+ });
447
+ console.log('Backup created:', backup.layer1BackupPath, backup.utexoBackupPath);
448
+
449
+ // Restore from file backup
450
+ const { targetDir } = restoreUtxoWalletFromBackup({
451
+ backupPath: './backups',
452
+ password: 'secure-password',
453
+ targetDir: './restored-wallet'
454
+ });
455
+ const restoredWallet = new UTEXOWallet(keys.mnemonic, { dataDir: targetDir, network: 'testnet' });
456
+ await restoredWallet.initialize();
457
+
458
+ // VSS backup (config optional; built from mnemonic + DEFAULT_VSS_SERVER_URL)
459
+ await wallet.vssBackup();
460
+ // Restore from VSS
461
+ const { targetDir: vssDir } = await restoreUtxoWalletFromVss({
462
+ mnemonic: keys.mnemonic,
463
+ targetDir: './restored-from-vss'
464
+ });
465
+ ```
466
+
467
+ ---
468
+
469
+ ## Full Examples
470
+
471
+ - [new-wallet](examples/new-wallet.mjs) – Generate keys and create a new UTEXO wallet
472
+ - [read-wallet](examples/read-wallet.mjs) – Initialize by mnemonic and call getXpub, getNetwork, getAddress, getBtcBalance, listAssets
473
+ - [create-utxos-asset](examples/create-utxos-asset.mjs) – Create UTXOs and issue a NIA asset
474
+ - [transfer](examples/transfer.mjs) – Two wallets: witness + blind receive, refresh, listTransfers (requires ASSET_ID and funded wallets)
475
+ - [onchain-flow](examples/onchain-flow.mjs) – On-chain transfer: receive + send
476
+ - [lightning-flow](examples/lightning-flow.mjs) – Lightning transfer: createLightningInvoice + payLightningInvoice
477
+ - [utexo-vss-backup-restore](examples/utexo-vss-backup-restore.mjs) – VSS backup and restore
478
+ - [utexo-file-backup-restore](examples/utexo-file-backup-restore.mjs) – File backup and restore
479
+
480
+ See [examples/README.md](examples/README.md) for run commands. CLI: [cli/](cli/).