0

When using web3 and the JSON RPC, is there a way to subscribe to Solidity events? For instance, I want to subscribe to every

event Transfer(address indexed from, address indexed to, uint256 value);

sent from the contract at address 0x123whatever.

Ideally, I could do this using a hosted JSON RPC provider, and not by running my own node. But if it's impossible on a hosted provider, I might begrudgingly accept instructions for how to do it running my own node.

1

The code below works with Metamask if you want to subscribe to events and show them on browser

if (typeof web3 !== 'undefined') {
          web3 = new Web3(web3.currentProvider);
        }
else
{
   console.log('Metamask not found');return;
}
var abi = [YOUR_CONTRACT_ABI_GOES_HERE];
var MyContract = web3.eth.contract(abi);
        var myContractInstance = MyContract.at("YOUR_CONTRACT_ADDRESS");
var transferEevent = myContractInstance.Transfer({"to":"TO_ADDRESS"},{fromBlock: FROM_BLOCK_NUMBER, toBlock: 'latest'});
transferEevent.watch(function(error, response) {

                 if (!error) {
                console.log(response); // you check args like response.args.fromAddress if you created the event parameter
                 } else {
                      console.error(error);
                 }
            });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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