0Pricing
Web3 & DApp Development Fundamentals · 课时

集成钱包

实现钱包连接逻辑,让用户能够将 MetaMask 或其他钱包连接到您的 DApp 以签署交易。

集成钱包 是 CoddyKit 上的免费 Web3 & DApp Development Fundamentals 课时。 这是第 2 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Web3 & DApp Development Fundamentals 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Web3 & DApp Development Fundamentals 课程共包含 3 节课。

本课时的部分内容尚未翻译,以英文显示。

The Gateway to Web3

Decentralized Applications (DApps) need a way for users to interact with the blockchain. Wallets like MetaMask serve as this crucial bridge, securely managing cryptographic keys and signing transactions.

Connecting a wallet allows your DApp to:

  • Read the user's blockchain address.
  • Request transaction approvals from the user.
  • Interact with smart contracts on behalf of the user.

Your DApp's Blockchain Interface

When a Web3 wallet (like MetaMask) is installed in a user's browser, it injects a special object into the browser's JavaScript environment: window.ethereum.

This window.ethereum object is your DApp's primary interface to communicate with the blockchain and the user's wallet. It provides an API to send requests and listen for events.

Is a Wallet Present?

Before trying to connect, your DApp should always check if window.ethereum exists. If it's not present, the user likely doesn't have a Web3 wallet installed, or it's not enabled.

You can then prompt them to install one, usually MetaMask, which is the most common.

if (window.ethereum) {
  console.log("MetaMask detected!");
} else {
  console.log("Please install MetaMask to use this DApp.");
}

Asking for Connection Permission

To get the user's blockchain address and enable transaction signing, your DApp must explicitly request access. This is done using the eth_requestAccounts method via the window.ethereum object.

This action will trigger a pop-up in the user's wallet, asking them to approve the connection. If approved, it returns an array of account addresses, typically just one.

Building a Connect Function

Let's create a simple JavaScript function to connect a user's wallet. This code assumes it runs in a browser environment where window.ethereum might be available.

async function connectWallet() {
  if (window.ethereum) {
    try {
      const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
      console.log('Connected account:', accounts[0]);
      alert(`Wallet connected! Account: ${accounts[0]}`);
      return accounts[0];
    } catch (error) {
      if (error.code === 4001) {
        console.log('User rejected connection.');
        alert('Connection rejected by user.');
      } else {
        console.error('Connection error:', error);
      }
    }
  } else {
    console.log('MetaMask not detected. Please install it!');
    alert('MetaMask not detected. Please install it to use this DApp.');
  }
  return null;
}

// In a real DApp, you'd call this function, e.g., on a button click:
// connectWallet(); // Uncomment to try connecting immediately

Displaying the Connected Account

Once the user successfully connects their wallet, the eth_requestAccounts method returns an array of their connected accounts. The first account accounts[0] is typically the user's currently selected address.

It's good practice to display this address in your DApp's UI to confirm the connection to the user. You can also get the currently selected address using window.ethereum.selectedAddress after a connection is established.

Staying Up-to-Date: Account Changes

Users can change their connected account, switch networks, or even disconnect their wallet at any time. Your DApp needs to react to these changes to maintain a consistent state and provide a good user experience.

The window.ethereum object emits events for these situations. The accountsChanged event is crucial for detecting when the user switches accounts or disconnects.

Reacting to Account Events

Here's how to set up an event listener to update your DApp when the user changes their active account in MetaMask. This code would typically run after your DApp has initialized.

if (window.ethereum) {
  window.ethereum.on('accountsChanged', (accounts) => {
    if (accounts.length === 0) {
      console.log('User disconnected all accounts.');
      alert('Wallet disconnected!');
      // Update UI to 'Not Connected' or prompt to connect
    } else {
      console.log('Switched account to:', accounts[0]);
      alert(`Account changed to: ${accounts[0]}`);
      // Update UI with new account address
    }
  });
  console.log("Listening for 'accountsChanged' events.");
} else {
  console.log("MetaMask not detected, cannot listen for account changes.");
}

Adapting to Network Changes

DApps often operate on specific blockchain networks (e.g., Ethereum Mainnet, Sepolia Testnet). Users might switch networks using their wallet interface.

Your DApp should listen for the chainChanged event to react to these network switches. If the user switches to an unsupported network, you might prompt them to switch back or disable DApp functionality until they do.

Robust Wallet Integration Tips

To build a robust and user-friendly DApp, consider these best practices:

  • Prompt Installation: If window.ethereum is missing, provide a clear link for users to install MetaMask.
  • User Feedback: Always show loading states or connection status in your UI.
  • Error Handling: Catch errors from eth_requestAccounts, especially user rejections (error.code === 4001).
  • Reconnect on Load: Consider checking for ethereum.selectedAddress on page load to auto-reconnect if the user previously granted permission.

Quick Check: Wallet Connection

When building a DApp, interacting with a user's wallet is fundamental. Consider the initial steps a DApp needs to take to connect with a user's MetaMask wallet.

Recap: Integrating Wallets

In this lesson, you learned how to integrate a Web3 wallet like MetaMask into your DApp. We covered checking for the window.ethereum object, requesting account access with eth_requestAccounts, and handling important events like accountsChanged.

Mastering wallet integration is crucial for building interactive and functional decentralized applications, allowing users to connect their identity and sign transactions on the blockchain.

常见问题解答

「集成钱包」课时是免费的吗?

是的 — 「集成钱包」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Web3 & DApp Development Fundamentals 课程的其余内容,请升级到 CoddyKit PRO。 Web3 & DApp Development Fundamentals 课程共包含 3 节课。

「集成钱包」这节课中我会学到什么?

实现钱包连接逻辑,让用户能够将 MetaMask 或其他钱包连接到您的 DApp 以签署交易。 你通过在浏览器中直接运行的动手代码来练习 Web3 & DApp Development Fundamentals,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Web3 & DApp Development Fundamentals 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Web3 & DApp Development Fundamentals 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 3 节。

「集成钱包」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Web3 & DApp Development Fundamentals 课中编写并运行代码吗?

能。每节 Web3 & DApp Development Fundamentals 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. React 与 Web3 框架
  2. 集成钱包
  3. 处理交易与事件
← 返回 Web3 & DApp Development Fundamentals