-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathexample-flow.mjs
More file actions
606 lines (525 loc) · 23.8 KB
/
Copy pathexample-flow.mjs
File metadata and controls
606 lines (525 loc) · 23.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
import axios from 'axios';
import fs from 'fs/promises';
import path from 'path';
import crypto from 'crypto';
import { fileURLToPath } from 'url';
import { WalletManager, createWallet, restoreFromBackup, restoreFromVss } from './dist/index.mjs';
// Configuration
const RGB_MANAGER_ENDPOINT = "http://127.0.0.1:8000";
const BITCOIN_NODE_ENDPOINT = "http://18.119.98.232:5000/execute";
const TRANSPORT_ENDPOINT = "rpc://regtest.thunderstack.org:3000/json-rpc";
const INDEXER_URL = "tcp://regtest.thunderstack.org:50001";
const VSS_SERVER_URL = "https://vss-server.utexo.com/vss";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
/**
* Mine blocks using the Bitcoin node endpoint
*/
async function mine(numBlocks) {
try {
const response = await axios.post(BITCOIN_NODE_ENDPOINT, {
args: `mine ${numBlocks}`
}, {
headers: {
'Content-Type': 'application/json'
}
});
console.log(`Mined ${numBlocks} blocks`);
return response.data;
} catch (error) {
throw new Error(`Unable to mine: ${error.message}`);
}
}
/**
* Send Bitcoin to an address using the Bitcoin node endpoint
*/
async function sendToAddress(address, amount) {
try {
const response = await axios.post(BITCOIN_NODE_ENDPOINT, {
args: `sendtoaddress ${address} ${amount}`
}, {
headers: {
'Content-Type': 'application/json'
}
});
const txid = response.data?.result || response.data;
console.log(`Sent ${amount} BTC to ${address}, TXID: ${txid}`);
return txid;
} catch (error) {
throw new Error(`Unable to send bitcoins: ${error.message}`);
}
}
/**
* Initialize a wallet with RGB SDK
*/
const sender_keys = {
mnemonic: 'maximum infant drama seed family ensure true view infant suggest muscle chase',
xpub: 'tpubD6NzVbkrYhZ4WiLr47UXxW8ry3SAQ4eZprUdQjhDmK8Kb42KmCQH9tKAvo6cpoAswLXmiyC8KtdvZNy3v5Zg5ugiiPoE8rLYRoRoPsWoKVX',
accountXpubVanilla: 'tpubDDQdhAci2b6tUYLz3guDfkF8KkUaFHmQ39wm9kwZmGtFEbMnh8ZrXzpogY15czxcdaaKzF5Zf73jAAtsog63hHNVnqPwhAYiTe7TCKbcNUT',
accountXpubColored: 'tpubDD6wJYTR8dqpH4kHevNxM4PGzi7y8kfvV7XckH1W2vTtxdwo9wDmThmm4dZVGE57wHmQerq7bY5TXEmmXTDvTBoqNvHrJ8DKaUHqEjyksi1',
masterFingerprint: 'e3059eb4',
xpriv: 'tprv8ZgxMBicQKsPdFK4ATowZ6UkQ1vEEjTfFYsr8DevM3KvkZmZ8oagyPhJkfuraQzWRmQo3YgvMH9sDpZEUpqGq839gp9kDX4BC9Abffr8uri'
}
const reciver_keys = {
mnemonic: 'favorite chicken wealth waste awake champion afford misery please fetch shy believe',
xpub: 'tpubD6NzVbkrYhZ4YNVmSHFij6bSByV4NLKaooQ5mBEf2wEYggCgGmdFkNSxzmxe9vUphZwJ5gykYgj4apnQAirTAd57dJKdsKQVShjxW7YwMsT',
accountXpubVanilla: 'tpubDDgTpsGJNJtG27ey2n3vNGM3U5VAK4Uot2k8z1XX6mJEnMx5vbCtWFY4vHcuYFbDtQpKTx97vL9vDgaWfNQTuzJ4BH2X5A9JYBrZxhr8gNz',
accountXpubColored: 'tpubDDZ8nouFqYMhNufYVt4YHeryC1RNewoerPwemPsrnF4HMoMscU8FS1cio8J19Lv1vPtB6p5Tzad5qTPG5k2vm1imbqNQyB83xf83F9KY85Z',
masterFingerprint: '2f4de38a',
xpriv: 'tprv8ZgxMBicQKsPeuTyYdb8KgwKcwy8D18gEVoJUfCMcfS9rBwueNofZsq6pfVULHAjDDapA857Pj6zp1zv9BqhrGgq3gQheSipDBWP4k3VnnM'
}
const Keysgenerated = {
mnemonic: 'panther real human slogan almost unfold task gown hold army fall save',
xpub: 'tpubD6NzVbkrYhZ4XzhbVsPwjczpu3tZi4ERagjPpivQxzm13Tb5Murmvbb1KeVA43PLPmFgCXS98XBF9w3QZVEAp3uimkjwjG3BiyvEeELPBf7',
accountXpubVanilla: 'tpubDCjUD8f5QGVjbgvKZRvPx7GCNncXoxGAAu9F26cApEpdEsjZiHPqJdjhHdSagVJBMRU4GCcq7N8nngPWENqWXfxBKiPrUvTLtkAuBNZbRbL',
accountXpubColored: 'tpubDC4VePJFVqLB473vPiiBVFHE46qsmKBsU5h7JqSz9BHTJVBbkDRFxKpBvfNzvkws3aNL1hJpQGMtUdneYazAjrKiuuhKH4nJzCZyMqZHy9k',
masterFingerprint: 'dfc09a55',
xpriv: 'tprv8ZgxMBicQKsPeXfocDjMLDLiL2NdYj3X1P8cYCt7YixcCyLJjX3Bk6y99U6Nm6QwrGi2wdNSn4wQDsDiLhPnCnCpjKFtdL7E6xp3MWrYeCn'
}
const signet_keys = {
mnemonic: 'zebra canyon believe puppy attend whip enough hover style blood boss aim',
xpub: 'tpubD6NzVbkrYhZ4XE3cTdpMfiLErtKy5YZexxehGeJwU7HCAdL3CUiGb5V1QtRqfDxqqJQ9X6W4MGoD6Dh93PMs3SKbCrTaEgV7o9EsZMdVxeL',
accountXpubVanilla: 'tpubDChRCioutECCiy9V7o5Uiw6hsZNPa9KydCQPZsZLjDDHEpGenAqG59hZuDrETEq4ESCur78P61w1stKM5CzNWLHSh2j1LV2m4wJQm45zDeZ',
accountXpubColored: 'tpubDCFrxT5TCk6LwC6FDcnNwqNMpDyG61BPZsJ9Nvxq15hGbAifmD9rdqs4TSU8QPd9xo7eTNUwHCcY1DRdhFD79fLpF9byF3nZN2qxm94K3MT',
masterFingerprint: '3780bc30',
xpriv: 'tprv8ZgxMBicQKsPdm1pZz9mGJg8Hrp2vDNkPf3uz8Ge3qUoL95Ga5tgQas9EmwVDcx67S2LACiGykAMrZCZoTAoqzdHjrj9rMTHYcyPPhAqYey'
}
const bitcoinNetwork = 'signet'; // Regtest network
function deriveVssSigningKeyFromMnemonic(mnemonic) {
const hmac = crypto.createHmac('sha256', 'rgb-lib-vss-backup-encryption-v1');
hmac.update(mnemonic, 'utf8');
return hmac.digest('hex');
}
/**
* Local backup flow: create backup file → restore into new data dir → optional WalletManager from restored dir.
* @param {import('./dist/index.mjs').WalletManager} wallet - Initialized wallet to backup
* @param {{ accountXpubVanilla: string, accountXpubColored: string, masterFingerprint: string, mnemonic: string }} keys - Wallet keys (for restored instance)
* @param {{ backupPassword?: string, backupDir?: string, restoredDataDir?: string, network?: string, transportEndpoint?: string }} options
* @returns {{ backupResponse: { message: string, backupPath: string }, restoredDataDir: string, restoredWallet?: import('./dist/index.mjs').WalletManager }}
*/
async function runLocalBackupFlow(wallet, keys, options = {}) {
const backupPassword = options.backupPassword ?? 'test-backup-password';
const backupDir = options.backupDir ?? path.join(__dirname, 'backups');
const restoredDataDir = options.restoredDataDir ?? path.join(__dirname, 'restored-wallet');
const network = options.network ?? 'signet';
const transportEndpoint = options.transportEndpoint ?? TRANSPORT_ENDPOINT;
console.log('\n--- Local backup flow ---');
console.log('Creating wallet backup (local file)...');
await fs.mkdir(backupDir, { recursive: true });
const backupResponse = await wallet.createBackup({
backupPath: backupDir,
password: backupPassword,
});
console.log('Backup response:', backupResponse);
console.log('Restoring wallet from backup (new data dir)...');
await fs.mkdir(restoredDataDir, { recursive: true });
restoreFromBackup({
backupFilePath: backupResponse.backupPath,
password: backupPassword,
dataDir: restoredDataDir,
});
console.log('Wallet restored to:', restoredDataDir);
const restoredWallet = new WalletManager({
xpubVan: keys.accountXpubVanilla,
xpubCol: keys.accountXpubColored,
masterFingerprint: keys.masterFingerprint,
mnemonic: keys.mnemonic,
network,
transportEndpoint,
dataDir: restoredDataDir,
});
const restoredAssets = restoredWallet.listAssets();
console.log('Assets after restore:', JSON.stringify(restoredAssets, null, 2));
return { backupResponse, restoredDataDir, restoredWallet };
}
/**
* VSS backup flow: configure VSS → upload backup → optional restore from VSS into new data dir.
* Uses storeId = wallet_<masterFingerprint> and signingKey derived from mnemonic (or env overrides).
* @param {import('./dist/index.mjs').WalletManager} wallet - Initialized wallet
* @param {{ masterFingerprint: string, mnemonic: string }} keys - Wallet keys for VSS config derivation
* @param {{ serverUrl?: string, vssRestoredDir?: string }} options
* @returns {{ vssConfig: { serverUrl: string, storeId: string, signingKey: string }, walletPath?: string }}
*/
async function runVssBackupFlow(wallet, keys, options = {}) {
const serverUrl = options.serverUrl ?? VSS_SERVER_URL;
const vssRestoredDir = options.vssRestoredDir ?? path.join(__dirname, 'restored-from-vss');
const storeId = process.env.VSS_STORE_ID ?? `wallet_${keys.masterFingerprint}`;
const signingKey = process.env.VSS_SIGNING_KEY ?? deriveVssSigningKeyFromMnemonic(keys.mnemonic);
const vssConfig = {
serverUrl,
storeId,
signingKey,
};
console.log("vssConfig", vssConfig);
console.log('\n--- VSS backup flow ---');
console.log('Configuring VSS backup...');
await wallet.configureVssBackup(vssConfig);
console.log('Triggering VSS backup...');
const vssVersion = await wallet.vssBackup(vssConfig);
console.log('VSS backup server version:', vssVersion);
const vssInfo = await wallet.vssBackupInfo(vssConfig);
console.log('VSS backup info:', vssInfo);
console.log('Restoring wallet from VSS into new data dir...');
await fs.mkdir(vssRestoredDir, { recursive: true });
const { walletPath } = restoreFromVss({
config: vssConfig,
targetDir: vssRestoredDir,
});
console.log('Wallet restored from VSS at:', walletPath);
return { vssConfig, walletPath };
}
async function initWallet(keys) {
console.log("\nInitializing wallet with RGB SDK...");
// Generate keys using the library
// const keys = await createWallet(bitcoinNetwork);
// const keys = {
// account_xpub_vanilla: 'tpubDDXmGYkFAqH94kgxcs1fqMbdffUm2mhjoVjhkcBzYJaXRvK4bziWubD5uy3pepvNySjXthPpqfRSeQLpujjGVfZ2yEr65vwDFxJmfxoZMJY',
// account_xpub_colored: 'tpubDCyE5hV4MiwR19jcY6mYm77Z5FDg9Swsv4EFoAKAfeqhf2mTLfEadaTHXdhzMenCqGvupoWyTetJyCoiVj168E7HPY8PMbVDp8WU3eZnTfa',
// master_fingerprint: '5eb2d564',
// mnemonic: 'pyramid gospel arch risk topple year wealth inch thing enemy inflict fiction'
// }
// Restore keys to verify they match
// const keys = await createWallet(bitcoinNetwork);
// In the original example, they restore from mnemonic, but we'll skip that for now
// since we just generated them
console.log("Keys generated:", keys);
// Initialize wallet manager
const wallet = new WalletManager({
xpubVan: keys.accountXpubVanilla,
xpubCol: keys.accountXpubColored,
masterFingerprint: keys.masterFingerprint,
mnemonic: keys.mnemonic,
network: bitcoinNetwork,
// rgb_node_endpoint: RGB_MANAGER_ENDPOINT,
transportEndpoint: TRANSPORT_ENDPOINT,
// indexerUrl: INDEXER_URL
});
console.log("Wallet created");
// Register wallet with RGB Node
wallet.registerWallet();
console.log("Wallet registered");
// Get BTC balance
const btcBalance = wallet.getBtcBalance();
console.log("BTC balance:", btcBalance);
await wallet.syncWallet();
// Get address
const address = wallet.getAddress();
console.log("Address:", address);
// Send some BTC to the address
// await sendToAddress(address, 1);
// await mine(3);
// Wait a bit for the transaction to be processed
// await new Promise(resolve => setTimeout(resolve, 2000));
// Get updated BTC balance
const updatedBtcBalance = await wallet.getBtcBalance();
console.log("Updated BTC balance:", updatedBtcBalance);
// Create UTXOs
// console.log("Creating UTXOs...");
// const utxosCreated = await wallet.createUtxos({ upTo: true, num: 2, size: 1500, feeRate: 1 });
// const psbt = await wallet.createUtxosBegin({
// upTo: true,
// num: 2,
// size: 1500,
// feeRate: 1
// });
// console.log('psbt', psbt);
// const signedPsbt = await wallet.signPsbt(psbt);
// const utxosCreated = wallet.createUtxosEnd({ signedPsbt: signedPsbt });
// console.log(`Created UTXOs successfully`, utxosCreated);
return { wallet, keys };
}
/**
* Main execution function
*/
async function main() {
console.log("Starting RGB SDK Wallet Example");
console.log("=".repeat(50));
// const test = await createWallet(bitcoinNetwork);
// console.log("createWallet", test);
// return
try {
// Initialize sender wallet
// const { wallet: senderWallet, keys: senderKeys } = await initWallet(reciver_keys);
// const keys = await createWallet(bitcoinNetwork);
const { wallet: senderWallet, keys: senderKeys } = await initWallet(signet_keys);
console.log("Running VSS backup flow...", senderKeys);
try {
const { vssConfig, walletPath } = await runVssBackupFlow(senderWallet, senderKeys, {
serverUrl: VSS_SERVER_URL,
});
console.log('VSS backup config:', vssConfig);
console.log('Wallet path:', walletPath);
} catch (vssErr) {
const msg = vssErr?.message ?? String(vssErr);
if (msg.includes('NotValidForName') || msg.includes('invalid peer certificate')) {
console.warn('VSS backup failed (TLS certificate hostname mismatch). Use a server URL whose host matches the server certificate (e.g. use the certificate hostname, not an IP).', msg);
} else {
console.warn('VSS backup flow failed:', msg);
}
}
return;
// const txss = await senderWallet.listTransfers();
// console.log("Transfers:", JSON.stringify(txss, null, 2));
// const senderWalletres = await senderWallet.blindReceive({
// // assetId: asset1.asset?.assetId || '',
// amount: 12
// });
// const invoiceData = await senderWallet.decodeRGBInvoice({ invoice: senderWalletres.invoice });
// console.log("Invoice data:", JSON.stringify(invoiceData, null, 2));
// console.log("Blind receive data:", senderWalletres);
// const txafter = await senderWallet.listTransfers();
// console.log("Transfers after blind receive:", JSON.stringify(txafter, null, 2));
// const ltransactions = await senderWallet.listTransactions();
// console.log("Transactions:", JSON.stringify(ltransactions, null, 2));
// return
// const { wallet: receiverWallet, keys: receiverKeys } = await initWallet(reciver_keys);
// return
// Issue NIA asset
// console.log("\nIssuing NIA asset...");
const unspents2 = await senderWallet.listUnspents();
console.log("Unspents2:", JSON.stringify(unspents2, null, 2));
return
const asset12 = senderWallet.issueAssetNia({
ticker: "USDT",
name: "Tether",
amounts: [777, 66],
precision: 0
});
console.log("Issued NIA asset:", JSON.stringify(asset12));
// Issue CFA asset (if supported)
// Note: CFA issuance might not be available in the current API
// console.log("\nIssuing CFA asset...");
// const asset2 = senderWallet.issueAssetCfa({
// ticker: "CFA",
// name: "Cfa",
// amounts: [777],
// precision: 2
// });
// console.log("Issued CFA asset:", JSON.stringify(asset2));
const asset1 = {
"assetId": "rgb:SovYOhF~-uCN8dS1-3sybTaH-D~uCxC9-AnNikLV-absJvWU",
"ticker": "USDT",
"name": "Tether",
"details": null,
"precision": 0,
"issuedSupply": 843,
"timestamp": 1769006491,
"addedAt": 1769006491,
"balance": {
"settled": 843,
"future": 843,
"spendable": 843
},
"media": null
}
// List assets
console.log("\nListing assets...");
const assets1 = senderWallet.listAssets();
console.log("Assets:", JSON.stringify(assets1, null, 2));
return
const asset_balance = senderWallet.getAssetBalance(asset1.assetId);
console.log("Asset balance:", JSON.stringify(asset_balance, null, 2));
// Initialize receiving wallet
console.log("\nInitializing receiving wallet...");
const { wallet: receiverWallet } = await initWallet(reciver_keys);
const btcAddress = receiverWallet.getAddress();
console.log("BTC address:", btcAddress);
receiverWallet.syncWallet();
const btcBalance2 = receiverWallet.getBtcBalance();
console.log("BTC balance:", JSON.stringify(btcBalance2));
// Send BTC to the address
const spsbt = senderWallet.sendBtcBegin({
address: btcAddress,
amount: 7000,
feeRate: 1
});
console.log("PSBT:", spsbt);
const signedSendPsbt = await senderWallet.signPsbt(spsbt);
console.log("Signed PSBT:", signedSendPsbt);
const btcEstimate = await senderWallet.estimateFee(signedSendPsbt);
console.log("BTC send estimate:", btcEstimate);
const sendBtcEndresult = senderWallet.sendBtcEnd({ signedPsbt: signedSendPsbt });
console.log("Send BTC result:", sendBtcEndresult);
mine(3);
// Wait for confirmation
await new Promise(resolve => setTimeout(resolve, 2000));
receiverWallet.syncWallet();
senderWallet.syncWallet();
const resultCombined = await senderWallet.sendBtc({
address: btcAddress,
amount: 7000,
feeRate: 1
});
console.log("Send BTC result:", resultCombined);
mine(1);
// Wait for confirmation
await new Promise(resolve => setTimeout(resolve, 2000));
receiverWallet.syncWallet();
const btcBalance = receiverWallet.getBtcBalance();
console.log("BTC balance:", JSON.stringify(btcBalance));
// return;
// Create blind receive
console.log("\nCreating blind receive...");
const receiveData1 = receiverWallet.blindReceive({
// assetId: asset1.asset?.assetId || '',
amount: 76
});
console.log("Blind receive data:", JSON.stringify(receiveData1, null, 2));
// Send assets
console.log("\nSending assets...", asset1);
const psbt = senderWallet.sendBegin({
assetId: asset1.assetId,
amount: 76,
invoice: receiveData1.invoice,
feeRate: 1,
minConfirmations: 1
});
console.log("PSBT:", psbt);
const signedPsbt = await senderWallet.signPsbt(psbt);
console.log("Signed PSBT:", signedPsbt);
const sendResult = senderWallet.sendEnd({ signedPsbt: signedPsbt });
// const sendResult = await senderWallet.send({
// assetId: asset1.assetId,
// amount: 76,
// invoice: receiveData1.invoice,
// minConfirmations: 1
// });
console.log("Send result:", sendResult);
// Refresh wallets
console.log("\nRefreshing wallets...");
receiverWallet.refreshWallet();
senderWallet.refreshWallet();
// Mine a block to confirm the transaction
console.log("\nMining block...");
await mine(10);
// Refresh wallets again after mining
receiverWallet.refreshWallet();
senderWallet.refreshWallet();
// List assets in receiver wallet
console.log("\nListing receiver assets...");
const rcvAssets = receiverWallet.listAssets();
console.log("Receiver assets:", JSON.stringify(rcvAssets, null, 2));
// Get asset balance
if (asset1.assetId) {
console.log("\nGetting asset balance...");
const rcvAssetBalance = receiverWallet.getAssetBalance(asset1.assetId);
console.log("Receiver asset balance:", JSON.stringify(rcvAssetBalance, null, 2));
}
// Create witness receive
console.log("\nCreating witness receive...");
const receiveData2 = receiverWallet.witnessReceive({
// assetId: asset1.asset?.assetId || '',
amount: 50
});
// Send assets
console.log("\nSending assets...", asset1);
const sendResult2 = await senderWallet.send({
assetId: asset1.assetId,
amount: 10,
witnessData: {
amountSat: 1000,
blinding: null,
},
invoice: receiveData2.invoice,
minConfirmations: 1
});
console.log("Send result:", sendResult2);
console.log("Witness receive data:", JSON.stringify(receiveData2, null, 2));
// Refresh wallets
console.log("\nRefreshing wallets...");
receiverWallet.refreshWallet();
senderWallet.refreshWallet();
// Mine a block to confirm the transaction
console.log("\nMining block...");
await mine(10);
// Refresh wallets again after mining
receiverWallet.refreshWallet();
senderWallet.refreshWallet();
// Sync wallet (if available)
// senderWallet.sync();
// List transfers
if (asset1.assetId) {
console.log("\nListing transfers...");
const transfers = senderWallet.listTransfers(asset1.assetId);
console.log("Transfers:", JSON.stringify(transfers, null, 2));
}
// List transactions
console.log("\nListing transactions...");
const transactions = senderWallet.listTransactions();
console.log("Transactions:", JSON.stringify(transactions, null, 2));
// List unspents
console.log("\nListing unspents...");
const unspents = receiverWallet.listUnspents();
console.log("Unspents:", JSON.stringify(unspents, null, 2));
// Send BTC (similar to sendBtc in original example)
console.log("\nSending BTC...");
const receiverAddress = receiverWallet.getAddress();
const btcTxid = await sendToAddress(receiverAddress, 0.0007);
console.log("Sent BTC, TXID:", btcTxid);
// Wait for confirmation
await new Promise(resolve => setTimeout(resolve, 2000));
// Refresh wallets
senderWallet.refreshWallet();
receiverWallet.refreshWallet();
// Local backup flow: create backup file → restore → new WalletManager from restored dir
await runLocalBackupFlow(senderWallet, senderKeys, {
backupPassword: 'test-backup-password',
network: bitcoinNetwork,
transportEndpoint: TRANSPORT_ENDPOINT,
});
// VSS backup flow (optional; requires VSS server and rgb-lib built with VSS)
// Uses VSS_SERVER_URL from top of file.
if (VSS_SERVER_URL) {
try {
await runVssBackupFlow(senderWallet, senderKeys, {
serverUrl: VSS_SERVER_URL,
});
} catch (vssErr) {
console.warn("VSS backup flow skipped or failed (native addon may segfault if VSS is unstable):", vssErr?.message ?? vssErr);
}
} else {
console.log("\nVSS backup flow skipped (set VSS_SERVER_URL at top of file to enable).");
}
console.log("\nExample completed successfully!");
console.log("=".repeat(50));
} catch (error) {
console.error("Error in main execution:", error);
if (error.response) {
console.error("Response data:", error.response.data);
console.error("Response status:", error.response.status);
}
process.exit(1);
}
}
// Run the example
const isMainModule = import.meta.url === `file://${process.argv[1]}` ||
import.meta.url.endsWith('example-flow.mjs') ||
process.argv[1]?.endsWith('example-flow.mjs');
if (isMainModule || process.argv[1]?.includes('example-flow.mjs')) {
console.log("RGB SDK Wallet Complete Example");
console.log("This example demonstrates:");
console.log("- Wallet creation and initialization");
console.log("- UTXO creation and management");
console.log("- RGB asset issuance");
console.log("- Asset transfers between wallets");
console.log("- Transaction and transfer listing");
console.log("");
main()
.then(() => {
console.log("All operations completed successfully!");
process.exit(0);
})
.catch((error) => {
console.error("Fatal error:", error);
process.exit(1);
});
}
export {
main,
initWallet,
mine,
sendToAddress,
runLocalBackupFlow,
runVssBackupFlow,
deriveVssSigningKeyFromMnemonic,
};