# eMoney Token Factory Integration Guide

**Date**: 2025-01-27
**Status**: ✅ **INTEGRATED**

---

## Overview

The eMoney Token Factory system has been successfully integrated into the DeFi Oracle Meta Mainnet (ChainID 138). This guide provides comprehensive documentation for using, deploying, and managing the eMoney token system.

## Architecture

### Core Components

1. **TokenFactory138** - Factory contract for deploying new eMoney tokens
2. **eMoneyToken** - UUPS upgradeable ERC-20 token with policy-controlled transfers
3. **PolicyManager** - Central rule engine for transfer authorization
4. **DebtRegistry** - Manages liens on accounts
5. **ComplianceRegistry** - Tracks account compliance status
6. **BridgeVault138** - Cross-chain bridge vault with light client verification

### Contract Locations

- **Contracts**: `contracts/emoney/`
- **Tests**: `test/emoney/`
- **Deployment Scripts**: `script/emoney/`

## Dependencies

### OpenZeppelin Contracts
- **Version**: v5.0.0
- **Upgradeable Contracts**: v5.0.0
- **Location**: `lib/openzeppelin-contracts/` and `lib/openzeppelin-contracts-upgradeable/`

### Solidity Version
- **Version**: 0.8.20
- **Configuration**: Updated in `foundry.toml`

### Remappings

```toml
@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/
@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/
forge-std/=lib/forge-std/src/
```

## Deployment

### Prerequisites

1. **Environment Variables**:
   ```bash
   export PRIVATE_KEY=<deployer_private_key>
   export RPC_URL=<chain138_rpc_url>
   export GOVERNANCE_MULTISIG=<multisig_address>
   export TOKEN_DEPLOYER_MULTISIG=<multisig_address>
   export POLICY_OPERATOR_MULTISIG=<multisig_address>
   export COMPLIANCE_OPERATOR_MULTISIG=<multisig_address>
   export DEBT_AUTHORITY_MULTISIG=<multisig_address>
   export ENFORCEMENT_OPERATOR_MULTISIG=<multisig_address>
   export BRIDGE_OPERATOR_MULTISIG=<multisig_address>
   ```

2. **Network Configuration**:
   - ChainID: 138
   - Network: DeFi Oracle Meta Mainnet

### Deployment Steps

#### Step 1: Deploy Core Infrastructure

```bash
cd /home/intlc/projects/smom-dbis-138
forge script script/emoney/Deploy.s.sol:DeployScript \
  --rpc-url $RPC_URL \
  --broadcast \
  --verify
```

This deploys:
- ComplianceRegistry
- DebtRegistry
- PolicyManager
- eMoneyToken implementation
- TokenFactory138
- BridgeVault138 (optional)

#### Step 2: Configure System

```bash
forge script script/emoney/Configure.s.sol:ConfigureScript \
  --rpc-url $RPC_URL \
  --broadcast
```

#### Step 3: Verify Deployment

```bash
forge script script/emoney/VerifyDeployment.s.sol:VerifyDeployment \
  --rpc-url $RPC_URL
```

### Deploying a New Token

```bash
# Set token configuration
export TOKEN_NAME="MyToken"
export TOKEN_SYMBOL="MTK"
export TOKEN_DECIMALS=18
export TOKEN_ISSUER=<issuer_address>
export LIEN_MODE=2  # 1 = hard freeze, 2 = encumbered

# Deploy via factory
forge script script/emoney/DeployToken.s.sol:DeployTokenScript \
  --rpc-url $RPC_URL \
  --broadcast
```

## Usage

### Creating a New Token

```solidity
import "@openzeppelin/contracts/access/AccessControl.sol";
import "../contracts/emoney/TokenFactory138.sol";

contract MyTokenDeployer {
    TokenFactory138 public factory;

    function deployToken(
        string memory name,
        string memory symbol,
        address issuer
    ) external returns (address) {
        ITokenFactory138.TokenConfig memory config = ITokenFactory138.TokenConfig({
            issuer: issuer,
            defaultLienMode: 2, // encumbered mode
            paused: false,
            bridgeOnly: false,
            bridge: address(0)
        });

        return factory.deployToken(name, symbol, config);
    }
}
```

### Policy-Controlled Transfers

All transfers are validated through the PolicyManager:

```solidity
import "../contracts/emoney/eMoneyToken.sol";

contract MyContract {
    eMoneyToken public token;

    function transferTokens(address to, uint256 amount) external {
        // PolicyManager automatically validates:
        // - Compliance status
        // - Frozen accounts
        // - Active liens
        // - Transfer restrictions

        token.transfer(to, amount);
    }
}
```

### Lien Enforcement

Two modes are supported:

1. **Hard Freeze Mode** (mode = 1):
   - Any active lien blocks ALL outbound transfers
   - Strict enforcement for high-security scenarios

2. **Encumbered Mode** (mode = 2):
   - Transfers allowed up to `freeBalance = balance - activeLienAmount`
   - More flexible for operational scenarios

### Compliance Management

```solidity
import "../contracts/emoney/ComplianceRegistry.sol";

// Set compliance status
complianceRegistry.setCompliance(account, true, riskTier, jurisdiction);

// Freeze/unfreeze account
complianceRegistry.setFrozen(account, true);
```

### Debt Management

```solidity
import "../contracts/emoney/DebtRegistry.sol";

// Place a lien
uint256 lienId = debtRegistry.placeLien(
    debtor,
    amount,
    expiry,
    priority,
    reasonCode
);

// Reduce lien amount
debtRegistry.reduceLien(lienId, reduceBy);

// Release lien
debtRegistry.releaseLien(lienId);
```

## Testing

### Run All Tests

```bash
forge test --match-path "test/emoney/**"
```

### Run Specific Test Suites

```bash
# Unit tests
forge test --match-path "test/emoney/unit/**"

# Integration tests
forge test --match-path "test/emoney/integration/**"

# Security tests
forge test --match-path "test/emoney/security/**"

# Upgrade tests
forge test --match-path "test/emoney/upgrade/**"

# Fuzz tests
forge test --match-path "test/emoney/fuzz/**"

# Invariant tests
forge test --match-path "test/emoney/invariants/**"
```

## Upgrading Token Implementation

See external `gru_emoney_token-factory/docs/UPGRADE_PROCEDURE.md` in the token factory repository for detailed upgrade procedures.

### Quick Upgrade Steps

1. **Validate Storage Layout**:
   ```bash
   tools/validate-storage-layout.sh
   ```

2. **Deploy New Implementation**:
   ```bash
   export TOKEN_PROXY_ADDRESS=<proxy_address>
   forge script script/emoney/Upgrade.s.sol:UpgradeScript \
     --rpc-url $RPC_URL \
     --broadcast
   ```

3. **Authorize Upgrade** (via multisig):
   ```bash
   forge script script/emoney/AuthorizeUpgrade.s.sol:AuthorizeUpgrade \
     --rpc-url $RPC_URL \
     --broadcast
   ```

4. **Verify Upgrade**:
   ```bash
   export TOKEN_PROXY_ADDRESS=<proxy_address>
   export EXPECTED_IMPLEMENTATION=<new_implementation_address>
   forge script script/emoney/VerifyUpgrade.s.sol:VerifyUpgrade \
     --rpc-url $RPC_URL
   ```

## Integration with Existing Systems

### CCIP Bridge Integration

The eMoney Token Factory can integrate with existing CCIP bridges:

```solidity
import "../contracts/emoney/BridgeVault138.sol";
import "../contracts/ccip/CCIPRouter.sol";

// Configure bridge vault to use CCIP router
bridgeVault.setLightClient(ccipRouter);
```

### Firefly Integration

Tokens can be registered with Hyperledger Firefly:

```solidity
// Deploy token via factory
address token = factory.deployToken(name, symbol, config);

// Register with Firefly token pool
// (requires Firefly SDK integration)
```

## Security Considerations

1. **Multi-Sig Requirements**: All administrative functions should use multi-sig wallets
2. **Access Control**: Roles are managed via OpenZeppelin AccessControl
3. **Reentrancy Protection**: All external calls are protected with ReentrancyGuard
4. **Upgrade Authorization**: Only DEFAULT_ADMIN_ROLE can authorize upgrades
5. **Compliance Enforcement**: All transfers are validated through PolicyManager

## Monitoring

### Key Events

- `TokenDeployed` - New token created via factory
- `TransferBlocked` - Transfer blocked by policy
- `LienPlaced` - New lien placed on account
- `LienReleased` - Lien released
- `ComplianceUpdated` - Compliance status changed
- `FrozenStatusChanged` - Account freeze status changed

### Metrics to Monitor

- Token deployment rate
- Transfer success/failure rates
- Active liens count
- Compliance violations
- Upgrade events

## Troubleshooting

### Common Issues

1. **Compilation Errors**:
   - Verify OpenZeppelin v5 is installed
   - Check Solidity version (0.8.20)
   - Verify remappings in `remappings.txt`

2. **Deployment Failures**:
   - Check RPC endpoint connectivity
   - Verify sufficient gas
   - Check multisig addresses are valid

3. **Transfer Failures**:
   - Check compliance status
   - Verify no active liens (hard freeze mode)
   - Check account freeze status
   - Verify policy manager configuration

## References

- External eMoney Token Factory README: `gru_emoney_token-factory/README.md`
- External Upgrade Procedure: `gru_emoney_token-factory/docs/UPGRADE_PROCEDURE.md`
- External Architecture Decision Records: `gru_emoney_token-factory/docs/ADRs/`
- [Integration Status](./INTEGRATION_STATUS.md)
