Skip to content

Textile Protocol v2.1 Documentation โ€‹

Welcome to the Textile Protocol v2.1 documentation! This directory contains guides for different audiences.

๐Ÿ“š Documentation Index โ€‹

For Developers โ€‹

Developer Guide

  • 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

Upgradeability Guide

  • 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 โ€‹

Auditor Introduction

  • 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.md in the monorepo

๐ŸŽจ Visual Documentation โ€‹

Flow Diagrams โ€‹

All major operations are documented with Mermaid diagrams in the flows/ directory:

  1. Architecture Overview - Complete system diagram
  2. Deposit Flow - LP deposit process
  3. Drawdown Flow - Borrower capital deployment
  4. Repayment Flow - Interest and principal repayment
  5. Withdrawal Approval Flow - Three-step withdrawal
  6. 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/):

ContractPurposeLines of CodeUpgradeable
StructuredPoolCoordinates pool operations & manages integrated credit line~1,200โœ… BeaconProxy
TrancheERC4626 vault for lenders~900โœ… BeaconProxy
ReserveImmutable asset custody~280โŒ Immutable

Infrastructure (contracts/v2.1/infrastructure/):

ContractPurposeLines of Code
RegistryCentral infrastructure hub405
WithdrawalRegistryManages withdrawal approvals326
UnderwriterRegistryPublic underwriter registry239
ProtocolConfigurationGlobal settings and fees147

Factory (contracts/v2.1/factory/):

ContractPurposeLines of Code
PoolFactoryDeploys pools via minimal proxies197

Abstract Base Contracts (2 Contracts) โ€‹

Located in contracts/v2.1/base/:

ContractPurposeLines
AccessControlHelpersGovernance self-bricking prevention106
AccessControlHelpersUpgradeableUpgradeable governance protection109

Supporting Libraries (6 Libraries) โ€‹

Organized by function in contracts/v2.1/libraries/:

LibraryLocationPurposeLines
Errorshelpers/Custom error definitions88
MathUtilsmath/Interest rate calculations122
ValidationLogiclogic/Settings validation155
SettingsProposallogic/2-step approval pattern101
Rolesaccess/Role definitions48
DataTypestypes/Data structures48

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:local

Addresses 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 call
  • getPoolMetrics() - Complete pool stats
  • getDebtDetails() - 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 โ€‹

MetricValue
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?

  1. Check existing issues on GitHub
  2. Create a new issue with details
  3. Tag with appropriate labels
  4. Follow up on discussion

Documentation Improvements โ€‹

Have a documentation suggestion?

  1. Identify which doc needs updating
  2. Submit a PR with changes
  3. Explain the improvement
  4. Tag @protocol-team for review

Code Contributions โ€‹

Want to contribute code?

  1. Read the Developer Guide
  2. Check open issues for "good first issue" tags
  3. Fork, branch, and implement
  4. Submit PR with tests
  5. 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 โ€‹


Happy Building! ๐Ÿš€

Last Updated: 2025-10-21Protocol Version: v2.1 (Single Tranche)Documentation Version: 1.3Test Suite: 884 tests passing โœ