|
| 1 | +# Blockchain Event Listener Service |
| 2 | + |
| 3 | +## Overview |
| 4 | +Implemented a background worker service that subscribes to Stellar blockchain events to keep the application state in sync. The service handles escrow deposits, releases, and refunds for both entire jobs and individual milestones. |
| 5 | + |
| 6 | +## Key Components |
| 7 | + |
| 8 | +### 1. Database Schema Extensions |
| 9 | +- **Milestones Table (`scripts/004-milestones.sql`)**: Stores milestone-level progress, linked to jobs. |
| 10 | +- **Notifications Table (`scripts/005-notifications.sql`)**: Stores platform-wide notifications for users. |
| 11 | + |
| 12 | +### 2. Upgraded Background Worker (`scripts/worker.ts`) |
| 13 | +- **Stellar Horizon Streaming**: Subscribes to payments for the platform escrow account. |
| 14 | +- **Memo-based Logic**: Distinguishes between Job-level (`JOB-{id}`) and Milestone-level (`MIL-{id}`) operations using transaction memos. |
| 15 | +- **Role-aware Processing**: Fetches client and freelancer wallet addresses to automatically identify whether a payment from escrow is a **Release** (to freelancer) or a **Refund** (to client). |
| 16 | +- **Idempotency**: Checks `escrow_transactions` before processing to prevent duplicate updates from the same blockchain transaction. |
| 17 | +- **Automatic Job Completion**: Synchronizes the main Job status to `completed` once all associated milestones have been released. |
| 18 | +- **Real Notifications**: Inserts notification records directly into the database during event processing. |
| 19 | + |
| 20 | +## How to Run |
| 21 | +1. Ensure the new SQL migrations are applied to your database: |
| 22 | + ```bash |
| 23 | + # Run these in your Neon console or via psql |
| 24 | + scripts/004-milestones.sql |
| 25 | + scripts/005-notifications.sql |
| 26 | + ``` |
| 27 | +2. Set the necessary environment variables in `.env`: |
| 28 | + - `DATABASE_URL`: Your Postgres connection string. |
| 29 | + - `ESCROW_ACCOUNT_ID`: The Stellar account monitoring for escrow payments. |
| 30 | + - `STELLAR_HORIZON_URL`: (Optional) Defaults to Testnet. |
| 31 | +3. Start the worker: |
| 32 | + ```bash |
| 33 | + npm run worker |
| 34 | + ``` |
| 35 | + |
| 36 | +## Design Decisions |
| 37 | +- **Separation of Concerns**: Kept the worker as a separate script to avoid blocking Next.js API routes. |
| 38 | +- **Resilience**: Implemented `SIGINT` handling for graceful shutdown and used SDK streaming for automatic reconnection. |
| 39 | +- **Scalability**: Used async/await and non-blocking SQL queries to handle concurrent events. |
0 commit comments