Version: 1.0.0
Target Networks: Base Sepolia (Chain ID84532) / Ethereum L1 (Sepolia / Mainnet) / Hardhat Localhost (31337)
Protocol Specification: docs/frontend_spec.md | docs/frontend_spec_zh.md
HoloFi is an institutional-grade Real World Asset (RWA) decentralized credit and over-collateralized lending protocol. It transforms physical Trading Card Game (TCG) collectibles (such as PSA/BGS/CGC graded card slabs) into liquid, productive on-chain capital.
The frontend application serves as "The Appraisal Laboratory & Private Banking Asset Manager". It bridges physical vault custody with EVM smart contracts, delivering:
- Borrower Portal (Card Merchants): Turn illiquid physical card inventory into instant EURC/USDC credit lines without selling underlying collectibles. Merchants monitor borrowing capacity, loan-to-value (LTV), and real-time Health Factors through a private-banking styled interface.
- Liquidity Provider Portal (LPs): Earn automated, risk-adjusted interest yields by supplying stablecoins to isolated ERC-4626 lending vaults (
Premium EURC PoolandDeluxe EURC Pool). - Institutional Admin Console: Manage end-to-end RWA custody operations, including French SIRET KYB compliance, physical parcel receiving, 4K appraisal audit, 3-stage oracle price validation, and server-secured ERC-721 voucher minting.
- Framework & Runtime: Next.js (App Router, React Server Components), React, TypeScript
- Styling: Tailwind CSS
- Web3 & Smart Contracts: Wagmi, Viem, RainbowKit, SIWE (EIP-4361)
- Database & Storage: MongoDB (Mongoose), Pinata IPFS, Vercel Blob
- Authentication: NextAuth.js
- Internationalization: next-intl (
en/fr) - Testing: Vitest, React Testing Library
holofi_frontend/
├── docs/ # Protocol specifications, workflows & architectural diagrams
│ ├── frontend_spec.md # ASD-STE100 English frontend specification whitepaper
│ ├── frontend_spec_zh.md # Chinese frontend specification whitepaper
│ ├── holofi-architecture.jpeg # Full-system 4-layer architecture diagram
│ ├── merchant-lp-interaction-sequence.jpeg # End-to-end sequence interaction diagram
│ ├── WORKFLOWS.md # Comprehensive protocol lifecycle workflows
│ └── terms_of_service.md # Legal terms for merchants and liquidity providers
├── scripts/ # Operational CLI automation scripts
│ ├── create-admin.ts # Seeds super-admin accounts into MongoDB
│ └── sync-abis.ts # Extracts and compiles contract ABIs from contract packages
├── src/
│ ├── app/ # Next.js 16 App Router pages and backend API handlers
│ │ ├── (auth)/ # Authentication routes: /login, /register, /profile
│ │ ├── admin/ # Institutional admin console: /admin, /kyb, /mint, /shipments, /vaults
│ │ ├── merchant/ # Card merchant portal: /verify, /shipments, /vaults, /borrow
│ │ ├── pools/ # Liquidity provider earn portal: /pools
│ │ ├── api/ # Backend route handlers (Auth, KYB, Shipments, Oracle, IPFS)
│ │ ├── layout.tsx # Root layout with Web3, Auth, and Intl providers
│ │ ├── page.tsx # Landing page with interactive credit simulator and showcase
│ │ └── globals.css # Tailwind CSS v4 design tokens and base styles
│ ├── components/ # Modular React UI components
│ │ ├── auth/ # Authentication forms and SIWE wallet binding controls
│ │ ├── cards/ # High-fidelity card rendering and slab image viewers
│ │ ├── home/ # Hero section, value proposition, and CreditSimulator
│ │ ├── layout/ # Global responsive Navbar and Footer
│ │ ├── merchant/ # HealthFactorMeter and merchant dashboard widgets
│ │ ├── pools/ # PoolCard, PoolDepositModal, PoolRedeemModal, and tx tables
│ │ ├── ui/ # Design system primitives: Toast, LanguageSwitcher, FileUpload
│ │ └── web3/ # Web3Provider, RainbowKit config, and ProtocolEventListener
│ ├── config/ # Core protocol configuration
│ │ ├── contracts.ts # Strict environment variable parser for 10 contract addresses
│ │ └── wagmi.ts # Wagmi v2 client, chain transports, and RainbowKit setup
│ ├── contracts/ # Smart contract ABIs and TypeScript definitions
│ │ └── abi/ # AccessControlManager, LoanCore, LendingPool, VaultCard, etc.
│ ├── hooks/ # Custom React hooks
│ │ └── web3/ # useLoanCore, useLendingPool, useVaultCard, useCardPriceFeed, useErc20
│ ├── i18n/ # next-intl configuration and routing middleware
│ ├── lib/ # Core backend services, database models, and utilities
│ │ ├── auth/ # NextAuth options, password hashing, and SIWE signature verification
│ │ ├── borrow/ # Health factor formulas, borrow capacity, and liquidation math
│ │ ├── cards/ # Card type index lookups and attestation hash computation
│ │ ├── db/ # MongoDB Mongoose connection and 8 data collection models
│ │ ├── format.ts # Currency, BigInt, address masking, and date formatters
│ │ ├── ipfs/ # Pinata IPFS file upload and ERC-721 metadata builders
│ │ ├── kyc/ # French SIRET validation and KYB document management
│ │ ├── pools/ # ERC-4626 share conversion and APY compounding math
│ │ ├── shipments/ # Inbound/outbound parcel state machines and audit workflows
│ │ ├── vaults/ # Multi-pool vault aggregators and risk monitors
│ │ └── web3/ # Server-side admin actions, viem clients, and explorer linkers
│ ├── messages/ # Internationalization dictionaries
│ │ ├── en.json # English translation dictionary
│ │ └── fr.json # French translation dictionary
│ └── types/ # TypeScript ambient declarations and NextAuth extensions
└── vitest.config.ts # Vitest configuration with React Testing Library setup
The following diagram illustrates the four-tier architecture connecting physical card custody with decentralized on-chain lending:
-
Presentation Layer (Client Portals):
- Built on React 19 and Next.js 16 with a clean "Warm Stone Minimalist Authority" design system.
- Provides role-tailored dashboards for Merchants (
/merchant), Liquidity Providers (/pools), and Protocol Operators (/admin). - Uses plain financial language (e.g., Borrowing Power instead of LTV, Digital Certificate instead of NFT, Asset Auction instead of Liquidation).
-
Application Layer (Next.js App Router & Services):
- React Server Components (RSC) handle secure server-side execution and sensitive admin transactions using
ADMIN_PRIVATE_KEY. - next-intl provides real-time client-side and server-side internationalization across English (
en) and French (fr). - Hybrid Auth Engine pairs NextAuth JWT sessions with EIP-4361 Sign-In with Ethereum (SIWE).
- React Server Components (RSC) handle secure server-side execution and sensitive admin transactions using
-
Web3 Integration Layer (Wagmi & Viem Engine):
- Wagmi v2 & Viem provide strictly-typed React hooks for smart contract reads, writes, and real-time event logs.
- RainbowKit delivers seamless wallet onboarding with support for MetaMask, Coinbase Wallet, and WalletConnect.
- ProtocolEventListener silently watches on-chain events (
CardMinted,VaultCreated,KybStatusUpdated) in the background to automatically revalidate Next.js cache tags.
-
Protocol & Infrastructure Layer:
- Base Sepolia / Ethereum L1: Executes all smart contract logic (
LoanCore,HoloFiLendingPool,VaultCard,CardPriceFeed,DutchAuction). - Pinata IPFS: Decentralized pinning for immutable ERC-721 image assets and metadata JSON.
- HoloFi Oracle API: Aggregates secondary marketplace sales data to compute Fair Market Value (FMV).
- MongoDB: Persists off-chain metadata, French SIRET KYB verifications, shipping manifests, and relational caches.
- Physical Vault (Freeport): High-security physical storage facility holding authenticated card slabs.
- Base Sepolia / Ethereum L1: Executes all smart contract logic (
The following sequence diagram illustrates the complete interaction lifecycle between Card Merchants, Liquidity Providers, Protocol Operators, and EVM Smart Contracts:
- Onboarding & Wallet Binding: Merchant registers with email/password, then links their Web3 wallet using EIP-4361 SIWE signature verification.
- French Corporate KYB: Merchant submits company credentials (legal representative ID, 14-digit French SIRET number, Kbis certificate). The protocol operator reviews and approves the merchant on-chain via
AccessControlManager. - Inbound Shipping Manifest: Merchant creates a digitally signed parcel manifest declaring physical card items and tracking numbers. Once submitted, the manifest becomes immutable.
- 4K Inspection & 3-Stage Minting: The custody vault receives the package, performs an unboxing audit, and validates grading authenticity. The protocol operator runs a 3-stage price check via the Oracle API, pins high-resolution images to Pinata IPFS, and mints an ERC-721
VaultCarddigital certificate to the merchant's wallet. - Vault Creation & Collateral Deposit: Merchant selects an isolated risk pool (
PremiumorDeluxe), creates an on-chainVaultviaLoanCore, and deposits theirVaultCardNFT as collateral. - EURC/USDC Drawdown: Merchant borrows stablecoins up to the pool's maximum LTV (
50%for Premium,40%for Deluxe). - Debt Repayment & Physical Redemption: Merchant repays principal plus accrued interest. Once debt is zero, the merchant withdraws the NFT, requests physical redemption, and the protocol burns the NFT on-chain before returning the slab.
- Pool Discovery: LP browses isolated lending pools, evaluating TVL, pool utilization, base APR, and collateral tiers.
- Stablecoin Deposit: LP approves EURC/USDC and deposits into
HoloFiLendingPool(an ERC-4626 vault). - Share Issuance & Yield Accrual: The pool mints yield-bearing
pTokenshares to the LP. As borrowers pay interest, share exchange rates increase automatically. - Redemption: LP redeems shares for underlying stablecoin principal plus compounding yield at any time (subject to pool liquidity).
- Hybrid Role-Based Access: Combines Web2 credentials with Web3 cryptographic proofs. Supports three roles:
MERCHANT,LP, andADMIN. - SIWE Integration: Generates cryptographically secure nonces, validates EIP-4361 message payloads, and executes
viem/verifyMessageto prevent replay attacks and CSRF vulnerabilities. - Key Files:
src/lib/auth/auth.ts: NextAuth session provider with credentials handler and JWT callbacks.src/app/api/auth/wallet-bind/route.ts: Endpoint for binding verified Ethereum addresses to user accounts.
- Institutional Compliance: Validates French corporate 14-digit SIRET numbers with Luhn checksum validation.
- Secure Document Upload: Encrypts and uploads Kbis excerpts and identity proofs to Vercel Blob Storage.
- On-Chain Whitelisting: Protocol operators approve applications through server-side calls that invoke
setKybStatusonAccessControlManager. - Key Files:
src/lib/kyc/siret.ts: SIRET format and algorithmic checksum validators.src/app/api/kyc-kyb/apply/route.ts: Merchant KYB submission endpoint.src/app/api/admin/kyc-kyb/review/route.ts: Operator review and on-chain whitelisting trigger.
6.3 Logistics & Physical Manifest Tracking (src/lib/shipments, src/app/merchant/shipments, src/app/admin/shipments)
- Immutable Inbound Manifests: Merchants declare graded slabs with certification numbers, game sets, grades, and declared values before shipping.
- Audit & Custody Logging: Operators record package arrival, box damage inspections, 4K slab verification photos, and vault storage locations.
- Outbound Redemptions: Manages return logistics for rejected items and collateral redemptions.
- Key Files:
src/lib/shipments/service.ts: Shipment lifecycle state machine (IN_TRANSIT→RECEIVED→VERIFIED/REJECTED).src/lib/db/models/CardShipment.ts: Manifest document schema.src/lib/db/models/ShipmentCardItem.ts: Itemized card slab declaration schema.
- 3-Stage Oracle Validation:
- Stage 1 (On-Chain): Checks if a valid cached FMV exists in
HoloFiCardPriceFeed. - Stage 2 (Oracle DB): If absent on-chain, fetches historical weighted-average sales from the Oracle API and calls
setPriceon-chain. - Stage 3 (Fallback Guard): If no secondary market sales exist, blocks minting to protect pool solvency.
- Stage 1 (On-Chain): Checks if a valid cached FMV exists in
- Attestation Hash Engine: Computes deterministic SHA-256 / Keccak-256 hashes binding certification numbers, vault IDs, timestamps, and image URLs.
- Key Files:
src/lib/web3/adminActions.ts: Server-side privileged contract actions (mintVaultCardOnChain,registerCardEligibilityOnChain).src/lib/ipfs/pinata.ts: Pinata IPFS file upload and metadata builders.src/app/api/oracle/price/route.ts: Oracle price aggregation proxy.
6.5 Over-Collateralized Lending & Risk Simulation (src/lib/borrow, src/lib/vaults, src/components/merchant)
-
Multi-Pool Risk Isolation:
-
Premium Pool: PSA 10 Gem Mint only (
50% Max LTV,70% Liquidation Threshold,5% APR,5% Penalty). -
Deluxe Pool: PSA 9 Mint cards (
40% Max LTV,60% Liquidation Threshold,8% APR,5% Penalty).
-
Premium Pool: PSA 10 Gem Mint only (
-
Health Factor Meter: Real-time visual risk gauge with three color states: Safe (
$\ge 1.5$ , Emerald), Warning ($1.0 - 1.5$ , Amber), and Liquidation ($< 1.0$ , Crimson). - Interactive Simulator: Dynamic slider simulating debt drawdowns and Health Factor impacts before submitting on-chain transactions.
-
Key Files:
-
src/lib/borrow/healthFactor.ts: Mathematical formulas for Health Factor and borrow limits. -
src/components/merchant/HealthFactorMeter.tsx: Interactive risk visualization component. -
src/hooks/web3/useLoanCore.ts: React hook managing vault creation, collateral deposits, borrows, and repayments.
-
- ERC-4626 Standard Compliance: Standardized vault accounting (
deposit,redeem,convertToShares,convertToAssets). - Dynamic APY & Utilization: Real-time interest rate models based on active pool borrow utilization.
- Key Files:
src/hooks/web3/useLendingPool.ts: Comprehensive pool interaction hook.src/components/pools/PoolCard.tsx: Liquidity pool display card with live metrics.src/components/pools/PoolDepositModal.tsx: Two-step ERC-20 approval and deposit modal.
- Full English and French localization with strict dictionary parity.
- Dynamic locale routing via Next.js middleware and persistent language selector.
- Key Files:
src/messages/en.json: English translation dictionary.src/messages/fr.json: French translation dictionary.src/components/ui/LanguageSwitcher.tsx: Global language toggle.
The frontend integrates with 10 protocol smart contracts on Base Sepolia / Localhost:
| Contract | Symbol / Name | Standard | Responsibilities |
|---|---|---|---|
AccessControlManager |
ACM |
Custom | Global role-based permissions (KYB_MANAGER_ROLE, MINTER_ROLE, ORACLE_ROLE) |
HoloFiVaultCard |
HCARD |
ERC-721 | Physical card digital ownership vouchers with metadata & attestation hashes |
HoloFiCardPriceFeed |
CardPriceFeed |
Custom | Oracle price aggregation, staleness thresholds, and batch price feeds |
HoloFiVaultLoanCore |
LoanCore |
Custom | Multi-vault management, collateral custody, borrow/repay execution, and health checks |
HoloFiLendingPoolFactory |
PoolFactory |
Factory | Deterministic deployment and tracking of isolated lending pool instances |
PremiumLendingPool |
pHOLO-PREM |
ERC-4626 | High-grade (PSA 10) stablecoin lending pool |
DeluxeLendingPool |
pHOLO-DLX |
ERC-4626 | Mid-grade (PSA 9) stablecoin lending pool |
PremiumGradeEligibilityPolicy |
Policy |
Custom | Admission validator enforcing PSA 10 eligibility on Premium Pool deposits |
DeluxeGradeEligibilityPolicy |
Policy |
Custom | Admission validator enforcing PSA 9 eligibility on Deluxe Pool deposits |
HoloFiDutchAuction |
DutchAuction |
Custom | Gradual Dutch auction engine for liquidating under-collateralized vaults |
MockAsset / EURC |
EURC |
ERC-20 | Protocol underlying stablecoin token |
Create a local .env file by copying .env.example:
cp .env.example .env| Variable Name | Required | Default / Example | Purpose |
|---|---|---|---|
NEXTAUTH_SECRET |
Yes | min_32_chars_random_string |
Cryptographic secret for signing NextAuth JWT sessions |
NEXTAUTH_URL |
Yes | http://localhost:3000 |
Canonical application URL for authentication callbacks |
MONGODB_URI |
Yes | mongodb://localhost:27017/holofi |
Connection string for MongoDB (shared with Oracle service) |
MONGODB_DB_NAME |
No | holofi |
Target MongoDB database name |
NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID |
Yes | c19e59cf5c77... |
WalletConnect Cloud Project ID for RainbowKit |
NEXT_PUBLIC_DEFAULT_CHAIN_ID |
Yes | 31337 / 84532 |
Default active chain (31337=Localhost, 84532=Base Sepolia) |
NEXT_PUBLIC_RPC_URL |
Yes | http://127.0.0.1:8545 |
Primary RPC endpoint for blockchain reads and transactions |
NEXT_PUBLIC_ACCESS_CONTROL_MANAGER_ADDRESS |
Yes | 0xe7f1725E... |
Address of AccessControlManager |
NEXT_PUBLIC_CARD_PRICE_FEED_ADDRESS |
Yes | 0xCf7Ed3Ac... |
Address of HoloFiCardPriceFeed |
NEXT_PUBLIC_POOL_FACTORY_ADDRESS |
Yes | 0xDc64a140... |
Address of HoloFiLendingPoolFactory |
NEXT_PUBLIC_VAULT_CARD_ADDRESS |
Yes | 0x5FC8d326... |
Address of HoloFiVaultCard (ERC-721) |
NEXT_PUBLIC_LOAN_CORE_ADDRESS |
Yes | 0x0165878A... |
Address of HoloFiVaultLoanCore |
NEXT_PUBLIC_DUTCH_AUCTION_ADDRESS |
Yes | 0x610178dA... |
Address of HoloFiDutchAuction |
NEXT_PUBLIC_DEFAULT_POOL_ADDRESS |
Yes | 0x856e4424... |
Default fallback lending pool address |
NEXT_PUBLIC_PREMIUM_POOL_ADDRESS |
Yes | 0x856e4424... |
Address of PremiumLendingPool |
NEXT_PUBLIC_DELUXE_POOL_ADDRESS |
Yes | 0xb0279Db6... |
Address of DeluxeLendingPool |
NEXT_PUBLIC_PREMIUM_POLICY_ADDRESS |
Yes | 0x0B306BF9... |
Address of PremiumGradeEligibilityPolicy |
NEXT_PUBLIC_DELUXE_POLICY_ADDRESS |
Yes | 0x9A676e78... |
Address of DeluxeGradeEligibilityPolicy |
NEXT_PUBLIC_MOCK_USDC_ADDRESS |
Yes | 0x5FbDB231... |
Address of underlying stablecoin (EURC/USDC) |
ADMIN_PRIVATE_KEY |
Yes | 0xac0974be... |
Server-only private key for executing admin contract actions |
PINATA_JWT |
Yes | eyJhbGci... |
Pinata API JWT token for uploading images and metadata to IPFS |
PINATA_GATEWAY |
Yes | gateway.pinata.cloud |
Pinata dedicated gateway domain |
NEXT_PUBLIC_IPFS_GATEWAY |
Yes | https://gateway.pinata.cloud/ipfs/ |
Public IPFS gateway prefix for client rendering |
ORACLE_API_URL |
Yes | http://localhost:3001 |
HoloFi Oracle API service base URL |
ORACLE_API_KEY |
Yes | bearer_token... |
API secret key for Oracle service communication |
BLOB_READ_WRITE_TOKEN |
Optional | vercel_blob_rw_... |
Vercel Blob token for cloud document storage |
Caution
Never expose ADMIN_PRIVATE_KEY or NEXTAUTH_SECRET on the client side. The frontend exclusively accesses ADMIN_PRIVATE_KEY inside server-only modules (src/lib/web3/adminActions.ts).
- Node.js
20.xor22.x(LTS recommended) - MongoDB instance running locally or on MongoDB Atlas
- Local EVM node (Hardhat/Anvil) or active Base Sepolia testnet RPC
npm installnpm run devOpen http://localhost:3000 in your browser.
# Seed an institutional administrator account into MongoDB
npm run create-admin
# Synchronize smart contract ABIs from contract build artifacts
npm run sync-abisAlways run the complete quality gate before submitting pull requests or deploying to production:
npx tsc --noEmit && npm run lint && npm run test && npm run build| Command | Action | Success Criteria |
|---|---|---|
npx tsc --noEmit |
Strict TypeScript typecheck | 0 compile errors across all components, hooks, and API routes |
npm run lint |
ESLint static code analysis | 0 linting errors or deprecated API usage |
npm run test |
Vitest unit & integration testing | All 16 test suites (109+ unit tests) pass |
npm run test:watch |
Vitest interactive test runner | Continuous feedback during test-driven development |
npm run build |
Next.js production build with Turbopack | Zero build warnings, all static and dynamic routes compiled |
Copyright © 2026 HoloFi Protocol. All rights reserved.

