From 7495dfd74a6b195766e901192864b7cf466b97c8 Mon Sep 17 00:00:00 2001 From: Ross Ragsdale Date: Tue, 10 Dec 2024 01:38:23 -0600 Subject: [PATCH 1/5] Liquidity Pool SIP initial draft This SIP defines a standard trait interface for liquidity pools on the Stacks blockchain. The standard enables independent implementation of liquidity pools while maintaining a unified interface, facilitating the development of swap aggregators and multi-hop transactions across multiple pools. --- sips/sip-03X/README.md | 226 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 226 insertions(+) create mode 100644 sips/sip-03X/README.md diff --git a/sips/sip-03X/README.md b/sips/sip-03X/README.md new file mode 100644 index 00000000..ca493a5c --- /dev/null +++ b/sips/sip-03X/README.md @@ -0,0 +1,226 @@ +# Preamble + +SIP Number: 03X + +Title: Standard Trait Definition for Liquidity Pools + +Author: rozar.btc + +Consideration: Technical + +Type: Standard + +Status: Draft + +Created: 10 December 2024 + +License: CC0-1.0 + +Layer: Traits + +Sign-off: [Sign Off] + +Discussions-To: [URL] + +# Abstract + +This SIP defines a standard trait interface for liquidity pools on the Stacks blockchain. The standard enables independent implementation of liquidity pools while maintaining a unified interface, facilitating the development of swap aggregators and multi-hop transactions across multiple pools. + +# License and Copyright + +This SIP is made available under the terms of the Creative Commons CC0 1.0 Universal license, available at https://creativecommons.org/publicdomain/zero/1.0/ + +# Introduction + +Liquidity pools are a fundamental component of decentralized finance, enabling automated market making and token swapping capabilities. Each pool manages a pair of SIP-010 fungible tokens and provides functionality for: + +1. Adding liquidity by depositing both tokens +2. Removing liquidity by burning LP tokens +3. Swapping one token for the other +4. Querying pool state and quotes + +By standardizing the interface for liquidity pools, we enable: +- Consistent interaction patterns across different implementations +- Development of swap aggregators and routing engines +- Common tooling and integration patterns +- Future extensibility through memo commands + +# Specification + +## Core Functions + +### Add Liquidity + +```clarity +(add-liquidity + ( + (token-a-amount uint) + (token-b-amount uint) + (memo (optional (buff 34))) + ) + (response uint uint)) +``` + +Adds liquidity by depositing both tokens, returns the amount of LP tokens minted. + +### Remove Liquidity + +```clarity +(remove-liquidity + ( + (lp-token-amount uint) + (memo (optional (buff 34))) + ) + (response (tuple (token-a uint) (token-b uint)) uint)) +``` + +Burns LP tokens and returns both underlying tokens. + +### Swap + +```clarity +(swap + ( + (token-in ) + (amount-in uint) + (memo (optional (buff 34))) + ) + (response uint uint)) +``` + +Swaps one token for the other. The output token is implictly determined by the pool token being passed in and/or if an optional memo is provided. + +## Quote Functions + +### Add Liquidity Quote + +```clarity +(get-add-liquidity-quote + ( + (token-a-amount uint) + (token-b-amount uint) + (memo (optional (buff 34))) + ) + (response + (tuple (token-a uint) (token-b uint) (lp-tokens uint)) + uint)) +``` + +Returns expected amounts for adding liquidity. + +### Remove Liquidity Quote + +```clarity +(get-remove-liquidity-quote + ( + (lp-token-amount uint) + (memo (optional (buff 34))) + ) + (response + (tuple (token-a uint) (token-b uint) (lp-tokens uint)) + uint)) +``` + +Returns expected amounts for removing liquidity. + +### Swap Quote + +```clarity +(get-swap-quote + ( + (token-in ) + (amount-in uint) + (memo (optional (buff 34))) + ) + (response (tuple (token-in uint) (token-out uint)) uint)) +``` + +Returns expected amounts for a swap. + +## Pool Information + +```clarity +(get-pool-info () + (response + (tuple + (token-a (tuple (contract principal) (identifier (string-ascii 32)) (reserve uint))) + (token-b (tuple (contract principal) (identifier (string-ascii 32)) (reserve uint))) + (lp-token (tuple (contract principal) (identifier (string-ascii 32)) (supply uint))) + ) + uint)) +``` + +Returns comprehensive pool information including token contracts, identifiers, reserves and supply. + +## Trait Implementation + +```clarity +(define-trait liquidity-pool-trait + ( + ;; Liquidity Operations + (add-liquidity (uint uint (optional (buff 34))) (response uint uint)) + (remove-liquidity (uint (optional (buff 34))) + (response (tuple (token-a uint) (token-b uint)) uint)) + + ;; Swap Operations + (swap ( uint (optional (buff 34))) (response uint uint)) + + ;; Quotes + (get-add-liquidity-quote (uint uint (optional (buff 34))) + (response (tuple (token-a uint) (token-b uint) (lp-tokens uint)) uint)) + (get-remove-liquidity-quote (uint (optional (buff 34))) + (response (tuple (token-a uint) (token-b uint) (lp-tokens uint)) uint)) + (get-swap-quote ( uint (optional (buff 34))) + (response (tuple (token-in uint) (token-out uint)) uint)) + + ;; Pool Information + (get-pool-info () + (response + (tuple + (token-a (tuple (contract principal) (identifier (string-ascii 32)) (reserve uint))) + (token-b (tuple (contract principal) (identifier (string-ascii 32)) (reserve uint))) + (lp-token (tuple (contract principal) (identifier (string-ascii 32)) (supply uint))) + ) + uint)) + ) +) +``` + +# Implementation Guidelines + +## Post Conditions +All slippage protection must be implemented using post conditions rather than explicit parameters. Implementations should set appropriate post conditions for: +- Minimum LP tokens when adding liquidity +- Minimum output tokens when removing liquidity +- Minimum output tokens when swapping + +## Memo Support +- Pools may support advanced operations through memo buffers +- Memo command documentation is out of scope for this SIP +- Memo parsing should be robust and fail gracefully + +# Applications + +## Swap Aggregators +Aggregators implementing this standard should: +1. Query pool info to discover token pairs +2. Use quote functions to calculate optimal routes +3. Set appropriate post conditions for slippage protection + +## Direct Integration +Applications directly integrating with pools should: +1. Verify pool and token contracts implement required traits +2. Use get-pool-info to fetch current state +3. Get quotes before executing operations +4. Set appropriate post conditions + +# Reference Implementation + +[Link to reference implementation repository] + +# Activation + +This SIP will be considered activated when: +1. The trait is deployed to mainnet +2. At least 3 different implementations are deployed +3. A functional swap aggregator demonstrates multi-hop capabilities From fa122b958f2a7561538f0143d25ee2962cd97306 Mon Sep 17 00:00:00 2001 From: Ross Ragsdale Date: Thu, 12 Dec 2024 19:24:18 -0600 Subject: [PATCH 2/5] Update README.md Update SIP with newest version matching reference implementation. --- sips/sip-03X/README.md | 337 ++++++++++++++++++++++++++++++++--------- 1 file changed, 268 insertions(+), 69 deletions(-) diff --git a/sips/sip-03X/README.md b/sips/sip-03X/README.md index ca493a5c..9eeb642f 100644 --- a/sips/sip-03X/README.md +++ b/sips/sip-03X/README.md @@ -24,7 +24,7 @@ Discussions-To: [URL] # Abstract -This SIP defines a standard trait interface for liquidity pools on the Stacks blockchain. The standard enables independent implementation of liquidity pools while maintaining a unified interface, facilitating the development of swap aggregators and multi-hop transactions across multiple pools. +This SIP defines a standard trait interface for liquidity pools on the Stacks blockchain. The standard enables independent implementation of liquidity pools while maintaining a unified interface, facilitating the development of swap aggregators and multi-hop transactions across multiple pools. The standard introduces an extensible opcode buffer system for advanced pool operations. # License and Copyright @@ -39,7 +39,8 @@ Liquidity pools are a fundamental component of decentralized finance, enabling a 3. Swapping one token for the other 4. Querying pool state and quotes -By standardizing the interface for liquidity pools, we enable: +The standard introduces an opcode buffer system that enables advanced pool operations while maintaining backward compatibility. This allows for future extensions such as concentrated liquidity, flash loans, and advanced routing without requiring interface changes. By standardizing the interface for liquidity pools, we enable: + - Consistent interaction patterns across different implementations - Development of swap aggregators and routing engines - Common tooling and integration patterns @@ -54,41 +55,43 @@ By standardizing the interface for liquidity pools, we enable: ```clarity (add-liquidity ( - (token-a-amount uint) - (token-b-amount uint) - (memo (optional (buff 34))) + (amount uint) + (opcode (optional (buff 16))) ) - (response uint uint)) + (response + (tuple (dx uint) (dy uint) (dk uint)) + uint)) ``` -Adds liquidity by depositing both tokens, returns the amount of LP tokens minted. +Adds liquidity by depositing proportional amounts of both tokens. Returns a tuple containing the amounts of token A (dx), token B (dy), and LP tokens minted (dk). ### Remove Liquidity ```clarity (remove-liquidity ( - (lp-token-amount uint) - (memo (optional (buff 34))) + (amount uint) + (opcode (optional (buff 16))) ) - (response (tuple (token-a uint) (token-b uint)) uint)) + (response + (tuple (dx uint) (dy uint) (dk uint)) + uint)) ``` -Burns LP tokens and returns both underlying tokens. +Burns LP tokens and returns both underlying tokens. The tuple contains the amounts of token A (dx), token B (dy), and LP tokens burned (dk). ### Swap ```clarity (swap ( - (token-in ) - (amount-in uint) - (memo (optional (buff 34))) + (amount uint) + (opcode (optional (buff 16))) ) (response uint uint)) ``` -Swaps one token for the other. The output token is implictly determined by the pool token being passed in and/or if an optional memo is provided. +Swaps one token for another. The direction of the swap is determined by the first byte of the opcode buffer (0x00 for token A input, 0x01 for token B input). ## Quote Functions @@ -97,12 +100,11 @@ Swaps one token for the other. The output token is implictly determined by the p ```clarity (get-add-liquidity-quote ( - (token-a-amount uint) - (token-b-amount uint) - (memo (optional (buff 34))) + (amount uint) + (opcode (optional (buff 16))) ) (response - (tuple (token-a uint) (token-b uint) (lp-tokens uint)) + (tuple (dx uint) (dy uint) (dk uint)) uint)) ``` @@ -113,11 +115,11 @@ Returns expected amounts for adding liquidity. ```clarity (get-remove-liquidity-quote ( - (lp-token-amount uint) - (memo (optional (buff 34))) + (amount uint) + (opcode (optional (buff 16))) ) (response - (tuple (token-a uint) (token-b uint) (lp-tokens uint)) + (tuple (dx uint) (dy uint) (dk uint)) uint)) ``` @@ -128,29 +130,17 @@ Returns expected amounts for removing liquidity. ```clarity (get-swap-quote ( - (token-in ) - (amount-in uint) - (memo (optional (buff 34))) + (amount uint) + (opcode (optional (buff 16))) ) - (response (tuple (token-in uint) (token-out uint)) uint)) + (response + (tuple (dx uint) (dy uint)) + uint)) ``` Returns expected amounts for a swap. -## Pool Information -```clarity -(get-pool-info () - (response - (tuple - (token-a (tuple (contract principal) (identifier (string-ascii 32)) (reserve uint))) - (token-b (tuple (contract principal) (identifier (string-ascii 32)) (reserve uint))) - (lp-token (tuple (contract principal) (identifier (string-ascii 32)) (supply uint))) - ) - uint)) -``` - -Returns comprehensive pool information including token contracts, identifiers, reserves and supply. ## Trait Implementation @@ -158,65 +148,274 @@ Returns comprehensive pool information including token contracts, identifiers, r (define-trait liquidity-pool-trait ( ;; Liquidity Operations - (add-liquidity (uint uint (optional (buff 34))) (response uint uint)) - (remove-liquidity (uint (optional (buff 34))) - (response (tuple (token-a uint) (token-b uint)) uint)) + (add-liquidity (uint (optional (buff 16))) + (response (tuple (dx uint) (dy uint) (dk uint)) uint)) + (remove-liquidity (uint (optional (buff 16))) + (response (tuple (dx uint) (dy uint) (dk uint)) uint)) ;; Swap Operations - (swap ( uint (optional (buff 34))) (response uint uint)) + (swap (uint (optional (buff 16))) (response uint uint)) ;; Quotes - (get-add-liquidity-quote (uint uint (optional (buff 34))) - (response (tuple (token-a uint) (token-b uint) (lp-tokens uint)) uint)) - (get-remove-liquidity-quote (uint (optional (buff 34))) - (response (tuple (token-a uint) (token-b uint) (lp-tokens uint)) uint)) - (get-swap-quote ( uint (optional (buff 34))) - (response (tuple (token-in uint) (token-out uint)) uint)) + (get-add-liquidity-quote (uint (optional (buff 16))) + (response (tuple (dx uint) (dy uint) (dk uint)) uint)) + (get-remove-liquidity-quote (uint (optional (buff 16))) + (response (tuple (dx uint) (dy uint) (dk uint)) uint)) + (get-swap-quote (uint (optional (buff 16))) + (response (tuple (dx uint) (dy uint)) uint)) - ;; Pool Information - (get-pool-info () - (response - (tuple - (token-a (tuple (contract principal) (identifier (string-ascii 32)) (reserve uint))) - (token-b (tuple (contract principal) (identifier (string-ascii 32)) (reserve uint))) - (lp-token (tuple (contract principal) (identifier (string-ascii 32)) (supply uint))) - ) - uint)) ) ) ``` # Implementation Guidelines +## AMM Design Flexibility +- Implementations may use any pricing formula or AMM design +- Quote functions must accurately reflect the actual behavior of the pool +- Pool behavior can be modified through opcode parameters + +## Fee Structure +- Fees and rebates can be implemented freely +- Quote functions must accurately reflect all fees and rebates +- Fee behavior can be modified through opcode parameters + +## Liquidity Operations +- Default behavior for add-liquidity should be documented +- Opcode parameters can modify liquidity allocation +- Support for single-sided, imbalanced, and oracle-weighted deposits + ## Post Conditions -All slippage protection must be implemented using post conditions rather than explicit parameters. Implementations should set appropriate post conditions for: -- Minimum LP tokens when adding liquidity -- Minimum output tokens when removing liquidity -- Minimum output tokens when swapping +- All slippage protection must be implemented using post conditions +- Post conditions should account for any opcode-modified behavior -## Memo Support -- Pools may support advanced operations through memo buffers -- Memo command documentation is out of scope for this SIP -- Memo parsing should be robust and fail gracefully +## Opcode Buffer Implementation +- Must handle missing or partial opcode buffers gracefully +- Unknown opcodes should be ignored +- Default behavior must be clearly documented +- All opcode-modified behaviors must be reflected in quotes # Applications ## Swap Aggregators Aggregators implementing this standard should: -1. Query pool info to discover token pairs +1. Query pool info to discover token pairs and reserves 2. Use quote functions to calculate optimal routes 3. Set appropriate post conditions for slippage protection +4. Properly construct opcode buffers for complex operations ## Direct Integration Applications directly integrating with pools should: 1. Verify pool and token contracts implement required traits 2. Use get-pool-info to fetch current state 3. Get quotes before executing operations -4. Set appropriate post conditions +4. Handle opcode buffer construction appropriately # Reference Implementation -[Link to reference implementation repository] +[Link to reference implementation repository](https://explorer.hiro.so/txid/SP2ZNGJ85ENDY6QRHQ5P2D4FXKGZWCKTB2T0Z55KS.dexterity-token?chain=mainnet) + +# OPCODE Buffer Specification + +The OPCODE buffer is a powerful 16-byte buffer that enables advanced pool operations through compact parameter encoding. This section provides detailed documentation for implementing and using the OPCODE system. + +## OPCODE Table + +| Byte Position | Bit Position | Section | Status | Function | Values | Description | +|--------------|--------------|---------|---------|-----------|---------|-------------| +| 0 | 0-1 | 1.1 | Implemented | Token Direction | 0x00: Token A input (default) | Controls swap direction | +| | | | | | 0x01: Token B input | | +| | 2-7 | - | Reserved | - | - | Reserved for future use | +| 1 | 0-7 | 2.1 | Proposed | Swap Type | 0x00: Exact input (default) | Controls swap execution | +| | | | | | 0x01: Exact output | | +| | | | | | 0x02-0xFF: Reserved | | +| 2 | 0-7 | 2.2 | Proposed | Fee Control | 0x00: Default fees | Modifies fee behavior | +| | | | | | 0x01: Reduced fees | | +| | | | | | 0x02: Dynamic fees | | +| | | | | | 0x03: Oracle fees | | +| 3 | 0-7 | 2.3 | Proposed | Liquidity | 0x00: Balanced (default) | Controls liquidity addition | +| | | | | | 0x01: Single-sided A | | +| | | | | | 0x02: Single-sided B | | +| | | | | | 0x03: Oracle-weighted | | +| 4-7 | 0-31 | 2.4 | Proposed | Oracle | Various | Price oracle integration | +| 8-11 | 0-31 | 2.5 | Proposed | Routing | Various | Route optimization | +| 12-13 | 0-15 | 2.6 | Proposed | Concentrated | Various | Concentrated liquidity | +| 14-15 | 0-15 | 2.7 | Proposed | Limit Orders | Various | Limit order parameters | + +## Table of Contents + +1. Implemented Operations + 1. Token Direction (Byte 0, Bits 0-1) + +2. Proposed Operations + 1. Swap Type (Byte 1) + 2. Fee Control (Byte 2) + 3. Liquidity Addition (Byte 3) + 4. Oracle Integration (Bytes 4-7) + 5. Route Optimization (Bytes 8-11) + 6. Concentrated Liquidity (Bytes 12-13) + 7. Limit Orders (Bytes 14-15) + +3. Future Extensions + 1. Flash Loans + 2. Yield Farming + 3. Governance + 4. MEV Protection + +## Buffer Structure +The buffer consists of 16 bytes (128 bits) that can encode various parameters and flags to modify pool behavior. Each section below details the specific byte ranges and their purposes. + +## 1. Implemented Operations + +### 1.1 Token Direction (Byte 0, Bits 0-1) +Controls the direction of token flow in swap operations. + +Values: +- 0x00: Token A is input token (default) +- 0x01: Token B is input token + +Implementation Notes: +- Must be checked first in swap operations +- Affects quote calculations +- Remaining bits (2-7) reserved for future use + +## 2. Theoretical Operations + +### 2.1 Swap Type (Byte 1) +Controls exact input vs exact output behavior + +Possible Values: +- 0x00: Exact input amount (default) +- 0x01: Exact output amount +- 0x02-0xFF: Reserved for future swap types + +Implementation Notes: +- Affects quote calculation methodology +- Must be considered in slippage calculations +- Can be combined with fee modifications + +### 2.2 Fee Modification (Byte 2) +Enables dynamic fee structures and custom rebate models + +Possible Values: +- 0x00: Default pool fees +- 0x01: Reduced fees with utility token burn +- 0x02: Dynamic fees based on pool imbalance +- 0x03: Oracle-based fees +- 0x04-0xFF: Reserved for future fee models + +Implementation Notes: +- Can modify both swap fees and LP rewards +- Could interact with governance systems +- Must be reflected in quote calculations + +### 2.3 Liquidity Addition Control (Byte 3) +Enables advanced liquidity provision strategies + +Possible Values: +- 0x00: Balanced deposit (default) +- 0x01: Single-sided Token A +- 0x02: Single-sided Token B +- 0x03: Oracle-weighted deposit +- 0x04: Imbalanced custom ratio +- 0x05-0xFF: Reserved for future strategies + +Implementation Notes: +- Affects add-liquidity behavior +- Must update pool balances correctly +- Should consider price impact + +### 2.4 Oracle Integration (Bytes 4-7) +Enables price oracle integration and TWAP calculations + +Byte Structure: +- Bytes 4-5: Oracle parameters +- Bytes 6-7: Time window + +Implementation Notes: +- Can be used for price feeds +- Enables advanced pricing models +- Supports external oracle integration + +### 2.5 Route Optimization (Bytes 8-11) +Enables advanced routing and arbitrage features + +Byte Structure: +- Byte 8: Route flags +- Bytes 9-11: Route parameters + +Implementation Notes: +- Supports multi-hop operations +- Enables atomic arbitrage +- Can specify route preferences + +### 2.6 Concentrated Liquidity (Bytes 12-13) +Enables Uniswap V3 style concentrated liquidity + +Byte Structure: +- Byte 12: Tick spacing and range +- Byte 13: Position parameters + +Implementation Notes: +- Defines liquidity ranges +- Supports multiple positions +- Enables fee tier selection + +### 2.7 Limit Orders (Bytes 14-15) +Enables limit order functionality + +Byte Structure: +- Byte 14: Order type and flags +- Byte 15: Time parameters + +Implementation Notes: +- Supports price limits +- Enables time-based execution +- Can implement stop-loss orders + +## 3. Future Extension Possibilities + +### 3.1 Flash Loans +- Loan amount encoding +- Collateral requirements +- Repayment terms + +### 3.2 Yield Farming +- Boost multipliers +- Program participation +- Reward distribution + +### 3.3 Governance +- Voting weight calculation +- Parameter updates +- Protocol integration + +### 3.4 MEV Protection +- Transaction ordering +- Sandwich protection +- Front-running mitigation + +## Developer Guidelines + +### Error Handling +- Invalid opcodes should not cause failures +- Unknown values should use defaults +- Partial buffers must be supported + +### Testing +- Test all opcode combinations +- Verify quote accuracy +- Validate state transitions + +### Documentation +- Document all supported opcodes +- Provide usage examples +- Keep modification history + +### Security Considerations +- Validate all parameters +- Check state transitions +- Prevent value extraction # Activation From 7cd9f38c12d73d53bb28fbc03bd18b6c32cceb20 Mon Sep 17 00:00:00 2001 From: Ross Ragsdale Date: Thu, 12 Dec 2024 20:03:00 -0600 Subject: [PATCH 3/5] Update README.md Minor updates to introduction text. --- sips/sip-03X/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sips/sip-03X/README.md b/sips/sip-03X/README.md index 9eeb642f..0cc96053 100644 --- a/sips/sip-03X/README.md +++ b/sips/sip-03X/README.md @@ -39,12 +39,12 @@ Liquidity pools are a fundamental component of decentralized finance, enabling a 3. Swapping one token for the other 4. Querying pool state and quotes -The standard introduces an opcode buffer system that enables advanced pool operations while maintaining backward compatibility. This allows for future extensions such as concentrated liquidity, flash loans, and advanced routing without requiring interface changes. By standardizing the interface for liquidity pools, we enable: +The standard introduces an opcode buffer system that enables advanced pool operations while maintaining backward compatibility. This allows for future extensions such as oracles, concentrated liquidity, limit orders, and advanced routing without requiring interface changes. By standardizing the interface for liquidity pools, we enable: - Consistent interaction patterns across different implementations - Development of swap aggregators and routing engines - Common tooling and integration patterns -- Future extensibility through memo commands +- Future extensibility through optional opcodes # Specification From 0606900e50b8dd949c8a57561e58f99a8cef84b5 Mon Sep 17 00:00:00 2001 From: "rozar.btc" Date: Tue, 17 Dec 2024 21:24:44 -0600 Subject: [PATCH 4/5] Update README.md --- sips/sip-03X/README.md | 453 +++++++++++------------------------------ 1 file changed, 123 insertions(+), 330 deletions(-) diff --git a/sips/sip-03X/README.md b/sips/sip-03X/README.md index 0cc96053..32d7293b 100644 --- a/sips/sip-03X/README.md +++ b/sips/sip-03X/README.md @@ -24,7 +24,7 @@ Discussions-To: [URL] # Abstract -This SIP defines a standard trait interface for liquidity pools on the Stacks blockchain. The standard enables independent implementation of liquidity pools while maintaining a unified interface, facilitating the development of swap aggregators and multi-hop transactions across multiple pools. The standard introduces an extensible opcode buffer system for advanced pool operations. +This SIP defines a minimalist trait interface for liquidity pools on the Stacks blockchain. The standard enables independent implementation of liquidity pools while maintaining a unified interface, facilitating the development of swap aggregators and multi-hop transactions across multiple pools. The standard introduces an extensible opcode buffer system that enables advanced pool operations while maintaining a simple core interface. # License and Copyright @@ -32,14 +32,14 @@ This SIP is made available under the terms of the Creative Commons CC0 1.0 Unive # Introduction -Liquidity pools are a fundamental component of decentralized finance, enabling automated market making and token swapping capabilities. Each pool manages a pair of SIP-010 fungible tokens and provides functionality for: +Liquidity pools are a fundamental component of decentralized finance, enabling automated market making and token swapping capabilities. Each pool manages a pair of SIP-010 fungible tokens and mints LP tokens to track liquidity provider shares. The core operations include: -1. Adding liquidity by depositing both tokens -2. Removing liquidity by burning LP tokens -3. Swapping one token for the other +1. Adding liquidity (deposit both tokens) +2. Removing liquidity (burn LP tokens) +3. Swapping one token for another 4. Querying pool state and quotes -The standard introduces an opcode buffer system that enables advanced pool operations while maintaining backward compatibility. This allows for future extensions such as oracles, concentrated liquidity, limit orders, and advanced routing without requiring interface changes. By standardizing the interface for liquidity pools, we enable: +This standard introduces a unified execute/quote interface with an opcode buffer system that enables advanced pool operations while maintaining backward compatibility. This allows for: - Consistent interaction patterns across different implementations - Development of swap aggregators and routing engines @@ -48,374 +48,165 @@ The standard introduces an opcode buffer system that enables advanced pool opera # Specification -## Core Functions - -### Add Liquidity +## Core Interface ```clarity -(add-liquidity +(define-trait liquidity-pool-trait ( - (amount uint) - (opcode (optional (buff 16))) - ) - (response - (tuple (dx uint) (dy uint) (dk uint)) - uint)) + (execute + (uint (optional (buff 16))) + (response (tuple (dx uint) (dy uint) (dk uint)) uint)) + (quote + (uint (optional (buff 16))) + (response (tuple (dx uint) (dy uint) (dk uint)) uint)) + ) +) ``` -Adds liquidity by depositing proportional amounts of both tokens. Returns a tuple containing the amounts of token A (dx), token B (dy), and LP tokens minted (dk). - -### Remove Liquidity +### Execute Function ```clarity -(remove-liquidity - ( - (amount uint) - (opcode (optional (buff 16))) - ) - (response - (tuple (dx uint) (dy uint) (dk uint)) - uint)) +(execute (amount uint) (opcode (optional (buff 16)))) ``` -Burns LP tokens and returns both underlying tokens. The tuple contains the amounts of token A (dx), token B (dy), and LP tokens burned (dk). +The execute function performs all pool operations based on the opcode provided: + +- Amount: The primary input amount (interpretation depends on operation) +- Opcode: Optional 16-byte buffer encoding operation parameters +- Returns: Tuple containing amounts (dx, dy, dk) representing: + - dx: Token A amount + - dy: Token B amount + - dk: LP token amount -### Swap +### Quote Function ```clarity -(swap - ( - (amount uint) - (opcode (optional (buff 16))) - ) - (response uint uint)) +(quote (amount uint) (opcode (optional (buff 16)))) ``` -Swaps one token for another. The direction of the swap is determined by the first byte of the opcode buffer (0x00 for token A input, 0x01 for token B input). +The quote function provides expected outputs for operations without execution: -## Quote Functions +- Amount: The primary input amount to quote +- Opcode: Same opcode buffer that would be used in execute +- Returns: Same tuple format as execute -### Add Liquidity Quote +## OPCODE Specification -```clarity -(get-add-liquidity-quote - ( - (amount uint) - (opcode (optional (buff 16))) - ) - (response - (tuple (dx uint) (dy uint) (dk uint)) - uint)) -``` +The first byte of the opcode buffer determines the core operation: -Returns expected amounts for adding liquidity. +| Value | Operation | Description | +|-------|-----------|-------------| +| 0x00 | SWAP_A_TO_B | Swap token A for token B | +| 0x01 | SWAP_B_TO_A | Swap token B for token A | +| 0x02 | ADD_LIQUIDITY | Add liquidity to pool | +| 0x03 | REMOVE_LIQUIDITY | Remove liquidity from pool | -### Remove Liquidity Quote +### Operation Details -```clarity -(get-remove-liquidity-quote - ( - (amount uint) - (opcode (optional (buff 16))) - ) - (response - (tuple (dx uint) (dy uint) (dk uint)) - uint)) -``` +#### Swap Operations (0x00, 0x01) +- Amount represents input token quantity +- dx/dy represent input/output amounts +- dk is unused (zero) -Returns expected amounts for removing liquidity. +#### Add Liquidity (0x02) +- Amount represents desired LP tokens +- dx/dy represent token deposits required +- dk represents LP tokens minted -### Swap Quote +#### Remove Liquidity (0x03) +- Amount represents LP tokens to burn +- dx/dy represent tokens returned +- dk represents LP tokens burned -```clarity -(get-swap-quote - ( - (amount uint) - (opcode (optional (buff 16))) - ) - (response - (tuple (dx uint) (dy uint)) - uint)) -``` +## Implementation Guidelines -Returns expected amounts for a swap. +### Core Requirements +1. Must implement both execute and quote functions +2. Must handle missing/empty opcode buffer gracefully +3. Must return consistent tuple format for all operations +4. Must implement SIP-010 trait for LP token +5. Quote must accurately reflect execute behavior +### Security Considerations -## Trait Implementation +1. Post conditions must be used for slippage protection +2. All state changes must occur atomically +3. Rounding must favor the pool +4. Operation validation must occur before state changes -```clarity -(define-trait liquidity-pool-trait - ( - ;; Liquidity Operations - (add-liquidity (uint (optional (buff 16))) - (response (tuple (dx uint) (dy uint) (dk uint)) uint)) - (remove-liquidity (uint (optional (buff 16))) - (response (tuple (dx uint) (dy uint) (dk uint)) uint)) - - ;; Swap Operations - (swap (uint (optional (buff 16))) (response uint uint)) - - ;; Quotes - (get-add-liquidity-quote (uint (optional (buff 16))) - (response (tuple (dx uint) (dy uint) (dk uint)) uint)) - (get-remove-liquidity-quote (uint (optional (buff 16))) - (response (tuple (dx uint) (dy uint) (dk uint)) uint)) - (get-swap-quote (uint (optional (buff 16))) - (response (tuple (dx uint) (dy uint)) uint)) - - ) -) -``` +### Best Practices + +1. Document default behavior without opcodes +2. Use descriptive error codes +3. Validate parameter ranges +4. Include clear logging/events +5. Document fee structures -# Implementation Guidelines +## Multi-Hop Router Integration -## AMM Design Flexibility -- Implementations may use any pricing formula or AMM design -- Quote functions must accurately reflect the actual behavior of the pool -- Pool behavior can be modified through opcode parameters +The standard enables efficient path execution through a router contract that can: -## Fee Structure -- Fees and rebates can be implemented freely -- Quote functions must accurately reflect all fees and rebates -- Fee behavior can be modified through opcode parameters +1. Chain multiple pool operations +2. Support routes up to 9 hops +3. Automatically propagate output amounts +4. Maintain consistent slippage protection -## Liquidity Operations -- Default behavior for add-liquidity should be documented -- Opcode parameters can modify liquidity allocation -- Support for single-sided, imbalanced, and oracle-weighted deposits +Example router functions: -## Post Conditions -- All slippage protection must be implemented using post conditions -- Post conditions should account for any opcode-modified behavior +```clarity +;; Single hop swap +(define-public (swap-1 + (amount uint) + (hop-1 {pool: , opcode: (optional (buff 16))})) + (let ((result (try! (execute-swap amount hop-1)))) + (ok (list result)))) -## Opcode Buffer Implementation -- Must handle missing or partial opcode buffers gracefully -- Unknown opcodes should be ignored -- Default behavior must be clearly documented -- All opcode-modified behaviors must be reflected in quotes +;; Multi-hop swap +(define-public (swap-2 + (amount uint) + (hop-1 {pool: , opcode: (optional (buff 16))}) + (hop-2 {pool: , opcode: (optional (buff 16))})) + (let ( + (result-1 (try! (execute-swap amount hop-1))) + (result-2 (try! (execute-swap (get dy result-1) hop-2)))) + (ok (list result-1 result-2)))) +``` # Applications ## Swap Aggregators -Aggregators implementing this standard should: -1. Query pool info to discover token pairs and reserves -2. Use quote functions to calculate optimal routes -3. Set appropriate post conditions for slippage protection -4. Properly construct opcode buffers for complex operations +Aggregators implementing this standard can: +1. Query pools implementing the trait +2. Calculate optimal routes +3. Execute atomic multi-hop swaps +4. Provide accurate quotes ## Direct Integration -Applications directly integrating with pools should: -1. Verify pool and token contracts implement required traits -2. Use get-pool-info to fetch current state -3. Get quotes before executing operations -4. Handle opcode buffer construction appropriately +Applications directly integrating should: +1. Verify trait implementation +2. Get quotes before execution +3. Set appropriate post conditions +4. Handle operation failures gracefully # Reference Implementation -[Link to reference implementation repository](https://explorer.hiro.so/txid/SP2ZNGJ85ENDY6QRHQ5P2D4FXKGZWCKTB2T0Z55KS.dexterity-token?chain=mainnet) - -# OPCODE Buffer Specification - -The OPCODE buffer is a powerful 16-byte buffer that enables advanced pool operations through compact parameter encoding. This section provides detailed documentation for implementing and using the OPCODE system. - -## OPCODE Table - -| Byte Position | Bit Position | Section | Status | Function | Values | Description | -|--------------|--------------|---------|---------|-----------|---------|-------------| -| 0 | 0-1 | 1.1 | Implemented | Token Direction | 0x00: Token A input (default) | Controls swap direction | -| | | | | | 0x01: Token B input | | -| | 2-7 | - | Reserved | - | - | Reserved for future use | -| 1 | 0-7 | 2.1 | Proposed | Swap Type | 0x00: Exact input (default) | Controls swap execution | -| | | | | | 0x01: Exact output | | -| | | | | | 0x02-0xFF: Reserved | | -| 2 | 0-7 | 2.2 | Proposed | Fee Control | 0x00: Default fees | Modifies fee behavior | -| | | | | | 0x01: Reduced fees | | -| | | | | | 0x02: Dynamic fees | | -| | | | | | 0x03: Oracle fees | | -| 3 | 0-7 | 2.3 | Proposed | Liquidity | 0x00: Balanced (default) | Controls liquidity addition | -| | | | | | 0x01: Single-sided A | | -| | | | | | 0x02: Single-sided B | | -| | | | | | 0x03: Oracle-weighted | | -| 4-7 | 0-31 | 2.4 | Proposed | Oracle | Various | Price oracle integration | -| 8-11 | 0-31 | 2.5 | Proposed | Routing | Various | Route optimization | -| 12-13 | 0-15 | 2.6 | Proposed | Concentrated | Various | Concentrated liquidity | -| 14-15 | 0-15 | 2.7 | Proposed | Limit Orders | Various | Limit order parameters | - -## Table of Contents - -1. Implemented Operations - 1. Token Direction (Byte 0, Bits 0-1) - -2. Proposed Operations - 1. Swap Type (Byte 1) - 2. Fee Control (Byte 2) - 3. Liquidity Addition (Byte 3) - 4. Oracle Integration (Bytes 4-7) - 5. Route Optimization (Bytes 8-11) - 6. Concentrated Liquidity (Bytes 12-13) - 7. Limit Orders (Bytes 14-15) - -3. Future Extensions - 1. Flash Loans - 2. Yield Farming - 3. Governance - 4. MEV Protection - -## Buffer Structure -The buffer consists of 16 bytes (128 bits) that can encode various parameters and flags to modify pool behavior. Each section below details the specific byte ranges and their purposes. - -## 1. Implemented Operations - -### 1.1 Token Direction (Byte 0, Bits 0-1) -Controls the direction of token flow in swap operations. - -Values: -- 0x00: Token A is input token (default) -- 0x01: Token B is input token - -Implementation Notes: -- Must be checked first in swap operations -- Affects quote calculations -- Remaining bits (2-7) reserved for future use - -## 2. Theoretical Operations - -### 2.1 Swap Type (Byte 1) -Controls exact input vs exact output behavior - -Possible Values: -- 0x00: Exact input amount (default) -- 0x01: Exact output amount -- 0x02-0xFF: Reserved for future swap types - -Implementation Notes: -- Affects quote calculation methodology -- Must be considered in slippage calculations -- Can be combined with fee modifications - -### 2.2 Fee Modification (Byte 2) -Enables dynamic fee structures and custom rebate models - -Possible Values: -- 0x00: Default pool fees -- 0x01: Reduced fees with utility token burn -- 0x02: Dynamic fees based on pool imbalance -- 0x03: Oracle-based fees -- 0x04-0xFF: Reserved for future fee models - -Implementation Notes: -- Can modify both swap fees and LP rewards -- Could interact with governance systems -- Must be reflected in quote calculations - -### 2.3 Liquidity Addition Control (Byte 3) -Enables advanced liquidity provision strategies - -Possible Values: -- 0x00: Balanced deposit (default) -- 0x01: Single-sided Token A -- 0x02: Single-sided Token B -- 0x03: Oracle-weighted deposit -- 0x04: Imbalanced custom ratio -- 0x05-0xFF: Reserved for future strategies - -Implementation Notes: -- Affects add-liquidity behavior -- Must update pool balances correctly -- Should consider price impact - -### 2.4 Oracle Integration (Bytes 4-7) -Enables price oracle integration and TWAP calculations - -Byte Structure: -- Bytes 4-5: Oracle parameters -- Bytes 6-7: Time window - -Implementation Notes: -- Can be used for price feeds -- Enables advanced pricing models -- Supports external oracle integration - -### 2.5 Route Optimization (Bytes 8-11) -Enables advanced routing and arbitrage features - -Byte Structure: -- Byte 8: Route flags -- Bytes 9-11: Route parameters - -Implementation Notes: -- Supports multi-hop operations -- Enables atomic arbitrage -- Can specify route preferences - -### 2.6 Concentrated Liquidity (Bytes 12-13) -Enables Uniswap V3 style concentrated liquidity - -Byte Structure: -- Byte 12: Tick spacing and range -- Byte 13: Position parameters - -Implementation Notes: -- Defines liquidity ranges -- Supports multiple positions -- Enables fee tier selection - -### 2.7 Limit Orders (Bytes 14-15) -Enables limit order functionality - -Byte Structure: -- Byte 14: Order type and flags -- Byte 15: Time parameters - -Implementation Notes: -- Supports price limits -- Enables time-based execution -- Can implement stop-loss orders - -## 3. Future Extension Possibilities - -### 3.1 Flash Loans -- Loan amount encoding -- Collateral requirements -- Repayment terms - -### 3.2 Yield Farming -- Boost multipliers -- Program participation -- Reward distribution - -### 3.3 Governance -- Voting weight calculation -- Parameter updates -- Protocol integration - -### 3.4 MEV Protection -- Transaction ordering -- Sandwich protection -- Front-running mitigation - -## Developer Guidelines - -### Error Handling -- Invalid opcodes should not cause failures -- Unknown values should use defaults -- Partial buffers must be supported - -### Testing -- Test all opcode combinations -- Verify quote accuracy -- Validate state transitions - -### Documentation -- Document all supported opcodes -- Provide usage examples -- Keep modification history +A reference implementation demonstrating all core functionality is available at: +[Link to reference implementation](https://explorer.hiro.so/txid/SP2ZNGJ85ENDY6QRHQ5P2D4FXKGZWCKTB2T0Z55KS.dexterity-token?chain=mainnet) -### Security Considerations -- Validate all parameters -- Check state transitions -- Prevent value extraction +It includes: +- Core pool implementation +- Multi-hop router +- Example integrations + +# Future Extensions + +The opcode buffer system enables future extensions without interface changes: + +1. Oracle Integration (Bytes 4-7) +2. Advanced Routing (Bytes 8-11) +3. Concentrated Liquidity (Bytes 12-13) +4. Limit Orders (Bytes 14-15) # Activation @@ -423,3 +214,5 @@ This SIP will be considered activated when: 1. The trait is deployed to mainnet 2. At least 3 different implementations are deployed 3. A functional swap aggregator demonstrates multi-hop capabilities + +The trait and router designs have been battle-tested in production, with live implementations handling significant trading volume. This provides confidence in the interface design and its ability to support a robust DeFi ecosystem. From f7b055156cc406adb6509536899a20bca487c96f Mon Sep 17 00:00:00 2001 From: "rozar.btc" Date: Tue, 24 Dec 2024 01:43:46 -0600 Subject: [PATCH 5/5] Update README.md --- sips/sip-03X/README.md | 188 +++++++++++++++++++++++------------------ 1 file changed, 104 insertions(+), 84 deletions(-) diff --git a/sips/sip-03X/README.md b/sips/sip-03X/README.md index 32d7293b..29333ed3 100644 --- a/sips/sip-03X/README.md +++ b/sips/sip-03X/README.md @@ -12,7 +12,7 @@ Type: Standard Status: Draft -Created: 10 December 2024 +Created: 24 December 2024 License: CC0-1.0 @@ -74,9 +74,9 @@ The execute function performs all pool operations based on the opcode provided: - Amount: The primary input amount (interpretation depends on operation) - Opcode: Optional 16-byte buffer encoding operation parameters - Returns: Tuple containing amounts (dx, dy, dk) representing: - - dx: Token A amount - - dy: Token B amount - - dk: LP token amount + - dx: Token A amount consumed + - dy: Token B amount produced + - dk: LP token amount minted/burned ### Quote Function @@ -92,127 +92,147 @@ The quote function provides expected outputs for operations without execution: ## OPCODE Specification -The first byte of the opcode buffer determines the core operation: +The opcode buffer is structured as follows: -| Value | Operation | Description | -|-------|-----------|-------------| -| 0x00 | SWAP_A_TO_B | Swap token A for token B | -| 0x01 | SWAP_B_TO_A | Swap token B for token A | -| 0x02 | ADD_LIQUIDITY | Add liquidity to pool | -| 0x03 | REMOVE_LIQUIDITY | Remove liquidity from pool | +| Byte Position | Description | +|---------------|-------------| +| 0 | Operation Type | +| 1 | Swap Type | +| 2 | Fee Type | +| 3 | Liquidity Type | +| 4-15 | Reserved for future use | -### Operation Details +### Operation Types (Byte 0) -#### Swap Operations (0x00, 0x01) -- Amount represents input token quantity -- dx/dy represent input/output amounts +```clarity +(define-constant OP_SWAP_A_TO_B 0x00) ;; Swap token A for B +(define-constant OP_SWAP_B_TO_A 0x01) ;; Swap token B for A +(define-constant OP_ADD_LIQUIDITY 0x02) ;; Add liquidity +(define-constant OP_REMOVE_LIQUIDITY 0x03) ;; Remove liquidity +``` + +### Swap Types (Byte 1) + +```clarity +(define-constant SWAP_EXACT_INPUT 0x00) ;; Exact input amount +(define-constant SWAP_EXACT_OUTPUT 0x01) ;; Exact output amount +``` + +### Fee Types (Byte 2) + +```clarity +(define-constant FEE_REDUCE_INPUT 0x00) ;; Fee reduces input amount +(define-constant FEE_REDUCE_OUTPUT 0x01) ;; Fee reduces output amount +(define-constant FEE_BURN_ENERGY 0x02) ;; Fee burns protocol token +``` + +### Liquidity Types (Byte 3) + +```clarity +(define-constant LIQUIDITY_BALANCED 0x00) ;; Balanced liquidity add/remove +``` + +## Operation Details + +### Swap Operations (0x00, 0x01) +- Amount represents exact input token quantity +- dx represents input amount after fees +- dy represents output amount - dk is unused (zero) +- Fee calculation determined by byte 2 (FEE_TYPE) -#### Add Liquidity (0x02) +### Add Liquidity (0x02) - Amount represents desired LP tokens - dx/dy represent token deposits required -- dk represents LP tokens minted +- dk represents actual LP tokens minted +- Liquidity type in byte 3 determines ratio calculation -#### Remove Liquidity (0x03) +### Remove Liquidity (0x03) - Amount represents LP tokens to burn - dx/dy represent tokens returned - dk represents LP tokens burned +- Liquidity type in byte 3 determines withdrawal strategy ## Implementation Guidelines ### Core Requirements -1. Must implement both execute and quote functions -2. Must handle missing/empty opcode buffer gracefully -3. Must return consistent tuple format for all operations -4. Must implement SIP-010 trait for LP token -5. Quote must accurately reflect execute behavior +1. Must implement both execute and quote functions exactly as specified +2. Must handle missing/empty opcode by defaulting to SWAP_A_TO_B with FEE_REDUCE_INPUT +3. Must implement SIP-010 trait for LP token +4. Quote must accurately predict execute behavior +5. Must use consistent precision (6 decimals recommended) ### Security Considerations -1. Post conditions must be used for slippage protection +1. Must implement comprehensive post conditions 2. All state changes must occur atomically -3. Rounding must favor the pool -4. Operation validation must occur before state changes - -### Best Practices - -1. Document default behavior without opcodes -2. Use descriptive error codes -3. Validate parameter ranges -4. Include clear logging/events -5. Document fee structures +3. Rounding must favor the pool (floor for outputs) +4. Must validate opcode format before execution +5. Must implement proper principal checks ## Multi-Hop Router Integration -The standard enables efficient path execution through a router contract that can: - -1. Chain multiple pool operations -2. Support routes up to 9 hops -3. Automatically propagate output amounts -4. Maintain consistent slippage protection - -Example router functions: +The standard enables path execution through a router contract with functions for 1-9 hops: ```clarity -;; Single hop swap +;; Router function type pattern +(define-public (swap-{n} + (amount uint) + (hop-1 {pool: , opcode: (optional (buff 16))}) + ... + (hop-n {pool: , opcode: (optional (buff 16))})) + (response (list 9 {dx: uint, dy: uint, dk: uint}) uint)) + +;; Example single-hop implementation (define-public (swap-1 (amount uint) (hop-1 {pool: , opcode: (optional (buff 16))})) - (let ((result (try! (execute-swap amount hop-1)))) - (ok (list result)))) - -;; Multi-hop swap -(define-public (swap-2 - (amount uint) - (hop-1 {pool: , opcode: (optional (buff 16))}) - (hop-2 {pool: , opcode: (optional (buff 16))})) (let ( - (result-1 (try! (execute-swap amount hop-1))) - (result-2 (try! (execute-swap (get dy result-1) hop-2)))) - (ok (list result-1 result-2)))) + (pool (get pool hop-1)) + (opcode (get opcode hop-1)) + (result (try! (contract-call? pool execute amount opcode)))) + (ok (list result)))) ``` -# Applications - -## Swap Aggregators -Aggregators implementing this standard can: -1. Query pools implementing the trait -2. Calculate optimal routes -3. Execute atomic multi-hop swaps -4. Provide accurate quotes - -## Direct Integration -Applications directly integrating should: -1. Verify trait implementation -2. Get quotes before execution -3. Set appropriate post conditions -4. Handle operation failures gracefully - # Reference Implementation -A reference implementation demonstrating all core functionality is available at: -[Link to reference implementation](https://explorer.hiro.so/txid/SP2ZNGJ85ENDY6QRHQ5P2D4FXKGZWCKTB2T0Z55KS.dexterity-token?chain=mainnet) +A reference implementation demonstrating all core functionality is available in the Dexterity Protocol: + +Contract: [SP2ZNGJ85ENDY6QRHQ5P2D4FXKGZWCKTB2T0Z55KS.dexterity-traits-v0] +SDK: [https://github.com/dexterity/sdk] -It includes: -- Core pool implementation -- Multi-hop router -- Example integrations +The implementation includes: +- Core pool implementation with full opcode support +- Multi-hop router supporting up to 5 hops +- TypeScript SDK for integration +- Comprehensive test suite # Future Extensions -The opcode buffer system enables future extensions without interface changes: +The opcode buffer system enables future extensions through reserved bytes: 1. Oracle Integration (Bytes 4-7) -2. Advanced Routing (Bytes 8-11) -3. Concentrated Liquidity (Bytes 12-13) -4. Limit Orders (Bytes 14-15) + - Price feed integration + - TWAP calculations + - Dynamic fee adjustment + +2. Advanced Routing (Bytes 8-11) + - Split routes + - Flash swap support + - Cross-chain bridging + +3. Advanced AMM Features (Bytes 12-15) + - Concentrated liquidity + - Range orders + - Dynamic fees + - Vault strategies # Activation This SIP will be considered activated when: -1. The trait is deployed to mainnet -2. At least 3 different implementations are deployed -3. A functional swap aggregator demonstrates multi-hop capabilities +1. The trait is deployed to mainnet at SP2ZNGJ85ENDY6QRHQ5P2D4FXKGZWCKTB2T0Z55KS.dexterity-traits-v0 +2. At least 3 different pool implementations adopt the trait +3. A functional swap aggregator demonstrates multi-hop capabilities across implementations -The trait and router designs have been battle-tested in production, with live implementations handling significant trading volume. This provides confidence in the interface design and its ability to support a robust DeFi ecosystem. +The trait and router designs have been battle-tested in production, with live implementations supporting multiple token pairs and significant trading volume.