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

feat(wallet): keplr connection #4430

Merged
merged 4 commits into from
Feb 3, 2022
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
2 changes: 2 additions & 0 deletions packages/wallet/ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@
"@endo/init": "^0.5.33",
"@agoric/notifier": "^0.3.33",
"@agoric/ui-components": "^0.2.28",
"@cosmjs/stargate": "^0.27.1",
"@emotion/react": "^11.5.0",
"@emotion/styled": "^11.3.0",
"@mui/icons-material": "^5.1.0",
"@mui/lab": "^5.0.0-alpha.67",
"@mui/material": "^5.1.0",
"@mui/styles": "^5.1.0",
"@testing-library/jest-dom": "^5.11.4",
Expand Down
19 changes: 14 additions & 5 deletions packages/wallet/ui/src/components/AppBar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import Tooltip from '@mui/material/Tooltip';

import WalletConnection from './WalletConnection';
import NavDrawer from './NavDrawer';
import ChainConnector from './ChainConnector';
import { withApplicationContext } from '../contexts/Application';

const logoUrl =
'https://agoric.com/wp-content/themes/agoric_2021_theme/assets/img/logo.svg';
Expand Down Expand Up @@ -44,7 +46,8 @@ const useStyles = makeStyles(theme => ({
},
}));

const AppBar = () => {
// Exported for testing only.
export const AppBarWithoutContext = ({ useChainBackend }) => {
const theme = useTheme();
const classes = useStyles(theme);

Expand All @@ -62,6 +65,13 @@ const AppBar = () => {
</a>
</div>
<div className={classes.appBarSection}>
<div className={classes.connector}>
{useChainBackend ? (
<ChainConnector></ChainConnector>
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I looked into code-splitting, but it seemed to be more complexity than it's worth for now. Using the async import would only save the app from loading a couple hundred lines of code.

) : (
<WalletConnection></WalletConnection>
)}
</div>
<div className={classes.connector}>
<Tooltip title="Help">
<IconButton
Expand All @@ -74,12 +84,11 @@ const AppBar = () => {
</IconButton>
</Tooltip>
</div>
<div className={classes.connector}>
<WalletConnection></WalletConnection>
</div>
</div>
</header>
);
};

export default AppBar;
export default withApplicationContext(AppBarWithoutContext, context => ({
useChainBackend: context.useChainBackend,
}));
158 changes: 158 additions & 0 deletions packages/wallet/ui/src/components/ChainConnector.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable react/display-name */
import React, { useEffect, useState } from 'react';
import clsx from 'clsx';
import { makeStyles } from '@mui/styles';
import LoadingButton from '@mui/lab/LoadingButton';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemText from '@mui/material/ListItemText';
import DialogTitle from '@mui/material/DialogTitle';
import Dialog from '@mui/material/Dialog';
import Snackbar from '@mui/material/Snackbar';
import MuiAlert from '@mui/material/Alert';

import { NETWORK_CONFIGS, suggestChain } from '../util/SuggestChain';

const useStyles = makeStyles(_ => ({
hidden: {
display: 'none',
},
connector: {
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
height: '100%',
},
centeredText: {
textAlign: 'center',
},
dialog: {
minWidth: 240,
},
}));

const Alert = React.forwardRef(function Alert(props, ref) {
return <MuiAlert elevation={6} ref={ref} variant="filled" {...props} />;
});

const ChainConnector = () => {
const classes = useStyles();
const [dialogOpened, setDialogOpened] = useState(false);
const [networkConfig, setNetworkConfig] = useState(null);
const [connectionInProgress, setConnectionInProgress] = useState(false);
const [snackbarMessage, setSnackbarMessage] = useState(null);

const handleSnackbarClose = (_, reason) => {
if (reason === 'clickaway') {
return;
}

setSnackbarMessage(null);
};

const showError = message => {
setSnackbarMessage(message);
};

const handleClose = () => {
setDialogOpened(false);
};

const selectNetworkConfig = nc => {
setNetworkConfig(nc);
setDialogOpened(false);
};

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

let networkChanged = false;
setConnectionInProgress(true);

const connect = async () => {
if (!window.getOfflineSigner || !window.keplr) {
setNetworkConfig(null);
setConnectionInProgress(false);
showError('Please install the Keplr extension');
} else if (window.keplr.experimentalSuggestChain) {
try {
const cosmJS = await suggestChain(networkConfig[0]);
if (!networkChanged) {
setConnectionInProgress(false);
window.cosmJS = cosmJS;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Setting this on the window so it can be tested through the console, but eventually the cosmJS ref should be stored in the application context.

}
} catch (e) {
if (!networkChanged) {
showError('Failed to connect to Keplr');
console.error(e);
setConnectionInProgress(false);
setNetworkConfig(null);
}
}
} else {
setNetworkConfig(null);
showError('Please use the most recent version of the Keplr extension');
}
};
connect();

return () => {
networkChanged = true;
};
}, [networkConfig]);

return (
<>
<div className={clsx('Connector', classes.connector)}>
<LoadingButton
loading={connectionInProgress}
color="primary"
variant="outlined"
onClick={() => setDialogOpened(true)}
>
{networkConfig ? 'Connected' : 'Connect Wallet'}
</LoadingButton>
</div>
<Dialog onClose={handleClose} open={dialogOpened}>
<div className={classes.dialog}>
<DialogTitle className={classes.centeredText}>
Select Network
</DialogTitle>
<List sx={{ pt: 0 }}>
{NETWORK_CONFIGS.map(nc => (
<ListItem
button
selected={nc === networkConfig}
onClick={() => selectNetworkConfig(nc)}
key={nc[0]}
>
<ListItemText
className={classes.centeredText}
primary={nc[1]}
/>
</ListItem>
))}
</List>
</div>
</Dialog>
<Snackbar
open={snackbarMessage !== null}
autoHideDuration={6000}
onClose={handleSnackbarClose}
>
<Alert
onClose={handleSnackbarClose}
severity="error"
sx={{ width: '100%' }}
>
{snackbarMessage}
</Alert>
</Snackbar>
</>
);
};

export default ChainConnector;
48 changes: 48 additions & 0 deletions packages/wallet/ui/src/components/tests/AppBar.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { mount } from 'enzyme';
import { createTheme, ThemeProvider } from '@mui/material';
import AppBar, { AppBarWithoutContext } from '../AppBar';
import ChainConnector from '../ChainConnector';
import WalletConnection from '../WalletConnection';

const withApplicationContext = (Component, _) => ({ ...props }) => {
return <Component useChainBackend={false} {...props} />;
};

jest.mock('../../contexts/Application', () => {
return { withApplicationContext };
});

jest.mock('../ChainConnector', () => () => 'Wallet Connection');

jest.mock('../WalletConnection', () => () => 'Chain Connector');

const appTheme = createTheme({
pallete: {
background: {
default: '#fff',
},
},
appBarHeight: '64px',
});

test('renders the wallet-connection when useChainBackend is false', () => {
const component = mount(
<ThemeProvider theme={appTheme}>
<AppBar />
</ThemeProvider>,
);

expect(component.find(WalletConnection).exists());
expect(component.find(ChainConnector).exists()).toBeFalsy();
});

test('renders the wallet-connection when useChainBackend is true', () => {
const component = mount(
<ThemeProvider theme={appTheme}>
<AppBarWithoutContext useChainBackend={true} />
</ThemeProvider>,
);

expect(component.find(ChainConnector).exists());
expect(component.find(WalletConnection).exists()).toBeFalsy();
});
Loading