繁体   English   中英

通过使用分类帐nano,我想签署交易并发送

[英]By using ledger nano s, I wanna sign a transaction and send it

我正在尝试发送以太坊交易,该交易通过Node.JS将ERC20令牌发送给具有Ledger Nano S的用户,但无法成功签名并发送该交易。

首先,我通过ledgerhq API的signTransaction方法对交易进行了签名,然后在对它进行签名之后,使用sendSignedTransaction将其发送到主网络。 当我执行以下代码时,Ledger接收请求并显示交易详细信息。 但是,按下Ledger的确认按钮后,控制台将返回错误“返回的错误:无效的签名:加密错误(无效的EC签名)”。

 import AppEth from "@ledgerhq/hw-app-eth"; import TransportU2F from "@ledgerhq/hw-transport-u2f"; import TransportNodeHid from "@ledgerhq/hw-transport-node-hid"; import EthereumTx from "ethereumjs-tx" const Web3 = require('web3'); import { addHexPrefix, bufferToHex, toBuffer } from 'ethereumjs-util'; const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545')); var destAddresses = ['0xa6acFa18468786473269Dc1521fd4ff40F6481D9']; var amount = 1000000000000; var i=0; var contract = new web3.eth.Contract([token contract ABI... ], '0x74a...'); const data1 = contract.methods.transfer(destAddresses[0], amount).encodeABI(); const exParams = { gasLimit: 6e6, gasPrice: 3e9, from: '0x1A...', data : data1, to: '0x74a...', value: '0x00', nonce: "0x0", chainId: 1, v: "0x01", r: "0x00", s: "0x00" } async function makeSign(txParams) { const tx = new EthereumTx(txParams); const txHex = tx.serialize().toString("hex"); const signedTransaction = '0x' + txHex; let transport; try { transport = await TransportNodeHid.create(); let eth2 = new AppEth(transport); const result = await eth2.signTransaction("m/44'/60'/0'/0", txHex).then(result => { web3.eth.sendSignedTransaction('0x' + txHex) .then(res => { console.log(res); }).catch(err => { console.log('sendSignedTransaction'); console.log(err); }); }).catch(err => { console.log('signTransaction'); console.log(err); }); txParams.r = `0x${result.r, 'hex'}`; txParams.s = `0x${result.s, 'hex'}`; txParams.v = `0x${result.v, 'hex'}`; return result; } catch (e) { console.log(e); } } makeSign(exParams).then(function () { console.log("Promise Resolved2"); }.catch(function () { console.log("Promise Rejected2"); }); 

当我仅使用signTransaction函数时,可以在分类帐设备中确认交易,并在控制台上返回txhash。 但是,最终我想将交易广播到主网。 你能给我个主意吗? 我需要任何反馈。 另外,如果有使用分类帐创建和广播原始交易的示例,请通知我。

您的代码已将交易发送到网络。 但是,仅等待“发送”承诺只会给您交易哈希,而不是收据。 您需要将其视为事件发射器,然后等待“确认”事件。

  const serializedTx = tx.serialize();
  web3.eth.sendSignedTransaction(serializedTx.toString('hex'))
    .once('transactionHash', hash => console.log('Tx hash', hash))
    .on('confirmation', (confNumber, receipt) => {
      console.log(`Confirmation #${confNumber}`, receipt);
    })
    .on('error', console.error);

要将其发送到主网,您可以在端口8545上运行本地geth节点并使用您的代码,也可以将web3指向infura或类似名称。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM