Web3 & DApp Development Fundamentals · Ders

Olayları Dinleme

Günlüklere abone olma

4. ders / 413 adım

Olayları Dinleme, CoddyKit'te ücretsiz bir Web3 & DApp Development Fundamentals dersidir. Bu, 4 dersinin 4. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Web3 & DApp Development Fundamentals öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Web3 & DApp Development Fundamentals kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

What Are Events

Smart contracts emit events to log that something happened — a transfer, an approval, a vote. Events are written to the transaction's logs.

  • They are cheaper than storage.
  • Off-chain apps subscribe to them to stay in sync.

Events in the ABI

To decode events, ethers needs their definitions in the ABI:

const abi = [ "event Transfer(address indexed from, address indexed to, uint256 value)", ]; const contract = new ethers.Contract(address, abi, provider);

The indexed keyword marks fields you can filter on.

const abi = [
  "event Transfer(address indexed from, address indexed to, uint256 value)",
];
const contract = new ethers.Contract(address, abi, provider);

Listening Live

Subscribe to new events with on. The callback fires whenever the event is emitted:

contract.on("Transfer", (from, to, value, event) => { console.log(from, "->", to, value); });

This needs a provider that supports subscriptions, such as a WebSocket connection.

contract.on("Transfer", (from, to, value, event) => {
  console.log(from, "->", to, value);
});

WebSocket Providers

Live subscriptions work best over a persistent connection. Use a WebSocket provider:

const provider = new ethers.WebSocketProvider( "wss://mainnet.example-rpc.io/KEY" );

HTTP providers can poll for events but a WebSocket pushes them in real time.

const provider = new ethers.WebSocketProvider(
  "wss://mainnet.example-rpc.io/KEY"
);

Listening Once

If you only care about the first occurrence, use once:

contract.once("Approval", (owner, spender, value) => { console.log("First approval seen"); });

The listener automatically removes itself after firing a single time.

contract.once("Approval", (owner, spender, value) => {
  console.log("First approval seen");
});

Querying Past Events

To read historical events, use queryFilter over a block range:

const logs = await contract.queryFilter( "Transfer", 19000000, 19000100 ); for (const log of logs) { console.log(log.args.from, log.args.value); }

Each log exposes decoded args.

const logs = await contract.queryFilter(
  "Transfer",
  19000000,
  19000100
);
for (const log of logs) {
  console.log(log.args.from, log.args.value);
}

Filtering by Indexed Fields

Build a filter to match specific indexed values — for example transfers to one address:

const filter = contract.filters.Transfer(null, myAddress); const logs = await contract.queryFilter(filter);

Passing null means match any value for that position.

const filter = contract.filters.Transfer(null, myAddress);
const logs = await contract.queryFilter(filter);

Live Filtered Listening

You can also pass a filter to on to react only to relevant events:

const filter = contract.filters.Transfer(null, myAddress); contract.on(filter, (from, to, value) => { console.log("Received:", value); });

This avoids processing events you do not care about.

const filter = contract.filters.Transfer(null, myAddress);
contract.on(filter, (from, to, value) => {
  console.log("Received:", value);
});

Removing Listeners

Long-running apps should clean up listeners to avoid leaks:

contract.off("Transfer", myHandler); // or remove all listeners for an event contract.removeAllListeners("Transfer");

Always remove listeners when a component unmounts or a job finishes.

contract.off("Transfer", myHandler);
// or remove all listeners for an event
contract.removeAllListeners("Transfer");

Handling Reorgs

Recent events can be reverted if the chain reorganizes. For reliable indexing:

  • Wait several confirmations before treating an event as final.
  • Track the block number and re-process if a reorg is detected.

This keeps your off-chain database consistent with the chain.

Provider-Level Log Filters

You can also subscribe at the provider level without a contract instance, using a raw log filter by topic:

provider.on({ address: tokenAddress, topics: [ethers.id("Transfer(address,address,uint256)")], }, (log) => { console.log("Raw log:", log); });

This is lower-level but works across many contracts at once.

provider.on({
  address: tokenAddress,
  topics: [ethers.id("Transfer(address,address,uint256)")],
}, (log) => {
  console.log("Raw log:", log);
});

Quick Check

Test your understanding of event handling.

Recap

You learned to work with contract events.

  • Events log on-chain activity to transaction logs.
  • on subscribes live (best over a WebSocket provider); once fires a single time.
  • queryFilter reads historical events over a block range.
  • Build filters from indexed fields; pass null to match any.
  • Remove listeners to avoid leaks and wait for confirmations against reorgs.
Başlamak ücretsiz

Yapay zeka eğitmeniyle Web3 & DApp Development Fundamentals öğren — ücretsiz

Tarayıcında gerçek kod yaz ve çalıştır, 7/24 yapay zeka eğitmeninden anında yardım al; web'de ya da uygulamada kaldığın yerden devam et.

Kurslar
29
Dersler
105

Sıkça Sorulan Sorular

“Olayları Dinleme” dersi ücretsiz mi?

Evet — “Olayları Dinleme” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Web3 & DApp Development Fundamentals kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Web3 & DApp Development Fundamentals kursu toplamda 4 dersten oluşur.

“Olayları Dinleme” dersinde ne öğreneceğim?

Günlüklere abone olma Web3 & DApp Development Fundamentals ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

Web3 & DApp Development Fundamentals öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Web3 & DApp Development Fundamentals, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 4. dersidir.

“Olayları Dinleme” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu Web3 & DApp Development Fundamentals dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Web3 & DApp Development Fundamentals dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. Sağlayıcıya Bağlanma
  2. Sözleşme Verilerini Okuma
  3. İşlem Gönderme
  4. Olayları Dinleme
← Web3 & DApp Development Fundamentals Sayfasına Dön