Merge pull request #2296 from MetaMask/precision-fix

Fix precision to account for small wei increase.
feature/default_network_editable
Dan Finlay 7 years ago committed by GitHub
commit f18615a82a
  1. 38
      test/unit/components/bn-as-decimal-input-test.js
  2. 11
      ui/app/components/bn-as-decimal-input.js

@ -48,4 +48,42 @@ describe('BnInput', function () {
checkValidity () { return true } }, checkValidity () { return true } },
}) })
}) })
it('can tolerate wei precision', function (done) {
const renderer = ReactTestUtils.createRenderer()
let valueStr = '1000000000'
const value = new BN(valueStr, 10)
const inputStr = '1.000000001'
let targetStr = '1000000001'
const target = new BN(targetStr, 10)
const precision = 9 // gwei precision
const scale = 9
const props = {
value,
scale,
precision,
onChange: (newBn) => {
assert.equal(newBn.toString(), target.toString(), 'should tolerate increase')
const reInput = BnInput.prototype.downsize(newBn.toString(), 9, 9)
assert.equal(reInput.toString(), inputStr, 'should tolerate increase')
done()
},
}
const inputComponent = h(BnInput, props)
const component = additions.renderIntoDocument(inputComponent)
renderer.render(inputComponent)
const input = additions.find(component, 'input.hex-input')[0]
ReactTestUtils.Simulate.change(input, { preventDefault () {}, target: {
value: inputStr,
checkValidity () { return true } },
})
})
}) })

@ -31,7 +31,7 @@ BnAsDecimalInput.prototype.render = function () {
const suffix = props.suffix const suffix = props.suffix
const style = props.style const style = props.style
const valueString = value.toString(10) const valueString = value.toString(10)
const newValue = this.downsize(valueString, scale, precision) const newValue = this.downsize(valueString, scale)
return ( return (
h('.flex-column', [ h('.flex-column', [
@ -145,14 +145,17 @@ BnAsDecimalInput.prototype.constructWarning = function () {
} }
BnAsDecimalInput.prototype.downsize = function (number, scale, precision) { BnAsDecimalInput.prototype.downsize = function (number, scale) {
// if there is no scaling, simply return the number // if there is no scaling, simply return the number
if (scale === 0) { if (scale === 0) {
return Number(number) return Number(number)
} else { } else {
// if the scale is the same as the precision, account for this edge case. // if the scale is the same as the precision, account for this edge case.
var decimals = (scale === precision) ? -1 : scale - precision var adjustedNumber = number
return Number(number.slice(0, -scale) + '.' + number.slice(-scale, decimals)) while (adjustedNumber.length < scale) {
adjustedNumber = '0' + adjustedNumber
}
return Number(adjustedNumber.slice(0, -scale) + '.' + adjustedNumber.slice(-scale))
} }
} }

Loading…
Cancel
Save