ethers-io / ethers.js

Complete Ethereum library and wallet implementation in JavaScript.
https://ethers.org/
MIT License
7.91k stars 1.84k forks source link

Ethers not connecting to ganache-cli #466

Closed koderholic closed 4 years ago

koderholic commented 5 years ago

When i try to connect to my running ganache-cli instance using the command : new ethers.providers.JsonRpcProvider()

I always end up with this error :

{ Error: invalid response - 0 at exports.XMLHttpRequest.request.onreadystatechange (/app/node_modules/ethers/utils/web.js:84:29) at exports.XMLHttpRequest.dispatchEvent (/app/node_modules/xmlhttprequest/lib/XMLHttpRequest.js:591:25) at setState (/app/node_modules/xmlhttprequest/lib/XMLHttpRequest.js:610:14) at exports.XMLHttpRequest.handleError (/app/node_modules/xmlhttprequest/lib/XMLHttpRequest.js:532:5) at ClientRequest.errorHandler (/app/node_modules/xmlhttprequest/lib/XMLHttpRequest.js:459:14) at ClientRequest.emit (events.js:189:13) at Socket.socketErrorListener (_http_client.js:392:9) at Socket.emit (events.js:189:13) at emitErrorNT (internal/streams/destroy.js:82:8) at emitErrorAndCloseNT (internal/streams/destroy.js:50:3) at process._tickCallback (internal/process/next_tick.js:63:19) statusCode: 0, responseText: 'Error: connect ECONNREFUSED 127.0.0.1:8545\n at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1097:14)' }

Ganache is running and listening on 127.0.0.1:8545 Ethers Version = "4.0.27" Ganache-cli Version : "^6.3.0"

Note : Remix connects to the same ganache-cli instance successfully

Please help, this is really urgent.

ricmoo commented 5 years ago

Ganache CLI usually runs on port 7333, instead of 8545... Can you double check the port?

Can you verify you can hit it using curl on the command line?

koderholic commented 5 years ago

Ganache CLI usually runs on port 7333, instead of 8545... Can you double check the port?

Can you verify you can hit it using curl on the command line?

I have tried using curl. still the same error. Although am running my ganache-cli in a docker container, I suspect that could also contribute.

koderholic commented 5 years ago

But I wonder why remix could connect to my ganache seamlessly.

edzillion commented 5 years ago

Did you ever figure this out @weboluchi ?

I am having a similar issue.

start ganache ganache-cli -i 5777 -p 8545 -m 'menmonic ...' [...] Listening on 127.0.0.1:8545

If I connect via the node cli I can connect and listAccounts() fine:

node
> ethers = require('ethers')
> provider = new ethers.providers.JsonRpcProvider()
> provider.listAccounts().then(result => console.log(result))

Promise {
  <pending>,
  domain:
   Domain {
     domain: null,
     _events:
      [Object: null prototype] {
        removeListener: [Function: updateExceptionCapture],
        newListener: [Function: updateExceptionCapture],
        error: [Function: debugDomainError] },
     _eventsCount: 3,
     _maxListeners: undefined,
     members: [] } }
> [ '0x5B88d914296317775A5405DF8FF6CCCb18507b0f',
  '0x78819734092A45cb7f9B78dCD660e6809fEE07E4',
  [ etcetera... ]

But if I try to connect from my react-native app I keep getting invalid response - 0:

import 'ethers/dist/shims.js'
import { ethers } from 'ethers'

const customHttpProvider = new ethers.providers.JsonRpcProvider()
_providerTest(customHttpProvider)

async _providerTest (provider) {    
    // await provider.ready
    try {
      const accounts = await provider.listAccounts()
      console.log('accounts', accounts)
    } catch (error) {
      console.error(error)
    }
  }

I get a lot of warnings if I run this, with some seemingly related:

- node_modules\expo\build\environment\logging.js:25:23 in warn
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:248:8 in setTimeout
- node_modules\ethers\dist\ethers.min.js:1:283646 in <unknown>
- node_modules\ethers\dist\shims.js:1:5963 in <unknown>
- node_modules\ethers\dist\shims.js:1:6022 in R
- node_modules\ethers\dist\ethers.min.js:1:283585 in fetchJson
- node_modules\ethers\dist\ethers.min.js:1:206210 in send
- node_modules\ethers\dist\ethers.min.js:1:206018 in listAccounts
* lib\utilities\metatx-client\index.js:32:29 in _providerTest$
[...]
* null:null in global code

invalid response - 0
- node_modules\ethers\dist\ethers.min.js:1:284071 in onreadystatechange
- node_modules\event-target-shim\lib\event-target.js:172:43 in dispatchEvent
- ... 8 more stack frames from framework internals

One thing I noticed is that the ready promise is different between these two situations.

Using node-cli it resolves to:

ready:                                   
 Promise {                               
   { chainId: 5777, name: 'unknown' },   
   domain:                               
    Domain {                             
      domain: null,                      
      _events: [Object],                 
      _eventsCount: 3,                   
      _maxListeners: undefined,          
      members: [] } },                   

whereas in react-native it resolves to this:

"ready": R {
    "": 49,
    "_onerror": null,
    "_result": undefined,
    "_state": undefined,
    "_subscribers": Array [
      R {
        "": 50,
        "_result": undefined,
        "_state": undefined,
        "_subscribers": Array [],
      },
      null,
      [Function anonymous],
    ],     

I have been logging my troubleshooting steps here: https://github.com/CirclesUBI/metatx-client/issues/2

edzillion commented 5 years ago

Some other info:

ricmoo commented 5 years ago

Hmmm. I do need to make a better error, but the “0” error usually indicates it is completely not connected. Does react native maybe use some sort of wrapper like docker, which remaps or blocks ports or something? Or is maybe XMLHttpRequest missing? If you console.log(ethers.platform), what do you get?

edzillion commented 5 years ago

hey thanks for the quick reply:

console.log('platform:', ethers.platform)

platform: browser

ricmoo commented 5 years ago

Ok... That’s good then, but eliminates one theory of mine why things won’t work. :p

While the react native is running, can you hit the Ganache with curl?

How is your environment set up? Does the RN run inside a docket on your computer?

edzillion commented 5 years ago

While the react native is running, can you hit the Ganache with curl?

So I wasn't really sure how to do that but I found this on a similar issue: $ curl -X POST --data '{"jsonrpc":"2.0","method":"web3_clientVersion","params":[],"id":67}' localhost:8545

It returns 400 Bad Request and so does hitting the url in the browser (http://localhost:8545)

How is your environment set up? Does the RN run inside a docket on your computer?

Not using docker. I am using expokit with react-native, which involves starting the packager and then building via Android Studio like explained here: https://docs.expo.io/versions/latest/expokit/expokit/

ricmoo commented 5 years ago

Are you running your app on a phone then, and connecting to the expokit on your desktop? I used it once before to debug another issue, and so in that setup for me, this would make sense. Since the URL is to local host, and the expo app was running on my phone, the phone’s local host isn’t the same as the computer’s local host. If you use it the same way I did.

Regardless, the bad request looks like it indicated other issues... does a command line script of ethers stil connect to Ganache?

edzillion commented 5 years ago

Regardless, the bad request looks like it indicated other issues... does a command line script of ethers stil connect to Ganache?

It does, tried it again, works as before.

ricmoo commented 4 years ago

This is a fairly old issue, and I think things may work better now that Ganache is a bit more standards compliant?

I'm going to close this, but if this is still an issue, please re-open it and I'll look into it right away.

Thanks! :)

mirceanis commented 4 years ago

I'm still experiencing this error. Digging deeper into the stack, it looks like request.responseText at line https://github.com/ethers-io/ethers.js/blob/05648177aa7a6bfaf50e0343606f7d08b541dc5a/src.ts/utils/web.ts#L121 is this:

address:"127.0.0.1"
code:"ECONNREFUSED"
errno:"ECONNREFUSED"
message:"connect ECONNREFUSED 127.0.0.1:8545"
port:8545
stack:"Error: connect ECONNREFUSED 127.0.0.1:8545
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1126:14)"
syscall:"connect"

A similar test in another test file worked for me and so did running a duplicate of the failing test in the same file which lead me to believe there may be some conflict or race condition on the pipe to ganache.

I managed to work around this error by condensing all the tests that used ganache into one file, avoiding the need to create multiple instances / connections.

ricmoo commented 4 years ago

That error looks like the Ganache server isn’t running yet, or has shut down when that test runs. Are you waiting for the Ganache to finish starting up before you start calling it, or not calling it after it has shut down?

mirceanis commented 4 years ago

I'm using the in-process provider so I'm not directly starting or stopping it.

import * as ganache from 'ganache-cli'
const provider = new ethers.providers.Web3Provider(ganache.provider());

I suspect this may cause a race condition when it's used like this in 2 separate test files