hey @cryptotester. you dont need moralis fo rthis im sure they probably do provide some functionality as @cryptokid shows above. Yeah you need to use a websocket provider if you want to constantly monitor real time events as they are emitted but in node you can simply just run code such as this
const Web3 = require("Web3")
var web3;
const provider = new Web3.providers.WebsocketProvider("INFURA_ENDPOINT_GOES_HERE")
web3 = new Web3(provider);
contract = new web3.eth.Contract(Contractabi, contractAddress);
async function mainScript() {
contract.events.eventName({}).on("data", (data) => {
try {
//do stuff each time your script detects the required event
} catch (err) {
console.error(err)
}
})
}
mainScript()
you just need to make an instance of whatever the contract is that has the event you need to subscribe to. Then subscribe to the particular event by calling contract.events
and using specificying th eevent youwant then when yoyr script detects the event execute whatever code you wsnt. The above code is very general and i dont know what your specific use case but if you want more of a specifc example cosider the case where you want to get real time price feeds from uniswap. Uniswap has a sync event that is emitted when the uniwap reserves for some token pair is updates. so if you subscribe to this event each time you can get real time price data. consider the code below
const UniswapV2Pair = require("../build/contracts/IUniswapV2Pair.json");
const Web3 = require('web3');
var web3;
const provider = new Web3.providers.WebsocketProvider("INFURA_ENDPOINT_GOES_HERE")
web3 = new Web3(provider);
module.exports = { web3http, web3ws }
// define address of Pair contract
const DaiWethPairAdd = "0xa478c2975ab1ea89e8196811f51a7b7ade33eb11";
// create web3 contract object
const unisswapPairContract = new web3ws.eth.Contract(UniswapV2Pair.abi, DaiWethPairAdd );
// reserve state
const state = {
token0: undefined,
token1: undefined,
};
const mainWSS = async () => {
// fetch current state of reserves
[state.token0, state.token1] = const _reserves = await uniswapPairContract.methods.getReserves().call();
// subscribe to Sync event of Pair
uniswapPairContract.events.Sync({}).on("data", (data) => updateState(data));
// calculate price and print
console.log(`Price ${DAI WETH} : ${state.token0 / state.token1}`)
};
const updateState = (data) => {
// update state
state.token0 = data.returnValues.reserve0) / 10 ** 18; //convert from wei
state.token1 = data.returnValues.reserve1 / 10 ** 18; //convert from wei
state.blockNumber = data.blockNumber;
// calculate price and print
console.log(`Price ${DAI WETH} : ${state.token0 / state.token1}`)
}
mainWSS();
when you call main() the prices will update each time the sync event is fired. Again not sure what your specific example is but with the genral example above and this specific one for uniswap price data you should be able oto get some ideas