# GSS Settlement Flow

## Overview

The Global Settlement System (GSS) implements a four-layer architecture for sovereign-grade settlement: Layer 1 (Sovereign), Layer 2 (DBIS Master), Layer 3 (Smart Clearing Fabric), and Layer 4 (Finality & Irreversibility). This flow documents the dual-ledger synchronization process.

## Prerequisites

- Source and destination banks are registered SCBs
- Valid sovereign settlement node (SSN) configuration
- Source and destination accounts exist
- Sufficient balance in source account
- Sovereign signature available (if required)

## Visual Flow Diagram

```
┌─────────────┐
│ Settlement  │
│  Request    │
└──────┬──────┘
       │
       │ 1. Settlement Entry
       ▼
┌─────────────────────────┐
│ Layer 1: Sovereign      │
│ Ledger Posting          │
│  - Account lookup        │
│  - Debit/Credit entries  │
│  - Generate hash         │
└──────┬──────────────────┘
       │
       │ 2. Sovereign Hash
       ▼
┌─────────────────────────┐
│ Layer 2: DBIS Master    │
│ Ledger Posting          │
│  - Master ledger entry  │
│  - Generate hash         │
└──────┬──────────────────┘
       │
       │ 3. DBIS Hash
       ▼
┌─────────────────────────┐
│ Layer 3: Signature      │
│ Validation (if provided) │
│  - HSM verification      │
│  - Identity check        │
└──────┬──────────────────┘
       │
       │ 4. Validated
       ▼
┌─────────────────────────┐
│ Layer 4: Master Entry   │
│ Creation                 │
│  - Dual-ledger commit   │
│  - Status: settled       │
└──────┬──────────────────┘
       │
       │ 5. Finality
       ▼
┌─────────────┐
│ Settlement  │
│  Complete   │
└─────────────┘
```

## Step-by-Step Process

### Step 1: Settlement Entry Creation
1. Receive settlement request with:
   - Source bank ID
   - Destination bank ID
   - Amount and currency
   - Asset type
   - Optional sovereign signature
2. Generate unique entry ID: `GSS-ENTRY-{uuid}`
3. Validate node configuration for source bank
4. Verify both banks are active SCBs

**Code Reference**: `src/core/settlement/gss/gss-master-ledger.service.ts:35-38`

### Step 2: Layer 1 - Sovereign Ledger Posting
1. Lookup source accounts:
   - Filter by sovereign bank ID
   - Match currency code and asset type
   - Select active account
2. Lookup destination accounts:
   - Filter by sovereign bank ID
   - Match currency code and asset type
   - Select active account
3. Post double-entry to sovereign ledger:
   - Debit source account
   - Credit destination account
   - Use ledger ID: `Sovereign_{sourceBankId}`
   - Transaction type: `Type_A`
4. Retrieve ledger entry and extract block hash
5. Store sovereign ledger hash

**Code Reference**: `src/core/settlement/gss/gss-master-ledger.service.ts:101-150`

### Step 3: Layer 2 - DBIS Master Ledger Posting
1. Lookup source accounts (same as Step 2)
2. Lookup destination accounts (same as Step 2)
3. Post double-entry to DBIS master ledger:
   - Debit source account
   - Credit destination account
   - Use ledger ID: `Master`
   - Transaction type: `Type_A`
   - Metadata: `{ gssEntry: true, masterLedger: true }`
4. Retrieve ledger entry and extract block hash
5. Store DBIS ledger hash

**Code Reference**: `src/core/settlement/gss/gss-master-ledger.service.ts:155-203`

### Step 4: Layer 3 - Sovereign Signature Validation (if provided)
1. Check if sovereign signature is provided
2. If provided:
   - Lookup sovereign identity by bank ID
   - Verify identity type is 'Settlement'
   - Validate signature using HSM (in production)
   - Verify signature matches entry data
3. If validation fails, throw error and rollback

**Code Reference**: `src/core/settlement/gss/gss-master-ledger.service.ts:208-232`

### Step 5: Layer 4 - Master Entry Creation & Finality
1. Create GSS master ledger entry with:
   - Entry ID
   - Node ID
   - Source and destination bank IDs
   - Amount, currency, asset type
   - Sovereign signature (if provided)
   - Dual-ledger commit flag: `true`
   - Sovereign ledger hash
   - DBIS ledger hash
   - Status: `settled`
   - Committed and settled timestamps
2. Verify dual-ledger synchronization:
   - Both hashes exist
   - Both ledger entries exist
   - Dual-commit flag is true
3. Return dual-ledger result

**Code Reference**: `src/core/settlement/gss/gss-master-ledger.service.ts:52-77`

### Step 6: Error Handling (if any step fails)
1. If error occurs after Step 1:
   - Create failed entry record
   - Set dual-ledger commit: `false`
   - Set status: `failed`
   - Log error details
2. Rollback any partial ledger entries
3. Throw error to caller

**Code Reference**: `src/core/settlement/gss/gss-master-ledger.service.ts:78-95`

## Error Handling

### Error: Accounts Not Found
- **Detection**: Account lookup returns empty array
- **Action**: Throw error "Accounts not found for sovereign ledger posting"
- **Recovery**: Verify account configuration, retry with correct parameters

### Error: Sovereign Signature Invalid
- **Detection**: Signature validation fails
- **Action**: Throw error "Sovereign identity not found" or "Signature invalid"
- **Recovery**: Request new signature, verify HSM configuration

### Error: Dual-Ledger Mismatch
- **Detection**: Hashes don't match or entries missing
- **Action**: Mark entry as failed, create reconciliation record
- **Recovery**: Manual reconciliation process, verify ledger integrity

### Error: Node Configuration Missing
- **Detection**: SSN not configured for source bank
- **Action**: Return error, prevent settlement
- **Recovery**: Configure SSN, retry settlement

## Integration Points

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

### API Endpoints
- `POST /api/v1/gss/settlement/execute` - Execute GSS settlement
- `GET /api/v1/gss/master-ledger/entries` - Query master ledger entries
- `GET /api/v1/gss/master-ledger/entries/:entryId` - Get specific entry
- `POST /api/v1/gss/master-ledger/verify` - Verify dual-ledger sync

### Database Models
- `GssMasterLedger` - Master ledger entries
- `SovereignSettlementNode` - SSN configuration
- `LedgerEntry` - Individual ledger entries

## Performance Metrics

- **Layer 1 (Sovereign Posting)**: < 100ms target
- **Layer 2 (DBIS Posting)**: < 100ms target
- **Layer 3 (Signature Validation)**: < 50ms target (if required)
- **Layer 4 (Master Entry)**: < 50ms target
- **Total End-to-End**: < 300ms target
- **Throughput**: 5,000+ settlements/second
- **Availability**: 99.99% uptime target

## Security Considerations

### Authentication
- Sovereign bank must be registered and active
- Node ID must match configured SSN

### Authorization
- Source bank must have settlement permissions
- Accounts must be active and accessible

### Data Integrity
- Dual-ledger commit ensures consistency
- Hash verification prevents tampering
- Sovereign signatures provide non-repudiation

### Audit Trail
- All entries logged with timestamps
- Dual-ledger hashes provide proof
- Failed entries tracked for reconciliation

## Testing Scenarios

### Happy Path
1. Valid settlement request
2. Successful sovereign ledger posting
3. Successful DBIS master ledger posting
4. Valid sovereign signature (if provided)
5. Successful master entry creation
6. Dual-ledger verification passes

### Error Scenarios
1. Accounts not found
2. Sovereign signature invalid
3. Dual-ledger mismatch
4. Node configuration missing
5. Network timeout during posting

### Edge Cases
1. Concurrent settlements to same account
2. Maximum settlement amount
3. Settlement with missing signature
4. Settlement during ledger maintenance
5. Cross-currency settlements

---

**Related Flows**:
- [GPN Payment Flow](./gpn-payment-flow.md)
- [Atomic Settlement Flow](./atomic-settlement-flow.md)
- [M-RTGS Settlement Flow](./m-rtgs-settlement-flow.md)

