Skip to Content

Swap Functions

Overview

Welsh Street utilizes Uniswap V2-style LP token model This design choice creates significant advantages over existing Stacks exchanges:

The WELSH STREET Exchange implements a constant product Automated Market Maker (AMM) with integrated fee distribution for protocol operations. 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 distributions and protocol operations:

  1. Fee Component: Goes directly to liquidity providers through the distribution system
  2. Revenue Component: Funds protocol operations for development and maintenance

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 distribution contract for liquidity providers
  • Revenue Component (rev-a): (amount-a * rev) / BASIS → Sent to treasury address for protocol operations
  • Net Input: amount-a-net = amount-a - fee-total → Added to WELSH reserves

Returns:

  • amount-in: Input WELSH token amount
  • amount-out: Output STREET token amount received by user
  • fee-a: WELSH tokens allocated to liquidity provider rewards
  • res-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 = k

Where:

  • 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

Distribution System Integration

Automatic Token Distribution:

;; Fee allocation to distributions (try! (transformer .WELSHcorgicoin fee-a .rewards)) (try! (contract-call? .rewards update-rewards-a fee-a))

Benefits:

  • Zero Dilution: Existing LP holders receive proportional distributions immediately
  • High Precision: 9-decimal precision prevents rounding losses
  • Automatic Updates: No manual intervention required for token 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:

  1. Calculating expected output using current reserves
  2. Setting minimum acceptable output amount
  3. 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) = k

Fee Impact on Reserves: Fees are extracted before the constant product calculation, ensuring:

  1. Liquidity providers receive genuine rewards
  2. Protocol receives sustainable revenue
  3. 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 treasury

Basic 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

1. Swap Fee Share

Purpose: Shared trading fees distributed to liquidity providers through the distribution contract.

Destination: Transferred directly to the .rewards contract - inaccessible to deployer/treasury.

Implementation in Swaps:

(fee-a (/ (* amount-a (var-get fee)) BASIS)) (fee-total (/ (* amount-a (+ (var-get fee) (var-get rev))) BASIS)) ;; Fee distribution in swap-a-b (if (> fee-total u0) (begin (try! (transformer .WELSHcorgicoin fee-a .rewards)) ;; Fee goes to rewards (try! (contract-call? .rewards update-rewards-a fee-a)) ) true)

Security: These funds are permanently allocated to LP distributions and cannot be accessed by the treasury or contract owner.

Last updated on