Building a Simple Web Wallet with Express and Web3.js

ยท

Project Setup

1. Environment Configuration

Install essential Ethereum development tools with these commands:

curl -s https://raw.githubusercontent.com/oscm/shell/master/lang/gcc/gcc.sh | bash
curl -s https://raw.githubusercontent.com/oscm/shell/master/lang/golang/golang-1.10.2.sh | bash
curl -s https://raw.githubusercontent.com/oscm/shell/master/blockchain/ethereum/centos/go-ethereum-1.8.8.sh | bash
curl -s https://raw.githubusercontent.com/oscm/shell/master/blockchain/ethereum/systemd/private.sh | bash
curl -s https://raw.githubusercontent.com/oscm/shell/master/lang/node.js/binrary/node-v10.1.0.sh | bash
curl -s https://raw.githubusercontent.com/oscm/shell/master/lang/node.js/binrary/profile.d.sh | bash
curl -s https://raw.githubusercontent.com/oscm/shell/master/blockchain/ethereum/truffle/truffle.sh | bash

2. Package Installation

Set up your Node.js project with required dependencies:

npm install express web3 ejs

Core Implementation

Main Application (main.js)

const express = require('express');
const app = express();
const Web3 = require('web3');
const fs = require('fs');
const net = require('net');

// Configuration
const web3 = new Web3('/home/ethereum/.ethereum/geth.ipc', net);
const abi = JSON.parse(fs.readFileSync(__dirname + '/abi/NKC.abi', 'utf-8'));
const contractAddress = "0x5F75DA091aBb25e055B91172C04371Ff4Dd563a0";
const coinbase = "0xaa96686a050e4916afbe9f6d62fa646dd8c51070";

// Routes
app.get('/', (req, res) => res.render("index"));
app.get('/account', (req, res) => {
  web3.eth.getAccounts().then(accounts => 
    res.render("account", { accounts })
  );
});

// Additional route handlers for balance checking, transfers, etc...

๐Ÿ‘‰ Learn more about Web3.js integration

Smart Contract Interface

ABI Configuration (abi/NKC.abi)

[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},...]

Frontend Views

Account Management (account.ejs)

<% accounts.forEach(function(account, index){ %>
  <div><%= index %>: <%= account %></div>
<% }) %>

<form action="/new">
  <input type="password" name="password">
  <button>Create Account</button>
</form>

Balance Display (showbalance.ejs)

<div>
  Account: <%= account %>, Balance: <%= balance %> ETH
</div>
<div>
  Token Balance: <%= token %> <%= name %>
</div>

Launching the Application

node main.js

Access your wallet at http://localhost:8080

FAQ Section

Q1: What security measures should I implement?

Always:

Q2: How do I connect to different networks?

Modify the Web3 provider initialization:

// For Infura:
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_KEY');

Q3: Can I deploy this to production?

Yes, but ensure you:

  1. Add proper error handling
  2. Implement rate limiting
  3. Set up monitoring
  4. Use environment variables for sensitive data

๐Ÿ‘‰ Explore advanced wallet security practices