Skip to content

Instantly share code, notes, and snippets.

@jc4p
Last active September 19, 2025 17:21
Show Gist options
  • Select an option

  • Save jc4p/1e747bb2958af05691583d34f499f408 to your computer and use it in GitHub Desktop.

Select an option

Save jc4p/1e747bb2958af05691583d34f499f408 to your computer and use it in GitHub Desktop.
import { generatePrivateKey, privateKeyToAccount, english, generateMnemonic, mnemonicToAccount } from 'viem/accounts';
import { writeFileSync } from 'fs';
// Parse command line arguments
const args = process.argv.slice(2);
let name = null;
let useMnemonic = false;
for (let i = 0; i < args.length; i++) {
if (args[i] === '--name' && args[i + 1]) {
name = args[i + 1];
} else if (args[i] === '--mnemonic') {
useMnemonic = true;
}
}
let privateKey;
let account;
let mnemonic;
if (useMnemonic) {
// Generate a mnemonic phrase
mnemonic = generateMnemonic(english);
// Get the account from the mnemonic
account = mnemonicToAccount(mnemonic);
// Extract the private key from the HD key
const hdKey = account.getHdKey();
privateKey = `0x${Buffer.from(hdKey.privKeyBytes).toString('hex')}`;
} else {
// Generate a random private key
privateKey = generatePrivateKey();
// Get the account (address) from the private key
account = privateKeyToAccount(privateKey);
}
// Save the private key and mnemonic to text files
const basename = name
? name
: new Date().toISOString().replace(/[:]/g, '-').split('.')[0];
const privateKeyFilename = `private-key-${basename}.txt`;
writeFileSync(privateKeyFilename, privateKey, 'utf8');
console.log(`Private key saved to: ${privateKeyFilename}`);
if (mnemonic) {
const mnemonicFilename = `mnemonic-${basename}.txt`;
writeFileSync(mnemonicFilename, mnemonic, 'utf8');
console.log(`Mnemonic saved to: ${mnemonicFilename}`);
}
console.log(`Address: ${account.address}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment