Repository navigation
feat: Complete PiggyCards integration with PIN authorization and provider support - #737
Conversation
…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]>
fix: ctx json parsing
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]>
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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
performAutoLogincurrently logs the rawuserId, 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: accessingrow[3]whensourceIdis not selected.In both provider-fetch loops inside
items(...):
- When
PIGGYCARDS_ENABLEDis defined, the query selects 4 columns includingsourceId, and accessingrow[3]is valid.- When
PIGGYCARDS_ENABLEDis not defined, the query only selects 3 columns:provider, savingsPercentage, denominationsType, but the parsing code still unconditionally readsrow[3]to derivesourceIdString.On non-PiggyCards builds this will likely be an out-of-bounds access on the
Rowand can crash at runtime.You already handle this correctly in
allLocations(for:...)usingrow.count > 3and 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) + } + } + #endifRepeat 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) / 100That 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 / 100Files 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 metadataThe added/updated
libPods-*.aframework entries,Pods-*.xcconfigfile references,Podsgroup children, and[CP] Check Pods Manifest.lock/[CP] Copy Pods Resourcesshell 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 ensurepod installhas 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 utilityThe updated log markers are fine, but using
DSLogger(and/or wrapping in#if DEBUG) instead of rawDashWallet/Sources/Models/Explore Dash/Model/DAO/GiftCardsDAO.swift (1)
60-71: Provider field propagation in DAO looks correct; minor style tweak possibleIncluding
GiftCard.provider <- dto.providerincreateand carryingexistingCard.providerthroughupdateCardDetailsandupdateBarcodekeeps the in-memory cache and DB in sync for the new provider field; clearingnoteinupdateCardDetailsalso matches the polling semantics.If you care about SwiftLint cleanliness, you can also align the last two parameters in the
insertcall to satisfyvertical_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 onlyThe 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 flagThe
TokenRefreshActorcorrectly serializes refresh operations and shares a single in‑flightTaskacross concurrent callers. To satisfy SwiftLint and simplify the state, you can remove theisRefreshingflag and avoid therefreshTask!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 byreturn resultcan 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
throwsfunctions, 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:
- Using a consistent logging framework with log levels
- Making debug logs conditional on build configuration
- 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
providerListcurrently 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 forproviderand clean up optional bindingThe CTX vs PiggyCards dispatch in
fetchGiftCardInfoand the guards infetchCTXGiftCardInfolook 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.rawValueor a smallenum/constant) to avoid string drift across the codebase.- Replace
let _ = giftCard.notewithgiftCard.note != nilin 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 casesThe new
getBrands,getGiftCards,createOrder,getOrderStatus, andgetExchangeRatecases 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:
.purchaseGiftCardand.getMerchantare marked “Legacy – to be removed”, and.getGiftCardis 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
getGiftCardpath, it’s worth verifying there are no remaining call sites to.getGiftCardor 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 possibleThe 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 onPiggyCardsGiftcardto avoid duplication and subtle inconsistencies.- Consider documenting the hard‑coded
disabledGiftCardsbrand 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/hasPiggycalculation andmerchantId 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
allLocationspattern 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_ENABLEDPiggyCards-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 everyallLocationscall 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 DEBUGso 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 = ?withdb.prepare(providersQuery, merchant.merchantId).- Checks
row.count > 3before touchingrow[3]forsourceId.- Handles multiple possible
sourceIdtypes and logs unknown-types defensively.Two small follow-ups:
- The log label
"MerchantDAO.items(userLocation): Found ..."insideallLocationsis misleading; renaming toMerchantDAO.allLocationswould avoid confusion.- Returning
PaginationResult(items: items, offset: Int.max)is a clear sentinel, but double-check that all pagination callers treatInt.maxas 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:PiggyCardsPriceTypeenum is fine; raw values could be omitted.The
PiggyCardsPriceTyperaw values repeat the case names (e.g.,"fixed"), and you already normalize API values withlowercased(), 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, andmerchantUrl.- Walks
giftCardProvidersto match the selectedprovider, storingsourceId, provider-specificdenominationsType, andsavingsFraction.- Falls back to merchant-level denominations when provider info is absent.
One minor nit: the
else { }after theif let giftCardProvidersis empty and can be removed, and you might want to explicitly comment what happens whensourceIdis missing (PiggyCards flow will then skip fetching gift cards inupdateMerchantInfo).
480-490: Error handling inupdateMerchantInfoswallows details.On error you only reset
isLoading:} catch { await MainActor.run { self.isLoading = false } }No log or user-facing
erroris 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 settingself.errorwhen 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.
saveGiftCardDummystores:
price: amount(fiat),note: giftCardId(order/payment ID),provider: provider.displayName.This matches the updated
GiftCardDAO which now includesprovider. As long as downstream UI knowsnotecarries 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:providerNameparameter tomarkGiftCardTransactionis unused.
markGiftCardTransaction(txId:provider:)ignores theproviderNameargument and instead switches onself.providerto settxMetadata.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:orderGiftCardpipeline is structurally sound but contains several debug leftovers.The high-level flow (use cached cards → select card → build
PiggyCardsOrderRequest→ callcreateOrder→ delegate toprocessOrderResponse) 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 giftCardsloop inside theinvalidAmountcase is empty.hasTokenis computed but never used.- The JSON encoding of
orderRequestand 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:parsePaymentURIis reasonable, but consider being more tolerant.The URI parsing:
- Validates non-empty,
dash:-prefixed strings.- Extracts address and
amountquery parameter from a simpledash: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: LegacygetMerchantstub should either be implemented or clearly deprecated.
getMerchant(merchantId:)currently just throws.unknownand is marked as “to be replaced”. If there are no callers left, it should be removed; if there are, you probably want it to callgetBrands/getGiftCardsor 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
⛔ Files ignored due to path filters (1)
Podfile.lockis 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.swiftDashWallet.xcodeproj/project.pbxprojDashWallet/Sources/UI/Explore Dash/Merchants & ATMs/Details/POIDetailsViewController.swiftDashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayViewModel.swiftDashWallet/Sources/Models/Explore Dash/Model/DashSpend/PiggyCardsConstants.swiftDashWallet/Sources/Models/Tx Metadata/ServiceName.swiftDashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsEndpoint.swiftCLAUDE.mdDashWallet/Sources/UI/Explore Dash/Views/DashSpend/GiftCardDetailsViewModel.swiftDashWallet/Sources/UI/Explore Dash/Merchants & ATMs/Details/Views/POIDetailsViewModel.swiftDashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsAPI.swiftDashWallet/Sources/Models/Explore Dash/Model/DAO/GiftCardsDAO.swiftDashWallet/Sources/Models/Explore Dash/Model/Entites/PiggyCardsModels.swiftDashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsRepository.swiftDashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsTokenService.swiftDashWallet/Sources/Models/Explore Dash/Infrastructure/DAO Impl/MerchantDAO.swiftDashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayScreen.swiftDashWallet/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.pbxprojCLAUDE.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.swiftDashWallet/Sources/Models/Explore Dash/Services/DashSpend/PiggyCards/PiggyCardsEndpoint.swiftCLAUDE.mdDashWallet/Sources/UI/Explore Dash/Views/DashSpend/GiftCardDetailsViewModel.swiftDashWallet/Sources/Models/Explore Dash/Model/Entites/PiggyCardsModels.swiftDashWallet/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.swiftDashWallet/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.swiftDashWallet/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 thepiggyCardscase 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
Serviceenum 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.swifthas a PBXFileReference, is added under theMigrationsgroup, 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.swiftis referenced as a PBXFileReference, grouped underPiggyCards, and added to the Sources phases for both the primary app and the additional target that already buildPiggyCardsTokenService.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_CONDITIONSnow includesPIGGYCARDS_ENABLEDfor dashwallet/dashpay Debug, Release, Testnet, and Testflight configs, preserving existing flags likeDEBUGandDASH_TESTNETwhere 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 correctIgnoring
*.db-shm,*.db-wal, andtxis 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 soundThe new
observeAllsubscription andupdateMetadataForGiftCards(_:)batching logic correctly reuses the existingmetadataQueuefor thread safety and dispatchesmetadataUpdatedon the main queue per tx. The behavior is consistent withonMetadataUpdatedand 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 straightforwardSwitching
baseURIto the production host, addingstagingBaseURI, 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
providerfield is appropriately typed to support multi-provider gift cards.
57-58: Excellent defensive decoding for migration safety.Using
try?to safely handle theprovidercolumn 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
providerparameter with a default value ofnil, 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
redeemTypeandgiftCardProviderswhen 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
sourceIdfield 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.isEmptyappropriately guards the loading display.DashWallet/Sources/UI/Explore Dash/Merchants & ATMs/Details/Views/POIDetailsView.swift (1)
287-287: Verified:sortedProvidersis 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
AddProviderToGiftCardsTablemigration sets a default value ofnilfor 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 goodUsing
sortedProvidersderived from a sortedproviderListand choosingselectedProviderfrom the first entry gives a predictable, discount-prioritized UI order while keepingsupportedProvidersas a lookup map. This is a solid improvement over relying on dictionary key order.Also applies to: 185-201
77-92: Good use ofcancellableBagreset on provider changeClearing
cancellableBagbefore 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 registrationAdding a nullable
providercolumn with a default ofnilis safe for existing rows and matches the newGiftCardmodel. Please double‑check that:
AddProviderToGiftCardsTableis appended to the global migrations list inDatabaseConnectionin ascendingversionorder, and- There are no older migrations that also touch the
gift_cardsschema in conflicting ways.DashWallet/Sources/UI/Explore Dash/Views/DashSpend/GiftCardDetailsViewModel.swift (1)
40-47: PiggyCards repository wiring and retry window look reasonableThe dedicated
piggyCardsRepositoryplusmaxRetries = 40at 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.
GiftCardStatusandPiggyCardsOrderStatuswith thegiftCardStatusmapping 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:getOrderStatusandgetExchangeRatewrappers look good.Both helpers:
- Call the appropriate
PiggyCardsAPIendpoint.- Map
HTTPClientErrorthroughparseErrorwith an accurate context string.- Use
PiggyCardsCachefor exchange-rate caching to avoid redundant network calls.No functional issues here.
339-362: Gift card fetch and caching are aligned withorderGiftCardusage.
getGiftCards(country:sourceId:merchantId:):
- Calls
.getGiftCardswith the brand ID (sourceId).- Validates
response.dataand throwsmerchantUnavailableif missing.- Caches cards per
merchantIdinPiggyCardsCachefor later use byorderGiftCard.This matches how
DashSpendPayViewModel.updateMerchantInfoprimes the cache before callingorderGiftCard. No issues here.
- 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]>
There was a problem hiding this comment.
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 matchsendCoinssecurity requirements.The BIP70 payment flow (
payWithDashUrl→fetchAndProcessPaymentRequest→DWPaymentProcessor.processPaymentInput) lacks explicit authentication, whilesendCoinsrequires PIN/biometric authentication before payment (lines 78-82).Verification confirms
DWPaymentProcessordoes not import or callDSAuthenticationManager, and the delegate methods inSendCoinsServiceresume the continuation without authentication. This creates a security gap where BIP70 payments bypass user authentication.Required fix: Add explicit authentication call to
payWithDashUrlbefore callingfetchAndProcessPaymentRequest, mirroring the pattern used insendCoins(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 buildprovidersQuerylike this:#if PIGGYCARDS_ENABLED SELECT provider, savingsPercentage, denominationsType, sourceId FROM gift_card_providers #else SELECT provider, savingsPercentage, denominationsType FROM gift_card_providers #endifbut inside the row iteration you always access
row[3]to derivesourceIdString:// Handle sourceId - it might be String, Int64, or nil var sourceIdString: String? = nil if let sourceId = row[3] as? String, !sourceId.isEmpty { ... } ...When
PIGGYCARDS_ENABLEDis not defined, the SELECT only has 3 columns, sorow[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
sourceIdin 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 arow.count > 3check, similar to what you do inallLocations(for: ...).You can also drop the unused
rowCountvariable in this loop to reduce noise.Also applies to: 193-225
416-427: Apply the same sourceId/column‑count fix in the paginated items(...) pathThe second gift‑card provider fetch in
items(...)(after the main paginated query) repeats the same pattern:providersQueryis conditionally compiled to include 3 vs 4 columns, but the row loop always indexesrow[3]forsourceIdString. This has the same potential out‑of‑range risk on builds withoutPIGGYCARDS_ENABLED.Mirror whichever fix you choose for the earlier loop here as well (always include
sourceIdin the SELECT, or guard withrow.count > 3), and consider removing the unusedrowCountto 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:
- Line 66: The
@MainActorattribute should be on its own line above the function declaration per Swift conventions.- Line 72: The
usedBiometricsparameter 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 amountIn the PiggyCards path you compute satoshis as:
let dashAmountInSatoshis = UInt64(giftCardInfo.amount * 100_000_000)If
giftCardInfo.amountcontains 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 formatIn
fetchPiggyCardsGiftCardInfo:
- If
orderStatus.data.statusis"complete"/"completed"butcards.firstisnilor the first card has neither a non‑emptyclaimCodenor a non‑emptyclaimLink, the switch falls through without setting an error, incrementingretryCount, or callingstopTicker(). 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 offbarcodeFormat.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
firstCardexists but bothclaimCodeandclaimLinkare 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 definitionsThe 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'intomerchantbut'fixed'intogift_card_providers. Filters elsewhere (e.g., inMerchantDAO) comparedenominationsTypeto 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 consistentCapturing
sourceIdand provider-specific savings/denomination type frommerchant.merchant?.giftCardProvidersand falling back tomerchant.merchant?.toSavingsFraction()provides a clean separation between CTX and PiggyCards, while still working when provider rows are missing. The post‑super.init()assignment ofisFixedDenominationfromproviderIsFixedis also safe with@Publishedproperties. One small mismatch: the comment says merchant-level denominations are a fallback “if we don't have provider-specific info”, but you currently always applymerchant.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: SimplifymarkGiftCardTransactionsignature or use the parameter
saveGiftCardDummyandmarkGiftCardTransactionnow correctly persist the provider (provider.displayName) on theGiftCardmodel and set TxMetadata.service to.ctxSpendvs.piggyCardsbased onself.provider. However,markGiftCardTransaction(txId:provider:)ignores itsproviderNameparameter and derives everything from the instance’sproviderproperty, 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
providerNameto drive service selection if you ever expect to mark transactions for a provider different fromself.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 nitThe updated
fetchGiftCardInfo()correctly:
- Stops polling when the gift card record goes away or
noteis 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.notewithgiftCard.note != nilin 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 plumbingThe
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, sourceIdand checksrow.count > 3before indexingrow[3], handlingString,Int64,Int, or other types forsourceIdrobustly.- Propagates
sourceIdStringintoExplorePointOfUse.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
rowCountlocal, but that’s purely cosmetic.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 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.swiftDashWallet/Sources/Models/Transactions/SendCoinsService.swiftDashWallet/Sources/Models/Explore Dash/Infrastructure/Database Connection/ExploreDatabaseConnection.swiftDashWallet/Sources/UI/Explore Dash/Views/DashSpend/GiftCardDetailsViewModel.swiftDashWallet/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.swiftDashWallet/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:
- Authenticate user via PIN/biometrics
- Sign transaction only after authentication succeeds
- 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 safeUsing an in‑memory
ConnectionwhendbPath()returnsnilprevents crashes during v3 download, and the DEBUG/Testflight hooks deferinsertTestMerchant()until afterconnect()so they won’t run against a nildb. The internalguard let db = self.dbininsertTestMerchant()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 patternThe
execute<Item>(query: String)overload now mirrors the typed‑query version by guarding ondb != niland 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 reasonableThe provider‑based branching in
updateMerchantInfo()is clear:
- CTX branch correctly uses
merchantInfo.discount(basis points) and denominationType.Rangevs fixed to setsavingsFraction,minimumAmount/maximumAmount, anddenominations.- PiggyCards branch pulls
giftCardsusingsourceId, selects a preferred card (Domino’s fixed cards, then “instant” cards, then first fallback), and derivessavingsFractionas(discountPercent - serviceFee)/100with sane defaults for missing min/max or malformed denominations.The final
MainActor.runthat clearsisLoading, sendsobjectWillChange, and recheckscheckAmountForErrors()gives the UI a consistent refresh point.Also applies to: 384-472
488-519: Locale‑invariant fiat amount formatting is a solid improvementThe
purchaseGiftCardAPI()path switching to anen_US_POSIXNumberFormatterwith explicit.decimal separator and fixed 2 fraction digits (driven byNSDecimalNumber(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.
Summary
This PR completes the PiggyCards gift card integration with proper PIN authorization, provider detection, and comprehensive polling support.
Major Features
Technical Changes
Authentication & Security
SendCoinsServiceto explicitly request PIN authorization before transaction signing@MainActorwrapper for authentication to ensure UI operations on main threadDatabase & Migration
providercolumn togift_cardstableAddProviderToGiftCardsTablemigrationGiftCardmodel and DAO with defensive column handlingPiggyCards API Integration
Bug Fixes
Testing Instructions
Files Changed
Notes
🤖 Generated with Claude Code
Co-Authored-By: Claude [email protected]
Summary by CodeRabbit
New Features
Improvements
Bug Fixes
✏️ Tip: You can customize this high-level summary in your review settings.