# Deployment Guide - Complete System

**Date**: Deployment Guide  
**Status**: ✅ READY

---

## Overview

This guide provides step-by-step instructions for deploying the complete system:
1. Vault System
2. ISO-4217 W Token System
3. Bridge Integrations

---

## Prerequisites

### Environment Setup

1. **Node.js & Foundry**
   ```bash
   # Install Foundry
   curl -L https://foundry.paradigm.xyz | bash
   foundryup
   ```

2. **Environment Variables**
   ```bash
   export PRIVATE_KEY=<your_private_key>
   export RPC_URL=<chain_138_rpc_url>
   export ADMIN_ADDRESS=<admin_address>
   ```

3. **OpenZeppelin Contracts**
   ```bash
   forge install OpenZeppelin/openzeppelin-contracts
   forge install OpenZeppelin/openzeppelin-contracts-upgradeable
   ```

---

## Deployment Order

### Phase 1: Core Systems

#### Step 1.1: Deploy Vault System

```bash
forge script script/vault/DeployVaultSystem.s.sol:DeployVaultSystem \
  --rpc-url $RPC_URL \
  --broadcast \
  --verify \
  -vvvv
```

**Output**:
- `RegulatedEntityRegistry`: `<address>`
- `XAUOracle`: `<address>`
- `RateAccrual`: `<address>`
- `Ledger`: `<address>`
- `CollateralAdapter`: `<address>`
- `eMoneyJoin`: `<address>`
- `VaultFactory`: `<address>`

**Post-Deployment**:
1. Add price feeds to XAUOracle
2. Set interest rates in RateAccrual
3. Register entities in RegulatedEntityRegistry
4. Approve currencies in eMoneyJoin

#### Step 1.2: Deploy ISO-4217 W Token System

```bash
forge script script/iso4217w/DeployWTokenSystem.s.sol:DeployWTokenSystem \
  --rpc-url $RPC_URL \
  --broadcast \
  --verify \
  -vvvv
```

**Output**:
- `ComplianceGuard`: `<address>`
- `ReserveOracle`: `<address>`
- `MintController`: `<address>`
- `BurnController`: `<address>`
- `TokenRegistry`: `<address>`
- `TokenFactory`: `<address>`

**Post-Deployment**:
1. Add oracles to ReserveOracle
2. Configure custodian addresses
3. Deploy W tokens (USDW, EURW, GBPW) via TokenFactory

---

### Phase 2: Bridge System

#### Step 2.1: Deploy Bridge Contracts (if not already deployed)

```bash
# Deploy BridgeRegistry
forge script script/bridge/DeployBridgeRegistry.s.sol:DeployBridgeRegistry \
  --rpc-url $RPC_URL \
  --broadcast \
  --verify

# Deploy BridgeEscrowVault
forge script script/bridge/DeployBridgeEscrowVault.s.sol:DeployBridgeEscrowVault \
  --rpc-url $RPC_URL \
  --broadcast \
  --verify
```

#### Step 2.2: Deploy Bridge Integrations

```bash
# Set environment variables
export BRIDGE_REGISTRY=<bridge_registry_address>
export BRIDGE_ESCROW_VAULT=<bridge_escrow_vault_address>
export VAULT_FACTORY=<vault_factory_address>
export TOKEN_FACTORY=<token_factory_address>
export W_TOKEN_REGISTRY=<token_registry_address>
export RESERVE_ORACLE=<reserve_oracle_address>
export COMPLIANCE_GUARD=<compliance_guard_address>
export POLICY_MANAGER=<policy_manager_address>
export EMONEY_COMPLIANCE_REGISTRY=<emoney_compliance_registry_address>

# Deploy integrations
forge script script/bridge/DeployBridgeIntegrations.s.sol:DeployBridgeIntegrations \
  --rpc-url $RPC_URL \
  --broadcast \
  --verify \
  -vvvv
```

**Output**:
- `VaultBridgeIntegration`: `<address>`
- `WTokenBridgeIntegration`: `<address>`
- `eMoneyBridgeIntegration`: `<address>`
- `WTokenReserveVerifier`: `<address>`
- `WTokenComplianceEnforcer`: `<address>`
- `eMoneyPolicyEnforcer`: `<address>`

---

### Phase 3: Configuration

#### Step 3.1: Configure Bridge Registry

```solidity
// Grant REGISTRAR_ROLE to integration contracts
bridgeRegistry.grantRole(keccak256("REGISTRAR_ROLE"), vaultBridgeIntegration);
bridgeRegistry.grantRole(keccak256("REGISTRAR_ROLE"), wTokenBridgeIntegration);
bridgeRegistry.grantRole(keccak256("REGISTRAR_ROLE"), eMoneyBridgeIntegration);
```

#### Step 3.2: Register Bridge Destinations

```solidity
// Register EVM destinations
bridgeRegistry.registerDestination(
    137,  // Polygon
    "Polygon",
    10,   // minFinalityBlocks
    3600, // timeoutSeconds (1 hour)
    10,   // baseFee (0.1% in bps)
    feeRecipient
);

// Register XRPL (non-EVM, chainId = 0)
bridgeRegistry.registerDestination(
    0,    // XRPL
    "XRPL",
    1,    // minFinalityLedgers
    3600, // timeoutSeconds
    5,    // baseFee (0.05% in bps)
    feeRecipient
);
```

#### Step 3.3: Register Tokens with Bridge

```solidity
// Register vault deposit tokens
vaultBridgeIntegration.registerDepositTokenDefault(depositToken);

// Register W tokens
wTokenBridgeIntegration.registerWTokenDefault("USD");
wTokenBridgeIntegration.registerWTokenDefault("EUR");
wTokenBridgeIntegration.registerWTokenDefault("GBP");

// Register eMoney tokens
eMoneyBridgeIntegration.registereMoneyTokenDefault(eMoneyToken, "USDC");
```

#### Step 3.4: Configure Verifiers

```solidity
// Register W tokens in Reserve Verifier
wTokenReserveVerifier.registerToken(usdwToken);
wTokenReserveVerifier.registerToken(eurwToken);

// Enable W tokens in Compliance Enforcer
wTokenComplianceEnforcer.enableToken(usdwToken);
wTokenComplianceEnforcer.enableToken(eurwToken);

// Enable eMoney tokens in Policy Enforcer
eMoneyPolicyEnforcer.enableToken(eMoneyToken);
```

---

## Deployment Verification

### Step 1: Verify Contracts on Explorer

1. Check all contracts on Blockscout/Etherscan
2. Verify source code
3. Verify constructor parameters
4. Check initial state

### Step 2: Run Tests

```bash
# Run all tests
forge test --rpc-url $RPC_URL -vv

# Run specific test suites
forge test --match-path test/vault/** -vv
forge test --match-path test/iso4217w/** -vv
forge test --match-path test/bridge/** -vv
```

### Step 3: Functional Tests

```solidity
// Test vault creation
vaultFactory.createVault(owner, entity, asset, currency);

// Test W token deployment
tokenFactory.deployToken("USD", "USDW Token", "USDW", 2, custodian);

// Test bridge registration
vaultBridgeIntegration.registerDepositTokenDefault(depositToken);
```

---

## Configuration Parameters

### Vault System

| Parameter | Value | Description |
|-----------|-------|-------------|
| Debt Ceiling | 1,000,000 ETH | Maximum debt per asset |
| Liquidation Ratio | 110% | Collateralization threshold |
| Credit Multiplier | 5x | Maximum credit against collateral |
| Interest Rate | 5% | Annual interest rate |

### ISO-4217 W Token System

| Parameter | Value | Description |
|-----------|-------|-------------|
| Reserve Threshold | 100% | Must be fully backed (m = 1.0) |
| Oracle Staleness | 1 hour | Maximum report age |
| Quorum Size | 3 | Number of oracles required |
| Min Bridge Amount | 100 USD | Minimum bridge amount |
| Max Bridge Amount | 10M USD | Maximum bridge amount |

### Bridge System

| Parameter | Value | Description |
|-----------|-------|-------------|
| Base Fee | 0.1% | Default bridge fee |
| Timeout | 1 hour | Refund eligibility timeout |
| Min Finality Blocks | 10 | Minimum confirmation blocks |

---

## Troubleshooting

### Issue: Compilation Errors

**Solution**:
```bash
# Clean and rebuild
forge clean
forge build

# Install dependencies
forge install OpenZeppelin/openzeppelin-contracts
```

### Issue: Deployment Fails

**Solution**:
1. Check RPC URL is correct
2. Verify private key has sufficient balance
3. Check gas limits
4. Verify contract addresses exist

### Issue: Bridge Registration Fails

**Solution**:
1. Verify REGISTRAR_ROLE is granted
2. Check token addresses are valid
3. Verify destination chain IDs exist
4. Check fee values are within bounds (0-10000 bps)

---

## Security Checklist

- [ ] All contracts verified on explorer
- [ ] Admin keys stored securely
- [ ] Multi-sig configured for admin operations
- [ ] Emergency pause functions tested
- [ ] Access control roles properly configured
- [ ] Reserve verification tested
- [ ] Compliance checks tested
- [ ] Bridge integrations tested

---

## Post-Deployment

### Monitoring Setup

1. Set up monitoring for:
   - Contract events
   - Reserve levels
   - Bridge operations
   - Health ratios

2. Configure alerts:
   - Reserve < Supply (W tokens)
   - Health ratio < 110% (vaults)
   - Bridge failures
   - Compliance violations

### Documentation

1. Document all contract addresses
2. Create operational runbooks
3. Document emergency procedures
4. Create user guides

---

## Next Steps

1. ✅ Verify all deployments
2. ✅ Run comprehensive tests
3. ✅ Set up monitoring
4. ✅ Create runbooks
5. ✅ Conduct security audit
6. ✅ Production rollout

---

**Last Updated**: Deployment Guide Complete
