Skip to content

Instantly share code, notes, and snippets.

@felix021
Last active Feb 8, 2018
Embed
What would you like to do?
Ethereum: Sign Transactions Offline in NodeJS | 用NodeJS对以太坊交易离线签名
#!/usr/bin/env node
'use strict';
// ethereum: generate signed transactions
// source: https://gist.github.com/neuhaus/7387edf411513a9f11f1242dcec8d62e
const fs = require('fs');
const rls = require('readline-sync');
const Accounts = require('web3-eth-accounts');
const web3utils = require('web3-utils');
const accounts = new Accounts();
async function main() {
if (process.argv.length < 6) {
console.log("Usage:\n" +
" sign-offline.js <filename> <recipient> <amount> <nonce> <gasprice>\n" +
" ~ filename: keystore file of your account\n" +
" ~ amount: ether(s) you intend to send (*NOT* in wei)\n" +
" ~ recipient: address prefixed with '0x'\n" +
" ~ nonce: web3.eth.getTransactionCount(from_address) is suggested\n" +
" ~ gasprice: in Gwei, ethstats.net is recommended for reference\n"
);
process.exit(1);
}
let filename = process.argv[2];
let recipient = process.argv[3];
let amount = web3utils.toWei(process.argv[4], "ether");
let nonce = process.argv[5];
let gasprice = web3utils.toWei(process.argv[6], "gwei");
console.log("File %s\nTo %s\nAmount %f wei\nNonce %d\nPrice %f Gwei\n",
filename, recipient, amount, nonce, gasprice);
let keystore = JSON.parse(fs.readFileSync(filename));
if (!("crypto" in keystore)) {
// MEW creates capitalized "crypto" property
// web3 expects it in lowercase
keystore.crypto = keystore.Crypto;
delete keystore.Crypto;
}
let password = rls.question('keystore Password? ', { hideEchoBack: true });
let myaccount = accounts.decrypt(keystore, password);
let data = await accounts.signTransaction({
to: recipient,
value: amount,
gas: 21000,
gasPrice: gasprice,
nonce: nonce,
chainId: 1 // mainNet
}, myaccount.privateKey);
console.log("signed raw transaction: ", data.rawTransaction);
}
main();
@neuhaus
Copy link

neuhaus commented Feb 8, 2018

Nice!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment