@dynamic-labs-sdk/bitcoin 0.23.2 → 0.23.3

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/dist/{addBitcoinInjectedWalletsExtension-DoK6Bz_8.cjs.js → addBitcoinInjectedWalletsExtension-CLSKGEnn.cjs.js} +36 -296
  2. package/dist/addBitcoinInjectedWalletsExtension-CLSKGEnn.cjs.js.map +1 -0
  3. package/dist/{addBitcoinInjectedWalletsExtension-Blf31mFB.esm.js → addBitcoinInjectedWalletsExtension-Cfb9iZNA.esm.js} +17 -217
  4. package/dist/addBitcoinInjectedWalletsExtension-Cfb9iZNA.esm.js.map +1 -0
  5. package/dist/addWaasBitcoinExtension-BGV8KNdF.esm.js +707 -0
  6. package/dist/addWaasBitcoinExtension-BGV8KNdF.esm.js.map +1 -0
  7. package/dist/addWaasBitcoinExtension-DsAO3xoD.cjs.js +758 -0
  8. package/dist/addWaasBitcoinExtension-DsAO3xoD.cjs.js.map +1 -0
  9. package/dist/bitcoinTransferAmount-ChA9XwDs.cjs.js +288 -0
  10. package/dist/bitcoinTransferAmount-ChA9XwDs.cjs.js.map +1 -0
  11. package/dist/bitcoinTransferAmount-DLbPaIMH.esm.js +222 -0
  12. package/dist/bitcoinTransferAmount-DLbPaIMH.esm.js.map +1 -0
  13. package/dist/index.cjs.js +13 -741
  14. package/dist/index.cjs.js.map +1 -1
  15. package/dist/index.esm.js +5 -704
  16. package/dist/index.esm.js.map +1 -1
  17. package/dist/injected.cjs.js +4 -3
  18. package/dist/injected.cjs.js.map +1 -1
  19. package/dist/injected.esm.js +2 -1
  20. package/dist/injected.esm.js.map +1 -1
  21. package/dist/tsconfig.lib.tsbuildinfo +1 -1
  22. package/dist/utils/bitcoinExecuteSwapTransaction/bitcoinExecuteSwapTransaction.d.ts.map +1 -1
  23. package/dist/utils/convertPsbtToBase64/convertPsbtToBase64.d.ts +3 -0
  24. package/dist/utils/convertPsbtToBase64/convertPsbtToBase64.d.ts.map +1 -0
  25. package/dist/utils/convertPsbtToBase64/index.d.ts +2 -0
  26. package/dist/utils/convertPsbtToBase64/index.d.ts.map +1 -0
  27. package/dist/utils/isHexEncodedPsbt/index.d.ts +2 -0
  28. package/dist/utils/isHexEncodedPsbt/index.d.ts.map +1 -0
  29. package/dist/utils/isHexEncodedPsbt/isHexEncodedPsbt.d.ts +3 -0
  30. package/dist/utils/isHexEncodedPsbt/isHexEncodedPsbt.d.ts.map +1 -0
  31. package/dist/waas.cjs.js +41 -0
  32. package/dist/waas.cjs.js.map +1 -0
  33. package/dist/waas.esm.js +40 -0
  34. package/dist/waas.esm.js.map +1 -0
  35. package/package.json +4 -4
  36. package/dist/addBitcoinInjectedWalletsExtension-Blf31mFB.esm.js.map +0 -1
  37. package/dist/addBitcoinInjectedWalletsExtension-DoK6Bz_8.cjs.js.map +0 -1
package/dist/index.cjs.js CHANGED
@@ -1,737 +1,10 @@
1
- //#region rolldown:runtime
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") {
10
- for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
- key = keys[i];
12
- if (!__hasOwnProp.call(to, key) && key !== except) {
13
- __defProp(to, key, {
14
- get: ((k) => from[k]).bind(null, key),
15
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
- });
17
- }
18
- }
19
- }
20
- return to;
21
- };
22
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
- value: mod,
24
- enumerable: true
25
- }) : target, mod));
26
-
27
- //#endregion
28
- const require_addBitcoinInjectedWalletsExtension = require('./addBitcoinInjectedWalletsExtension-DoK6Bz_8.cjs.js');
1
+ const require_addWaasBitcoinExtension = require('./addWaasBitcoinExtension-DsAO3xoD.cjs.js');
2
+ const require_bitcoinTransferAmount = require('./bitcoinTransferAmount-ChA9XwDs.cjs.js');
3
+ const require_addBitcoinInjectedWalletsExtension = require('./addBitcoinInjectedWalletsExtension-CLSKGEnn.cjs.js');
29
4
  let _dynamic_labs_sdk_assert_package_version = require("@dynamic-labs-sdk/assert-package-version");
30
5
  let _dynamic_labs_sdk_client_core = require("@dynamic-labs-sdk/client/core");
31
6
  let _dynamic_labs_sdk_client = require("@dynamic-labs-sdk/client");
32
- let _dynamic_labs_sdk_api_core = require("@dynamic-labs/sdk-api-core");
33
- let bitcoinjs_lib = require("bitcoinjs-lib");
34
- let _dynamic_labs_sdk_client_waas_core = require("@dynamic-labs-sdk/client/waas/core");
35
- let _bitcoinerlab_secp256k1 = require("@bitcoinerlab/secp256k1");
36
- _bitcoinerlab_secp256k1 = __toESM(_bitcoinerlab_secp256k1);
37
- let ecpair = require("ecpair");
38
-
39
- //#region src/errors/TransactionBroadcastFailedError.ts
40
- var TransactionBroadcastFailedError = class extends _dynamic_labs_sdk_client.BaseError {
41
- response;
42
- constructor({ response }) {
43
- super({
44
- cause: null,
45
- code: "transaction_broadcast_failed_error",
46
- details: `Status: ${response.status} ${response.statusText}`,
47
- docsUrl: null,
48
- name: "TransactionBroadcastFailedError",
49
- shortMessage: "Failed to broadcast transaction to mempool"
50
- });
51
- this.response = response;
52
- }
53
- };
54
-
55
- //#endregion
56
- //#region src/errors/TransactionRequiredError.ts
57
- var TransactionRequiredError = class extends _dynamic_labs_sdk_client.BaseError {
58
- constructor() {
59
- super({
60
- cause: null,
61
- code: "transaction_required_error",
62
- docsUrl: null,
63
- name: "TransactionRequiredError",
64
- shortMessage: "No transaction specified for broadcast"
65
- });
66
- }
67
- };
68
-
69
- //#endregion
70
- //#region src/waas/constants.ts
71
- /**
72
- * Mempool.space API URL for mainnet
73
- */
74
- const MEMPOOL_API_URL = "https://mempool.space/api";
75
- /**
76
- * Number of satoshis per Bitcoin
77
- */
78
- const SATOSHIS_PER_BTC = 1e8;
79
- /**
80
- * Bitcoin's dust limit in satoshis
81
- * Outputs below this value are considered "dust" and will be rejected by nodes
82
- */
83
- const DUST_LIMIT = 546;
84
- /**
85
- * Accurate vSize constants for Native SegWit (P2WPKH) transactions
86
- * Used for precise fee estimation
87
- */
88
- const VSIZE_OVERHEAD = 10.5;
89
- const VSIZE_INPUT_P2WPKH = 68;
90
- const VSIZE_OUTPUT_P2WPKH = 31;
91
- /**
92
- * Minimum relay fee in satoshis
93
- * Added to fee estimate to ensure transaction propagation
94
- */
95
- const MIN_RELAY_FEE = 111;
96
- /**
97
- * Conservative default fee estimate in satoshis
98
- * Used as fallback when fee estimation fails
99
- */
100
- const DEFAULT_FEE_ESTIMATE = 1e3;
101
- /**
102
- * RBF (Replace-By-Fee) sequence number
103
- * 0xfffffffd = 4294967293 (enables RBF, not final)
104
- */
105
- const RBF_SEQUENCE = 4294967293;
106
-
107
- //#endregion
108
- //#region src/waas/utils/broadcastTransaction/broadcastTransaction.ts
109
- /**
110
- * Sends a raw Bitcoin transaction to the mempool
111
- *
112
- * @param rawTransaction - The raw transaction in hex format
113
- * @returns The transaction ID
114
- * @throws {TransactionRequiredError} if no transaction is specified
115
- * @throws {TransactionBroadcastFailedError} if broadcasting fails
116
- * @not-instrumented
117
- */
118
- const broadcastTransaction = async (rawTransaction) => {
119
- if (!rawTransaction) throw new TransactionRequiredError();
120
- const response = await fetch(`${MEMPOOL_API_URL}/tx`, {
121
- body: rawTransaction,
122
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
123
- method: "POST"
124
- });
125
- if (!response.ok) throw new TransactionBroadcastFailedError({ response });
126
- return response.text();
127
- };
128
-
129
- //#endregion
130
- //#region src/errors/InsufficientFundsError.ts
131
- var InsufficientFundsError = class extends _dynamic_labs_sdk_client.BaseError {
132
- availableSatoshis;
133
- requiredSatoshis;
134
- constructor({ availableSatoshis, requiredSatoshis }) {
135
- const availableBtc = availableSatoshis / SATOSHIS_PER_BTC;
136
- const requiredBtc = requiredSatoshis / SATOSHIS_PER_BTC;
137
- super({
138
- cause: null,
139
- code: "insufficient_funds_error",
140
- details: `Available: ${availableBtc} BTC (${availableSatoshis} satoshis), Required: ${requiredBtc} BTC (${requiredSatoshis} satoshis)`,
141
- docsUrl: null,
142
- name: "InsufficientFundsError",
143
- shortMessage: "Insufficient funds for transaction"
144
- });
145
- this.availableSatoshis = availableSatoshis;
146
- this.requiredSatoshis = requiredSatoshis;
147
- }
148
- };
149
-
150
- //#endregion
151
- //#region src/errors/InvalidAmountError.ts
152
- var InvalidAmountError = class extends _dynamic_labs_sdk_client.BaseError {
153
- amountInSatoshis;
154
- constructor({ amountInSatoshis, reason }) {
155
- super({
156
- cause: null,
157
- code: "invalid_amount_error",
158
- details: `Amount: ${amountInSatoshis} satoshis`,
159
- docsUrl: null,
160
- name: "InvalidAmountError",
161
- shortMessage: reason
162
- });
163
- this.amountInSatoshis = amountInSatoshis;
164
- }
165
- };
166
-
167
- //#endregion
168
- //#region src/errors/NoUTXOsFoundError.ts
169
- var NoUTXOsFoundError = class extends _dynamic_labs_sdk_client.BaseError {
170
- address;
171
- constructor({ address: address$1 }) {
172
- super({
173
- cause: null,
174
- code: "no_utxos_found_error",
175
- details: `Address: ${address$1}`,
176
- docsUrl: null,
177
- name: "NoUTXOsFoundError",
178
- shortMessage: "No UTXOs found for this address"
179
- });
180
- this.address = address$1;
181
- }
182
- };
183
-
184
- //#endregion
185
- //#region src/errors/SegwitOutputScriptError.ts
186
- var SegwitOutputScriptError = class extends _dynamic_labs_sdk_client.BaseError {
187
- constructor() {
188
- super({
189
- cause: null,
190
- code: "segwit_output_script_error",
191
- docsUrl: null,
192
- name: "SegwitOutputScriptError",
193
- shortMessage: "Failed to create segwit output script"
194
- });
195
- }
196
- };
197
-
198
- //#endregion
199
- //#region src/waas/utils/addInputsToPsbt/addInputsToPsbt.ts
200
- /**
201
- * Adds inputs to PSBT from selected UTXOs
202
- *
203
- * @param options.network - Bitcoin network configuration (mainnet or testnet)
204
- * @param options.psbt - The PSBT instance to add inputs to
205
- * @param options.publicKeyPair - Key pair containing the public key for witness script
206
- * @param options.selectedUTXOs - Array of UTXOs to add as inputs
207
- * @not-instrumented
208
- */
209
- const addInputsToPsbt = (options) => {
210
- const { network, psbt, publicKeyPair, selectedUTXOs } = options;
211
- for (const utxo of selectedUTXOs) {
212
- const outputScript = bitcoinjs_lib.payments.p2wpkh({
213
- network,
214
- pubkey: publicKeyPair.publicKey
215
- }).output;
216
- if (!outputScript) throw new SegwitOutputScriptError();
217
- const txidBuffer = new Uint8Array((0, _dynamic_labs_sdk_client_core.getBuffer)().from(utxo.txid, "hex").reverse());
218
- psbt.addInput({
219
- hash: txidBuffer,
220
- index: utxo.vout,
221
- sequence: RBF_SEQUENCE,
222
- witnessUtxo: {
223
- script: outputScript,
224
- value: BigInt(utxo.value)
225
- }
226
- });
227
- }
228
- };
229
-
230
- //#endregion
231
- //#region src/waas/utils/addOutputsToPsbt/addOutputsToPsbt.ts
232
- /**
233
- * Adds outputs to PSBT (recipient and optionally change)
234
- *
235
- * @param options.accountAddress - The sender's address for receiving change
236
- * @param options.amountInSatoshis - Amount to send to the recipient in satoshis
237
- * @param options.changeAmount - Amount to return as change in satoshis
238
- * @param options.hasChangeOutput - Whether to include a change output
239
- * @param options.network - Bitcoin network configuration (mainnet or testnet)
240
- * @param options.psbt - The PSBT instance to add outputs to
241
- * @param options.recipientAddress - The recipient's Bitcoin address
242
- * @not-instrumented
243
- */
244
- const addOutputsToPsbt = (options) => {
245
- const { accountAddress, amountInSatoshis, changeAmount, hasChangeOutput, network, psbt, recipientAddress } = options;
246
- if (amountInSatoshis < DUST_LIMIT) throw new InvalidAmountError({
247
- amountInSatoshis,
248
- reason: `Amount is below dust limit of ${DUST_LIMIT} satoshis (${DUST_LIMIT / SATOSHIS_PER_BTC} BTC)`
249
- });
250
- psbt.addOutput({
251
- script: bitcoinjs_lib.address.toOutputScript(recipientAddress, network),
252
- value: BigInt(amountInSatoshis)
253
- });
254
- if (hasChangeOutput) psbt.addOutput({
255
- script: bitcoinjs_lib.address.toOutputScript(accountAddress, network),
256
- value: BigInt(changeAmount)
257
- });
258
- };
259
-
260
- //#endregion
261
- //#region src/errors/FeeRecommendationsFetchError.ts
262
- var FeeRecommendationsFetchError = class extends _dynamic_labs_sdk_client.BaseError {
263
- response;
264
- constructor({ response }) {
265
- super({
266
- cause: null,
267
- code: "fee_recommendations_fetch_error",
268
- details: `Status: ${response.status} ${response.statusText}`,
269
- docsUrl: null,
270
- name: "FeeRecommendationsFetchError",
271
- shortMessage: "Failed to fetch fee recommendations from mempool"
272
- });
273
- this.response = response;
274
- }
275
- };
276
-
277
- //#endregion
278
- //#region src/waas/utils/getFeeRecommendations/getFeeRecommendations.ts
279
- /**
280
- * Gets fee recommendations from mempool.space API
281
- *
282
- * @returns Fee recommendation data with rates in sat/vB
283
- * @throws FeeRecommendationsFetchError if fetching fee recommendations fails
284
- * @not-instrumented
285
- */
286
- const getFeeRecommendations = async () => {
287
- const response = await fetch(`${MEMPOOL_API_URL}/v1/fees/recommended`);
288
- if (!response.ok) throw new FeeRecommendationsFetchError({ response });
289
- return response.json();
290
- };
291
-
292
- //#endregion
293
- //#region src/waas/utils/estimateTransactionFee/estimateTransactionFee.ts
294
- /**
295
- * Estimates transaction fees based on number of inputs and outputs using accurate vSize
296
- *
297
- * @param options.feePriority - Priority level for fee estimation ('low', 'medium', or 'high')
298
- * @param options.numInputs - Number of transaction inputs (UTXOs being spent)
299
- * @param options.numOutputs - Number of transaction outputs
300
- * @returns Estimated fee in satoshis
301
- * @not-instrumented
302
- */
303
- const estimateTransactionFee = async ({ feePriority = "medium", numInputs, numOutputs }) => {
304
- try {
305
- const feeData = await getFeeRecommendations();
306
- let feePerByte;
307
- if (feePriority === "high") feePerByte = feeData.fastestFee ?? feeData.halfHourFee ?? 1;
308
- else if (feePriority === "low") feePerByte = feeData.economyFee ?? feeData.hourFee ?? 1;
309
- else feePerByte = feeData.halfHourFee ?? feeData.hourFee ?? feeData.economyFee ?? 1;
310
- const vSize = VSIZE_OVERHEAD + numInputs * VSIZE_INPUT_P2WPKH + numOutputs * VSIZE_OUTPUT_P2WPKH;
311
- return Math.ceil(feePerByte * vSize) + MIN_RELAY_FEE;
312
- } catch {
313
- return DEFAULT_FEE_ESTIMATE;
314
- }
315
- };
316
-
317
- //#endregion
318
- //#region src/waas/utils/calculateFeeAndChange/calculateFeeAndChange.ts
319
- /**
320
- * Calculates fee estimate and change amount, handling dust limit
321
- *
322
- * @param options.amountInSatoshis - Amount to send in satoshis
323
- * @param options.feePriority - Priority level for fee estimation ('low', 'medium', or 'high')
324
- * @param options.selectedTotalValue - Total value of selected UTXOs in satoshis
325
- * @param options.selectedUTXOs - Array of selected UTXOs for the transaction
326
- * @returns Object with feeEstimate, changeAmountNumber, and hasChangeOutput
327
- * @not-instrumented
328
- */
329
- const calculateFeeAndChange = async ({ amountInSatoshis, feePriority, selectedTotalValue, selectedUTXOs }) => {
330
- let feeEstimate = await estimateTransactionFee({
331
- feePriority,
332
- numInputs: selectedUTXOs.length,
333
- numOutputs: 1
334
- });
335
- let maxToSpend = selectedTotalValue - feeEstimate;
336
- let changeAmount = BigInt(maxToSpend) - amountInSatoshis;
337
- if (changeAmount > 0 && Number(changeAmount) >= DUST_LIMIT) {
338
- feeEstimate = await estimateTransactionFee({
339
- feePriority,
340
- numInputs: selectedUTXOs.length,
341
- numOutputs: 2
342
- });
343
- maxToSpend = selectedTotalValue - feeEstimate;
344
- changeAmount = BigInt(maxToSpend) - amountInSatoshis;
345
- }
346
- const finalChangeAmountNumber = Number(changeAmount);
347
- const hasChangeOutput = changeAmount > 0 && finalChangeAmountNumber >= DUST_LIMIT;
348
- if (changeAmount > 0 && finalChangeAmountNumber < DUST_LIMIT) feeEstimate += finalChangeAmountNumber;
349
- return {
350
- changeAmountNumber: finalChangeAmountNumber,
351
- feeEstimate,
352
- hasChangeOutput
353
- };
354
- };
355
-
356
- //#endregion
357
- //#region src/waas/utils/calculateUTXOTotal/calculateUTXOTotal.ts
358
- /**
359
- * Calculates the total value of UTXOs
360
- *
361
- * @param utxos - Array of UTXOs
362
- * @returns Total value in satoshis
363
- * @not-instrumented
364
- */
365
- const calculateUTXOTotal = (utxos) => utxos.reduce((total, utxo) => total + utxo.value, 0);
366
-
367
- //#endregion
368
- //#region src/errors/UTXOsFetchError.ts
369
- var UTXOsFetchError = class extends _dynamic_labs_sdk_client.BaseError {
370
- address;
371
- response;
372
- constructor({ address: address$1, response }) {
373
- super({
374
- cause: null,
375
- code: "utxos_fetch_error",
376
- details: `Address: ${address$1}, Status: ${response.status} ${response.statusText}`,
377
- docsUrl: null,
378
- name: "UTXOsFetchError",
379
- shortMessage: "Failed to fetch UTXOs from mempool"
380
- });
381
- this.address = address$1;
382
- this.response = response;
383
- }
384
- };
385
-
386
- //#endregion
387
- //#region src/waas/utils/getUTXOs/getUTXOs.ts
388
- /**
389
- * Gets UTXOs for a Bitcoin address from mempool.space API
390
- *
391
- * @param address - The Bitcoin address to get UTXOs for
392
- * @returns Array of UTXOs
393
- * @throws UTXOsFetchError if fetching UTXOs fails
394
- * @not-instrumented
395
- */
396
- const getUTXOs = async (address$1) => {
397
- const response = await fetch(`${MEMPOOL_API_URL}/address/${address$1}/utxo`);
398
- if (!response.ok) throw new UTXOsFetchError({
399
- address: address$1,
400
- response
401
- });
402
- return response.json();
403
- };
404
-
405
- //#endregion
406
- //#region src/waas/utils/selectUTXOsLargestFirst/selectUTXOsLargestFirst.ts
407
- /**
408
- * Selects UTXOs using Largest-First (Accumulator) strategy
409
- * Sorts UTXOs by value (descending) and selects until we have enough to cover amount + fees
410
- *
411
- * @param options.targetAmount - Target amount in satoshis (amount + fees + dust limit)
412
- * @param options.utxos - Array of available UTXOs to select from
413
- * @returns Selected UTXOs
414
- * @not-instrumented
415
- */
416
- const selectUTXOsLargestFirst = (options) => {
417
- const { targetAmount, utxos } = options;
418
- const sortedUTXOs = [...utxos].sort((a, b) => b.value - a.value);
419
- const selected = [];
420
- let total = 0;
421
- for (const utxo of sortedUTXOs) {
422
- selected.push(utxo);
423
- total += utxo.value;
424
- if (total >= targetAmount) break;
425
- }
426
- return selected;
427
- };
428
-
429
- //#endregion
430
- //#region src/waas/utils/validateAndSelectUTXOs/validateAndSelectUTXOs.ts
431
- /**
432
- * Validates and ensures sufficient funds for the transaction
433
- *
434
- * @param options.allUTXOs - Complete array of available UTXOs for the address
435
- * @param options.amountInSatoshis - Amount to send in satoshis
436
- * @param options.feeEstimate - Estimated transaction fee in satoshis
437
- * @param options.selectedTotal - Total value of initially selected UTXOs in satoshis
438
- * @param options.selectedUTXOs - Array of initially selected UTXOs
439
- * @returns Validated selected UTXOs
440
- * @throws InsufficientFundsError if insufficient funds
441
- * @not-instrumented
442
- */
443
- const validateAndSelectUTXOs = (options) => {
444
- const { allUTXOs, amountInSatoshis, feeEstimate, selectedTotal, selectedUTXOs } = options;
445
- const requiredAmount = amountInSatoshis + feeEstimate;
446
- if (selectedTotal >= requiredAmount) return selectedUTXOs;
447
- if (selectedUTXOs.length < allUTXOs.length) {
448
- const allTotal = calculateUTXOTotal(allUTXOs);
449
- if (allTotal < requiredAmount) throw new InsufficientFundsError({
450
- availableSatoshis: allTotal,
451
- requiredSatoshis: amountInSatoshis
452
- });
453
- return allUTXOs;
454
- }
455
- throw new InsufficientFundsError({
456
- availableSatoshis: selectedTotal,
457
- requiredSatoshis: amountInSatoshis
458
- });
459
- };
460
-
461
- //#endregion
462
- //#region src/errors/TaprootAddressNotSupportedError.ts
463
- var TaprootAddressNotSupportedError = class extends _dynamic_labs_sdk_client.BaseError {
464
- constructor() {
465
- super({
466
- cause: null,
467
- code: "taproot_address_not_supported",
468
- docsUrl: null,
469
- name: "TaprootAddressNotSupportedError",
470
- shortMessage: "Taproot addresses are not supported for PSBT building. Only Native SegWit (P2WPKH) addresses are allowed."
471
- });
472
- }
473
- };
474
-
475
- //#endregion
476
- //#region src/waas/utils/validateNotTaproot/validateNotTaproot.ts
477
- /**
478
- * Validates that the address is not a Taproot address
479
- * Only Native SegWit (P2WPKH) is supported for PSBT building
480
- *
481
- * @param accountAddress - The account address to check
482
- * @throws TaprootAddressNotSupportedError if address is Taproot
483
- * @not-instrumented
484
- */
485
- const validateNotTaproot = (accountAddress) => {
486
- if (accountAddress.toLowerCase().startsWith("bc1p") || accountAddress.toLowerCase().startsWith("tb1p")) throw new TaprootAddressNotSupportedError();
487
- };
488
7
 
489
- //#endregion
490
- //#region src/waas/utils/buildPsbt/buildPsbt.ts
491
- /**
492
- * Builds a PSBT for a Bitcoin transaction with real UTXOs
493
- * Uses Largest-First UTXO selection strategy with accurate vSize fee estimation
494
- *
495
- * @param options.accountAddress - The sender's Bitcoin address
496
- * @param options.amountInSatoshis - Amount to send in satoshis
497
- * @param options.feePriority - Priority level for fee estimation ('low', 'medium', or 'high')
498
- * @param options.network - Bitcoin network configuration (mainnet or testnet)
499
- * @param options.publicKeyHex - The sender's public key in hexadecimal format
500
- * @param options.recipientAddress - The recipient's Bitcoin address
501
- * @returns A PSBT in Base64 format
502
- * @throws Error if insufficient funds, no UTXOs, or other errors
503
- * @not-instrumented
504
- */
505
- const buildPsbt = async ({ accountAddress, amountInSatoshis, feePriority = "medium", network, publicKeyHex, recipientAddress }) => {
506
- if (amountInSatoshis <= BigInt(0)) throw new InvalidAmountError({
507
- amountInSatoshis: Number(amountInSatoshis),
508
- reason: "Amount must be greater than 0"
509
- });
510
- validateNotTaproot(accountAddress);
511
- const allUTXOs = await getUTXOs(accountAddress);
512
- if (allUTXOs.length === 0) throw new NoUTXOsFoundError({ address: accountAddress });
513
- const publicKeyBuffer = new Uint8Array((0, _dynamic_labs_sdk_client_core.getBuffer)().from(publicKeyHex, "hex"));
514
- const publicKeyPair = (0, ecpair.ECPairFactory)(_bitcoinerlab_secp256k1.default).fromPublicKey(publicKeyBuffer, { compressed: true });
515
- const amountInSatoshisNumber = Number(amountInSatoshis);
516
- const initialFeeEstimate = await estimateTransactionFee({
517
- feePriority,
518
- numInputs: 1,
519
- numOutputs: 1
520
- });
521
- let selectedUTXOs = selectUTXOsLargestFirst({
522
- targetAmount: amountInSatoshisNumber + initialFeeEstimate + DUST_LIMIT,
523
- utxos: allUTXOs
524
- });
525
- selectedUTXOs = validateAndSelectUTXOs({
526
- allUTXOs,
527
- amountInSatoshis: amountInSatoshisNumber,
528
- feeEstimate: initialFeeEstimate,
529
- selectedTotal: calculateUTXOTotal(selectedUTXOs),
530
- selectedUTXOs
531
- });
532
- const selectedTotalValue = calculateUTXOTotal(selectedUTXOs);
533
- const { changeAmountNumber, feeEstimate, hasChangeOutput } = await calculateFeeAndChange({
534
- amountInSatoshis,
535
- feePriority,
536
- selectedTotalValue,
537
- selectedUTXOs
538
- });
539
- const maxToSpend = selectedTotalValue - feeEstimate;
540
- if (maxToSpend < amountInSatoshisNumber) throw new InsufficientFundsError({
541
- availableSatoshis: maxToSpend,
542
- requiredSatoshis: amountInSatoshisNumber
543
- });
544
- const psbt = new bitcoinjs_lib.Psbt({ network });
545
- addInputsToPsbt({
546
- network,
547
- psbt,
548
- publicKeyPair,
549
- selectedUTXOs
550
- });
551
- addOutputsToPsbt({
552
- accountAddress,
553
- amountInSatoshis: amountInSatoshisNumber,
554
- changeAmount: changeAmountNumber,
555
- hasChangeOutput,
556
- network,
557
- psbt,
558
- recipientAddress
559
- });
560
- return psbt.toBase64();
561
- };
562
-
563
- //#endregion
564
- //#region src/errors/PublicKeyNotFoundError.ts
565
- var PublicKeyNotFoundError = class extends _dynamic_labs_sdk_client.BaseError {
566
- constructor(address$1) {
567
- super({
568
- cause: null,
569
- code: "public_key_not_found_error",
570
- docsUrl: null,
571
- name: "PublicKeyNotFoundError",
572
- shortMessage: `No public key found for address ${address$1}`
573
- });
574
- }
575
- };
576
-
577
- //#endregion
578
- //#region src/waas/utils/getPublicKeyForWalletAccount/getPublicKeyForWalletAccount.ts
579
- /**
580
- * Gets the public key for a wallet account from the user's verified credentials
581
- * @not-instrumented
582
- */
583
- const getPublicKeyForWalletAccount = (walletAccount, client) => {
584
- const user = (0, _dynamic_labs_sdk_client_core.getCore)(client).state.get().user;
585
- for (const credential of user?.verifiedCredentials ?? []) {
586
- const additionalAddress = credential.walletAdditionalAddresses?.find((addr) => addr.address === walletAccount.address);
587
- if (additionalAddress?.publicKey) return additionalAddress.publicKey;
588
- }
589
- throw new PublicKeyNotFoundError(walletAccount.address);
590
- };
591
-
592
- //#endregion
593
- //#region src/waas/utils/createWalletProviderForWaasBitcoin/createWalletProviderForWaasBitcoin.ts
594
- /** @not-instrumented */
595
- const createWalletProviderForWaasBitcoin = (sdkClient) => {
596
- const chain = "BTC";
597
- const walletProviderType = _dynamic_labs_sdk_api_core.WalletProviderEnum.EmbeddedWallet;
598
- const key = (0, _dynamic_labs_sdk_client_core.formatWalletProviderKey)({
599
- chain,
600
- displayName: _dynamic_labs_sdk_client_waas_core.DYNAMIC_WAAS_METADATA.displayName,
601
- walletProviderType
602
- });
603
- const waasProvider = (0, _dynamic_labs_sdk_client_waas_core.createWaasProvider)({
604
- chain,
605
- sdkClient
606
- });
607
- const getActiveNetworkId = async () => (0, _dynamic_labs_sdk_client_core.getActiveNetworkIdFromLastKnownRegistry)({
608
- client: sdkClient,
609
- walletProviderKey: key
610
- });
611
- const switchActiveNetwork = async ({ networkId }) => (0, _dynamic_labs_sdk_client_core.switchActiveNetworkInLastKnownRegistry)({
612
- client: sdkClient,
613
- networkId,
614
- walletProviderKey: key
615
- });
616
- const getConnectedAddresses = async () => {
617
- return { addresses: (0, _dynamic_labs_sdk_client_waas_core.getAllUserWaasAddressesForChain)({ chain }, sdkClient) };
618
- };
619
- const signPsbt$1 = async ({ request, walletAccount }) => {
620
- (0, _dynamic_labs_sdk_client_core.assertDefined)(walletAccount, "Wallet account is required");
621
- const waasClient = await waasProvider.getWaasClient();
622
- const { signature: signedSessionId } = await (0, _dynamic_labs_sdk_client_core.getSignedSessionId)(sdkClient);
623
- const mfaToken = await (0, _dynamic_labs_sdk_client_core.consumeMfaTokenIfRequiredForAction)({ mfaAction: _dynamic_labs_sdk_api_core.MFAAction.WalletWaasSign }, sdkClient);
624
- return { signedPsbt: await waasClient.signTransaction({
625
- authToken: sdkClient.token ?? void 0,
626
- mfaToken,
627
- senderAddress: walletAccount.address,
628
- signedSessionId,
629
- transaction: request.unsignedPsbtBase64
630
- }) };
631
- };
632
- const signPsbts$1 = async ({ requests, walletAccount }) => {
633
- (0, _dynamic_labs_sdk_client_core.assertDefined)(walletAccount, "Wallet account is required");
634
- return { signedPsbts: await Promise.all(requests.map(async (request) => {
635
- const { signedPsbt } = await signPsbt$1({
636
- request,
637
- walletAccount
638
- });
639
- return signedPsbt;
640
- })) };
641
- };
642
- const signMessage = async ({ message, walletAccount }) => {
643
- (0, _dynamic_labs_sdk_client_core.assertDefined)(walletAccount, "Wallet account is required");
644
- const waasClient = await waasProvider.getWaasClient();
645
- const { signature: signedSessionId } = await (0, _dynamic_labs_sdk_client_core.getSignedSessionId)(sdkClient);
646
- const mfaToken = await (0, _dynamic_labs_sdk_client_core.consumeMfaTokenIfRequiredForAction)({ mfaAction: _dynamic_labs_sdk_api_core.MFAAction.WalletWaasSign }, sdkClient);
647
- return { signature: await waasClient.signMessage({
648
- accountAddress: walletAccount.address,
649
- authToken: sdkClient.token ?? void 0,
650
- bitcoinConfig: { network: "mainnet" },
651
- message,
652
- mfaToken,
653
- signedSessionId
654
- }) };
655
- };
656
- const buildPsbt$1 = async ({ transaction, walletAccount }) => {
657
- (0, _dynamic_labs_sdk_client_core.assertDefined)(walletAccount, "Wallet account is required");
658
- const publicKeyHex = getPublicKeyForWalletAccount(walletAccount, sdkClient);
659
- return buildPsbt({
660
- accountAddress: walletAccount.address,
661
- amountInSatoshis: transaction.amount,
662
- feePriority: transaction.feePriority ?? "medium",
663
- network: bitcoinjs_lib.networks.bitcoin,
664
- publicKeyHex,
665
- recipientAddress: transaction.recipientAddress
666
- });
667
- };
668
- const sendBitcoin$1 = async ({ transaction, walletAccount }) => {
669
- (0, _dynamic_labs_sdk_client_core.assertDefined)(walletAccount, "Wallet account is required");
670
- const { signedPsbt } = await signPsbt$1({
671
- request: {
672
- allowedSighash: [],
673
- unsignedPsbtBase64: await buildPsbt$1({
674
- transaction: {
675
- amount: transaction.amount,
676
- recipientAddress: transaction.recipientAddress
677
- },
678
- walletAccount
679
- })
680
- },
681
- walletAccount
682
- });
683
- const psbt = bitcoinjs_lib.Psbt.fromBase64(signedPsbt, { network: bitcoinjs_lib.networks.bitcoin });
684
- psbt.finalizeAllInputs();
685
- return { transactionId: await broadcastTransaction(psbt.extractTransaction().toHex()) };
686
- };
687
- return {
688
- ...waasProvider,
689
- buildPsbt: buildPsbt$1,
690
- chain,
691
- executeSwapTransaction: (args) => require_addBitcoinInjectedWalletsExtension.bitcoinExecuteSwapTransaction(args, sdkClient),
692
- getActiveNetworkId,
693
- getConnectedAddresses,
694
- groupKey: (0, _dynamic_labs_sdk_client_core.formatWalletProviderGroupKey)(_dynamic_labs_sdk_client_waas_core.DYNAMIC_WAAS_METADATA.displayName),
695
- key,
696
- metadata: {
697
- displayName: _dynamic_labs_sdk_client_waas_core.DYNAMIC_WAAS_METADATA.displayName,
698
- icon: _dynamic_labs_sdk_client_waas_core.DYNAMIC_WAAS_METADATA.icon
699
- },
700
- sendBitcoin: sendBitcoin$1,
701
- signMessage,
702
- signPsbt: signPsbt$1,
703
- signPsbts: signPsbts$1,
704
- switchActiveNetwork,
705
- transferAmount: (args) => require_addBitcoinInjectedWalletsExtension.bitcoinTransferAmount(args, sdkClient),
706
- walletProviderType
707
- };
708
- };
709
-
710
- //#endregion
711
- //#region src/waas/addWaasBitcoinExtension/addWaasBitcoinExtension.ts
712
- const WAAS_BITCOIN_EXTENSION_KEY = "waasBitcoin";
713
- /**
714
- * Adds the Dynamic WaaS (Wallet as a Service) Bitcoin extension to the Dynamic client.
715
- *
716
- * This extension enables embedded wallet functionality for Bitcoin blockchain,
717
- * allowing users to have wallets managed by Dynamic's infrastructure.
718
- *
719
- * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
720
- * @not-instrumented
721
- */
722
- const addWaasBitcoinExtension = (client = (0, _dynamic_labs_sdk_client_core.getDefaultClient)()) => {
723
- if ((0, _dynamic_labs_sdk_client_core.hasExtension)({ extensionKey: WAAS_BITCOIN_EXTENSION_KEY }, client)) return;
724
- (0, _dynamic_labs_sdk_client_core.registerExtension)({ extensionKey: WAAS_BITCOIN_EXTENSION_KEY }, client);
725
- require_addBitcoinInjectedWalletsExtension.registerBitcoinNetworkProviderBuilder(client);
726
- const walletProviderRegistry = (0, _dynamic_labs_sdk_client_core.getWalletProviderRegistry)(client);
727
- const walletProvider = createWalletProviderForWaasBitcoin(client);
728
- walletProviderRegistry.register({
729
- priority: _dynamic_labs_sdk_client_core.WalletProviderPriority.WALLET_SDK,
730
- walletProvider
731
- });
732
- };
733
-
734
- //#endregion
735
8
  //#region src/addBitcoinExtension/addBitcoinExtension.ts
736
9
  /**
737
10
  * Adds the Bitcoin extension to the Dynamic client.
@@ -746,7 +19,7 @@ const addWaasBitcoinExtension = (client = (0, _dynamic_labs_sdk_client_core.getD
746
19
  */
747
20
  const addBitcoinExtension = (client = (0, _dynamic_labs_sdk_client_core.getDefaultClient)()) => {
748
21
  require_addBitcoinInjectedWalletsExtension.addBitcoinInjectedWalletsExtension(client);
749
- addWaasBitcoinExtension(client);
22
+ require_addWaasBitcoinExtension.addWaasBitcoinExtension(client);
750
23
  };
751
24
 
752
25
  //#endregion
@@ -779,7 +52,7 @@ const isBitcoinNetworkProvider = (networkProvider) => networkProvider.chain ===
779
52
  */
780
53
  const signMessageWithCustomOptions = async ({ walletAccount, message, protocol, addressType }, client = (0, _dynamic_labs_sdk_client.getDefaultClient)()) => {
781
54
  const provider = (0, _dynamic_labs_sdk_client_core.getWalletProviderFromWalletAccount)({ walletAccount }, client);
782
- if (!require_addBitcoinInjectedWalletsExtension.isBitcoinWalletProvider(provider)) throw new require_addBitcoinInjectedWalletsExtension.NotBitcoinProviderError({ providerKey: provider.key });
55
+ if (!require_bitcoinTransferAmount.isBitcoinWalletProvider(provider)) throw new require_bitcoinTransferAmount.NotBitcoinProviderError({ providerKey: provider.key });
783
56
  if (!provider.signMessage) throw new _dynamic_labs_sdk_client_core.MethodNotImplementedError("signMessage");
784
57
  return provider.signMessage({
785
58
  addressType,
@@ -801,7 +74,7 @@ const signMessageWithCustomOptions = async ({ walletAccount, message, protocol,
801
74
  */
802
75
  const signPsbt = async ({ walletAccount, request }, client = (0, _dynamic_labs_sdk_client.getDefaultClient)()) => {
803
76
  const provider = (0, _dynamic_labs_sdk_client_core.getWalletProviderFromWalletAccount)({ walletAccount }, client);
804
- if (!require_addBitcoinInjectedWalletsExtension.isBitcoinWalletProvider(provider)) throw new require_addBitcoinInjectedWalletsExtension.NotBitcoinProviderError({ providerKey: provider.key });
77
+ if (!require_bitcoinTransferAmount.isBitcoinWalletProvider(provider)) throw new require_bitcoinTransferAmount.NotBitcoinProviderError({ providerKey: provider.key });
805
78
  return provider.signPsbt({
806
79
  request,
807
80
  walletAccount
@@ -820,7 +93,7 @@ const signPsbt = async ({ walletAccount, request }, client = (0, _dynamic_labs_s
820
93
  */
821
94
  const signPsbts = async ({ walletAccount, requests }, client = (0, _dynamic_labs_sdk_client.getDefaultClient)()) => {
822
95
  const provider = (0, _dynamic_labs_sdk_client_core.getWalletProviderFromWalletAccount)({ walletAccount }, client);
823
- if (!require_addBitcoinInjectedWalletsExtension.isBitcoinWalletProvider(provider)) throw new require_addBitcoinInjectedWalletsExtension.NotBitcoinProviderError({ providerKey: provider.key });
96
+ if (!require_bitcoinTransferAmount.isBitcoinWalletProvider(provider)) throw new require_bitcoinTransferAmount.NotBitcoinProviderError({ providerKey: provider.key });
824
97
  return provider.signPsbts({
825
98
  requests,
826
99
  walletAccount
@@ -829,18 +102,17 @@ const signPsbts = async ({ walletAccount, requests }, client = (0, _dynamic_labs
829
102
 
830
103
  //#endregion
831
104
  //#region src/exports/index.ts
832
- (0, _dynamic_labs_sdk_assert_package_version.assertPackageVersion)(require_addBitcoinInjectedWalletsExtension.name, require_addBitcoinInjectedWalletsExtension.version);
105
+ (0, _dynamic_labs_sdk_assert_package_version.assertPackageVersion)(require_bitcoinTransferAmount.name, require_bitcoinTransferAmount.version);
833
106
 
834
107
  //#endregion
835
108
  exports.InvalidPsbtError = require_addBitcoinInjectedWalletsExtension.InvalidPsbtError;
836
- exports.TransactionBroadcastFailedError = TransactionBroadcastFailedError;
837
- exports.TransactionRequiredError = TransactionRequiredError;
838
- exports.__toESM = __toESM;
109
+ exports.TransactionBroadcastFailedError = require_addWaasBitcoinExtension.TransactionBroadcastFailedError;
110
+ exports.TransactionRequiredError = require_addWaasBitcoinExtension.TransactionRequiredError;
839
111
  exports.addBitcoinExtension = addBitcoinExtension;
840
112
  exports.isBitcoinNetworkProvider = isBitcoinNetworkProvider;
841
- exports.isBitcoinWalletAccount = require_addBitcoinInjectedWalletsExtension.isBitcoinWalletAccount;
842
- exports.sendBitcoin = require_addBitcoinInjectedWalletsExtension.sendBitcoin;
843
- exports.sendRawTransaction = require_addBitcoinInjectedWalletsExtension.sendRawTransaction;
113
+ exports.isBitcoinWalletAccount = require_bitcoinTransferAmount.isBitcoinWalletAccount;
114
+ exports.sendBitcoin = require_bitcoinTransferAmount.sendBitcoin;
115
+ exports.sendRawTransaction = require_bitcoinTransferAmount.sendRawTransaction;
844
116
  exports.signMessageWithCustomOptions = signMessageWithCustomOptions;
845
117
  exports.signPsbt = signPsbt;
846
118
  exports.signPsbts = signPsbts;