Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Unable to add new account to existing wallet #446

Merged
merged 1 commit into from
Mar 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions packages/adena-extension/public/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,19 @@
"manifest_version": 3,
"version": "1.9.2",
"action": {
"default_popup": "popup.html"
"default_icon": {
"16": "icons/icon16.png",
"32": "icons/icon32.png"
},
"default_title": "Adena"
},
"background": {
"service_worker": "background.js"
},
"permissions": ["storage", "tabs"],
"content_scripts": [
{
"matches": ["*://*/*"],
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],
Expand Down
31 changes: 16 additions & 15 deletions packages/adena-extension/src/App/app-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,27 @@ import theme from '@styles/theme';
import { RecoilRoot } from 'recoil';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { AdenaProvider, WalletProvider } from '@common/provider';
import { AppProviderErrorBoundary, AppReloadFallback } from '@common/error-boundary';

const queryClient = new QueryClient();

const AppProvider = ({ children }: { children: ReactNode }): ReactElement => {
return (
<>
<RecoilRoot>
<QueryClientProvider client={queryClient}>
<AdenaProvider>
<WalletProvider>
<ThemeProvider theme={theme}>
<Suspense fallback={<div>Loading...</div>}>
{children}
</Suspense>
</ThemeProvider>
</WalletProvider>
</AdenaProvider>
</QueryClientProvider>
</RecoilRoot>
</>
<React.Fragment>
<AppProviderErrorBoundary fallback={<AppReloadFallback />}>
<RecoilRoot>
<QueryClientProvider client={queryClient}>
<AdenaProvider>
<WalletProvider>
<ThemeProvider theme={theme}>
<Suspense fallback={<div>Loading...</div>}>{children}</Suspense>
</ThemeProvider>
</WalletProvider>
</AdenaProvider>
</QueryClientProvider>
</RecoilRoot>
</AppProviderErrorBoundary>
</React.Fragment>
);
};

Expand Down
14 changes: 13 additions & 1 deletion packages/adena-extension/src/App/popup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,22 @@ import AppProvider from './app-provider';
import useApp from './use-app';
import { GlobalPopupStyle } from '@styles/global-style';
import { HashRouter } from 'react-router-dom';
import { useInitWallet } from '@hooks/use-init-wallet';
import { useWallet } from '@hooks/use-wallet';
import useLink from '@hooks/use-link';

const RunApp = (): ReactElement => {
useApp();
return <PopupRouter />;
useInitWallet();
const { existWallet, isLoadingExistWallet } = useWallet();
const { openRegister } = useLink();

if (isLoadingExistWallet === false && existWallet === false) {
openRegister();
window.close();
}

return existWallet ? <PopupRouter /> : <></>;
};

const App = (): ReactElement => {
Expand Down
33 changes: 32 additions & 1 deletion packages/adena-extension/src/background.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,44 @@
import { ChromeLocalStorage } from '@common/storage';
import { MessageHandler } from './inject/message';

function existsWallet(): Promise<boolean> {
const storage = new ChromeLocalStorage();
return storage
.get('SERIALIZED')
.then(async (serialized) => typeof serialized === 'string' && serialized.length !== 0)
.catch(() => false);
}

chrome.runtime.onInstalled.addListener((details) => {
if (details.reason === 'install') {
chrome.tabs.create({
url: chrome.runtime.getURL('/register.html'),
});
} else if (details.reason === 'update') {
console.log('update');
existsWallet().then(() => {
chrome.action.setPopup({ popup: '/popup.html' });
});
}
});

chrome.action.onClicked.addListener((tab) => {
existsWallet()
.then(async (exist) => {
if (!exist) {
await chrome.action.setPopup({ tabId: tab.id, popup: '/popup.html' });
chrome.tabs.create({
url: chrome.runtime.getURL('/register.html'),
});
} else {
await chrome.action.setPopup({ tabId: tab.id, popup: '' });
}
})
.catch(async () => {
await chrome.action.setPopup({ tabId: tab.id, popup: '' });
chrome.tabs.create({
url: chrome.runtime.getURL('/register.html'),
});
});
});

chrome.runtime.onMessage.addListener(MessageHandler.createHandler);
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import React, { ErrorInfo } from 'react';

import { CommonError } from '@common/errors/common';

interface Props {
fallback: React.ReactNode;
children?: React.ReactNode;
}

interface State {
hasError: boolean;
}

export class AppProviderErrorBoundary extends React.Component<Props, State> {
public state: State = {
hasError: false,
};

public static getDerivedStateFromError(error: Error): State {
if (error instanceof CommonError) {
if (error.getStatus() === 401) {
return { hasError: true };
}
}
return { hasError: false };
}

public componentDidCatch(error: Error, errorInfo: ErrorInfo): void {
console.error('Uncaught error:', error, errorInfo);
}

public render(): React.ReactNode {
if (this.state.hasError) {
return this.props.fallback;
}

return this.props.children;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import React, { useEffect } from 'react';

export const AppReloadFallback: React.FC = () => {
useEffect(() => {
location.reload();
}, []);

return <React.Fragment />;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './app-reload-fallback';
2 changes: 2 additions & 0 deletions packages/adena-extension/src/common/error-boundary/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './app-provider-error-boundary';
export * from './fallback';
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ const ERROR_VALUE = {
status: 400,
type: 'FAILED_TO_RUN',
},
FAILED_INITIALIZE_CHROME_API: {
status: 401,
type: 'FAILED_INITIALIZE_CHROME_API',
},
};

type ErrorType = keyof typeof ERROR_VALUE;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Storage } from '.';
import { StorageMigrator, StorageModelLatest } from '@migrates/storage-migrator';
import { CommonError } from '@common/errors/common';

type StorageKeyTypes =
| 'NETWORKS'
Expand Down Expand Up @@ -42,6 +43,9 @@ export class ChromeLocalStorage implements Storage {
private current: StorageModelLatest | null = null;

constructor() {
if (!chrome.storage) {
throw new CommonError('FAILED_INITIALIZE_CHROME_API');
}
this.storage = chrome.storage.local;
this.migrator = new StorageMigrator(StorageMigrator.migrations(), this.storage);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import { CommonError } from '@common/errors/common';
import { Storage } from '.';

export class ChromeSessionStorage implements Storage {
private storage: chrome.storage.SessionStorageArea;

constructor() {
if (!chrome.storage) {
throw new CommonError('FAILED_INITIALIZE_CHROME_API');
}
this.storage = chrome.storage.session;
}

Expand Down
3 changes: 3 additions & 0 deletions packages/adena-extension/src/hooks/use-clear.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { BalanceState, CommonState, NetworkState, WalletState } from '@states';
import { useQueryClient } from '@tanstack/react-query';
import { useResetRecoilState, useSetRecoilState } from 'recoil';
import { useAdenaContext } from './use-context';

Expand All @@ -15,6 +16,7 @@ export const useClear = (): UseClearReturn => {
establishService,
tokenService,
} = useAdenaContext();
const queryClient = useQueryClient();
const clearCurrentAccount = useResetRecoilState(WalletState.currentAccount);
const setWalletState = useSetRecoilState(WalletState.state);
const clearTransactionHistory = useResetRecoilState(WalletState.transactionHistory);
Expand All @@ -41,6 +43,7 @@ export const useClear = (): UseClearReturn => {
await chainService.clear();
await establishService.clear();
await tokenService.clear();
queryClient.clear();
return true;
};

Expand Down
4 changes: 0 additions & 4 deletions packages/adena-extension/src/hooks/use-init-wallet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@ import { useEffect } from 'react';

import { RoutePath } from '@types';
import useAppNavigate from './use-app-navigate';
import useLink from './use-link';
import { useLoadAccounts } from './use-load-accounts';
import { useMatch } from 'react-router-dom';
import { useAddressBook } from './use-address-book';

export const useInitWallet = (): void => {
const { navigate } = useAppNavigate();
const { openRegister } = useLink();
const isApproveLoginPage = useMatch('/approve/*');

const { state } = useLoadAccounts();
Expand All @@ -19,10 +17,8 @@ export const useInitWallet = (): void => {
switch (state) {
case 'NONE':
case 'LOADING':
break;
case 'CREATE':
case 'FAIL':
openRegister();
break;
case 'LOGIN':
if (!isApproveLoginPage) {
Expand Down
12 changes: 6 additions & 6 deletions packages/adena-extension/src/hooks/use-wallet.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
import { useQuery } from '@tanstack/react-query';
import { useAdenaContext, useWalletContext } from './use-context';
import { useAdenaContext } from './use-context';

export interface UseWalletReturn {
existWallet: boolean;
existWallet: boolean | undefined;
isLoadingExistWallet: boolean;
}

export const useWallet = (): UseWalletReturn => {
const { wallet } = useWalletContext();
const { walletService } = useAdenaContext();

const { data: existWallet = false } = useQuery(
['wallet/existWallet', walletService, wallet],
const { data: existWallet, isLoading: isLoadingExistWallet } = useQuery(
['wallet/existWallet', walletService],
async () => {
const existWallet = await walletService.existsWallet().catch(() => false);
return existWallet;
},
{},
);

return { existWallet };
return { existWallet, isLoadingExistWallet };
};
7 changes: 2 additions & 5 deletions packages/adena-extension/src/router/popup/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,10 @@ import LoadingMain from './loading-main';
import { CreatePassword } from '@pages/popup/certify/create-password';
import { LaunchAdena } from '@pages/popup/certify/launch-adena';
import ApproveSignFailedScreen from '@pages/popup/wallet/approve-sign-failed-screen';
import { useInitWallet } from '@hooks/use-init-wallet';

export const PopupRouter = (): JSX.Element => {
useInitWallet();

return (
<>
<React.Fragment>
<Header />
<Routes>
<Route path={RoutePath.Home} element={<Navigate replace to={RoutePath.Wallet} />} />
Expand Down Expand Up @@ -127,6 +124,6 @@ export const PopupRouter = (): JSX.Element => {
</Routes>
<Navigation />
<LoadingMain />
</>
</React.Fragment>
);
};
2 changes: 1 addition & 1 deletion packages/adena-extension/src/services/wallet/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export class WalletService {
public existsWallet = (): Promise<boolean> => {
return this.walletRepository
.getSerializedWallet()
.then(() => true)
.then((serializedWallet) => !!serializedWallet)
.catch(() => false);
};

Expand Down
15 changes: 0 additions & 15 deletions packages/adena-extension/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,27 +85,12 @@ const config = {
transform: (content, path) =>
Buffer.from(
JSON.stringify({
name: packageInfo.name,
version: packageInfo.version,
description: packageInfo.description,
icons: {
16: 'icons/icon16.png',
32: 'icons/icon32.png',
48: 'icons/icon48.png',
128: 'icons/icon128.png',
},
background: {
service_worker: 'background.js',
},
content_scripts: [
{
matches: ['<all_urls>'],
js: ['content.js'],
},
],
action: {
default_popup: 'popup.html',
},
...JSON.parse(content.toString()),
}),
),
Expand Down
Loading