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 Unit tests in Wallet migration branch #988

Open
wants to merge 50 commits into
base: new-delegate-factory
Choose a base branch
from
Open
Changes from 1 commit
Commits
Show all changes
50 commits
Select commit Hold shift + click to select a range
29c4c2a
Add wagmi config and start replacing web3-react
hernandoagf Mar 4, 2025
ead5e44
Replace network param from web3-react hooks
hernandoagf Mar 5, 2025
b9bb625
Remove chain id and address imports from web3-react
hernandoagf Mar 5, 2025
629ddb0
Add wagmi cli and generate abis
hernandoagf Mar 5, 2025
3aa106f
Add wagmi CLI and and start implementing read hooks
hernandoagf Mar 5, 2025
ed060be
Replace DSR logic to use bigint
hernandoagf Mar 6, 2025
428b258
Replace remaining read contract calls for Viem read contracts
hernandoagf Mar 6, 2025
11f0211
Update some BigNumber references to big int
hernandoagf Mar 6, 2025
b81512b
Update first write hook to wagmi flow
hernandoagf Mar 6, 2025
61bbfd0
Update approve write hook to new flow
hernandoagf Mar 7, 2025
1048323
Update MKR deposit hook to new write flow
hernandoagf Mar 7, 2025
4648e8d
Update MKR withdraw hooks to new flow
hernandoagf Mar 7, 2025
90af873
Update ESM burn write hook to new flow
hernandoagf Mar 7, 2025
03465be
Migrate the ESM shutdown write hook to new flow
hernandoagf Mar 7, 2025
b4b44fd
Migrate delegate create write hook to new flow
hernandoagf Mar 7, 2025
09a28d4
Migrate executive vote hooks to new flow
hernandoagf Mar 7, 2025
9be0b77
Migrate poll creation hook to new flow
hernandoagf Mar 7, 2025
6b2cafe
Migrate delegate lock hook to new flow
hernandoagf Mar 10, 2025
1f09bd6
Migrate delegate free hook to new flow
hernandoagf Mar 10, 2025
4a00ce4
Update poll vote and gasless vote flows to use Viem
hernandoagf Mar 11, 2025
24fb0e6
Remove dethcrypto/eth-sdk packages and related code
hernandoagf Mar 11, 2025
f537ecc
Replace ethers references for viem
hernandoagf Mar 11, 2025
610b388
Update lockfile
hernandoagf Mar 11, 2025
26e8549
Remove remaining Ethers references
hernandoagf Mar 12, 2025
e24c0cf
Replace all bignumber references for bigint
hernandoagf Mar 12, 2025
5f916a1
Remove unused dependencies and code
hernandoagf Mar 13, 2025
9d24302
Fix issue when fetching logs
hernandoagf Mar 13, 2025
e7f5331
Update typescript to v5 and theme-ui to v0.16
hernandoagf Mar 13, 2025
fa2a2c8
Merge branch 'new-delegate-factory' into wallet-refactor
hernandoagf Mar 14, 2025
1215752
Fix big int formatting issues
hernandoagf Mar 14, 2025
0ffd12b
Remove unnecessary step in CI
hernandoagf Mar 14, 2025
61a3653
Fix wallet connection in e2e tests
hernandoagf Mar 14, 2025
da6192c
Fix wallet connection in e2e tests
hernandoagf Mar 14, 2025
36e576c
Fixes for e2e tests
hernandoagf Mar 14, 2025
d59b4e5
Merge branch 'new-delegate-factory' into wallet-refactor
hernandoagf Mar 14, 2025
c747d26
Handle 0n balance
adamgoth Mar 17, 2025
30a6fdc
Remove ethers peer dependency from defender relay client
hernandoagf Mar 17, 2025
85af6a0
Update file extensions
hernandoagf Mar 17, 2025
74e4745
Install Vitest packages
hernandoagf Mar 17, 2025
aa34188
Update Jest references to Vitest
hernandoagf Mar 17, 2025
ca85138
Fix tests
hernandoagf Mar 18, 2025
74e4e86
Fix remaining unit tests
hernandoagf Mar 18, 2025
e1f04d8
Add test:ci command
hernandoagf Mar 18, 2025
4c26f33
Add missing coverage package
hernandoagf Mar 18, 2025
ad1b8d2
Merge branch 'new-delegate-factory' into wallet-refactor
hernandoagf Mar 18, 2025
cee83c2
Remove new BigNumber references
hernandoagf Mar 18, 2025
d321973
Merge branch 'wallet-refactor' into replace-jest-for-vitest
hernandoagf Mar 18, 2025
fda4d90
Merge branch 'new-delegate-factory' into replace-jest-for-vitest
hernandoagf Mar 18, 2025
29241f5
Update mock function
hernandoagf Mar 18, 2025
1379b00
Merge branch 'new-delegate-factory' into replace-jest-for-vitest
hernandoagf Mar 19, 2025
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
Next Next commit
Add wagmi config and start replacing web3-react
hernandoagf committed Mar 4, 2025
commit 29c4c2acf31a7c0f0983797a23092ac28cf7d703
6 changes: 0 additions & 6 deletions __tests__/setup.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import '@testing-library/jest-dom';
import '@testing-library/jest-dom/extend-expect';
import { mockIntersectionObserver } from '../__tests__/helpers';
import { useWeb3React } from '@web3-react/core';
import { ethers } from 'ethers';
import { config } from 'lib/config';

@@ -40,11 +39,6 @@ jest.mock('modules/address/components/AddressIcon', () => {
ethers.utils.Logger.setLogLevel(ethers.utils.Logger.levels.ERROR);

beforeAll(async () => {
(useWeb3React as jest.Mock).mockReturnValue({
account: '',
activate: () => null
});

if (typeof window !== 'undefined') {
// https://jestjs.io/docs/en/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom
Object.defineProperty(window, 'matchMedia', {
6 changes: 4 additions & 2 deletions modules/address/components/AddressDelegatedTo.tsx
Original file line number Diff line number Diff line change
@@ -10,7 +10,6 @@ import { Box, Text, Flex, IconButton, Heading } from 'theme-ui';
import { useBreakpointIndex } from '@theme-ui/match-media';
import { Icon } from '@makerdao/dai-ui-icons';
import BigNumber from 'lib/bigNumberJs';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import Skeleton from 'modules/app/components/SkeletonThemed';
import { DelegationHistoryWithExpirationDate } from 'modules/delegates/types';
import { useState } from 'react';
@@ -23,6 +22,8 @@ import { parseUnits } from 'ethers/lib/utils';
import { formatValue } from 'lib/string';
import { DateWithHover } from 'modules/app/components/DateWithHover';
import EtherscanLink from 'modules/web3/components/EtherscanLink';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

type CollapsableRowProps = {
delegate: DelegationHistoryWithExpirationDate;
@@ -192,7 +193,8 @@ type AddressDelegatedToProps = {

const AddressDelegatedTo = ({ delegatedTo, totalDelegated }: AddressDelegatedToProps): JSX.Element => {
const bpi = useBreakpointIndex();
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);

return (
<Box>
6 changes: 4 additions & 2 deletions modules/address/components/AddressDetail.tsx
Original file line number Diff line number Diff line change
@@ -18,14 +18,16 @@ import AddressDelegatedTo from './AddressDelegatedTo';
import SkeletonThemed from 'modules/app/components/SkeletonThemed';
import { AddressMKRDelegatedStats } from './AddressMKRDelegatedStats';
import AddressIconBox from './AddressIconBox';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { ErrorBoundary } from 'modules/app/components/ErrorBoundary';
import Tabs from 'modules/app/components/Tabs';
import { useDelegatedTo } from 'modules/delegates/hooks/useDelegatedTo';
import { InternalLink } from 'modules/app/components/InternalLink';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

export function AddressDetail({ addressInfo }: { addressInfo: AddressApiResponse }): React.ReactElement {
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);
const { data: statsData } = useSWR<AddressAPIStats>(
addressInfo
? `/api/address/stats?address=${
6 changes: 4 additions & 2 deletions modules/address/components/AddressIconBox.tsx
Original file line number Diff line number Diff line change
@@ -12,12 +12,13 @@ import { Box, Text, Flex } from 'theme-ui';
import { Icon } from '@makerdao/dai-ui-icons';
import { Address } from './Address';
import Tooltip from 'modules/app/components/Tooltip';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { useAccount } from 'modules/app/hooks/useAccount';
import { useSingleDelegateInfo } from 'modules/delegates/hooks/useSingleDelegateInfo';
import { useVoteProxyAddress } from 'modules/app/hooks/useVoteProxyAddress';
import EtherscanLink from 'modules/web3/components/EtherscanLink';
import splitDelegateName from 'modules/delegates/helpers/splitDelegateName';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

type PropTypes = {
address: string;
@@ -32,7 +33,8 @@ export default function AddressIconBox({
width = 41,
limitTextLength = 0
}: PropTypes): React.ReactElement {
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);

const { account, voteProxyContractAddress, voteDelegateContractAddress } = useAccount();
const { data: delegate } = useSingleDelegateInfo(address);
39 changes: 6 additions & 33 deletions modules/address/components/Avatar.tsx
Original file line number Diff line number Diff line change
@@ -6,12 +6,9 @@ SPDX-License-Identifier: AGPL-3.0-or-later
*/

import { SupportedChainId } from 'modules/web3/constants/chainID';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { useEffect, useCallback, useState, ReactChild, CSSProperties } from 'react';
import { AvatarResolver } from '@ensdomains/ens-avatar';
import { useCallback, useState, ReactChild, CSSProperties } from 'react';
import Jazzicon from './Jazzicon';
import logger from 'lib/logger';
import { useEnsAvatar, useEnsName } from 'wagmi';

export interface AvatarProps {
size: number;
@@ -21,34 +18,10 @@ export interface AvatarProps {
}

export function Avatar({ size, address, defaultComponent, style }: AvatarProps): JSX.Element {
const { chainId, provider: library } = useWeb3();
const [avatarUri, setAvatarUri] = useState<string | null>(null);

useEffect(() => {
let mounted = true;

const fetchAvatarUri = async () => {
if (library && address && chainId !== SupportedChainId.TENDERLY) {
const avt = new AvatarResolver(library, { cache: 3600 /* cache for an hour */ });
try {
const ensName = await library.lookupAddress(address);
if (ensName) {
const uri = await avt.getAvatar(ensName, {});
if (uri && mounted) {
setAvatarUri(uri);
}
}
} catch (err) {
logger.error(err);
}
}
};

fetchAvatarUri();
return () => {
mounted = false;
};
}, [address, library]);
const { data: ensName } = useEnsName({ address: address as `0x${string}` });
const { data: avatarUri } = useEnsAvatar({
name: ensName || undefined
});

const [loaded, setLoaded] = useState(false);

99 changes: 99 additions & 0 deletions modules/app/components/Icon/index.tsx
Original file line number Diff line number Diff line change
@@ -156,6 +156,105 @@ const icons = {
/>
</g>
)
},
ethereum: {
viewBox: '0 0 24 24',
path: (
<>
<path
d="M12 23.9963C18.6274 23.9963 24 18.6245 24 11.9981C24 5.37174 18.6274 0 12 0C5.37258 0 0 5.37174 0 11.9981C0 18.6245 5.37258 23.9963 12 23.9963Z"
fill="#F2F4F7"
/>
<path
d="M6.75195 12.1619L12.3747 15.4254V9.64941L6.75195 12.1619Z"
fill="white"
fillOpacity="0.602"
/>
<g opacity="0.6">
<mask
id="mask0_3496_151481"
style={{ maskType: 'luminance' }}
maskUnits="userSpaceOnUse"
x="6"
y="9"
width="13"
height="7"
>
<path d="M6 9.39551H18.2759V15.8146H6V9.39551Z" fill="white" />
</mask>
<g mask="url(#mask0_3496_151481)">
<path
d="M12.1392 9.39551L6 12.1876L12.1392 15.8146L18.2759 12.1876L12.1392 9.39551Z"
fill="#010101"
/>
</g>
</g>
<g opacity="0.45">
<mask
id="mask1_3496_151481"
style={{ maskType: 'luminance' }}
maskUnits="userSpaceOnUse"
x="6"
y="2"
width="7"
height="14"
>
<path d="M6 2H12.1392V15.8131H6V2Z" fill="white" />
</mask>
<g mask="url(#mask1_3496_151481)">
<path d="M6 12.1861L12.1392 15.8131V2L6 12.1861Z" fill="#010101" />
</g>
</g>
<g opacity="0.8">
<mask
id="mask2_3496_151481"
style={{ maskType: 'luminance' }}
maskUnits="userSpaceOnUse"
x="12"
y="2"
width="7"
height="14"
>
<path d="M12.1426 2H18.2817V15.8131H12.1426V2Z" fill="white" />
</mask>
<g mask="url(#mask2_3496_151481)">
<path d="M12.1426 2V15.8131L18.2793 12.1861L12.1426 2Z" fill="#010101" />
</g>
</g>
<g opacity="0.45">
<mask
id="mask3_3496_151481"
style={{ maskType: 'luminance' }}
maskUnits="userSpaceOnUse"
x="6"
y="13"
width="7"
height="9"
>
<path d="M6 13.3516H12.1392V22.0004H6V13.3516Z" fill="white" />
</mask>
<g mask="url(#mask3_3496_151481)">
<path d="M6 13.3506L12.1392 21.9995V16.9776L6 13.3506Z" fill="#010101" />
</g>
</g>
<g opacity="0.8">
<mask
id="mask4_3496_151481"
style={{ maskType: 'luminance' }}
maskUnits="userSpaceOnUse"
x="12"
y="13"
width="7"
height="9"
>
<path d="M12.1426 13.3516H18.2841V22.0004H12.1426V13.3516Z" fill="white" />
</mask>
<g mask="url(#mask4_3496_151481)">
<path d="M12.1426 16.9786V22.0004L18.2841 13.3516L12.1426 16.9786Z" fill="#010101" />
</g>
</g>
</>
)
}
};

6 changes: 4 additions & 2 deletions modules/app/components/SystemStatsSidebar.tsx
Original file line number Diff line number Diff line change
@@ -19,13 +19,14 @@ import { useTokenBalance } from 'modules/web3/hooks/useTokenBalance';
import { useMkrOnHat } from 'modules/executive/hooks/useMkrOnHat';
import { formatValue } from 'lib/string';
import { useContractAddress } from 'modules/web3/hooks/useContractAddress';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { Tokens } from 'modules/web3/constants/tokens';
import { ArbitrumPollingAddressMap } from 'modules/web3/constants/addresses';
import { SupportedNetworks } from 'modules/web3/constants/networks';
import EtherscanLink from 'modules/web3/components/EtherscanLink';
import { DialogOverlay, DialogContent } from './Dialog';
import BoxWithClose from './BoxWithClose';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

type StatField =
| 'chief contract'
@@ -83,7 +84,8 @@ export default function SystemStatsSidebar({
fields: StatField[];
className?: string;
}): JSX.Element {
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);

const statsMap = {
'chief contract': key => {
6 changes: 4 additions & 2 deletions modules/app/components/TxFinal.tsx
Original file line number Diff line number Diff line change
@@ -9,8 +9,9 @@ SPDX-License-Identifier: AGPL-3.0-or-later
import { Box, Button, Flex, Text } from 'theme-ui';
import TxIndicators from 'modules/app/components/TxIndicators';
import { Transaction, TXMined } from 'modules/web3/types/transaction';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import EtherscanLink from 'modules/web3/components/EtherscanLink';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

export const TxFinal = ({
title,
@@ -29,7 +30,8 @@ export const TxFinal = ({
success: boolean;
children?: React.ReactNode;
}): React.ReactElement => {
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);

return (
<Flex sx={{ flexDirection: 'column', textAlign: 'center' }}>
6 changes: 4 additions & 2 deletions modules/app/components/TxInProgress.tsx
Original file line number Diff line number Diff line change
@@ -9,8 +9,9 @@ SPDX-License-Identifier: AGPL-3.0-or-later
import { Flex, Text, Box } from '@theme-ui/components';
import TxIndicators from 'modules/app/components/TxIndicators';
import { TXMined } from 'modules/web3/types/transaction';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import EtherscanLink from 'modules/web3/components/EtherscanLink';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

type Props = {
tx: any;
@@ -19,7 +20,8 @@ type Props = {
};

export const TxInProgress = ({ tx, txPending, setTxId }: Props): JSX.Element => {
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);

return (
<Flex sx={{ flexDirection: 'column', textAlign: 'center' }}>
8 changes: 0 additions & 8 deletions modules/app/components/__tests__/Header.spec.tsx
Original file line number Diff line number Diff line change
@@ -13,7 +13,6 @@ SPDX-License-Identifier: AGPL-3.0-or-later
import { screen } from '@testing-library/react';
import Header from '../layout/Header';
import { renderWithTheme as render } from '../../../../__tests__/helpers';
import { useWeb3React } from '@web3-react/core';
import { formatAddress } from 'lib/utils';
import { useSingleDelegateInfo } from 'modules/delegates/hooks/useSingleDelegateInfo';
import { useAccount } from 'modules/app/hooks/useAccount';
@@ -43,9 +42,6 @@ jest.mock('modules/web3/connections', () => ({ connectorToWalletName: () => null

describe('Header component', () => {
beforeEach(() => {
(useWeb3React as jest.Mock).mockReturnValue({
account: ''
});
(useSingleDelegateInfo as jest.Mock).mockReturnValue({ data: null });
(useAccount as jest.Mock).mockReturnValue({
account: ''
@@ -65,10 +61,6 @@ describe('Header component', () => {
test('display account when connected', async () => {
const address = '0x477b8D5eF7C2C42DB84deB555419cd817c336b6J';

(useWeb3React as jest.Mock).mockReturnValue({
account: address,
activate: () => null
});
(useAccount as jest.Mock).mockReturnValue({
account: address
});
6 changes: 4 additions & 2 deletions modules/app/components/layout/Header.tsx
Original file line number Diff line number Diff line change
@@ -20,9 +20,10 @@ import { InternalLink } from 'modules/app/components/InternalLink';
import { Menu, MenuButton, MenuItem, MenuList } from '@reach/menu-button';
import { useGasPrice } from 'modules/web3/hooks/useGasPrice';
import { ExternalLink } from '../ExternalLink';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { GASNOW_URL, SupportedNetworks } from 'modules/web3/constants/networks';
import { ClientRenderOnly } from '../ClientRenderOnly';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

const MenuItemContent = ({ label, icon }: { label: React.ReactNode; icon: string }) => {
return (
@@ -131,7 +132,8 @@ const Header = (): JSX.Element => {
const [showMobileMenu, setShowMobileMenu] = useState(false);
const bpi = useBreakpointIndex();
const { account } = useAccount();
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);
const { data: gas } = useGasPrice({ network });
const [mode, setMode] = useColorMode();
const [renderedMode, setRenderedMode] = useState('light');
9 changes: 5 additions & 4 deletions modules/app/components/layout/header/AccountBox.tsx
Original file line number Diff line number Diff line change
@@ -10,22 +10,23 @@ import { useState } from 'react';
import { Flex, Text, Box, Button } from 'theme-ui';
import { Icon } from '@makerdao/dai-ui-icons';
import { formatAddress } from 'lib/utils';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import AddressIcon from 'modules/address/components/AddressIcon';
import { WalletName } from 'modules/web3/constants/wallets';
import { InternalLink } from 'modules/app/components/InternalLink';
import EtherscanLink from 'modules/web3/components/EtherscanLink';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

type Props = {
address: string;
accountName?: WalletName;
accountName?: string;
change: () => void;
disconnect: () => void;
};

const AccountBox = ({ address, accountName, change, disconnect }: Props): JSX.Element => {
const [copied, setCopied] = useState(false);
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);

return (
<Flex sx={{ flexDirection: 'column' }}>
129 changes: 35 additions & 94 deletions modules/app/components/layout/header/AccountSelect.tsx
Original file line number Diff line number Diff line change
@@ -15,18 +15,13 @@ import TransactionBox from './TransactionBox';
import VotingWeight from './VotingWeight';
import ConnectWalletButton from 'modules/web3/components/ConnectWalletButton';
import { NetworkAlertModal, ChainIdError } from 'modules/web3/components/NetworkAlertModal';
import { useWeb3React } from '@web3-react/core';
import { ErrorBoundary } from '../../ErrorBoundary';
import { useRouter } from 'next/router';
import { isAndroid, isIOS } from 'react-device-detect';
import { SUPPORTED_WALLETS, WalletName, ConnectionType } from 'modules/web3/constants/wallets';
import { connectorToWalletName, getConnection } from 'modules/web3/connections';
import { isSupportedChain } from 'modules/web3/helpers/chain';
import { getIsMetaMask } from 'modules/web3/helpers/getIsMetaMask';
import logger from 'lib/logger';
import useSelectedConnectionStore from 'modules/app/stores/selectedConnection';
import { DialogContent, DialogOverlay } from '../../Dialog';
import { checkInjectedProvider } from 'modules/web3/helpers/checkInjectedProvider';
import { useAccount, useConnect, useDisconnect } from 'wagmi';
import { SupportedConnectors } from 'modules/web3/constants/networks';

const closeButtonStyle: ThemeUICSSObject = {
height: 4,
@@ -39,81 +34,45 @@ const closeButtonStyle: ThemeUICSSObject = {

const AccountSelect = (): React.ReactElement => {
const router = useRouter();
const { account: address, connector, chainId } = useWeb3React();
const { connectors, connect } = useConnect({
mutation: {
onSuccess: () => {
close();
},
onError: (e, { connector }) => {
logger.error(e);
let message = '';

if ('id' in connector && e.toString().includes('ProviderNotFoundError') && connector.id === 'safe') {
message = 'Please try connecting from within the Safe{Wallet} app.';
} else {
message = 'Something went wrong. Select an option to connect.';
}

setError(message);
}
}
});

const { disconnect } = useDisconnect();
const { address, connector: connectedConnector, chainId } = useAccount();

const [pending, txs] = useTransactionStore(state => [
state.transactions.findIndex(tx => tx.status === 'pending') > -1,
state.transactions
]);

const [showDialog, setShowDialog] = useState(false);
const [accountName, setAccountName] = useState<WalletName>();
const [changeWallet, setChangeWallet] = useState(false);
const [chainIdError, setChainIdError] = useState<ChainIdError>(null);
const setSelectedConnection = useSelectedConnectionStore(state => state.setSelectedConnection);

const close = () => {
setShowDialog(false);
setError(null);
};

const handleModalToggle = (connectionType: ConnectionType, shouldOpenModal: boolean) => {
if (connectionType === ConnectionType.WALLET_CONNECT) {
shouldOpenModal ? setShowDialog(true) : setTimeout(() => setShowDialog(false), 1500);
}
};

// Handles UI state for loading
const [loadingConnectors, setLoadingConnectors] = useState({});
const [error, setError] = useState<string | null>(null);

const handleError = e => {
logger.error(e);
let message = '';
if (e.toString().includes('NoSafeContext') || e.toString().includes('safe context')) {
message = 'Please try connecting from within the Gnosis Safe app.';
} else {
message = 'Something went wrong. Select an option to connect.';
}
setError(message);
};

// Handles the logic when clicking on a connector
const onClickConnection = async (connectionType: ConnectionType | undefined, name: WalletName) => {
if (!connectionType) return;
setError(null);
try {
const connection = getConnection(connectionType);

setLoadingConnectors({
[name]: true
});

// Temporarily close the connections modal to move focus to the WalletConnect modal
handleModalToggle(connectionType, false);

// This is needed because of this issue https://github.com/MetaMask/metamask-extension/issues/3133
checkInjectedProvider();

await connection.connector.activate();

setSelectedConnection(connection.type);

setChangeWallet(false);

setLoadingConnectors({
[name]: false
});
} catch (e) {
handleError(e);
setLoadingConnectors({
[name]: false
});
// Open modal again after failed WalletConnect connection to display the error
handleModalToggle(connectionType, true);
}
};

useEffect(() => {
setShowDialog(false);
}, [router.pathname]);
@@ -127,37 +86,25 @@ const AccountSelect = (): React.ReactElement => {
}
}, [chainId]);

const isMetaMask = getIsMetaMask();

const disconnect = () => {
setError(null);
if (connector?.deactivate) {
void connector.deactivate();
} else {
void connector.resetState();
}
};

const walletOptions = Object.keys(SUPPORTED_WALLETS).map((connectionName: WalletName, index) => (
const walletOptions = connectors.map((connector, index) => (
<Flex
key={connectionName}
key={connector.id}
sx={{ alignItems: 'center', justifyContent: 'space-between', mt: index !== 0 ? 3 : 0 }}
>
<Flex sx={{ alignItems: 'center' }}>
<Icon name={SUPPORTED_WALLETS[connectionName]?.name} color="text" />
<Text sx={{ ml: 3 }}>{SUPPORTED_WALLETS[connectionName]?.name}</Text>
<Icon
name={connector.id === 'safe' ? SupportedConnectors.GNOSIS_SAFE : connector.name}
color="text"
/>
<Text sx={{ ml: 3 }}>{connector.name}</Text>
</Flex>
<Button
sx={{ minWidth: '120px' }}
variant="mutedOutline"
key={connectionName}
onClick={
(isAndroid || isIOS) && !isMetaMask && SUPPORTED_WALLETS[connectionName]?.deeplinkUri
? () => window.location.replace(SUPPORTED_WALLETS[connectionName]?.deeplinkUri || '')
: () => onClickConnection(SUPPORTED_WALLETS[connectionName]?.connectionType, connectionName)
}
key={connector.id}
onClick={() => connect({ connector })}
>
{loadingConnectors[connectionName] ? 'Loading...' : 'Select'}
Select
</Button>
</Flex>
));
@@ -172,12 +119,6 @@ const AccountSelect = (): React.ReactElement => {
</Flex>
);

useEffect(() => {
if (connector) {
setAccountName(connectorToWalletName(connector));
}
}, [address]);

return (
<Box sx={{ ml: ['auto', 3, 0] }}>
<NetworkAlertModal chainIdError={chainIdError} deactivate={disconnect} />
@@ -212,7 +153,7 @@ const AccountSelect = (): React.ReactElement => {
<ErrorBoundary componentName="Account Details">
<AccountBox
address={address}
accountName={accountName}
accountName={connectedConnector?.name}
change={() => setChangeWallet(true)}
disconnect={disconnect}
/>
92 changes: 29 additions & 63 deletions modules/app/components/layout/header/NetworkSelect.tsx
Original file line number Diff line number Diff line change
@@ -6,15 +6,12 @@ SPDX-License-Identifier: AGPL-3.0-or-later
*/

import React, { useState, useCallback } from 'react';
import React, { useState } from 'react';
import { Box, Flex, Text, Close, ThemeUICSSObject } from 'theme-ui';
import { Icon } from '@makerdao/dai-ui-icons';
import ConnectNetworkButton from 'modules/web3/components/ConnectNetworkButton';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { CHAIN_INFO } from 'modules/web3/constants/networks';
import { SupportedChainId } from 'modules/web3/constants/chainID';
import { isSupportedChain } from 'modules/web3/helpers/chain';
import { DialogContent, DialogOverlay } from '../../Dialog';
import { useChains, useClient, useSwitchChain } from 'wagmi';
import Icon from 'modules/app/components/Icon';

export type ChainIdError = null | 'network mismatch' | 'unsupported network';

@@ -45,81 +42,50 @@ const closeButtonStyle: ThemeUICSSObject = {
};

const NetworkSelect = (): React.ReactElement => {
const { chainId, account, connector } = useWeb3();
const client = useClient();
const chains = useChains();
const { switchChain } = useSwitchChain();
const [error, setError] = useState<any>(undefined);

const switchChain = useCallback(
async (desiredChainId: number) => {
// if we're already connected to the desired chain, return
if (desiredChainId === chainId) {
setError(undefined);
return;
const handleSwitchChain = (chainId: number) => {
switchChain(
{ chainId },
{
onSettled: () => {
close();
}
}

// if they want to connect to the default chain and we're already connected, return
if (desiredChainId === -1 && chainId !== undefined) {
setError(undefined);
return;
}

try {
await connector.activate(desiredChainId === -1 ? undefined : desiredChainId);
setError(undefined);
} catch (err) {
setError(err);
}
},
[connector, chainId, setError]
);

// We can only switch MM network if injected connector is active
const disabled = !account;
);
};

const [showDialog, setShowDialog] = useState(false);

const close = () => setShowDialog(false);

const isProduction = process.env.NODE_ENV === 'production' && process.env.NEXT_PUBLIC_VERCEL_ENV !== 'development';

const networkOptions = Object.keys(CHAIN_INFO)
.filter(
k => CHAIN_INFO[k].type === 'normal'
)
.filter(k => !isProduction || CHAIN_INFO[k].showInProduction)
.map(chainKey => (
<Flex
sx={walletButtonStyle}
key={CHAIN_INFO[chainKey].label}
onClick={() => {
switchChain(CHAIN_INFO[chainKey].chainId);
setShowDialog(false);
}}
>
<Icon name={CHAIN_INFO[chainKey].label} sx={{ width: '22px', height: '22px' }} />
<Text sx={{ ml: 3 }}>{CHAIN_INFO[chainKey].label}</Text>
</Flex>
));
const networkOptions = chains.map(chain => (
<Flex sx={walletButtonStyle} key={chain.id} onClick={() => handleSwitchChain(chain.id)}>
<Icon name="ethereum" sx={{ width: '22px', height: '22px' }} />
<Text sx={{ ml: 3 }}>{chain.name}</Text>
</Flex>
));

return (
<Box sx={{ ml: ['auto', 3, 0] }}>
{chainId && (
<ConnectNetworkButton
onClickConnect={() => {
setError(undefined);
setShowDialog(true);
}}
activeNetwork={isSupportedChain(chainId) ? CHAIN_INFO[chainId].label : 'Unsupported Network'}
disabled={disabled}
/>
)}
<ConnectNetworkButton
onClickConnect={() => {
setError(undefined);
setShowDialog(true);
}}
activeNetwork={client?.chain.name || 'Ethereum'}
/>

<DialogOverlay isOpen={showDialog} onDismiss={close}>
<DialogContent ariaLabel="Change Network" widthDesktop="400px">
<Flex sx={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
<Text variant="microHeading">Switch Network</Text>
<Close sx={closeButtonStyle} aria-label="close" onClick={close} />
</Flex>
{chainId && networkOptions}
{networkOptions}
{error && (
<Text sx={{ mt: 2 }} variant="error">
An error has occured.
6 changes: 4 additions & 2 deletions modules/app/components/layout/header/TransactionBox.tsx
Original file line number Diff line number Diff line change
@@ -10,8 +10,9 @@ import { Flex, Text, Spinner } from 'theme-ui';
import { Icon } from '@makerdao/dai-ui-icons';

import { Transaction } from 'modules/web3/types/transaction';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import EtherscanLink from 'modules/web3/components/EtherscanLink';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

type Props = {
tx: Transaction;
@@ -22,7 +23,8 @@ type MainProps = {
txs: Transaction[];
};
const TransactionRow = ({ tx, index }: Props): JSX.Element => {
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);

return (
<Flex
4 changes: 2 additions & 2 deletions modules/app/context/AccountContext.tsx
Original file line number Diff line number Diff line change
@@ -15,7 +15,7 @@ import { useCurrentUserVoteProxyContract } from '../hooks/useCurrentUserVoteProx
import { useCurrentUserVoteProxyOldContract } from '../hooks/useCurrentUserVoteProxyOldContract';
import { useVoteProxyAddress } from '../hooks/useVoteProxyAddress';
import { useVoteProxyOldAddress } from '../hooks/useVoteProxyOldAddress';
import { useWeb3React } from '@web3-react/core';
import { useAccount } from 'wagmi';

interface AccountContextProps {
account?: string;
@@ -46,7 +46,7 @@ type PropTypes = {
};

export const AccountProvider = ({ children }: PropTypes): React.ReactElement => {
const { account } = useWeb3React();
const { address: account } = useAccount();

const { data: voteDelegateContract } = useCurrentUserVoteDelegateContract();
const { data: voteDelegateContractAddress, mutate: mutateVoteDelegate } = useVoteDelegateAddress(account);
6 changes: 4 additions & 2 deletions modules/app/hooks/useVoteProxyAddress.ts
Original file line number Diff line number Diff line change
@@ -9,7 +9,8 @@ SPDX-License-Identifier: AGPL-3.0-or-later
import useSWR from 'swr';
import { useContracts } from 'modules/web3/hooks/useContracts';
import { getVoteProxyAddresses, VoteProxyAddresses } from '../helpers/getVoteProxyAddresses';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

type VoteProxyAddressResponse = {
data?: VoteProxyAddresses;
@@ -19,7 +20,8 @@ type VoteProxyAddressResponse = {

export const useVoteProxyAddress = (account?: string): VoteProxyAddressResponse => {
const { voteProxyFactory } = useContracts();
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);

const { data, error } = useSWR(account ? `${account}/vote-proxy-address` : null, async () => {
return await getVoteProxyAddresses(voteProxyFactory, account as string, network);
6 changes: 4 additions & 2 deletions modules/app/hooks/useVoteProxyOldAddress.ts
Original file line number Diff line number Diff line change
@@ -10,9 +10,10 @@ import useSWR from 'swr';
import { useContracts } from 'modules/web3/hooks/useContracts';
import { getVoteProxyAddresses, VoteProxyAddresses } from '../helpers/getVoteProxyAddresses';
import { MainnetSdk } from '@dethcrypto/eth-sdk-client';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';

import { SupportedNetworks } from 'modules/web3/constants/networks';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

type VoteProxyAddressResponse = {
data?: VoteProxyAddresses;
@@ -22,7 +23,8 @@ type VoteProxyAddressResponse = {

export const useVoteProxyOldAddress = (account?: string): VoteProxyAddressResponse => {
const { voteProxyFactoryOld } = useContracts() as MainnetSdk;
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);

const { data, error } = useSWR(
account && network !== SupportedNetworks.MAINNET ? `${account}/vote-proxy-address` : null,
6 changes: 4 additions & 2 deletions modules/delegates/components/DelegateDetail.tsx
Original file line number Diff line number Diff line change
@@ -29,22 +29,24 @@ import LastVoted from 'modules/polling/components/LastVoted';
import { useLockedMkr } from 'modules/mkr/hooks/useLockedMkr';
import DelegatedByAddress from 'modules/delegates/components/DelegatedByAddress';
import { useAccount } from 'modules/app/hooks/useAccount';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { Address } from 'modules/address/components/Address';
import { formatDelegationHistory } from '../helpers/formatDelegationHistory';
import { CoreUnitModal } from './modals/CoreUnitModal';
import { CoreUnitButton } from './modals/CoreUnitButton';
import { InternalLink } from 'modules/app/components/InternalLink';
import DelegateContractInfo from 'modules/migration/components/DelegateContractInfo';
import EtherscanLink from 'modules/web3/components/EtherscanLink';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

type PropTypes = {
delegate: Delegate;
};

export function DelegateDetail({ delegate }: PropTypes): React.ReactElement {
const { voteDelegateAddress } = delegate;
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);
const { cache } = useSWRConfig();
const [showCoreUnitModal, setShowCoreUnitModal] = useState(false);

9 changes: 6 additions & 3 deletions modules/delegates/components/DelegatedByAddress.tsx
Original file line number Diff line number Diff line change
@@ -15,14 +15,15 @@ import Skeleton from 'modules/app/components/SkeletonThemed';
import Tooltip from 'modules/app/components/Tooltip';
import { DelegationHistory } from 'modules/delegates/types';
import { formatDateWithTime } from 'lib/datetime';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { SupportedNetworks } from 'modules/web3/constants/networks';
import { BigNumber } from 'ethers';
import { formatValue } from 'lib/string';
import { parseUnits } from 'ethers/lib/utils';
import { BigNumberJS } from 'lib/bigNumberJs';
import AddressIconBox from 'modules/address/components/AddressIconBox';
import EtherscanLink from 'modules/web3/components/EtherscanLink';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

type DelegatedByAddressProps = {
delegators: DelegationHistory[];
@@ -107,7 +108,8 @@ const CollapsableRow = ({ delegator, network, bpi, totalDelegated }: Collapsable
)}
<Text key={blockTimestamp} variant="smallCaps" sx={{ pl: 2 }}>
{`${formatValue(
BigNumber.from(lockAmount.indexOf('-') === 0 ? lockAmount.substring(1) : lockAmount), 'wad'
BigNumber.from(lockAmount.indexOf('-') === 0 ? lockAmount.substring(1) : lockAmount),
'wad'
)}${bpi > 0 ? ' MKR' : ''}`}
</Text>
<Text key={blockTimestamp} variant="smallCaps" sx={{ pl: 2 }}>
@@ -176,7 +178,8 @@ const CollapsableRow = ({ delegator, network, bpi, totalDelegated }: Collapsable

const DelegatedByAddress = ({ delegators, totalDelegated }: DelegatedByAddressProps): JSX.Element => {
const bpi = useBreakpointIndex();
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);

const [sortBy, setSortBy] = useState({
type: 'mkr',
6 changes: 4 additions & 2 deletions modules/delegates/components/DelegatesSystemInfo.tsx
Original file line number Diff line number Diff line change
@@ -14,9 +14,10 @@ import { DelegatesAPIStats } from '../types';
import { useContractAddress } from 'modules/web3/hooks/useContractAddress';
import { useTotalSupply } from 'modules/web3/hooks/useTotalSupply';
import { BigNumberWAD } from 'modules/web3/constants/numbers';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { Tokens } from 'modules/web3/constants/tokens';
import EtherscanLink from 'modules/web3/components/EtherscanLink';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

export function DelegatesSystemInfo({
stats,
@@ -27,7 +28,8 @@ export function DelegatesSystemInfo({
}): React.ReactElement {
const delegateFactoryAddress = useContractAddress('voteDelegateFactory');
const oldDelegateFactoryAddress = useContractAddress('voteDelegateFactoryOld');
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);

const { data: totalMkr } = useTotalSupply(Tokens.MKR);

6 changes: 4 additions & 2 deletions modules/delegates/components/modals/Confirm.tsx
Original file line number Diff line number Diff line change
@@ -8,10 +8,11 @@ SPDX-License-Identifier: AGPL-3.0-or-later

import { Button, Flex, Text } from 'theme-ui';
import { Delegate, DelegateInfo, DelegatePaginated } from '../../types';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { BigNumber } from 'ethers';
import { formatValue } from 'lib/string';
import EtherscanLink from 'modules/web3/components/EtherscanLink';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

type Props = {
mkrToDeposit: BigNumber;
@@ -22,7 +23,8 @@ type Props = {

export const ConfirmContent = ({ mkrToDeposit, delegate, onClick, onBack }: Props): JSX.Element => {
const { address, voteDelegateAddress } = delegate;
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);

return (
<Flex sx={{ flexDirection: 'column', textAlign: 'center' }}>
6 changes: 4 additions & 2 deletions modules/delegates/hooks/useSingleDelegateInfo.ts
Original file line number Diff line number Diff line change
@@ -6,9 +6,10 @@ SPDX-License-Identifier: AGPL-3.0-or-later
*/

import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import useSWR, { useSWRConfig } from 'swr';
import { DelegateInfo } from '../types';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

type DelegateInfoResponse = {
data: DelegateInfo | null;
@@ -17,7 +18,8 @@ type DelegateInfoResponse = {
};

export const useSingleDelegateInfo = (address: string): DelegateInfoResponse => {
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);
const { cache } = useSWRConfig();
const dataKey = `/api/delegates/${address}/info?network=${network}`;

6 changes: 4 additions & 2 deletions modules/esm/components/ESMHistory.tsx
Original file line number Diff line number Diff line change
@@ -9,19 +9,21 @@ SPDX-License-Identifier: AGPL-3.0-or-later
import BigNumber from 'lib/bigNumberJs';
import { Card, Text, Spinner } from 'theme-ui';
import { useBreakpointIndex } from '@theme-ui/match-media';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { formatRound } from 'lib/utils';
import { formatDateWithTime, formatDateWithoutTime } from 'lib/datetime';
import { AllEsmJoinsRecord } from 'modules/gql/generated/graphql';
import EtherscanLink from 'modules/web3/components/EtherscanLink';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

type Props = {
allEsmJoins: AllEsmJoinsRecord[] | undefined;
};

const ESMHistory = ({ allEsmJoins }: Props): JSX.Element => {
const bpi = useBreakpointIndex();
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);

return (
<Card mt={3} p={3} pb={4}>
6 changes: 4 additions & 2 deletions modules/esm/components/ShutdownModal.tsx
Original file line number Diff line number Diff line change
@@ -12,9 +12,10 @@ import { formatValue } from 'lib/string';
import { Icon } from '@makerdao/dai-ui-icons';
import { TXMined } from 'modules/web3/types/transaction';
import { BigNumber } from 'ethers';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { useEsmShutdown } from '../hooks/useEsmShutdown';
import EtherscanLink from 'modules/web3/components/EtherscanLink';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

const ModalContent = ({
setShowDialog,
@@ -24,7 +25,8 @@ const ModalContent = ({
thresholdAmount?: BigNumber;
}): React.ReactElement => {
const [step, setStep] = useState('default');
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);
const { shutdown, tx } = useEsmShutdown();

const close = () => {
6 changes: 4 additions & 2 deletions modules/esm/components/burnModal/BurnTxSuccess.tsx
Original file line number Diff line number Diff line change
@@ -8,12 +8,14 @@ SPDX-License-Identifier: AGPL-3.0-or-later

import { Flex, Button, Text, Close } from 'theme-ui';
import { Icon } from '@makerdao/dai-ui-icons';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { TXMined } from 'modules/web3/types/transaction';
import EtherscanLink from 'modules/web3/components/EtherscanLink';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

const BurnTxSuccess = ({ tx, close }) => {
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);

return (
<Flex sx={{ flexDirection: 'column', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
6 changes: 4 additions & 2 deletions modules/executive/components/VoteModal/DefaultView.tsx
Original file line number Diff line number Diff line change
@@ -25,8 +25,9 @@ import { useVoteProxyVote } from 'modules/executive/hooks/useVoteProxyVote';
import { useAccount } from 'modules/app/hooks/useAccount';
import { formatValue } from 'lib/string';
import { BigNumber, utils } from 'ethers';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import EtherscanLink from 'modules/web3/components/EtherscanLink';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

export default function DefaultVoteModalView({
proposal,
@@ -48,7 +49,8 @@ export default function DefaultVoteModalView({
const bpi = useBreakpointIndex();

const { voteProxyContractAddress, voteDelegateContractAddress, votingAccount } = useAccount();
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);
const { data: lockedMkr, mutate: mutateLockedMkr } = useLockedMkr(votingAccount);

const spellAddress = proposal ? proposal.address : address ? address : '';
6 changes: 4 additions & 2 deletions modules/executive/hooks/useMkrOnHat.ts
Original file line number Diff line number Diff line change
@@ -10,7 +10,8 @@ import useSWR from 'swr';
import { useContracts } from 'modules/web3/hooks/useContracts';
import { BigNumber } from 'ethers';
import { getChiefApprovals } from 'modules/web3/api/getChiefApprovals';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

type MkrOnHatResponse = {
data?: BigNumber;
@@ -20,7 +21,8 @@ type MkrOnHatResponse = {
};

export const useMkrOnHat = (): MkrOnHatResponse => {
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);
const { chief } = useContracts();

const { data, error, mutate } = useSWR(`${chief.address}/mkr-on-hat`, async () => {
6 changes: 4 additions & 2 deletions modules/executive/hooks/useSpellData.ts
Original file line number Diff line number Diff line change
@@ -8,8 +8,9 @@ SPDX-License-Identifier: AGPL-3.0-or-later

import useSWR, { useSWRConfig } from 'swr';
import { SpellData } from 'modules/executive/types/spellData';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { fetchJson } from 'lib/fetchJson';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

type SpellDataResponse = {
data?: SpellData;
@@ -19,7 +20,8 @@ type SpellDataResponse = {
};

export const useSpellData = (proposalAddress: string): SpellDataResponse => {
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);

const dataKey = proposalAddress
? `/api/executive/analyze-spell/${proposalAddress}?network=${network}`
4 changes: 2 additions & 2 deletions modules/gql/hooks/useGqlQuery.ts
Original file line number Diff line number Diff line change
@@ -7,8 +7,8 @@ SPDX-License-Identifier: AGPL-3.0-or-later
*/

import useSWR from 'swr';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { gqlRequest } from '../gqlRequest';
import { useChainId } from 'wagmi';

type GqlQueryResponse = {
data: any;
@@ -25,7 +25,7 @@ export const useGqlQuery = ({
variables?: Record<string, string>;
cacheKey: string;
}): GqlQueryResponse => {
const { chainId } = useWeb3();
const chainId = useChainId();

const { data, error } = useSWR(`gql-query/${chainId}/${cacheKey}`, async () => {
return await gqlRequest({ chainId, query, variables });
6 changes: 4 additions & 2 deletions modules/gql/hooks/useLandingPageDelegates.ts
Original file line number Diff line number Diff line change
@@ -6,16 +6,18 @@ SPDX-License-Identifier: AGPL-3.0-or-later
*/

import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import useSWR, { SWRResponse, useSWRConfig } from 'swr';
import { DelegatesPaginatedAPIResponse } from 'modules/delegates/types';
import { DelegateInfo } from 'modules/delegates/types';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

export const useLandingPageDelegates = (): [
SWRResponse<DelegatesPaginatedAPIResponse>,
SWRResponse<DelegateInfo[]>
] => {
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);
const { cache } = useSWRConfig();
const delegatesDataKey = `/api/delegates/v2?network=${network}&delegateType=ALIGNED&pageSize=5&orderBy=MKR&orderDirection=DESC`;
const delegatesInfoDataKey = `/api/delegates/info?network=${network}`;
6 changes: 4 additions & 2 deletions modules/home/components/Participation.tsx
Original file line number Diff line number Diff line change
@@ -14,11 +14,12 @@ import { format, sub } from 'date-fns';
import ParticipationChart from './ParticipationChart';
import forumPosts from '../data/forumPosts.json';
import { DelegateInfo, DelegatePaginated } from 'modules/delegates/types';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import SkeletonThemed from 'modules/app/components/SkeletonThemed';
import { AllLocksResponse, ForumPost } from '../types/participation';
import DelegateAvatarNameLight from 'modules/delegates/components/DelegateAvatarNameLight';
import { ErrorBoundary } from 'modules/app/components/ErrorBoundary';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

const ForumPosts = ({ posts, bpi }: { posts: ForumPost[]; bpi: number }) => {
return (
@@ -81,7 +82,8 @@ export default function Participation({
activeDelegates: DelegateInfo[] | DelegatePaginated[];
bpi: number;
}): React.ReactElement {
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);
const MONTHS_PAST = 6;
// This makes sure the timestamp is the same throughout the day so the SWR cache-key doesn't change
const unixtimeStart =
7 changes: 5 additions & 2 deletions modules/migration/hooks/useLinkedDelegateInfo.tsx
Original file line number Diff line number Diff line change
@@ -6,9 +6,10 @@ SPDX-License-Identifier: AGPL-3.0-or-later
*/

import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { useDelegateContractExpirationDate } from 'modules/delegates/hooks/useDelegateContractExpirationDate';
import { getLatestOwnerFromOld, getOriginalOwnerFromNew } from 'modules/migration/delegateAddressLinks';
import { useAccount, useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

export function useLinkedDelegateInfo(): {
latestOwnerAddress?: string;
@@ -17,7 +18,9 @@ export function useLinkedDelegateInfo(): {
originalOwnerConnected: boolean;
latestOwnerHasDelegateContract: boolean;
} {
const { account: address, network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);
const { address } = useAccount();

const {
data: { expiration: delegateContractExpirationDate }
6 changes: 4 additions & 2 deletions modules/mkr/hooks/useMKRVotingWeight.ts
Original file line number Diff line number Diff line change
@@ -6,9 +6,10 @@ SPDX-License-Identifier: AGPL-3.0-or-later
*/

import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import useSWR, { useSWRConfig } from 'swr';
import { getMKRVotingWeight, MKRVotingWeightResponse } from '../helpers/getMKRVotingWeight';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

type VotingWeightResponse = {
data?: MKRVotingWeightResponse;
@@ -26,7 +27,8 @@ export const useMKRVotingWeight = ({
// they can have voting power through their delegate contract, but the balance is not theirs
excludeDelegateOwnerBalance?: boolean;
}): VotingWeightResponse => {
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);
const { cache } = useSWRConfig();

const dataKey = `/user/polling-voting-weight/${address}/${network}`;
65 changes: 65 additions & 0 deletions modules/wagmi/config/config.default.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { createConfig, createStorage, fallback, http, noopStorage } from 'wagmi';
import { mainnet } from 'wagmi/chains';
import { SupportedChainId } from 'modules/web3/constants/chainID';
import { coinbaseWallet, metaMask, safe, walletConnect } from 'wagmi/connectors';

export const tenderly = {
id: SupportedChainId.TENDERLY as const,
name: 'mainnet_sep_30_0',
network: 'tenderly',
// This is used by RainbowKit to display a chain icon for small screens
iconUrl: 'tokens/weth.svg',
nativeCurrency: {
decimals: 18,
name: 'Ethereum',
symbol: 'ETH'
},
rpcUrls: {
public: { http: [`https://virtual.mainnet.rpc.tenderly.co/${process.env.NEXT_PUBLIC_TENDERLY_RPC_KEY}`] },
default: { http: [`https://virtual.mainnet.rpc.tenderly.co/${process.env.NEXT_PUBLIC_TENDERLY_RPC_KEY}`] }
},
blockExplorers: {
default: { name: '', url: '' }
}
};

const connectors = [
metaMask(),
walletConnect({
name: 'Sky Governance Portal',
projectId: process.env.NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID || 'd5c6af7c0680adbaad12f33744ee4413'
}),
coinbaseWallet(),
safe()
];

export const wagmiConfigDev = createConfig({
chains: [mainnet, tenderly],
ssr: true,
connectors,
transports: {
[mainnet.id]: fallback([
http(`https://mainnet.infura.io/v3/${process.env.INFURA_KEY}`),
http(`https://eth-mainnet.g.alchemy.com/v2/${process.env.ALCHEMY_KEY}`)
]),
[tenderly.id]: http(`https://virtual.mainnet.rpc.tenderly.co/${process.env.NEXT_PUBLIC_TENDERLY_RPC_KEY}`)
},
multiInjectedProviderDiscovery: false,
storage: createStorage({
storage: typeof window !== 'undefined' && window.localStorage ? window.localStorage : noopStorage,
key: 'wagmi-dev'
})
});

export const wagmiConfigProd = createConfig({
chains: [mainnet],
ssr: true,
connectors,
transports: {
[mainnet.id]: fallback([
http(`https://mainnet.infura.io/v3/${process.env.INFURA_KEY}`),
http(`https://eth-mainnet.g.alchemy.com/v2/${process.env.ALCHEMY_KEY}`)
])
},
multiInjectedProviderDiscovery: false
});
4 changes: 2 additions & 2 deletions modules/web3/components/ConnectNetworkButton.tsx
Original file line number Diff line number Diff line change
@@ -6,7 +6,7 @@ SPDX-License-Identifier: AGPL-3.0-or-later
*/

import { Icon } from '@makerdao/dai-ui-icons';
import Icon from 'modules/app/components/Icon';
import { Button, Flex, Text } from 'theme-ui';

type Props = {
@@ -46,7 +46,7 @@ export default function ConnectNetworkButton({
>
<Flex sx={{ alignItems: 'center' }}>
<Flex sx={{ mr: [1, 2] }}>
<Icon name={activeNetwork} sx={{ width: '22px', height: '22px' }} />
<Icon name="ethereum" sx={{ width: '22px', height: '22px' }} />
</Flex>
<Text data-testid="active-network-name">{activeNetwork}</Text>
</Flex>
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -34,11 +34,13 @@
"@metamask/post-message-stream": "^7.0.0",
"@metamask/providers": "^14.0.2",
"@octokit/core": "^4.0.5",
"@rainbow-me/rainbowkit": "^2.2.4",
"@reach/dialog": "^0.16.2",
"@reach/listbox": "^0.18.0",
"@reach/menu-button": "^0.16.2",
"@reach/tabs": "^0.10.3",
"@reach/tooltip": "^0.16.2",
"@tanstack/react-query": "^5.67.1",
"@theme-ui/color": "^0.14.4",
"@theme-ui/css": "^0.12.0",
"@theme-ui/match-media": "^0.12.0",
@@ -90,6 +92,8 @@
"unified": "^10.1.2",
"uuid": "^8.3.0",
"valid-url": "^1.0.9",
"viem": "^2.23.6",
"wagmi": "^2.14.12",
"zustand": "^2.2.3"
},
"devDependencies": {
117 changes: 63 additions & 54 deletions pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -10,7 +10,6 @@ import { AppProps } from 'next/app';
import { SWRConfig } from 'swr';
import { ThemeProvider, Flex, Box } from 'theme-ui';
import { Global } from '@emotion/core';
import { ethers } from 'ethers';
import '@reach/dialog/styles.css';
import '@reach/listbox/styles.css';
import '@reach/menu-button/styles.css';
@@ -29,15 +28,21 @@ import debug from 'debug';
import Banner from 'modules/app/components/layout/header/Banner';
import bannerContent from 'modules/home/data/bannerContent.json';
import { MigrationBanner } from 'modules/migration/components/MigrationBanner';
import { Web3Provider } from 'modules/web3/components/Web3Provider';
import React, { useMemo } from 'react';
import { Analytics } from '@vercel/analytics/react';
import { WagmiProvider } from 'wagmi';
import { wagmiConfigDev, wagmiConfigProd } from 'modules/wagmi/config/config.default';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Web3Provider } from 'modules/web3/components/Web3Provider';

const vitalslog = debug('govpo:vitals');
export const reportWebVitals = vitalslog;

const App = ({ Component, pageProps }: AppProps): React.ReactElement => {
ethers.utils.Logger.setLogLevel(ethers.utils.Logger.levels.ERROR);
const isProduction =
process.env.NODE_ENV === 'production' && process.env.NEXT_PUBLIC_VERCEL_ENV !== 'development';
const wagmiConfig = isProduction ? wagmiConfigProd : wagmiConfigDev;
const queryClient = new QueryClient();

const activeBannerContent = bannerContent.find(({ active }) => active === true);
const banners = useMemo(() => {
@@ -55,60 +60,64 @@ const App = ({ Component, pageProps }: AppProps): React.ReactElement => {
);
}, []);
return (
<Web3Provider>
{/* @ts-ignore */}
<ThemeProvider theme={theme}>
<Analytics />
<WagmiProvider config={wagmiConfig}>
<QueryClientProvider client={queryClient}>
<Web3Provider>
{/* @ts-ignore */}
<ThemeProvider theme={theme}>
<Analytics />

<NextNprogress
color="#1aab9b"
startPosition={0.3}
stopDelayMs={200}
height={3}
showOnShallow={true}
options={{ showSpinner: false }}
/>
<AccountProvider>
<BallotProvider>
<HeadComponent />
<SWRConfig
value={{
// default to 60 second refresh intervals
refreshInterval: 60000,
revalidateOnMount: true,
fetcher: url => fetchJson(url)
}}
>
<Global
styles={{
'*': {
WebkitFontSmoothing: 'antialiased',
MozOsxFontSmoothing: 'grayscale'
}
}}
/>
<NextNprogress
color="#1aab9b"
startPosition={0.3}
stopDelayMs={200}
height={3}
showOnShallow={true}
options={{ showSpinner: false }}
/>
<AccountProvider>
<BallotProvider>
<HeadComponent />
<SWRConfig
value={{
// default to 60 second refresh intervals
refreshInterval: 60000,
revalidateOnMount: true,
fetcher: url => fetchJson(url)
}}
>
<Global
styles={{
'*': {
WebkitFontSmoothing: 'antialiased',
MozOsxFontSmoothing: 'grayscale'
}
}}
/>

<Flex
sx={{
flexDirection: 'column',
variant: 'layout.root',
<Flex
sx={{
flexDirection: 'column',
variant: 'layout.root',

paddingTop: 5,
overflowX: 'hidden'
}}
>
{banners && <Box sx={{ pb: 3 }}>{banners}</Box>}
<Box sx={{ px: [3, 4] }}>
<Component {...pageProps} />
</Box>
<Header />
</Flex>
</SWRConfig>
</BallotProvider>
</AccountProvider>
<ToastContainer position="top-right" theme="light" />
</ThemeProvider>
</Web3Provider>
paddingTop: 5,
overflowX: 'hidden'
}}
>
{banners && <Box sx={{ pb: 3 }}>{banners}</Box>}
<Box sx={{ px: [3, 4] }}>
<Component {...pageProps} />
</Box>
<Header />
</Flex>
</SWRConfig>
</BallotProvider>
</AccountProvider>
<ToastContainer position="top-right" theme="light" />
</ThemeProvider>
</Web3Provider>
</QueryClientProvider>
</WagmiProvider>
);
};

9 changes: 6 additions & 3 deletions pages/account.tsx
Original file line number Diff line number Diff line change
@@ -20,7 +20,6 @@ import Withdraw from 'modules/mkr/components/Withdraw';
import { Icon } from '@makerdao/dai-ui-icons';
import { HeadComponent } from 'modules/app/components/layout/Head';
import { useAccount } from 'modules/app/hooks/useAccount';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { AddressDetail } from 'modules/address/components/AddressDetail';
import ManageDelegation from 'modules/delegates/components/ManageDelegation';
import { useDelegateCreate } from 'modules/delegates/hooks/useDelegateCreate';
@@ -34,9 +33,12 @@ import AccountSelect from 'modules/app/components/layout/header/AccountSelect';
import { ClientRenderOnly } from 'modules/app/components/ClientRenderOnly';
import EtherscanLink from 'modules/web3/components/EtherscanLink';
import { DialogContent, DialogOverlay } from 'modules/app/components/Dialog';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

const AccountPage = (): React.ReactElement => {
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);
const {
account,
mutate: mutateAccount,
@@ -45,7 +47,8 @@ const AccountPage = (): React.ReactElement => {
votingAccount
} = useAccount();

const { latestOwnerConnected, latestOwnerHasDelegateContract, originalOwnerAddress } = useLinkedDelegateInfo();
const { latestOwnerConnected, latestOwnerHasDelegateContract, originalOwnerAddress } =
useLinkedDelegateInfo();
const { data: addressInfo, error: errorLoadingAddressInfo } = useAddressInfo(votingAccount, network);
const { data: originalOwnerContractAddress } = useVoteDelegateAddress(originalOwnerAddress);
const { data: chiefBalance } = useLockedMkr(voteProxyContractAddress || account);
6 changes: 4 additions & 2 deletions pages/address/[address]/index.tsx
Original file line number Diff line number Diff line change
@@ -23,11 +23,12 @@ import { AddressDetail } from 'modules/address/components/AddressDetail';
import { DelegateDetail, DelegatesSystemInfo } from 'modules/delegates/components';
import { HeadComponent } from 'modules/app/components/layout/Head';
import ManageDelegation from 'modules/delegates/components/ManageDelegation';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import useSWR, { useSWRConfig } from 'swr';
import { ErrorBoundary } from 'modules/app/components/ErrorBoundary';
import { InternalLink } from 'modules/app/components/InternalLink';
import { DelegatesAPIStats, DelegatesPaginatedAPIResponse } from 'modules/delegates/types';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

const AddressView = ({
addressInfo,
@@ -114,7 +115,8 @@ const AddressView = ({
export default function AddressPage(): JSX.Element {
const router = useRouter();
const { address } = router.query;
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);
const { cache } = useSWRConfig();

const dataKeyAccount = `/api/address/${address}?network=${network}`;
6 changes: 4 additions & 2 deletions pages/custom-spell/[address].tsx
Original file line number Diff line number Diff line change
@@ -10,7 +10,6 @@ import { useEffect } from 'react';
import { Button, Card, Flex, Text, Heading, Box } from 'theme-ui';
import PrimaryLayout from 'modules/app/components/layout/layouts/Primary';
import { useState } from 'react';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { useAccount } from 'modules/app/hooks/useAccount';
import { useVotedProposals } from 'modules/executive/hooks/useVotedProposals';
import VoteModal from 'modules/executive/components/VoteModal';
@@ -19,6 +18,8 @@ import { SpellData } from 'modules/executive/types';
import { DEFAULT_NETWORK } from 'modules/web3/constants/networks';
import { SpellDetailsOverview } from 'modules/executive/components/SpellDetailsOverview';
import EtherscanLink from 'modules/web3/components/EtherscanLink';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

type Props = {
spellAddress: string;
@@ -27,7 +28,8 @@ type Props = {

export default function CustomSpellAddress({ spellAddress, spellDetails }: Props): JSX.Element {
const [voting, setVoting] = useState(false);
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);
const { account, votingAccount } = useAccount();

const { data: votedProposals, mutate: mutateVotedProposals } = useVotedProposals();
6 changes: 4 additions & 2 deletions pages/custom-spell/index.tsx
Original file line number Diff line number Diff line change
@@ -10,7 +10,6 @@ import { useEffect } from 'react';
import { Button, Card, Flex, Text, Input, Spinner, Heading } from 'theme-ui';
import PrimaryLayout from 'modules/app/components/layout/layouts/Primary';
import { useState } from 'react';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { useAccount } from 'modules/app/hooks/useAccount';
import { useVotedProposals } from 'modules/executive/hooks/useVotedProposals';
import VoteModal from 'modules/executive/components/VoteModal';
@@ -19,13 +18,16 @@ import { SpellData } from 'modules/executive/types';
import { SpellDetailsOverview } from 'modules/executive/components/SpellDetailsOverview';
import logger from 'lib/logger';
import { toast } from 'react-toastify';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

export default function CustomSpell(): JSX.Element {
const [spellAddress, setSpellAddress] = useState<string | null>(null);
const [spellData, setSpellData] = useState<SpellData | null | undefined>(undefined);
const [loading, setLoading] = useState(false);
const [voting, setVoting] = useState(false);
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);
const { account, votingAccount } = useAccount();

const { data: votedProposals, mutate: mutateVotedProposals } = useVotedProposals();
6 changes: 4 additions & 2 deletions pages/dashboard/index.tsx
Original file line number Diff line number Diff line change
@@ -11,7 +11,6 @@ import { Box, Button, Card, Flex, Heading, Text, Input } from 'theme-ui';
import PrimaryLayout from 'modules/app/components/layout/layouts/Primary';
import Stack from 'modules/app/components/layout/layouts/Stack';
import { HeadComponent } from 'modules/app/components/layout/Head';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { fetchJson } from 'lib/fetchJson';
import { ErrorBoundary } from 'modules/app/components/ErrorBoundary';
import {
@@ -26,9 +25,12 @@ import {
import { invalidateCache } from 'modules/cache/invalidateCache';
import { toast } from 'react-toastify';
import { getCacheInfo } from 'modules/cache/getCacheInfo';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

const DashboardPage = (): React.ReactElement => {
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);
const [loading, setLoading] = useState(false);
const [pollId, setPollId] = useState('');
const [password, setPassword] = useState('');
9 changes: 6 additions & 3 deletions pages/delegates/index.tsx
Original file line number Diff line number Diff line change
@@ -29,7 +29,6 @@ import { DelegatesStatusFilter } from 'modules/delegates/components/filters/Dele
import { DelegatesSortFilter } from 'modules/delegates/components/filters/DelegatesSortFilter';
import { DelegatesShowExpiredFilter } from 'modules/delegates/components/filters/DelegatesShowExpiredFilter';
import { useAccount } from 'modules/app/hooks/useAccount';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { ErrorBoundary } from 'modules/app/components/ErrorBoundary';
import { InternalLink } from 'modules/app/components/InternalLink';
import { fetchDelegatesPageData } from 'modules/delegates/api/fetchDelegatesPageData';
@@ -39,6 +38,8 @@ import { getTestBreakout } from 'modules/app/helpers/getTestBreakout';
import { useIntersectionObserver } from 'modules/app/hooks/useIntersectionObserver';
import { DelegatesPaginatedAPIResponse } from 'modules/delegates/types';
import SkeletonThemed from 'modules/app/components/SkeletonThemed';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

type DelegatesPageProps = DelegatesPaginatedAPIResponse & {
seed: number;
@@ -58,7 +59,8 @@ const Delegates = ({
paginationInfo: propPaginationInfo,
seed: propSeed
}: DelegatesPageProps) => {
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);
const { voteDelegateContractAddress } = useAccount();
const [
showAligned,
@@ -442,7 +444,8 @@ export default function DelegatesPage({
paginationInfo: prefetchedPaginationInfo,
seed
}: DelegatesPageProps): JSX.Element {
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);

const fallbackData = isDefaultNetwork(network)
? {
9 changes: 6 additions & 3 deletions pages/executive.tsx
Original file line number Diff line number Diff line change
@@ -37,7 +37,6 @@ import useUiFiltersStore from 'modules/app/stores/uiFilters';
import { Proposal } from 'modules/executive/types';
import { HeadComponent } from 'modules/app/components/layout/Head';
import { useAccount } from 'modules/app/hooks/useAccount';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { isDefaultNetwork } from 'modules/web3/helpers/networks';
import { useContracts } from 'modules/web3/hooks/useContracts';
import { MainnetSdk } from '@dethcrypto/eth-sdk-client';
@@ -49,6 +48,8 @@ import SkeletonThemed from 'modules/app/components/SkeletonThemed';
import { SupportedNetworks } from 'modules/web3/constants/networks';
import { ExecutivePageData, fetchExecutivePageData } from 'modules/executive/api/fetchExecutivePageData';
import { InternalLink } from 'modules/app/components/InternalLink';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

const MigrationBadge = ({ children, py = [2, 3] }) => (
<Badge
@@ -78,7 +79,8 @@ export const ExecutiveOverview = ({ proposals }: { proposals?: Proposal[] }): JS
voteProxyOldContractAddress,
votingAccount
} = useAccount();
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);

const [showHistorical, setShowHistorical] = React.useState(false);

@@ -446,7 +448,8 @@ export const ExecutiveOverview = ({ proposals }: { proposals?: Proposal[] }): JS
export default function ExecutiveOverviewPage({
proposals: prefetchedProposals
}: ExecutivePageData): JSX.Element {
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);

const fallbackData = isDefaultNetwork(network)
? {
9 changes: 6 additions & 3 deletions pages/executive/[proposal-id].tsx
Original file line number Diff line number Diff line change
@@ -36,7 +36,6 @@ import { HeadComponent } from 'modules/app/components/layout/Head';
import { BigNumber } from 'ethers';
import { ZERO_ADDRESS } from 'modules/web3/constants/addresses';
import { useAccount } from 'modules/app/hooks/useAccount';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { ErrorBoundary } from 'modules/app/components/ErrorBoundary';
import AddressIconBox from 'modules/address/components/AddressIconBox';
import { DEFAULT_NETWORK } from 'modules/web3/constants/networks';
@@ -45,6 +44,8 @@ import { StatusText } from 'modules/app/components/StatusText';
import EtherscanLink from 'modules/web3/components/EtherscanLink';
import { trimProposalKey } from 'modules/executive/helpers/trimProposalKey';
import { parseUnits } from 'ethers/lib/utils';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

type Props = {
proposal: Proposal;
@@ -86,7 +87,8 @@ const ProposalView = ({ proposal, spellDiffs }: Props): JSX.Element => {
const { account } = useAccount();

const bpi = useBreakpointIndex();
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);
const { cache } = useSWRConfig();

const dataKey = `/api/executive/supporters?network=${network}`;
@@ -419,7 +421,8 @@ export default function ProposalPage({
const [_proposal, _setProposal] = useState<Proposal>();
const [error, setError] = useState<string>();
const { query } = useRouter();
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);

/**Disabling spell-effects until multi-transactions endpoint is ready */
// const spellAddress = prefetchedProposal?.address;
6 changes: 4 additions & 2 deletions pages/index.tsx
Original file line number Diff line number Diff line change
@@ -20,7 +20,6 @@ import { PlayButton } from 'modules/home/components/PlayButton';
import PageLoadingPlaceholder from 'modules/app/components/PageLoadingPlaceholder';
import VideoModal from 'modules/app/components/VideoModal';
import { isDefaultNetwork } from 'modules/web3/helpers/networks';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { ErrorBoundary } from 'modules/app/components/ErrorBoundary';
import Skeleton from 'react-loading-skeleton';
import { SupportedNetworks } from 'modules/web3/constants/networks';
@@ -42,6 +41,8 @@ import { useVotedProposals } from 'modules/executive/hooks/useVotedProposals';
import { fetchLandingPageData } from 'modules/home/api/fetchLandingPageData';
import { LandingPageData } from 'modules/home/api/fetchLandingPageData';
import { useLandingPageDelegates } from 'modules/gql/hooks/useLandingPageDelegates';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

const LandingPage = ({
proposals,
@@ -293,7 +294,8 @@ export default function Index({
hat: prefetchedHat,
mkrInChief: prefetchedMkrInChief
}: LandingPageData): JSX.Element {
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);
const [delegatesData, delegatesInfo] = useLandingPageDelegates();
const fallbackData = isDefaultNetwork(network)
? {
9 changes: 6 additions & 3 deletions pages/polling.tsx
Original file line number Diff line number Diff line change
@@ -35,7 +35,6 @@ import BallotStatus from 'modules/polling/components/BallotStatus';
import PageLoadingPlaceholder from 'modules/app/components/PageLoadingPlaceholder';
import { useAllUserVotes } from 'modules/polling/hooks/useAllUserVotes';
import { HeadComponent } from 'modules/app/components/layout/Head';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { useAccount } from 'modules/app/hooks/useAccount';
import { isDefaultNetwork } from 'modules/web3/helpers/networks';
import { ErrorBoundary } from 'modules/app/components/ErrorBoundary';
@@ -46,6 +45,8 @@ import PollsSort from 'modules/polling/components/filters/PollsSort';
import { PollsPaginatedResponse } from 'modules/polling/types/pollsResponse';
import { PollOrderByEnum, PollStatusEnum } from 'modules/polling/polling.constants';
import SkeletonThemed from 'modules/app/components/SkeletonThemed';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

export type PollingPageProps = PollsPaginatedResponse & {
activePollIds: number[];
@@ -107,7 +108,8 @@ const PollingOverview = ({
}, [router]);

const bpi = useBreakpointIndex();
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);

const [loading, setLoading] = useState(fetchOnLoad);
const [isRendering, setIsRendering] = useState(true);
@@ -489,7 +491,8 @@ export default function PollingOverviewPage({
paginationInfo: prefetchedPaginationInfo,
activePollIds: prefetchedActivePollIds
}: PollingPageProps): JSX.Element {
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);

const fallbackData = isDefaultNetwork(network)
? {
6 changes: 4 additions & 2 deletions pages/polling/[poll-hash].tsx
Original file line number Diff line number Diff line change
@@ -37,7 +37,6 @@ import BigNumber from 'lib/bigNumberJs';
import PollWinningOptionBox from 'modules/polling/components/PollWinningOptionBox';
import { usePollTally } from 'modules/polling/hooks/usePollTally';
import { useAccount } from 'modules/app/hooks/useAccount';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { fetchSinglePoll } from 'modules/polling/api/fetchPollBy';
import { DEFAULT_NETWORK, SupportedNetworks } from 'modules/web3/constants/networks';
import { ErrorBoundary } from 'modules/app/components/ErrorBoundary';
@@ -48,6 +47,8 @@ import usePollsStore from 'modules/polling/stores/polls';
import { DialogOverlay, DialogContent } from 'modules/app/components/Dialog';
import BoxWithClose from 'modules/app/components/BoxWithClose';
import { PollOrderByEnum } from 'modules/polling/polling.constants';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

const editMarkdown = (content: string) => {
// hide the duplicate proposal title
@@ -396,7 +397,8 @@ export default function PollPage({ poll: prefetchedPoll }: { poll?: Poll }): JSX
const [_poll, _setPoll] = useState<Poll>();
const [error, setError] = useState<string>();
const { query, isFallback } = useRouter();
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);

// fetch poll contents at run-time if on any network other than the default
useEffect(() => {
9 changes: 6 additions & 3 deletions pages/polling/review.tsx
Original file line number Diff line number Diff line change
@@ -23,7 +23,6 @@ import ReviewBox from 'modules/polling/components/review/ReviewBox';
import PageLoadingPlaceholder from 'modules/app/components/PageLoadingPlaceholder';
import { objectToGetParams, getNumberWithOrdinal } from 'lib/utils';
import { useAccount } from 'modules/app/hooks/useAccount';
import { useWeb3 } from 'modules/web3/hooks/useWeb3';
import { isDefaultNetwork } from 'modules/web3/helpers/networks';
import { BallotContext } from 'modules/polling/context/BallotContext';
import ActivePollsBox from 'modules/polling/components/review/ActivePollsBox';
@@ -36,6 +35,8 @@ import { ErrorBoundary } from 'modules/app/components/ErrorBoundary';
import AccountNotConnected from 'modules/web3/components/AccountNotConnected';
import EtherscanLink from 'modules/web3/components/EtherscanLink';
import { TagCount } from 'modules/app/types/tag';
import { useChainId } from 'wagmi';
import { chainIdToNetworkName } from 'modules/web3/helpers/chain';

export type PollingReviewPageProps = {
polls: PollListItem[];
@@ -45,7 +46,8 @@ export type PollingReviewPageProps = {

const PollingReview = ({ polls: activePolls, activePollIds, tags }: PollingReviewPageProps) => {
const bpi = useBreakpointIndex();
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);

const [showMarkdownModal, setShowMarkdownModal] = useState(false);
const [modalPollId, setModalPollId] = useState<number | undefined>(undefined);
@@ -338,7 +340,8 @@ export default function PollingReviewPage({
activePollIds: prefetchedActivePollIds,
tags: prefetchedTags
}: PollingReviewPageProps): JSX.Element {
const { network } = useWeb3();
const chainId = useChainId();
const network = chainIdToNetworkName(chainId);

const fallbackData = isDefaultNetwork(network)
? {
1,474 changes: 1,317 additions & 157 deletions yarn.lock

Large diffs are not rendered by default.