Skip to content

Commit

Permalink
Wagmi & Viem Migration (#1423)
Browse files Browse the repository at this point in the history
  • Loading branch information
AtelyPham authored Jul 21, 2023
1 parent 6c000a5 commit 7fad099
Show file tree
Hide file tree
Showing 169 changed files with 4,682 additions and 13,366 deletions.
1 change: 1 addition & 0 deletions .github/workflows/check-build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ jobs:
touch apps/bridge-dapp/.env
echo NX_BRIDGE_APP_DOMAIN=${{ secrets.NX_BRIDGE_APP_DOMAIN }} >> apps/bridge-dapp/.env
echo WALLET_CONNECT_PROJECT_ID=${{ secrets.WALLET_CONNECT_PROJECT_ID }} >> apps/bridge-dapp/.env
echo HOSTED_ORBIT_MULTLICALL3_ADDRESS=${{ secrets.HOSTED_ORBIT_MULTLICALL3_ADDRESS }} >> apps/bridge-dapp/.env
echo ATHENA_ORBIT_MULTICALL3_DEPLOYMENT_BLOCK=${{ secrets.ATHENA_ORBIT_MULTICALL3_DEPLOYMENT_BLOCK }} >> apps/bridge-dapp/.env
echo HERMES_ORBIT_MULTICALL3_DEPLOYMENT_BLOCK=${{ secrets.HERMES_ORBIT_MULTICALL3_DEPLOYMENT_BLOCK }} >> apps/bridge-dapp/.env
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/deploy-bridge-dapp-dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ jobs:
run: |
touch apps/bridge-dapp/.env
echo NX_BRIDGE_APP_DOMAIN=${{ secrets.NX_BRIDGE_APP_DOMAIN }} >> apps/bridge-dapp/.env
echo WALLET_CONNECT_PROJECT_ID=${{ secrets.WALLET_CONNECT_PROJECT_ID }} >> apps/bridge-dapp/.env
echo HOSTED_ORBIT_MULTLICALL3_ADDRESS=${{ secrets.HOSTED_ORBIT_MULTLICALL3_ADDRESS }} >> apps/bridge-dapp/.env
echo ATHENA_ORBIT_MULTICALL3_DEPLOYMENT_BLOCK=${{ secrets.ATHENA_ORBIT_MULTICALL3_DEPLOYMENT_BLOCK }} >> apps/bridge-dapp/.env
echo HERMES_ORBIT_MULTICALL3_DEPLOYMENT_BLOCK=${{ secrets.HERMES_ORBIT_MULTICALL3_DEPLOYMENT_BLOCK }} >> apps/bridge-dapp/.env
Expand Down
4 changes: 4 additions & 0 deletions .github/workflows/deploy-webbsite-dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ jobs:
run: yarn add -D -W netlify-cli

- name: Build project
# Fix: JavaScript heap out of memory
# https://github.com/actions/runner-images/issues/70#issuecomment-1191708172
env:
NODE_OPTIONS: '--max_old_space_size=4096'
run: yarn build:webbsite

- name: Deploy site
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ jobs:
touch apps/bridge-dapp/.env
echo NX_BRIDGE_APP_DOMAIN=${{ secrets.NX_BRIDGE_APP_DOMAIN }} >> apps/bridge-dapp/.env
echo WALLET_CONNECT_PROJECT_ID=${{ secrets.WALLET_CONNECT_PROJECT_ID }} >> apps/bridge-dapp/.env
echo HOSTED_ORBIT_MULTLICALL3_ADDRESS=${{ secrets.HOSTED_ORBIT_MULTLICALL3_ADDRESS }} >> apps/bridge-dapp/.env
echo ATHENA_ORBIT_MULTICALL3_DEPLOYMENT_BLOCK=${{ secrets.ATHENA_ORBIT_MULTICALL3_DEPLOYMENT_BLOCK }} >> apps/bridge-dapp/.env
echo HERMES_ORBIT_MULTICALL3_DEPLOYMENT_BLOCK=${{ secrets.HERMES_ORBIT_MULTICALL3_DEPLOYMENT_BLOCK }} >> apps/bridge-dapp/.env
Expand Down
2 changes: 2 additions & 0 deletions apps/bridge-dapp/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ NX_BRIDGE_APP_DOMAIN=http:localhost:3000

POLKADOT_TEST_ACCOUNT_ADDRESS="<YOUR_POLKADOT_TEST_ACCOUNT_ADDRESS>"

WALLET_CONNECT_PROJECT_ID="<WALLET_CONNECT_PROJECT_ID>"

# If you want to enable the local orbit integration,
# you need to set the local anchor addresses of the local orbit instance
LOCAL_ORBIT_ANCHOR_ADDRESS=""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export const ChainListCardWrapper: FC<ChainListCardWrapperProps> = ({
return getActiveSourceChains(apiConfig.chains).map((val) => {
const currency = getNativeCurrencyFromConfig(
apiConfig.currencies,
calculateTypedChainId(val.chainType, val.chainId)
calculateTypedChainId(val.chainType, val.id)
);

return {
Expand Down Expand Up @@ -84,7 +84,7 @@ export const ChainListCardWrapper: FC<ChainListCardWrapperProps> = ({
const isSupported =
activeWallet &&
activeWallet.supportedChainIds.includes(
calculateTypedChainId(chain.chainType, chain.chainId)
calculateTypedChainId(chain.chainType, chain.id)
);

let bridge: Bridge | undefined;
Expand Down
60 changes: 32 additions & 28 deletions apps/bridge-dapp/src/components/Header/WalletButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ import {
import { FC, useCallback, useMemo, useState } from 'react';
import { ClearDataModal } from './ClearDataModal';
import { HeaderButton } from './HeaderButton';
import { WebbWeb3Provider, isViemError } from '@webb-tools/web3-api-provider';
import { WebbError, WebbErrorCodes } from '@webb-tools/dapp-types';

export const WalletButton: FC<{ account: Account; wallet: WalletConfig }> = ({
account,
Expand All @@ -35,14 +37,20 @@ export const WalletButton: FC<{ account: Account; wallet: WalletConfig }> = ({
// Clear data modal
const [isOpen, setIsOpen] = useState(false);

const { activeChain, noteManager, purgeNoteAccount, inactivateApi } =
useWebContext();
const {
activeApi,
activeChain,
noteManager,
purgeNoteAccount,
inactivateApi,
} = useWebContext();

// Get all note, syncNotes and isSyncingNote function
const {
allNotes,
isSyncingNote,
syncNotes: handleSyncNotes,
syncNotesProgress,
} = useNoteAccount();

const { setMainComponent, notificationApi, logger } = useWebbUI();
Expand Down Expand Up @@ -78,13 +86,11 @@ export const WalletButton: FC<{ account: Account; wallet: WalletConfig }> = ({

// Calculate the account explorer url
const accountExplorerUrl = useMemo(() => {
if (!activeChain?.blockExplorerStub) return '#';
if (!activeChain?.blockExplorers) return '#';

const uri = activeChain.blockExplorerStub.endsWith('/')
? `address/${account.address}`
: `/address/${account.address}`;
const url = activeChain.blockExplorers.default.url;

return `${activeChain.blockExplorerStub}${uri}`;
return new URL(`/address/${account.address}`, url).toString();
}, [activeChain, account]);

// Clear data function
Expand Down Expand Up @@ -148,32 +154,25 @@ export const WalletButton: FC<{ account: Account; wallet: WalletConfig }> = ({

// Funciton to switch account within the connected wallet
const handleSwitchAccount = useCallback(async () => {
if (!activeChain) {
notificationApi({
variant: 'error',
message: 'No active chain',
});
// Switch account only support on web3 provider
if (!activeApi || !(activeApi instanceof WebbWeb3Provider)) {
return;
}

if (
typeof window !== 'undefined' &&
typeof window.ethereum !== 'undefined'
) {
try {
await window.ethereum.request({
method: 'wallet_requestPermissions',
params: [
{
eth_accounts: {},
},
],
});
} catch (error) {
console.log(error);
try {
const walletClient = activeApi.walletClient;

await walletClient.requestPermissions({ eth_accounts: {} });
} catch (error) {
let message = WebbError.from(WebbErrorCodes.SwitchAccountFailed).message;

if (isViemError(error)) {
message = error.shortMessage;
}

notificationApi({ variant: 'error', message });
}
}, [activeChain, notificationApi]);
}, [activeApi, notificationApi]);

// Disconnect function
// TODO: The disconnect function does not work properly
Expand Down Expand Up @@ -276,6 +275,11 @@ export const WalletButton: FC<{ account: Account; wallet: WalletConfig }> = ({
<div className="flex items-center space-x-1">
<Button
isLoading={isSyncingNote}
loadingText={
Number.isNaN(syncNotesProgress)
? ''
: `${syncNotesProgress.toFixed(2)}%`
}
onClick={() => handleSyncNotes(handleNewNotes, handleSyncNotes)}
variant="utility"
>
Expand Down
18 changes: 14 additions & 4 deletions apps/bridge-dapp/src/components/Header/WalletModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export const WalletModal: FC = () => {

const { notificationApi } = useWebbUI();

const { chains } = useWebContext();
const { apiConfig, chains } = useWebContext();

const chain = useMemo(() => {
if (!selectedChain) {
Expand All @@ -38,15 +38,25 @@ export const WalletModal: FC = () => {
return selectedChain;
}, [chains, selectedChain]);

const supportedWalletCfgs = useMemo(() => {
return chain.wallets
.map((walletId) => apiConfig.wallets[walletId])
.filter((w) => !!w);
}, [apiConfig.wallets, chain.wallets]);

// Get the current failed or connecting wallet
const getCurrentWallet = useCallback(() => {
const walletId = failedWalletId ?? connectingWalletId;
if (!walletId) {
return undefined;
}

return chain.wallets[walletId];
}, [chain, failedWalletId, connectingWalletId]);
if (!chain.wallets.includes(walletId)) {
return undefined;
}

return apiConfig.wallets[walletId];
}, [failedWalletId, connectingWalletId, chain.wallets, apiConfig.wallets]);

const isNotInstalledError = useMemo(() => {
if (!connectError) {
Expand Down Expand Up @@ -140,7 +150,7 @@ export const WalletModal: FC = () => {
isCenter
>
<WalletConnectionCard
wallets={Object.values(chain.wallets)}
wallets={supportedWalletCfgs}
onWalletSelect={handleWalletSelect}
onClose={() => toggleModal(false)}
connectingWalletId={connectingWalletId}
Expand Down
15 changes: 13 additions & 2 deletions apps/bridge-dapp/src/components/tables/LoadingTable.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { Spinner } from '@webb-tools/icons';
import { useNoteAccount } from '@webb-tools/react-hooks';
import { Typography } from '@webb-tools/webb-ui-components';
import { useEffect, useState } from 'react';

export const LoadingTable = () => {
const { syncNotesProgress } = useNoteAccount();

return (
<div className="h-[511px] bg-mono-0 dark:bg-mono-160 rounded-lg flex items-center justify-center">
<div>
Expand All @@ -11,7 +14,10 @@ export const LoadingTable = () => {
</div>

<Typography variant="h5" ta="center" fw="bold">
Syncing notes
Syncing notes{' '}
{Number.isNaN(syncNotesProgress)
? ''
: `${syncNotesProgress.toFixed(2)}%`}
</Typography>

<LoadingText />
Expand All @@ -38,7 +44,12 @@ const LoadingText = () => {
}, []);

return (
<Typography variant="body2" fw="semibold" className="!text-mono-100">
<Typography
ta="center"
variant="body2"
fw="semibold"
className="!text-mono-100"
>
Please wait a few minutes{`...`.slice(0, dots)}
</Typography>
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { useWebContext } from '@webb-tools/api-provider-environment';
import cx from 'classnames';
import { WebbError, WebbErrorCodes } from '@webb-tools/dapp-types';
import {
Download,
ExchangeLine,
InformationLine,
WalletLineIcon,
Download,
} from '@webb-tools/icons';
import { Web3Provider } from '@webb-tools/web3-api-provider';
import { WebbWeb3Provider } from '@webb-tools/web3-api-provider';
import {
Button,
CheckBox,
Expand All @@ -16,12 +16,13 @@ import {
ModalHeader,
Typography,
} from '@webb-tools/webb-ui-components';
import { FC, useCallback, useState } from 'react';
import { CreateAccountModalProps } from './types';
import cx from 'classnames';
import Lottie from 'lottie-react';
import privacySecurityJson from './privacy-security.json';
import congratsJson from './congrats.json';
import { FC, useCallback, useState } from 'react';
import { createSignInMessage } from '../../constants/signIn';
import congratsJson from './congrats.json';
import privacySecurityJson from './privacy-security.json';
import { CreateAccountModalProps } from './types';

const successBridgeInfo = [
{
Expand Down Expand Up @@ -62,35 +63,42 @@ export const CreateAccountModal: FC<CreateAccountModalProps> = ({
// Loading button when user hits create account
const [isCreating, setIsCreating] = useState(false);

const { loginNoteAccount } = useWebContext();
const { loginNoteAccount, activeApi } = useWebContext();

const loginWithMetamask = useCallback(async () => {
try {
setIsCreating(true);
const metamask = await Web3Provider.fromExtension();
const accounts = await metamask.eth.getAccounts();
if (accounts.length && accounts[0] != null) {
const msg = createSignInMessage(
accounts[0],
await metamask.eth.getChainId()
);

const signedString = await metamask.eth.personal.sign(
msg,
accounts[0],
undefined as any
);
await loginNoteAccount(signedString.slice(0, 66));

setIsSuccess?.(true);

if (!activeApi) {
throw WebbError.from(WebbErrorCodes.ApiNotReady);
}

if (!(activeApi instanceof WebbWeb3Provider)) {
throw WebbError.from(WebbErrorCodes.NotImplemented);
}

const account = activeApi.accounts.activeOrDefault;
if (!account) {
throw WebbError.from(WebbErrorCodes.NoAccountAvailable);
}

const msg = createSignInMessage(
account.address,
await activeApi.getChainId()
);

const signedString = await activeApi.sign(msg);

await loginNoteAccount(signedString.slice(0, 66));

setIsSuccess?.(true);
} catch (error) {
console.log('Error occurs when creating note account');
console.log(error);
} finally {
setIsCreating(false);
}
}, [loginNoteAccount, setIsSuccess]);
}, [activeApi, loginNoteAccount, setIsSuccess]);

const handleOpenChange = useCallback(
async (nextOpen: boolean) => {
Expand Down
Loading

0 comments on commit 7fad099

Please sign in to comment.