This PR implements a dedicated backend endpoint for calculating impermanent loss (IL) risk for liquidity providers. The endpoint accepts entry and current price ratios and algorithmically calculates the percentage of impermanent loss based on the constant product formula.
- GET endpoint:
/api/v1/analytics/impermanent-loss - Mathematical implementation: Standard IL formula
2 * sqrt(price_ratio) / (1 + price_ratio) - 1 - Input validation: Ensures positive price ratios
- Standardized response: JSON wrapper with success flag and timestamp
- Swagger documentation: Complete API documentation with examples
src/analytics/analytics.service.ts: AddedcalculateImpermanentLoss()methodsrc/analytics/analytics.controller.ts: AddedgetImpermanentLoss()endpointsrc/analytics/analytics.module.ts: No changes needed (existing structure)
test-impermanent-loss.js: Endpoint integration teststest-il-formula.js: Mathematical formula validationIMPERMANENT_LOSS_ENDPOINT.md: Comprehensive documentation
GET /api/v1/analytics/impermanent-loss?entryPriceRatio=1.0¤tPriceRatio=1.5{
"success": true,
"data": {
"entryPriceRatio": 1.0,
"currentPriceRatio": 1.5,
"impermanentLossPercentage": -2.02
},
"timestamp": "2024-01-15T10:30:00.000Z"
}- ✅ No price change = 0% IL
- ✅ Price increase/decrease symmetry
- ✅ Input validation (zero/negative prices)
- ✅ Mathematical accuracy
- ✅ Response structure validation
- ✅ Error handling
- ✅ Swagger documentation
- ✅ CORS compatibility
- Performance: Heavy mathematical processing moved to backend
- Consistency: Standardized calculation across all clients
- Scalability: Leverages API infrastructure for high-volume requests
- Power User Value: Advanced liquidity providers can hedge positions
- Developer Experience: Well-documented endpoint with examples
- Input validation prevents mathematical errors
- Global exception handling for consistent error responses
- CORS configuration maintained
- Rate limiting through existing throttling guards
Complete API documentation available at:
- Swagger UI:
http://localhost:3000/api/docs - Technical documentation:
IMPERMANENT_LOSS_ENDPOINT.md
- Start the development server:
npm run start:dev - Test the formula validation:
node test-il-formula.js - Test the endpoint:
node test-impermanent-loss.js - View Swagger documentation: Navigate to
/api/docs
- Code follows existing project patterns
- Mathematical implementation is correct
- Input validation implemented
- Error handling in place
- Swagger documentation complete
- Test scripts provided
- Documentation created
- No breaking changes to existing endpoints
Resolves #88: "feat: Create an API endpoint for historical impermanent loss calculation"
This implementation provides advanced liquidity providers with the tools they need to calculate impermanent loss risk before depositing funds, moving heavy mathematical processing off the frontend and into the scalable API layer.