1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-23 09:52:26 +01:00

Got basic validations working

This commit is contained in:
Dan Finlay 2017-03-22 15:14:33 -07:00
parent 9f1f0bff1e
commit 77907038ff
5 changed files with 199 additions and 108 deletions

View File

@ -9,6 +9,7 @@ module.exports = HexAsDecimalInput
inherits(HexAsDecimalInput, Component) inherits(HexAsDecimalInput, Component)
function HexAsDecimalInput () { function HexAsDecimalInput () {
this.state = { invalid: null }
Component.call(this) Component.call(this)
} }
@ -23,50 +24,101 @@ function HexAsDecimalInput () {
HexAsDecimalInput.prototype.render = function () { HexAsDecimalInput.prototype.render = function () {
const props = this.props const props = this.props
const { value, onChange, min } = props const state = this.state
const { value, onChange, min, max } = props
const toEth = props.toEth const toEth = props.toEth
const suffix = props.suffix const suffix = props.suffix
const decimalValue = decimalize(value, toEth) const decimalValue = decimalize(value, toEth)
const style = props.style const style = props.style
return ( return (
h('.flex-row', { h('.flex-column', [
style: { h('.flex-row', {
alignItems: 'flex-end',
lineHeight: '13px',
fontFamily: 'Montserrat Light',
textRendering: 'geometricPrecision',
},
}, [
h('input.hex-input', {
type: 'number',
min,
style: extend({
display: 'block',
textAlign: 'right',
backgroundColor: 'transparent',
border: '1px solid #bdbdbd',
}, style),
value: decimalValue,
onChange: (event) => {
const hexString = (event.target.value === '') ? '' : hexify(event.target.value)
onChange(hexString)
},
}),
h('div', {
style: { style: {
color: ' #AEAEAE', alignItems: 'flex-end',
fontSize: '12px', lineHeight: '13px',
marginLeft: '5px', fontFamily: 'Montserrat Light',
marginRight: '6px', textRendering: 'geometricPrecision',
width: '20px',
}, },
}, suffix), }, [
h('input.hex-input', {
type: 'number',
required: true,
min: min,
max: max,
style: extend({
display: 'block',
textAlign: 'right',
backgroundColor: 'transparent',
border: '1px solid #bdbdbd',
}, style),
value: parseInt(decimalValue),
onChange: (event) => {
const target = event.target
const valid = target.checkValidity()
if (valid) {
this.setState({ invalid: null })
}
const hexString = (event.target.value === '') ? '' : hexify(event.target.value)
onChange(hexString)
},
onInvalid: (event) => {
const msg = this.constructWarning()
if (msg === state.invalid) {
return
}
this.setState({ invalid: msg })
event.preventDefault()
},
}),
h('div', {
style: {
color: ' #AEAEAE',
fontSize: '12px',
marginLeft: '5px',
marginRight: '6px',
width: '20px',
},
}, suffix),
]),
state.invalid ? h('span.error', {
style: {
position: 'absolute',
right: '0px',
textAlign: 'right',
transform: 'translateY(26px)',
padding: '3px',
background: 'rgba(255,255,255,0.85)',
zIndex: '1',
textTransform: 'capitalize',
border: '2px solid #E20202',
},
}, state.invalid) : null,
]) ])
) )
} }
HexAsDecimalInput.prototype.constructWarning = function () {
const { name, min, max } = this.props
let message = name ? name + ' ' : ''
if (min && max) {
message += `must be greater than or equal to ${min} and less than or equal to ${max}.`
} else if (min) {
message += `must be greater than or equal to ${min}.`
} else if (max) {
message += `must be less than or equal to ${max}.`
} else {
message += 'Invalid input.'
}
return message
}
function hexify (decimalString) { function hexify (decimalString) {
const hexBN = new BN(decimalString, 10) const hexBN = new BN(decimalString, 10)
return '0x' + hexBN.toString('hex') return '0x' + hexBN.toString('hex')

View File

@ -12,15 +12,17 @@ const addressSummary = util.addressSummary
const nameForAddress = require('../../lib/contract-namer') const nameForAddress = require('../../lib/contract-namer')
const HexInput = require('./hex-as-decimal-input') const HexInput = require('./hex-as-decimal-input')
const DEFAULT_GAS_PRICE = '0x4a817c800' const DEFAULT_GAS_PRICE_BN = new BN(20000000000, '10')
const DEFAULT_GAS_PRICE_BN = new BN(DEFAULT_GAS_PRICE.substr(2), 16) const DEFAULT_GAS_PRICE = DEFAULT_GAS_PRICE_BN.toString(16)
const FOUR_BN = new BN('4', 10)
const MIN_GAS_PRICE_BN = new BN(20000000)
module.exports = PendingTxDetails module.exports = PendingTxDetails
inherits(PendingTxDetails, Component) inherits(PendingTxDetails, Component)
function PendingTxDetails () { function PendingTxDetails () {
Component.call(this) Component.call(this)
this.state = { valid: true }
} }
const PTXP = PendingTxDetails.prototype const PTXP = PendingTxDetails.prototype
@ -40,6 +42,7 @@ PTXP.render = function () {
const gasPrice = (state.gasPrice === undefined) ? txData.gasPrice : state.gasPrice const gasPrice = (state.gasPrice === undefined) ? txData.gasPrice : state.gasPrice
var txFee = state.txFee || txData.txFee || '' var txFee = state.txFee || txData.txFee || ''
var txFeeBn = new BN(txFee, 16)
var maxCost = state.maxCost || txData.maxCost || '' var maxCost = state.maxCost || txData.maxCost || ''
var dataLength = txParams.data ? (txParams.data.length - 2) / 2 : 0 var dataLength = txParams.data ? (txParams.data.length - 2) / 2 : 0
var imageify = props.imageifyIdenticons === undefined ? true : props.imageifyIdenticons var imageify = props.imageifyIdenticons === undefined ? true : props.imageifyIdenticons
@ -124,6 +127,7 @@ PTXP.render = function () {
h('.cell.value', { h('.cell.value', {
}, [ }, [
h(HexInput, { h(HexInput, {
name: 'Gas Limit',
value: gas, value: gas,
min: 21000, // The hard lower limit for gas. min: 21000, // The hard lower limit for gas.
suffix: 'UNITS', suffix: 'UNITS',
@ -145,9 +149,10 @@ PTXP.render = function () {
h('.cell.value', { h('.cell.value', {
}, [ }, [
h(HexInput, { h(HexInput, {
name: 'Gas Price',
value: gasPrice, value: gasPrice,
suffix: 'WEI', suffix: 'WEI',
min: DEFAULT_GAS_PRICE_BN.div(FOUR_BN).toString(10), min: MIN_GAS_PRICE_BN.toString(10),
style: { style: {
position: 'relative', position: 'relative',
top: '5px', top: '5px',
@ -163,7 +168,7 @@ PTXP.render = function () {
// Max Transaction Fee (calculated) // Max Transaction Fee (calculated)
h('.cell.row', [ h('.cell.row', [
h('.cell.label', 'Max Transaction Fee'), h('.cell.label', 'Max Transaction Fee'),
h(EthBalance, { value: txFee.toString(16) }), h(EthBalance, { value: txFeeBn.toString(16) }),
]), ]),
h('.cell.row', { h('.cell.row', {
@ -181,8 +186,7 @@ PTXP.render = function () {
}, },
}, [ }, [
h(EthBalance, { h(EthBalance, {
value: '0x' + txFee.add(new BN(txParams.value, 16)).toString(16), value: maxCost.toString(16),
maxCost.toString(16),
inline: true, inline: true,
labelColor: 'black', labelColor: 'black',
fontSize: '16px', fontSize: '16px',
@ -267,6 +271,10 @@ PTXP.componentDidUpdate = function (prevProps, previousState) {
} }
} }
PTXP.isValid = function () {
return this.state.valid
}
PTXP.calculateGas = function () { PTXP.calculateGas = function () {
const txMeta = this.gatherParams() const txMeta = this.gatherParams()
log.debug(`pending-tx-details calculating gas for ${JSON.stringify(txMeta)}`) log.debug(`pending-tx-details calculating gas for ${JSON.stringify(txMeta)}`)
@ -274,6 +282,10 @@ PTXP.calculateGas = function () {
var txParams = txMeta.txParams var txParams = txMeta.txParams
var gasCost = new BN(ethUtil.stripHexPrefix(txParams.gas || txMeta.estimatedGas), 16) var gasCost = new BN(ethUtil.stripHexPrefix(txParams.gas || txMeta.estimatedGas), 16)
var gasPrice = new BN(ethUtil.stripHexPrefix(txParams.gasPrice || DEFAULT_GAS_PRICE), 16) var gasPrice = new BN(ethUtil.stripHexPrefix(txParams.gasPrice || DEFAULT_GAS_PRICE), 16)
const valid = !gasPrice.lt(MIN_GAS_PRICE_BN)
this.props.validChanged(valid)
var txFee = gasCost.mul(gasPrice) var txFee = gasCost.mul(gasPrice)
var txValue = new BN(ethUtil.stripHexPrefix(txParams.value || '0x0'), 16) var txValue = new BN(ethUtil.stripHexPrefix(txParams.value || '0x0'), 16)
var maxCost = txValue.add(txFee) var maxCost = txValue.add(txFee)

View File

@ -17,11 +17,15 @@ function mapStateToProps (state) {
inherits(PendingTx, Component) inherits(PendingTx, Component)
function PendingTx () { function PendingTx () {
Component.call(this) Component.call(this)
this.state = { valid: true }
} }
PendingTx.prototype.render = function () { PendingTx.prototype.render = function () {
const props = this.props const props = this.props
const newProps = extend(props, {ref: 'details'}) const newProps = extend(props, {
ref: 'details',
validChanged: this.validChanged.bind(this),
})
const txData = props.txData const txData = props.txData
return ( return (
@ -30,70 +34,87 @@ PendingTx.prototype.render = function () {
key: txData.id, key: txData.id,
}, [ }, [
// tx info h('form#pending-tx-form', {
h(PendingTxDetails, newProps), onSubmit: (event) => {
event.preventDefault()
const form = document.querySelector('form#pending-tx-form')
const valid = form.checkValidity()
this.setState({ valid })
h('style', ` if (valid && this.refs.details.verifyGasParams()) {
.conf-buttons button { props.sendTransaction(txData, event)
margin-left: 10px; } else {
text-transform: uppercase; this.props.dispatch(actions.displayWarning('Invalid Gas Parameters'))
} }
`),
txData.simulationFails ?
h('.error', {
style: {
marginLeft: 50,
fontSize: '0.9em',
},
}, 'Transaction Error. Exception thrown in contract code.')
: null,
props.insufficientBalance ?
h('span.error', {
style: {
marginLeft: 50,
fontSize: '0.9em',
},
}, 'Insufficient balance for transaction')
: null,
// send + cancel
h('.flex-row.flex-space-around.conf-buttons', {
style: {
display: 'flex',
justifyContent: 'flex-end',
margin: '14px 25px',
}, },
}, [ }, [
props.insufficientBalance ? // tx info
h('button', { h(PendingTxDetails, newProps),
onClick: props.buyEth,
}, 'Buy Ether') h('style', `
.conf-buttons button {
margin-left: 10px;
text-transform: uppercase;
}
`),
txData.simulationFails ?
h('.error', {
style: {
marginLeft: 50,
fontSize: '0.9em',
},
}, 'Transaction Error. Exception thrown in contract code.')
: null, : null,
h('button', { props.insufficientBalance ?
onClick: () => { h('span.error', {
this.refs.details.resetGasFields() style: {
}, marginLeft: 50,
}, 'Reset'), fontSize: '0.9em',
},
}, 'Insufficient balance for transaction')
: null,
h('button.confirm.btn-green', { // send + cancel
disabled: props.insufficientBalance, h('.flex-row.flex-space-around.conf-buttons', {
onClick: (txData, event) => { style: {
if (this.refs.details.verifyGasParams()) { display: 'flex',
props.sendTransaction(txData, event) justifyContent: 'flex-end',
} else { margin: '14px 25px',
this.props.dispatch(actions.displayWarning('Invalid Gas Parameters'))
}
}, },
}, 'Accept'), }, [
h('button.cancel.btn-red', {
onClick: props.cancelTransaction, props.insufficientBalance ?
}, 'Reject'), h('button', {
onClick: props.buyEth,
}, 'Buy Ether')
: null,
h('button', {
onClick: () => {
this.refs.details.resetGasFields()
},
}, 'Reset'),
h('input.confirm.btn-green', {
type: 'submit',
value: 'ACCEPT',
style: { marginLeft: '10px' },
disabled: props.insufficientBalance || !this.state.valid,
}),
h('button.cancel.btn-red', {
onClick: props.cancelTransaction,
}, 'Reject'),
]),
]), ]),
]) ])
) )
} }
PendingTx.prototype.validChanged = function (newValid) {
this.setState({ valid: newValid })
}

View File

@ -158,7 +158,7 @@ ConfirmTxScreen.prototype.checkBalanceAgainstTx = function (txData) {
} }
ConfirmTxScreen.prototype.buyEth = function (address, event) { ConfirmTxScreen.prototype.buyEth = function (address, event) {
event.stopPropagation() this.stopPropagation(event)
this.props.dispatch(actions.buyEthView(address)) this.props.dispatch(actions.buyEthView(address))
} }
@ -172,14 +172,14 @@ ConfirmTxScreen.prototype.onTxChange = function (txData) {
// Must default to any local state txData, // Must default to any local state txData,
// to allow manual override of gas calculations. // to allow manual override of gas calculations.
ConfirmTxScreen.prototype.sendTransaction = function (txData, event) { ConfirmTxScreen.prototype.sendTransaction = function (txData, event) {
event.stopPropagation() this.stopPropagation(event)
const state = this.state || {} const state = this.state || {}
const txMeta = state.txData const txMeta = state.txData
this.props.dispatch(actions.updateAndApproveTx(txMeta || txData)) this.props.dispatch(actions.updateAndApproveTx(txMeta || txData))
} }
ConfirmTxScreen.prototype.cancelTransaction = function (txData, event) { ConfirmTxScreen.prototype.cancelTransaction = function (txData, event) {
event.stopPropagation() this.stopPropagation(event)
this.props.dispatch(actions.cancelTx(txData)) this.props.dispatch(actions.cancelTx(txData))
} }
@ -187,32 +187,38 @@ ConfirmTxScreen.prototype.signMessage = function (msgData, event) {
log.info('conf-tx.js: signing message') log.info('conf-tx.js: signing message')
var params = msgData.msgParams var params = msgData.msgParams
params.metamaskId = msgData.id params.metamaskId = msgData.id
event.stopPropagation() this.stopPropagation(event)
this.props.dispatch(actions.signMsg(params)) this.props.dispatch(actions.signMsg(params))
} }
ConfirmTxScreen.prototype.stopPropagation = function (event) {
if (event.stopPropagation) {
event.stopPropagation()
}
}
ConfirmTxScreen.prototype.signPersonalMessage = function (msgData, event) { ConfirmTxScreen.prototype.signPersonalMessage = function (msgData, event) {
log.info('conf-tx.js: signing personal message') log.info('conf-tx.js: signing personal message')
var params = msgData.msgParams var params = msgData.msgParams
params.metamaskId = msgData.id params.metamaskId = msgData.id
event.stopPropagation() this.stopPropagation(event)
this.props.dispatch(actions.signPersonalMsg(params)) this.props.dispatch(actions.signPersonalMsg(params))
} }
ConfirmTxScreen.prototype.cancelMessage = function (msgData, event) { ConfirmTxScreen.prototype.cancelMessage = function (msgData, event) {
log.info('canceling message') log.info('canceling message')
event.stopPropagation() this.stopPropagation(event)
this.props.dispatch(actions.cancelMsg(msgData)) this.props.dispatch(actions.cancelMsg(msgData))
} }
ConfirmTxScreen.prototype.cancelPersonalMessage = function (msgData, event) { ConfirmTxScreen.prototype.cancelPersonalMessage = function (msgData, event) {
log.info('canceling personal message') log.info('canceling personal message')
event.stopPropagation() this.stopPropagation(event)
this.props.dispatch(actions.cancelPersonalMsg(msgData)) this.props.dispatch(actions.cancelPersonalMsg(msgData))
} }
ConfirmTxScreen.prototype.goHome = function (event) { ConfirmTxScreen.prototype.goHome = function (event) {
event.stopPropagation() this.stopPropagation(event)
this.props.dispatch(actions.goHome()) this.props.dispatch(actions.goHome())
} }

View File

@ -32,7 +32,7 @@ input:focus, textarea:focus {
height: 500px; height: 500px;
} }
button { button, input[type="submit"] {
font-family: 'Montserrat Bold'; font-family: 'Montserrat Bold';
outline: none; outline: none;
cursor: pointer; cursor: pointer;
@ -46,17 +46,17 @@ button {
box-shadow: 0px 3px 6px rgba(247, 134, 28, 0.36); box-shadow: 0px 3px 6px rgba(247, 134, 28, 0.36);
} }
button.btn-green { .btn-green, input[type="submit"].btn-green {
background: rgba(106, 195, 96, 1); background: rgba(106, 195, 96, 1);
box-shadow: 0px 3px 6px rgba(106, 195, 96, 0.36); box-shadow: 0px 3px 6px rgba(106, 195, 96, 0.36);
} }
button.btn-red { .btn-red {
background: rgba(254, 35, 17, 1); background: rgba(254, 35, 17, 1);
box-shadow: 0px 3px 6px rgba(254, 35, 17, 0.36); box-shadow: 0px 3px 6px rgba(254, 35, 17, 0.36);
} }
button[disabled] { button[disabled], input[type="submit"][disabled] {
cursor: not-allowed; cursor: not-allowed;
background: rgba(197, 197, 197, 1); background: rgba(197, 197, 197, 1);
box-shadow: 0px 3px 6px rgba(197, 197, 197, 0.36); box-shadow: 0px 3px 6px rgba(197, 197, 197, 0.36);
@ -66,10 +66,10 @@ button.spaced {
margin: 2px; margin: 2px;
} }
button:not([disabled]):hover { button:not([disabled]):hover, input[type="submit"]:not([disabled]):hover {
transform: scale(1.1); transform: scale(1.1);
} }
button:not([disabled]):active { button:not([disabled]):active, input[type="submit"]:not([disabled]):active {
transform: scale(0.95); transform: scale(0.95);
} }