BlueWallet/screen/wallets/list.js

459 lines
15 KiB
JavaScript
Raw Normal View History

2018-01-30 22:42:38 +00:00
import React, { Component } from 'react';
import { View, TouchableOpacity, Text, FlatList, RefreshControl, ScrollView } from 'react-native';
2018-01-30 22:42:38 +00:00
import {
BlueTransactionOnchainIcon,
2018-03-17 22:39:21 +02:00
BlueLoading,
SafeBlueArea,
2018-06-24 23:22:46 +01:00
WalletsCarousel,
BlueTransactionIncommingIcon,
BlueTransactionOutgoingIcon,
BlueTransactionPendingIcon,
2018-09-04 23:18:24 +01:00
BlueTransactionOffchainIcon,
2018-12-28 16:43:38 -05:00
BlueTransactionExpiredIcon,
2018-06-24 23:22:46 +01:00
BlueList,
BlueListItem,
2018-06-28 02:43:28 +01:00
BlueHeaderDefaultMain,
BlueTransactionOffchainIncomingIcon,
2018-03-17 22:39:21 +02:00
} from '../../BlueComponents';
import { Icon } from 'react-native-elements';
import { NavigationEvents } from 'react-navigation';
import ReactNativeHapticFeedback from 'react-native-haptic-feedback';
2018-03-18 02:48:23 +00:00
import PropTypes from 'prop-types';
import { LightningCustodianWallet } from '../../class';
2018-03-17 22:39:21 +02:00
let EV = require('../../events');
2018-07-06 16:41:48 +01:00
let A = require('../../analytics');
2018-03-18 02:48:23 +00:00
/** @type {AppStorage} */
let BlueApp = require('../../BlueApp');
2018-05-28 20:18:11 +01:00
let loc = require('../../loc');
2018-01-30 22:42:38 +00:00
export default class WalletsList extends Component {
static navigationOptions = ({ navigation }) => ({
headerStyle: {
backgroundColor: '#FFFFFF',
borderBottomWidth: 0,
elevation: 0,
},
headerRight: (
<TouchableOpacity
style={{ marginHorizontal: 16, width: 40, height: 40, justifyContent: 'center', alignItems: 'flex-end' }}
onPress={() => navigation.navigate('Settings')}
>
<Icon name="kebab-horizontal" size={22} type="octicon" color={BlueApp.settings.foregroundColor} />
</TouchableOpacity>
),
});
2018-01-30 22:42:38 +00:00
constructor(props) {
super(props);
this.state = {
isLoading: true,
wallets: BlueApp.getWallets().concat(false),
lastSnappedTo: 0,
2018-03-17 22:39:21 +02:00
};
EV(EV.enum.WALLETS_COUNT_CHANGED, this.refreshFunction.bind(this));
// here, when we receive TRANSACTIONS_COUNT_CHANGED we do not query
// remote server, we just redraw the screen
EV(EV.enum.TRANSACTIONS_COUNT_CHANGED, this.refreshFunction.bind(this));
2018-01-30 22:42:38 +00:00
}
componentDidMount() {
2018-03-17 22:39:21 +02:00
this.refreshFunction();
}
2018-01-30 22:42:38 +00:00
2018-07-02 12:09:34 +01:00
/**
* Forcefully fetches TXs and balance for lastSnappedTo (i.e. current) wallet.
* Triggered manually by user on pull-to-refresh.
2018-07-02 12:09:34 +01:00
*/
2018-06-24 23:22:46 +01:00
refreshTransactions() {
if (!(this.lastSnappedTo < BlueApp.getWallets().length)) {
// last card, nop
console.log('last card, nop');
return;
}
2018-03-17 22:39:21 +02:00
this.setState(
2018-06-24 23:22:46 +01:00
{
isTransactionsLoading: true,
},
async function() {
let that = this;
setTimeout(async function() {
// more responsive
let noErr = true;
try {
2018-06-28 02:43:28 +01:00
await BlueApp.fetchWalletBalances(that.lastSnappedTo || 0);
let start = +new Date();
await BlueApp.fetchWalletTransactions(that.lastSnappedTo || 0);
let end = +new Date();
console.log('fetch tx took', (end - start) / 1000, 'sec');
2018-06-24 23:22:46 +01:00
} catch (err) {
noErr = false;
console.warn(err);
}
if (noErr) await BlueApp.saveToDisk(); // caching
that.refreshFunction();
}, 1);
},
);
}
2018-07-02 12:09:34 +01:00
/**
* Redraws the screen
*/
2018-06-24 23:22:46 +01:00
refreshFunction() {
2018-07-06 16:41:48 +01:00
if (BlueApp.getBalance() !== 0) {
A(A.ENUM.GOT_NONZERO_BALANCE);
}
this.setState({
isLoading: false,
isTransactionsLoading: false,
dataSource: BlueApp.getTransactions(),
wallets: BlueApp.getWallets().concat(false),
});
2018-06-24 23:22:46 +01:00
}
txMemo(hash) {
if (BlueApp.tx_metadata[hash] && BlueApp.tx_metadata[hash]['memo']) {
2018-06-28 02:43:28 +01:00
return BlueApp.tx_metadata[hash]['memo'];
2018-06-24 23:22:46 +01:00
}
return '';
}
handleClick(index, gradients) {
console.log('click', index);
2018-06-24 23:22:46 +01:00
let wallet = BlueApp.wallets[index];
if (wallet) {
this.props.navigation.navigate('WalletTransactions', {
wallet: wallet,
gradients: gradients,
2018-06-24 23:22:46 +01:00
});
} else {
// if its out of index - this must be last card with incentive to create wallet
this.props.navigation.navigate('AddWallet');
}
}
onSnapToItem(index) {
console.log('onSnapToItem', index);
this.lastSnappedTo = index;
this.setState({ lastSnappedTo: index });
2018-06-24 23:22:46 +01:00
if (index < BlueApp.getWallets().length) {
// not the last
2018-06-24 23:22:46 +01:00
}
2018-07-02 14:51:24 +01:00
// now, lets try to fetch balance and txs for this wallet in case it has changed
this.lazyRefreshWallet(index);
}
/**
* Decides whether wallet with such index shoud be refreshed,
* refreshes if yes and redraws the screen
* @param index {Integer} Index of the wallet.
* @return {Promise.<void>}
*/
async lazyRefreshWallet(index) {
/** @type {Array.<AbstractWallet>} wallets */
let wallets = BlueApp.getWallets();
if (!wallets[index]) {
return;
}
2018-07-02 14:51:24 +01:00
let oldBalance = wallets[index].getBalance();
let noErr = true;
2018-07-14 21:32:36 +01:00
let didRefresh = false;
2018-07-02 14:51:24 +01:00
try {
2018-07-14 21:32:36 +01:00
if (wallets && wallets[index] && wallets[index].timeToRefreshBalance()) {
2018-07-02 14:51:24 +01:00
console.log('snapped to, and now its time to refresh wallet #', index);
await wallets[index].fetchBalance();
2018-07-07 14:04:32 +01:00
if (oldBalance !== wallets[index].getBalance() || wallets[index].getUnconfirmedBalance() !== 0) {
console.log('balance changed, thus txs too');
2018-07-02 14:51:24 +01:00
// balance changed, thus txs too
await wallets[index].fetchTransactions();
this.refreshFunction();
2018-07-14 21:32:36 +01:00
didRefresh = true;
} else if (wallets[index].timeToRefreshTransaction()) {
console.log(wallets[index].getLabel(), 'thinks its time to refresh TXs');
2018-07-14 21:32:36 +01:00
await wallets[index].fetchTransactions();
if (wallets[index].fetchPendingTransactions) {
await wallets[index].fetchPendingTransactions();
}
if (wallets[index].fetchUserInvoices) {
await wallets[index].fetchUserInvoices();
}
2018-07-14 21:32:36 +01:00
this.refreshFunction();
didRefresh = true;
2018-07-03 21:11:02 +01:00
} else {
console.log('balance not changed');
2018-07-02 14:51:24 +01:00
}
}
} catch (Err) {
noErr = false;
console.warn(Err);
}
2018-07-14 21:32:36 +01:00
if (noErr && didRefresh) {
2018-07-02 14:51:24 +01:00
await BlueApp.saveToDisk(); // caching
}
2018-01-30 22:42:38 +00:00
}
_keyExtractor = (_item, index) => index.toString();
2018-09-18 03:24:42 -04:00
renderListHeaderComponent = () => {
return (
<View>
<Text
style={{
paddingLeft: 15,
fontWeight: 'bold',
fontSize: 24,
marginVertical: 8,
color: BlueApp.settings.foregroundColor,
}}
>
{loc.transactions.list.title}
</Text>
</View>
);
};
handleLongPress = () => {
if (BlueApp.getWallets().length > 1) {
this.props.navigation.navigate('ReorderWallets');
} else {
ReactNativeHapticFeedback.trigger('notificationError', false);
}
};
rowTitle = item => {
if (item.type === 'user_invoice' || item.type === 'payment_request') {
2019-01-06 11:48:58 -05:00
if (isNaN(item.value)) {
item.value = '0';
2019-01-06 04:44:08 -05:00
}
const currentDate = new Date();
const now = (currentDate.getTime() / 1000) | 0;
const invoiceExpiration = item.timestamp + item.expire_time;
if (invoiceExpiration > now) {
return loc.formatBalanceWithoutSuffix(item.value && item.value, item.walletPreferredBalanceUnit, true).toString();
} else if (invoiceExpiration < now) {
if (item.ispaid) {
return loc.formatBalanceWithoutSuffix(item.value && item.value, item.walletPreferredBalanceUnit, true).toString();
} else {
return loc.lnd.expired;
}
}
} else {
return loc.formatBalanceWithoutSuffix(item.value && item.value, item.walletPreferredBalanceUnit, true).toString();
}
};
rowTitleStyle = item => {
let color = '#37c0a1';
if (item.type === 'user_invoice' || item.type === 'payment_request') {
const currentDate = new Date();
const now = (currentDate.getTime() / 1000) | 0;
const invoiceExpiration = item.timestamp + item.expire_time;
if (invoiceExpiration > now) {
color = '#37c0a1';
} else if (invoiceExpiration < now) {
if (item.ispaid) {
color = '#37c0a1';
} else {
color = '#FF0000';
}
}
} else if (item.value / 100000000 < 0) {
color = BlueApp.settings.foregroundColor;
}
return {
fontWeight: '600',
fontSize: 16,
color: color,
};
};
2018-01-30 22:42:38 +00:00
render() {
2018-03-17 22:39:21 +02:00
const { navigate } = this.props.navigation;
2018-01-30 22:42:38 +00:00
if (this.state.isLoading) {
2018-03-17 22:39:21 +02:00
return <BlueLoading />;
2018-01-30 22:42:38 +00:00
}
return (
<SafeBlueArea style={{ flex: 1, backgroundColor: '#FFFFFF' }}>
2018-12-11 22:33:28 -05:00
<NavigationEvents
onWillFocus={() => {
this.refreshFunction();
}}
/>
<ScrollView
refreshControl={<RefreshControl onRefresh={() => this.refreshTransactions()} refreshing={this.state.isTransactionsLoading} />}
2018-09-30 23:12:42 -04:00
>
<BlueHeaderDefaultMain leftText={loc.wallets.list.title} onNewWalletPress={() => this.props.navigation.navigate('AddWallet')} />
<WalletsCarousel
data={this.state.wallets}
handleClick={(index, headerColor) => {
this.handleClick(index, headerColor);
}}
handleLongPress={this.handleLongPress}
onSnapToItem={index => {
this.onSnapToItem(index);
}}
/>
<BlueList>
<FlatList
ListHeaderComponent={this.renderListHeaderComponent}
2018-10-10 20:36:32 +01:00
ListEmptyComponent={
<View style={{ top: 50, height: 100 }}>
<Text
style={{
fontSize: 18,
color: '#9aa0aa',
textAlign: 'center',
}}
>
{loc.wallets.list.empty_txs1}
</Text>
<Text
style={{
fontSize: 18,
color: '#9aa0aa',
textAlign: 'center',
}}
>
{loc.wallets.list.empty_txs2}
</Text>
</View>
}
data={this.state.dataSource}
extraData={this.state.dataSource}
keyExtractor={this._keyExtractor}
renderItem={rowData => {
return (
<BlueListItem
avatar={(() => {
// is it lightning refill tx?
if (rowData.item.category === 'receive' && rowData.item.confirmations < 3) {
return (
<View style={{ width: 25 }}>
<BlueTransactionPendingIcon />
</View>
);
}
if (rowData.item.type && rowData.item.type === 'bitcoind_tx') {
return (
<View style={{ width: 25 }}>
<BlueTransactionOnchainIcon />
</View>
);
}
if (rowData.item.type === 'paid_invoice') {
// is it lightning offchain payment?
return (
<View style={{ width: 25 }}>
<BlueTransactionOffchainIcon />
</View>
);
}
2018-12-28 17:16:30 -05:00
if (rowData.item.type === 'user_invoice' || rowData.item.type === 'payment_request') {
if (!rowData.item.ispaid) {
const currentDate = new Date();
const now = (currentDate.getTime() / 1000) | 0;
const invoiceExpiration = rowData.item.timestamp + rowData.item.expire_time;
if (invoiceExpiration < now) {
return (
<View style={{ width: 25 }}>
<BlueTransactionExpiredIcon />
</View>
);
}
} else {
2018-12-28 16:43:38 -05:00
return (
<View style={{ width: 25 }}>
2018-12-28 17:16:30 -05:00
<BlueTransactionOffchainIncomingIcon />
2018-12-28 16:43:38 -05:00
</View>
);
}
}
if (!rowData.item.confirmations) {
return (
<View style={{ width: 25 }}>
<BlueTransactionPendingIcon />
</View>
);
} else if (rowData.item.value < 0) {
return (
<View style={{ width: 25 }}>
<BlueTransactionOutgoingIcon />
</View>
);
} else {
return (
<View style={{ width: 25 }}>
<BlueTransactionIncommingIcon />
</View>
);
}
})()}
title={loc.transactionTimeToReadable(rowData.item.received)}
subtitle={
(rowData.item.confirmations < 7 ? loc.transactions.list.conf + ': ' + rowData.item.confirmations + ' ' : '') +
this.txMemo(rowData.item.hash) +
(rowData.item.memo || '')
}
onPress={() => {
if (rowData.item.hash) {
navigate('TransactionDetails', {
hash: rowData.item.hash,
});
} else if (
rowData.item.type === 'user_invoice' ||
rowData.item.type === 'payment_request' ||
rowData.item.type === 'paid_invoice'
) {
const lightningWallet = this.state.wallets.filter(wallet => wallet.type === LightningCustodianWallet.type);
if (typeof lightningWallet === 'object') {
if (lightningWallet.length === 1) {
this.props.navigation.navigate('LNDViewInvoice', {
invoice: rowData.item,
fromWallet: lightningWallet[0],
});
}
}
}
}}
badge={{
value: 3,
textStyle: { color: 'orange' },
containerStyle: { marginTop: 0 },
}}
hideChevron
rightTitle={this.rowTitle(rowData.item)}
rightTitleStyle={this.rowTitleStyle(rowData.item)}
/>
);
}}
/>
</BlueList>
</ScrollView>
2018-01-30 22:42:38 +00:00
</SafeBlueArea>
);
}
2018-03-17 22:39:21 +02:00
}
2018-03-18 02:48:23 +00:00
WalletsList.propTypes = {
navigation: PropTypes.shape({
navigate: PropTypes.func,
}),
};