0

I understand we need mnemonic as we did use it in deploying contract with truffle so as to be able to send ether from our ropsten account private keys. I could not find a way use the same in my server.js file to call contract functions. I want to build a webapp which neither uses local node nor metamask and all the transactions are carried by my account. I am sharing my code which i derived from various sources but don't know why is it not executing:

const express = require('express');
const Web3 = require('web3');
const fs = require('fs');

const app = express();
app.use(express.json());

console.log('server side code running');
app.listen(3000, () => {
    console.log('Listening on port 3000');
});

if (typeof web3 !== 'undefined') {
    web3 = new Web3(web3.currentProvider);
}
else {
    web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/<api key>"));
}

var contractabi = JSON.parse(fs.readFileSync('abi.json', 'utf8'));
var contractaddress = '0xb51adbdd256930bd6b4c613add6fcca31db49827';
var contract = new web3.eth.Contract(contractabi,contractaddress);

const privateKey = 'my private key';
const account = web3.eth.accounts.privateKeyToAccount('0x' + privateKey);
web3.eth.accounts.wallet.add(account);
web3.eth.defaultAccount = account.address;
contract.methods.set(7)
    .send({
        from: web3.eth.defaultAccount,
        gas: 2000000,
        gasPrice: 4000000000
    })

Error I'm facing: UnhandledPromiseRejectionWarning: Error: Invalid JSON RPC response: "" I think it returns a promise which i'm not able to use. I need help! and if there are alternate ways to do the same, i'm excited to know

0

You don't need web3 condition, because nobody can inject web3 to your nodejs app.

const web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/TOKEN"));

It looks like url is not correct, based on the error, make sure that you use correct url.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.