@sidhujag/sysweb3-keyring 2.1.3 → 2.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +47 -47
  3. package/cjs/hardware-transaction-authority.js +36 -0
  4. package/cjs/hardware-transaction-authority.js.map +1 -0
  5. package/cjs/index.js +5 -5
  6. package/cjs/index.js.map +1 -1
  7. package/cjs/keyring-core.js +171 -220
  8. package/cjs/keyring-core.js.map +1 -1
  9. package/cjs/keyring-host.js +113 -0
  10. package/cjs/keyring-host.js.map +1 -0
  11. package/cjs/keyring-manager.js +15 -151
  12. package/cjs/keyring-manager.js.map +1 -1
  13. package/cjs/ledger/host-types.js.map +1 -1
  14. package/cjs/ledger/index.js +44 -19
  15. package/cjs/ledger/index.js.map +1 -1
  16. package/cjs/providers.js +3 -1
  17. package/cjs/providers.js.map +1 -1
  18. package/cjs/software.js +10 -56
  19. package/cjs/software.js.map +1 -1
  20. package/cjs/transactions/ethereum.js +306 -229
  21. package/cjs/transactions/ethereum.js.map +1 -1
  22. package/cjs/transactions/evm-local-signer.js +15 -0
  23. package/cjs/transactions/evm-local-signer.js.map +1 -1
  24. package/cjs/transactions/evm-submission.js +61 -65
  25. package/cjs/transactions/evm-submission.js.map +1 -1
  26. package/cjs/transactions/hardware-psbt.js +11 -8
  27. package/cjs/transactions/hardware-psbt.js.map +1 -1
  28. package/cjs/transactions/index.js +10 -2
  29. package/cjs/transactions/index.js.map +1 -1
  30. package/cjs/transactions/prepared-evm.js +10 -7
  31. package/cjs/transactions/prepared-evm.js.map +1 -1
  32. package/cjs/transactions/syscoin-core.js +308 -205
  33. package/cjs/transactions/syscoin-core.js.map +1 -1
  34. package/cjs/trezor/connect.js +19 -2
  35. package/cjs/trezor/connect.js.map +1 -1
  36. package/cjs/trezor/index.js +38 -16
  37. package/cjs/trezor/index.js.map +1 -1
  38. package/cjs/types.js.map +1 -1
  39. package/cjs/utils/excluded-utxos.js +6 -2
  40. package/cjs/utils/excluded-utxos.js.map +1 -1
  41. package/cjs/utils/owned-blockbook-account.js +45 -0
  42. package/cjs/utils/owned-blockbook-account.js.map +1 -0
  43. package/esm/current-vault-refusal.js +3 -0
  44. package/esm/current-vault-refusal.js.map +1 -0
  45. package/esm/evm-fees.js +242 -0
  46. package/esm/evm-fees.js.map +1 -0
  47. package/esm/hardware-transaction-authority.js +33 -0
  48. package/esm/hardware-transaction-authority.js.map +1 -0
  49. package/esm/initial-state.js +102 -0
  50. package/esm/initial-state.js.map +1 -0
  51. package/esm/keyring-core.js +2781 -0
  52. package/esm/keyring-core.js.map +1 -0
  53. package/esm/keyring-host.js +108 -0
  54. package/esm/keyring-host.js.map +1 -0
  55. package/esm/ledger/dmk-session.js +1 -0
  56. package/esm/ledger/dmk-session.js.map +1 -1
  57. package/esm/ledger/dmk-utxo.js +9 -3
  58. package/esm/ledger/dmk-utxo.js.map +1 -1
  59. package/esm/ledger/host-types.js.map +1 -1
  60. package/esm/ledger/index.js +44 -19
  61. package/esm/ledger/index.js.map +1 -1
  62. package/esm/network-utils.js +70 -0
  63. package/esm/network-utils.js.map +1 -0
  64. package/esm/providers.js +3 -1
  65. package/esm/providers.js.map +1 -1
  66. package/esm/software-hd-account.js +20 -0
  67. package/esm/software-hd-account.js.map +1 -0
  68. package/esm/storage-core.js +258 -0
  69. package/esm/storage-core.js.map +1 -0
  70. package/esm/transactions/ethereum.js +2753 -0
  71. package/esm/transactions/ethereum.js.map +1 -0
  72. package/esm/transactions/evm-cancellation.js +40 -0
  73. package/esm/transactions/evm-cancellation.js.map +1 -0
  74. package/esm/transactions/evm-local-signer.js +202 -0
  75. package/esm/transactions/evm-local-signer.js.map +1 -0
  76. package/esm/transactions/evm-submission.js +187 -0
  77. package/esm/transactions/evm-submission.js.map +1 -0
  78. package/esm/transactions/prepared-evm.js +194 -0
  79. package/esm/transactions/prepared-evm.js.map +1 -0
  80. package/esm/transactions/syscoin-core.js +714 -0
  81. package/esm/transactions/syscoin-core.js.map +1 -0
  82. package/esm/trezor/connect.js +19 -2
  83. package/esm/trezor/connect.js.map +1 -1
  84. package/esm/trezor/index.js +38 -16
  85. package/esm/trezor/index.js.map +1 -1
  86. package/esm/types.js.map +1 -1
  87. package/esm/utils/excluded-utxos.js +57 -0
  88. package/esm/utils/excluded-utxos.js.map +1 -0
  89. package/esm/utils/owned-blockbook-account.js +9 -0
  90. package/esm/utils/owned-blockbook-account.js.map +1 -0
  91. package/esm/utils/psbt.js +32 -0
  92. package/esm/utils/psbt.js.map +1 -0
  93. package/esm/utils/watch-descriptor.js +138 -0
  94. package/esm/utils/watch-descriptor.js.map +1 -0
  95. package/package.json +5 -11
  96. package/types/hardware-transaction-authority.d.ts +5 -0
  97. package/types/index.d.ts +3 -3
  98. package/types/keyring-core.d.ts +22 -51
  99. package/types/keyring-host.d.ts +46 -0
  100. package/types/keyring-manager.d.ts +13 -18
  101. package/types/ledger/host-types.d.ts +4 -1
  102. package/types/ledger/index.d.ts +1 -1
  103. package/types/ledger/types.d.ts +3 -2
  104. package/types/providers.d.ts +1 -1
  105. package/types/software.d.ts +6 -19
  106. package/types/transactions/ethereum.d.ts +14 -11
  107. package/types/transactions/evm-local-signer.d.ts +2 -2
  108. package/types/transactions/evm-submission.d.ts +11 -4
  109. package/types/transactions/hardware-psbt.d.ts +1 -1
  110. package/types/transactions/index.d.ts +3 -2
  111. package/types/transactions/prepared-evm.d.ts +4 -1
  112. package/types/transactions/syscoin-core.d.ts +48 -21
  113. package/types/trezor/connect.d.ts +6 -3
  114. package/types/trezor/index.d.ts +4 -3
  115. package/types/types.d.ts +95 -63
  116. package/types/utils/excluded-utxos.d.ts +1 -1
  117. package/types/utils/owned-blockbook-account.d.ts +3 -0
  118. package/cjs/hardware-wallet-manager-singleton.js +0 -34
  119. package/cjs/hardware-wallet-manager-singleton.js.map +0 -1
  120. package/cjs/storage.js +0 -20
  121. package/cjs/storage.js.map +0 -1
  122. package/cjs/transactions/syscoin.js +0 -16
  123. package/cjs/transactions/syscoin.js.map +0 -1
  124. package/cjs/utils/blockbook-cache.js +0 -76
  125. package/cjs/utils/blockbook-cache.js.map +0 -1
  126. package/types/hardware-wallet-manager-singleton.d.ts +0 -19
  127. package/types/storage.d.ts +0 -5
  128. package/types/transactions/syscoin.d.ts +0 -9
  129. package/types/utils/blockbook-cache.d.ts +0 -6
@@ -0,0 +1,714 @@
1
+ import { INetworkType } from '@sidhujag/sysweb3-network';
2
+ import * as syscoinjs from 'syscoinjs-lib';
3
+ // import { BIP_84, ONE_HUNDRED_MILLION, SYSCOIN_BASIC_FEE } from 'utils';
4
+ import { formatUnits } from '../ethers-v6';
5
+ import { KeyringAccountType, } from '../types';
6
+ import { excludedOutpointIds, filterExcludedUtxos, assertNoExcludedInputs, } from '../utils/excluded-utxos';
7
+ import { fetchOwnedBlockbookAccount } from '../utils/owned-blockbook-account';
8
+ import { PsbtUtils } from '../utils/psbt';
9
+ import { assertPsbtAccountScope, } from '../utils/psbt-account-scope';
10
+ export const createHardwareSignerUnavailableError = (hardware) => Object.assign(new Error(`${hardware} signer is unavailable in this host`), {
11
+ code: 'HARDWARE_SIGNER_UNAVAILABLE',
12
+ });
13
+ const sweepError = (code, message) => ({
14
+ error: true,
15
+ code,
16
+ message,
17
+ });
18
+ const sweepAtomicValue = (value) => {
19
+ const text = typeof value === 'number'
20
+ ? Number.isSafeInteger(value)
21
+ ? String(value)
22
+ : ''
23
+ : typeof value === 'string' ||
24
+ typeof value === 'bigint' ||
25
+ syscoinjs.utils.BN.isBN(value)
26
+ ? value.toString()
27
+ : '';
28
+ if (!/^\d+$/.test(text))
29
+ throw sweepError('INVALID_NATIVE_SWEEP_UTXOS', 'Invalid native sweep atomic value.');
30
+ return new syscoinjs.utils.BN(text);
31
+ };
32
+ function captureBlockbookRead(options, assertContext) {
33
+ if (!options)
34
+ throw new Error('Missing owned UTXO read');
35
+ const { fetch, signal, assertCurrent: assertHost } = options;
36
+ if (typeof fetch !== 'function' ||
37
+ typeof assertHost !== 'function' ||
38
+ typeof signal?.aborted !== 'boolean')
39
+ throw new Error('Invalid owned UTXO read');
40
+ const assertCurrent = () => {
41
+ if (signal.aborted)
42
+ throw new Error('Wallet UTXO preparation context changed');
43
+ const result = assertHost();
44
+ if (result !== undefined) {
45
+ if (result &&
46
+ (typeof result === 'object' || typeof result === 'function'))
47
+ void Promise.resolve(result).catch(() => undefined);
48
+ throw new Error('Owned UTXO read requires a synchronous guard');
49
+ }
50
+ assertContext();
51
+ if (signal.aborted)
52
+ throw new Error('Wallet UTXO preparation context changed');
53
+ };
54
+ assertCurrent();
55
+ const transport = Object.freeze({
56
+ signal,
57
+ async fetch(input, init) {
58
+ assertCurrent();
59
+ const response = await fetch(input, init);
60
+ assertCurrent();
61
+ return response;
62
+ },
63
+ });
64
+ return { assertCurrent, transport };
65
+ }
66
+ async function readOwnedFee(explorerUrl, { assertCurrent, transport }) {
67
+ assertCurrent();
68
+ const fee = await syscoinjs.utils.fetchEstimateFee(explorerUrl, 1, undefined, transport);
69
+ assertCurrent();
70
+ return fee / 1024;
71
+ }
72
+ /** Public network fee estimate. It has no wallet, account or signing access. */
73
+ export async function readPublicSyscoinFee(explorerUrl, owner) {
74
+ return readOwnedFee(explorerUrl, captureBlockbookRead(owner, () => undefined));
75
+ }
76
+ /** Bind both transaction preparation and address reads to the active wallet. */
77
+ export function captureOwnedSyscoinRead(options, getState, captureSigningContext) {
78
+ if (!options)
79
+ throw new Error('Missing owned UTXO read');
80
+ const assertSession = captureSigningContext(true);
81
+ const { activeNetwork, activeAccountId, activeAccountType, accounts } = getState();
82
+ if (activeNetwork.kind !== INetworkType.Syscoin)
83
+ throw new Error('Switch to UTXO chain');
84
+ const selected = accounts[activeAccountType]?.[activeAccountId];
85
+ if (!selected)
86
+ throw new Error('Active account not found');
87
+ const account = Object.freeze({
88
+ address: selected.address,
89
+ xpub: selected.xpub,
90
+ });
91
+ const network = Object.freeze({ ...activeNetwork });
92
+ const read = captureBlockbookRead(options, () => {
93
+ assertSession();
94
+ const current = getState();
95
+ const selected = current.accounts[current.activeAccountType]?.[current.activeAccountId];
96
+ if (current.activeAccountId !== activeAccountId ||
97
+ current.activeAccountType !== activeAccountType ||
98
+ selected?.address !== account.address ||
99
+ selected?.xpub !== account.xpub ||
100
+ current.activeNetwork.kind !== network.kind ||
101
+ current.activeNetwork.chainId !== network.chainId ||
102
+ current.activeNetwork.slip44 !== network.slip44 ||
103
+ current.activeNetwork.currency !== network.currency ||
104
+ current.activeNetwork.url !== network.url)
105
+ throw new Error('Wallet UTXO preparation context changed');
106
+ });
107
+ return {
108
+ account,
109
+ accountId: activeAccountId,
110
+ accountType: activeAccountType,
111
+ read: Object.freeze({ ...read, network, xpub: account.xpub }),
112
+ };
113
+ }
114
+ export class SyscoinTransactionsCore {
115
+ constructor(getSyscoinSigner, getReadOnlySigner, getState, hardwareSigners, captureSigningContext) {
116
+ this.getTransactionPSBT = async ({ txOptions, outputs, changeAddress, feeRateBN, xpub, fundingUtxos, }, main) => {
117
+ try {
118
+ // Use syscoinjs-lib directly for transaction creation
119
+ const result = await main.createTransaction(txOptions, changeAddress, outputs, feeRateBN, xpub, // sysFromXpubOrAddress
120
+ ...(fundingUtxos ? [fundingUtxos] : []));
121
+ if (result && result.psbt) {
122
+ return { psbt: result.psbt, fee: result.fee };
123
+ }
124
+ throw new Error('psbt not found');
125
+ }
126
+ catch (error) {
127
+ // Propagate structured error from syscoinjs-lib
128
+ if (error.error && error.code) {
129
+ throw error;
130
+ }
131
+ // Wrap non-structured errors
132
+ throw {
133
+ error: true,
134
+ code: 'TRANSACTION_CREATION_FAILED',
135
+ message: error.message || 'Failed to create transaction',
136
+ details: error,
137
+ };
138
+ }
139
+ };
140
+ this.decodeRawTransaction = (psbtOrHex, isRawHex = false) => {
141
+ const { main } = this.getReadOnlySigner();
142
+ if (isRawHex) {
143
+ // Handle raw transaction hex
144
+ const bitcoinTx = syscoinjs.utils.bitcoinjs.Transaction.fromHex(psbtOrHex);
145
+ return main.decodeRawTransaction(bitcoinTx);
146
+ }
147
+ else {
148
+ // Handle PSBT format (existing behavior)
149
+ const psbtObj = PsbtUtils.fromPali(psbtOrHex, this.getState().activeNetwork);
150
+ return main.decodeRawTransaction(psbtObj);
151
+ }
152
+ };
153
+ this.getRecommendedFee = async (explorerUrl, ownedRead) => {
154
+ const { read } = this.captureOwnedRead(ownedRead);
155
+ if (explorerUrl !== read.network.url)
156
+ throw new Error('Owned UTXO read endpoint changed');
157
+ return readOwnedFee(explorerUrl, read);
158
+ };
159
+ // Internal method for signing with the HD signer
160
+ this.signPSBTWithSigner = async ({ psbt, signer, }) => await signer.sign(psbt);
161
+ this.createNativeSweepPSBT = async ({ txOptions, changeAddress, receivingAddress, feeRateBN, source, excluded, }, main, read) => {
162
+ const raw = await syscoinjs.utils.fetchBackendUTXOS(main.blockbookURL, source, undefined, read.transport);
163
+ read.assertCurrent();
164
+ const excludedNativeValues = new Map();
165
+ const rows = excluded.size
166
+ ? filterExcludedUtxos(raw, excluded, (row, outpoint) => {
167
+ const unambiguous = !excludedNativeValues.has(outpoint) &&
168
+ row.assetInfo == null &&
169
+ (row.txId === undefined ||
170
+ row.txid === undefined ||
171
+ row.txId === row.txid);
172
+ excludedNativeValues.set(outpoint, unambiguous ? row.value : undefined);
173
+ }).utxos
174
+ : Array.isArray(raw)
175
+ ? raw
176
+ : raw?.utxos;
177
+ if (!Array.isArray(rows))
178
+ throw sweepError('INVALID_NATIVE_SWEEP_UTXOS', 'Invalid native sweep UTXO response.');
179
+ const seen = new Set();
180
+ const expected = new Set();
181
+ let gross = new syscoinjs.utils.BN(0);
182
+ const utxos = [];
183
+ for (const row of rows) {
184
+ const txid = row?.txId ?? row?.txid;
185
+ if (typeof txid !== 'string' ||
186
+ !/^[0-9a-fA-F]{64}$/.test(txid) ||
187
+ !Number.isSafeInteger(row.vout) ||
188
+ row.vout < 0 ||
189
+ row.vout > 0xffffffff ||
190
+ (row.txId !== undefined &&
191
+ row.txid !== undefined &&
192
+ row.txId !== row.txid) ||
193
+ (row.assetInfo != null &&
194
+ (typeof row.assetInfo !== 'object' || Array.isArray(row.assetInfo))))
195
+ throw sweepError('INVALID_NATIVE_SWEEP_UTXOS', 'Invalid native sweep outpoint.');
196
+ const outpoint = `${txid.toLowerCase()}:${row.vout}`;
197
+ if (seen.has(outpoint))
198
+ throw sweepError('INVALID_NATIVE_SWEEP_UTXOS', 'Duplicate native sweep outpoint.');
199
+ seen.add(outpoint);
200
+ const value = sweepAtomicValue(row.value);
201
+ // Native MAX must leave asset carriers and their allocations untouched.
202
+ if (row.assetInfo != null)
203
+ continue;
204
+ expected.add(outpoint);
205
+ gross = gross.add(value);
206
+ utxos.push({ ...row, value });
207
+ }
208
+ if (gross.isZero()) {
209
+ const error = sweepError('INSUFFICIENT_FUNDS', 'No native UTXOs are available to sweep.');
210
+ const excludedNativeOutpoints = [...excludedNativeValues].flatMap(([outpoint, value]) => {
211
+ if (typeof value === 'number')
212
+ return Number.isSafeInteger(value) && value > 0 ? [outpoint] : [];
213
+ if (typeof value === 'string' &&
214
+ value.length <= 20 &&
215
+ !/[^0-9]/.test(value) &&
216
+ /[1-9]/.test(value) &&
217
+ (value.length < 20 || value <= '18446744073709551615'))
218
+ return [outpoint];
219
+ return [];
220
+ });
221
+ if (excludedNativeOutpoints.length)
222
+ throw { ...error, excludedNativeOutpoints };
223
+ throw error;
224
+ }
225
+ // The library sanitizes this snapshot once; its optional UTXO argument
226
+ // prevents a second funding lookup between resolving MAX and building it.
227
+ const result = await main.createTransaction(txOptions, changeAddress, [{ address: receivingAddress, value: gross, subtractFeeFrom: true }], feeRateBN, source, { utxos, assets: new Map() });
228
+ const inputs = result.psbt?.txInputs;
229
+ const outputs = result.psbt?.txOutputs;
230
+ const selected = Array.isArray(inputs)
231
+ ? inputs.map((input) => `${Buffer.from(input.hash).reverse().toString('hex')}:${input.index}`)
232
+ : [];
233
+ if (selected.length !== expected.size ||
234
+ new Set(selected).size !== expected.size ||
235
+ selected.some((outpoint) => !expected.has(outpoint)) ||
236
+ !Array.isArray(outputs) ||
237
+ outputs.length !== 1)
238
+ throw sweepError('INCOMPLETE_NATIVE_SWEEP', 'The builder did not preserve the complete native sweep.');
239
+ const script = syscoinjs.utils.bitcoinjs.address.toOutputScript(receivingAddress, main.network);
240
+ const recipient = sweepAtomicValue(outputs[0].value);
241
+ const fee = sweepAtomicValue(result.fee);
242
+ if (!Buffer.from(outputs[0].script).equals(Buffer.from(script)) ||
243
+ recipient.isZero() ||
244
+ !recipient.add(fee).eq(gross))
245
+ throw sweepError('INCOMPLETE_NATIVE_SWEEP', 'The native sweep amounts do not match its PSBT.');
246
+ return {
247
+ psbt: result.psbt,
248
+ fee: result.fee,
249
+ grossAmount: formatUnits(gross.toString(), 8).replace(/\.0$/, ''),
250
+ recipientAmount: formatUnits(recipient.toString(), 8).replace(/\.0$/, ''),
251
+ };
252
+ };
253
+ // Create unsigned PSBT for any transaction type
254
+ this.createUnsignedPSBT = async ({ txOptions = {}, isMax = false, nativeSweep = false, amount, receivingAddress, feeRateBN, token = null, }, owned) => {
255
+ // Ensure RBF is enabled by default if not explicitly set
256
+ const finalTxOptions = { rbf: true, ...txOptions };
257
+ const { account, accountType: activeAccountType, excluded, main, read, } = owned;
258
+ const xpub = account.xpub;
259
+ const isSingleAddressImported = activeAccountType === KeyringAccountType.Imported &&
260
+ xpub === account.address;
261
+ // For imported extended-key accounts we store BIP84 xpubs (zpub/vpub).
262
+ // Blockbook derives different address branches depending on version bytes, so preserve xpub as-is.
263
+ const sourceForUtxoLookup = isSingleAddressImported
264
+ ? account.address
265
+ : xpub;
266
+ // Convert amount to satoshis (1 SYS = 1e8 satoshis)
267
+ // Using BigNumber to prevent precision loss
268
+ const amountStr = amount.toString();
269
+ // Safe conversion without parseFloat to avoid precision loss
270
+ // Split the string to handle decimal values properly
271
+ const parts = amountStr.split('.');
272
+ const integerPart = parts[0] || '0';
273
+ const decimalPart = parts[1] || '';
274
+ // Pad or truncate decimal part to 8 places (satoshi precision)
275
+ const paddedDecimal = decimalPart.padEnd(8, '0').substring(0, 8);
276
+ // Combine to get satoshis (integer + decimal as one number)
277
+ const satoshiStr = integerPart + paddedDecimal;
278
+ // Remove leading zeros but keep at least one digit
279
+ const trimmedSatoshis = satoshiStr.replace(/^0+/, '') || '0';
280
+ const value = new syscoinjs.utils.BN(trimmedSatoshis);
281
+ // If this is a single-address imported account (WIF import), use the account.address for both from and change
282
+ const changeAddress = isSingleAddressImported
283
+ ? account.address
284
+ : await owned.getOwnedAddress(xpub, true);
285
+ read.assertCurrent();
286
+ try {
287
+ if (nativeSweep) {
288
+ return await this.createNativeSweepPSBT({
289
+ txOptions: finalTxOptions,
290
+ changeAddress,
291
+ receivingAddress,
292
+ feeRateBN,
293
+ source: sourceForUtxoLookup,
294
+ excluded,
295
+ }, main, read);
296
+ }
297
+ const fundingUtxos = excluded.size
298
+ ? filterExcludedUtxos(await syscoinjs.utils.fetchBackendUTXOS(main.blockbookURL, sourceForUtxoLookup, undefined, read.transport), excluded)
299
+ : undefined;
300
+ read.assertCurrent();
301
+ if (token && token.guid) {
302
+ // Token transaction: use assetAllocationSend
303
+ // Create a Map for the asset allocation
304
+ const assetMap = new Map();
305
+ assetMap.set(token.guid, {
306
+ changeAddress,
307
+ outputs: [
308
+ {
309
+ value: value,
310
+ address: receivingAddress,
311
+ },
312
+ ],
313
+ });
314
+ // Pass xpub to get back just the PSBT without signing and sending
315
+ // syscoinjs-lib will validate asset existence and sufficient balance
316
+ const result = await main.assetAllocationSend(finalTxOptions, assetMap, changeAddress, feeRateBN, sourceForUtxoLookup, // Pass source (address for WIF imports, zpub/vpub for HD)
317
+ ...(fundingUtxos ? [fundingUtxos] : []));
318
+ if (excluded.size)
319
+ assertNoExcludedInputs(result.psbt, excluded);
320
+ // Return PSBT and fee
321
+ return { psbt: result.psbt, fee: result.fee };
322
+ }
323
+ else {
324
+ // Native transaction: use getTransactionPSBT to create unsigned PSBT
325
+ const outputs = [
326
+ {
327
+ address: receivingAddress,
328
+ value: value, // Pass BN object directly
329
+ ...(isMax && { subtractFeeFrom: true }), // Only add subtractFeeFrom if isMax is true
330
+ },
331
+ ];
332
+ const result = await this.getTransactionPSBT({
333
+ txOptions: finalTxOptions,
334
+ outputs,
335
+ changeAddress,
336
+ feeRateBN,
337
+ xpub: sourceForUtxoLookup,
338
+ fundingUtxos,
339
+ }, main);
340
+ if (excluded.size)
341
+ assertNoExcludedInputs(result.psbt, excluded);
342
+ return result;
343
+ }
344
+ }
345
+ catch (error) {
346
+ // Re-throw structured errors from syscoinjs-lib
347
+ if (error.error && error.code) {
348
+ throw error;
349
+ }
350
+ // Wrap other errors in structured format
351
+ throw {
352
+ error: true,
353
+ code: 'TRANSACTION_CREATION_FAILED',
354
+ message: error.message || 'Failed to create unsigned PSBT',
355
+ details: error,
356
+ };
357
+ }
358
+ };
359
+ // Sign PSBT with appropriate method - separated for better error handling
360
+ this.signPSBTWithMethod = async (psbt, ownedRead) => {
361
+ const { assertCurrent, network: activeNetwork, transport } = ownedRead;
362
+ assertCurrent();
363
+ const { activeAccountId, activeAccountType, accounts } = this.getState();
364
+ const account = accounts[activeAccountType]?.[activeAccountId];
365
+ if (!account)
366
+ throw new Error('Active account not found');
367
+ // Device choice belongs to the selected account, never to PSBT/caller flags.
368
+ const isTrezor = activeAccountType === KeyringAccountType.Trezor ||
369
+ account.isTrezorWallet === true;
370
+ const isLedger = activeAccountType === KeyringAccountType.Ledger ||
371
+ account.isLedgerWallet === true;
372
+ const scope = Object.freeze({
373
+ account: Object.freeze({ address: account.address, xpub: account.xpub }),
374
+ accountId: activeAccountId,
375
+ accountType: activeAccountType,
376
+ network: activeNetwork,
377
+ });
378
+ const sign = isLedger
379
+ ? this.hardwareSigners.ledger
380
+ : isTrezor
381
+ ? this.hardwareSigners.trezor
382
+ : undefined;
383
+ if ((isLedger || isTrezor) && typeof sign !== 'function')
384
+ throw createHardwareSignerUnavailableError(isLedger ? 'Ledger' : 'Trezor');
385
+ if (isTrezor || isLedger)
386
+ assertPsbtAccountScope(psbt, scope);
387
+ if (isLedger || isTrezor) {
388
+ const assertHardwareCurrent = () => {
389
+ try {
390
+ assertCurrent();
391
+ }
392
+ catch {
393
+ // The vendor retry loop already treats AbortError as terminal.
394
+ throw Object.assign(new Error('Wallet signing context changed'), {
395
+ name: 'AbortError',
396
+ });
397
+ }
398
+ };
399
+ const signed = await sign({
400
+ psbt,
401
+ account: Object.freeze({ id: account.id, xpub: account.xpub }),
402
+ network: scope.network,
403
+ scope,
404
+ assertCurrent: assertHardwareCurrent,
405
+ signal: transport.signal,
406
+ ...(isLedger && {
407
+ getRawTransaction: (txid) => syscoinjs.utils.fetchBackendRawTx(activeNetwork.url, txid, transport),
408
+ }),
409
+ });
410
+ assertHardwareCurrent();
411
+ return signed;
412
+ }
413
+ else {
414
+ // HD signing (seed-based HDAccount or imported BIP84 zprv/vprv account).
415
+ // Some Blockbook deployments return UTXOs without per-input derivation `path`,
416
+ // which causes bitcoinjs-lib to throw "Need derivation path to sign with HD".
417
+ //
418
+ // We can recover by enriching PSBT inputs with a proprietary `path` field using
419
+ // Blockbook's xpub token list (address -> path mapping), which reliably includes paths.
420
+ const account = accounts[activeAccountType]?.[activeAccountId];
421
+ const accountXpub = account?.xpub;
422
+ const accountAddress = account?.address;
423
+ const isSingleAddressImported = activeAccountType === KeyringAccountType.Imported &&
424
+ Boolean(accountXpub) &&
425
+ Boolean(accountAddress) &&
426
+ accountXpub === accountAddress;
427
+ const isImportedExtended = activeAccountType === KeyringAccountType.Imported &&
428
+ Boolean(accountXpub) &&
429
+ !isSingleAddressImported;
430
+ // IMPORTANT: Imported extended keys (zprv/vprv) are typically *account-level* keys.
431
+ // syscoinjs-lib signs using the imported key as the BIP32 root, so PSBT `path` must be
432
+ // relative (change/index), not the full `m/84'/.../change/index`. If we keep full paths,
433
+ // bip32.derivePath can throw, leaving no derivations and causing "Need derivation path".
434
+ if (isImportedExtended) {
435
+ const inputs = psbt?.data?.inputs || [];
436
+ for (const input of inputs) {
437
+ const unknowns = input?.unknownKeyVals || [];
438
+ const pathKv = unknowns.find((kv) => kv?.key?.toString?.() === 'path');
439
+ if (!pathKv?.value)
440
+ continue;
441
+ const fullPath = String(Buffer.from(pathKv.value).toString());
442
+ const parts = fullPath.split('/').filter(Boolean);
443
+ // Expected: m/84'/slip44'/account'/change/index
444
+ if (parts.length >= 2) {
445
+ const change = parts[parts.length - 2];
446
+ const index = parts[parts.length - 1];
447
+ const rel = `${change}/${index}`;
448
+ pathKv.value = Buffer.from(rel);
449
+ }
450
+ }
451
+ }
452
+ const needsAnyPath = psbt?.data?.inputs?.some((input) => {
453
+ const unknowns = input?.unknownKeyVals || [];
454
+ return (!input.bip32Derivation?.length &&
455
+ !input.tapBip32Derivation?.length &&
456
+ !unknowns.some((kv) => kv?.key?.toString?.() === 'path'));
457
+ });
458
+ if (needsAnyPath &&
459
+ accountXpub &&
460
+ !isSingleAddressImported &&
461
+ typeof psbt.addUnknownKeyValToInput === 'function') {
462
+ // Fetch address->path mapping from Blockbook xpub endpoint
463
+ const blockbookUrl = activeNetwork.url;
464
+ const res = await fetchOwnedBlockbookAccount(blockbookUrl, accountXpub, transport);
465
+ assertCurrent();
466
+ const tokens = Array.isArray(res?.tokens) ? res.tokens : [];
467
+ const addrToPath = new Map();
468
+ for (const t of tokens) {
469
+ if (t?.name && t?.path) {
470
+ addrToPath.set(String(t.name), String(t.path));
471
+ }
472
+ }
473
+ const inputs = psbt?.data?.inputs || [];
474
+ for (let i = 0; i < inputs.length; i++) {
475
+ const input = inputs[i];
476
+ const unknowns = input?.unknownKeyVals || [];
477
+ const hasPath = unknowns.some((kv) => kv?.key?.toString?.() === 'path');
478
+ if (hasPath)
479
+ continue;
480
+ const addrKv = unknowns.find((kv) => kv?.key?.toString?.() === 'address');
481
+ const addr = addrKv?.value
482
+ ? String(Buffer.from(addrKv.value).toString())
483
+ : null;
484
+ if (!addr)
485
+ continue;
486
+ const fullPath = addrToPath.get(addr);
487
+ if (!fullPath)
488
+ continue;
489
+ // Imported extended keys are account-level (BIP84 account node), so we must provide a
490
+ // path relative to that node (change/index), not the full m/84'/... path.
491
+ const pathForSigner = isImportedExtended
492
+ ? (() => {
493
+ const parts = String(fullPath).split('/').filter(Boolean);
494
+ // Expected: m/84'/slip44'/account'/change/index
495
+ if (parts.length >= 2) {
496
+ const change = parts[parts.length - 2];
497
+ const index = parts[parts.length - 1];
498
+ return `${change}/${index}`;
499
+ }
500
+ return fullPath;
501
+ })()
502
+ : fullPath;
503
+ psbt.addUnknownKeyValToInput(i, {
504
+ key: Buffer.from('path'),
505
+ value: Buffer.from(pathForSigner),
506
+ });
507
+ }
508
+ }
509
+ assertCurrent();
510
+ assertPsbtAccountScope(psbt, scope);
511
+ const { hd } = this.getSigner();
512
+ const signedPsbt = await this.signPSBTWithSigner({
513
+ psbt,
514
+ signer: hd,
515
+ });
516
+ assertCurrent();
517
+ return signedPsbt;
518
+ }
519
+ };
520
+ // Create unsigned PSBT and estimate fee - NO SIGNING
521
+ this.getEstimateSysTransactionFee = async ({ txOptions = {}, isMax = false, nativeSweep = false, amount, receivingAddress, feeRate, token = null, excludedOutpoints = [], }, ownedRead) => {
522
+ try {
523
+ if (nativeSweep !== false &&
524
+ (nativeSweep !== true || isMax !== true || token !== null))
525
+ throw sweepError('INVALID_NATIVE_SWEEP', 'Native sweep requires explicit MAX and a native transaction.');
526
+ // Ensure RBF is enabled by default if not explicitly set
527
+ const finalTxOptions = { rbf: true, ...txOptions };
528
+ const preparation = this.captureOwnedRead(ownedRead);
529
+ const { main, getOwnedAddress } = this.getReadOnlySigner(preparation.read);
530
+ if (typeof getOwnedAddress !== 'function' ||
531
+ main.blockbookURL !== preparation.read.network.url)
532
+ throw new Error('Owned UTXO read adapter is unavailable');
533
+ const owned = {
534
+ ...preparation,
535
+ main,
536
+ getOwnedAddress,
537
+ excluded: excludedOutpointIds(excludedOutpoints),
538
+ };
539
+ const selectedToken = token ? { ...token } : token;
540
+ const { assetWhiteList } = finalTxOptions;
541
+ if (assetWhiteList instanceof Map)
542
+ finalTxOptions.assetWhiteList = new Map(assetWhiteList);
543
+ else if (assetWhiteList instanceof Set)
544
+ finalTxOptions.assetWhiteList = new Set(assetWhiteList);
545
+ for (const key of ['memo', 'memoHeader', 'blobHash', 'blobData']) {
546
+ const bytes = finalTxOptions[key];
547
+ if (bytes instanceof Uint8Array)
548
+ finalTxOptions[key] = Buffer.from(bytes);
549
+ }
550
+ const actualFeeRate = feeRate === undefined
551
+ ? await readOwnedFee(main.blockbookURL, owned.read)
552
+ : feeRate;
553
+ owned.read.assertCurrent();
554
+ // Convert fee rate to satoshis/byte and ensure minimum relay of 1 sat/vB
555
+ // Blockbook returns coins per kB; after division by 1024, some testnets
556
+ // can yield < 1 sat/vB (e.g., 0.9765625). Round up and clamp to 1 to
557
+ // avoid zero-fee transactions due to truncation when converting to BN.
558
+ const satPerByte = Math.max(1, Math.ceil(actualFeeRate * 1e8));
559
+ const feeRateBN = new syscoinjs.utils.BN(satPerByte);
560
+ // Step 2: Create unsigned PSBT
561
+ const result = await this.createUnsignedPSBT({
562
+ txOptions: finalTxOptions,
563
+ isMax,
564
+ nativeSweep,
565
+ amount,
566
+ receivingAddress,
567
+ feeRateBN,
568
+ token: selectedToken,
569
+ }, owned);
570
+ owned.read.assertCurrent();
571
+ const quote = {
572
+ fee: result.fee / 1e8,
573
+ psbt: PsbtUtils.toPali(result.psbt), // Return UNSIGNED PSBT as JSON
574
+ ...(nativeSweep
575
+ ? {
576
+ grossAmount: result.grossAmount,
577
+ recipientAmount: result.recipientAmount,
578
+ }
579
+ : {}),
580
+ };
581
+ owned.read.assertCurrent();
582
+ return quote;
583
+ }
584
+ catch (error) {
585
+ // Pass through structured errors from syscoinjs-lib
586
+ if (error.error && error.code) {
587
+ // Convert fee from satoshis to SYS if available
588
+ if (error.fee !== undefined) {
589
+ // If fee is a BN object, convert to number first
590
+ if (typeof error.fee === 'object' && error.fee.toNumber) {
591
+ error.fee = error.fee.toNumber() / 1e8;
592
+ }
593
+ else {
594
+ error.fee = error.fee / 1e8;
595
+ }
596
+ }
597
+ if (error.remainingFee !== undefined) {
598
+ // If remainingFee is a BN object, convert to number first
599
+ if (typeof error.remainingFee === 'object' &&
600
+ error.remainingFee.toNumber) {
601
+ error.remainingFee = error.remainingFee.toNumber() / 1e8;
602
+ }
603
+ else {
604
+ error.remainingFee = error.remainingFee / 1e8;
605
+ }
606
+ }
607
+ if (error.shortfall !== undefined) {
608
+ // If shortfall is a BN object, convert to number first
609
+ if (typeof error.shortfall === 'object' && error.shortfall.toNumber) {
610
+ error.shortfall = error.shortfall.toNumber() / 1e8;
611
+ }
612
+ else {
613
+ error.shortfall = error.shortfall / 1e8;
614
+ }
615
+ }
616
+ throw error;
617
+ }
618
+ // Wrap other errors
619
+ throw {
620
+ error: true,
621
+ code: 'TRANSACTION_CREATION_FAILED',
622
+ message: error.message || 'Failed to estimate transaction fee',
623
+ details: error,
624
+ };
625
+ }
626
+ };
627
+ // Removed createAndSignSysTransaction - functionality merged into getEstimateSysTransactionFee
628
+ this.signPSBT = async ({ psbt }, ownedRead) => {
629
+ const { read } = this.captureOwnedRead(ownedRead);
630
+ const psbtObj = PsbtUtils.fromPali(psbt, read.network);
631
+ const unsigned = Buffer.from(psbtObj.data.globalMap.unsignedTx.toBuffer());
632
+ // Scope validation temporarily removes other signers' hints. Preserve the
633
+ // public metadata for the next cosigner, without exposing it to our signer.
634
+ const cosignerMetadata = psbtObj.data.inputs.map((input, index) => ({
635
+ hash: Buffer.from(psbtObj.txInputs[index].hash),
636
+ index: psbtObj.txInputs[index].index,
637
+ bip32Derivation: input.bip32Derivation?.map((value) => ({ ...value })),
638
+ tapBip32Derivation: input.tapBip32Derivation?.map((value) => ({
639
+ ...value,
640
+ })),
641
+ path: input.unknownKeyVals
642
+ ?.filter((value) => Buffer.from(value.key).toString() === 'path')
643
+ .map((value) => ({
644
+ key: Buffer.from(value.key),
645
+ value: Buffer.from(value.value),
646
+ }))[0],
647
+ }));
648
+ const signedPsbt = await this.signPSBTWithMethod(psbtObj, read);
649
+ read.assertCurrent();
650
+ if (!unsigned.equals(Buffer.from(signedPsbt.data.globalMap.unsignedTx.toBuffer())))
651
+ throw new Error('Signed PSBT differs from the prepared transaction');
652
+ signedPsbt.data.inputs.forEach((input, index) => {
653
+ if (input.finalScriptSig || input.finalScriptWitness)
654
+ return;
655
+ const metadata = cosignerMetadata[index];
656
+ if (!metadata)
657
+ return;
658
+ const signed = signedPsbt.txInputs[index];
659
+ if (!signed ||
660
+ metadata.index !== signed.index ||
661
+ !metadata.hash.equals(Buffer.from(signed.hash)))
662
+ throw new Error('Wallet signing context changed');
663
+ if (metadata.bip32Derivation)
664
+ input.bip32Derivation = metadata.bip32Derivation;
665
+ if (metadata.tapBip32Derivation)
666
+ input.tapBip32Derivation = metadata.tapBip32Derivation;
667
+ if (metadata.path) {
668
+ input.unknownKeyVals = (input.unknownKeyVals || []).filter((value) => Buffer.from(value.key).toString() !== 'path');
669
+ input.unknownKeyVals.push(metadata.path);
670
+ }
671
+ });
672
+ const result = PsbtUtils.toPali(signedPsbt);
673
+ read.assertCurrent();
674
+ return result;
675
+ };
676
+ this.sendTransaction = async (rawTransaction, authority) => {
677
+ let read;
678
+ let fetch;
679
+ let signal;
680
+ let prepare;
681
+ try {
682
+ if (!authority)
683
+ throw new Error('Missing owned UTXO submission context');
684
+ const { assertCurrent } = authority;
685
+ ({ fetch, signal, prepare } = authority);
686
+ if (typeof prepare !== 'function')
687
+ throw new Error('Missing UTXO submission admission');
688
+ ({ read } = this.captureOwnedRead({ assertCurrent, fetch, signal }));
689
+ }
690
+ catch {
691
+ throw Object.assign(new Error('UTXO submission was not dispatched'), {
692
+ code: 'UTXO_SUBMISSION_NOT_DISPATCHED',
693
+ transactionNotBroadcast: true,
694
+ });
695
+ }
696
+ // SyscoinJS owns the admission, final synchronous guard and exact ACK.
697
+ // The POST uses the captured transport directly so a matching ACK can
698
+ // still be observed after a host context change without a signal abort.
699
+ const { result: txid } = await syscoinjs.utils.sendRawTransaction(read.network.url, rawTransaction, undefined, { assertCurrent: read.assertCurrent, fetch, prepare, signal });
700
+ return { txid };
701
+ };
702
+ if (typeof captureSigningContext !== 'function')
703
+ throw new Error('Missing UTXO signing context');
704
+ this.getSigner = getSyscoinSigner;
705
+ this.getReadOnlySigner = getReadOnlySigner;
706
+ this.getState = getState;
707
+ this.hardwareSigners = hardwareSigners;
708
+ this.captureSigningContext = captureSigningContext;
709
+ }
710
+ captureOwnedRead(options) {
711
+ return captureOwnedSyscoinRead(options, this.getState, this.captureSigningContext);
712
+ }
713
+ }
714
+ //# sourceMappingURL=syscoin-core.js.map