I am a beginner in Ethereum development. I am using Web3 js 1.0 to build a simple node js application that sends ether from one wallet to another on Mainnet.

I am having problem in creating buffer from private key, keep getting this error-

Error: Expected private key to be an Uint8Array with length 32.

This is my code:

//Private keys
const key1 = "0xb7bxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

//Generate Byte Buffer for key
const buffer1 = Buffer.from(key1, "hex");

const rawTx = {
  nonce: web3.utils.toHex(count),
  to: addTo,
  value: web3.utils.toHex(bal - 10000000000 * 21000),
  gasLimit: web3.utils.toHex(21000),
  gasPrice: web3.utils.toHex(10000000000),

const txn = new Tx(rawTx);

const serialTx = txn.serialize();
const raw = "0x" + serialTx.toString("hex");

web3.eth.sendSignedTransaction(raw).on("transactionHash", (txHash) => {
  console.log("transactionHash:", txHash);

I read somewhere that you have to remove the 0x from the Private key before passing it to the Buffer method? Is it true?

2 Answers 2


If you change your code to this, it should do the trick.

const buffer1 = Buffer.from(key1.substring(2,66), "hex");

  • Probably you wanted to use key1.substring(2, 66) so it will skip the 0x prefix.
    – Ismael
    Commented Feb 9, 2022 at 20:38
  • Yes, I meant that. Thank you. Edited. @Ismael Commented Feb 17, 2022 at 21:31

Try with the following code:

public function transfer(
    privateKey: string,
    fromAccount: string,
    toAccount: string,
    amount: string
  ) {
    const privateKeyBUF = Buffer.from(privateKey, 'hex');
    const contract = new this.web3.eth.Contract(
      { from: fromAccount }

    amount = this.web3.utils.toHex(this.web3.utils.toWei(amount));
    return from(this.web3.eth.getTransactionCount(fromAccount)).pipe(
      switchMap((count) => {
        const rawTransaction = {
          from: fromAccount,
          gasPrice: this.web3.utils.toHex(20 * 1e9),
          gasLimit: this.web3.utils.toHex(210000),
          to: [ContractAddress],
          value: 0x0,
          data: contract.methods.transfer(toAccount, amount).encodeABI(),
          nonce: this.web3.utils.toHex(count),

        const transaction = new Tx(rawTransaction, { chain: 'chain' });

        return from(
            '0x' + transaction.serialize().toString('hex')

      map((transaction) => {
        return transaction;

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.