# juspay/hyperswitch — Kavach Visual Invariant Atlas

> Open-source Rust payments switch: Euclid routing DSL compiler, surcharge math, and multi-currency minor/major unit conversion.

- **Repository:** https://github.com/juspay/hyperswitch
- **Commit:** `b748596` (branch `main`)
- **Proof Tier:** `gold_showcase`
- **Stateful Backend Supported:** `true`
- **Scan:** 1052 ms · 1450 files · $0.00 LLM tokens

## Detected Stateful Drivers & Gateways

| Driver | Language | Category | Kavach Adapter |
| :--- | :--- | :--- | :--- |
| `kavach-host (Rust scoped)` | rust | http | `kavach-host` |

## Extracted System Invariants (3)

| Invariant | Proof State | Category | Rule Kind | Evidence |
| :--- | :--- | :--- | :--- | :--- |
| `routing_ast_vir_equivalence` | `verified` | state | `state_machine` | `harness/hyperswitch-host/src/main.rs:274-301` |
| `surcharge_exact_ceiling_conservation` | `verified` | conservation | `conservation` | `harness/hyperswitch-host/src/main.rs:315-400` |
| `currency_unit_roundtrip_conservation` | `verified` | conservation | `conservation` | `harness/hyperswitch-host/src/main.rs:402-517` |

### `routing_ast_vir_equivalence`
- **Summary:** Production VirInterpreterBackend connector selection and matched rule name must match reference AST InterpreterBackend.
- **Proof State:** `verified`
- **Code:** `harness/hyperswitch-host/src/main.rs:274-301`

### `surcharge_exact_ceiling_conservation`
- **Summary:** Surcharge and tax-on-surcharge minor units must equal exact base-10 integer ceiling(amount * pct / 100).
- **Proof State:** `verified`
- **Code:** `harness/hyperswitch-host/src/main.rs:315-400`

### `currency_unit_roundtrip_conservation`
- **Summary:** Major unit strings, connector base-unit formatting, and round-trip convert_back must preserve exact ISO-4217 decimal scale (0, 2, 3, or 4 digits).
- **Proof State:** `verified`
- **Code:** `harness/hyperswitch-host/src/main.rs:402-517`

## Guided Causal Flows

### H1: Numeric /= double-negation flips Euclid routing
Rule amount /= (100, 200) lowers to NegativeConjunction around NumValueRefinement::NotEqual, making VirInterpreterBackend reject non-excluded amounts.

1. **`in_routing`**: Steps 1-5 route valid card payments; step 6 evaluates rule 'amount /= (100, 200) -> stripe' with amount_minor=5000.
2. **`fn_ast_lower`**: lower_number! assigns NumValueRefinement::NotEqual while lower_comparison assigns NegativeConjunction.
3. **`fn_vir_eval`**: VirInterpreterBackend evaluates all(|v| !ctx.check_presence(v)), computing !(5000 != 100) && !(5000 != 200) = false.
4. **`bug_h1`**: Payment amount=5000 falls through to default ['adyen'] instead of rule_1 ['stripe'].
5. **`inv_routing`**: routing_ast_vir_equivalence fails at step 6: VIR=(None, ['adyen']) vs AST=(Some('rule_1'), ['stripe']).

### H2: Binary f64 surcharge overcharge compounds into tax
Percentage::apply_and_ceil_result multiplies f64 and calls .ceil(), turning exact 700.00 into 701 cents.

1. **`in_surcharge`**: Steps 1-5 calculate healthy surcharges; step 6 calculates 7.0% surcharge + 14.0% tax on amount_minor=10000 ($100.00).
2. **`fn_pct_ceil`**: apply_and_ceil_result computes (10000_f64 * (7.0 / 100.0)).ceil() = (700.00000000000011).ceil() = 701.
3. **`bug_h2`**: Overcharged surcharge=701 feeds tax_on_surcharge_percentage=14.0%, producing tax=99 instead of exact 98.
4. **`inv_surcharge`**: surcharge_exact_ceiling_conservation fails at step 6 (surcharge 701 vs 700, tax 99 vs 98).

### H3a: 4-decimal CLF treated as 2-decimal (100x corruption)
MinorUnit/MajorUnit helpers omit is_four_decimal_currency(), distorting CLF minor/major conversions by 100x.

1. **`in_currency`**: Steps 1-5 convert healthy 2-decimal currencies; step 6 converts amount_minor=12345 CLF (1.2345 CLF).
2. **`fn_minor_major`**: MinorUnit::to_major_unit_as_f64 divides by 100 instead of 10000 and formats 2 decimals ('123.45').
3. **`bug_h3_clf`**: Forward outputs 123.45 CLF (100x high) while StringMajorUnit::convert_back('1.2345') returns 123 minor units (99% loss).
4. **`inv_currency`**: currency_unit_roundtrip_conservation fails at step 6.

### H3b: 3-decimal BHD truncated to {:.2} in connector formatting
Currency::to_currency_base_unit formats with {:.2} unconditionally, rounding 1.235 BHD to '1.24'.

1. **`in_currency`**: Steps 1-5 convert healthy 2-decimal currencies; step 6 converts amount_minor=1235 BHD (1.235 BHD).
2. **`fn_currency_base`**: to_currency_base_unit_asf64 yields 1.235, then to_currency_base_unit formats '{amount_f64:.2}'.
3. **`bug_h3_bhd`**: Connector wire payload receives '1.24' BHD (corrupting the 3rd decimal digit).
4. **`inv_currency`**: currency_unit_roundtrip_conservation fails at step 6.

## Replay-Verified Proofs (188/188 variants, 184/184 regressions)

- **HS1: VirInterpreterBackend Numeric NotEqual Double-Negation** (`crates/euclid/src/frontend/ast/lowering.rs:72-96`) — Inverts /= routing DSL rules (!(ctx != prog) == (ctx == prog)), misrouting payments. [37/37 variants · verdict `fixed`]
- **HS2: IEEE-754 f64 Surcharge & Compounding Tax Overcharge** (`crates/common_utils/src/types.rs:97-116`) — Float drift turns exact integer percentages into +1c overcharges on surcharge and tax. [37/37 variants · verdict `fixed`]
- **HS3: CLF 4-Decimal 100x Scaling & BHD 3-Decimal Truncation** (`crates/common_utils/src/types.rs:452-486`) — Omits 4-decimal currency checks and formats 3-decimal currencies with {:.2}. [114/114 variants · verdict `fixed`]

## Starter `.kavach/invariants.yaml`

```yaml
service: hyperswitch
invariants:
  - name: routing_ast_vir_equivalence
    kind: non_negative
    sink: routing:vir
    field: $.equivalence_ok
  - name: surcharge_exact_ceiling_conservation
    kind: conservation
    sink: payment:surcharge
    field: $.overcharge_cents
  - name: currency_unit_roundtrip_conservation
    kind: conservation
    sink: payment:currency
    field: $.scaling_drift
```

## Driver Wrap Snippet

```text
// Scoped Rust host wrapper (kavach-host stdin/stdout JSONL)
kavach_host::serve(|env, input| {
  router.evaluate_payment_intent(env, input)
})
```

## Run Locally (Zero Upload)

```bash
brew install kavachlabs/tap/kavach && kavach map --auto --open
```
