BlueWallet/hooks/useWatchConnectivity.ios.ts

280 lines
10 KiB
TypeScript
Raw Normal View History

2024-11-08 21:33:35 -04:00
import { useCallback, useEffect, useRef } from 'react';
import {
transferCurrentComplicationUserInfo,
2024-05-20 10:54:13 +01:00
updateApplicationContext,
useInstalled,
2024-11-08 21:33:35 -04:00
usePaired,
2024-05-20 10:54:13 +01:00
useReachability,
watchEvents,
} from 'react-native-watch-connectivity';
2024-05-18 11:36:16 -04:00
import { MultisigHDWallet } from '../class';
import loc from '../loc';
2024-05-20 10:54:13 +01:00
import { Chain } from '../models/bitcoinUnits';
import { FiatUnit } from '../models/fiatUnit';
2024-05-31 13:18:01 -04:00
import { useSettings } from '../hooks/context/useSettings';
import { useStorage } from '../hooks/context/useStorage';
2024-11-11 18:29:45 -04:00
import { isNotificationsEnabled, majorTomToGroundControl } from '../blue_modules/notifications';
import { LightningTransaction, Transaction } from '../class/wallets/types';
2020-07-18 20:33:43 +01:00
2024-11-08 23:00:38 -04:00
interface Message {
request?: string;
message?: string;
walletIndex?: number;
amount?: number;
description?: string;
hideBalance?: boolean;
}
interface Reply {
(response: Record<string, any>): void;
}
interface LightningInvoiceCreateRequest {
walletIndex: number;
amount: number;
description?: string;
}
export function useWatchConnectivity() {
const { walletsInitialized, wallets, fetchWalletTransactions, saveToDisk, txMetadata } = useStorage();
2024-04-17 21:05:48 -04:00
const { preferredFiatCurrency } = useSettings();
const isReachable = useReachability();
2024-11-08 21:33:35 -04:00
const isInstalled = useInstalled();
const isPaired = usePaired();
const messagesListenerActive = useRef(false);
const lastPreferredCurrency = useRef(FiatUnit.USD.endPointKey);
const createContextPayload = () => ({
randomID: `${Date.now()}${Math.floor(Math.random() * 1000)}`,
});
useEffect(() => {
2024-11-08 22:48:13 -04:00
if (!isInstalled || !isPaired || !walletsInitialized || !isReachable) return;
2024-11-08 21:33:35 -04:00
const contextPayload = createContextPayload();
try {
updateApplicationContext(contextPayload);
console.debug('Transferred user info:', contextPayload);
} catch (error) {
console.error('Failed to transfer user info:', error);
}
2024-11-08 21:33:35 -04:00
}, [isReachable, walletsInitialized, isInstalled, isPaired]);
useEffect(() => {
2024-11-08 22:48:13 -04:00
if (!isInstalled || !isPaired || !walletsInitialized || !isReachable || !preferredFiatCurrency) return;
2024-11-08 21:33:35 -04:00
2024-11-08 22:38:58 -04:00
if (lastPreferredCurrency.current !== preferredFiatCurrency.endPointKey) {
try {
const currencyPayload = { preferredFiatCurrency: preferredFiatCurrency.endPointKey };
transferCurrentComplicationUserInfo(currencyPayload);
2024-11-08 22:38:58 -04:00
lastPreferredCurrency.current = preferredFiatCurrency.endPointKey;
console.debug('Apple Watch: updated preferred fiat currency', currencyPayload);
2024-11-08 21:33:35 -04:00
} catch (error) {
console.error('Error updating preferredFiatCurrency on watch:', error);
}
2024-11-08 21:33:35 -04:00
} else {
console.debug('WatchConnectivity: preferred currency has not changed');
}
2024-11-08 22:48:13 -04:00
}, [preferredFiatCurrency, walletsInitialized, isReachable, isInstalled, isPaired]);
2019-05-02 16:33:03 -04:00
2024-11-08 22:48:13 -04:00
const handleLightningInvoiceCreateRequest = useCallback(
2024-11-08 23:00:38 -04:00
async ({ walletIndex, amount, description = loc.lnd.placeholder }: LightningInvoiceCreateRequest): Promise<string | undefined> => {
2024-11-08 22:48:13 -04:00
const wallet = wallets[walletIndex];
if (wallet.allowReceive() && amount > 0) {
try {
2024-11-08 23:00:38 -04:00
if ('addInvoice' in wallet) {
const invoiceRequest = await wallet.addInvoice(amount, description);
2024-11-11 18:29:45 -04:00
if (await isNotificationsEnabled()) {
2024-11-08 23:00:38 -04:00
const decoded = await wallet.decodeInvoice(invoiceRequest);
2024-11-11 18:29:45 -04:00
majorTomToGroundControl([], [decoded.payment_hash], []);
2024-11-08 23:00:38 -04:00
return invoiceRequest;
}
console.debug('Created Lightning invoice:', { invoiceRequest });
2024-11-08 23:00:38 -04:00
return invoiceRequest;
}
2024-11-08 22:48:13 -04:00
} catch (invoiceError) {
console.error('Error creating invoice:', invoiceError);
}
2019-05-02 16:33:03 -04:00
}
2024-11-08 22:48:13 -04:00
},
[wallets],
);
2019-05-02 16:33:03 -04:00
2024-11-08 21:33:35 -04:00
const constructWalletsToSendToWatch = useCallback(async () => {
if (!Array.isArray(wallets) || !walletsInitialized) return;
2024-11-08 22:48:13 -04:00
const walletsToProcess = await Promise.allSettled(
2024-11-08 21:33:35 -04:00
wallets.map(async wallet => {
try {
const receiveAddress = wallet.chain === Chain.ONCHAIN ? await wallet.getAddressAsync() : wallet.getAddress();
2024-11-08 23:00:38 -04:00
const transactions: Transaction[] = wallet
.getTransactions()
.slice(0, 10)
.map((transaction: Transaction & LightningTransaction) => ({
type: determineTransactionType(transaction),
amount: transaction.value ?? 0,
memo:
'hash' in (transaction as Transaction)
? txMetadata[(transaction as Transaction).hash]?.memo || transaction.memo || ''
: transaction.memo || '',
time: transaction.received ?? transaction.time,
2024-11-08 23:00:38 -04:00
}));
2024-11-08 22:48:13 -04:00
const walletData = {
2024-11-08 22:48:13 -04:00
label: wallet.getLabel(),
balance: Number(wallet.getBalance()),
2024-11-08 22:48:13 -04:00
type: wallet.type,
preferredBalanceUnit: wallet.getPreferredBalanceUnit(),
receiveAddress,
transactions,
chain: wallet.chain,
hideBalance: wallet.hideBalance ? 1 : 0,
2024-11-08 22:48:13 -04:00
...(wallet.chain === Chain.ONCHAIN &&
wallet.type !== MultisigHDWallet.type && {
xpub: wallet.getXpub() || wallet.getSecret(),
}),
2024-11-08 23:00:38 -04:00
...(wallet.allowBIP47() &&
wallet.isBIP47Enabled() &&
'getBIP47PaymentCode' in wallet && { paymentCode: wallet.getBIP47PaymentCode() }),
2024-11-08 22:48:13 -04:00
};
console.debug('Constructed wallet data for watch:', {
label: walletData.label,
type: walletData.type,
preferredBalanceUnit: walletData.preferredBalanceUnit,
transactionCount: transactions.length,
2024-11-08 22:48:13 -04:00
});
return walletData;
} catch (error) {
console.error('Failed to construct wallet data:', error);
return null;
2024-11-08 22:48:13 -04:00
}
2024-11-08 21:33:35 -04:00
}),
);
2024-11-08 22:48:13 -04:00
const processedWallets = walletsToProcess
.filter(result => result.status === 'fulfilled' && result.value !== null)
2024-11-08 23:00:38 -04:00
.map(result => (result as PromiseFulfilledResult<any>).value);
2024-11-08 22:48:13 -04:00
console.debug('Constructed wallets to process for Apple Watch:', {
walletCount: processedWallets.length,
walletLabels: processedWallets.map(wallet => wallet.label),
});
return { wallets: processedWallets, randomID: `${Date.now()}${Math.floor(Math.random() * 1000)}` };
2024-11-08 21:33:35 -04:00
}, [wallets, walletsInitialized, txMetadata]);
const determineTransactionType = (transaction: Transaction & LightningTransaction): string => {
const confirmations = (transaction as Transaction).confirmations ?? 0;
if (confirmations < 3) {
return 'pending_transaction';
}
if (transaction.type === 'bitcoind_tx') {
return 'onchain';
}
if (transaction.type === 'paid_invoice') {
return 'offchain';
}
if (transaction.type === 'user_invoice' || transaction.type === 'payment_request') {
const currentDate = new Date();
const now = Math.floor(currentDate.getTime() / 1000);
const timestamp = transaction.timestamp ?? 0;
const expireTime = transaction.expire_time ?? 0;
const invoiceExpiration = timestamp + expireTime;
if (!transaction.ispaid && invoiceExpiration < now) {
return 'expired_transaction';
} else {
return 'incoming_transaction';
}
}
if ((transaction.value ?? 0) < 0) {
return 'outgoing_transaction';
} else {
return 'incoming_transaction';
}
};
const handleMessages = useCallback(
async (message: Message, reply: Reply) => {
console.debug('Received message from Apple Watch:', message);
try {
if (message.request === 'createInvoice' && typeof message.walletIndex === 'number' && typeof message.amount === 'number') {
const createInvoiceRequest = await handleLightningInvoiceCreateRequest({
walletIndex: message.walletIndex,
amount: message.amount,
description: message.description,
});
reply({ invoicePaymentRequest: createInvoiceRequest });
} else if (message.message === 'sendApplicationContext') {
const walletsToProcess = await constructWalletsToSendToWatch();
if (walletsToProcess) {
updateApplicationContext(walletsToProcess);
console.debug('Transferred user info on request:', walletsToProcess);
}
} else if (message.message === 'fetchTransactions') {
await fetchWalletTransactions();
await saveToDisk();
reply({});
} else if (
message.message === 'hideBalance' &&
typeof message.walletIndex === 'number' &&
typeof message.hideBalance === 'boolean' &&
message.walletIndex >= 0 &&
message.walletIndex < wallets.length
) {
wallets[message.walletIndex].hideBalance = message.hideBalance;
await saveToDisk();
reply({});
}
} catch (error) {
console.error('Error handling message:', error);
reply({});
}
},
[fetchWalletTransactions, saveToDisk, wallets, constructWalletsToSendToWatch, handleLightningInvoiceCreateRequest],
);
useEffect(() => {
if (!isInstalled || !isPaired || !walletsInitialized) return;
const sendWalletData = async () => {
try {
const walletsToProcess = await constructWalletsToSendToWatch();
if (walletsToProcess) {
updateApplicationContext(walletsToProcess);
console.debug('Apple Watch: sent wallet data via transferUserInfo', walletsToProcess);
}
} catch (error) {
console.error('Failed to send wallets to watch:', error);
}
};
sendWalletData();
}, [walletsInitialized, isInstalled, isPaired, constructWalletsToSendToWatch]);
useEffect(() => {
if (!isInstalled) return;
const unsubscribe = watchEvents.addListener('message', (message: any) => {
if (message.request === 'wakeUpApp') {
console.debug('Received wake-up request from Apple Watch');
} else {
handleMessages(message, () => {});
}
});
messagesListenerActive.current = true;
console.debug('Message listener set up for Apple Watch');
return () => {
unsubscribe();
messagesListenerActive.current = false;
console.debug('Message listener for Apple Watch cleaned up');
};
}, [isInstalled, handleMessages]);
}
2020-10-12 12:36:35 -04:00
export default useWatchConnectivity;