0% found this document useful (0 votes)
6 views

Wallet Feature Technical Documentation

The wallet feature provides a secure financial transaction system for users to manage virtual accounts, transfer money, and track transactions, integrated with VFD Bank's API. Key components include WalletService, API endpoints for various wallet operations, and functionalities such as escrow management and beneficiary handling. The system also incorporates security measures like KYC validation, transaction PINs, and comprehensive error handling to ensure data integrity.

Uploaded by

Muwaffaq Aliyu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Wallet Feature Technical Documentation

The wallet feature provides a secure financial transaction system for users to manage virtual accounts, transfer money, and track transactions, integrated with VFD Bank's API. Key components include WalletService, API endpoints for various wallet operations, and functionalities such as escrow management and beneficiary handling. The system also incorporates security measures like KYC validation, transaction PINs, and comprehensive error handling to ensure data integrity.

Uploaded by

Muwaffaq Aliyu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Wallet Feature Technical Documentation

Overview
The wallet feature provides a comprehensive financial transaction system that enables users to
create virtual accounts, manage funds, transfer money, and track transaction history. This
system is integrated with a third-party banking API (VFD Bank) to provide real financial
transactions while maintaining a secure, managed environment within the application.

This document outlines the technical implementation details of the wallet system, including
architecture, core components, API endpoints, and integration points.

Key Components
WalletService

The primary service that handles all wallet-related operations. It interacts with the database
through PrismaService and with the banking API through walletApi.

Dependencies

●​ PrismaService: Database ORM for interacting with the database


●​ KycService: Service for validating transactions based on KYC requirements
●​ walletApi: Axios instance configured for the banking API
●​ Bcrypt: For transaction PIN verification
●​ Crypto: For generating secure signatures
●​ UUID: For generating unique identifiers

Architecture
The wallet system consists of the following components:

1.​ WalletService: Core service handling all wallet operations


2.​ WalletController: RESTful API endpoints for wallet operations
3.​ Database Models: Prisma schema definitions for wallet-related entities
4.​ DTO Objects: Data transfer objects for API requests and responses
5.​ Integration Layer: Connection to the VFD Bank API

API Endpoints
Metho Endpoint Description Authenticatio
d n

POST /wallet/virtual-acc Create a virtual account Required


ount

GET /wallet/account Get account details Required

GET /wallet/beneficiary Get beneficiary details Required

GET /wallet/banks Get list of all banks Required

POST /wallet/transfer Initiate a transfer Required

POST /wallet/escrow/hold Move amount to escrow Required

POST /wallet/escrow/rele Release amount from escrow Required


ase

GET /wallet/balance Get wallet balance Required

GET /wallet/transaction Get transaction history Required


s

POST /wallet/wallet-to-w Transfer funds to another wallet Required


allet

POST /wallet/save/benefi Add a new beneficiary Required


ciary

GET /wallet/save/benefi Get list of saved beneficiaries Required


ciary

DELE /wallet/beneficiary Remove a beneficiary Required


TE /:id

POST /wallet/test/credit Simulate credit (Test Only) Required

GET /wallet/test/accoun Get test account details (Test Only) Required


ts

Core Functionality
1. Virtual Account Management

Creating Virtual Accounts


typescript

async createVirtualAccount(user: AuthUser, amount: number)

●​ Creates a temporary virtual bank account for receiving funds


●​ Account validity: 40 hours (2400 minutes)
●​ Amount validation: Equal or less than specified amount
●​ Stores account information in the user's wallet

Getting Account Details


typescript

async getAccountDetails(accountNumber?: string)

●​ Retrieves detailed information about an account from the banking API

2. Wallet Operations

Balance Management
typescript

async getWalletBalance(userId: bigint)

●​ Retrieves a user's wallet balance, escrow amount, and account details

Transaction History
typescript

async getTransactionHistory(userId: bigint)

●​ Retrieves a paginated list of a user's transaction history

3. Money Transfer Functionality

Transfer Between Wallets


typescript

async transferToWallet(userId: number, dto: WalletTransferDto)

●​ Transfers money between user wallets within the platform


●​ Requires transaction PIN verification
●​ Creates corresponding transaction records for both sender and recipient
●​ Implements atomic transactions using Prisma's transaction feature

External Bank Transfers


typescript

async processTransfer(transferData: any, user: AuthUser)

●​ Facilitates transfers to external bank accounts


●​ Generates secure signatures for transfers
●​ Validates transaction via KYC service before processing
●​ Updates wallet balance upon successful transfer

Direct (Non-Escrow) Transfers


typescript

async directTransfer(fromUserId: number, toUserId: number, amount:


number, escrow?: any)

●​ Performs direct wallet-to-wallet transfers without escrow protection


●​ Updates both sender and recipient wallets atomically
●​ Creates debit/credit transaction records

4. Escrow System

Move to Escrow
typescript

async moveToEscrow(userId: number, amount: number, sellerId: number)

●​ Moves funds from buyer's wallet to seller's escrow account


●​ Ensures buyer has sufficient balance
●​ Creates transaction record

Release from Escrow


typescript

async releaseFromEscrow(buyerId: number, sellerId: number, amount:


number, escrow: any)

●​ Releases funds from escrow to the seller's wallet


●​ Handles edge cases to prevent negative escrow amounts

Service Charge and Fees

●​ For escrow transactions: 3% service charge


●​ For non-escrow transactions: 1.5% service charge

5. Beneficiary Management

Adding Beneficiaries
typescript

async addBeneficiary(userId: number, dto: CreateBeneficiaryDto)

●​ Adds another user as a beneficiary for easier transfers


●​ Prevents adding self as beneficiary
●​ Returns beneficiary details including wallet information

Retrieving Beneficiaries
typescript

async getBeneficiaries(userId: number, query:


GetBeneficiariesQueryDto)

●​ Returns paginated list of user's beneficiaries


●​ Supports searching by name or username
●​ Includes detailed beneficiary information

Removing Beneficiaries
typescript

async removeBeneficiary(userId: number, beneficiaryId: number)

●​ Removes a beneficiary from the user's list

6. Referral System

Processing Referral Bonuses


typescript

async processReferralBonus(userId: number, transactionAmount: number,


serviceCharge: number, transactionId: string)

●​ Awards bonuses to referrers (5% of service charge)


●​ Creates referral bonus records
●​ Credits referrer's wallet

Referral Flow

1.​ Referral Code Generation: Unique 8-character codes for users


2.​ User Sign-Up with Referral: New users enter code during registration
3.​ Transaction Processing: When a referred user completes a transaction:
○​ System calculates the service charge (3% for escrow, 1.5% for non-escrow)
○​ 5% of the service charge is awarded as a referral bonus
○​ The bonus is credited directly to the referrer's wallet
○​ A record is created in the user_referral_bonus table

Bonus Calculation Example

●​ Transaction amount: ₦100,000


●​ Escrow service charge: ₦3,000 (3%)
●​ Referral bonus: ₦150 (5% of ₦3,000)

7. Transaction Logging

Creating Transaction Logs


typescript

async createTransactionLog(data: CreateTransactionLogDto)

●​ Creates detailed logs for all transactions


●​ Sets expiration date for logs (1 month)

Log Cleanup
typescript

async cleanupExpiredLogs()

●​ Deletes expired transaction logs


●​ Can be run as a scheduled job

8. Test Features (Development Environment)

Simulating Credits
typescript

async simulateCredit(accountNo: string, amount: number, narration?:


string)

●​ Simulates receiving money in a wallet (testing only)


●​ Updates wallet balance
●​ Creates corresponding transaction records

Test Account Management


typescript
async getTestAccountDetails(type: 'inter' | 'intra')

●​ Provides test account details for development/testing


●​ Determines if an account is a test account

Data Models
Wallet

●​ id: Unique identifier


●​ user_id: Associated user ID
●​ balance: Current balance
●​ escrowAmount: Amount held in escrow
●​ merchantName: Display name
●​ merchantId: Unique merchant ID
●​ reference: Reference for the wallet
●​ accountNumber: Virtual account number
●​ accountExpiresAt: Expiration time for the virtual account

Wallet Transaction

●​ id: Unique identifier (UUID)


●​ user_id: Associated user ID
●​ walletId: Associated wallet ID
●​ sessionId: Unique session identifier
●​ transactionType: Type of transaction (credit/debit/transfer/escrow)
●​ amount: Transaction amount
●​ reference: Unique reference
●​ fromAccountName: Source account name
●​ accountNumber: Account number (if applicable)
●​ action: Transaction action (default/topup/withdrawal)
●​ toAccount: Destination account (if applicable)
●​ toBank: Destination bank (if applicable)
●​ txnId: External transaction ID (if applicable)

Wallet Beneficiary

●​ id: Unique identifier


●​ user_id: Owner user ID
●​ wallet_id: Beneficiary wallet ID
●​ alias: Custom name for the beneficiary
●​ created_at: Creation timestamp
●​ updated_at: Last update timestamp
Transaction Log

●​ transaction_type: Type of transaction


●​ status: Transaction status
●​ amount: Transaction amount
●​ currency: Currency used
●​ from_user_id: Sender user ID
●​ to_user_id: Recipient user ID (if applicable)
●​ reference: Transaction reference
●​ metadata: Additional transaction data
●​ expires_at: Log expiration date

User (Referral Fields)

●​ referral_code: Unique referral code (String, max 10 chars)


●​ referred_by: ID of the user who referred this user
●​ referrals: List of users referred by this user

User Referral Bonus

●​ id: Unique identifier


●​ referrer: User ID of the referrer
●​ referee: User ID of the referred user
●​ transaction_id: Associated transaction ID
●​ transaction_type: Type of transaction (ESCROW, WALLET_TRANSFER, etc.)
●​ service_charge: Service charge amount
●​ bonus_amount: Bonus amount awarded
●​ status: Status of the bonus (default: "completed")
●​ created_at: Creation timestamp
●​ completed_at: Timestamp when bonus was awarded
●​ currency: Currency code (e.g., "NGN")

Error Handling
The service implements comprehensive error handling, including:

1.​ HTTP Exceptions: Appropriate HTTP error codes for different error scenarios
2.​ Custom Error Handling: Via the handleApiError method
3.​ Transaction Rollback: Using Prisma's transaction feature to ensure data integrity

Security Features
1.​ Transaction PIN: Required for sensitive operations
2.​ PIN Encryption: PIN is stored using bcrypt hashing
3.​ Transaction Signatures: SHA-512 hashing for secure transfer signatures
4.​ KYC Validation: Transactions are validated against KYC requirements

Integration Points
VFD Bank API

●​ Virtual account creation


●​ Account details retrieval
●​ Bank transfers
●​ Beneficiary management
●​ Bank list retrieval

Testing Support
The wallet service includes features to support testing:

1.​ Test Accounts: Pre-configured accounts for testing different scenarios


2.​ Credit Simulation: Ability to simulate receiving funds
3.​ Environment Detection: Different endpoints for production vs. testing

Implementation Notes
1.​ All monetary operations use Prisma transactions to ensure atomicity
2.​ Transaction references and IDs are generated using UUID to ensure uniqueness
3.​ Balance updates use increment/decrement operations to prevent race conditions
4.​ Error handling includes specific error types for different failure scenarios
5.​ Escrow functionality provides protection for marketplace transactions

Limitations and Considerations


1.​ Virtual accounts have a limited validity period (40 hours)
2.​ Transaction logs expire after 1 month and require cleanup
3.​ The system assumes a single currency (NGN) for most operations
4.​ The KYC service must validate transactions before they are processed

Future Enhancements
1.​ Tiered Referral Program: Different bonus rates based on user activity or tier
2.​ Time-Limited Campaigns: Special referral rates during promotional periods
3.​ Multi-level Referrals: Extending the program to second-level referrals
4.​ Notifications: Alerting users when they earn referral bonuses
5.​ Analytics Dashboard: Providing users with visual analytics of their referral performance

Implementation Notes
1.​ Security Considerations:
○​ Referral code uniqueness is guaranteed via database constraints
○​ Validation of referral codes during sign-up
○​ Error handling is designed to be non-blocking for the main transaction flow
○​ Idempotency prevents duplicate bonus awards for the same transaction
2.​ Integration Points:
○​ User Registration: The processReferralSignup function is called during user
creation
○​ Transaction Completion: The processReferralBonus is called in the
handleCompletedStatus method of the EscrowService

You might also like