通过使用账本nanos,我想签署一笔交易并发送它



我正试图通过Node.JS向Ledger Nano S的用户发送发送ERC20代币的以太坊交易,但我无法成功签署和发送此交易。

首先,我通过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节点并保持代码不变,也可以在infura或类似位置指向web3。

最新更新