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: add external wallet management functionality #9

Merged
merged 6 commits into from
Jun 22, 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: 1 addition & 1 deletion packages/wallet-management/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"publishConfig": {
"access": "public"
},
"author": "Eugene Chybisov <eugene@li.finance>",
"author": "Adrian Weniger <adrian@li.finance>",
"homepage": "https://github.com/lifinance/wallet-management",
"repository": {
"type": "git",
Expand Down
5 changes: 4 additions & 1 deletion packages/widget-embedded/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@
"@mui/icons-material": "^5.8.3",
"@mui/lab": "^5.0.0-alpha.85",
"@mui/material": "^5.8.3",
"@lifi/wallet-management": "^1.0.2",
"@lifinance/sdk": "^1.0.0-beta.11",
"ethers": "^5.6.9",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-router-dom": "^6.3.0",
Expand All @@ -50,4 +53,4 @@
"last 1 safari version"
]
}
}
}
51 changes: 50 additions & 1 deletion packages/widget-embedded/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,16 @@ import {
} from '@mui/material';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import React, { useEffect, useState } from 'react';
import { ethers } from 'ethers';
import { createRoot } from 'react-dom/client';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import './index.css';
import {
addChain,
switchChain,
switchChainAndAddToken,
} from '@lifi/wallet-management';
import { Token } from '@lifinance/sdk';
import { reportWebVitals } from './reportWebVitals';

function ValueLabelComponent({
Expand All @@ -40,14 +47,54 @@ if (!rootElement) {
}
const root = createRoot(rootElement);

const provider = new ethers.providers.Web3Provider(
(window as any).ethereum,
'any',
);

const walletCallbacks = {
connect: async () => {
await provider.send('eth_requestAccounts', []);
const signer = provider.getSigner();
const address = await signer.getAddress();
localStorage.setItem('demoEagerConnect', address);
return signer;
},
disconnect: async () => {
localStorage.removeItem('demoEagerConnect');
},
provideSigner: async () => {
const eagerAddress = localStorage.getItem('demoEagerConnect');
if (
(window as any).ethereum &&
(window as any).ethereum.selectedAddress.toLowerCase() ===
eagerAddress?.toLowerCase()
) {
return provider.getSigner();
}
return undefined;
},
switchChain: async (reqChainId: number) => {
await switchChain(reqChainId);
return provider.getSigner();
},
addToken: async (token: Token, chainId: number) => {
await switchChainAndAddToken(chainId, token);
},
addChain: async (chainId: number) => {
return addChain(chainId);
},
};

const widgetDrawerConfig: WidgetConfig = {
fromChain: 'pol',
toChain: 'bsc',
// disableInternalWalletManagement: true,
// walletCallbacks,
// fromToken: '0x0000000000000000000000000000000000000000',
// toToken: '0xcc42724c6683b7e57334c4e856f4c9965ed682bd',
// disableColorSchemes: true,
};

const widgetConfig: WidgetConfig = {
...widgetDrawerConfig,
containerStyle: {
Expand All @@ -74,6 +121,8 @@ const App = () => {
const [primary, setPrimaryColor] = useState('#3F49E1');
const [secondary, setSecondaryColor] = useState('#F5B5FF');
const [darkMode, setDarkMode] = useState(prefersDarkMode);
const [disableInternalWalletManagement, setDisableInternalWalletManagement] =
useState(false);
const [systemColor, setSystemColor] = useState(true);
const [theme, setTheme] = useState(() =>
createTheme({
Expand Down
7 changes: 7 additions & 0 deletions packages/widget/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useEffect } from 'react';
import { Route, Routes } from 'react-router-dom';
import { AppProps, AppProvider } from './AppProvider';
import { AppContainer } from './components/AppContainer';
Expand All @@ -9,6 +10,7 @@ import { SelectWalletPage } from './pages/SelectWalletPage';
import { SettingsPage } from './pages/SettingsPage';
import { SwapPage } from './pages/SwapPage';
import { SwapRoutesPage } from './pages/SwapRoutesPage';
import { useWallet } from './providers/WalletProvider';
import { routes } from './utils/routes';

export const App: React.FC<AppProps> = ({ config }) => {
Expand All @@ -20,6 +22,11 @@ export const App: React.FC<AppProps> = ({ config }) => {
};

export const AppDefault = () => {
const { attemptEagerConnect } = useWallet();
useEffect(() => {
attemptEagerConnect();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<AppContainer>
<Header />
Expand Down
9 changes: 8 additions & 1 deletion packages/widget/src/components/Header/WalletHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Box, IconButton, Typography } from '@mui/material';
import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate } from 'react-router-dom';
import { useWallet } from '../../providers/WalletProvider';
import { useWidgetConfig } from '../../providers/WidgetProvider';
import { routes } from '../../utils/routes';
import { HeaderAppBar } from './Header.style';

Expand Down Expand Up @@ -66,8 +67,14 @@ export const WalletHeader: React.FC = () => {

const ConnectButton = () => {
const { pathname } = useLocation();
const config = useWidgetConfig();
const { connect: walletConnect } = useWallet();
const navigate = useNavigate();
const connect = () => {
const connect = async () => {
if (config.disableInternalWalletManagement) {
await walletConnect();
return;
}
navigate(routes.selectWallet);
};
return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {

export const SelectWalletPage = () => {
const { t } = useTranslation();

const navigate = useNavigate();
const { connect } = useWallet();
const containerElement = useScrollableContainer();
Expand Down
60 changes: 47 additions & 13 deletions packages/widget/src/providers/WalletProvider/WalletProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ const initialContext: WalletContextProps = {
switchChain: stub,
addChain: stub,
addToken: stub,
attemptEagerConnect: stub,
account: {},
};

Expand All @@ -49,51 +50,75 @@ export const WalletProvider: FC<PropsWithChildren<{}>> = ({ children }) => {
const connect = useCallback(
async (wallet?: Wallet) => {
if (config.disableInternalWalletManagement) {
// TODO
const signer = await config.walletCallbacks.connect();
const account = await extractAccountFromSigner(signer);
setAccount(account);
return;
}
await walletManagementConnect(wallet);
},
[config.disableInternalWalletManagement, walletManagementConnect],
[
config.disableInternalWalletManagement,
config.walletCallbacks,
walletManagementConnect,
],
);

const disconnect = useCallback(async () => {
if (config.disableInternalWalletManagement) {
await config.walletCallbacks.disconnect();
setAccount({});
return;
}
await walletManagementDisconnect();
}, [config.disableInternalWalletManagement, walletManagementDisconnect]);
}, [
config.disableInternalWalletManagement,
config.walletCallbacks,
walletManagementDisconnect,
]);

// only for injected wallets
const switchChain = useCallback(
async (chainId: number) => {
if (config.disableInternalWalletManagement) {
// TODO
return false;
const signer = await config.walletCallbacks.switchChain(chainId);
const account = await extractAccountFromSigner(signer);
setAccount(account);
}
return walletSwitchChain(chainId);
},
[config.disableInternalWalletManagement],
[config.disableInternalWalletManagement, config.walletCallbacks],
);

const addChain = useCallback(
async (chainId: number) => {
if (!config.disableInternalWalletManagement) {
await walletAddChain(chainId);
if (config.disableInternalWalletManagement) {
return config.walletCallbacks.addChain(chainId);
}
return walletAddChain(chainId);
},
[config.disableInternalWalletManagement],
[config.disableInternalWalletManagement, config.walletCallbacks],
);

const addToken = useCallback(
async (chainId: number, token: Token) => {
if (!config.disableInternalWalletManagement) {
await switchChainAndAddToken(chainId, token);
if (config.disableInternalWalletManagement) {
return config.walletCallbacks.addToken(token, chainId);
}
return switchChainAndAddToken(chainId, token);
},
[config.disableInternalWalletManagement],
[config.disableInternalWalletManagement, config.walletCallbacks],
);

const attemptEagerConnect = useCallback(async () => {
if (config.disableInternalWalletManagement) {
const signer = await config.walletCallbacks.provideSigner();
const account = await extractAccountFromSigner(signer);
console.log(account);
setAccount((oldAccount) => ({ ...account }));
}
}, [config.disableInternalWalletManagement, config.walletCallbacks]);

// keep account information up to date
useEffect(() => {
const updateAccount = async () => {
Expand All @@ -112,9 +137,18 @@ export const WalletProvider: FC<PropsWithChildren<{}>> = ({ children }) => {
switchChain,
addChain,
addToken,
attemptEagerConnect,
account,
}),
[account, addChain, addToken, connect, disconnect, switchChain],
[
account,
addChain,
addToken,
connect,
disconnect,
switchChain,
attemptEagerConnect,
],
);

return (
Expand Down
3 changes: 2 additions & 1 deletion packages/widget/src/providers/WalletProvider/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ import { Signer } from 'ethers';

export interface WalletContextProps {
account: WalletAccount;
addChain(chainId: number): Promise<void>;
addChain(chainId: number): Promise<boolean>;
addToken(chainId: number, token: Token): Promise<void>;
disconnect(): void;
switchChain(chainId: number): Promise<boolean>;
connect(wallet?: Wallet | undefined): Promise<void>;
attemptEagerConnect(): Promise<void>;
}

export interface WalletAccount {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export const WidgetProvider: React.FC<
return config;
}
}, [config, fromChain, fromToken, toChain, toToken]);

return (
<WidgetContext.Provider value={value}>{children}</WidgetContext.Provider>
);
Expand Down
13 changes: 7 additions & 6 deletions packages/widget/src/types/widget.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ChainKey } from '@lifinance/sdk';
import { ChainKey, Token } from '@lifinance/sdk';
import { PaletteMode, PaletteOptions, Shape } from '@mui/material';
import { TypographyOptions } from '@mui/material/styles/createTypography';
import { Signer } from 'ethers';
Expand All @@ -12,11 +12,12 @@ export type ThemeConfig = {
};

export interface WidgetWalletCallbacks {
connect(): Signer;
disconnect(): void;
provideSigner(): Signer;
switchChain(): Signer;
addToken(): void;
connect(): Promise<Signer>;
disconnect(): Promise<void>;
provideSigner(): Promise<Signer | undefined>;
switchChain(reqChainId: number): Promise<Signer>;
addToken(token: Token, chainId: number): Promise<void>;
addChain(chainId: number): Promise<boolean>;
}

interface WidgetConfigBase {
Expand Down
Loading