Solidity How to Read the Transaction Log
How To Declare and Trigger an Event
In club t o declare an event, you lot demand to apply the post-obit syntax:
The definition of the outcome contains the proper noun of the event and the parameters you want to relieve when you trigger the event.
Once you have alleged your event, you tin can emit an result from within a function, as follows:
emit MyEvent(block.timestamp, 'hello');
Allow's build an example to meet how this actually works.
In your final, create a new directory and use truffle init
to build a new truffle projection. Open the project using your favorite code editor and create a new contract named EventExample.sol
in the contracts folder, and then copy-paste the following code:
Create the corresponding migration file 2_deploy_eventExample.js
:
const EventExample = artifacts.require("EventExample"); module.exports = part (deployer) {
deployer.deploy(EventExample);
};
Let'south deploy at present the contract using truffle migrate
, but earlier migrating don't forget to edit your truffle-config.js
file to configure the network and the compiler.
In your terminal, get-go the Truffle console using truffle panel
.
Nosotros're going to telephone call the storeData
office and examine the logs of the created transaction. Let's start by getting an instance of the deployed contract:
let eventExample = await EventExample.deployed()
We can now call the part using:
let tx = await eventExample.storeData(10)
If you lot print the content of the transaction receipt logs tx.receipt.rawLogs
, which store an assortment of the triggered events that happened during the execution of the transaction, yous will get an array with one object that looks similar this:
You can see that the event information is stored nether the data field in hexadecimal.
How logsBloom Helps to Efficiently Search the Blockchain
To efficiently scan the blockchain looking for events with certain data, yous can add the indexed
keyword in forepart of the event data that you want to employ to filter the events recorded in the blockchain.
issue DataStored(uint256 data1, uint256 indexed data2)
Allow'due south try it out in the example we've simply built:
You lot demand to redeploy the contract using migrate --reset
.
Repeat the same previous steps for getting an case of the deployed contract and calling the storeData
function:
> eventExample = wait EventExample.deployed()
> tx = await eventExample.storeData(10, 15)
Then examine the tx.receipt.rawLogs
. You lot will see the post-obit result:
The data1
field is displayed under data
whereas the indexed field data2
is displayed under the topics
field. As a rule, the indexed parameters go under topics
and the non-indexed parameters become under information
.
The kickoff topic is the hash of the signature of the event, described in the Solidity docs:
topics[0]
:keccak(EVENT_NAME+"("+EVENT_ARGS.map(canonical_type_of).join(",")+")")
(canonical_type_of
is a function that only returns the canonical type of a given statement, due east.g. foruint indexed foo
, it would renderuint256
). If the result is declared every bitanonymous
thetopics[0]
is non generated;
Note: The maximum number of parameters that can be indexed in an event is iii.
Each block header contains a field called logsBloom
and this is the Bloom filter composed of indexable information (log address and log topic) contained in the receipt for each transaction in the transactions list portion of the cake.
When looking for specific events that belong to a certain address or incorporate certain data in the entire blockchain or office of it, the node goes through the block headers and examines the Blossom filter of each block in order to decide if that cake contains the desired log.
How To Read an Result From the Blockchain
Events are meant to exist consumed from outside the blockchain, and this tin can exist done either from the frontend or from a Node.js project.
To make the client simple, I'm going to demonstrate how to read events from a Node project.
Start by creating a new folder chosen client
inside the projection and execute the post-obit commands:
> npm init -y
> npm i web3 --save
> bear upon alphabetize.js
The content of index.js
volition exist as follows:
I have used WebSocket provider instead of HTTP provider since the latter does not back up subscriptions.
In that location are actually 3 ways to read events data from the blockchain:
- From the receipt of a transaction — This is what nosotros did in the previous
index.js
. If you lot executenode alphabetize.js
, you will get the information and topics. - Subscribe to an event — As described in this department of the web3 docs, in that location are three means to subscribe to an event:
-
in one case
: Subscribes to an event and unsubscribes immediately after the kickoff event or error; will merely fire for a single effect. Remove the code containing the transaction execution inindex.js
file and supersede it with the following:
eventExample.once("DataStored", (error, result) => {
if (!fault) console.log(event);
});
From your final, commencement the Node project by executing node index.js
. You won't see anything printed since it's still waiting for the first DataStored
upshot. Open up another last and get the deployed contract example. So call the storeData
function. Yous will now meet an event printed in the commencement panel.
-
events
: Subscribe to an event. The subscription is washed equally follows:myContract.events.MyEvent([options][, callback])
. In this example, we will watch for theDataStored
effect that containsdata2
with a value of 5 or ix.
eventExample.events
.DataStored({ filter: { data2: [5, nine] } })
.on("data", (event) => {
panel.log(consequence);
});
-
events.allEvents
: This is the aforementioned equally events but receives all events from this smart contract. Optionally the filter holding tin can filter those events.
3. Become previous events — This can be washed using getPastEvents
by calling it as follows: myContract.getPastEvents(consequence[, options][, callback])
. the full list of options is described in the docs. One of import option is fromBlock
since if information technology'south not specified, you will get merely the events of the latest block.
eventExample.getPastEvents("DataStored", { fromBlock: 0 }).then((events) => console.log(events));
Source: https://betterprogramming.pub/learn-solidity-events-2801d6a99a92
0 Response to "Solidity How to Read the Transaction Log"
Post a Comment