You can download the TronSocket SDK from NPM using the command below and follow the steps to listen to Tron Blockchain events and transactions. But first you need to create a token.
Please log the error with the key value “messageLimitPerSecond” in the error handle process because we don't disconnect you when you exceed your message per second limit. we just send a message. However, you may miss some events during this interval. So either listen to these events by filtering them or upgrade your plan.
You can also assume that every time you receive this message you miss an event.
Install SDK
npmi@tronsocket/sdk
Event Types
There are a total of 4 events in the TronSocket Event Listener API and you can listen to them. “transaction” and ‘block’ return only one type of data while ‘contract’ and ‘solidity’ return log or event data. There are helper methods in the SDK to detect them.
Listening to events with the TronSocket SDK is very easy, all you need to do is enter your token as the 1st parameter and set “testnet” true or false in the 2nd parameter and you can easily listen to events on the Nile Testnet network or the Tron Mainnet network.
First of all, you must make sure that the connection is established using the “connect” method.
Also, if you are not getting errors with the Socket.IO polling feature in your current development process. you can enable polling by passing the true parameter to the connect method.
Yes, you can listen to events, blocks and transactions on the Tron Blockchain network with WebSocket with just the above lines.
Use with Filter
In the example above, we didn't add any filters, which means that you will listen to all events moment by moment on the blockchain network. But in such a case, you need a lot of usage limits, right? So you can only listen to certain transactions or events with filters. Take a look at the examples below.
In the example below you can only listen to transactions between two addresses.
import TronSocket, { Transaction, TransactionFilter,} from"@tronsocket/sdk/node";constsocket=newTronSocket("your_token_here",true);awaitsocket.connect().then((connected) => {console.log("Connected:", connected);}).catch((error) => {console.error("Error:", error);});consttransaction= (data:Transaction) => {console.log(data);}consttransactionFilter:TransactionFilter= { toAddress:"TJr3QjX...", fromAddress:"TJr3QjX..."}socket.subscribe("transaction", transaction, transactionFilter); // Subscribe to transaction events with the filter
On & Off
There are basically two methods you will use in the SDK. These are “on” and “off”. I assume that every developer already knows them. You can also use “subscribe” and “unsubscribe” methods as long version.
In the “off”, i.e. unscribe process, if you are listening to the event with filter, please do not forget to send the filter parameter.