'Sending a signed transaction is not working - Web3 / Node.js

I am trying to send an Ethereum transaction using a private key in Node.js using the web3 library.

I have tried many pieces of code but I get the same issues every time:

  1. The transaction hash is not found on Rinkeby
  2. The transaction doesn't work (no gas is spent and the ethereum doesn't go from one account to the other)
  3. When I run the getTransaction function of web3, it returns null

However, sometimes the transactions pass after a long time (as if gas was too low and then it eventually worked).

Here is my current code :

const provider = new HDWalletProvider({ privateKeys: [pk], providerOrUrl: process.env.ETH_TESTNET_API_URL });
const web3 = new Web3(provider);
const address = await web3.eth.getAccounts();
await web3.eth.sendTransaction({
    from: address[0],
    to,
    nonce, // I made sure that this nonce is the right one
    value: Web3.utils.toHex(Web3.utils.toWei(`${amount}`, 'ether')),
})
.on('transactionHash', resolve);
      await web3.eth.sendSignedTransaction(signedTx.rawTransaction).on('transactionHash', resolve);

I also tried this code, but it gives me the same result :

const signedTx = await web3.eth.accounts.signTransaction({
        to: toAddress,
        value: Web3.utils.toHex(Web3.utils.toWei(`${amount}`, 'ether')),
        gas: gas, // this comes from the estimate gas function
        nonce: nonce, // I made sure this is the right nonce
        data: contract.methods.transfer(to, Web3.utils.toWei(`${amount}`)).encodeABI(),
    },
    privateKey
);
await web3.eth.sendSignedTransaction(signedTx.rawTransaction).on('transactionHash', resolve);

I've been stuck on this for a couple of days, and since the transaction doesn't appear anywhere (not on rinkeby etherscan nor with getTransaction) I can't find a way to debug that.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source