Added precondition to transaction.to for a positive integer as an amount

This commit is contained in:
Braydon Fuller 2015-04-10 18:07:20 -04:00
parent f5d3f5b951
commit 3005e19cbf
4 changed files with 68 additions and 8 deletions

View File

@ -639,6 +639,10 @@ Transaction.prototype.getChangeOutput = function() {
* @return {Transaction} this, for chaining
*/
Transaction.prototype.to = function(address, amount) {
$.checkArgument(
JSUtil.isPositiveInteger(amount),
'Amount is expected to be a positive integer'
);
this.addOutput(new Output({
script: Script(new Address(address)),
satoshis: amount

View File

@ -68,5 +68,17 @@ module.exports = {
});
});
return target;
},
/**
* Checks that a value is a positive integer
*
* @param {*} value
* @return {Boolean}
*/
isPositiveInteger: function isPositiveInteger(value) {
return typeof value === 'number' &&
isFinite(value) &&
Math.floor(value) === value &&
value >= 0;
}
};

View File

@ -50,9 +50,10 @@ describe('Transaction', function() {
object.outputs[0].satoshis.should.equal(testAmount - 10000);
});
it('can take a string argument as an amount', function() {
var stringTx = new Transaction().to('mrU9pEmAx26HcbKVrABvgL7AwA5fjNFoDc', '10000');
(stringTx.outputAmount).should.equal(10000);
it('will not accept NaN as an amount', function() {
(function() {
var stringTx = new Transaction().to('mrU9pEmAx26HcbKVrABvgL7AwA5fjNFoDc', NaN);
}).should.throw('Amount is expected to be a positive integer');
});
it('returns the fee correctly', function() {

View File

@ -32,4 +32,47 @@ describe('js utils', function() {
});
describe('isPositiveInteger', function() {
it('false for float', function() {
var a = JSUtil.isPositiveInteger(0.1);
a.should.equal(false);
});
it('false for string float', function() {
var a = JSUtil.isPositiveInteger('0.1');
a.should.equal(false);
});
it('false for string integer', function() {
var a = JSUtil.isPositiveInteger('1');
a.should.equal(false);
});
it('false for negative integer', function() {
var a = JSUtil.isPositiveInteger(-1);
a.should.equal(false);
});
it('false for negative integer string', function() {
var a = JSUtil.isPositiveInteger('-1');
a.should.equal(false);
});
it('false for infinity', function() {
var a = JSUtil.isPositiveInteger(Infinity);
a.should.equal(false);
});
it('false for NaN', function() {
var a = JSUtil.isPositiveInteger(NaN);
a.should.equal(false);
});
it('true for positive integer', function() {
var a = JSUtil.isPositiveInteger(1000);
a.should.equal(true);
});
});
});