Skip to content

Commit

Permalink
Update network when not consistent
Browse files Browse the repository at this point in the history
  • Loading branch information
leonbit2022 committed Sep 15, 2023
1 parent 414fedb commit 7e2f292
Show file tree
Hide file tree
Showing 8 changed files with 100 additions and 5 deletions.
13 changes: 11 additions & 2 deletions packages/example/src/components/Account/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ import Main from './Main';
import Aside from './Aside';
import { useBalance } from '../../hook/useBalance';
import { useAppStore } from '../../mobx';
import { AccountLabel } from './styles';
import { AccountHeader, AccountLabel } from './styles';
import { useCurrencyRate } from '../../hook/useCurrencyRate';
import { WalletType } from '../../interface';
import { Message, MessageType } from '../../kits';
import LightningAppStatus from '../Lightning/AppStatus';
import { Background } from '../Background';
import { useNetworkCheck } from '../../hook/useNetworkCheck';

const Account = observer(() => {
const {
Expand All @@ -20,9 +21,17 @@ const Account = observer(() => {
const { balance, refresh, loadingBalance, errorMessage } = useBalance();
useCurrencyRate();
useRegisterXpub();
const { isSettingNetwork, networkMessage } = useNetworkCheck();

return (
<Background loading={isLoading}>
<Background
loading={isLoading || isSettingNetwork}
loadingTip={isSettingNetwork ? <div><p>Continue at MetaMask</p><p>Please confirm your network type.</p></div> : ''}
>
<AccountHeader>
{networkMessage && <Message type={MessageType.Info}>{networkMessage}</Message>}
</AccountHeader>

<Main balance={balance} loadingBalance={loadingBalance} loadingBalanceErrorMessage={errorMessage} />
<Aside refreshBalance={refresh} loadingBalance={loadingBalance} />

Expand Down
7 changes: 7 additions & 0 deletions packages/example/src/components/Account/styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,13 @@ export const AccountLabel = styled.p`
}
`;

export const AccountHeader = styled.div`
position: fixed;
top: 50px;
left: 0;
width: 100%;
`;

export const AccountMain = styled.div`
width: 560px;
padding: 40px;
Expand Down
5 changes: 3 additions & 2 deletions packages/example/src/components/Background/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ import { Loader, Modal, Transition } from 'semantic-ui-react';
interface BackgroundProps {
children: React.ReactNode
loading?: boolean
loadingTip?: React.ReactNode
}

export const Background = observer(({ children, loading = false }: BackgroundProps) => {
export const Background = observer(({ children, loading = false, loadingTip = '' }: BackgroundProps) => {
const loadingModalParent = useRef<HTMLDivElement | null>(null);
const {
persistDataLoaded,
Expand All @@ -20,7 +21,7 @@ export const Background = observer(({ children, loading = false }: BackgroundPro
<>
<div ref={loadingModalParent}>
<Modal open={loading} mountNode={loadingModalParent.current}>
<Loader inverted />
<Loader inverted content={loadingTip} />
</Modal>
</div>

Expand Down
47 changes: 47 additions & 0 deletions packages/example/src/hook/useNetworkCheck.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { useEffect, useState } from 'react';
import { useAppStore } from '../mobx';
import { getNetworkInSnap, updateNetworkInSnap } from '../lib/snap';
import { BitcoinNetwork } from '../interface';
import { AppStatus } from '../mobx/runtime';
import { capitalize } from '../utils/stringHelper';

export const useNetworkCheck = () => {
const { current, persistDataLoaded, settings: { setNetwork }, switchToAccount, runtime: { setStatus } } = useAppStore();
const [networkMessage, setNetworkMessage] = useState<string>('');
const [isSettingNetwork, setIsSettingNetwork] = useState<boolean>(false);

const switchNetworkAndUpdateState = (targetNetwork: BitcoinNetwork) => {
setNetwork(targetNetwork);
current && switchToAccount(current.mfp, current.scriptType, targetNetwork);
setStatus(AppStatus.FetchBalance);
};

useEffect(() => {
if(!persistDataLoaded){
return;
}

if(current){
getNetworkInSnap().then(network => {
if(network === ''){
setIsSettingNetwork(true);
updateNetworkInSnap(current.network).then(() => {
setIsSettingNetwork(false);
});
} else {
const networkInSnap = network === 'test' ? BitcoinNetwork.Test : BitcoinNetwork.Main;
const isNetworkTheSame = networkInSnap === current.network;
if (!isNetworkTheSame) {
switchNetworkAndUpdateState(networkInSnap);
setNetworkMessage(`Currently In ${capitalize(networkInSnap)}`);
}
}
});
}
}, [persistDataLoaded, current]);

return {
isSettingNetwork,
networkMessage
};
};
5 changes: 5 additions & 0 deletions packages/example/src/kits/Message/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ import { useEffect, useState } from 'react';
import { ReactComponent as ErrorIcon } from './images/error.svg';
import { ReactComponent as SucceedIcon } from '../../assets/vector.svg';
import { Transition } from 'semantic-ui-react';
import InfoIcon from '../../components/Icons/InfoIcon';

export enum MessageType {
Error,
Succeed,
Info,
}

interface MessageProps {
Expand All @@ -27,6 +29,7 @@ export const Message = ({
const timeout = !duration ? {
[MessageType.Succeed]: 1500,
[MessageType.Error]: 2000,
[MessageType.Info]: 5000,
}[type] : duration;
useEffect(() => {
if (visible) {
Expand All @@ -45,6 +48,8 @@ export const Message = ({
case MessageType.Succeed:
messageTypeIcon = <SucceedIcon />;
break;
case MessageType.Info:
messageTypeIcon = <InfoIcon color='#1F69FF' />;
}

return (
Expand Down
4 changes: 3 additions & 1 deletion packages/example/src/kits/Message/styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,7 @@ export const MessageContent = styled.div`
export const MessageCopy = styled.span<{ type: MessageType }>`
font-weight: 600;
color: ${(props) =>
props.type === MessageType.Error ? '#F54814' : '#21A35D'};
props.type === MessageType.Error ? '#F54814' : (
props.type === MessageType.Succeed ? '#21A35D' : '#1F69FF'
)};
`;
21 changes: 21 additions & 0 deletions packages/example/src/lib/snap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,27 @@ export async function updateNetworkInSnap(network: BitcoinNetwork) {
}
}

export async function getNetworkInSnap() {
try {
return await ethereum.request({
method: 'wallet_invokeSnap',
params: {
snapId,
request: {
method: 'btc_network',
params: {
action: 'get',
},
},
},
});
} catch (err: any) {
const error = new SnapError(err?.message || 'Get Snap Network failed');
logger.error(error);
throw error;
}
}

export async function signPsbt(
base64Psbt: string,
network: BitcoinNetwork,
Expand Down
3 changes: 3 additions & 0 deletions packages/example/src/utils/stringHelper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const capitalize = (str: string) => {
return str.charAt(0).toUpperCase() + str.slice(1);
};

0 comments on commit 7e2f292

Please sign in to comment.