-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
8744fae
commit 3c1983e
Showing
2 changed files
with
93 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
import { Coin } from '../src/wallet/coin'; | ||
import { CoinSelector } from '../src/wallet/coin-selector.ts'; | ||
import { Transaction } from 'bitcoinjs-lib'; | ||
import { validTransactions } from './fixtures/transaction'; | ||
|
||
describe('CoinSelector', () => { | ||
let coins: Coin[]; | ||
let transaction: Transaction; | ||
let coinSelector: CoinSelector; | ||
const feeRate: number = 5; | ||
let totalBalance: number = 0; | ||
|
||
beforeAll(() => { | ||
coinSelector = new CoinSelector(feeRate); | ||
// Add Balance | ||
coins = []; | ||
for (let i = 0; i < 10; i++) { | ||
const value = Math.random() * 1000; | ||
const coin = new Coin({ value }); | ||
coins.push(coin); | ||
totalBalance += coin.value - coin.estimateSpendingFee(feeRate); | ||
} | ||
}); | ||
|
||
it('should generate cost of change', () => { | ||
const costOfChange: number = coinSelector.costOfChange; | ||
expect(typeof costOfChange).toBe('number'); | ||
|
||
// Calculate transaction output value | ||
const txOutValue: number = Math.floor(totalBalance - costOfChange); | ||
|
||
// Create a new transaction | ||
transaction = new Transaction(); | ||
// Add an output with random scriptPubKey: We are only concered about its value | ||
transaction.addOutput( | ||
Buffer.from(validTransactions[0].raw.outs[0].script, 'hex'), | ||
1, | ||
); | ||
|
||
// Calculate fees | ||
let fees = transaction.virtualSize() * feeRate; | ||
fees += 31 * feeRate; // ChangeOutputFee: P2WPKH is 31 B | ||
const finalTxOutValue = txOutValue - fees; | ||
|
||
// Set the transaction output value | ||
transaction.outs[0].value = finalTxOutValue; | ||
}); | ||
|
||
it('should add change to fee if it is dust', () => { | ||
const { coins: selectCoins, change } = coinSelector.select( | ||
coins, | ||
transaction, | ||
); | ||
expect(selectCoins.length).toBeGreaterThan(0); | ||
|
||
// The above calculation makes sure the Change is always less than costOfChange: Dust | ||
expect(change).toBe(0); | ||
}); | ||
}); |