import { CoinSelect, Custom, DeepFirst, Merge, type Account as WalletAccount, type TransactionInfo as WalletTxInfo, } from "@ledgerhq/wallet-btc/index"; import { FeeNotLoaded } from "@ledgerhq/ledger-wallet-framework/errors"; import { getMainAccount } from "@ledgerhq/ledger-wallet-framework/account/index"; import type { Transaction, UtxoStrategy, BtcOperationExtra } from "./types"; import { bitcoinPickingStrategy } from "./types"; import { buildAccountTx } from "./buildAndSign"; import wallet from "@ledgerhq/wallet-btc/index"; import { getWalletAccount } from "./getWalletAccount"; import { Account } from "@ledgerhq/types-live"; import type { BitcoinCoinConfig } from "./config"; import type { Logger } from "@ledgerhq/coin-module-framework/config"; const isBtcOperationExtra = (extra: unknown): extra is BtcOperationExtra => { if (extra === null || extra === undefined || typeof extra !== "object") return false; if (!("inputs" in extra)) return true; return extra.inputs === undefined || Array.isArray(extra.inputs); }; const selectUtxoPickingStrategy = (walletAccount: WalletAccount, utxoStrategy: UtxoStrategy) => { const handler = { [bitcoinPickingStrategy.MERGE_OUTPUTS]: Merge, [bitcoinPickingStrategy.DEEP_OUTPUTS_FIRST]: DeepFirst, [bitcoinPickingStrategy.OPTIMIZE_SIZE]: CoinSelect, [bitcoinPickingStrategy.CUSTOM]: Custom, }[utxoStrategy.strategy]; if (!handler) throw new Error("Unsupported Bitcoin UTXO picking strategy"); return new handler( walletAccount.xpub.crypto, walletAccount.xpub.derivationMode, utxoStrategy.excludeUTXOs, ); }; type PendingOperation = { hash: string; extra?: BtcOperationExtra; }; const getEffectiveUtxoStrategy = (transaction: Transaction): UtxoStrategy => transaction.replaceTxId ? { ...transaction.utxoStrategy, strategy: bitcoinPickingStrategy.OPTIMIZE_SIZE, } : transaction.utxoStrategy; const getAccountPendingOperations = ( account: Account, replaceTxId?: string, ): PendingOperation[] | undefined => { const mainAccount = replaceTxId ? getMainAccount(account, undefined) : undefined; return mainAccount?.pendingOperations?.map(op => { const extra = isBtcOperationExtra(op.extra) ? op.extra : undefined; return extra !== undefined && extra !== null ? { hash: op.hash, extra } : { hash: op.hash }; }); }; const enrichPendingOperations = async ( walletAccount: WalletAccount, pendingOperations: PendingOperation[] | undefined, ): Promise => { const explorerPendings = await wallet.getAccountPendings(walletAccount); const explorerPendingOperations: Array<{ hash: string; extra: BtcOperationExtra }> = explorerPendings.map(tx => ({ hash: tx.id, extra: { inputs: tx.inputs.map(input => `${input.output_hash}-${input.output_index}`), }, })); const byHash = new Map((pendingOperations || []).map(op => [op.hash, op] as const)); for (const op of explorerPendingOperations) { const existing = byHash.get(op.hash); if (!existing) { byHash.set(op.hash, op); continue; } const existingInputs = existing.extra?.inputs; if (!Array.isArray(existingInputs) || existingInputs.length === 0) { byHash.set(op.hash, { ...existing, extra: op.extra }); } } return [...byHash.values()]; }; const getPendingOperations = async ( logger: Logger, account: Account, walletAccount: WalletAccount, replaceTxId?: string, ): Promise => { const pendingOperations = getAccountPendingOperations(account, replaceTxId); if (!replaceTxId) return pendingOperations; try { return await enrichPendingOperations(walletAccount, pendingOperations); } catch (error) { // Ignore explorer pending enrichment errors and fallback to account pending operations only. logger("btcwallet", "pending enrichment fallback", { error }); return pendingOperations; } }; export const buildTransaction = async ( config: BitcoinCoinConfig, logger: Logger, account: Account, transaction: Transaction, ): Promise => { const { feePerByte, recipient, opReturnData, utxoStrategy, changeAddress } = transaction; if (!feePerByte) { throw new FeeNotLoaded(); } const walletAccount = getWalletAccount(account); // For RBF edits (speedup/cancel), always use OPTIMIZE_SIZE so replacement can reuse // conflicting inputs regardless of the original manual strategy selection. const effectiveUtxoStrategy = getEffectiveUtxoStrategy(transaction); const utxoPickingStrategy = selectUtxoPickingStrategy(walletAccount, effectiveUtxoStrategy); const maxSpendable = await wallet.estimateAccountMaxSpendable( logger, walletAccount, feePerByte.toNumber(), //!\ wallet-btc handles fees as JS number utxoStrategy.excludeUTXOs, [recipient], opReturnData, ); logger("btcwallet", "building transaction", transaction); const pendingOperations = await getPendingOperations( logger, account, walletAccount, transaction.replaceTxId, ); transaction.rbf = ["bitcoin", "bitcoin_testnet", "bitcoin_regtest"].includes( walletAccount.params.currency, ) ? true : false; const txInfo = await buildAccountTx(logger, config, { fromAccount: walletAccount, dest: transaction.recipient, amount: transaction.useAllAmount ? maxSpendable : transaction.amount, feePerByte: feePerByte.toNumber(), //!\ wallet-btc handles fees as JS number utxoPickingStrategy, // Definition of replaceable, per the standard: https://github.com/bitcoin/bips/blob/61ccc84930051e5b4a99926510d0db4a8475a4e6/bip-0125.mediawiki#summary sequence: transaction.rbf ? 0 : 0xffffffff, opReturnData, changeAddress, ...(transaction.replaceTxId === undefined ? {} : { originalTxId: transaction.replaceTxId }), ...(pendingOperations === undefined ? {} : { pendingOperations }), ...(transaction.networkInfo?.relayFeePerByte === undefined ? {} : { relayFeePerByteSatVb: transaction.networkInfo.relayFeePerByte }), }); logger("btcwallet", "txInfo", txInfo); return txInfo; };