diff --git a/DEVELOPER_GUIDELINES.md b/DEVELOPER_GUIDELINES.md new file mode 100644 index 0000000..6417415 --- /dev/null +++ b/DEVELOPER_GUIDELINES.md @@ -0,0 +1,351 @@ +# Developer Guidelines + +This document provides comprehensive guidelines for developers contributing to the OADA UNHCR Yield Donation Module project. + +## ๐Ÿ“‹ Table of Contents + +- [Getting Started](#getting-started) +- [Code Style](#code-style) +- [Contract Development](#contract-development) +- [Testing Guidelines](#testing-guidelines) +- [Security Considerations](#security-considerations) +- [Contributing](#contributing) + +## ๐Ÿš€ Getting Started + +### Prerequisites + +- [Aiken](https://aiken-lang.org/) compiler (v1.9.0+) +- [Nix](https://nixos.org/) package manager +- Cardano development environment + +### Installation + +1. **Clone the repository**: + + ```bash + git clone https://github.com/OptimFinance/clean-code.git + cd yield-donation + ``` + +2. **Setup development environment**: + + ```bash + nix develop + ``` + +3. **Install dependencies**: + ```bash + cd oada + aiken check + ``` + +### Project Structure + +``` +oada-donate/ +โ”œโ”€โ”€ oada/ # Main Aiken project +โ”‚ โ”œโ”€โ”€ validators/ # Smart contract validators +โ”‚ โ”œโ”€โ”€ lib/ # Library modules +โ”‚ โ”œโ”€โ”€ aiken.toml # Project configuration +โ”‚ โ””โ”€โ”€ plutus.json # Plutus compatibility layer +โ”œโ”€โ”€ aiken-common/ # Shared Aiken utilities +โ”œโ”€โ”€ test/ # Test suite +โ”œโ”€โ”€ flake.nix # Nix development environment +โ””โ”€โ”€ README.md # This file +``` + +## ๐Ÿ‘จโ€๐Ÿ’ป Code Style + +### Naming Conventions + +- **Functions and Variables**: Use `snake_case` +- **Types and Validators**: Use `PascalCase` +- **Private Functions**: Prefix with underscore (`_`) + +### Documentation + +- Document all public functions with clear descriptions +- Include parameter types and return values +- Add examples for complex logic +- Use inline comments for business logic explanations + +### Error Handling + +- Use `expect` for required values +- Provide meaningful error messages +- Handle edge cases explicitly +- Validate inputs thoroughly + +## ๐Ÿ”ง Contract Development + +### Adding New Validators + +1. **Create the validator file** in `oada/validators/` +2. **Define the datum type** with clear field descriptions +3. **Implement required functions**: + - `mint/2` for minting operations + - `spend/3` for spending operations +4. **Add comprehensive tests** + +#### Example Validator Structure + +```aiken +validator(parameter1: Type1, parameter2: Type2) { + fn mint(redeemer: RedeemerType, ctx: ScriptContext) { + // Minting logic + } + + fn spend(datum: DatumType, redeemer: RedeemerType, ctx: ScriptContext) { + // Spending logic + } +} +``` + +### Validation Functions + +When creating validation functions in `lib/oada/validation.ak`: + +1. **Use clear parameter names** +2. **Document the business logic** +3. **Handle all edge cases** +4. **Return boolean values for validation** + +### Datum and Redeemer Design + +#### Datum Guidelines + +- Keep datum structures minimal and focused +- Use descriptive field names +- Include validation constraints in the datum when possible +- Document the purpose of each field + +#### Redeemer Guidelines + +- Design redeemers to be explicit about the action being performed +- Use sum types for different operations +- Include necessary parameters for validation +- Keep redeemers immutable and stateless + +### Common Patterns + +#### Input Validation + +```aiken +fn validate_input(input: Input, ctx: ScriptContext) -> Bool { + and{ + // Check input exists + list.has(ctx.transaction.inputs, input)?, + // Validate input value + value.quantity_of(input.output.value, token_policy, "") > 0?, + // Check authorization + list.has(ctx.transaction.extra_signatories, required_key)? + } +} +``` + +#### Output Validation + +```aiken +fn validate_output(output: Output, expected_value: Int) -> Bool { + and{ + // Check output value + value.quantity_of(output.value, token_policy, "") == expected_value?, + // Validate address + output.address.payment_credential == expected_credential?, + // Check datum if required + output.datum == expected_datum? + } +} +``` + +## ๐Ÿงช Testing Guidelines + +### Test Types + +1. **Unit Tests**: Test individual functions +2. **Integration Tests**: Test validator interactions +3. **Property Tests**: Test invariants and properties +4. **Edge Cases**: Test boundary conditions + +### Test Structure + +```aiken +test test_function_name() { + // Setup + let input = create_test_input() + + // Execute + let result = function_under_test(input) + + // Assert + result == expected_output +} +``` + +### Testing Best Practices + +- **Test Coverage**: Aim for 100% coverage of public functions +- **Edge Cases**: Test boundary conditions and error cases +- **Property Testing**: Use property-based testing for complex logic +- **Integration Testing**: Test validator interactions thoroughly +- **Mock Data**: Use realistic test data that matches production scenarios + +### Running Tests + +```bash +# Run all tests +cd oada +aiken test + +# Run tests in watch mode +aiken test --watch + +# Run specific test file +aiken test validators/donate_soada.ak + +# Run tests with coverage +aiken test --coverage +``` + +## ๐Ÿ”’ Security Considerations + +### Input Validation + +- Validate all inputs thoroughly +- Check for malicious or unexpected data +- Implement proper bounds checking +- Validate cryptographic signatures + +### Access Control + +- Implement proper authorization checks +- Use whitelists for privileged operations +- Verify signatories for sensitive actions +- Implement role-based access control + +### Resource Limits + +- Set appropriate limits for operations +- Prevent resource exhaustion attacks +- Implement rate limiting where applicable +- Monitor gas consumption + +### Audit Trail + +- Maintain clear transaction logs +- Include sufficient context in redeemers +- Log important state changes +- Enable transaction tracing + +### Common Security Patterns + +#### Authorization Check + +```aiken +fn check_authorization(required_key: KeyHash, ctx: ScriptContext) -> Bool { + list.has(ctx.transaction.extra_signatories, required_key) +} +``` + +#### Value Validation + +```aiken +fn validate_value(amount: Int, min: Int, max: Int) -> Bool { + and{ + amount >= min, + amount <= max + } +} +``` + +#### State Transition Validation + +```aiken +fn validate_state_transition(old_state: State, new_state: State) -> Bool { + // Ensure state transitions are valid + and{ + new_state.version > old_state.version, + new_state.timestamp > old_state.timestamp, + // Add other validation rules + } +} +``` + +## ๐Ÿค Contributing + +### Development Workflow + +1. **Fork the repository** +2. **Create a feature branch**: `git checkout -b feature/your-feature` +3. **Make your changes** following the development guidelines +4. **Add tests** for new functionality +5. **Run the test suite**: `aiken test` +6. **Submit a pull request** + +### Pull Request Guidelines + +1. **Clear description** of changes +2. **Reference related issues** +3. **Include tests** for new functionality +4. **Update documentation** if needed +5. **Ensure all tests pass** + +### Code Review Process + +1. **Automated checks** must pass +2. **At least one review** from maintainers +3. **Address feedback** before merging +4. **Squash commits** for clean history + +### Commit Message Guidelines + +Use conventional commit format: + +``` +type(scope): description + +[optional body] + +[optional footer] +``` + +Types: + +- `feat`: New feature +- `fix`: Bug fix +- `docs`: Documentation changes +- `style`: Code style changes +- `refactor`: Code refactoring +- `test`: Test changes +- `chore`: Build/tooling changes + +### Code Review Checklist + +- [ ] Code follows style guidelines +- [ ] Tests are included and passing +- [ ] Documentation is updated +- [ ] Security considerations addressed +- [ ] Performance impact considered +- [ ] Error handling implemented +- [ ] Edge cases covered + +## ๐Ÿ“š Additional Resources + +- [Aiken Documentation](https://aiken-lang.org/) +- [Cardano Developer Portal](https://developers.cardano.org/) +- [Plutus Documentation](https://plutus.readthedocs.io/) +- [Aiken Style Guide](https://aiken-lang.org/style-guide) + +## ๐Ÿ“„ License + +This project is licensed under the MIT License - see the [LICENSE.md](../LICENSE.md) file for details. + +## ๐Ÿ†˜ Getting Help + +- **Issues**: [GitHub Issues](https://github.com/OptimFinance/clean-code/issues) +- **Discussions**: [GitHub Discussions](https://github.com/OptimFinance/clean-code/discussions) + +--- + +**Note**: These guidelines are living documents. Please contribute improvements and updates as the project evolves. diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..a962b46 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +# MIT License + +Copyright (c) 2025 Optim Finance + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..bd970f6 --- /dev/null +++ b/README.md @@ -0,0 +1,230 @@ +# OADA UNHCR Yield Donation Module + +A decentralized donation protocol built on Cardano using Aiken smart contracts. OADA enables automated charitable giving through staking mechanisms and yield distribution. + +## ๐Ÿ“‹ Table of Contents + +- [Overview](#overview) +- [Architecture](#architecture) +- [Contract Structure](#contract-structure) +- [Getting Started](#getting-started) +- [Testing](#testing) +- [Contributing](#contributing) + +## ๐ŸŽฏ Overview + +OADA is a sophisticated DeFi protocol that combines staking, yield generation, and automated charitable donations. The protocol allows users to stake tokens and automatically donate a portion of their yield to charitable causes while maintaining control over their funds. + +### Key Features + +- **Automated Donations**: Configurable donation ratios for yield distribution +- **Staking Mechanics**: sOTOKEN and OTOKEN exchange mechanisms +- **Yield Management**: Automated yield calculation and distribution +- **NFT Rewards**: CIP-68 compliant NFTs for donation tracking +- **Batch Processing**: Efficient batch staking operations + +## ๐Ÿ—๏ธ Architecture + +The OADA protocol consists of several interconnected smart contracts that work together to provide a complete donation and staking ecosystem: + +``` +OADA Protocol +โ”œโ”€โ”€ Core Contracts +โ”‚ โ”œโ”€โ”€ Staking AMO (Automated Market Operations) +โ”‚ โ”œโ”€โ”€ Donation Validator +โ”‚ โ”œโ”€โ”€ Batch Stake Validator +โ”‚ โ””โ”€โ”€ Collateral AMO +โ”œโ”€โ”€ Supporting Contracts +โ”‚ โ”œโ”€โ”€ Token Policies (OTOKEN, sOTOKEN) +โ”‚ โ”œโ”€โ”€ Fee Claim Rules +โ”‚ โ””โ”€โ”€ Donation Strategies +โ””โ”€โ”€ Utilities + โ”œโ”€โ”€ Validation Functions + โ””โ”€โ”€ Common Types +``` + +## ๐Ÿ“œ Contract Structure + +### Core Validators + +#### 1. `donate_soada.ak` - Main Donation Validator + +**Purpose**: Handles the core donation logic and NFT minting + +**Key Functions**: + +- `mint(redeemer: IdMintRedeemer, ctx: ScriptContext)`: Mints donation positions +- `spend(datum: DonationDatum, redeemer: (Int, Int, Int), ctx: ScriptContext)`: Processes donations + +**Datum Structure**: + +```aiken +type DonationDatum { + owner: KeyHash, + donation_ratio: (Int, Int), // Ratio as (numerator, denominator) + initial_exchange: (Int, Int) // Initial exchange rate +} +``` + +#### 2. `staking_amo.ak` - Staking Automated Market Operations + +**Purpose**: Manages sOTOKEN supply and exchange rates + +**Key Functions**: + +- `mint(redeemer: IdMintRedeemer, ctx: ScriptContext)`: Mints staking positions +- `spend(datum: StakingAmoDatum, _redeemer: Data, ctx: ScriptContext)`: Updates staking parameters + +**Datum Structure**: + +```aiken +type StakingAmoDatum { + sotoken: PolicyId, + sotoken_amount: Int, + sotoken_backing: Int, + sotoken_limit: Int, + odao_fee: Int, + fee_claimer: Id, + fee_claim_rule: ScriptHash, + odao_sotoken: Int +} +``` + +#### 3. `batch_stake.ak` - Batch Staking Validator + +**Purpose**: Handles batch staking and unstaking operations + +**Key Functions**: + +- `spend(datum: BatchStakeDatum, redeemer: BatchStakeRedeemer, ctx: ScriptContext)`: Processes batch operations + +**Redeemer Types**: + +```aiken +type BatchStakeRedeemer { + CancelStake + DigestStake(Int, Option) +} +``` + +#### 4. `collateral_amo.ak` - Collateral Management + +**Purpose**: Manages collateral and strategy deployment + +#### 5. `deposit_amo.ak` - Deposit Management + +**Purpose**: Handles deposit operations and liquidity management + +### Supporting Contracts + +#### Token Policies + +- `otoken_policy.ak`: OTOKEN minting policy +- `sotoken_rule.ak`: sOTOKEN validation rules +- `otoken_rule.ak`: OTOKEN validation rules + +#### Fee Management + +- `fee_claim_rule.ak`: Fee claiming logic +- `donation_strategy.ak`: Donation strategy management + +### Utility Modules + +#### `validation.ak` - Core Validation Functions + +Key functions for contract validation: + +- `update_sotoken_amount/11`: Updates sOTOKEN amounts and exchange rates +- `spawn_strategy/11`: Deploys new strategies +- `despawn_strategy/9`: Destroys strategies and returns funds + +## ๐Ÿš€ Getting Started + +### Prerequisites + +- [Aiken](https://aiken-lang.org/) compiler (v1.9.0+) +- [Nix](https://nixos.org/) package manager +- Cardano development environment + +### Installation + +1. **Clone the repository**: + + ```bash + git clone https://github.com/OptimFinance/clean-code.git + cd yield-donation + ``` + +2. **Setup development environment**: + + ```bash + nix develop + ``` + +3. **Install dependencies**: + ```bash + cd oada + aiken check + ``` + +### Project Structure + +``` +oada-donate/ +โ”œโ”€โ”€ oada/ # Main Aiken project +โ”‚ โ”œโ”€โ”€ validators/ # Smart contract validators +โ”‚ โ”œโ”€โ”€ lib/ # Library modules +โ”‚ โ”œโ”€โ”€ aiken.toml # Project configuration +โ”‚ โ””โ”€โ”€ plutus.json # Plutus compatibility layer +โ”œโ”€โ”€ aiken-common/ # Shared Aiken utilities +โ”œโ”€โ”€ test/ # Test suite +โ”œโ”€โ”€ flake.nix # Nix development environment +โ”œโ”€โ”€ README.md # This file +โ”œโ”€โ”€ DEVELOPER_GUIDELINES.md # Developer guidelines +โ””โ”€โ”€ LICENSE.md # MIT License +``` + +## ๐Ÿ‘จโ€๐Ÿ’ป Development Guidelines + +For comprehensive development guidelines, code style, testing practices, and contribution workflows, please see [DEVELOPER_GUIDELINES.md](DEVELOPER_GUIDELINES.md). + +## ๐Ÿงช Testing + +### Quick Start + +```bash +cd oada +aiken test +``` + +For comprehensive testing guidelines, best practices, and advanced testing techniques, see [DEVELOPER_GUIDELINES.md](DEVELOPER_GUIDELINES.md#testing-guidelines). + +## ๐Ÿค Contributing + +We welcome contributions! Please see [DEVELOPER_GUIDELINES.md](DEVELOPER_GUIDELINES.md#contributing) for detailed information about: + +- Development workflow +- Pull request guidelines +- Code review process +- Commit message conventions +- Code review checklist + +## ๐Ÿ“š Additional Resources + +- [Aiken Documentation](https://aiken-lang.org/) +- [Cardano Developer Portal](https://developers.cardano.org/) +- [Plutus Documentation](https://plutus.readthedocs.io/) + +## ๐Ÿ“„ License + +This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details. + +## ๐Ÿ†˜ Support + +- **Issues**: [GitHub Issues](https://github.com/optim/oada-donate/issues) +- **Discussions**: [GitHub Discussions](https://github.com/optim/oada-donate/discussions) +- **Documentation**: [Project Wiki](https://github.com/optim/oada-donate/wiki) + +--- + +**Note**: This is a development version. For production use, ensure thorough testing and security audits.