Request Payment SubTab - EIP 681 (#671)

* progress

* Normalize bity api response

* Filter api response

* Track swap information in component state

* Update dropdown onchange

* remove dead code

* Update Min Max Validation

* Update minmax err msg && fix onChangeOriginKind

* Add origin & destination to redux state

* Update types & Update tests

* Update types

* Update swap.spec.ts test

* Remove commented out code

* Remove hardcoded coin array

* Create types.ts for swap reducer

* Update swapinput type

* Update bityRates in localStorage & Replace all instances of ...Kind / ...Amount props

* Add shapeshift banner

* initial work for sagas

* Update Types

* Update swap reducer initial state

* Update Types & Store empty obj for bityRates / options

* Update more types

* added shapeshift file and rates comments

* action reducers and prop mapping to components

* add typings and swap icon

* more actions reducers and sagas

* debugging shapeshift service

* add Headers

* Fix content type

* add order reset saga and ui fixes

* remove console log and swap b/w Bity and Shapeshift

* working state for Shapeshift and Bity - tested with mainnet

* add icon component

* UI improvements and fix select bug

* fix timer bug

* add bity fallback options and toFixed floats

* tslint errors

* add arrow to dropdown and add support footer

* Add service provider

* fix minor $ bug and stop timer on order complete

* better load UX and dropdown UX

* fixed single test

* currRate prop bugs and reduce LS bloat

* takeEvery on timer saga and don't clear state.options to restartSwap reducer

* export tx sagas and fix minor type

* Add ShapeShift Rates functionality when selecting a ShapeShift pair.

* type fixes

* BugFix: Don't change displayed ShapeShift Rate Inputs on every dropdown change
Also contains some caching / performance improvements

* BugFix: Don't remote rate inputs when falsy amount

* fix type error

* Progress commit

* Implement saga logic

* Make address field factory component

* Shorten debounce time

* Make new actions / sagas  for handling single token lookup

* Implement working version of litesend

* make unit dropdown searchable, add props for all tokens, custom validation

* add string generators for EIP 681 token & ether transactions

* add new selectors

* add request payment tab

* Change saga into selector

* Add failing spec

* fix broken test

* add debounce to error message

* fix tests

* update snapshots

* test coverage

* move setState disabled property from debounce so we instantly can go to next step on valid amounts

* reset amount value (useful for switching between tabs)

* much deeper test coverage, fix debounce ux, and fix bity flashing at swap page load

* fix minor failing test

* seperate shapeshift erc20 token whitelist

* fix saveState store bug

* break orderTimeRemaining saga up and rewrite tests

* fix tslint error

* add isReadOnly prop to address field

* use AddressField component, add additional validation

* make prop optional

* correct validation

* allow for request tab to be used with view only wallet

* account for undefined activeTab

* add types
This commit is contained in:
Danny Skubak 2018-01-02 22:18:10 -05:00 committed by Daniel Ternyak
parent edde125798
commit b939e8ceda
12 changed files with 347 additions and 29 deletions

View File

@ -2,7 +2,11 @@ import React from 'react';
import { AddressFieldFactory } from './AddressFieldFactory';
import { donationAddressMap } from 'config/data';
export const AddressField: React.SFC<{}> = () => (
interface Props {
isReadOnly?: boolean;
}
export const AddressField: React.SFC<Props> = ({ isReadOnly }) => (
<AddressFieldFactory
withProps={({ currentTo, isValid, onChange, readOnly }) => (
<input
@ -10,7 +14,7 @@ export const AddressField: React.SFC<{}> = () => (
type="text"
value={currentTo.raw}
placeholder={donationAddressMap.ETH}
readOnly={!!readOnly}
readOnly={!!(isReadOnly || readOnly)}
onChange={onChange}
/>
)}

View File

@ -6,26 +6,36 @@ import translate, { translateRaw } from 'translations';
interface Props {
hasUnitDropdown?: boolean;
showAllTokens?: boolean;
customValidator?(rawAmount: string): boolean;
}
export const AmountField: React.SFC<Props> = ({ hasUnitDropdown }) => (
export const AmountField: React.SFC<Props> = ({
hasUnitDropdown,
showAllTokens,
customValidator
}) => (
<AmountFieldFactory
withProps={({ currentValue: { raw }, isValid, onChange, readOnly }) => (
<Aux>
<label>{translate('SEND_amount')}</label>
<div className="input-group">
<input
className={`form-control ${isValid ? 'is-valid' : 'is-invalid'}`}
className={`form-control ${
isAmountValid(raw, customValidator, isValid) ? 'is-valid' : 'is-invalid'
}`}
type="number"
placeholder={translateRaw('SEND_amount_short')}
value={raw}
readOnly={!!readOnly}
onChange={onChange}
/>
{hasUnitDropdown && <UnitDropDown />}
{hasUnitDropdown && <UnitDropDown showAllTokens={showAllTokens} />}
</div>
</Aux>
)}
/>
);
const isAmountValid = (raw, customValidator, isValid) =>
customValidator ? customValidator(raw) : isValid;

View File

@ -2,7 +2,7 @@ import React, { Component } from 'react';
import { setUnitMeta, TSetUnitMeta } from 'actions/transaction';
import Dropdown from 'components/ui/Dropdown';
import { withConditional } from 'components/hocs';
import { TokenBalance, getShownTokenBalances } from 'selectors/wallet';
import { TokenBalance, MergedToken, getShownTokenBalances, getTokens } from 'selectors/wallet';
import { Query } from 'components/renderCbs';
import { connect } from 'react-redux';
import { AppState } from 'reducers';
@ -15,6 +15,8 @@ interface DispatchProps {
interface StateProps {
unit: string;
tokens: TokenBalance[];
allTokens: MergedToken[];
showAllTokens?: boolean;
}
const StringDropdown = Dropdown as new () => Dropdown<string>;
@ -22,14 +24,15 @@ const ConditionalStringDropDown = withConditional(StringDropdown);
class UnitDropdownClass extends Component<DispatchProps & StateProps> {
public render() {
const { tokens, unit } = this.props;
const { tokens, allTokens, showAllTokens, unit } = this.props;
const focusedTokens = showAllTokens ? allTokens : tokens;
return (
<div className="input-group-btn">
<Query
params={['readOnly']}
withQuery={({ readOnly }) => (
<ConditionalStringDropDown
options={['ether', ...getTokenSymbols(tokens)]}
options={['ether', ...getTokenSymbols(focusedTokens)]}
value={unit}
condition={!readOnly}
conditionalProps={{
@ -46,11 +49,12 @@ class UnitDropdownClass extends Component<DispatchProps & StateProps> {
this.props.setUnitMeta(unit);
};
}
const getTokenSymbols = (tokens: TokenBalance[]) => tokens.map(t => t.symbol);
const getTokenSymbols = (tokens: (TokenBalance | MergedToken)[]) => tokens.map(t => t.symbol);
function mapStateToProps(state: AppState) {
return {
tokens: getShownTokenBalances(state, true),
allTokens: getTokens(state),
unit: getUnit(state)
};
}

View File

@ -15,7 +15,15 @@ interface Props<T> {
onChange?(value: T): void;
}
export default class DropdownComponent<T> extends Component<Props<T>, {}> {
interface State {
search: string;
}
export default class DropdownComponent<T> extends Component<Props<T>, State> {
public state = {
search: ''
};
private dropdownShell: DropdownShell | null;
public render() {
@ -45,25 +53,51 @@ export default class DropdownComponent<T> extends Component<Props<T>, {}> {
private renderOptions = () => {
const { options, value, menuAlign, extra } = this.props;
const { search } = this.state;
const searchable = options.length > 20;
const menuClass = classnames({
'dropdown-menu': true,
[`dropdown-menu-${menuAlign || ''}`]: !!menuAlign
});
const searchableStyle = {
maxHeight: '300px',
overflowY: 'auto'
};
const searchRegex = new RegExp(search, 'gi');
const onSearchChange = e => {
this.setState({ search: e.target.value });
};
return (
<ul className={menuClass}>
{options.map((option, i) => {
return (
<li key={i}>
<a
className={option === value ? 'active' : ''}
onClick={this.onChange.bind(null, option)}
>
{this.props.formatTitle ? this.formatTitle(option) : option}
</a>
</li>
);
})}
<ul className={menuClass} style={searchable ? searchableStyle : {}}>
{searchable && (
<input
className="form-control"
placeholder={'Search'}
onChange={onSearchChange}
value={search}
/>
)}
{options
.filter(option => {
if (searchable && search.length) {
return option.toString().match(searchRegex);
}
return true;
})
.map((option, i) => {
return (
<li key={i}>
<a
className={option === value ? 'active' : ''}
onClick={this.onChange.bind(null, option)}
>
{this.props.formatTitle ? this.formatTitle(option) : option}
</a>
</li>
);
})}
{extra && <li key={'separator'} role="separator" className="divider" />}
{extra}
</ul>

View File

@ -0,0 +1,18 @@
@import "common/sass/variables";
.RequestPayment {
&-qr {
position: relative;
background: #FFF;
cursor: pointer;
}
&-codeContainer {
padding-top: 20px;
}
&-codeBox {
min-height: 180px;
overflow-x: hidden;
}
}

View File

@ -0,0 +1,186 @@
import React from 'react';
import { connect } from 'react-redux';
import { AppState } from 'reducers';
import translate from 'translations';
import { IWallet } from 'libs/wallet';
import { QRCode } from 'components/ui';
import { getUnit, getDecimal } from 'selectors/transaction/meta';
import {
getCurrentTo,
getCurrentValue,
ICurrentTo,
ICurrentValue
} from 'selectors/transaction/current';
import BN from 'bn.js';
import { NetworkConfig } from 'config/data';
import { validNumber, validDecimal } from 'libs/validators';
import { getGasLimit } from 'selectors/transaction';
import { AddressField, AmountField, GasField } from 'components';
import { SetGasLimitFieldAction } from 'actions/transaction/actionTypes/fields';
import { buildEIP681EtherRequest, buildEIP681TokenRequest } from 'libs/values';
import { getNetworkConfig, getSelectedTokenContractAddress } from 'selectors/config';
import './RequestPayment.scss';
import { reset, TReset, setCurrentTo, TSetCurrentTo } from 'actions/transaction';
interface OwnProps {
wallet: AppState['wallet']['inst'];
}
interface StateProps {
unit: string;
currentTo: ICurrentTo;
currentValue: ICurrentValue;
gasLimit: SetGasLimitFieldAction['payload'];
networkConfig: NetworkConfig | undefined;
decimal: number;
tokenContractAddress: string;
}
interface ActionProps {
reset: TReset;
setCurrentTo: TSetCurrentTo;
}
type Props = OwnProps & StateProps & ActionProps;
const isValidAmount = decimal => amount => validNumber(+amount) && validDecimal(amount, decimal);
class RequestPayment extends React.Component<Props, {}> {
public state = {
recipientAddress: ''
};
public componentDidMount() {
if (this.props.wallet) {
this.setWalletAsyncState(this.props.wallet);
}
this.props.reset();
}
public componentWillUnmount() {
this.props.reset();
}
public componentWillReceiveProps(nextProps: Props) {
if (nextProps.wallet && this.props.wallet !== nextProps.wallet) {
this.setWalletAsyncState(nextProps.wallet);
}
}
public render() {
const {
tokenContractAddress,
gasLimit,
currentTo,
currentValue,
networkConfig,
unit,
decimal
} = this.props;
const chainId = networkConfig ? networkConfig.chainId : undefined;
const eip681String = this.generateEIP681String(
currentTo.raw,
tokenContractAddress,
currentValue,
gasLimit,
unit,
decimal,
chainId
);
return (
<div className="RequestPayment">
<div className="Tab-content-pane">
<AddressField isReadOnly={true} />
<div className="row form-group">
<div className="col-xs-11">
<AmountField
hasUnitDropdown={true}
showAllTokens={true}
customValidator={isValidAmount(decimal)}
/>
</div>
</div>
<div className="row form-group">
<div className="col-xs-11">
<GasField />
</div>
</div>
{!!eip681String.length && (
<div className="row form-group">
<div className="col-xs-6">
<label>{translate('Payment QR & Code')}</label>
<div className="RequestPayment-qr well well-lg">
<QRCode data={eip681String} />
</div>
</div>
<div className="col-xs-6 RequestPayment-codeContainer">
<textarea
className="RequestPayment-codeBox form-control"
value={eip681String}
disabled={true}
/>
</div>
</div>
)}
</div>
</div>
);
}
private async setWalletAsyncState(wallet: IWallet) {
this.props.setCurrentTo(await wallet.getAddressString());
}
private generateEIP681String(
currentTo: string,
tokenContractAddress: string,
currentValue,
gasLimit: { raw: string; value: BN | null },
unit: string,
decimal: number,
chainId?: number
) {
if (
!isValidAmount(decimal)(currentValue.raw) ||
!chainId ||
!gasLimit ||
!gasLimit.raw.length ||
!currentTo.length ||
(unit !== 'ether' && !tokenContractAddress.length)
) {
return '';
}
if (unit === 'ether') {
return buildEIP681EtherRequest(currentTo, chainId, currentValue);
} else {
return buildEIP681TokenRequest(
currentTo,
tokenContractAddress,
chainId,
currentValue,
decimal,
gasLimit
);
}
}
}
function mapStateToProps(state: AppState): StateProps {
return {
unit: getUnit(state),
currentTo: getCurrentTo(state),
currentValue: getCurrentValue(state),
gasLimit: getGasLimit(state),
networkConfig: getNetworkConfig(state),
decimal: getDecimal(state),
tokenContractAddress: getSelectedTokenContractAddress(state)
};
}
export default connect(mapStateToProps, { reset, setCurrentTo })(RequestPayment);

View File

@ -3,3 +3,4 @@ export * from './Fields';
export * from './UnavailableWallets';
export * from './SideBar';
export { default as WalletInfo } from './WalletInfo';
export { default as RequestPayment } from './RequestPayment';

View File

@ -22,6 +22,14 @@ export type WalletTypes = IReadOnlyWallet | IFullWallet | undefined | null;
type Props = StateProps & RouteComponentProps<{}>;
const determineActiveTab = (wallet: WalletTypes, activeTab: string) => {
if (wallet && wallet.isReadOnly && (activeTab === 'send' || activeTab === undefined)) {
return 'info';
}
return activeTab;
};
class SendTransaction extends React.Component<Props> {
public render() {
const { wallet, location } = this.props;
@ -29,7 +37,7 @@ class SendTransaction extends React.Component<Props> {
const tabProps: TabProps<SubTabProps> = {
root: 'account',
activeTab: wallet ? (wallet.isReadOnly ? 'info' : activeTab) : activeTab,
activeTab: determineActiveTab(wallet, activeTab),
sideBar: <SideBar />,
tabs,
subTabProps: { wallet }

View File

@ -2,7 +2,7 @@
import React from 'react';
// REDUX
import translate from 'translations';
import { Fields, UnavailableWallets, WalletInfo } from './components/index';
import { Fields, UnavailableWallets, WalletInfo, RequestPayment } from './components/index';
import { Tab } from 'components/SubTabs';
import { SubTabProps } from 'containers/Tabs/SendTransaction';
@ -37,6 +37,16 @@ const InfoTab: Tab<SubTabProps> = {
return <div>{content}</div>;
}
};
const tabs: Tab<SubTabProps>[] = [SendTab, InfoTab];
const RequestTab: Tab<SubTabProps> = {
path: 'request',
name: translate('Request Payment'),
render(props: SubTabProps) {
const content = props && props.wallet ? <RequestPayment wallet={props.wallet} /> : null;
return <div>{content}</div>;
}
};
const tabs: Tab<SubTabProps>[] = [SendTab, RequestTab, InfoTab];
export default tabs;

View File

@ -1,5 +1,7 @@
import { Wei } from 'libs/units';
import { Wei, toTokenBase } from 'libs/units';
import { addHexPrefix } from 'ethereumjs-util';
import BN from 'bn.js';
export function stripHexPrefix(value: string) {
return value.replace('0x', '');
}
@ -35,3 +37,23 @@ export function networkIdToName(networkId: string | number): string {
throw new Error(`Network ${networkId} is unsupported.`);
}
}
export const buildEIP681EtherRequest = (
recipientAddr: string,
chainId: number,
etherValue: { raw: string; value: Wei | '' }
) => `ethereum:${recipientAddr}${chainId !== 1 ? `@${chainId}` : ''}?value=${etherValue.raw}e18`;
export const buildEIP681TokenRequest = (
recipientAddr: string,
contractAddr: string,
chainId: number,
tokenValue: { raw: string; value: Wei | '' },
decimal: number,
gasLimit: { raw: string; value: BN | null }
) =>
`ethereum:${contractAddr}${
chainId !== 1 ? `@${chainId}` : ''
}/transfer?address=${recipientAddr}&uint256=${toTokenBase(tokenValue.raw, decimal)}&gas=${
gasLimit.raw
}`;

View File

@ -72,7 +72,6 @@ export function* handleConfigureLiteSend(): SagaIterator {
yield put(showLiteSend(false));
return yield put(reset());
}
if (result.transactionReset) {
yield cancel(liteSendProc);
}

View File

@ -9,6 +9,7 @@ import {
import { INode } from 'libs/nodes/INode';
import { AppState } from 'reducers';
import { getNetworkConfigFromId } from 'utils/network';
import { getUnit } from 'selectors/transaction/meta';
import { isEtherUnit } from 'libs/units';
import { SHAPESHIFT_TOKEN_WHITELIST } from 'api/shapeshift';
@ -43,6 +44,27 @@ export function getAllTokens(state: AppState): Token[] {
return networkTokens.concat(state.customTokens);
}
export function getSelectedTokenContractAddress(state: AppState): string {
const allTokens = getAllTokens(state);
const currentUnit = getUnit(state);
if (currentUnit === 'ether') {
return '';
}
return allTokens.reduce((tokenAddr, tokenInfo) => {
if (tokenAddr && tokenAddr.length) {
return tokenAddr;
}
if (tokenInfo.symbol === currentUnit) {
return tokenInfo.address;
}
return tokenAddr;
}, '');
}
export function tokenExists(state: AppState, token: string): boolean {
const existInWhitelist = SHAPESHIFT_TOKEN_WHITELIST.includes(token);
const existsInNetwork = !!getAllTokens(state).find(t => t.symbol === token);