fix: simplify wallet choices and use bnb chain

This commit is contained in:
TerryM
2026-06-02 02:58:01 +08:00
parent b9fe7ff168
commit 0edcc80513
7 changed files with 197 additions and 248 deletions

View File

@@ -1,6 +1,14 @@
import { requestWalletNonce, verifyWalletSignature } from "./api";
export type WalletKind = "tokenPocket" | "metaMask" | "imToken";
const bnbChainIdHex = "0x38";
export type EthereumProvider = {
isMetaMask?: boolean;
isTokenPocket?: boolean;
isImToken?: boolean;
providers?: EthereumProvider[];
request: <T = unknown>(args: {
method: string;
params?: unknown[];
@@ -13,13 +21,54 @@ export function getInjectedEthereum(): EthereumProvider | null {
return maybeWindow.ethereum ?? null;
}
export async function signInWithInjectedWallet(): Promise<{
export function getInjectedWallet(kind?: WalletKind): EthereumProvider | null {
const ethereum = getInjectedEthereum();
if (!ethereum || !kind) return ethereum;
const providers = ethereum.providers?.length
? ethereum.providers
: [ethereum];
const match = providers.find((provider) => {
if (kind === "metaMask") return provider.isMetaMask;
if (kind === "tokenPocket") return provider.isTokenPocket;
if (kind === "imToken") return provider.isImToken;
return false;
});
return match ?? null;
}
async function ensureBnbChain(ethereum: EthereumProvider): Promise<void> {
try {
await ethereum.request({
method: "wallet_switchEthereumChain",
params: [{ chainId: bnbChainIdHex }],
});
} catch (error) {
const code = (error as { code?: number | string }).code;
if (code !== 4902 && code !== "4902") throw error;
await ethereum.request({
method: "wallet_addEthereumChain",
params: [
{
blockExplorerUrls: ["https://bscscan.com"],
chainId: bnbChainIdHex,
chainName: "BNB Smart Chain",
nativeCurrency: { decimals: 18, name: "BNB", symbol: "BNB" },
rpcUrls: ["https://bsc-dataseed.binance.org"],
},
],
});
}
}
export async function signInWithInjectedWallet(kind?: WalletKind): Promise<{
token: string;
wallet: string;
}> {
const ethereum = getInjectedEthereum();
const ethereum = getInjectedWallet(kind);
if (!ethereum) throw new Error("No injected wallet found");
await ensureBnbChain(ethereum);
const accounts = await ethereum.request<string[]>({
method: "eth_requestAccounts",
});