Trading Pool v2
Overview
Trading Pool v2 (amm-pool-v2-02.clar) is a version of amm-pool-v2-01.clar that addresses security issues, accuracy problems, and code quality concerns identified through code review. v2 replaces the power-based Generalized Mean formula with the Solidly formula (x^nΒ·y + xΒ·y^n = k) and integrates Clarity v4 restrict-assets? for enhanced security.
Key improvements over v1:
Security: Division-by-zero protection, balance underflow prevention, fee validation, input validation
Accuracy: Improved pow-down/pow-up error model, better threshold handling
Performance: 60-77% gas cost reduction using native
sqrtiinstead of iterative power calculationsCode Quality: Constants organization, standardized error handling, Clarity 3 compatibility
Changes from v1 to v2
Security Improvements
1. Division-by-Zero Protection
Added explicit checks for
balance-x > 0before division in price calculationsPrevents runtime errors in edge cases
2. Balance Underflow Prevention
Replaced conditional logic with explicit assertions
Example:
(asserts! (> balance-y dy) ERR-NO-LIQUIDITY)before(- balance-y dy)Applied to:
swap-x-for-y,swap-y-for-x,reduce-position
3. Fee Validation
Explicit validation to prevent zero swaps
Validates:
dx > 0,dx > fee,fee-rebate <= fee
4. Input Validation
Added
validate-pool-paramshelper functionValidates:
token-x β token-y,factor <= ONE_8Applied to:
create-pool,add-to-position
5. Threshold Handling
Improved handling to prevent division by zero when
t >= ONE_8Safe division because
t-componly used whent < threshold
Accuracy Improvements
1. pow-down/pow-up Error Model
v1 used mul-up which compounded error:
v2 uses direct division with proper rounding:
Changes:
Removed
mul-upto avoid compounding errorDirect division with round-up for error calculation
Added
MIN_POW_ABSOLUTE_ERRORconstantUses
<=instead of<for comparison
2. get-switch-threshold Usage
Result cached at function start instead of multiple calls
Reduces redundant computation
Code Quality Improvements
1. Constants Organization
All constants defined at top (lines 27-58)
Replaced magic numbers with named constants (e.g.,
MAX_UINT)
2. Address References
Changed from relative (
.executor-dao) to absolute addresses ('SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.executor-dao')
3. Clarity 3 Compatibility
Uses
stacks-block-heightinstead ofblock-height
4. Error Handling
Standardized patterns across all functions
What Are the Biggest Changes?
1. New Mathematical Formula (Power-Based β Solidly)
Before (v1): Used power calculations with pow-fixed function
Small swaps (0.0001 units) often returned zero
High gas costs: 800k for swaps
Precision loss when subtracting nearly equal fixed-point numbers
Example: Pool with 0.1 units each, t=0.05, swap 0.0001 β returned 0
Now (v2): Uses Solidly formula with native sqrti
All swap sizes work correctly
60-77% gas reduction (180k-320k for swaps)
Closed-form solutions: no iteration needed
Formula: where
2. Enhanced Security with restrict-assets?
Before (v1): Relied on token behavior
Now (v2): Clarity v4 restrict-assets? enforcement
Automatic rollback if token transfers exceed specified amount
Protection against reentrancy attacks
Enforced swap amounts
3. Better Price Accuracy
Before (v1): Power calculations lost precision in small swaps
Now (v2): Closed-form solutions with native sqrti
Accurate for all pool sizes
Scale-invariant behavior
No precision loss from subtracting similar numbers
Problems Addressed
Problem 1: Small Swap Precision Loss
Root cause: For small swaps, x^Ξ± - (x+dx)^Ξ± loses precision when subtracting nearly equal fixed-point numbers.
Example:
Solution: Solidly formula uses quadratic formula y' = (-x' + β(x'Β² + 4k/x')) / 2 with native sqrti, avoiding subtraction of similar numbers.
Problem 2: High Gas Costs
Root cause: Complex power calculations require many computational steps and iterations.
Solution: Solidly formula has closed-form solutions:
n=1 (volatile): Direct division, 77% gas reduction (800k β 180k)
n=2 (stable): Quadratic formula with
sqrti, 60% gas reduction (800k β 320k)
Problem 3: Security Gaps
Root cause: v1 relied on token behavior without blockchain-level enforcement.
Solution:
Clarity v4
restrict-assets?enforces transfer limits at blockchain levelExplicit validation: division-by-zero protection, balance underflow prevention, fee validation
Input validation via
validate-pool-paramshelper
Problem 4: Scale Dependence
Root cause: v1 formula behavior varied with absolute pool size due to fixed-point precision.
Solution: Solidly formula is scale-invariantβpool with [1, 1] behaves identically to [1000, 1000] in terms of price impact and slippage.
Implementation Status
Development Complete (December 2025)
β Core Implementation: Complete
Solidly formula implemented and tested
restrict-assets?security integration completeGas optimizations applied
All existing v1 features working
44/44 tests passing
β Development Environment: Complete
Clarinet SDK upgraded to v3.11.0 with full Clarity v4 support
Comprehensive test suite passing
Security scenarios validated (normal, token drain, STX drain)
Mathematical properties verified (price bounds, function symmetry)
Error code behavior confirmed
π Next Steps: External Security Audit
Contract ready for professional security audit
Testnet deployment for user testing
Mainnet deployment via DAO proposal after audit approval
Deployment Approach
The upgrade will replace the existing amm-pool-v2-01 contract with amm-pool-v2-02. This is a logic-only upgrade that:
β Requires no pool migration
β Requires no liquidity provider action
β Maintains all existing pool parameters and balances
β Seamless from the user perspective
All existing pools will automatically benefit from the improved formula and enhanced security without any user intervention.
What This Means for You
If You're a Trader:
β Small swaps will work reliably
β Lower transaction fees (40-77% reduction)
β More accurate pricing
β Same familiar interface and pool structure
β Enhanced protection against malicious tokens
If You're a Liquidity Provider:
β More efficient pools (less gas waste)
β Better price stability
β Same rewards structure
β Improved pool token (LP Token) consistency
β No migration requiredβyour positions automatically benefit
β Additional security for your liquidity
If You're a Developer:
β Same API as v1 (easy integration)
β Four new utility functions for advanced use cases:
get-y-in-given-x-out: Calculate Y needed when withdrawing Xget-x-in-given-y-out: Calculate X needed when withdrawing Yget-x-given-price: Calculate X to reach target priceget-y-given-price: Calculate Y to reach target price
β Better documentation and clearer code
β
restrict-assets?examples for building secure integrations
Performance Metrics
Gas Cost Comparison (Simnet Testing)
create-pool
150k
130k
110k
13-27%
add-to-position
200k
160k
140k
20-30%
swap
800k
320k
180k
60-77%
reduce-position
180k
150k
130k
17-28%
Precision Improvement (1,000 test swaps)
1e-8 to 1e-6
95%
0%
1e-6 to 1e-4
30%
0%
1e-4 to 1e-2
5%
0%
> 1e-2
<1%
0%
Contract Size
Lines
761
728
Functions
48
52
Tests
18
22
Alternative Methodologies Evaluated
Before selecting Solidly, we evaluated several alternative AMM formulas:
1. Wombat Exchange
Invariant: (x - A/x) + (y - A/y) = D
Pros: Good precision for stable pairs, proven in production
Cons: Not scale-invariant (A must equal
Ξ± Γ LΒ²for consistent behavior), requires custom square root
2. Solidly (Selected)
Invariant: x^nΒ·y + xΒ·y^n = k
Pros: Scale-invariant, closed-form for n=1,2 using native
sqrti, deployed on Solidly, Velodrome, AerodromeCons: Limited to nβ€2 for closed-form solutions
3. Saddle Finance
Invariant: A(x + y) + xy = k
Pros: Simpler than Curve, decent for stable pairs
Cons: Not scale-invariant (similar to Wombat), limited production usage
4. Hybrid Constant Function
Invariant: w(x + y) + (1-w)(xy)/(x+y) = k
Pros: Interesting theoretical properties
Cons: Limited production testing, partially scale-invariant
Selection Rationale
Scale Invariant
No
Yes
No
Partial
Small Swap Precision
Good
Excellent
Good
Moderate
Native Clarity Support
No (custom sqrt)
Yes (sqrti)
No
Yes
Production Use
Yes
Yes
Limited
No
Decision: Solidly selected for scale invariance and native sqrti support.
Why Not nβ₯3?
n=3+ requires Newton's method iteration:
Non-deterministic gas costs
Precision issues in fixed-point
<1% of pools would use it
Decision: Prioritize closed-form solutions (n=1,2).
Implementation Details
Invariant Calculation
Swap Calculation (n=2)
Mapping Strategy
0.8-1.0
n=1
2xy = k
Volatile
0.2-0.8
n=2
xΒ²y + xyΒ² = k
Semi-stable
<0.2
n=2
xΒ²y + xyΒ² = k
Stable
New API Functions
v2 adds 4 read-only functions:
get-y-in-given-x-out- Calculate Y needed when withdrawing Xget-x-in-given-y-out- Calculate X needed when withdrawing Yget-x-given-price- Calculate X to reach target priceget-y-given-price- Calculate Y to reach target price
Frequently Asked Questions
Q: Will my existing LP positions be affected? A: No action required. Logic-only upgrade. Existing positions benefit from the improved formula without migration.
Q: Will the pool parameter still exist? A: The parameter remains for backward compatibility. It's internally mapped to (1 or 2) in v2:
β (volatile, constant product-like)
β (stable, enhanced curve)
Q: Why not support more values (n=3, n=4, etc.)? A: Higher values require iterative Newton's method calculations, which would:
Increase gas costs unpredictably
Introduce precision issues
Benefit less than 1% of pools
Add complexity for minimal gain
The and cases cover all practical use cases with closed-form solutions.
Q: Is this battle-tested? A: The Solidly formula is used by:
Velodrome Finance: ~$50M daily volume
Aerodrome: ~$100M daily volume
Solidly (original): Production deployment
Combined: $150M+ daily volume
Implementation tested on Stacks testnet with 44/44 tests passing. Security audit scheduled before mainnet deployment.
Q: When can we expect deployment? A: Development is complete with 44/44 tests passing. Timeline:
β Development & Testing: Complete (Clarinet SDK v3.11.0 with Clarity v4 support)
π External Security Audit: Contract ready for professional audit
π Testnet Deployment: User testing after audit completion
π Mainnet Deployment: Via DAO proposal after audit approval
Updates will be provided as milestones are reached.
Q: Will there be any downtime during the upgrade? A: No. Seamless upgrade with no service interruption. Pools continue operating normally.
Q: Can I still use the same helper functions? A: All v1 helper functions remain:
swap-helper(automatic routing)swap-helper-a,swap-helper-b,swap-helper-c(multi-hop)get-oracle-instant,get-oracle-resilient(price oracles)get-position-given-mint,get-position-given-burnget-token-given-position
Plus four new functions for advanced use cases.
Timeline Summary
Core Development
β Complete
Solidly formula + restrict-assets? implemented
SDK Tooling
β Complete
Clarinet SDK v3.11.0 with Clarity v4 support
Testing
β Complete
44/44 tests passing (functionality, security, mathematics)
Security Audit
π Ready
Contract ready for external audit
Testnet Deployment
π Planned
User testing after audit
Mainnet Deployment
π Planned
Via DAO proposal after audit approval
Summary
Trading Pool v2 improvements:
Mathematical Formula: Solidly formula fixes precision issues and reduces gas costs by 60-77%
Security Enhancements:
Clarity v4
restrict-assets?for malicious token protectionDivision-by-zero protection, balance underflow prevention, fee validation
Input validation via
validate-pool-paramshelper
Accuracy Improvements:
Improved pow-down/pow-up error model
Better threshold handling
No precision loss in small swaps
Code Quality:
Constants organization, standardized error handling
Clarity 3 compatibility (
stacks-block-height)Absolute address references
Proven Technology: Solidly formula used by DEXs with $150M+ daily volume
Backward Compatible: Same API, same parameter (mapped to ), same error codes
Migration
Logic-only upgrade. No pool migration required. No user action required.
Breaking Changes
Address references changed from relative to absolute
Requires Clarity 3 compatible environment
Non-Breaking Changes
Public API: All function signatures unchanged
Error codes: All error codes unchanged
Return types: All return types unchanged
Mathematical formulas: Core formulas unchanged (only error handling improved)
Technical Details: The Math Behind v2
Formula Evolution
v1 (Power-Based):
Where is a parameter between 0 and 1:
: Constant product (Uniswap-like)
: Constant sum (mStable-like)
: Curve-like behavior
Issues:
Small swaps lose precision when subtracting nearly equal numbers
Power calculations require iterative methods
High gas costs (800k per swap)
v2 (Solidly):
Where is derived from :
: (volatile pairs)
: (stable pairs)
Improvements:
Closed-form solutions using native
sqrtiNo precision loss from subtraction
60-77% gas reduction
Why Solidly?
Alternative AMM formulas were evaluated to address v1 limitations.
Alternatives Explored
1. Wombat Exchange
Formula:
Pros: Good precision for stable pairs, production deployment
Cons: Not scale-invariant (parameter must scale with pool size: ), requires custom square root implementation
2. Curve StableSwap
Formula:
Pros: Highly optimized for stable pairs, industry standard
Cons: Complex multi-token formula, requires Newton's method iteration, high gas costs
3. Saddle Finance
Formula:
Pros: Simpler than Curve, good for stable pairs
Cons: Not scale-invariant (similar to Wombat), limited production usage
4. Solidly (Selected)
Formula:
Pros: Scale-invariant, closed-form solutions for , uses native
sqrti, production deploymentCons: Limited to for closed-form solutions
5. Hybrid Constant Function
Formula:
Pros: Interesting theoretical properties, uses native functions
Cons: Limited production testing, partially scale-invariant
Comprehensive Comparison
Criterion
v1 (Power)
v2 (Solidly)
Wombat
Curve
Saddle
Hybrid
Formula
Complex
Scale Invariant
Partial
β Yes
β No
β Yes
β No
Partial
Small Swap Precision
β Poor
β Excellent
Good
β Excellent
Good
Moderate
Native Clarity Support
Partial (pow issues)
β Yes (sqrti)
β No
β No
Partial
β Yes
Gas Efficiency
Low (800k)
β High (180-320k)
Moderate
Low
Moderate
High
Deterministic Gas
β No (iterations)
β Yes
β No
β No
Moderate
β Yes
Production Use
ALEX only
β Major DEXs
Yes
β Major DEXs
Limited
No
Daily Volume
~$500K
~$150M+
~$20M
~$100M+
~$1M
N/A
Implementation Complexity
High
Low
Moderate
High
Moderate
Low
Security Features
Basic
β restrict-assets?
Basic
Basic
Basic
Basic
Direct Solutions
For (volatile pairs):
Invariant:
Given new , solve for :
Output:
Gas: 180k per swap (77% reduction from v1)
For (stable pairs):
Invariant:
Given new , factor and rearrange:
Using quadratic formula:
Output:
Gas: 320k per swap (60% reduction from v1)
This uses Clarity's native sqrti function for the square root, providing exact results without iteration.
Glossary Updates for v2
Factor ( parameter)
In v2, the factor is mapped to the exponent in the Solidly formula:
: Maps to (volatile pairs, constant product behavior)
: Maps to (stable pairs, enhanced curve behavior)
This mapping is handled automatically by the contract and is invisible to users.
Invariant
The value that remains constant after accounting for fees in a swap:
v1:
v2:
Scale Invariance
A mathematical property where the formula behaves identically regardless of the absolute pool size. For example, a pool with [1, 1] behaves the same as a pool with [1000, 1000] in terms of price impact and slippage.
Closed-Form Solution
A mathematical solution that can be calculated directly (non-iteratively) using a formula. v2 uses closed-form solutions for both and cases, resulting in deterministic gas costs and perfect precision.
restrict-assets?
A Clarity v4 security feature that enforces maximum transfer amounts at the blockchain level. If a token attempts to transfer more than the specified allowance, the entire transaction automatically rolls back, preventing malicious behavior.
References
Solidly Exchange: https://solidly.exchange
Velodrome Finance: https://velodrome.finance
Aerodrome: https://aerodrome.finance
Wombat Whitepaper: https://www.wombat.exchange/Wombat_Whitepaper_Public.pdf
Curve StableSwap: https://curve.fi/whitepaper
Clarity sqrti: https://docs.stacks.co/reference/clarity/functions#sqrti
Clarity restrict-assets?: https://docs.stacks.co/clarity/keywords#restrict-assets
Questions or feedback? Join the discussion in the ALEX Discord or GitHub.
Last updated
Was this helpful?