Talking about blockchain (10): Events and Logs in Ethereum

Talking about blockchain (10): Events and Logs in Ethereum

Events and logs in Ethereum are particularly confusing concepts. This article will help you sort them out.

First of all, Events and Logs in Ethereum are basically the same concept. They are called Events in Solidity and web3.js, and Logs in the Ethereum Yellow Paper. You can understand it as follows: Ethereum implements the Events function through Logs. Smart contract code writes logs into the blockchain through the LOG opcode.

Where are the log contents located in the blockchain?

The log content is part of the transaction receipts. The entire log content, including other contents of the Receipts, will generate a ReceiptsRoot stored in the header of the block. The complete data is stored off-chain.

There are three main uses for events and logs:

  1. Help the user client (web3.js) read the return value of the smart contract;

  2. Smart contract asynchronously notifies the user client (web3.js);

  3. Storage for smart contracts (much cheaper than Storage);

Let's explain them one by one:

1. Help the user client (web3.js) read the return value of the smart contract:

Assume the following smart contract:

 contract ExampleContract {
// some state variables ...
  function foo(int256 _value) returns (int256) {
// manipulate state ...
return _value;
}
}

We can simulate calling the smart contract through the message call function of web3.js:

 var returnValue = exampleContract.foo.call(2);
console.log(returnValue) // 2

But in the real environment, we need to send a transaction to call a smart contract. At this time, we will not be able to get the return value of the smart contract. Because the transaction is currently just sent, and it will take some time before it is packaged and executed. At this time, the return value of the call is only the txid or tx hash value of the transaction.

 var returnValue = exampleContract.foo.sendTransaction(2, {from: web3.eth.coinbase});
console.log(returnValue) // transaction hash

This is where events come into play:

 //The following is the solidity smart contract code contract ExampleContract {
  event ReturnValue(address indexed _from, int256 _value);
 function foo(int256 _value) returns (int256) {
    ReturnValue(msg.sender, _value);
return _value;
}
}
//The following is the web3.js user client code var exampleEvent = exampleContract.ReturnValue({_from: web3.eth.coinbase});
 exampleEvent.watch(function(err, result) {
if (err) {
console.log(err)
return;
}
  console.log(result.args._value)
  // check that result.args._from is web3.eth.coinbase then
  // display result.args._value in the UI and call
      // exampleEvent.stopWatching()
})
exampleContract.foo.sendTransaction(2, {from: web3.eth.coinbase})
 When the transaction is packaged, the callback in web3.js will be called, and web3.js can get the return value of the smart contract call in the transaction.
As for why the transaction is packaged and the callback in web3 is called, that is another question. A brief explanation is as follows: web3 will be connected to a node in Ethereum. When the node learns that a transaction has entered a block, it will notify the connected web3 of the relevant information.

2. Smart contract asynchronously notifies the user client (web3.js):

 The above example is a typical example of a smart contract notifying a user client, but there are many more asynchronous calls that can be implemented in a similar way, thus realizing the ability of a smart contract to asynchronously call a user client.
Note: Smart contracts are usually written in solidity and run on Ethereum nodes (EVM).
Note: The user client is usually written in web3.js and runs on a web server. web3.js is connected to an Ethereum node.

3. Storage for smart contracts (much cheaper than Storage):

Compared to the storage of smart contract accounts, it is much cheaper to store some information in the form of logs. The approximate price of storage is: 20,000 gas per 32 bytes (256 bits) of storage. The log is about 8 gas per byte.

Let’s look at an example:

 //Solidity smart contract code, simulating user deposit function contract CryptoExchange {
  event Deposit(uint256 indexed _market, address indexed _sender, uint256 _amount, uint256 _time);
 function deposit(uint256 _amount, uint256 _market) returns (int256) {
    // perform deposit, update user's balance, etc
    Deposit(_market, msg.sender, _amount, now);
}
//When a household calls a smart contract to deposit a certain amount of money, the smart contract needs to actively notify the user client to update the corresponding information.
//The following is the web3.js code:
 var depositEvent = cryptoExContract.Deposit({_sender: userAddress});
depositEvent.watch(function(err, result) {
if (err) {
console.log(err)
return;
}
  // append details of result.args to UI
})
 //Specify the block range of interest by adding the fromBlock parameter
 var depositEventAll = cryptoExContract.Deposit({_sender: userAddress}, {fromBlock: 0, toBlock: 'latest'});
depositEventAll.watch(function(err, result) {
if (err) {
console.log(err)
return;
}
  // append details of result.args to UI
//If you don't want to be notified again, you can call:
  //depositEventAll.stopWatching();
})

//Note: The indexed keyword indicates that logs are indexed by this field to improve query efficiency.

The above content is compiled by the author based on online information and personal understanding. If reprinted, please indicate the source "Talk about Blockchain". For more Ethereum knowledge, please read other articles or videos of "Talk about Blockchain", and follow the WeChat public account of "Talk about Blockchain": ttblockchain

<<:  Currency expert: Fedcoin is the last straw to solve the dollar crisis

>>:  Who is swimming naked when the Bitcoin tide recedes: Industry insiders say value will not disappear due to regulation

Recommend

How to read women's palms and tell fortunes about marriage

For women, marriage is the most important thing i...

One eye is bigger than the other, how is the fortune?

A person has a different development trajectory d...

How to read facial moles

Everyone has moles on their face, some are auspic...

Bitcoin Hard Fork: If You Want Peace, Prepare for War

The author of this article, Piotr Piasecki, is a ...

UUPOOL CKB Mining Tutorial - Bminer

navigation: Register and log in to Shuangyou acco...

Is it good or bad if the wealth line is clear and straight? What does it mean?

The money line to a certain extent indicates a pe...

Palmistry for second marriages - palmistry for second marriages

Marriage is full of uncertainties. Many people th...

What are the special moles on the back of the neck? What's the saying?

Moles grow in various parts of our body, especial...

Can the thickness of fingertips reflect one's social skills?

The thickness and shape of the thumb knuckles, as...

Are men with bags under their eyes unfaithful in relationships?

The most important thing in dealing with a relati...