pool source realm
View source
Pool
Concentrated liquidity AMM pools with tick-based pricing.
Overview
Pool contracts implement Uniswap V3-style concentrated liquidity, allowing LPs to provide liquidity within custom price ranges for maximum capital efficiency.
Configuration
- Pool Creation Fee: 100 GNS (default)
- Protocol Fee: Disabled (0) or 1/4 to 1/10 of swap fees (denominator: 4-10)
- Withdrawal Fee: 1% on collected fees
- Fee Tiers: 0.01%, 0.05%, 0.3%, 1%
- Tick Spacing: Auto-set by fee tier
- Max Liquidity Per Tick: 2^128 - 1
Core Concepts
Concentrated Liquidity
Liquidity providers concentrate capital within custom price ranges instead of 0-∞. This allows LPs to allocate capital where it's most likely to generate fees - near the current price for volatile pairs, or within tight ranges for stable pairs. Capital efficiency can improve by orders of magnitude depending on range selection and pair volatility. For more details, check out GnoSwap Docs.
Tick System
- Price space divided into discrete ticks (0.01% apart)
- Each tick represents ~0.01% price change
- Positions defined by upper/lower tick boundaries
- Liquidity activated only when price in range
Key Functions
CreatePool
Deploys new trading pair.
- Requires 100 GNS creation fee
- Valid fee tier required
- Initial price via sqrtPriceX96
- Unique token pair per fee tier
- Note: No price validation performed (see Security Considerations)
Mint
Adds liquidity to position (called by Position contract).
- Calculates token amounts from liquidity
- Updates tick bitmap
- Transfers tokens from owner
- Returns actual amounts used
Burn
Removes liquidity without collecting tokens.
- Two-step: burn then collect
- Calculates owed amounts
- Updates position state
Collect
Claims tokens from burned position + fees.
- Transfers principal and fees
- Updates tokensOwed
- Applies withdrawal fee
Swap
Core swap execution (called by Router).
- Iterates through ticks
- Updates price and liquidity
- Calculates fees
- Maintains TWAP oracle
Swap Callback
The Swap function uses a callback pattern for token transfers, following the Uniswap V3 flash swap design.
Callback Signature:
1func(cur realm, amount0Delta, amount1Delta int64, _ *pool.CallbackMarker) error
Delta Convention:
| Delta | Meaning |
|---|---|
Positive (> 0) |
Amount the pool must RECEIVE (input token) |
Negative (< 0) |
Amount the pool has SENT (output token) |
Swap Direction Examples:
For zeroForOne = true (token0 → token1):
amount0Delta > 0: Pool receives token0 (input)amount1Delta < 0: Pool sends token1 (output)
For zeroForOne = false (token1 → token0):
amount0Delta < 0: Pool sends token0 (output)amount1Delta > 0: Pool receives token1 (input)
Callback Implementation Example:
1func swapCallback(cur realm, amount0Delta, amount1Delta int64) error {
2 caller := runtime.PreviousRealm().Address()
3 poolAddr := chain.PackageAddress("gno.land/r/gnoswap/pool")
4
5 // Security check: ensure this callback is invoked by the legitimate pool
6 if caller != poolAddr {
7 return errors.New("unauthorized caller")
8 }
9
10 if amount0Delta > 0 {
11 // Transfer token0 to pool
12 common.SafeGRC20Transfer(cross, token0Path, poolAddr, amount0Delta)
13 }
14 if amount1Delta > 0 {
15 // Transfer token1 to pool
16 common.SafeGRC20Transfer(cross, token1Path, poolAddr, amount1Delta)
17 }
18 return nil
19}
Important Notes:
- It is recommended that the callback verify the caller is the legitimate pool to prevent unauthorized invocations
- The callback MUST transfer at least the positive delta amount to the pool
- Return
nilon success, or an error to revert the swap - Pool validates balance increase after callback execution
Technical Details
Price Math
Q96 Format: Prices stored as sqrtPriceX96 = sqrt(price) * 2^96
Price 1:1 → sqrtPriceX96 = 79228162514264337593543950336
Price 1:4 → sqrtPriceX96 = 39614081257132168796771975168
Price 100:1 → sqrtPriceX96 = 792281625142643375935439503360
Tick to Price: price = 1.0001^tick
tick 0 = price 1
tick 6932 = price ~2
tick -6932 = price ~0.5
Liquidity Math
Range Liquidity Formula:
L = amount / (sqrt(upper) - sqrt(lower)) // current < lower
L = amount * sqrt(current) / (upper - current) // lower < current < upper
L = amount / (sqrt(current) - sqrt(lower)) // current > upper
Impermanent Loss:
- Narrow range: Higher fees, higher IL
- Wide range: Lower fees, lower IL
- Stable pairs: ±0.1% ranges optimal
- Volatile pairs: ±10%+ ranges recommended
Fee Mechanics
Swap Fees:
- Charged on input amount
- Accumulates as feeGrowthGlobal
- Distributed pro-rata to in-range liquidity
Fee Calculation:
fees = feeGrowthInside * liquidity
feeGrowthInside = feeGrowthGlobal - feeGrowthOutside
Protocol fees:
- Optional 0% or 4-10% of swap fees
- Configurable per pool
- Sent to protocol fee contract
Security
Reentrancy Protection
- Pools lock during swaps (
slot0.unlocked) - External calls after state updates
- Checks-effects-interactions pattern
Price Manipulation
- TWAP oracle resists manipulation
- Large swaps limited by liquidity
- Slippage protection required
Pool Creation Griefing
Issue: CreatePool allows arbitrary initial prices without validation, enabling griefing attacks where pools are created at extreme prices (e.g., 1 GNO = 0.000001 USDC).
Impact:
- Pool becomes temporarily unusable
- No rational LP will provide liquidity at distorted prices
- Price cannot self-correct without liquidity
Recovery Mechanism: Griefed pools can be restored through an atomic transaction:
- Add Liquidity: Provide wide-range liquidity at the distorted price
- Execute Swap: Trade to move price toward market rate
- Remove Liquidity: Withdraw the provided liquidity
The executor acts as both LP (losing value to slippage) and arbitrageur (gaining from price correction). These effects largely cancel out, with only gas and protocol fees as net cost.
Example Recovery Transaction:
// Atomic recovery for griefed pool
1. position.Mint(fullRange, largeAmount) // Add liquidity
2. router.Swap(correctPrice) // Fix price via arbitrage
3. position.Burn(positionId) // Remove liquidity
4. position.Collect(positionId) // Collect tokens
Prevention:
- 100 GNS creation fee provides deterrent
- Consider implementing price oracle validation for high-value pairs
- Monitor pool creation events for suspicious activity
Rounding
- Division rounds down (favors protocol)
- Minimum liquidity enforced
- Full precision for amounts
3
const ErrSpoofedRealm
const StoreKeyPools, StoreKeyFeeAmountTickSpacing, StoreKeySlot0FeeProtocol, StoreKeyPoolCreationFee, StoreKeyPendingProtocolFees, StoreKeyWithdrawalFeeBPS, StoreKeyUnlocked, StoreKeySwapStartHook, StoreKeySwapEndHook, StoreKeyTickCrossHook
1const (
2 // Pool data storage keys
3 StoreKeyPools StoreKey = "pools" // Map containing all pools
4 StoreKeyFeeAmountTickSpacing StoreKey = "feeAmountTickSpacing" // Fee tier to tick spacing mapping
5 StoreKeySlot0FeeProtocol StoreKey = "slot0FeeProtocol" // Protocol fee percentage
6
7 // Protocol fee storage keys
8 StoreKeyPoolCreationFee StoreKey = "poolCreationFee" // Pool creation fee amount
9 StoreKeyPendingProtocolFees StoreKey = "pendingProtocolFees" // tokenPath -> amount held locally for protocol_fee
10 StoreKeyWithdrawalFeeBPS StoreKey = "withdrawalFeeBPS" // Withdrawal fee in basis points
11 StoreKeyUnlocked StoreKey = "unlocked" // Global pool reentrancy lock
12
13 // Swap hook storage keys
14 StoreKeySwapStartHook StoreKey = "swapStartHook" // Swap start hook function
15 StoreKeySwapEndHook StoreKey = "swapEndHook" // Swap end hook function
16 StoreKeyTickCrossHook StoreKey = "tickCrossHook" // Tick cross hook function
17)88
func Burn
crossing ActionBurn removes liquidity from a position.
func Collect
crossing ActionCollect transfers owed tokens from a position to recipient.
func CollectProtocol
crossing ActionCollectProtocol collects protocol fees from a pool.
Parameters:
- token0Path: path of the first token
- token1Path: path of the second token
- fee: pool fee tier
- recipient: recipient address for fees
- amount0Requested: amount of token0 to collect
- amount1Requested: amount of token1 to collect
Returns:
- string: amount of token0 collected
- string: amount of token1 collected
func CreatePool
crossing ActionCreatePool creates a new liquidity pool for a token pair.
Parameters:
- token0Path: path of the first token
- token1Path: path of the second token
- fee: pool fee tier
- sqrtPriceX96: initial sqrt price (Q64.96 format)
func DecodeTickKey
ActionDecodeTickKey decodes a string key to a tick.
func DrySwap
ActionDrySwap simulates a swap without executing it, returning the expected output.
This is a read-only operation that does not modify pool state. Used by router for multi-hop swap simulations and by clients for price quotes.
Parameters:
- token0Path: path of the first token
- token1Path: path of the second token
- fee: pool fee tier
- zeroForOne: true if swapping token0 for token1
- amountSpecified: amount to swap
- sqrtPriceLimitX96: price limit for the swap
Returns:
- string: amount of token0 delta
- string: amount of token1 delta
- bool: swap success status
func EncodePositionKey
ActionEncodePositionKey encodes a position range into a fixed-width 20-byte string.
func EncodeTickKey
ActionEncodeTickKey encodes a tick to a string key for the tick tree.
func ExistsPoolPath
ActionExistsPoolPath checks if a pool exists at the given path.
func GetBalanceToken0
ActionGetBalanceToken0 returns the balance of token0 in the pool.
func GetBalanceToken1
ActionGetBalanceToken1 returns the balance of token1 in the pool.
func GetBalances
ActionGetBalances returns the balances of the pool.
func GetFee
ActionGetFee returns the fee tier of the pool.
func GetFeeAmountTickSpacing
ActionGetFeeAmountTickSpacing returns the tick spacing for a given fee tier.
func GetFeeAmountTickSpacings
ActionGetFeeAmountTickSpacings returns all fee tier to tick spacing mappings.
func GetFeeGrowthGlobal0X128
ActionGetFeeGrowthGlobal0X128 returns the global fee growth for token0.
func GetFeeGrowthGlobal1X128
ActionGetFeeGrowthGlobal1X128 returns the global fee growth for token1.
func GetFeeGrowthGlobalX128
ActionGetFeeGrowthGlobalX128 returns the global fee growth for both tokens.
func GetImplementationPackagePath
ActionGetImplementationPackagePath returns the package path of the currently active implementation.
func GetInitializedTicksInRange
ActionGetInitializedTicksInRange returns initialized ticks within the given range.
func GetLiquidity
ActionGetLiquidity returns the current liquidity in the pool.
func GetObservation
Action1func GetObservation(poolPath string, secondsAgo int64) (tickCumulative int64, liquidityCumulative, secondsPerLiquidityCumulativeX128 string, blockTimestamp int64)GetObservation returns observation data for calculating time-weighted averages.
func GetPoolCount
ActionGetPoolCount returns the total number of pools.
func GetPoolCreationFee
ActionGetPoolCreationFee returns the current pool creation fee.
func GetPoolPath
ActionGetPoolPath generates a unique pool path string based on the token paths and fee tier.
func GetPoolPaths
ActionGetPoolPaths returns a paginated list of pool paths.
func GetPoolPositionCount
ActionGetPoolPositionCount returns the number of positions in a pool.
func GetPoolPositionKeys
ActionGetPoolPositionKeys returns a paginated list of position keys in a pool.
func GetPositionFeeGrowthInside0LastX128
ActionGetPositionFeeGrowthInside0LastX128 returns the last recorded fee growth inside for token0.
func GetPositionFeeGrowthInside1LastX128
ActionGetPositionFeeGrowthInside1LastX128 returns the last recorded fee growth inside for token1.
func GetPositionFeeGrowthInsideLastX128
ActionGetPositionFeeGrowthInsideLastX128 returns the last recorded fee growth inside for both tokens.
func GetPositionLiquidity
ActionGetPositionLiquidity returns the liquidity of a position.
func GetPositionTokensOwed
ActionGetPositionTokensOwedInfos returns the amount of tokens owed for both tokens.
func GetPositionTokensOwed0
ActionGetPositionTokensOwed0 returns the amount of token0 owed to a position.
func GetPositionTokensOwed1
ActionGetPositionTokensOwed1 returns the amount of token1 owed to a position.
func GetProtocolFeesToken0
ActionGetProtocolFeesToken0 returns accumulated protocol fees for token0.
func GetProtocolFeesToken1
ActionGetProtocolFeesToken1 returns accumulated protocol fees for token1.
func GetProtocolFeesTokens
ActionGetProtocolFeesTokens returns the accumulated protocol fees for both tokens.
func GetSlot0FeeProtocol
ActionGetSlot0FeeProtocol returns the protocol fee rate from slot0.
func GetSlot0SqrtPriceX96
ActionGetSlot0SqrtPriceX96 returns the current sqrt price from slot0.
func GetSlot0Tick
ActionGetSlot0Tick returns the current tick from slot0.
func GetSlot0Unlocked
ActionGetSlot0Unlocked returns the locked status from slot0.
func GetTWAP
ActionGetTWAP returns the time-weighted average price for a pool. Returns arithmetic mean tick and harmonic mean liquidity over the time period.
func GetTickBitmaps
ActionGetTickBitmaps returns the tick bitmap for a given word position.
func GetTickCumulativeOutside
ActionGetTickCumulativeOutside returns the tick cumulative value outside a tick.
func GetTickFeeGrowthOutside0X128
ActionGetTickFeeGrowthOutside0X128 returns fee growth outside for token0 at a tick.
func GetTickFeeGrowthOutside1X128
ActionGetTickFeeGrowthOutside1X128 returns fee growth outside for token1 at a tick.
func GetTickFeeGrowthOutsideX128
ActionGetTickFeeGrowthOutsideX128 returns fee growth outside for both tokens at a tick.
func GetTickInitialized
ActionGetTickInitialized returns whether a tick is initialized.
func GetTickLiquidityGross
ActionGetTickLiquidityGross returns the total liquidity that references a tick.
func GetTickLiquidityNet
ActionGetTickLiquidityNet returns the net liquidity change at a tick.
func GetTickSecondsOutside
ActionGetTickSecondsOutside returns seconds spent outside a tick.
func GetTickSecondsPerLiquidityOutsideX128
ActionGetTickSecondsPerLiquidityOutsideX128 returns seconds per liquidity outside a tick.
func GetTickSpacing
ActionGetTickSpacing returns the tick spacing of the pool.
func GetToken0Path
ActionGetToken0Path returns the path of token0 in the pool.
func GetToken1Path
ActionGetToken1Path returns the path of token1 in the pool.
func GetWithdrawalFee
ActionGetWithdrawalFee returns the current withdrawal fee rate.
func HandleWithdrawalFee
crossing ActionHandleWithdrawalFee processes withdrawal fees for a position.
Parameters:
- token0Path: path of the first token
- amount0: amount of token0 to withdraw
- token1Path: path of the second token
- amount1: amount of token1 to withdraw
- positionCaller: caller address for the position
Returns:
- string: withdrawal fee amount of token0
- string: withdrawal fee amount of token1
- string: net amount of token0 after fees
- string: net amount of token1 after fees
func IncreaseObservationCardinalityNext
crossing ActionIncreaseObservationCardinalityNext increases the observation cardinality for a pool.
Parameters:
- token0Path: path of the first token
- token1Path: path of the second token
- fee: pool fee tier
- cardinalityNext: new observation cardinality limit
func Mint
crossing ActionMint adds liquidity to a position.
Parameters:
- token0Path: path of the first token
- token1Path: path of the second token
- fee: pool fee tier
- tickLower: lower tick boundary
- tickUpper: upper tick boundary
- liquidityAmount: amount of liquidity to add
- positionCaller: caller address for the position
Returns:
- string: amount of token0 added
- string: amount of token1 added
func NewDefaultFeeAmountTickSpacing
Actionfunc NewPoolPositionsTree
ActionNewPoolPositionsTree creates a BPTree for storing pool position info (fanout 16), owned by the pool domain realm so leaf-slot writes are not readonly tainted.
func NewPoolTicksTree
ActionNewPoolTicksTree creates a BPTree for storing pool tick info (fanout 32), owned by the pool domain realm so leaf-slot writes are not readonly tainted.
func NewPoolsTree
Actionfunc RegisterInitializer
crossing Action1func RegisterInitializer(cur realm, initializer func(_ int, rlm realm, poolStore IPoolStore) IPool)RegisterInitializer registers a new pool implementation version. This function is called by each version (v1, v2, etc.) during initialization to register their implementation with the proxy system.
The initializer function creates a new instance of the implementation using the provided poolStore interface.
The stateInitializer function creates the initial state for this version.
Security: Only contracts within the domain path can register initializers. Each package path can only register once to prevent duplicate registrations.
func SetFeeProtocol
crossing ActionSetFeeProtocol sets the protocol fee rates for a pool.
Parameters:
- feeProtocol0: protocol fee rate for token0
- feeProtocol1: protocol fee rate for token1
func SetPoolCreationFee
crossing ActionSetPoolCreationFee sets the pool creation fee.
func SetSwapEndHook
crossing ActionSetSwapEndHook sets the hook to be called at the end of a swap.
func SetSwapStartHook
crossing ActionSetSwapStartHook sets the hook to be called at the start of a swap.
func SetTickCrossHook
crossing Action1func SetTickCrossHook(cur realm, hook func(cur realm, poolPath string, tickId int32, zeroForOne bool, timestamp int64))SetTickCrossHook sets the hook to be called when a tick is crossed during a swap.
func SetWithdrawalFee
crossing ActionSetWithdrawalFee sets the withdrawal fee rate.
Parameters:
- fee: withdrawal fee in basis points
func Swap
crossing Action 1func Swap(
2 cur realm,
3 token0Path string,
4 token1Path string,
5 fee uint32,
6 recipient address,
7 zeroForOne bool,
8 amountSpecified string,
9 sqrtPriceLimitX96 string,
10 payer address,
11 swapCallback func(cur realm, amount0Delta, amount1Delta int64, callbackMarker *CallbackMarker) error,
12) (string, string)Swap executes a token swap in the pool.
Parameters:
- token0Path: path of the first token
- token1Path: path of the second token
- fee: pool fee tier
- recipient: recipient address for output tokens
- zeroForOne: true if swapping token0 for token1
- amountSpecified: amount to swap (positive for exact input, negative for exact output)
- sqrtPriceLimitX96: price limit for the swap
- payer: address that will pay for the swap
- swapCallback: callback function for token transfer, callbackMarker is used to identify the callback
Returns:
- string: amount of token0 delta
- string: amount of token1 delta
func UpgradeImpl
crossing ActionUpgradeImpl switches the active pool implementation to a different version. This function allows seamless upgrades from one version to another without data migration or downtime.
Security: Only admin or governance can perform upgrades. The new implementation must have been previously registered via RegisterInitializer.
func NewCallbackMarker
ActionNewCallbackMarker allocates a CallbackMarker in the pool realm. Construction must happen here because /r/-declared types can only be allocated in their owning realm (interrealm v2 checkConstructionTime). Callers in other realms (e.g. pool/v1 impl) borrow into pool via borrow rule #1 (function defined in /r/ package).
func NewPoolStore
ActionNewPoolStore creates a new pool store instance with the provided KV store. This function is used by the upgrade system to create storage instances for each implementation.
func NewDefaultObservation
Actionfunc NewObservation
Actionfunc GetObservationState
ActionGetObservationState returns the observation state for a given pool path.
func NewObservationState
Actionfunc GetPool
ActionGetPool returns a copy of the pool for the given token pair and fee tier.
func NewPool
Actionfunc GetPosition
ActionGetPosition returns the position info for a given key.
func NewDefaultPositionInfo
Actionfunc NewPositionInfo
Actionfunc NewSlot0
Actionfunc GetTickInfo
ActionGetTickInfo returns the tick info for a given tick.
func NewTickInfo
Actionfunc NewTokenPair
Action15
type CallbackMarker
structtype IPool
interfaceIPool interface defines all public methods that must be implemented by pool contract versions. This interface serves as the contract between the proxy layer and implementation versions, ensuring that all versions (v1, v2, v3, etc.) maintain the same public API.
This design enables seamless upgrades while maintaining backwards compatibility. When upgrading from v1 to v2, the proxy simply switches the implementation pointer without changing the public interface, ensuring zero downtime and no breaking changes.
type IPoolGetter
interface 1type IPoolGetter interface {
2 ExistsPoolPath(poolPath string) bool
3
4 GetBalanceToken0(poolPath string) int64
5
6 GetBalanceToken1(poolPath string) int64
7
8 GetFee(poolPath string) uint32
9
10 GetFeeAmountTickSpacing(fee uint32) (spacing int32)
11
12 GetFeeGrowthGlobal0X128(poolPath string) *u256.Uint
13
14 GetFeeGrowthGlobal1X128(poolPath string) *u256.Uint
15
16 GetFeeGrowthGlobalX128(poolPath string) (*u256.Uint, *u256.Uint)
17
18 GetLiquidity(poolPath string) *u256.Uint
19
20 GetObservation(poolPath string, secondsAgo int64) (tickCumulative int64, liquidityCumulative, secondsPerLiquidityCumulativeX128 string, blockTimestamp int64)
21
22 GetPoolCreationFee() int64
23
24 GetPositionFeeGrowthInside0LastX128(poolPath, key string) string
25
26 GetPositionFeeGrowthInside1LastX128(poolPath, key string) string
27
28 GetPositionFeeGrowthInsideLastX128(poolPath, key string) (string, string)
29
30 GetPositionLiquidity(poolPath, key string) string
31
32 GetPositionTokensOwed0(poolPath, key string) int64
33
34 GetPositionTokensOwed1(poolPath, key string) int64
35
36 GetProtocolFeesToken0(poolPath string) int64
37
38 GetProtocolFeesToken1(poolPath string) int64
39
40 GetSlot0FeeProtocol(poolPath string) uint8
41
42 GetSlot0SqrtPriceX96(poolPath string) *u256.Uint
43
44 GetSlot0Tick(poolPath string) int32
45
46 GetSlot0Unlocked(poolPath string) bool
47
48 GetTickCumulativeOutside(poolPath string, tick int32) int64
49
50 GetTickFeeGrowthOutside0X128(poolPath string, tick int32) string
51
52 GetTickFeeGrowthOutside1X128(poolPath string, tick int32) string
53
54 GetTickFeeGrowthOutsideX128(poolPath string, tick int32) (string, string)
55
56 GetTickInitialized(poolPath string, tick int32) bool
57
58 GetTickLiquidityGross(poolPath string, tick int32) string
59
60 GetTickLiquidityNet(poolPath string, tick int32) string
61
62 GetTickSecondsOutside(poolPath string, tick int32) uint32
63
64 GetTickSecondsPerLiquidityOutsideX128(poolPath string, tick int32) string
65
66 GetTickSpacing(poolPath string) int32
67
68 GetToken0Path(poolPath string) string
69
70 GetToken1Path(poolPath string) string
71
72 GetWithdrawalFee() uint64
73
74 GetTWAP(poolPath string, secondsAgo uint32) (int32, *u256.Uint, error)
75
76 GetPoolCount() int
77 GetPoolPaths(offset, count int) []string
78 GetFeeAmountTickSpacings() map[uint32]int32
79
80 GetPoolPositionCount(poolPath string) int
81 GetPoolPositionKeys(poolPath string, offset, count int) []string
82
83 GetInitializedTicksInRange(poolPath string, tickLower, tickUpper int32) []int32
84
85 // Structure getters
86 GetPool(token0Path, token1Path string, fee uint32) (*Pool, error)
87 GetTickInfo(poolPath string, tick int32) (TickInfo, error)
88 GetTickBitmaps(poolPath string, wordPos int16) (string, error)
89 GetPosition(poolPath, key string) (PositionInfo, error)
90 GetObservationState(poolPath string) (*ObservationState, error)
91}IPoolGetter interface defines data retrieval operations. These methods provide read-only access to pool state and data.
type IPoolManager
interface 1type IPoolManager interface {
2 // CreatePool creates a new concentrated liquidity pool.
3 CreatePool(
4 _ int,
5 rlm realm,
6 token0Path string,
7 token1Path string,
8 fee uint32,
9 sqrtPriceX96 string,
10 )
11
12 // SetPoolCreationFee sets the pool creation fee.
13 SetPoolCreationFee(_ int, rlm realm, fee int64)
14
15 IncreaseObservationCardinalityNext(
16 _ int,
17 rlm realm,
18 token0Path string,
19 token1Path string,
20 fee uint32,
21 cardinalityNext uint16,
22 )
23}IPoolManager interface defines pool management operations. These methods handle pool creation and fee configuration.
type IPoolPosition
interface 1type IPoolPosition interface {
2 // Mint adds liquidity to a pool position.
3 Mint(
4 _ int,
5 rlm realm,
6 token0Path string,
7 token1Path string,
8 fee uint32,
9 tickLower int32,
10 tickUpper int32,
11 liquidityAmount string,
12 positionCaller address,
13 ) (string, string)
14
15 // Burn removes liquidity from a position.
16 Burn(
17 _ int,
18 rlm realm,
19 token0Path string,
20 token1Path string,
21 fee uint32,
22 tickLower int32,
23 tickUpper int32,
24 liquidityAmount string,
25 positionCaller address,
26 ) (string, string)
27
28 // Collect transfers owed tokens from a position to recipient.
29 Collect(
30 _ int,
31 rlm realm,
32 token0Path string,
33 token1Path string,
34 fee uint32,
35 recipient address,
36 tickLower int32,
37 tickUpper int32,
38 amount0Requested string,
39 amount1Requested string,
40 ) (string, string)
41
42 SetWithdrawalFee(_ int, rlm realm, fee uint64)
43
44 HandleWithdrawalFee(
45 _ int,
46 rlm realm,
47 token0Path string,
48 amount0 string,
49 token1Path string,
50 amount1 string,
51 positionCaller address,
52 ) (string, string, string, string)
53}IPoolPosition interface defines position management operations. These methods handle liquidity provision and position management.
type IPoolStore
interface 1type IPoolStore interface {
2 HasPools() bool
3 GetPools() *bptree.BPTree
4 SetPools(_ int, rlm realm, pools *bptree.BPTree) error
5
6 HasFeeAmountTickSpacing() bool
7 GetFeeAmountTickSpacing() map[uint32]int32
8 SetFeeAmountTickSpacing(_ int, rlm realm, feeAmountTickSpacing map[uint32]int32) error
9
10 HasSlot0FeeProtocol() bool
11 GetSlot0FeeProtocol() uint8
12 SetSlot0FeeProtocol(_ int, rlm realm, slot0FeeProtocol uint8) error
13
14 HasPoolCreationFee() bool
15 GetPoolCreationFee() int64
16 SetPoolCreationFee(_ int, rlm realm, poolCreationFee int64) error
17
18 HasPendingProtocolFees() bool
19 GetPendingProtocolFees() map[string]int64
20 SetPendingProtocolFees(_ int, rlm realm, pendingProtocolFees map[string]int64) error
21
22 HasWithdrawalFeeBPS() bool
23 GetWithdrawalFeeBPS() uint64
24 SetWithdrawalFeeBPS(_ int, rlm realm, withdrawalFeeBPS uint64) error
25
26 HasUnlocked() bool
27 GetUnlocked() bool
28 SetUnlocked(_ int, rlm realm, unlocked bool) error
29
30 HasSwapStartHook() bool
31 GetSwapStartHook() func(cur realm, poolPath string, timestamp int64)
32 SetSwapStartHook(_ int, rlm realm, swapStartHook func(cur realm, poolPath string, timestamp int64)) error
33
34 HasSwapEndHook() bool
35 GetSwapEndHook() func(cur realm, poolPath string) error
36 SetSwapEndHook(_ int, rlm realm, swapEndHook func(cur realm, poolPath string) error) error
37
38 HasTickCrossHook() bool
39 GetTickCrossHook() func(cur realm, poolPath string, tickId int32, zeroForOne bool, timestamp int64)
40 SetTickCrossHook(_ int, rlm realm, tickCrossHook func(cur realm, poolPath string, tickId int32, zeroForOne bool, timestamp int64)) error
41}IPoolStore interface defines the storage abstraction for pool data. This interface provides a clean separation between business logic and storage, allowing different implementations to use the same storage interface.
All pool implementations (v1, v2, etc.) use this interface to access and modify pool state, ensuring data consistency across versions.
type IPoolSwap
interface 1type IPoolSwap interface {
2 Swap(
3 _ int,
4 rlm realm,
5 token0Path string,
6 token1Path string,
7 fee uint32,
8 recipient address,
9 zeroForOne bool,
10 amountSpecified string,
11 sqrtPriceLimitX96 string,
12 payer address,
13 swapCallback func(cur realm, amount0Delta, amount1Delta int64, callbackMarker *CallbackMarker) error,
14 ) (string, string)
15
16 DrySwap(
17 token0Path string,
18 token1Path string,
19 fee uint32,
20 zeroForOne bool,
21 amountSpecified string,
22 sqrtPriceLimitX96 string,
23 ) (string, string, bool)
24
25 SetSwapEndHook(_ int, rlm realm, hook func(cur realm, poolPath string) error)
26
27 SetSwapStartHook(_ int, rlm realm, hook func(cur realm, poolPath string, timestamp int64))
28
29 SetTickCrossHook(_ int, rlm realm, hook func(cur realm, poolPath string, tickId int32, zeroForOne bool, timestamp int64))
30
31 CollectProtocol(
32 _ int,
33 rlm realm,
34 token0Path string,
35 token1Path string,
36 fee uint32,
37 recipient address,
38 amount0Requested string,
39 amount1Requested string,
40 ) (string, string)
41
42 SetFeeProtocol(_ int, rlm realm, feeProtocol0, feeProtocol1 uint8)
43}IPoolSwap interface defines swap and protocol fee operations. These methods handle token swaps and protocol fee management.
type Observation
struct1type Observation struct {
2 blockTimestamp int64 // timestamp of the observation
3 tickCumulative int64 // cumulative tick up to this timestamp
4 liquidityCumulative string // cumulative liquidity up to this timestamp
5 secondsPerLiquidityCumulativeX128 string // cumulative seconds per liquidity
6 initialized bool // whether this observation has been initialized
7}Methods on Observation
func BlockTimestamp
method on ObservationObservation Getters methods
func Clone
method on Observationfunc Initialized
method on Observationfunc LiquidityCumulative
method on Observationfunc SecondsPerLiquidityCumulativeX128
method on Observationfunc SetBlockTimestamp
method on ObservationObservation Setters methods
func SetInitialized
method on Observationfunc SetLiquidityCumulative
method on Observationfunc SetSecondsPerLiquidityCumulativeX128
method on Observationfunc SetTickCumulative
method on Observationfunc TickCumulative
method on Observationtype ObservationState
struct1type ObservationState struct {
2 observations map[uint16]*Observation // circular buffer of observations
3 index uint16 // the most-recently updated index of the observations array
4 cardinality uint16 // the current maximum number of observations that are being stored
5 cardinalityNext uint16 // the next maximum number of observations to store, triggered in observations.write
6}ObservationState manages the oracle's historical data
Methods on ObservationState
func Cardinality
method on ObservationStatefunc CardinalityNext
method on ObservationStatefunc Index
method on ObservationStateObservationState Getters methods
func Observations
method on ObservationStatefunc SetCardinality
method on ObservationStatefunc SetCardinalityNext
method on ObservationStatefunc SetIndex
method on ObservationStateObservationState Setters methods
func SetObservation
method on ObservationStatefunc SetObservations
method on ObservationStatetype Pool
struct 1type Pool struct {
2 // token0/token1 path of the pool
3 token0Path string
4 token1Path string
5 fee uint32 // fee tier of the pool
6 tickSpacing int32 // spacing between ticks
7 slot0 Slot0
8 balances TokenPair // balances of the pool
9 protocolFees TokenPair
10 feeGrowthGlobal0X128 *u256.Uint // uint256
11 feeGrowthGlobal1X128 *u256.Uint // uint256
12 liquidity *u256.Uint // total amount of active liquidity in the pool (within current tick range)
13 ticks *bptree.BPTree // tick(int32) -> TickInfo
14 tickBitmaps map[int16]string // tick(wordPos)(int16) -> bitMap(tickWord ^ mask)(string)
15 positions *bptree.BPTree // maps the key (caller, lower tick, upper tick) to a unique position
16
17 observationState *ObservationState // oracle state with historical observations
18}type Pool describes a single Pool's state A pool is identificed with a unique key (token0, token1, fee), where token0 < token1
Methods on Pool
func BalanceToken0
method on Poolfunc BalanceToken1
method on Poolfunc Balances
method on Poolfunc Clone
method on Poolfunc DeleteTick
method on Poolfunc Fee
method on Poolfunc FeeGrowthGlobal0X128
method on Poolfunc FeeGrowthGlobal1X128
method on Poolfunc GetTick
method on Poolfunc HasTick
method on Poolfunc IterateTicks
method on Poolfunc Liquidity
method on Poolfunc ObservationState
method on Poolfunc PoolPath
method on PoolPool Getters methods
func Positions
method on Poolfunc ProtocolFees
method on Poolfunc ProtocolFeesToken0
method on Poolfunc ProtocolFeesToken1
method on Poolfunc SetBalanceToken0
method on Poolfunc SetBalanceToken1
method on Poolfunc SetBalances
method on Poolfunc SetFee
method on Poolfunc SetFeeGrowthGlobal0X128
method on Poolfunc SetFeeGrowthGlobal1X128
method on Poolfunc SetLiquidity
method on Poolfunc SetObservationState
method on Poolfunc SetPosition
method on Poolfunc SetPositions
method on Poolfunc SetProtocolFees
method on Poolfunc SetProtocolFeesToken0
method on Poolfunc SetProtocolFeesToken1
method on Poolfunc SetSlot0
method on Poolfunc SetTick
method on Poolfunc SetTickBitmap
method on Poolfunc SetTickBitmaps
method on Poolfunc SetTickSpacing
method on Poolfunc SetTicks
method on Poolfunc SetToken0Path
method on PoolPool Setters methods
func SetToken1Path
method on Poolfunc Slot0
method on Poolfunc Slot0FeeProtocol
method on Poolfunc Slot0SqrtPriceX96
method on Poolfunc Slot0Tick
method on Poolfunc Slot0Unlocked
method on Poolfunc TickBitmaps
method on Poolfunc TickSpacing
method on Poolfunc Ticks
method on Poolfunc Token0Path
method on Poolfunc Token1Path
method on Pooltype PositionInfo
struct 1type PositionInfo struct {
2 liquidity string // amount of liquidity owned by this position
3 feeGrowthInside0LastX128 string // fee growth per unit of liquidity for token0 as of last update
4 feeGrowthInside1LastX128 string // fee growth per unit of liquidity for token1 as of last update
5
6 // accumulated fees in token0 waiting to be collected
7 tokensOwed0 int64
8
9 // accumulated fees in token1 waiting to be collected
10 tokensOwed1 int64
11}PositionInfo stores liquidity and fee state for a position. Liquidity and fee-growth fields are stored as decimal strings to reduce storage cost, while transferable owed amounts stay as int64 for token transfer boundaries.
Methods on PositionInfo
func FeeGrowthInside0LastX128
method on PositionInfofunc FeeGrowthInside1LastX128
method on PositionInfofunc Liquidity
method on PositionInfofunc SetFeeGrowthInside0LastX128
method on PositionInfofunc SetFeeGrowthInside1LastX128
method on PositionInfofunc SetLiquidity
method on PositionInfofunc SetTokensOwed0
method on PositionInfofunc SetTokensOwed1
method on PositionInfofunc TokensOwed0
method on PositionInfofunc TokensOwed1
method on PositionInfotype Slot0
struct1type Slot0 struct {
2 sqrtPriceX96 *u256.Uint // current price of the pool as a sqrt(token1/token0) Q96 value
3 tick int32 // current tick of the pool, i.e according to the last tick transition that was run
4 feeProtocol uint8 // protocol fee for both tokens of the pool
5 unlocked bool // whether the pool is currently locked to reentrancy
6}Methods on Slot0
func FeeProtocol
method on Slot0func SetFeeProtocol
method on Slot0func SetSqrtPriceX96
method on Slot0func SetTick
method on Slot0func SetUnlocked
method on Slot0func SqrtPriceX96
method on Slot0func Tick
method on Slot0func Unlocked
method on Slot0type StoreKey
identStoreKey defines the keys used for storing pool data in the KV store. These keys are prefixed with the domain address to ensure namespace isolation.
type TickInfo
struct 1type TickInfo struct {
2 liquidityGross string // total position liquidity that references this tick
3 liquidityNet string // amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)
4
5 // fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
6 // only has relative meaning, not absolute — the value depends on when the tick is initialized
7 feeGrowthOutside0X128 string
8 feeGrowthOutside1X128 string
9
10 tickCumulativeOutside int64 // cumulative tick value on the other side of the tick
11
12 // the seconds per unit of liquidity on the _other_ side of this tick (relative to the current tick)
13 // only has relative meaning, not absolute — the value depends on when the tick is initialized
14 secondsPerLiquidityOutsideX128 string
15
16 // the seconds spent on the other side of the tick (relative to the current tick)
17 // only has relative meaning, not absolute — the value depends on when the tick is initialized
18 secondsOutside uint32
19
20 initialized bool // whether the tick is initialized
21}TickInfo stores information about a specific tick in the pool. TIcks represent discrete price points that can be used as boundaries for positions.
Methods on TickInfo
func Clone
method on TickInfofunc FeeGrowthOutside0X128
method on TickInfofunc FeeGrowthOutside1X128
method on TickInfofunc Initialized
method on TickInfofunc LiquidityGross
method on TickInfoTickInfo Getters methods
func LiquidityNet
method on TickInfofunc SecondsOutside
method on TickInfofunc SecondsPerLiquidityOutsideX128
method on TickInfofunc SetFeeGrowthOutside0X128
method on TickInfofunc SetFeeGrowthOutside1X128
method on TickInfofunc SetInitialized
method on TickInfofunc SetLiquidityGross
method on TickInfoTickInfo Setters methods
func SetLiquidityNet
method on TickInfofunc SetSecondsOutside
method on TickInfofunc SetSecondsPerLiquidityOutsideX128
method on TickInfofunc SetTickCumulativeOutside
method on TickInfofunc TickCumulativeOutside
method on TickInfotype TokenPair
struct11
- errors stdlib
- gno.land/p/gnoswap/store package
- gno.land/p/gnoswap/uint256 package
- gno.land/p/gnoswap/version_manager package
- gno.land/p/nt/bptree/v0 package
- gno.land/p/nt/ufmt/v0 package
- gno.land/r/gnoswap/access realm
- gno.land/r/gnoswap/rbac realm
- strconv stdlib
- strings stdlib
- time stdlib