Certainly! Here’s a 2024-updated guide to building a simple Bitcoin wallet service in NestJS that allows users to:
- Create a Bitcoin wallet (address + private key)
- Send Bitcoin
- View transaction history
We'll use the bitcoinjs-lib for wallet operations and Blockstream API (or similar) for blockchain data. For production, consider using a full node or a service like BlockCypher, but for simplicity, we'll use public APIs.
1. Install Dependencies
npm install @nestjs/common @nestjs/core @nestjs/platform-express rxjs
npm install bitcoinjs-lib axios
2. Create the Wallet Service
src/bitcoin/bitcoin.service.ts
import { Injectable } from '@nestjs/common';
import * as bitcoin from 'bitcoinjs-lib';
import axios from 'axios';
const NETWORK = bitcoin.networks.testnet; // Use testnet for development
@Injectable()
export class BitcoinService {
// 1. Create a new wallet (address + private key)
createWallet() {
const keyPair = bitcoin.ECPair.makeRandom({ network: NETWORK });
const { address } = bitcoin.payments.p2pkh({ pubkey: keyPair.publicKey, network: NETWORK });
const privateKey = keyPair.toWIF();
return { address, privateKey };
}
// 2. Get transaction history for an address
async getTransactions(address: string) {
// Using Blockstream API for testnet
const url = `https://blockstream.info/testnet/api/address/${address}/txs`;
const { data } = await axios.get(url);
return data;
}
// 3. Send Bitcoin (simplified, assumes single input, single output)
async sendBitcoin(fromWIF: string, toAddress: string, amountSats: number) {
const keyPair = bitcoin.ECPair.fromWIF(fromWIF, NETWORK);
const { address: fromAddress } = bitcoin.payments.p2pkh({ pubkey: keyPair.publicKey, network: NETWORK });
// 1. Fetch UTXOs
const utxosUrl = `https://blockstream.info/testnet/api/address/${fromAddress}/utxo`;
const { data: utxos } = await axios.get(utxosUrl);
if (!utxos.length) throw new Error('No UTXOs found');
// 2. Build transaction
const psbt = new bitcoin.Psbt({ network: NETWORK });
let inputSum = 0;
for (const utxo of utxos) {
psbt.addInput({
hash: utxo.txid,
index: utxo.vout,
nonWitnessUtxo: Buffer.from(
(await axios.get(`https://blockstream.info/testnet/api/tx/${utxo.txid}/hex`)).data,
'hex'
),
});
inputSum += utxo.value;
if (inputSum >= amountSats + 1000) break; // 1000 sats fee
}
if (inputSum < amountSats + 1000) throw new Error('Insufficient balance');
// 3. Add outputs
psbt.addOutput({ address: toAddress, value: amountSats });
// Change
if (inputSum > amountSats + 1000) {
psbt.addOutput({ address: fromAddress, value: inputSum - amountSats - 1000 });
}
// 4. Sign
psbt.signAllInputs(keyPair);
psbt.finalizeAllInputs();
// 5. Broadcast
const txHex = psbt.extractTransaction().toHex();
const { data: txid } = await axios.post(
'https://blockstream.info/testnet/api/tx',
txHex,
{ headers: { 'Content-Type': 'text/plain' } }
);
return { txid };
}
}
3. Create the Controller
src/bitcoin/bitcoin.controller.ts
import { Controller, Post, Body, Get, Query } from '@nestjs/common';
import { BitcoinService } from './bitcoin.service';
@Controller('bitcoin')
export class BitcoinController {
constructor(private readonly bitcoinService: BitcoinService) {}
@Post('create-wallet')
createWallet() {
return this.bitcoinService.createWallet();
}
@Get('transactions')
getTransactions(@Query('address') address: string) {
return this.bitcoinService.getTransactions(address);
}
@Post('send')
sendBitcoin(
@Body() body: { fromWIF: string; toAddress: string; amountSats: number }
) {
return this.bitcoinService.sendBitcoin(body.fromWIF, body.toAddress, body.amountSats);
}
}
4. Register the Module
src/bitcoin/bitcoin.module.ts
import { Module } from '@nestjs/common';
import { BitcoinService } from './bitcoin.service';
import { BitcoinController } from './bitcoin.controller';
@Module({
controllers: [BitcoinController],
providers: [BitcoinService],
})
export class BitcoinModule {}
src/app.module.ts
import { Module } from '@nestjs/common';
import { BitcoinModule } from './bitcoin/bitcoin.module';
@Module({
imports: [BitcoinModule],
})
export class AppModule {}
5. Run Your App
npm run start
6. Test Endpoints
- Create Wallet:
POST /bitcoin/create-wallet
- Send Bitcoin:
POST /bitcoin/send
Body: { "fromWIF": "...", "toAddress": "...", "amountSats": 10000 }
- View Transactions:
GET /bitcoin/transactions?address=...
Notes & Security
- Never expose private keys in production!
- For mainnet, change
NETWORK and API URLs.
- For real apps, use secure key storage, rate limiting, and error handling.
- For more advanced features (multi-input, multi-output, fee estimation), expand the logic.
Let me know if you need a full repo or more advanced features!