JeremyEnglert / JointsWP

A blank WordPress theme built with Foundation 6, giving you all the power and flexibility you need to build complex, mobile friendly websites without having to start from scratch.
http://jointswp.com
851 stars 272 forks source link

Web3 code is not working for private Ethereum(geth) node but same code is working in public ethereum #404

Closed NithinTD closed 5 years ago

NithinTD commented 5 years ago

geth version : 1.9.0-stable-52f24617, node version : v8.16.0, web3 version : -- web3@1.0.0-beta.36.

genesis.json:

{
 "config": {
"chainId": 966308076,
"homesteadBlock": 0,
"eip155Block": 0,
"eip158Block": 0
},
"alloc": {},
"difficulty" : "0x20000",
"gasLimit"   : "0x8880000"
 }

web3 code:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

const Web3 = require('web3');
var Accounts = require('web3-eth-accounts');
var artifacts = require('../truffle/build/contracts/ManagePolicies.json');
const Privatekey = '0x67D65FE626EA8138397157B7F883C35C31824C81DE9C020340954694C7858988';

var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8543'));
var accounts = new Accounts();
const ContractAdddress = '0x5c6D08282319372264544047EcCE26017902d268';
const contractABI = artifacts.abi;

const contract = new web3.eth.Contract(contractABI,ContractAdddress);

var app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.get('/getReceipt', (req, res) => {
        const txnHash = req.body.txnHash;
        web3.eth.getTransactionReceipt(txnHash, (err, receipt) => {
            if (receipt == null || err) {
                console.log(receipt, err);
                return res.json({
                    'status': false,
                    'TxnReceipt': 'Transaction is not mined yet, Please try after some time'
                });
            } else {
                return res.json({'status': true, 'TxnReceipt': receipt});
            }
        })
      });

   app.post('/storePolicy', (req, res) => {
        let PolicyID         = req.query.PolicyID;
        let InsuredFullName  = req.query.InsuredFullName;
        let PolicyType       = req.query.PolicyType;
        let InsuredPremium   = req.query.InsuredPremium;
        let InsuredVehicleNo = req.query.InsuredVehicleNo;
        let PolicyStartDate  = req.query.PolicyStartDate;
        let PolicyEndDate    = req.query.PolicyEndDate;
        let hashedPrivateKey =  web3.utils.toHex('0x67D65FE626EA8138397157B7F883C35C31824C81DE9C020340954694C7858988');
        let coinbaseAddress  = accounts.privateKeyToAccount(Privatekey);
          const txn = {
              from: coinbaseAddress.address,
              to: ContractAdddress,
              data: contract.methods.storePolicy(PolicyID,InsuredFullName,PolicyType,InsuredPremium,InsuredVehicleNo,PolicyStartDate,PolicyEndDate).encodeABI(),
              gasLimit: web3.utils.toHex(1000000)
          };
          web3.eth.accounts.signTransaction(txn, hashedPrivateKey)
              .then((signedTxn) => {
                  web3.eth.sendSignedTransaction(signedTxn.raw || signedTxn.rawTransaction)
                      .once('transactionHash', hash => {
                          return res.json({'status': true, 'hash': hash});
                      }).on('receipt', receipt => {
                          return res.json({'status': true, 'receipt': receipt});
                      }).on("error", err => {
                          return res.json({'status': false, 'errors': [err.toString()]});
                      });
              }).catch((err) => {
                  return res.json({'status': false, 'errors': [err.toString()]});
              });
  });

  app.get('/getPolicy', (req, res) => {
    PolicyID = req.query.PolicyID;
    console.log(PolicyID);
    contract.methods.getPolicy(PolicyID).call( function (err, result) {
      if (err) {
        console.log(err);
        res.status(200).send("Error fetching Policy details");
      } else {
        console.log(result);
        res.status(200).json({"status": true, "result": result});
      }
    })
  })

   app.get('/getPolicyCount', (req, res) => {
   contract.methods.getPolicyCount().call( function (err, result) {
    if (err) {
  console.log(err);
  res.status(200).send("Error fetching PolicyCount");
} else {
  console.log(result);
  res.status(200).json({"status": true , "result": result});
}
})
})

app.use(function(req, res, next) {
next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});

module.exports = app;

1.web3 code is working in public ethereum but the same code is not working in private(geth).

2.for Post method I am getting a hash but for get methods, I am getting the error

  1. Is there any problem with my geth or genesis.json.

error:

    Error: Returned values aren't valid, did it run Out of Gas?
at ABICoder.decodeParameters (/home/nithin/project/ConnectedVehicles/node_modules/web3-eth-abi/src/index.js:226:15)
at Contract._decodeMethodReturn (/home/nithin/project/ConnectedVehicles/node_modules/web3-eth-contract/src/index.js:465:22)
at Method.outputFormatter (/home/nithin/project/ConnectedVehicles/node_modules/web3-eth-contract/src/index.js:818:46)
at Method.formatOutput (/home/nithin/project/ConnectedVehicles/node_modules/web3-core-method/src/index.js:163:54)
at sendTxCallback (/home/nithin/project/ConnectedVehicles/node_modules/web3-core-method/src/index.js:473:33)
at /home/nithin/project/ConnectedVehicles/node_modules/web3-core-requestmanager/src/index.js:147:9
at XMLHttpRequest.request.onreadystatechange (/home/nithin/project/ConnectedVehicles/node_modules/web3-providers-http/src/index.js:91:13)
at XMLHttpRequestEventTarget.dispatchEvent (/home/nithin/project/ConnectedVehicles/node_modules/xhr2-cookies/dist/xml-http-request-event-target.js:34:22)
at XMLHttpRequest._setReadyState (/home/nithin/project/ConnectedVehicles/node_modules/xhr2-cookies/dist/xml-http-request.js:208:14)
at XMLHttpRequest._onHttpResponseEnd (/home/nithin/project/ConnectedVehicles/node_modules/xhr2-cookies/dist/xml-http-request.js:318:14)
at IncomingMessage.<anonymous> (/home/nithin/project/ConnectedVehicles/node_modules/xhr2-cookies/dist/xml-http-request.js:289:61)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:139:11)
at process._tickCallback (internal/process/next_tick.js:181:9)
JeremyEnglert commented 5 years ago

I'm thinking this was meant for a different project?