Appearance
Textile Protocol v2.1 Documentation โ
Welcome to the Textile Protocol v2.1 documentation! This directory contains guides for different audiences.
๐ Documentation Index โ
For Developers โ
- Quick start (5-minute setup)
- Architecture overview
- Code examples using viem/wagmi
- Frontend and backend integration
- Auto-interest compounding feature guide
- The Graph subgraph setup
- Event handling and error handling
- Complete function reference
- Audience: Frontend and backend developers
- UUPS proxy pattern explained
- Storage layout rules and best practices
- Testing and verification procedures
- Emergency procedures and rollback
- Complete upgrade example code
- Audience: Protocol admins, DevOps, security teams
For Security Auditors โ
- Complete architecture documentation
- Access control and trust boundaries
- Mathematical specifications
- All core flows with sequence diagrams
- Invariants and safety properties
- Comprehensive audit checklist
- Audience: Security auditors and protocol architects
For DevOps/Deployment โ
Deployment Guide (Available in protocol package)
- Step-by-step deployment instructions
- Local, testnet, and mainnet deployment
- Environment variables reference
- Post-deployment configuration
- Troubleshooting guide
- Audience: DevOps engineers, deployers
- Location:
packages/protocol/scripts/v2.1/README.mdin the monorepo
๐จ Visual Documentation โ
Flow Diagrams โ
All major operations are documented with Mermaid diagrams in the flows/ directory:
- Architecture Overview - Complete system diagram
- Deposit Flow - LP deposit process
- Drawdown Flow - Borrower capital deployment
- Repayment Flow - Interest and principal repayment
- Withdrawal Approval Flow - Three-step withdrawal
- Factory Deployment Flow - Pool deployment sequence
Flow Diagrams README - How to view and use the diagrams
๐๏ธ Protocol Architecture โ
๐ Critical: One Pool = One Borrower โ
Each pool in v2.1 serves exactly one borrower (designated at creation, immutable). This is a fundamental design choice:
- Each StructuredPool has integrated credit line management for one borrower address
- To support multiple borrowers, deploy multiple pools
- Lenders can diversify by depositing into multiple pools
Core Components (8 Contracts) โ
Organized into logical subdirectories for better maintainability:
Core Pool & Tranche (contracts/v2.1/core/):
| Contract | Purpose | Lines of Code | Upgradeable |
|---|---|---|---|
| StructuredPool | Coordinates pool operations & manages integrated credit line | ~1,200 | โ BeaconProxy |
| Tranche | ERC4626 vault for lenders | ~900 | โ BeaconProxy |
| Reserve | Immutable asset custody | ~280 | โ Immutable |
Infrastructure (contracts/v2.1/infrastructure/):
| Contract | Purpose | Lines of Code |
|---|---|---|
| Registry | Central infrastructure hub | 405 |
| WithdrawalRegistry | Manages withdrawal approvals | 326 |
| UnderwriterRegistry | Public underwriter registry | 239 |
| ProtocolConfiguration | Global settings and fees | 147 |
Factory (contracts/v2.1/factory/):
| Contract | Purpose | Lines of Code |
|---|---|---|
| PoolFactory | Deploys pools via minimal proxies | 197 |
Abstract Base Contracts (2 Contracts) โ
Located in contracts/v2.1/base/:
| Contract | Purpose | Lines |
|---|---|---|
| AccessControlHelpers | Governance self-bricking prevention | 106 |
| AccessControlHelpersUpgradeable | Upgradeable governance protection | 109 |
Supporting Libraries (6 Libraries) โ
Organized by function in contracts/v2.1/libraries/:
| Library | Location | Purpose | Lines |
|---|---|---|---|
| Errors | helpers/ | Custom error definitions | 88 |
| MathUtils | math/ | Interest rate calculations | 122 |
| ValidationLogic | logic/ | Settings validation | 155 |
| SettingsProposal | logic/ | 2-step approval pattern | 101 |
| Roles | access/ | Role definitions | 48 |
| DataTypes | types/ | Data structures | 48 |
Deprecated Contracts (v2-deprecated) โ
Legacy contracts from earlier protocol versions are maintained in contracts/v2-deprecated/ for reference and backwards compatibility. These include:
- Core:
CreditLineController.sol,CreditLineLIController.sol,VaultV2.sol,VaultV2LI.sol - Libraries: Minimal error set (24 lines), legacy validation, interest index logic, rate calculations
- Interfaces: Legacy controller and vault interfaces
Note: Deprecated contracts are not recommended for new deployments.
๐งช Testing โ
Test Coverage โ
35+ comprehensive test files organized by component:
- Tranche: 8 test files (ERC4626 compliance, fees, inflation protection, interest compounding, access control)
- StructuredPool: 7 test files (deployment, access control, underwriter, tranche settings, repayment during shutdown, upgradeability, drawdown, repayment, interest)
- Registry: 4 test files (registration, access control, role rotation)
- Reserve: 2 test files (custody, access control)
- WithdrawalRegistry: 3 test files (request/approve/consume flows, access control)
- ProtocolConfiguration: 2 test files (configuration, access control, governance self-bricking prevention)
- Factory: 3 test files (deployment, security, access control)
- Libraries: 3 test files (math, validation, roles)
- Total Test Cases: 884 individual tests โ
Running Tests โ
bash
# All v2.1 tests
cd packages/protocol
yarn test
# Specific component
yarn hardhat test test/v2.1/Tranche/
# With gas reporting
REPORT_GAS=true yarn test
# With coverage
yarn hardhat coverage๐ Quick Start โ
1. Local Development โ
bash
# Terminal 1: Start Hardhat node
cd packages/protocol
yarn hardhat node
# Terminal 2: Deploy v2.1
yarn deploy:v2:localAddresses saved to: packages/constants/src/addresses.localhost.json
2. Interact with a Pool โ
typescript
import { useContractRead, useContractWrite } from 'wagmi'
import { parseUnits } from 'viem'
import { SAMPLE_POOL } from '@textile/constants'
// Deposit
const { write: deposit } = useContractWrite({
address: trancheAddress,
abi: TrancheABI,
functionName: 'deposit',
args: [parseUnits('1000', 6), userAddress]
})See Developer Guide for complete examples.
3. Deploy to Testnet โ
bash
# Configure environment variables
cp .env.example .env
# Edit .env with your keys
# Deploy to Celo Sepolia (Celo testnet)
yarn deploy:v2:celo-sepolia๐ฏ Key Improvements in v2.1 โ
Coming from v1.x or v2.0? Here's what's new:
1. ERC4626 Standard Compliance โ
- Tranches are now industry-standard vaults
- Compatible with DeFi aggregators
- Standardized deposit/withdraw interface
2. Immutable Custody (Reserve) โ
- Trustless asset custody
- No upgrade mechanism
- Guardian with 3-day timelock for emergencies only
3. Consolidated Architecture โ
- Credit line logic is now integrated directly into
StructuredPool - Reduces architectural complexity and deployment steps
- Pool includes integrated credit line management
- State preserved during upgrades via BeaconProxy pattern
4. Factory Pattern โ
- Deploy pools and tranches via BeaconProxies
- Standardized and secure mass upgrade capability via Beacons
- Auto-registers pool in Registry
5. Helper Functions โ
getVirtualBalances()- All accounting in one callgetPoolMetrics()- Complete pool statsgetDebtDetails()- Full debt breakdown- More efficient RPC usage
6. Withdrawal Approval System โ
- Optional two-step withdrawal flow
- Reserved shares prevent borrowing approved funds
- Better liquidity management
- Prevents bank-run scenarios
7. Settings Proposals โ
- 2-step approval for critical changes (if pool has underwriter)
- Manager proposes, underwriter approves
- Default 7-day expiry window (not a mandatory waiting period)
- Without underwriter, changes apply immediately
8. Per-Second Interest โ
- RAY precision (10^27) calculations
- 4th order binomial approximation for accurate compounding
- More accurate than daily/monthly compounding
- Fair for all participants
๐ Statistics โ
Code Metrics โ
- Total Contracts: 9 core + 2 base contracts = 11 active contracts
- Supporting Libraries: 6 libraries (organized in
helpers/,math/,logic/,access/,types/) - Deprecated Contracts: 4 legacy contracts + 5 deprecated libraries (in
v2-deprecated/) - Lines of Solidity: ~4,400 lines (v2.1 active code)
- Test Files: 35+ comprehensive test suites
- Test Coverage: >95% line coverage
- Documentation: 3,500+ lines across 4 major docs
Performance โ
| Metric | Value |
|---|---|
| Pool Deployment Gas | ~3.5M gas |
| Deposit Gas | ~80k-150k gas |
| Withdrawal Gas | ~70k-90k gas |
| Drawdown Gas | ~120k gas |
| Repayment Gas | ~150k gas |
๐ Security โ
Audit Status โ
- [x] Internal code review complete
- [x] 884 tests passing (35+ test suites)
- [x] Mathematical validation complete
- [x] Upgradeability implementation complete
- [ ] External security audit (pending)
- [ ] Mainnet deployment (after audit)
Best Practices Implemented โ
- โ Custom errors for gas efficiency
- โ ReentrancyGuard on all state-changing functions
- โ Checks-Effects-Interactions pattern
- โ Pausable emergency stops with asymmetric shutdown (repayments allowed)
- โ Inflation attack protection
- โ Settings proposal pattern with 2-step approval
- โ Role-based access control with governance self-bricking prevention
- โ Immutable custody layer
- โ AccessControlHelpers pattern for secure role rotation
๐ค Contributing โ
Report Issues โ
Found a bug or have a suggestion?
- Check existing issues on GitHub
- Create a new issue with details
- Tag with appropriate labels
- Follow up on discussion
Documentation Improvements โ
Have a documentation suggestion?
- Identify which doc needs updating
- Submit a PR with changes
- Explain the improvement
- Tag @protocol-team for review
Code Contributions โ
Want to contribute code?
- Read the Developer Guide
- Check open issues for "good first issue" tags
- Fork, branch, and implement
- Submit PR with tests
- Pass CI checks and review
๐ Version History โ
v2.1 (Current) โ
- Initial release of structured pool architecture
- Single tranche per pool
- ERC4626 compliance
- Immutable custody
- Settings proposals with 2-step approval
- Auto-interest compounding control (per-LP income distribution)
v2.0 (Deprecated) โ
- Experimental multi-tranche implementation
- Not recommended for production use
- Migrate to v2.1
v1.x (Legacy, Still Supported) โ
- Original vault implementation
- No forced migration
- Can coexist with v2.1
๐ Contact โ
- Protocol Team: @textileprotocol (Telegram)
- General Support: support@textilecredit.com
- Security Issues: benoit@textilecredit.com (please report responsibly)
- Partnerships: tomer@textilecredit.com
Happy Building! ๐
Last Updated: 2025-10-21Protocol Version: v2.1 (Single Tranche)Documentation Version: 1.3Test Suite: 884 tests passing โ