-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathindex.js
712 lines (682 loc) · 20.8 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
import React, { PureComponent } from 'react';
import {
SafeAreaView,
TextInput,
Text,
StyleSheet,
View,
TouchableOpacity,
KeyboardAvoidingView,
InteractionManager,
} from 'react-native';
import { connect } from 'react-redux';
import { colors, fontStyles, baseStyles } from '../../../styles/common';
import { getPaymentRequestOptionsTitle } from '../../UI/Navbar';
import FeatherIcon from 'react-native-vector-icons/Feather';
import Fuse from 'fuse.js';
import AssetList from './AssetList';
import PropTypes from 'prop-types';
import {
weiToFiat,
toWei,
balanceToFiat,
renderFromWei,
fiatNumberToWei,
fromWei,
isDecimal,
fiatNumberToTokenMinimalUnit,
renderFromTokenMinimalUnit,
fromTokenMinimalUnit,
toTokenMinimalUnit,
} from '../../../util/number';
import { strings } from '../../../../locales/i18n';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import StyledButton from '../StyledButton';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import { generateETHLink, generateERC20Link, generateUniversalLinkRequest } from '../../../util/payment-link-generator';
import Device from '../../../util/device';
import currencySymbols from '../../../util/currency-symbols.json';
import { NetworksChainId } from '@metamask/controllers';
import { getTicker } from '../../../util/transactions';
import { toLowerCaseEquals } from '../../../util/general';
import { getTokenListArray } from '../../../reducers/tokens';
import { utils as ethersUtils } from 'ethers';
const KEYBOARD_OFFSET = 120;
const styles = StyleSheet.create({
wrapper: {
backgroundColor: colors.white,
flex: 1,
},
contentWrapper: {
paddingTop: 24,
paddingHorizontal: 24,
},
title: {
...fontStyles.normal,
fontSize: 16,
},
searchWrapper: {
marginVertical: 8,
},
searchInput: {
marginHorizontal: 0,
paddingTop: Device.isAndroid() ? 12 : 2,
borderRadius: 8,
paddingHorizontal: 38,
fontSize: 16,
backgroundColor: colors.white,
height: 40,
width: '100%',
color: colors.grey400,
borderColor: colors.grey100,
borderWidth: 1,
...fontStyles.normal,
},
searchIcon: {
position: 'absolute',
textAlignVertical: 'center',
marginTop: Device.isAndroid() ? 9 : 10,
marginLeft: 12,
},
input: {
...fontStyles.normal,
backgroundColor: colors.white,
borderWidth: 0,
fontSize: 24,
paddingBottom: 0,
paddingRight: 0,
paddingLeft: 0,
paddingTop: 0,
},
eth: {
...fontStyles.normal,
fontSize: 24,
paddingTop: Device.isAndroid() ? 3 : 0,
paddingLeft: 10,
textTransform: 'uppercase',
},
fiatValue: {
...fontStyles.normal,
fontSize: 18,
},
split: {
flex: 1,
flexDirection: 'row',
},
ethContainer: {
flex: 1,
flexDirection: 'row',
paddingLeft: 6,
paddingRight: 10,
},
container: {
flex: 1,
flexDirection: 'row',
paddingRight: 10,
paddingVertical: 10,
paddingLeft: 14,
position: 'relative',
backgroundColor: colors.white,
borderColor: colors.grey100,
borderRadius: 4,
borderWidth: 1,
},
amounts: {
maxWidth: '70%',
},
switchContainer: {
flex: 1,
flexDirection: 'column',
alignSelf: 'center',
right: 0,
},
switchTouchable: {
flexDirection: 'row',
alignSelf: 'flex-end',
right: 0,
},
enterAmountWrapper: {
flex: 1,
flexDirection: 'column',
},
button: {
marginBottom: 16,
},
buttonsWrapper: {
flex: 1,
flexDirection: 'row',
alignSelf: 'center',
},
buttonsContainer: {
flex: 1,
flexDirection: 'column',
alignSelf: 'flex-end',
},
scrollViewContainer: {
flexGrow: 1,
},
errorWrapper: {
backgroundColor: colors.red000,
borderRadius: 4,
marginTop: 8,
},
errorText: {
color: colors.fontError,
alignSelf: 'center',
},
assetsWrapper: {
marginTop: 16,
},
assetsTitle: {
...fontStyles.normal,
fontSize: 16,
marginBottom: 8,
},
secondaryAmount: {
flexDirection: 'row',
},
currencySymbol: {
...fontStyles.normal,
fontSize: 24,
},
currencySymbolSmall: {
...fontStyles.normal,
fontSize: 18,
},
});
const fuse = new Fuse([], {
shouldSort: true,
threshold: 0.45,
location: 0,
distance: 100,
maxPatternLength: 32,
minMatchCharLength: 1,
keys: [
{ name: 'name', weight: 0.5 },
{ name: 'symbol', weight: 0.5 },
],
});
const defaultEth = {
symbol: 'ETH',
name: 'Ether',
isETH: true,
};
const defaultAssets = [
defaultEth,
{
address: '0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359',
decimals: 18,
erc20: true,
logo: 'sai.svg',
name: 'Sai Stablecoin v1.0',
symbol: 'SAI',
},
];
const MODE_SELECT = 'select';
const MODE_AMOUNT = 'amount';
/**
* View to generate a payment request link
*/
class PaymentRequest extends PureComponent {
static navigationOptions = ({ navigation, route }) =>
getPaymentRequestOptionsTitle(strings('payment_request.title'), navigation, route);
static propTypes = {
/**
* Object that represents the navigator
*/
navigation: PropTypes.object,
/**
* ETH-to-current currency conversion rate from CurrencyRateController
*/
conversionRate: PropTypes.number,
/**
* Currency code for currently-selected currency from CurrencyRateController
*/
currentCurrency: PropTypes.string,
/**
* Object containing token exchange rates in the format address => exchangeRate
*/
contractExchangeRates: PropTypes.object,
/**
* Primary currency, either ETH or Fiat
*/
primaryCurrency: PropTypes.string,
/**
* A string that represents the selected address
*/
selectedAddress: PropTypes.string,
/**
* Array of ERC20 assets
*/
tokens: PropTypes.array,
/**
* A string representing the chainId
*/
chainId: PropTypes.string,
/**
* Current provider ticker
*/
ticker: PropTypes.string,
/**
* List of tokens from TokenListController (Formatted into array)
*/
tokenList: PropTypes.array,
/**
* Object that represents the current route info like params passed to it
*/
route: PropTypes.object,
};
amountInput = React.createRef();
state = {
searchInputValue: '',
results: [],
selectedAsset: undefined,
mode: MODE_SELECT,
internalPrimaryCurrency: '',
cryptoAmount: undefined,
amount: undefined,
secondaryAmount: undefined,
symbol: undefined,
showError: false,
inputWidth: { width: '99%' },
};
/**
* Set chainId, internalPrimaryCurrency and receiveAssets, if there is an asset set to this payment request chose it automatically, to state
*/
componentDidMount = () => {
const { primaryCurrency, route, tokenList } = this.props;
const receiveAsset = route?.params?.receiveAsset;
this.setState({
internalPrimaryCurrency: primaryCurrency,
inputWidth: { width: '100%' },
});
if (receiveAsset) {
this.goToAmountInput(receiveAsset);
}
// TODO: Fuse will only be updated once on mount. When we convert this component to hooks, we can utilize useEffect to update fuse.
// Update fuse collection with token list
fuse.setCollection(tokenList);
};
componentDidUpdate = () => {
InteractionManager.runAfterInteractions(() => {
this.amountInput.current && this.amountInput.current.focus();
});
};
/**
* Go to asset selection view and modify navbar accordingly
*/
goToAssetSelection = () => {
const { navigation } = this.props;
navigation && navigation.setParams({ mode: MODE_SELECT, dispatch: undefined });
this.setState({
mode: MODE_SELECT,
amount: undefined,
cryptoAmount: undefined,
secondaryAmount: undefined,
symbol: undefined,
});
};
/**
* Go to enter amount view, with selectedAsset and modify navbar accordingly
*
* @param {object} selectedAsset - Asset selected to build the payment request
*/
goToAmountInput = async (selectedAsset) => {
const { navigation } = this.props;
navigation && navigation.setParams({ mode: MODE_AMOUNT, dispatch: this.goToAssetSelection });
await this.setState({ selectedAsset, mode: MODE_AMOUNT });
this.updateAmount();
};
/**
* Handle search input result
*
* @param {string} searchInputValue - String containing assets query
*/
handleSearch = (searchInputValue) => {
const { tokenList } = this.props;
if (typeof searchInputValue !== 'string') {
searchInputValue = this.state.searchInputValue;
}
const fuseSearchResult = fuse.search(searchInputValue);
const addressSearchResult = tokenList.filter((token) => toLowerCaseEquals(token.address, searchInputValue));
const results = [...addressSearchResult, ...fuseSearchResult];
this.setState({ searchInputValue, results });
};
/**
* Renders a view that allows user to select assets to build the payment request
* Either top picks and user's assets are available to select
*/
renderSelectAssets = () => {
const { tokens, chainId, ticker, tokenList } = this.props;
const { inputWidth } = this.state;
let results;
if (chainId === '1') {
results = this.state.searchInputValue ? this.state.results : defaultAssets;
} else if (Object.values(NetworksChainId).find((value) => value === chainId)) {
results = [defaultEth];
} else {
results = [{ ...defaultEth, symbol: getTicker(ticker), name: '' }];
}
const userTokens = tokens.map((token) => {
const contract = tokenList.find((contractToken) => contractToken.address === token.address);
if (contract) return contract;
return token;
});
return (
<View style={baseStyles.flexGrow} testID={'request-screen'}>
<View>
<Text style={styles.title}>{strings('payment_request.choose_asset')}</Text>
</View>
{chainId === '1' && (
<View style={styles.searchWrapper}>
<TextInput
style={[styles.searchInput, inputWidth]}
autoCapitalize="none"
autoCorrect={false}
clearButtonMode="while-editing"
onChangeText={this.handleSearch}
onSubmitEditing={this.handleSearch}
placeholder={strings('payment_request.search_assets')}
placeholderTextColor={colors.grey400}
returnKeyType="go"
value={this.state.searchInputValue}
blurOnSubmit
testID={'request-search-asset-input'}
/>
<FeatherIcon
onPress={this.focusInput}
name="search"
size={18}
color={colors.grey400}
style={styles.searchIcon}
/>
</View>
)}
<View style={styles.assetsWrapper} testID={'searched-asset-results'}>
<Text style={styles.assetsTitle}>
{this.state.searchInputValue
? strings('payment_request.search_results')
: strings('payment_request.search_top_picks')}
</Text>
<AssetList
searchResults={results}
handleSelectAsset={this.goToAmountInput}
selectedAsset={this.state.selectedAsset}
searchQuery={this.state.searchInputValue}
emptyMessage={strings('payment_request.search_no_tokens_found')}
/>
</View>
{userTokens.length > 0 && (
<View style={styles.assetsWrapper}>
<Text style={styles.assetsTitle}>{strings('payment_request.your_tokens')}</Text>
<AssetList
searchResults={userTokens}
handleSelectAsset={this.goToAmountInput}
selectedAsset={this.state.selectedAsset}
searchQuery={this.state.searchInputValue}
/>
</View>
)}
</View>
);
};
/**
* Handles payment request parameters for ETH as primaryCurrency
*
* @param {string} amount - String containing amount number from input, as token value
* @returns {object} - Object containing respective symbol, secondaryAmount and cryptoAmount according to amount and selectedAsset
*/
handleETHPrimaryCurrency = (amount) => {
const { conversionRate, currentCurrency, contractExchangeRates } = this.props;
const { selectedAsset } = this.state;
let secondaryAmount;
const symbol = selectedAsset.symbol;
const undefAmount = isDecimal(amount) && !ethersUtils.isHexString(amount) ? amount : 0;
const cryptoAmount = amount;
const exchangeRate = selectedAsset && selectedAsset.address && contractExchangeRates[selectedAsset.address];
if (selectedAsset.symbol !== 'ETH') {
secondaryAmount = exchangeRate
? balanceToFiat(undefAmount, conversionRate, exchangeRate, currentCurrency)
: undefined;
} else {
secondaryAmount = weiToFiat(toWei(undefAmount), conversionRate, currentCurrency);
}
return { symbol, secondaryAmount, cryptoAmount };
};
/**
* Handles payment request parameters for Fiat as primaryCurrency
*
* @param {string} amount - String containing amount number from input, as fiat value
* @returns {object} - Object containing respective symbol, secondaryAmount and cryptoAmount according to amount and selectedAsset
*/
handleFiatPrimaryCurrency = (amount) => {
const { conversionRate, currentCurrency, contractExchangeRates } = this.props;
const { selectedAsset } = this.state;
const symbol = currentCurrency;
const exchangeRate = selectedAsset && selectedAsset.address && contractExchangeRates[selectedAsset.address];
const undefAmount = (isDecimal(amount) && amount) || 0;
let secondaryAmount, cryptoAmount;
if (selectedAsset.symbol !== 'ETH' && exchangeRate && exchangeRate !== 0) {
const secondaryMinimalUnit = fiatNumberToTokenMinimalUnit(
undefAmount,
conversionRate,
exchangeRate,
selectedAsset.decimals
);
secondaryAmount =
renderFromTokenMinimalUnit(secondaryMinimalUnit, selectedAsset.decimals) + ' ' + selectedAsset.symbol;
cryptoAmount = fromTokenMinimalUnit(secondaryMinimalUnit, selectedAsset.decimals);
} else {
secondaryAmount = renderFromWei(fiatNumberToWei(undefAmount, conversionRate)) + ' ' + strings('unit.eth');
cryptoAmount = fromWei(fiatNumberToWei(undefAmount, conversionRate));
}
return { symbol, secondaryAmount, cryptoAmount };
};
/**
* Handles amount update, setting amount related state parameters, it handles state according to internalPrimaryCurrency
*
* @param {string} amount - String containing amount number from input
*/
updateAmount = (amount) => {
const { internalPrimaryCurrency, selectedAsset } = this.state;
const { conversionRate, contractExchangeRates, currentCurrency } = this.props;
const currencySymbol = currencySymbols[currentCurrency];
const exchangeRate = selectedAsset && selectedAsset.address && contractExchangeRates[selectedAsset.address];
let res;
// If primary currency is not crypo we need to know if there are conversion and exchange rates to handle0,
// fiat conversion for the payment request
if (internalPrimaryCurrency !== 'ETH' && conversionRate && (exchangeRate || selectedAsset.isETH)) {
res = this.handleFiatPrimaryCurrency(amount?.replace(',', '.'));
} else {
res = this.handleETHPrimaryCurrency(amount?.replace(',', '.'));
}
const { cryptoAmount, symbol } = res;
if (amount && amount[0] === currencySymbol) amount = amount.substr(1);
if (res.secondaryAmount && res.secondaryAmount[0] === currencySymbol)
res.secondaryAmount = res.secondaryAmount.substr(1);
if (amount && amount === '0') amount = undefined;
this.setState({ amount, cryptoAmount, secondaryAmount: res.secondaryAmount, symbol, showError: false });
};
/**
* Updates internalPrimaryCurrency
*/
switchPrimaryCurrency = async () => {
const { internalPrimaryCurrency, secondaryAmount } = this.state;
const primarycurrencies = {
ETH: 'Fiat',
Fiat: 'ETH',
};
await this.setState({ internalPrimaryCurrency: primarycurrencies[internalPrimaryCurrency] });
this.updateAmount(secondaryAmount.split(' ')[0]);
};
/**
* Resets amount on payment request
*/
onReset = () => {
this.updateAmount();
};
/**
* Generates payment request link and redirects to PaymentRequestSuccess view with it
* If there is an error, an error message will be set to display on the view
*/
onNext = () => {
const { selectedAddress, navigation, chainId } = this.props;
const { cryptoAmount, selectedAsset } = this.state;
try {
if (cryptoAmount && cryptoAmount > '0') {
let eth_link;
if (selectedAsset.isETH) {
const amount = toWei(cryptoAmount).toString();
eth_link = generateETHLink(selectedAddress, amount, chainId);
} else {
const amount = toTokenMinimalUnit(cryptoAmount, selectedAsset.decimals).toString();
eth_link = generateERC20Link(selectedAddress, selectedAsset.address, amount, chainId);
}
// Convert to universal link / app link
const link = generateUniversalLinkRequest(eth_link);
navigation &&
navigation.replace('PaymentRequestSuccess', {
link,
qrLink: eth_link,
amount: cryptoAmount,
symbol: selectedAsset.symbol,
});
} else {
this.setState({ showError: true });
}
} catch (e) {
this.setState({ showError: true });
}
};
/**
* Renders a view that allows user to set payment request amount
*/
renderEnterAmount = () => {
const { conversionRate, contractExchangeRates, currentCurrency } = this.props;
const { amount, secondaryAmount, symbol, cryptoAmount, showError, selectedAsset, internalPrimaryCurrency } =
this.state;
const currencySymbol = currencySymbols[currentCurrency];
const exchangeRate = selectedAsset && selectedAsset.address && contractExchangeRates[selectedAsset.address];
let switchable = true;
if (!conversionRate) {
switchable = false;
} else if (selectedAsset.symbol !== 'ETH' && !exchangeRate) {
switchable = false;
}
return (
<View style={styles.enterAmountWrapper} testID={'request-amount-screen'}>
<View>
<Text style={styles.title}>{strings('payment_request.enter_amount')}</Text>
</View>
<View style={styles.searchWrapper}>
<View style={styles.container}>
<View style={styles.ethContainer}>
<View style={styles.amounts}>
<View style={styles.split}>
{internalPrimaryCurrency !== 'ETH' && (
<Text style={styles.currencySymbol}>{currencySymbol}</Text>
)}
<TextInput
autoCapitalize="none"
autoCorrect={false}
keyboardType="numeric"
numberOfLines={1}
onChangeText={this.updateAmount}
placeholder={strings('payment_request.amount_placeholder')}
placeholderTextColor={colors.grey100}
spellCheck={false}
style={styles.input}
value={amount}
onSubmitEditing={this.onNext}
ref={this.amountInput}
testID={'request-amount-input'}
/>
<Text style={styles.eth} numberOfLines={1}>
{symbol}
</Text>
</View>
<View style={styles.secondaryAmount}>
{secondaryAmount && internalPrimaryCurrency === 'ETH' && (
<Text style={styles.currencySymbolSmall}>{currencySymbol}</Text>
)}
{secondaryAmount && (
<Text style={styles.fiatValue} numberOfLines={1}>
{secondaryAmount}
</Text>
)}
</View>
</View>
{switchable && (
<View style={styles.switchContainer}>
<TouchableOpacity
onPress={this.switchPrimaryCurrency}
style={styles.switchTouchable}
>
<FontAwesome
onPress={this.focusInput}
name="exchange"
size={18}
color={colors.grey200}
style={{ transform: [{ rotate: '270deg' }] }}
/>
</TouchableOpacity>
</View>
)}
</View>
</View>
{showError && (
<View style={styles.errorWrapper}>
<Text style={styles.errorText}>{strings('payment_request.request_error')}</Text>
</View>
)}
</View>
<KeyboardAvoidingView
style={styles.buttonsWrapper}
behavior={'padding'}
keyboardVerticalOffset={KEYBOARD_OFFSET}
enabled={Device.isIos()}
>
<View style={styles.buttonsContainer}>
<StyledButton type={'normal'} onPress={this.onReset} containerStyle={[styles.button]}>
{strings('payment_request.reset')}
</StyledButton>
<StyledButton
type={'blue'}
onPress={this.onNext}
containerStyle={[styles.button]}
disabled={!cryptoAmount || cryptoAmount === '0'}
>
{strings('payment_request.next')}
</StyledButton>
</View>
</KeyboardAvoidingView>
</View>
);
};
render() {
const { mode } = this.state;
return (
<SafeAreaView style={styles.wrapper}>
<KeyboardAwareScrollView
style={styles.contentWrapper}
contentContainerStyle={styles.scrollViewContainer}
>
{mode === MODE_SELECT ? this.renderSelectAssets() : this.renderEnterAmount()}
</KeyboardAwareScrollView>
</SafeAreaView>
);
}
}
const mapStateToProps = (state) => ({
conversionRate: state.engine.backgroundState.CurrencyRateController.conversionRate,
currentCurrency: state.engine.backgroundState.CurrencyRateController.currentCurrency,
contractExchangeRates: state.engine.backgroundState.TokenRatesController.contractExchangeRates,
searchEngine: state.settings.searchEngine,
selectedAddress: state.engine.backgroundState.PreferencesController.selectedAddress,
tokens: state.engine.backgroundState.TokensController.tokens,
primaryCurrency: state.settings.primaryCurrency,
ticker: state.engine.backgroundState.NetworkController.provider.ticker,
chainId: state.engine.backgroundState.NetworkController.provider.chainId,
tokenList: getTokenListArray(state),
});
export default connect(mapStateToProps)(PaymentRequest);