Search Apps Documentation Source Content File Folder Download Copy Actions Download State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

pool source realm

Readme 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 nil on 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:

  1. Add Liquidity: Provide wide-range liquidity at the distorted price
  2. Execute Swap: Trade to move price toward market rate
  3. 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

Constants 3

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)
source

Functions 88

func Burn

crossing Action
 1func Burn(
 2	cur realm,
 3	token0Path string,
 4	token1Path string,
 5	fee uint32,
 6	tickLower int32,
 7	tickUpper int32,
 8	liquidityAmount string,
 9	positionCaller address,
10) (string, string)
source

Burn removes liquidity from a position.

func Collect

crossing Action
 1func Collect(
 2	cur realm,
 3	token0Path string,
 4	token1Path string,
 5	fee uint32,
 6	recipient address,
 7	tickLower int32,
 8	tickUpper int32,
 9	amount0Requested string,
10	amount1Requested string,
11) (string, string)
source

Collect transfers owed tokens from a position to recipient.

func CollectProtocol

crossing Action
1func CollectProtocol(
2	cur realm,
3	token0Path string,
4	token1Path string,
5	fee uint32,
6	recipient address,
7	amount0Requested string,
8	amount1Requested string,
9) (string, string)
source

CollectProtocol 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 Action
1func CreatePool(
2	cur realm,
3	token0Path string,
4	token1Path string,
5	fee uint32,
6	sqrtPriceX96 string,
7)
source

CreatePool 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 DrySwap

Action
1func DrySwap(
2	token0Path string,
3	token1Path string,
4	fee uint32,
5	zeroForOne bool,
6	amountSpecified string,
7	sqrtPriceLimitX96 string,
8) (string, string, bool)
source

DrySwap 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

Action
1func EncodePositionKey(tickLower, tickUpper int32) string
source

EncodePositionKey encodes a position range into a fixed-width 20-byte string.

func EncodeTickKey

Action
1func EncodeTickKey(tick int32) string
source

EncodeTickKey encodes a tick to a string key for the tick tree.

func GetBalances

Action
1func GetBalances(poolPath string) (int64, int64)
source

GetBalances returns the balances of the pool.

func GetFee

Action
1func GetFee(poolPath string) uint32
source

GetFee returns the fee tier of the pool.

func GetInitializedTicksInRange

Action
1func GetInitializedTicksInRange(poolPath string, tickLower, tickUpper int32) []int32
source

GetInitializedTicksInRange returns initialized ticks within the given range.

func GetLiquidity

Action
1func GetLiquidity(poolPath string) string
source

GetLiquidity returns the current liquidity in the pool.

func GetObservation

Action
1func GetObservation(poolPath string, secondsAgo int64) (tickCumulative int64, liquidityCumulative, secondsPerLiquidityCumulativeX128 string, blockTimestamp int64)
source

GetObservation returns observation data for calculating time-weighted averages.

func GetPoolPath

Action
1func GetPoolPath(token0Path, token1Path string, fee uint32) string
source

GetPoolPath generates a unique pool path string based on the token paths and fee tier.

func GetPoolPaths

Action
1func GetPoolPaths(offset, count int) []string
source

GetPoolPaths returns a paginated list of pool paths.

func GetPoolPositionKeys

Action
1func GetPoolPositionKeys(poolPath string, offset, count int) []string
source

GetPoolPositionKeys returns a paginated list of position keys in a pool.

func GetPositionTokensOwed

Action
1func GetPositionTokensOwed(poolPath, key string) (int64, int64)
source

GetPositionTokensOwedInfos returns the amount of tokens owed for both tokens.

func GetProtocolFeesTokens

Action
1func GetProtocolFeesTokens(poolPath string) (int64, int64)
source

GetProtocolFeesTokens returns the accumulated protocol fees for both tokens.

func GetTWAP

Action
1func GetTWAP(poolPath string, secondsAgo uint32) (int32, string, error)
source

GetTWAP returns the time-weighted average price for a pool. Returns arithmetic mean tick and harmonic mean liquidity over the time period.

func GetTickBitmaps

Action
1func GetTickBitmaps(poolPath string, wordPos int16) (string, error)
source

GetTickBitmaps returns the tick bitmap for a given word position.

func GetTickFeeGrowthOutsideX128

Action
1func GetTickFeeGrowthOutsideX128(poolPath string, tick int32) (string, string)
source

GetTickFeeGrowthOutsideX128 returns fee growth outside for both tokens at a tick.

func GetTickLiquidityGross

Action
1func GetTickLiquidityGross(poolPath string, tick int32) string
source

GetTickLiquidityGross returns the total liquidity that references a tick.

func GetTickLiquidityNet

Action
1func GetTickLiquidityNet(poolPath string, tick int32) string
source

GetTickLiquidityNet returns the net liquidity change at a tick.

func HandleWithdrawalFee

crossing Action
1func HandleWithdrawalFee(
2	cur realm,
3	token0Path string,
4	amount0 string,
5	token1Path string,
6	amount1 string,
7	positionCaller address,
8) (string, string, string, string)
source

HandleWithdrawalFee 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 Action
1func IncreaseObservationCardinalityNext(
2	cur realm,
3	token0Path string,
4	token1Path string,
5	fee uint32,
6	cardinalityNext uint16,
7)
source

IncreaseObservationCardinalityNext 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 Action
 1func Mint(
 2	cur realm,
 3	token0Path string,
 4	token1Path string,
 5	fee uint32,
 6	tickLower int32,
 7	tickUpper int32,
 8	liquidityAmount string,
 9	positionCaller address,
10) (string, string)
source

Mint 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 NewPoolPositionsTree

Action
1func NewPoolPositionsTree() *bptree.BPTree
source

NewPoolPositionsTree 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

Action
1func NewPoolTicksTree() *bptree.BPTree
source

NewPoolTicksTree 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 RegisterInitializer

crossing Action
1func RegisterInitializer(cur realm, initializer func(_ int, rlm realm, poolStore IPoolStore) IPool)
source

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 Action
1func SetFeeProtocol(cur realm, feeProtocol0, feeProtocol1 uint8)
source

SetFeeProtocol sets the protocol fee rates for a pool.

Parameters:

  • feeProtocol0: protocol fee rate for token0
  • feeProtocol1: protocol fee rate for token1

func SetSwapEndHook

crossing Action
1func SetSwapEndHook(cur realm, hook func(cur realm, poolPath string) error)
source

SetSwapEndHook sets the hook to be called at the end of a swap.

func SetSwapStartHook

crossing Action
1func SetSwapStartHook(cur realm, hook func(cur realm, poolPath string, timestamp int64))
source

SetSwapStartHook sets the hook to be called at the start of a swap.

func SetTickCrossHook

crossing Action
1func SetTickCrossHook(cur realm, hook func(cur realm, poolPath string, tickId int32, zeroForOne bool, timestamp int64))
source

SetTickCrossHook sets the hook to be called when a tick is crossed during a swap.

func SetWithdrawalFee

crossing Action
1func SetWithdrawalFee(cur realm, fee uint64)
source

SetWithdrawalFee 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)
source

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 Action
1func UpgradeImpl(cur realm, packagePath string)
source

UpgradeImpl 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

Action
1func NewCallbackMarker() *CallbackMarker
source

NewCallbackMarker 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

Action
1func NewPoolStore(kvStore store.KVStore) IPoolStore
source

NewPoolStore 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 NewObservation

Action
1func NewObservation(
2	blockTimestamp int64,
3	tickCumulative int64,
4	liquidityCumulative string,
5	secondsPerLiquidityCumulativeX128 string,
6	initialized bool,
7) *Observation
source

func GetObservationState

Action
1func GetObservationState(poolPath string) (*ObservationState, error)
source

GetObservationState returns the observation state for a given pool path.

func GetPool

Action
1func GetPool(token0Path, token1Path string, fee uint32) (*Pool, error)
source

GetPool returns a copy of the pool for the given token pair and fee tier.

func NewPool

Action
1func NewPool(
2	token0Path string,
3	token1Path string,
4	fee uint32,
5	sqrtPriceX96 *u256.Uint,
6	tickSpacing int32,
7	tick int32,
8	slot0FeeProtocol uint8,
9) *Pool
source

func GetPosition

Action
1func GetPosition(poolPath, key string) (PositionInfo, error)
source

GetPosition returns the position info for a given key.

func GetTickInfo

Action
1func GetTickInfo(poolPath string, tick int32) (TickInfo, error)
source

GetTickInfo returns the tick info for a given tick.

Types 15

type IPool

interface
1type IPool interface {
2	IPoolManager
3	IPoolPosition
4	IPoolSwap
5	IPoolGetter
6}
source

IPool 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}
source

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}
source

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}
source

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}
source

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}
source

IPoolSwap interface defines swap and protocol fee operations. These methods handle token swaps and protocol fee management.

type Observation

struct
1type 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}
source

Methods on Observation

func BlockTimestamp

method on Observation
1func (o *Observation) BlockTimestamp() int64
source

Observation Getters methods

func Clone

method on Observation
1func (o *Observation) Clone() *Observation
source

func Initialized

method on Observation
1func (o *Observation) Initialized() bool
source

func SetBlockTimestamp

method on Observation
1func (o *Observation) SetBlockTimestamp(blockTimestamp int64)
source

Observation Setters methods

func SetInitialized

method on Observation
1func (o *Observation) SetInitialized(initialized bool)
source

func SetTickCumulative

method on Observation
1func (o *Observation) SetTickCumulative(tickCumulative int64)
source

type ObservationState

struct
1type 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}
source

ObservationState manages the oracle's historical data

Methods on ObservationState

func Cardinality

method on ObservationState
1func (os *ObservationState) Cardinality() uint16
source

func CardinalityNext

method on ObservationState
1func (os *ObservationState) CardinalityNext() uint16
source

func Index

method on ObservationState
1func (os *ObservationState) Index() uint16
source

ObservationState Getters methods

func Observations

method on ObservationState
1func (os *ObservationState) Observations() map[uint16]*Observation
source

func SetCardinality

method on ObservationState
1func (os *ObservationState) SetCardinality(cardinality uint16)
source

func SetCardinalityNext

method on ObservationState
1func (os *ObservationState) SetCardinalityNext(cardinalityNext uint16)
source

func SetIndex

method on ObservationState
1func (os *ObservationState) SetIndex(index uint16)
source

ObservationState Setters methods

func SetObservation

method on ObservationState
1func (os *ObservationState) SetObservation(index uint16, observation *Observation)
source

func SetObservations

method on ObservationState
1func (os *ObservationState) SetObservations(observations map[uint16]*Observation)
source

type 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}
source

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 Balances

method on Pool
1func (p *Pool) Balances() TokenPair
source

func Clone

method on Pool
1func (p *Pool) Clone() *Pool
source

func Fee

method on Pool
1func (p *Pool) Fee() uint32
source

func GetTick

method on Pool
1func (p *Pool) GetTick(tick int32) (TickInfo, error)
source

func HasTick

method on Pool
1func (p *Pool) HasTick(tick int32) bool
source

func IterateTicks

method on Pool
1func (p *Pool) IterateTicks(startTick int32, endTick int32, fn func(tick int32, tickInfo TickInfo) bool)
source

func Liquidity

method on Pool
1func (p *Pool) Liquidity() *u256.Uint
source

func PoolPath

method on Pool
1func (p *Pool) PoolPath() string
source

Pool Getters methods

func Positions

method on Pool
1func (p *Pool) Positions() *bptree.BPTree
source

func SetBalances

method on Pool
1func (p *Pool) SetBalances(balances TokenPair)
source

func SetFee

method on Pool
1func (p *Pool) SetFee(fee uint32)
source

func SetLiquidity

method on Pool
1func (p *Pool) SetLiquidity(liquidity *u256.Uint)
source

func SetPosition

method on Pool
1func (p *Pool) SetPosition(posKey string, positionInfo PositionInfo)
source

func SetPositions

method on Pool
1func (p *Pool) SetPositions(positions *bptree.BPTree)
source

func SetSlot0

method on Pool
1func (p *Pool) SetSlot0(slot0 Slot0)
source

func SetTick

method on Pool
1func (p *Pool) SetTick(tick int32, tickInfo TickInfo)
source

func SetTickBitmap

method on Pool
1func (p *Pool) SetTickBitmap(wordPos int16, tickBitmap string)
source

func SetTickBitmaps

method on Pool
1func (p *Pool) SetTickBitmaps(tickBitmaps map[int16]string)
source

func SetTicks

method on Pool
1func (p *Pool) SetTicks(ticks *bptree.BPTree)
source

func SetToken0Path

method on Pool
1func (p *Pool) SetToken0Path(token0Path string)
source

Pool Setters methods

func Slot0

method on Pool
1func (p *Pool) Slot0() Slot0
source

func TickBitmaps

method on Pool
1func (p *Pool) TickBitmaps() map[int16]string
source

func Ticks

method on Pool
1func (p *Pool) Ticks() *bptree.BPTree
source

type 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}
source

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 Liquidity

method on PositionInfo
1func (p *PositionInfo) Liquidity() string
source

func SetLiquidity

method on PositionInfo
1func (p *PositionInfo) SetLiquidity(liquidity string)
source

func SetTokensOwed0

method on PositionInfo
1func (p *PositionInfo) SetTokensOwed0(tokensOwed0 int64)
source

func SetTokensOwed1

method on PositionInfo
1func (p *PositionInfo) SetTokensOwed1(tokensOwed1 int64)
source

func TokensOwed0

method on PositionInfo
1func (p *PositionInfo) TokensOwed0() int64
source

func TokensOwed1

method on PositionInfo
1func (p *PositionInfo) TokensOwed1() int64
source

type Slot0

struct
1type 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}
source

Methods on Slot0

func SetTick

method on Slot0
1func (s *Slot0) SetTick(tick int32)
source

func SetUnlocked

method on Slot0
1func (s *Slot0) SetUnlocked(unlocked bool)
source

func Tick

method on Slot0
1func (s *Slot0) Tick() int32
source

func Unlocked

method on Slot0
1func (s *Slot0) Unlocked() bool
source

type StoreKey

ident
1type StoreKey string
source

StoreKey defines the keys used for storing pool data in the KV store. These keys are prefixed with the domain address to ensure namespace isolation.

Methods on StoreKey

func String

method on StoreKey
1func (s StoreKey) String() string
source

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}
source

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 TickInfo
1func (t *TickInfo) Clone() TickInfo
source

func LiquidityGross

method on TickInfo
1func (t *TickInfo) LiquidityGross() string
source

TickInfo Getters methods

func SetInitialized

method on TickInfo
1func (t *TickInfo) SetInitialized(initialized bool)
source

func SetLiquidityGross

method on TickInfo
1func (t *TickInfo) SetLiquidityGross(liquidityGross string)
source

TickInfo Setters methods

func SetLiquidityNet

method on TickInfo
1func (t *TickInfo) SetLiquidityNet(liquidityNet string)
source

type TokenPair

struct
1type TokenPair struct {
2	token0, token1 int64
3}
source

Methods on TokenPair

func SetToken0

method on TokenPair
1func (p *TokenPair) SetToken0(token0 int64)
source

func SetToken1

method on TokenPair
1func (p *TokenPair) SetToken1(token1 int64)
source

func Token0

method on TokenPair
1func (p *TokenPair) Token0() int64
source

func Token1

method on TokenPair
1func (p *TokenPair) Token1() int64
source

Imports 11

Source Files 12