0Pricing
Web3 & DApp Development Fundamentals · Lezione

Eventi e storage a confronto

Compromessi in termini di gas

Eventi e storage a confronto è una lezione Web3 & DApp Development Fundamentals gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Web3 & DApp Development Fundamentals, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Web3 & DApp Development Fundamentals include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

Two Ways to Record Data

When something happens in a contract you can record it in storage or in an event log. Choosing wisely is a core gas-optimization skill.

This lesson compares the trade-offs so you know when to use each.

Storage Recap

Storage is the contract's permanent state. It is the only data the contract itself can read back later, but writing to it is very expensive.

<code>mapping(address => uint256) public balances; // contract can read this</code>

Events Recap

Events write to the transaction log. They are far cheaper, but the contract cannot read them back on-chain - only off-chain clients can.

<code>event BalanceChanged(address indexed who, uint256 newBalance);
// off-chain apps read this; the contract cannot</code>

Gas Cost Difference

Writing a fresh storage slot (an SSTORE from zero) costs around 20,000 gas. Emitting a log topic or word costs only a few hundred gas. Events can be an order of magnitude cheaper.

The Golden Rule

A simple guideline:

  • Store data the contract needs to read or use in future logic
  • Emit data only the outside world needs (history, UI, analytics)

Do not store data purely for display - emit it instead.

What Must Be Storage

Balances, ownership, allowances, and any value used in require checks or future calculations must live in storage, because the contract reads them.

<code>function transfer(address to, uint256 amt) public {
    require(balances[msg.sender] >= amt); // needs storage
    balances[msg.sender] -= amt;
    balances[to] += amt;
}</code>

What Can Be Events Only

A transaction history, audit trail, or notification feed is perfect for events. The contract never needs to revisit those records, so storing them would waste gas.

<code>event Logged(address indexed user, string action, uint256 time);

function act(string memory a) public {
    emit Logged(msg.sender, a, block.timestamp); // no storage
}</code>

Use Both Together

The most common pattern is to store the new state and emit an event describing the change. The storage value drives logic; the event keeps the UI in sync.

<code>function deposit() public payable {
    balances[msg.sender] += msg.value; // storage for logic
    emit BalanceChanged(msg.sender, balances[msg.sender]); // event for UI
}</code>

Logs Cannot Be Queried On-Chain

A critical limitation: another contract cannot read your emitted logs. If contract B needs a value, contract A must expose it via storage or a return value, never via an event.

Avoid Storing for History

A common beginner mistake is pushing every action into a storage array to build a history. This grows unbounded and becomes hugely expensive. Emit events instead and let an off-chain indexer rebuild the history.

<code>// Anti-pattern: unbounded, costly
// historyArray.push(record);

// Better:
emit ActionRecorded(msg.sender, block.timestamp);</code>

Decision Checklist

Ask: Does any on-chain code read this value later?

  • Yes - storage (and optionally emit too)
  • No, it is only for display or audit - event only

This single question resolves most design choices.

Quick Check

Test your understanding of events versus storage.

Recap

You learned the storage vs events trade-off:

  • Storage is readable on-chain but expensive (~20k gas per fresh slot)
  • Events are cheap but only off-chain clients can read them
  • Store what the contract needs; emit what only the outside world needs
  • The common pattern: update storage AND emit an event

Never store data purely for history or display.

Domande Frequenti

La lezione «Eventi e storage a confronto» è gratuita?

Sì — il testo completo di «Eventi e storage a confronto» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Web3 & DApp Development Fundamentals, passa a CoddyKit PRO. Il corso Web3 & DApp Development Fundamentals include 4 lezioni in totale.

Cosa imparerò in «Eventi e storage a confronto»?

Compromessi in termini di gas Eserciti Web3 & DApp Development Fundamentals con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Web3 & DApp Development Fundamentals?

Non è richiesta alcuna esperienza precedente. Web3 & DApp Development Fundamentals su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Eventi e storage a confronto»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Web3 & DApp Development Fundamentals?

Sì. Ogni lezione Web3 & DApp Development Fundamentals include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Dichiarazione degli eventi
  2. Parametri indicizzati
  3. Ascolto degli eventi
  4. Eventi e storage a confronto
← Torna a Web3 & DApp Development Fundamentals