Skip to content

Commit

Permalink
wallet: drop change to fee if amount is dust
Browse files Browse the repository at this point in the history
This commit refactors the CoinSelector class to properly handle the calculation
of change cost. The change amount is now checked against the cost of change,
and if the change is less than the cost, the cost is added to the transaction fee.
This ensures that the transaction output is correctly adjusted based on the
current fee rate and the size of the change output.
  • Loading branch information
Ayush170-Future committed Feb 16, 2024
1 parent 490be82 commit 8744fae
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/wallet/coin-selector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,25 @@ export class CoinSelector {

const selected = this.selectCoins(pointers, target);

const change =
let change =
selected.reduce(
(acc, index) => acc + pointers[index].effectiveValue,
0,
) - target;

// TODO: check if change is lower than dust limit, if so add it to fee
// Calculate the cost of change
const LONG_TERM_FEERATE = 5 // in sats/vB
const outputSize = 31; // P2WPKH output is 31 B
const inputSizeOfChangeUTXO = 68.0; // P2WPKH input is 68.0 vbytes

const costOfChangeOutput = outputSize * this.feeRate;
const costOfSpendingChange = inputSizeOfChangeUTXO * LONG_TERM_FEERATE;
const costOfChange = costOfChangeOutput + costOfSpendingChange;

// Check if change is less than the cost of change
if(change <= costOfChange) {
change = 0;
}

return {
coins: selected.map((index) => pointers[index].coin),
Expand Down

0 comments on commit 8744fae

Please sign in to comment.