Go-Ethereum – How to Access Geth from Node.js

go-ethereumnodejsweb3js

I have geth running on localhost:

geth.exe --testnet --fast --cache 1024 --ipcpath \\.\pipe\geth.ipc --rpccorsdomain * --rpcport 8545 --rpc

If I do the following:

var Web3 = require('web3');
var web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
var abi = ...
web3.eth.Contract(abi,"0x5cb023C894D7838Ee7C0eE43AFD8D10D75Cd89bd");

This gives me an error: TypeError: Cannot redefine property: currentProvider on the last line, error happens inside web3-core\src\index.js:42:16

Second syntax, which one can find on the net:

web3.eth.contract(abi)

gives another error: TypeError: web3.eth.contract is not a function

What is the right syntax to execute contract from nodejs with geth?

Best Answer

Please check your web3 version with,

var Web3 = require('web3');
var web3 = new Web3();
web3.version

If you get 1.0.0-beta.11 or similar (rather than 0.20.0) then you've picked up the new version. npm now installs the new version by default.

You can either go back to the older version with npm install web3@0.20.0, or consult the documentation for the new version for all the (many, many) changes.

This should answer your specific question with the new syntax:

const Web3 = require('web3');
const web3 = new Web3('http://localhost:8545');
const contract = new web3.eth.Contract(abi, '0x.....');
Related Topic