Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix payment channels request #946

Merged
merged 8 commits into from
Jul 26, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 103 additions & 4 deletions app/components/Nav/Main/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import NetInfo from '@react-native-community/netinfo';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { createStackNavigator, createBottomTabNavigator } from 'react-navigation';
import ENS from 'ethjs-ens';
import GlobalAlert from '../../UI/GlobalAlert';
import FlashMessage from 'react-native-flash-message';
import BackgroundTimer from 'react-native-background-timer';
Expand Down Expand Up @@ -60,7 +61,7 @@ import TransactionsNotificationManager from '../../../core/TransactionsNotificat
import Engine from '../../../core/Engine';
import AppConstants from '../../../core/AppConstants';
import PushNotification from 'react-native-push-notification';
import I18n from '../../../../locales/i18n';
import I18n, { strings } from '../../../../locales/i18n';
import { colors } from '../../../styles/common';
import LockManager from '../../../core/LockManager';
import FadeOutOverlay from '../../UI/FadeOutOverlay';
Expand All @@ -77,7 +78,9 @@ import PaymentChannelDeposit from '../../Views/PaymentChannel/PaymentChannelDepo
import PaymentChannelSend from '../../Views/PaymentChannel/PaymentChannelSend';
import Networks from '../../../util/networks';
import { CONNEXT_DEPOSIT } from '../../../util/transactions';
import { toChecksumAddress } from 'ethereumjs-util';
import { toChecksumAddress, isValidAddress } from 'ethereumjs-util';
import { isENS } from '../../../util/address';
import Logger from '../../../util/Logger';

const styles = StyleSheet.create({
flex: {
Expand Down Expand Up @@ -469,13 +472,109 @@ class Main extends PureComponent {

initializePaymentChannels = () => {
PaymentChannelsClient.init(this.props.selectedAddress);
PaymentChannelsClient.hub.on('payment::request', request => {
this.setState({ paymentChannelRequest: true, paymentChannelRequestInfo: request });
PaymentChannelsClient.hub.on('payment::request', async request => {
const validRequest = { ...request };
// Validate amount
if (isNaN(request.amount)) {
Alert.alert(
strings('payment_channel_request.title_error'),
strings('payment_channel_request.amount_error_message')
);
return;
}

const isAddress = !request.to || request.to.substring(0, 2).toLowerCase() === '0x';
const isInvalidAddress = isAddress && !isValidAddress(request.to);

// Validate address
if (isInvalidAddress || (!isAddress && !isENS(request.to))) {
Alert.alert(
strings('payment_channel_request.title_error'),
strings('payment_channel_request.address_error_message')
);
return;
}

// Check if ENS and resolve the address before sending
if (isENS(request.to)) {
this.setState(
{
paymentChannelRequest: true,
paymentChannelRequestInfo: null
},
() => {
InteractionManager.runAfterInteractions(async () => {
const {
state: { network },
provider
} = Engine.context.NetworkController;
const ensProvider = new ENS({ provider, network });
try {
const resolvedAddress = await ensProvider.lookup(request.to.trim());
if (isValidAddress(resolvedAddress)) {
validRequest.to = resolvedAddress;
validRequest.ensName = request.to;
this.setState({
paymentChannelRequest: true,
paymentChannelRequestInfo: validRequest
});
return;
}
} catch (e) {
Logger.log('Error with payment request', request);
}
Alert.alert(
strings('payment_channel_request.title_error'),
strings('payment_channel_request.address_error_message')
);
this.setState({
paymentChannelRequest: false,
paymentChannelRequestInfo: null
});
});
}
);
} else {
this.setState({
paymentChannelRequest: true,
paymentChannelRequestInfo: validRequest
});
}
});

PaymentChannelsClient.hub.on('payment::complete', () => {
// show the success screen
this.setState({ paymentChannelRequestCompleted: true });
// hide the modal and reset state
setTimeout(() => {
setTimeout(() => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is strange, why two settimeouts? you're calling one settimeout inside the other directly

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there are different timeouts

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right. My bad. Fixed it here: #957

this.setState({
paymentChannelRequest: false,
paymentChannelRequestLoading: false,
paymentChannelRequestInfo: {}
});
setTimeout(() => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

did you do this on purpose? no delay time and you're setting the state two times in this callback

Copy link
Contributor Author

@brunobar79 brunobar79 Jul 29, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did it on purpose. The delay times are below (See here) The reason of it is that I need to give enough time the modal to close before changing the flag.

this.setState({
paymentChannelRequestCompleted: false
});
});
}, 1500);
}, 800);
});

PaymentChannelsClient.hub.on('payment::error', error => {
if (error === 'INVALID_ENS_NAME') {
Alert.alert(
strings('payment_channel_request.title_error'),
strings('payment_channel_request.address_error_message')
);
} else if (error.indexOf('insufficient_balance') !== -1) {
Alert.alert(
strings('payment_channel_request.error'),
strings('payment_channel_request.balance_error_message')
);
}

// hide the modal and reset state
setTimeout(() => {
setTimeout(() => {
Expand Down
11 changes: 4 additions & 7 deletions app/components/UI/AccountInput/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,17 @@ import PropTypes from 'prop-types';
import { ScrollView, Platform, StyleSheet, Text, TextInput, TouchableOpacity, View, Keyboard } from 'react-native';
import { colors, fontStyles } from '../../../styles/common';
import { connect } from 'react-redux';
import { renderShortAddress } from '../../../util/address';
import { renderShortAddress, isENS } from '../../../util/address';
import MaterialIcon from 'react-native-vector-icons/MaterialIcons';
import ElevatedView from 'react-native-elevated-view';
import ENS from 'ethjs-ens';
import networkMap from 'ethjs-ens/lib/network-map.json';
import Engine from '../../../core/Engine';
import { strings } from '../../../../locales/i18n';
import AppConstants from '../../../core/AppConstants';
import { isValidAddress } from 'ethereumjs-util';
import DeviceSize from '../../../util/DeviceSize';
import EthereumAddress from '../EthereumAddress';

const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';
import AppConstants from '../../../core/AppConstants';

const styles = StyleSheet.create({
root: {
Expand Down Expand Up @@ -211,8 +209,7 @@ class AccountInput extends PureComponent {
};

isEnsName = recipient => {
const rec = recipient && recipient.split('.');
if (!rec || rec.length === 1 || !AppConstants.supportedTLDs.includes(rec[rec.length - 1])) {
if (!isENS(recipient)) {
this.setState({ ensRecipient: undefined });
return false;
}
Expand All @@ -223,7 +220,7 @@ class AccountInput extends PureComponent {
const { address } = this.state;
try {
const resolvedAddress = await this.ens.lookup(recipient.trim());
if (address !== ZERO_ADDRESS && isValidAddress(resolvedAddress)) {
if (address !== AppConstants.ZERO_ADDRESS && isValidAddress(resolvedAddress)) {
this.setState({ address: resolvedAddress, ensRecipient: recipient });
return true;
}
Expand Down
4 changes: 4 additions & 0 deletions app/components/UI/Navbar/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -523,6 +523,10 @@ export function getWalletNavbarOptions(title, navigation) {
setTimeout(() => {
DeeplinkManager.parse(data.walletConnectURI);
}, 500);
} else if (data && data.indexOf(AppConstants.MM_UNIVERSAL_LINK_HOST) !== -1) {
setTimeout(() => {
DeeplinkManager.parse(data);
}, 500);
}
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ exports[`PaymentChannelApproval should render correctly 1`] = `
"backgroundColor": "#FFFFFF",
"borderTopLeftRadius": 10,
"borderTopRightRadius": 10,
"minHeight": "62%",
"minHeight": "65%",
"paddingBottom": 20,
}
}
Expand Down Expand Up @@ -218,8 +218,8 @@ exports[`PaymentChannelApproval should render correctly 1`] = `
}
}
>
$
1.00
DAI
</Text>
</View>
</View>
Expand Down
43 changes: 36 additions & 7 deletions app/components/UI/PaymentChannelApproval/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Platform, Animated, StyleSheet, Text, View } from 'react-native';
import { ActivityIndicator, Platform, Animated, StyleSheet, Text, View } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import ActionView from '../ActionView';
import ElevatedView from 'react-native-elevated-view';
Expand All @@ -10,16 +10,23 @@ import { strings } from '../../../../locales/i18n';
import { colors, fontStyles } from '../../../styles/common';
import DeviceSize from '../../../util/DeviceSize';
import WebsiteIcon from '../WebsiteIcon';
import { renderAccountName, renderShortAddress } from '../../../util/address';
import { renderAccountName } from '../../../util/address';
import EthereumAddress from '../EthereumAddress';

const styles = StyleSheet.create({
root: {
backgroundColor: colors.white,
borderTopLeftRadius: 10,
borderTopRightRadius: 10,
minHeight: Platform.OS === 'ios' ? '62%' : '80%',
minHeight: Platform.OS === 'ios' ? '65%' : '80%',
paddingBottom: DeviceSize.isIphoneX() ? 20 : 0
},
emptyContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: colors.white
},
wrapper: {
paddingHorizontal: 25
},
Expand Down Expand Up @@ -202,9 +209,31 @@ class PaymentChannelApproval extends PureComponent {
.toFixed(2)
.toString();

renderAddressOrEns = (to, ensName) => {
if (!to) return null;

if (ensName) {
return <Text style={styles.selectedAddress}>{ensName}</Text>;
}

return <EthereumAddress style={styles.selectedAddress} address={to} type={'short'} />;
};

renderLoader = () => (
<View style={styles.root}>
<View style={styles.emptyContainer}>
<ActivityIndicator style={styles.loader} size="small" />
</View>
</View>
);

render = () => {
if (!this.props.info) {
return this.renderLoader();
}

const {
info: { title, detail, to },
info: { title, detail, to, ensName },
onConfirm,
onCancel,
selectedAddress,
Expand Down Expand Up @@ -278,17 +307,17 @@ class PaymentChannelApproval extends PureComponent {
{title}
</Text>
) : (
<Text style={styles.selectedAddress}>{renderShortAddress(to)}</Text>
this.renderAddressOrEns(to, ensName)
)}
</View>
</View>
<Text style={styles.intro}>{strings('paymentRequest.is_requesting_you_to_pay')}</Text>
<View style={styles.total}>
<Text style={styles.totalPrice}> ${formattedAmount}</Text>
<Text style={styles.totalPrice}>{formattedAmount} DAI</Text>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we have locale for this, strings('unit.dai') i believe

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I really don't think there's a good reason to add DAI, ETH to locales since it doesn't have translation but if want to keep it consistent I'll do it.

</View>
{detail && (
<View style={styles.permissions}>
<Text style={styles.permissionText} numberOfLines={1}>
<Text style={styles.permissionText}>
<Text style={styles.permission}> {detail}</Text>
</Text>
</View>
Expand Down
3 changes: 1 addition & 2 deletions app/components/Views/BrowserTab/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ import BackupAlert from '../../UI/BackupAlert';
import DrawerStatusTracker from '../../../core/DrawerStatusTracker';

const { HOMEPAGE_URL } = AppConstants;
const SUPPORTED_TOP_LEVEL_DOMAINS = ['eth', 'test'];

const styles = StyleSheet.create({
wrapper: {
Expand Down Expand Up @@ -820,7 +819,7 @@ export class BrowserTab extends PureComponent {
const urlObj = new URL(url);
const { hostname } = urlObj;
const tld = hostname.split('.').pop();
if (SUPPORTED_TOP_LEVEL_DOMAINS.indexOf(tld.toLowerCase()) !== -1) {
if (AppConstants.supportedTLDs.indexOf(tld.toLowerCase()) !== -1) {
return true;
}
return false;
Expand Down
3 changes: 2 additions & 1 deletion app/core/AppConstants.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,6 @@ export default {
},
MM_UNIVERSAL_LINK_HOST: 'metamask.app.link',
DAI_ADDRESS: '0x89d24a6b4ccb1b6faa2625fe562bdd9a23260359',
HOMEPAGE_URL: 'https://home.metamask.io/'
HOMEPAGE_URL: 'https://home.metamask.io/',
ZERO_ADDRESS: '0x0000000000000000000000000000000000000000'
};
15 changes: 13 additions & 2 deletions app/core/PaymentChannelsClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import AsyncStorage from '@react-native-community/async-storage';
// eslint-disable-next-line
import * as Connext from 'connext';
import EthQuery from 'ethjs-query';

import TransactionsNotificationManager from './TransactionsNotificationManager';
import { hideMessage } from 'react-native-flash-message';
import { toWei, toBN, renderFromWei, BNToHex } from '../util/number';
Expand Down Expand Up @@ -591,8 +592,18 @@ const reloadClient = () => {
};

const onPaymentConfirm = async request => {
await instance.send({ sendAmount: request.amount, sendRecipient: request.to });
hub.emit('payment::complete', request);
try {
const balance = parseFloat(instance.getState().balance);
const sendAmount = parseFloat(request.amount);
if (balance < sendAmount) {
hub.emit('payment::error', 'insufficient_balance');
} else {
await instance.send({ sendAmount: request.amount, sendRecipient: request.to });
hub.emit('payment::complete', request);
}
} catch (e) {
hub.emit('payment::error', e.toString());
}
};

function initListeners() {
Expand Down
15 changes: 15 additions & 0 deletions app/util/address.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { toChecksumAddress } from 'ethereumjs-util';
import Engine from '../core/Engine';
import AppConstants from '../core/AppConstants';
/**
* Returns full checksummed address
*
Expand Down Expand Up @@ -60,3 +61,17 @@ export async function importAccountFromPrivateKey(private_key) {
throw e;
}
}

/**
* Validates an ENS name
*
* @param {String} name - String corresponding to an ENS name
* @returns {boolean} - Returns a boolean indicating if it is valid
*/
export function isENS(name) {
const rec = name && name.split('.');
if (!rec || rec.length === 1 || !AppConstants.supportedTLDs.includes(rec[rec.length - 1])) {
return false;
}
return true;
}
7 changes: 7 additions & 0 deletions locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -940,5 +940,12 @@
"title": "You're offline",
"text": "Check your internet connection and try again",
"try_again": "Try again"
},
"payment_channel_request": {
"title_error": "Invalid request",
"error": "Error",
"amount_error_message": "The amount must be a number",
"address_error_message": "The address is invalid",
"balance_error_message": "Insufficient balance"
}
}
Loading