Web3js: Create Wallet, Check Balance and Send Ethers

ยท

2 min read

Below are code snippets that work for creating wallet addresses, checking wallet balances, and sending ether to another wallet. My provider is infura, get your free account already.

npm package versions

"web3": "^1.3.6", "ethereumjs-tx": "^2.1.2"

Create Wallet Address

Below is an extraction of my code that works which I use in building my Dapp, basically I am managing the user's wallet credentials.

 const wssethProvider =
    "wss://rinkeby.infura.io/ws/v3/YOUR-API-KEY";
exports.createETHAddress = async (req, res, next) => {
  try {
    const { email, userId } = req.body;

    const web3 = new Web3(new Web3.providers.WebsocketProvider(wssethProvider));
    web3.setProvider(new Web3.providers.WebsocketProvider(wssethProvider));
    const account = web3.eth.accounts.wallet.create(1, `${email}${userId}`);
    const accountKeyStore = web3.eth.accounts.encrypt(
      account[0].privateKey,
      `SMART__07b7ee54020142cb8d7b2a6c963a0b4e`
    );

    res.json({
      status: "ok",
      account: account[0],
      accountKeyStore,
    });

  } catch (e) {
    next(User.checkDuplicateEmail(e));
  }

Check Balance

exports.getETHBalance = async (req, res, next) => {
  try {
    const { address } = req.params;
      const web3 = new Web3(
        new Web3.providers.WebsocketProvider(wssethProvider)
      );
      web3.setProvider(new Web3.providers.WebsocketProvider(wssethProvider));
      let balance = await web3.eth.getBalance(address);
      balance = web3.utils.fromWei(balance, "ether");
        res.json({
          status: "ok",
          balance: String(balance)
        });
  } catch (e) {
    next(User.checkDuplicateEmail(e));
  }
};

Transfer Ether

Using ethereumjs-tx to sing transactions, and web3 to broadcast the transaction to the network for verification and processing.

exports.transferEth = async (req, res, next) => {
  try {
  const web3 = new Web3(new Web3.providers.WebsocketProvider(wssethProvider));
    web3.setProvider(new Web3.providers.WebsocketProvider(wssethProvider));
    web3.eth.defaultAccount = req.body.from;

    const {
 amount, to, sendersPrivateKey, from
} = req.body;
     const privateKey = await Buffer.from(sendersPrivateKey.substr(2), 'hex');

     const myBalanceWei = await web3.eth.getBalance(web3.eth.defaultAccount);
      const myBalance = web3.utils.fromWei(myBalanceWei, 'ether');
      console.log(`Your wallet balance is currently ${myBalance}`);

      const nonce = await web3.eth.getTransactionCount(web3.eth.defaultAccount);
      console.log(`The outgoing transaction count for your wallet address is: ${nonce}`);

      const gasPrices = await getCurrentGasPrices();
      console.log(`The current gas price is ${gasPrices.low} ETH/GAS`);

  const details = {
    from,
    to,
    value: web3.utils.toHex(web3.utils.toWei(amount, 'ether')),
    gasLimit: 21000,
    gasPrice: gasPrices.low * 1000000000, // converts the gwei price to wei
    nonce,
    chainId: 4 // EIP 155 chainId - mainnet: 1, rinkeby: 4
  };


    const transaction = new EthereumTx.Transaction(details, { chain: 'rinkeby' });
  await transaction.sign(privateKey);

  const serializedTransaction = await transaction.serialize();
  const sd = String(`0x${serializedTransaction.toString('hex')}`);
  const transactionId = await web3.eth.sendSignedTransaction(sd);

    return res.send(transactionId);
  } catch (error) {
    return res.send('Failed to send transaction');
  }
};

Note that, all transactions are recorded on the rinkeby testnet, do well to switch to the main net url provided by infura which can be found on your dashboard.

Resources Used

Feel free to ask me questions about this code in the comments, cheers!!๐Ÿ˜Š