|
| 1 | +/** |
| 2 | + * UTXO Consolidation Endpoint |
| 3 | + * |
| 4 | + * This endpoint consolidates all available hash-locked UTXOs in the database into a single output. |
| 5 | + * It gathers all the tokens created by the fund endpoint and combines them back into one UTXO |
| 6 | + * locked to the treasury address. |
| 7 | + * |
| 8 | + * Process: |
| 9 | + * 1. Retrieves all confirmed, unused UTXOs from the database |
| 10 | + * 2. Creates a transaction with all UTXOs as inputs |
| 11 | + * 3. Unlocks each input using its stored secret |
| 12 | + * 4. Creates a single change output locked to the treasury address |
| 13 | + * 5. Broadcasts the consolidation transaction |
| 14 | + * |
| 15 | + * @route POST /api/consolidate |
| 16 | + * @returns {Object} Consolidation status |
| 17 | + * - txid: Transaction ID of the consolidation |
| 18 | + * - utxosConsolidated: Number of UTXOs combined |
| 19 | + * - totalSatoshis: Total satoshis consolidated |
| 20 | + * |
| 21 | + * Use Cases: |
| 22 | + * - Reclaim unused tokens |
| 23 | + * - Reduce UTXO fragmentation |
| 24 | + * - Prepare treasury for new funding rounds |
| 25 | + */ |
| 26 | + |
| 27 | +import { Request, Response } from 'express' |
| 28 | +import { P2PKH, SatoshisPerKilobyte, Transaction } from '@bsv/sdk' |
| 29 | +import HashPuzzle from '../HashPuzzle' |
| 30 | +import db from '../db' |
| 31 | +import Arc from '../arc' |
| 32 | +import { address } from '../functions/address' |
| 33 | + |
| 34 | +export default async function (_req: Request, res: Response) { |
| 35 | + try { |
| 36 | + // Retrieve all confirmed, unused UTXOs from the database |
| 37 | + const utxos = await db.collection('utxos').find({ |
| 38 | + confirmed: true, |
| 39 | + fileHash: null, |
| 40 | + invalid: null, |
| 41 | + spent: { $ne: true } |
| 42 | + }).toArray() |
| 43 | + |
| 44 | + console.log({ utxosFound: utxos.length }) |
| 45 | + |
| 46 | + if (utxos.length === 0) { |
| 47 | + res.send({ error: 'No UTXOs available to consolidate' }) |
| 48 | + return |
| 49 | + } |
| 50 | + |
| 51 | + // Calculate total satoshis being consolidated |
| 52 | + const totalSatoshis = utxos.reduce((sum, utxo) => sum + utxo.satoshis, 0) |
| 53 | + |
| 54 | + // Create consolidation transaction |
| 55 | + const tx = new Transaction() |
| 56 | + |
| 57 | + // Add each UTXO as an input |
| 58 | + for (const utxo of utxos) { |
| 59 | + // Retrieve the source transaction from the database |
| 60 | + const sourceTransactionDoc = await db.collection('txs').findOne({ txid: utxo.txid }) |
| 61 | + |
| 62 | + if (!sourceTransactionDoc) { |
| 63 | + console.error(`Source transaction not found for UTXO ${utxo.txid}:${utxo.vout}`) |
| 64 | + continue |
| 65 | + } |
| 66 | + |
| 67 | + const sourceTransaction = Transaction.fromHexBEEF(sourceTransactionDoc.beef) |
| 68 | + |
| 69 | + // Add input with hash puzzle unlock |
| 70 | + tx.addInput({ |
| 71 | + sourceTransaction, |
| 72 | + sourceOutputIndex: utxo.vout, |
| 73 | + unlockingScriptTemplate: new HashPuzzle().unlock(utxo.secret.secret) |
| 74 | + }) |
| 75 | + } |
| 76 | + |
| 77 | + // Add single output back to treasury address |
| 78 | + tx.addOutput({ |
| 79 | + change: true, |
| 80 | + lockingScript: new P2PKH().lock(address) |
| 81 | + }) |
| 82 | + |
| 83 | + // Calculate fees and sign transaction |
| 84 | + await tx.fee(new SatoshisPerKilobyte(100)) |
| 85 | + await tx.sign() |
| 86 | + |
| 87 | + // Broadcast transaction |
| 88 | + const initialResponse = await tx.broadcast(Arc) |
| 89 | + console.log({ initialResponse }) |
| 90 | + |
| 91 | + const txid = tx.id('hex') |
| 92 | + |
| 93 | + // Store consolidation transaction in database |
| 94 | + const txDbResponse = await db.collection('txs').insertOne({ |
| 95 | + txid, |
| 96 | + beef: tx.toHexBEEF(), |
| 97 | + arc: [initialResponse], |
| 98 | + type: 'consolidation', |
| 99 | + utxosConsolidated: utxos.length, |
| 100 | + totalSatoshis |
| 101 | + }) |
| 102 | + |
| 103 | + // Mark consolidated UTXOs as spent |
| 104 | + await db.collection('utxos').updateMany( |
| 105 | + { |
| 106 | + _id: { $in: utxos.map(u => u._id) } |
| 107 | + }, |
| 108 | + { |
| 109 | + $set: { spent: true, spentInTx: txid } |
| 110 | + } |
| 111 | + ) |
| 112 | + |
| 113 | + res.send({ |
| 114 | + txid, |
| 115 | + utxosConsolidated: utxos.length, |
| 116 | + totalSatoshis, |
| 117 | + txDbResponse |
| 118 | + }) |
| 119 | + } catch (error) { |
| 120 | + console.error('Failed to consolidate UTXOs', error) |
| 121 | + res.status(500).json({ error: error.message }) |
| 122 | + } |
| 123 | +} |
0 commit comments