Skip to content

Commit

Permalink
Automatic connection (#98)
Browse files Browse the repository at this point in the history
* revert

* Automatic connection

* Update index.tsx

* lint

* explicit versions
  • Loading branch information
Szegoo authored May 9, 2024
1 parent 6f52d14 commit 6a0c59d
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 12 deletions.
14 changes: 7 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@
"@mui/lab": "5.0.0-alpha.134",
"@mui/material": "^5.15.14",
"@mui/x-date-pickers": "^6.19.5",
"@polkadot/api": "latest",
"@polkadot/api-contract": "latest",
"@polkadot/extension-dapp": "latest",
"@polkadot/extension-inject": "latest",
"@polkadot/types": "latest",
"@polkadot/ui-keyring": "latest",
"@polkadot/util": "^12.6.2",
"@polkadot/api": "11.0.2",
"@polkadot/api-contract": "11.0.2",
"@polkadot/extension-dapp": "0.47.3",
"@polkadot/extension-inject": "0.47.3",
"@polkadot/types": "11.0.2",
"@polkadot/ui-keyring": "3.6.6",
"@polkadot/util": "12.6.2",
"@polkadot/util-crypto": "^12.6.2",
"@types/humanize-duration": "^3.27.3",
"@vercel/analytics": "^1.2.2",
Expand Down
47 changes: 43 additions & 4 deletions src/contexts/account/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ import type { Signer } from '@polkadot/api/types';
import { InjectedAccountWithMeta } from '@polkadot/extension-inject/types';
import React, { createContext, useContext, useEffect, useReducer } from 'react';

const APP_NAME = 'Corehub';
const LOCAL_STORAGE_ACCOUNTS = 'accounts';
const LOCAL_STORAGE_ACTIVE_ACCOUNT = 'active-account';

export enum KeyringState {
// eslint-disable-next-line no-unused-vars
DISCONNECTED = 'disconnected',
Expand Down Expand Up @@ -83,6 +87,7 @@ const AccountProvider = ({ children }: Props) => {
const [state, dispatch] = useReducer(reducer, initialState);

const setActiveAccount = (acct: any) => {
localStorage.setItem(LOCAL_STORAGE_ACTIVE_ACCOUNT, JSON.stringify(acct));
dispatch({ type: 'SET_ACTIVE_ACCOUNT', payload: acct });
};

Expand All @@ -91,20 +96,32 @@ const AccountProvider = ({ children }: Props) => {
const asyncLoadAccounts = async () => {
try {
const extensionDapp = await import('@polkadot/extension-dapp');
const { web3Accounts, web3Enable } = extensionDapp;
await web3Enable('Corehub');
const { web3Accounts } = extensionDapp;
const accounts: InjectedAccountWithMeta[] = await web3Accounts();
dispatch({ type: 'KEYRING_READY' });
dispatch({ type: 'SET_ACCOUNTS', payload: accounts });
if (accounts.length)
dispatch({ type: 'SET_ACTIVE_ACCOUNT', payload: accounts[0] });
} catch (e) {
dispatch({ type: 'KEYRING_ERROR' });
}
};
asyncLoadAccounts();
};

useEffect(() => {
const accounts = state.accounts;
if (accounts.length) {
const activeAccount = localStorage.getItem(LOCAL_STORAGE_ACTIVE_ACCOUNT);
const account = activeAccount
? accounts.find((acc: any) => acc.address == activeAccount) ??
accounts[0]
: accounts[0];

dispatch({ type: 'SET_ACTIVE_ACCOUNT', payload: account });

localStorage.setItem(LOCAL_STORAGE_ACCOUNTS, JSON.stringify(accounts));
}
}, [state.accounts]);

useEffect(() => {
const getInjector = async () => {
if (!state.activeAccount) return;
Expand All @@ -117,6 +134,28 @@ const AccountProvider = ({ children }: Props) => {

const disconnectWallet = () => dispatch({ type: 'DISCONNECT' });

useEffect(() => {
const asyncLoad = async () => {
const { web3Enable } = await import('@polkadot/extension-dapp');
await web3Enable(APP_NAME);

const item = localStorage.getItem(LOCAL_STORAGE_ACCOUNTS);
if (!item) return;
try {
const accounts = JSON.parse(item) as InjectedAccountWithMeta[];
if (accounts.length > 0) {
// load accounts automatically
dispatch({ type: 'KEYRING_READY' });
dispatch({ type: 'SET_ACCOUNTS', payload: accounts });
}
} catch {
// error handling
}
};

if ((window as any).injectedWeb3) asyncLoad();
}, []);

return (
<AccountDataContext.Provider
value={{ state, setActiveAccount, connectWallet, disconnectWallet }}
Expand Down
7 changes: 6 additions & 1 deletion src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { ThemeProvider } from '@mui/material/styles';
import { Analytics } from '@vercel/analytics/react';
import { NextPage } from 'next';
import { AppProps } from 'next/app';
import dynamic from 'next/dynamic';
import Head from 'next/head';
import * as React from 'react';
import '../../styles/global.scss';
Expand All @@ -13,7 +14,6 @@ import theme from '@/utils/muiTheme';

import { Layout } from '@/components';

import { AccountProvider } from '@/contexts/account';
import {
CoretimeApiContextProvider,
RelayApiContextProvider,
Expand All @@ -37,6 +37,11 @@ interface MyAppProps extends AppProps {
Component: NextPageWithLayout;
}

const AccountProvider = dynamic(
() => import('../contexts/account').then((a) => a.AccountProvider),
{ ssr: false }
);

export default function MyApp(props: MyAppProps) {
const { Component, emotionCache = clientSideEmotionCache, pageProps } = props;
const getLayout = Component.getLayout ?? ((page) => <Layout>{page}</Layout>);
Expand Down

0 comments on commit 6a0c59d

Please sign in to comment.