web3 / web3.js

Collection of comprehensive TypeScript libraries for Interaction with the Ethereum JSON RPC API and utility functions.
https://web3js.org/
Other
19.34k stars 4.96k forks source link

Promise web3.eth.getAccounts() not working with 1.0.0-beta.46 #2412

Closed dexterchan closed 5 years ago

dexterchan commented 5 years ago

web3 version 1.0.0-beta.46 is not able to fetch account with ganache

Expected behavior

await web3.eth.getAccounts() is able to output list of accounts

Actual behavior

the command failed with exception asking callback definition. It does not happen in web3 1.0.0-beta.35, web3 1.0.0-beta.37

Steps to reproduce the behavior

Step 1: init ganache and web3 as below "dependencies": { "ganache-cli": "^6.3.0", "web3": "^1.0.0-beta.46" },

Step 2: run following codes: const ganache = require('ganache-cli'); //access Eth test network const Web3 = require('web3'); //Web3 "class" const web3 = new Web3(ganache.provider()); accounts = await web3.eth.getAccounts(); <--- failed with exception

Error Logs

Error: No callback provided to provider's send function. As of web3 1.0, provider.send is no longer synchronous and must be passed a callback as its final argument. at b.send (node_modules/ganache-cli/build/ganache-core.node.cli.js:47:88610) at GetAccountsMethod._callee$ (node_modules/web3-core-method/dist/web3-core-method.cjs.js:454:55) at tryCatch (node_modules/regenerator-runtime/runtime.js:62:40) at Generator.invoke [as _invoke] (node_modules/regenerator-runtime/runtime.js:288:22) at Generator.prototype.(anonymous function) [as next] (node_modules/regenerator-runtime/runtime.js:114:21) at asyncGeneratorStep (node_modules/@babel/runtime/helpers/asyncToGenerator.js:3:24) at _next (node_modules/@babel/runtime/helpers/asyncToGenerator.js:25:9) at node_modules/@babel/runtime/helpers/asyncToGenerator.js:32:7 at GetAccountsMethod. (node_modules/@babel/runtime/helpers/asyncToGenerator.js:21:12) at GetAccountsMethod.execute (node_modules/web3-core-method/dist/web3-core-method.cjs.js:477:25) at Proxy.anonymousFunction (node_modules/web3-core-method/dist/web3-core-method.cjs.js:228:25)

Versions

web3 1.0.0-beta.46

dexterchan commented 5 years ago

seem last version runnable with above code is 1.0.0-beta.37

nivida commented 5 years ago

Could you please update your issue to be aligned with the issue template? Otherwise, I have to close this issue.

dexterchan commented 5 years ago

Could you please update your issue to be aligned with the issue template? Otherwise, I have to close this issue.

done, updated.... thank you

iheqi commented 5 years ago

BTW, both web3.eth.getAccounts().then(console.log); and web3.eth.getAccounts(console.log) have no error, but nothing output.

nivida commented 5 years ago

@dexterchan Thanks for updating the issue. This happens because of the ganache-provider and will be fixed in the next version. (PR: https://github.com/ethereum/web3.js/pull/2426)

aks30498 commented 5 years ago

@dexterchan Thanks for updating the issue. This happens because of the ganache-provider and will be fixed in the next version. (PR: #2426)

Am trying to use the same function with truffle and infura I am getting these behaviours for different versions: beta-46: Cannot read property map() of undefined One answer on stackexchange says use beta-36 to fix this issue

beta-36 and beta-37: Nothing after the getAccounts() statement gets executed, blank screen.

beta-26: core.addProviders is not a function

Here is the code:

const HDWalletProvider = require('truffle-hdwallet-provider');
const Web3 = require('web3');
const {interface , bytecode} = require('./compile');

const provider = new HDWalletProvider(mnemonic,
'https://rinkeby.infura.io/v3/my_project_id');

const web3 = new Web3(provider);

const deploy = async() => {
    const accounts = await web3.eth.getAccounts();
    console.log('Attempting to deploy from account', accounts[0]);
    const result = await new web3.eth.Contract(JSON.parse(interface))
                             .deploy({data: bytecode, arguments: ['Hi There!']})
                             .send({'from': accounts[0], 'gas': '1000000'});

    console.log('Contract deployed to: ', result.options.address);
};
deploy();

Please help.....

chaitanyapotti commented 5 years ago

@aks30498 What's your version of truffle-hdwallet-provider? I'm using

 "truffle-hdwallet-provider": "^1.0.5",
 "web3": "1.0.0-beta.37"

and it works

aks30498 commented 5 years ago

@chaitanyapotti I have truffle 0.0.3 .... Anyways.... I removed "v3" from Infura link.... And it worked... :)

GNSPS commented 5 years ago

This is still unresolved for me. truffle-hdwallet-provider@1.0.5 and INFURA together with web3@1.0.0-beta47 stop execution at await web3.eth.getAccounts() without any error output.

chaitanyapotti commented 5 years ago

Yes @GNSPS it doesn't work with Infura, web3@1.0.0-beta.47 and truffle-hdwallet-provider@1.0.5 I've tried using both v3 and non-v3 links of Infura This issue needs to be reopened.

UnhandledPromiseRejectionWarning: Error: invalid json request
    at C:\Users\Naina\source\repos\Learning-solidity\kickstart\node_modules\truffle-hdwallet-provider\dist\index.js:15:620862
    at e.i.onreadystatechange (C:\Users\Naina\source\repos\Learning-solidity\kickstart\node_modules\truffle-hdwallet-provider\dist\index.js:15:775522)
    at e.t.dispatchEvent (C:\Users\Naina\source\repos\Learning-solidity\kickstart\node_modules\truffle-hdwallet-provider\dist\index.js:1:152983)
    at e._setReadyState (C:\Users\Naina\source\repos\Learning-solidity\kickstart\node_modules\truffle-hdwallet-provider\dist\index.js:15:780284)
    at e._onHttpResponseEnd (C:\Users\Naina\source\repos\Learning-solidity\kickstart\node_modules\truffle-hdwallet-provider\dist\index.js:15:783369)
    at IncomingMessage.<anonymous> (C:\Users\Naina\source\repos\Learning-solidity\kickstart\node_modules\truffle-hdwallet-provider\dist\index.js:15:782627)
    at IncomingMessage.emit (events.js:187:15)
    at endReadableNT (_stream_readable.js:1094:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)

The error message can be logged by putting a try catch block. @nivida

Downgrading web3 to 1.0.0-beta.37 however resolves the issue

GNSPS commented 5 years ago

1.0.0-beta.37 still not working for me. 😞

Even inside a try catch block I get no output whatsoever.

aks30498 commented 5 years ago

@GNSPS you need to remove v3 from infura link... I was stuck for 3 days as well... finally using beta.37 and truffle^0.0.3 and removing v3 from the link worked.... here's package:

"truffle-hdwallet-provider": "0.0.3", "web3": "^1.0.0-beta.37"

and code:

 const HDWalletProvider = require('truffle-hdwallet-provider');
    const Web3 = require('web3');
    const {bytecode , interface} = require('./compile');

    const provider = new HDWalletProvider({mnemonic},
    'https://rinkeby.infura.io/{project_id}');

    const web3 = new Web3(provider);

    const deploy = async() => {

    const accounts = await web3.eth.getAccounts().catch((e) => { console.log(e); });
    console.log('Attempting to deploy from account', accounts[0]);

    const result = await new web3.eth.Contract(JSON.parse(interface))
                             .deploy({data: bytecode, arguments: ['Hi There!']})
                             .send({'from': accounts[0], 'gas': '1000000'}).catch((e) => { console.log(e); });

    console.log('Contract deployed to: ', result.options.address);
}
deploy();
GNSPS commented 5 years ago

This does indeed fix it! 😄 Thank you @aks30498!

AJSihota commented 5 years ago

Still getting the same error even with @aks30498's step. "truffle-hdwallet-provider": "0.0.3", "web3": "^1.0.0-beta.37"

and code is the following =>

const HDWalletProvider = require("truffle-hdwallet-provider");
const Web3 = require("web3");
const compiledFactory = require("./build/CampaignFactory.json");

const provider = new HDWalletProvider(
  mneumonic,
  "https://rinkeby.infura.io/{accountId}"
);

const web3 = new Web3(provider);

const deploy = async () => {
  const accounts = await web3.eth.getAccounts().catch((e) => {console.log(e);});

  console.log("Attempting to deploy from account..." + accounts);

  const result = await new web3.eth.Contract(
    JSON.parse(compiledFactory.interface)
  )
    .deploy({ data: compiledFactory.bytecode })
    .send({ gas: "1000000", from: accounts[0] }).catch((e) => {console.log(e);});

  console.log("This is the address : " + result.options.address);
};
deploy();

Anything i could be missing? Thanks

aks30498 commented 5 years ago

Still getting the same error even with @aks30498's step. "truffle-hdwallet-provider": "0.0.3", "web3": "^1.0.0-beta.37"

and code is the following =>

const HDWalletProvider = require("truffle-hdwallet-provider");
const Web3 = require("web3");
const compiledFactory = require("./build/CampaignFactory.json");

const provider = new HDWalletProvider(
  mneumonic,
  "https://rinkeby.infura.io/{accountId}"
);

const web3 = new Web3(provider);

const deploy = async () => {
  const accounts = await web3.eth.getAccounts().catch((e) => {console.log(e);});

  console.log("Attempting to deploy from account..." + accounts);

  const result = await new web3.eth.Contract(
    JSON.parse(compiledFactory.interface)
  )
    .deploy({ data: compiledFactory.bytecode })
    .send({ gas: "1000000", from: accounts[0] }).catch((e) => {console.log(e);});

  console.log("This is the address : " + result.options.address);
};
deploy();

Anything i could be missing? Thanks

@AJSihota It shows some error or just nothing at all... and returns after some time ? When i faced issue in this part of course... it was related to gas and using 'gas': '3000000' fixed it. Also i think u should use accounts[0] to print the exact address intead of accounts which would print the array of all the addresses in first console log statement (although it wouldnt give any error but....just saying).

AJSihota commented 5 years ago

@aks30498 This is my error message when I run the code above :

Error: Web3ProviderEngine does not support synchronous requests.
    at Web3ProviderEngine.send (/Users/user/Downloads/kickstart/node_modules/web3-provider-engine/index.js:54:9)
    at HDWalletProvider.send (/Users/user/Downloads/kickstart/node_modules/truffle-hdwallet-provider/index.js:33:27)
    at GetAccountsMethod._callee$ (/Users/user/Downloads/kickstart/node_modules/web3-core-method/dist/web3-core-method.cjs.js:454:55)
    at tryCatch (/Users/user/Downloads/kickstart/node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:62:40)
    at Generator.invoke [as _invoke] (/Users/user/Downloads/kickstart/node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:288:22)
    at Generator.prototype.(anonymous function) [as next] (/Users/user/Downloads/kickstart/node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:114:21)
    at asyncGeneratorStep (/Users/user/Downloads/kickstart/node_modules/@babel/runtime/helpers/asyncToGenerator.js:3:24)
    at _next (/Users/user/Downloads/kickstart/node_modules/@babel/runtime/helpers/asyncToGenerator.js:25:9)
    at /Users/user/Downloads/kickstart/node_modules/@babel/runtime/helpers/asyncToGenerator.js:32:7
    at new Promise (<anonymous>)
    at GetAccountsMethod.<anonymous> (/Users/user/Downloads/kickstart/node_modules/@babel/runtime/helpers/asyncToGenerator.js:21:12)
    at GetAccountsMethod.execute (/Users/user/Downloads/kickstart/node_modules/web3-core-method/dist/web3-core-method.cjs.js:477:25)
    at Proxy.anonymousFunction (/Users/user/Downloads/kickstart/node_modules/web3-core-method/dist/web3-core-method.cjs.js:228:25)
    at deploy (/Users/user/Downloads/kickstart/ethereum/deploy.js:13:35)
    at Object.<anonymous> (/Users/user/Downloads/kickstart/ethereum/deploy.js:25:1)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
(node:2704) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '0' of undefined
    at deploy (/Users/user/Downloads/kickstart/ethereum/deploy.js:15:64)
    at process._tickCallback (internal/process/next_tick.js:68:7)
    at Function.Module.runMain (internal/modules/cjs/loader.js:745:11)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
(node:2704) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:2704) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I've tried adjusting my gas amount and printing from first index of accounts instead of the entire array. But still getting this error message. I'm handling the callbacks with catch(e) but not sure if there could be something else I missed

aks30498 commented 5 years ago

@AJSihota Exact same code worked for me when i deployed it!! i just redeployed it using my code to double check. And the error that it shows to you should be in the case when you called the getAccounts() method synchronously. Just make sure that async await is used correctly in your script. People have raised issue with this error earlier but using promises/async-await fixes it and we already have that in our code. Am also a newbie to solidity so i don't know what else can it be! I mean, the same code with same versions of dependencies works for me (just deployed a few seconds ago!)

Ok... so to make sure there isn't any itty-bitty error that we're missing, i just copied the code given by you in your comment, entered my mnemonic and address, changed gas to 3000000 and it worked for me. I can't reproduce your issue.

Raj2367 commented 5 years ago

First I was using 1.0.0-beta.26...it was showing error as "core.addProviders is not a function"... Then I change my web3 version to 1.0.0-beta.37 and now it is working properly... Thanks @dexterchan

KanishkShirodkar commented 5 years ago

TypeError: core.addProviders is not a function , is there any other function i can use instead?? or any other way?

varunraj commented 5 years ago

I had the same issue described here. Code is exiting at below line without any error in console.

const accounts = await web3.eth.getAccounts();

I was able to solve the problem when I run the deploy code after executing below command/.

set NODE_TLS_REJECT_UNAUTHORIZED=0

AanshSavla commented 4 years ago

This problem is because the dapps and metamask have stopped exposing user accounts by default on web page. Just use 'ethereum.enable()' as first line of your javascript code. It worked for me.

ZeeshanAhmadKhalil commented 1 year ago

@aks30498 This is my error message when I run the code above :

Error: Web3ProviderEngine does not support synchronous requests.
    at Web3ProviderEngine.send (/Users/user/Downloads/kickstart/node_modules/web3-provider-engine/index.js:54:9)
    at HDWalletProvider.send (/Users/user/Downloads/kickstart/node_modules/truffle-hdwallet-provider/index.js:33:27)
    at GetAccountsMethod._callee$ (/Users/user/Downloads/kickstart/node_modules/web3-core-method/dist/web3-core-method.cjs.js:454:55)
    at tryCatch (/Users/user/Downloads/kickstart/node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:62:40)
    at Generator.invoke [as _invoke] (/Users/user/Downloads/kickstart/node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:288:22)
    at Generator.prototype.(anonymous function) [as next] (/Users/user/Downloads/kickstart/node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:114:21)
    at asyncGeneratorStep (/Users/user/Downloads/kickstart/node_modules/@babel/runtime/helpers/asyncToGenerator.js:3:24)
    at _next (/Users/user/Downloads/kickstart/node_modules/@babel/runtime/helpers/asyncToGenerator.js:25:9)
    at /Users/user/Downloads/kickstart/node_modules/@babel/runtime/helpers/asyncToGenerator.js:32:7
    at new Promise (<anonymous>)
    at GetAccountsMethod.<anonymous> (/Users/user/Downloads/kickstart/node_modules/@babel/runtime/helpers/asyncToGenerator.js:21:12)
    at GetAccountsMethod.execute (/Users/user/Downloads/kickstart/node_modules/web3-core-method/dist/web3-core-method.cjs.js:477:25)
    at Proxy.anonymousFunction (/Users/user/Downloads/kickstart/node_modules/web3-core-method/dist/web3-core-method.cjs.js:228:25)
    at deploy (/Users/user/Downloads/kickstart/ethereum/deploy.js:13:35)
    at Object.<anonymous> (/Users/user/Downloads/kickstart/ethereum/deploy.js:25:1)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
(node:2704) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '0' of undefined
    at deploy (/Users/user/Downloads/kickstart/ethereum/deploy.js:15:64)
    at process._tickCallback (internal/process/next_tick.js:68:7)
    at Function.Module.runMain (internal/modules/cjs/loader.js:745:11)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
(node:2704) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:2704) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I've tried adjusting my gas amount and printing from first index of accounts instead of the entire array. But still getting this error message. I'm handling the callbacks with catch(e) but not sure if there could be something else I missed

I am using loopring SDK to get EcDSA Signature but getting the same error while passing web3 as follows:

import Web3 from "web3";
import {
    LoopringAPI,
    LOOPRING_EXPORTED_ACCOUNT,
    testTypedData,
    TOKEN_INFO,
} from "@Config/Wallet/loopring-sdk";

const PrivateKeyProvider = require("truffle-privatekey-provider");
const provider = new PrivateKeyProvider(
    LOOPRING_EXPORTED_ACCOUNT.privateKey, //todo: use ethAccountPrivateKey here
    `https://${chain}.infura.io/v3/${infuraProjectId}`
);

var web3 = new Web3(provider);

const eddsaKey = await sdk.getEcDSASig(
            web3,
            testTypedData,
            LOOPRING_EXPORTED_ACCOUNT.address,
            sdk.GetEcDSASigType.HasDataStruct,
            sdk.ChainId.GOERLI,
            LOOPRING_EXPORTED_ACCOUNT.accountId,
            "",
            sdk.ConnectorNames.Unknown
        );

Error:

error===> Error: Web3ProviderEngine does not support synchronous requests.
    at Web3ProviderEngine.send (/Users/uni/Projects/NFTDD/nftdd-wallet/node_modules/web3-provider-engine/index.js:114:9)
    at PrivateKeyProvider.send (/Users/uni/Projects/NFTDD/nftdd-wallet/node_modules/truffle-privatekey-provider/index.js:39:27)
    at response (/Users/uni/Projects/NFTDD/nftdd-wallet/node_modules/@loopring-web/loopring-sdk/dist/loopring-sdk.cjs.development.js:3091:30)
    at new Promise (<anonymous>)
    at Object.getEcDSASig (/Users/uni/Projects/NFTDD/nftdd-wallet/node_modules/@loopring-web/loopring-sdk/dist/loopring-sdk.cjs.development.js:3090:24)
    at handler (webpack-internal:///(api)/./pages/api/transaction-l2.ts:53:88)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Object.apiResolver (/Users/uni/Projects/NFTDD/nftdd-wallet/node_modules/next/dist/server/api-utils/node.js:363:9)
    at async DevServer.runApi (/Users/uni/Projects/NFTDD/nftdd-wallet/node_modules/next/dist/server/next-server.js:487:9)
    at async Object.fn (/Users/uni/Projects/NFTDD/nftdd-wallet/node_modules/next/dist/server/next-server.js:749:37)
    at async Router.execute (/Users/uni/Projects/NFTDD/nftdd-wallet/node_modules/next/dist/server/router.js:253:36)
    at async DevServer.run (/Users/uni/Projects/NFTDD/nftdd-wallet/node_modules/next/dist/server/base-server.js:384:29)
    at async DevServer.run (/Users/uni/Projects/NFTDD/nftdd-wallet/node_modules/next/dist/server/dev/next-dev-server.js:741:20)
    at async DevServer.handleRequest (/Users/uni/Projects/NFTDD/nftdd-wallet/node_modules/next/dist/server/base-server.js:322:20)
    at async Server.<anonymous> (/Users/uni/Projects/NFTDD/nftdd-wallet/server.js:26:17)