Hooks and Programmable Lending
Learning Objectives
Explain how Hooks work including the execution model, state management, and transaction modification capabilities
Compare Hooks to Ethereum smart contracts understanding similarities, differences, and trade-offs
Identify what Hooks enable for lending including interest calculation, collateral management, and liquidation automation
Assess Hooks limitations and risks including execution constraints, audit requirements, and maturity concerns
Evaluate the current Hooks ecosystem understanding development status, tooling, and timeline expectations
- **Security through simplicity** - Fewer features = smaller attack surface
- **Performance** - No arbitrary code execution = predictable transaction costs
- **Reliability** - Native features are extensively tested protocol code
This approach created a stable, fast network. It also limited innovation—developers couldn't build arbitrary applications without waiting for protocol amendments.
Hooks changed this.
Introduced in 2024, Hooks allow developers to attach custom WebAssembly code to XRPL accounts. When transactions interact with a hooked account, the code executes—enabling custom logic without modifying the base protocol.
- Before Hooks: Could only use native features (trust lines, escrow)—insufficient for Aave-style protocols
- After Hooks: Can build interest rate models, liquidation logic, pool accounting—everything lending requires
But Hooks are new, and new infrastructure carries risk.
This lesson provides both the technical understanding and the appropriate skepticism for evaluating Hooks-based lending.
Understanding when and how Hooks run:
HOOK EXECUTION MODEL:
When Hooks Execute:
├── Before transaction (ttTRANSACTION): Can modify or reject
├── After transaction (ttCALLBACK): Can emit new transactions
├── On every transaction involving the hooked account
└── Hooks don't run independently—triggered by transactions
Hook Account Flow:
- Transaction targets Account X (has Hook installed)
- Hook code loads
- Hook executes BEFORE transaction settles
- Hook can:
- Transaction settles (if accepted)
- Hook may run AFTER for callbacks
VISUAL FLOW:
Incoming TX ──> [Hook Pre-Process] ──> Accept/Reject/Modify
│
├── If Accept ──> TX Settles ──> [Hook Post-Process]
│ │
│ └── May Emit new TX
│
└── If Reject ──> TX Fails (with reason code)
KEY CONCEPTS:
Deterministic Execution:
├── Same inputs always produce same outputs
├── No randomness allowed
├── Validators must agree on results
└── Essential for consensus
Resource Limits:
├── Execution time limits
├── Memory limits
├── State storage limits
├── Fee implications for complex Hooks
└── Prevents DoS attacks
State Persistence:
├── Hooks can read/write state
├── State persists between executions
├── Like contract storage in Ethereum
├── Enables complex applications
└── Limited size
```
How Hooks are created and deployed:
HOOK DEVELOPMENT PROCESS:
Writing Hooks:
Language:
├── C (most common currently)
├── Compiles to WebAssembly (WASM)
├── Assembly-level control
├── Steep learning curve vs. Solidity
└── Other languages possible in future
Available Functions:
├── Transaction inspection (read incoming TX data)
├── State operations (read/write hook state)
├── Emission (create new transactions)
├── Utility functions (math, crypto)
├── Tracing/debugging
└── Limited but sufficient for DeFi
DEPLOYMENT:
- Write Hook code (C)
- Compile to WASM
- Test on testnet
- Audit (if serious)
- Deploy via SetHook transaction
- Hook attached to your account
- Active immediately
HOOK INSTALLATION:
SetHook Transaction:
├── Specifies: Hook code (WASM binary)
├── Specifies: Namespace (isolate state)
├── Specifies: Flags (when to trigger)
├── Specifies: Grant permissions
└── Fee proportional to code size
Multiple Hooks:
├── Account can have multiple Hooks
├── Execute in defined order
├── Chain logic together
├── Compose functionality
└── Complexity management
DEVELOPMENT EXAMPLE (Pseudocode):
// Simple Hook: Reject payments under 10 XRP
int64_t hook(uint32_t reserved) {
// Get transaction type
int64_t tt = otxn_type();
// Only process payments
if (tt != ttPAYMENT)
return accept("Not a payment", 13);
// Get payment amount
int64_t amount = otxn_amount();
// Check threshold
if (amount < 10000000) // 10 XRP in drops
return rollback("Payment too small", 17);
return accept("Payment accepted", 16);
}
```
Persistent storage for lending protocols:
HOOK STATE:
What Hook State Is:
├── Key-value storage attached to Hook
├── 32-byte keys, variable-value sizes
├── Persists between executions
├── Readable by other Hooks (if permitted)
└── Like Ethereum contract storage
State Operations:
├── state_set(): Write value
├── state(): Read value
├── state_foreign(): Read other Hook's state
└── Limited total size per Hook
STATE FOR LENDING:
What You'd Store:
User Positions:
├── Key: User account hash
├── Value: Collateral amount, debt amount, last update
├── Track each user's position
└── Update on deposits, borrows, repayments
Protocol State:
├── Key: Fixed protocol keys
├── Value: Total supplied, total borrowed, reserve factor
├── Track aggregate metrics
├── Update interest rate calculations
Interest Accrual:
├── Key: Per-position or global
├── Value: Last accrual timestamp, cumulative index
├── Enable compound interest
└── Update on interactions or periodically
EXAMPLE STATE STRUCTURE:
// Position state for user Alice
Key: sha256("POSITION:" + Alice_account)
Value: {
collateral_amount: 1000 XRP (in drops)
debt_amount: 500 USD (in smallest unit)
last_update_ledger: 80000000
health_factor: 1.5 (calculated, may not store)
}
// Protocol globals
Key: sha256("GLOBAL:TOTAL_SUPPLIED")
Value: 1000000 XRP
Key: sha256("GLOBAL:UTILIZATION")
Value: 65% (scaled integer)
STATE LIMITATIONS:
Size Limits:
├── Per-key value limits
├── Total state size limits
├── Must design efficient encoding
└── Can't store unlimited data
Gas/Fee Implications:
├── State writes cost more than reads
├── Large state operations expensive
├── Optimize for efficiency
└── Different economics than Ethereum
State Migration:
├── Upgrading Hooks may need state migration
├── Old state may not fit new schema
├── Planning required for upgrades
└── Governance consideration
---
How Hooks differ from Solidity contracts:
FEATURE COMPARISON:
| XRPL Hooks | Ethereum Contracts
───────────────────────────────────────────────────────────────
Language | C → WASM | Solidity → EVM
Execution Trigger | TX to account | Contract call
State Storage | Limited key-value | Extensive storage
Composability | Limited | Extensive
Flash Loans | Complex to impl | Native pattern
Gas Model | Fixed fee tiers | Variable gas
Transaction Speed | 3-5 seconds | 12-15 seconds
Developer Ecosystem | Small | Massive
Audit Resources | Limited | Extensive
Battle Testing | Minimal | Years of exploits
EXECUTION MODEL DIFFERENCES:
Ethereum:
├── Contract is called by transaction
├── Contract can call other contracts
├── Deep composability (contract A calls B calls C)
├── msg.sender, tx.origin patterns
├── Reentrancy is possible (and dangerous)
└── Very flexible
XRPL Hooks:
├── Hook triggered by transaction TO hooked account
├── Hook can emit new transactions
├── But emitted TXs settle later (not same ledger usually)
├── Limited call-chain depth
├── Reentrancy model different
└── More constrained
IMPLICATIONS FOR LENDING:
Ethereum Advantage - Composability:
├── Deposit aTokens in another protocol
├── Borrow, then immediately use in yield farming
├── Complex strategies in single TX
└── Deep DeFi legos
XRPL Limitation:
├── Can deposit and get receipt token
├── But using that token elsewhere is separate TX
├── Multi-step strategies need multiple TXs
├── Less composable (currently)
XRPL Advantage - Simplicity:
├── Simpler model may mean fewer bugs
├── Less reentrancy risk (different model)
├── Easier to reason about
└── Security through constraints
```
Critical lending feature assessment:
FLASH LOANS ON XRPL:
Ethereum Flash Loan Model:
├── Borrow → Use → Repay in SAME transaction
├── Atomic: If repay fails, everything reverts
├── Zero capital risk to borrower
├── Enables capital-efficient liquidations
└── Core DeFi primitive
XRPL Challenge:
Atomicity Problem:
├── Hooks emit transactions
├── Emitted TXs settle in FUTURE ledger
├── Not same-TX atomicity
├── Can't borrow-use-repay in single ledger close
└── Different model needed
POSSIBLE APPROACHES:
Approach 1: Pseudo-Flash via Hook Chain
├── Complex Hook that processes everything internally
├── No external TX needed
├── Limited to what one Hook can do
├── May work for simple cases
└── Not true composable flash loan
Approach 2: Trusted Settlement
├── Flash loan provider trusts certain contracts
├── If repayment fails, clawback
├── Requires clawback-enabled tokens
├── Not trustless in same way
└── Different trust assumptions
Approach 3: Payment Channels
├── Pre-fund channel, use off-chain
├── Settle on-chain
├── Different mechanism entirely
└── Not really flash loans
REALISTIC ASSESSMENT:
Flash loans as Ethereum knows them:
├── Probably not possible on XRPL
├── Fundamentally different execution model
├── May need different patterns
Alternative Approaches:
├── Capital-efficient liquidations possible other ways
├── Keeper networks with staked capital
├── Different but potentially functional
└── Not a complete blocker
Implication:
├── XRPL lending will look different than Ethereum
├── Can't just copy Aave architecture
├── Need XRPL-native designs
└── Opportunity for innovation
```
Assessing ecosystem readiness:
MATURITY COMPARISON:
ETHEREUM SMART CONTRACTS:
Battle Testing:
├── 8+ years of production
├── $100B+ TVL at peak
├── Billions lost to hacks (learning)
├── Well-understood attack vectors
├── Extensive security research
└── Known unknowns
Developer Ecosystem:
├── Millions of Solidity developers
├── Extensive tooling
├── Multiple audit firms
├── Bug bounty culture
├── OpenZeppelin libraries
└── Mature infrastructure
Lending Specific:
├── Aave: 4+ years, multiple versions
├── Compound: 6+ years
├── Known vulnerabilities documented
├── Best practices established
└── Safe patterns exist
XRPL HOOKS:
Battle Testing:
├── ~1 year since mainnet launch
├── Minimal TVL in hooks
├── No major hacks (small target)
├── Attack vectors less explored
├── Security research limited
└── Unknown unknowns
Developer Ecosystem:
├── Dozens/hundreds of Hooks devs
├── Tooling developing
├── Few audit firms familiar
├── Bug bounty programs emerging
├── No standard libraries yet
└── Early infrastructure
Lending Specific:
├── No major lending protocol deployed
├── No production track record
├── Best practices not established
├── Patterns being discovered
└── First mover risk
RISK ASSESSMENT:
Early XRPL Lending Protocol Risk:
├── Smart contract risk: HIGH (unproven code)
├── Economic design risk: MEDIUM (can learn from ETH)
├── Operational risk: HIGH (new tooling)
├── Audit quality risk: HIGH (limited expertise)
└── Total: SIGNIFICANTLY HIGHER than Ethereum
Timeline Expectation:
├── For mature XRPL lending: 2-4 years
├── For basic functional lending: 1-2 years
├── For fully battle-tested: 3-5+ years
└── Patience required
---
How a Hooks-based lending protocol would work:
XRPL LENDING PROTOCOL ARCHITECTURE:
CORE COMPONENTS:
Pool Hook
Collateral Hook
Liquidation Hook
Interest Hook
Oracle Hook (or External Integration)
TRANSACTION FLOWS:
Deposit Flow:
User ──[Payment]──> Pool Hook Account
Pool Hook:
├── Receives payment
├── Updates user's supply balance (state)
├── Emits share tokens to user
├── Updates total supplied
└── Accepts transaction
Borrow Flow:
User ──[Borrow Request TX]──> Pool Hook Account
Pool Hook:
├── Checks user's collateral (cross-hook state read)
├── Calculates health factor with new borrow
├── If healthy: Emits borrowed asset to user
├── Updates debt balance (state)
└── Accepts if valid, rejects if unhealthy
Liquidation Flow:
Liquidator ──[Liquidation TX]──> Liquidation Hook Account
Liquidation Hook:
├── Identifies target position
├── Calculates health factor
├── If HF < 1.0: Proceeds
├── Receives repayment from liquidator
├── Emits collateral to liquidator
├── Updates position state
└── Accepts if valid liquidation
```
Specific implementation difficulties:
CHALLENGE 1: CROSS-HOOK COMMUNICATION
Problem:
├── Pool, Collateral, Liquidation are separate Hooks
├── Need to share state
├── Hook state isolation by default
└── Must design communication
Solutions:
├── state_foreign(): Read other Hook's state
├── Shared namespace grants
├── Common account with multiple Hooks
├── Careful permission design
└── Still more complex than single Solidity contract
---
CHALLENGE 2: INTEREST ACCRUAL
Problem:
├── Interest should compound continuously
├── Hooks only run on transactions
├── No background processes
└── How to keep interest updated?
Solutions:
├── Accrue on every interaction (like Ethereum)
├── Store: lastUpdateLedger, interestIndex
├── Calculate: time elapsed × rate
├── Update both position and global state
├── Works but requires careful math
Implementation:
├── On any position interaction:
├── 1. Get current ledger
├── 2. Calculate time since last update
├── 3. Apply interest to debt/supply
├── 4. Update lastUpdateLedger
└── Matches Aave pattern
---
CHALLENGE 3: LIQUIDATION TIMING
Problem:
├── Position becomes unhealthy between TXs
├── No automatic trigger
├── Must wait for someone to call liquidation
└── Position may deteriorate further
Solutions:
├── Keeper network monitors positions
├── Economic incentive (liquidation bonus)
├── Any transaction can trigger check
├── Similar to Ethereum model
└── Not a blocker, just requires infrastructure
---
CHALLENGE 4: ORACLE INTEGRATION
Problem:
├── Need reliable price feeds
├── Can't use DEX prices safely (manipulation)
├── External oracles must push to XRPL
└── Oracle infrastructure immature
Solutions:
├── Build oracle push mechanism
├── Multiple sources for redundancy
├── TWAP from DEX + external validation
├── Chainlink equivalent needed
└── Major infrastructure requirement
Current State:
├── No dominant XRPL oracle solution
├── Various projects working on it
├── Gap in ecosystem
└── Must be solved for lending
---
CHALLENGE 5: UPGRADABILITY
Problem:
├── Hooks code deployed to account
├── Bugs found after deployment
├── How to upgrade safely?
└── User funds at risk during migration
Solutions:
├── Proxy patterns (like Ethereum)
├── Governance-controlled upgrades
├── Time-locks and safety checks
├── State migration procedures
└── Plan for upgrades from start
Realistic timeline assessment:
ACHIEVABLE TODAY (2025):
Basic Lending Hook:
├── Single-asset collateral
├── Single-asset borrowing
├── Simple interest model
├── Manual-ish liquidations
├── Proof of concept quality
└── Not production-ready for serious capital
What Exists:
├── Hooks documentation and tooling
├── Testnet deployments
├── Developer experimentation
├── No major lending protocol in production
└── Ecosystem building phase
ACHIEVABLE NEAR-TERM (2025-2026):
Functional Lending Protocol:
├── Multi-asset support
├── Automated interest accrual
├── Keeper-enabled liquidations
├── Basic oracle integration
├── Audit completed
├── Small TVL deployment
└── Beta quality, use with caution
Requirements:
├── Team with Hooks expertise
├── Proper audit investment
├── Oracle solution
├── Liquidity bootstrapping
├── Community building
└── 12-18 months development
ACHIEVABLE MEDIUM-TERM (2026-2028):
Mature Lending Protocol:
├── Battle-tested code
├── Significant TVL ($100M+?)
├── Multiple audits
├── Proven liquidation system
├── Reliable oracle infrastructure
├── Governance system
└── Comparable to early Aave
Requirements:
├── Sustained development
├── Market cycle survival
├── Ecosystem maturation
├── Regulatory clarity
├── User adoption
└── Years of operation
HONEST TIMELINE:
For "Aave on XRPL" quality:
├── Technical capability: Now
├── Ecosystem maturity: 2-3 years
├── Battle-tested confidence: 4-5 years
├── First mover: 1-2 years
└── Patient capital required
---
How to assess any XRPL lending protocol:
EVALUATION FRAMEWORK:
CATEGORY 1: CODE QUALITY (30%)
Questions:
├── Is code open source? Can you review it?
├── How complex is the Hook code?
├── Are there obvious vulnerabilities?
├── Does it follow known patterns?
└── Is there documentation?
Red Flags:
├── Closed source code
├── No documentation
├── Overly complex for stated function
├── No version control history
├── Copy-paste without understanding
Green Flags:
├── Clean, readable code
├── Comprehensive documentation
├── Clear logic flow
├── Matches stated functionality
├── Active development history
---
CATEGORY 2: AUDIT STATUS (25%)
Questions:
├── Has it been audited?
├── By whom? (reputation matters)
├── Are audit reports public?
├── Were findings fixed?
├── Any ongoing security program?
Red Flags:
├── "Audit pending" indefinitely
├── Unknown auditor
├── Audit report hidden
├── Critical findings not fixed
├── No bug bounty
Green Flags:
├── Reputable auditor completed
├── Public report available
├── All critical/high fixed
├── Active bug bounty
├── Security-first culture
---
CATEGORY 3: TEAM QUALITY (20%)
Questions:
├── Who built it? (real names or pseudonyms)
├── What's their track record?
├── Do they have Hooks expertise?
├── Are they responsive to issues?
├── Long-term commitment?
Red Flags:
├── Anonymous team, no track record
├── No visible community engagement
├── Can't answer technical questions
├── Signs of exit planning
├── Over-promising timelines
Green Flags:
├── Known team or strong pseudonymous reputation
├── Prior relevant experience
├── Active community presence
├── Technical depth evident
├── Long-term roadmap
---
CATEGORY 4: ECONOMIC DESIGN (15%)
Questions:
├── Where do yields come from?
├── Is interest model sustainable?
├── Are parameters conservative?
├── How does liquidation work?
├── Token economics?
Red Flags:
├── Yields too good to be true
├── Complex token schemes
├── Aggressive parameters
├── No clear revenue model
├── Emission-dependent yields
Green Flags:
├── Clear interest rate model
├── Conservative collateralization
├── Sustainable protocol revenue
├── No mandatory native token
├── Aligned incentives
---
CATEGORY 5: OPERATIONAL MATURITY (10%)
Questions:
├── How long has it been running?
├── Any incidents? How handled?
├── What's the TVL trajectory?
├── User testimonials?
├── Governance process?
Red Flags:
├── Just launched, high TVL claims
├── Incidents covered up
├── Mysterious TVL spikes
├── No real users
├── Unilateral control
Green Flags:
├── Months of operation
├── Transparent incident handling
├── Organic growth
├── Active user community
├── Evolving governance
Appropriate caution levels:
RISK CALIBRATION FOR XRPL LENDING:
RISK TIER 1: EXPERIMENTAL
Description: First weeks/months, unaudited or newly audited
Appropriate Allocation: 0-1% of crypto portfolio
Who Should Participate: Developers, testers, tiny positions
Expected: Bugs, exploits, total loss possible
RISK TIER 2: EARLY STAGE
Description: Audited, few months operation, small TVL
Appropriate Allocation: 1-3% of crypto portfolio
Who Should Participate: Risk-tolerant, understand Hooks
Expected: Some issues, protocol may pivot
RISK TIER 3: MATURING
Description: Multiple audits, year+ operation, growing TVL
Appropriate Allocation: 3-10% of crypto portfolio
Who Should Participate: DeFi-savvy investors
Expected: Occasional issues, generally stable
RISK TIER 4: ESTABLISHED
Description: Years of operation, large TVL, battle-tested
Appropriate Allocation: 10-20% of crypto portfolio
Who Should Participate: General crypto investors
Expected: Rare issues, professional response
CURRENT XRPL LENDING STATE:
Most protocols: Tier 1 or non-existent
Timeline to Tier 3: 2-3 years
Timeline to Tier 4: 4-5+ years
Compare to Ethereum:
├── Aave: Tier 4 (5+ years)
├── Compound: Tier 4 (6+ years)
├── New protocols: Tier 1-2
└── XRPL lending: Pre-Tier 1 to Tier 1
---
✅ Hooks technical capability exists - XRPL can execute custom WebAssembly code on transactions. The technology works at the protocol level.
✅ Lending logic is implementable - There's no fundamental reason Hooks can't implement interest calculation, collateral management, and liquidation logic. The building blocks exist.
✅ Developer interest is growing - Teams are actively working on DeFi applications including lending. The ecosystem is building.
⚠️ Hooks security in practice - Limited production deployment means attack vectors may not be well understood. Unknown unknowns exist.
⚠️ Flash loan alternatives - Whether XRPL can achieve capital-efficient liquidations without traditional flash loans is unproven.
⚠️ Ecosystem timeline - How quickly mature lending infrastructure will emerge depends on developer adoption, funding, and market conditions.
🔴 Treating Hooks like battle-tested smart contracts - Hooks have a fraction of the production testing that Ethereum contracts have. The risk profile is much higher.
🔴 First-mover overconfidence - Early XRPL lending protocols will likely have issues. Being first doesn't mean being safe.
🔴 Assuming Ethereum patterns transfer directly - XRPL's execution model is different. Copying Aave architecture without adaptation will likely fail.
Hooks enable lending on XRPL—that's clear. What's not clear is the timeline to mature, safe lending protocols. The technical capability exists, but the ecosystem needs years of development, auditing, and battle-testing before XRPL lending matches Ethereum's maturity. Early participants take substantial risk; patient observers may capture opportunity with less exposure.
Assignment: Design a theoretical Hooks-based lending protocol architecture, identifying required components, their interactions, and technical challenges.
Requirements:
Part 1: Component Design (30%)
- Pool Hook (manages liquidity pool)
- Collateral Hook (manages user positions)
- Interest Hook (calculates and applies interest)
- Liquidation Hook (handles unhealthy positions)
- Key state variables
- Main functions/logic paths
- Trigger conditions
- Emitted transactions
Part 2: Interaction Diagram (25%)
- Deposit flow (user deposits collateral)
- Borrow flow (user borrows against collateral)
- Repay flow (user repays debt)
- Liquidation flow (liquidator clears position)
Show which Hooks interact and what data flows between them.
Part 3: Technical Challenge Analysis (25%)
- Cross-Hook state sharing
- Interest accrual timing
- Oracle price integration
- Liquidation triggering without flash loans
- Upgrade path for bug fixes
Part 4: Risk Assessment (20%)
What could go wrong?
What's the potential impact?
What mitigations exist?
What's your confidence level?
Technical soundness (30%)
Comprehensiveness (25%)
Practical feasibility (25%)
Risk awareness (20%)
Time investment: 2-3 hours
Value: This exercise forces you to think through lending implementation details, preparing you to evaluate real protocols.
Knowledge Check
Question 1 of 4(Tests Basic Understanding):
- hooks.xrpl.org - Official Hooks documentation
- XRPL developer documentation on SetHook
- Hooks examples and tutorials
- Hooks Amendment Specification
- WebAssembly (WASM) documentation
- C programming for embedded/constrained systems
- XRPL Labs announcements
- Developer community forums
- Conference presentations on Hooks
For Next Lesson:
Lesson 10 examines emerging XRPL lending protocols—what's being built, what's claimed, and how to evaluate them against the frameworks established in this and previous lessons.
End of Lesson 9
Total words: ~6,700
Estimated completion time: 65 minutes reading + 2-3 hours for deliverable exercise
Key Takeaways
Hooks are XRPL's programmability layer
: WebAssembly code executing on transactions enables custom logic—the foundation for lending protocols.
Hooks differ significantly from Ethereum contracts
: The execution model, composability, and state management work differently. Direct Ethereum copies won't translate.
Flash loans are challenging on XRPL
: Different atomicity model makes Ethereum-style flash loans difficult. Alternative patterns needed for capital-efficient liquidations.
Ecosystem maturity is years away
: Hooks are technically capable but the development ecosystem, audit infrastructure, and battle-testing will take 2-5 years.
Due diligence is critical
: Any early XRPL lending protocol requires extensive evaluation of code, audits, team, and economic design. The framework provided helps structure this assessment. ---