我正在尝试通过 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。然而,最终我想将交易广播到主网。你能给我任何想法吗?我想要任何反馈。另外,如果有任何使用分类账创建和广播原始交易的示例,请注意我。
最佳答案
您的代码已将交易发送到网络。然而,仅仅等待“发送” promise 只会给你交易哈希值,而不是收据。您需要将其视为事件发射器并等待“确认”事件。
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 Node 并使用不变的代码,或者将 web3 指向 infura或类似的。
关于javascript - 通过使用 ledger nano s,我想签署一笔交易并将其发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54070083/