How NeuralHook works

Four layers that each depend on the next — remove any one and the project breaks.

Hook is live on Unichain Sepolia
NeuralHook · 0x6DCb…89c0Confirmed · block 50918795Gas · 41,116 per update

Trust guarantee

The AI cannot hallucinate a fee.

NeuralHook.sol calls ECDSA.recover(resultHash, sig) == trustedOracle on every submission. Any tampered, replayed, or fabricated output simply reverts. No admin override. No governance delay. The TEE signature is the permission.

TEE Signed

Output signed inside the 0G enclave before it leaves the model

2-of-3 Verified

Three Gensyn agents must reach consensus before any chain call

On-Chain Proof

ECDSA.recover validates every result atomically inside beforeSwap

Data flow

Pool State0G InferenceGensyn ConsensusKeeperHubNeuralHook.sol
01

Smart Contracts

Uniswap v4 · Solidity 0.8.26 · Foundry

NeuralHook.sol registers four hook callbacks inside the Uniswap v4 PoolManager: beforeSwap, afterSwap, beforeAddLiquidity, and afterRemoveLiquidity. Dynamic fees are enabled via DYNAMIC_FEE_FLAG (0x800000). The beforeSwap callback overrides the pool fee atomically — no separate governance transaction required.

Every fee change requires a valid ECDSA signature from the trusted oracle address. ECDSA.tryRecover catches signature malleability and zero-byte bypass attacks. A faked, replayed, or stale inference result reverts the transaction. Staleness is enforced: results older than 10 minutes are rejected on-chain (MAX_STALENESS = 600).

IL is computed on-chain using sqrtPriceX96: IL = 1 − 2q/(1+q²) where q is the sqrt-price ratio. ILInsuranceFund.sol caps each payout at 10% of reserves per claim to prevent drain attacks. The fund was seeded with 0.01 ETH at deployment.

The hook is deployed at 0x6DCb771F0A8A61F2679989453af9549C9ceA89c0 on Unichain Sepolia (chain ID 1301). Pool state (sqrtPriceX96, currentTick) is read live from the PoolManager using StateLibrary.extsload — the same extsload pattern used by the Uniswap v4 periphery.

LanguageSolidity 0.8.26 · via_ir optimizer
NetworkUnichain Sepolia · Chain ID 1301
NeuralHook0x6DCb771F0A8A61F2679989453af9549C9ceA89c0
ILInsuranceFund0x4D575ac6C3df76C7E22EB59715F0a9e839f16811
Fee TiersLOW 0.05% / MED 0.30% / HIGH 0.75% / CRIT 1.00%
Tests20 passing (Foundry forge test)
02

AI Inference Layer

0G Sealed Inference · TEE · ECDSA

0G Sealed Inference runs the IL risk model inside a Trusted Execution Environment (TEE). Inputs are: rolling 30-period volatility (σ), tick proximity (distance from current price to position range boundaries), and 5-period signed price momentum. These three features combine into a composite risk score.

Output: a 4-class risk label (LOW / MEDIUM / HIGH / CRITICAL), recommended fee in basis points, rebalance signal (bool), and yield score (0–255) — all signed by the TEE private key using ECDSA before leaving the enclave. The signed message structure matches NeuralHook.sol exactly: solidityPackedKeccak256([resultHash, ilRisk, predictedILBps, recommendedFee, rebalanceSignal, yieldScore, timestamp, chainId, hookAddress]).

Live sqrtPriceX96 is read from the PoolManager via StateLibrary.extsload on every inference cycle. This gives agents the real current ETH price (≈ $2000 at pool init) rather than a simulated value. If the pool slot is empty or out of sanity bounds, agents fall back to simulated metrics without stalling.

When OG_PROVIDER_ADDRESS is unset, a local heuristic model produces identical output structure and signs it with the same oracle key. The signature scheme is identical — local mode cannot be distinguished from TEE mode by the smart contract.

Provider0G Network Sealed Inference (local heuristic fallback)
Input featuresσ (volatility) · tick proximity · momentum · live sqrtPriceX96
OutputILRisk class · feeBps · rebalanceSignal · yieldScore
SigningECDSA secp256k1 · solidityPackedKeccak256
Staleness checkMAX_STALENESS = 600s enforced on-chain
03

Agent Consensus

Gensyn AXL · 3-Node Gossip · 2-of-3

Three independent TypeScript agents each run a 30-second inference loop: read live pool state, call the inference layer, produce a signed InferenceResult, then gossip their vote to the other two agents via HTTP (Gensyn AXL when configured, HTTP fallback otherwise). Each vote carries the full signed result and the agent's measured round-trip latency.

When any node collects two matching votes (same ilRisk class), consensus is declared. Tie-break rule: higher risk class wins, so NeuralHook is asymmetrically conservative. The lowest-latency agreeing agent's signature becomes the canonical result submitted on-chain.

Only agent-0 (NODE_ID=0) calls submitConsensusResult on-chain. Agents 1 and 2 gossip and vote but never touch the chain. This prevents nonce collisions when all agents share the same oracle key — which was the root cause of all failed on-chain submissions before this architecture was finalized.

TransportGensyn AXL HTTP gossip (HTTP fallback)
Nodes3 independent TypeScript agents (ports 4000–4002)
Threshold2-of-3 matching ilRisk class
Tie-breakHigher risk class wins (conservative bias)
SubmissionAgent-0 only — prevents nonce collisions
04

KeeperHub Execution

MCP Tool · eth_call Simulation · Polling

KeeperHub wraps the final on-chain submission step. Before broadcasting, it simulates the transaction via eth_call — confirming the consensus signature and all parameters are valid without spending gas. A revert in simulation means the signature is wrong, the timestamp is stale, or the fee is invalid; the entry is logged with success=false.

Gas price is fetched fresh from the network on every submission (2× the current maxFeePerGas). This prevents the gas from being hardcoded or pumped by a retry loop — the original source of a stuck high-gas transaction that blocked the wallet for several hours during testing.

On-chain state is confirmed via a 30-second polling loop that reads lastUpdateTimestamp, currentFee, and currentRisk directly from the contract. Unichain Sepolia's public RPC does not support eth_newFilter (event subscriptions), so polling is the only viable approach.

Every execution — success or failure — writes an AuditEntry: txHash, action, ilRisk, fee, gasUsed, timestamp, success. Entries are surfaced live on the Dashboard Audit Trail and queryable via GET /audit-log. The last 200 entries are retained in memory.

InterfaceMCP Tool (Model Context Protocol)
Pre-flighteth_call simulation before every broadcast
GasLive network estimate × 2 (no hardcoded values)
State poll30s interval · reads lastUpdateTimestamp + currentFee
RPCpublicnode.com (load-balanced sepolia.unichain.org had stuck txs)
Audit logEvery execution recorded · last 200 entries retained
05

Run it locally

Node.js 18+ · 2 terminals · contracts already deployed

Prerequisites

Node.js18 or later — check with: node --version
GitAny recent version
WalletA private key with Unichain Sepolia ETH for gas

Step 1Clone and install

The agents/ directory includes an .npmrc that resolves peer dependency conflicts automatically — npm install should complete without any flags.

git clone https://github.com/Hijanhv/NeuralHook
cd NeuralHook
cd agents && npm install && cd ..
cd frontend && npm install && cd ..

Step 2Configure agents

The .env.example already has the deployed contract addresses and RPC URL pre-filled. You only need to add your wallet private key.

cd agents
cp .env.example .env

# Edit .env — only these two lines need filling in:
PRIVATE_KEY=0x<your-wallet-private-key>
ORACLE_PRIVATE_KEY=0x<same-key-is-fine>

# Everything else (addresses, RPC, chain ID) is pre-filled

Step 3Start the agents (terminal 1)

cd agents
npm start

# Starts 3 agents on :4000 :4001 :4002
# Look for: [agent-0] simulation passed — broadcasting

Step 4Start the frontend (terminal 2)

Copy the frontend env file then start the dev server. The frontend reads live agent data and on-chain state automatically.

cd frontend
cp .env.local.example .env.local
npm run dev -- --port 3001

Step 5Open the dashboard

http://localhost:3001/dashboard

# You should see:
# • Data source: live agents
# • Agent mesh: 3 nodes healthy
# • Consensus feed updating every 30s
# • Cryptographic Proof panel: signature + oracle address

Note — wallet funding

The oracle wallet needs a small amount of Unichain Sepolia ETH to pay gas for on-chain submissions (~41k gas per round). Get testnet ETH from the Unichain faucet or bridge from Sepolia. 0.05 ETH covers hundreds of submissions.

ETHGlobal Open Agents 2026

Built for ETHGlobal Open Agents 2026. Demonstrates that AI agents can be integrated into DeFi infrastructure without compromising on-chain security — every agent action requires a cryptographic proof that the smart contract verifies atomically.

Uniswap v4
Dynamic fee hook + IL insurance
0G Network
Sealed inference + TEE signing
Gensyn
AXL 3-node consensus
KeeperHub
MCP execution + full audit