이벤트 및 로깅 데이터
이벤트를 사용하여 블록체인에 정보를 기록하고 외부 애플리케이션의 효율적인 모니터링과 색인 생성을 가능하게 하는 방법을 학습합니다.
이벤트 및 로깅 데이터은(는) CoddyKit의 무료 Blockchain Smart Contracts with Solidity 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Blockchain Smart Contracts with Solidity 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Blockchain Smart Contracts with Solidity 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What are Solidity Events?
Smart contracts often need to communicate with the outside world. This is where events come in!
Events are a special feature in Solidity that allow your smart contracts to publish information to the blockchain log.
Think of them as notifications that external applications can listen for.
The Power of Event Logs
Events are crucial because directly reading contract state from off-chain applications can be inefficient and costly.
- Cost-Effective: Storing data in events is cheaper than storing it in contract state.
- Indexable History: They provide a historical record of actions, easily searchable by off-chain tools.
- Monitoring: Wallets, explorers, and dApps can "subscribe" to events to react to changes.
Defining Your First Event
Declaring an event is similar to defining a function, but you use the event keyword.
You specify a name for the event and a list of parameters it will carry, just like function arguments.
These parameters define the data that will be logged when the event is emitted.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract EventExample {
// Declares an event named 'LogMessage'
// It takes a string and a number as parameters
event LogMessage(string message, uint256 timestamp);
}Triggering an Event
Once an event is declared, you can "trigger" it using the emit keyword within any function of your contract.
When emit is called, the event's data is recorded in the transaction's log, but not directly in the contract's storage.
This makes events a lightweight way to signal information.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract EventExample {
event LogMessage(string message, uint256 timestamp);
function doSomethingAndLog(string memory _msg) public {
// Emits the LogMessage event
// current timestamp is block.timestamp
emit LogMessage(_msg, block.timestamp);
}
}Making Events Searchable
You can add the indexed keyword to up to three event parameters. This makes them searchable and filterable by off-chain applications.
indexedparameters: Stored in a special part of the log called "topics."- Non-
indexedparameters: Stored in the "data" part of the log. - Benefit: Off-chain tools can quickly find transactions related to specific indexed values.
Event with Indexed Parameters
Let's see how to declare and emit an event with an indexed parameter.
Notice how `sender` is marked `indexed`, making it easy to filter for all events from a specific address.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract IndexedEventExample {
event Transfer(address indexed from, address indexed to, uint256 amount);
function transferTokens(address _to, uint256 _amount) public {
// Imagine some transfer logic here
// Then emit the event
emit Transfer(msg.sender, _to, _amount);
}
}Logs are Not State
It's important to understand that event logs are not stored within the contract's state.
- State: Data stored directly in the contract, readable by other contracts and functions. Expensive.
- Logs: Part of the blockchain's transaction receipts. They are immutable and persistent, but not directly accessible by other contracts. Cheaper.
Events are primarily for off-chain consumption.
Practical Event Applications
Events are used everywhere in smart contracts. Here are some common applications:
- Token Transfers: ERC-20 and ERC-721 standards heavily rely on `Transfer` and `Approval` events.
- Ownership Changes: Notifying when a contract's owner is updated.
- Data Updates: Signalling when important contract variables have changed.
- User Interface Feedback: DApps listen for events to update UI in real-time.
Off-Chain Interaction
While Solidity contracts can't directly read events, off-chain applications (like web dApps) use web3 libraries (e.g., Web3.js, Ethers.js) to:
- Filter Past Events: Query historical blockchain data for specific events.
- Subscribe to New Events: Listen for events as they are emitted in real-time.
This enables powerful, responsive decentralized applications.
Event Concepts Check
Consider the following Solidity event declaration:
event UserRegistered(
address indexed userAddress,
string userName,
uint256 indexed registrationTime
);
Which parameters are indexed and therefore easily searchable by off-chain tools?
Recap: Events & Logging
You've learned about the power of events in Solidity!
- Events are emitted by contracts to log data on the blockchain.
- They are crucial for off-chain monitoring, indexing, and dApp interaction.
- Use the `event` keyword to declare and `emit` to trigger them.
- `indexed` parameters make events easily searchable.
This mechanism is vital for building responsive and data-driven decentralized applications.
자주 묻는 질문
“이벤트 및 로깅 데이터” 강의는 무료인가요?
네 — “이벤트 및 로깅 데이터” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Blockchain Smart Contracts with Solidity 강의 전체를 잠금 해제할 수 있습니다. Blockchain Smart Contracts with Solidity 강의에는 총 4개의 강의가 포함되어 있습니다.
“이벤트 및 로깅 데이터”에서 뭘 배우나요?
이벤트를 사용하여 블록체인에 정보를 기록하고 외부 애플리케이션의 효율적인 모니터링과 색인 생성을 가능하게 하는 방법을 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 Blockchain Smart Contracts with Solidity을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Blockchain Smart Contracts with Solidity을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Blockchain Smart Contracts with Solidity은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“이벤트 및 로깅 데이터” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Blockchain Smart Contracts with Solidity 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Blockchain Smart Contracts with Solidity 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 상태 변수와 저장소 배치
- 매핑과 동적 배열
- 이벤트 및 로깅 데이터
- 스토리지 슬롯과 가스 최적화