About
Risk-Aware Lending with Agentic Auto Top-Ups (Sepolia + Amoy + Alfajores) TL;DR
A non-custodial lending protocol on Ethereum Sepolia with a built-in Repay Buffer and a personalized credit score (OCCR). A lightweight agent on Polygon Amoy pays a tiny HTTP 402 fee to authorize automated “top-up” repayments (no swaps, no bridging). Self Protocol on Celo Alfajores enforces “one human → one credit line.” Clean mono-repo, fully instrumented demo, and tidy commits.
What problem are we solving?
Liquidation risk is scary for retail users, especially in volatile markets.
Cross-chain automation is flaky: bridging assets/swaps introduce slippage, MEV, and operational risk.
One-size-fits-all LTV ignores user behavior and on-chain reputation.
Sybil abuse can sabotage risk controls and incentive design.
Our answer:
Keep user funds on the lending chain (Sepolia), in a Repay Buffer owned by the lending pool.
Make automation pay-per-action via a 402 fee on Polygon Amoy—no value transfer cross-chain.
Personalize collateral limits with OCCR (On-Chain Credit Risk) scoring.
Gate borrowing with Self Protocol verification on Celo for unique humans.
High-level flow (happy path)
Verify identity (Celo Alfajores): User completes Self verification → our backend/allowlist attests → IdentityVerifier.setVerified(user, true) on Sepolia (or Merkle proof).
Deposit collateral (Sepolia): User deposits cWETH; pool tracks collateralBalance.
Borrow (Sepolia): Pool computes personalized LTV using OCCR → user borrows tUSDC.
Pre-fund Repay Buffer (Sepolia): User sends some tUSDC to their Repay Buffer (repayBuffer[user]).
Turn on Auto Top-Up (Frontend): Set HF threshold (e.g., 1.10). An Agent monitors HF.
Market dips: HF falls below threshold. Agent calls /api/topup → receives 402 challenge (pay small fee on Polygon Amoy).
Agent pays 402 on Amoy: Sends 0.5 USDC (or MATIC) to payTo with a session memo → submits proofTxHash back to /api/topup.
Server verifies + repays from Buffer: Server confirms Amoy payment, re-reads HF on Sepolia, computes needed repayment, and calls repayFromBuffer(user, amount). → HF recovers without swaps/bridges; user funds never left Sepolia.
Why this design?
No-swap safety: Eliminates slippage, MEV, and bridge risk. All principal/interest stays on Sepolia.
Agentic but opt-in: Paying the 402 fee proves user/agent intent for each automated action.
Personalized risk: OCCR adjusts LTVs using observable on-chain behavior, not just static tiers.
Sybil resistance: Self enforces one human per credit line for sane risk controls.
Architecture (three chains, clear roles)
Ethereum Sepolia (Core Protocol)
LendingPool.sol — deposits/borrows/repays/liquidations + Repay Buffer (depositBuffer, withdrawBuffer, repayFromBuffer).
OCCRScore.sol — maintains scoreMicro[user] in [0..1e6] and emits CreditScoreUpdated.
IdentityVerifier.sol — isVerified(address) gate for borrowing; supports admin attest or Merkle allowlist.
TestToken.sol — simple 18-decimals tokens for collateral (cWETH) and debt (tUSDC).
Polygon Amoy (x402 lane)
Agent pays a small on-chain fee (USDC/MATIC) to payTo. No user funds bridged. Fee → permission to trigger automation.
Celo Alfajores (Identity)
Self Protocol verification → backend attests or Merkleizes verified addresses for IdentityVerifier.
Repo map (mono-repo):
/contracts # Foundry/Hardhat (Sepolia) /frontend # Next.js 15 (App Router, TS) + /api/topup (402 endpoint) /agents # Node/TS agent that watches HF & pays 402 /indexer # Lightweight event indexer + REST (Token API for scores/positions)
Core protocol details (Sepolia)
LendingPool (essentials)
Config: baseLTVbps, liqThresholdBps, liquidationBonusBps, price1e18.
State: collateralBalance[user], debtBalance[user], repayBuffer[user].
Views:
valueOfCollateral(user)
userMaxBorrowable(user)
isUnderwater(user)
getHealthFactor(user) = (value * liqThresholdBps/10000) / max(debt, 1)
Actions:
deposit(amount)
borrow(amount) → requires IdentityVerifier.isVerified(msg.sender)
repay(amount)
liquidate(user, repayAmount)
Buffer ops: depositBuffer(amount), withdrawBuffer(amount), repayFromBuffer(user, amount)
(Optional) repayOnBehalf(user, amount)
No-swap rule: All repayFromBuffer sources are the user’s buffer inside the pool on Sepolia.
OCCRScore (personalized LTV)
scoreMicro[user] ∈ [0..1e6] where 0 = best.
Weights (example): Historical 35%, Current 25%, Utilization 15%, Txn 15%, New 10%.
Hooks: onBorrow, onRepay, onLiquidation adjust subscores.
Personalized LTV:
risk = scoreMicro / 1e6
personalizedLTVbps = baseLTVbps * (1 - risk)
Emit CreditScoreUpdated(user, scoreMicro)
Intuition:
Historical: repayments vs. liquidations over time.
Current: recent behavior, e.g., days since last repay, active HF.
Utilization: debt / (debt + free capacity) or variant.
Txn: on-chain activity breadth/frequency (anti-dust behavior).
New: cold-start penalty that fades as data accrues.
IdentityVerifier
isVerified(address) → bool.
Path A (on-chain-lite): backend verifies Self proof and calls setVerified(user, true) (owner-only).
Path B (Merkle): set merkleRoot; user calls prove(proof) to set verifiedHuman[user] = true.
x402 Agentic loop (Amoy + Frontend API)
/api/topup (Next.js API route)
Request: { user, minHF, proofTxHash? }
If no proof: return 402 challenge JSON
{
"payTo": "0x...amoy", "amount": "500000", "token": "USDC", "chain": "polygon-amoy", "session": "<uuid>" }
If proofTxHash:
Verify on Amoy that fee amount token was sent to payTo (and memo session if used).
Read user HF on Sepolia.
Compute needed = targetHF - currentHF → estimate minimal repay.
Call repayFromBuffer(user, min(needed, repayBuffer[user])).
Return { ok: true, repaid: "<amount>" }.
Agent (Node/TS)
Monitors HF via Sepolia RPC.
When HF < threshold:
POST /api/topup → get 402.
Pay Amoy fee (USDC/MATIC).
POST /api/topup with proofTxHash.
Logs: “Repaid X from buffer; HF now Y.”
Key point: The fee is the only cross-chain value. Collateral and debt never move chains.
Indexer + Token API (off-chain analytics surface)
Lightweight service (ethers.js listeners + sqlite/json) that ingests events: Deposit, Borrow, Repay, Liquidate, BufferDeposit, BufferWithdraw, BufferRepay, CreditScoreUpdated.
Maintains per-user state (positions, counts, tx stats) and recomputes OCCR off-chain for comparison/tuning.
REST endpoints:
GET /api/scores/:address → { scoreMicro, factors, updatedAt }
GET /api/users/:address/position → { collateral, debt, hf, buffer, history }
Frontend: shows On-chain OCCR vs Indexed OCCR (beta) + mini-charts (score & HF over time).
Security & trust model (transparent for judges)
Non-custodial: Users control deposits; Repay Buffer is inside the pool and withdrawable unless used.
No bridging risk: We never move principal/interest off Sepolia.
x402 fee is low-risk: Only a small fee on Amoy; failing to pay just means no automation that cycle.
Identity trust hop: For MVP, backend attests Self verification (or Merkle). We document the path to direct on-chain verification post-hackathon.
Upgradability / Admins: Minimal, clearly documented (e.g., owner price control for demo).
Observability: Event logs for every state change; indexer provides time-series for audits.
User experience (what the judge sees)
Connect wallet → Not Verified (borrow locked).
Click Verify with Self → returns Verified; borrow unlocked.
Deposit cWETH → Borrow tUSDC (LTV personalized by OCCR).
Deposit Repay Buffer (e.g., 50 tUSDC).
Toggle Auto Top-Up; set threshold HF = 1.10.
Admin simulates price drop → HF dips.
Agent pays x402 on Amoy → server repays from Buffer → HF recovers.
OCCR updates (on-chain & indexed).
User withdraws leftover buffer, repays, then withdraws collateral.
What’s innovative here?
Agentic safety net without swaps: automation that never touches principal across chains.
Behavior-aware credit: OCCR turns on-chain traces into live LTV personalization.
Human-bound credit lines: Self verification ensures one unique borrower per line.
Composable lanes: Three chains, each doing what they’re best at (credit core, cheap fee signal, identity).
Tech stack (concise)
Contracts: Solidity (Foundry/Hardhat), Sepolia deployments.
Frontend: Next.js 15 (App Router, TS), wagmi/ethers, /api/topup.
Agent: Node/TS script (Amoy RPC, simple loop).
Indexer: Node/TS service with ethers listeners + sqlite/json.
Infra: Alchemy RPCs; test tokens; minimal admin price control for demos.
CI/dev-ex: Env templates, scripts, first-commit scaffolds, architecture diagram (PNG/SVG).
Example math (readable for judges)
HF:
HF = (collateralValue * liqThresholdBps / 10000) / max(debt, 1)
Personalized LTV:
risk = scoreMicro / 1e6 personalizedLTVbps = baseLTVbps * (1 - risk) Example: baseLTV = 70%, scoreMicro = 200k → risk=0.2 → LTV = 56%.
Roadmap after hackathon
On-chain Self proof verification or cross-chain attestation.
Price oracles (Pyth/Chainlink) + multi-asset markets.
Smarter OCCR (ML-assisted factors, anomaly detection) and “Good-Borrower” rewards.
Optional DEX integration as separate module (while keeping Buffer-first design).
Substreams migration for scalable indexing.
From the public ETHGlobal showcase page. Votes, swipes and the judge score are hackfeed's own.






