skip to Main Content

I can interact with a smart contract when using a local node(ganache).
But when I try to interact with a public node with the following method, I get sender account not recognized

const web3 = new Web3(new HttpProvider('http://localhost:8545'));
const wallet = web3.eth.accounts.privateKeyToAccount(privateKey);
web3.eth.accounts.wallet.add(wallet);
web3.eth.defaultAccount = wallet.address;

const contractObj = new web3.eth.Contract(abi, contractAddress);
const receipt = await contractObj.methods.NameofTheMethod(x).send({ 
  from: myAddress,
  gasLimit: value
});

How can I make it working without third party wallets like @truffle/HDWalletProvider?

2

Answers


  1. Chosen as BEST ANSWER

    I have tried the manual way of signing the transaction and sending it to node. Like this:

    const web3 = new Web3(new HttpProvider('http://localhost:8545'));
    const { address } = web3.eth.accounts.privateKeyToAccount(privateKey);
    
    const contract = new web3.eth.Contract(abi, contractAddress);
    const data = await contract.methods.nameOfTheMethod(x).encodeABI();
    const transaction = {
      data,
      from: address,
      gas: '0x6DDD0',
      gasLimit: value,
    };
    const signedTrx = await web3.eth.signTransaction(transaction, privateKey);
    const receipt = await web3.eth.sendSignedTransaction(signedTrx.rawTransaction);
    console.log(receipt);
    

    Don't know if it's the only way except using @truffle/HDWalletProvider


  2. Your local node knows the private key of the sender => is able to sign the transaction (on the local node).

    The 3rd party node doesn’t know the private key – that’s why you got the error message.

    You can pass the private key to the app so it can sign the transaction locally, and send the already signed transaction to the node without revealing the private key.


    const HDWalletProvider = require("@truffle/hdwallet-provider");
    const provider = new HDWalletProvider({
        privateKeys: ["0x<your_private_key>"],
        providerOrUrl: "https://<node_provider_url>/"
    });
    const web3 = new Web3(provider);
    

    NPM package: https://www.npmjs.com/package/@truffle/hdwallet-provider


    Without using external package, you can pass the private key using the wallet.add() method.

    const web3 = new Web3("https://<node_provider_url>/");
    web3.eth.accounts.wallet.add("0x<your_private_key>");
    

    Docs: https://web3js.readthedocs.io/en/v1.10.0/web3-eth-accounts.html#wallet-add

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search