0

I am listening on an event that's happening on smart contract. event UpdatedMaxNumber(address indexed player, uint maxNumber, uint256 timestamp);
My original code works fine and updates the new number in the UI:

contract.events.UpdatedMaxNumber()
 .on('data', function(event) { //switching 'data' for 'message' does not work
  console.log('Updated max number event fired', event);
  let s = "Updated max number: " + event.returnValues[1];
  document.getElementById("viewNumber").innerHTML = s;
}).on('error', console.error);

Then in the console I got: MetaMask: The event 'data' is deprecated and will be removed in the future. Use 'message' instead. For more information, see: https://eips.ethereum.org/EIPS/eip-1193#message
That page suggests Provider.on('message', listener: (message: ProviderMessage) => void): Provider;

I then tried the following code:

web3.currentProvider.on('message', (message) => {
      console.log("message:", message);
  }).on('error', console.error);

This is the log and there is no maxNumber:

{
    "type": "eth_subscription",
    "data": {
        "subscription": "0x6e4d8735d0389c5a02b16bb6354bc126",
        "result": {
            "hash": "0xb1cf7e86d6d3d55bc0f5dc9caaad6c176b8634e6c6d4ad75e734137952faad93",
            "parentHash": "0x5cd1a79601986e49adfe02e06a4f1c8bf5056b6ac2c70417ba357c1ce3f7b5fa",
            "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
            "miner": "0x9b7E335088762aD8061C04D08C37902ABC8ACb87",
            "stateRoot": "0xc5afd4c85cac9b747f8a49d03a724730728c0c335c12fad22fbe7cd1ddd69eef",
            "transactionsRoot": "0xc11074beeea3711f9854ee2bad2fd22def890a90a5ef7508b8c75f564978a414",
            "receiptsRoot": "0xac7e11ac98eb5e723aa0fb697ed9b86e5a66e387400acdc3dbb69ddf74375e20",
            "logsBloom": "0x80004103810740a000b012221c84420000384c00010040800292002c420b802800020081c000801108221d51088401aa2410102082221104043c5d01a264040045208008110521004016800b0928090c85212004018460411028e4461006142b20209802824840002006030c000c0801010a00c8415000d48000c035001802450e42104483371124040035000002e690649014a3402c0120100390802060b0002200020291400112680080840090010e085242322300304888a030268e10808580002962220001018a018814ff124004022440001008401002049594012662085c561184003020088842545328a48044700802101928101204010280010a4401",
            "difficulty": "0",
            "number": 5596480,
            "gasLimit": 30000000,
            "gasUsed": 13809799,
            "nonce": "0x0000000000000000",
            "mixHash": "0x8a650b6f8b2d3a497476bf78bec86dc2ef7255ce1b4d456e490bf3da5e315e4a",
            "timestamp": 1711858404,
            "extraData": "0xd883010d0b846765746888676f312e32312e36856c696e7578"
        }
    }
}

Here's the question, how can I use the "event message" and still get the last updated maxNumber? Working code can be seen https://guess-number-q57u.onrender.com/

2

2 Answers 2

1

Your log output seems to be correct. You might need to parse or decode it, like:

const parsedLog = contractInterface.parseLog(log)

To get the details regarding a particular event being triggered corresponding to a transaction with respect to a contract function call, the following code can be used:

  1. Using ethers.js v6.11.1 (i.e., the latest available version at this point in time):
const { ethers } = require('ethers')

const provider = new ethers.JsonRpcProvider("YOUR_JSON_RPC_URL")

const privateKey = "YOUR_PRIVATE_KEY"

const signer = new ethers.Wallet(privateKey, provider)

const contractAddress = "YOUR_CONTRACT_ADDRESS"

const contractAbi = [
    /* YOUR_CONTRACT_ABI */
]

const contract = new ethers.Contract(contractAddress, contractAbi, signer)

contract.functionName(arg1, arg2, ...).then((tx) => {

    tx.wait().then(async (txReceipt) => {

        const contractInterface = ethers.Interface.from(contractAbi)

        txReceipt.logs.forEach(log => {
            const parsedLog = contractInterface.parseLog(log)
            if (parsedLog) {
                if (parsedLog.name == 'YourEventName') {
                    console.log(parsedLog.args)
                }
            }
        });
    })
})
  1. Using web3.js v4.7.0 (i.e., the latest available version at this point in time):
const { Web3 } = require('web3')

const web3 = new Web3("YOUR_JSON_RPC_URL")

const privateKey = "YOUR_PRIVATE_KEY"

const signer = web3.eth.accounts.privateKeyToAccount(privateKey);

const contractAddress = "YOUR_CONTRACT_ADDRESS"

const contractAbi = [
    /* YOUR_CONTRACT_ABI */
]

const contract = new web3.eth.Contract(contractAbi, contractAddress)

const encodedData = contract.methods.functionName(arg1, arg2, ...).encodeABI();

// Get current gas price
web3.eth.getGasPrice()
    .then(async (gasPrice) => {
        // Estimate gas limit
        web3.eth.estimateGas({
            to: contractAddress,
            data: encodedData,
            nonce: await web3.eth.getTransactionCount(signer.address),

        }).then(async (gasLimit) => {

            const txObject = {
                to: contractAddress,
                from: signer.address,
                data: encodedData,
                gas: gasLimit,
                gasPrice: gasPrice,
                nonce: await web3.eth.getTransactionCount(signer.address),
            };

            signer.signTransaction(txObject).then(async (signedTx) => {

                const txReceipt = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);

                txReceipt.logs.forEach(log => {

                    if (log.address == contractAddress.toLowerCase()) {

                        const decodedLog = web3.eth.abi.decodeLog(
                            contractAbi.find(e => e.type === 'event' && e.name == 'YourEventName').inputs,
                            log.data,
                            log.topics.slice(1)
                        );
                        console.log("YourEventName Event: ", decodedLog);

                    }
                })
            })
        })
    })
0

I will close this question since I used an old example using v 1.3.0, not knowing that there is a current version 4.7.0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.