$ show 0dotxyz/marginfi-v2
This repository contains the full implementation of the Marginfi v2 protocol, a decentralized lending and borrowing platform on Solana. The core is an Anchor-based Rust smart contract that manages deposits, borrows, repays, liquidations, orders, and flash loans across multiple assets. It integrates with external lending protocols (Kamino, Drift, Solend, JupLend) via cross-program invocation (CPI), allowing users to use positions from those protocols as collateral. The codebase also includes a comprehensive CLI tool (p0-cli) for admin operations and user interaction, a standalone type crate for shared data structures, multiple mock programs for integration testing, and extensive test suites (Rust integration tests, TypeScript bankrun tests, and fuzz testing with Trident and libfuzzer). The architecture is a single Solana program with a rich set of instruction handlers, supported by off-chain tooling. The repository demonstrates high engineering craftsmanship with well-structured code, reusable components, and thorough testing across many edge cases.
The LLM identified 4 files worth highlighting for reuse:
A standalone crate providing zero-copy data structures (Bank, MarginfiAccount, FeeState, etc.) with bytemuck support and optional Anchor integration. This is the canonical type definition for marginfi's on-chain state, used by the program, CLI, and tests. It is well-isolated, has minimal dependencies, and could be extracted by any project that needs to interact with marginfi accounts or replicate the state model.
A custom forward-allocating bump allocator that replaces Solana's default allocator for the program. It supports heap_pos/heap_restore for memory recycling, useful for compute-heavy operations like risk engine calculations. The allocator is isolated, uses only core/std, and demonstrates non-obvious Solana optimization. Could be extracted into any Solana program that needs to avoid heap reallocation overhead.
A dual-window (hourly/daily) outflow rate limiter implementation using slot-based tracking with sequence numbers. Includes unit tests for edge cases like overflow, empty updates, and unauthorized admin. The logic is generic and encapsulated in a struct with clear methods (record, can_perform, update). Could be extracted as a standalone library for any Solana program needing rate limiting on aggregate outflows.
Provides utilities to validate the ordering of instructions within a transaction, enforcing that certain operations (like liquidation start/end) are paired and that only allowed programs are invoked. This is a critical security pattern for protocols that require multi-step transactions. The implementation is self-contained, uses only solana_program types, and could be reused by any program needing to introspect and constrain transaction layout.