Skip to content

Validate coupon status before redemption to prevent duplicate or invalid redemptions #67

@Josue19-08

Description

@Josue19-08

➡️ Title

Validate coupon status before redemption to prevent duplicate or invalid redemptions

📘 Description

Create a comprehensive validation service that checks coupon status both on-chain and off-chain before allowing redemption. This service will prevent duplicate redemptions, expired coupon usage, and other invalid redemption attempts.

Context: Before any coupon redemption, we need to validate multiple conditions: ownership, expiration, redemption status, and contract state. This validation must be thorough and consistent across all redemption flows.

✅ Acceptance Criteria

Validation service creation

  • Create src/services/coupon-validation.service.ts
  • Implement comprehensive validation logic
  • Export validation functions for reuse
  • Add proper error handling and logging

Main validation function

  • Create validateCouponForRedemption(couponId, userId) function that:
    • Performs all necessary validation checks
    • Returns detailed validation result
    • Provides specific error messages for failures
    • Logs validation attempts

Database validation checks

  • validateCouponExists(couponId): Check coupon exists in database
  • validateCouponOwnership(couponId, userId): Verify user owns the coupon
  • validateCouponStatus(couponId): Check status is 'active' (not redeemed)
  • validateCouponExpiration(couponId): Check expiration date hasn't passed
  • validateUserWallet(userId): Ensure user has valid wallet address

Contract validation checks

  • validateContractCouponStatus(tokenId): Call is_valid_coupon() on contract
  • validateContractOwnership(tokenId, userAddress): Verify on-chain ownership
  • validateContractNotRedeemed(tokenId): Check contract redemption status
  • Handle contract connectivity issues gracefully

Validation result structure

  • Return validation object with:
    • isValid: Boolean indicating overall validation result
    • errors: Array of specific validation errors
    • warnings: Array of potential issues
    • couponData: Coupon information if valid
    • contractData: On-chain data if accessible

Specific validation functions

  • checkCouponExpiry(expirationDate): Date comparison logic
  • checkRedemptionWindow(coupon): Validate redemption time constraints
  • checkDailyRedemptionLimits(userId): Prevent abuse (if applicable)
  • checkBusinessOperatingHours(coupon): Validate redemption timing
  • checkGeographicRestrictions(coupon, userLocation): Location-based validation

Error classification

  • ValidationError: Base class for validation errors
  • CouponNotFoundError: Coupon doesn't exist
  • UnauthorizedRedemptionError: User doesn't own coupon
  • CouponExpiredError: Past expiration date
  • CouponAlreadyRedeemedError: Already used
  • ContractValidationError: On-chain validation failed

Database query optimization

  • Create efficient query for coupon validation data
  • Join necessary tables in single query where possible
  • Index optimization for validation queries
  • Cache validation results for repeated checks

Contract interaction optimization

  • Batch contract calls when possible
  • Implement retry logic for contract failures
  • Cache contract responses temporarily
  • Handle network timeouts gracefully

Integration helpers

  • preValidateCouponBatch(couponIds): Validate multiple coupons
  • validateAndLockCoupon(couponId, userId): Atomic validation with locking
  • refreshCouponValidation(couponId): Re-validate cached results
  • getValidationSummary(userId): User's coupon validation overview

Logging and monitoring

  • Log all validation attempts with results
  • Track validation failure patterns
  • Monitor validation performance metrics
  • Alert on unusual validation patterns

Testing

  • Create tests in src/tests/coupon-validation.test.ts
  • Test each validation scenario individually
  • Test combined validation logic
  • Test error handling for each validation type
  • Mock contract calls for testing
  • Test performance with large datasets

Configuration

  • Add validation settings to config:
    • Maximum redemption attempts per day
    • Grace period for expired coupons
    • Contract call timeout settings
    • Validation cache duration

Documentation

  • Document all validation rules and logic
  • Provide examples of validation responses
  • Document error codes and meanings
  • Create troubleshooting guide for validation failures

Performance optimization

  • Implement validation result caching
  • Optimize database queries for speed
  • Parallel validation checks where possible
  • Early exit on first validation failure

Integration points

  • Used by redemption endpoint
  • Used by coupon display components
  • Used by business partner verification
  • Used by administrative tools

⚠ Use kebab-case for all file and folder names.
⚠ Do not use default alias imports or relative paths like ../../components/foo.
⚠ Use alias paths with @, e.g. @/components/foo.
⚠ Structure the code with reusable components and reuse existing ones.

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions