การผสานรวมกระเป๋าเงิน
นำตรรกะการเชื่อมต่อกระเป๋าเงินมาใช้ เพื่อให้ผู้ใช้เชื่อมต่อ MetaMask หรือกระเป๋าเงินอื่นกับ DApp ของคุณสำหรับลงนามธุรกรรมได้
การผสานรวมกระเป๋าเงิน เป็นบทเรียน Web3 & DApp Development Fundamentals ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 3 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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 immediatelyDisplaying 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.ethereumis 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.selectedAddresson 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.
เรียนรู้ Web3 & DApp Development Fundamentals ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 29
- บทเรียน
- 105
คำถามที่พบบ่อย
บทเรียน “การผสานรวมกระเป๋าเงิน” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การผสานรวมกระเป๋าเงิน” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Web3 & DApp Development Fundamentals ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Web3 & DApp Development Fundamentals มีบทเรียนทั้งหมด 3 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การผสานรวมกระเป๋าเงิน”
นำตรรกะการเชื่อมต่อกระเป๋าเงินมาใช้ เพื่อให้ผู้ใช้เชื่อมต่อ MetaMask หรือกระเป๋าเงินอื่นกับ DApp ของคุณสำหรับลงนามธุรกรรมได้ คุณปฏิบัติ Web3 & DApp Development Fundamentals ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Web3 & DApp Development Fundamentals หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Web3 & DApp Development Fundamentals บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 3 บทเรียน
บทเรียน “การผสานรวมกระเป๋าเงิน” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Web3 & DApp Development Fundamentals นี้ได้ไหม
ได้ บทเรียน Web3 & DApp Development Fundamentals ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- React และเฟรมเวิร์ก Web3
- การผสานรวมกระเป๋าเงิน
- การจัดการธุรกรรมและเหตุการณ์