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
I have tried the manual way of signing the transaction and sending it to node. Like this:
Don't know if it's the only way except using
@truffle/HDWalletProvider
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.
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.Docs: https://web3js.readthedocs.io/en/v1.10.0/web3-eth-accounts.html#wallet-add