<commit_before>import { useState, useEffect } from 'react';
import usePrevious from 'hooks/usePrevious';
import useInterval from './useInterval';
import useBCH from 'hooks/useBCH';
import BigNumber from 'bignumber.js';
import Bitcoin from '@psf/bitcoincashjs-lib';
import coininfo from 'utils/coininfo';
import {
    loadStoredWallet,
    isValidStoredWallet,
    isLegacyMigrationRequired,
    getHashArrayFromWallet,
    isActiveWebsocket,
    getWalletBalanceFromUtxos,
    toHash160,
} from 'utils/cashMethods';
import {
    isValidCashtabSettings,
    isValidCashtabCache,
    isValidContactList,
    parseInvalidSettingsForMigration,
} from 'utils/validation';
import localforage from 'localforage';
import { currency } from 'components/Common/Ticker';
import {
    xecReceivedNotification,
    xecReceivedNotificationWebsocket,
    eTokenReceivedNotification,
} from 'components/Common/Notifications';
import {
    getUtxosChronik,
    organizeUtxosByType,
    getPreliminaryTokensArray,
    finalizeTokensArray,
    finalizeSlpUtxos,
    getTxHistoryChronik,
    parseChronikTx,
} from 'utils/chronik';
import { ChronikClient } from 'chronik-client';
// For XEC, eCash chain:
const chronik = new ChronikClient(currency.chronikUrl);
import cashaddr from 'ecashaddrjs';

const useWallet = () => {
    const [walletRefreshInterval, setWalletRefreshInterval] = useState(
        currency.websocketDisconnectedRefreshInterval,
    );
    const [wallet, setWallet] = useState(false);
    const [chronikWebsocket, setChronikWebsocket] = useState(null);
    const [contactList, setContactList] = useState([{}]);
    const [cashtabSettings, setCashtabSettings] = useState(false);
    const [cashtabCache, setCashtabCache] = useState(
        currency.defaultCashtabCache,
    );
    const [fiatPrice, setFiatPrice] = useState(null);
    const [apiError, setApiError] = useState(false);
    const [checkFiatInterval, setCheckFiatInterval] = useState(null);
    const [hasUpdated, setHasUpdated] = useState(false);
    const { getBCH } = useBCH();
    const [loading, setLoading] = useState(true);
    const [apiIndex, setApiIndex] = useState(0);
    const [BCH, setBCH] = useState(getBCH(apiIndex));
    const { balances, tokens } = isValidStoredWallet(wallet)
        ? wallet.state
        : {
              balances: {},
              tokens: [],
              utxos: null,
          };
    const previousBalances = usePrevious(balances);
    const previousTokens = usePrevious(tokens);

    // If you catch API errors, call this function
    const tryNextAPI = () => {
        let currentApiIndex = apiIndex;
        // How many APIs do you have?
        const apiString = process.env.REACT_APP_BCHA_APIS;

        const apiArray = apiString.split(',');

        console.log(`You have ${apiArray.length} APIs to choose from`);
        console.log(`Current selection: ${apiIndex}`);
        // If only one, exit
        if (apiArray.length === 0) {
            console.log(
                `There are no backup APIs, you are stuck with this error`,
            );
            return;
        } else if (currentApiIndex < apiArray.length - 1) {
            currentApiIndex += 1;
            console.log(
                `Incrementing API index from ${apiIndex} to ${currentApiIndex}`,
            );
        } else {
            // Otherwise use the first option again
            console.log(`Retrying first API index`);
            currentApiIndex = 0;
        }
        //return setApiIndex(currentApiIndex);
        console.log(`Setting Api Index to ${currentApiIndex}`);
        setApiIndex(currentApiIndex);
        return setBCH(getBCH(currentApiIndex));
        // If you have more than one, use the next one
        // If you are at the "end" of the array, use the first one
    };

    const deriveAccount = async (BCH, { masterHDNode, path }) => {
        const node = BCH.HDNode.derivePath(masterHDNode, path);

        // temporary comparison
        const localNode = masterHDNode.derivePath(path);
        if (JSON.stringify(node) === JSON.stringify(localNode)) {
            console.log(path + ': derivePath() output match');
        }

        const publicKey = BCH.HDNode.toPublicKey(node).toString('hex');

        // temporary comparison
        const localPublicKey = localNode.getPublicKeyBuffer().toString('hex');
        if (publicKey === localPublicKey) {
            console.log(path + ': getPublicKeyBuffer() output match');
        }

        const cashAddress = BCH.HDNode.toCashAddress(node);

        // temporary comparison
        const localCashAddress = cashaddr.encode(
            'bitcoincash',
            'P2PKH',
            localNode.getIdentifier(),
        );
        if (cashAddress === localCashAddress) {
            console.log(path + ': toCashAddress output match');
        }

        const hash160 = toHash160(cashAddress);
        const slpAddress = BCH.SLP.Address.toSLPAddress(cashAddress);

        // temporary comparison
        // see return statement for original toWIF
        const localFundingWif = localNode.keyPair.toWIF();
        if (BCH.HDNode.toWIF(node) === localFundingWif) {
            console.log(path + ': toWIF() output match');
        }

        return {
            publicKey,
            hash160,
            cashAddress,
            slpAddress,
            fundingWif: BCH.HDNode.toWIF(node),<commit_msg>[Cashtab] [BCH Deprecation] [HD Node] Pt 3/3 - Deprecate BCH.HDNode<commit_after>import { useState, useEffect } from 'react';
import usePrevious from 'hooks/usePrevious';
import useInterval from './useInterval';
import useBCH from 'hooks/useBCH';
import BigNumber from 'bignumber.js';
import Bitcoin from '@psf/bitcoincashjs-lib';
import coininfo from 'utils/coininfo';
import {
    loadStoredWallet,
    isValidStoredWallet,
    isLegacyMigrationRequired,
    getHashArrayFromWallet,
    isActiveWebsocket,
    getWalletBalanceFromUtxos,
    toHash160,
} from 'utils/cashMethods';
import {
    isValidCashtabSettings,
    isValidCashtabCache,
    isValidContactList,
    parseInvalidSettingsForMigration,
} from 'utils/validation';
import localforage from 'localforage';
import { currency } from 'components/Common/Ticker';
import {
    xecReceivedNotification,
    xecReceivedNotificationWebsocket,
    eTokenReceivedNotification,
} from 'components/Common/Notifications';
import {
    getUtxosChronik,
    organizeUtxosByType,
    getPreliminaryTokensArray,
    finalizeTokensArray,
    finalizeSlpUtxos,
    getTxHistoryChronik,
    parseChronikTx,
} from 'utils/chronik';
import { ChronikClient } from 'chronik-client';
// For XEC, eCash chain:
const chronik = new ChronikClient(currency.chronikUrl);
import cashaddr from 'ecashaddrjs';

const useWallet = () => {
    const [walletRefreshInterval, setWalletRefreshInterval] = useState(
        currency.websocketDisconnectedRefreshInterval,
    );
    const [wallet, setWallet] = useState(false);
    const [chronikWebsocket, setChronikWebsocket] = useState(null);
    const [contactList, setContactList] = useState([{}]);
    const [cashtabSettings, setCashtabSettings] = useState(false);
    const [cashtabCache, setCashtabCache] = useState(
        currency.defaultCashtabCache,
    );
    const [fiatPrice, setFiatPrice] = useState(null);
    const [apiError, setApiError] = useState(false);
    const [checkFiatInterval, setCheckFiatInterval] = useState(null);
    const [hasUpdated, setHasUpdated] = useState(false);
    const { getBCH } = useBCH();
    const [loading, setLoading] = useState(true);
    const [apiIndex, setApiIndex] = useState(0);
    const [BCH, setBCH] = useState(getBCH(apiIndex));
    const { balances, tokens } = isValidStoredWallet(wallet)
        ? wallet.state
        : {
              balances: {},
              tokens: [],
              utxos: null,
          };
    const previousBalances = usePrevious(balances);
    const previousTokens = usePrevious(tokens);

    // If you catch API errors, call this function
    const tryNextAPI = () => {
        let currentApiIndex = apiIndex;
        // How many APIs do you have?
        const apiString = process.env.REACT_APP_BCHA_APIS;

        const apiArray = apiString.split(',');

        console.log(`You have ${apiArray.length} APIs to choose from`);
        console.log(`Current selection: ${apiIndex}`);
        // If only one, exit
        if (apiArray.length === 0) {
            console.log(
                `There are no backup APIs, you are stuck with this error`,
            );
            return;
        } else if (currentApiIndex < apiArray.length - 1) {
            currentApiIndex += 1;
            console.log(
                `Incrementing API index from ${apiIndex} to ${currentApiIndex}`,
            );
        } else {
            // Otherwise use the first option again
            console.log(`Retrying first API index`);
            currentApiIndex = 0;
        }
        //return setApiIndex(currentApiIndex);
        console.log(`Setting Api Index to ${currentApiIndex}`);
        setApiIndex(currentApiIndex);
        return setBCH(getBCH(currentApiIndex));
        // If you have more than one, use the next one
        // If you are at the "end" of the array, use the first one
    };

    const deriveAccount = async (BCH, { masterHDNode, path }) => {
        const node = masterHDNode.derivePath(path);
        const publicKey = node.getPublicKeyBuffer().toString('hex');
        const cashAddress = cashaddr.encode(
            'bitcoincash',
            'P2PKH',
            node.getIdentifier(),
        );
        const hash160 = toHash160(cashAddress);
        const slpAddress = BCH.SLP.Address.toSLPAddress(cashAddress);

        return {
            publicKey,
            hash160,
            cashAddress,
            slpAddress,
            fundingWif: node.keyPair.toWIF(),
{'fraction_non_alphanumeric': 0.10373907742328795, 'fraction_numerical': 0.003861003861003861, 'mean_word_length': 2.7727098505174395, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '801873', 'n_tokens_mistral': 2854, 'n_tokens_neox': 2860, 'n_words': 676}