Skip to content

Defi-Oracle-Tooling/GREM-GRU-eMoney-Companion

Repository files navigation

GREM-GRU-eMoney-Companion

Multi-Asset Private Pool Controller for e-Money tokens on Polygon PoS blockchain, integrating with Foundry, OpenZeppelin, and DODO Exchange.

Overview

This project implements a sophisticated rebalancing system for e-money tokens (eUSD, eEUR, eXAU) that automatically maintains price pegs through integration with DODO pools and price oracles. The system enforces risk management guardrails including deviation bands, slippage protection, cooldowns, and inventory limits.

Key Features

  • Multi-Asset Support: Manage multiple e-money tokens (eUSD, eEUR, eXAU) with individual configurations
  • Per-Asset Risk Management: Configurable deviation bands, notional caps, cooldowns per asset
  • DODO Integration: Execute rebalancing trades through DODO PMM pools
  • Oracle Integration: Reference price feeds for deviation calculation
  • Slippage Protection: Configurable slippage limits and price validation
  • Inventory Management: Floor/ceiling limits for treasury balances
  • Automated Bot: TypeScript bot for continuous monitoring and execution
  • Polygon PoS Ready: Optimized for Polygon mainnet and Mumbai testnet

Architecture

┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   Price Oracle  │    │  Multi-Asset     │    │   DODO Pool     │
│   (Reference)   │───▶│   Controller     │◀──▶│  (Liquidity)    │
└─────────────────┘    └──────────────────┘    └─────────────────┘
                              │
                              ▼
                       ┌──────────────┐
                       │   Treasury   │
                       │  (Reserves)  │
                       └──────────────┘

Contract Structure

Core Contracts

  1. PrivatePoolControllerMulti.sol - Main controller managing multiple assets
  2. IEMoneyToken.sol - Interface for e-money tokens
  3. IDODOPool.sol - Interface for DODO PMM pools
  4. IPriceOracle.sol - Interface for price oracles

Mock Contracts (Testing)

  1. MockEMoneyToken.sol - Mock e-money token implementation
  2. MockDODOPool.sol - Mock DODO pool for testing
  3. MockPriceOracle.sol - Mock oracle for deviation testing

Risk Management

Each asset can be configured with individual risk parameters:

struct Risk {
    uint256 maxNotionalPerTx;      // Maximum notional per transaction
    uint256 maxNotionalPerBlock;   // Maximum notional per block
    uint256 maxSlippageBps;        // Maximum slippage in basis points
    uint256 cooldownSecs;          // Cooldown between executions
    uint256 upperBandBps;          // Upper deviation band
    uint256 lowerBandBps;          // Lower deviation band
    uint256 minTreasuryBase;       // Minimum treasury balance
    uint256 maxTreasuryBase;       // Maximum treasury balance
    uint256 leverageCapBps;        // Leverage policy (placeholder)
}

Quick Start

1. Installation

npm install

2. Environment Setup

Create .env file:

PRIVATE_KEY=0x...                    # Deployer/bot private key
POLYGON_RPC_URL=https://...          # Polygon RPC endpoint
POLYGONSCAN_API_KEY=...              # For contract verification
CONTROLLER_ADDRESS=0x...             # Deployed controller address
DRY_RUN=true                         # Bot dry run mode

3. Deployment

Deploy to Mumbai testnet:

npm run deploy:mumbai

Deploy to Polygon mainnet:

npm run deploy:polygon

4. Configuration

The deployment script automatically configures three assets:

  • eUSD: 1:1 USD peg with tight bands (±0.10%)
  • eEUR: EUR/USD rate with standard bands
  • eXAU: Gold price with wider bands (±0.20%)

5. Run Monitoring Bot

# Dry run mode (recommended first)
npm run bot:dry-run

# Live mode
npm run bot:start

Bot Configuration

The monitoring bot supports the following configuration:

interface BotConfig {
    rpcUrl: string;                 // Polygon RPC endpoint
    privateKey: string;             // Bot wallet private key
    controllerAddress: string;      // Controller contract address
    assets: AssetConfig[];          // Asset-specific configurations
    pollingIntervalMs: number;      // Monitoring frequency
    gasLimit: string;               // Transaction gas limit
    maxGasPriceGwei: number;        // Maximum gas price
    dryRun: boolean;                // Dry run mode
}

Asset Operations

Adding New Assets

bytes32 keyUSD = controller.getAssetKey("eUSD");
Risk memory risk = Risk({
    maxNotionalPerTx: 200_000e18,
    maxNotionalPerBlock: 500_000e18,
    maxSlippageBps: 30,        // 0.30%
    cooldownSecs: 15,          // 15 seconds
    upperBandBps: 10,          // +0.10%
    lowerBandBps: 10,          // -0.10%
    minTreasuryBase: 10_000e18,
    maxTreasuryBase: 50_000_000e18,
    leverageCapBps: 10_000
});

controller.addAsset(
    keyUSD,
    address(eUSDToken),
    treasuryAddress,
    address(dodoPool),
    address(oracle),
    risk
);

Executing Rebalancing

The controller automatically determines trade direction based on price deviation:

  • Positive deviation (market > reference): Sell base token
  • Negative deviation (market < reference): Buy base token
// Example: Market is 0.15% above peg, sell base to push price down
controller.execute(
    keyUSD,           // Asset key
    1,                // Direction: +1 = sell base, -1 = buy base
    100_000e18,       // Size in quote notional
    1.015e18          // Maximum acceptable price (slippage protection)
);

Testing

Unit Tests

# Run basic Solidity tests
# Note: Full Foundry setup required for complete test suite
npx hardhat test

Integration Testing

The repository includes comprehensive tests covering:

  • Asset configuration and validation
  • Deviation calculation and band enforcement
  • Execution logic and risk limits
  • Cooldown and per-block caps
  • Slippage protection
  • Emergency pause functionality
  • Multi-asset independence

Security Considerations

Access Control

  • Admin-only functions: Asset management, risk parameter updates
  • Emergency controls: Individual asset pause, global controls

Risk Mitigations

  • Deviation bands: Only execute when price moves outside acceptable range
  • Slippage protection: Maximum acceptable price validation
  • Rate limiting: Per-transaction and per-block notional caps
  • Cooldown periods: Prevent rapid successive executions
  • Inventory limits: Floor/ceiling controls on treasury balances

Oracle Dependencies

  • Price staleness checks: Validate oracle update frequency
  • Confidence intervals: Support for oracle confidence metrics
  • Multiple oracle support: Interface allows oracle aggregation

Deployment Addresses

Mumbai Testnet

PrivatePoolControllerMulti: 0x...
eUSD Token: 0x...
eEUR Token: 0x...
eXAU Token: 0x...

Polygon Mainnet

PrivatePoolControllerMulti: 0x...
# Production addresses to be added after deployment

Integration with DODO

The system integrates with DODO's Proactive Market Maker (PMM) model:

  1. Price Discovery: Monitor DODO pool mid-prices vs oracle references
  2. Trade Execution: Use sellBase()/sellQuote() functions
  3. Slippage Management: Query functions for price impact estimation
  4. Liquidity Access: Leverage DODO's aggregated liquidity

Monitoring and Alerts

The bot provides comprehensive monitoring:

  • Deviation Tracking: Real-time price deviation monitoring
  • Execution Alerts: Transaction confirmations and failures
  • Gas Optimization: Gas price monitoring and limits
  • Error Handling: Graceful handling of network and contract errors

Future Enhancements

  • MEV Protection: Private mempool integration
  • Advanced Oracles: Chainlink, Band Protocol integration
  • Cross-Chain: Support for multiple blockchain deployments
  • Dynamic Risk: Machine learning-based risk parameter adjustment
  • Governance: Decentralized parameter management

License

MIT License - see LICENSE file for details.

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Ensure all tests pass
  5. Submit a pull request

Support

For questions and support, please open an issue in the GitHub repository.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors