Skip to content

Commit

Permalink
feat: allow to cap number of inputs for calcInputs (#147)
Browse files Browse the repository at this point in the history
  • Loading branch information
troggy authored and sunify committed Sep 6, 2019
1 parent f6842ad commit e51fdea
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
13 changes: 12 additions & 1 deletion lib/transaction.js
Original file line number Diff line number Diff line change
Expand Up @@ -714,7 +714,7 @@ export default class Transaction {
}
}

static calcInputs(unspent, from, amount, color = 0) {
static calcInputs(unspent, from, amount, color = 0, limit) {
const myUnspent = unspent.filter(
({ output }) =>
output.color === color &&
Expand All @@ -736,6 +736,17 @@ export default class Transaction {
if (greaterThanOrEqual(sum, BigInt(amount))) {
break;
}
if (limit && inputs.length + 1 === limit) {
const diff = subtract(BigInt(amount), sum);
const oneMore = myUnspent
.slice(i + 1).find(u => greaterThanOrEqual(BigInt(u.output.value), diff));

if (oneMore) {
inputs.push(new Input(oneMore.outpoint));
sum = add(sum, BigInt(oneMore.output.value));
}
break;
}
}

if (lessThan(sum, BigInt(amount))) {
Expand Down
22 changes: 22 additions & 0 deletions lib/transaction.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,28 @@ describe('transactions', () => {
deposit2.hash(),
);
});

it('should use limit if provided', async () => {
const deposit3 = Tx.deposit(2, 100, ADDR_1);
const deposit4 = Tx.deposit(2, 400, ADDR_1);
const moreUnspent = [
...unspent,
{ output: deposit3.outputs[0], outpoint: new Outpoint(deposit3.hash(), 0) },
{ output: deposit4.outputs[0], outpoint: new Outpoint(deposit4.hash(), 0) },
];

const inputs1 = calcInputs(moreUnspent, ADDR_1, 350, 0, 2);
expect(inputs1.length).to.eq(2);
expect(ethUtil.bufferToHex(inputs1[0].prevout.hash)).to.eq(
deposit1.hash(),
);
expect(ethUtil.bufferToHex(inputs1[1].prevout.hash)).to.eq(
deposit4.hash(),
);
expect(() =>
calcInputs(moreUnspent, ADDR_1, 550, 0, 2)
).to.throw('Not enough inputs');
});
});

describe('Tx.calcOutputs', () => {
Expand Down

0 comments on commit e51fdea

Please sign in to comment.