principlejavascriptCritical
Wallet security: protecting private keys in Node.js scripts and CI/CD
Viewed 0 times
private key securityenv varsdotenvLedger hardhatkey managementsecrets
Problem
Private keys are frequently leaked in git repositories, CI logs, or hard-coded in deployment scripts, leading to fund theft.
Solution
Use environment variables loaded from .env files (with dotenv). Never commit .env files. Use hardware wallets (Ledger) via @nomicfoundation/hardhat-ledger for mainnet deployments. For CI, use secrets managers.
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider);Why
A leaked private key gives full, irrevocable access to all assets controlled by that key. There is no recovery mechanism once funds are stolen.
Gotchas
- process.env.PRIVATE_KEY must NOT include the 0x prefix when using it with some libraries
- GitHub's secret scanning will detect and alert on committed private keys, but the key is already compromised
- Rotate keys immediately if exposure is suspected — gas up a new wallet and transfer all assets
Code Snippets
Safe private key usage with dotenv
// .env (never commit this file)
// PRIVATE_KEY=0xabc123...
// Add .env to .gitignore!
import 'dotenv/config';
import { ethers } from 'ethers';
function getSigner(provider) {
const key = process.env.PRIVATE_KEY;
if (!key) throw new Error('PRIVATE_KEY env var not set');
if (!key.startsWith('0x')) throw new Error('PRIVATE_KEY must start with 0x');
return new ethers.Wallet(key, provider);
}
// In hardhat.config.ts:
// networks: { mainnet: { accounts: [process.env.PRIVATE_KEY!] } }Context
Setting up deployment scripts, CI/CD pipelines, or any Node.js script that signs transactions
Revisions (0)
No revisions yet.