Swap Functions
Overview
The Welsh Street Exchange implements a constant product Automated Market Maker (AMM) with integrated fee distribution for sustainable protocol growth. The swap functions swap-a-b and swap-b-a enable bidirectional token swapping between Welsh Corgi Coin (WELSH) and Street Token (STREET) using the mathematical formula x * y = k, where liquidity is preserved through constant product mechanics.
Contract Architecture
The exchange maintains dual reserve pools and implements a two-tier fee system that supports both liquidity provider rewards and protocol treasury funding:
- Fee Component: Goes directly to liquidity providers through the rewards system
- Revenue Component: Funds protocol treasury for development and growth
Core Swap Functions
swap-a-b: Welsh → Street Swap
Exchanges Welsh tokens for Street tokens using constant product AMM mechanics with integrated fee distribution.
(define-public (swap-a-b (amount-a uint))
(let (
(res-a (var-get reserve-a))
(res-b (var-get reserve-b))
(lock-a (var-get locked-a))
(lock-b (var-get locked-b))
(fee-total (/ (* amount-a (+ (var-get fee) (var-get rev))) BASIS))
(rev-a (/ (* amount-a (var-get rev)) BASIS))
(fee-a (/ (* amount-a (var-get fee)) BASIS))
(amount-a-net (- amount-a fee-total))
(num (* amount-a-net res-b))
(den (+ res-a amount-a-net))
(amount-b (/ num den))
(amount-b-net amount-b)
(res-a-new (+ res-a amount-a-net))
(res-b-new (- res-b amount-b-net))
(lock-a-new (if (> res-a u0) (/ (* lock-a res-a-new) res-a) lock-a))
(lock-b-new (if (> res-b u0) (/ (* lock-b res-b-new) res-b) lock-b))
(treasury (var-get treasury-address))
)
(begin
(asserts! (> amount-a u0) ERR_ZERO_AMOUNT)
(asserts! (> amount-b-net u0) ERR_INVALID_AMOUNT)
(try! (contract-call? .welshcorgicoin transfer amount-a tx-sender .exchange none))
(try! (transformer .welshcorgicoin rev-a treasury))
(try! (transformer .welshcorgicoin fee-a .rewards))
(try! (transformer .street amount-b-net tx-sender))
(try! (contract-call? .rewards update-rewards-a fee-a))
(var-set reserve-a res-a-new)
(var-set reserve-b res-b-new)
(var-set locked-a lock-a-new)
(var-set locked-b lock-b-new)
(ok {
amount-in: amount-a,
amount-out: amount-b-net,
fee-a: fee-a,
res-a: res-a,
res-a-new: res-a-new,
res-b: res-b,
res-b-new: res-b-new,
rev-a: rev-a })
)
)
)Parameters:
amount-a: Amount of Welsh tokens to swap (in natural units)
AMM Calculation Formula: The swap uses the constant product formula with fee deduction:
amount-a-net = amount-a - fee-total
amount-b = (amount-a-net * res-b) / (res-a + amount-a-net)Fee Distribution:
- Fee Component (
fee-a):(amount-a * fee) / BASIS→ Sent to rewards contract for liquidity providers - Revenue Component (
rev-a):(amount-a * rev) / BASIS→ Sent to treasury address for protocol growth - Net Input:
amount-a-net = amount-a - fee-total→ Added to Welsh reserves
Returns:
amount-in: Input Welsh token amountamount-out: Output Street token amount received by userfee-a: Welsh tokens allocated to liquidity provider rewardsres-a/res-a-new: Welsh reserve amounts (before/after swap)res-b/res-b-new: Street reserve amounts (before/after swap)rev-a: Welsh tokens sent to treasury
Requirements:
- Input amount must be greater than zero
- Output amount must be greater than zero (prevents zero-output swaps)
- User must have sufficient Welsh token balance
- Liquidity pool must be initialized
Swap Mechanics
Constant Product AMM
The Welsh Street Exchange implements the constant product formula:
x * y = kWhere:
x= Welsh token reserves (reserve-a)y= Street token reserves (reserve-b)k= Constant product (maintained across swaps)
Slippage and Price Impact
Price Impact Calculation: Price impact increases with swap size relative to pool depth. Larger swaps experience higher slippage due to the constant product curve.
Slippage Formula:
price-impact = 1 - (output-amount / (input-amount * current-rate))Reserve Updates
Reserve Management:
- Welsh Reserves: Updated with net input amount (after fees) for both swap directions
- Street Reserves: Updated with net input amount (after fees) for both swap directions
- Atomic Updates: Both reserves updated atomically to maintain consistency
Integration Points
Rewards System Integration
Automatic Reward Distribution:
;; Fee allocation to rewards
(try! (transformer .welshcorgicoin fee-a .rewards))
(try! (contract-call? .rewards update-rewards-a fee-a))Benefits:
- Zero Dilution: Existing LP holders receive proportional rewards immediately
- High Precision: 9-decimal precision prevents rounding losses
- Automatic Updates: No manual intervention required for reward distribution
Treasury Integration
Protocol Revenue Flow:
;; Revenue allocation to treasury
(try! (transformer .welshcorgicoin rev-a treasury))Treasury Features:
- Configurable Address: Treasury address can be updated by current treasury
- Lock Protection: Treasury can be permanently locked to prevent changes
- Multi-Token Support: Receives both Welsh and Street tokens from swaps
Error Handling
Error Constants
(define-constant ERR_ZERO_AMOUNT (err u700))Swap-Specific Validations:
- Input Validation: Prevents zero-amount swaps
- Output Validation: Prevents zero-output scenarios (insufficient liquidity)
- Balance Validation: Ensures sufficient user token balance
- Reserve Validation: Implicitly checks for initialized liquidity pools
Edge Case Handling
Slippage Protection: Users should implement slippage tolerance in their applications by:
- Calculating expected output using current reserves
- Setting minimum acceptable output amount
- Comparing actual output with expectations
Liquidity Depth Considerations:
- Small pools: Higher price impact for large swaps
- Large pools: Lower price impact, better capital efficiency
- Zero liquidity: Swaps will fail with ERR_ZERO_AMOUNT
Mathematical Properties
Constant Product Preservation
Invariant Maintenance:
;; Before swap: reserve-a * reserve-b = k
;; After swap: (reserve-a + amount-a-net) * (reserve-b - amount-b-net) = kFee Impact on Reserves: Fees are extracted before the constant product calculation, ensuring:
- Liquidity providers receive genuine rewards
- Protocol receives sustainable revenue
- AMM mechanics remain mathematically sound
Arbitrage Resistance
Price Discovery: The constant product curve creates natural arbitrage opportunities that:
- Align exchange prices with external markets
- Provide MEV opportunities for arbitrageurs
- Generate additional volume and fees for LP holders
Security Features
Access Controls
Public Functions:
- Both swap functions are publicly accessible
- No special permissions required for swapping
Administrative Functions:
- Fee/revenue rate updates restricted to contract owner
- Treasury management restricted to treasury address
Economic Security
MEV Protection:
- Transparent fee structure prevents hidden extraction
- Predictable slippage based on mathematical formulas
Liquidity Protection:
- Constant product formula prevents reserve depletion
- Minimum fee rates ensure sustainable rewards
- Maximum fee rates prevent excessive extraction
Usage Examples
Basic Welsh → Street Swap
;; Swap 1,000 Welsh tokens for Street tokens
(contract-call? .exchange swap-a-b u1000000000) ;; 1,000 tokens (6 decimals)
;; Expected behavior:
;; 1. Deducts 2% total fees (20 Welsh tokens at default rates)
;; 2. Uses 980 Welsh for constant product calculation
;; 3. Returns calculated Street tokens to user
;; 4. Distributes 10 Welsh to LP rewards, 10 Welsh to treasuryBasic Street → Welsh Swap
;; Swap 100,000 Street tokens for Welsh tokens
(contract-call? .exchange swap-b-a u100000000000) ;; 100,000 tokens (6 decimals)
;; Expected behavior:
;; 1. Deducts 2% total fees (2,000 Street tokens at default rates)
;; 2. Uses 98,000 Street for constant product calculation
;; 3. Returns calculated Welsh tokens to user
;; 4. Distributes 1,000 Street to LP rewards, 1,000 Street to treasury