Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Watching contract events with Infura #73

Closed
dapplion opened this issue Feb 12, 2018 · 25 comments
Closed

Watching contract events with Infura #73

dapplion opened this issue Feb 12, 2018 · 25 comments

Comments

@dapplion
Copy link

Issue #13 shared the inability to listen to contract events through JSON-RPC calls using Infura a year ago. Does any team member have a suggestion on how to achieve so currently? Thank you so much.

@ncocchiaro
Copy link
Contributor

We support websocket endpoints on mainnet, ropsten and rinkeby now that allow you to listen to events:

wss://mainnet.infura.io/ws
wss://ropsten.infura.io/ws
wss://rinkeby.infura.io/ws

The alternative would be to call eth_getLogs starting at a block that's relevant to the contract.

@StarNeit
Copy link

@ncocchiaro , would you please explain more details how to watch contract events?

@StarNeit
Copy link

I am using Infura to mint tokens, but I am not able to find a way to confirm whether transaction is succeeded or failed.

const txhash = "0x5bba2e5cbe643b9a6ccbc5664c737fb411a79e0324c53c4559f081c47e2c6f54"; web3.eth.getTransactionReceipt(txhash).then(txObj => { console.log(txObj); }).catch(err => { console.log(err); })

Error: Web3ProviderEngine does not support synchronous requests.

Please let me know how to watch events when using infura, thank you so much.

@ncocchiaro
Copy link
Contributor

@StarNeit an example of how to use Pub/Sub via websockets to listen for new blocks can be found in #29 (which as it seems you've found by now) and I'm pasting it below. You should be able to adapt that for logs, following the geth pub/sub documentation at https://github.com/ethereum/go-ethereum/wiki/RPC-PUB-SUB.

#!/usr/bin/env node
const Web3 = require('web3');

const web3 = new Web3(new Web3.providers.WebsocketProvider('wss://mainnet.infura.io/ws'));

const subscription = web3.eth.subscribe('newBlockHeaders', (error, blockHeader) => {
  if (error) return console.error(error);

  console.log('Successfully subscribed!', blockHeader);
}).on('data', (blockHeader) => {
  console.log('data: ', blockHeader);
});

// unsubscribes the subscription
subscription.unsubscribe((error, success) => {
  if (error) return console.error(error);

  console.log('Successfully unsubscribed!');
});

The other issue with Web3ProviderEngine is unrelated and due to Web3 not returning promises, so you're effectively calling a method synchronously, which is disallowed.

@StarNeit
Copy link

@ncocchiaro , Thank you for your kind explanation.
But, how can I get transaction list of my own contract?
I only would like to get event of my contract. Is that possible?

@StarNeit
Copy link

@ncocchiaro , Thank you.

I solved problem by using getTransactionReceipt. 👍 👍 👍

@ncocchiaro
Copy link
Contributor

Great, let us know if you have other issues.

@vijaytabhatt
Copy link

@StarNeit can you please tell me how did you solve by getTransactionReceipt?
I am writing a contract where listing to events in my contract is very important
how do we listen to our custom events using websocketprovider?

@sulliwane
Copy link

@ncocchiaro is kovan wss://kovan.infura.io/ws on the roadmap?

@ncocchiaro
Copy link
Contributor

We plan on adding support for the Parity pub/sub interface (all the existing websocket endpoints are backed by Geth), at that point it's possible we'll add a Kovan endpoint. In the meantime if you require a PoA network and don't strictly require Parity my suggestion is to try Rinkeby.

@sulliwane
Copy link

Thanks for the update. One more question, it seems the websocket interface doesn't implement non pub/pub methodes (like getBlock()...) I suppose it's by design ?

@walfridosp
Copy link

I'm trying to use:

var subscription = web3.eth.subscribe('logs', {
    address: ['0x06012c8cf97bead5deae237070f9587f8e7a266d', '0x06012c8cf97bead5deae237070f9587f8e7a266e'],
    topics: null
}, function(error, result){
    if (!error)
        console.log(result);
})
.on("data", function(log){
    console.log(log);
})
.on("changed", function(log){
});

But I'm getting the following error:

Uncaught Error: Provided address ... is invalid, the capitalization checksum test failed

As per the documentation: https://web3js.readthedocs.io/en/1.0/web3-eth-subscribe.html#subscribe

address - String|Array: An address or a list of addresses to only get logs from particular account(s).

Can I pass an Array of addresses instead of a single address?

@rhlsthrm
Copy link

If you want to watch contract events, use this API: http://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#contract-events

myContract.events.MyEvent({
    filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23
    fromBlock: 0
}, function(error, event){ console.log(event); })
.on('data', function(event){
    console.log(event); // same results as the optional callback above
})
.on('changed', function(event){
    // remove event from local database
})
.on('error', console.error);

@timxor
Copy link

timxor commented Jun 14, 2018

Hey @ncocchiaro ! Long time no see :D Is there still no support for a truffle-kovan endpoint from infura?! Thanks man, hope you have been well~

@ncocchiaro
Copy link
Contributor

Hey @tcsiwula, we have the RPC endpoint at https://kovan.infura.io/YOUR_API_KEY but not yet a websockets endpoint for Kovan.

@ramxis
Copy link

ramxis commented Jul 14, 2018

I am having the same issue, the problem is i cannot use Websockets as I am using web3 0.20.6, as when i use web3 1.0 my constant function gives me the error "UnhandledPromiseRejectionWarning: Error: Couldn't decode uint256 from ABI: 0x" when using infura. Since i was not able to resolve the issue with constant functions when using infura so i switched to web3 0.20.6 which works fine for everything except events. Both events and Constant functions works fine if i use ganache but as soon as i connect to infura every thing breaks down. Please tell me how can i watch or get events using infura and web3 v 0.20.6?

@stefek99
Copy link

Micro rant in a related issue: #13 (comment)

Now realizing I need to update my web3.js, TypeError: Web3.providers.WebsocketProvider is not a constructor.

Trying to set up super basic demo using web3.js 1.0.0 and const web3 = new Web3(new Web3.providers.WebsocketProvider('wss://ropsten.infura.io/ws'));

Sample code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Metamask + WebSockets + web3.js 1.0.0</title>

    <!-- USING THIS VERSION: https://github.com/ethereum/web3.js/blob/1.0/dist/web3.js -->
    <script src="lib/web3-v1.0.0-beta.34.js"></script>

    <script>
    var address = "0x2328bc22d5705b2cde99e02a780e2fecdca4ad6b"; // https://ropsten.etherscan.io/address/0x2328bc22d5705b2cde99e02a780e2fecdca4ad6b
    var ABI = [{"constant":true,"inputs":[],"name":"timestampEnd","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"howManyGuaranteed","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"addr","type":"address"}],"name":"getPosition","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"bid","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[],"name":"HEAD","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"initialPrice","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"contributors","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"instructions","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"beneficiary","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"bids","outputs":[{"name":"prev","type":"uint256"},{"name":"next","type":"uint256"},{"name":"value","type":"uint256"},{"name":"contributor","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getGuaranteedContributorsLenght","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"finalize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"addr","type":"address"}],"name":"refundOnBehalf","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"lastBidID","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"refund","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"howMany","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"bids","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"guaranteedContributors","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"increaseTimeIfBidBeforeEnd","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"description","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPosition","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_description","type":"string"}],"name":"setDescription","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"price","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_contribution","type":"uint256"},{"name":"_startSearch","type":"uint256"}],"name":"searchInsertionPoint","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"LIMIT","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"finalized","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"priceGuaranteed","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getAccountListLenght","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"TAIL","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"increaseTimeBy","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"accountsList","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"winner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"guaranteedContributions","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_instructions","type":"string"}],"name":"setInstructions","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"_price","type":"uint256"},{"name":"_description","type":"string"},{"name":"_timestampEnd","type":"uint256"},{"name":"_beneficiary","type":"address"},{"name":"_howMany","type":"uint256"},{"name":"_howManyGuaranteed","type":"uint256"},{"name":"_priceGuaranteed","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"addr","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"timestamp","type":"uint256"}],"name":"GuaranteedBid","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"number","type":"uint256"}],"name":"LogNumber","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"text","type":"string"}],"name":"LogText","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"addr","type":"address"}],"name":"LogAddress","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"bidder","type":"address"},{"indexed":true,"name":"price","type":"uint256"},{"indexed":true,"name":"timestamp","type":"uint256"}],"name":"BidEvent","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"addr","type":"address"},{"indexed":true,"name":"value","type":"uint256"},{"indexed":true,"name":"timestamp","type":"uint256"}],"name":"Refund","type":"event"}];

    const web3 = new Web3(new Web3.providers.WebsocketProvider('wss://ropsten.infura.io/ws'));

    setTimeout(function() {
      var contract = new web3.eth.Contract(ABI, address);

      contract.methods.getAccountListLenght().call(function(err, res) {
        console.log(err, res);
      });

    }, 2000); // 2 seconds to initiatilize the thing

    </script>

  </head>
  <body>
  
  </body>
</html>

WebSocket connection to 'wss://ropsten.infura.io/ws' failed: Error during WebSocket handshake: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received
WebsocketProvider
connection not open on send()

@acidfreako
Copy link

yep i got the same error , i am asking the same question on gitter channel.

@woshidama323
Copy link

Have you fixed this problem ?

@acidfreako
Copy link

Yes I did downgrades Yk beta version 33 and solved the problem

@wodxumingxu
Copy link

i got the same error, what is Yk you refers to? @acidfreako

@JeeChoi
Copy link

JeeChoi commented Jul 30, 2018

the problem/fix(?) is described here: web3/web3.js#1559
like @acidfreako said, you need to downgrade web3.js beta to version 33

@acidfreako
Copy link

@wodxumingxu yes downgrading the web3 from beta 34 to 33 helped

@ghost
Copy link

ghost commented Aug 9, 2018

@ncocchiaro Can you already tell when there will be support for websockets on Kovan?

@ncocchiaro
Copy link
Contributor

Good timing! We now have a wss://kovan.infura.io/ws endpoint, and have just published new documentation on the websocket API: https://infura.io/docs/wss/introduction. Please create a new issue if you see any problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests