You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

548 lines
18 KiB

7 years ago
import React, { Component } from 'react';
import { View, TouchableOpacity, Dimensions, Text, ListView } from 'react-native';
7 years ago
import {
BlueText,
BlueTransactionOnchainIcon,
ManageFundsBigButton,
7 years ago
BlueLoading,
SafeBlueArea,
6 years ago
WalletsCarousel,
BlueTransactionIncommingIcon,
BlueTransactionOutgoingIcon,
BlueTransactionPendingIcon,
BlueSendButtonIcon,
BlueReceiveButtonIcon,
BlueRefreshIcon,
BlueList,
BlueListItem,
6 years ago
BlueHeaderDefaultMain,
is,
7 years ago
} from '../../BlueComponents';
import { Icon } from 'react-native-elements';
7 years ago
import PropTypes from 'prop-types';
import { LightningCustodianWallet } from '../../class/lightning-custodian-wallet';
const BigNumber = require('bignumber.js');
7 years ago
let EV = require('../../events');
6 years ago
let A = require('../../analytics');
7 years ago
/** @type {AppStorage} */
let BlueApp = require('../../BlueApp');
let loc = require('../../loc');
const { height, width } = Dimensions.get('window');
7 years ago
let ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
7 years ago
export default class WalletsList extends Component {
static navigationOptions = {
6 years ago
tabBarVisible: false,
7 years ago
};
7 years ago
constructor(props) {
super(props);
this.state = {
isLoading: true,
7 years ago
};
EV(EV.enum.WALLETS_COUNT_CHANGED, this.refreshFunction.bind(this));
7 years ago
}
async componentDidMount() {
7 years ago
this.refreshFunction();
7 years ago
} // end of componendDidMount
6 years ago
/**
* Forcefully fetches TXs and balance for lastSnappedTo (i.e. current) wallet
*/
6 years ago
refreshTransactions() {
7 years ago
this.setState(
6 years ago
{
isTransactionsLoading: true,
},
async function() {
let that = this;
setTimeout(async function() {
// more responsive
let noErr = true;
try {
6 years ago
await BlueApp.fetchWalletBalances(that.lastSnappedTo || 0);
let start = +new Date();
await BlueApp.fetchWalletTransactions(that.lastSnappedTo || 0);
let end = +new Date();
console.log('tx took', (end - start) / 1000, 'sec');
6 years ago
} catch (err) {
noErr = false;
console.warn(err);
}
if (noErr) await BlueApp.saveToDisk(); // caching
that.refreshFunction();
}, 1);
},
);
}
6 years ago
/**
* Redraws the screen
*/
6 years ago
refreshFunction() {
6 years ago
if (BlueApp.getBalance() !== 0) {
A(A.ENUM.GOT_NONZERO_BALANCE);
}
6 years ago
setTimeout(() => {
console.log('refreshFunction()');
let showSend = false;
let showReceive = false;
let showManageFundsBig = false;
let showManageFundsSmallButton = false;
let wallets = BlueApp.getWallets();
let wallet = wallets[this.lastSnappedTo || 0];
if (wallet) {
showSend = wallet.allowSend();
showReceive = wallet.allowReceive();
}
let showRereshButton = (BlueApp.getWallets().length > 0 && true) || false;
if (wallet && wallet.type === new LightningCustodianWallet().type && !showSend) {
showManageFundsBig = true;
showManageFundsSmallButton = false;
showRereshButton = false;
}
if (wallet && wallet.type === new LightningCustodianWallet().type && wallet.getBalance() > 0) {
showRereshButton = false;
showManageFundsSmallButton = true;
}
6 years ago
this.setState({
isLoading: false,
isTransactionsLoading: false,
showReceiveButton: showReceive,
showSendButton: showSend,
showManageFundsBigButton: showManageFundsBig,
showManageFundsSmallButton,
showRereshButton,
dataSource: ds.cloneWithRows(BlueApp.getTransactions(this.lastSnappedTo || 0)),
6 years ago
});
}, 1);
}
txMemo(hash) {
if (BlueApp.tx_metadata[hash] && BlueApp.tx_metadata[hash]['memo']) {
6 years ago
return BlueApp.tx_metadata[hash]['memo'];
6 years ago
}
return '';
}
handleClick(index) {
console.log('cick', index);
let wallet = BlueApp.wallets[index];
if (wallet) {
this.props.navigation.navigate('WalletDetails', {
address: wallet.getAddress(), // either one of them will work
secret: wallet.getSecret(),
6 years ago
});
} 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({
isLoading: false,
showReceiveButton: false,
showManageFundsBigButton: false,
showManageFundsSmallButton: false,
6 years ago
showSendButton: false,
showRereshButton: false,
6 years ago
// TODO: погуглить че это за ебала ds.cloneWithRows, можно ли быстрее сделать прогрузку транзакций на экран
6 years ago
dataSource: ds.cloneWithRows(BlueApp.getTransactions(index)),
});
if (index < BlueApp.getWallets().length) {
// do not show for last card
let showSend = false;
let showReceive = false;
let showManageFundsBig = false;
let wallets = BlueApp.getWallets();
let wallet = wallets[this.lastSnappedTo || 0];
if (wallet) {
showSend = wallet.allowSend();
showReceive = wallet.allowReceive();
}
console.log({ showSend });
let showRereshButton = true;
let showManageFundsSmallButton = true;
if (wallet && wallet.type === new LightningCustodianWallet().type && !showSend) {
showManageFundsBig = true;
showRereshButton = false;
showManageFundsSmallButton = false;
}
if (wallet && wallet.type === new LightningCustodianWallet().type) {
showRereshButton = false;
} else {
showManageFundsSmallButton = false;
}
console.log({ showManageFundsBig });
6 years ago
setTimeout(
() =>
this.setState({
showReceiveButton: showReceive,
showManageFundsBigButton: showManageFundsBig,
showManageFundsSmallButton,
showSendButton: showSend,
showRereshButton,
}),
6 years ago
50,
); // just to animate it, no real function
}
// now, lets try to fetch balance and txs for this wallet in case it has changed
this.lazyRefreshWallet(index);
}
isLightning() {
let w = BlueApp.getWallets()[this.lastSnappedTo || 0];
if (w && w.type === new LightningCustodianWallet().type) {
return true;
}
return false;
}
/**
* 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;
}
let oldBalance = wallets[index].getBalance();
let noErr = true;
let didRefresh = false;
try {
if (wallets && wallets[index] && wallets[index].timeToRefreshBalance()) {
console.log('snapped to, and now its time to refresh wallet #', index);
await wallets[index].fetchBalance();
if (oldBalance !== wallets[index].getBalance() || wallets[index].getUnconfirmedBalance() !== 0) {
console.log('balance changed, thus txs too');
// balance changed, thus txs too
await wallets[index].fetchTransactions();
this.refreshFunction();
didRefresh = true;
} else if (wallets[index].timeToRefreshTransaction()) {
console.log(wallets[index].getLabel(), 'thinks its time to refresh TXs');
await wallets[index].fetchTransactions();
if (wallets[index].fetchPendingTransactions) {
await wallets[index].fetchPendingTransactions();
}
this.refreshFunction();
didRefresh = true;
6 years ago
} else {
console.log('balance not changed');
}
}
} catch (Err) {
noErr = false;
console.warn(Err);
}
if (noErr && didRefresh) {
await BlueApp.saveToDisk(); // caching
}
7 years ago
}
render() {
7 years ago
const { navigate } = this.props.navigation;
7 years ago
if (this.state.isLoading) {
7 years ago
return <BlueLoading />;
7 years ago
}
return (
<SafeBlueArea>
<BlueHeaderDefaultMain leftText={loc.wallets.list.title} onClose={() => navigate('Settings')} />
6 years ago
<WalletsCarousel
data={BlueApp.getWallets().concat(false)}
handleClick={index => {
this.handleClick(index);
}}
onSnapToItem={index => {
this.onSnapToItem(index);
7 years ago
}}
7 years ago
/>
6 years ago
{(() => {
if (this.state.showManageFundsSmallButton) {
return (
<TouchableOpacity
style={{ alignSelf: 'flex-end', right: 10, flexDirection: 'row' }}
onPress={() => {
let walletIndex = this.lastSnappedTo || 0;
let c = 0;
for (let w of BlueApp.getWallets()) {
if (c++ === walletIndex) {
console.log('navigating to secret ', w.getSecret());
navigate('ManageFunds', { fromSecret: w.getSecret() });
}
}
}}
>
<BlueText style={{ fontWeight: '600', fontSize: 16 }}>Manage funds</BlueText>
<Icon
style={{ position: 'relative' }}
name="link"
type="font-awesome"
size={14}
color={BlueApp.settings.foregroundColor}
iconStyle={{ left: 5, transform: [{ rotate: '90deg' }] }}
/>
</TouchableOpacity>
);
}
})()}
6 years ago
{(() => {
if (this.state.isTransactionsLoading) {
return <BlueLoading />;
} else {
return (
<View style={{ flex: 1 }}>
6 years ago
<View style={{ flex: 1, flexDirection: 'row', height: 50 }}>
6 years ago
<Text
style={{
paddingLeft: 15,
paddingTop: 15,
fontWeight: 'bold',
fontSize: 24,
7 years ago
color: BlueApp.settings.foregroundColor,
7 years ago
}}
6 years ago
>
{loc.transactions.list.title}
</Text>
{(() => {
if (this.state.showRereshButton) {
return <BlueRefreshIcon onPress={() => this.refreshTransactions()} />;
}
})()}
</View>
<View
style={{
top: is.ipad() ? 60 : 120,
position: 'absolute',
width: width,
}}
>
{(() => {
if (BlueApp.getTransactions(this.lastSnappedTo || 0).length === 0) {
return (
<View>
<Text
style={{
fontSize: 18,
color: '#9aa0aa',
textAlign: 'center',
}}
>
{(this.isLightning() &&
'Lightning wallet should be used for your daily\ntransactions. Fees are unfairly cheap and\nspeed is blazing fast.') ||
loc.wallets.list.empty_txs1}
</Text>
<Text
style={{
fontSize: 18,
color: '#9aa0aa',
textAlign: 'center',
}}
>
{(this.isLightning() && '\nTo start using it tap on "manage funds"\nand topup your balance') ||
loc.wallets.list.empty_txs2}
</Text>
</View>
);
}
})()}
6 years ago
</View>
6 years ago
<View style={{ top: 30, position: 'absolute' }}>
<BlueList>
<ListView
maxHeight={height - 330 + 10}
width={width - 5}
left={5}
enableEmptySections
dataSource={this.state.dataSource}
renderRow={rowData => {
return (
<BlueListItem
avatar={(() => {
if (rowData.category && rowData.category === 'receive') {
// is it lightning onchain tx?
if (rowData.confirmations < 3) {
return (
<View style={{ width: 25 }}>
<BlueTransactionPendingIcon />
</View>
);
} else {
return (
<View style={{ width: 25 }}>
<BlueTransactionOnchainIcon />
</View>
);
}
}
6 years ago
if (!rowData.confirmations) {
return (
<View style={{ width: 25 }}>
<BlueTransactionPendingIcon />
</View>
);
} else if (rowData.value < 0) {
return (
<View style={{ width: 25 }}>
<BlueTransactionOutgoingIcon />
</View>
);
} else {
return (
<View style={{ width: 25 }}>
<BlueTransactionIncommingIcon />
</View>
);
}
})()}
title={loc.transactionTimeToReadable(rowData.received)}
6 years ago
subtitle={
(rowData.confirmations < 7 ? loc.transactions.list.conf + ': ' + rowData.confirmations + ' ' : '') +
this.txMemo(rowData.hash) +
(rowData.memo || '')
6 years ago
}
6 years ago
onPress={() => {
if (rowData.hash) {
navigate('TransactionDetails', {
hash: rowData.hash,
});
}
6 years ago
}}
badge={{
value: 3,
textStyle: { color: 'orange' },
containerStyle: { marginTop: 0 },
}}
chevron={false}
chevronColor="transparent"
rightTitle={new BigNumber(rowData.value).div(100000000).toString()}
6 years ago
rightTitleStyle={{
position: 'relative',
right: -30,
top: -7,
fontWeight: '600',
fontSize: 16,
color: rowData.value / 100000000 < 0 ? BlueApp.settings.foregroundColor : '#37c0a1',
6 years ago
}}
/>
);
}}
/>
</BlueList>
</View>
6 years ago
</View>
);
}
})()}
{(() => {
if (this.state.showReceiveButton) {
return (
<BlueReceiveButtonIcon
onPress={() => {
let start = +new Date();
6 years ago
let walletIndex = this.lastSnappedTo || 0;
console.log('receiving on #', walletIndex);
let c = 0;
for (let w of BlueApp.getWallets()) {
if (c++ === walletIndex) {
console.log('found receiving address, secret=', w.getAddress(), ',', w.getSecret());
navigate('ReceiveDetails', { address: w.getAddress(), secret: w.getSecret() });
if (w.getAddress()) {
// EV(EV.enum.RECEIVE_ADDRESS_CHANGED, w.getAddress());
}
6 years ago
}
}
let end = +new Date();
console.log('took', (end - start) / 1000, 'sec');
6 years ago
}}
/>
);
}
})()}
{(() => {
if (this.state.showSendButton) {
6 years ago
return (
<BlueSendButtonIcon
onPress={() => {
let walletIndex = this.lastSnappedTo || 0;
let c = 0;
for (let w of BlueApp.getWallets()) {
if (c++ === walletIndex) {
if (w.type === new LightningCustodianWallet().type) {
navigate('ScanLndInvoice', { fromSecret: w.getSecret() });
} else {
navigate('SendDetails', { fromAddress: w.getAddress(), fromSecret: w.getSecret() });
}
}
}
}}
/>
);
}
})()}
{(() => {
if (this.state.showManageFundsBigButton) {
return (
<ManageFundsBigButton
onPress={() => {
let walletIndex = this.lastSnappedTo || 0;
let c = 0;
for (let w of BlueApp.getWallets()) {
if (c++ === walletIndex) {
console.log('navigating to secret ', w.getSecret());
navigate('ManageFunds', { fromSecret: w.getSecret() });
6 years ago
}
}
}}
/>
);
}
})()}
7 years ago
</SafeBlueArea>
);
}
7 years ago
}
7 years ago
WalletsList.propTypes = {
navigation: PropTypes.shape({
navigate: PropTypes.func,
}),
};