From ae8b058650a934d941caaaaae99f5f26a0f1e3ea Mon Sep 17 00:00:00 2001 From: zzggo Date: Wed, 5 Feb 2025 15:54:17 +1100 Subject: [PATCH 1/3] fixed: user address not being displayed when clicked button before fully loaded --- src/ui/hooks/useProfileHook.ts | 19 +- src/ui/stores/useProfileStore.ts | 48 ++- src/ui/views/EvmMove/MoveFromEvm/index.tsx | 48 ++- src/ui/views/EvmMove/MoveFromFlow/index.tsx | 40 +-- .../EvmMove/MoveFromParent/MoveToken.tsx | 299 ---------------- src/ui/views/EvmMove/MoveFromParent/index.tsx | 325 ------------------ src/ui/views/EvmMove/TransferFrom.tsx | 10 +- src/ui/views/EvmMove/TransferTo.tsx | 26 +- 8 files changed, 83 insertions(+), 732 deletions(-) delete mode 100644 src/ui/views/EvmMove/MoveFromParent/MoveToken.tsx delete mode 100644 src/ui/views/EvmMove/MoveFromParent/index.tsx diff --git a/src/ui/hooks/useProfileHook.ts b/src/ui/hooks/useProfileHook.ts index 3f231275..d07851fe 100644 --- a/src/ui/hooks/useProfileHook.ts +++ b/src/ui/hooks/useProfileHook.ts @@ -17,7 +17,6 @@ export const useProfileHook = () => { const { setMainAddress, setEvmAddress, - setUserWallet, setInitial, setChildAccount, setCurrent, @@ -28,6 +27,7 @@ export const useProfileHook = () => { setOtherAccounts, setLoggedInAccounts, setWalletList, + setParentWallet, initialStart, } = useProfileStore(); @@ -93,6 +93,7 @@ export const useProfileHook = () => { const freshUserInfo = useCallback(async () => { if (!usewallet || !walletLoaded) return; try { + //TODO: should rethink the wording of the wallet functions, have it be parent evm and child or something similar. State name and should be the same frontend and background. const [currentWallet, isChild, mainAddress] = await Promise.all([ usewallet.getCurrentWallet(), usewallet.getActiveWallet(), @@ -102,14 +103,14 @@ export const useProfileHook = () => { if (!currentWallet) { throw new Error('Current wallet is undefined'); } - + const mainwallet = await usewallet.returnMainWallet(); + setParentWallet(mainwallet!); if (isChild === 'evm') { const evmWalletData = await setupEvmWallet(mainAddress!); await setCurrent(evmWalletData); } else if (isChild) { await setCurrent(currentWallet); } else { - const mainwallet = await usewallet.returnMainWallet(); await setCurrent(mainwallet); } @@ -155,6 +156,7 @@ export const useProfileHook = () => { setCurrent, setupEvmWallet, setMainLoading, + setParentWallet, ]); // 1. First called in index.ts, get the user info(name and avatar) and the main address @@ -177,22 +179,13 @@ export const useProfileHook = () => { const wallet: WalletResponse[] = await usewallet.getUserWallets(); const fData: WalletResponse[] = wallet.filter((item) => item.blockchain !== null); - setUserWallet(fData); if (initialStart) { await usewallet.openapi.putDeviceInfo(fData); setInitial(false); } const formattedWallets = formatWallets(fData); setWalletList(formattedWallets); - }, [ - usewallet, - initialStart, - setUserWallet, - setInitial, - formatWallets, - setWalletList, - walletLoaded, - ]); + }, [usewallet, initialStart, setInitial, formatWallets, setWalletList, walletLoaded]); // 3. Third called in index.ts check the child account and set the child account const fetchUserWallet = useCallback(async () => { diff --git a/src/ui/stores/useProfileStore.ts b/src/ui/stores/useProfileStore.ts index f76dd223..f0bc8658 100644 --- a/src/ui/stores/useProfileStore.ts +++ b/src/ui/stores/useProfileStore.ts @@ -7,12 +7,12 @@ import type { ChildAccount, WalletType, UserInfoResponse } from '../../shared/ty interface ProfileState { mainAddress: string; evmAddress: string; - userWallet: any | null; currentWalletIndex: number; + parentWallet: WalletType; evmWallet: WalletType; - walletList: any[]; + walletList: WalletType[]; initialStart: boolean; - currentWallet: any; + currentWallet: WalletType; mainAddressLoading: boolean; childAccounts: ChildAccount; evmLoading: boolean; @@ -22,8 +22,8 @@ interface ProfileState { loggedInAccounts: LoggedInAccount[]; setMainAddress: (address: string) => void; setEvmAddress: (address: string) => void; - setUserWallet: (wallet: any) => void; setCurrentWalletIndex: (index: number) => void; + setParentWallet: (wallet: WalletType) => void; setEvmWallet: (wallet: WalletType) => void; setWalletList: (list: any[]) => void; setInitial: (initial: boolean) => void; @@ -38,21 +38,23 @@ interface ProfileState { clearProfileData: () => void; } +const INITIAL_WALLET = { + name: '', + icon: '', + address: '', + chain_id: 'flow', + id: 1, + coins: ['flow'], + color: '', +}; + export const useProfileStore = create((set) => ({ mainAddress: '', evmAddress: '', - userWallet: null, currentWalletIndex: 0, - evmWallet: { - name: '', - icon: '', - address: '', - chain_id: 'evm', - id: 1, - coins: ['flow'], - color: '', - }, - currentWallet: {}, + parentWallet: { ...INITIAL_WALLET }, + evmWallet: { ...INITIAL_WALLET, chain_id: 'evm' }, + currentWallet: { ...INITIAL_WALLET }, walletList: [], initialStart: true, mainAddressLoading: true, @@ -64,8 +66,8 @@ export const useProfileStore = create((set) => ({ listLoading: true, setMainAddress: (address) => set({ mainAddress: address }), setEvmAddress: (address) => set({ evmAddress: address }), - setUserWallet: (wallet) => set({ userWallet: wallet }), setCurrentWalletIndex: (index) => set({ currentWalletIndex: index }), + setParentWallet: (wallet) => set({ parentWallet: wallet }), setEvmWallet: (wallet) => set({ evmWallet: wallet }), setWalletList: (list) => set({ walletList: list }), setInitial: (initial) => set({ initialStart: initial }), @@ -81,20 +83,12 @@ export const useProfileStore = create((set) => ({ set({ mainAddress: '', evmAddress: '', - userWallet: null, currentWalletIndex: 0, - evmWallet: { - name: '', - icon: '', - address: '', - chain_id: 'evm', - id: 1, - coins: ['flow'], - color: '', - }, + parentWallet: { ...INITIAL_WALLET }, + evmWallet: { ...INITIAL_WALLET, chain_id: 'evm' }, walletList: [], initialStart: true, - currentWallet: {}, + currentWallet: { ...INITIAL_WALLET }, mainAddressLoading: true, childAccounts: {}, evmLoading: true, diff --git a/src/ui/views/EvmMove/MoveFromEvm/index.tsx b/src/ui/views/EvmMove/MoveFromEvm/index.tsx index 2b1441da..414421eb 100644 --- a/src/ui/views/EvmMove/MoveFromEvm/index.tsx +++ b/src/ui/views/EvmMove/MoveFromEvm/index.tsx @@ -6,6 +6,8 @@ import { useHistory } from 'react-router-dom'; import type { Contact } from '@/shared/types/network-types'; import { isValidEthereumAddress, withPrefix } from '@/shared/utils/address'; import { WarningStorageLowSnackbar } from '@/ui/FRWComponent/WarningStorageLowSnackbar'; +import { useCoinStore } from '@/ui/stores/useCoinStore'; +import { useProfileStore } from '@/ui/stores/useProfileStore'; import { useStorageCheck } from '@/ui/utils/useStorageCheck'; import type { CoinItem } from 'background/service/coinList'; import { LLSpinner } from 'ui/FRWComponent'; @@ -60,13 +62,14 @@ const EMPTY_COIN: CoinItem = { const MoveFromEvm = (props: TransferConfirmationProps) => { const usewallet = useWallet(); const history = useHistory(); - const [userWallet, setWallet] = useState(null); + const { parentWallet, evmWallet, userInfo } = useProfileStore(); + const { coins: coinList } = useCoinStore(); + const [currentCoin, setCurrentCoin] = useState('flow'); - const [coinList, setCoinList] = useState([]); // const [exceed, setExceed] = useState(false); const [amount, setAmount] = useState(''); // const [validated, setValidated] = useState(null); - const [userInfo, setUser] = useState(USER_CONTACT); + const [flowUserInfo, setFlowUser] = useState(USER_CONTACT); const [evmUserInfo, setEvmUser] = useState(EVM_CONTACT); const [network, setNetwork] = useState('mainnet'); const [evmAddress, setEvmAddress] = useState(''); @@ -80,41 +83,31 @@ const MoveFromEvm = (props: TransferConfirmationProps) => { coin: currentCoin, // Rendering this component means we are moving from an EVM account // If we are not moving to an EVM account, we are moving to a FLOW account - movingBetweenEVMAndFlow: !isValidEthereumAddress(userInfo.address), + movingBetweenEVMAndFlow: !isValidEthereumAddress(flowUserInfo.address), }); const isLowStorage = isSufficient !== undefined && !isSufficient; // isSufficient is undefined when the storage check is not yet completed const isLowStorageAfterAction = sufficientAfterAction !== undefined && !sufficientAfterAction; const setUserWallet = useCallback(async () => { - // const walletList = await storage.get('userWallet'); - setLoading(true); - const wallet = await usewallet.getMainWallet(); const network = await usewallet.getNetwork(); const token = await usewallet.getCurrentCoin(); setNetwork(network); setCurrentCoin(token); - // userWallet - await setWallet(wallet); - const evmWallet = await usewallet.getEvmWallet(); setEvmAddress(evmWallet.address); - const coinList = await usewallet.getCoinList(); - setCoinList(coinList); const tokenResult = await usewallet.openapi.getEvmTokenInfo(token, network); const coinInfo = coinList.find( (coin) => coin && coin.unit.toLowerCase() === tokenResult!.symbol.toLowerCase() ); setCoinInfo(coinInfo!); - const info = await usewallet.getUserInfo(false); - const userContact = { ...USER_CONTACT, - address: withPrefix(wallet) || '', - avatar: info.avatar, - contact_name: info.username, + address: withPrefix(parentWallet.address) || '', + avatar: userInfo!.avatar, + contact_name: userInfo!.username, }; - setUser(userContact); + setFlowUser(userContact); const evmContact = { ...EVM_CONTACT, @@ -127,18 +120,18 @@ const MoveFromEvm = (props: TransferConfirmationProps) => { // const result = await usewallet.openapi.fetchTokenList(network); setLoading(false); return; - }, [usewallet]); + }, [usewallet, evmWallet, userInfo, coinList, parentWallet]); const moveToken = async () => { setLoading(true); usewallet - .withdrawFlowEvm(amount, userInfo.address) + .withdrawFlowEvm(amount, flowUserInfo.address) .then(async (createRes) => { usewallet.listenTransaction( createRes, true, 'Transfer from EVM complete', - `Your have moved ${amount} Flow to your address ${userWallet}. \nClick to view this transaction.` + `Your have moved ${amount} Flow to your address ${parentWallet.address}. \nClick to view this transaction.` ); await usewallet.setDashIndex(0); history.push('/dashboard?activity=1'); @@ -172,7 +165,7 @@ const MoveFromEvm = (props: TransferConfirmationProps) => { createRes, true, 'Transfer from EVM complete', - `Your have moved ${amount} ${flowId.split('.')[2]} to your address ${userWallet}. \nClick to view this transaction.` + `Your have moved ${amount} ${flowId.split('.')[2]} to your address ${parentWallet.address}. \nClick to view this transaction.` ); await usewallet.setDashIndex(0); history.push('/dashboard?activity=1'); @@ -203,8 +196,11 @@ const MoveFromEvm = (props: TransferConfirmationProps) => { }; useEffect(() => { - setUserWallet(); - }, [setUserWallet]); + setLoading(true); + if (userInfo && coinList.length > 0) { + setUserWallet(); + } + }, [userInfo, coinList, setUserWallet]); useEffect(() => { handleCoinInfo(); @@ -247,7 +243,7 @@ const MoveFromEvm = (props: TransferConfirmationProps) => { - {userWallet && } + {parentWallet.address && } { )} - {evmAddress && } + {evmAddress && } diff --git a/src/ui/views/EvmMove/MoveFromFlow/index.tsx b/src/ui/views/EvmMove/MoveFromFlow/index.tsx index d6081f8d..a18026e6 100644 --- a/src/ui/views/EvmMove/MoveFromFlow/index.tsx +++ b/src/ui/views/EvmMove/MoveFromFlow/index.tsx @@ -6,6 +6,8 @@ import { useHistory } from 'react-router-dom'; import type { Contact } from '@/shared/types/network-types'; import { withPrefix, isValidEthereumAddress } from '@/shared/utils/address'; import { WarningStorageLowSnackbar } from '@/ui/FRWComponent/WarningStorageLowSnackbar'; +import { useCoinStore } from '@/ui/stores/useCoinStore'; +import { useProfileStore } from '@/ui/stores/useProfileStore'; import { useStorageCheck } from '@/ui/utils/useStorageCheck'; import type { CoinItem } from 'background/service/coinList'; import { LLSpinner } from 'ui/FRWComponent'; @@ -75,13 +77,14 @@ const MoveFromFlow = (props: TransferConfirmationProps) => { const usewallet = useWallet(); const history = useHistory(); - const [userWallet, setWallet] = useState(null); + const { evmWallet, mainAddress, currentWallet, userInfo } = useProfileStore(); + const { coins: coinList } = useCoinStore(); + const [currentCoin, setCurrentCoin] = useState('flow'); - const [coinList, setCoinList] = useState([]); // const [exceed, setExceed] = useState(false); const [amount, setAmount] = useState(''); // const [validated, setValidated] = useState(null); - const [userInfo, setUser] = useState(USER_CONTACT); + const [flowUserInfo, setSender] = useState(USER_CONTACT); const [evmUserInfo, setEvmUser] = useState(EVM_CONTACT); const [network, setNetwork] = useState('mainnet'); const [evmAddress, setEvmAddress] = useState(''); @@ -102,32 +105,22 @@ const MoveFromFlow = (props: TransferConfirmationProps) => { const isLowStorageAfterAction = sufficientAfterAction !== undefined && !sufficientAfterAction; const setUserWallet = useCallback(async () => { - // const walletList = await storage.get('userWallet'); - setLoading(true); const token = await usewallet.getCurrentCoin(); console.log('getCurrentCoin ', token); - const wallet = await usewallet.getMainWallet(); const network = await usewallet.getNetwork(); setNetwork(network); setCurrentCoin(token); - // userWallet - await setWallet(wallet); - const coinList = await usewallet.getCoinList(); - setCoinList(coinList); - const evmWallet = await usewallet.getEvmWallet(); - console.log('evmWallet ', evmWallet); setEvmAddress(evmWallet.address); const coinInfo = coinList.find((coin) => coin.unit.toLowerCase() === token.toLowerCase()); setCoinInfo(coinInfo!); - const info = await usewallet.getUserInfo(false); const userContact = { ...USER_CONTACT, - address: withPrefix(wallet) || '', - avatar: info.avatar, - contact_name: info.username, + address: withPrefix(mainAddress) || '', + avatar: userInfo!.avatar, + contact_name: userInfo!.username, }; - setUser(userContact); + setSender(userContact); const evmContact = { ...EVM_CONTACT, @@ -140,7 +133,7 @@ const MoveFromFlow = (props: TransferConfirmationProps) => { setLoading(false); return; - }, [usewallet]); + }, [usewallet, evmWallet, userInfo, coinList, mainAddress]); const moveToken = async () => { setLoading(true); @@ -216,8 +209,11 @@ const MoveFromFlow = (props: TransferConfirmationProps) => { }, [coinList, currentCoin]); useEffect(() => { - setUserWallet(); - }, [setUserWallet]); + setLoading(true); + if (userInfo && coinList.length > 0) { + setUserWallet(); + } + }, [userInfo, coinList, setUserWallet]); useEffect(() => { handleCoinInfo(); @@ -260,7 +256,7 @@ const MoveFromFlow = (props: TransferConfirmationProps) => { - {userWallet && } + {currentWallet && } { )} - {evmAddress && } + {evmAddress && } diff --git a/src/ui/views/EvmMove/MoveFromParent/MoveToken.tsx b/src/ui/views/EvmMove/MoveFromParent/MoveToken.tsx deleted file mode 100644 index aa4430f4..00000000 --- a/src/ui/views/EvmMove/MoveFromParent/MoveToken.tsx +++ /dev/null @@ -1,299 +0,0 @@ -import AttachMoneyRoundedIcon from '@mui/icons-material/AttachMoneyRounded'; -import { - Box, - Typography, - IconButton, - ListItemText, - Select, - MenuItem, - ListItemIcon, - FormControl, - InputAdornment, - Input, - Chip, - Tooltip, -} from '@mui/material'; -import { StyledEngineProvider } from '@mui/material/styles'; -import { makeStyles } from '@mui/styles'; -import BN from 'bignumber.js'; -import React, { useState, useEffect, useCallback } from 'react'; - -import SlideRelative from '@/ui/FRWComponent/SlideRelative'; -import { useCoinStore } from '@/ui/stores/useCoinStore'; - -import CancelIcon from '../../../../components/iconfont/IconClose'; - -const useStyles = makeStyles(() => ({ - customInputLabel: { - '& legend': { - visibility: 'visible', - }, - }, - inputBox: { - minHeight: '64px', - paddingRight: '12px', - paddingLeft: '0', - py: '14px', - zIndex: '999', - fontSize: '24px', - backgroundColor: '#282828', - borderRadius: '12px', - boxSizing: 'border-box', - }, - selectRoot: { - fontFamily: 'IBM Plex Sans, sans-serif', - fontSize: '0.875rem', - boxSizing: 'border-box', - borderRadius: '0.75em', - marginRight: '0', - textAlign: 'left', - lineHeight: '1.5', - display: 'flex', - gap: '8px', - color: '#CDD2D7', - border: '1px solid #282828', - - // &.${selectUnstyledClasses.expanded} { - // &::after { - // content: '▴'; - // } - // } - - // &::after { - // content: '▾'; - // float: right; - // } - '&ul': { - fontFamily: 'IBM Plex Sans, sans-serif', - fontSize: '0.875rem', - boxSizing: 'border-box', - padding: '5px', - margin: '10px 0', - maxHeight: '400px', - backgroundColor: '#282828', - border: 'none', - borderRadius: '0.75em', - color: '#CDD2D7', - overflow: 'auto', - outline: '0px', - }, - '& .MuiOutlinedInput-notchedOutline': { - border: 'none !important', - borderWidth: '0px !important', - outline: 'none !important', - }, - }, - selectList: { - fontFamily: 'IBM Plex Sans, sans-serif', - fontSize: '0.875rem', - boxSizing: 'border-box', - padding: '5px', - margin: '10px 0', - maxHeight: '400px', - backgroundColor: '#282828', - border: '1px solid #787878', - borderRadius: '0.75em', - color: '#CDD2D7', - overflow: 'auto', - outline: '0px', - }, - exceedBox: { - background: 'rgba(196,69,54,0.08)', - display: 'flex', - height: '25px', - }, -})); - -const MoveToken = ({ - amount, - setAmount, - secondAmount, - setSecondAmount, - exceed, - setExceed, - coinInfo, - setCurrentCoin, - coinList, -}) => { - const classes = useStyles(); - const { availableFlow } = useCoinStore(); - const [coin, setCoin] = useState('flow'); - const [coinType, setCoinType] = useState(0); - - const handleMaxClick = () => { - if (coinInfo) { - if (coinInfo.unit.toLowerCase() === 'flow') { - setAmount(availableFlow); - } else { - // const minimumValue = minAmount > 0.001 ? minAmount : 0.001; - const newAmount = coinInfo.balance - 0; - setAmount(newAmount); - } - } - }; - - const renderValue = (option) => { - setCurrentCoin(option); - setCoin(option); - const selectCoin = coinList.find((coin) => coin.unit === option); - return selectCoin && ; - }; - - const swap = () => { - setCoinType(!coinType); - }; - - const currentCoinType = useCallback(() => { - setCoin(coinInfo.unit); - }, [coinInfo.unit]); - - useEffect(() => { - currentCoinType(); - }, [currentCoinType]); - - useEffect(() => { - if (coinType) { - const secondInt = parseInt(secondAmount); - const value = new BN(secondInt).dividedBy(new BN(coinInfo.price)).toNumber(); - if (coinInfo.balance - value < 0) { - setExceed(true); - } else { - setExceed(false); - } - if (isNaN(value)) { - setAmount(0); - } else { - setAmount(parseFloat(value.toFixed(3))); - } - } - }, [coinInfo.balance, coinInfo.price, coinType, secondAmount, setAmount, setExceed]); - - useEffect(() => { - if (!coinType) { - if (coinInfo && amount) { - const result = parseFloat((coinInfo.amountbalance - amount).toPrecision()); - if (coinInfo.balance - amount < 0) { - setExceed(true); - } else if (coin === 'flow' && result < 0.001) { - setExceed(true); - } else { - setExceed(false); - } - const value = new BN(amount).times(new BN(coinInfo.price)).toFixed(3); - setSecondAmount(value); - } - } - }, [amount, coin, coinInfo, coinType, setExceed, setSecondAmount]); - - return ( - - - - - - - { - // let value = event.target.value; - // value = (Math.round(value * 100) / 100).toFixed(2) - setExceed(false); - setAmount(event.target.value); - }} - inputProps={{ sx: { fontSize: '24px' } }} - endAdornment={ - - - - } - /> - - - - {chrome.i18n.getMessage('Balance')} - {coinInfo.balance} - - - - - - - {chrome.i18n.getMessage('Insufficient_balance') + - (coin === 'flow' - ? chrome.i18n.getMessage('on_Flow_the_balance_cant_less_than_0001_FLOW') - : '')} - - - - - - ); -}; - -export default MoveToken; diff --git a/src/ui/views/EvmMove/MoveFromParent/index.tsx b/src/ui/views/EvmMove/MoveFromParent/index.tsx deleted file mode 100644 index a8f1f4fc..00000000 --- a/src/ui/views/EvmMove/MoveFromParent/index.tsx +++ /dev/null @@ -1,325 +0,0 @@ -import CloseIcon from '@mui/icons-material/Close'; -import { Box, Button, Typography, Drawer, IconButton, Grid } from '@mui/material'; -import { ThemeProvider } from '@mui/material/styles'; -import React, { useState, useEffect, useCallback } from 'react'; -import { useHistory } from 'react-router-dom'; - -import type { Contact } from '@/shared/types/network-types'; -import { isValidEthereumAddress, withPrefix } from '@/shared/utils/address'; -import { WarningStorageLowSnackbar } from '@/ui/FRWComponent/WarningStorageLowSnackbar'; -import { useProfileStore } from '@/ui/stores/useProfileStore'; -import { useStorageCheck } from '@/ui/utils/useStorageCheck'; -import { type CoinItem } from 'background/service/coinList'; -import { LLSpinner } from 'ui/FRWComponent'; -import { useWallet } from 'ui/utils'; - -import IconSwitch from '../../../../components/iconfont/IconSwitch'; -import theme from '../../../style/LLTheme'; -import TransferFrom from '../TransferFrom'; -import TransferTo from '../TransferTo'; - -import MoveToken from './MoveToken'; - -interface TransferConfirmationProps { - isConfirmationOpen: boolean; - data: any; - handleCloseIconClicked: () => void; - handleCancelBtnClicked: () => void; - handleAddBtnClicked: () => void; -} -const USER_CONTACT = { - address: '', - id: 0, - contact_name: '', - avatar: '', - domain: { - domain_type: 999, - value: '', - }, -} as unknown as Contact; - -const CHILD_CONTACT = { - address: '', - id: 0, - contact_name: '', - avatar: '', - domain: { - domain_type: 999, - value: '', - }, -} as unknown as Contact; - -const EMPTY_COIN: CoinItem = { - coin: '', - unit: '', - balance: 0, - price: 0, - change24h: 0, - total: 0, - icon: '', -}; - -const MoveFromParent = (props: TransferConfirmationProps) => { - enum ENV { - Mainnet = 'mainnet', - Testnet = 'testnet', - } - enum Error { - Exceed = 'Insufficient balance', - Fail = 'Cannot find swap pair', - } - - // declare enum Strategy { - // GitHub = 'GitHub', - // Static = 'Static', - // CDN = 'CDN' - // } - - const usewallet = useWallet(); - const history = useHistory(); - const { childAccounts } = useProfileStore(); - const [userWallet, setWallet] = useState(null); - const [currentCoin, setCurrentCoin] = useState('flow'); - const [coinList, setCoinList] = useState([]); - // const [exceed, setExceed] = useState(false); - const [amount, setAmount] = useState(''); - // const [validated, setValidated] = useState(null); - const [userInfo, setUser] = useState(USER_CONTACT); - const [childUserInfo, setChildUser] = useState(CHILD_CONTACT); - const [network, setNetwork] = useState('mainnet'); - const [childAddress, setChildAddress] = useState(''); - const [coinInfo, setCoinInfo] = useState(EMPTY_COIN); - const [secondAmount, setSecondAmount] = useState('0.0'); - const [isLoading, setLoading] = useState(false); - const [errorType, setErrorType] = useState(null); - const [exceed, setExceed] = useState(false); - const { sufficient: isSufficient, sufficientAfterAction } = useStorageCheck({ - transferAmount: Number(amount) || 0, - coin: currentCoin, - // Determine if the transfer is between EVM and Flow - movingBetweenEVMAndFlow: - isValidEthereumAddress(userInfo.address) !== isValidEthereumAddress(childUserInfo.address), - }); - - const isLowStorage = isSufficient !== undefined && !isSufficient; // isSufficient is undefined when the storage check is not yet completed - const isLowStorageAfterAction = sufficientAfterAction !== undefined && !sufficientAfterAction; - - const setUserWallet = useCallback(async () => { - // const walletList = await storage.get('userWallet'); - setLoading(true); - const token = await usewallet.getCurrentCoin(); - console.log('getCurrentCoin ', token); - const wallet = await usewallet.getMainWallet(); - const network = await usewallet.getNetwork(); - setNetwork(network); - setCurrentCoin(token); - // userWallet - await setWallet(wallet); - const coinList = await usewallet.getCoinList(); - setCoinList(coinList); - const currentAddress = await usewallet.getCurrentAddress(); - setChildAddress(currentAddress!); - const coinInfo = coinList.find((coin) => coin.unit.toLowerCase() === token.toLowerCase()); - setCoinInfo(coinInfo!); - - const info = await usewallet.getUserInfo(false); - const userContact = { - ...USER_CONTACT, - address: withPrefix(wallet) || '', - avatar: info.avatar, - contact_name: info.username, - }; - setUser(userContact); - - const cwallet = childAccounts[currentAddress!]; - const childContact = { - ...CHILD_CONTACT, - address: withPrefix(currentAddress!) || '', - avatar: cwallet.thumbnail.url, - contact_name: cwallet.name, - }; - - setChildUser(childContact); - // const result = await usewallet.openapi.fetchTokenList(network); - setLoading(false); - - return; - }, [usewallet, childAccounts]); - - const moveToken = async () => { - setLoading(true); - const tokenResult = await usewallet.openapi.getTokenInfo(currentCoin, network); - console.log('tokenResult ', tokenResult); - usewallet - .moveFTfromChild(childUserInfo!.address, 'flowTokenProvider', amount!, tokenResult!.name) - .then(async (createRes) => { - usewallet.listenTransaction( - createRes, - true, - 'Transfer complete', - `Your have moved ${amount} Flow to your address ${childAddress}. \nClick to view this transaction.` - ); - await usewallet.setDashIndex(0); - history.push('/dashboard?activity=1'); - setLoading(false); - props.handleCloseIconClicked(); - }) - .catch((err) => { - console.log(err); - setLoading(false); - }); - }; - - const handleMove = async () => { - console.log('currentCoin ', currentCoin); - moveToken(); - }; - - const handleCoinInfo = useCallback(async () => { - if (coinList.length > 0) { - const coinInfo = coinList.find( - (coin) => coin.unit.toLowerCase() === currentCoin.toLowerCase() - ); - setCoinInfo(coinInfo!); - } - }, [coinList, currentCoin]); - - useEffect(() => { - setUserWallet(); - }, [setUserWallet]); - - useEffect(() => { - handleCoinInfo(); - }, [currentCoin, handleCoinInfo]); - - return ( - - - - - - - {chrome.i18n.getMessage('move_tokens')} - - - - - - - - - {childAddress && ( - - )} - - {isLoading ? ( - - - - ) : ( - - - - )} - - {userWallet && } - - - - - {coinInfo.unit && ( - - )} - - - - - - - - - ); -}; - -export default MoveFromParent; diff --git a/src/ui/views/EvmMove/TransferFrom.tsx b/src/ui/views/EvmMove/TransferFrom.tsx index a831e1c2..ef05d27f 100644 --- a/src/ui/views/EvmMove/TransferFrom.tsx +++ b/src/ui/views/EvmMove/TransferFrom.tsx @@ -11,19 +11,19 @@ const tempEmoji = { }; const TransferFrom = ({ wallet, userInfo, isChild = false }) => { - const { currentWallet } = useProfileStore(); + const { parentWallet } = useProfileStore(); const [emoji, setEmoji] = useState(tempEmoji); const getEmoji = useCallback(async () => { const emojiObject = { ...tempEmoji, - emoji: currentWallet.icon, - name: currentWallet.name, - bgcolor: currentWallet.color, + emoji: parentWallet.icon, + name: parentWallet.name, + bgcolor: parentWallet.color, type: 'parent', }; setEmoji(emojiObject); - }, [currentWallet.icon, currentWallet.name, currentWallet.color, setEmoji]); + }, [parentWallet, setEmoji]); useEffect(() => { getEmoji(); diff --git a/src/ui/views/EvmMove/TransferTo.tsx b/src/ui/views/EvmMove/TransferTo.tsx index 9a61fdeb..c6605263 100644 --- a/src/ui/views/EvmMove/TransferTo.tsx +++ b/src/ui/views/EvmMove/TransferTo.tsx @@ -1,8 +1,9 @@ -import React, { useState, useEffect } from 'react'; import { Box, Typography, CardMedia } from '@mui/material'; import { StyledEngineProvider } from '@mui/material/styles'; +import React, { useState, useEffect, useCallback } from 'react'; + +import { useProfileStore } from '@/ui/stores/useProfileStore'; import { formatAddress } from 'ui/utils'; -import { useWallet } from 'ui/utils'; const tempEmoji = { emoji: '🥥', @@ -11,29 +12,24 @@ const tempEmoji = { }; const TransferTo = ({ wallet, userInfo }) => { - const usewallet = useWallet(); + const { evmWallet } = useProfileStore(); const [emoji, setEmoji] = useState(tempEmoji); - const getEmoji = async () => { - console.log('isEvm ', emoji); + const getEmoji = useCallback(async () => { if (!emoji['type']) { - const currentWallet = await usewallet.getEvmWallet(); - console.log('getEvmWallet ', currentWallet); + console.log('getEvmWallet ', evmWallet); const emojiObject = tempEmoji; - emojiObject.emoji = currentWallet.icon; - emojiObject.name = currentWallet.name; - emojiObject.bgcolor = currentWallet.color; + emojiObject.emoji = evmWallet.icon; + emojiObject.name = evmWallet.name; + emojiObject.bgcolor = evmWallet.color; emojiObject['type'] = 'evm'; setEmoji(emojiObject); } - - console.log('emoji ', emoji); - }; + }, [emoji, evmWallet]); useEffect(() => { - console.log('transfer to ', wallet, userInfo); getEmoji(); - }, [userInfo]); + }, [getEmoji]); return ( From 022af236e7c0069924990a8cd19738babf811c3c Mon Sep 17 00:00:00 2001 From: zzggo Date: Wed, 5 Feb 2025 16:19:50 +1100 Subject: [PATCH 2/3] fixed: test function --- src/ui/hooks/__tests__/useProfileHook.test.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/ui/hooks/__tests__/useProfileHook.test.ts b/src/ui/hooks/__tests__/useProfileHook.test.ts index d3d4c855..2d07013c 100644 --- a/src/ui/hooks/__tests__/useProfileHook.test.ts +++ b/src/ui/hooks/__tests__/useProfileHook.test.ts @@ -32,7 +32,7 @@ vi.mock('@/ui/stores/useProfileStore', () => ({ setMainAddress: vi.fn(), setEvmAddress: vi.fn(), setEvmWallet: vi.fn(), - setUserWallet: vi.fn(), + setParentWallet: vi.fn(), setCurrent: vi.fn(), setChildAccount: vi.fn(), setUserInfo: vi.fn(), @@ -119,7 +119,7 @@ describe('useProfileHook', () => { setMainAddress: mocks.setMainAddress, setEvmAddress: mocks.setEvmAddress, setEvmWallet: mocks.setEvmWallet, - setUserWallet: vi.fn(), + setParentWallet: vi.fn(), setCurrent: vi.fn(), setChildAccount: vi.fn(), setUserInfo: vi.fn(), @@ -158,13 +158,13 @@ describe('useProfileHook', () => { describe('freshUserWallet', () => { it('should update user wallet data', async () => { const mockSetWalletList = vi.fn(); - const mockSetUserWallet = vi.fn(); + const mockSetParentWallet = vi.fn(); vi.mocked(useProfileStore).mockReturnValueOnce({ setMainAddress: vi.fn(), setEvmAddress: vi.fn(), setEvmWallet: vi.fn(), - setUserWallet: mockSetUserWallet, + setParentWallet: mockSetParentWallet, setCurrent: vi.fn(), setChildAccount: vi.fn(), setUserInfo: vi.fn(), @@ -183,7 +183,7 @@ describe('useProfileHook', () => { }); expect(mockSetWalletList).toHaveBeenCalled(); - expect(mockSetUserWallet).toHaveBeenCalled(); + expect(mockSetParentWallet).toHaveBeenCalled(); }); }); @@ -198,7 +198,7 @@ describe('useProfileHook', () => { setMainAddress: vi.fn(), setEvmAddress: vi.fn(), setEvmWallet: vi.fn(), - setUserWallet: vi.fn(), + setParentWallet: vi.fn(), setCurrent: vi.fn(), setChildAccount: vi.fn(), setUserInfo: mockSetUserInfo, From dacd7e2ad4a6a176152bcab98ddeb116e0bfac76 Mon Sep 17 00:00:00 2001 From: zzggo Date: Wed, 5 Feb 2025 16:38:47 +1100 Subject: [PATCH 3/3] fixed: vitest with parent wallet test cases --- src/ui/hooks/__tests__/useProfileHook.test.ts | 31 +++++++++++++------ 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/src/ui/hooks/__tests__/useProfileHook.test.ts b/src/ui/hooks/__tests__/useProfileHook.test.ts index 2d07013c..78ab7e2a 100644 --- a/src/ui/hooks/__tests__/useProfileHook.test.ts +++ b/src/ui/hooks/__tests__/useProfileHook.test.ts @@ -110,6 +110,12 @@ vi.mock('@/ui/utils/WalletContext', () => ({ loggedInAccounts: ['account1'], }), }, + returnMainWallet: vi.fn().mockResolvedValue({ + name: 'Test Wallet', + address: '0x138c20de202897fb', + type: 'flow', + blockchain: 'flow', + }), }), })); @@ -159,31 +165,39 @@ describe('useProfileHook', () => { it('should update user wallet data', async () => { const mockSetWalletList = vi.fn(); const mockSetParentWallet = vi.fn(); + const mockSetCurrent = vi.fn(); + const mockSetMainLoading = vi.fn(); - vi.mocked(useProfileStore).mockReturnValueOnce({ + vi.mocked(useProfileStore).mockReturnValue({ setMainAddress: vi.fn(), setEvmAddress: vi.fn(), setEvmWallet: vi.fn(), setParentWallet: mockSetParentWallet, - setCurrent: vi.fn(), + setCurrent: mockSetCurrent, setChildAccount: vi.fn(), setUserInfo: vi.fn(), setOtherAccounts: vi.fn(), setLoggedInAccounts: vi.fn(), - setMainLoading: vi.fn(), + setMainLoading: mockSetMainLoading, setEvmLoading: vi.fn(), setInitial: vi.fn(), setWalletList: mockSetWalletList, initialStart: true, }); - const { freshUserWallet } = useProfileHook(); + const { fetchUserWallet } = useProfileHook(); await act(async () => { - await freshUserWallet(); + await fetchUserWallet(); }); - expect(mockSetWalletList).toHaveBeenCalled(); - expect(mockSetParentWallet).toHaveBeenCalled(); + expect(mockSetParentWallet).toHaveBeenCalledWith({ + name: 'Test Wallet', + address: '0x138c20de202897fb', + type: 'flow', + blockchain: 'flow', + }); + expect(mockSetCurrent).toHaveBeenCalled(); + expect(mockSetMainLoading).toHaveBeenCalledWith(false); }); }); @@ -193,8 +207,7 @@ describe('useProfileHook', () => { const mockSetOtherAccounts = vi.fn(); const mockSetLoggedInAccounts = vi.fn(); - // Mock the profile store - vi.mocked(useProfileStore).mockReturnValueOnce({ + vi.mocked(useProfileStore).mockReturnValue({ setMainAddress: vi.fn(), setEvmAddress: vi.fn(), setEvmWallet: vi.fn(),