web3.js运行交易操作文件出现:Error: Expected private key to be an Uint8Array with length 32错误

源码

//app.js文件内容
const reselt = require('dotenv').config(); // 默认读取项目根目录下的.env文件,用process.env.调用
// 1.导入ethereumjs-tx库
var Tx = require('ethereumjs-tx').Transaction;
// 2.建立Web3连接
const Web3 = require('web3');
const web3 = new Web3('https://ropsten.infura.io/v3/your infura api');

// 一、准备账户

// 1.声明账户变量
const account1 = 'your account1 address'
const account2 = 'your account2 address'
// 2.读取并存储私钥环境变量
const pk1 = process.env.PRIVATE_KEY_1
const pk2 = process.env.PRIVATE_KEY_2
// 3.使用私钥对交易进行签名
const privateKey1 = Buffer.from(pk1, 'hex')
const privateKey2 = Buffer.from(pk2, 'hex')
// 4.构建交易对象
// web3.eth.getTranctionCount() 获取交易的nounce
web3.eth.getTransactionCount(account1, (err, txCount) => {
    
    
  // 注意 该交易对象没有 from 字段,当使用account1的私钥签署这个交易时,它将被推算出来
  const txObject = {
    
    
    // nounce 账号的前一个交易计数,必须先使用web3.utils.toHex()将值转换成十六进制
    nonce: web3.utils.toHex(txCount),
    // to 目标账户
    to: account2,
    // value 要发送的以太币金额,值必须是十六进制,且单位必须是wei,所以需要用we3.utils.toWei()转换单位
    value: web3.utils.toHex(web3.utils.toWei('0.1', 'ether')),
    // gasLimit 交易能消耗Gas的上限
    gasLimit: web3.utils.toHex(21000),
    // gasPrice Gas价格,这里是 10 GWei
    gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei'))
  }
  // 5.签署交易
  const tx = new Tx(txObject, {
    
    
    chain: 'ropsten',
    hardfork: 'petersburg'
  })
  tx.sign(privateKey1)
  const serializedTx = tx.serialize()
  const raw = '0x' + serializedTx.toString('hex')
  // 6.广播交易
  // web3.eth.senSignedTransaction() 将已签名的序列化交易发送到测试网络
  web3.eth.sendSignedTransaction(raw, (err, txHash) => {
    
    
    console.log('txHash:', txHash)
    // 可以去ropsten.etherscan.io查看交易详情
  })
})


错误原因

私钥的长度>32,一般私钥都是由0x开头+一串字母和数字混合组成,这里在声明raw变量时,把privateKey1转换成字符串的形式之后在开头加上了‘0x’,和我在.env文件定义的私钥冲突了,所以导致长度超出32引起错误

解决办法

只能打开.env文件将私钥开头的0x删掉,删除raw的没用。

Guess you like

Origin blog.csdn.net/weixin_46353030/article/details/121123386