{"author":{"address":"0xBb4445E9BAeD87aD6890f81f2a6A0394b417A3c7","user":"https://learnblockchain.cn/people/2184"},"content":{"body":"新建文件夹`web3modal_metamask`和`index.js`文件\r\n\r\n输入文件内容如下：\r\n\r\n```\r\n\u003c!DOCTYPE html\u003e\r\n\u003chtml lang=\"en\"\u003e\r\n\u003chead\u003e\r\n  \u003cmeta charset=\"UTF-8\"\u003e\r\n  \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"\u003e\r\n  \u003ctitle\u003eConnect MetaMask Wallet\u003c/title\u003e\r\n\u003c/head\u003e\r\n\u003cbody\u003e\r\n  \u003cbutton id=\"connectWallet\"\u003eConnect Wallet\u003c/button\u003e\r\n  \u003cdiv id=\"walletInfo\"\u003e\r\n    \u003cp\u003eAddress: \u003cspan id=\"walletAddress\"\u003eNot connected\u003c/span\u003e\u003c/p\u003e\r\n    \u003cp\u003eBalance: \u003cspan id=\"walletBalance\"\u003eNot connected\u003c/span\u003e ETH\u003c/p\u003e\r\n  \u003c/div\u003e\r\n\r\n  \u003c!-- Load web3modal and ethers.js from CDN --\u003e\r\n  \u003cscript src=\"https://unpkg.com/web3modal@1.9.5/dist/index.js\"\u003e\u003c/script\u003e\r\n  \u003cscript src=\"https://cdn.ethers.io/lib/ethers-5.2.umd.min.js\"\u003e\u003c/script\u003e\r\n  \u003cscript\u003e\r\n    let web3Modal;\r\n    let provider;\r\n    let signer;\r\n\r\n    async function init() {\r\n      const providerOptions = {\r\n        // Here you can define different wallet providers if needed\r\n      };\r\n\r\n      web3Modal = new Web3Modal.default({\r\n        cacheProvider: false, // optional\r\n        providerOptions, // required\r\n      });\r\n\r\n      document.getElementById('connectWallet').addEventListener('click', onConnect);\r\n    }\r\n\r\n    async function onConnect() {\r\n      try {\r\n        provider = await web3Modal.connect();\r\n        const web3Provider = new ethers.providers.Web3Provider(provider);\r\n        signer = web3Provider.getSigner();\r\n        const address = await signer.getAddress();\r\n        document.getElementById('walletAddress').textContent = address;\r\n\r\n        // Get balance\r\n        const balance = await web3Provider.getBalance(address);\r\n        const balanceInEth = ethers.utils.formatEther(balance);\r\n        document.getElementById('walletBalance').textContent = balanceInEth;\r\n      } catch (e) {\r\n        console.error(e);\r\n      }\r\n    }\r\n\r\n    window.addEventListener('load', init);\r\n  \u003c/script\u003e\r\n\u003c/body\u003e\r\n\u003c/html\u003e\r\n\r\n```\r\n\r\n\r\n\r\n### 关键点：\r\n\r\n1. **确保使用正确的CDN URL**：使用了最新版本的web3modal和ethers.js的CDN链接。\r\n2. **初始化和加载顺序**：确保在页面加载后初始化web3Modal，并在点击按钮时触发连接事件。\r\n\r\n### 执行步骤：\r\n\r\n1. 确保已安装Node.js和npm。\r\n2. 安装所需的依赖：\r\n\r\n```\r\nyarn add web3modal ethers\r\n```\r\n\r\n1. 创建并打开 `index.html` 文件，复制并粘贴上述代码。\r\n2. 运行一个本地服务器以查看HTML文件，例如使用 `http-server`：\r\n\r\n```\r\nnpm install -g http-server\r\nhttp-server\r\n```\r\n\r\n1. 打开浏览器并导航到 `http://localhost:8080`，你应该会看到一个【Connect Wallet】按钮。点击该按钮，请求MetaMask钱包授权，并在页面上显示钱包地址和余额。\r\n\r\n确保MetaMask已安装且已解锁。如果问题依旧，请提供控制台的详细错误信息，以便进一步排查。\r\n\r\n\r\n![image-20240715171650809.png](https://img.learnblockchain.cn/attachments/2024/07/G3WwSLJk669508d5f2465.png)\r\n\r\n将这个项目部署到Vercel，你需要按照以下步骤进行操作：\r\n\r\n并安装`vercel` CLI工具：\r\n\r\n```\r\nnpm install -g vercel\r\n```\r\n\r\n### 创建一个 Vercel 配置文件\r\n\r\n在你的项目根目录下创建一个`vercel.json`文件，内容如下：\r\n\r\n```\r\n{\r\n  \"version\": 2,\r\n  \"builds\": [\r\n    {\r\n      \"src\": \"index.html\",\r\n      \"use\": \"@vercel/static\"\r\n    }\r\n  ],\r\n  \"routes\": [\r\n    {\r\n      \"src\": \"/(.*)\",\r\n      \"dest\": \"/index.html\"\r\n    }\r\n  ]\r\n}\r\n```\r\n\r\n### 部署到 Vercel\r\n\r\n在终端中运行以下命令登录到你的Vercel账户（如果你还没有Vercel账户，可以在命令行中注册）：\r\n\r\n```\r\nvercel login\r\n```\r\n\r\n输出结果：\r\n\r\n```\r\nhb@yhbdeMacBook-Air web3Modal_metamask % vercel login\r\n(node:49097) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.\r\n(Use `node --trace-deprecation ...` to show where the warning was created)\r\nVercel CLI 34.3.1\r\n? Log in to Vercel Continue with Email\r\n? Enter your email address: 1131764933@qq.com\r\nWe sent an email to 1131764933@qq.com. Please follow the steps provided inside it and make sure the security code matches Sunny Dormouse.\r\n\u003e Success! Email authentication complete for 1131764933@qq.com\r\nCongratulations! You are now logged in. In order to deploy something, run `vercel`.\r\n💡  Connect your Git Repositories to deploy every branch push automatically (https://vercel.link/git).\r\n\r\n\r\n```\r\n\r\n然后在项目根目录中运行以下命令来部署项目：\r\n\r\n```\r\nvercel\r\n```\r\n\r\nVercel会提示你选择项目的相关设置，一般直接按回车键选择默认设置即可。部署成功后，Vercel会生成一个访问链接，并显示在终端中。\r\n\r\n```\r\nhb@yhbdeMacBook-Air web3Modal_metamask % vercel\r\n(node:49403) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.\r\n(Use `node --trace-deprecation ...` to show where the warning was created)\r\nVercel CLI 34.3.1\r\n? Set up and deploy “~/web3Modal_metamask”? yes\r\n? Which scope do you want to deploy to? egama's projects\r\n? Link to existing project? no\r\n? What’s your project’s name? web3-modal-metamask\r\n? In which directory is your code located? ./\r\n🔗  Linked to egamas-projects/web3-modal-metamask (created .vercel and added it to .gitignore)\r\n🔍  Inspect: https://vercel.com/egamas-projects/web3-modal-metamask/CnhDqTVbUayT7wyKcYVtgJ1CZDiK [3s]\r\n✅  Production: https://web3-modal-metamask-mr5q05f8r-egamas-projects.vercel.app [3s]\r\n📝  Deployed to production. Run `vercel --prod` to overwrite later (https://vercel.link/2F).\r\n💡  To change the domain or build command, go to https://vercel.com/egamas-projects/web3-modal-metamask/settings\r\n```\r\n\r\n\r\n\r\n### 5. 查看部署的项目\r\n\r\n访问Vercel提供的链接，你应该会看到你的网页，其中包括【Connect Wallet】按钮，点击该按钮可以请求MetaMask钱包授权，并显示钱包地址和余额。\r\n\r\n你的项目结构如下：\r\n\r\n```\r\nmy-web3-project/\r\n│\r\n├── index.html\r\n├── package.json\r\n└── vercel.json\r\n```\r\n\r\n完成这些步骤后，Vercel会提供一个访问链接，访问该链接即可查看部署的项目。","title":"使用 web3modal SDK实现连接MetaMask 钱包，部署到Vercel"},"history":null,"timestamp":1721043213,"version":1}