ตัวอย่าง DApp เบื้องต้น
สร้าง DApp อย่างง่ายที่อ่านข้อมูลจากสัญญาอัจฉริยะซึ่งนำไปใช้งานแล้ว และแสดงข้อมูลบนหน้าเว็บ
ตัวอย่าง DApp เบื้องต้น เป็นบทเรียน Web3 & DApp Development Fundamentals ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 3 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Web3 & DApp Development Fundamentals และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Web3 & DApp Development Fundamentals มีบทเรียนทั้งหมด 3 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Building Our First DApp
Welcome to building your first Decentralized Application (DApp)! In this lesson, we'll create a simple DApp that reads a message stored on a smart contract and displays it on a web page.
This example will tie together concepts you've learned about smart contracts and front-end interaction.
The Simple Message Contract
First, let's define the smart contract. This contract will be very basic: it just stores a single string variable, myMessage, which we'll make public so its value can be easily read from outside the contract.
Remember, this contract would be compiled and deployed to a blockchain (like Ethereum).
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SimpleMessage {
string public myMessage = "Hello CoddyKit DApp!";
}Contract Address & ABI
Once our SimpleMessage contract is deployed to a blockchain, we get two critical pieces of information:
- Contract Address: This is like the contract's unique street address on the blockchain.
- ABI (Application Binary Interface): This is a JSON description of the contract's functions and variables. It tells our front-end how to 'talk' to the contract.
We'll use these in our web application to connect and read data.
Front-end HTML Structure
Our DApp needs a basic web page to display the message. We'll create an index.html file with a heading and a paragraph where our contract's message will appear. We'll also link our JavaScript file (app.js) and the Web3.js library.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CoddyKit DApp</title>
</head>
<body>
<h1>DApp Message Reader</h1>
<p>Message from contract: <span id="contractMessage">Loading...</span></p>
<script src="https://cdn.jsdelivr.net/npm/web3@1.7.0/dist/web3.min.js"></script>
<script src="app.js"></script>
</body>
</html>Connecting with Web3.js
Now for the JavaScript (app.js)! We need to connect our web page to the Ethereum blockchain. The Web3.js library helps us do this. It will look for a provider, like MetaMask, in the user's browser.
// app.js
let web3;
async function initWeb3() {
if (window.ethereum) {
web3 = new Web3(window.ethereum);
try {
await window.ethereum.request({ method: 'eth_requestAccounts' });
console.log("Connected to MetaMask!");
} catch (error) {
console.error("User denied account access");
}
} else if (window.web3) {
web3 = new Web3(window.web3.currentProvider);
} else {
console.log('Non-Ethereum browser detected. Try MetaMask!');
// Fallback for read-only access (e.g., Infura)
// web3 = new Web3(new Web3.providers.HttpProvider("YOUR_INFURA_URL"));
}
}
Instantiating the Contract Object
With Web3.js connected to a provider, we can now create a JavaScript object that represents our deployed SimpleMessage smart contract. We do this using its contract address and ABI.
The ABI tells Web3.js which functions are available on the contract.
// app.js (continued)
const contractAddress = "0xYourDeployedContractAddressHere"; // REPLACE THIS!
const contractABI = [
{
"inputs": [],
"name": "myMessage",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
}
];
let simpleMessageContract;
async function loadContract() {
if (!web3) await initWeb3();
simpleMessageContract = new web3.eth.Contract(contractABI, contractAddress);
console.log("Contract loaded:", simpleMessageContract);
}Reading Contract Data
Now that we have our contract object, reading the myMessage variable is straightforward. Since myMessage is a public view variable, we can call its auto-generated getter function directly without sending a transaction (which means no gas cost).
// app.js (continued)
async function readMessage() {
if (!simpleMessageContract) await loadContract();
try {
// Call the auto-generated getter for 'myMessage'
const message = await simpleMessageContract.methods.myMessage().call();
console.log("Message from contract:", message);
return message;
} catch (error) {
console.error("Error reading message:", error);
return "Error loading message.";
}
}Full DApp JavaScript (app.js)
Here's the complete app.js file that ties everything together. It connects to the blockchain, loads the contract, reads the message, and then updates the HTML to display it when the page loads.
Remember to replace 0xYourDeployedContractAddressHere with your actual deployed contract address!
// app.js
let web3; // Declare web3 globally
const contractAddress = "0xYourDeployedContractAddressHere"; // REPLACE THIS!
const contractABI = [
{
"inputs": [],
"name": "myMessage",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
}
];
let simpleMessageContract;
async function initWeb3() {
if (window.ethereum) { web3 = new Web3(window.ethereum); await window.ethereum.request({ method: 'eth_requestAccounts' }); }
else if (window.web3) { web3 = new Web3(window.web3.currentProvider); }
else { console.log('Non-Ethereum browser detected. Try MetaMask!'); }
}
async function loadContract() {
if (!web3) await initWeb3();
simpleMessageContract = new web3.eth.Contract(contractABI, contractAddress);
}
async function readMessage() {
if (!simpleMessageContract) await loadContract();
try {
const message = await simpleMessageContract.methods.myMessage().call();
return message;
} catch (error) {
console.error("Error reading message:", error);
return "Error loading message.";
}
}
document.addEventListener('DOMContentLoaded', async () => {
const messageElement = document.getElementById('contractMessage');
await initWeb3();
await loadContract();
const msg = await readMessage();
messageElement.innerText = msg;
});DApp Interaction Check
Which of the following are essential pieces of information needed by a front-end DApp to interact with a deployed smart contract?
Recap: Your First DApp
Congratulations! You've just walked through the process of building a basic DApp.
- We defined a simple Solidity smart contract.
- We learned about the importance of the contract's address and ABI.
- We created an HTML page and used Web3.js to connect to the blockchain.
- Finally, we instantiated our contract object and read data from it, displaying it on our web page.
This fundamental pattern of connecting, interacting, and displaying is at the heart of most DApps!
คำถามที่พบบ่อย
บทเรียน “ตัวอย่าง DApp เบื้องต้น” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “ตัวอย่าง DApp เบื้องต้น” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Web3 & DApp Development Fundamentals ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Web3 & DApp Development Fundamentals มีบทเรียนทั้งหมด 3 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “ตัวอย่าง DApp เบื้องต้น”
สร้าง DApp อย่างง่ายที่อ่านข้อมูลจากสัญญาอัจฉริยะซึ่งนำไปใช้งานแล้ว และแสดงข้อมูลบนหน้าเว็บ คุณปฏิบัติ Web3 & DApp Development Fundamentals ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Web3 & DApp Development Fundamentals หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Web3 & DApp Development Fundamentals บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 3 บทเรียน
บทเรียน “ตัวอย่าง DApp เบื้องต้น” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Web3 & DApp Development Fundamentals นี้ได้ไหม
ได้ บทเรียน Web3 & DApp Development Fundamentals ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- ส่วนหน้าและส่วนหลังใน Web3
- การเชื่อมต่อกับ Ethereum (Web3.js/Ethers.js)
- ตัวอย่าง DApp เบื้องต้น