You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于HTML/JavaScript的彩票DApp适配Trust Wallet、MetaMask等多钱包的WalletConnect集成方案求助

Hey there! I've worked through your code and requirements, and Web3Modal is exactly the tool you need to support MetaMask, Trust Wallet (via WalletConnect), and other mainstream wallets in one unified flow. Here's a complete, polished implementation that fits your existing project structure:


完整集成方案

Step 1: Updated HTML Structure

First, let's clean up your HTML to keep it focused (you can retain your existing Bootstrap styling):

<div class="container">
  <div class="row">
    <div class="col-md-12">
      <h5>彩票DApp - 钱包连接</h5>
      <p id="connection-status">未连接钱包,请点击下方按钮连接</p>
      
      <div id="prepare">
        <button class="btn btn-primary" id="btn-connect">连接钱包</button>
      </div>

      <div id="connected" style="display: none">
        <button class="btn btn-primary" id="btn-disconnect">断开连接</button>
        <hr>
        <div id="network-info">
          <p><strong>当前网络:</strong> <span id="network-name"></span></p>
          <p><strong>当前账户:</strong> <span id="selected-account"></span></p>
        </div>
        <hr>
        <h4>账户余额</h4>
        <table class="table table-listing">
          <thead>
            <th>地址</th>
            <th>ETH余额</th>
          </thead>
          <tbody id="accounts">
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<!-- 余额模板 -->
<div id="templates" style="display: none">
  <template id="template-balance">
    <tr>
      <th class="address"></th>
      <td class="balance"></td>
    </tr>
  </template>
</div>

<!-- 引入依赖库 -->
<script src="https://unpkg.com/web3@1.2.11/dist/web3.min.js"></script>
<script src="https://unpkg.com/web3modal@1.9.0/dist/index.js"></script>
<script src="https://unpkg.com/evm-chains@0.2.0/dist/umd/index.min.js"></script>
<script src="https://unpkg.com/@walletconnect/web3-provider@1.2.1/dist/umd/index.min.js"></script>
<script src="https://unpkg.com/fortmatic@2.0.6/dist/fortmatic.js"></script>

<!-- 自定义业务逻辑 -->
<script>
// 这里放我们的JS代码
</script>

Step 2: Web3Modal核心配置与业务逻辑

Replace your example.js content with this code (make sure to replace placeholder values with your own):

// 全局变量
let web3Modal;
let provider;
let web3;
let contractH;

// 你的合约信息(替换为自己的)
const CONTRACT_ADDRESS = "0x35C00a/*MY CONTRACT ADDRESS */8D639145";
const CONTRACT_ABI = [/*my contract ABI*/];
// Infura ID(替换为自己的)
const INFURA_ID = "3c68/* my infura ID */5811f301753";

// 初始化Web3Modal配置
function initWeb3Modal() {
  const providerOptions = {
    walletconnect: {
      package: window.WalletConnectProvider,
      options: {
        infuraId: INFURA_ID,
      }
    },
    // 自动支持MetaMask(无需额外配置,Web3Modal会自动检测)
  };

  web3Modal = new window.Web3Modal({
    cacheProvider: false, // 不缓存钱包选择
    providerOptions,
    disableInjectedProvider: false, // 启用MetaMask等注入式钱包
  });
}

// 连接钱包逻辑
async function connectWallet() {
  try {
    // 打开钱包选择弹窗
    provider = await web3Modal.connect();
    
    // 初始化Web3实例
    web3 = new window.Web3(provider);
    
    // 监听钱包事件(账户切换、网络切换)
    provider.on("accountsChanged", handleAccountsChanged);
    provider.on("chainChanged", handleChainChanged);
    
    // 加载账户和网络信息
    await loadAccountData();
    
    // 初始化合约实例
    contractH = new web3.eth.Contract(CONTRACT_ABI, CONTRACT_ADDRESS);
    console.log("合约实例已初始化:", contractH);
    
  } catch (error) {
    console.error("连接失败:", error);
    alert("钱包连接失败,请重试");
  }
}

// 断开钱包逻辑
async function disconnectWallet() {
  if (provider?.disconnect) {
    await provider.disconnect();
  }
  
  // 重置状态
  web3Modal.clearCachedProvider();
  provider = null;
  web3 = null;
  contractH = null;
  
  // 更新UI
  document.getElementById("prepare").style.display = "block";
  document.getElementById("connected").style.display = "none";
  document.getElementById("connection-status").textContent = "未连接钱包,请点击下方按钮连接";
}

// 加载账户和余额数据
async function loadAccountData() {
  // 获取账户列表
  const accounts = await web3.eth.getAccounts();
  const selectedAccount = accounts[0];
  
  // 获取网络信息
  const chainId = await web3.eth.getChainId();
  const networkName = await window.EVMChains.getChainName(chainId);
  
  // 更新UI
  document.getElementById("selected-account").textContent = selectedAccount;
  document.getElementById("network-name").textContent = networkName || `Chain ID: ${chainId}`;
  
  // 加载余额
  const accountsTable = document.getElementById("accounts");
  accountsTable.innerHTML = "";
  
  for (const account of accounts) {
    const balance = await web3.eth.getBalance(account);
    const balanceEth = web3.utils.fromWei(balance, "ether");
    
    // 使用模板创建行
    const template = document.getElementById("template-balance");
    const row = document.importNode(template.content, true);
    row.querySelector(".address").textContent = account;
    row.querySelector(".balance").textContent = `${balanceEth.slice(0, 6)} ETH`;
    
    accountsTable.appendChild(row);
  }
  
  // 切换UI状态
  document.getElementById("prepare").style.display = "none";
  document.getElementById("connected").style.display = "block";
  document.getElementById("connection-status").textContent = "钱包已连接";
}

// 处理账户切换
function handleAccountsChanged(accounts) {
  if (accounts.length === 0) {
    disconnectWallet();
  } else {
    loadAccountData();
  }
}

// 处理网络切换
function handleChainChanged(chainId) {
  loadAccountData();
}

// 页面加载完成后初始化
window.addEventListener("load", () => {
  initWeb3Modal();
  
  // 绑定按钮事件
  document.getElementById("btn-connect").addEventListener("click", connectWallet);
  document.getElementById("btn-disconnect").addEventListener("click", disconnectWallet);
});

Step 3: 测试Trust Wallet扫码连接

  1. 确保你的DApp运行在HTTPS环境下(WalletConnect要求,本地测试可以用ngrok或者localhost的HTTPS工具)
  2. 点击「连接钱包」按钮,选择「WalletConnect」选项
  3. 会弹出一个二维码,打开你的Trust Wallet移动端APP
  4. 在Trust Wallet中点击右上角的扫码图标,扫描二维码,确认连接即可

Key Notes

  • 多钱包支持: 这个方案自动支持MetaMask(注入式钱包)、Trust Wallet(WalletConnect)、Coinbase Wallet等主流钱包,无需额外开发
  • 事件监听: 代码中已经处理了账户切换、网络切换的事件,保证UI实时更新
  • 合约集成: 连接成功后自动初始化你的彩票合约实例,你可以直接调用合约方法(比如contractH.methods.yourMethod().send({from: selectedAccount}))
  • Infura配置: 确保替换INFURA_ID为你自己的Infura项目ID,用于WalletConnect的RPC节点

如果你需要调试或者有其他定制需求,随时提供你的完整项目代码,我可以帮你进一步优化!


内容的提问来源于stack exchange,提问作者owl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 17:27:52