Leveraging Golden Ratio Mathematics for Provably Optimal DeFi Swaps
๐ Documentation โข ๐ Quick Start โข ๐๏ธ Architecture โข ๐ Security โข ๐งฎ Mathematics โข ๐ค Contributing
|
Version: Overall Security Score: ๐ข 8.69/10 Production Readiness: โ Audit Ready |
|
๐ Test Coverage: 94% production code (179 tests passing)
๐ Security Tests: 40+ dedicated security tests
๐ก๏ธ Static Analysis: 0 critical, 0 high severity findings
โฝ Gas Efficiency: 218K - 350K per swap (optimized)
๐ฆ Contract Size: ~3,500 lines across 18 files
๐ Audit Score: 8.69/10 - Ready for external audit
|
|
|
|
|
๐๏ธ Architecture & Design |
๐ Security & Testing
|
๐งฎ Mathematics & API |
โญ New! Comprehensive security documentation (5,000+ lines) prepared for external audit
Node.js >= 16.0.0
npm >= 8.0.0
Git >= 2.0.0# 1. Clone repository
git clone https://github.com/Bofh-Reloaded/BofhContract.git
cd BofhContract
# 2. Install dependencies
npm install
# 3. Configure environment
cp env.json.example env.json
# Edit env.json with your BSC testnet mnemonic and BSCScan API key
# 4. Compile contracts
npm run compile
# 5. Run tests
npm test
# 6. Generate coverage report
npm run coverageCreate env.json in the project root:
{
"mnemonic": "your twelve word mnemonic phrase here",
"BSCSCANAPIKEY": "YOUR_BSCSCAN_API_KEY"
}
โ ๏ธ SECURITY WARNING: Never commitenv.jsonto version control! It's already in.gitignore.
# Run all tests (179 passing)
npm test
# Run with detailed gas reporting
REPORT_GAS=true npm test
# Generate coverage report (94% production code)
npm run coverage
# Run security scan (Slither)
npm run security# Deploy to local Hardhat network (for testing)
npm run deploy:local
# Deploy to BSC testnet
npm run deploy:testnet
# Configure deployed contract
npm run configure:testnet
# Verify contract on BSCScan
npm run verify:testnetโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ BofhContractV2.sol โ
โ Main Implementation: Swap Execution & Optimization โ
โ โข executeSwap() - Single swap execution โ
โ โข executeMultiSwap() - Multi-path optimization โ
โ โข executeBatchSwaps() - Atomic batch operations โ
โ Lines: 404 | Coverage: 90.83% โ
โโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ inherits
โโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ BofhContractBase.sol โ
โ Security & Risk Management โ
โ โข Access control (owner/operator roles) โ
โ โข Risk parameters (slippage, liquidity, impact) โ
โ โข Emergency functions (pause, recovery) โ
โ Lines: 361 | Coverage: 93.65% โ
โโโโโโโโโฌโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโ
โ โ โ
โโโโโโโโโผโโโโโโโ โโโโโโโโผโโโโโโโ โโโโโโโผโโโโโโโโโ
โ SecurityLib โ โ MathLib โ โ PoolLib โ
โโโโโโโโโโโโโโโโค โโโโโโโโโโโโโโโค โโโโโโโโโโโโโโโโค
โ โข Reentrancy โ โ โข sqrt() โ โ โข analyzePoolโ
โ โข Access โ โ โข cbrt() โ โ โข priceImpactโ
โ โข MEV Guard โ โ โข geoMean() โ โ โข validate() โ
โ โข Rate Limit โ โ โข goldenฯ() โ โ โข CPMM calc โ
โโโโโโโโโโโโโโโโค โโโโโโโโโโโโโโโค โโโโโโโโโโโโโโโโค
โ Lines: 300 โ โ Lines: 171 โ โ Lines: 274 โ
โ Cov: 93.48% โ โ Cov: 100% โ โ Cov: 95.24% โ
โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ
| Component | Lines | Coverage | Purpose |
|---|---|---|---|
BofhContractV2.sol |
404 | โ 90.83% | Swap execution, golden ratio optimization, batch operations |
BofhContractBase.sol |
361 | โ 93.65% | Security primitives, risk parameters, emergency controls |
MathLib.sol |
171 | โ 100% | Newton's method (sqrt, cbrt), golden ratio, geometric mean |
PoolLib.sol |
274 | โ 95.24% | CPMM analysis, price impact, liquidity validation |
SecurityLib.sol |
300 | โ 93.48% | Reentrancy guards, access control, MEV protection |
| Production Total | 1,510 | โ 94% | All core functionality |
IBofhContract.sol- Public API for swap executionIBofhContractBase.sol- Base functionality interfaceISwapInterfaces.sol- DEX integration interfaces
UniswapV2Adapter.sol- Uniswap V2 integration (0.3% fee)PancakeSwapAdapter.sol- PancakeSwap V2 integration (0.25% fee)
๐ Total: 18 Solidity files, ~3,500 lines of production code
|
Access Control
Reentrancy Protection
MEV Protection
Input Validation
Emergency Controls
Code Safety
|
Static Analysis
Test Coverage Attack Vectors Analyzed
Audit Preparation
|
|
1,372 lines covering:
|
1,400+ lines covering:
|
507 lines covering:
|
1,100+ lines covering:
|
| Limitation | Risk | Mitigation | V3 Plan |
|---|---|---|---|
| No Oracle Integration | ๐ก Medium | MEV protection, price impact limits, liquidity thresholds | Chainlink/Band integration |
| Centralization (single owner) | ๐ก Medium | Event emission, access controls, multisig recommended | DAO governance |
| No Upgradeability | ๐ข Low | Comprehensive testing, external audit | Transparent proxy pattern |
| Firm | Specialty | Cost | Timeline |
|---|---|---|---|
| Trail of Bits | Mathematical correctness | $40K-$60K | 3-4 weeks |
| OpenZeppelin | DeFi protocol security | $30K-$50K | 2-3 weeks |
| ConsenSys Diligence | Automated + manual | $25K-$45K | 2-4 weeks |
| CertiK | Formal verification | $20K-$40K | 3-4 weeks |
| Quantstamp | Cost-effective audits | $15K-$35K | 2-3 weeks |
๐ See AUDIT_PREPARATION.md for complete details
|
The system uses the golden ratio for provably optimal path splitting in multi-way swaps: Proof of Optimality: Using Lagrange multipliers to minimize total price impact: Benefits:
|
CPMM Analysis: Third-order Taylor expansion: Where:
Implementation:
Mathematical Rigor:
|
๐ See MATHEMATICAL_FOUNDATIONS.md for complete derivations and proofs
|
|
test/
โโโ BofhContractV2.test.js # Main contract tests (45 tests)
โโโ Libraries.test.js # Library function tests (62 tests)
โโโ EmergencyFunctions.test.js # Emergency controls (11 tests)
โโโ BatchSwaps.test.js # Batch operations (18 tests)
โโโ GasOptimization.test.js # Gas benchmarks (15 tests)
โโโ EdgeCases.test.js # Boundary conditions (12 tests)
โโโ MEVProtection.test.js # Flash loans, rate limiting (8 tests)
โโโ AccessControl.test.js # Permissions (6 tests)
โโโ PriceImpact.test.js # CPMM calculations (2 tests)- โ Reentrancy Protection (12 tests) - All attack vectors blocked
- โ Access Control (15 tests) - Owner/operator enforcement
- โ MEV Protection (8 tests) - Flash loan detection working
- โ Input Validation (10 tests) - All edge cases covered
- โ Emergency Functions (11 tests) - Pause/recovery verified
| Operation | Gas Cost | Notes |
|---|---|---|
| Simple 2-way swap | ~218,000 |
Baseline swap operation |
| Complex 3-hop swap | ~282,000 |
Multi-hop execution |
| Complex 4-hop swap | ~316,000 |
Golden ratio optimization |
| Complex 5-hop swap (max) | ~350,000 |
Maximum path length |
| Batch 2 swaps | ~467,000 |
~233K per swap (7% overhead) |
| Batch 5 swaps | ~752,000 |
~150K per swap (31% savings) โ |
| Batch 10 swaps (max) | ~1,496,000 |
~150K per swap (31% savings) โ |
โ Unchecked Loop Iterators - ~200 gas saved per iteration โ Inline CPMM Calculations - ~5,000 gas saved per swap โ Custom Errors - ~24 gas saved per revert โ Storage Packing - 1 storage slot saved per struct โ Function Selector Optimization - Planned for V3
Individual Swaps: 218,000 gas ร 5 = 1,090,000 gas
Batch 5 Swaps: 752,000 gas
Savings: 338,000 gas (31% reduction) โ
โก See GAS_OPTIMIZATION_PHASE3_RESULTS.md for detailed benchmarks
|
Compilation & Testing npm run compile # Compile contracts
npm test # Run all tests
npm run coverage # Coverage reportLinting & Formatting npm run lint # Run all linters
npm run lint:sol # Lint Solidity
npm run lint:js # Lint JavaScript
npm run format # Format all files
npm run format:check # Check formattingSecurity npm run security # Run Slither scan
npm run security:install # Install Slither
npm audit # Check dependencies |
Deployment npm run deploy # Deploy (local)
npm run deploy:local # Deploy to Hardhat
npm run deploy:testnet # Deploy to BSC testnet
npm run deploy:mainnet # Deploy to BSC mainnetVerification npm run verify:testnet # Verify on BSC testnet
npm run verify:mainnet # Verify on BSC mainnetConfiguration npm run configure:testnet # Configure testnet
npm run configure:mainnet # Configure mainnet |
| Workflow | Trigger | Actions |
|---|---|---|
| CI | All branches | Lint โ Compile โ Test โ Coverage |
| Security | Weekly schedule | Slither scan โ npm audit โ Dependabot |
| Gas Report | Pull requests | Gas usage comparison โ Comment on PR |
{
"@openzeppelin/contracts": "4.9.6" // Security-audited libraries
}|
Core Tools
|
Testing & Analysis
|
- Issue #24 - Fix antiMEV stack depth in
executeMultiSwap - Issue #25 - Complete Hardhat deployment scripts
- Issue #27 - Remove legacy Truffle dependencies
- Issue #26 - Add emergency token recovery function
- Issue #31 - Implement batch operations support
- Issue #28 - Increase test coverage to 90%+ (achieved 94%)
- Issue #29 - Prepare comprehensive security audit documentation
- Issue #33 - Complete monitoring stack (Prometheus + Grafana)
- Issue #30 - Storage layout optimization
- Issue #32 - Oracle integration (Chainlink price feeds)
- Issue #34 - Finalize production readiness roadmap
- External security audit engagement
- Testnet deployment (2+ weeks monitoring)
- Bug bounty program setup
- Multisig wallet deployment
- Production deployment to BSC mainnet
- Multi-DEX routing optimization
- Cross-chain support exploration
- DAO governance implementation (V3)
๐ See Sprint 5 Roadmap for detailed timeline
We welcome contributions from the community! BofhContract is open for improvements in mathematics, security, performance, and documentation.
|
High Priority
|
Medium Priority
|
|
Always Welcome
|
Future Exploration
|
# 1. Fork the repository
# 2. Create feature branch
git checkout -b feature/AmazingFeature
# 3. Make changes and add tests
# 4. Run linters
npm run lint
# 5. Run tests
npm test
# 6. Generate coverage (should maintain 90%+)
npm run coverage
# 7. Commit changes
git commit -m 'โจ feat: Add AmazingFeature'
# 8. Push to branch
git push origin feature/AmazingFeature
# 9. Create Pull RequestWe follow Conventional Commits:
feat: New feature
fix: Bug fix
docs: Documentation
style: Formatting
refactor: Code restructuring
test: Testing
chore: Maintenance
UNLICENSED - Proprietary software for research and educational purposes.
This software is provided for research, educational, and testing purposes only. Production use requires explicit permission. See LICENSE for details.
|
Complete guides, API reference, and architectural deep-dives |
Bug reports, feature requests, and technical questions |
Community chat, ideas, and general questions |
|
OpenZeppelin Security best practices and audited libraries |
Uniswap Team Pioneering the CPMM standard (xยทy=k) |
Hardhat Team Excellent development tooling and ecosystem |
DeFi Community Research and innovation in AMM optimization |
v1.5.0 | 179 Tests Passing | 94% Coverage | 8.69/10 Security | Audit Ready
โญ Star us on GitHub โข ๐ Read the Docs โข ๐ Security Report
Made with โค๏ธ by the BOFH team
Last Updated: November 10, 2025