Skip to content

Commit

Permalink
feat: WT-2157 Handle add new network and switch network functionality (
Browse files Browse the repository at this point in the history
  • Loading branch information
sharonsheah authored Mar 1, 2024
1 parent 34b1729 commit 325e7bc
Show file tree
Hide file tree
Showing 10 changed files with 109 additions and 10 deletions.
2 changes: 1 addition & 1 deletion packages/checkout/sdk/src/network/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ async function switchNetworkInWallet(
}

// eslint-disable-next-line consistent-return
async function addNetworkToWallet(
export async function addNetworkToWallet(
networkMap: NetworkMap,
web3Provider: Web3Provider,
chainId: ChainId,
Expand Down
18 changes: 18 additions & 0 deletions packages/checkout/sdk/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ import {
SellResult,
TokenInfo,
GetTokenInfoParams,
AddNetworkParams,
} from './types';
import { CheckoutConfiguration } from './config';
import { createReadOnlyProviders } from './readOnlyProviders/readOnlyProvider';
Expand Down Expand Up @@ -281,6 +282,23 @@ export class Checkout {
return { provider: web3Provider };
}

/**
* Adds the network for the current wallet provider.
* @param {AddNetworkParams} params - The parameters for adding the network.
* @returns {Promise<any>} - A promise that resolves to the result of adding the network.
*/
public async addNetwork(
params: AddNetworkParams,
): Promise<any> {
const addNetworkRes = await network.addNetworkToWallet(
this.config.networkMap,
params.provider,
params.chainId,
);

return addNetworkRes;
}

/**
* Switches the network for the current wallet provider.
* @param {SwitchNetworkParams} params - The parameters for switching the network.
Expand Down
10 changes: 10 additions & 0 deletions packages/checkout/sdk/src/types/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,16 @@ import { ChainId } from './chains';
import { NetworkInfo } from './networkInfo';
import { TokenInfo } from './tokenInfo';

/**
* Interface representing the parameters for {@link Checkout.addNetwork}.
* @property {Web3Provider} provider - The provider to connect to the network.
* @property {ChainId} chainId - The ID of the network to add. We only support adding Immutable zkEVM and Immutable zkEVM Testnet.
*/
export interface AddNetworkParams {
provider: Web3Provider;
chainId: ChainId;
}

/**
* Interface representing the parameters for {@link Checkout.switchNetwork}.
* @property {Web3Provider} provider - The provider to connect to the network.
Expand Down
20 changes: 13 additions & 7 deletions packages/checkout/widgets-lib/src/lib/walletConnect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,14 @@ const lightThemeVariables = {
// Whitelisted wallet ids on WalletConnect explorer API
const metamaskId = 'c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96';
const frontierId = '85db431492aa2e8672e93f4ea7acf10c88b97b867b0d373107af63dc4880f041';
const coinbaseId = 'fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa';
const ledgerLiveId = '19177a98252e07ddfc9af2083ba8e07ef627cb6103467ffebb3f8f4205fd7927';
// const coinbaseId = 'fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa';
// const phantomId = 'a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393';
// const rainbowId = '1ae92b26df02f0abca6304df07debccd18262fdf5fe82daa81593582dac9a369';

const productionWalletWhitelist = [metamaskId, frontierId, ledgerLiveId];
const sandboxWalletWhitelist = [metamaskId];

export class WalletConnectManager {
private static instance: WalletConnectManager;

Expand Down Expand Up @@ -112,11 +116,8 @@ export class WalletConnectManager {
const modal = new WalletConnectModal({
projectId: this.walletConnectConfig.projectId,
chains: this.environment === Environment.PRODUCTION ? productionModalChains : testnetModalChains,
explorerRecommendedWalletIds: [
metamaskId,
frontierId,
coinbaseId,
],
explorerRecommendedWalletIds: this.environment === Environment.PRODUCTION
? productionWalletWhitelist : sandboxWalletWhitelist,
explorerExcludedWalletIds: 'ALL',
themeMode: this.theme,
themeVariables: this.theme === WidgetTheme.DARK ? darkThemeVariables : lightThemeVariables,
Expand Down Expand Up @@ -163,8 +164,13 @@ export class WalletConnectManager {
}

private async loadWalletListings(): Promise<Response | undefined> {
const whitelistedWallets = this.environment === Environment.PRODUCTION
? productionWalletWhitelist : sandboxWalletWhitelist;

const whitelistedWalletIds = whitelistedWallets.map((walletId) => `${walletId}`).join(',');
// eslint-disable-next-line max-len
const walletListingsApi = `https://explorer-api.walletconnect.com/v3/wallets?projectId=${this.walletConnectConfig.projectId}&ids=${metamaskId},${frontierId},${coinbaseId}`;
const walletListingsApi = `https://explorer-api.walletconnect.com/v3/wallets?projectId=${this.walletConnectConfig.projectId}&ids=${whitelistedWalletIds}`;

try {
const response = await fetch(walletListingsApi);
const data = await response.json();
Expand Down
1 change: 1 addition & 0 deletions packages/checkout/widgets-lib/src/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"zkEVM": {
"heading": "You’ll be asked to switch to the Immutable zkEVM network",
"body": "Check for the pop-up from MetaMask and 'Approve' to switch. If this is the first time, MetaMask will also ask you to add the network.",
"bodyWalletConnect": "Check for the pop-up from your wallet to switch. If this is the first time, your wallet will also ask you to add the network.",
"button": {
"text": "Ready to Switch",
"retryText": "Try Again"
Expand Down
1 change: 1 addition & 0 deletions packages/checkout/widgets-lib/src/locales/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"zkEVM": {
"heading": "Immutable zkEVMネットワークに切り替えるように求められます",
"body": "MetaMaskからのポップアップを確認し、「承認」して切り替えてください。これが初めての場合、MetaMaskはネットワークを追加するように求めることもあります。",
"bodyWalletConnect": "ウォレットからのポップアップを確認して切り替えます。これが初めての場合、ウォレットはネットワークの追加を求めます。",
"button": {
"text": "切り替えの準備ができました",
"retryText": "再試行する"
Expand Down
1 change: 1 addition & 0 deletions packages/checkout/widgets-lib/src/locales/ko.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"zkEVM": {
"heading": "Immutable zkEVM 네트워크로 전환하라는 요청을 받게 됩니다",
"body": "MetaMask 팝업에서 '승인'을 선택하고 전환하세요. 처음이라면 MetaMask에서 네트워크 추가를 요구할 수도 있습니다.",
"bodyWalletConnect": "지갑에서 팝업을 확인하여 전환하십시오. 처음이라면 지갑에서 네트워크 추가를 요청합니다.",
"button": {
"text": "전환 준비됨",
"retryText": "다시 시도"
Expand Down
1 change: 1 addition & 0 deletions packages/checkout/widgets-lib/src/locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"zkEVM": {
"heading": "将要求您切换到Immutable zkEVM网络",
"body": "检查MetaMask的弹窗并选择'批准'以切换。如果这是第一次,MetaMask还会要求您添加网络。",
"bodyWalletConnect": "请检查您的钱包弹出窗口以进行切换。如果这是第一次,您的钱包还会要求您添加网络。",
"button": {
"text": "准备切换",
"retryText": "再试一次"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
useCallback, useContext, useEffect, useState,
} from 'react';
import { useTranslation } from 'react-i18next';
import { isWalletConnectProvider } from 'lib/providerUtils';
import { SimpleTextBody } from '../../../components/Body/SimpleTextBody';
import { FooterButton } from '../../../components/Footer/FooterButton';
import { HeaderNavigation } from '../../../components/Header/HeaderNavigation';
Expand Down Expand Up @@ -38,7 +39,65 @@ export function SwitchNetworkZkEVM() {
controlType: 'Button',
});

if (!provider.provider.request) return;

const currentChainId = provider.provider.request({ method: 'eth_chainId', params: [] });
// eslint-disable-next-line radix
const parsedChainId = parseInt(currentChainId.toString());

if (parsedChainId === getL2ChainId(checkout.config)) {
connectDispatch({
payload: {
type: ConnectActions.SET_PROVIDER,
provider,
},
});

viewDispatch({
payload: {
type: ViewActions.UPDATE_VIEW,
view: {
type: ConnectWidgetViews.SUCCESS,
},
},
});

return;
}

try {
let walletName = '';
if (isWalletConnectProvider(provider)) {
walletName = (provider.provider as any)?.session?.peer?.metadata?.name.toLowerCase();
}
if (walletName === 'metamask') {
try {
await checkout.addNetwork({
provider,
chainId: getL2ChainId(checkout.config),
});
connectDispatch({
payload: {
type: ConnectActions.SET_PROVIDER,
provider,
},
});

viewDispatch({
payload: {
type: ViewActions.UPDATE_VIEW,
view: {
type: ConnectWidgetViews.SUCCESS,
},
},
});
return;
} catch {
// eslint-disable-next-line no-console
console.warn('Failed to add network to wallet, skipping add network');
}
}

const switchRes = await checkout.switchNetwork({
provider,
chainId: getL2ChainId(checkout.config),
Expand Down Expand Up @@ -84,7 +143,9 @@ export function SwitchNetworkZkEVM() {
<SimpleTextBody
heading={t('views.SWITCH_NETWORK.zkEVM.heading')}
>
{t('views.SWITCH_NETWORK.zkEVM.body')}
{isWalletConnectProvider(provider) ? (
t('views.SWITCH_NETWORK.zkEVM.bodyWalletConnect')) : (
t('views.SWITCH_NETWORK.zkEVM.body'))}
</SimpleTextBody>
</SimpleLayout>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
SwapEventType,
WalletEventType,
WalletNetworkSwitch,
WidgetTheme, WidgetType, ProviderEventType, ProviderUpdated, WidgetConfiguration, WidgetProperties
WidgetTheme, WidgetType, ProviderEventType, ProviderUpdated, WidgetProperties
} from '@imtbl/checkout-sdk';
import { Environment } from '@imtbl/config';
import { passport } from './passport';
Expand Down

0 comments on commit 325e7bc

Please sign in to comment.