Skip to content

Instantly share code, notes, and snippets.

@bayramlcm
Created June 14, 2024 08:09
Show Gist options
  • Save bayramlcm/334b014ef5607cb787113ae94397b95b to your computer and use it in GitHub Desktop.
Save bayramlcm/334b014ef5607cb787113ae94397b95b to your computer and use it in GitHub Desktop.
Ethereum Wallet Utilities with ethers
const { ethers } = require("ethers");
// Function to create a random wallet
async function createRandomWallet() {
const wallet = ethers.Wallet.createRandom();
const address = wallet.address;
const privateKey = wallet.privateKey;
const mnemonic = wallet.mnemonic.phrase;
console.log(`Address: ${address}`);
console.log(`Private Key: ${privateKey}`);
console.log(`Mnemonic: ${mnemonic}`);
}
// Function to log in to a wallet using a private key
function loginWallet(privateKey) {
const wallet = new ethers.Wallet(privateKey);
const address = wallet.address;
console.log(`Address: ${address}`);
}
// Function to send a transaction
async function sendTransaction(privateKey, recipient, amount, rpcURL) {
const provider = new ethers.JsonRpcProvider(rpcURL);
const wallet = new ethers.Wallet(privateKey, provider);
const tx = {
to: recipient,
value: ethers.parseEther(amount)
};
const transaction = await wallet.sendTransaction(tx);
await transaction.wait();
console.log(`Transaction hash: ${transaction.hash}`);
console.log(`Transaction details: ${JSON.stringify(transaction)}`);
}
// Function to check the balance of an address
async function getBalance(address, rpcURL) {
const provider = new ethers.JsonRpcProvider(rpcURL);
const balance = await provider.getBalance(address);
console.log(`Balance: ${ethers.formatEther(balance)} ETH`);
}
// Function to check the balance on the mainnet
async function getBalanceMainnet(address) {
const provider = ethers.getDefaultProvider('mainnet');
const balance = await provider.getBalance(address);
console.log(`Balance: ${ethers.formatEther(balance)} ETH`);
}
// Example usage
const publicAddress = "0xE7A13A089b36C600EeB6Ef070C79216ACB450399";
const privateAddress = "0xe2725ced5b2174eb13e78b8a8991c53777809a11bd2fb2f4c1d084eef29ba5eb";
const mnemonic = "urge swarm bless endless kit smile action aspect play wonder collect glad";
// Create a new random wallet and show its details
createRandomWallet();
// Log in to a wallet using a private key and show the address
loginWallet(privateAddress);
// Send a transaction with the specified private key, recipient address, and amount
sendTransaction(privateAddress, "0x4cE41b3D7d4974eF2bfa15bb42D8c8E98bBa49ab", "0.1", "http://127.0.0.1:7545");
// Check and show the balance of the specified address on the local network (ganache)
getBalance(publicAddress, "http://127.0.0.1:7545");
// Check and show the balance of the specified address on the mainnet
getBalanceMainnet("0x882e747c5c2e0366d4fd6f9f95780467c6549732");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment