如何通过Wagmi的InjectedConnector连接Trust Wallet?加载异常求助
问题:Wagmi集成Trust Wallet无响应,按钮持续处于加载状态
尝试通过InjectedConnector实现Wagmi与Trust Wallet的集成,但点击「Connect your Trust Wallet」按钮后无弹窗,按钮一直显示「Is loading...」。
错误原因分析
- Trust Wallet注入对象识别错误:Trust Wallet注入的Provider并非
window.trustwallet,而是window.ethereum,且会附带isTrustWallet标识属性,原代码的getProvider逻辑无法正确定位到Trust Wallet的Provider。 - 加载状态绑定错误:按钮加载状态绑定了
useAccount的isLoading,但该状态仅用于账户信息的加载,而非连接操作的加载状态,连接操作的加载状态需从useConnect钩子获取。
解决方案
方案1:正确配置InjectedConnector识别Trust Wallet
修改App.jsx中的trustWalletConnector配置,通过检测window.ethereum的专属标识来定位Trust Wallet的Provider:
export const trustWalletConnector = new InjectedConnector({ chains, options: { name: "Trust Wallet", shimDisconnect: true, getProvider: () => { if (typeof window === "undefined") return undefined; // 优先检测Trust Wallet的注入Provider if (window.ethereum?.isTrustWallet) { return window.ethereum; } // 兼容其他可能的注入方式 return window.ethereum || window.web3?.currentProvider; }, }, });
方案2:使用WalletConnect兼容Trust Wallet(更稳定)
Trust Wallet原生支持WalletConnect协议,可直接复用WalletConnectConnector,避免依赖浏览器注入的Provider,兼容性更强:
// 在ConnectAccount.jsx中修改Trust Wallet连接逻辑 <button onClick={() => { connect({ connector: walletConnectConnector, options: { qrcodeModalOptions: { mobileLinks: ["trust"], // 优先唤起Trust Wallet App }, }, }); }} > {connectIsLoading ? "Is loading..." : "Connect your Trust Wallet"} </button>
修复加载状态绑定错误
在ConnectAccount.jsx中,将按钮加载状态改为useConnect返回的专属加载状态:
import { useAccount, useConnect } from "wagmi"; import { metamaskConnector, trustWalletConnector, walletConnectConnector } from "./App"; export default function ConnectAccount() { const { address, isConnected } = useAccount(); // 从useConnect获取连接操作的加载状态 const { connect, isLoading: connectIsLoading } = useConnect(); return ( <> <button onClick={() => { connect({ connector: trustWalletConnector }); }} > {connectIsLoading ? "Is loading..." : "Connect your Trust Wallet"} </button> <button onClick={() => { connect({ connector: metamaskConnector }); }} > {connectIsLoading ? "Is loading..." : "Connect your Metamask Wallet"} </button> {isConnected ? <span>{address}</span> : null} </> ); }
额外注意事项
- 确保用户已安装Trust Wallet浏览器扩展,或移动端打开dApp时已安装Trust Wallet App。
- 使用WalletConnect方式时,需保证
projectId有效,可通过WalletConnect官方渠道获取。
内容的提问来源于stack exchange,提问作者Mila A
相关产品推荐
相关产品推荐

