-
Notifications
You must be signed in to change notification settings - Fork 2
feat: improve Raffl Protocol to v2 #5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ubinatus
wants to merge
15
commits into
main
Choose a base branch
from
improvements
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
…ions - Updated .solhint.json to allow a max line length of 125 and disabled use-natspec. - Upgraded solhint dependency to version 6.0.2. - Added new documentation files for VRF recovery, including user guide, quick reference, and technical documentation. - Enhanced Raffl and RafflFactory contracts to support VRF request tracking, retry functionality, and emergency fail mechanism. - Introduced new events for VRF request retries and emergency failures. - Updated tests to cover new VRF retry and emergency fail scenarios.
- Introduced internal functions for modifier checks in Raffl and FactoryFeeManager contracts to improve code readability. - Added additional validation checks for prize and entry conditions in Raffl and RafflFactory contracts. - Updated error handling for ETH transfers and token operations in TokenLib to provide clearer revert reasons. - Refactored loops to use length variables for better performance and clarity. - Improved test cases to reflect changes in error handling and contract logic.
- Introduced a new documentation file detailing the Raffl Protocol, including an overview, architecture, lifecycle flowchart, data structures, fee system, entry system, external dependencies, security features, supported networks, key constants, and events. - Enhanced understanding of the protocol's functionality and structure for developers and users.
- Introduced multiple test files covering various aspects of the Raffl protocol, including access control, edge cases, fuzz testing, integration, security, and token gating. - Enhanced coverage for ownership transfers, fee collection, VRF handling, and entry purchase scenarios. - Implemented tests for edge cases in prize distribution, entry limits, and token gate requirements. - Improved overall robustness and reliability of the Raffl protocol through extensive testing.
… Protocol - Added detailed sections on Chainlink exception handling, including a two-step winner selection process and various exception scenarios. - Documented gas usage, recovery functions, and the fee system architecture related to VRF requests. - Improved clarity on token gating, entry systems, and prize requirements, enhancing overall understanding of the protocol's robustness and reliability.
Raffl.sol: - Pack factory, settled, prizesRefunded, gameStatus into single slot - Reorder state variables for optimal 32-byte alignment - Reduce storage from ~17 slots to ~11 slots RafflFactory.sol: - Pack callbackGasLimit, requestConfirmations, nativePayment into one slot - Optimize VRFRequest struct: uint256 requestTime -> uint64 (2 slots instead of 3) - Optimize ActiveRaffle struct: uint256 deadline -> uint64 (1 slot instead of 2) - Add _raffleToActiveIndex mapping for O(1) raffle removal - Replace O(n) linear search with O(1) index lookup in _removeRaffleFromActive
- Rename requestId parameter to vrfRequestId to avoid shadowing state variable - Add SubscriptionConfigUpdated event to handleSubscription() for better monitoring - Add indexed parameter to RaffleCreated event for efficient log filtering - Update IRaffl interface with improved NatSpec documentation
Raffl.sol: - Cache entryPrice in buyEntries() to avoid redundant SLOAD - Cache entryToken in refundEntries() and _purchaseEntry() - Pass cached entryPrice to _purchaseEntry() as parameter - Cache entryToken in _transferPool() and pass to helper functions - Update _distributePoolFunds() and _transferTokens() signatures RafflFactory.sol: - Add unchecked increment in checkUpkeep() loop - Cache _activeRaffles.length to avoid repeated SLOAD - Pre-calculate loop iterations to avoid repeated subtraction These optimizations reduce gas costs for frequently called functions by minimizing storage reads (SLOAD = 2100 gas cold, 100 gas warm).
Add detailed documentation for: - VRF callback out-of-gas scenarios - VRF never responds (network/subscription issues) - Automation (checkUpkeep/performUpkeep) failures - disperseRewards() transfer failures - Stale VRF response after retry - LINK subscription issues Each scenario includes: - ASCII diagrams showing the failure flow - State changes (or lack thereof) - Recovery options with specific function calls - Edge cases and limitations Also adds: - Complete recovery decision tree - Configuration constants reference - Monitoring recommendations
…ling - Rewrite TokenLib with inline assembly for balanceOf, safeTransfer, safeTransferFrom (~200-600 gas savings per call) - Add assembly ETH transfers in Raffl._transferEth and refundEntries (~100-200 gas per transfer) - Optimize event emissions with assembly log2 for EntriesBought (~50-100 gas) - Cache struct reads in loops (_transferPrizes, _ensureTokenGating) to reduce SLOADs - Use selector constant instead of string signature in createRaffle prize transfers - Add assembly keccak256 in nextSalt() (~50-100 gas) - Optimize checkUpkeep loop with struct caching and block.timestamp caching All 378 tests pass. Slither analysis shows no new vulnerabilities.
- forge-std: v1.8.1 → v1.14.0 - prettier: 3.7.4 → 3.8.0
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Overview
This PR introduces significant improvements to the Raffl Protocol, including a comprehensive VRF recovery system, performance optimizations, security enhancements, and extensive documentation. The changes represent a major version bump to v2.0.0.
📊 Summary Statistics
🚀 Major Features
1. VRF Recovery System
Problem Solved: Previously, raffles could get permanently stuck if Chainlink VRF requests failed or timed out, leaving user funds locked in the contract.
Solution: Implemented a comprehensive recovery system with two permissionless mechanisms:
Retry VRF Request (
retryVRFRequest)VRFRequestRetriedevent for monitoringEmergency Fail (
emergencyFailRaffle)RaffleEmergencyFailedeventKey Changes:
VRFRequeststruct to track request status and timingVRFStatusenum (None, Pending, Fulfilled, Failed)_raffleVRFRequestsand_requestIdsfulfillRandomWordsto handle retry scenariosDocumentation Added:
VRF-RECOVERY-USER-GUIDE.md- User-friendly guideVRF-RECOVERY-TECHNICAL.md- Developer documentationVRF-RECOVERY-QUICK-REFERENCE.md- Quick reference cardVRF-RECOVERY-README.md- Overview and index2. Performance Optimizations
Storage Layout Optimization
Raffl.sol: Reduced from ~17 storage slots to ~11 slots
factory,settled,prizesRefunded,gameStatusinto single slotRafflFactory.sol: Optimized struct packing
callbackGasLimit,requestConfirmations,nativePaymentinto one slotVRFRequest.requestTimefromuint256touint64(2 slots → 1 slot)ActiveRaffle.deadlinefromuint256touint64(2 slots → 1 slot)O(1) Raffle Removal
_raffleToActiveIndexmapping for O(1) lookup_removeRaffleFromActiveStorage Read Caching
Raffl.sol:
entryPriceinbuyEntries()to avoid redundant SLOADentryTokeninrefundEntries()and_purchaseEntry()RafflFactory.sol:
_activeRaffles.lengthincheckUpkeep()loopuncheckedincrement in loops where overflow is impossibleGas Impact: Reduces gas costs for frequently called functions by minimizing storage reads (SLOAD = 2100 gas cold, 100 gas warm).
3. Security Enhancements
Slither Warning Fixes
requestIdparameter tovrfRequestIdto avoid shadowing state variableSubscriptionConfigUpdatedevent tohandleSubscription()for better monitoringindexedparameter toRaffleCreatedevent for efficient log filteringIRafflinterface with improved NatSpec documentationEnhanced Error Handling
TokenLib4. Comprehensive Test Suite
Added 10 new test files covering:
RafflFactory.AccessControl.t.sol) - 467 linesRafflFactory.EdgeCases.t.sol) - 579 linesRafflFactory.VRFRetry.t.sol) - 547 linesRafflFactory.VRFRetryERC20.t.sol) - 161 linesRaffl.ChainlinkExceptions.t.sol) - 531 linesRaffl.DisperseRewards.t.sol) - 481 linesRaffl.Fuzz.t.sol) - 545 linesRaffl.Integration.t.sol) - 550 linesRaffl.Security.t.sol) - 622 linesRaffl.VRFCallbackFailure.t.sol) - 325 linesRaffl.VRFEdgeCases.t.sol) - 447 linesRaffl.EntriesEdgeCases.t.sol) - 493 linesRaffl.ExtraRecipientEdgeCases.t.sol) - 540 linesRaffl.ERC721Prizes.t.sol) - 594 linesRaffl.TokenGating.t.sol) - 464 linesTotal New Test Coverage: ~6,500+ lines of comprehensive test cases
5. Documentation
Added comprehensive documentation suite:
PROTOCOL_OVERVIEW.md (1,624 lines)
ENTERPRISE-AUDIT-PREPARATION-SUMMARY.md (699 lines)
AUDIT-READINESS-REPORT.md (577 lines)
VRF Recovery Documentation (4 files, ~2,100 lines total)
6. Code Quality Improvements
Solidity Version Upgrade
Code Refactoring
Dependency Updates
bun.lockbwith latest dependenciespackage.jsondependencies🔧 Technical Details
Contract Changes
RafflFactory.solcheckUpkeep()Raffl.solInterface Updates
IRaffl.sol: Added new functions and improved documentationIFactoryFeeManager.sol: Enhanced interface definitionsIFeeManager.sol: Updated interfaceError Libraries
RafflErrors.sol: Added new error typesRafflFactoryErrors.sol: Added VRF-related errors📝 Breaking Changes
Version Bump
Interface Changes
RafflFactory:retryVRFRequest(address raffle)emergencyFailRaffle(address raffle)getVRFRequestInfo(address raffle)hasVRFRequestTimedOut(address raffle)Event Changes
VRFRequestRetried(address indexed raffle, uint256 indexed requestId)RaffleEmergencyFailed(address indexed raffle)SubscriptionConfigUpdated(...)RaffleCreatedevent withindexedparameter✅ Testing
Test Coverage
Test Files Modified
VRFCoordinatorV2PlusMock.sol)Common.sol)🔒 Security Considerations
📦 Dependencies
bun.lockb(110,477 → 131,008 bytes)package.jsondependencies🎯 Migration Notes
For Users
For Developers
RafflFactoryfunctions for integrationFor Auditors
ENTERPRISE-AUDIT-PREPARATION-SUMMARY.mdfor detailed audit information📚 Documentation
All documentation is located in the
/docsdirectory:PROTOCOL_OVERVIEW.mdVRF-RECOVERY-README.md(start here)ENTERPRISE-AUDIT-PREPARATION-SUMMARY.mdVRF-RECOVERY-QUICK-REFERENCE.md🚦 Deployment Checklist
📈 Impact
User Experience
Developer Experience
Protocol Health
🔗 Related Issues
This PR addresses:
📅 Version
v2.0.0 - Major Release
This PR represents a significant milestone in the Raffl Protocol's development, introducing critical recovery mechanisms, performance improvements, and comprehensive documentation to ensure a robust and user-friendly raffle platform.