# API Documentation - Complete System

**Date**: API Documentation  
**Status**: ✅ COMPLETE

---

## Overview

This document provides complete API documentation for:
1. Vault System
2. ISO-4217 W Token System
3. Bridge Integrations

---

## 1. Vault System API

### 1.1 Ledger Contract

#### `modifyCollateral(address vault, address asset, int256 delta)`

**Description**: Modify collateral balance for a vault

**Parameters**:
- `vault`: Vault address
- `asset`: Collateral asset address (address(0) for ETH)
- `delta`: Amount change (positive to add, negative to remove)

**Requirements**:
- Caller must have `VAULT_ROLE`
- Asset must be registered
- Collateral cannot go negative

**Events**:
- `CollateralModified(address indexed vault, address indexed asset, int256 delta)`

---

#### `modifyDebt(address vault, address currency, int256 delta)`

**Description**: Modify debt balance for a vault (accrues interest automatically)

**Parameters**:
- `vault`: Vault address
- `currency`: Debt currency address
- `delta`: Amount change (positive to add debt, negative to repay)

**Requirements**:
- Caller must have `VAULT_ROLE`
- Interest is accrued before modification

**Events**:
- `DebtModified(address indexed vault, address indexed currency, int256 delta)`

---

#### `getVaultHealth(address vault)`

**Description**: Get vault health ratio, collateral value, and debt value

**Returns**:
- `healthRatio`: Health ratio (in basis points, max = type(uint256).max if no debt)
- `collateralValue`: Total collateral value in XAU
- `debtValue`: Total debt value in XAU

**View Function**: Yes

---

#### `canBorrow(address vault, address currency, uint256 amount)`

**Description**: Check if vault can borrow specified amount

**Returns**:
- `canBorrow`: True if borrow is allowed
- `reasonCode`: Reason code if borrow not allowed (bytes32(0) if allowed)

**View Function**: Yes

**Reason Codes**:
- `keccak256("DEBT_CEILING_EXCEEDED")`: Debt ceiling would be exceeded
- `keccak256("INSUFFICIENT_COLLATERAL")`: Insufficient collateral
- `keccak256("HEALTH_RATIO_TOO_LOW")`: Health ratio too low

---

#### `setRiskParameters(address asset, uint256 debtCeiling, uint256 liquidationRatio, uint256 creditMultiplier)`

**Description**: Set risk parameters for an asset

**Parameters**:
- `asset`: Asset address
- `debtCeiling`: Maximum debt for this asset (in asset decimals)
- `liquidationRatio`: Liquidation threshold (in basis points, e.g., 11000 = 110%)
- `creditMultiplier`: Credit multiplier (in basis points, e.g., 50000 = 5x)

**Requirements**:
- Caller must have `DEFAULT_ADMIN_ROLE`
- `liquidationRatio` <= 10000 (100%)
- `creditMultiplier` <= 100000 (10x)

---

### 1.2 Vault Contract

#### `deposit(address asset, uint256 amount)`

**Description**: Deposit collateral into vault

**Parameters**:
- `asset`: Collateral asset address
- `amount`: Amount to deposit

**Requirements**:
- Caller must be authorized (owner or operator)
- For ETH: Send native ETH with transaction
- For ERC20: Approve token first

**Events**:
- `Deposited(address indexed user, address indexed asset, uint256 amount)`

---

#### `withdraw(address asset, uint256 amount)`

**Description**: Withdraw collateral from vault

**Parameters**:
- `asset`: Collateral asset address
- `amount`: Amount to withdraw

**Requirements**:
- Caller must be authorized
- Vault must remain healthy after withdrawal

**Events**:
- `Withdrawn(address indexed user, address indexed asset, uint256 amount)`

---

#### `borrow(address currency, uint256 amount)`

**Description**: Borrow eMoney against collateral

**Parameters**:
- `currency`: eMoney currency address
- `amount`: Amount to borrow

**Requirements**:
- Vault must be healthy
- Debt ceiling not exceeded
- Sufficient collateral

**Events**:
- `Borrowed(address indexed user, address indexed currency, uint256 amount)`

---

#### `repay(address currency, uint256 amount)`

**Description**: Repay eMoney debt

**Parameters**:
- `currency`: eMoney currency address
- `amount`: Amount to repay

**Requirements**:
- Must have sufficient debt
- eMoney tokens must be approved

**Events**:
- `Repaid(address indexed user, address indexed currency, uint256 amount)`

---

#### `getHealth()`

**Description**: Get vault health information

**Returns**:
- `healthRatio`: Health ratio (in basis points)
- `collateralValue`: Collateral value in XAU
- `debtValue`: Debt value in XAU

**View Function**: Yes

---

### 1.3 VaultFactory Contract

#### `createVault(address owner, address entity, address asset, address currency)`

**Description**: Create a new vault with deposit and debt tokens

**Parameters**:
- `owner`: Vault owner address
- `entity`: Regulated entity address
- `asset`: Collateral asset address
- `currency`: eMoney currency address

**Returns**:
- `vault`: Address of created vault
- `depositToken`: Address of deposit token
- `debtToken`: Address of debt token

**Requirements**:
- Caller must have `VAULT_DEPLOYER_ROLE`
- `owner` and `entity` must not be zero address

**Events**:
- `VaultCreated(address indexed vault, address indexed entity, address indexed owner, address depositToken, address debtToken)`

---

## 2. ISO-4217 W Token System API

### 2.1 ISO4217WToken Contract

#### `mint(address to, uint256 amount)`

**Description**: Mint W tokens (1:1 with fiat reserve)

**Parameters**:
- `to`: Recipient address
- `amount`: Amount to mint (in token decimals)

**Requirements**:
- Caller must have `MINTER_ROLE`
- Reserve must be >= (Supply + Amount)
- Money multiplier = 1.0 enforced

**Events**:
- `Minted(address indexed to, uint256 amount, string indexed currencyCode)`

---

#### `burn(address from, uint256 amount)`

**Description**: Burn W tokens (on redemption)

**Parameters**:
- `from`: Source address
- `amount`: Amount to burn

**Requirements**:
- Caller must have `BURNER_ROLE`
- `from` must have sufficient balance

**Events**:
- `Burned(address indexed from, uint256 amount, string indexed currencyCode)`

---

#### `updateVerifiedReserve(uint256 reserveBalance)`

**Description**: Update verified reserve balance

**Parameters**:
- `reserveBalance`: Reserve balance (in base currency units)

**Requirements**:
- Caller must have `RESERVE_UPDATE_ROLE`
- Reserve should be >= Supply (warning emitted if not)

**Events**:
- `ReserveUpdated(uint256 reserveBalance, uint256 totalSupply)`

---

#### `isReserveSufficient()`

**Description**: Check if reserve is sufficient (>= supply)

**Returns**: True if reserve >= supply

**View Function**: Yes

---

#### `currencyCode()`

**Description**: Get ISO-4217 currency code (e.g., "USD")

**Returns**: 3-letter currency code

**View Function**: Yes

---

#### `verifiedReserve()`

**Description**: Get verified reserve balance

**Returns**: Reserve balance (in base currency units)

**View Function**: Yes

---

### 2.2 MintController Contract

#### `mint(address token, address to, uint256 amount, bytes32 settlementId, address custodian)`

**Description**: Mint W tokens with reserve verification

**Parameters**:
- `token`: W token address
- `to`: Recipient address
- `amount`: Amount to mint
- `settlementId`: Fiat settlement ID
- `custodian`: Custodian address

**Requirements**:
- Caller must have `MINTER_ROLE`
- Reserve must be sufficient (verified via oracle)
- Oracle quorum must be met
- Compliance checks must pass

**Events**:
- `Minted(address indexed token, address indexed to, uint256 amount, bytes32 settlementId)`

---

#### `canMint(address token, uint256 amount)`

**Description**: Check if minting is allowed

**Returns**: True if minting is allowed

**View Function**: Yes

**Checks**:
- Reserve sufficiency
- Oracle quorum
- Compliance validation

---

### 2.3 BurnController Contract

#### `redeem(address token, address from, uint256 amount)`

**Description**: Redeem W tokens (burn and release fiat)

**Parameters**:
- `token`: W token address
- `from`: Redeemer address
- `amount`: Amount to redeem

**Returns**: Redemption ID for tracking

**Requirements**:
- Caller must have `REDEEMER_ROLE`
- Token must be approved
- Redemption must be allowed

**Events**:
- `Redeemed(address indexed token, address indexed from, uint256 amount, bytes32 redemptionId)`

---

#### `canRedeem(address token, uint256 amount)`

**Description**: Check if redemption is allowed

**Returns**: True if redemption is allowed

**View Function**: Yes

---

### 2.4 ReserveOracle Contract

#### `submitReserveReport(address token, uint256 reserveBalance, uint256 timestamp)`

**Description**: Submit reserve report (oracle only)

**Parameters**:
- `token`: W token address
- `reserveBalance`: Reserve balance
- `timestamp`: Report timestamp

**Requirements**:
- Caller must have `ORACLE_ROLE`

**Events**:
- `ReserveReportSubmitted(address indexed token, address indexed oracle, uint256 reserveBalance, uint256 timestamp)`

---

#### `getVerifiedReserve(address token)`

**Description**: Get verified reserve balance (consensus)

**Returns**: Consensus reserve balance

**View Function**: Yes

**Note**: Requires quorum

---

#### `isQuorumMet(address token)`

**Description**: Check if oracle quorum is met

**Returns**: True if quorum met

**View Function**: Yes

---

## 3. Bridge Integration API

### 3.1 VaultBridgeIntegration Contract

#### `registerDepositToken(address depositToken, uint256[] destinationChainIds, uint256 minAmount, uint256 maxAmount, uint8 riskLevel, uint256 bridgeFeeBps)`

**Description**: Register vault deposit token with bridge

**Parameters**:
- `depositToken`: Deposit token address
- `destinationChainIds`: Array of allowed destination chain IDs
- `minAmount`: Minimum bridge amount
- `maxAmount`: Maximum bridge amount
- `riskLevel`: Risk level (0-255)
- `bridgeFeeBps`: Bridge fee in basis points

**Requirements**:
- Caller must have `INTEGRATOR_ROLE`

**Events**:
- `DepositTokenRegistered(address indexed depositToken, address indexed vault, uint256[] destinationChainIds)`

---

#### `registerDepositTokenDefault(address depositToken)`

**Description**: Register deposit token with default configuration

**Parameters**:
- `depositToken`: Deposit token address

**Requirements**:
- Caller must have `INTEGRATOR_ROLE`

---

### 3.2 WTokenBridgeIntegration Contract

#### `registerWToken(string currencyCode, uint256[] destinationChainIds, uint256 minAmount, uint256 maxAmount, uint8 riskLevel, uint256 bridgeFeeBps)`

**Description**: Register W token with bridge

**Parameters**:
- `currencyCode`: ISO-4217 currency code (e.g., "USD")
- `destinationChainIds`: Array of allowed destination chain IDs
- `minAmount`: Minimum bridge amount
- `maxAmount`: Maximum bridge amount
- `riskLevel`: Risk level (0-255)
- `bridgeFeeBps`: Bridge fee in basis points

**Requirements**:
- Caller must have `INTEGRATOR_ROLE`
- Token must exist in TokenRegistry

**Events**:
- `WTokenRegistered(address indexed token, string indexed currencyCode, uint256[] destinationChainIds)`

---

#### `registerWTokenDefault(string currencyCode)`

**Description**: Register W token with default configuration

**Parameters**:
- `currencyCode`: ISO-4217 currency code

**Requirements**:
- Caller must have `INTEGRATOR_ROLE`

---

### 3.3 WTokenReserveVerifier Contract

#### `verifyReserveBeforeBridge(address token, uint256 bridgeAmount)`

**Description**: Verify reserve before bridge operation

**Parameters**:
- `token`: W token address
- `bridgeAmount`: Amount to bridge

**Returns**: True if reserve is sufficient

**View Function**: Yes

**Checks**:
- Reserve >= (Supply - BridgeAmount) * 100%

**Reverts**: If reserve insufficient

---

#### `registerToken(address token)`

**Description**: Register W token for reserve verification

**Parameters**:
- `token`: W token address

**Requirements**:
- Caller must have `OPERATOR_ROLE`
- Token must implement IISO4217WToken

**Events**:
- `TokenVerified(address indexed token, bool verified)`

---

### 3.4 WTokenComplianceEnforcer Contract

#### `checkComplianceBeforeBridge(address token, uint256 bridgeAmount)`

**Description**: Check compliance before bridge operation

**Parameters**:
- `token`: W token address
- `bridgeAmount`: Amount to bridge

**Returns**: True if compliant

**View Function**: Yes

**Checks**:
- Money multiplier = 1.0
- GRU isolation
- ISO-4217 validation

**Reverts**: If compliance violation

**Events**:
- `ComplianceChecked(address indexed token, bytes32 reasonCode, bool compliant)`

---

### 3.5 eMoneyPolicyEnforcer Contract

#### `checkTransferAuthorization(address token, address from, address to, uint256 amount)`

**Description**: Check if transfer is authorized

**Parameters**:
- `token`: eMoney token address
- `from`: Source address
- `to`: Destination address
- `amount`: Transfer amount

**Returns**: True if authorized

**View Function**: Yes

**Checks**:
- PolicyManager authorization
- ComplianceRegistry restrictions

**Reverts**: If not authorized

**Events**:
- `TransferAuthorized(address indexed token, address indexed from, address indexed to, uint256 amount, bool authorized)`

---

## 4. Error Codes

### Vault System Errors

| Error Code | Description |
|------------|-------------|
| `Ledger: asset not registered` | Asset not registered in ledger |
| `Ledger: insufficient collateral` | Attempting to withdraw more than available |
| `Ledger: invalid liquidation ratio` | Liquidation ratio > 100% |
| `Ledger: invalid credit multiplier` | Credit multiplier > 10x |
| `Ledger: debt ceiling exceeded` | Borrowing would exceed debt ceiling |
| `Vault: not authorized` | Caller not authorized to use vault |
| `Vault: insufficient collateral` | Not enough collateral for operation |

### ISO-4217 W Token Errors

| Error Code | Description |
|------------|-------------|
| `ISO4217WToken: reserve insufficient - money multiplier violation` | Reserve < Supply (m < 1.0) |
| `MintController: reserve insufficient` | Reserve not sufficient for mint |
| `MintController: oracle quorum not met` | Oracle quorum not met |
| `MintController: compliance violation` | Compliance check failed |
| `BurnController: token not approved` | Token not approved for redemption |
| `BurnController: redemption not allowed` | Redemption not allowed |

### Bridge Integration Errors

| Error Code | Description |
|------------|-------------|
| `WTokenReserveVerifier: insufficient reserve` | Reserve insufficient for bridge |
| `WTokenComplianceEnforcer: compliance violation` | Compliance check failed |
| `eMoneyPolicyEnforcer: transfer not authorized` | Transfer not authorized by policy |

---

## 5. Events Reference

### Vault System Events

```solidity
event CollateralModified(address indexed vault, address indexed asset, int256 delta);
event DebtModified(address indexed vault, address indexed currency, int256 delta);
event VaultCreated(address indexed vault, address indexed entity, address indexed owner, address depositToken, address debtToken);
event Deposited(address indexed user, address indexed asset, uint256 amount);
event Borrowed(address indexed user, address indexed currency, uint256 amount);
```

### ISO-4217 W Token Events

```solidity
event Minted(address indexed to, uint256 amount, string indexed currencyCode);
event Burned(address indexed from, uint256 amount, string indexed currencyCode);
event ReserveUpdated(uint256 reserveBalance, uint256 totalSupply);
event Redeemed(address indexed token, address indexed from, uint256 amount, bytes32 redemptionId);
```

### Bridge Integration Events

```solidity
event DepositTokenRegistered(address indexed depositToken, address indexed vault, uint256[] destinationChainIds);
event WTokenRegistered(address indexed token, string indexed currencyCode, uint256[] destinationChainIds);
event ReserveVerified(address indexed token, uint256 reserve, uint256 supply, uint256 bridgeAmount, bool sufficient);
event ComplianceChecked(address indexed token, bytes32 reasonCode, bool compliant);
event TransferAuthorized(address indexed token, address indexed from, address indexed to, uint256 amount, bool authorized);
```

---

## 6. Usage Examples

### Example 1: Create Vault and Deposit Collateral

```solidity
// 1. Create vault via factory
(address vault, , ) = vaultFactory.createVault(owner, entity, eth, usdc);

// 2. Deposit ETH collateral
vault.deposit{value: 10 ether}(address(0), 10 ether);
```

### Example 2: Borrow eMoney

```solidity
// Borrow 1000 USDC against collateral
vault.borrow(usdcToken, 1000e6);
```

### Example 3: Deploy and Mint USDW

```solidity
// 1. Deploy USDW via factory
address usdw = tokenFactory.deployToken("USD", "USDW Token", "USDW", 2, custodian);

// 2. Update reserve
iso4217wToken(usdw).updateVerifiedReserve(10000e2); // 10,000 USD reserve

// 3. Mint USDW
mintController.mint(usdw, user, 1000e2, settlementId, custodian);
```

### Example 4: Bridge W Token

```solidity
// 1. Verify reserve
wTokenReserveVerifier.verifyReserveBeforeBridge(usdw, 1000e2);

// 2. Check compliance
wTokenComplianceEnforcer.checkComplianceBeforeBridge(usdw, 1000e2);

// 3. Bridge
bridgeEscrowVault.deposit(usdw, 1000e2, DestinationType.EVM, destinationData);
```

---

**Last Updated**: API Documentation Complete
