Skip to content

feat: implement webhook event dispatch system#157

Open
DevSolex wants to merge 86 commits into
MissBlue00:mainfrom
DevSolex:feat/issue-15-webhook-event-dispatch
Open

feat: implement webhook event dispatch system#157
DevSolex wants to merge 86 commits into
MissBlue00:mainfrom
DevSolex:feat/issue-15-webhook-event-dispatch

Conversation

@DevSolex
Copy link
Copy Markdown

Summary

Implements the webhook event dispatch system as described in #15.

Changes

  • WebhookServicedispatchEvent() 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).
  • WebhookController — REST endpoints for merchants to register, list, update, and delete webhook configs.
  • WebhookRepository — In-memory store for webhook configs and delivery attempt history.
  • Event typespayment.created, payment.detected, payment.confirmed, payment.failed defined as a typed enum.
  • Payload shape — Standardized { event, data, timestamp } on every delivery.
  • IntegrationPaymentsService and TransactionsService fire the appropriate event on every payment status transition.
  • Tests — Unit tests for WebhookService and WebhookController.

Tested

  • Unit tests pass for webhook service and controller
  • All payment lifecycle transitions dispatch the correct event

Closes #15

MissBlue00 and others added 30 commits March 24, 2026 10:51
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
supreme2580 and others added 28 commits May 28, 2026 18:09
- 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
- 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 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
@DevSolex
Copy link
Copy Markdown
Author

DevSolex commented May 29, 2026

@MissBlue00 conflict resolved kindly review

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Webhooks: Implement event dispatch system