Wallet Logic Engine — Dev Prompt

AI development specification document

Development Prompt: mCard Intelligent Wallet Optimization Engine

Overview

Build a production-grade backend service that intelligently selects the optimal payment source (or multi-source payment stack) for every transaction a user makes with their mCard. The system evaluates all of a user's connected financial accounts in real time, scores each eligible funding source against a weighted model, and returns a recommended payment stack that maximizes the user's financial benefit while respecting their chosen optimization strategy. An AI adaptive mode dynamically selects the best strategy per transaction based on real-time context.


System Architecture

Core Service: WalletOptimizationEngine

The engine is invoked at the point of transaction authorization (or pre-authorization). It receives transaction context and user profile, evaluates all eligible funding sources, and returns an optimized payment stack.

Pipeline (4 phases)

  1. Preference Loading — Retrieve the user's optimization profile (selected strategy, risk tolerance, credit utilization limits, cash preservation preference, etc.).
  2. Eligibility Filtering — From all connected accounts, identify which funding sources can be used for this transaction type, merchant, and amount. Filter out accounts that are frozen, insufficient balance, unsupported merchant category, etc.
  3. Scoring & Evaluation — Score each eligible source across six weighted dimensions (see Scoring Model below). If AI adaptive mode is active, evaluate all strategies and select the best one for this specific transaction.
  4. Payment Stack Optimization — Determine whether to split the transaction across multiple sources (e.g., apply expiring loyalty credit first, then charge the remainder to a rewards card). Return the final ordered payment stack with per-source amounts, reasons, and projected benefits.

Scoring Model

Each eligible funding source receives a composite score using this weighted formula:

score =
  rewardValue   × 0.30 +
  discountValue × 0.25 +
  expiryUrgency × 0.15 +
  preferenceFit × 0.15 −
  feeCost       × 0.10 −
  creditRisk    × 0.05

Dimension Definitions

| Dimension | Weight | Description | |---|---|---| | rewardValue | +0.30 | Cash-equivalent value of rewards, points, or cashback earned by using this source for this transaction. Factor in category multipliers (e.g., 3x on travel), point valuations, and caps. | | discountValue | +0.25 | Immediate monetary discount applied by using this source (promo credits, loyalty balances, coupon redemptions, merchant-specific offers). | | expiryUrgency | +0.15 | Urgency of using expiring value. If a loyalty credit or promo balance expires soon, this source gets a higher score to prevent value loss. Scale: 0 = no expiry, 1.0 = expires today. | | preferenceFit | +0.15 | How well this source aligns with the user's selected optimization strategy and risk profile. A business card scores high when optimization_goal = business_expense; a no-fee account scores high when optimization_goal = min_fees. | | feeCost | −0.10 | Total fees incurred by using this source: FX fees, cash advance fees, wire fees, convenience surcharges, network fees. 0 = no fees, 1.0 = maximum fee scenario. | | creditRisk | −0.05 | Negative impact on the user's credit health or debt exposure. Using a credit card near its utilization limit scores high; using checking scores 0. Factor in current utilization, days until statement closes, and whether the user's risk profile is debt-averse. |

Score Output

Each source's final score is a value between 0 and 1 (clamped). The highest-scoring source(s) are selected for the payment stack. When scores are close (within 0.05), the engine may split the transaction to capture benefits from multiple sources.


Optimization Strategies (User-Selectable Presets)

Each strategy modifies the scoring weights, eligibility rules, and post-processing logic. Users select one as their default, or enable AI Adaptive Mode.

1. Maximize Rewards

  • Goal: Earn the most rewards, points, and cashback on every transaction.
  • Key behaviors: Prefer highest reward rate source; use expiring rewards before they expire; allow higher credit utilization (up to 45%).
  • Preferences: prefer_highest_reward_rate: true, use_expiring_rewards_first: true, credit_utilization_limit: 0.45

2. Business Expense Optimization

  • Goal: Route business expenses to a business card for tax tracking while earning rewards.
  • Key behaviors: Detect merchant category codes (MCC) that indicate business expenses; prefer business credit card; auto-flag transaction for tax deduction tracking; save receipt metadata.
  • Preferences: flag_business_mcc: true, prefer_business_card: true, receipt_tracking: true, credit_utilization_limit: 0.40

3. Use Free Money First

  • Goal: Apply gift balances, promotional credits, loyalty points, coupons, and merchant-specific discounts before touching bank or credit.
  • Key behaviors: Always exhaust free-money sources first; prioritize by expiry urgency; use credit/debit only as last resort for the remainder.
  • Preferences: apply_promo_credits: true, apply_loyalty_credits: true, apply_gift_balances: true, apply_coupon_discounts: true, bank_credit_as_last_resort: true

4. Balanced Optimization

  • Goal: Maximize overall value without increasing debt risk. The smart default.
  • Key behaviors: Balance rewards vs fees vs risk; keep credit utilization under 30%; prompt user before charging more than $300 to credit if risk-averse.
  • Preferences: credit_utilization_limit: 0.30, ask_before_credit_above: 300, cash_preservation: true

5. Preserve Cash

  • Goal: Minimize immediate cash outflow. Use credit strategically to defer payment.
  • Key behaviors: Prefer credit cards with grace periods; defer cash outflow to statement due date; calculate the cash preservation window (days between transaction and payment due date).
  • Preferences: prefer_credit_over_debit: true, defer_to_statement_date: true, credit_utilization_limit: 0.35

6. Minimize Fees

  • Goal: Route transactions to avoid FX fees, cash advance fees, convenience surcharges, and wire fees.
  • Key behaviors: Detect transaction type (wire transfer, international, cash advance); scan fee structures across all accounts; select zero-fee or lowest-fee source.
  • Preferences: avoid_cash_advance: true, avoid_fx_fees: true, avoid_convenience_fees: true, prefer_no_fee_accounts: true

7. Build My Credit

  • Goal: Build credit history and earn rewards with zero debt held.
  • Key behaviors: Charge the purchase to a credit card that reports to all 3 bureaus; instantly pay off the credit card balance from the user's checking account; ensure 0% utilization is reported at statement close; maximize utilization cycling (charge → pay off → charge again within a billing cycle); target 8% utilization for optimal credit score impact.
  • Preferences: charge_credit_then_instant_payoff: true, auto_pay_credit_from_checking: true, ensure_zero_statement_balance: true, maximize_credit_utilization_cycling: true, target_utilization: 0.08, rewards_on_credit_spend: true, credit_bureau_reporting: monthly_positive

AI Adaptive Mode

When AI Adaptive Mode is enabled, the engine does NOT use a single fixed strategy. Instead, for each transaction it:

  1. Evaluates all strategies against the current transaction context.
  2. Selects the best strategy for that specific moment.
  3. Explains its choice with a human-readable reason.

Real-Time Context Factors

The AI considers these factors when selecting a strategy per transaction:

  • Merchant category (MCC code — grocery, gas, streaming, electronics, wire transfer, etc.)
  • Available balances across all connected accounts
  • Reward rates for this merchant category on each card
  • Expiring credits — loyalty points, promo balances, or gift credits expiring within a threshold window
  • Credit utilization — current utilization on each credit line vs. the user's limit
  • Fees — FX fees, cash advance fees, surcharges applicable to this transaction
  • Cash flow forecast — upcoming bills, predicted income, days until next paycheck
  • Time of day — some rewards programs have time-sensitive bonuses
  • Statement cycle position — days until statement closes (matters for credit utilization reporting)
  • User's historical choices — the AI learns from the user's past overrides and preferences

Strategy Selection Logic

For each transaction, the AI runs all 7 strategies through the scoring engine and compares the resulting benefit projections. It selects the strategy that produces the highest net benefit (rewards + discounts + credit-building value − fees − risk-adjusted debt cost). The AI outputs:

  • selected_strategy: the strategy ID and name
  • reason: a plain-language explanation (e.g., "Expiring loyalty credits detected — highest value recovery")
  • confidence: 0–1 score indicating how clearly this strategy won
  • alternatives_considered: ranked list of other strategies with their scores

Learning Loop

The AI improves over time by tracking:

  • When the user accepts vs. overrides the recommended strategy
  • Spending patterns by category, merchant, time, and geography
  • Reward earning rates actually realized vs. projected
  • Credit score trajectory over time

The model adjusts its scoring weights and strategy selection heuristics based on outcomes, becoming more personalized with each transaction.


Payment Stack Construction

A single transaction may be split across multiple funding sources. The engine constructs an ordered payment stack:

Input:  transaction = { merchant, amount, category, mcc, location }
        userProfile = { optimization_goal, risk_profile, credit_limits, ... }
        connectedAccounts = [ { source, type, balance, reward_rate, fees, expiry, ... } ]

Output: paymentStack = [
  { source: "Sponsor Free Money", amount: 10.00, reason: "Eligible grocery promo — applied first" },
  { source: "Loyalty Credit",     amount: 18.00, reason: "Expiring in 5 days — used before lost" },
  { source: "Grocery Rewards Card", amount: 58.42, reason: "5% cashback on remaining balance" },
]

Stack Ordering Rules

  1. Free money first — promo credits, gift balances, loyalty points, coupons (ordered by expiry urgency).
  2. Rewards-earning sources — credit/debit cards with category-specific reward multipliers.
  3. Bank accounts — checking/savings as the last resort (no rewards, but no debt).
  4. Deferred payment options — BNPL or credit with grace period, used when cash preservation is the goal.

Split Logic

  • If a free-money source covers part of the transaction, apply it first and charge the remainder to the next source in the stack.
  • If no single source has sufficient balance, split across sources by priority.
  • If the user's credit utilization would exceed their limit on a single card, split across multiple cards to stay under threshold.

API Specification

POST /wallet/optimize

Request:

{
  "user_id": "string",
  "transaction": {
    "merchant": "string",
    "amount": "number",
    "category": "string",
    "mcc": "string",
    "location": { "country": "string", "currency": "string" }
  },
  "ai_mode": "boolean"
}

Response:

{
  "selected_strategy": {
    "id": "string",
    "name": "string",
    "reason": "string"
  },
  "payment_stack": [
    {
      "source": "string",
      "amount": "number",
      "reason": "string"
    }
  ],
  "projected_benefits": {
    "reward_earned": "string",
    "fees_avoided": "string",
    "credit_impact": "string",
    "cash_preserved": "string"
  },
  "ai_analysis": {
    "confidence": "number",
    "alternatives_considered": [
      { "strategy_id": "string", "score": "number", "summary": "string" }
    ]
  },
  "eligible_accounts_scored": [
    {
      "source": "string",
      "scores": {
        "reward": "number",
        "discount": "number",
        "expiry": "number",
        "fit": "number",
        "fee": "number",
        "risk": "number"
      },
      "composite_score": "number",
      "selected": "boolean"
    }
  ]
}

Data Models

User Optimization Profile

{
  "user_id": "string",
  "optimization_goal": "max_rewards | business_expense | free_money_first | balanced | preserve_cash | min_fees | build_credit | ai_adaptive",
  "risk_profile": "rewards_priority | tax_optimized | value_preservation | debt_averse | cash_conservative | fee_sensitive | credit_builder",
  "cash_preservation": "boolean",
  "credit_utilization_limit": "number (0-1)",
  "ask_before_credit_above": "number (dollar threshold)",
  "prefer_highest_reward_rate": "boolean",
  "use_expiring_rewards_first": "boolean",
  "apply_promo_credits": "boolean",
  "apply_loyalty_credits": "boolean",
  "apply_gift_balances": "boolean",
  "apply_coupon_discounts": "boolean",
  "bank_credit_as_last_resort": "boolean",
  "avoid_cash_advance": "boolean",
  "avoid_fx_fees": "boolean",
  "prefer_credit_over_debit": "boolean",
  "defer_to_statement_date": "boolean",
  "charge_credit_then_instant_payoff": "boolean",
  "auto_pay_credit_from_checking": "boolean",
  "ensure_zero_statement_balance": "boolean",
  "maximize_credit_utilization_cycling": "boolean",
  "target_utilization": "number (0-1)",
  "ai_learning_enabled": "boolean"
}

Connected Account

{
  "account_id": "string",
  "source_name": "string",
  "type": "credit_card | debit_card | checking | savings | crypto_wallet | bnpl | loyalty | promo_credit | gift_balance",
  "balance": "number",
  "reward_rate": "number",
  "reward_categories": [{ "category": "string", "multiplier": "number" }],
  "fees": {
    "fx_fee": "number (0-1)",
    "cash_advance_fee": "number (0-1)",
    "wire_fee": "number",
    "convenience_fee": "number (0-1)"
  },
  "credit_limit": "number (nullable)",
  "current_balance": "number (nullable, for credit cards)",
  "statement_close_date": "date (nullable)",
  "payment_due_date": "date (nullable)",
  "expiry_date": "date (nullable, for promo/loyalty balances)",
  "reports_to_bureaus": "boolean",
  "is_frozen": "boolean",
  "supported_mccs": ["string"]
}

Technical Requirements

  1. Latency: The optimization must complete in under 200ms to avoid friction at point of sale.
  2. Real-time account data: Integrate with account aggregation providers (Plaid, MX, or similar) for live balances, utilization, and reward rates.
  3. MCC enrichment: Maintain a merchant category code database to classify transactions and match reward categories.
  4. Reward rate engine: Maintain up-to-date reward rate tables for each connected card (category multipliers, point valuations, caps, rotating categories).
  5. Credit bureau integration: For the "Build My Credit" strategy, integrate with credit monitoring APIs to track utilization reporting cycles and ensure instant payoffs land before statement close.
  6. Fee detection: Detect FX transactions, cash advance scenarios, wire transfers, and convenience fees from transaction metadata.
  7. Learning model: Train a model on user acceptance/override data to personalize strategy selection and scoring weights over time. Start with rule-based heuristics and transition to a learned model as data accumulates.
  8. Auditability: Log every optimization decision with full scoring breakdown, selected strategy, and AI reasoning for regulatory compliance and user transparency.
  9. Fallback: If the optimization service is unavailable, fall back to the user's default payment source (last-used card or primary checking).

Security & Compliance

  • All financial account data encrypted at rest and in transit.
  • PCI DSS compliance for any card data handling.
  • User must explicitly consent to AI Adaptive Mode before it activates.
  • The system must never expose full account numbers or sensitive credentials in API responses.
  • Credit-building strategy must comply with Fair Credit Reporting Act (FCRA) — instant payoffs are initiated by the user's own funds, not third-party credit repair tactics.

Acceptance Criteria

  1. Given a transaction and user profile, the engine returns a payment stack with per-source amounts and reasons within 200ms.
  2. Each eligible account is scored across all 6 dimensions with a composite score between 0 and 1.
  3. When a user selects "Maximize Rewards," the engine selects the source with the highest reward value for that merchant category.
  4. When a user selects "Use Free Money First," the engine exhausts all promo/loyalty/gift balances before charging bank or credit.
  5. When a user selects "Build My Credit," the engine charges a credit card and initiates an instant payoff from checking, reporting 0% utilization.
  6. When AI Adaptive Mode is enabled, the engine evaluates all strategies, selects the best one per transaction, and returns a human-readable reason.
  7. The engine splits transactions across multiple sources when free-money sources partially cover the amount.
  8. The engine respects credit utilization limits and will not recommend a source that would push utilization above the user's threshold.
  9. The engine avoids fee-incurring sources when a zero-fee alternative exists and avoid_* preferences are set.
  10. The AI learning loop adjusts scoring weights based on user acceptance/override history over time.