@sidhujag/sysweb3-keyring 1.0.626 → 1.0.628

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