import React, { useCallback, useContext, useEffect, useRef, useState } from 'react'; import { BackHandler, InteractionManager, Keyboard, KeyboardAvoidingView, Platform, ScrollView, StyleSheet, TextInput, View, } from 'react-native'; import { useRoute, useFocusEffect } from '@react-navigation/native'; import Share from 'react-native-share'; import QRCodeComponent from '../../components/QRCodeComponent'; import { BlueLoading, BlueButtonLink, BlueText, BlueSpacing20, BlueCard, BlueSpacing40 } from '../../BlueComponents'; import navigationStyle from '../../components/navigationStyle'; import BottomModal from '../../components/BottomModal'; import { Chain, BitcoinUnit } from '../../models/bitcoinUnits'; import HandoffComponent from '../../components/handoff'; import AmountInput from '../../components/AmountInput'; import DeeplinkSchemaMatch from '../../class/deeplink-schema-match'; import loc, { formatBalance } from '../../loc'; import { BlueStorageContext } from '../../blue_modules/storage-context'; import Notifications from '../../blue_modules/notifications'; import { TransactionPendingIconBig } from '../../components/TransactionPendingIconBig'; import * as BlueElectrum from '../../blue_modules/BlueElectrum'; import { SuccessView } from '../send/success'; import { useTheme } from '../../components/themes'; import Button from '../../components/Button'; import triggerHapticFeedback, { HapticFeedbackTypes } from '../../blue_modules/hapticFeedback'; import { fiatToBTC, satoshiToBTC } from '../../blue_modules/currency'; import { useExtendedNavigation } from '../../hooks/useExtendedNavigation'; import CopyTextToClipboard from '../../components/CopyTextToClipboard'; const ReceiveDetails = () => { const { walletID, address } = useRoute().params; const { wallets, saveToDisk, sleep, isElectrumDisabled, fetchAndSaveWalletTransactions } = useContext(BlueStorageContext); const wallet = wallets.find(w => w.getID() === walletID); const [customLabel, setCustomLabel] = useState(); const [customAmount, setCustomAmount] = useState(); const [customUnit, setCustomUnit] = useState(BitcoinUnit.BTC); const [bip21encoded, setBip21encoded] = useState(); const [isCustom, setIsCustom] = useState(false); const [isCustomModalVisible, setIsCustomModalVisible] = useState(false); const [showPendingBalance, setShowPendingBalance] = useState(false); const [showConfirmedBalance, setShowConfirmedBalance] = useState(false); const [showAddress, setShowAddress] = useState(false); const { goBack, setParams } = useExtendedNavigation(); const { colors } = useTheme(); const [intervalMs, setIntervalMs] = useState(5000); const [eta, setEta] = useState(''); const [initialConfirmed, setInitialConfirmed] = useState(0); const [initialUnconfirmed, setInitialUnconfirmed] = useState(0); const [displayBalance, setDisplayBalance] = useState(''); const fetchAddressInterval = useRef(); const receiveAddressButton = useRef(); const stylesHook = StyleSheet.create({ modalContent: { backgroundColor: colors.modal, borderTopColor: colors.foregroundColor, borderWidth: colors.borderWidth, }, customAmount: { borderColor: colors.formBorder, borderBottomColor: colors.formBorder, backgroundColor: colors.inputBackgroundColor, }, customAmountText: { color: colors.foregroundColor, }, root: { backgroundColor: colors.elevated, }, rootBackgroundColor: { backgroundColor: colors.elevated, }, amount: { color: colors.foregroundColor, }, label: { color: colors.foregroundColor, }, modalButton: { backgroundColor: colors.modalButton, }, }); useEffect(() => { if (showConfirmedBalance) { triggerHapticFeedback(HapticFeedbackTypes.NotificationSuccess); } }, [showConfirmedBalance]); // re-fetching address balance periodically useEffect(() => { console.log('receive/defails - useEffect'); if (fetchAddressInterval.current) { // interval already exists, lets cleanup it and recreate, so theres no duplicate intervals clearInterval(fetchAddressInterval.current); fetchAddressInterval.current = undefined; } fetchAddressInterval.current = setInterval(async () => { try { const decoded = DeeplinkSchemaMatch.bip21decode(bip21encoded); const address2use = address || decoded.address; if (!address2use) return; console.log('checking address', address2use, 'for balance...'); const balance = await BlueElectrum.getBalanceByAddress(address2use); console.log('...got', balance); if (balance.unconfirmed > 0) { if (initialConfirmed === 0 && initialUnconfirmed === 0) { // saving initial values for later (when tx gets confirmed) setInitialConfirmed(balance.confirmed); setInitialUnconfirmed(balance.unconfirmed); setIntervalMs(25000); triggerHapticFeedback(HapticFeedbackTypes.ImpactHeavy); } const txs = await BlueElectrum.getMempoolTransactionsByAddress(address2use); const tx = txs.pop(); if (tx) { const rez = await BlueElectrum.multiGetTransactionByTxid([tx.tx_hash], 10, true); if (rez && rez[tx.tx_hash] && rez[tx.tx_hash].vsize) { const satPerVbyte = Math.round(tx.fee / rez[tx.tx_hash].vsize); const fees = await BlueElectrum.estimateFees(); if (satPerVbyte >= fees.fast) { setEta(loc.formatString(loc.transactions.eta_10m)); } if (satPerVbyte >= fees.medium && satPerVbyte < fees.fast) { setEta(loc.formatString(loc.transactions.eta_3h)); } if (satPerVbyte < fees.medium) { setEta(loc.formatString(loc.transactions.eta_1d)); } } } setDisplayBalance( loc.formatString(loc.transactions.pending_with_amount, { amt1: formatBalance(balance.unconfirmed, BitcoinUnit.LOCAL_CURRENCY, true).toString(), amt2: formatBalance(balance.unconfirmed, BitcoinUnit.BTC, true).toString(), }), ); setShowPendingBalance(true); setShowAddress(false); } else if (balance.unconfirmed === 0 && initialUnconfirmed !== 0) { // now, handling a case when unconfirmed == 0, but in past it wasnt (i.e. it changed while user was // staring at the screen) const balanceToShow = balance.confirmed - initialConfirmed; if (balanceToShow > 0) { // address has actually more coins than initially, so we definitely gained something setShowConfirmedBalance(true); setShowPendingBalance(false); setShowAddress(false); clearInterval(fetchAddressInterval.current); fetchAddressInterval.current = undefined; setDisplayBalance( loc.formatString(loc.transactions.received_with_amount, { amt1: formatBalance(balanceToShow, BitcoinUnit.LOCAL_CURRENCY, true).toString(), amt2: formatBalance(balanceToShow, BitcoinUnit.BTC, true).toString(), }), ); fetchAndSaveWalletTransactions(walletID); } else { // rare case, but probable. transaction evicted from mempool (maybe cancelled by the sender) setShowConfirmedBalance(false); setShowPendingBalance(false); setShowAddress(true); } } } catch (error) { console.log(error); } }, intervalMs); }, [bip21encoded, address, initialConfirmed, initialUnconfirmed, intervalMs, fetchAndSaveWalletTransactions, walletID]); const renderConfirmedBalance = () => { return ( {isCustom && ( <> {customLabel} )} {displayBalance} ); }; const renderPendingBalance = () => { return ( {isCustom && ( <> {customLabel} )} {displayBalance} {eta} ); }; const handleBackButton = () => { goBack(null); return true; }; useEffect(() => { BackHandler.addEventListener('hardwareBackPress', handleBackButton); return () => { BackHandler.removeEventListener('hardwareBackPress', handleBackButton); clearInterval(fetchAddressInterval.current); fetchAddressInterval.current = undefined; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const renderReceiveDetails = () => { return ( {isCustom && ( <> {getDisplayAmount() && ( {getDisplayAmount()} )} {customLabel?.length > 0 && ( {customLabel} )} )}