# Atomic Settlement Flow

## Overview

Atomic settlement ensures that cross-chain and cross-ledger transactions either complete entirely or fail entirely, with no partial state. This flow implements a dual-commitment protocol that commits to both sovereign and DBIS master ledgers atomically.

## Prerequisites

- Source and destination banks are registered
- Valid transaction request
- Sufficient balance in source account
- Both ledgers (sovereign and DBIS) are operational
- Atomic settlement service initialized

## Visual Flow Diagram

```
┌─────────────┐
│ Transaction │
│  Request    │
└──────┬──────┘
       │
       │ 1. Prepare Commitment
       ▼
┌─────────────────────────┐
│ Prepare Dual-Commitment │
│  - Generate commitment   │
│  - Create settlement ID  │
└──────┬──────────────────┘
       │
       │ 2. Commit to Sovereign
       ▼
┌─────────────────────────┐
│ Commit to Sovereign    │
│  Ledger                  │
│  - Post debit/credit    │
│  - Generate hash         │
└──────┬──────────────────┘
       │
       │ 3. Commit to DBIS
       ▼
┌─────────────────────────┐
│ Commit to DBIS Master   │
│  Ledger                  │
│  - Post debit/credit    │
│  - Generate hash         │
└──────┬──────────────────┘
       │
       │ 4. Verify Commitments
       ▼
┌─────────────────────────┐
│ Verify Dual-Commitment  │
│  - Compare hashes        │
│  - Verify both posted    │
└──────┬──────────────────┘
       │
       │ 5. Finalize
       ▼
┌─────────────┐
│ Settlement  │
│  Complete   │
└─────────────┘
```

## Step-by-Step Process

### Step 1: Prepare Dual-Commitment
1. Receive atomic settlement request with:
   - Source bank ID
   - Destination bank ID
   - Amount and currency
   - Asset type
   - Transaction ID (optional)
2. Generate unique settlement ID: `{uuid}`
3. Generate transaction ID if not provided: `{uuid}`
4. Create commitment data structure:
   - Settlement ID
   - Transaction details
   - Timestamp
   - Nonce for uniqueness
5. Prepare commitment hash input

**Code Reference**: `src/core/settlement/isn/atomic-settlement.service.ts:33-42`

### Step 2: Commit to Sovereign Ledger
1. Post to sovereign ledger:
   - Lookup source account in sovereign bank
   - Lookup destination account
   - Create debit entry on source
   - Create credit entry on destination
   - Use ledger ID: `Sovereign_{sourceBankId}`
2. Retrieve ledger entry
3. Extract block hash from ledger entry
4. Store sovereign ledger hash
5. If posting fails, throw error and terminate

**Code Reference**: `src/core/settlement/isn/atomic-settlement.service.ts:44-49`

### Step 3: Commit to DBIS Master Ledger
1. Post to DBIS master ledger:
   - Lookup source account
   - Lookup destination account
   - Create debit entry on source
   - Create credit entry on destination
   - Use ledger ID: `Master`
   - Include metadata: `{ atomicSettlement: true, settlementId }`
2. Retrieve ledger entry
3. Extract block hash from ledger entry
4. Store DBIS ledger hash
5. If posting fails, rollback sovereign ledger and throw error

**Code Reference**: `src/core/settlement/isn/atomic-settlement.service.ts:51-52`

### Step 4: Verify Dual-Commitment
1. Compare hashes:
   - Retrieve sovereign ledger hash
   - Retrieve DBIS ledger hash
   - Verify both hashes exist and are non-empty
2. Verify ledger entries:
   - Query sovereign ledger entry by hash
   - Query DBIS ledger entry by hash
   - Verify both entries exist
   - Verify entry details match (amount, accounts, etc.)
3. If verification fails:
   - Rollback both ledger entries
   - Mark settlement as failed
   - Throw error

**Code Reference**: `src/core/settlement/isn/atomic-settlement.service.ts:54-58`

### Step 5: Finalize Settlement
1. Calculate settlement time:
   - Start time recorded at Step 1
   - End time = current time
   - Settlement time = end - start
2. Create atomic settlement record:
   - Settlement ID
   - Transaction ID
   - Source and destination bank IDs
   - Amount, currency, asset type
   - Settlement mode: `atomic`
   - Dual-ledger commit: `true`
   - Sovereign ledger hash
   - DBIS ledger hash
   - Settlement time (milliseconds)
   - Status: `settled`
   - Committed and settled timestamps
3. Return settlement result with:
   - Settlement ID
   - Status: `settled`
   - Both ledger hashes
   - Settlement time

**Code Reference**: `src/core/settlement/isn/atomic-settlement.service.ts:60-90`

### Step 6: Error Handling
1. If any step fails:
   - Create failed settlement record
   - Set status: `failed`
   - Set dual-ledger commit: `false`
   - Record error details
2. Rollback any partial ledger entries:
   - If sovereign posted but DBIS failed: rollback sovereign
   - If DBIS posted but verification failed: rollback both
3. Log error for investigation

**Code Reference**: `src/core/settlement/isn/atomic-settlement.service.ts:91-111`

## Error Handling

### Error: Commitment Preparation Failure
- **Detection**: Cannot generate commitment
- **Action**: Return error, terminate flow
- **Recovery**: Verify input parameters, retry

### Error: Sovereign Ledger Post Failure
- **Detection**: Ledger posting fails
- **Action**: Terminate flow, no rollback needed
- **Recovery**: Verify ledger availability, check account status

### Error: DBIS Ledger Post Failure
- **Detection**: DBIS posting fails after sovereign posted
- **Action**: Rollback sovereign ledger entry
- **Recovery**: Retry after verifying DBIS ledger status

### Error: Dual-Commitment Verification Failure
- **Detection**: Hashes don't match or entries missing
- **Action**: Rollback both ledger entries
- **Recovery**: 
  - Investigate ledger integrity
  - Verify hash generation
  - Retry settlement

### Error: Concurrent Modification
- **Detection**: Account balance changed during settlement
- **Action**: Rollback and retry
- **Recovery**: Implement optimistic locking

## Integration Points

### Related Services
- **Atomic Settlement Service**: `src/core/settlement/isn/atomic-settlement.service.ts`
- **Ledger Service**: `src/core/ledger/ledger.service.ts`
- **Account Service**: `src/core/accounts/account.service.ts`
- **GSS Master Ledger**: `src/core/settlement/gss/gss-master-ledger.service.ts`

### API Endpoints
- `POST /api/v1/isn/atomic-settlement/execute` - Execute atomic settlement
- `GET /api/v1/isn/atomic-settlement/:settlementId` - Get settlement status
- `POST /api/v1/isn/atomic-settlement/verify` - Verify dual-commitment

### Database Models
- `AtomicSettlement` - Atomic settlement records
- `LedgerEntry` - Individual ledger entries

## Performance Metrics

- **Commitment Preparation**: < 10ms target
- **Sovereign Ledger Post**: < 50ms target
- **DBIS Ledger Post**: < 50ms target
- **Verification**: < 20ms target
- **Total End-to-End**: < 130ms target
- **Throughput**: 10,000+ atomic settlements/second
- **Availability**: 99.99% uptime target

## Security Considerations

### Atomicity Guarantee
- Dual-commitment ensures both ledgers update or neither
- Rollback mechanism prevents partial state
- Verification step ensures consistency

### Data Integrity
- Hash verification prevents tampering
- Dual-ledger hashes provide proof
- Settlement records provide audit trail

### Concurrency Control
- Account locking during settlement
- Optimistic locking for balance checks
- Transaction isolation

## Testing Scenarios

### Happy Path
1. Valid settlement request
2. Successful commitment preparation
3. Successful sovereign ledger post
4. Successful DBIS ledger post
5. Verification passes
6. Settlement finalized

### Error Scenarios
1. Commitment preparation failure
2. Sovereign ledger post failure
3. DBIS ledger post failure
4. Verification failure
5. Concurrent modification

### Edge Cases
1. Maximum settlement amount
2. Minimum settlement amount
3. Same bank source and destination
4. Cross-currency settlement
5. Network partition during settlement

---

**Related Flows**:
- [GSS Settlement Flow](./gss-settlement-flow.md)
- [Cross-Chain Settlement Flow](./cross-chain-settlement-flow.md)
- [M-RTGS Settlement Flow](./m-rtgs-settlement-flow.md)

