diff --git a/docs/src/README.md b/docs/src/README.md index e5502ddd..723d4b2f 100644 --- a/docs/src/README.md +++ b/docs/src/README.md @@ -1,7 +1,33 @@ # Templar Protocol User Guide -This is a high-level user guide for the Templar Protocol smart contracts. +This is a comprehensive user guide for the Templar Protocol smart contracts. For definitions of key terms and concepts, refer to the [Glossary](./glossary.md). -[The API documentation can be found here](../doc/templar_common/index.html). +## Quick Navigation + +- **[Smart Contract Addresses](./contracts.md)** - Official contract addresses and verification +- **[Protocol Governance](./governance.md)** - Administrative controls and upgrade mechanisms +- **[Oracle System](./oracles.md)** - Price feed infrastructure and monitoring +- **[Security Reporting](./security.md)** - Security practices and vulnerability reporting +- **[Monitoring and Risk Management](./monitoring.md)** - Protocol health monitoring systems +- **[Testing and Coverage](./testing.md)** - Comprehensive test suite documentation + +## Market Operations + +- **[Market Overview](./market/README.md)** - Core market functionality +- **[Supply Assets](./market/supply.md)** - How to supply assets to earn yield +- **[Borrow Assets](./market/borrow.md)** - How to borrow against collateral +- **[Liquidations](./market/liquidate.md)** - Liquidation mechanisms and procedures + +## Additional Resources + +- **[API Documentation](../../target/doc/templar_common/index.html)** - Technical API reference (generated by `cargo doc`) +- **[Implementation Notes](./notes.md)** - Technical implementation details + +## Getting Started + +1. **Review Security**: Start with our [Security documentation](./security.md) to understand the protocol's security model +2. **Check Contract Addresses**: Get the latest deployed contracts from [Contract Addresses](./contracts.md) +3. **Understand Market Operations**: Learn about [Market Operations](./market/README.md) +4. **Explore Oracle System**: Understand price feeds in [Oracle Documentation](./oracles.md) diff --git a/docs/src/SUMMARY.md b/docs/src/SUMMARY.md index f481bdbf..5829c317 100644 --- a/docs/src/SUMMARY.md +++ b/docs/src/SUMMARY.md @@ -1,6 +1,12 @@ # Summary - [Introduction](./README.md) +- [Smart Contract Addresses](./contracts.md) +- [Protocol Governance](./governance.md) +- [Oracle System](./oracles.md) +- [Security Reporting](./security.md) +- [Monitoring and Risk Management](./monitoring.md) +- [Testing and Coverage](./testing.md) - [Market](./market/README.md) - [Supply](./market/supply.md) - [Borrow](./market/borrow.md) diff --git a/docs/src/contracts.md b/docs/src/contracts.md new file mode 100644 index 00000000..50b94c04 --- /dev/null +++ b/docs/src/contracts.md @@ -0,0 +1,79 @@ +# Smart Contract Addresses + +This page provides information about Templar Protocol smart contracts and how to interact with them. + +## Deployed Addresses + +### NEAR Mainnet +- **Registry**: `` +- **Pyth Oracle**: `` +- **LST Oracle Adapter**: `` + +### NEAR Testnet +- **Registry**: `` +- **Pyth Oracle**: `` +- **LST Oracle Adapter**: `` + +## Contract Architecture + +### Registry Contract +The registry is the central contract that: +- Stores approved market contract versions +- Deploys new markets with specific configurations +- Maintains a list of all deployed markets + +### Market Contracts +Market contracts are deployed dynamically through the registry. Each market represents a single asset pair (COLLATERAL → BORROW). + +To get the current list of deployed markets: +```bash +near view list_deployments '{"offset": 0, "count": 100}' +``` + +### Oracle Contracts +- **Pyth Oracle**: Provides price feeds for assets ([Documentation](https://docs.pyth.network/)) +- **LST Oracle Adapter**: Transforms base oracle prices for liquid staking tokens + +## Interacting with Contracts + +### Querying Market Information +```bash +# Get all deployed markets +near view list_deployments '{"offset": 0, "count": 100}' + +# Get specific market deployment info +near view get_deployment '{"account_id": ""}' + +# Query market configuration +near view get_configuration '{}' +``` + +### Contract Verification + +All smart contracts use reproducible builds. To verify deployed code: + +1. **Build locally**: + ```bash + cd contract/market + cargo near build reproducible-wasm + ``` + +2. **Compare with registry deployment records**: + ```bash + # Get deployment hash from registry + near view get_deployment '{"account_id": ""}' + ``` + +## Contract ABIs and Schemas + +After building, contract WASMs are available in `target/near/`: +- **Market**: `target/near/templar_market_contract/templar_market_contract.wasm` +- **Registry**: `target/near/templar_registry_contract/templar_registry_contract.wasm` +- **LST Oracle**: `target/near/templar_lst_oracle_contract/templar_lst_oracle_contract.wasm` + +## Getting Current Addresses + +For deployed contract addresses, check: +- **Official Website**: [templarfi.org](https://templarfi.org/) +- **Discord**: [Templar Protocol Discord](https://discord.gg/KAvMtYpbep) +- **Telegram**: [Templar Protocol Telegram](https://t.me/templarprotocol) diff --git a/docs/src/governance.md b/docs/src/governance.md new file mode 100644 index 00000000..a7ce24b2 --- /dev/null +++ b/docs/src/governance.md @@ -0,0 +1,130 @@ +# Protocol Governance and Administrative Controls + +This document outlines the current administrative structure and governance controls of Templar Protocol. + +## Contract Upgradeability + +### Registry Contract +- **Upgrade Status**: Upgradeable through owner account +- **Owner Account**: `` +- **Upgrade Mechanism**: Direct contract code replacement +- **Timelock**: No timelock implemented + +### Market Contracts +- **Upgrade Status**: Immutable once deployed +- **Deployment**: Markets are deployed through the registry with immutable code +- **Version Control**: New market versions can be deployed through registry +- **Existing Markets**: Cannot be upgraded; users must migrate to new versions + +## Administrative Roles and Capabilities + +### Registry Owner Capabilities +The registry owner account has the following administrative privileges: + +1. **Version Management** + - Add new market contract versions: `add_version()` + - Remove contract versions: `remove_version()` + - Deploy new markets: `deploy_market()` + +2. **Market Deployment** + - Deploy markets with specific configurations + - Set initial full-access keys for deployed markets + - Control market naming and sub-account creation + +3. **Registry Management** + - Update registry contract code + - Manage storage and versioning + +### Market Contract Administration +Once deployed, market contracts have **no admin functions**: +- Markets operate autonomously based on initial configuration +- No ability to pause, upgrade, or modify market parameters +- All operations follow predetermined protocol rules + +## Access Control Implementation + +### Registry Access Control +```rust +// Only owner can add versions +#[payable] +pub fn add_version(&mut self, version_key: String, code: Vec) { + self.assert_owner(); // Validates caller is owner + // ... version addition logic +} + +// Only owner can deploy markets +#[payable] +pub fn deploy_market(&mut self, ...) { + self.assert_owner(); // Validates caller is owner + // ... deployment logic +} +``` + +### Market Access Control +Markets implement role-based access for specific operations: +- **Public Operations**: Supply, borrow, withdraw, liquidate +- **No Admin Operations**: Markets have no administrative override capabilities + +## Owner Configuration + +### Current Setup +- **Registry Owner**: Single account +- **Security Consideration**: Single point of failure exists + +## Upgrade Capabilities + +### Registry Upgrades +Registry owner can: +1. **Replace Contract Code**: Direct contract upgrade capability +2. **Add Market Versions**: Deploy new market contract versions +3. **Remove Versions**: Remove outdated market versions + +### Market Version Updates +- **Version Deployment**: New market versions can be added to registry +- **User Migration**: Users must manually migrate to new market versions +- **No Forced Migration**: Existing markets continue operating + +## Emergency Procedures + +### Market Issues +Since markets are immutable: +- **Bug Discovery**: Deploy patched version through registry +- **User Migration**: Users must manually migrate to new markets +- **Asset Safety**: Existing deposits remain in original markets + +### Registry Issues +- **Emergency Upgrade**: Owner can deploy fixes immediately +- **No Automated Backup**: Manual procedures required + +## Current Governance Model + +### Owner-Based Control +- **No Governance Token**: Protocol operates without governance tokens +- **Single Owner**: All administrative decisions made by registry owner account +- **No Voting Mechanism**: No on-chain voting implemented + +## Time Locks and Delays + +### Current Implementation +- **No Timelocks**: Registry owner can execute upgrades immediately +- **No Mandatory Delays**: No enforced waiting periods for changes + +## Transparency and Monitoring + +### Public Visibility +- **Source Code**: All code publicly available on GitHub +- **Deployment History**: Registry maintains deployment records via `list_deployments()` +- **Audit Reports**: `` + +### Monitoring Systems +- **Contract State**: Manual monitoring required +- **Upgrade Notifications**: Manual notifications required +- **Community Communication**: Manual announcements through official channels + +## Risk Assessment + +### Current Mitigation +- **Code Review**: Security reviews before deployment +- **Open Source**: Public code visibility allows community review +- **Testing**: Comprehensive test suite (280+ tests) +- **Immutable Markets**: Market contracts cannot be modified once deployed diff --git a/docs/src/monitoring.md b/docs/src/monitoring.md new file mode 100644 index 00000000..2c2fe1d2 --- /dev/null +++ b/docs/src/monitoring.md @@ -0,0 +1,83 @@ +# Monitoring and Risk Management + +Templar Protocol uses available tools and established practices for monitoring protocol health and managing risks. + +## Protocol Monitoring Tools + +### Available Monitoring + +#### Bot Infrastructure +The protocol includes operational bots for automated tasks: + +- **Liquidation Bot**: Monitors positions and executes liquidations + - Configurable intervals and concurrency + - Market registry monitoring + - Oracle price feed integration + - Automated liquidation execution + +- **Accumulator Bot**: Handles interest accumulation + - Periodic interest calculations + - Multi-market support + - Configurable execution parameters + +#### Gas Usage Monitoring +Gas analysis tools provide performance insights: + +```bash +./script/ci/gas-report.sh +``` + +This generates detailed reports on: +- Function execution costs +- Snapshot iteration limits +- Performance bottlenecks + +### Manual Monitoring Procedures + +#### Protocol Health Checks +Regular checks can be performed using: + +1. **Market Status**: Query market configurations and states +2. **Oracle Health**: Verify price feed freshness and accuracy +3. **Liquidation Activity**: Monitor liquidation frequency and success rates +4. **Gas Efficiency**: Track transaction costs and optimize operations + +#### Market Data Analysis +Using available view functions: +- Total Value Locked calculations +- Utilization rate monitoring +- Interest rate analysis +- Position health assessment + +## Risk Management + +### Economic Risk Assessment + +#### Available Analysis Tools +- **Market Configuration Review**: Analyze MCR ratios and interest rate models +- **Oracle Price Monitoring**: Track price volatility and feed reliability +- **Liquidation Efficiency**: Monitor liquidation success rates +- **Position Analysis**: Assess individual and aggregate position health + +#### Risk Mitigation Strategies +- **Conservative Parameters**: Well-tested collateralization ratios +- **Oracle Integration**: Multiple validation layers for price feeds +- **Liquidation Incentives**: Economic incentives for timely liquidations +- **Interest Rate Models**: Dynamic models responding to market conditions + +### Operational Monitoring + +#### Smart Contract Health +- **Function Success Rates**: Monitor transaction success/failure patterns +- **Gas Efficiency**: Track and optimize gas usage +- **State Consistency**: Verify protocol state integrity +- **Access Control**: Monitor administrative function usage + +#### Network Dependencies +- **NEAR Network Performance**: Monitor blockchain health and congestion +- **Oracle Provider Status**: Track Pyth Network reliability +- **RPC Node Health**: Monitor API responsiveness + +## Future Monitoring Enhancements + + diff --git a/docs/src/oracles.md b/docs/src/oracles.md new file mode 100644 index 00000000..9c463039 --- /dev/null +++ b/docs/src/oracles.md @@ -0,0 +1,175 @@ +# Oracle System Documentation + +Templar Protocol relies on external price oracles to determine asset values for collateralization and liquidation calculations. + +## Oracle Architecture + +### Primary Oracle Provider +- **Pyth Network**: Primary price feed provider +- **Oracle Contract**: (mainnet) / `pyth-oracle.testnet` (testnet) +- **Documentation**: [Pyth Network Documentation](https://docs.pyth.network/) + +### LST Oracle Adapter +For Liquid Staking Tokens (LSTs), Templar uses a custom oracle adapter: +- **Purpose**: Transforms underlying asset prices using redemption rates +- **Contract**: +- **Functionality**: Applies LST redemption rates to base asset prices + +## Price Feed Configuration + +### Market Oracle Settings +Each market is configured with specific oracle parameters: + +```rust +pub struct PriceOracleConfiguration { + /// Account ID of the oracle contract + pub account_id: AccountId, + /// Price identifier for borrow asset + pub borrow_asset_price_id: PriceIdentifier, + /// Borrow asset decimals for price conversion + pub borrow_asset_decimals: u8, + /// Price identifier for collateral asset + pub collateral_asset_price_id: PriceIdentifier, + /// Collateral asset decimals for price conversion + pub collateral_asset_decimals: u8, + /// Maximum acceptable price age in seconds + pub price_maximum_age_s: u32, +} +``` + +### Price Identifiers +Price feeds are identified using Pyth Network's standardized price IDs: +- **USDT**: `1fc18861232290221461220bd4e2acd1dcdfbc89c84092c93c18bdc7756c1588` (testnet) +- **NEAR**: `27e867f0f4f61076456d1a73b14c7edc1cf5cef4f4d6193a33424288f11bd0f4` (testnet) + +## Update Frequency and Freshness + +### Pyth Network Updates +- **Update Frequency**: Continuously updated (sub-second intervals) +- **On-Chain Updates**: Pulled on-demand by protocol operations +- **Price Staleness**: Configurable maximum age per market (typically 60 seconds) + +### Price Validation +Markets validate price freshness before use: +```rust +// Reject prices older than configured maximum age +pub price_maximum_age_s: u32, +``` + +If prices are stale: +- Operations that require prices (borrow, liquidate) will fail +- Users must wait for fresh price data +- No fallback to potentially manipulated prices + +## Oracle Security Measures + +### Price Manipulation Protection + +1. **Confidence Intervals**: Pyth prices include confidence bands +2. **Multiple Data Sources**: Pyth aggregates from multiple price providers +3. **Outlier Detection**: Automatic filtering of anomalous price data +4. **Time-Weighted Averages**: EMA (Exponentially Weighted Moving Average) prices used + +### Circuit Breakers +- **Maximum Age Limits**: Reject stale price data +- **Confidence Thresholds**: Reject prices with excessive uncertainty +- **Price Deviation Limits**: (Future enhancement) Reject extreme price movements + +## Oracle Monitoring and Maintenance + +### Available Monitoring Tools +The protocol provides tools for monitoring: + +1. **Price Feed Health** + - Oracle response monitoring via bot infrastructure + - Price staleness validation in market operations + - Manual price feed verification procedures + +2. **Price Validation** + - Built-in price age limits in market contracts + - Confidence interval validation from Pyth + - Manual cross-validation with external sources + +### Manual Monitoring Procedures + + + +### Emergency Response + +#### Oracle Failure Scenarios +1. **Temporary Outage**: + - Operations requiring prices will pause + - Users can still withdraw existing positions + - No new borrows or liquidations until oracle recovery + +2. **Price Manipulation Attack**: + - Markets will reject stale prices automatically + - Manual review of suspicious price movements required + - Coordination with oracle provider for investigation needed + +3. **Oracle Provider Issues**: + - Alternative oracle providers could be evaluated + - Market migration would require new deployments + - Communication with affected users through official channels + +## LST Oracle Adapter Details + +### Functionality +The LST oracle adapter enhances base oracle functionality: + +```rust +pub struct PriceTransformer { + pub multiplier: Decimal, // Conversion multiplier + pub shift: i8, // Decimal shift adjustment +} +``` + +### Supported Transformations +- **LST Price Calculation**: `base_price * redemption_rate` +- **Decimal Normalization**: Price scaling for different asset decimals +- **Rate Updates**: Real-time redemption rate queries + +### Example: stNEAR Price Calculation +1. Fetch NEAR price from Pyth oracle +2. Query stNEAR redemption rate from staking contract +3. Calculate: `stNEAR_price = NEAR_price * redemption_rate` + +## Oracle Integration Testing + +### Available Tests +1. **LST Oracle Integration**: Tests LST oracle adapter functionality +2. **Price Transformation**: Tests price conversion and decimal handling +3. **Market Integration**: Oracle configuration used in market liquidation tests + +### Mock Oracle Contract +A mock oracle contract exists at `mock/oracle/` providing: +- Controllable price feeds for testing +- Basic oracle interface simulation +- Integration with test infrastructure + +## Oracle Provider Diversification + +### Current Setup +- **Primary**: Pyth Network +- **Backup**: None currently deployed + +### Future Enhancements +1. **Multiple Oracle Support**: Integrate additional oracle providers +2. **Price Aggregation**: Combine prices from multiple sources +3. **Fallback Mechanisms**: Automatic failover to backup oracles +4. **Price Deviation Alerts**: Detect inconsistencies between providers + +## Gas Optimization + +### Oracle Call Costs + + + +### Optimization Strategies +- **Batch Price Queries**: Retrieve multiple prices in single call +- **Caching**: Store recent prices to reduce oracle calls +- **Gas Estimation**: Dynamic gas allocation based on oracle complexity + +## Compliance and Auditing + + diff --git a/docs/src/security.md b/docs/src/security.md new file mode 100644 index 00000000..1d9d1e53 --- /dev/null +++ b/docs/src/security.md @@ -0,0 +1,76 @@ +# Security Reporting + +Templar Protocol takes security seriously and encourages responsible disclosure of security vulnerabilities. + +## Security Contact + +For security vulnerabilities and sensitive issues: +- **Email**: [security@templarprotocol.com](mailto:security@templarprotocol.com) +- **Telegram**: [@peer2f00l](https://t.me/peer2f00l) + +## Security Alerts + +Important security notices will be posted on the official Discord server, Telegram channel, and X (Twitter) account as stated in the [SECURITY.md](../SECURITY.md) file. + +## Audit Information + +- **Current Status**: `` + +## Current Security Measures + +### Development Security + +#### Code Review Process +- **GitHub Pull Requests**: Standard GitHub review process +- **Code Quality Tools**: Automated formatting (`cargo fmt`) and linting (`cargo clippy`) +- **Static Analysis**: Clippy linting integrated into CI workflows + +#### Testing Security +- **Comprehensive Test Suite**: 280 tests covering protocol functionality +- **Security-Related Testing**: Tests include security scenarios +- **Integration Testing**: Full protocol interaction testing + +### Contract Security + +#### Access Control +Registry contracts implement owner-based access control: +```rust +#[payable] +pub fn add_version(&mut self, version_key: String, code: Vec) { + self.assert_owner(); // Only owner can add versions + // ... +} +``` + +#### Market Immutability +- **Market Contracts**: Immutable once deployed - no admin functions +- **Protocol Rules**: All operations follow predetermined protocol rules +- **No Pause Mechanisms**: Markets operate autonomously + +### Deployment Security + +#### Reproducible Builds +- **Deterministic Compilation**: All contracts built reproducibly +- **Code Verification**: Hash verification against deployed bytecode +- **Open Source**: All code publicly available for review + +## Responsible Disclosure + +### Disclosure Process +1. **Report**: Send vulnerability details to security@templarprotocol.com +2. **Investigation**: Security team will assess the report +3. **Resolution**: Fix development and deployment +4. **Public Disclosure**: Coordinated disclosure after fix + +### Report Guidelines +Please include: +- Clear description of the vulnerability +- Steps to reproduce the issue +- Potential impact assessment +- Suggested fixes (if available) + +## Community Involvement + +- **Open Source Review**: All code available for community audit +- **Security Discussions**: Technical security discussions welcomed +- **Vulnerability Reporting**: Clear process for security researchers documented diff --git a/docs/src/testing.md b/docs/src/testing.md new file mode 100644 index 00000000..f9a980f4 --- /dev/null +++ b/docs/src/testing.md @@ -0,0 +1,154 @@ +# Testing and Code Coverage + +Templar Protocol maintains comprehensive test suites to ensure protocol security and reliability. + +## Test Execution + +### Running All Tests +```bash +./script/test.sh +``` + +This script: +1. Pre-builds all test contracts using `script/prebuild-test-contracts.sh` +2. Runs tests using `cargo nextest run` + +### Test Structure + +The test suite includes: + +- **Unit Tests**: Located in each module's `tests/` directory +- **Integration Tests**: Full protocol interaction tests +- **Market Tests**: Comprehensive market functionality tests +- **Registry Tests**: Contract deployment and management tests +- **Oracle Tests**: Limited LST oracle and price transformation tests + +### Test Categories + +#### Market Contract Tests +- **Basic Operations**: Supply, borrow, collateralize, withdraw +- **Liquidation**: Liquidation scenarios and edge cases +- **Interest Rates**: Interest accrual and rate calculations +- **MCR (Minimum Collateralization Ratio)**: Maintenance and liquidation ratios +- **Edge Cases**: Boundary conditions and error states + +#### Registry Contract Tests +- **Deployment**: Market deployment from registry +- **Version Management**: Adding and managing contract versions +- **Access Control**: Admin permissions and restrictions + +#### Integration Tests +- **End-to-End Workflows**: Complete user journeys +- **Cross-Contract Interactions**: Registry-to-market deployments +- **Oracle Integration**: Basic LST oracle and price transformation tests + +## Test Coverage + +### Current Coverage Areas + +The test suite covers: + +1. **Core Protocol Logic** + - Asset management operations (supply, borrow, collateralize, withdraw) + - Interest rate calculations and accumulation + - Liquidation mechanics and edge cases + - Collateralization requirements and validation + +2. **Smart Contract Interfaces** + - NEP-141 (Fungible Token) integration + - NEP-245 (Multi Token) support + - Basic oracle price feed integration + - Cross-contract interactions + +3. **Error Handling** + - Invalid parameter handling + - Access control violations + - Arithmetic overflow/underflow protection + - Edge case boundary testing + +4. **Integration Testing** + - Full protocol workflows + - Registry-to-market deployments + - Basic oracle integration (LST oracle and price transformation) + +### Test Execution Statistics + +``` +Test Results (Current): +├── Total Tests Available: 280 +├── Includes unit tests for all contracts and modules +├── Integration tests for full protocol workflows +├── Bot tests for liquidation and accumulator logic +└── Utility tests for common functionality + +Success Rate: 100% (all tests passing) +``` + +**Note**: Specific code coverage percentages require additional tooling setup. + +### Continuous Integration + +Tests run automatically on: +- Production deployment builds +- Staging deployment builds (triggered by pull requests) + +**Note**: Tests are executed via `workflow_call` in deployment workflows, not directly on pull requests or commits. + +## Test Environment + +Tests use: +- **near-workspaces**: NEAR blockchain simulation +- **Mock Contracts**: Isolated testing environment +- **Deterministic Scenarios**: Reproducible test conditions + +### Mock Components +- **Mock FT**: Simulated fungible tokens +- **Mock Oracle**: Controlled price feeds +- **Mock MT**: Multi-token simulation + +## Coverage Reporting + +### Available Tools + +To generate coverage reports, additional tooling can be installed: + +```bash +# Install cargo-llvm-cov (optional) +cargo install cargo-llvm-cov + +# Generate coverage report (when tooling is set up) +cargo llvm-cov --html --output-dir coverage-report + +# View report +open coverage-report/index.html +``` + +**Note**: Coverage reporting tools are not integrated into the CI pipeline. + +## Performance Testing + +### Gas Usage Analysis +Gas usage analysis is available through existing tools: + +```bash +./script/ci/gas-report.sh +``` + +This generates a comprehensive gas report for all market operations, including: +- Individual function gas costs +- Snapshot iteration limits +- Performance optimization targets + +## Test Data + +Test scenarios include: +- **Market Configuration Testing**: Using test configurations with sample assets +- **Basic Functionality Testing**: Standard protocol operations +- **Edge Case Testing**: Boundary conditions and error states + +## Quality Assurance + +- **Automated Testing**: Tests run in deployment workflows +- **Code Review**: GitHub pull request review process +- **Security Testing**: Basic security-related tests included in test suite +- **Regression Testing**: Full test suite runs with each deployment