Web3js

RangeError: private key length is invalid (In New ETH Transaction 務實)

  • October 2, 2018

遵循這個 Ans Ans1Ans2但沒有得到解決方案。

const web3 = new Web3('https://ropsten.infura.io/v3/3c52917848e945229c0d33d632b10490');

const account1 = '0x0982081d5a2bba0a9da9fe722c92edc0cb0e9b6a'
const account2 = '0xabc46ddc17a0c37ef70e8a153d4724f199705e8b'

const ac1_pvtkey =Buffer.from('XXXX9F79B587B1DE553E2ADCA3DC8D49BE3E2840083D970C41D83F7FD471XXXX');

const ac2_pvtkey =Buffer.from('XXXXC15FBDB4634400B7F8FA17C9491B2E346AEC1BC86A493B18F5759042XXXX');

//在這裡建立事務————–

`web3.eth.getTransactionCount(account2, (err, txCount) => {
   const txObject = {
   nonce: web3.utils.toHex(txCount),
   to: account2,
   value: web3.utils.toHex(web3.utils.toWei('0.2','ether')),
   gaslimit: web3.utils.toHex(2100),
   gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei'))
   }

控制台.log(txObject)

//在這裡簽署交易————–

const tx = new Tx(txObject);
tx.sign(ac2_pvtkey); //using account2 private key

————————- 錯誤給予 ———————— -

var sig = secp256k1.sign(msgHash, privateKey);
                   ^
RangeError: private key length is invalid `

回答我的問題

//Admin's eth Address ------------
const account1 = process.env.ADMIN_ETH_ADDR;
//Admin's eth private key -----------------
const ac1_pvtkey = Buffer.from(process.env.ADMIN_ETH_PVT_KEY, 'hex');

實際交易創建 -> 簽署 tx -> 序列化 tx -> 獲取交易雜湊

var txnCount = web3.eth.getTransactionCount(account1);

     var txObject = {
         nonce: web3.toHex(txnCount),
         gasPrice: web3.toHex(100000000000),
         gasLimit: web3.toHex(140000),
         to: to, //to is ETH address-----
         value: web3.toHex(web3.toWei(amount,'ether')),//amount to be send----
         data: '0xcfa'
     };

     try{

         var transaction = new tx(txObject);
         transaction.sign(ac1_pvtkey);

         var serializedTx = transaction.serialize();

         console.log(serializedTx.toString('hex'));
         transactionId = web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'));

         console.log(transactionId);

     } catch (e) {
         return console.error(e);
         console.log("Error ETH Transaction ");
     }

希望這可以幫助。謝謝

不要與 ‘Ox’ 一起使用 刪除私鑰中的那些

引用自:https://ethereum.stackexchange.com/questions/56407