0
const Web3 = require('web3');
const { ethers } = require('ethers');
const { Web3Provider } = require('@ethersproject/providers');

// Virtual addresses

const fromAddress = '0x1234567890123456789012345678901234567890';
const privateKey = '0x1234567890123456789012345678901234567890123456789012345678901234';
const toAddress = '0x0987654321098765432109876543210987654321';

// Set up provider const provider = new

Web3.providers.HttpProvider('https://mainnet.infura.io/v3/f8863437e6e44eb5a850c074eb3eb8ad');
const web3 = new Web3(provider);
const { BigNumber } = require('bignumber.js');
const Tx = require('ethereumjs-tx').Transaction;

// Connect to Metamask

const ethersProvider = new Web3Provider(web3.currentProvider);

// Set up wallet

const wallet = new ethers.Wallet(privateKey, ethersProvider);

exports.transfer = async (req, res) => {
  try {
    const amount = web3.utils.toWei('1', 'ether');
    const currentNonce = await web3.eth.getTransactionCount(fromAddress, 'latest');
    const accountNonce =
      '0x' + (await web3.eth.getTransactionCount(fromAddress) + 1).toString(16)

    const txObject = {
      to: toAddress,
      value: web3.utils.toHex(amount),
      gas: web3.utils.toHex(21000),
      gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
      nonce: accountNonce
    };

    const signedTx = await web3.eth.accounts.signTransaction(txObject, privateKey);

    const result = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);

    res.send(`Transaction hash: ${result.transactionHash}`);
  } catch (error) {
    console.error(error);
    res.status(500).send('Something went wrong');
  }
}
1
  • What are currentNonce and accountNonce values?
    – Ismael
    Commented May 3, 2023 at 15:37

1 Answer 1

0

The nonce is an increasing numeric value. You're trying to assign a hexadecimal value and here comes the error. Try to remove the "0x" prefix and the base 16 conversion:

const amount = web3.utils.toWei('1', 'ether');
    const currentNonce = await web3.eth.getTransactionCount(fromAddress, 'latest');
    const accountNonce =
      await web3.eth.getTransactionCount(fromAddress) + 1;

    const txObject = {
      to: toAddress,
      value: web3.utils.toHex(amount),
      gas: web3.utils.toHex(21000),
      gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
      nonce: accountNonce
    };

Also, unless you know what you're doing, I suggest you reading this answer on how to set the nonce value correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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