Skip to content

blockradar/sample-integration-backend

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Web3 Afrika Pay Backend Service

A comprehensive NestJS backend service that demonstrates how to integrate Blockradar for managing user wallets and processing stablecoin deposits. This service provides user authentication, wallet management, and transaction handling across multiple blockchain networks.

πŸš€ Features

  • User Authentication: JWT-based authentication with signup and login
  • Multi-Blockchain Support: Support for 5 major blockchains (Base, BSC, Solana, Polygon, Tron)
  • Stablecoin Deposits: USDC and USDT support across compatible networks
  • Wallet Management: Automatic wallet creation for users across supported blockchains
  • Blockradar Integration: Seamless integration with Blockradar API for address generation
  • Database: PostgreSQL with TypeORM for data persistence
  • Security: Password hashing, JWT authentication, and secure wallet configurations

πŸ› οΈ Prerequisites

Before running this service, ensure you have:

  • Node.js (v16 or higher)
  • npm or yarn
  • PostgreSQL database
  • Blockradar API credentials (see below)

πŸ“‹ Supported Blockchains & Tokens

Blockchain Token Network Type
Base USDC EVM
BSC (Binance Smart Chain) USDT EVM
Solana USDC SOLANA
Polygon USDC EVM
Tron USDT TRON

πŸ”‘ Getting Blockradar API Keys

Blockradar offers two ways to authenticate: the traditional method with separate API keys per wallet, or the newer Master API Key approach for better maintainability.

Option 1: Master API Key (Recommended)

Blockradar now supports a Master API Key that allows you to manage all your wallets with a single API key, making it much easier to maintain and scale.

  1. Sign up at Blockradar
  2. Get your Master API Key from https://dashboard.blockradar.co/developers
  3. Create wallets for each blockchain you want to support in your dashboard
  4. Note the Wallet IDs for each wallet you create

Benefits of Master API Key:

  • Single API key for all operations
  • Easier maintenance and deployment
  • Better security management
  • Future-proof approach

Option 2: Individual API Keys (Legacy)

The traditional method requires separate API keys for each wallet:

  1. Create wallets for each blockchain you want to support:

    • Go to your dashboard
    • Navigate to "Wallets" section
    • Create a wallet for each supported blockchain (Base, BSC, Solana, Polygon, Tron)
    • For each wallet, you'll get:
      • WALLET_ID: The unique identifier for your wallet
      • WALLET_KEY: The API key for accessing that wallet
      • Asset IDs for specific tokens (USDC/USDT)
  2. Note the credentials for each wallet as you'll need them for environment configuration

⚠️ Migration Recommendation: It's strongly advised to migrate to the Master API Key approach for better maintainability and security.

βš™οΈ Environment Configuration

  1. Copy the example environment file:
cp env.example .env
  1. Choose one of the two configuration approaches:
# Database Configuration
DATABASE_HOST=localhost
DATABASE_PORT=5432
DATABASE_NAME=web3_afrika_pay
DATABASE_USERNAME=your_db_username
DATABASE_PASSWORD=your_db_password

# JWT Configuration
JWT_SECRET=your_super_secure_jwt_secret_key_here
JWT_EXPIRES_IN=24h

# Application Configuration
PORT=3000
NODE_ENV=development

### Configuration Option A: Master API Key (Recommended)

# Blockradar Master API Key Configuration (Recommended)
BLOCKRADAR_MASTER_API_KEY=your_master_api_key_from_dashboard
BLOCKRADAR_SOLANA_WALLET_ID=your_solana_wallet_id
BLOCKRADAR_BASE_WALLET_ID=your_base_wallet_id
BLOCKRADAR_BSC_WALLET_ID=your_bsc_wallet_id
BLOCKRADAR_POLYGON_WALLET_ID=your_polygon_wallet_id
BLOCKRADAR_TRON_WALLET_ID=your_tron_wallet_id

# Asset IDs (optional - can be discovered via API)
BLOCKRADAR_SOLANA_USDC_ASSET_ID=your_solana_usdc_asset_id
BLOCKRADAR_BASE_USDC_ASSET_ID=your_base_usdc_asset_id
BLOCKRADAR_BSC_USDT_ASSET_ID=your_bsc_usdt_asset_id
BLOCKRADAR_POLYGON_USDC_ASSET_ID=your_polygon_usdc_asset_id
BLOCKRADAR_TRON_USDT_ASSET_ID=your_tron_usdt_asset_id

Configuration Option B: Individual API Keys (Legacy)

Blockradar Individual API Keys Configuration (Legacy)

Solana Configuration

BLOCKRADAR_SOLANA_WALLET_ID=your_solana_wallet_id BLOCKRADAR_SOLANA_WALLET_KEY=your_solana_wallet_key BLOCKRADAR_SOLANA_USDC_ASSET_ID=your_solana_usdc_asset_id

Base Configuration

BLOCKRADAR_BASE_WALLET_ID=your_base_wallet_id BLOCKRADAR_BASE_WALLET_KEY=your_base_wallet_key BLOCKRADAR_BASE_USDC_ASSET_ID=your_base_usdc_asset_id

BSC Configuration

BLOCKRADAR_BSC_WALLET_ID=your_bsc_wallet_id BLOCKRADAR_BSC_WALLET_KEY=your_bsc_wallet_key BLOCKRADAR_BSC_USDT_ASSET_ID=your_bsc_usdt_asset_id

Polygon Configuration

BLOCKRADAR_POLYGON_WALLET_ID=your_polygon_wallet_id BLOCKRADAR_POLYGON_WALLET_KEY=your_polygon_wallet_key BLOCKRADAR_POLYGON_USDT_ASSET_ID=your_polygon_usdt_asset_id

Tron Configuration

BLOCKRADAR_TRON_WALLET_ID=your_tron_wallet_id BLOCKRADAR_TRON_WALLET_KEY=your_tron_wallet_key BLOCKRADAR_TRON_USDT_ASSET_ID=your_tron_usdt_asset_id


**Important Notes:**

- **Master API Key**: Only requires `BLOCKRADAR_MASTER_API_KEY` and wallet IDs, making it much simpler to manage
- **Individual Keys**: Each blockchain requires its own wallet ID and key from Blockradar (legacy approach)
- **Asset IDs**: Can be optional if using Master API Key, as they can be discovered via API calls
- Make sure to get the correct asset IDs for USDC/USDT on each network if not using Master API Key
- Keep your JWT secret secure and randomly generated
- Database synchronization is enabled in development mode only

## πŸ”§ Blockradar Configuration Setup

After setting up your environment variables, you need to update the `src/config/blockradar.ts` file to support the Master API Key approach.

### For Master API Key (Recommended)

If using the Master API Key approach, update your `src/config/blockradar.ts` file to use the master key for all wallet operations:

```typescript
import { env } from 'src/utils/env.config';
import { BlockchainSlug, AssetSlug } from 'src/wallets/types';

export const supportedWallets = {
  [BlockchainSlug.BASE]: {
    id: env.BLOCKRADAR_BASE_WALLET_ID,
    key: env.BLOCKRADAR_MASTER_API_KEY, // Use master key
    asset: {
      [AssetSlug.USDC]: {
        id: env.BLOCKRADAR_BASE_USDC_ASSET_ID,
      },
    },
  },
  [BlockchainSlug.BSC]: {
    id: env.BLOCKRADAR_BSC_WALLET_ID,
    key: env.BLOCKRADAR_MASTER_API_KEY, // Use master key
    asset: {
      [AssetSlug.USDT]: {
        id: env.BLOCKRADAR_BSC_USDT_ASSET_ID,
      },
    },
  },
  [BlockchainSlug.SOLANA]: {
    id: env.BLOCKRADAR_SOLANA_WALLET_ID,
    key: env.BLOCKRADAR_MASTER_API_KEY, // Use master key
    asset: {
      [AssetSlug.USDC]: {
        id: env.BLOCKRADAR_SOLANA_USDC_ASSET_ID,
      },
    },
  },
  [BlockchainSlug.POLYGON]: {
    id: env.BLOCKRADAR_POLYGON_WALLET_ID,
    key: env.BLOCKRADAR_MASTER_API_KEY, // Use master key
    asset: {
      [AssetSlug.USDC]: {
        id: env.BLOCKRADAR_POLYGON_USDC_ASSET_ID,
      },
    },
  },
  [BlockchainSlug.TRON]: {
    id: env.BLOCKRADAR_TRON_WALLET_ID,
    key: env.BLOCKRADAR_MASTER_API_KEY, // Use master key
    asset: {
      [AssetSlug.USDT]: {
        id: env.BLOCKRADAR_TRON_USDT_ASSET_ID,
      },
    },
  },
};

For Individual API Keys (Legacy)

If using the traditional individual API keys approach, your current src/config/blockradar.ts configuration will work as-is, using the separate keys for each wallet.

Migration Guide: From Individual Keys to Master API Key

To migrate from individual API keys to the Master API Key:

  1. Get your Master API Key from https://dashboard.blockradar.co/developers
  2. Update your .env file:
    • Add: BLOCKRADAR_MASTER_API_KEY=your_master_api_key_here
    • Keep your wallet IDs but remove the individual wallet keys
  3. Update src/config/blockradar.ts:
    • Replace all individual key: env.BLOCKRADAR_*_WALLET_KEY entries with key: env.BLOCKRADAR_MASTER_API_KEY
  4. Test your integration to ensure all wallet operations work correctly
  5. Remove old environment variables from your .env file

This migration will significantly simplify your configuration management!

πŸ—„οΈ Database Setup

  1. Create a PostgreSQL database:
CREATE DATABASE web3_afrika_pay;
  1. The application will automatically create tables when you start it (in development mode).

Database Schema

The service uses three main entities:

Users

  • id (UUID, Primary Key)
  • name (VARCHAR)
  • email (VARCHAR, Unique)
  • password (VARCHAR, Hashed)
  • createdAt (TIMESTAMP)
  • updatedAt (TIMESTAMP)

Wallets

  • id (UUID, Primary Key)
  • userId (UUID, Foreign Key)
  • address (VARCHAR, Blockchain address)
  • type (ENUM: EVM, SOLANA, TRON)
  • createdAt (TIMESTAMP)
  • updatedAt (TIMESTAMP)

Transactions

  • id (UUID, Primary Key)
  • userId (UUID, Foreign Key)
  • walletId (UUID, Foreign Key)
  • amount (VARCHAR)
  • type (VARCHAR)

πŸš€ Installation & Setup

  1. Install dependencies:
yarn install
  1. Start the application in development mode:
yarn start:dev
  1. For production:
yarn build
yarn start:prod

The API will be available at http://localhost:3000 (or your configured PORT).

πŸ“š API Documentation

Base URL

http://localhost:3000

Authentication

All protected endpoints require a JWT token in the Authorization header:

Authorization: Bearer <your_jwt_token>

1. Health Check

GET /

Returns a simple welcome message to verify the service is running.

Response:

{
  "message": "Welcome to Web3 Afrika Pay Backend Service!"
}

2. User Registration

POST /auth/signup

Creates a new user account and automatically generates wallets for supported blockchains.

Request Body:

{
  "name": "John Doe",
  "email": "john.doe@example.com",
  "password": "securepassword123"
}

Validation Rules:

  • name: String, 2-255 characters
  • email: Valid email format
  • password: String, 6-255 characters

Response (201 Created):

{
  "user": {
    "id": "uuid-here",
    "name": "John Doe",
    "email": "john.doe@example.com"
  },
  "token": "jwt_token_here"
}

Error Responses:

  • 409 Conflict: User with this email already exists
  • 400 Bad Request: Validation failed

3. User Login

POST /auth/login

Authenticates a user and returns a JWT token.

Request Body:

{
  "email": "john.doe@example.com",
  "password": "securepassword123"
}

Response (200 OK):

{
  "user": {
    "id": "uuid-here",
    "name": "John Doe",
    "email": "john.doe@example.com"
  },
  "token": "jwt_token_here"
}

Error Responses:

  • 401 Unauthorized: Invalid credentials
  • 400 Bad Request: Validation failed

4. Initiate Deposit

POST /transactions/initiate-deposit

Generates or retrieves a wallet address for a specific blockchain to receive deposits.

Headers:

Authorization: Bearer <jwt_token>

Request Body:

{
  "blockchain": "SOLANA",
  "token": "USDC"
}

Blockchain Options:

  • BASE (USDC)
  • BSC (USDT)
  • SOLANA (USDC)
  • POLYGON (USDC)
  • TRON (USDT)

Token Options:

  • USDC (for Base, Solana, Polygon)
  • USDT (for BSC, Tron)

Response (201 Created):

{
  "address": "wallet_address_here"
}

Error Responses:

  • 401 Unauthorized: Invalid or missing JWT token
  • 404 Not Found: User not found
  • 400 Bad Request: Invalid blockchain or token combination

5. Webhook Endpoint

POST /transactions/webhook

Endpoint for receiving webhooks from Blockradar. Currently returns a placeholder response.

Note: This endpoint is not yet implemented and serves as a placeholder for future webhook integration.

Response (200 OK):

{
  "statusCode": 200
}

πŸ”§ Development Scripts

# Development
yarn start:dev          # Start with hot reload
yarn start:debug        # Start with debugger

# Production
yarn build             # Build the application
yarn start:prod        # Start production build

# Testing
yarn test              # Run unit tests
yarn test:e2e          # Run end-to-end tests
yarn test:cov          # Run tests with coverage

# Code Quality
yarn lint              # Run ESLint
yarn format            # Format code with Prettier

πŸ—οΈ Architecture Overview

Core Modules

  1. Auth Module: Handles user registration, login, and JWT authentication
  2. Transactions Module: Manages deposit initiation and wallet address generation
  3. Blockradar Module: Integrates with Blockradar API for wallet operations
  4. Users Module: User entity and related operations
  5. Wallets Module: Wallet entity and blockchain-specific configurations

Key Services

  • AuthService: User authentication and registration
  • TransactionsService: Deposit processing and wallet management
  • BlockradarService: Communication with Blockradar API

Security Features

  • Password hashing with bcryptjs
  • JWT token-based authentication
  • Request validation with class-validator
  • CORS enabled
  • SQL injection protection via TypeORM

🚨 Important Notes

  1. Wallet Creation: When a user signs up, the system automatically creates wallets for SOLANA, BASE, and TRON blockchains. While the configuration supports 5 blockchains (Base, BSC, Solana, Polygon, Tron), only 3 wallets are created because Base is EVM-compatible and can be used for other EVM chains like BSC and Polygon.

  2. Environment Variables: Never commit your .env file to version control. Use the provided env.example as a template.

  3. API Keys: Keep your Blockradar API keys secure and never expose them in client-side code.

  4. Master API Key Migration: It's strongly recommended to use the Master API Key approach for easier management. You can get your Master API Key from https://dashboard.blockradar.co/developers.

  5. Database: In development, TypeORM will automatically synchronize your database schema. Be cautious in production environments.

  6. Webhook Implementation: The webhook endpoint is currently a placeholder. You'll need to implement the actual webhook handling logic based on Blockradar's webhook specifications.

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Submit a pull request

Note

This repo was created during a live workshop to explain the easy integration of Blockradar in building a multichain stablecoin powered app in minutes, you can watch the live session here https://www.youtube.com/live/CijO5pMsLms?si=GUdLneUOmvfWFKQ3

πŸ“ License

This project is licensed under the UNLICENSED license.

πŸ†˜ Support

For issues related to:

  • Blockradar API: Contact Blockradar support

πŸ”„ Future Enhancements

  • Implement webhook handling for transaction notifications
  • Add withdrawal functionality
  • Implement transaction history
  • Add balance checking
  • Support for additional blockchains
  • Enhanced error handling and logging

About

This repo was created to demonstrate the easy integration of Blockradar on a live workshop, what the full session here https://www.youtube.com/live/CijO5pMsLms?si=GUdLneUOmvfWFKQ3

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published