트랜잭션 및 이벤트 처리
DApp에서 트랜잭션을 전송하고 트랜잭션 확인을 처리하며 스마트 계약 이벤트를 수신하여 UI를 업데이트하는 방법을 배웁니다.
트랜잭션 및 이벤트 처리은(는) CoddyKit의 무료 Web3 & DApp Development Fundamentals 강의입니다. 이것은 3개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Web3 & DApp Development Fundamentals 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Web3 & DApp Development Fundamentals 강의에는 총 3개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Making DApps Dynamic
So far, you've learned how to connect your DApp to the blockchain and read data. But what if you want to change data or perform actions?
This lesson teaches you how to send transactions from your DApp to modify blockchain state and how to listen for real-time updates using smart contract events.
What is a Blockchain Transaction?
A blockchain transaction is a signed message that changes the state of the blockchain. Every transaction costs a small fee called gas, paid in Ether (ETH).
Common DApp transactions include:
- Sending Ether to another address.
- Calling a smart contract function that writes or modifies data.
- Deploying a new smart contract.
Sending Transactions from Your DApp
To send a transaction that calls a smart contract function, your DApp needs to:
- Connect to a blockchain provider (e.g., MetaMask).
- Get a signer (the connected user's wallet).
- Call the desired contract function, passing any required parameters.
The user's wallet will then prompt them to confirm and sign the transaction.
Calling a Write Function Example
Here's how you might call a simple setValue function on a smart contract using Ethers.js. Remember, contract refers to your instantiated contract object.
// Assuming 'contract' is an Ethers.js Contract instance
// and 'signer' is obtained from the connected wallet.
async function updateValue(newValue) {
try {
const tx = await contract.connect(signer).setValue(newValue);
console.log("Transaction sent: ", tx.hash);
// Wait for the transaction to be mined
await tx.wait();
console.log("Transaction confirmed!");
} catch (error) {
console.error("Error sending transaction:", error);
}
}Waiting for Transaction Confirmation
After sending a transaction, it's not immediately processed. It goes into a transaction pool and waits to be included in a block by a miner or validator.
The await tx.wait() call is crucial. It pauses your DApp's execution until the transaction is mined and confirmed on the blockchain, ensuring your UI reflects the latest state.
Understanding Transaction Receipts
When tx.wait() resolves, it returns a transaction receipt. This receipt contains important information about the transaction's outcome:
blockHashandblockNumber: Where it was included.gasUsed: The actual gas consumed.status: Indicates if the transaction was successful (1) or failed (0).
Always check the status to ensure the contract call executed as expected!
Introducing Smart Contract Events
Smart contract events are a powerful mechanism for your contracts to 'broadcast' information to external applications (like your DApp) when something significant happens.
Think of them as logs or notifications that DApps can listen to. They are a cost-effective way to communicate data from the blockchain without storing it directly on-chain.
Emitting Events in Solidity
In Solidity, you first define an event with its parameters, then use the emit keyword to trigger it within a function. Here's a simple example:
pragma solidity ^0.8.0;
contract MyContract {
uint public value;
// Define an event
event ValueChanged(address indexed user, uint oldValue, uint newValue);
function setValue(uint _newValue) public {
uint _oldValue = value;
value = _newValue;
// Emit the event
emit ValueChanged(msg.sender, _oldValue, _newValue);
}
}Listening for Events in Your DApp
Your DApp can subscribe to specific events emitted by a contract. When an event occurs, your DApp receives the event data, allowing you to update the UI or trigger other actions in real-time.
This avoids constant 'polling' (repeatedly asking the blockchain for updates), making your DApp more efficient.
// Assuming 'contract' is an Ethers.js Contract instance
contract.on("ValueChanged", (user, oldValue, newValue, event) => {
console.log(`Value changed by ${user}`);
console.log(`From ${oldValue} to ${newValue}`);
// Update your DApp's UI here, e.g., display the new value
updateDisplay(newValue);
});
console.log("Listening for ValueChanged events...");Quick Check: Tx & Events
When calling a smart contract function that modifies state from your DApp, what is the primary purpose of using await tx.wait()?
Recap & Next Steps
You've learned how to make your DApps truly interactive!
- You can now send transactions to modify blockchain state.
- You know how to wait for confirmation and handle transaction receipts.
- You understand how smart contract events provide real-time updates to your DApp.
These skills are fundamental for building dynamic and responsive decentralized applications. Keep practicing to master DApp interaction!
AI 튜터와 함께 Web3 & DApp Development Fundamentals을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 29
- 레슨
- 105
자주 묻는 질문
“트랜잭션 및 이벤트 처리” 강의는 무료인가요?
네 — “트랜잭션 및 이벤트 처리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Web3 & DApp Development Fundamentals 강의 전체를 잠금 해제할 수 있습니다. Web3 & DApp Development Fundamentals 강의에는 총 3개의 강의가 포함되어 있습니다.
“트랜잭션 및 이벤트 처리”에서 뭘 배우나요?
DApp에서 트랜잭션을 전송하고 트랜잭션 확인을 처리하며 스마트 계약 이벤트를 수신하여 UI를 업데이트하는 방법을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 Web3 & DApp Development Fundamentals을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Web3 & DApp Development Fundamentals을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Web3 & DApp Development Fundamentals은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 3번째 강의입니다.
“트랜잭션 및 이벤트 처리” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Web3 & DApp Development Fundamentals 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Web3 & DApp Development Fundamentals 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- React 및 Web3 프레임워크
- 지갑 통합
- 트랜잭션 및 이벤트 처리