feat: implement webhook event dispatch system#157
Open
DevSolex wants to merge 86 commits into
Open
Conversation
feat(api): implement system health check endpoint GET /health
- Add @nestjs/passport and passport-jwt for JWT authentication - Create JwtStrategy extracting merchant_id from token payload - Implement global JwtAuthGuard with @public() bypass decorator - Add @CurrentMerchant() decorator to access req.user - Mark health and root endpoints as public
feat(api): implement JWT authentication strategy and guards
- Add GET /treasury/reserves endpoint for public transparency - Create TreasuryModule, TreasuryService, TreasuryController - Include reserve ratio calculation for each asset - Add TODO stubs for on-chain Stellar queries - Add .env.example with required environment variables
Resolve conflicts: - Keep TreasuryModule and AuthModule in app.module.ts - Keep @stellar/stellar-sdk, passport, and passport-jwt in dependencies
feat(api): implement Proof-of-Reserves (PoR) API
- Add @nestjs/throttler for rate limiting protection - Create ThrottlerRedisGuard tracking by merchant_id for auth routes - Create ThrottlerStorageRedisService with TODO for Redis implementation - Configure 100 req/min for public, 1000 req/min for auth routes
- Happy path: Registration -> Payment -> Confirmation -> Mint - Error paths: invalid signatures, insufficient balances, rate limits - Uses Jest and Supertest with real JwtAuthGuard/JwtStrategy - Install jsonwebtoken as dev dep for test token generation
feat(api): implement rate limiting middleware
Document backup/restore, PITR, cross-region replication, and runbooks for common payment gateway failures. Add dry-run drill scripts for Windows PowerShell and POSIX shells. Made-with: Cursor
…ger--openapi-documentation feat: add swagger docs and route to /docs
…ntainers feat(infra): configure multi-stage pnpm docker builds
- Fix unescaped quotes in checkout page - Replace impure Math.random with stable state - Remove unused imports - Replace img tags with Next.js Image
- Add POST /treasury/redeem endpoint (authenticated via JWT) - Validate merchant balance before redemption - Invoke Soroban burn simulation generating burn_tx_hash - Create pending redemption record for withdrawal worker to process - Add RedeemDto with amount, currency, and destination fields - Add RedeemResponse interface - Wire RedemptionRepository through WorkerModule exports - Add create() method to RedemptionRepository
…em-endpoint feat(treasury): implement asset redemption and burn endpoint
- Add BlockchainWatcher service with @nestjs/schedule cron polling - Poll Stellar Horizon every 30s for incoming payments to watched deposit addresses - Detect transfers where amount >= expected and mark as detected - Public watchDeposit() method for other modules to register addresses - Register and export BlockchainWatcher in WorkerModule
…ansaction-watcher feat(worker): implement blockchain transaction watcher
- Add DepositAddress interface and DepositNetwork enum (STELLAR, BTC, ETH) - Add DepositAddressService with generateAddress() per network - Stellar: shared hot wallet address with unique memo - BTC: deterministic derivation from xpub (BIP84) - ETH: deterministic derivation from xpub (BIP44) - Add GenerateDepositAddressDto - Add POST /payments/:paymentId/deposit-address endpoint (authenticated) - Add GET /payments/:paymentId/deposit-addresses endpoint - Add findOne() to PaymentsService for intent lookup - Register DepositAddressService in PaymentsModule
…ss-generation feat(payments): implement crypto deposit address generation
- Rewrite Prisma schema with 4 core tables per requirements: - merchants: id (UUID), email (unique), password_hash, kyc_status, timestamps - payment_intents: id (UUID), merchant_id (FK), amount (Decimal), currency, status (PENDING/DETECTED/CONFIRMED/FAILED), timestamps - treasury_assets: symbol (PK), total_minted, total_reserved - webhook_endpoints: id (UUID), merchant_id (FK), url, secret, timestamps - Add PrismaService (extends PrismaClient with lifecycle hooks) - Add global PrismaModule wired into AppModule - Add @prisma/client and prisma deps to apps/api - Generate initial migration SQL for all 4 tables - Regenerate Prisma client
…e-core-schema feat(db): initialize Prisma with core PostgreSQL schema
- Add AnchorService with processAnchorRefund(transactionId) method - Handle full and partial refunds for failed deposit/withdrawal transactions - Validate transaction exists and is in refundable (failed) status - Prevent duplicate refunds on already-refunded transactions - Add RefundResult interface (transactionId, success, amountRefunded, totalAmount, isPartialRefund, status, error, refundedAt) - Add AnchorTransaction interface with registration support - Export all types from package index - Build passes with zero TypeScript errors
…efund feat(anchor): implement processAnchorRefund function
- Add AnchorService.createSep31DirectPayment(params) implementing SEP-31 flow - Validate sender/receiver KYC via SEP-12 (stub with TODO for real endpoint) - Generate unique payment ID and execute Stellar payment (stub) - Track payment lifecycle: pending -> completed | failed - Add DirectPaymentParams interface (senderId, receiverId, amount, assetCode, senderKyc, receiverKyc, originalTransactionRef) - Add DirectPaymentResult interface (success, paymentId, stellarTransactionHash, status) - Add Sep12KycData interface for KYC fields - Build passes with zero TypeScript errors
…ment feat(anchor): implement createSep31DirectPayment function
- Add AnchorService.submitCustomerInfo(customerData) for SEP-12 KYC - Support both new customer creation and partial/full updates - Handle identity document uploads with file content support - Validate required fields (firstName, lastName, email, countryCode) on creation - Return CustomerPutResponse with status (NEEDS_INFO | PROCESSING | APPROVED | REJECTED) - Add CustomerData interface with optional fields and IdentityDocument - Add FileContent interface with Uint8Array data - Build passes with zero TypeScript errors
…info feat(anchor): implement submitCustomerInfo function for SEP-12
- Add deploy workflow with blue/green environment switching - Configure smoke tests before traffic switch - Implement rollback mechanism via workflow_dispatch - Add canary release support with weighted traffic routing - Build and push Docker image to GitHub Container Registry
…oyment Implement blue-green deployment strategy
- Create FeeQuote, FeeBreakdown, and TransactionType interfaces - Support asset-specific fee schedules (flat + percentage) - Return detailed fee breakdown with effective rate - Generate unique quote IDs with 60-second expiry
…r-fee Add calculateAnchorFee function
- Create KycStatusResponse interface with pending|approved|rejected status - Implement checkKycStatus(accountId) with SEP-12 customer lookup - Add linkAccount() to associate Stellar accounts with customer records - Handle missing KYC data gracefully with descriptive message
Add checkKycStatus function
- Add BullMQ queue for webhook delivery with exponential backoff - Retry schedule: 10s, 1m, 5m, 30m (4 attempts total) - Log failures permanently for merchant debugging via GET /webhooks/:id/failures - Add WebhooksModule with CRUD endpoints for webhook endpoints - Sign webhook payloads with HMAC-SHA256 - Include webhook metadata headers (signature, event type, attempt, event ID)
…etry Implement Redis-backed webhook retry queue
Author
|
@MissBlue00 conflict resolved kindly review |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Implements the webhook event dispatch system as described in #15.
Changes
dispatchEvent()builds a standardized payload and delivers to all active merchant endpoints. Includes HMAC-SHA256 request signing, 10s timeout, and exponential backoff retry (up to 3 attempts).payment.created,payment.detected,payment.confirmed,payment.faileddefined as a typed enum.{ event, data, timestamp }on every delivery.PaymentsServiceandTransactionsServicefire the appropriate event on every payment status transition.WebhookServiceandWebhookController.Tested
Closes #15