diff options
author | Dan Finlay <542863+danfinlay@users.noreply.github.com> | 2019-08-07 05:53:50 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-08-07 05:53:50 +0800 |
commit | db08881d4527e8a037f401ef22b849e52152864f (patch) | |
tree | 6032d7a4ae67371889eece1d8490c26d5a119dd5 /ui/app/pages/send | |
parent | 4139019d0f4dd83f56da400ca7e0e6d1976d1716 (diff) | |
parent | 86ad9564a064fd6158dab6a3c9e5b10614ef6e68 (diff) | |
download | tangerine-wallet-browser-7.0.0.tar tangerine-wallet-browser-7.0.0.tar.gz tangerine-wallet-browser-7.0.0.tar.bz2 tangerine-wallet-browser-7.0.0.tar.lz tangerine-wallet-browser-7.0.0.tar.xz tangerine-wallet-browser-7.0.0.tar.zst tangerine-wallet-browser-7.0.0.zip |
Merge pull request #6969 from MetaMask/developv7.0.0
Master Version Bump
Diffstat (limited to 'ui/app/pages/send')
45 files changed, 1628 insertions, 635 deletions
diff --git a/ui/app/pages/send/account-list-item/account-list-item.container.js b/ui/app/pages/send/account-list-item/account-list-item.container.js index 21f800306..3fadec4f8 100644 --- a/ui/app/pages/send/account-list-item/account-list-item.container.js +++ b/ui/app/pages/send/account-list-item/account-list-item.container.js @@ -1,8 +1,8 @@ import { connect } from 'react-redux' import { - getConversionRate, - getCurrentCurrency, - getNativeCurrency, + getConversionRate, + getCurrentCurrency, + getNativeCurrency, } from '../send.selectors.js' import { getIsMainnet, diff --git a/ui/app/pages/send/send-content/add-recipient/add-recipient.component.js b/ui/app/pages/send/send-content/add-recipient/add-recipient.component.js new file mode 100644 index 000000000..e5edbc08d --- /dev/null +++ b/ui/app/pages/send/send-content/add-recipient/add-recipient.component.js @@ -0,0 +1,243 @@ +import React, { Component } from 'react' +import PropTypes from 'prop-types' +import Fuse from 'fuse.js' +import Identicon from '../../../../components/ui/identicon' +import {isValidAddress} from '../../../../helpers/utils/util' +import Dialog from '../../../../components/ui/dialog' +import ContactList from '../../../../components/app/contact-list' +import RecipientGroup from '../../../../components/app/contact-list/recipient-group/recipient-group.component' +import {ellipsify} from '../../send.utils' + +export default class AddRecipient extends Component { + + static propTypes = { + className: PropTypes.string, + query: PropTypes.string, + ownedAccounts: PropTypes.array, + addressBook: PropTypes.array, + updateGas: PropTypes.func, + updateSendTo: PropTypes.func, + ensResolution: PropTypes.string, + toError: PropTypes.string, + toWarning: PropTypes.string, + ensResolutionError: PropTypes.string, + selectedToken: PropTypes.object, + hasHexData: PropTypes.bool, + tokens: PropTypes.array, + addressBookEntryName: PropTypes.string, + contacts: PropTypes.array, + nonContacts: PropTypes.array, + } + + constructor (props) { + super(props) + this.recentFuse = new Fuse(props.nonContacts, { + shouldSort: true, + threshold: 0.45, + location: 0, + distance: 100, + maxPatternLength: 32, + minMatchCharLength: 1, + keys: [ + { name: 'address', weight: 0.5 }, + ], + }) + + this.contactFuse = new Fuse(props.contacts, { + shouldSort: true, + threshold: 0.45, + location: 0, + distance: 100, + maxPatternLength: 32, + minMatchCharLength: 1, + keys: [ + { name: 'name', weight: 0.5 }, + { name: 'address', weight: 0.5 }, + ], + }) + } + + static contextTypes = { + t: PropTypes.func, + metricsEvent: PropTypes.func, + } + + state = { + isShowingTransfer: false, + isShowingAllRecent: false, + } + + selectRecipient = (to, nickname = '') => { + const { updateSendTo, updateGas } = this.props + + updateSendTo(to, nickname) + updateGas({ to }) + } + + searchForContacts = () => { + const { query, contacts } = this.props + + let _contacts = contacts + + if (query) { + this.contactFuse.setCollection(contacts) + _contacts = this.contactFuse.search(query) + } + + return _contacts + } + + searchForRecents = () => { + const { query, nonContacts } = this.props + + let _nonContacts = nonContacts + + if (query) { + this.recentFuse.setCollection(nonContacts) + _nonContacts = this.recentFuse.search(query) + } + + return _nonContacts + } + + render () { + const { ensResolution, query, addressBookEntryName } = this.props + const { isShowingTransfer } = this.state + + let content + + if (isValidAddress(query)) { + content = this.renderExplicitAddress(query) + } else if (ensResolution) { + content = this.renderExplicitAddress(ensResolution, addressBookEntryName || query) + } else if (isShowingTransfer) { + content = this.renderTransfer() + } + + return ( + <div className="send__select-recipient-wrapper"> + { this.renderDialogs() } + { content || this.renderMain() } + </div> + ) + } + + renderExplicitAddress (address, name) { + return ( + <div + key={address} + className="send__select-recipient-wrapper__group-item" + onClick={() => this.selectRecipient(address, name)} + > + <Identicon address={address} diameter={28} /> + <div className="send__select-recipient-wrapper__group-item__content"> + <div className="send__select-recipient-wrapper__group-item__title"> + {name || ellipsify(address)} + </div> + { + name && ( + <div className="send__select-recipient-wrapper__group-item__subtitle"> + {ellipsify(address)} + </div> + ) + } + </div> + </div> + ) + } + + renderTransfer () { + const { ownedAccounts } = this.props + const { t } = this.context + + return ( + <div className="send__select-recipient-wrapper__list"> + <div + className="send__select-recipient-wrapper__list__link" + onClick={() => this.setState({ isShowingTransfer: false })} + > + <div className="send__select-recipient-wrapper__list__back-caret"/> + { t('backToAll') } + </div> + <RecipientGroup + label={t('myAccounts')} + items={ownedAccounts} + onSelect={this.selectRecipient} + /> + </div> + ) + } + + renderMain () { + const { t } = this.context + const { query, ownedAccounts = [], addressBook } = this.props + + return ( + <div className="send__select-recipient-wrapper__list"> + <ContactList + addressBook={addressBook} + searchForContacts={this.searchForContacts.bind(this)} + searchForRecents={this.searchForRecents.bind(this)} + selectRecipient={this.selectRecipient.bind(this)} + > + { + (ownedAccounts && ownedAccounts.length > 1) && !query && ( + <div + className="send__select-recipient-wrapper__list__link" + onClick={() => this.setState({ isShowingTransfer: true })} + > + { t('transferBetweenAccounts') } + </div> + ) + } + </ContactList> + </div> + ) + } + + renderDialogs () { + const { toError, toWarning, ensResolutionError, ensResolution } = this.props + const { t } = this.context + const contacts = this.searchForContacts() + const recents = this.searchForRecents() + + if (contacts.length || recents.length) { + return null + } + + if (ensResolutionError) { + return ( + <Dialog + type="error" + className="send__error-dialog" + > + {ensResolutionError} + </Dialog> + ) + } + + if (toError && toError !== 'required' && !ensResolution) { + return ( + <Dialog + type="error" + className="send__error-dialog" + > + {t(toError)} + </Dialog> + ) + } + + + if (toWarning) { + return ( + <Dialog + type="warning" + className="send__error-dialog" + > + {t(toWarning)} + </Dialog> + ) + } + } + +} diff --git a/ui/app/pages/send/send-content/add-recipient/add-recipient.container.js b/ui/app/pages/send/send-content/add-recipient/add-recipient.container.js new file mode 100644 index 000000000..eb980aa82 --- /dev/null +++ b/ui/app/pages/send/send-content/add-recipient/add-recipient.container.js @@ -0,0 +1,44 @@ +import { connect } from 'react-redux' +import { + accountsWithSendEtherInfoSelector, + getSendEnsResolution, + getSendEnsResolutionError, +} from '../../send.selectors.js' +import { + getAddressBook, + getAddressBookEntry, +} from '../../../../selectors/selectors' +import { + updateSendTo, +} from '../../../../store/actions' +import AddRecipient from './add-recipient.component' + +export default connect(mapStateToProps, mapDispatchToProps)(AddRecipient) + +function mapStateToProps (state) { + const ensResolution = getSendEnsResolution(state) + + let addressBookEntryName = '' + if (ensResolution) { + const addressBookEntry = getAddressBookEntry(state, ensResolution) || {} + addressBookEntryName = addressBookEntry.name + } + + const addressBook = getAddressBook(state) + + return { + ownedAccounts: accountsWithSendEtherInfoSelector(state), + addressBook, + ensResolution, + addressBookEntryName, + ensResolutionError: getSendEnsResolutionError(state), + contacts: addressBook.filter(({ name }) => !!name), + nonContacts: addressBook.filter(({ name }) => !name), + } +} + +function mapDispatchToProps (dispatch) { + return { + updateSendTo: (to, nickname) => dispatch(updateSendTo(to, nickname)), + } +} diff --git a/ui/app/pages/send/send-content/send-to-row/send-to-row.utils.js b/ui/app/pages/send/send-content/add-recipient/add-recipient.js index b3b0d2da3..b3b0d2da3 100644 --- a/ui/app/pages/send/send-content/send-to-row/send-to-row.utils.js +++ b/ui/app/pages/send/send-content/add-recipient/add-recipient.js diff --git a/ui/app/pages/send/send-content/send-to-row/send-to-row.selectors.js b/ui/app/pages/send/send-content/add-recipient/add-recipient.selectors.js index a6160d335..a39db7813 100644 --- a/ui/app/pages/send/send-content/send-to-row/send-to-row.selectors.js +++ b/ui/app/pages/send/send-content/add-recipient/add-recipient.selectors.js @@ -12,7 +12,7 @@ function getToDropdownOpen (state) { } function sendToIsInError (state) { - return Boolean(state.send.errors.to) + return Boolean(state.send.errors.to) } function sendToIsInWarning (state) { diff --git a/ui/app/pages/send/send-content/add-recipient/ens-input.component.js b/ui/app/pages/send/send-content/add-recipient/ens-input.component.js new file mode 100644 index 000000000..498d72605 --- /dev/null +++ b/ui/app/pages/send/send-content/add-recipient/ens-input.component.js @@ -0,0 +1,272 @@ +import React, { Component } from 'react' +import PropTypes from 'prop-types' +import c from 'classnames' +import { isValidENSAddress, isValidAddress, isValidAddressHead } from '../../../../helpers/utils/util' +import {ellipsify} from '../../send.utils' + +import debounce from 'debounce' +import copyToClipboard from 'copy-to-clipboard/index' +import ENS from 'ethjs-ens' +import networkMap from 'ethjs-ens/lib/network-map.json' +import log from 'loglevel' + + +// Local Constants +const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000' +const ZERO_X_ERROR_ADDRESS = '0x' + +export default class EnsInput extends Component { + static contextTypes = { + t: PropTypes.func, + } + + static propTypes = { + className: PropTypes.string, + network: PropTypes.string, + selectedAddress: PropTypes.string, + selectedName: PropTypes.string, + onChange: PropTypes.func, + updateSendTo: PropTypes.func, + updateEnsResolution: PropTypes.func, + scanQrCode: PropTypes.func, + updateEnsResolutionError: PropTypes.func, + addressBook: PropTypes.array, + onPaste: PropTypes.func, + onReset: PropTypes.func, + onValidAddressTyped: PropTypes.func, + } + + state = { + recipient: null, + input: '', + toError: null, + toWarning: null, + } + + componentDidMount () { + const network = this.props.network + const networkHasEnsSupport = getNetworkEnsSupport(network) + this.setState({ ensResolution: ZERO_ADDRESS }) + + if (networkHasEnsSupport) { + const provider = global.ethereumProvider + this.ens = new ENS({ provider, network }) + this.checkName = debounce(this.lookupEnsName, 200) + } + } + + // If an address is sent without a nickname, meaning not from ENS or from + // the user's own accounts, a default of a one-space string is used. + componentDidUpdate (prevProps) { + const { + input, + } = this.state + const { + network, + } = this.props + + if (prevProps.network !== network) { + const provider = global.ethereumProvider + this.ens = new ENS({ provider, network }) + this.onChange({ target: { value: input } }) + } + } + + resetInput = () => { + const { updateEnsResolution, updateEnsResolutionError, onReset } = this.props + this.onChange({ target: { value: '' } }) + onReset() + updateEnsResolution('') + updateEnsResolutionError('') + } + + lookupEnsName = (recipient) => { + recipient = recipient.trim() + + log.info(`ENS attempting to resolve name: ${recipient}`) + this.ens.lookup(recipient) + .then((address) => { + if (address === ZERO_ADDRESS) throw new Error(this.context.t('noAddressForName')) + if (address === ZERO_X_ERROR_ADDRESS) throw new Error(this.context.t('ensRegistrationError')) + this.props.updateEnsResolution(address) + }) + .catch((reason) => { + if (isValidENSAddress(recipient) && reason.message === 'ENS name not defined.') { + this.props.updateEnsResolutionError(this.context.t('ensNotFoundOnCurrentNetwork')) + } else { + log.error(reason) + this.props.updateEnsResolutionError(reason.message) + } + }) + } + + onPaste = event => { + event.clipboardData.items[0].getAsString(text => { + if (isValidAddress(text)) { + this.props.onPaste(text) + } + }) + } + + onChange = e => { + const { network, onChange, updateEnsResolution, updateEnsResolutionError, onValidAddressTyped } = this.props + const input = e.target.value + const networkHasEnsSupport = getNetworkEnsSupport(network) + + this.setState({ input }, () => onChange(input)) + + // Empty ENS state if input is empty + // maybe scan ENS + + if (!networkHasEnsSupport && !isValidAddress(input) && !isValidAddressHead(input)) { + updateEnsResolution('') + updateEnsResolutionError(!networkHasEnsSupport ? 'Network does not support ENS' : '') + return + } + + if (isValidENSAddress(input)) { + this.lookupEnsName(input) + } else if (onValidAddressTyped && isValidAddress(input)) { + onValidAddressTyped(input) + } else { + updateEnsResolution('') + updateEnsResolutionError('') + } + } + + render () { + const { t } = this.context + const { className, selectedAddress } = this.props + const { input } = this.state + + if (selectedAddress) { + return this.renderSelected() + } + + return ( + <div className={c('ens-input', className)}> + <div + className={c('ens-input__wrapper', { + 'ens-input__wrapper__status-icon--error': false, + 'ens-input__wrapper__status-icon--valid': false, + })} + > + <div className="ens-input__wrapper__status-icon" /> + <input + className="ens-input__wrapper__input" + type="text" + placeholder={t('recipientAddressPlaceholder')} + onChange={this.onChange} + onPaste={this.onPaste} + value={selectedAddress || input} + autoFocus + /> + <div + className={c('ens-input__wrapper__action-icon', { + 'ens-input__wrapper__action-icon--erase': input, + 'ens-input__wrapper__action-icon--qrcode': !input, + })} + onClick={() => { + if (input) { + this.resetInput() + } else { + this.props.scanQrCode() + } + }} + /> + </div> + </div> + ) + } + + renderSelected () { + const { t } = this.context + const { className, selectedAddress, selectedName, addressBook } = this.props + const contact = addressBook.filter(item => item.address === selectedAddress)[0] || {} + const name = contact.name || selectedName + + + return ( + <div className={c('ens-input', className)}> + <div + className="ens-input__wrapper ens-input__wrapper--valid" + > + <div className="ens-input__wrapper__status-icon ens-input__wrapper__status-icon--valid" /> + <div + className="ens-input__wrapper__input ens-input__wrapper__input--selected" + placeholder={t('recipientAddress')} + onChange={this.onChange} + > + <div className="ens-input__selected-input__title"> + {name || ellipsify(selectedAddress)} + </div> + { name && <div className="ens-input__selected-input__subtitle">{selectedAddress}</div> } + </div> + <div + className="ens-input__wrapper__action-icon ens-input__wrapper__action-icon--erase" + onClick={this.resetInput} + /> + </div> + </div> + ) + } + + ensIcon (recipient) { + const { hoverText } = this.state + + return ( + <span + className="#ensIcon" + title={hoverText} + style={{ + position: 'absolute', + top: '16px', + left: '-25px', + }} + > + { this.ensIconContents(recipient) } + </span> + ) + } + + ensIconContents () { + const { loadingEns, ensFailure, ensResolution, toError } = this.state || { ensResolution: ZERO_ADDRESS } + + if (toError) return + + if (loadingEns) { + return ( + <img + src="images/loading.svg" + style={{ + width: '30px', + height: '30px', + transform: 'translateY(-6px)', + }} + /> + ) + } + + if (ensFailure) { + return <i className="fa fa-warning fa-lg warning'" /> + } + + if (ensResolution && (ensResolution !== ZERO_ADDRESS)) { + return ( + <i + className="fa fa-check-circle fa-lg cursor-pointer" + style={{ color: 'green' }} + onClick={event => { + event.preventDefault() + event.stopPropagation() + copyToClipboard(ensResolution) + }} + /> + ) + } + } +} + +function getNetworkEnsSupport (network) { + return Boolean(networkMap[network]) +} diff --git a/ui/app/pages/send/send-content/add-recipient/ens-input.container.js b/ui/app/pages/send/send-content/add-recipient/ens-input.container.js new file mode 100644 index 000000000..d74f44832 --- /dev/null +++ b/ui/app/pages/send/send-content/add-recipient/ens-input.container.js @@ -0,0 +1,20 @@ +import EnsInput from './ens-input.component' +import { + getCurrentNetwork, + getSendTo, + getSendToNickname, +} from '../../send.selectors' +import { + getAddressBook, +} from '../../../../selectors/selectors' +const connect = require('react-redux').connect + + +export default connect( + state => ({ + network: getCurrentNetwork(state), + selectedAddress: getSendTo(state), + selectedName: getSendToNickname(state), + addressBook: getAddressBook(state), + }) +)(EnsInput) diff --git a/ui/app/pages/send/send-content/add-recipient/ens-input.js b/ui/app/pages/send/send-content/add-recipient/ens-input.js new file mode 100644 index 000000000..6833ccd03 --- /dev/null +++ b/ui/app/pages/send/send-content/add-recipient/ens-input.js @@ -0,0 +1 @@ +export { default } from './ens-input.container' diff --git a/ui/app/pages/send/send-content/add-recipient/index.js b/ui/app/pages/send/send-content/add-recipient/index.js new file mode 100644 index 000000000..d661bd74b --- /dev/null +++ b/ui/app/pages/send/send-content/add-recipient/index.js @@ -0,0 +1 @@ +export { default } from './add-recipient.container' diff --git a/ui/app/pages/send/send-content/add-recipient/tests/add-recipient-component.test.js b/ui/app/pages/send/send-content/add-recipient/tests/add-recipient-component.test.js new file mode 100644 index 000000000..7570e7fcb --- /dev/null +++ b/ui/app/pages/send/send-content/add-recipient/tests/add-recipient-component.test.js @@ -0,0 +1,202 @@ +import React from 'react' +import assert from 'assert' +import { shallow } from 'enzyme' +import sinon from 'sinon' +import AddRecipient from '../add-recipient.component' +import Dialog from '../../../../../components/ui/dialog' + +const propsMethodSpies = { + closeToDropdown: sinon.spy(), + openToDropdown: sinon.spy(), + updateGas: sinon.spy(), + updateSendTo: sinon.spy(), + updateSendToError: sinon.spy(), + updateSendToWarning: sinon.spy(), +} + +describe('AddRecipient Component', function () { + let wrapper + let instance + + beforeEach(() => { + wrapper = shallow(<AddRecipient + closeToDropdown={propsMethodSpies.closeToDropdown} + inError={false} + inWarning={false} + network={'mockNetwork'} + openToDropdown={propsMethodSpies.openToDropdown} + to={'mockTo'} + toAccounts={['mockAccount']} + toDropdownOpen={false} + updateGas={propsMethodSpies.updateGas} + updateSendTo={propsMethodSpies.updateSendTo} + updateSendToError={propsMethodSpies.updateSendToError} + updateSendToWarning={propsMethodSpies.updateSendToWarning} + addressBook={[{ address: '0x80F061544cC398520615B5d3e7A3BedD70cd4510', name: 'Fav 5' }]} + nonContacts={[{ address: '0x70F061544cC398520615B5d3e7A3BedD70cd4510', name: 'Fav 7' }]} + contacts={[{ address: '0x60F061544cC398520615B5d3e7A3BedD70cd4510', name: 'Fav 6' }]} + />, { context: { t: str => str + '_t' } }) + instance = wrapper.instance() + }) + + afterEach(() => { + propsMethodSpies.closeToDropdown.resetHistory() + propsMethodSpies.openToDropdown.resetHistory() + propsMethodSpies.updateSendTo.resetHistory() + propsMethodSpies.updateSendToError.resetHistory() + propsMethodSpies.updateSendToWarning.resetHistory() + propsMethodSpies.updateGas.resetHistory() + }) + + describe('selectRecipient', () => { + + it('should call updateSendTo', () => { + assert.equal(propsMethodSpies.updateSendTo.callCount, 0) + instance.selectRecipient('mockTo2', 'mockNickname') + assert.equal(propsMethodSpies.updateSendTo.callCount, 1) + assert.deepEqual( + propsMethodSpies.updateSendTo.getCall(0).args, + ['mockTo2', 'mockNickname'] + ) + }) + + it('should call updateGas if there is no to error', () => { + assert.equal(propsMethodSpies.updateGas.callCount, 0) + instance.selectRecipient(false) + assert.equal(propsMethodSpies.updateGas.callCount, 1) + }) + }) + + describe('render', () => { + it('should render a component', () => { + assert.equal(wrapper.find('.send__select-recipient-wrapper').length, 1) + }) + + it('should render no content if there are no recents, transfers, and contacts', () => { + wrapper.setProps({ + ownedAccounts: [], + addressBook: [], + }) + + assert.equal(wrapper.find('.send__select-recipient-wrapper__list__link').length, 0) + assert.equal(wrapper.find('.send__select-recipient-wrapper__group').length, 0) + }) + + it('should render transfer', () => { + wrapper.setProps({ + ownedAccounts: [{ address: '0x123', name: '123' }, { address: '0x124', name: '124' }], + addressBook: [{ address: '0x456', name: 'test-name' }], + }) + wrapper.setState({ isShowingTransfer: true }) + + const xferLink = wrapper.find('.send__select-recipient-wrapper__list__link') + assert.equal(xferLink.length, 1) + + + const groups = wrapper.find('RecipientGroup') + assert.equal(groups.shallow().find('.send__select-recipient-wrapper__group').length, 1) + }) + + it('should render ContactList', () => { + wrapper.setProps({ + ownedAccounts: [{ address: '0x123', name: '123' }, { address: '0x124', name: '124' }], + addressBook: [{ address: '0x125' }], + }) + + const contactList = wrapper.find('ContactList') + + assert.equal(contactList.length, 1) + }) + + it('should render contacts', () => { + wrapper.setProps({ + addressBook: [ + { address: '0x125', name: 'alice' }, + { address: '0x126', name: 'alex' }, + { address: '0x127', name: 'catherine' }, + ], + }) + wrapper.setState({ isShowingTransfer: false }) + + const xferLink = wrapper.find('.send__select-recipient-wrapper__list__link') + assert.equal(xferLink.length, 0) + + const groups = wrapper.find('ContactList') + assert.equal(groups.length, 1) + + assert.equal(groups.find('.send__select-recipient-wrapper__group-item').length, 0) + }) + + it('should render error when query has no results', () => { + wrapper.setProps({ + addressBook: [], + toError: 'bad', + contacts: [], + nonContacts: [], + }) + + const dialog = wrapper.find(Dialog) + + assert.equal(dialog.props().type, 'error') + assert.equal(dialog.props().children, 'bad_t') + assert.equal(dialog.length, 1) + }) + + it('should render error when query has ens does not resolve', () => { + wrapper.setProps({ + addressBook: [], + toError: 'bad', + ensResolutionError: 'very bad', + contacts: [], + nonContacts: [], + }) + + const dialog = wrapper.find(Dialog) + + assert.equal(dialog.props().type, 'error') + assert.equal(dialog.props().children, 'very bad') + assert.equal(dialog.length, 1) + }) + + it('should render warning', () => { + wrapper.setProps({ + addressBook: [], + query: 'yo', + toWarning: 'watchout', + }) + + const dialog = wrapper.find(Dialog) + + assert.equal(dialog.props().type, 'warning') + assert.equal(dialog.props().children, 'watchout_t') + assert.equal(dialog.length, 1) + }) + + it('should not render error when ens resolved', () => { + wrapper.setProps({ + addressBook: [], + toError: 'bad', + ensResolution: '0x128', + }) + + const dialog = wrapper.find(Dialog) + + assert.equal(dialog.length, 0) + }) + + it('should not render error when query has results', () => { + wrapper.setProps({ + addressBook: [ + { address: '0x125', name: 'alice' }, + { address: '0x126', name: 'alex' }, + { address: '0x127', name: 'catherine' }, + ], + toError: 'bad', + }) + + const dialog = wrapper.find(Dialog) + + assert.equal(dialog.length, 0) + }) + }) +}) diff --git a/ui/app/pages/send/send-content/add-recipient/tests/add-recipient-container.test.js b/ui/app/pages/send/send-content/add-recipient/tests/add-recipient-container.test.js new file mode 100644 index 000000000..5ca0b2c23 --- /dev/null +++ b/ui/app/pages/send/send-content/add-recipient/tests/add-recipient-container.test.js @@ -0,0 +1,72 @@ +import assert from 'assert' +import proxyquire from 'proxyquire' +import sinon from 'sinon' + +let mapStateToProps +let mapDispatchToProps + +const actionSpies = { + updateSendTo: sinon.spy(), +} + +proxyquire('../add-recipient.container.js', { + 'react-redux': { + connect: (ms, md) => { + mapStateToProps = ms + mapDispatchToProps = md + return () => ({}) + }, + }, + '../../send.selectors.js': { + getSendEnsResolution: (s) => `mockSendEnsResolution:${s}`, + getSendEnsResolutionError: (s) => `mockSendEnsResolutionError:${s}`, + accountsWithSendEtherInfoSelector: (s) => `mockAccountsWithSendEtherInfoSelector:${s}`, + }, + '../../../../selectors/selectors': { + getAddressBook: (s) => [{ name: `mockAddressBook:${s}` }], + getAddressBookEntry: (s) => `mockAddressBookEntry:${s}`, + }, + '../../../../store/actions': actionSpies, +}) + +describe('add-recipient container', () => { + + describe('mapStateToProps()', () => { + + it('should map the correct properties to props', () => { + assert.deepEqual(mapStateToProps('mockState'), { + addressBook: [{ name: 'mockAddressBook:mockState' }], + contacts: [{ name: 'mockAddressBook:mockState' }], + ensResolution: 'mockSendEnsResolution:mockState', + ensResolutionError: 'mockSendEnsResolutionError:mockState', + ownedAccounts: 'mockAccountsWithSendEtherInfoSelector:mockState', + addressBookEntryName: undefined, + nonContacts: [], + }) + }) + + }) + + describe('mapDispatchToProps()', () => { + let dispatchSpy + let mapDispatchToPropsObject + + beforeEach(() => { + dispatchSpy = sinon.spy() + mapDispatchToPropsObject = mapDispatchToProps(dispatchSpy) + }) + + describe('updateSendTo()', () => { + it('should dispatch an action', () => { + mapDispatchToPropsObject.updateSendTo('mockTo', 'mockNickname') + assert(dispatchSpy.calledOnce) + assert(actionSpies.updateSendTo.calledOnce) + assert.deepEqual( + actionSpies.updateSendTo.getCall(0).args, + ['mockTo', 'mockNickname'] + ) + }) + }) + }) + +}) diff --git a/ui/app/pages/send/send-content/send-to-row/tests/send-to-row-selectors.test.js b/ui/app/pages/send/send-content/add-recipient/tests/add-recipient-selectors.test.js index 0fa342d1e..82f481187 100644 --- a/ui/app/pages/send/send-content/send-to-row/tests/send-to-row-selectors.test.js +++ b/ui/app/pages/send/send-content/add-recipient/tests/add-recipient-selectors.test.js @@ -3,9 +3,9 @@ import { getToDropdownOpen, getTokens, sendToIsInError, -} from '../send-to-row.selectors.js' +} from '../add-recipient.selectors.js' -describe('send-to-row selectors', () => { +describe('add-recipient selectors', () => { describe('getToDropdownOpen()', () => { it('should return send.getToDropdownOpen', () => { diff --git a/ui/app/pages/send/send-content/send-to-row/tests/send-to-row-utils.test.js b/ui/app/pages/send/send-content/add-recipient/tests/add-recipient-utils.test.js index f8a6dd96f..182504c5d 100644 --- a/ui/app/pages/send/send-content/send-to-row/tests/send-to-row-utils.test.js +++ b/ui/app/pages/send/send-content/add-recipient/tests/add-recipient-utils.test.js @@ -12,7 +12,7 @@ const stubs = { isValidAddress: sinon.stub().callsFake(to => Boolean(to.match(/^[0xabcdef123456798]+$/))), } -const toRowUtils = proxyquire('../send-to-row.utils.js', { +const toRowUtils = proxyquire('../add-recipient.js', { '../../../../helpers/utils/util': { isValidAddress: stubs.isValidAddress, }, @@ -22,7 +22,7 @@ const { getToWarningObject, } = toRowUtils -describe('send-to-row utils', () => { +describe('add-recipient utils', () => { describe('getToErrorObject()', () => { it('should return a required error if to is falsy', () => { diff --git a/ui/app/pages/send/send-content/index.js b/ui/app/pages/send/send-content/index.js index 891c17e6a..542da4674 100644 --- a/ui/app/pages/send/send-content/index.js +++ b/ui/app/pages/send/send-content/index.js @@ -1 +1 @@ -export { default } from './send-content.component' +export { default } from './send-content.container' diff --git a/ui/app/pages/send/send-content/send-amount-row/amount-max-button/amount-max-button.component.js b/ui/app/pages/send/send-content/send-amount-row/amount-max-button/amount-max-button.component.js index 7901ccef6..05545669a 100644 --- a/ui/app/pages/send/send-content/send-amount-row/amount-max-button/amount-max-button.component.js +++ b/ui/app/pages/send/send-content/send-amount-row/amount-max-button/amount-max-button.component.js @@ -64,12 +64,12 @@ export default class AmountMaxButton extends Component { const { maxModeOn, buttonDataLoading, inError } = this.props return ( - <div className={'send-v2__amount-max'} onClick={buttonDataLoading || inError ? null : this.onMaxClick}> - <input type="checkbox" checked={maxModeOn} /> - <div className={classnames('send-v2__amount-max__button', { 'send-v2__amount-max__button__disabled': buttonDataLoading || inError })}> - {this.context.t('max')} - </div> - </div> - ) + <div className={'send-v2__amount-max'} onClick={buttonDataLoading || inError ? null : this.onMaxClick}> + <input type="checkbox" checked={maxModeOn} /> + <div className={classnames('send-v2__amount-max__button', { 'send-v2__amount-max__button__disabled': buttonDataLoading || inError })}> + {this.context.t('max')} + </div> + </div> + ) } } diff --git a/ui/app/pages/send/send-content/send-asset-row/send-asset-row.component.js b/ui/app/pages/send/send-content/send-asset-row/send-asset-row.component.js index de2d9462f..1dcd0bd2c 100644 --- a/ui/app/pages/send/send-content/send-asset-row/send-asset-row.component.js +++ b/ui/app/pages/send/send-content/send-asset-row/send-asset-row.component.js @@ -59,7 +59,7 @@ export default class SendAssetRow extends Component { <SendRowWrapper label={`${t('asset')}:`}> <div className="send-v2__asset-dropdown"> { this.renderSelectedToken() } - { this.renderAssetDropdown() } + { this.props.tokens.length > 0 ? this.renderAssetDropdown() : null } </div> </SendRowWrapper> ) @@ -101,7 +101,7 @@ export default class SendAssetRow extends Component { return ( <div - className="send-v2__asset-dropdown__asset" + className={ this.props.tokens.length > 0 ? 'send-v2__asset-dropdown__asset' : 'send-v2__asset-dropdown__single-asset' } onClick={() => this.selectToken()} > <div className="send-v2__asset-dropdown__asset-icon"> diff --git a/ui/app/pages/send/send-content/send-content.component.js b/ui/app/pages/send/send-content/send-content.component.js index d799806c7..aff675e7a 100644 --- a/ui/app/pages/send/send-content/send-content.component.js +++ b/ui/app/pages/send/send-content/send-content.component.js @@ -2,18 +2,25 @@ import React, { Component } from 'react' import PropTypes from 'prop-types' import PageContainerContent from '../../../components/ui/page-container/page-container-content.component' import SendAmountRow from './send-amount-row' -import SendFromRow from './send-from-row' import SendGasRow from './send-gas-row' import SendHexDataRow from './send-hex-data-row' -import SendToRow from './send-to-row' import SendAssetRow from './send-asset-row' +import Dialog from '../../../components/ui/dialog' export default class SendContent extends Component { + static contextTypes = { + t: PropTypes.func, + } + static propTypes = { updateGas: PropTypes.func, scanQrCode: PropTypes.func, + showAddToAddressBookModal: PropTypes.func, showHexData: PropTypes.bool, + to: PropTypes.string, + ownedAccounts: PropTypes.array, + addressBook: PropTypes.array, } updateGas = (updateData) => this.props.updateGas(updateData) @@ -22,22 +29,40 @@ export default class SendContent extends Component { return ( <PageContainerContent> <div className="send-v2__form"> - <SendFromRow /> - <SendToRow - updateGas={this.updateGas} - scanQrCode={ _ => this.props.scanQrCode()} - /> + { this.maybeRenderAddContact() } <SendAssetRow /> <SendAmountRow updateGas={this.updateGas} /> <SendGasRow /> - {(this.props.showHexData && ( - <SendHexDataRow - updateGas={this.updateGas} - /> - ))} + { + this.props.showHexData && ( + <SendHexDataRow + updateGas={this.updateGas} + /> + ) + } </div> </PageContainerContent> ) } + maybeRenderAddContact () { + const { t } = this.context + const { to, addressBook = [], ownedAccounts = [], showAddToAddressBookModal } = this.props + const isOwnedAccount = !!ownedAccounts.find(({ address }) => address.toLowerCase() === to.toLowerCase()) + const contact = addressBook.find(({ address }) => address === to) || {} + + if (isOwnedAccount || contact.name) { + return + } + + return ( + <Dialog + type="message" + className="send__dialog" + onClick={showAddToAddressBookModal} + > + {t('newAccountDetectedDialogMessage')} + </Dialog> + ) + } } diff --git a/ui/app/pages/send/send-content/send-content.container.js b/ui/app/pages/send/send-content/send-content.container.js new file mode 100644 index 000000000..a0732fc20 --- /dev/null +++ b/ui/app/pages/send/send-content/send-content.container.js @@ -0,0 +1,38 @@ +import { connect } from 'react-redux' +import SendContent from './send-content.component' +import { + accountsWithSendEtherInfoSelector, + getSendTo, +} from '../send.selectors' +import { + getAddressBook, +} from '../../../selectors/selectors' +import actions from '../../../store/actions' + +function mapStateToProps (state) { + return { + to: getSendTo(state), + addressBook: getAddressBook(state), + ownedAccounts: accountsWithSendEtherInfoSelector(state), + } +} + +function mapDispatchToProps (dispatch) { + return { + showAddToAddressBookModal: (recipient) => dispatch(actions.showModal({ + name: 'ADD_TO_ADDRESSBOOK', + recipient, + })), + } +} + +function mergeProps (stateProps, dispatchProps, ownProps) { + return { + ...ownProps, + ...stateProps, + ...dispatchProps, + showAddToAddressBookModal: () => dispatchProps.showAddToAddressBookModal(stateProps.to), + } +} + +export default connect(mapStateToProps, mapDispatchToProps, mergeProps)(SendContent) diff --git a/ui/app/pages/send/send-content/send-gas-row/gas-fee-display/gas-fee-display.component.js b/ui/app/pages/send/send-content/send-gas-row/gas-fee-display/gas-fee-display.component.js index 3f5587318..37af59e29 100644 --- a/ui/app/pages/send/send-content/send-gas-row/gas-fee-display/gas-fee-display.component.js +++ b/ui/app/pages/send/send-content/send-gas-row/gas-fee-display/gas-fee-display.component.js @@ -39,11 +39,11 @@ export default class GasFeeDisplay extends Component { ) : gasLoadingError ? <div className="currency-display.currency-display--message"> - {this.context.t('setGasPrice')} - </div> + {this.context.t('setGasPrice')} + </div> : <div className="currency-display"> - {this.context.t('loading')} - </div> + {this.context.t('loading')} + </div> } <button className="gas-fee-reset" diff --git a/ui/app/pages/send/send-content/send-gas-row/send-gas-row.component.js b/ui/app/pages/send/send-content/send-gas-row/send-gas-row.component.js index 4c09ed564..ed064695e 100644 --- a/ui/app/pages/send/send-content/send-gas-row/send-gas-row.component.js +++ b/ui/app/pages/send/send-content/send-gas-row/send-gas-row.component.js @@ -90,26 +90,26 @@ export default class SendGasRow extends Component { const { metricsEvent } = this.context const gasPriceButtonGroup = <div> - <GasPriceButtonGroup - className="gas-price-button-group--small" - showCheck={false} - {...gasPriceButtonGroupProps} - handleGasPriceSelection={async (...args) => { - metricsEvent({ - eventOpts: { - category: 'Transactions', - action: 'Edit Screen', - name: 'Changed Gas Button', - }, - }) - await gasPriceButtonGroupProps.handleGasPriceSelection(...args) - if (maxModeOn) { - this.setMaxAmount() - } - }} - /> - { this.renderAdvancedOptionsButton() } - </div> + <GasPriceButtonGroup + className="gas-price-button-group--small" + showCheck={false} + {...gasPriceButtonGroupProps} + handleGasPriceSelection={async (...args) => { + metricsEvent({ + eventOpts: { + category: 'Transactions', + action: 'Edit Screen', + name: 'Changed Gas Button', + }, + }) + await gasPriceButtonGroupProps.handleGasPriceSelection(...args) + if (maxModeOn) { + this.setMaxAmount() + } + }} + /> + { this.renderAdvancedOptionsButton() } + </div> const gasFeeDisplay = <GasFeeDisplay conversionRate={conversionRate} convertedCurrency={convertedCurrency} @@ -134,7 +134,7 @@ export default class SendGasRow extends Component { isSpeedUp={false} /> { this.renderAdvancedOptionsButton() } - </div> + </div> if (advancedInlineGasShown) { return advancedGasInputs diff --git a/ui/app/pages/send/send-content/send-row-wrapper/send-row-warning-message/send-row-warning-message.component.js b/ui/app/pages/send/send-content/send-row-wrapper/send-row-warning-message/send-row-warning-message.component.js index f1caa8f99..6ddddbb3d 100644 --- a/ui/app/pages/send/send-content/send-row-wrapper/send-row-warning-message/send-row-warning-message.component.js +++ b/ui/app/pages/send/send-content/send-row-wrapper/send-row-warning-message/send-row-warning-message.component.js @@ -18,7 +18,7 @@ export default class SendRowWarningMessage extends Component { const warningMessage = warningType in warnings && warnings[warningType] return ( - warningMessage + warningMessage ? <div className="send-v2__warning">{this.context.t(warningMessage)}</div> : null ) diff --git a/ui/app/pages/send/send-content/send-row-wrapper/tests/send-row-wrapper-component.test.js b/ui/app/pages/send/send-content/send-row-wrapper/tests/send-row-wrapper-component.test.js index 30280e1d0..533ca2ebe 100644 --- a/ui/app/pages/send/send-content/send-row-wrapper/tests/send-row-wrapper-component.test.js +++ b/ui/app/pages/send/send-content/send-row-wrapper/tests/send-row-wrapper-component.test.js @@ -54,25 +54,25 @@ describe('SendContent Component', function () { it('should render its second child as a child of the send-v2__form-field, if it has two children', () => { wrapper = shallow(<SendRowWrapper - errorType={'mockErrorType'} - label={'mockLabel'} - showError={false} - > - <span>Mock Custom Label Content</span> - <span>Mock Form Field</span> - </SendRowWrapper>) + errorType={'mockErrorType'} + label={'mockLabel'} + showError={false} + > + <span>Mock Custom Label Content</span> + <span>Mock Form Field</span> + </SendRowWrapper>) assert.equal(wrapper.find('.send-v2__form-row > .send-v2__form-field').childAt(0).text(), 'Mock Form Field') }) it('should render its first child as the last child of the send-v2__form-label, if it has two children', () => { wrapper = shallow(<SendRowWrapper - errorType={'mockErrorType'} - label={'mockLabel'} - showError={false} - > - <span>Mock Custom Label Content</span> - <span>Mock Form Field</span> - </SendRowWrapper>) + errorType={'mockErrorType'} + label={'mockLabel'} + showError={false} + > + <span>Mock Custom Label Content</span> + <span>Mock Form Field</span> + </SendRowWrapper>) assert.equal(wrapper.find('.send-v2__form-row > .send-v2__form-label').childAt(1).text(), 'Mock Custom Label Content') }) }) diff --git a/ui/app/pages/send/send-content/send-to-row/index.js b/ui/app/pages/send/send-content/send-to-row/index.js deleted file mode 100644 index 121f15148..000000000 --- a/ui/app/pages/send/send-content/send-to-row/index.js +++ /dev/null @@ -1 +0,0 @@ -export { default } from './send-to-row.container' diff --git a/ui/app/pages/send/send-content/send-to-row/send-to-row-README.md b/ui/app/pages/send/send-content/send-to-row/send-to-row-README.md deleted file mode 100644 index e69de29bb..000000000 --- a/ui/app/pages/send/send-content/send-to-row/send-to-row-README.md +++ /dev/null diff --git a/ui/app/pages/send/send-content/send-to-row/send-to-row.component.js b/ui/app/pages/send/send-content/send-to-row/send-to-row.component.js deleted file mode 100644 index 9baf327c1..000000000 --- a/ui/app/pages/send/send-content/send-to-row/send-to-row.component.js +++ /dev/null @@ -1,91 +0,0 @@ -import React, { Component } from 'react' -import PropTypes from 'prop-types' -import SendRowWrapper from '../send-row-wrapper' -import EnsInput from '../../../../components/app/ens-input' -import { getToErrorObject, getToWarningObject } from './send-to-row.utils.js' - -export default class SendToRow extends Component { - - static propTypes = { - closeToDropdown: PropTypes.func, - hasHexData: PropTypes.bool.isRequired, - inError: PropTypes.bool, - inWarning: PropTypes.bool, - network: PropTypes.string, - openToDropdown: PropTypes.func, - selectedToken: PropTypes.object, - to: PropTypes.string, - toAccounts: PropTypes.array, - toDropdownOpen: PropTypes.bool, - tokens: PropTypes.array, - updateGas: PropTypes.func, - updateSendTo: PropTypes.func, - updateSendToError: PropTypes.func, - updateSendToWarning: PropTypes.func, - scanQrCode: PropTypes.func, - } - - static contextTypes = { - t: PropTypes.func, - metricsEvent: PropTypes.func, - } - - handleToChange (to, nickname = '', toError, toWarning, network) { - const { hasHexData, updateSendTo, updateSendToError, updateGas, tokens, selectedToken, updateSendToWarning } = this.props - const toErrorObject = getToErrorObject(to, toError, hasHexData, tokens, selectedToken, network) - const toWarningObject = getToWarningObject(to, toWarning, tokens, selectedToken) - updateSendTo(to, nickname) - updateSendToError(toErrorObject) - updateSendToWarning(toWarningObject) - if (toErrorObject.to === null) { - updateGas({ to }) - } - } - - render () { - const { - closeToDropdown, - inError, - inWarning, - network, - openToDropdown, - to, - toAccounts, - toDropdownOpen, - } = this.props - - return ( - <SendRowWrapper - errorType={'to'} - label={`${this.context.t('to')}: `} - showError={inError} - showWarning={inWarning} - warningType={'to'} - > - <EnsInput - scanQrCode={_ => { - this.context.metricsEvent({ - eventOpts: { - category: 'Transactions', - action: 'Edit Screen', - name: 'Used QR scanner', - }, - }) - this.props.scanQrCode() - }} - accounts={toAccounts} - closeDropdown={() => closeToDropdown()} - dropdownOpen={toDropdownOpen} - inError={inError} - name={'address'} - network={network} - onChange={({ toAddress, nickname, toError, toWarning }) => this.handleToChange(toAddress, nickname, toError, toWarning, this.props.network)} - openDropdown={() => openToDropdown()} - placeholder={this.context.t('recipientAddress')} - to={to} - /> - </SendRowWrapper> - ) - } - -} diff --git a/ui/app/pages/send/send-content/send-to-row/send-to-row.container.js b/ui/app/pages/send/send-content/send-to-row/send-to-row.container.js deleted file mode 100644 index 2cbe9fcd0..000000000 --- a/ui/app/pages/send/send-content/send-to-row/send-to-row.container.js +++ /dev/null @@ -1,54 +0,0 @@ -import { connect } from 'react-redux' -import { - getCurrentNetwork, - getSelectedToken, - getSendTo, - getSendToAccounts, - getSendHexData, -} from '../../send.selectors.js' -import { - getToDropdownOpen, - getTokens, - sendToIsInError, - sendToIsInWarning, -} from './send-to-row.selectors.js' -import { - updateSendTo, -} from '../../../../store/actions' -import { - updateSendErrors, - updateSendWarnings, - openToDropdown, - closeToDropdown, -} from '../../../../ducks/send/send.duck' -import SendToRow from './send-to-row.component' - -export default connect(mapStateToProps, mapDispatchToProps)(SendToRow) - -function mapStateToProps (state) { - return { - hasHexData: Boolean(getSendHexData(state)), - inError: sendToIsInError(state), - inWarning: sendToIsInWarning(state), - network: getCurrentNetwork(state), - selectedToken: getSelectedToken(state), - to: getSendTo(state), - toAccounts: getSendToAccounts(state), - toDropdownOpen: getToDropdownOpen(state), - tokens: getTokens(state), - } -} - -function mapDispatchToProps (dispatch) { - return { - closeToDropdown: () => dispatch(closeToDropdown()), - openToDropdown: () => dispatch(openToDropdown()), - updateSendTo: (to, nickname) => dispatch(updateSendTo(to, nickname)), - updateSendToError: (toErrorObject) => { - dispatch(updateSendErrors(toErrorObject)) - }, - updateSendToWarning: (toWarningObject) => { - dispatch(updateSendWarnings(toWarningObject)) - }, - } -} diff --git a/ui/app/pages/send/send-content/send-to-row/tests/send-to-row-component.test.js b/ui/app/pages/send/send-content/send-to-row/tests/send-to-row-component.test.js deleted file mode 100644 index c180d97f1..000000000 --- a/ui/app/pages/send/send-content/send-to-row/tests/send-to-row-component.test.js +++ /dev/null @@ -1,166 +0,0 @@ -import React from 'react' -import assert from 'assert' -import { shallow } from 'enzyme' -import sinon from 'sinon' -import proxyquire from 'proxyquire' - -const SendToRow = proxyquire('../send-to-row.component.js', { - './send-to-row.utils.js': { - getToErrorObject: (to, toError) => ({ - to: to === false ? null : `mockToErrorObject:${to}${toError}`, - }), - getToWarningObject: (to, toWarning) => ({ - to: to === false ? null : `mockToWarningObject:${to}${toWarning}`, - }), - }, -}).default - -import SendRowWrapper from '../../send-row-wrapper/send-row-wrapper.component' -import EnsInput from '../../../../../components/app/ens-input' - -const propsMethodSpies = { - closeToDropdown: sinon.spy(), - openToDropdown: sinon.spy(), - updateGas: sinon.spy(), - updateSendTo: sinon.spy(), - updateSendToError: sinon.spy(), - updateSendToWarning: sinon.spy(), -} - -sinon.spy(SendToRow.prototype, 'handleToChange') - -describe('SendToRow Component', function () { - let wrapper - let instance - - beforeEach(() => { - wrapper = shallow(<SendToRow - closeToDropdown={propsMethodSpies.closeToDropdown} - inError={false} - inWarning={false} - network={'mockNetwork'} - openToDropdown={propsMethodSpies.openToDropdown} - to={'mockTo'} - toAccounts={['mockAccount']} - toDropdownOpen={false} - updateGas={propsMethodSpies.updateGas} - updateSendTo={propsMethodSpies.updateSendTo} - updateSendToError={propsMethodSpies.updateSendToError} - updateSendToWarning={propsMethodSpies.updateSendToWarning} - />, { context: { t: str => str + '_t' } }) - instance = wrapper.instance() - }) - - afterEach(() => { - propsMethodSpies.closeToDropdown.resetHistory() - propsMethodSpies.openToDropdown.resetHistory() - propsMethodSpies.updateSendTo.resetHistory() - propsMethodSpies.updateSendToError.resetHistory() - propsMethodSpies.updateSendToWarning.resetHistory() - SendToRow.prototype.handleToChange.resetHistory() - }) - - describe('handleToChange', () => { - - it('should call updateSendTo', () => { - assert.equal(propsMethodSpies.updateSendTo.callCount, 0) - instance.handleToChange('mockTo2', 'mockNickname') - assert.equal(propsMethodSpies.updateSendTo.callCount, 1) - assert.deepEqual( - propsMethodSpies.updateSendTo.getCall(0).args, - ['mockTo2', 'mockNickname'] - ) - }) - - it('should call updateSendToError', () => { - assert.equal(propsMethodSpies.updateSendToError.callCount, 0) - instance.handleToChange('mockTo2', '', 'mockToError') - assert.equal(propsMethodSpies.updateSendToError.callCount, 1) - assert.deepEqual( - propsMethodSpies.updateSendToError.getCall(0).args, - [{ to: 'mockToErrorObject:mockTo2mockToError' }] - ) - }) - - it('should call updateSendToWarning', () => { - assert.equal(propsMethodSpies.updateSendToWarning.callCount, 0) - instance.handleToChange('mockTo2', '', '', 'mockToWarning') - assert.equal(propsMethodSpies.updateSendToWarning.callCount, 1) - assert.deepEqual( - propsMethodSpies.updateSendToWarning.getCall(0).args, - [{ to: 'mockToWarningObject:mockTo2mockToWarning' }] - ) - }) - - it('should not call updateGas if there is a to error', () => { - assert.equal(propsMethodSpies.updateGas.callCount, 0) - instance.handleToChange('mockTo2') - assert.equal(propsMethodSpies.updateGas.callCount, 0) - }) - - it('should call updateGas if there is no to error', () => { - assert.equal(propsMethodSpies.updateGas.callCount, 0) - instance.handleToChange(false) - assert.equal(propsMethodSpies.updateGas.callCount, 1) - }) - }) - - describe('render', () => { - it('should render a SendRowWrapper component', () => { - assert.equal(wrapper.find(SendRowWrapper).length, 1) - }) - - it('should pass the correct props to SendRowWrapper', () => { - const { - errorType, - label, - showError, - } = wrapper.find(SendRowWrapper).props() - - assert.equal(errorType, 'to') - - assert.equal(label, 'to_t: ') - - assert.equal(showError, false) - }) - - it('should render an EnsInput as a child of the SendRowWrapper', () => { - assert(wrapper.find(SendRowWrapper).childAt(0).is(EnsInput)) - }) - - it('should render the EnsInput with the correct props', () => { - const { - accounts, - closeDropdown, - dropdownOpen, - inError, - name, - network, - onChange, - openDropdown, - placeholder, - to, - } = wrapper.find(SendRowWrapper).childAt(0).props() - assert.deepEqual(accounts, ['mockAccount']) - assert.equal(dropdownOpen, false) - assert.equal(inError, false) - assert.equal(name, 'address') - assert.equal(network, 'mockNetwork') - assert.equal(placeholder, 'recipientAddress_t') - assert.equal(to, 'mockTo') - assert.equal(propsMethodSpies.closeToDropdown.callCount, 0) - closeDropdown() - assert.equal(propsMethodSpies.closeToDropdown.callCount, 1) - assert.equal(propsMethodSpies.openToDropdown.callCount, 0) - openDropdown() - assert.equal(propsMethodSpies.openToDropdown.callCount, 1) - assert.equal(SendToRow.prototype.handleToChange.callCount, 0) - onChange({ toAddress: 'mockNewTo', nickname: 'mockNewNickname', toError: 'mockToError', toWarning: 'mockToWarning' }) - assert.equal(SendToRow.prototype.handleToChange.callCount, 1) - assert.deepEqual( - SendToRow.prototype.handleToChange.getCall(0).args, - ['mockNewTo', 'mockNewNickname', 'mockToError', 'mockToWarning', 'mockNetwork' ] - ) - }) - }) -}) diff --git a/ui/app/pages/send/send-content/send-to-row/tests/send-to-row-container.test.js b/ui/app/pages/send/send-content/send-to-row/tests/send-to-row-container.test.js deleted file mode 100644 index bb8702e9a..000000000 --- a/ui/app/pages/send/send-content/send-to-row/tests/send-to-row-container.test.js +++ /dev/null @@ -1,134 +0,0 @@ -import assert from 'assert' -import proxyquire from 'proxyquire' -import sinon from 'sinon' - -let mapStateToProps -let mapDispatchToProps - -const actionSpies = { - updateSendTo: sinon.spy(), -} -const duckActionSpies = { - closeToDropdown: sinon.spy(), - openToDropdown: sinon.spy(), - updateSendErrors: sinon.spy(), - updateSendWarnings: sinon.spy(), -} - -proxyquire('../send-to-row.container.js', { - 'react-redux': { - connect: (ms, md) => { - mapStateToProps = ms - mapDispatchToProps = md - return () => ({}) - }, - }, - '../../send.selectors.js': { - getCurrentNetwork: (s) => `mockNetwork:${s}`, - getSelectedToken: (s) => `mockSelectedToken:${s}`, - getSendHexData: (s) => s, - getSendTo: (s) => `mockTo:${s}`, - getSendToAccounts: (s) => `mockToAccounts:${s}`, - }, - './send-to-row.selectors.js': { - getToDropdownOpen: (s) => `mockToDropdownOpen:${s}`, - sendToIsInError: (s) => `mockInError:${s}`, - sendToIsInWarning: (s) => `mockInWarning:${s}`, - getTokens: (s) => `mockTokens:${s}`, - }, - '../../../../store/actions': actionSpies, - '../../../../ducks/send/send.duck': duckActionSpies, -}) - -describe('send-to-row container', () => { - - describe('mapStateToProps()', () => { - - it('should map the correct properties to props', () => { - assert.deepEqual(mapStateToProps('mockState'), { - hasHexData: true, - inError: 'mockInError:mockState', - inWarning: 'mockInWarning:mockState', - network: 'mockNetwork:mockState', - selectedToken: 'mockSelectedToken:mockState', - to: 'mockTo:mockState', - toAccounts: 'mockToAccounts:mockState', - toDropdownOpen: 'mockToDropdownOpen:mockState', - tokens: 'mockTokens:mockState', - }) - }) - - }) - - describe('mapDispatchToProps()', () => { - let dispatchSpy - let mapDispatchToPropsObject - - beforeEach(() => { - dispatchSpy = sinon.spy() - mapDispatchToPropsObject = mapDispatchToProps(dispatchSpy) - }) - - describe('closeToDropdown()', () => { - it('should dispatch an action', () => { - mapDispatchToPropsObject.closeToDropdown() - assert(dispatchSpy.calledOnce) - assert(duckActionSpies.closeToDropdown.calledOnce) - assert.equal( - duckActionSpies.closeToDropdown.getCall(0).args[0], - undefined - ) - }) - }) - - describe('openToDropdown()', () => { - it('should dispatch an action', () => { - mapDispatchToPropsObject.openToDropdown() - assert(dispatchSpy.calledOnce) - assert(duckActionSpies.openToDropdown.calledOnce) - assert.equal( - duckActionSpies.openToDropdown.getCall(0).args[0], - undefined - ) - }) - }) - - describe('updateSendTo()', () => { - it('should dispatch an action', () => { - mapDispatchToPropsObject.updateSendTo('mockTo', 'mockNickname') - assert(dispatchSpy.calledOnce) - assert(actionSpies.updateSendTo.calledOnce) - assert.deepEqual( - actionSpies.updateSendTo.getCall(0).args, - ['mockTo', 'mockNickname'] - ) - }) - }) - - describe('updateSendToError()', () => { - it('should dispatch an action', () => { - mapDispatchToPropsObject.updateSendToError('mockToErrorObject') - assert(dispatchSpy.calledOnce) - assert(duckActionSpies.updateSendErrors.calledOnce) - assert.equal( - duckActionSpies.updateSendErrors.getCall(0).args[0], - 'mockToErrorObject' - ) - }) - }) - - describe('updateSendToWarning()', () => { - it('should dispatch an action', () => { - mapDispatchToPropsObject.updateSendToWarning('mockToWarningObject') - assert(dispatchSpy.calledOnce) - assert(duckActionSpies.updateSendWarnings.calledOnce) - assert.equal( - duckActionSpies.updateSendWarnings.getCall(0).args[0], - 'mockToWarningObject' - ) - }) - }) - - }) - -}) diff --git a/ui/app/pages/send/send-content/tests/send-content-component.test.js b/ui/app/pages/send/send-content/tests/send-content-component.test.js index 521c6523e..451d2ea53 100644 --- a/ui/app/pages/send/send-content/tests/send-content-component.test.js +++ b/ui/app/pages/send/send-content/tests/send-content-component.test.js @@ -5,17 +5,21 @@ import SendContent from '../send-content.component.js' import PageContainerContent from '../../../../components/ui/page-container/page-container-content.component' import SendAmountRow from '../send-amount-row/send-amount-row.container' -import SendFromRow from '../send-from-row/send-from-row.container' import SendGasRow from '../send-gas-row/send-gas-row.container' -import SendToRow from '../send-to-row/send-to-row.container' import SendHexDataRow from '../send-hex-data-row/send-hex-data-row.container' import SendAssetRow from '../send-asset-row/send-asset-row.container' +import Dialog from '../../../../components/ui/dialog' describe('SendContent Component', function () { let wrapper beforeEach(() => { - wrapper = shallow(<SendContent showHexData={true} />) + wrapper = shallow( + <SendContent + showHexData={true} + />, + { context: { t: str => str + '_t' } } + ) }) describe('render', () => { @@ -31,23 +35,55 @@ describe('SendContent Component', function () { it('should render the correct row components as grandchildren of the PageContainerContent component', () => { const PageContainerContentChild = wrapper.find(PageContainerContent).children() - assert(PageContainerContentChild.childAt(0).is(SendFromRow)) - assert(PageContainerContentChild.childAt(1).is(SendToRow)) - assert(PageContainerContentChild.childAt(2).is(SendAssetRow)) - assert(PageContainerContentChild.childAt(3).is(SendAmountRow)) - assert(PageContainerContentChild.childAt(4).is(SendGasRow)) - assert(PageContainerContentChild.childAt(5).is(SendHexDataRow)) + assert(PageContainerContentChild.childAt(0).is(Dialog), 'row[0] should be Dialog') + assert(PageContainerContentChild.childAt(1).is(SendAssetRow), 'row[1] should be SendAssetRow') + assert(PageContainerContentChild.childAt(2).is(SendAmountRow), 'row[2] should be SendAmountRow') + assert(PageContainerContentChild.childAt(3).is(SendGasRow), 'row[3] should be SendGasRow') + assert(PageContainerContentChild.childAt(4).is(SendHexDataRow), 'row[4] should be SendHexDataRow') }) it('should not render the SendHexDataRow if props.showHexData is false', () => { wrapper.setProps({ showHexData: false }) const PageContainerContentChild = wrapper.find(PageContainerContent).children() - assert(PageContainerContentChild.childAt(0).is(SendFromRow)) - assert(PageContainerContentChild.childAt(1).is(SendToRow)) - assert(PageContainerContentChild.childAt(2).is(SendAssetRow)) - assert(PageContainerContentChild.childAt(3).is(SendAmountRow)) - assert(PageContainerContentChild.childAt(4).is(SendGasRow)) - assert.equal(PageContainerContentChild.childAt(5).exists(), false) + assert(PageContainerContentChild.childAt(0).is(Dialog), 'row[0] should be Dialog') + assert(PageContainerContentChild.childAt(1).is(SendAssetRow), 'row[1] should be SendAssetRow') + assert(PageContainerContentChild.childAt(2).is(SendAmountRow), 'row[2] should be SendAmountRow') + assert(PageContainerContentChild.childAt(3).is(SendGasRow), 'row[3] should be SendGasRow') + assert.equal(PageContainerContentChild.childAt(4).exists(), false) }) + + it('should not render the Dialog if addressBook contains "to" address', () => { + wrapper.setProps({ + showHexData: false, + to: '0x80F061544cC398520615B5d3e7A3BedD70cd4510', + addressBook: [{ address: '0x80F061544cC398520615B5d3e7A3BedD70cd4510', name: 'dinodan' }], + }) + const PageContainerContentChild = wrapper.find(PageContainerContent).children() + assert(PageContainerContentChild.childAt(0).is(SendAssetRow), 'row[1] should be SendAssetRow') + assert(PageContainerContentChild.childAt(1).is(SendAmountRow), 'row[2] should be SendAmountRow') + assert(PageContainerContentChild.childAt(2).is(SendGasRow), 'row[3] should be SendGasRow') + assert.equal(PageContainerContentChild.childAt(3).exists(), false) + }) + + it('should not render the Dialog if ownedAccounts contains "to" address', () => { + wrapper.setProps({ + showHexData: false, + to: '0x80F061544cC398520615B5d3e7A3BedD70cd4510', + addressBook: [], + ownedAccounts: [{ address: '0x80F061544cC398520615B5d3e7A3BedD70cd4510', name: 'dinodan' }], + }) + const PageContainerContentChild = wrapper.find(PageContainerContent).children() + assert(PageContainerContentChild.childAt(0).is(SendAssetRow), 'row[1] should be SendAssetRow') + assert(PageContainerContentChild.childAt(1).is(SendAmountRow), 'row[2] should be SendAmountRow') + assert(PageContainerContentChild.childAt(2).is(SendGasRow), 'row[3] should be SendGasRow') + assert.equal(PageContainerContentChild.childAt(3).exists(), false) + }) + }) + + it('should not render the asset dropdown if token length is 0 ', () => { + wrapper.setProps({ tokens: [] }) + const PageContainerContentChild = wrapper.find(PageContainerContent).children() + assert(PageContainerContentChild.childAt(1).is(SendAssetRow)) + assert(PageContainerContentChild.childAt(1).find('send-v2__asset-dropdown__single-asset'), true) }) }) diff --git a/ui/app/pages/send/send-footer/send-footer.utils.js b/ui/app/pages/send/send-footer/send-footer.utils.js index 91ac29014..ce65535a6 100644 --- a/ui/app/pages/send/send-footer/send-footer.utils.js +++ b/ui/app/pages/send/send-footer/send-footer.utils.js @@ -76,7 +76,7 @@ function constructUpdatedTx ({ function addressIsNew (toAccounts, newAddress) { const newAddressNormalized = newAddress.toLowerCase() - const foundMatching = toAccounts.some(({ address }) => address === newAddressNormalized) + const foundMatching = toAccounts.some(({ address }) => address.toLowerCase() === newAddressNormalized) return !foundMatching } diff --git a/ui/app/pages/send/send-header/send-header.component.js b/ui/app/pages/send/send-header/send-header.component.js index 76e35494a..5bc76fcd3 100644 --- a/ui/app/pages/send/send-header/send-header.component.js +++ b/ui/app/pages/send/send-header/send-header.component.js @@ -24,8 +24,10 @@ export default class SendHeader extends Component { render () { return ( <PageContainerHeader + className="send__header" onClose={() => this.onClose()} title={this.context.t(this.props.titleKey)} + headerCloseText={this.context.t('cancel')} /> ) } diff --git a/ui/app/pages/send/send-header/send-header.selectors.js b/ui/app/pages/send/send-header/send-header.selectors.js index d7c9d3766..01b90409b 100644 --- a/ui/app/pages/send/send-header/send-header.selectors.js +++ b/ui/app/pages/send/send-header/send-header.selectors.js @@ -1,6 +1,7 @@ const { getSelectedToken, getSendEditingTransactionId, + getSendTo, } = require('../send.selectors.js') const selectors = { @@ -14,6 +15,10 @@ function getTitleKey (state) { const isEditing = Boolean(getSendEditingTransactionId(state)) const isToken = Boolean(getSelectedToken(state)) + if (!getSendTo(state)) { + return 'addRecipient' + } + if (isEditing) { return 'edit' } else if (isToken) { @@ -24,14 +29,14 @@ function getTitleKey (state) { } function getSubtitleParams (state) { - const isEditing = Boolean(getSendEditingTransactionId(state)) - const token = getSelectedToken(state) + const isEditing = Boolean(getSendEditingTransactionId(state)) + const token = getSelectedToken(state) - if (isEditing) { - return [ 'editingTransaction' ] - } else if (token) { - return [ 'onlySendTokensToAccountAddress', [ token.symbol ] ] - } else { - return [ 'onlySendToEtherAddress' ] - } + if (isEditing) { + return [ 'editingTransaction' ] + } else if (token) { + return [ 'onlySendTokensToAccountAddress', [ token.symbol ] ] + } else { + return [ 'onlySendToEtherAddress' ] + } } diff --git a/ui/app/pages/send/send-header/tests/send-header-selectors.test.js b/ui/app/pages/send/send-header/tests/send-header-selectors.test.js index e0c6a3ab3..d22845f84 100644 --- a/ui/app/pages/send/send-header/tests/send-header-selectors.test.js +++ b/ui/app/pages/send/send-header/tests/send-header-selectors.test.js @@ -8,39 +8,44 @@ const { '../send.selectors': { getSelectedToken: (mockState) => mockState.t, getSendEditingTransactionId: (mockState) => mockState.e, + getSendTo: (mockState) => mockState.to, }, }) describe('send-header selectors', () => { describe('getTitleKey()', () => { + it('should return the correct key when "to" is empty', () => { + assert.equal(getTitleKey({ e: 1, t: true, to: '' }), 'addRecipient') + }) + it('should return the correct key when getSendEditingTransactionId is truthy', () => { - assert.equal(getTitleKey({ e: 1, t: true }), 'edit') + assert.equal(getTitleKey({ e: 1, t: true, to: '0x123' }), 'edit') }) it('should return the correct key when getSendEditingTransactionId is falsy and getSelectedToken is truthy', () => { - assert.equal(getTitleKey({ e: null, t: 'abc' }), 'sendTokens') + assert.equal(getTitleKey({ e: null, t: 'abc', to: '0x123' }), 'sendTokens') }) it('should return the correct key when getSendEditingTransactionId is falsy and getSelectedToken is falsy', () => { - assert.equal(getTitleKey({ e: null }), 'sendETH') + assert.equal(getTitleKey({ e: null, to: '0x123' }), 'sendETH') }) }) describe('getSubtitleParams()', () => { it('should return the correct params when getSendEditingTransactionId is truthy', () => { - assert.deepEqual(getSubtitleParams({ e: 1, t: true }), [ 'editingTransaction' ]) + assert.deepEqual(getSubtitleParams({ e: 1, t: true, to: '0x123' }), [ 'editingTransaction' ]) }) it('should return the correct params when getSendEditingTransactionId is falsy and getSelectedToken is truthy', () => { assert.deepEqual( - getSubtitleParams({ e: null, t: { symbol: 'ABC' } }), + getSubtitleParams({ e: null, t: { symbol: 'ABC' }, to: '0x123' }), [ 'onlySendTokensToAccountAddress', [ 'ABC' ] ] ) }) it('should return the correct params when getSendEditingTransactionId is falsy and getSelectedToken is falsy', () => { - assert.deepEqual(getSubtitleParams({ e: null }), [ 'onlySendToEtherAddress' ]) + assert.deepEqual(getSubtitleParams({ e: null, to: '0x123' }), [ 'onlySendToEtherAddress' ]) }) }) diff --git a/ui/app/pages/send/send.component.js b/ui/app/pages/send/send.component.js index 5f0c9c9f2..cb07dcb59 100644 --- a/ui/app/pages/send/send.component.js +++ b/ui/app/pages/send/send.component.js @@ -7,10 +7,14 @@ import { getToAddressForGasUpdate, doesAmountErrorRequireUpdate, } from './send.utils' - +import debounce from 'lodash.debounce' +import { getToWarningObject, getToErrorObject } from './send-content/add-recipient/add-recipient' import SendHeader from './send-header' +import AddRecipient from './send-content/add-recipient' import SendContent from './send-content' import SendFooter from './send-footer' +import EnsInput from './send-content/add-recipient/ens-input' + export default class SendTransactionScreen extends PersistentForm { @@ -27,12 +31,14 @@ export default class SendTransactionScreen extends PersistentForm { gasLimit: PropTypes.string, gasPrice: PropTypes.string, gasTotal: PropTypes.string, + to: PropTypes.string, history: PropTypes.object, network: PropTypes.string, primaryCurrency: PropTypes.string, recentBlocks: PropTypes.array, selectedAddress: PropTypes.string, selectedToken: PropTypes.object, + tokens: PropTypes.array, tokenBalance: PropTypes.string, tokenContract: PropTypes.object, fetchBasicGasEstimates: PropTypes.func, @@ -42,10 +48,24 @@ export default class SendTransactionScreen extends PersistentForm { scanQrCode: PropTypes.func, qrCodeDetected: PropTypes.func, qrCodeData: PropTypes.object, + ensResolution: PropTypes.string, + ensResolutionError: PropTypes.string, } static contextTypes = { t: PropTypes.func, + metricsEvent: PropTypes.func, + } + + state = { + query: '', + toError: null, + toWarning: null, + } + + constructor (props) { + super(props) + this.dValidate = debounce(this.validate, 1000) } componentWillReceiveProps (nextProps) { @@ -63,34 +83,6 @@ export default class SendTransactionScreen extends PersistentForm { } } - updateGas ({ to: updatedToAddress, amount: value, data } = {}) { - const { - amount, - blockGasLimit, - editingTransactionId, - gasLimit, - gasPrice, - recentBlocks, - selectedAddress, - selectedToken = {}, - to: currentToAddress, - updateAndSetGasLimit, - } = this.props - - updateAndSetGasLimit({ - blockGasLimit, - editingTransactionId, - gasLimit, - gasPrice, - recentBlocks, - selectedAddress, - selectedToken, - to: getToAddressForGasUpdate(updatedToAddress, currentToAddress), - value: value || amount, - data, - }) - } - componentDidUpdate (prevProps) { const { amount, @@ -105,6 +97,10 @@ export default class SendTransactionScreen extends PersistentForm { updateSendErrors, updateSendTokenBalance, tokenContract, + to, + toNickname, + addressBook, + updateToNicknameIfNecessary, } = this.props const { @@ -159,6 +155,7 @@ export default class SendTransactionScreen extends PersistentForm { tokenContract, address, }) + updateToNicknameIfNecessary(to, toNickname, addressBook) this.updateGas() } } @@ -173,9 +170,9 @@ export default class SendTransactionScreen extends PersistentForm { componentDidMount () { this.props.fetchBasicGasEstimates() - .then(() => { - this.updateGas() - }) + .then(() => { + this.updateGas() + }) } componentWillMount () { @@ -196,6 +193,39 @@ export default class SendTransactionScreen extends PersistentForm { this.props.resetSendState() } + onRecipientInputChange = query => { + if (query) { + this.dValidate(query) + } else { + this.validate(query) + } + + this.setState({ + query, + }) + } + + validate (query) { + const { + hasHexData, + tokens, + selectedToken, + network, + } = this.props + + if (!query) { + return this.setState({ toError: '', toWarning: '' }) + } + + const toErrorObject = getToErrorObject(query, null, hasHexData, tokens, selectedToken, network) + const toWarningObject = getToWarningObject(query, null, tokens, selectedToken) + + this.setState({ + toError: toErrorObject.to, + toWarning: toWarningObject.to, + }) + } + updateSendToken () { const { from: { address }, @@ -211,20 +241,104 @@ export default class SendTransactionScreen extends PersistentForm { }) } + updateGas ({ to: updatedToAddress, amount: value, data } = {}) { + const { + amount, + blockGasLimit, + editingTransactionId, + gasLimit, + gasPrice, + recentBlocks, + selectedAddress, + selectedToken = {}, + to: currentToAddress, + updateAndSetGasLimit, + } = this.props + + updateAndSetGasLimit({ + blockGasLimit, + editingTransactionId, + gasLimit, + gasPrice, + recentBlocks, + selectedAddress, + selectedToken, + to: getToAddressForGasUpdate(updatedToAddress, currentToAddress), + value: value || amount, + data, + }) + } + render () { - const { history, showHexData } = this.props + const { history, to } = this.props + let content + + if (to) { + content = this.renderSendContent() + } else { + content = this.renderAddRecipient() + } return ( <div className="page-container"> - <SendHeader history={history}/> - <SendContent - updateGas={(updateData) => this.updateGas(updateData)} - scanQrCode={_ => this.props.scanQrCode()} - showHexData={showHexData} - /> - <SendFooter history={history}/> + <SendHeader history={history} /> + { this.renderInput() } + { content } </div> ) } + renderInput () { + return ( + <EnsInput + className="send__to-row" + scanQrCode={_ => { + this.context.metricsEvent({ + eventOpts: { + category: 'Transactions', + action: 'Edit Screen', + name: 'Used QR scanner', + }, + }) + this.props.scanQrCode() + }} + onChange={this.onRecipientInputChange} + onValidAddressTyped={(address) => this.props.updateSendTo(address, '')} + onPaste={text => this.props.updateSendTo(text)} + onReset={() => this.props.updateSendTo('', '')} + updateEnsResolution={this.props.updateSendEnsResolution} + updateEnsResolutionError={this.props.updateSendEnsResolutionError} + /> + ) + } + + renderAddRecipient () { + const { scanQrCode } = this.props + const { toError, toWarning } = this.state + + return ( + <AddRecipient + updateGas={({ to, amount, data } = {}) => this.updateGas({ to, amount, data })} + scanQrCode={scanQrCode} + query={this.state.query} + toError={toError} + toWarning={toWarning} + /> + ) + } + + renderSendContent () { + const { history, showHexData, scanQrCode } = this.props + + return [ + <SendContent + key="send-content" + updateGas={({ to, amount, data } = {}) => this.updateGas({ to, amount, data })} + scanQrCode={scanQrCode} + showHexData={showHexData} + />, + <SendFooter key="send-footer" history={history} />, + ] + } + } diff --git a/ui/app/pages/send/send.container.js b/ui/app/pages/send/send.container.js index 69adbb765..0863c60d4 100644 --- a/ui/app/pages/send/send.container.js +++ b/ui/app/pages/send/send.container.js @@ -24,16 +24,25 @@ import { getSendHexDataFeatureFlagState, getSendFromObject, getSendTo, + getSendToNickname, getTokenBalance, getQrCodeData, + getSendEnsResolution, + getSendEnsResolutionError, } from './send.selectors' import { + getAddressBook, +} from '../../selectors/selectors' +import { getTokens } from './send-content/add-recipient/add-recipient.selectors' +import { updateSendTo, updateSendTokenBalance, updateGasData, setGasTotal, showQrScanner, qrCodeDetected, + updateSendEnsResolution, + updateSendEnsResolutionError, } from '../../store/actions' import { resetSendState, @@ -45,6 +54,9 @@ import { import { calcGasTotal, } from './send.utils.js' +import { + isValidENSAddress, +} from '../../helpers/utils/util' import { SEND_ROUTE, @@ -72,11 +84,16 @@ function mapStateToProps (state) { selectedAddress: getSelectedAddress(state), selectedToken: getSelectedToken(state), showHexData: getSendHexDataFeatureFlagState(state), + ensResolution: getSendEnsResolution(state), + ensResolutionError: getSendEnsResolutionError(state), to: getSendTo(state), + toNickname: getSendToNickname(state), + tokens: getTokens(state), tokenBalance: getTokenBalance(state), tokenContract: getSelectedTokenContract(state), tokenToFiatRate: getSelectedTokenToFiatRate(state), qrCodeData: getQrCodeData(state), + addressBook: getAddressBook(state), } } @@ -111,5 +128,15 @@ function mapDispatchToProps (dispatch) { qrCodeDetected: (data) => dispatch(qrCodeDetected(data)), updateSendTo: (to, nickname) => dispatch(updateSendTo(to, nickname)), fetchBasicGasEstimates: () => dispatch(fetchBasicGasEstimates()), + updateSendEnsResolution: (ensResolution) => dispatch(updateSendEnsResolution(ensResolution)), + updateSendEnsResolutionError: (message) => dispatch(updateSendEnsResolutionError(message)), + updateToNicknameIfNecessary: (to, toNickname, addressBook) => { + if (isValidENSAddress(toNickname)) { + const addressBookEntry = addressBook.find(({ address}) => to === address) || {} + if (!addressBookEntry.name !== toNickname) { + dispatch(updateSendTo(to, addressBookEntry.name || '')) + } + } + }, } } diff --git a/ui/app/pages/send/send.scss b/ui/app/pages/send/send.scss index e69de29bb..9b95f1b39 100644 --- a/ui/app/pages/send/send.scss +++ b/ui/app/pages/send/send.scss @@ -0,0 +1,233 @@ +.send { + &__header { + position: relative; + background-color: $Grey-000; + border-bottom: none; + padding: 14px 0 3px 0; + + .page-container__title { + @extend %h4; + text-align: center; + } + + .page-container__header-close-text { + @extend %link; + font-size: 1rem; + line-height: 1.1875rem; + position: absolute; + right: 1rem; + } + } + + &__dialog { + margin: 1rem; + cursor: pointer; + } + + &__error-dialog { + margin: 1rem; + } + + &__to-row { + margin: 0; + padding: .5rem; + flex: 0 0 auto; + background-color: $Grey-000; + border-bottom: 1px solid $alto; + } + + &__select-recipient-wrapper { + @extend %col-nowrap; + flex: 1 1 auto; + height: 0; + + &__list { + overflow-y: auto; + + &__link { + @extend %link; + @extend %row-nowrap; + padding: 1rem; + font-size: 1rem; + border-bottom: 1px solid $alto; + align-items: center; + } + + &__back-caret { + @extend %bg-contain; + display: block; + background-image: url('/images/caret-left.svg'); + width: 18px; + height: 18px; + margin-right: .5rem; + } + } + + &__recent-group-wrapper { + @extend %col-nowrap; + + &__load-more { + @extend %link; + font-size: .75rem; + line-height: 1.0625rem; + padding: .5rem; + text-align: center; + border-bottom: 1px solid $alto; + } + } + + &__group { + @extend %col-nowrap; + } + + &__group-label { + @extend %h8; + background-color: $Grey-000; + color: $Grey-600; + line-height: .875rem; + padding: .5rem 1rem; + border-bottom: 1px solid $alto; + + &:first-of-type { + border-top: 1px solid $alto; + } + } + + &__group-item, &__group-item--selected { + @extend %row-nowrap; + padding: .75rem 1rem; + align-items: center; + border-bottom: 1px solid $alto; + cursor: pointer; + + &:hover { + background-color: rgba($alto, 0.2); + } + + .identicon { + margin-right: 1rem; + flex: 0 0 auto; + } + + &__content { + @extend %col-nowrap; + flex: 1 1 auto; + width: 0; + } + + &__title { + font-size: .875rem; + line-height: 1.25rem; + color: $black; + } + + &__subtitle { + @extend %h8; + color: $Grey-500; + } + } + + &__group-item--selected { + border: 2px solid #2b7cd6; + border-radius: 8px; + } + } +} + +.ens-input { + @extend %row-nowrap; + + &__wrapper { + @extend %row-nowrap; + flex: 1 1 auto; + width: 0; + align-items: center; + background: $white; + border-radius: .5rem; + padding: .75rem .5rem; + border: 1px solid $Grey-100; + transition: border-color 150ms ease-in-out; + + &:focus-within { + border-color: $Grey-500; + } + + &__status-icon { + @extend %bg-contain; + background-image: url("/images/search-black.svg"); + width: 1.125rem; + height: 1.125rem; + margin: .25rem .5rem .25rem .25rem; + + &--error { + + } + + &--valid { + background-image: url("/images/check-green-solid.svg"); + } + } + + &__input { + @extend %h6; + flex: 1 1 auto; + width: 0; + border: 0; + outline: none; + + &::placeholder { + color: $Grey-200; + } + } + + &__action-icon { + @extend %bg-contain; + cursor: pointer; + + &--erase { + background-image: url("/images/close-gray.svg"); + width: .75rem; + height: .75rem; + margin: 0 .25rem; + } + + &--qrcode { + background-image: url("/images/qr-blue.svg"); + width: 1.5rem; + height: 1.5rem; + margin: 0 .25rem; + } + } + + &--valid { + border-color: $Blue-500; + + .ens-input__wrapper { + &__status-icon { + background-image: url("/images/check-green-solid.svg"); + } + + &__input { + @extend %col-nowrap; + font-size: .75rem; + line-height: .75rem; + font-weight: 400; + color: $Blue-500; + } + } + } + } + + &__selected-input { + &__title { + @extend %ellipsify; + font-size: .875rem; + } + + &__subtitle { + font-size: 0.75rem; + color: $Grey-500; + margin-top: .25rem; + } + } +} diff --git a/ui/app/pages/send/send.selectors.js b/ui/app/pages/send/send.selectors.js index d4035df28..ed2917020 100644 --- a/ui/app/pages/send/send.selectors.js +++ b/ui/app/pages/send/send.selectors.js @@ -6,6 +6,7 @@ const { const { getMetaMaskAccounts, getSelectedAddress, + getAddressBook, } = require('../../selectors/selectors') const { estimateGasPriceFromRecentBlocks, @@ -17,7 +18,6 @@ import { const selectors = { accountsWithSendEtherInfoSelector, - getAddressBook, getAmountConversionRate, getBlockGasLimit, getConversionRate, @@ -43,6 +43,8 @@ const selectors = { getSendHexData, getSendHexDataFeatureFlagState, getSendEditingTransactionId, + getSendEnsResolution, + getSendEnsResolutionError, getSendErrors, getSendFrom, getSendFromBalance, @@ -50,6 +52,7 @@ const selectors = { getSendMaxModeState, getSendTo, getSendToAccounts, + getSendToNickname, getSendWarnings, getTokenBalance, getTokenExchangeRate, @@ -63,7 +66,6 @@ module.exports = selectors function accountsWithSendEtherInfoSelector (state) { const accounts = getMetaMaskAccounts(state) const { identities } = state.metamask - const accountsWithSendEtherInfo = Object.entries(accounts).map(([key, account]) => { return Object.assign({}, account, identities[key]) }) @@ -71,10 +73,6 @@ function accountsWithSendEtherInfoSelector (state) { return accountsWithSendEtherInfo } -function getAddressBook (state) { - return state.metamask.addressBook -} - function getAmountConversionRate (state) { return getSelectedToken(state) ? getSelectedTokenToFiatRate(state) @@ -237,6 +235,10 @@ function getSendTo (state) { return state.metamask.send.to } +function getSendToNickname (state) { + return state.metamask.send.toNickname +} + function getSendToAccounts (state) { const fromAccounts = accountsWithSendEtherInfoSelector(state) const addressBookAccounts = getAddressBook(state) @@ -251,6 +253,14 @@ function getTokenBalance (state) { return state.metamask.send.tokenBalance } +function getSendEnsResolution (state) { + return state.metamask.send.ensResolution +} + +function getSendEnsResolutionError (state) { + return state.metamask.send.ensResolutionError +} + function getTokenExchangeRate (state, tokenSymbol) { const pair = `${tokenSymbol.toLowerCase()}_eth` const tokenExchangeRates = state.metamask.tokenExchangeRates diff --git a/ui/app/pages/send/send.utils.js b/ui/app/pages/send/send.utils.js index 4acc174f9..1f9bc202a 100644 --- a/ui/app/pages/send/send.utils.js +++ b/ui/app/pages/send/send.utils.js @@ -35,6 +35,7 @@ module.exports = { isBalanceSufficient, isTokenBalanceSufficient, removeLeadingZeroes, + ellipsify, } function calcGasTotal (gasLimit = '0', gasPrice = '0') { @@ -318,7 +319,7 @@ function estimateGasPriceFromRecentBlocks (recentBlocks) { return parseInt(next, 16) < parseInt(currentLowest, 16) ? next : currentLowest }) }) - .sort((a, b) => parseInt(a, 16) > parseInt(b, 16) ? 1 : -1) + .sort((a, b) => parseInt(a, 16) > parseInt(b, 16) ? 1 : -1) return lowestPrices[Math.floor(lowestPrices.length / 2)] } @@ -330,3 +331,7 @@ function getToAddressForGasUpdate (...addresses) { function removeLeadingZeroes (str) { return str.replace(/^0*(?=\d)/, '') } + +function ellipsify (text, first = 6, last = 4) { + return `${text.slice(0, first)}...${text.slice(-last)}` +} diff --git a/ui/app/pages/send/tests/send-component.test.js b/ui/app/pages/send/tests/send-component.test.js index 81955cc1d..5b7cafed5 100644 --- a/ui/app/pages/send/tests/send-component.test.js +++ b/ui/app/pages/send/tests/send-component.test.js @@ -5,8 +5,9 @@ import { shallow } from 'enzyme' import sinon from 'sinon' import timeout from '../../../../lib/test-timeout' +import AddRecipient from '../send-content/add-recipient/add-recipient.container' import SendHeader from '../send-header/send-header.container' -import SendContent from '../send-content/send-content.component' +import SendContent from '../send-content/send-content.container' import SendFooter from '../send-footer/send-footer.container' const mockBasicGasEstimates = { @@ -20,6 +21,7 @@ const propsMethodSpies = { resetSendState: sinon.spy(), fetchBasicGasEstimates: sinon.stub().returns(Promise.resolve(mockBasicGasEstimates)), fetchGasEstimates: sinon.spy(), + updateToNicknameIfNecessary: sinon.spy(), } const utilsMethodStubs = { getAmountErrorObject: sinon.stub().returns({ amount: 'mockAmountError' }), @@ -63,6 +65,7 @@ describe('Send Component', function () { updateSendErrors={propsMethodSpies.updateSendErrors} updateSendTokenBalance={propsMethodSpies.updateSendTokenBalance} resetSendState={propsMethodSpies.resetSendState} + updateToNicknameIfNecessary={propsMethodSpies.updateToNicknameIfNecessary} />) }) @@ -332,13 +335,18 @@ describe('Send Component', function () { assert.equal(wrapper.find('.page-container').length, 1) }) - it('should render SendHeader, SendContent and SendFooter', () => { + it('should render SendHeader and AddRecipient', () => { assert.equal(wrapper.find(SendHeader).length, 1) - assert.equal(wrapper.find(SendContent).length, 1) - assert.equal(wrapper.find(SendFooter).length, 1) + assert.equal(wrapper.find(AddRecipient).length, 1) }) it('should pass the history prop to SendHeader and SendFooter', () => { + wrapper.setProps({ + to: '0x80F061544cC398520615B5d3e7A3BedD70cd4510', + }) + assert.equal(wrapper.find(SendHeader).length, 1) + assert.equal(wrapper.find(SendContent).length, 1) + assert.equal(wrapper.find(SendFooter).length, 1) assert.deepEqual( wrapper.find(SendFooter).props(), { @@ -348,7 +356,93 @@ describe('Send Component', function () { }) it('should pass showHexData to SendContent', () => { + wrapper.setProps({ + to: '0x80F061544cC398520615B5d3e7A3BedD70cd4510', + }) assert.equal(wrapper.find(SendContent).props().showHexData, true) }) }) + + describe('validate when input change', () => { + let clock + + beforeEach(() => { + clock = sinon.useFakeTimers() + }) + + afterEach(() => { + clock.restore() + }) + + it('should validate when input changes', () => { + const instance = wrapper.instance() + instance.onRecipientInputChange('0x80F061544cC398520615B5d3e7A3BedD70cd4510') + + assert.deepEqual(instance.state, { + query: '0x80F061544cC398520615B5d3e7A3BedD70cd4510', + toError: null, + toWarning: null, + }) + }) + + it('should validate when input changes and has error', () => { + const instance = wrapper.instance() + instance.onRecipientInputChange('0x80F061544cC398520615B5d3e7a3BedD70cd4510') + + clock.tick(1001) + assert.deepEqual(instance.state, { + query: '0x80F061544cC398520615B5d3e7a3BedD70cd4510', + toError: 'invalidAddressRecipient', + toWarning: null, + }) + }) + + it('should validate when input changes and has error', () => { + wrapper.setProps({ network: 'bad' }) + const instance = wrapper.instance() + instance.onRecipientInputChange('0x80F061544cC398520615B5d3e7a3BedD70cd4510') + + clock.tick(1001) + assert.deepEqual(instance.state, { + query: '0x80F061544cC398520615B5d3e7a3BedD70cd4510', + toError: 'invalidAddressRecipientNotEthNetwork', + toWarning: null, + }) + }) + + it('should synchronously validate when input changes to ""', () => { + wrapper.setProps({ network: 'bad' }) + const instance = wrapper.instance() + instance.onRecipientInputChange('0x80F061544cC398520615B5d3e7a3BedD70cd4510') + + clock.tick(1001) + assert.deepEqual(instance.state, { + query: '0x80F061544cC398520615B5d3e7a3BedD70cd4510', + toError: 'invalidAddressRecipientNotEthNetwork', + toWarning: null, + }) + + instance.onRecipientInputChange('') + assert.deepEqual(instance.state, { + query: '', + toError: '', + toWarning: '', + }) + }) + + it('should warn when send to a known token contract address', () => { + wrapper.setProps({ + selectedToken: '0x888', + }) + const instance = wrapper.instance() + instance.onRecipientInputChange('0x13cb85823f78Cff38f0B0E90D3e975b8CB3AAd64') + + clock.tick(1001) + assert.deepEqual(instance.state, { + query: '0x13cb85823f78Cff38f0B0E90D3e975b8CB3AAd64', + toError: null, + toWarning: 'knownAddressRecipient', + }) + }) + }) }) diff --git a/ui/app/pages/send/tests/send-container.test.js b/ui/app/pages/send/tests/send-container.test.js index 131c42f59..f4142bc2d 100644 --- a/ui/app/pages/send/tests/send-container.test.js +++ b/ui/app/pages/send/tests/send-container.test.js @@ -41,12 +41,19 @@ proxyquire('../send.container.js', { getSendHexDataFeatureFlagState: (s) => `mockSendHexDataFeatureFlagState:${s}`, getSendAmount: (s) => `mockAmount:${s}`, getSendTo: (s) => `mockTo:${s}`, + getSendToNickname: (s) => `mockToNickname:${s}`, getSendEditingTransactionId: (s) => `mockEditingTransactionId:${s}`, getSendFromObject: (s) => `mockFrom:${s}`, getTokenBalance: (s) => `mockTokenBalance:${s}`, getQrCodeData: (s) => `mockQrCodeData:${s}`, + getSendEnsResolution: (s) => `mockSendEnsResolution:${s}`, + getSendEnsResolutionError: (s) => `mockSendEnsResolutionError:${s}`, + }, + './send-content/add-recipient/add-recipient.selectors': { + getTokens: s => `mockTokens:${s}`, }, '../../selectors/selectors': { + getAddressBook: (s) => `mockAddressBook:${s}`, getSelectedAddress: (s) => `mockSelectedAddress:${s}`, }, '../../store/actions': actionSpies, @@ -83,6 +90,11 @@ describe('send container', () => { tokenContract: 'mockTokenContract:mockState', tokenToFiatRate: 'mockTokenToFiatRate:mockState', qrCodeData: 'mockQrCodeData:mockState', + tokens: 'mockTokens:mockState', + ensResolution: 'mockSendEnsResolution:mockState', + ensResolutionError: 'mockSendEnsResolutionError:mockState', + toNickname: 'mockToNickname:mockState', + addressBook: 'mockAddressBook:mockState', }) }) diff --git a/ui/app/pages/send/tests/send-selectors-test-data.js b/ui/app/pages/send/tests/send-selectors-test-data.js index cff26a191..54a494b63 100644 --- a/ui/app/pages/send/tests/send-selectors-test-data.js +++ b/ui/app/pages/send/tests/send-selectors-test-data.js @@ -60,6 +60,7 @@ module.exports = { { 'address': '0x06195827297c7a80a443b6894d3bdb8824b43896', 'name': 'Address Book Account 1', + 'chainId': '3', }, ], 'tokens': [ diff --git a/ui/app/pages/send/tests/send-selectors.test.js b/ui/app/pages/send/tests/send-selectors.test.js index ccc126795..e199aa97e 100644 --- a/ui/app/pages/send/tests/send-selectors.test.js +++ b/ui/app/pages/send/tests/send-selectors.test.js @@ -4,7 +4,6 @@ import selectors from '../send.selectors.js' const { accountsWithSendEtherInfoSelector, // autoAddToBetaUI, - getAddressBook, getBlockGasLimit, getAmountConversionRate, getConversionRate, @@ -103,20 +102,6 @@ describe('send selectors', () => { // }) // }) - describe('getAddressBook()', () => { - it('should return the address book', () => { - assert.deepEqual( - getAddressBook(mockState), - [ - { - address: '0x06195827297c7a80a443b6894d3bdb8824b43896', - name: 'Address Book Account 1', - }, - ], - ) - }) - }) - describe('getAmountConversionRate()', () => { it('should return the token conversion rate if a token is selected', () => { assert.equal( @@ -511,6 +496,7 @@ describe('send selectors', () => { { address: '0x06195827297c7a80a443b6894d3bdb8824b43896', name: 'Address Book Account 1', + chainId: '3', }, ] ) diff --git a/ui/app/pages/send/tests/send-utils.test.js b/ui/app/pages/send/tests/send-utils.test.js index bf9cba14a..4930b7ee1 100644 --- a/ui/app/pages/send/tests/send-utils.test.js +++ b/ui/app/pages/send/tests/send-utils.test.js @@ -72,9 +72,9 @@ describe('send utils', () => { call_, [12, 15, { toNumericBase: 'hex', - multiplicandBase: 16, - multiplierBase: 16, - } ] + multiplicandBase: 16, + multiplierBase: 16, + } ] ) }) }) diff --git a/ui/app/pages/send/to-autocomplete.component.js b/ui/app/pages/send/to-autocomplete.component.js index 183967c58..c65f93c07 100644 --- a/ui/app/pages/send/to-autocomplete.component.js +++ b/ui/app/pages/send/to-autocomplete.component.js @@ -27,10 +27,10 @@ export default class ToAutoComplete extends Component { getListItemIcon (listItemAddress, toAddress) { return toAddress && listItemAddress === toAddress ? <i className={'fa fa-check fa-lg'} - style={{ - color: '#02c9b1', - }} - /> + style={{ + color: '#02c9b1', + }} + /> : null } @@ -121,8 +121,8 @@ export default class ToAutoComplete extends Component { /> { to - ? null - : <i className={'fa fa-caret-down fa-lg send-v2__to-autocomplete__down-caret'} + ? null + : <i className={'fa fa-caret-down fa-lg send-v2__to-autocomplete__down-caret'} onClick={() => this.handleInputEvent()} style={{ style: {color: '#dedede'}, @@ -131,8 +131,8 @@ export default class ToAutoComplete extends Component { } { dropdownOpen - ? this.renderDropdown() - : null + ? this.renderDropdown() + : null } </div> ) diff --git a/ui/app/pages/send/to-autocomplete/to-autocomplete.js b/ui/app/pages/send/to-autocomplete/to-autocomplete.js index 328a5b62b..8ad579958 100644 --- a/ui/app/pages/send/to-autocomplete/to-autocomplete.js +++ b/ui/app/pages/send/to-autocomplete/to-autocomplete.js @@ -37,11 +37,7 @@ ToAutoComplete.prototype.renderDropdown = function () { } = this.props const { accountsToRender } = this.state - return accountsToRender.length && h('div', {}, [ - - h('div.send-v2__from-dropdown__close-area', { - onClick: closeDropdown, - }), + return !!accountsToRender.length && h('div', {}, [ h('div.send-v2__from-dropdown__list', {}, [ @@ -93,7 +89,6 @@ ToAutoComplete.prototype.componentDidUpdate = function (nextProps) { ToAutoComplete.prototype.render = function () { const { to, - dropdownOpen, onChange, inError, qrScanner, @@ -118,12 +113,8 @@ ToAutoComplete.prototype.render = function () { style: { color: '#33333' }, onClick: () => this.props.scanQrCode(), })), - !to && h(`i.fa.fa-caret-down.fa-lg.send-v2__to-autocomplete__down-caret`, { - style: { color: '#dedede' }, - onClick: () => this.handleInputEvent(), - }), - dropdownOpen && this.renderDropdown(), + this.renderDropdown(), ]) } |