Skip to content

Commit

Permalink
fix: async beignet wallet
Browse files Browse the repository at this point in the history
  • Loading branch information
limpbrains committed Nov 20, 2024
1 parent ff16301 commit 4a3cc1c
Show file tree
Hide file tree
Showing 16 changed files with 193 additions and 128 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
"@synonymdev/slashtags-widget-price-feed": "1.1.0",
"@synonymdev/web-relay": "1.0.7",
"bech32": "2.0.0",
"beignet": "0.0.46",
"beignet": "0.0.48",
"bip21": "2.0.3",
"bip32": "4.0.0",
"bip39": "3.1.0",
Expand Down
12 changes: 5 additions & 7 deletions src/AppOnboarded.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import RootNavigator from './navigation/root/RootNavigator';
import InactivityTracker from './components/InactivityTracker';
import { showToast } from './utils/notifications';
import { startWalletServices } from './utils/startup';
import { getOnChainWalletElectrum } from './utils/wallet';
import { getOnChainWalletElectrumAsync } from './utils/wallet';
import { unsubscribeFromLightningSubscriptions } from './utils/lightning';
import { useAppSelector } from './hooks/redux';
import { dispatch } from './store/helpers';
Expand All @@ -25,8 +25,6 @@ import {
import { updateSettings } from './store/slices/settings';
// import { updateExchangeRates } from './store/actions/wallet';

const electrum = getOnChainWalletElectrum();

const AppOnboarded = (): ReactElement => {
const { t } = useTranslation('other');
const appState = useRef(AppState.currentState);
Expand Down Expand Up @@ -59,24 +57,24 @@ const AppOnboarded = (): ReactElement => {
// on AppState change
const appStateSubscription = AppState.addEventListener(
'change',
(nextAppState) => {
async (nextAppState) => {
dispatch(updateUi({ appState: nextAppState }));

const electrum = await getOnChainWalletElectrumAsync();
// on App to foreground
if (
appState.current.match(/inactive|background/) &&
nextAppState === 'active'
) {
// resubscribe to electrum connection changes
electrum?.startConnectionPolling();
electrum.startConnectionPolling();
}

// on App to background
if (
appState.current.match(/active|inactive/) &&
nextAppState === 'background'
) {
electrum?.stopConnectionPolling();
electrum.stopConnectionPolling();
}

appState.current = nextAppState;
Expand Down
23 changes: 23 additions & 0 deletions src/hooks/wallet.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { Wallet as TWallet } from 'beignet';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';

import { useAppDispatch, useAppSelector } from '../hooks/redux';
Expand All @@ -9,6 +11,7 @@ import { ignoreSwitchUnitToast } from '../store/slices/user';
import { EUnit } from '../store/types/wallet';
import i18n from '../utils/i18n';
import { showToast } from '../utils/notifications';
import { getOnChainWalletAsync } from '../utils/wallet';
import { useCurrency } from './displayValues';

/**
Expand Down Expand Up @@ -63,3 +66,23 @@ export const useSwitchUnitAnnounced = (): (() => void) => {

return switchUnitAnnounced;
};

/**
* Wait for the onchain wallet to be loaded.
*/
export const useOnchainWallet = (): { wallet: TWallet | null } => {
const [wallet, setWallet] = useState<TWallet | null>(null);

useEffect(() => {
const getWallet = async (): Promise<void> => {
const w = await getOnChainWalletAsync();
setWallet(w);
};

getWallet();
}, []);

return {
wallet,
};
};
15 changes: 12 additions & 3 deletions src/screens/Activity/ActivityDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ import type {
RootStackScreenProps,
} from '../../navigation/types';
import { i18nTime } from '../../utils/i18n';
import { useSwitchUnit } from '../../hooks/wallet';
import { useOnchainWallet, useSwitchUnit } from '../../hooks/wallet';
import { contactsSelector } from '../../store/reselect/slashtags';
import { ETransferStatus } from '../../store/types/wallet';

Expand Down Expand Up @@ -157,6 +157,7 @@ const OnchainActivityDetail = ({
const isSend = txType === EPaymentType.sent;
const total = isSend ? fee + value : value;

const { wallet } = useOnchainWallet();
const { t } = useTranslation('wallet');
const { t: tTime } = useTranslation('intl', { i18n: i18nTime });
const switchUnit = useSwitchUnit();
Expand Down Expand Up @@ -210,17 +211,21 @@ const OnchainActivityDetail = ({
}, [confirmed, isBoosted, txId]);

const boostedParents = useMemo(() => {
if (!wallet) {
return [];
}
return getBoostedTransactionParents({
wallet,
txId,
boostedTransactions,
});
}, [boostedTransactions, txId]);
}, [boostedTransactions, txId, wallet]);

const hasBoostedParents = useMemo(() => {
return boostedParents.length > 0;
}, [boostedParents.length]);

const handleBoostParentPress = (parentTxId): void => {
const handleBoostParentPress = (parentTxId: string): void => {
const activityItem = activityItems.find((i) => {
return i.activityType === EActivityType.onchain && i.txId === parentTxId;
});
Expand Down Expand Up @@ -301,6 +306,10 @@ const OnchainActivityDetail = ({
return <View />;
}, [txDetails]);

if (!wallet) {
return <ActivityIndicator />;
}

let fees = fee;
let paymentAmount = value;
let status = (
Expand Down
4 changes: 2 additions & 2 deletions src/screens/Settings/GapLimit/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { gapLimitOptionsSelector } from '../../../store/reselect/wallet';
import { ScrollView, TextInput, View } from '../../../styles/components';
import { Caption13Up } from '../../../styles/text';
import { showToast } from '../../../utils/notifications';
import { getOnChainWallet, refreshWallet } from '../../../utils/wallet';
import { getOnChainWalletAsync, refreshWallet } from '../../../utils/wallet';

const GapLimit = ({}: SettingsScreenProps<'GapLimit'>): ReactElement => {
const { t } = useTranslation('settings');
Expand Down Expand Up @@ -68,7 +68,7 @@ const GapLimit = ({}: SettingsScreenProps<'GapLimit'>): ReactElement => {

const saveGapLimit = async (): Promise<void> => {
setLoading(true);
const wallet = getOnChainWallet();
const wallet = await getOnChainWalletAsync();
const res = wallet.updateGapLimit({
lookAhead: Number(lookAhead),
lookBehind: Number(lookBehind),
Expand Down
49 changes: 25 additions & 24 deletions src/store/actions/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,12 @@ import {
createDefaultWallet,
getCurrentWallet,
getOnChainWallet,
getOnChainWalletAsync,
getOnChainWalletTransaction,
getOnChainWalletTransactionAsync,
getSelectedNetwork,
getSelectedWallet,
refreshWallet,
waitForWallet,
} from '../../utils/wallet';
import {
dispatch,
Expand All @@ -38,7 +39,7 @@ import {
getWalletStore,
} from '../helpers';
import { EAvailableNetwork } from '../../utils/networks';
import { removeKeyFromObject } from '../../utils/helpers';
import { removeKeyFromObject, sleep } from '../../utils/helpers';
import { TGetImpactedAddressesRes } from '../types/checks';
import { updateActivityList } from '../utils/activity';
import { ETransactionSpeed } from '../types/settings';
Expand Down Expand Up @@ -94,6 +95,7 @@ export const createWalletThunk = async ({
return err(response.error.message);
}
dispatch(createWallet(response.value));
await sleep(1000); // give Beignet some time to propagate the data
dispatch(setWalletExits());
return ok('');
} catch (e) {
Expand Down Expand Up @@ -125,7 +127,7 @@ export const generateNewReceiveAddress = async ({
keyDerivationPath?: IKeyDerivationPath;
}): Promise<Result<IAddress>> => {
try {
const wallet = getOnChainWallet();
const wallet = await getOnChainWalletAsync();
return wallet.generateNewReceiveAddress({ addressType, keyDerivationPath });
} catch (e) {
console.log(e);
Expand All @@ -138,22 +140,22 @@ export const generateNewReceiveAddress = async ({
* @returns {Promise<string>}
*/
export const clearUtxos = async (): Promise<string> => {
const wallet = getOnChainWallet();
const wallet = await getOnChainWalletAsync();
return await wallet.clearUtxos();
};

export const updateWalletBalance = ({
balance,
}: {
balance: number;
}): Result<string> => {
try {
const wallet = getOnChainWallet();
return wallet.updateWalletBalance({ balance });
} catch (e) {
return err(e);
}
};
// export const updateWalletBalance = ({
// balance,
// }: {
// balance: number;
// }): Result<string> => {
// try {
// const wallet = getOnChainWalletAsync();
// return wallet.updateWalletBalance({ balance });
// } catch (e) {
// return err(e);
// }
// };

/**
* Parses and adds unconfirmed transactions to the store.
Expand Down Expand Up @@ -216,7 +218,7 @@ export const injectFakeTransaction = (
// scanAllAddresses?: boolean;
// replaceStoredTransactions?: boolean;
// }): Promise<Result<string | undefined>> => {
// const wallet = getOnChainWallet();
// const wallet = async getOnChainWalletAsync();
// return await wallet.updateTransactions({
// scanAllAddresses,
// replaceStoredTransactions,
Expand All @@ -233,7 +235,7 @@ export const deleteOnChainTransactionById = async ({
}: {
txid: string;
}): Promise<void> => {
const wallet = getOnChainWallet();
const wallet = await getOnChainWalletAsync();
return await wallet.deleteOnChainTransactionById({ txid });
};

Expand All @@ -255,7 +257,7 @@ export const addBoostedTransaction = async ({
type?: EBoostType;
fee: number;
}): Promise<Result<IBoostedTransaction>> => {
const wallet = getOnChainWallet();
const wallet = await getOnChainWalletAsync();
return await wallet.addBoostedTransaction({
newTxId,
oldTxId,
Expand Down Expand Up @@ -290,7 +292,7 @@ export const setupOnChainTransaction = async ({
outputs?: IOutput[]; // Used to pre-specify outputs to use.
} = {}): Promise<TSetupTransactionResponse> => {
rbf = rbf ?? getSettingsStore().rbf;
const transaction = getOnChainWalletTransaction();
const transaction = await getOnChainWalletTransactionAsync();
return await transaction.setupTransaction({
inputTxHashes,
utxos,
Expand All @@ -310,7 +312,7 @@ export const getChangeAddress = async ({
}: {
addressType?: EAddressType;
}): Promise<Result<IAddress>> => {
const wallet = getOnChainWallet();
const wallet = await getOnChainWalletAsync();
return await wallet.getChangeAddress(addressType);
};

Expand All @@ -331,8 +333,7 @@ export const updateSendTransaction = (
* @returns {Result<string>}
*/
export const resetSendTransaction = async (): Promise<Result<string>> => {
await waitForWallet();
const transaction = getOnChainWalletTransaction();
const transaction = await getOnChainWalletTransactionAsync();
return transaction.resetSendTransaction();
};

Expand All @@ -341,7 +342,7 @@ export const updateSelectedAddressType = async ({
}: {
addressType: EAddressType;
}): Promise<void> => {
const wallet = getOnChainWallet();
const wallet = await getOnChainWalletAsync();
const addressTypesToMonitor = wallet.addressTypesToMonitor;
if (!addressTypesToMonitor.includes(addressType)) {
// Append the new address type so we monitor it in subsequent sessions.
Expand Down
2 changes: 1 addition & 1 deletion src/store/utils/activity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ export const updateOnChainActivityList = async (): Promise<Result<string>> => {
});
const activityItems = await Promise.all(promises);

const boostFormattedItems = formatBoostedActivityItems({
const boostFormattedItems = await formatBoostedActivityItems({
items: activityItems,
boostedTransactions,
selectedWallet,
Expand Down
4 changes: 2 additions & 2 deletions src/store/utils/fees.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { dispatch, getFeesStore } from '../helpers';
import { updateOnchainFees } from '../slices/fees';
import { getFeeEstimates } from '../../utils/wallet/transactions';
import { EAvailableNetwork } from '../../utils/networks';
import { getOnChainWallet, getSelectedNetwork } from '../../utils/wallet';
import { getOnChainWalletAsync, getSelectedNetwork } from '../../utils/wallet';
import { IOnchainFees } from 'beignet';

export const REFRESH_INTERVAL = 60 * 30; // in seconds, 30 minutes
Expand Down Expand Up @@ -46,6 +46,6 @@ export const refreshOnchainFeeEstimates = async ({
}: {
forceUpdate?: boolean;
}): Promise<Result<IOnchainFees>> => {
const wallet = getOnChainWallet();
const wallet = await getOnChainWalletAsync();
return await wallet.updateFeeEstimates(forceUpdate);
};
Loading

0 comments on commit 4a3cc1c

Please sign in to comment.