diff --git a/docs/reference/agent-lessons/codex-fix-phantom-unsupported-network.md b/docs/reference/agent-lessons/codex-fix-phantom-unsupported-network.md new file mode 100644 index 000000000..2337ac792 --- /dev/null +++ b/docs/reference/agent-lessons/codex-fix-phantom-unsupported-network.md @@ -0,0 +1 @@ +No new lessons. diff --git a/services/user-front/src/components/Providers.tsx b/services/user-front/src/components/Providers.tsx index 40da417d2..9541c6f3f 100644 --- a/services/user-front/src/components/Providers.tsx +++ b/services/user-front/src/components/Providers.tsx @@ -2,47 +2,98 @@ import * as React from "react"; import { + connectorsForWallets, RainbowKitProvider, - getDefaultConfig, darkTheme, } from "@rainbow-me/rainbowkit"; +import { + coinbaseWallet, + metaMaskWallet, + rabbyWallet, + walletConnectWallet, +} from "@rainbow-me/rainbowkit/wallets"; import { WagmiProvider, createConfig, http } from "wagmi"; import { injected } from "wagmi/connectors"; -import { hardhat, sepolia, baseSepolia, arbitrumSepolia } from "wagmi/chains"; +import { + arbitrum, + hardhat, + sepolia, + baseSepolia, + arbitrumSepolia, +} from "wagmi/chains"; +import type { EIP1193Provider } from "viem"; import { QueryClientProvider, QueryClient } from "@tanstack/react-query"; import { isIgnorableWalletExtensionError, toWalletExtensionErrorDetails, } from "@/utils/walletExtensionErrors"; +import { getSupportedEvmInjectedProvider } from "@/utils/evmProvider"; import { getRpcUrlForChain } from "@/utils/runtimeEnv"; import "@rainbow-me/rainbowkit/styles.css"; -const chains = [hardhat, sepolia, baseSepolia, arbitrumSepolia] as const; +const chains = [ + hardhat, + sepolia, + baseSepolia, + arbitrumSepolia, + arbitrum, +] as const; const walletConnectProjectId = process.env.NEXT_PUBLIC_REOWN_PROJECT_ID?.trim() || process.env.NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID?.trim() || ""; -const config = walletConnectProjectId - ? getDefaultConfig({ - appName: "Synapse Network Dashboard", - projectId: walletConnectProjectId, - chains, - ssr: false, - }) - : createConfig({ - chains, - ssr: false, - connectors: [ - injected({ shimDisconnect: true, unstable_shimAsyncInject: 2_000 }), +const appName = "Synapse Network Dashboard"; +const transports = { + [hardhat.id]: http(getRpcUrlForChain(hardhat.id)), + [sepolia.id]: http(), + [baseSepolia.id]: http(), + [arbitrumSepolia.id]: http(getRpcUrlForChain(arbitrumSepolia.id)), + [arbitrum.id]: http(getRpcUrlForChain(arbitrum.id)), +}; +const connectors = walletConnectProjectId + ? connectorsForWallets( + [ + { + groupName: "Recommended EVM wallets", + wallets: [ + metaMaskWallet, + rabbyWallet, + coinbaseWallet, + walletConnectWallet, + ], + }, ], - transports: { - [hardhat.id]: http(getRpcUrlForChain(hardhat.id)), - [sepolia.id]: http(), - [baseSepolia.id]: http(), - [arbitrumSepolia.id]: http(getRpcUrlForChain(arbitrumSepolia.id)), - }, - }); + { + appName, + projectId: walletConnectProjectId, + } + ) + : [ + injected({ + shimDisconnect: true, + unstable_shimAsyncInject: 2_000, + target: () => { + const provider = getSupportedEvmInjectedProvider(); + if (!provider) { + return undefined; + } + + return { + id: "synapse-supported-evm-wallet", + name: "Supported EVM Wallet", + provider: provider as unknown as EIP1193Provider, + }; + }, + }), + ]; + +const config = createConfig({ + chains, + ssr: false, + connectors, + transports, +}); const queryClient = new QueryClient(); diff --git a/services/user-front/src/components/dashboard-workspace/OwnerCreditsPage.tsx b/services/user-front/src/components/dashboard-workspace/OwnerCreditsPage.tsx index acb9b47cb..5b9e1f98c 100644 --- a/services/user-front/src/components/dashboard-workspace/OwnerCreditsPage.tsx +++ b/services/user-front/src/components/dashboard-workspace/OwnerCreditsPage.tsx @@ -843,6 +843,7 @@ export default function OwnerCreditsPage() { walletBalanceChanged: t("creditsPage.depositWalletBalanceChanged"), networkSwitchPending: t("creditsPage.depositNetworkSwitchPending"), networkSwitchFailed: t("creditsPage.depositNetworkSwitchFailed"), + unsupportedWallet: t("creditsPage.depositUnsupportedWallet"), permitTimedOut: t("creditsPage.depositPermitTimedOut"), permitFallbackAvailable: t("creditsPage.depositPermitFallbackAvailable"), approveTransactionFailed: t("creditsPage.depositApproveFailed"), diff --git a/services/user-front/src/hooks/useVaultDeposit.test.tsx b/services/user-front/src/hooks/useVaultDeposit.test.tsx index 7e3dc226f..26a21f45f 100644 --- a/services/user-front/src/hooks/useVaultDeposit.test.tsx +++ b/services/user-front/src/hooks/useVaultDeposit.test.tsx @@ -332,6 +332,29 @@ describe("useVaultDeposit", () => { expect(signTypedDataAsyncMock).not.toHaveBeenCalled(); }); + it("does not open Phantom when the required EVM network is unsupported", async () => { + chainIdState.value = 1; + const request = vi.fn(); + (globalThis as typeof globalThis & { ethereum?: unknown }).ethereum = { + isPhantom: true, + request, + }; + + const { result } = renderHook(() => + useVaultDeposit({ initialAmount: "10" }) + ); + + await result.current.handleDeposit(); + + await waitFor(() => { + expect(result.current.depositError).toContain( + "Phantom does not support the Synapse EVM settlement network" + ); + }); + expect(request).not.toHaveBeenCalled(); + expect(signTypedDataAsyncMock).not.toHaveBeenCalled(); + }); + it("adds the required network when wallet reports the chain is unknown", async () => { chainIdState.value = 1; const request = vi diff --git a/services/user-front/src/hooks/useVaultDeposit.ts b/services/user-front/src/hooks/useVaultDeposit.ts index 0a2fca43f..b1371f1ec 100644 --- a/services/user-front/src/hooks/useVaultDeposit.ts +++ b/services/user-front/src/hooks/useVaultDeposit.ts @@ -31,6 +31,7 @@ import { import { normalizeMoneyString } from "@/utils/money"; import { isWalletUserRejectedError } from "@/utils/walletActionErrors"; import { showWalletStatusToast } from "@/utils/walletToast"; +import { getSupportedEvmInjectedProvider } from "@/utils/evmProvider"; import { normalizeTokenDecimals, shortAddress, @@ -112,6 +113,7 @@ type VaultDepositCopy = { walletBalanceChanged: string; networkSwitchPending: string; networkSwitchFailed: string; + unsupportedWallet: string; permitTimedOut: string; permitFallbackAvailable: string; approveTransactionFailed: string; @@ -163,6 +165,8 @@ const DEFAULT_VAULT_DEPOSIT_COPY: VaultDepositCopy = { "Open your wallet extension to finish the network switch.", networkSwitchFailed: "Unable to switch network from the app. Please switch in your wallet and retry.", + unsupportedWallet: + "Phantom does not support the Synapse EVM settlement network. Please reconnect with MetaMask, Rabby, or Coinbase Wallet.", permitTimedOut: "Wallet did not respond. If you use a hardware wallet, try Approve transaction instead.", permitFallbackAvailable: @@ -869,19 +873,10 @@ export function useVaultDeposit(options?: UseVaultDepositOptions) { ]); const switchToRequiredNetwork = useCallback(async () => { - const ethereum = ( - globalThis as typeof globalThis & { - ethereum?: { - request: (args: { - method: string; - params?: unknown[]; - }) => Promise; - }; - } - ).ethereum; + const ethereum = getSupportedEvmInjectedProvider(); if (!ethereum) { - setDepositError(copy.walletReconnect); - showWalletStatusToast(copy.walletReconnect, { icon: "🔌" }); + setDepositError(copy.unsupportedWallet); + showWalletStatusToast(copy.unsupportedWallet, { icon: "🔌" }); return; } diff --git a/services/user-front/src/i18n/resources/en/creditsPage.ts b/services/user-front/src/i18n/resources/en/creditsPage.ts index 6fd584c78..cdeb96d1b 100644 --- a/services/user-front/src/i18n/resources/en/creditsPage.ts +++ b/services/user-front/src/i18n/resources/en/creditsPage.ts @@ -114,6 +114,8 @@ const creditsPage: I18nMessages["creditsPage"] = { "Open your wallet extension to finish the network switch.", depositNetworkSwitchFailed: "Unable to switch network from the app. Please switch in your wallet and retry.", + depositUnsupportedWallet: + "Phantom does not support the Synapse EVM settlement network. Reconnect with MetaMask, Rabby, or Coinbase Wallet.", depositPermitTimedOut: "Wallet did not respond. If you use a hardware wallet, try Approve transaction instead.", depositPermitFallbackAvailable: diff --git a/services/user-front/src/i18n/resources/zh/creditsPage.ts b/services/user-front/src/i18n/resources/zh/creditsPage.ts index 3edf73d28..efe3970f2 100644 --- a/services/user-front/src/i18n/resources/zh/creditsPage.ts +++ b/services/user-front/src/i18n/resources/zh/creditsPage.ts @@ -97,6 +97,8 @@ const creditsPage: I18nMessages["creditsPage"] = { depositWalletBalanceChanged: "钱包余额已变化,请重新确认金额。", depositNetworkSwitchPending: "请打开钱包插件完成网络切换。", depositNetworkSwitchFailed: "无法从页面切换网络,请在钱包中切换后重试。", + depositUnsupportedWallet: + "Phantom 不支持 Synapse 当前的 EVM 结算网络。请改用 MetaMask、Rabby 或 Coinbase Wallet 重新连接。", depositPermitTimedOut: "钱包似乎没有响应。如果你使用硬件钱包,请尝试改用 Approve 交易。", depositPermitFallbackAvailable: diff --git a/services/user-front/src/i18n/schema.ts b/services/user-front/src/i18n/schema.ts index b6777eb85..efe53f860 100644 --- a/services/user-front/src/i18n/schema.ts +++ b/services/user-front/src/i18n/schema.ts @@ -1102,6 +1102,7 @@ export type I18nMessages = { depositWalletBalanceChanged: string; depositNetworkSwitchPending: string; depositNetworkSwitchFailed: string; + depositUnsupportedWallet: string; depositPermitTimedOut: string; depositPermitFallbackAvailable: string; depositApproveFailed: string; diff --git a/services/user-front/src/utils/evmProvider.test.ts b/services/user-front/src/utils/evmProvider.test.ts new file mode 100644 index 000000000..275d7af2b --- /dev/null +++ b/services/user-front/src/utils/evmProvider.test.ts @@ -0,0 +1,48 @@ +// @vitest-environment jsdom + +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { + getSupportedEvmInjectedProvider, + getSupportedEvmInjectedProviderOrThrow, + isPhantomEvmProvider, + UNSUPPORTED_PHANTOM_EVM_WALLET_MESSAGE, +} from "@/utils/evmProvider"; + +describe("evmProvider", () => { + beforeEach(() => { + vi.restoreAllMocks(); + delete (globalThis as typeof globalThis & { ethereum?: unknown }).ethereum; + delete (globalThis as typeof globalThis & { phantom?: unknown }).phantom; + }); + + it("filters Phantom when it is the only injected provider", () => { + const phantom = { isPhantom: true, request: vi.fn() }; + (globalThis as typeof globalThis & { ethereum?: unknown }).ethereum = + phantom; + + expect(isPhantomEvmProvider(phantom)).toBe(true); + expect(getSupportedEvmInjectedProvider()).toBeUndefined(); + }); + + it("selects a supported EVM provider from a multi-provider injection", () => { + const phantom = { isPhantom: true, request: vi.fn() }; + const metamask = { isMetaMask: true, request: vi.fn() }; + (globalThis as typeof globalThis & { ethereum?: unknown }).ethereum = { + providers: [phantom, metamask], + request: vi.fn(), + }; + + expect(getSupportedEvmInjectedProvider()).toBe(metamask); + }); + + it("throws a controlled product error when only Phantom is available", () => { + (globalThis as typeof globalThis & { ethereum?: unknown }).ethereum = { + isPhantom: true, + request: vi.fn(), + }; + + expect(() => getSupportedEvmInjectedProviderOrThrow()).toThrow( + UNSUPPORTED_PHANTOM_EVM_WALLET_MESSAGE + ); + }); +}); diff --git a/services/user-front/src/utils/evmProvider.ts b/services/user-front/src/utils/evmProvider.ts new file mode 100644 index 000000000..9bac0343a --- /dev/null +++ b/services/user-front/src/utils/evmProvider.ts @@ -0,0 +1,71 @@ +"use client"; + +type InjectedProviderRequestArgs = { + method: string; + params?: unknown; +}; + +export type SupportedEvmInjectedProvider = { + request: (args: InjectedProviderRequestArgs) => Promise; + isCoinbaseWallet?: boolean; + isMetaMask?: boolean; + isPhantom?: boolean; + isRabby?: boolean; + providers?: SupportedEvmInjectedProvider[]; +}; + +type EthereumGlobal = typeof globalThis & { + ethereum?: SupportedEvmInjectedProvider; + phantom?: { + ethereum?: SupportedEvmInjectedProvider; + }; +}; + +export const UNSUPPORTED_PHANTOM_EVM_WALLET_MESSAGE = + "Phantom does not support the Synapse EVM settlement network. Please use MetaMask, Rabby, Coinbase Wallet, or set Phantom Default App Wallet to Always Ask and reconnect with an EVM wallet."; + +export function isPhantomEvmProvider( + provider: SupportedEvmInjectedProvider | null | undefined +): boolean { + if (!provider) { + return false; + } + + const phantomEthereum = (globalThis as EthereumGlobal).phantom?.ethereum; + return provider.isPhantom === true || provider === phantomEthereum; +} + +function getInjectedProviderCandidates(): SupportedEvmInjectedProvider[] { + const ethereum = (globalThis as EthereumGlobal).ethereum; + if (!ethereum) { + return []; + } + + const providers = Array.isArray(ethereum.providers) + ? ethereum.providers + : [ethereum]; + return providers.filter(Boolean); +} + +export function getSupportedEvmInjectedProvider(): + | SupportedEvmInjectedProvider + | undefined { + const providers = getInjectedProviderCandidates().filter( + (provider) => !isPhantomEvmProvider(provider) + ); + + return ( + providers.find((provider) => provider.isMetaMask === true) ?? + providers.find((provider) => provider.isRabby === true) ?? + providers.find((provider) => provider.isCoinbaseWallet === true) ?? + providers[0] + ); +} + +export function getSupportedEvmInjectedProviderOrThrow(): SupportedEvmInjectedProvider { + const provider = getSupportedEvmInjectedProvider(); + if (!provider) { + throw new Error(UNSUPPORTED_PHANTOM_EVM_WALLET_MESSAGE); + } + return provider; +} diff --git a/services/user-front/src/utils/payForService.ts b/services/user-front/src/utils/payForService.ts index 76fa3bbdf..74f761554 100644 --- a/services/user-front/src/utils/payForService.ts +++ b/services/user-front/src/utils/payForService.ts @@ -9,6 +9,10 @@ import type { Address, EIP1193Provider, Hash } from "viem"; import contractConfig from "@/contract-config.json"; import SynapseCoreABI from "@/SynapseCoreABI.json"; import MockUSDCABI from "@/MockUSDCABI.json"; +import { + getSupportedEvmInjectedProviderOrThrow, + type SupportedEvmInjectedProvider, +} from "@/utils/evmProvider"; import { getRpcUrl } from "@/utils/runtimeEnv"; export type PayForServiceInput = { @@ -22,14 +26,10 @@ export type PayForServiceInput = { }; const ensureWalletTransport = () => { - const injectedEthereum = (globalThis as { ethereum?: EIP1193Provider }) - .ethereum; - if (!injectedEthereum) { - throw new Error( - "No injected wallet found. Please install MetaMask or use a web3 wallet." - ); - } - return custom(injectedEthereum); + return custom( + getSupportedEvmInjectedProviderOrThrow() as SupportedEvmInjectedProvider & + EIP1193Provider + ); }; const normalizeAddress = (value: string): Address => value as Address; diff --git a/services/user-front/src/utils/walletSignature.ts b/services/user-front/src/utils/walletSignature.ts index dfb7b2f72..e0cf6653e 100644 --- a/services/user-front/src/utils/walletSignature.ts +++ b/services/user-front/src/utils/walletSignature.ts @@ -1,6 +1,7 @@ "use client"; import { toHex } from "viem"; +import { getSupportedEvmInjectedProviderOrThrow } from "@/utils/evmProvider"; export function shouldFallbackSignError(message: string): boolean { return ( @@ -21,16 +22,8 @@ export function isWalletUnstableError(message: string): boolean { } export async function readInjectedAccounts(): Promise { - const ethereum = ( - globalThis as { - ethereum?: { request: (args: { method: string }) => Promise }; - } - ).ethereum; - if (!ethereum) { - return []; - } - try { + const ethereum = getSupportedEvmInjectedProviderOrThrow(); const accounts = await ethereum.request({ method: "eth_accounts" }); if (!Array.isArray(accounts)) { return []; @@ -47,18 +40,7 @@ export async function signWithInjectedProvider( message: string, walletAddress: string ): Promise { - const ethereum = ( - globalThis as { - ethereum?: { - request: (args: { method: string; params: unknown[] }) => Promise; - }; - } - ).ethereum; - if (!ethereum) { - throw new Error( - "Wallet provider unavailable. Please reconnect wallet and retry." - ); - } + const ethereum = getSupportedEvmInjectedProviderOrThrow(); const hexMessage = toHex(message); const attempts: Array = [ @@ -71,10 +53,10 @@ export async function signWithInjectedProvider( let lastError: unknown = null; for (const params of attempts) { try { - const signature = await ethereum.request({ + const signature = (await ethereum.request({ method: "personal_sign", params, - }); + })) as unknown; if (typeof signature === "string" && signature.length > 0) { return signature; }