Skip to content

Instantly share code, notes, and snippets.

@neuhaus
Last active October 16, 2023 23:56
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save neuhaus/7387edf411513a9f11f1242dcec8d62e to your computer and use it in GitHub Desktop.
Save neuhaus/7387edf411513a9f11f1242dcec8d62e to your computer and use it in GitHub Desktop.
Ethereum: Sign an offline transaction with Node and web3
#!/usr/bin/env node
'use strict';
// ethereum: generate signed transactions
const fs = require('fs-extra');
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" +
"\tsign-offline.js filename recipient amount nonce gasprice\n\n" +
"\t\t amount is given in ether, gas price is given in gwei");
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 to %s amount %f eth nonce %d price %f",
filename, recipient, amount, nonce, gasprice);
let keystore = await fs.readJson(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 = 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();
@felix021
Copy link

felix021 commented Feb 8, 2018

thanks for your code, and here are some tiny improvements I think helpful:

let fs = require('fs')
...
let keystore = JSON.parse(fs.readFileSync(filename));
...
let data      = await accounts.signTransaction({

@alisonsilvabt
Copy link

Today web3-eth-accounts forces you to define a provider. Or do I have the wrong version?

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