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.
Gnoweb
The root Render("") delegates to the active implementation and shows realm identity, halt flags, stored pool count, creation and withdrawal fees, the four fee tiers and tick spacings, and separate token0/token1 protocol-fee denominators.
GNS creation fees use six-decimal base units; withdrawal fees use basis points and swap fee tiers use pips. Rendering reads stored counts and fixed configuration without traversing pools. Unsupported paths return 404.
Configuration
- Pool Creation Fee: 100 GNS (default)
- Protocol Fee: Disabled (0) or a denominator of 4-10, routing 1/4 to 1/10 of swap fees to the protocol
- Withdrawal Fee: 1% on fee-bearing collection (configurable)
- Fee Tiers: 0.01%, 0.05%, 0.3%, 1%
- Tick Spacing: Auto-set by fee tier
- Max Liquidity Per Tick: Depends on tick spacing; use
GetMaxLiquidityPerTickrather than2^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 a new trading pair.
- Requires 100 GNS creation fee by default
- Valid fee tier required
- Accepts either token path order and canonicalizes token0/token1
- If paths are reversed, the initial square-root price is inverted
- Initial
sqrtPriceX96must be in[MIN_SQRT_RATIO, MAX_SQRT_RATIO) - Does not compare the initial price with an oracle or external market price
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.
- Pool-level operation: burn first, then collect owed tokens
- Calculates owed principal
- Updates position state
Collect
Pays tokens owed by a pool position without a withdrawal fee. This fee-free
path is normally used for principal after Burn.
- Transfers the requested portion of
tokensOwed - Updates
tokensOwed
CollectSwapFee
Pays accrued swap fees through the fee-bearing collection path.
- Applies the configured withdrawal fee
- Returns gross collected amounts and the fee withheld
Position.DecreaseLiquidityandPosition.CollectFeeinvoke the appropriate pool paths internally
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 swapCallback(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, _ *pool.CallbackMarker) error {
2 caller := cur.Previous().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(0, cur, token0Path, poolAddr, amount0Delta)
13 }
14 if amount1Delta > 0 {
15 // Transfer token1 to pool
16 common.SafeGRC20Transfer(0, cur, token1Path, poolAddr, amount1Delta)
17 }
18 return nil
19}
Important Notes:
- A custom callback should verify that the caller is the legitimate pool.
- In the router flow, the supplied closure performs that pool-origin check
before calling
router.SwapCallback; the Router implementation then checks that its caller is Router v1. - 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 the 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
Range Liquidity:
Liquidity is calculated from the token required by the current price:
- Below the range (
current < lower): token0 only - In the range (
lower <= current < upper): both token0 and token1 - Above the range (
current >= upper): token1 only
The integer formulas use the square-root prices and round in the direction
required by the mint or burn operation; there is no single amount formula
that applies to all three cases.
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:
0disables protocol fee collection4through10are denominators:4routes 25% and10routes 10% of swap fees to the protocol- Governance-managed configuration applies to the pool set, not an independent percentage selected on each pool
Security
Reentrancy Protection
- The live guard is the pool-wide
Unlockedkey in the pool KV store, managed bypool/v1/lock.gno.Slot0.unlockedis a separate stored field and is not the guard;GetSlot0Unlockedreports that field, not the live lock. - The lock is not swap-specific.
CreatePool,Mint,Burn,Collect,CollectSwapFee,CollectProtocol,SetFeeProtocol,SetWithdrawalFee,SetPoolCreationFee,IncreaseObservationCardinalityNext,SetSwapStartHook,SetSwapEndHook,SetTickCrossHook,Swap, and the read-onlyDrySwapall assert that the pool is unlocked before doing any work. - The unlocked assertion is read-only and runs before the access checks, so a call that aborts on authorization leaves no persisted lock behind.
- Settlement order is operation-specific rather than uniformly
checks-effects-interactions.
Swapsettles optimistically through the callback and verifies the resulting balance increase afterwards, whileMintpulls tokens before its final pool save. Review the specific path rather than assuming every write precedes every external call.
Price Manipulation
- TWAP oracle provides time-weighted observations for monitoring; it is not an automatic initial-price guard
- Large swaps limited by liquidity
- Slippage protection required
Pool Creation Griefing
Issue: CreatePool validates the fee tier, token canonicalization, and
square-root price bounds, but does not compare the initial price with an
oracle or external market price. A pool can therefore be created at an
economically inappropriate extreme price.
Impact:
- Pool may be temporarily unusable
- No rational LP may provide liquidity at a distorted price
- Price cannot self-correct without liquidity
Recovery Mechanism: Recovery requires coordinated liquidity provision and swaps to move the price toward a desired market rate, followed by liquidity removal. The protocol does not perform this correction automatically, and profitability depends on market conditions, fees, and slippage.
Example Recovery Sequence:
This pseudocode assumes the integrating realm function has a current cur token.
// Illustrative sequence; the caller must compose and execute these operations
1. position.Mint(cross(cur), ..., fullRange, largeAmount, ...) // Add liquidity
2. router.ExactInSwapRoute(cross(cur), ..., targetRoute, ...) // Fix price via arbitrage
3. position.DecreaseLiquidity(cross(cur), positionId, ...) // Remove liquidity and collect principal
4. position.CollectFee(cross(cur), positionId) // Collect any remaining fees
Prevention:
- 100 GNS creation fee provides deterrent
- Consider implementing price oracle validation for high-value pairs
- Monitor pool creation events for suspicious activity
Rounding
- Integer math rounds directionally for the input/output invariant; not every division rounds down
- Minimum liquidity enforced
- Full precision for amounts
3
const MAX_TICK
const StoreKeyPools, StoreKeyObservations, StoreKeyFeeAmountTickSpacing, StoreKeySlot0FeeProtocol, StoreKeyPoolCreationFee, StoreKeyPendingProtocolFees, StoreKeyWithdrawalFeeBPS, StoreKeyUnlocked, StoreKeySwapStartHook, StoreKeySwapEndHook, StoreKeyTickCrossHook
1const (
2 // Pool data storage keys
3 StoreKeyPools StoreKey = "pools" // Map containing all pools
4 StoreKeyObservations StoreKey = "observations" // poolPath -> observation B+tree
5 StoreKeyFeeAmountTickSpacing StoreKey = "feeAmountTickSpacing" // Fee tier to tick spacing mapping
6 StoreKeySlot0FeeProtocol StoreKey = "slot0FeeProtocol" // Protocol fee denominator(s)
7
8 // Protocol fee storage keys
9 StoreKeyPoolCreationFee StoreKey = "poolCreationFee" // Pool creation fee amount
10 StoreKeyPendingProtocolFees StoreKey = "pendingProtocolFees" // tokenPath -> amount held locally for protocol_fee
11 StoreKeyWithdrawalFeeBPS StoreKey = "withdrawalFeeBPS" // Withdrawal fee in basis points
12 StoreKeyUnlocked StoreKey = "unlocked" // Global pool reentrancy lock
13
14 // Swap hook storage keys
15 StoreKeySwapStartHook StoreKey = "swapStartHook" // Swap start hook function
16 StoreKeySwapEndHook StoreKey = "swapEndHook" // Swap end hook function
17 StoreKeyTickCrossHook StoreKey = "tickCrossHook" // Tick cross hook function
18)90
func Burn
crossing ActionBurn removes liquidity from a position.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- token0Path: Path of the first token in the pool pair.
- token1Path: Path of the second token in the pool pair.
- fee: Fee tier identifying the pool.
- tickLower: Lower inclusive tick boundary of the position range.
- tickUpper: Upper exclusive tick boundary of the position range.
- liquidityAmount: Decimal liquidity amount to remove from the position.
- positionCaller: Position-contract address whose position is decreased.
Returns:
- amount0: Token0 principal credited to the position, as a decimal string; the pool operation leaves it owed until a subsequent collection.
- amount1: Token1 principal credited to the position, as a decimal string; the pool operation leaves it owed until a subsequent collection.
Halt check: reverts while the Withdraw halt scope is active.
func Collect
crossing ActionCollect pays tokens owed to a position out to recipient in full. No withdrawal fee is charged on this path; see CollectSwapFee for the fee-bearing path.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- token0Path: Path of the first token in the pool pair.
- token1Path: Path of the second token in the pool pair.
- fee: Fee tier identifying the pool.
- recipient: Non-zero address receiving the owed token amounts.
- tickLower: Lower inclusive tick boundary of the position range.
- tickUpper: Upper exclusive tick boundary of the position range.
- amount0Requested: Decimal token0 amount requested from the position's accrued principal.
- amount1Requested: Decimal token1 amount requested from the position's accrued principal.
Returns:
- amount0: Token0 principal transferred to recipient, as a decimal string.
- amount1: Token1 principal transferred to recipient, as a decimal string.
Halt check: reverts while the Withdraw halt scope is active.
func CollectProtocol
crossing ActionCollectProtocol collects protocol fees from a pool.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- token0Path: Path of the first token in the pool pair.
- token1Path: Path of the second token in the pool pair.
- fee: Fee tier identifying the pool.
- recipient: Address receiving the collected protocol fees.
- amount0Requested: Decimal token0 protocol-fee amount requested; collection is capped at the available amount.
- amount1Requested: Decimal token1 protocol-fee amount requested; collection is capped at the available amount.
Returns:
- amount0: Token0 protocol fee transferred to recipient, as a decimal string.
- amount1: Token1 protocol fee transferred to recipient, as a decimal string.
Halt check: reverts while the Withdraw halt scope is active.
func CollectSwapFee
crossing ActionCollectSwapFee pays accrued swap fees for a position out to recipient, net of the withdrawal fee.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- token0Path: Path of the first token in the pool pair.
- token1Path: Path of the second token in the pool pair.
- fee: Fee tier identifying the pool.
- recipient: Non-zero address receiving the collected token amounts after withdrawal-fee deduction.
- tickLower: Lower inclusive tick boundary of the position range.
- tickUpper: Upper exclusive tick boundary of the position range.
- amount0Requested: Decimal token0 amount requested; the configured maximum value requests all token0 fees owed.
- amount1Requested: Decimal token1 amount requested; the configured maximum value requests all token1 fees owed.
Returns:
- amount0: Collected token0 amount before withdrawal-fee deduction, as a decimal string.
- amount1: Collected token1 amount before withdrawal-fee deduction, as a decimal string.
- fee0: Withdrawal fee withheld from token0, as a decimal string.
- fee1: Withdrawal fee withheld from token1, as a decimal string.
Halt check: reverts while the Withdraw halt scope is active.
func CreatePool
crossing ActionCreatePool creates a new liquidity pool for a token pair.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- token0Path: Token contract path supplied for token0; the pool orders the pair canonically rather than preserving the supplied order.
- token1Path: Token contract path supplied for token1; must form a distinct registered pair with token0Path.
- fee: Fee tier for the pool; determines its tick spacing and swap fee.
- sqrtPriceX96: Initial square-root price in Q64.96 fixed-point form; it is inverted when the supplied token order is reversed and must be in bounds.
Halt check: reverts while the Pool halt scope is active.
func DecodeTickKey
ActionDecodeTickKey decodes a fixed-width ordered tick key. Parameters:
- key: fixed-width ordered tick key produced by EncodeTickKey.
Returns:
- tick: signed tick index decoded from key.
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 in the pool pair.
- token1Path: Path of the second token in the pool pair.
- fee: Fee tier identifying the pool.
- zeroForOne: True to sell token0 for token1; false to sell token1 for token0.
- amountSpecified: Decimal signed amount; positive requests exact input and negative requests exact output.
- sqrtPriceLimitX96: Price boundary in Q64.96 fixed-point form at which the simulation must stop.
Returns:
- amount0: Simulated signed token0 delta, as a decimal string; "0" on an unsuccessful simulation.
- amount1: Simulated signed token1 delta, as a decimal string; "0" on an unsuccessful simulation.
- error: Nil when the simulation succeeds; non-nil when validation, computation, or pool-balance checks fail.
func EncodePositionKey
ActionEncodePositionKey encodes a position range as two ordered tick keys. Parameters:
- tickLower: lower signed tick index of the position range.
- tickUpper: upper signed tick index of the position range.
Returns:
- key: concatenation of the ordered encodings of tickLower and tickUpper.
func EncodeTickKey
ActionEncodeTickKey encodes a tick as a fixed-width 4-byte key whose lexicographic order matches the signed numeric order. Parameters:
- tick: signed tick index to encode.
Returns:
- key: fixed-width ordered key whose lexicographical ordering matches the signed numeric ordering of tick.
func ExistsPoolPath
ActionExistsPoolPath checks if a pool exists at the given path. Parameters:
- poolPath: Canonical pool path identifying the pool to check.
Returns:
- bool: True when a pool is registered at poolPath; false otherwise.
func GetBalanceToken0
ActionGetBalanceToken0 returns the balance of token0 in the pool. Parameters:
- poolPath: Canonical pool path identifying the pool to query.
Returns:
- int64: Current token0 balance held by the pool, in token base units.
- error: Non-nil when poolPath does not identify an existing pool.
func GetBalanceToken1
ActionGetBalanceToken1 returns the balance of token1 in the pool. Parameters:
- poolPath: Canonical pool path identifying the pool to query.
Returns:
- int64: Current token1 balance held by the pool, in token base units.
- error: Non-nil when poolPath does not identify an existing pool.
func GetBalances
ActionGetBalances returns the balances of the pool. Parameters:
- poolPath: Canonical pool path identifying the pool whose balances are read.
Returns:
- int64: Current token0 balance held by the pool, in token base units.
- int64: Current token1 balance held by the pool, in token base units.
- error: Non-nil when poolPath does not identify an existing pool.
func GetFee
ActionGetFee returns the fee tier of the pool. Parameters:
- poolPath: Canonical pool path identifying the pool whose fee tier is read.
Returns:
- uint32: Configured fee tier for the pool.
- error: Non-nil when poolPath does not identify an existing pool.
func GetFeeAmountTickSpacing
ActionGetFeeAmountTickSpacing returns the tick spacing for a given fee tier. Parameters:
- fee: Fee tier whose supported tick spacing is requested.
Returns:
- spacing: Tick spacing configured for fee.
- err: Non-nil when fee is not one of the supported fee tiers.
func GetFeeAmountTickSpacings
ActionGetFeeAmountTickSpacings returns all fee tier to tick spacing mappings. Returns:
- map[uint32]int32: Copy of the configured fee-tier-to-tick-spacing mapping.
func GetFeeGrowthGlobal0X128
ActionGetFeeGrowthGlobal0X128 returns the global fee growth for token0. Parameters:
- poolPath: Canonical pool path identifying the pool to query.
Returns:
- string: Token0 global fee growth, serialized as a base-10 X128 accumulator.
- error: Non-nil when poolPath does not identify an existing pool.
func GetFeeGrowthGlobal1X128
ActionGetFeeGrowthGlobal1X128 returns the global fee growth for token1. Parameters:
- poolPath: Canonical pool path identifying the pool to query.
Returns:
- string: Token1 global fee growth, serialized as a base-10 X128 accumulator.
- error: Non-nil when poolPath does not identify an existing pool.
func GetFeeGrowthGlobalX128
ActionGetFeeGrowthGlobalX128 returns the global fee growth for both tokens. Parameters:
- poolPath: Canonical pool path identifying the pool to query.
Returns:
- string: Token0 global fee growth, serialized as a base-10 X128 accumulator.
- string: Token1 global fee growth, serialized as a base-10 X128 accumulator.
- error: Non-nil when poolPath does not identify an existing pool.
func GetImplementationPackagePath
ActionGetImplementationPackagePath returns the package path of the currently active implementation.
Returns:
- packagePath: Full package path of the active implementation; empty before any version has been registered.
func GetInitializedTicksInRange
Action1func GetInitializedTicksInRange(poolPath string, tickLower, tickUpper int32) ([]int32, error)GetInitializedTicksInRange returns initialized ticks within the given range. Parameters:
- poolPath: Canonical pool path whose ticks are enumerated.
- tickLower: Lower inclusive tick bound for enumeration.
- tickUpper: Upper bound for enumeration; ticks are selected through the pool's range iterator.
Returns:
- []int32: Tick indices that are initialized in the requested range.
- error: Non-nil when poolPath does not identify an existing pool.
func GetLiquidity
ActionGetLiquidity returns the current liquidity in the pool. Parameters:
- poolPath: Canonical pool path identifying the pool whose liquidity is read.
Returns:
- string: Current pool liquidity, serialized as a base-10 unsigned integer.
- error: Non-nil when poolPath does not identify an existing pool.
func GetPendingProtocolFees
ActionGetPendingProtocolFees returns the pending protocol fee amount per token path. Returns:
- map[string]int64: Copy of pending protocol fees keyed by token contract path, with amounts in token base units.
func GetPoolCreationFee
ActionGetPoolCreationFee returns the current pool creation fee. Returns:
- int64: Pool creation fee charged when a new pool is created, in configured native-token base units.
func GetPoolPath
ActionGetPoolPath generates a unique pool path string based on the token paths and fee tier. Parameters:
- token0Path: path of the first token contract; it is reordered with token1Path when needed to form canonical pool order.
- token1Path: path of the second token contract; it is reordered with token0Path when it sorts earlier.
- fee: pool fee tier encoded as its decimal uint32 value in the path.
Returns:
- poolPath: canonical token0:token1:fee identifier with token paths in lexicographical order.
func GetPoolPositions
ActionGetPoolPositions returns a read-only view of a pool's positions, keyed by position key. nil is returned when the pool does not exist. Parameters:
- poolPath: Canonical pool path identifying the pool whose positions are read.
Returns:
- *rotree.ReadOnlyTree: Read-only tree keyed by position key; nil when the pool does not exist.
func GetPools
ActionGetPools returns a read-only view of every pool, keyed by pool path. Reading an entry yields a clone, so the view cannot mutate realm state. Returns:
- *rotree.ReadOnlyTree: Read-only tree keyed by canonical pool path; each entry is cloned before it is exposed.
func GetPositionFeeGrowthInside0LastX128
ActionGetPositionFeeGrowthInside0LastX128 returns the last recorded fee growth inside for token0. Parameters:
- poolPath: Canonical pool path identifying the pool containing the position.
- key: Position key identifying the position within the pool.
Returns:
- string: Position's last token0 fee-growth-inside accumulator, serialized as a base-10 X128 value.
- error: Non-nil when the pool or position key cannot be found.
func GetPositionFeeGrowthInside1LastX128
ActionGetPositionFeeGrowthInside1LastX128 returns the last recorded fee growth inside for token1. Parameters:
- poolPath: Canonical pool path identifying the pool containing the position.
- key: Position key identifying the position within the pool.
Returns:
- string: Position's last token1 fee-growth-inside accumulator, serialized as a base-10 X128 value.
- error: Non-nil when the pool or position key cannot be found.
func GetPositionFeeGrowthInsideLastX128
ActionGetPositionFeeGrowthInsideLastX128 returns the last recorded fee growth inside for both tokens. Parameters:
- poolPath: Canonical pool path identifying the pool containing the position.
- key: Position key identifying the position within the pool.
Returns:
- string: Position's last token0 fee-growth-inside accumulator, serialized as a base-10 X128 value.
- string: Position's last token1 fee-growth-inside accumulator, serialized as a base-10 X128 value.
- error: Non-nil when the pool or position key cannot be found.
func GetPositionLiquidity
ActionGetPositionLiquidity returns the liquidity of a position. Parameters:
- poolPath: Canonical pool path identifying the pool containing the position.
- key: Position key identifying the position within the pool.
Returns:
- string: Position liquidity, serialized as a base-10 unsigned integer.
- error: Non-nil when the pool or position key cannot be found.
func GetPositionTokensOwed
ActionGetPositionTokensOwedInfos returns the amount of tokens owed for both tokens. Parameters:
- poolPath: Canonical pool path identifying the pool containing the position.
- key: Position key identifying the position within the pool.
Returns:
- int64: Amount of token0 owed to the position, in token base units.
- int64: Amount of token1 owed to the position, in token base units.
- error: Non-nil when the pool or position key cannot be found.
func GetPositionTokensOwed0
ActionGetPositionTokensOwed0 returns the amount of token0 owed to a position. Parameters:
- poolPath: Canonical pool path identifying the pool containing the position.
- key: Position key identifying the position within the pool.
Returns:
- int64: Amount of token0 owed to the position, in token base units.
- error: Non-nil when the pool or position key cannot be found.
func GetPositionTokensOwed1
ActionGetPositionTokensOwed1 returns the amount of token1 owed to a position. Parameters:
- poolPath: Canonical pool path identifying the pool containing the position.
- key: Position key identifying the position within the pool.
Returns:
- int64: Amount of token1 owed to the position, in token base units.
- error: Non-nil when the pool or position key cannot be found.
func GetProtocolFeesToken0
ActionGetProtocolFeesToken0 returns accumulated protocol fees for token0. Parameters:
- poolPath: Canonical pool path identifying the pool whose fees are read.
Returns:
- int64: Accumulated protocol fee for token0, in token base units.
- error: Non-nil when poolPath does not identify an existing pool.
func GetProtocolFeesToken1
ActionGetProtocolFeesToken1 returns accumulated protocol fees for token1. Parameters:
- poolPath: Canonical pool path identifying the pool whose fees are read.
Returns:
- int64: Accumulated protocol fee for token1, in token base units.
- error: Non-nil when poolPath does not identify an existing pool.
func GetProtocolFeesTokens
ActionGetProtocolFeesTokens returns the accumulated protocol fees for both tokens. Parameters:
- poolPath: Canonical pool path identifying the pool whose fees are read.
Returns:
- int64: Accumulated protocol fee for token0, in token base units.
- int64: Accumulated protocol fee for token1, in token base units.
- error: Non-nil when poolPath does not identify an existing pool.
func GetSlot0FeeProtocol
ActionGetSlot0FeeProtocol returns the protocol fee rate from slot0. Parameters:
- poolPath: Canonical pool path identifying the pool to query.
Returns:
- uint8: Packed protocol-fee denominator configuration from slot0; token0 occupies the low nibble and token1 the high nibble.
- error: Non-nil when poolPath does not identify an existing pool.
func GetSlot0SqrtPriceX96
ActionGetSlot0SqrtPriceX96 returns the current sqrt price from slot0. Parameters:
- poolPath: Canonical pool path identifying the pool to query.
Returns:
- string: Current square-root price in Q64.96 fixed-point form, serialized as a base-10 unsigned integer.
- error: Non-nil when poolPath does not identify an existing pool.
func GetSlot0Tick
ActionGetSlot0Tick returns the current tick from slot0. Parameters:
- poolPath: Canonical pool path identifying the pool to query.
Returns:
- int32: Current active tick index stored in slot0.
- error: Non-nil when poolPath does not identify an existing pool.
func GetSlot0Unlocked
ActionGetSlot0Unlocked reports whether the pool is currently unlocked. Parameters:
- poolPath: Canonical pool path identifying the pool to query.
Returns:
- bool: True when the pool is not holding its reentrancy lock; false when the pool is currently locked.
- error: Non-nil when poolPath does not identify an existing pool.
func GetTickBitmaps
ActionGetTickBitmaps returns the tick bitmap for a given word position. Parameters:
- poolPath: Canonical pool path identifying the pool containing the bitmap.
- wordPos: Signed bitmap word position to read.
Returns:
- string: Bitmap word serialized as a base-10 unsigned integer.
- error: Non-nil when the pool or bitmap word is not found.
func GetTickCumulativeOutside
ActionGetTickCumulativeOutside returns the tick cumulative value outside a tick. Parameters:
- poolPath: Canonical pool path identifying the pool containing the tick.
- tick: Tick index whose outside tick cumulative is requested.
Returns:
- int64: Tick cumulative recorded outside tick.
- error: Non-nil when the pool or tick is not found.
func GetTickFeeGrowthOutside0X128
ActionGetTickFeeGrowthOutside0X128 returns fee growth outside for token0 at a tick. Parameters:
- poolPath: Canonical pool path identifying the pool containing the tick.
- tick: Tick index whose outside fee growth is requested.
Returns:
- string: Token0 fee growth outside tick, serialized as a base-10 X128 accumulator.
- error: Non-nil when the pool or tick is not found.
func GetTickFeeGrowthOutside1X128
ActionGetTickFeeGrowthOutside1X128 returns fee growth outside for token1 at a tick. Parameters:
- poolPath: Canonical pool path identifying the pool containing the tick.
- tick: Tick index whose outside fee growth is requested.
Returns:
- string: Token1 fee growth outside tick, serialized as a base-10 X128 accumulator.
- error: Non-nil when the pool or tick is not found.
func GetTickFeeGrowthOutsideX128
ActionGetTickFeeGrowthOutsideX128 returns fee growth outside for both tokens at a tick. Parameters:
- poolPath: Canonical pool path identifying the pool containing the tick.
- tick: Tick index whose outside fee growth is requested.
Returns:
- string: Token0 fee growth outside tick, serialized as a base-10 X128 accumulator.
- string: Token1 fee growth outside tick, serialized as a base-10 X128 accumulator.
- error: Non-nil when the pool or tick is not found.
func GetTickInitialized
ActionGetTickInitialized returns whether a tick is initialized. Parameters:
- poolPath: Canonical pool path identifying the pool containing the tick.
- tick: Tick index whose initialization flag is requested.
Returns:
- bool: True when the tick has initialized liquidity and outside accumulators.
- error: Non-nil when the pool or tick is not found.
func GetTickLiquidityGross
ActionGetTickLiquidityGross returns the total liquidity that references a tick. Parameters:
- poolPath: Canonical pool path identifying the pool containing the tick.
- tick: Tick index whose gross liquidity is requested.
Returns:
- string: Gross liquidity referencing the tick, serialized as a base-10 unsigned integer.
- error: Non-nil when the pool or tick is not found.
func GetTickLiquidityNet
ActionGetTickLiquidityNet returns the net liquidity change at a tick. Parameters:
- poolPath: Canonical pool path identifying the pool containing the tick.
- tick: Tick index whose net liquidity change is requested.
Returns:
- string: Signed net liquidity change at the tick, serialized as a base-10 integer.
- error: Non-nil when the pool or tick is not found.
func GetTickSecondsOutside
ActionGetTickSecondsOutside returns seconds spent outside a tick. Parameters:
- poolPath: Canonical pool path identifying the pool containing the tick.
- tick: Tick index whose outside time is requested.
Returns:
- uint32: Seconds accumulated outside the tick.
- error: Non-nil when the pool or tick is not found.
func GetTickSecondsPerLiquidityOutsideX128
ActionGetTickSecondsPerLiquidityOutsideX128 returns seconds per liquidity outside a tick. Parameters:
- poolPath: Canonical pool path identifying the pool containing the tick.
- tick: Tick index whose outside accumulator is requested.
Returns:
- string: Seconds-per-liquidity outside tick in X128 precision, serialized as a base-10 unsigned integer.
- error: Non-nil when the pool or tick is not found.
func GetTickSpacing
ActionGetTickSpacing returns the tick spacing of the pool. Parameters:
- poolPath: Canonical pool path identifying the pool whose spacing is read.
Returns:
- int32: Tick spacing associated with the pool's fee tier.
- error: Non-nil when poolPath does not identify an existing pool.
func GetToken0Path
ActionGetToken0Path returns the path of token0 in the pool. Parameters:
- poolPath: Canonical pool path identifying the pool to query.
Returns:
- string: Canonical token0 contract path stored by the pool.
- error: Non-nil when poolPath does not identify an existing pool.
func GetToken1Path
ActionGetToken1Path returns the path of token1 in the pool. Parameters:
- poolPath: Canonical pool path identifying the pool to query.
Returns:
- string: Canonical token1 contract path stored by the pool.
- error: Non-nil when poolPath does not identify an existing pool.
func GetWithdrawalFee
ActionGetWithdrawalFee returns the current withdrawal fee rate. Returns:
- uint64: Withdrawal fee rate in basis points; zero means no withdrawal fee is charged.
func IncreaseObservationCardinalityNext
crossing ActionIncreaseObservationCardinalityNext increases the observation cardinality for a pool.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- token0Path: Path of the first token in the pool pair.
- token1Path: Path of the second token in the pool pair.
- fee: Fee tier identifying the pool.
- cardinalityNext: Requested maximum number of oracle observations retained for the pool.
Halt check: reverts while the Pool halt scope is active.
func Mint
crossing ActionMint adds liquidity to a position.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- token0Path: Path of the first token in the pool pair.
- token1Path: Path of the second token in the pool pair.
- fee: Fee tier identifying the pool.
- tickLower: Lower inclusive tick boundary of the position range.
- tickUpper: Upper exclusive tick boundary of the position range.
- liquidityAmount: Decimal liquidity amount to add to the position.
- positionCaller: Position-contract address whose position receives the liquidity.
Returns:
- amount0: Token0 amount required for the liquidity addition, as a decimal string.
- amount1: Token1 amount required for the liquidity addition, as a decimal string.
Halt check: reverts while the Pool halt scope is active.
func NewDefaultFeeAmountTickSpacing
ActionNewDefaultFeeAmountTickSpacing returns the default tick spacing for each supported fee tier.
Returns:
- map[uint32]int32: fee-tier to tick-spacing mapping for 100, 500, 3000, and 10000 tiers.
func NewObservationsTree
ActionNewObservationsTree creates the top-level B+tree that indexes pool observation trees by pool path.
Returns:
- tree: Empty B+tree suitable for storing pool-path observation trees.
func 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.
Returns:
- *bptree.BPTree: empty position storage tree with fanout 16.
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.
Returns:
- *bptree.BPTree: empty tick storage tree with fanout 32.
func NewPoolsTree
ActionNewPoolsTree creates the BPTree used to store pools by pool path.
Returns:
- *bptree.BPTree: empty pool storage tree with fanout 32.
func Observe
ActionObserve returns the tick and seconds-per-liquidity cumulatives for each requested lookback, matching Uniswap V3's observe(uint32[] secondsAgos). Parameters:
- poolPath: Canonical pool path whose oracle history is queried.
- secondsAgos: Lookback intervals in seconds; one cumulative pair is returned for each value, in the same order.
Returns:
- []int64: Tick cumulative values corresponding to each requested lookback.
- []string: Seconds-per-liquidity cumulative X128 values, serialized as base-10 strings, corresponding to each lookback.
- error: Non-nil when pool or observation data cannot be read.
func OracleConsult
ActionOracleConsult returns the arithmetic mean tick and harmonic mean liquidity over a lookback, following Uniswap V3 OracleLibrary's consult convention. Parameters:
- poolPath: Canonical pool path whose oracle data is queried.
- secondsAgo: Lookback duration in seconds used to compute the time-weighted values.
Returns:
- int32: Arithmetic mean tick over the requested lookback.
- string: Harmonic mean liquidity over the lookback, serialized as a base-10 unsigned integer.
- error: Non-nil when the pool or required observation history is unavailable.
func 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.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- initializer: Version factory receiving the forwarded discriminator, current realm, and shared IPoolStore; it returns the implementation instance to register and later activate.
Security: Only contracts within the domain path can register initializers. Each package path can only register once to prevent duplicate registrations.
func Render
Render delegates web rendering to the active implementation.
func SetFeeProtocol
crossing ActionSetFeeProtocol sets the protocol fee rates for a pool.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- feeProtocol0: Token0 protocol-fee denominator; zero disables it, while non-zero supported values route the corresponding fraction to protocol.
- feeProtocol1: Token1 protocol-fee denominator; zero disables it, while non-zero supported values route the corresponding fraction to protocol.
Halt check: reverts while the Pool halt scope is active.
func SetPoolCreationFee
crossing ActionSetPoolCreationFee sets the pool creation fee.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- fee: New pool creation fee, in the configured native-token base units.
Halt check: reverts while the Pool halt scope is active.
func SetSwapEndHook
crossing ActionSetSwapEndHook sets the hook to be called at the end of a swap.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- hook: Callback invoked with the current realm and pool path after swap settlement; its error is propagated to abort the swap.
func SetSwapStartHook
crossing ActionSetSwapStartHook sets the hook to be called at the start of a swap.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- hook: Callback invoked with the current realm, pool path, and swap timestamp before swap computation.
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.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- hook: Callback invoked with the current realm, pool path, crossed tick index, swap direction, and block timestamp.
func SetWithdrawalFee
crossing ActionSetWithdrawalFee sets the withdrawal fee rate.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- fee: Withdrawal fee in basis points; zero disables the fee.
Halt check: reverts while the Pool halt scope is active.
func SnapshotCumulativesInside
ActionSnapshotCumulativesInside returns the tick, seconds-per-liquidity, and seconds cumulatives accrued while the pool price was inside [tickLower, tickUpper). Both boundary ticks must be initialized.
Snapshots are only comparable across an interval during which a position in the range existed, matching Uniswap V3's snapshotCumulativesInside. Parameters:
- poolPath: Canonical pool path whose oracle snapshot is queried.
- tickLower: Lower inclusive tick boundary of the position range.
- tickUpper: Upper exclusive tick boundary of the position range; both boundary ticks must be initialized.
Returns:
- int64: Tick cumulative accrued while the price was inside the range.
- string: Seconds-per-liquidity-inside X128 accumulator, serialized as a base-10 string.
- uint32: Seconds accrued while the price was inside the range.
- error: Non-nil when the pool, observations, or initialized boundaries are unavailable.
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 swapCallback func(cur realm, amount0Delta, amount1Delta int64, callbackMarker *CallbackMarker) error,
11) (string, string)Swap executes a token swap in the pool.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- token0Path: Path of the first token in the pool pair.
- token1Path: Path of the second token in the pool pair.
- fee: Fee tier identifying the pool.
- recipient: Address receiving output tokens.
- zeroForOne: True to sell token0 for token1; false to sell token1 for token0.
- amountSpecified: Decimal signed amount; positive requests exact input and negative requests exact output.
- sqrtPriceLimitX96: Price boundary in Q64.96 fixed-point form at which the swap must stop.
- swapCallback: Callback invoked with the current realm, signed token deltas, and a callback marker; it must settle the input token and return a non-nil error to abort settlement.
Returns:
- amount0: Signed token0 delta for the swap, as a decimal string.
- amount1: Signed token1 delta for the swap, as a decimal string.
Halt check: reverts while the Pool halt scope is active.
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.
Parameters:
- cur: Current realm context; callers use cross(cur) when crossing into this realm.
- packagePath: Full package path of a version previously registered for this pool domain.
Security: Only admin or governance can perform upgrades. The new implementation must have been previously registered via RegisterInitializer. The pool must not be locked (see assertPoolUnlocked).
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). Returns:
- marker: New marker value allocated in the pool realm for swap-callback validation.
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. Parameters:
- kvStore: KV store used to persist and retrieve pool-domain state.
Returns:
- poolStore: an IPoolStore implementation backed by kvStore.
func DefaultObservation
ActionDefaultObservation returns the zero, uninitialized observation used for an empty slot.
Returns:
- observation: Observation with zero timestamp and accumulators and Initialized false.
func GetObservationAt
ActionGetObservationAt returns a safe copy of the observation stored at index. An in-range but uninitialized slot returns the zero observation, matching Uniswap V3's fixed observation-array getter.
ref: uniswap v3 IUniswapV3PoolState.observations(uint256 index) Parameters:
- poolPath: Canonical pool path identifying the pool containing the observation.
- index: Zero-based observation-array index; values at or above the fixed cardinality bound return an error.
Returns:
- Observation: Observation at index, or the zero observation when the slot is in range but has never been written.
- error: Non-nil when the pool is missing or index is out of range.
func MakeObservation
ActionMakeObservation constructs an observation from its stored oracle accumulators.
Parameters:
- blockTimestamp: Timestamp associated with the observation.
- tickCumulative: Signed cumulative tick at blockTimestamp.
- secondsPerLiquidityCumulativeX128: Decimal Q128-scaled cumulative seconds-per-liquidity value.
- initialized: Whether this observation slot is initialized and usable.
Returns:
- observation: Observation containing the supplied timestamp, accumulators, and initialization flag.
func NewObservationTree
ActionNewObservationTree creates an empty pool-local observation tree keyed by uint16 index.
Returns:
- tree: Initialized observation tree ready for Get, Set, and Has operations.
func NewPoolObservationsTree
ActionNewPoolObservationsTree creates a circular observation buffer with slot zero initialized.
Parameters:
- currentTime: Timestamp assigned to the initial observation at index zero.
Returns:
- tree: Observation tree containing an initialized zero-index observation with zero cumulative values.
func NewPool
ActionNewPool constructs a pool with the supplied token pair, fee, price, and tick configuration.
Parameters:
- token0Path: path of the pool's token0 asset.
- token1Path: path of the pool's token1 asset.
- fee: fee tier used by swaps.
- sqrtPriceX96: initial sqrt(token1/token0) price scaled by 2^96.
- tickSpacing: spacing between initialized ticks.
- tick: initial current tick.
- slot0FeeProtocol: packed protocol-fee denominator configuration for slot0.
Returns:
- *Pool: initialized pool with empty balances, fee growth, ticks, bitmaps, and positions.
func NewDefaultPositionInfo
ActionNewDefaultPositionInfo returns the zero-accounting position state used for a new pool position.
Returns:
- info: Position info with zero liquidity, zero fee-growth checkpoints, and no tokens owed.
func NewPositionInfo
ActionNewPositionInfo creates a zeroed position state for a tick range.
Returns:
- PositionInfo: position with zero liquidity, fee-growth checkpoints, and owed tokens.
func GetSlot0
ActionGetSlot0 returns a safe copy of the pool's slot0 (sqrt price, tick, protocol fee, lock state, and oracle cursor/capacity metadata). The clone happens here, at the proxy boundary, so every implementation version can return its internal Slot0 by value without each one having to remember to defend against callers mutating the shared sqrtPriceX96. Parameters:
- poolPath: Canonical pool path identifying the pool to query.
Returns:
- Slot0: Copy of the pool's slot0 state, including price, tick, protocol fee, lock, and observation metadata; panics if the pool is missing.
func NewSlot0
ActionNewSlot0 constructs slot0 with the supplied price, tick, protocol fee, and lock state. Observation metadata starts with index zero and cardinality one.
Parameters:
- sqrtPriceX96: initial sqrt(token1/token0) price scaled by 2^96.
- tick: initial current pool tick.
- feeProtocol: packed token0/token1 protocol-fee denominator configuration.
- unlocked: initial reentrancy-lock state.
Returns:
- Slot0: initialized slot0 value with one observation slot.
func GetTickInfo
ActionGetTickInfo returns the tick info for a given tick. Parameters:
- poolPath: Canonical pool path identifying the pool containing the tick.
- tick: Tick index whose complete state is requested.
Returns:
- TickInfo: Safe copy of the requested tick's liquidity and oracle/fee accumulator fields.
- error: Non-nil when the pool or tick is not found.
func NewTickInfo
ActionNewTickInfo creates an uninitialized tick state with zero accumulators.
Returns:
- TickInfo: default tick state with all numeric fields zero and Initialized false.
func NewTokenPair
ActionNewTokenPair creates a token-pair balance value initialized to zero.
Returns:
- TokenPair: zero token0 and token1 balances.
16
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 // Parameters:
3 // - poolPath: Canonical pool path to test in the pool registry.
4 //
5 // Returns:
6 // - exists: True when a pool is registered at poolPath.
7 ExistsPoolPath(poolPath string) bool
8
9 // Parameters:
10 // - poolPath: Canonical path identifying the pool whose token0 balance is read.
11 //
12 // Returns:
13 // - balanceToken0: Current internal token0 balance recorded for the pool.
14 // - err: Non-nil when poolPath does not identify a registered pool.
15 GetBalanceToken0(poolPath string) (int64, error)
16
17 // Parameters:
18 // - poolPath: Canonical path identifying the pool whose token1 balance is read.
19 //
20 // Returns:
21 // - balanceToken1: Current internal token1 balance recorded for the pool.
22 // - err: Non-nil when poolPath does not identify a registered pool.
23 GetBalanceToken1(poolPath string) (int64, error)
24
25 // Parameters:
26 // - poolPath: Canonical path identifying the pool whose fee tier is read.
27 //
28 // Returns:
29 // - fee: Configured fee tier for the pool.
30 // - err: Non-nil when poolPath does not identify a registered pool.
31 GetFee(poolPath string) (uint32, error)
32
33 // Parameters:
34 // - fee: Fee tier whose configured tick spacing is requested.
35 //
36 // Returns:
37 // - spacing: Tick interval associated with fee.
38 // - err: Non-nil when no tick spacing is configured for fee.
39 GetFeeAmountTickSpacing(fee uint32) (spacing int32, err error)
40
41 // Parameters:
42 // - poolPath: Canonical path identifying the pool whose token0 fee growth is read.
43 //
44 // Returns:
45 // - feeGrowthGlobal0X128: Token0 global fee-growth accumulator scaled by 2^128.
46 // - err: Non-nil when poolPath does not identify a registered pool.
47 GetFeeGrowthGlobal0X128(poolPath string) (*u256.Uint, error)
48
49 // Parameters:
50 // - poolPath: Canonical path identifying the pool whose token1 fee growth is read.
51 //
52 // Returns:
53 // - feeGrowthGlobal1X128: Token1 global fee-growth accumulator scaled by 2^128.
54 // - err: Non-nil when poolPath does not identify a registered pool.
55 GetFeeGrowthGlobal1X128(poolPath string) (*u256.Uint, error)
56
57 // Parameters:
58 // - poolPath: Canonical path identifying the pool whose fee growth is read.
59 //
60 // Returns:
61 // - feeGrowthGlobal0X128: Token0 global fee-growth accumulator scaled by 2^128.
62 // - feeGrowthGlobal1X128: Token1 global fee-growth accumulator scaled by 2^128.
63 // - err: Non-nil when poolPath does not identify a registered pool.
64 GetFeeGrowthGlobalX128(poolPath string) (*u256.Uint, *u256.Uint, error)
65
66 // Parameters:
67 // - poolPath: Canonical path identifying the pool whose active liquidity is read.
68 //
69 // Returns:
70 // - liquidity: Current active liquidity as a u256 value.
71 // - err: Non-nil when poolPath does not identify a registered pool.
72 GetLiquidity(poolPath string) (*u256.Uint, error)
73
74 // Returns:
75 // - pendingProtocolFees: Map from token contract path to pending protocol-fee amount.
76 GetPendingProtocolFees() map[string]int64
77
78 // Returns:
79 // - poolCreationFee: Configured fee amount charged when creating a pool.
80 GetPoolCreationFee() int64
81
82 // Parameters:
83 // - poolPath: Canonical path identifying the pool containing the position.
84 // - key: Encoded position key identifying the position's tick range.
85 //
86 // Returns:
87 // - feeGrowthInside0LastX128: Token0 inside-fee-growth checkpoint as a decimal Q128-scaled string.
88 // - err: Non-nil when poolPath or key cannot be resolved.
89 GetPositionFeeGrowthInside0LastX128(poolPath, key string) (string, error)
90
91 // Parameters:
92 // - poolPath: Canonical path identifying the pool containing the position.
93 // - key: Encoded position key identifying the position's tick range.
94 //
95 // Returns:
96 // - feeGrowthInside1LastX128: Token1 inside-fee-growth checkpoint as a decimal Q128-scaled string.
97 // - err: Non-nil when poolPath or key cannot be resolved.
98 GetPositionFeeGrowthInside1LastX128(poolPath, key string) (string, error)
99
100 // Parameters:
101 // - poolPath: Canonical path identifying the pool containing the position.
102 // - key: Encoded position key identifying the position's tick range.
103 //
104 // Returns:
105 // - feeGrowthInside0LastX128: Token0 inside-fee-growth checkpoint as a decimal Q128-scaled string.
106 // - feeGrowthInside1LastX128: Token1 inside-fee-growth checkpoint as a decimal Q128-scaled string.
107 // - err: Non-nil when poolPath or key cannot be resolved.
108 GetPositionFeeGrowthInsideLastX128(poolPath, key string) (string, string, error)
109
110 // Parameters:
111 // - poolPath: Canonical path identifying the pool containing the position.
112 // - key: Encoded position key identifying the position's tick range.
113 //
114 // Returns:
115 // - liquidity: Position liquidity as a decimal string.
116 // - err: Non-nil when poolPath or key cannot be resolved.
117 GetPositionLiquidity(poolPath, key string) (string, error)
118
119 // Parameters:
120 // - poolPath: Canonical path identifying the pool containing the position.
121 // - key: Encoded position key identifying the position's tick range.
122 //
123 // Returns:
124 // - tokensOwed0: Token0 amount owed to the position in the pool ledger.
125 // - err: Non-nil when poolPath or key cannot be resolved.
126 GetPositionTokensOwed0(poolPath, key string) (int64, error)
127
128 // Parameters:
129 // - poolPath: Canonical path identifying the pool containing the position.
130 // - key: Encoded position key identifying the position's tick range.
131 //
132 // Returns:
133 // - tokensOwed1: Token1 amount owed to the position in the pool ledger.
134 // - err: Non-nil when poolPath or key cannot be resolved.
135 GetPositionTokensOwed1(poolPath, key string) (int64, error)
136
137 // Parameters:
138 // - poolPath: Canonical path identifying the pool whose protocol fees are read.
139 //
140 // Returns:
141 // - protocolFeesToken0: Accrued token0 protocol-fee amount.
142 // - err: Non-nil when poolPath does not identify a registered pool.
143 GetProtocolFeesToken0(poolPath string) (int64, error)
144
145 // Parameters:
146 // - poolPath: Canonical path identifying the pool whose protocol fees are read.
147 //
148 // Returns:
149 // - protocolFeesToken1: Accrued token1 protocol-fee amount.
150 // - err: Non-nil when poolPath does not identify a registered pool.
151 GetProtocolFeesToken1(poolPath string) (int64, error)
152
153 // Parameters:
154 // - poolPath: Canonical path identifying the pool's slot0 protocol fee configuration.
155 //
156 // Returns:
157 // - feeProtocol: Token-direction protocol-fee denominator/configuration stored in slot0.
158 // - err: Non-nil when poolPath does not identify a registered pool.
159 GetSlot0FeeProtocol(poolPath string) (uint8, error)
160
161 // Parameters:
162 // - poolPath: Canonical path identifying the pool's current square-root price.
163 //
164 // Returns:
165 // - sqrtPriceX96: Current square-root price encoded as a u256 Q96 value.
166 // - err: Non-nil when poolPath does not identify a registered pool.
167 GetSlot0SqrtPriceX96(poolPath string) (*u256.Uint, error)
168
169 // Parameters:
170 // - poolPath: Canonical path identifying the pool whose current tick is read.
171 //
172 // Returns:
173 // - tick: Current signed price tick.
174 // - err: Non-nil when poolPath does not identify a registered pool.
175 GetSlot0Tick(poolPath string) (int32, error)
176
177 // Parameters:
178 // - poolPath: Canonical path identifying the pool whose lock state is read.
179 //
180 // Returns:
181 // - unlocked: True when the pool is available for another state-changing operation.
182 // - err: Non-nil when poolPath does not identify a registered pool.
183 GetSlot0Unlocked(poolPath string) (bool, error)
184
185 // Parameters:
186 // - poolPath: Canonical path identifying the pool containing the tick.
187 // - tick: Signed tick whose outside cumulative is requested.
188 //
189 // Returns:
190 // - tickCumulativeOutside: Signed cumulative tick value stored outside tick.
191 // - err: Non-nil when poolPath or tick cannot be resolved.
192 GetTickCumulativeOutside(poolPath string, tick int32) (int64, error)
193
194 // Parameters:
195 // - poolPath: Canonical path identifying the pool containing the tick.
196 // - tick: Signed tick whose token0 fee-growth outside value is requested.
197 //
198 // Returns:
199 // - feeGrowthOutside0X128: Token0 fee-growth outside tick, encoded as a decimal Q128-scaled string.
200 // - err: Non-nil when poolPath or tick cannot be resolved.
201 GetTickFeeGrowthOutside0X128(poolPath string, tick int32) (string, error)
202
203 // Parameters:
204 // - poolPath: Canonical path identifying the pool containing the tick.
205 // - tick: Signed tick whose token1 fee-growth outside value is requested.
206 //
207 // Returns:
208 // - feeGrowthOutside1X128: Token1 fee-growth outside tick, encoded as a decimal Q128-scaled string.
209 // - err: Non-nil when poolPath or tick cannot be resolved.
210 GetTickFeeGrowthOutside1X128(poolPath string, tick int32) (string, error)
211
212 // Parameters:
213 // - poolPath: Canonical path identifying the pool containing the tick.
214 // - tick: Signed tick whose outside fee growth is requested.
215 //
216 // Returns:
217 // - feeGrowthOutside0X128: Token0 fee-growth outside tick, encoded as a decimal Q128-scaled string.
218 // - feeGrowthOutside1X128: Token1 fee-growth outside tick, encoded as a decimal Q128-scaled string.
219 // - err: Non-nil when poolPath or tick cannot be resolved.
220 GetTickFeeGrowthOutsideX128(poolPath string, tick int32) (string, string, error)
221
222 // Parameters:
223 // - poolPath: Canonical path identifying the pool containing the tick.
224 // - tick: Signed tick whose initialization state is requested.
225 //
226 // Returns:
227 // - initialized: True when tick has initialized liquidity/fee-growth state.
228 // - err: Non-nil when poolPath or tick cannot be resolved.
229 GetTickInitialized(poolPath string, tick int32) (bool, error)
230
231 // Parameters:
232 // - poolPath: Canonical path identifying the pool containing the tick.
233 // - tick: Signed tick whose gross liquidity is requested.
234 //
235 // Returns:
236 // - liquidityGross: Gross liquidity associated with tick, encoded as a decimal string.
237 // - err: Non-nil when poolPath or tick cannot be resolved.
238 GetTickLiquidityGross(poolPath string, tick int32) (string, error)
239
240 // Parameters:
241 // - poolPath: Canonical path identifying the pool containing the tick.
242 // - tick: Signed tick whose net liquidity is requested.
243 //
244 // Returns:
245 // - liquidityNet: Signed net liquidity change at tick, encoded as a decimal string.
246 // - err: Non-nil when poolPath or tick cannot be resolved.
247 GetTickLiquidityNet(poolPath string, tick int32) (string, error)
248
249 // Parameters:
250 // - poolPath: Canonical path identifying the pool containing the tick.
251 // - tick: Signed tick whose elapsed outside time is requested.
252 //
253 // Returns:
254 // - secondsOutside: Seconds elapsed outside tick's range.
255 // - err: Non-nil when poolPath or tick cannot be resolved.
256 GetTickSecondsOutside(poolPath string, tick int32) (uint32, error)
257
258 // Parameters:
259 // - poolPath: Canonical path identifying the pool containing the tick.
260 // - tick: Signed tick whose outside seconds-per-liquidity value is requested.
261 //
262 // Returns:
263 // - secondsPerLiquidityOutsideX128: Outside seconds-per-liquidity accumulator encoded as a decimal Q128-scaled string.
264 // - err: Non-nil when poolPath or tick cannot be resolved.
265 GetTickSecondsPerLiquidityOutsideX128(poolPath string, tick int32) (string, error)
266
267 // Parameters:
268 // - poolPath: Canonical path identifying the pool whose tick spacing is read.
269 //
270 // Returns:
271 // - tickSpacing: Configured signed tick interval for the pool.
272 // - err: Non-nil when poolPath does not identify a registered pool.
273 GetTickSpacing(poolPath string) (int32, error)
274
275 // Parameters:
276 // - poolPath: Canonical path identifying the pool whose token0 path is read.
277 //
278 // Returns:
279 // - token0Path: Registered token contract path assigned to token0.
280 // - err: Non-nil when poolPath does not identify a registered pool.
281 GetToken0Path(poolPath string) (string, error)
282
283 // Parameters:
284 // - poolPath: Canonical path identifying the pool whose token1 path is read.
285 //
286 // Returns:
287 // - token1Path: Registered token contract path assigned to token1.
288 // - err: Non-nil when poolPath does not identify a registered pool.
289 GetToken1Path(poolPath string) (string, error)
290
291 // Returns:
292 // - withdrawalFeeBPS: Configured withdrawal fee in basis points.
293 GetWithdrawalFee() uint64
294
295 // Returns:
296 // - pools: Read-only tree containing registered pool entries.
297 GetPools() *rotree.ReadOnlyTree
298 // Returns:
299 // - feeAmountTickSpacings: Map from fee tier to configured tick spacing.
300 GetFeeAmountTickSpacings() map[uint32]int32
301
302 // Parameters:
303 // - poolPath: Canonical path identifying the pool whose positions are viewed.
304 //
305 // Returns:
306 // - positions: Read-only tree containing position entries for poolPath, or nil when poolPath is not registered.
307 GetPoolPositions(poolPath string) *rotree.ReadOnlyTree
308
309 // Parameters:
310 // - poolPath: Canonical path identifying the pool to scan.
311 // - tickLower: Inclusive lower tick bound for the requested range.
312 // - tickUpper: Exclusive upper tick bound for the requested range.
313 //
314 // Returns:
315 // - ticks: Initialized ticks in [tickLower, tickUpper), ordered by tick.
316 // - err: Non-nil when poolPath or the requested range is invalid.
317 GetInitializedTicksInRange(poolPath string, tickLower, tickUpper int32) ([]int32, error)
318
319 // Parameters:
320 // - poolPath: Canonical path identifying the pool containing the tick.
321 // - tick: Signed tick whose complete state is requested.
322 //
323 // Returns:
324 // - info: Tick state including initialization, liquidity, fee-growth, and oracle accumulators.
325 // - err: Non-nil when poolPath or tick cannot be resolved.
326 GetTickInfo(poolPath string, tick int32) (TickInfo, error)
327 // Parameters:
328 // - poolPath: Canonical path identifying the pool whose bitmap is read.
329 // - wordPos: Signed bitmap word position containing 256 tick-initialization bits.
330 //
331 // Returns:
332 // - bitmap: Decimal-encoded bitmap word for wordPos.
333 // - err: Non-nil when poolPath or wordPos cannot be resolved.
334 GetTickBitmaps(poolPath string, wordPos int16) (string, error)
335}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 // Parameters:
4 // - _: Noncrossing implementation-call discriminator; pass 0.
5 // - rlm: Current realm context forwarded unchanged by the pool proxy.
6 // - token0Path: Registered token contract path for token0.
7 // - token1Path: Registered token contract path for token1.
8 // - fee: Fee tier identifying the new pool and its tick spacing.
9 // - sqrtPriceX96: Initial token1/token0 square-root price encoded as a Q96 decimal string.
10 CreatePool(
11 _ int,
12 rlm realm,
13 token0Path string,
14 token1Path string,
15 fee uint32,
16 sqrtPriceX96 string,
17 )
18
19 // SetPoolCreationFee sets the pool creation fee.
20 // Parameters:
21 // - _: Noncrossing implementation-call discriminator; pass 0.
22 // - rlm: Current realm context forwarded unchanged by the pool proxy.
23 // - fee: Pool-creation fee amount to store for future pool creation operations.
24 SetPoolCreationFee(_ int, rlm realm, fee int64)
25}IPoolManager interface defines pool management operations. These methods handle pool creation and fee configuration.
type IPoolOracle
interface 1type IPoolOracle interface {
2 // GetSlot0 returns a safe copy of a pool's price, tick, protocol-fee, lock,
3 // and oracle cursor/capacity state, corresponding to Uniswap V3 slot0().
4 //
5 // ref: https://github.com/Uniswap/v3-core/blob/e3589b192d0be27e100cd0daaf6c97204fdb1899/contracts/interfaces/pool/IUniswapV3PoolState.sol#L21-L32
6 // Parameters:
7 // - poolPath: Canonical path identifying the pool whose slot0 state is read.
8 //
9 // Returns:
10 // - slot0: Safe copy of the pool's price, tick, protocol-fee, lock, and oracle cursor/capacity state.
11 GetSlot0(poolPath string) Slot0
12
13 // GetObservationAt returns the observation stored at index, corresponding to
14 // Uniswap V3 observations(uint256). An in-range uninitialized slot returns a
15 // zero observation; an out-of-range index returns an error.
16 //
17 // ref: https://github.com/Uniswap/v3-core/blob/e3589b192d0be27e100cd0daaf6c97204fdb1899/contracts/interfaces/pool/IUniswapV3PoolState.sol#L99-L115
18 // Parameters:
19 // - poolPath: Canonical path identifying the pool containing the observation.
20 // - index: uint16 observation-buffer index to read.
21 //
22 // Returns:
23 // - observation: Stored observation, or the zero observation for an in-range uninitialized slot.
24 // - err: Non-nil when poolPath is unknown or index is outside the pool's observation buffer.
25 GetObservationAt(poolPath string, index uint16) (Observation, error)
26
27 // Observe returns tick and seconds-per-liquidity cumulatives for every
28 // requested lookback, corresponding to Uniswap V3 observe(uint32[]).
29 //
30 // ref: https://github.com/Uniswap/v3-core/blob/e3589b192d0be27e100cd0daaf6c97204fdb1899/contracts/interfaces/pool/IUniswapV3PoolDerivedState.sol#L18-L21
31 // Parameters:
32 // - poolPath: Canonical path identifying the pool whose oracle data is read.
33 // - secondsAgos: Lookback durations in seconds; one cumulative pair is returned for each entry in order.
34 //
35 // Returns:
36 // - tickCumulatives: Signed cumulative ticks corresponding to each requested lookback.
37 // - secondsPerLiquidityCumulativesX128: Q128-scaled seconds-per-liquidity cumulatives as decimal strings, in request order.
38 // - err: Non-nil when the pool or requested lookback cannot be served by its observations.
39 Observe(poolPath string, secondsAgos []uint32) ([]int64, []string, error)
40
41 // SnapshotCumulativesInside returns accumulators accrued while the pool price
42 // was inside [tickLower, tickUpper), corresponding to Uniswap V3
43 // snapshotCumulativesInside(int24,int24).
44 //
45 // ref: https://github.com/Uniswap/v3-core/blob/e3589b192d0be27e100cd0daaf6c97204fdb1899/contracts/interfaces/pool/IUniswapV3PoolDerivedState.sol#L23-L39
46 // Parameters:
47 // - poolPath: Canonical path identifying the pool whose inside accumulators are read.
48 // - tickLower: Lower boundary of the half-open tick range [tickLower, tickUpper).
49 // - tickUpper: Upper boundary of the half-open tick range [tickLower, tickUpper).
50 //
51 // Returns:
52 // - tickCumulativeInside: Signed tick accumulator while the price was inside the range.
53 // - secondsPerLiquidityInsideX128: Q128-scaled seconds-per-liquidity accumulator inside the range.
54 // - secondsInside: Number of seconds for which the price was inside the range.
55 // - err: Non-nil when poolPath or the requested tick range is invalid or unavailable.
56 SnapshotCumulativesInside(
57 poolPath string,
58 tickLower int32,
59 tickUpper int32,
60 ) (int64, *u256.Uint, uint32, error)
61
62 // OracleConsult returns the arithmetic mean tick and harmonic mean liquidity
63 // over secondsAgo, following Uniswap V3 periphery's OracleLibrary.consult.
64 //
65 // ref: https://github.com/Uniswap/v3-periphery/blob/0682387198a24c7cd63566a2c58398533860a5d1/contracts/libraries/OracleLibrary.sol#L16-L41
66 // Parameters:
67 // - poolPath: Canonical path identifying the pool consulted for the time-weighted oracle values.
68 // - secondsAgo: Lookback duration in seconds over which the arithmetic mean tick and harmonic mean liquidity are calculated.
69 //
70 // Returns:
71 // - arithmeticMeanTick: Time-weighted arithmetic mean tick over secondsAgo.
72 // - harmonicMeanLiquidity: Harmonic mean liquidity over secondsAgo, represented as a u256 value.
73 // - err: Non-nil when poolPath is unknown or the requested history is unavailable.
74 OracleConsult(poolPath string, secondsAgo uint32) (int32, *u256.Uint, error)
75
76 // IncreaseObservationCardinalityNext schedules growth of the circular
77 // observation buffer, corresponding to Uniswap V3
78 // increaseObservationCardinalityNext(uint16).
79 //
80 // ref: https://github.com/Uniswap/v3-core/blob/e3589b192d0be27e100cd0daaf6c97204fdb1899/contracts/interfaces/pool/IUniswapV3PoolActions.sol#L98-L102
81 // Parameters:
82 // - _: Noncrossing implementation-call discriminator; pass 0.
83 // - rlm: Current realm context forwarded unchanged by the pool proxy.
84 // - token0Path: Registered token contract path for token0.
85 // - token1Path: Registered token contract path for token1.
86 // - fee: Fee tier identifying the pool.
87 // - cardinalityNext: Requested next observation-buffer capacity; must not exceed the implementation maximum.
88 IncreaseObservationCardinalityNext(
89 _ int,
90 rlm realm,
91 token0Path string,
92 token1Path string,
93 fee uint32,
94 cardinalityNext uint16,
95 )
96}IPoolOracle defines the pool's Uniswap V3-aligned oracle surface.
Its public methods mirror the relevant Uniswap V3 pool-state, derived-state, and action specifications, adapted for GnoSwap's singleton pool realm: every operation identifies its pool with poolPath, and uint values cross the public boundary using GnoSwap types or decimal strings rather than the EVM ABI.
ref: https://github.com/Uniswap/v3-core/blob/e3589b192d0be27e100cd0daaf6c97204fdb1899/contracts/interfaces/pool/IUniswapV3PoolState.sol#L21-L32 ref: https://github.com/Uniswap/v3-core/blob/e3589b192d0be27e100cd0daaf6c97204fdb1899/contracts/interfaces/pool/IUniswapV3PoolDerivedState.sol#L18-L39
type IPoolPosition
interface 1type IPoolPosition interface {
2 // Mint adds liquidity to a pool position.
3 // Parameters:
4 // - _: Noncrossing implementation-call discriminator; pass 0.
5 // - rlm: Current realm context forwarded unchanged by the pool proxy.
6 // - token0Path: Registered token contract path for token0.
7 // - token1Path: Registered token contract path for token1.
8 // - fee: Fee tier identifying the pool.
9 // - tickLower: Lower inclusive tick of the position's price range; must align to pool spacing.
10 // - tickUpper: Upper exclusive tick of the position's price range; must align to pool spacing.
11 // - liquidityAmount: Positive decimal liquidity amount to add.
12 // - positionCaller: Position-contract address that provides tokens for the mint.
13 //
14 // Returns:
15 // - amount0: Token0 amount consumed, encoded as a decimal string.
16 // - amount1: Token1 amount consumed, encoded as a decimal string.
17 Mint(
18 _ int,
19 rlm realm,
20 token0Path string,
21 token1Path string,
22 fee uint32,
23 tickLower int32,
24 tickUpper int32,
25 liquidityAmount string,
26 positionCaller address,
27 ) (string, string)
28
29 // Burn removes liquidity and credits principal to the pool position entry;
30 // Collect later transfers that principal without a withdrawal fee.
31 // Parameters:
32 // - _: Noncrossing implementation-call discriminator; pass 0.
33 // - rlm: Current realm context forwarded unchanged by the pool proxy.
34 // - token0Path: Registered token contract path for token0.
35 // - token1Path: Registered token contract path for token1.
36 // - fee: Fee tier identifying the pool.
37 // - tickLower: Lower tick of the position's price range; must align to pool spacing.
38 // - tickUpper: Upper tick of the position's price range; must align to pool spacing.
39 // - liquidityAmount: Non-negative decimal liquidity amount to remove.
40 // - positionCaller: Position-contract address associated with the pool position.
41 //
42 // Returns:
43 // - amount0: Token0 principal credited to the position, encoded as a decimal string.
44 // - amount1: Token1 principal credited to the position, encoded as a decimal string.
45 Burn(
46 _ int,
47 rlm realm,
48 token0Path string,
49 token1Path string,
50 fee uint32,
51 tickLower int32,
52 tickUpper int32,
53 liquidityAmount string,
54 positionCaller address,
55 ) (string, string)
56
57 // CollectSwapFee pays accrued swap fees and applies the withdrawal fee;
58 // Collect pays principal owed by Burn without that fee.
59 // Parameters:
60 // - _: Noncrossing implementation-call discriminator; pass 0.
61 // - rlm: Current realm context forwarded unchanged by the pool proxy.
62 // - token0Path: Registered token contract path for token0.
63 // - token1Path: Registered token contract path for token1.
64 // - fee: Fee tier identifying the pool.
65 // - recipient: Nonzero address receiving collected tokens after any withdrawal fee.
66 // - tickLower: Lower tick of the position's price range.
67 // - tickUpper: Upper tick of the position's price range.
68 // - amount0Requested: Non-negative decimal amount of token0 requested; the int64 maximum requests all owed token0.
69 // - amount1Requested: Non-negative decimal amount of token1 requested; the int64 maximum requests all owed token1.
70 //
71 // Returns:
72 // - amount0: Token0 amount collected before withdrawal-fee deduction, as a decimal string.
73 // - amount1: Token1 amount collected before withdrawal-fee deduction, as a decimal string.
74 // - fee0: Withdrawal fee withheld from token0, as a decimal string.
75 // - fee1: Withdrawal fee withheld from token1, as a decimal string.
76 CollectSwapFee(
77 _ int,
78 rlm realm,
79 token0Path string,
80 token1Path string,
81 fee uint32,
82 recipient address,
83 tickLower int32,
84 tickUpper int32,
85 amount0Requested string,
86 amount1Requested string,
87 ) (amount0, amount1, fee0, fee1 string)
88
89 // Parameters:
90 // - _: Noncrossing implementation-call discriminator; pass 0.
91 // - rlm: Current realm context forwarded unchanged by the pool proxy.
92 // - token0Path: Registered token contract path for token0.
93 // - token1Path: Registered token contract path for token1.
94 // - fee: Fee tier identifying the pool.
95 // - recipient: Nonzero address receiving owed principal.
96 // - tickLower: Lower tick of the position's price range.
97 // - tickUpper: Upper tick of the position's price range.
98 // - amount0Requested: Non-negative decimal amount of token0 principal requested.
99 // - amount1Requested: Non-negative decimal amount of token1 principal requested.
100 //
101 // Returns:
102 // - amount0: Token0 principal transferred to recipient, as a decimal string.
103 // - amount1: Token1 principal transferred to recipient, as a decimal string.
104 Collect(
105 _ int,
106 rlm realm,
107 token0Path string,
108 token1Path string,
109 fee uint32,
110 recipient address,
111 tickLower int32,
112 tickUpper int32,
113 amount0Requested string,
114 amount1Requested string,
115 ) (amount0, amount1 string)
116
117 // Parameters:
118 // - _: Noncrossing implementation-call discriminator; pass 0.
119 // - rlm: Current realm context forwarded unchanged by the pool proxy.
120 // - fee: Withdrawal fee rate in basis points to apply to fee-bearing position payouts.
121 SetWithdrawalFee(_ int, rlm realm, fee uint64)
122}IPoolPosition interface defines position management operations. These methods handle liquidity provision and position management.
type IPoolStore
interface 1type IPoolStore interface {
2 // Returns:
3 // - exists: True when the backing pool registry tree has been initialized.
4 HasPools() bool
5 // Returns:
6 // - pools: Stored B+tree containing pool state entries; the implementation panics if the KV value is unreadable, wrongly typed, or nil.
7 GetPools() *bptree.BPTree
8 // Parameters:
9 // - _: Leading integer discriminator forwarded to the storage setter; pass 0.
10 // - rlm: Propagated realm context; the setter rejects a context that is not current.
11 // - pools: B+tree replacing the stored pool registry.
12 //
13 // Returns:
14 // - err: Nil after storing pools; non-nil for a non-current rlm or an underlying KV-store write failure.
15 SetPools(_ int, rlm realm, pools *bptree.BPTree) error
16
17 // Returns:
18 // - exists: True when the backing observation registry tree has been initialized.
19 HasObservations() bool
20 // Returns:
21 // - observations: Stored B+tree containing pool observation trees; the implementation panics if the KV value is unreadable, wrongly typed, or nil.
22 GetObservations() *bptree.BPTree
23 // Parameters:
24 // - _: Leading integer discriminator forwarded to the storage setter; pass 0.
25 // - rlm: Propagated realm context; the setter rejects a context that is not current.
26 // - observations: B+tree replacing the stored observation registry.
27 //
28 // Returns:
29 // - err: Nil after storing observations; non-nil for a non-current rlm or an underlying KV-store write failure.
30 SetObservations(_ int, rlm realm, observations *bptree.BPTree) error
31
32 // Returns:
33 // - exists: True when the fee-to-tick-spacing map has been initialized.
34 HasFeeAmountTickSpacing() bool
35 // Returns:
36 // - feeAmountTickSpacing: Stored fee-tier to tick-spacing map; the implementation panics if the KV value is unreadable, wrongly typed, or nil.
37 GetFeeAmountTickSpacing() map[uint32]int32
38 // Parameters:
39 // - _: Leading integer discriminator forwarded to the storage setter; pass 0.
40 // - rlm: Propagated realm context; the setter rejects a context that is not current.
41 // - feeAmountTickSpacing: Map replacing the configured fee-tier to tick-spacing values.
42 //
43 // Returns:
44 // - err: Nil after storing the mapping; non-nil for a non-current rlm or an underlying KV-store write failure.
45 SetFeeAmountTickSpacing(_ int, rlm realm, feeAmountTickSpacing map[uint32]int32) error
46
47 // Returns:
48 // - exists: True when the slot0 protocol-fee configuration has been initialized.
49 HasSlot0FeeProtocol() bool
50 // Returns:
51 // - slot0FeeProtocol: Stored packed protocol-fee denominator configuration; the implementation panics if the KV value is unreadable or wrongly typed.
52 GetSlot0FeeProtocol() uint8
53 // Parameters:
54 // - _: Leading integer discriminator forwarded to the storage setter; pass 0.
55 // - rlm: Propagated realm context; the setter rejects a context that is not current.
56 // - slot0FeeProtocol: Protocol-fee denominator/configuration to store in slot0.
57 //
58 // Returns:
59 // - err: Nil after storing the value; non-nil for a non-current rlm or an underlying KV-store write failure.
60 SetSlot0FeeProtocol(_ int, rlm realm, slot0FeeProtocol uint8) error
61
62 // Returns:
63 // - exists: True when a pool-creation fee has been initialized.
64 HasPoolCreationFee() bool
65 // Returns:
66 // - poolCreationFee: Stored pool-creation charge in the chain's smallest currency unit; the implementation panics if the KV value is unreadable or wrongly typed.
67 GetPoolCreationFee() int64
68 // Parameters:
69 // - _: Leading integer discriminator forwarded to the storage setter; pass 0.
70 // - rlm: Propagated realm context; the setter rejects a context that is not current.
71 // - poolCreationFee: Pool-creation fee amount to store.
72 //
73 // Returns:
74 // - err: Nil after storing the fee; non-nil for a non-current rlm or an underlying KV-store write failure.
75 SetPoolCreationFee(_ int, rlm realm, poolCreationFee int64) error
76
77 // Returns:
78 // - exists: True when the pending protocol-fee map has been initialized.
79 HasPendingProtocolFees() bool
80 // Returns:
81 // - pendingProtocolFees: Stored token-path map of pending protocol-fee amounts in the chain's smallest currency unit; the implementation panics if the KV value is unreadable or wrongly typed.
82 GetPendingProtocolFees() map[string]int64
83 // Parameters:
84 // - _: Leading integer discriminator forwarded to the storage setter; pass 0.
85 // - rlm: Propagated realm context; the setter rejects a context that is not current.
86 // - pendingProtocolFees: Map replacing all pending protocol-fee balances.
87 //
88 // Returns:
89 // - err: Nil after storing the map; non-nil for a non-current rlm or an underlying KV-store write failure.
90 SetPendingProtocolFees(_ int, rlm realm, pendingProtocolFees map[string]int64) error
91 // Parameters:
92 // - tokenPath: Registered token contract path whose pending protocol fee is read.
93 //
94 // Returns:
95 // - amount: Pending protocol-fee amount recorded for tokenPath, or zero when none is stored.
96 GetPendingProtocolFee(tokenPath string) int64
97 // Parameters:
98 // - _: Leading integer discriminator forwarded to the storage setter; pass 0.
99 // - rlm: Propagated realm context; the setter rejects a context that is not current.
100 // - tokenPath: Registered token contract path whose pending fee is updated.
101 // - amount: Pending protocol-fee amount to store for tokenPath.
102 //
103 // Returns:
104 // - err: Nil after storing the amount; non-nil for a non-current rlm, unauthorized code-realm write, or underlying authorization failure.
105 SetPendingProtocolFee(_ int, rlm realm, tokenPath string, amount int64) error
106 // Parameters:
107 // - _: Leading integer discriminator forwarded to the storage setter; pass 0.
108 // - rlm: Propagated realm context; the setter rejects a context that is not current.
109 // - tokenPath: Registered token contract path whose pending fee entry is removed.
110 //
111 // Returns:
112 // - err: Nil after removing the entry; non-nil for a non-current rlm, unauthorized code-realm write, or underlying authorization failure.
113 RemovePendingProtocolFee(_ int, rlm realm, tokenPath string) error
114
115 // Returns:
116 // - exists: True when a withdrawal-fee basis-point value has been initialized.
117 HasWithdrawalFeeBPS() bool
118 // Returns:
119 // - withdrawalFeeBPS: Stored withdrawal fee in basis points.
120 GetWithdrawalFeeBPS() uint64
121 // Parameters:
122 // - _: Leading integer discriminator forwarded to the storage setter; pass 0.
123 // - rlm: Propagated realm context; the setter rejects a context that is not current.
124 // - withdrawalFeeBPS: Withdrawal fee rate in basis points to store.
125 //
126 // Returns:
127 // - err: Nil after storing the rate; non-nil for a non-current rlm or an underlying KV-store write failure.
128 SetWithdrawalFeeBPS(_ int, rlm realm, withdrawalFeeBPS uint64) error
129
130 // Returns:
131 // - exists: True when the pool unlocked flag has been initialized.
132 HasUnlocked() bool
133 // Returns:
134 // - unlocked: Persisted global reentrancy-lock state; true means pool operations may proceed without the lock, and malformed/missing storage panics.
135 GetUnlocked() bool
136 // Parameters:
137 // - _: Leading integer discriminator forwarded to the storage setter; pass 0.
138 // - rlm: Propagated realm context; the setter rejects a context that is not current.
139 // - unlocked: Lock flag to store; false marks the pool as locked.
140 //
141 // Returns:
142 // - err: Nil after storing the flag; non-nil for a non-current rlm or an underlying KV-store write failure.
143 SetUnlocked(_ int, rlm realm, unlocked bool) error
144
145 // Returns:
146 // - exists: True when a swap-start hook has been initialized.
147 HasSwapStartHook() bool
148 // Returns:
149 // - swapStartHook: Stored callback receiving current realm, pool path, and timestamp; callers should check HasSwapStartHook before retrieving it.
150 GetSwapStartHook() func(cur realm, poolPath string, timestamp int64)
151 // Parameters:
152 // - _: Leading integer discriminator forwarded to the storage setter; pass 0.
153 // - rlm: Propagated realm context; the setter rejects a context that is not current.
154 // - swapStartHook: Callback invoked with current realm, pool path, and timestamp before swaps.
155 //
156 // Returns:
157 // - err: Nil after storing the hook; non-nil for a non-current rlm or an underlying KV-store write failure.
158 SetSwapStartHook(_ int, rlm realm, swapStartHook func(cur realm, poolPath string, timestamp int64)) error
159
160 // Returns:
161 // - exists: True when a swap-end hook has been initialized.
162 HasSwapEndHook() bool
163 // Returns:
164 // - swapEndHook: Stored callback receiving current realm and pool path and returning a hook error; callers should check HasSwapEndHook before retrieving it.
165 GetSwapEndHook() func(cur realm, poolPath string) error
166 // Parameters:
167 // - _: Leading integer discriminator forwarded to the storage setter; pass 0.
168 // - rlm: Propagated realm context; the setter rejects a context that is not current.
169 // - swapEndHook: Callback invoked with current realm and pool path after swaps; it may return an error.
170 //
171 // Returns:
172 // - err: Nil after storing the hook; non-nil for a non-current rlm or an underlying KV-store write failure.
173 SetSwapEndHook(_ int, rlm realm, swapEndHook func(cur realm, poolPath string) error) error
174
175 // Returns:
176 // - exists: True when a tick-cross hook has been initialized.
177 HasTickCrossHook() bool
178 // Returns:
179 // - tickCrossHook: Stored callback receiving current realm, pool path, crossed tick, direction, and timestamp; callers should check HasTickCrossHook before retrieving it.
180 GetTickCrossHook() func(cur realm, poolPath string, tickId int32, zeroForOne bool, timestamp int64)
181 // Parameters:
182 // - _: Leading integer discriminator forwarded to the storage setter; pass 0.
183 // - rlm: Propagated realm context; the setter rejects a context that is not current.
184 // - tickCrossHook: Callback invoked with current realm, pool path, crossed tick, direction, and timestamp.
185 //
186 // Returns:
187 // - err: Nil after storing the hook; non-nil for a non-current rlm or an underlying KV-store write failure.
188 SetTickCrossHook(_ int, rlm realm, tickCrossHook func(cur realm, poolPath string, tickId int32, zeroForOne bool, timestamp int64)) error
189}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 // Parameters:
3 // - _: Noncrossing implementation-call discriminator; pass 0.
4 // - rlm: Current realm context forwarded unchanged by the pool proxy.
5 // - token0Path: Registered token contract path for token0.
6 // - token1Path: Registered token contract path for token1.
7 // - fee: Fee tier identifying the pool.
8 // - recipient: Nonzero address receiving swap output.
9 // - zeroForOne: Swap direction; true swaps token0 for token1, false swaps token1 for token0.
10 // - amountSpecified: Signed decimal amount; positive requests exact input and negative requests exact output.
11 // - sqrtPriceLimitX96: Q96-encoded decimal square-root price limit for the swap.
12 // - swapCallback: Callback that receives the current realm, signed token deltas, and marker, and must settle the input-token balance or return an error.
13 //
14 // Returns:
15 // - amount0: Signed token0 delta produced by the swap, encoded as a decimal string.
16 // - amount1: Signed token1 delta produced by the swap, encoded as a decimal string.
17 Swap(
18 _ int,
19 rlm realm,
20 token0Path string,
21 token1Path string,
22 fee uint32,
23 recipient address,
24 zeroForOne bool,
25 amountSpecified string,
26 sqrtPriceLimitX96 string,
27 swapCallback func(cur realm, amount0Delta, amount1Delta int64, callbackMarker *CallbackMarker) error,
28 ) (string, string)
29
30 // Parameters:
31 // - token0Path: Registered token contract path for token0.
32 // - token1Path: Registered token contract path for token1.
33 // - fee: Fee tier identifying the pool.
34 // - zeroForOne: Swap direction; true swaps token0 for token1, false swaps token1 for token0.
35 // - amountSpecified: Signed decimal amount; positive requests exact input and negative requests exact output.
36 // - sqrtPriceLimitX96: Q96-encoded decimal square-root price limit for the simulated swap.
37 //
38 // Returns:
39 // - amount0: Signed token0 delta predicted by the simulation, encoded as a decimal string.
40 // - amount1: Signed token1 delta predicted by the simulation, encoded as a decimal string.
41 // - err: Non-nil when parsing or swap simulation validation fails; successful simulations return nil.
42 DrySwap(
43 token0Path string,
44 token1Path string,
45 fee uint32,
46 zeroForOne bool,
47 amountSpecified string,
48 sqrtPriceLimitX96 string,
49 ) (string, string, error)
50
51 // Parameters:
52 // - _: Noncrossing implementation-call discriminator; pass 0.
53 // - rlm: Current realm context forwarded unchanged by the pool proxy.
54 // - hook: Callback invoked after a swap with the current realm and pool path; a returned error aborts the swap.
55 SetSwapEndHook(_ int, rlm realm, hook func(cur realm, poolPath string) error)
56
57 // Parameters:
58 // - _: Noncrossing implementation-call discriminator; pass 0.
59 // - rlm: Current realm context forwarded unchanged by the pool proxy.
60 // - hook: Callback invoked before a swap with the current realm, pool path, and block timestamp.
61 SetSwapStartHook(_ int, rlm realm, hook func(cur realm, poolPath string, timestamp int64))
62
63 // Parameters:
64 // - _: Noncrossing implementation-call discriminator; pass 0.
65 // - rlm: Current realm context forwarded unchanged by the pool proxy.
66 // - hook: Callback invoked when a tick is crossed, receiving current realm, pool path, tick id, direction, and timestamp.
67 SetTickCrossHook(_ int, rlm realm, hook func(cur realm, poolPath string, tickId int32, zeroForOne bool, timestamp int64))
68
69 // Parameters:
70 // - _: Noncrossing implementation-call discriminator; pass 0.
71 // - rlm: Current realm context forwarded unchanged by the pool proxy.
72 // - token0Path: Registered token contract path for token0.
73 // - token1Path: Registered token contract path for token1.
74 // - fee: Fee tier identifying the pool.
75 // - recipient: Nonzero address receiving collected protocol fees.
76 // - amount0Requested: Non-negative decimal amount of token0 protocol fees requested, capped by availability.
77 // - amount1Requested: Non-negative decimal amount of token1 protocol fees requested, capped by availability.
78 //
79 // Returns:
80 // - amount0: Token0 protocol fees transferred to recipient, encoded as a decimal string.
81 // - amount1: Token1 protocol fees transferred to recipient, encoded as a decimal string.
82 CollectProtocol(
83 _ int,
84 rlm realm,
85 token0Path string,
86 token1Path string,
87 fee uint32,
88 recipient address,
89 amount0Requested string,
90 amount1Requested string,
91 ) (amount0, amount1 string)
92
93 // Parameters:
94 // - _: Noncrossing implementation-call discriminator; pass 0.
95 // - rlm: Current realm context forwarded unchanged by the pool proxy.
96 // - feeProtocol0: Protocol-fee denominator/configuration for token0 swaps.
97 // - feeProtocol1: Protocol-fee denominator/configuration for token1 swaps.
98 SetFeeProtocol(_ int, rlm realm, feeProtocol0, feeProtocol1 uint8)
99}IPoolSwap interface defines swap and protocol fee operations. These methods handle token swaps and protocol fee management.
type Observation
structMethods on Observation
func BlockTimestamp
method on ObservationObservation getter methods. BlockTimestamp returns the observation's block timestamp.
Returns:
- blockTimestamp: Timestamp at which this observation was recorded.
func Initialized
method on ObservationInitialized reports whether the observation contains initialized oracle data.
Returns:
- initialized: True when the observation slot has been initialized; false for an empty slot.
func SecondsPerLiquidityCumulativeX128
method on ObservationSecondsPerLiquidityCumulativeX128 returns the Q128-encoded cumulative seconds-per-liquidity value recorded by the observation.
Returns:
- secondsPerLiquidityCumulativeX128: Decimal string containing the cumulative value scaled by 2^128.
func TickCumulative
method on ObservationTickCumulative returns the signed cumulative tick recorded by the observation.
Returns:
- tickCumulative: Cumulative tick value through the observation timestamp.
type ObservationTree
structObservationTree is a pool-local oracle ring buffer keyed by index. It owns the B+tree key encoding so oracle code works with uint16 indices.
Methods on ObservationTree
func Get
method on ObservationTreeGet looks up an observation by its circular-buffer index.
Parameters:
- index: uint16 observation slot to read.
Returns:
- observation: Stored observation when the tree contains a value of the expected type; otherwise the zero observation.
- ok: True when a stored value was found and decoded as an Observation; false for nil/uninitialized trees, missing slots, or a type mismatch.
func Has
method on ObservationTreeHas reports whether an observation slot exists in the tree.
Parameters:
- index: uint16 observation slot to test.
Returns:
- exists: True when the initialized tree contains index; false for nil/uninitialized trees or an absent slot.
func Set
method on ObservationTreeSet stores an observation at a circular-buffer index.
Parameters:
- index: uint16 observation slot to write.
- observation: Observation value to associate with index.
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 encoded lower/upper tick pairs to aggregate pool accounting
16}Pool describes a single pool's state. A pool is identified with a unique key (token0, token1, fee), where token0 < token1.
Methods on Pool
func BalanceToken0
method on PoolBalanceToken0 returns the pool's current token0 balance.
Returns:
- int64: token0 balance available in the pool.
func BalanceToken1
method on PoolBalanceToken1 returns the pool's current token1 balance.
Returns:
- int64: token1 balance available in the pool.
func Balances
method on PoolBalances returns the pool's current token balances.
Returns:
- TokenPair: token0 and token1 balances tracked by the pool.
func Clone
method on PoolClone copies a pool's own fields and leaves its collections nil: ticks, tickBitmaps, and positions are not copied. Oracle observations are stored separately from Pool.
The copy is shallow because the read-only pool view clones every entry a caller reads, so copying the collections would walk the whole tick tree for each entry on a page. Read them through their own lookups instead: GetTickInfo / GetInitializedTicksInRange for ticks, GetTickBitmaps for the bitmaps, GetPoolPositions for positions, and GetSlot0 / GetObservationAt for oracle metadata and entries. A caller that needs a working copy of a collection -- DrySwap is the only one -- assembles it from those getters.
Returns:
- *Pool: shallow pool copy with scalar state and cloned numeric values; nil when the receiver is nil.
func DeleteTick
method on PoolDeleteTick removes the tick state for the given tick index.
Parameters:
- tick: tick index to remove.
func DeleteTickBitmap
method on PoolDeleteTickBitmap deletes the tick bitmap for the given word position.
Parameters:
- wordPos: signed bitmap word position to remove.
func Fee
method on PoolFee returns the pool's fee tier.
Returns:
- uint32: fee tier used by swaps in this pool.
func FeeGrowthGlobal0X128
method on PoolFeeGrowthGlobal0X128 returns cumulative token0 fee growth per unit of liquidity.
Returns:
- *u256.Uint: token0 fee-growth accumulator scaled by 2^128.
func FeeGrowthGlobal1X128
method on PoolFeeGrowthGlobal1X128 returns cumulative token1 fee growth per unit of liquidity.
Returns:
- *u256.Uint: token1 fee-growth accumulator scaled by 2^128.
func GetPosition
method on PoolGetPosition returns the position information for key.
Parameters:
- key: encoded lower/upper tick-range key to look up.
Returns:
- PositionInfo: stored aggregate position for the key.
- error: non-nil when the key is absent or contains a value of the wrong type.
func GetTick
method on PoolGetTick returns the state stored for a tick.
Parameters:
- tick: tick index to look up.
Returns:
- TickInfo: stored tick state.
- error: non-nil when the tick is absent; a present value of the wrong type causes a panic.
func HasTick
method on PoolHasTick reports whether a tick entry exists in the pool's tick tree.
Parameters:
- tick: tick index to check.
Returns:
- bool: true when the encoded tick is present; false otherwise.
func IterateTicks
method on Pool1func (p *Pool) IterateTicks(startTick int32, endTick int32, fn func(tick int32, tickInfo TickInfo) bool)IterateTicks visits pool ticks in the inclusive range [startTick, endTick]. Iteration stops when the callback returns true.
Parameters:
- startTick: first tick index in the inclusive range.
- endTick: last tick index in the inclusive range.
- fn: callback receiving each decoded tick and its state; return true to stop iteration.
func Liquidity
method on PoolLiquidity returns the pool's active liquidity for the current tick range.
Returns:
- *u256.Uint: active liquidity amount.
func PoolPath
method on PoolPool Getters methods PoolPath returns the canonical pool path derived from token0, token1, and the fee tier.
Returns:
- string: pool identifier assembled from the pool's token paths and fee.
func Positions
method on PoolPositions returns the tree containing aggregate position state by range key.
Returns:
- *bptree.BPTree: pool position storage tree.
func ProtocolFees
method on PoolProtocolFees returns protocol fees accrued in both pool tokens.
Returns:
- TokenPair: token0 and token1 protocol-fee balances.
func ProtocolFeesToken0
method on PoolProtocolFeesToken0 returns protocol fees accrued in token0.
Returns:
- int64: token0 amount reserved as protocol fees.
func ProtocolFeesToken1
method on PoolProtocolFeesToken1 returns protocol fees accrued in token1.
Returns:
- int64: token1 amount reserved as protocol fees.
func SetBalanceToken0
method on PoolSetBalanceToken0 updates the pool's tracked token0 balance.
Parameters:
- token0: new token0 balance.
func SetBalanceToken1
method on PoolSetBalanceToken1 updates the pool's tracked token1 balance.
Parameters:
- token1: new token1 balance.
func SetBalances
method on PoolSetBalances replaces the pool's tracked balances for both tokens.
Parameters:
- balances: token0 and token1 balances to store.
func SetFee
method on PoolSetFee stores the pool's fee tier.
Parameters:
- fee: fee tier to use for swaps in this pool.
func SetFeeGrowthGlobal0X128
method on PoolSetFeeGrowthGlobal0X128 stores the token0 fee-growth accumulator.
Parameters:
- feeGrowthGlobal0X128: token0 fee growth per liquidity unit, scaled by 2^128.
func SetFeeGrowthGlobal1X128
method on PoolSetFeeGrowthGlobal1X128 stores the token1 fee-growth accumulator.
Parameters:
- feeGrowthGlobal1X128: token1 fee growth per liquidity unit, scaled by 2^128.
func SetLiquidity
method on PoolSetLiquidity stores the pool's active liquidity for the current tick range.
Parameters:
- liquidity: active liquidity amount to store.
func SetPosition
method on PoolSetPosition stores position information under an encoded range key.
Parameters:
- posKey: encoded lower/upper tick-range key.
- positionInfo: aggregate position state to store.
func SetPositions
method on PoolSetPositions replaces the tree containing aggregate position state.
Parameters:
- positions: position storage tree to use.
func SetProtocolFees
method on PoolSetProtocolFees replaces the pool's accrued protocol fees for both tokens.
Parameters:
- protocolFees: token0 and token1 protocol-fee balances to store.
func SetProtocolFeesToken0
method on PoolSetProtocolFeesToken0 updates the pool's accrued token0 protocol fees.
Parameters:
- token0: new token0 protocol-fee balance.
func SetProtocolFeesToken1
method on PoolSetProtocolFeesToken1 updates the pool's accrued token1 protocol fees.
Parameters:
- token1: new token1 protocol-fee balance.
func SetSlot0
method on PoolSetSlot0 replaces the pool's current price, tick, lock, and oracle cursor state.
Parameters:
- slot0: slot0 state to store.
func SetTick
method on PoolSetTick stores tick state under its encoded tick key.
Parameters:
- tick: tick index to store.
- tickInfo: tick state associated with the index.
func SetTickBitmap
method on PoolSetTickBitmap stores one initialized-tick bitmap word.
Parameters:
- wordPos: signed bitmap word position.
- tickBitmap: encoded bitmap bits for that word.
func SetTickBitmaps
method on PoolSetTickBitmaps replaces the map of initialized-tick bitmap words.
Parameters:
- tickBitmaps: bitmap words keyed by signed word position.
func SetTickSpacing
method on PoolSetTickSpacing stores the permitted spacing between initialized ticks.
Parameters:
- tickSpacing: tick spacing to configure for the pool.
func SetTicks
method on PoolSetTicks replaces the tree containing pool tick state.
Parameters:
- ticks: tick storage tree to use.
func SetToken0Path
method on PoolPool Setters methods SetToken0Path stores the path of the pool's token0 asset.
Parameters:
- token0Path: token0 asset path to store.
func SetToken1Path
method on PoolSetToken1Path stores the path of the pool's token1 asset.
Parameters:
- token1Path: token1 asset path to store.
func Slot0
method on PoolSlot0 returns the pool's current price, tick, lock, and oracle cursor state.
Returns:
- Slot0: current slot0 state, including the price and observation metadata.
func Slot0FeeProtocol
method on PoolSlot0FeeProtocol returns the packed protocol-fee denominators from slot0.
Returns:
- uint8: packed token0/token1 protocol-fee denominator configuration.
func Slot0SqrtPriceX96
method on PoolSlot0SqrtPriceX96 returns the current square-root price in Q96 fixed-point form.
Returns:
- *u256.Uint: stored sqrt(token1/token0) price scaled by 2^96.
func Slot0Tick
method on PoolSlot0Tick returns the current pool tick.
Returns:
- int32: tick corresponding to the current pool price.
func Slot0Unlocked
method on PoolSlot0Unlocked reports whether the pool is currently available for reentrant operations.
Returns:
- bool: true when the pool is unlocked; false while its swap lock is held.
func TickBitmaps
method on PoolTickBitmaps returns the map of initialized-tick bitmap words.
Returns:
- map[int16]string: bitmap words keyed by signed word position.
func TickSpacing
method on PoolTickSpacing returns the permitted spacing between initialized ticks.
Returns:
- int32: tick spacing configured for the pool.
func Ticks
method on PoolTicks returns the tree containing tick state keyed by encoded tick.
Returns:
- *bptree.BPTree: pool tick storage tree.
func Token0Path
method on PoolToken0Path returns the path of the pool's token0 asset.
Returns:
- string: token0 path stored in the pool.
func Token1Path
method on PoolToken1Path returns the path of the pool's token1 asset.
Returns:
- string: token1 path stored in the pool.
type PositionInfo
struct 1type PositionInfo struct {
2 liquidity string // aggregate liquidity for this tick-range key
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 token0 amount waiting to be collected (principal or swap fee)
7 tokensOwed0 int64
8
9 // accumulated token1 amount waiting to be collected (principal or swap fee)
10 tokensOwed1 int64
11}PositionInfo stores aggregate liquidity, fee-growth checkpoints, and tokens owed for one pool-scoped lower/upper tick key.
Methods on PositionInfo
func FeeGrowthInside0LastX128
method on PositionInfoFeeGrowthInside0LastX128 returns the token0 fee-growth checkpoint for this position.
Returns:
- string: token0 inside fee-growth checkpoint scaled by 2^128.
func FeeGrowthInside1LastX128
method on PositionInfoFeeGrowthInside1LastX128 returns the token1 fee-growth checkpoint for this position.
Returns:
- string: token1 inside fee-growth checkpoint scaled by 2^128.
func Liquidity
method on PositionInfoLiquidity returns aggregate liquidity for this position range.
Returns:
- string: position liquidity encoded as a decimal string.
func SetFeeGrowthInside0LastX128
method on PositionInfoSetFeeGrowthInside0LastX128 updates the token0 fee-growth checkpoint.
Parameters:
- feeGrowthInside0LastX128: token0 inside fee-growth checkpoint scaled by 2^128, encoded as a decimal string.
func SetFeeGrowthInside1LastX128
method on PositionInfoSetFeeGrowthInside1LastX128 updates the token1 fee-growth checkpoint.
Parameters:
- feeGrowthInside1LastX128: token1 inside fee-growth checkpoint scaled by 2^128, encoded as a decimal string.
func SetLiquidity
method on PositionInfoSetLiquidity updates aggregate liquidity for this position range.
Parameters:
- liquidity: position liquidity encoded as a decimal string.
func SetTokensOwed0
method on PositionInfoSetTokensOwed0 updates token0 accumulated for this position.
Parameters:
- tokensOwed0: token0 principal or fee amount awaiting collection.
func SetTokensOwed1
method on PositionInfoSetTokensOwed1 updates token1 accumulated for this position.
Parameters:
- tokensOwed1: token1 principal or fee amount awaiting collection.
func TokensOwed0
method on PositionInfoTokensOwed0 returns token0 accumulated for this position.
Returns:
- int64: token0 principal or fee amount awaiting collection.
func TokensOwed1
method on PositionInfoTokensOwed1 returns token1 accumulated for this position.
Returns:
- int64: token1 principal or fee amount awaiting collection.
type 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 // packed protocol-fee denominators: token0 low nibble, token1 high nibble
5 unlocked bool // whether the pool is currently locked to reentrancy
6 observationIndex uint16 // the index of the most-recently written observation
7 observationCardinality uint16 // the current maximum number of observations stored
8 observationCardinalityNext uint16 // the next maximum number of observations to store
9}Slot0 mirrors Uniswap V3's slot0(): current price/tick/protocol-fee/lock state and the oracle cursor/capacity metadata.
Methods on Slot0
func Clone
method on Slot0Clone returns a value-type copy of Slot0 that shares no mutable state with the original, so callers cannot reach back into pool internals through the returned sqrtPriceX96 pointer.
Returns:
- Slot0: value copy with a cloned sqrt-price pointer.
func FeeProtocol
method on Slot0FeeProtocol returns the packed protocol-fee denominators in slot0.
Returns:
- uint8: packed token0/token1 protocol-fee denominator configuration.
func ObservationCardinality
method on Slot0ObservationCardinality returns the number of observation slots currently available.
Returns:
- uint16: current observation capacity.
func ObservationCardinalityNext
method on Slot0ObservationCardinalityNext returns the requested future observation capacity.
Returns:
- uint16: next observation capacity to use when the ring grows.
func ObservationIndex
method on Slot0ObservationIndex returns the index of the most recently written observation.
Returns:
- uint16: current observation ring-buffer index.
func SetFeeProtocol
method on Slot0SetFeeProtocol updates the packed slot0 protocol-fee denominators.
Parameters:
- feeProtocol: packed token0/token1 protocol-fee denominator configuration.
func SetObservationCardinality
method on Slot0SetObservationCardinality updates the current observation capacity.
Parameters:
- observationCardinality: current number of observation slots available.
func SetObservationCardinalityNext
method on Slot0SetObservationCardinalityNext updates the requested future observation capacity.
Parameters:
- observationCardinalityNext: next capacity to use when the ring grows.
func SetObservationIndex
method on Slot0SetObservationIndex updates the index of the most recently written observation.
Parameters:
- observationIndex: observation ring-buffer index to store.
func SetSqrtPriceX96
method on Slot0SetSqrtPriceX96 updates the slot0 sqrt price.
Parameters:
- sqrtPriceX96: sqrt(token1/token0) price scaled by 2^96; it is cloned before storage.
func SetTick
method on Slot0SetTick updates the current slot0 tick.
Parameters:
- tick: current pool tick to store.
func SetUnlocked
method on Slot0SetUnlocked updates the slot0 reentrancy-lock state.
Parameters:
- unlocked: true to mark the pool unlocked, false to mark it locked.
func SqrtPriceX96
method on Slot0SqrtPriceX96 returns a copy of the current sqrt price in Q96 fixed-point form.
Returns:
- *u256.Uint: cloned sqrt(token1/token0) price scaled by 2^96.
func Tick
method on Slot0Tick returns the current pool tick recorded in slot0.
Returns:
- int32: current tick.
func Unlocked
method on Slot0Unlocked reports whether the pool's reentrancy lock is open.
Returns:
- bool: true when unlocked and false while the pool is locked.
type 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 TickInfoClone returns an independent value copy of this tick's stored state.
Returns:
- TickInfo: copied liquidity, fee-growth, time, and initialization fields.
func FeeGrowthOutside0X128
method on TickInfoFeeGrowthOutside0X128 returns token0 fee growth on the side of this tick opposite the current tick.
Returns:
- string: token0 outside fee-growth accumulator scaled by 2^128.
func FeeGrowthOutside1X128
method on TickInfoFeeGrowthOutside1X128 returns token1 fee growth on the side of this tick opposite the current tick.
Returns:
- string: token1 outside fee-growth accumulator scaled by 2^128.
func Initialized
method on TickInfoInitialized reports whether this tick has active initialized state.
Returns:
- bool: true when the tick is initialized; false otherwise.
func LiquidityGross
method on TickInfoTickInfo Getters methods LiquidityGross returns total position liquidity referencing this tick.
Returns:
- string: gross liquidity encoded as a decimal string.
func LiquidityNet
method on TickInfoLiquidityNet returns net liquidity applied when this tick is crossed.
Returns:
- string: signed net liquidity encoded as a decimal string.
func SecondsOutside
method on TickInfoSecondsOutside returns the time spent on the side of this tick opposite the current tick.
Returns:
- uint32: seconds accumulated outside the tick.
func SecondsPerLiquidityOutsideX128
method on TickInfoSecondsPerLiquidityOutsideX128 returns seconds per liquidity outside this tick.
Returns:
- string: outside seconds-per-liquidity accumulator scaled by 2^128.
func SetFeeGrowthOutside0X128
method on TickInfoSetFeeGrowthOutside0X128 stores token0 outside fee growth for this tick.
Parameters:
- feeGrowthOutside0X128: token0 outside fee growth scaled by 2^128, encoded as a decimal string.
func SetFeeGrowthOutside1X128
method on TickInfoSetFeeGrowthOutside1X128 stores token1 outside fee growth for this tick.
Parameters:
- feeGrowthOutside1X128: token1 outside fee growth scaled by 2^128, encoded as a decimal string.
func SetInitialized
method on TickInfoSetInitialized updates whether this tick is initialized.
Parameters:
- initialized: true to mark the tick initialized, false otherwise.
func SetLiquidityGross
method on TickInfoTickInfo Setters methods SetLiquidityGross stores total position liquidity referencing this tick.
Parameters:
- liquidityGross: gross liquidity encoded as a decimal string.
func SetLiquidityNet
method on TickInfoSetLiquidityNet stores the net liquidity change applied when crossing this tick.
Parameters:
- liquidityNet: signed net liquidity encoded as a decimal string.
func SetSecondsOutside
method on TickInfoSetSecondsOutside stores the seconds accumulated outside this tick.
Parameters:
- secondsOutside: elapsed seconds outside the tick.
func SetSecondsPerLiquidityOutsideX128
method on TickInfoSetSecondsPerLiquidityOutsideX128 stores outside seconds-per-liquidity growth.
Parameters:
- secondsPerLiquidityOutsideX128: outside seconds per liquidity scaled by 2^128, encoded as a decimal string.
func SetTickCumulativeOutside
method on TickInfoSetTickCumulativeOutside stores cumulative tick value outside this tick.
Parameters:
- tickCumulativeOutside: cumulative tick value on the opposite side.
func TickCumulativeOutside
method on TickInfoTickCumulativeOutside returns cumulative tick value on the side opposite the current tick.
Returns:
- int64: outside cumulative tick value.
type TokenPair
structMethods on TokenPair
func SetToken0
method on TokenPairSetToken0 updates the token0 amount in the pair.
Parameters:
- token0: token0 amount to store.
func SetToken1
method on TokenPairSetToken1 updates the token1 amount in the pair.
Parameters:
- token1: token1 amount to store.
func Token0
method on TokenPairToken0 returns the token0 amount in the pair.
Returns:
- int64: stored token0 amount.
func Token1
method on TokenPairToken1 returns the token1 amount in the pair.
Returns:
- int64: stored token1 amount.
12
- errors stdlib
- gno.land/p/gnoswap/store/v1 package
- gno.land/p/gnoswap/uint256/v1 package
- gno.land/p/gnoswap/utils/v1 package
- gno.land/p/gnoswap/version_manager/v1 package
- gno.land/p/nt/bptree/rotree/v0 package
- gno.land/p/nt/bptree/v0 package
- gno.land/p/nt/ufmt/v0 package
- gno.land/r/gnoswap/access/v1 realm
- gno.land/r/gnoswap/rbac/v1 realm
- strconv stdlib
- strings stdlib