Skip to content

nahiid-dev/Sentinel-AMM

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

14 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Sentinel AMM: AI-Predictive Liquidity, Automated & Secured by Chainlink

An intelligent, automated liquidity management strategy for Uniswap V3 that leverages an off-chain AI model for price prediction, Chainlink Automation for decentralized execution, and Chainlink Price Feeds for on-chain security.

Submitted to the Chainlink Chronos Hackathon 2025

Note: Sentinel AMM is the practical, secure, and decentralized implementation of the concepts explored in our core research project, Uni-Dex-Marketplace. It was rapidly developed over 3 days for the hackathon to demonstrate a robust architectural pattern that solves real-world DeFi challenges using multiple Chainlink services.


๐ŸŽฏ Project Goal & Scientific Approach

The core idea behind this project is to scientifically simulate, analyze, and compare two distinct approaches to liquidity management on Uniswap V3, moving from a reactive model to a proactive, intelligent one.

Strategy 1: The Baseline (Reactive)

  • Foundation: Based on the current spot price.
  • Behavior: This strategy acts reactively. The smart contract only reallocates liquidity if a significant price change pushes the current position out of its active range. It is simple, robust, but inherently lagging behind the market.

Strategy 2: The Predictive (Proactive)

  • Foundation: Powered by a Deep Learning (LSTM) model.
  • Behavior: This approach proactively adjusts the liquidity range by forecasting future token prices. The predictions are fed to the smart contract, allowing it to position liquidity ahead of expected market movements, aiming to maximize fee capture and minimize impermanent loss.

For this hackathon, we focused on building a production-ready version of the Predictive Strategy, solving its inherent security and centralization flaws using the Chainlink ecosystem.


๐Ÿ“– The Story: From a Research Prototype to a Fortified Protocol

Our journey began as a research-driven initiative to revolutionize AMM liquidity strategies. We initially developed a powerful off-chain LSTM model to forecast prices and a smart contract that dynamically adjusted Uniswap V3 liquidity positions based on these predictions.

While promising, this initial version suffered from two critical vulnerabilities:

  1. A Centralized Point of Failure: The entire system relied on a centralized Python script running on a private server to trigger adjustments. If our server went down, the strategy would halt.
  2. A Blind Trust Security Risk: The smart contract blindly trusted the price from our off-chain API. A faulty prediction or a compromised API could lead to catastrophic losses.

Sentinel AMM is the evolution of this concept, transforming the prototype into a secure, resilient, and truly decentralized protocol. We solved these core challenges by deeply integrating two of Chainlink's cornerstone services:

๐Ÿ›ก๏ธ Chainlink Price Feeds as a "Safety Guardrail"

Our smart contract no longer blindly trusts the AI. It first fetches the highly reliable, decentralized market price from Chainlink Price Feeds. If the AI's prediction deviates by more than a predefined threshold (e.g., 10%) from this on-chain source of truth, the transaction is safely reverted, protecting all capital.

โš™๏ธ Chainlink Automation as a "Decentralized Executor"

We replaced our fragile, centralized script with Chainlink's battle-tested automation network. This ensures our strategy is executed reliably and consistently, removing our server as a single point of failure and transforming our system into a truly decentralized application (dApp).


๐Ÿ›๏ธ System Architecture & Simulation Logic

Our system architecture is designed for a fully decentralized future, while our testing framework provides a robust simulation of this vision.

Production Architecture Vision

The diagram below illustrates the final, production-ready architecture.

graph TD
    subgraph "Phase 1: Off-Chain Modeling"
        A[AI/LSTM Price Model API]
    end

    subgraph "Phase 2: Chainlink Secure Bridge"
        B[Chainlink Automation] -- "1. Time-based Trigger" --> F[Chainlink Functions]
        F -- "2. Fetches Prediction" --> A
        A -- "3. Returns Prediction" --> F
        F -- "4. Delivers Data On-Chain" --> E
        G[Chainlink Price Feeds]
    end

    subgraph "Phase 3: On-Chain Muscle"
        E[AutomationTrigger.sol] -- "5. Executes Adjustment" --> H[SentinelAMM.sol]
        H -- "7. Manages Liquidity" --> I[Uniswap V3 Pool]
        G -- "6. Provides On-Chain Truth for Validation" --> H
    end
Loading

Hackathon Simulation: How We Test This Vision

For this hackathon, we built a comprehensive end-to-end test that accurately simulates this entire flow within a Hardhat mainnet fork.

  • The Python script (sentinel_test.py) plays the role of the entire off-chain world: It acts as both the Chainlink Automation keeper and the Chainlink Functions oracle.
  • The manualTrigger() function in AutomationTrigger.sol serves as a secure entry point for our test script to inject the off-chain data (the AI prediction) into the on-chain system, simulating the final step of a Chainlink Functions call.

This approach allows us to validate the full on-chain logicโ€”including security checks and state changesโ€”before deploying to production.


๐Ÿ”ฌ Technical Deep Dive & Code Highlights

On-Chain Logic

SentinelAMM.sol - The Vault & Guardrail

This contract holds the assets and the core logic. Its most critical function is updatePredictionAndAdjust, which enforces the Chainlink security check.

// contracts/SentinelAMM.sol

function updatePredictionAndAdjust(
    int24 predictedTick,
    uint256 predictedPrice_8_decimals
) external nonReentrant onlyAuth {
    // 1. Fetch on-chain truth from Chainlink
    (, int256 currentChainlinkPrice_8_decimals, , , ) = priceFeed.latestRoundData();
    require(currentChainlinkPrice_8_decimals > 0, "Sentinel: Invalid Chainlink price");

    // 2. Calculate deviation between AI prediction and on-chain price
    uint256 difference = _getDifference(uint256(currentChainlinkPrice_8_decimals), predictedPrice_8_decimals);
    uint256 tenPercentOfCurrent = uint256(currentChainlinkPrice_8_decimals) / 10;

    // 3. Revert if deviation is too high
    require(
        difference <= tenPercentOfCurrent,
        "Sentinel: Prediction deviates too much!"
    );

    // 4. If safe, proceed with liquidity adjustment...
    _adjustLiquidityBasedOnTick(predictedTick);
}

AutomationTrigger.sol - The Decentralized Entrypoint

This contract is designed to be called by Chainlink Automation. For our simulation, it contains the manualTrigger function.

// contracts/AutomationTrigger.sol

contract AutomationTrigger is AutomationCompatibleInterface {
    ISentinelAMM public immutable sentinel;
    address public immutable owner;

    // The function called by our Python test script to simulate a Chainlink action
    function manualTrigger(int24 predictedTick, uint256 predictedPrice_8_decimals) external {
        require(msg.sender == owner, "Only owner can trigger manually");
        sentinel.updatePredictionAndAdjust(predictedTick, predictedPrice_8_decimals);
    }

    // Standard Chainlink Automation functions
    function checkUpkeep(...) external pure override returns (bool upkeepNeeded, bytes memory performData) {
        upkeepNeeded = true;
        performData = "";
    }

    function performUpkeep(...) external override {
        // In production, this would trigger a Chainlink Functions request.
    }
}

The Off-Chain Simulation (sentinel_test.py)

Our Python script orchestrates the entire test cycle. The _trigger_adjustment function is a key part of this simulation.

# test/sentinel_test.py

def _trigger_adjustment(self, funding_account, private_key, stage_name="adjustment"):
    # 1. Fetch prediction from our AI model's API
    predicted_price = self.get_predicted_price_from_api()
    if not predicted_price: return None

    # 2. Fetch the live on-chain price for comparison and logging
    chainlink_price = self.get_chainlink_price()
    logger.info(f"AI Predicted: ${predicted_price:.2f} | Chainlink Live: ${chainlink_price:.2f if chainlink_price else 'N/A'}")

    # 3. Calculate the necessary parameters for the smart contract
    predicted_tick, price_for_contract = self.calculate_tick_and_price_for_contract(predicted_price)
    if predicted_tick is None: return None

    # 4. Call the 'manualTrigger' function on-chain, simulating the final step of a Chainlink job
    tx_call = self.trigger_contract.functions.manualTrigger(predicted_tick, price_for_contract)

    # 5. Sign and send the transaction
    receipt = web3_utils.send_transaction(...)
    return receipt

๐Ÿงฐ Tech Stack

  • Smart Contracts: Solidity, Hardhat, OpenZeppelin
  • Decentralized Services: Chainlink Automation, Chainlink Price Feeds
  • DeFi Protocol: Uniswap V3
  • AI Modeling & Off-chain Execution: Python, PyTorch, web3.py
  • Deployment & Tooling: ethers.js, hardhat-deploy
  • Infrastructure: Infura/Alchemy (for mainnet forking)

๐Ÿ“ Project Structure

/
โ”œโ”€โ”€ contracts/
โ”‚   โ”œโ”€โ”€ SentinelAMM.sol
โ”‚   โ”œโ”€โ”€ AutomationTrigger.sol
โ”‚   โ””โ”€โ”€ mocks/
โ”‚       โ””โ”€โ”€ MockAggregatorV3.sol
โ”œโ”€โ”€ deploy/
โ”‚   โ””โ”€โ”€ 01-deploy-sentinel.js
โ”œโ”€โ”€ test/
โ”‚   โ”œโ”€โ”€ utils/
โ”‚   โ””โ”€โ”€ sentinel_test.py
โ”œโ”€โ”€ .env.example
โ”œโ”€โ”€ hardhat.config.js
โ”œโ”€โ”€ helper-hardhat-config.js
โ”œโ”€โ”€ requirements.txt
โ””โ”€โ”€ run_sentinel_test.sh

๐Ÿš€ How to Run the Simulation Locally

๐Ÿงฉ Prerequisites

  • Node.js (v18+)
  • Python (v3.10+) & venv

โš™๏ธ Setup

# Clone the repository
git clone https://github.com/NShahab/Sentinel-AMM.git
cd Sentinel-AMM

# Install Node.js and Python dependencies
npm install
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

# Configure environment variables
cp .env.example .env
# Edit .env and add your MAINNET_RPC_URL and PRIVATE_KEY
nano .env

โ–ถ๏ธ Run the Full Pipeline

This single command runs the entire pipeline:

chmod +x run_sentinel_test.sh
bash run_sentinel_test.sh

This script will:

  • Spin up a Hardhat local fork of the Ethereum mainnet.
  • Deploy SentinelAMM and mock contracts.
  • Simulate LSTM prediction input.
  • Run the full liquidity adjustment & on-chain verification.
  • Save result logs to a CSV file.
  • Cleanly shut down the environment.

๐Ÿ”ฎ Future Work & Vision

  • ๐Ÿ”— Integrate Chainlink Functions: Replace the manualTrigger simulation with a full Chainlink Functions implementation to decentralize the AI prediction data source.
  • โšก Expand to L2s: Deploy the strategy on Layer 2 networks like Arbitrum and Optimism to reduce gas costs.
  • ๐Ÿ–ฅ๏ธ Build a dApp Interface: Build a user-facing dApp for depositing funds into the strategy vault and monitoring real-time performance.
  • ๐Ÿง  Advanced Strategies: Incorporate more complex models, such as Reinforcement Learning agents, for dynamic strategy adjustments.
  • ๐Ÿ“œ Publish Research: Formalize the findings of this comparative analysis into an academic paper or whitepaper.

๐Ÿชช License

MIT


๐Ÿค About

Sentinel AMM is a submission for the Chainlink Chronos Hackathon 2025, built by a team passionate about bridging predictive AI and DeFi liquidity.

About

AI-Predictive Liquidity Automated & Secured by Chainlink. A project for the Chainlink Chromion Hackathon.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

โšก