Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Playground

assert.gno

package pool

import (
	ufmt "gno.land/p/nt/ufmt/v0"
	pl "gno.land/r/gnoswap/pool"
)

func assertIsNotUserCall(_ int, rlm realm) {
	previousRealm := rlm.Previous()
	if previousRealm.IsUserCall() {
		panic(newErrorWithDetail(
			errNotAccessEOA,
			ufmt.Sprintf("previousRealm(%s) is EOA", previousRealm.Address()),
		))
	}
}

// assertIsNotEqualsTokens asserts that the token0Path and token1Path are not equal.
func assertIsNotEqualsTokens(token0Path, token1Path string) {
	if token0Path == token1Path {
		panic(newErrorWithDetail(
			errDuplicateTokenInPool,
			ufmt.Sprintf("expected token0Path(%s) != token1Path(%s)", token0Path, token1Path),
		))
	}
}

// assertIsSupportedFeeTier asserts that the fee is a supported fee tier.
func assertIsSupportedFeeTier(fee uint32) {
	if !isValidFeeTier(fee) {
		panic(newErrorWithDetail(
			errUnsupportedFeeTier,
			ufmt.Sprintf("expected fee(%d) to be one of %d, %d, %d, %d", fee, FeeTier100, FeeTier500, FeeTier3000, FeeTier10000),
		))
	}
}

// assertIsNotExistsPoolPath asserts that the pool path does not exist.
func assertIsNotExistsPoolPath(instance *poolV1, token0Path, token1Path string, fee uint32) {
	poolPath := pl.GetPoolPath(token0Path, token1Path, fee)

	pools := instance.store.GetPools()
	if pools.Has(poolPath) {
		panic(newErrorWithDetail(
			errPoolAlreadyExists,
			ufmt.Sprintf("expected poolPath(%s:%s:%d) not to exist", token0Path, token1Path, fee),
		))
	}
}

func assertIsValidTokenOrder(token0Path, token1Path string) {
	if token0Path >= token1Path {
		panic(newErrorWithDetail(
			errInvalidInput,
			ufmt.Sprintf("expected token0Path(%s) < token1Path(%s)", token0Path, token1Path),
		))
	}
}

doc.gno

// package v1 implements GnoSwap's concentrated liquidity pools based on Uniswap V3.
// It manages liquidity positions, executes swaps, and maintains pool state including
// price, liquidity, and fee calculations.
//
// The pool contract is the core of the GnoSwap AMM, supporting:
// - Concentrated liquidity within custom price ranges
// - Multiple fee tiers (0.01%, 0.05%, 0.3%, 1%)
// - Single-tick and cross-tick swaps
// - Protocol fee collection
// - Tick bitmap optimization for gas efficiency
package pool

errors.gno

package pool

import (
	ufmt "gno.land/p/nt/ufmt/v0"
)

// Error definitions for pool operations
const (
	errUnsupportedFeeTier        = "[GNOSWAP-POOL-001] unsupported fee tier"
	errPoolAlreadyExists         = "[GNOSWAP-POOL-002] pool already created"
	errOutOfRange                = "[GNOSWAP-POOL-003] out of range for numeric value"
	errInvalidInput              = "[GNOSWAP-POOL-004] invalid input data"
	errDataNotFound              = "[GNOSWAP-POOL-005] requested data not found"
	errLiquidityCalculation      = "[GNOSWAP-POOL-006] invalid liquidity calculated"
	errZeroLiquidity             = "[GNOSWAP-POOL-007] zero liquidity"
	errDuplicateTokenInPool      = "[GNOSWAP-POOL-008] same token used in single pool"
	errTickLowerInvalid          = "[GNOSWAP-POOL-009] tickLower is invalid"
	errTickUpperInvalid          = "[GNOSWAP-POOL-010] tickUpper is invalid"
	errInvalidSwapAmount         = "[GNOSWAP-POOL-011] invalid swap amount"
	errInvalidProtocolFeePct     = "[GNOSWAP-POOL-012] invalid protocol fee percentage"
	errInvalidWithdrawalFeePct   = "[GNOSWAP-POOL-013] invalid withdrawal fee percentage"
	errLockedPool                = "[GNOSWAP-POOL-014] cannot modify pool while locked"
	errPriceOutOfRange           = "[GNOSWAP-POOL-015] swap price out of range"
	errTransferFailed            = "[GNOSWAP-POOL-016] token transfer failed"
	errInvalidTickAndTickSpacing = "[GNOSWAP-POOL-017] invalid tick and tick spacing requested"
	errInvalidTickRange          = "[GNOSWAP-POOL-018] tickLower is greater than or equal to tickUpper"
	errUnderflow                 = "[GNOSWAP-POOL-019] underflow"
	errOverflow                  = "[GNOSWAP-POOL-020] overflow"
	errBalanceUpdateFailed       = "[GNOSWAP-POOL-021] balance update failed"
	errNotAccessEOA              = "[GNOSWAP-POOL-022] not access EOA"
	errInsufficientPayment       = "[GNOSWAP-POOL-023] insufficient payment"
	errNotInitializedObservation = "[GNOSWAP-POOL-024] not initialized observation"
	errObservationTooOld         = "[GNOSWAP-POOL-025] target timestamp before oldest observation"
	errObservationBeforeEpoch    = "[GNOSWAP-POOL-026] lookback window starts before unix epoch"
	errInsufficientPoolBalance   = "[GNOSWAP-POOL-027] insufficient pool balance for swap"
)

// newErrorWithDetail adds detail to an error message.
func newErrorWithDetail(message string, detail string) string {
	finalErr := ufmt.Errorf("%s || %s", message, detail)
	return finalErr.Error()
}

// makeErrorWithDetails creates an error with additional context.
func makeErrorWithDetails(message string, details string) error {
	return ufmt.Errorf("%s || %s", message, details)
}

event_info.gno

package pool

import (
	"gno.land/p/gnoswap/utils/v1"

	pl "gno.land/r/gnoswap/pool"
)

type tickEventInfo struct {
	tickID   int32
	tickInfo pl.TickInfo
}

// ToString serializes tick event information as a compact JSON object.
// The object includes the tick index and every persisted TickInfo field using
// the short event keys documented below.
//
// Returns:
//   - string: JSON object containing tick, liquidity, fee-growth, cumulative-time, and initialization fields.
func (t *tickEventInfo) ToString() string {
	return "{\"t\":" + utils.FormatInt(t.tickID) +
		",\"lg\":\"" + t.tickInfo.LiquidityGross() + "\"" +
		",\"ln\":\"" + t.tickInfo.LiquidityNet() + "\"" +
		",\"fg0\":\"" + t.tickInfo.FeeGrowthOutside0X128() + "\"" +
		",\"fg1\":\"" + t.tickInfo.FeeGrowthOutside1X128() + "\"" +
		",\"tco\":\"" + utils.FormatInt(t.tickInfo.TickCumulativeOutside()) + "\"" +
		",\"spl\":\"" + t.tickInfo.SecondsPerLiquidityOutsideX128() + "\"" +
		",\"so\":\"" + utils.FormatUint(t.tickInfo.SecondsOutside()) + "\"" +
		",\"i\":\"" + utils.FormatBool(t.tickInfo.Initialized()) + "\"}"
}

// NewTickEventInfo creates event data for one tick and its persisted state.
//
// Parameters:
//   - tickID: tick index represented by the event.
//   - tickInfo: tick state whose fields are serialized by ToString.
//
// Returns:
//   - *tickEventInfo: event information value retaining the supplied tick index and state.
func NewTickEventInfo(tickID int32, tickInfo pl.TickInfo) *tickEventInfo {
	return &tickEventInfo{
		tickID:   tickID,
		tickInfo: tickInfo,
	}
}

factory_param.gno

package pool

import (
	"strings"

	"gno.land/p/gnoswap/consts/v1"
	u256 "gno.land/p/gnoswap/uint256/v1"
	ufmt "gno.land/p/nt/ufmt/v0"
	"gno.land/r/gnoswap/pool"
)

const (
	FeeTier100   uint32 = 100
	FeeTier500   uint32 = 500
	FeeTier3000  uint32 = 3000
	FeeTier10000 uint32 = 10000
)

const (
	MIN_SQRT_RATIO string = "4295128739"
	MAX_SQRT_RATIO string = "1461446703485210103287273052203988822378723970342"
)

// poolCreateConfig holds the essential parameters for creating a new pool.
type poolCreateConfig struct {
	token0Path       string
	token1Path       string
	fee              uint32
	sqrtPriceX96     *u256.Uint
	tickSpacing      int32
	slot0FeeProtocol uint8
}

// newPoolParams defines the essential parameters for creating a new pool.
func newPoolParams(
	token0Path string,
	token1Path string,
	fee uint32,
	sqrtPriceX96 string,
	tickSpacing int32,
	slot0FeeProtocol uint8,
) *poolCreateConfig {
	price := u256.MustFromDecimal(sqrtPriceX96)
	return &poolCreateConfig{
		token0Path:       token0Path,
		token1Path:       token1Path,
		fee:              fee,
		sqrtPriceX96:     price,
		tickSpacing:      tickSpacing,
		slot0FeeProtocol: slot0FeeProtocol,
	}
}

// Returns:
//   - sqrtPriceX96: configured initial square-root price as a mutable u256
//     integer in Q64.96 representation.
func (p *poolCreateConfig) SqrtPriceX96() *u256.Uint { return p.sqrtPriceX96 }

// Returns:
//   - tickSpacing: configured spacing between usable initialized ticks.
func (p *poolCreateConfig) TickSpacing() int32 { return p.tickSpacing }

// Returns:
//   - token0Path: configured token0 contract path.
func (p *poolCreateConfig) Token0Path() string { return p.token0Path }

// Returns:
//   - token1Path: configured token1 contract path.
func (p *poolCreateConfig) Token1Path() string { return p.token1Path }

// Returns:
//   - fee: configured pool fee tier as a uint32 fee-unit value.
func (p *poolCreateConfig) Fee() uint32 { return p.fee }

func (p *poolCreateConfig) update() error {
	token0Path := p.token0Path
	token1Path := p.token1Path

	// Always validate that the price is within valid range
	if err := validateSqrtPriceX96(p.sqrtPriceX96); err != nil {
		return err
	}

	if !p.isInOrder() {
		token0Path, token1Path = token1Path, token0Path

		// newPrice = 2^192 / oldPrice
		newPrice := u256.Zero().Div(consts.Q192(), p.sqrtPriceX96)

		// Check if calculated price is within valid range
		if err := validateSqrtPriceX96(newPrice); err != nil {
			return err
		}

		p.sqrtPriceX96 = newPrice
	}

	p.token0Path = token0Path
	p.token1Path = token1Path

	return nil
}

// isInOrder checks if token paths are in lexicographical (or, alphabetical) order
func (p *poolCreateConfig) isInOrder() bool {
	if strings.Compare(p.token0Path, p.token1Path) < 0 {
		return true
	}
	return false
}

func (p *poolCreateConfig) poolPath() string {
	return pool.GetPoolPath(p.token0Path, p.token1Path, p.fee)
}

// validateSqrtPriceX96 validates that the given sqrtPriceX96 is within valid range
func validateSqrtPriceX96(sqrtPriceX96 *u256.Uint) error {
	// Valid range is [minSqrtRatio, maxSqrtRatio) - same as TickMathGetTickAtSqrtRatio
	if sqrtPriceX96.Lt(consts.MinSqrtRatio()) || sqrtPriceX96.Gte(consts.MaxSqrtRatio()) {
		return makeErrorWithDetails(
			errOutOfRange,
			ufmt.Sprintf("sqrtPriceX96(%s) is out of range", sqrtPriceX96.ToString()),
		)
	}
	return nil
}

func isValidFeeTier(feeTier uint32) bool {
	switch feeTier {
	case FeeTier100, FeeTier500, FeeTier3000, FeeTier10000:
		return true
	}

	return false
}

getter.gno

package pool

import (
	"errors"
	"time"

	u256 "gno.land/p/gnoswap/uint256/v1"
	rotree "gno.land/p/nt/bptree/rotree/v0"
	ufmt "gno.land/p/nt/ufmt/v0"
	pl "gno.land/r/gnoswap/pool"
)

// GetPoolPath generates a unique pool path string based on the token paths and fee tier.
// Parameters:
//   - token0Path: first token contract path; pool paths canonicalize token order.
//   - token1Path: second token contract path; pool paths canonicalize token order.
//   - fee: fee tier encoded in the pool identifier.
//
// Returns:
//   - poolPath: canonical token0:token1:fee pool identifier.
func GetPoolPath(token0Path, token1Path string, fee uint32) string {
	return pl.GetPoolPath(token0Path, token1Path, fee)
}

// GetFeeAmountTickSpacing retrieves the tick spacing associated with a given fee amount.
// Parameters:
//   - fee: fee tier whose configured tick spacing is requested.
//
// Returns:
//   - spacing: configured signed tick interval for fee.
//   - err: nil when fee is configured; an unsupported-fee error otherwise.
func (i *poolV1) GetFeeAmountTickSpacing(fee uint32) (spacing int32, err error) {
	feeAmountTickSpacing := i.store.GetFeeAmountTickSpacing()

	spacing, exist := feeAmountTickSpacing[fee]
	if !exist {
		return 0, errors.New(newErrorWithDetail(
			errUnsupportedFeeTier,
			ufmt.Sprintf("expected fee(%d) to be one of %d, %d, %d, %d", fee, FeeTier100, FeeTier500, FeeTier3000, FeeTier10000),
		))
	}

	return spacing, nil
}

// Parameters:
//   - poolPath: canonical pool identifier to look up.
//
// Returns:
//   - token0Path: canonical token0 contract path stored in the pool.
//   - err: nil when the pool exists; the pool lookup error otherwise.
func (i *poolV1) GetToken0Path(poolPath string) (string, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return "", err
	}
	return pool.Token0Path(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier to look up.
//
// Returns:
//   - token1Path: canonical token1 contract path stored in the pool.
//   - err: nil when the pool exists; the pool lookup error otherwise.
func (i *poolV1) GetToken1Path(poolPath string) (string, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return "", err
	}
	return pool.Token1Path(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier to look up.
//
// Returns:
//   - fee: configured fee tier stored in the pool.
//   - err: nil when the pool exists; the pool lookup error otherwise.
func (i *poolV1) GetFee(poolPath string) (uint32, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return 0, err
	}
	return pool.Fee(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier to look up.
//
// Returns:
//   - balanceToken0: pool-held token0 balance in the token's smallest unit.
//   - err: nil when the pool exists; the pool lookup error otherwise.
func (i *poolV1) GetBalanceToken0(poolPath string) (int64, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return 0, err
	}
	return pool.BalanceToken0(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier to look up.
//
// Returns:
//   - balanceToken1: pool-held token1 balance in the token's smallest unit.
//   - err: nil when the pool exists; the pool lookup error otherwise.
func (i *poolV1) GetBalanceToken1(poolPath string) (int64, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return 0, err
	}
	return pool.BalanceToken1(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier to look up.
//
// Returns:
//   - tickSpacing: configured signed interval between usable initialized ticks.
//   - err: nil when the pool exists; the pool lookup error otherwise.
func (i *poolV1) GetTickSpacing(poolPath string) (int32, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return 0, err
	}
	return pool.TickSpacing(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier to look up.
//
// Returns:
//   - maxLiquidity: decimal representation of the maximum liquidity permitted
//     at one tick for the pool's tick spacing.
//   - err: nil when the pool exists; the pool lookup error otherwise.
func (i *poolV1) GetMaxLiquidityPerTick(poolPath string) (string, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return "", err
	}
	return calculateMaxLiquidityPerTick(pool.TickSpacing()).ToString(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier to look up.
//
// Returns:
//   - feeProtocol: packed token0/token1 protocol-fee denominator configuration
//     stored in slot0.
//   - err: nil when the pool exists; the pool lookup error otherwise.
func (i *poolV1) GetSlot0FeeProtocol(poolPath string) (uint8, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return 0, err
	}
	return pool.Slot0FeeProtocol(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier to look up.
//
// Returns:
//   - unlocked: true when the pool's slot0 reentrancy lock is open.
//   - err: nil when the pool exists; the pool lookup error otherwise.
func (i *poolV1) GetSlot0Unlocked(poolPath string) (bool, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return false, err
	}
	return pool.Slot0Unlocked(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier to look up.
//
// Returns:
//   - slot0: current pool price, tick, observation, and lock metadata; panics
//     when poolPath does not identify an existing pool.
func (i *poolV1) GetSlot0(poolPath string) pl.Slot0 {
	return i.mustGetPool(poolPath).Slot0()
}

// Parameters:
//   - poolPath: canonical pool identifier containing the observation ring.
//   - index: observation slot index; in-range unwritten slots return a default
//     observation, while indices at or above maxObservationCardinality error.
//
// Returns:
//   - observation: observation stored at index, or the default zero observation
//     for an in-range slot that has never been written.
//   - err: nil for a valid pool and index; a pool, observation, or range error
//     otherwise.
func (i *poolV1) GetObservationAt(poolPath string, index uint16) (pl.Observation, error) {
	if _, err := i.getPool(poolPath); err != nil {
		return pl.DefaultObservation(), err
	}

	// Uniswap's observations(uint256) getter is backed by a fixed-size array:
	// an in-range but never-written slot returns the zero observation, while an
	// out-of-range index reverts.
	if index >= maxObservationCardinality {
		return pl.DefaultObservation(), makeErrorWithDetails(errDataNotFound, ufmt.Sprintf("observation index %d out of range", index))
	}

	observations, err := i.getObservations(poolPath)
	if err != nil {
		return pl.DefaultObservation(), err
	}

	observation, ok := observations.Get(index)
	if !ok {
		return pl.DefaultObservation(), nil
	}

	return observation, nil
}

// Observe returns the tick and seconds-per-liquidity cumulatives for each
// requested lookback. It reads the current block timestamp once and never
// writes an observation, matching Uniswap V3's view-only observe call.
// Parameters:
//   - poolPath: canonical pool identifier whose observation history is queried.
//   - secondsAgos: lookback durations in seconds; one cumulative pair is
//     produced for each entry, with zero meaning the current cumulative value.
//
// Returns:
//   - tickCumulatives: cumulative tick values aligned by index with secondsAgos.
//   - secondsPerLiquidityCumulativeX128s: cumulative seconds-per-liquidity
//     values aligned with secondsAgos and scaled by 2^128 as decimal strings.
//   - err: nil when every requested lookback can be resolved; an observation
//     history, epoch, cardinality, or interpolation error otherwise.
func (i *poolV1) Observe(poolPath string, secondsAgos []uint32) ([]int64, []string, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return nil, nil, err
	}

	observations, err := i.getObservations(poolPath)
	if err != nil {
		return nil, nil, err
	}

	slot0 := pool.Slot0()
	return observe(
		observations,
		time.Now().Unix(),
		secondsAgos,
		slot0.Tick(),
		slot0.ObservationIndex(),
		pool.Liquidity(),
		slot0.ObservationCardinality(),
	)
}

// SnapshotCumulativesInside returns the oracle accumulators that accrued while
// the pool price was inside [tickLower, tickUpper).
// Parameters:
//   - poolPath: canonical pool identifier whose oracle accumulators are queried.
//   - tickLower: inclusive lower tick boundary of the range.
//   - tickUpper: exclusive upper tick boundary of the range.
//
// Returns:
//   - tickCumulativeInside: cumulative tick value accrued while price was
//     inside [tickLower, tickUpper).
//   - secondsPerLiquidityInsideX128: seconds-per-liquidity accumulator accrued
//     inside the range, scaled by 2^128.
//   - secondsInside: number of seconds during which price was inside the range.
//   - err: nil when bounds, boundary ticks, and observations are valid; the
//     corresponding validation or observation error otherwise.
func (i *poolV1) SnapshotCumulativesInside(
	poolPath string,
	tickLower int32,
	tickUpper int32,
) (int64, *u256.Uint, uint32, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return 0, nil, 0, err
	}

	observations, err := i.getObservations(poolPath)
	if err != nil {
		return 0, nil, 0, err
	}

	return snapshotCumulativesInside(pool, observations, tickLower, tickUpper)
}

// Parameters:
//   - poolPath: canonical pool identifier to look up.
//
// Returns:
//   - feeGrowthGlobal0X128: global token0 fee-growth accumulator scaled by 2^128.
//   - err: nil when the pool exists; the pool lookup error otherwise.
func (i *poolV1) GetFeeGrowthGlobal0X128(poolPath string) (*u256.Uint, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return nil, err
	}
	return pool.FeeGrowthGlobal0X128(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier to look up.
//
// Returns:
//   - feeGrowthGlobal1X128: global token1 fee-growth accumulator scaled by 2^128.
//   - err: nil when the pool exists; the pool lookup error otherwise.
func (i *poolV1) GetFeeGrowthGlobal1X128(poolPath string) (*u256.Uint, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return nil, err
	}
	return pool.FeeGrowthGlobal1X128(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier to look up.
//
// Returns:
//   - protocolFeesToken0: protocol fees accrued in token0's smallest unit.
//   - err: nil when the pool exists; the pool lookup error otherwise.
func (i *poolV1) GetProtocolFeesToken0(poolPath string) (int64, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return 0, err
	}
	return pool.ProtocolFeesToken0(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier to look up.
//
// Returns:
//   - protocolFeesToken1: protocol fees accrued in token1's smallest unit.
//   - err: nil when the pool exists; the pool lookup error otherwise.
func (i *poolV1) GetProtocolFeesToken1(poolPath string) (int64, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return 0, err
	}
	return pool.ProtocolFeesToken1(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier to look up.
//
// Returns:
//   - liquidity: current active pool liquidity as a u256 integer.
//   - err: nil when the pool exists; the pool lookup error otherwise.
func (i *poolV1) GetLiquidity(poolPath string) (*u256.Uint, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return nil, err
	}
	return pool.Liquidity(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier containing the position.
//   - key: position key identifying its lower and upper tick range.
//
// Returns:
//   - position: pointer to a copy of the stored position information; panics
//     when the pool or position is absent or has an unexpected type.
func (i *poolV1) MustGetPosition(poolPath, key string) *pl.PositionInfo {
	pool := i.mustGetPool(poolPath)

	positions := pool.Positions()

	result := positions.Get(key)
	if result == nil {
		panic(newErrorWithDetail(
			errDataNotFound,
			ufmt.Sprintf("expected position(%s) to exist", key),
		))
	}

	position, ok := result.(pl.PositionInfo)
	if !ok {
		panic("failed to cast position to PositionInfo")
	}

	return &position
}

// Parameters:
//   - poolPath: canonical pool identifier containing the position.
//   - key: position key identifying its lower and upper tick range.
//
// Returns:
//   - feeGrowthInside0LastX128: token0 fee-growth-inside value last accounted
//     for the position, encoded as a decimal integer scaled by 2^128.
//   - err: nil when pool and position exist; the lookup error otherwise.
func (i *poolV1) GetPositionFeeGrowthInside0LastX128(poolPath, key string) (string, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return "", err
	}
	position, err := pool.GetPosition(key)
	if err != nil {
		return "", err
	}
	return position.FeeGrowthInside0LastX128(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier containing the position.
//   - key: position key identifying its lower and upper tick range.
//
// Returns:
//   - feeGrowthInside1LastX128: token1 fee-growth-inside value last accounted
//     for the position, encoded as a decimal integer scaled by 2^128.
//   - err: nil when pool and position exist; the lookup error otherwise.
func (i *poolV1) GetPositionFeeGrowthInside1LastX128(poolPath, key string) (string, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return "", err
	}
	position, err := pool.GetPosition(key)
	if err != nil {
		return "", err
	}
	return position.FeeGrowthInside1LastX128(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier containing the position.
//   - key: position key identifying its lower and upper tick range.
//
// Returns:
//   - tokensOwed0: token0 fees owed to the position in token0's smallest unit.
//   - err: nil when pool and position exist; the lookup error otherwise.
func (i *poolV1) GetPositionTokensOwed0(poolPath, key string) (int64, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return 0, err
	}
	position, err := pool.GetPosition(key)
	if err != nil {
		return 0, err
	}
	return position.TokensOwed0(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier containing the position.
//   - key: position key identifying its lower and upper tick range.
//
// Returns:
//   - tokensOwed1: token1 fees owed to the position in token1's smallest unit.
//   - err: nil when pool and position exist; the lookup error otherwise.
func (i *poolV1) GetPositionTokensOwed1(poolPath, key string) (int64, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return 0, err
	}
	position, err := pool.GetPosition(key)
	if err != nil {
		return 0, err
	}
	return position.TokensOwed1(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier containing the tick.
//   - tick: signed tick index whose gross liquidity is requested.
//
// Returns:
//   - liquidityGross: total liquidity referencing the tick, encoded as a decimal
//     integer string.
//   - err: nil when pool and tick exist; the lookup error otherwise.
func (i *poolV1) GetTickLiquidityGross(poolPath string, tick int32) (string, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return "", err
	}

	tickInfo, err := pool.GetTick(tick)
	if err != nil {
		return "", err
	}
	return tickInfo.LiquidityGross(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier containing the tick.
//   - tick: signed tick index whose net liquidity change is requested.
//
// Returns:
//   - liquidityNet: signed net liquidity change applied when crossing the tick,
//     encoded as a decimal integer string.
//   - err: nil when pool and tick exist; the lookup error otherwise.
func (i *poolV1) GetTickLiquidityNet(poolPath string, tick int32) (string, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return "", err
	}

	tickInfo, err := pool.GetTick(tick)
	if err != nil {
		return "", err
	}
	return tickInfo.LiquidityNet(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier containing the tick.
//   - tick: signed tick index whose token0 fee-growth-outside value is requested.
//
// Returns:
//   - feeGrowthOutside0X128: token0 fee-growth-outside accumulator scaled by
//     2^128, encoded as a decimal string.
//   - err: nil when pool and tick exist; the lookup error otherwise.
func (i *poolV1) GetTickFeeGrowthOutside0X128(poolPath string, tick int32) (string, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return "", err
	}

	tickInfo, err := pool.GetTick(tick)
	if err != nil {
		return "", err
	}
	return tickInfo.FeeGrowthOutside0X128(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier containing the tick.
//   - tick: signed tick index whose token1 fee-growth-outside value is requested.
//
// Returns:
//   - feeGrowthOutside1X128: token1 fee-growth-outside accumulator scaled by
//     2^128, encoded as a decimal string.
//   - err: nil when pool and tick exist; the lookup error otherwise.
func (i *poolV1) GetTickFeeGrowthOutside1X128(poolPath string, tick int32) (string, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return "", err
	}

	tickInfo, err := pool.GetTick(tick)
	if err != nil {
		return "", err
	}
	return tickInfo.FeeGrowthOutside1X128(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier containing the tick.
//   - tick: signed tick index whose token fee-growth-outside values are requested.
//
// Returns:
//   - feeGrowthOutside0X128: token0 fee-growth-outside accumulator scaled by 2^128,
//     encoded as a decimal string.
//   - feeGrowthOutside1X128: token1 fee-growth-outside accumulator scaled by 2^128,
//     encoded as a decimal string.
//   - err: nil when pool and tick exist; the lookup error otherwise.
func (i *poolV1) GetTickFeeGrowthOutsideX128(poolPath string, tick int32) (string, string, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return "", "", err
	}

	tickInfo, err := pool.GetTick(tick)
	if err != nil {
		return "", "", err
	}

	return tickInfo.FeeGrowthOutside0X128(), tickInfo.FeeGrowthOutside1X128(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier containing the tick.
//   - tick: signed tick index whose cumulative tick-outside value is requested.
//
// Returns:
//   - tickCumulativeOutside: cumulative tick value recorded outside the tick's
//     active range.
//   - err: nil when pool and tick exist; the lookup error otherwise.
func (i *poolV1) GetTickCumulativeOutside(poolPath string, tick int32) (int64, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return 0, err
	}

	tickInfo, err := pool.GetTick(tick)
	if err != nil {
		return 0, err
	}
	return tickInfo.TickCumulativeOutside(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier containing the tick.
//   - tick: signed tick index whose seconds-per-liquidity accumulator is
//     requested.
//
// Returns:
//   - secondsPerLiquidityOutsideX128: seconds-per-liquidity-outside accumulator
//     encoded as a decimal integer scaled by 2^128.
//   - err: nil when pool and tick exist; the lookup error otherwise.
func (i *poolV1) GetTickSecondsPerLiquidityOutsideX128(poolPath string, tick int32) (string, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return "", err
	}

	tickInfo, err := pool.GetTick(tick)
	if err != nil {
		return "", err
	}
	return tickInfo.SecondsPerLiquidityOutsideX128(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier containing the tick.
//   - tick: signed tick index whose seconds-outside accumulator is requested.
//
// Returns:
//   - secondsOutside: seconds elapsed outside the tick's side of the active
//     range, as recorded by the pool.
//   - err: nil when pool and tick exist; the lookup error otherwise.
func (i *poolV1) GetTickSecondsOutside(poolPath string, tick int32) (uint32, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return 0, err
	}

	tickInfo, err := pool.GetTick(tick)
	if err != nil {
		return 0, err
	}
	return tickInfo.SecondsOutside(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier containing the tick.
//   - tick: signed tick index whose initialization flag is requested.
//
// Returns:
//   - initialized: true when the tick has been initialized in the pool.
//   - err: nil when pool and tick can be read; the lookup error otherwise.
func (i *poolV1) GetTickInitialized(poolPath string, tick int32) (bool, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return false, err
	}

	tickInfo, err := pool.GetTick(tick)
	if err != nil {
		return false, err
	}
	return tickInfo.Initialized(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier to look up.
//
// Returns:
//   - tick: current signed slot0 tick.
//   - err: nil when the pool exists; the pool lookup error otherwise.
func (i *poolV1) GetSlot0Tick(poolPath string) (int32, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return 0, err
	}
	return pool.Slot0Tick(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier to look up.
//
// Returns:
//   - sqrtPriceX96: current square-root price as a u256 Q64.96 integer.
//   - err: nil when the pool exists; the pool lookup error otherwise.
func (i *poolV1) GetSlot0SqrtPriceX96(poolPath string) (*u256.Uint, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return nil, err
	}
	return pool.Slot0SqrtPriceX96(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier to look up.
//
// Returns:
//   - feeGrowthGlobal0X128: global token0 fee-growth accumulator scaled by 2^128.
//   - feeGrowthGlobal1X128: global token1 fee-growth accumulator scaled by 2^128.
//   - err: nil when the pool exists; the pool lookup error otherwise.
func (i *poolV1) GetFeeGrowthGlobalX128(poolPath string) (*u256.Uint, *u256.Uint, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return nil, nil, err
	}
	return pool.FeeGrowthGlobal0X128(), pool.FeeGrowthGlobal1X128(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier containing the position.
//   - key: position key identifying its lower and upper tick range.
//
// Returns:
//   - feeGrowthInside0LastX128: token0 fee-growth-inside value last accounted
//     for the position, encoded as a decimal integer scaled by 2^128.
//   - feeGrowthInside1LastX128: token1 fee-growth-inside value last accounted
//     for the position, encoded as a decimal integer scaled by 2^128.
//   - err: nil when pool and position exist; the lookup error otherwise.
func (i *poolV1) GetPositionFeeGrowthInsideLastX128(poolPath, key string) (string, string, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return "", "", err
	}
	position, err := pool.GetPosition(key)
	if err != nil {
		return "", "", err
	}
	return position.FeeGrowthInside0LastX128(),
		position.FeeGrowthInside1LastX128(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier containing the position.
//   - key: position key identifying its lower and upper tick range.
//
// Returns:
//   - liquidity: position liquidity encoded as a decimal integer string.
//   - err: nil when pool and position exist; the lookup error otherwise.
func (i *poolV1) GetPositionLiquidity(poolPath, key string) (string, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return "", err
	}
	position, err := pool.GetPosition(key)
	if err != nil {
		return "", err
	}
	return position.Liquidity(), nil
}

// Parameters:
//   - poolPath: canonical pool identifier whose existence is checked.
//
// Returns:
//   - exists: true when the pool tree contains poolPath.
func (i *poolV1) ExistsPoolPath(poolPath string) bool {
	pools := i.store.GetPools()
	return pools.Has(poolPath)
}

// Returns:
//   - poolCreationFee: configured pool-creation charge in the chain's smallest
//     currency unit.
func (i *poolV1) GetPoolCreationFee() int64 {
	return i.store.GetPoolCreationFee()
}

// Returns:
//   - withdrawalFeeBPS: configured withdrawal fee in basis points, where 100
//     basis points equals one percent.
func (i *poolV1) GetWithdrawalFee() uint64 {
	return i.store.GetWithdrawalFeeBPS()
}

// OracleConsult returns the time-weighted average price for a pool over a specified period.
//
// Parameters:
//   - poolPath: canonical pool identifier whose observations are consulted.
//   - secondsAgo: lookback duration in seconds for the time-weighted query.
//
// Returns:
//   - arithmeticMeanTick: arithmetic mean tick over the requested lookback.
//   - harmonicMeanLiquidity: harmonic mean active liquidity as a u256 integer.
//   - err: nil when the pool history covers secondsAgo; an observation or
//     lookback error otherwise.
func (i *poolV1) OracleConsult(poolPath string, secondsAgo uint32) (int32, *u256.Uint, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return 0, nil, err
	}

	observations, err := i.getObservations(poolPath)
	if err != nil {
		return 0, nil, err
	}

	tick, liquidity, err := oracleConsult(pool, observations, secondsAgo)
	if err != nil {
		return 0, nil, err
	}

	return tick, liquidity, nil
}

// GetPools returns a read-only view of every pool, keyed by pool path.
// Callers paginate it themselves through IterateByOffset.
// Returns:
//   - pools: read-only tree keyed by canonical pool path; entries are exposed
//     through safe read-only wrappers and callers paginate the tree themselves.
func (i *poolV1) GetPools() *rotree.ReadOnlyTree {
	return rotree.Wrap(i.store.GetPools(), clonePoolEntry)
}

// GetFeeAmountTickSpacings returns all fee tier to tick spacing mappings.
// Returns:
//   - feeAmountTickSpacings: copy of the configured fee-tier to tick-spacing
//     mapping.
func (i *poolV1) GetFeeAmountTickSpacings() map[uint32]int32 {
	return i.store.GetFeeAmountTickSpacing()
}

// GetPoolPositions returns a read-only view of a pool's positions, keyed by
// position key. Callers paginate it themselves through IterateByOffset.
// nil is returned when the pool does not exist.
// Parameters:
//   - poolPath: canonical pool identifier whose positions are exposed.
//
// Returns:
//   - positions: read-only tree keyed by position key, or nil when poolPath
//     does not identify an existing pool.
func (i *poolV1) GetPoolPositions(poolPath string) *rotree.ReadOnlyTree {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return nil
	}

	// makeEntrySafeFn is a function that makes an entry safe to read.
	// But PositionInfo is immutable, so we can just return the entry as is.
	return rotree.Wrap(pool.Positions(), nil)
}

// Tick enumeration

// GetInitializedTicksInRange returns initialized ticks within the given range.
// Parameters:
//   - poolPath: canonical pool identifier whose initialized ticks are listed.
//   - tickLower: inclusive lower tick bound for enumeration.
//   - tickUpper: inclusive upper tick bound for enumeration.
//
// Returns:
//   - ticks: initialized tick indices in the requested inclusive range, in
//     encoded tree order; empty when no ticks are initialized there.
//   - err: nil when the pool exists; the pool lookup error otherwise.
func (i *poolV1) GetInitializedTicksInRange(poolPath string, tickLower, tickUpper int32) ([]int32, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return nil, err
	}

	ticks := make([]int32, 0)

	pool.IterateTicks(tickLower, tickUpper, func(tick int32, _ pl.TickInfo) bool {
		ticks = append(ticks, tick)
		return false
	})

	return ticks, nil
}

// Structure getters

// GetTickInfo returns the tick info for a given tick.
// Parameters:
//   - poolPath: canonical pool identifier containing the tick.
//   - tick: signed tick index whose full state is requested.
//
// Returns:
//   - tickInfo: initialized state and outside accumulators for tick.
//   - err: nil when the pool and tick can be read; the corresponding lookup
//     error otherwise.
func (i *poolV1) GetTickInfo(poolPath string, tick int32) (pl.TickInfo, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return pl.NewTickInfo(), err
	}

	return pool.GetTick(tick)
}

// GetTickBitmaps returns the tick bitmap for a given word position.
// Parameters:
//   - poolPath: canonical pool identifier whose bitmap map is queried.
//   - wordPos: signed bitmap-word position to retrieve.
//
// Returns:
//   - bitmap: decimal string encoding the initialized-tick bitmap word at
//     wordPos.
//   - err: nil when the pool and bitmap word exist; the pool lookup or missing
//     bitmap error otherwise.
func (i *poolV1) GetTickBitmaps(poolPath string, wordPos int16) (string, error) {
	pool, err := i.getPool(poolPath)
	if err != nil {
		return "", err
	}

	tickBitmap, ok := pool.TickBitmaps()[wordPos]
	if !ok {
		return "", ufmt.Errorf("tick bitmap %d not found", wordPos)
	}

	return tickBitmap, nil
}

getter_utils.gno

package pool

import (
	pl "gno.land/r/gnoswap/pool"
)

// The functions below are makeEntrySafeFn transformations handed to
// rotree.Wrap. They run on every read through a read-only view, so each one
// returns a value the caller may hold without reaching realm-owned state.

// clonePoolEntry is the transformation for the pool tree. Pool is mutable and
// its setters are declared in /r/gnoswap/pool, so an external holder of the
// stored pointer could write realm state through it.
//
// Pool.Clone leaves the pool's collections nil; see it for which lookups read
// them instead.
func clonePoolEntry(value any) any {
	pool, ok := value.(*pl.Pool)
	if !ok {
		return nil
	}

	return pool.Clone()
}

gnomod.toml

module = "gno.land/r/gnoswap/pool/v1"
gno = "0.9"

[addpkg]
  creator = "g1q5tjjv3kkslzwf2na9y9wk7e5a8ugph8xfsk04"
  height = 557783
  max_deposit = "100000000ugnot"

init.gno

package pool

import (
	ufmt "gno.land/p/nt/ufmt/v0"
	"gno.land/r/gnoswap/access/v1"
	"gno.land/r/gnoswap/emission"
	"gno.land/r/gnoswap/pool"
)

const (
	// slot0FeeProtocol is the protocol-fee denominator (0 or 4-10).
	// Zero disables protocol fees; 4 routes 1/4 of swap fees to the protocol.
	// This parameter can be modified through governance.
	defaultSlot0FeeProtocol = uint8(0)

	// poolCreationFee is the fee that is charged when a user creates a pool.
	// The fee is denominated in GNS tokens.
	// This parameter can be modified through governance.
	defaultPoolCreationFee = int64(100_000_000) // 100_GNS

	// withdrawalFeeBPS is the fee that is charged when a user withdraws their collected fees
	// The fee is denominated in BPS (Basis Points)
	// Example: 100 BPS = 1%
	// This parameter can be modified through governance.
	defaultWithdrawalFeeBPS = uint64(100)

	defaultUnlocked = true
)

func init(cur realm) {
	registerPoolV1(cur)
}

func registerPoolV1(cur realm) {
	pool.RegisterInitializer(cross(cur), func(_ int, rlm realm, poolStore pool.IPoolStore) pool.IPool {
		access.AssertIsRlmCurrent(0, rlm)

		err := initStoreData(0, rlm, poolStore)
		if err != nil {
			panic(err)
		}

		emission.SetDefaultInitialPoolChecker(cross(rlm), func(poolPath string) bool {
			return pool.ExistsPoolPath(poolPath)
		})

		return NewPoolV1(poolStore)
	})
}

func initStoreData(_ int, rlm realm, poolStore pool.IPoolStore) error {
	if !poolStore.HasPools() {
		err := poolStore.SetPools(0, rlm, pool.NewPoolsTree())
		if err != nil {
			return err
		}
	}

	if !poolStore.HasObservations() {
		err := poolStore.SetObservations(0, rlm, pool.NewObservationsTree())
		if err != nil {
			return err
		}
	}

	if err := validatePoolObservations(poolStore); err != nil {
		return err
	}

	if !poolStore.HasFeeAmountTickSpacing() {
		err := poolStore.SetFeeAmountTickSpacing(0, rlm, pool.NewDefaultFeeAmountTickSpacing())
		if err != nil {
			return err
		}
	}

	if !poolStore.HasPoolCreationFee() {
		err := poolStore.SetPoolCreationFee(0, rlm, defaultPoolCreationFee)
		if err != nil {
			return err
		}
	}

	pendingProtocolFees := make(map[string]int64)
	if poolStore.HasPendingProtocolFees() {
		pendingProtocolFees = poolStore.GetPendingProtocolFees()
	}
	if err := poolStore.SetPendingProtocolFees(0, rlm, pendingProtocolFees); err != nil {
		return err
	}

	if !poolStore.HasSlot0FeeProtocol() {
		err := poolStore.SetSlot0FeeProtocol(0, rlm, defaultSlot0FeeProtocol)
		if err != nil {
			return err
		}
	}

	if !poolStore.HasWithdrawalFeeBPS() {
		err := poolStore.SetWithdrawalFeeBPS(0, rlm, defaultWithdrawalFeeBPS)
		if err != nil {
			return err
		}
	}

	if !poolStore.HasUnlocked() {
		err := poolStore.SetUnlocked(0, rlm, defaultUnlocked)
		if err != nil {
			return err
		}
	}

	// Initialize swap start hook with no-op function
	if !poolStore.HasSwapStartHook() {
		noopSwapStart := func(cur realm, poolPath string, timestamp int64) {}
		err := poolStore.SetSwapStartHook(0, rlm, noopSwapStart)
		if err != nil {
			return err
		}
	}

	// Initialize swap end hook with no-op function
	if !poolStore.HasSwapEndHook() {
		noopSwapEnd := func(cur realm, poolPath string) error {
			return nil
		}
		err := poolStore.SetSwapEndHook(0, rlm, noopSwapEnd)
		if err != nil {
			return err
		}
	}

	// Initialize tick cross hook with no-op function
	if !poolStore.HasTickCrossHook() {
		noopTickCross := func(cur realm, poolPath string, tickId int32, zeroForOne bool, timestamp int64) {}
		err := poolStore.SetTickCrossHook(0, rlm, noopTickCross)
		if err != nil {
			return err
		}
	}

	return nil
}

// validatePoolObservations ensures every persisted pool owns an observation tree.
// CreatePool initializes the pair in one transaction; this check catches an
// implementation or upgrade that would otherwise leave a pool unusable later.
func validatePoolObservations(poolStore pool.IPoolStore) error {
	pools := poolStore.GetPools()
	observations := poolStore.GetObservations()

	var validationErr error
	pools.Iterate("", "", func(poolPath string, _ any) bool {
		if !observations.Has(poolPath) {
			validationErr = ufmt.Errorf("expected observations for poolPath(%s) to exist", poolPath)
			return true
		}
		return false
	})

	return validationErr
}

instance.gno

package pool

import (
	"gno.land/r/gnoswap/pool"
)

type poolV1 struct {
	store pool.IPoolStore
}

// NewPoolV1 constructs the version-one pool implementation around shared
// persistent storage.
//
// Parameters:
//   - store: pool-domain storage implementation used by the returned API.
//
// Returns:
//   - implementation: IPool backed by store.
func NewPoolV1(store pool.IPoolStore) pool.IPool {
	return &poolV1{
		store: store,
	}
}

lock.gno

package pool

import "errors"

// assertPoolUnlocked is the read-only reentrancy guard. It reports the global
// pool lock state without mutating it, so it is safe to call before the access
// checks: a call that aborts on authorization afterwards leaves no persisted
// lock behind (which would otherwise leak under interrealm v2, where a panic
// crossing the realm boundary skips the deferred unlockPool). It also keeps the
// "cannot modify pool while locked" message as the first failure for any
// entrypoint invoked while a swap holds the lock (reentrancy protection).
func (i *poolV1) assertPoolUnlocked() {
	if i.store.HasUnlocked() && !i.store.GetUnlocked() {
		panic(errors.New(errLockedPool))
	}
}

func (i *poolV1) lockPool(_ int, rlm realm) {
	i.assertPoolUnlocked()

	if err := i.store.SetUnlocked(0, rlm, false); err != nil {
		panic(err)
	}
}

func (i *poolV1) unlockPool(_ int, rlm realm) {
	if err := i.store.SetUnlocked(0, rlm, true); err != nil {
		panic(err)
	}
}

manager.gno

package pool

import (
	"chain"
	"errors"
	"time"

	prabc "gno.land/p/gnoswap/rbac/v1"
	"gno.land/p/gnoswap/utils/v1"
	ufmt "gno.land/p/nt/ufmt/v0"

	"gno.land/r/gnoswap/access/v1"
	"gno.land/r/gnoswap/common"
	gns "gno.land/r/gnoswap/gns"
	"gno.land/r/gnoswap/halt/v1"
	pl "gno.land/r/gnoswap/pool"

	en "gno.land/r/gnoswap/emission"
)

const GNS_TOKEN_KEY string = "gno.land/r/gnoswap/gns.GNS"

// CreatePool creates a new concentrated liquidity pool.
//
// Deploys a new AMM pool for a token pair with the specified fee tier.
// Charges the configured pool-creation fee (100 GNS by default).
// Accepts either token path order, canonicalizes token0/token1, and sets the
// initial price and tick spacing for that canonical order.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the pool proxy.
//   - token0Path: first token contract path; either order is accepted and the
//     stored pair is canonicalized.
//   - token1Path: second token contract path; either order is accepted and the
//     stored pair is canonicalized.
//   - fee: supported pool fee tier (100=0.01%, 500=0.05%, 3000=0.3%, 10000=1%).
//   - sqrtPriceX96: initial square-root price in Q64.96 format, constrained to
//     [MIN_SQRT_RATIO, MAX_SQRT_RATIO).
//
// Tick spacing by fee tier:
//   - 0.01%: 1 tick
//   - 0.05%: 10 ticks
//   - 0.30%: 60 ticks
//   - 1.00%: 200 ticks
//
// Requirements:
//   - Tokens must be different after canonicalization/wrapping
//   - Fee tier must be supported
//   - Pool must not already exist
//   - Caller must have the configured creation fee
//
// Price initialization:
//   - The initial sqrt price must be in [MIN_SQRT_RATIO, MAX_SQRT_RATIO).
//   - No oracle or external market-price sanity check is performed.
//   - If paths are supplied in reverse order, the stored sqrt price is
//     inverted to match the canonical token0/token1 order.
//
// Recovery from an economically inappropriate price:
//  1. Add wide-range liquidity at the current price.
//  2. Execute a swap to move the price toward the desired market rate.
//  3. Remove the liquidity.
//
// The executor's LP losses offset arbitrage gains, minus fees and slippage.
func (i *poolV1) CreatePool(
	_ int,
	rlm realm,
	token0Path string,
	token1Path string,
	fee uint32,
	sqrtPriceX96 string,
) {
	access.AssertIsRlmCurrent(0, rlm)

	i.assertPoolUnlocked()
	halt.AssertIsNotHaltedPool()

	assertIsSupportedFeeTier(fee)
	assertIsNotExistsPoolPath(i, token0Path, token1Path, fee)

	i.lockPool(0, rlm)
	defer i.unlockPool(0, rlm)

	en.MintAndDistributeGns(cross(rlm))

	slot0FeeProtocol := i.store.GetSlot0FeeProtocol()

	tickSpacing, err := i.GetFeeAmountTickSpacing(fee)
	if err != nil {
		panic(err)
	}

	poolInfo := newPoolParams(
		token0Path,
		token1Path,
		fee,
		sqrtPriceX96,
		tickSpacing,
		slot0FeeProtocol,
	)

	err = poolInfo.update()
	if err != nil {
		panic(err)
	}

	// validate token paths are not the same after wrapping
	assertIsNotEqualsTokens(poolInfo.token0Path, poolInfo.token1Path)

	// check if wrapped token paths are registered
	common.MustRegistered(poolInfo.token0Path, poolInfo.token1Path)

	pool := newPool(poolInfo)
	poolPath := poolInfo.poolPath()

	pools := i.store.GetPools()
	pools.Set(poolPath, pool)

	err = i.store.SetPools(0, rlm, pools)
	if err != nil {
		panic(err)
	}

	observations := i.store.GetObservations()
	observations.Set(poolPath, pl.NewPoolObservationsTree(time.Now().Unix()))
	if err := i.store.SetObservations(0, rlm, observations); err != nil {
		panic(err)
	}

	poolCreationFee := i.store.GetPoolCreationFee()

	if poolCreationFee > 0 {
		previousRealm := rlm.Previous()
		previousRealmAddr := previousRealm.Address()
		poolAddr := access.MustGetAddress(prabc.ROLE_POOL.String())
		gns.TransferFrom(cross(rlm), previousRealmAddr, poolAddr, poolCreationFee)

		chain.Emit(
			"PoolCreationFee",
			"prevAddr", previousRealmAddr.String(),
			"prevRealm", previousRealm.PkgPath(),
			"poolPath", poolPath,
			"feeTokenPath", GNS_TOKEN_KEY,
			"feeAmount", utils.FormatInt(poolCreationFee),
		)
	}

	i.settleProtocolFee(0, rlm, GNS_TOKEN_KEY, poolCreationFee)

	previousRealm := rlm.Previous()
	chain.Emit(
		"CreatePool",
		"prevAddr", previousRealm.Address().String(),
		"prevRealm", previousRealm.PkgPath(),
		"token0Path", poolInfo.Token0Path(),
		"token1Path", poolInfo.Token1Path(),
		"fee", utils.FormatUint(fee),
		"sqrtPriceX96", poolInfo.SqrtPriceX96().ToString(),
		"poolPath", poolPath,
		"tick", utils.FormatInt(pool.Slot0Tick()),
		"tickSpacing", utils.FormatInt(poolInfo.TickSpacing()),
	)
}

// SetFeeProtocol sets the protocol fee denominators for all managed pools.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the pool proxy.
//   - feeProtocol0: token0 protocol-fee denominator; must be 0 or 4-10.
//     Zero disables protocol fees; 4 routes one quarter of swap fees and 10
//     routes one tenth to the protocol.
//   - feeProtocol1: token1 protocol-fee denominator with the same 0 or 4-10
//     constraint and fee share semantics as feeProtocol0.
//
// Only callable by admin or governance.
func (i *poolV1) SetFeeProtocol(_ int, rlm realm, feeProtocol0, feeProtocol1 uint8) {
	access.AssertIsRlmCurrent(0, rlm)

	i.assertPoolUnlocked()
	halt.AssertIsNotHaltedPool()

	caller := rlm.Previous().Address()
	access.AssertIsAdminOrGovernance(caller)

	i.lockPool(0, rlm)
	defer i.unlockPool(0, rlm)

	err := i.setFeeProtocolInternal(0, rlm, feeProtocol0, feeProtocol1)
	if err != nil {
		panic(err)
	}
}

// setFeeAmountTickSpacing associates a tick spacing value with a fee amount.
func (i *poolV1) setFeeAmountTickSpacing(_ int, rlm realm, fee uint32, tickSpacing int32) error {
	feeAmountTickSpacing := i.store.GetFeeAmountTickSpacing()
	feeAmountTickSpacing[fee] = tickSpacing

	return i.store.SetFeeAmountTickSpacing(0, rlm, feeAmountTickSpacing)
}

func (i *poolV1) getPool(poolPath string) (*pl.Pool, error) {
	pools := i.store.GetPools()

	iPool := pools.Get(poolPath)
	if iPool == nil {
		return nil, ufmt.Errorf("expected poolPath(%s) to exist", poolPath)
	}

	p, ok := iPool.(*pl.Pool)
	if !ok {
		return nil, ufmt.Errorf("failed to cast pool to *Pool: %T", iPool)
	}

	return p, nil
}

// mustGetPool retrieves a pool instance by its path and ensures it exists.
func (i *poolV1) mustGetPool(poolPath string) (pool *pl.Pool) {
	p, err := i.getPool(poolPath)
	if err != nil {
		panic(makeErrorWithDetails(errDataNotFound, err.Error()))
	}

	return p
}

func (i *poolV1) mustGetPoolBy(token0Path, token1Path string, fee uint32) *pl.Pool {
	poolPath := GetPoolPath(token0Path, token1Path, fee)
	return i.mustGetPool(poolPath)
}

func (i *poolV1) getObservations(poolPath string) (*pl.ObservationTree, error) {
	observations := i.store.GetObservations()
	value := observations.Get(poolPath)
	if value == nil {
		return nil, ufmt.Errorf("expected observations for poolPath(%s) to exist", poolPath)
	}

	tree, ok := value.(*pl.ObservationTree)
	if !ok {
		return nil, ufmt.Errorf("failed to cast observations for poolPath(%s): %T", poolPath, value)
	}

	return tree, nil
}

func (i *poolV1) mustGetObservations(poolPath string) *pl.ObservationTree {
	tree, err := i.getObservations(poolPath)
	if err != nil {
		panic(makeErrorWithDetails(errDataNotFound, err.Error()))
	}
	return tree
}

// savePool updates a pool in the pools map and persists to storage.
// This ensures that modifications to pool objects are properly saved.
func (i *poolV1) savePool(_ int, rlm realm, pool *pl.Pool) error {
	pools := i.store.GetPools()
	pools.Set(pool.PoolPath(), pool)

	return i.store.SetPools(0, rlm, pools)
}

// setFeeProtocolInternal updates the protocol fee for all pools and emits an event.
func (i *poolV1) setFeeProtocolInternal(_ int, rlm realm, feeProtocol0, feeProtocol1 uint8) error {
	oldFee := i.store.GetSlot0FeeProtocol()
	newFee, err := i.setFeeProtocol(0, rlm, feeProtocol0, feeProtocol1)
	if err != nil {
		return err
	}

	feeProtocol0Old := oldFee % 16
	feeProtocol1Old := oldFee >> 4

	previousRealm := rlm.Previous()
	chain.Emit(
		"SetFeeProtocol",
		"prevAddr", previousRealm.Address().String(),
		"prevRealm", previousRealm.PkgPath(),
		"prevFeeProtocol0", utils.FormatUint(feeProtocol0Old),
		"prevFeeProtocol1", utils.FormatUint(feeProtocol1Old),
		"feeProtocol0", utils.FormatUint(feeProtocol0),
		"feeProtocol1", utils.FormatUint(feeProtocol1),
		"newFee", utils.FormatUint(newFee),
	)

	return nil
}

// setFeeProtocol updates the protocol fee configuration for all managed pools.
//
// This function combines the protocol fee values for token0 and token1 into a single `uint8` value,
// where:
//   - Lower 4 bits store feeProtocol0 (for token0).
//   - Upper 4 bits store feeProtocol1 (for token1).
//
// The updated fee protocol is applied uniformly to all pools managed by the system.
//
// Parameters:
//   - feeProtocol0: protocol fee for token0 (must be 0 or between 4 and 10 inclusive).
//   - feeProtocol1: protocol fee for token1 (must be 0 or between 4 and 10 inclusive).
//
// Returns:
//   - newFee (uint8): the combined fee protocol value.
//
// Example:
// If feeProtocol0 = 4 and feeProtocol1 = 5:
//
//	newFee = 4 + (5 << 4)
//	// Results in: 0x54 (84 in decimal)
//	// Binary: 0101 0100
//	//         ^^^^ ^^^^
//	//       fee1=5  fee0=4
//
// Notes:
//   - This function ensures that all pools under management are updated to use the same fee protocol.
//   - Caller restrictions (e.g., admin or governance) are not enforced in this function.
//   - Ensure the system is not halted before updating fees.
func (i *poolV1) setFeeProtocol(_ int, rlm realm, feeProtocol0, feeProtocol1 uint8) (uint8, error) {
	if err := validateFeeProtocol(feeProtocol0, feeProtocol1); err != nil {
		return 0, err
	}

	// combine both protocol fee into a single byte:
	// - feePrtocol0 occupies the lower 4 bits
	// - feeProtocol1 is shifted the lower 4 positions to occupy the upper 4 bits
	newFee := feeProtocol0 + (feeProtocol1 << 4) // ( << 4 ) = ( * 16 )

	pools := i.store.GetPools()

	// Update slot0 for each pool
	pools.Iterate("", "", func(poolPath string, poolI any) bool {
		pool, ok := poolI.(*pl.Pool)
		if !ok {
			panic(ufmt.Errorf("failed to cast pool to *Pool: %T", pool))
		}

		slot0 := pool.Slot0()
		slot0.SetFeeProtocol(newFee)

		pool.SetSlot0(slot0)
		return false
	})

	// update slot0
	err := i.store.SetSlot0FeeProtocol(0, rlm, newFee)
	if err != nil {
		return 0, err
	}

	return newFee, nil
}

// validateFeeProtocol validates the fee protocol values for token0 and token1.
//
// This function checks whether the provided fee protocol values (`feeProtocol0` and `feeProtocol1`)
// are valid using the `isValidFeeProtocolValue` function. If either value is invalid, it returns
// an error indicating that the protocol fee percentage is invalid.
//
// Parameters:
//   - feeProtocol0: uint8, the fee protocol value for token0.
//   - feeProtocol1: uint8, the fee protocol value for token1.
//
// Returns:
//   - error: Returns `errInvalidProtocolFeePct` if either `feeProtocol0` or `feeProtocol1` is invalid.
//     Returns `nil` if both values are valid.
func validateFeeProtocol(feeProtocol0, feeProtocol1 uint8) error {
	if !isValidFeeProtocolValue(feeProtocol0) || !isValidFeeProtocolValue(feeProtocol1) {
		return errors.New(errInvalidProtocolFeePct)
	}
	return nil
}

// isValidFeeProtocolValue checks if a fee protocol value is within acceptable range.
// Valid values are either 0 (disabled) or between 4 and 10 inclusive.
//
// The value is used as a denominator: protocolFee = swapFee / feeProtocol
// (e.g., feeProtocol=4 means 1/4 = 25% of swap fees go to protocol)
func isValidFeeProtocolValue(value uint8) bool {
	return value == 0 || (value >= 4 && value <= 10)
}

oracle.gno

package pool

import (
	"errors"
	"time"

	"gno.land/p/gnoswap/consts/v1"
	u256 "gno.land/p/gnoswap/uint256/v1"
	pl "gno.land/r/gnoswap/pool"
)

// maxObservationCardinality defines the maximum number of observations to store
const maxObservationCardinality uint16 = 65535

// oracleConsult calculates the time-weighted average price between two points in time.
// It returns the arithmetic mean tick and harmonic mean liquidity over the time period.
func oracleConsult(p *pl.Pool, observations *pl.ObservationTree, secondsAgo uint32) (int32, *u256.Uint, error) {
	if secondsAgo == 0 {
		return 0, nil, errors.New("secondsAgo must be greater than 0")
	}

	if observations == nil {
		return 0, nil, errors.New("observations not initialized")
	}
	slot0 := p.Slot0()

	// Get observations for current time and secondsAgo
	secondsAgos := []uint32{secondsAgo, 0}
	blockTimestamp := time.Now().Unix()

	tickCumulatives, secondsPerLiquidityCumulativeX128s, err := observe(
		observations,
		blockTimestamp,
		secondsAgos,
		slot0.Tick(),
		slot0.ObservationIndex(),
		p.Liquidity(),
		slot0.ObservationCardinality(),
	)
	if err != nil {
		return 0, nil, err
	}

	tickCumulativesDelta := tickCumulatives[1] - tickCumulatives[0]
	secondsPerLiquidityDelta := u256.Zero().Sub(
		u256.MustFromDecimal(secondsPerLiquidityCumulativeX128s[1]),
		u256.MustFromDecimal(secondsPerLiquidityCumulativeX128s[0]),
	)

	arithmeticMeanTick := int32(tickCumulativesDelta / int64(secondsAgo))
	if tickCumulativesDelta < 0 && (tickCumulativesDelta%int64(secondsAgo) != 0) {
		arithmeticMeanTick--
	}

	if secondsPerLiquidityDelta.IsZero() {
		return arithmeticMeanTick, u256.Zero(), nil
	}

	// Calculate harmonic mean liquidity
	secondsAgoX160 := u256.Zero().Mul(u256.NewUint(uint64(secondsAgo)), consts.Max160())
	denominator := u256.Zero().Lsh(secondsPerLiquidityDelta, 32)
	harmonicMeanLiquidity := u256.Zero().Div(secondsAgoX160, denominator)

	return arithmeticMeanTick, harmonicMeanLiquidity, nil
}

// snapshotCumulativesInside returns the accumulators that accrued while the
// current price was inside [tickLower, tickUpper), following Uniswap V3's
// snapshotCumulativesInside flow.
func snapshotCumulativesInside(
	p *pl.Pool,
	observations *pl.ObservationTree,
	tickLower int32,
	tickUpper int32,
) (int64, *u256.Uint, uint32, error) {
	if err := validateTicks(tickLower, tickUpper); err != nil {
		return 0, nil, 0, err
	}

	lower := getTick(p, tickLower)
	if !lower.Initialized() {
		return 0, nil, 0, makeErrorWithDetails(errDataNotFound, "lower tick is not initialized")
	}

	upper := getTick(p, tickUpper)
	if !upper.Initialized() {
		return 0, nil, 0, makeErrorWithDetails(errDataNotFound, "upper tick is not initialized")
	}

	lowerSecondsPerLiquidityOutsideX128 := u256.MustFromDecimal(lower.SecondsPerLiquidityOutsideX128())
	upperSecondsPerLiquidityOutsideX128 := u256.MustFromDecimal(upper.SecondsPerLiquidityOutsideX128())
	slot0 := p.Slot0()

	if slot0.Tick() < tickLower {
		return lower.TickCumulativeOutside() - upper.TickCumulativeOutside(),
			u256.Zero().Sub(lowerSecondsPerLiquidityOutsideX128, upperSecondsPerLiquidityOutsideX128),
			lower.SecondsOutside() - upper.SecondsOutside(), nil
	}

	if slot0.Tick() < tickUpper {
		if observations == nil {
			return 0, nil, 0, errors.New("observations not initialized")
		}

		currentTime := time.Now().Unix()
		tickCumulative, secondsPerLiquidityCumulativeX128, err := observeSingle(
			observations,
			currentTime,
			0,
			slot0.Tick(),
			slot0.ObservationIndex(),
			p.Liquidity(),
			slot0.ObservationCardinality(),
		)
		if err != nil {
			return 0, nil, 0, err
		}

		secondsPerLiquidityInsideX128 := u256.Zero().Sub(
			u256.Zero().Sub(
				u256.MustFromDecimal(secondsPerLiquidityCumulativeX128),
				lowerSecondsPerLiquidityOutsideX128,
			),
			upperSecondsPerLiquidityOutsideX128,
		)

		return tickCumulative - lower.TickCumulativeOutside() - upper.TickCumulativeOutside(),
			secondsPerLiquidityInsideX128,
			uint32(currentTime) - lower.SecondsOutside() - upper.SecondsOutside(), nil
	}

	return upper.TickCumulativeOutside() - lower.TickCumulativeOutside(),
		u256.Zero().Sub(upperSecondsPerLiquidityOutsideX128, lowerSecondsPerLiquidityOutsideX128),
		upper.SecondsOutside() - lower.SecondsOutside(), nil
}

func transform(last pl.Observation, blockTimestamp int64, tick int32, liquidity *u256.Uint) (pl.Observation, error) {
	timeDelta := blockTimestamp - last.BlockTimestamp()
	if timeDelta < 0 {
		return pl.DefaultObservation(), errors.New("time delta must be greater than 0")
	}

	// calculate cumulative values
	tickCumulative := last.TickCumulative() + int64(tick)*timeDelta

	// calculate seconds per liquidity
	liquidityForCalc := liquidity
	if liquidity.IsZero() {
		liquidityForCalc = u256.One()
	}

	// secondsPerLiquidity += timeDelta * 2^128 / max(1, liquidity)
	secondsPerLiquidityDelta := u256.MulDiv(
		u256.NewUintFromInt64(timeDelta),
		consts.Q128(),
		liquidityForCalc,
	)

	prevSecPerLiq := u256.MustFromDecimal(last.SecondsPerLiquidityCumulativeX128())
	secondsPerLiquidityCumulativeX128 := u256.Zero().Add(
		prevSecPerLiq,
		secondsPerLiquidityDelta,
	)

	observation := pl.MakeObservation(
		blockTimestamp,
		tickCumulative,
		secondsPerLiquidityCumulativeX128.ToString(),
		true,
	)
	return observation, nil
}

func grow(observations *pl.ObservationTree, current, next uint16) (uint16, error) {
	if observations == nil {
		return current, errors.New("observations not initialized")
	}

	if current <= 0 {
		return current, errors.New("current must be greater than 0")
	}

	if next <= current {
		return current, nil
	}

	if next > maxObservationCardinality {
		return current, errors.New("next exceeds maximum")
	}

	// Reserve every new slot now so the caller that increases capacity pays for
	// its storage. This matches Uniswap's Oracle.grow behavior and prevents an
	// unrestricted reservation from shifting allocation cost to later swappers.
	for i := current; i < next; i++ {
		observations.Set(i, pl.MakeObservation(1, 0, "0", false))
	}

	return next, nil
}

func writeObservation(
	observations *pl.ObservationTree,
	index uint16,
	blockTimestamp int64,
	tick int32,
	liquidity *u256.Uint,
	cardinality uint16,
	cardinalityNext uint16,
) (indexUpdated uint16, cardinalityUpdated uint16, err error) {
	if observations == nil {
		return 0, 0, errors.New("observations not initialized")
	}
	if cardinality == 0 {
		return 0, 0, errors.New("observation cardinality must be greater than 0")
	}

	last, err := observationAt(observations, index)
	if err != nil {
		return 0, 0, err
	}

	if last.BlockTimestamp() == blockTimestamp {
		return index, cardinality, nil
	}

	// Check if we need to grow the cardinality
	if cardinalityNext > cardinality && index == cardinality-1 {
		cardinalityUpdated = cardinalityNext
	} else {
		cardinalityUpdated = cardinality
	}

	indexUpdated = (index + 1) % cardinalityUpdated
	observation, err := transform(last, blockTimestamp, tick, liquidity)
	if err != nil {
		return 0, 0, err
	}

	observations.Set(indexUpdated, observation)
	return indexUpdated, cardinalityUpdated, nil
}

// observationAt returns the observation at a specific index
// Returns error if the observation doesn't exist
func observationAt(observations *pl.ObservationTree, index uint16) (pl.Observation, error) {
	if observations == nil {
		return pl.DefaultObservation(), errors.New("observations not initialized")
	}
	obs, ok := observations.Get(index)
	if !ok {
		return pl.DefaultObservation(), errors.New(errNotInitializedObservation)
	}

	return obs, nil
}

// observeSingle returns the data for a single observation at a specific time ago
func observeSingle(
	observations *pl.ObservationTree,
	time int64,
	secondsAgo uint32,
	tick int32,
	index uint16,
	liquidity *u256.Uint,
	cardinality uint16,
) (int64, string, error) {
	if secondsAgo == 0 {
		// if secondsAgo is 0, return current values
		last, err := observationAt(observations, index)
		if err != nil {
			return 0, "", err
		}

		if last.BlockTimestamp() != time {
			// need to create virtual observation for current time
			transformed, err := transform(last, time, tick, liquidity)
			if err != nil {
				return 0, "", err
			}

			return transformed.TickCumulative(), transformed.SecondsPerLiquidityCumulativeX128(), nil
		}

		return last.TickCumulative(), last.SecondsPerLiquidityCumulativeX128(), nil
	}

	// A lookback longer than the chain's own age would place the target before unix epoch.
	if int64(secondsAgo) > time {
		return 0, "", errors.New(errObservationBeforeEpoch)
	}

	target := time - int64(secondsAgo)

	// find the observations before and after the target
	beforeOrAt, atOrAfter, err := getSurroundingObservations(
		observations,
		target,
		tick,
		index,
		liquidity,
		cardinality,
	)
	if err != nil {
		return 0, "", err
	}

	if target == beforeOrAt.BlockTimestamp() {
		return beforeOrAt.TickCumulative(), beforeOrAt.SecondsPerLiquidityCumulativeX128(), nil
	}

	if target == atOrAfter.BlockTimestamp() {
		return atOrAfter.TickCumulative(), atOrAfter.SecondsPerLiquidityCumulativeX128(), nil
	}

	// interpolate between the two observations
	observationTimeDelta := atOrAfter.BlockTimestamp() - beforeOrAt.BlockTimestamp()
	targetDelta := target - beforeOrAt.BlockTimestamp()

	// tickCumulative += (tickCumulativeAfter - tickCumulativeBefore) / observationTimeDelta * targetDelta
	tickCumulative := beforeOrAt.TickCumulative() +
		((atOrAfter.TickCumulative()-beforeOrAt.TickCumulative())/observationTimeDelta)*targetDelta

	beforeSecPerLiq := u256.MustFromDecimal(beforeOrAt.SecondsPerLiquidityCumulativeX128())
	afterSecPerLiq := u256.MustFromDecimal(atOrAfter.SecondsPerLiquidityCumulativeX128())

	// for secondsPerLiquidity, need to interpolate carefully
	secondsPerLiquidityDelta := u256.Zero().Sub(afterSecPerLiq, beforeSecPerLiq)

	secondsPerLiquidity := u256.Zero().Add(
		beforeSecPerLiq,
		u256.MulDiv(
			secondsPerLiquidityDelta,
			u256.NewUintFromInt64(targetDelta),
			u256.NewUintFromInt64(observationTimeDelta),
		),
	)

	return tickCumulative, secondsPerLiquidity.ToString(), nil
}

// getSurroundingObservations finds the observations immediately before and after the target timestamp.
// It uses binary search over the logical time-ordered view of the circular buffer.
// Logical order starts at (index+1) % cardinality (oldest) and ends at index (latest).
func getSurroundingObservations(
	observations *pl.ObservationTree,
	target int64,
	tick int32,
	index uint16,
	liquidity *u256.Uint,
	cardinality uint16,
) (pl.Observation, pl.Observation, error) {
	// Optimistically set before to the newest observation
	beforeOrAt, err := observationAt(observations, index)
	if err != nil {
		return pl.DefaultObservation(), pl.DefaultObservation(), err
	}

	// Timestamps are int64, so natural ordering applies. Uniswap V3 needs a
	// wraparound-aware comparison here only because it stores them as uint32.
	// If the target is chronologically at or after the newest observation, we can early return
	if beforeOrAt.BlockTimestamp() <= target {
		if beforeOrAt.BlockTimestamp() == target {
			// If newest observation equals target, we're in the same block, so we can ignore atOrAfter
			return beforeOrAt, pl.DefaultObservation(), nil
		}
		// Otherwise, we need to transform
		atOrAfter, err := transform(beforeOrAt, target, tick, liquidity)
		if err != nil {
			return pl.DefaultObservation(), pl.DefaultObservation(), err
		}
		return beforeOrAt, atOrAfter, nil
	}

	// Now, set before to the oldest observation
	start := (index + 1) % cardinality
	beforeOrAt, err = observationAt(observations, start)
	if err != nil || !beforeOrAt.Initialized() {
		beforeOrAt, err = observationAt(observations, 0)
		if err != nil {
			return pl.DefaultObservation(), pl.DefaultObservation(), err
		}
	}

	// Ensure that the target is chronologically at or after the oldest observation
	if beforeOrAt.BlockTimestamp() > target {
		return pl.DefaultObservation(), pl.DefaultObservation(), errors.New(errObservationTooOld)
	}

	// If we've reached this point, we have to binary search
	return binarySearch(observations, target, index, cardinality)
}

func binarySearch(
	observations *pl.ObservationTree,
	target int64,
	index uint16,
	cardinality uint16,
) (pl.Observation, pl.Observation, error) {
	l := uint64((index + 1) % cardinality) // oldest observation
	r := l + uint64(cardinality) - 1       // newest observation
	var i uint64
	var beforeOrAt, atOrAfter pl.Observation
	var err error

	for {
		i = (l + r) / 2

		beforeIndex := uint16(i % uint64(cardinality))
		beforeOrAt, err = observationAt(observations, beforeIndex)
		if err != nil || !beforeOrAt.Initialized() {
			// we've landed on an uninitialized tick, keep searching higher (more recently)
			l = i + 1
			continue
		}

		afterIndex := uint16((i + 1) % uint64(cardinality))
		atOrAfter, err = observationAt(observations, afterIndex)
		if err != nil {
			return pl.DefaultObservation(), pl.DefaultObservation(), err
		}

		targetAtOrAfter := beforeOrAt.BlockTimestamp() <= target

		// check if we've found the answer!
		if targetAtOrAfter && target <= atOrAfter.BlockTimestamp() {
			break
		}

		if !targetAtOrAfter {
			r = i - 1
		} else {
			l = i + 1
		}
	}

	return beforeOrAt, atOrAfter, nil
}

// observe returns the cumulative tick and liquidity as of each timestamp secondsAgo from the current time.
func observe(
	observations *pl.ObservationTree,
	time int64,
	secondsAgos []uint32,
	tick int32,
	index uint16,
	liquidity *u256.Uint,
	cardinality uint16,
) ([]int64, []string, error) {
	if cardinality <= 0 {
		return nil, nil, errors.New("observation cardinality must be greater than 0")
	}

	historyCount := len(secondsAgos)
	tickCumulatives := make([]int64, historyCount)
	secondsPerLiquidityCumulativeX128s := make([]string, historyCount)

	for i, secondsAgo := range secondsAgos {
		tickCumulative, secondsPerLiquidity, err := observeSingle(
			observations,
			time,
			secondsAgo,
			tick,
			index,
			liquidity,
			cardinality,
		)
		if err != nil {
			return nil, nil, err
		}

		tickCumulatives[i] = tickCumulative
		secondsPerLiquidityCumulativeX128s[i] = secondsPerLiquidity
	}

	return tickCumulatives, secondsPerLiquidityCumulativeX128s, nil
}

pool.gno

package pool

import (
	"chain"
	"errors"

	"gno.land/r/gnoswap/common"
	"gno.land/r/gnoswap/halt/v1"
	pl "gno.land/r/gnoswap/pool"

	"gno.land/p/gnoswap/gnsmath/v1"
	i256 "gno.land/p/gnoswap/int256/v1"
	u256 "gno.land/p/gnoswap/uint256/v1"
	"gno.land/p/gnoswap/utils/v1"
	ufmt "gno.land/p/nt/ufmt/v0"

	prabc "gno.land/p/gnoswap/rbac/v1"
	_ "gno.land/r/gnoswap/rbac/v1"

	"gno.land/r/gnoswap/access/v1"
)

// Mint adds liquidity to a pool position.
//
// Increases liquidity for a position within specified tick range.
// Calculates required token amounts based on current pool price.
// Updates tick state and transfers tokens atomically.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the pool proxy.
//   - token0Path: Registered token contract path for token0.
//   - token1Path: Registered token contract path for token1.
//   - fee: Fee tier; supported tiers are 100, 500, 3000, and 10000 (0.01%, 0.05%, 0.3%, and 1%).
//   - tickLower: Inclusive lower price-range tick; must be aligned to the pool tick spacing.
//   - tickUpper: Exclusive upper price-range tick; must be aligned to the pool tick spacing.
//   - liquidityAmount: Positive decimal string specifying liquidity to add; it is converted to uint256 and then int128.
//   - positionCaller: Nonzero position-contract address that supplies tokens for this mint.
//
// Returns:
//   - amount0: Token0 amount consumed, returned as a decimal string.
//   - amount1: Token1 amount consumed, returned as a decimal string.
//
// Requirements:
//   - Pool must exist for token pair and fee
//   - Liquidity amount must be positive
//   - Ticks must be valid and aligned to spacing
//
// Only callable by position contract.
func (i *poolV1) Mint(
	_ int,
	rlm realm,
	token0Path string,
	token1Path string,
	fee uint32,
	tickLower int32,
	tickUpper int32,
	liquidityAmount string,
	positionCaller address,
) (string, string) {
	access.AssertIsRlmCurrent(0, rlm)

	i.assertPoolUnlocked()
	halt.AssertIsNotHaltedPool()

	caller := rlm.Previous().Address()
	access.AssertIsPosition(caller)
	access.AssertIsValidAddress(positionCaller)

	i.lockPool(0, rlm)
	defer i.unlockPool(0, rlm)

	liquidity := u256.MustFromDecimal(liquidityAmount)
	if liquidity.IsZero() {
		panic(errors.New(errZeroLiquidity))
	}

	pool := i.mustGetPoolBy(token0Path, token1Path, fee)

	tickSpacing := pool.TickSpacing()
	checkTickSpacing(tickLower, tickSpacing)
	checkTickSpacing(tickUpper, tickSpacing)

	liquidityDelta := gnsmath.SafeConvertToInt128(liquidity)
	positionParam := newModifyPositionParams(positionCaller, tickLower, tickUpper, liquidityDelta)
	observations := i.mustGetObservations(pool.PoolPath())
	_, amount0, amount1, err := modifyPosition(pool, observations, positionParam)
	if err != nil {
		panic(err)
	}

	poolAddr := access.MustGetAddress(prabc.ROLE_POOL.String())

	if amount0.Gt(u256.Zero()) {
		i.safeTransferFrom(0, rlm, pool, positionCaller, poolAddr, pool.Token0Path(), amount0, true)
	}

	if amount1.Gt(u256.Zero()) {
		i.safeTransferFrom(0, rlm, pool, positionCaller, poolAddr, pool.Token1Path(), amount1, false)
	}

	// Save pool state after modifyPosition may have updated liquidity
	err = i.savePool(0, rlm, pool)
	if err != nil {
		panic(err)
	}

	return amount0.ToString(), amount1.ToString()
}

// Burn removes liquidity from a pool position and credits principal as tokens
// owed to that pool-level position entry.
//
// The pool operation itself does not transfer tokens; a subsequent Collect call
// pays the credited principal. Position.DecreaseLiquidity wraps Burn and the
// fee-free Collect call within one atomic public operation.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the pool proxy.
//   - token0Path: Registered token contract path for token0.
//   - token1Path: Registered token contract path for token1.
//   - fee: Fee tier identifying the pool.
//   - tickLower: Lower tick of the position's price range; must match pool spacing.
//   - tickUpper: Upper tick of the position's price range; must match pool spacing.
//   - liquidityAmount: Non-negative decimal liquidity amount, at most 2^127-1 after conversion to int128.
//   - positionCaller: Nonzero position-contract address associated with the pool position.
//
// Returns:
//   - amount0: Token0 principal credited to the pool position, as a decimal string.
//   - amount1: Token1 principal credited to the pool position, as a decimal string.
//
// Note: Tokens remain in pool until Collect is called.
// Only callable by position contract.
func (i *poolV1) Burn(
	_ int,
	rlm realm,
	token0Path string,
	token1Path string,
	fee uint32,
	tickLower int32,
	tickUpper int32,
	liquidityAmount string, // parsed as uint256, then checked against int128
	positionCaller address,
) (string, string) {
	access.AssertIsRlmCurrent(0, rlm)

	i.assertPoolUnlocked()
	halt.AssertIsNotHaltedWithdraw()

	caller := rlm.Previous().Address()
	access.AssertIsPosition(caller)
	access.AssertIsValidAddress(positionCaller)

	i.lockPool(0, rlm)
	defer i.unlockPool(0, rlm)

	liqAmount := u256.MustFromDecimal(liquidityAmount)
	liqAmountInt256 := gnsmath.SafeConvertToInt128(liqAmount)
	liqDelta := i256.Zero().Neg(liqAmountInt256)

	posParams := newModifyPositionParams(positionCaller, tickLower, tickUpper, liqDelta)
	pool := i.mustGetPoolBy(token0Path, token1Path, fee)
	observations := i.mustGetObservations(pool.PoolPath())
	position, amount0, amount1, err := modifyPosition(pool, observations, posParams)
	if err != nil {
		panic(err)
	}

	if amount0.Gt(u256.Zero()) || amount1.Gt(u256.Zero()) {
		amount0 = toUint128(amount0)
		amount1 = toUint128(amount1)

		position.SetTokensOwed0(gnsmath.SafeAddInt64(position.TokensOwed0(), gnsmath.SafeConvertToInt64(amount0)))
		position.SetTokensOwed1(gnsmath.SafeAddInt64(position.TokensOwed1(), gnsmath.SafeConvertToInt64(amount1)))
	}

	positionKey := getPositionKey(tickLower, tickUpper)

	setPosition(pool, positionKey, position)

	err = i.savePool(0, rlm, pool)
	if err != nil {
		panic(err)
	}

	// actual token transfer happens in Collect()
	return amount0.ToString(), amount1.ToString()
}

// CollectSwapFee pays out accrued swap fees for a position.
//
// The withdrawal fee is deducted from the collected amount and settled to the
// protocol fee realm; the remainder is transferred to recipient. Only accrued
// swap fees belong on this path - principal returned by Burn is not fee
// bearing and must go through Collect.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the pool proxy.
//   - token0Path: Registered token contract path for token0.
//   - token1Path: Registered token contract path for token1.
//   - fee: Fee tier identifying the pool.
//   - recipient: Nonzero address receiving the post-fee token amounts.
//   - tickLower: Lower tick of the position's price range.
//   - tickUpper: Upper tick of the position's price range.
//   - amount0Requested: Non-negative decimal int64 amount of token0 requested; the int64 maximum requests all owed token0.
//   - amount1Requested: Non-negative decimal int64 amount of token1 requested; the int64 maximum requests all owed token1.
//
// Returns:
//   - amount0: Token0 amount collected before withdrawal-fee deduction, as a decimal string.
//   - amount1: Token1 amount collected 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.
//
// Only callable by position contract.
func (i *poolV1) CollectSwapFee(
	_ int,
	rlm realm,
	token0Path string,
	token1Path string,
	fee uint32,
	recipient address,
	tickLower int32,
	tickUpper int32,
	amount0Requested string,
	amount1Requested string,
) (amount0, amount1, fee0, fee1 string) {
	collected0, collected1, withheld0, withheld1 := i.collect(
		0, rlm,
		token0Path, token1Path, fee,
		recipient,
		tickLower, tickUpper,
		amount0Requested, amount1Requested,
		true,
	)

	return utils.FormatInt(collected0), utils.FormatInt(collected1),
		utils.FormatInt(withheld0), utils.FormatInt(withheld1)
}

// Collect pays out tokens owed to a position, transferring the full amount to
// recipient.
//
// No withdrawal fee is charged: this path carries principal credited by Burn,
// which the protocol does not tax. Accrued swap fees belong on CollectSwapFee.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the pool proxy.
//   - token0Path: Registered token contract path for token0.
//   - token1Path: Registered token contract path for token1.
//   - fee: Fee tier identifying the pool.
//   - recipient: Nonzero address receiving the owed token amounts.
//   - tickLower: Lower tick of the position's price range.
//   - tickUpper: Upper tick of the position's price range.
//   - amount0Requested: Non-negative decimal int64 amount of token0 requested; the int64 maximum requests all owed token0.
//   - amount1Requested: Non-negative decimal int64 amount of token1 requested; the int64 maximum requests all owed token1.
//
// Returns:
//   - amount0: Token0 principal transferred to recipient, as a decimal string.
//   - amount1: Token1 principal transferred to recipient, as a decimal string.
//
// Only callable by position contract.
func (i *poolV1) Collect(
	_ int,
	rlm realm,
	token0Path string,
	token1Path string,
	fee uint32,
	recipient address,
	tickLower int32,
	tickUpper int32,
	amount0Requested string,
	amount1Requested string,
) (amount0, amount1 string) {
	collected0, collected1, _, _ := i.collect(
		0, rlm,
		token0Path, token1Path, fee,
		recipient,
		tickLower, tickUpper,
		amount0Requested, amount1Requested,
		false,
	)

	return utils.FormatInt(collected0), utils.FormatInt(collected1)
}

// collect settles the pool ledger for a position and pays the recipient.
//
// The payout is capped by the position's tokensOwed, never by a caller
// supplied number, and the ledger is written before any token leaves the
// realm. Both happen under a single pool lock, so the pool's accounting and
// its token balance are never observably out of step.
//
// The collected amount is NOT capped by the pool's internal balance: a balance
// short of the owed amount means the internal ledger has drifted, so the call
// reverts rather than silently paying out less.
//
// applyWithdrawalFee selects the fee policy; pass false for a fee-free payout.
// It is the entry point, not the configured rate, that decides whether the
// protocol fee is settled: a rate of zero must still flush a backlog left
// pending by an earlier halted settlement.
func (i *poolV1) collect(
	_ int,
	rlm realm,
	token0Path string,
	token1Path string,
	fee uint32,
	recipient address,
	tickLower int32,
	tickUpper int32,
	amount0Requested string,
	amount1Requested string,
	applyWithdrawalFee bool,
) (amount0, amount1, fee0, fee1 int64) {
	access.AssertIsRlmCurrent(0, rlm)

	i.assertPoolUnlocked()
	halt.AssertIsNotHaltedWithdraw()

	caller := rlm.Previous().Address()
	access.AssertIsPosition(caller)
	access.AssertIsValidAddress(recipient)

	i.lockPool(0, rlm)
	defer i.unlockPool(0, rlm)

	amount0Req := utils.SafeParseInt64(amount0Requested)
	amount1Req := utils.SafeParseInt64(amount1Requested)

	if amount0Req < 0 || amount1Req < 0 {
		panic(errors.New(errInvalidInput))
	}

	pool := i.mustGetPoolBy(token0Path, token1Path, fee)
	// The pool position key encodes only the lower and upper ticks. It is scoped
	// to this pool, so NFTs sharing a range use the same aggregate pool entry.
	positionKey := getPositionKey(tickLower, tickUpper)
	position, err := pool.GetPosition(positionKey)
	if err != nil {
		panic(newErrorWithDetail(
			errDataNotFound,
			ufmt.Sprintf("positionKey(%s) does not exist", positionKey),
		))
	}

	amount0 = minRequestedAmount(amount0Req, position.TokensOwed0())
	amount1 = minRequestedAmount(amount1Req, position.TokensOwed1())

	if amount0 > 0 {
		tokenOwed0 := gnsmath.SafeSubInt64(position.TokensOwed0(), amount0)
		token0Balance, err := updatePoolBalance(pool.BalanceToken0(), pool.BalanceToken1(), amount0, true)
		if err != nil {
			panic(err)
		}

		position.SetTokensOwed0(tokenOwed0)
		pool.SetBalanceToken0(token0Balance)
	}
	if amount1 > 0 {
		tokenOwed1 := gnsmath.SafeSubInt64(position.TokensOwed1(), amount1)
		token1Balance, err := updatePoolBalance(pool.BalanceToken0(), pool.BalanceToken1(), amount1, false)
		if err != nil {
			panic(err)
		}

		position.SetTokensOwed1(tokenOwed1)
		pool.SetBalanceToken1(token1Balance)
	}

	setPosition(pool, positionKey, position)

	if err := i.savePool(0, rlm, pool); err != nil {
		panic(err)
	}

	withdrawalFeeBPS := ZeroBps
	if applyWithdrawalFee {
		withdrawalFeeBPS = i.store.GetWithdrawalFeeBPS()
	}

	// Effects are persisted above; everything below leaves the realm.
	fee0, amount0AfterFee := deductWithdrawalFee(amount0, withdrawalFeeBPS)
	fee1, amount1AfterFee := deductWithdrawalFee(amount1, withdrawalFeeBPS)

	if applyWithdrawalFee {
		// Called even for a zero fee, and for a zero withdrawal fee rate, so that
		// anything left pending for these tokens by an earlier halted settlement
		// is flushed.
		i.settleProtocolFee(0, rlm, token0Path, fee0)
		i.settleProtocolFee(0, rlm, token1Path, fee1)
	}

	if amount0AfterFee > 0 {
		common.SafeGRC20Transfer(0, rlm, token0Path, recipient, amount0AfterFee)
	}
	if amount1AfterFee > 0 {
		common.SafeGRC20Transfer(0, rlm, token1Path, recipient, amount1AfterFee)
	}

	return amount0, amount1, fee0, fee1
}

// CollectProtocol collects accumulated protocol fees from swap operations.
// Only callable by admin or governance.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the pool proxy.
//   - token0Path: Registered token contract path for token0.
//   - token1Path: Registered token contract path for token1.
//   - fee: Fee tier identifying the pool.
//   - recipient: Nonzero address receiving the collected protocol fees.
//   - amount0Requested: Non-negative decimal amount of token0 protocol fees requested; capped at the available balance.
//   - amount1Requested: Non-negative decimal amount of token1 protocol fees requested; capped at the available balance.
//
// Returns:
//   - amount0: Token0 protocol fees transferred to recipient, as a decimal string.
//   - amount1: Token1 protocol fees transferred to recipient, as a decimal string.
func (i *poolV1) CollectProtocol(
	_ int,
	rlm realm,
	token0Path string,
	token1Path string,
	fee uint32,
	recipient address,
	amount0Requested string, // uint128
	amount1Requested string, // uint128
) (string, string) {
	access.AssertIsRlmCurrent(0, rlm)

	i.assertPoolUnlocked()
	halt.AssertIsNotHaltedWithdraw()

	previousRealm := rlm.Previous()
	caller := previousRealm.Address()
	access.AssertIsAdminOrGovernance(caller)

	common.MustRegistered(token0Path, token1Path)

	i.lockPool(0, rlm)
	defer i.unlockPool(0, rlm)

	amount0, amount1 := i.collectProtocol(
		0,
		rlm,
		token0Path,
		token1Path,
		fee,
		recipient,
		amount0Requested,
		amount1Requested,
	)

	chain.Emit(
		"CollectProtocol",
		"prevAddr", caller.String(),
		"prevRealm", previousRealm.PkgPath(),
		"token0Path", token0Path,
		"token1Path", token1Path,
		"fee", utils.FormatUint(fee),
		"recipient", recipient.String(),
		"internal_amount0", amount0,
		"internal_amount1", amount1,
	)

	return amount0, amount1
}

// collectProtocol performs the actual protocol fee collection.
// It ensures requested amounts don't exceed available protocol fees.
// Returns amount0, amount1 as strings representing collected fees.
func (i *poolV1) collectProtocol(
	_ int,
	rlm realm,
	token0Path string,
	token1Path string,
	fee uint32,
	recipient address,
	amount0Requested string,
	amount1Requested string,
) (string, string) {
	pool := i.mustGetPoolBy(token0Path, token1Path, fee)

	amount0Req := utils.SafeParseInt64(amount0Requested)
	amount1Req := utils.SafeParseInt64(amount1Requested)

	if amount0Req < 0 || amount1Req < 0 {
		panic(errors.New(errInvalidInput))
	}

	amount0 := minRequestedAmount(amount0Req, pool.ProtocolFeesToken0())
	amount1 := minRequestedAmount(amount1Req, pool.ProtocolFeesToken1())

	amount0, amount1 = i.saveProtocolFees(pool, amount0, amount1)

	newBalanceToken0, err := updatePoolBalance(pool.BalanceToken0(), pool.BalanceToken1(), amount0, true)
	if err != nil {
		panic(err)
	}
	pool.SetBalanceToken0(newBalanceToken0)

	newBalanceToken1, err := updatePoolBalance(pool.BalanceToken0(), pool.BalanceToken1(), amount1, false)
	if err != nil {
		panic(err)
	}
	pool.SetBalanceToken1(newBalanceToken1)

	err = i.savePool(0, rlm, pool)
	if err != nil {
		panic(err)
	}

	common.SafeGRC20Transfer(0, rlm, pool.Token0Path(), recipient, amount0)
	common.SafeGRC20Transfer(0, rlm, pool.Token1Path(), recipient, amount1)

	return utils.FormatInt(amount0), utils.FormatInt(amount1)
}

// saveProtocolFees updates the protocol fee balances after collection.
// Returns amount0, amount1 representing the fees deducted from protocol reserves.
func (i *poolV1) saveProtocolFees(pool *pl.Pool, amount0, amount1 int64) (int64, int64) {
	if pool.ProtocolFeesToken0() < amount0 {
		panic(errors.New(errUnderflow))
	}
	pool.SetProtocolFeesToken0(gnsmath.SafeSubInt64(pool.ProtocolFeesToken0(), amount0))

	if pool.ProtocolFeesToken1() < amount1 {
		panic(errors.New(errUnderflow))
	}
	pool.SetProtocolFeesToken1(gnsmath.SafeSubInt64(pool.ProtocolFeesToken1(), amount1))

	return amount0, amount1
}

func minRequestedAmount(request, available int64) int64 {
	if request > available {
		return available
	}

	return request
}

// IncreaseObservationCardinalityNext schedules growth of a pool's circular observation buffer.
//
// Parameters:
//   - _: Noncrossing implementation-call discriminator; pass 0.
//   - rlm: Current realm context forwarded unchanged by the pool proxy.
//   - token0Path: Registered token contract path for token0.
//   - token1Path: Registered token contract path for token1.
//   - fee: Fee tier identifying the pool.
//   - cardinalityNext: Requested observation-buffer capacity; must not exceed the configured maximum.
func (i *poolV1) IncreaseObservationCardinalityNext(
	_ int,
	rlm realm,
	token0Path string,
	token1Path string,
	fee uint32,
	cardinalityNext uint16,
) {
	access.AssertIsRlmCurrent(0, rlm)

	i.assertPoolUnlocked()
	halt.AssertIsNotHaltedPool()

	pool := i.mustGetPoolBy(token0Path, token1Path, fee)
	slot0Before := pool.Slot0()
	observationCardinalityNextOld := slot0Before.ObservationCardinalityNext()

	i.lockPool(0, rlm)
	defer i.unlockPool(0, rlm)

	observations := i.mustGetObservations(pool.PoolPath())
	if cardinalityNext > maxObservationCardinality {
		panic("observation cardinality next exceeds maximum")
	}
	observationCardinalityNextNew, err := grow(
		observations,
		slot0Before.ObservationCardinalityNext(),
		cardinalityNext,
	)
	if err != nil {
		panic(err)
	}
	slot0After := pool.Slot0()
	slot0After.SetObservationCardinalityNext(observationCardinalityNextNew)
	pool.SetSlot0(slot0After)

	if observationCardinalityNextOld != observationCardinalityNextNew {
		previousRealm := rlm.Previous()
		chain.Emit(
			"IncreaseObservationCardinalityNext",
			"prevAddr", previousRealm.Address().String(),
			"prevRealm", previousRealm.PkgPath(),
			"poolPath", pool.PoolPath(),
			"cardinalityNext", utils.FormatUint(observationCardinalityNextNew),
		)
	}
}

position.gno

package pool

import (
	"errors"
	"time"

	"gno.land/p/gnoswap/gnsmath/v1"
	i256 "gno.land/p/gnoswap/int256/v1"
	u256 "gno.land/p/gnoswap/uint256/v1"
	ufmt "gno.land/p/nt/ufmt/v0"

	pl "gno.land/r/gnoswap/pool"
)

// getPositionKey generates a compact deterministic key for a liquidity position.
//
// Creates deterministic identifier for position tracking.
// Ensures unique positions per price range while preserving lexical ordering.
//
// Used internally for position state management.
//
// Parameters:
//   - tickLower: Lower boundary tick of position range
//   - tickUpper: Upper boundary tick of position range
//
// Key Format: EncodePositionKey(tickLower, tickUpper)
func getPositionKey(
	tickLower int32,
	tickUpper int32,
) string {
	return pl.EncodePositionKey(tickLower, tickUpper)
}

// positionUpdate updates a position's liquidity and calculates fees owed.
// Returns the updated position information and any error.
func positionUpdate(
	position pl.PositionInfo,
	liquidityDelta *i256.Int,
	feeGrowthInside0X128 *u256.Uint,
	feeGrowthInside1X128 *u256.Uint,
) (pl.PositionInfo, error) {
	isZeroLiquidityDelta := liquidityDelta.IsZero()

	posLiquidity := u256.MustFromDecimal(position.Liquidity())
	if posLiquidity.IsZero() && isZeroLiquidityDelta {
		return pl.NewDefaultPositionInfo(), makeErrorWithDetails(
			errZeroLiquidity,
			"both liquidityDelta and current position's liquidity are zero",
		)
	}

	if liquidityDelta.IsNeg() {
		absDelta := i256.Zero().Set(liquidityDelta).Abs()
		if absDelta.Gt(posLiquidity) {
			return pl.NewDefaultPositionInfo(), makeErrorWithDetails(
				errZeroLiquidity,
				ufmt.Sprintf("liquidity delta(%s) is greater than current liquidity(%s)",
					liquidityDelta.ToString(), posLiquidity.ToString()),
			)
		}
	}

	var liquidityNext *u256.Uint
	if isZeroLiquidityDelta {
		liquidityNext = posLiquidity
	} else {
		liquidityNext = gnsmath.LiquidityMathAddDelta(posLiquidity, liquidityDelta)
	}

	feeGrowthLast0 := u256.MustFromDecimal(position.FeeGrowthInside0LastX128())
	feeGrowthLast1 := u256.MustFromDecimal(position.FeeGrowthInside1LastX128())

	diff0 := u256.Zero().Sub(feeGrowthInside0X128, feeGrowthLast0)
	diff1 := u256.Zero().Sub(feeGrowthInside1X128, feeGrowthLast1)

	tokensOwed0 := u256.Zero()
	if !diff0.IsZero() {
		tokensOwed0 = u256.MulDiv(diff0, posLiquidity, q128FromDecimal)
	}

	tokensOwed1 := u256.Zero()
	if !diff1.IsZero() {
		tokensOwed1 = u256.MulDiv(diff1, posLiquidity, q128FromDecimal)
	}

	if !isZeroLiquidityDelta {
		position.SetLiquidity(liquidityNext.ToString())
	}

	position.SetFeeGrowthInside0LastX128(feeGrowthInside0X128.ToString())
	position.SetFeeGrowthInside1LastX128(feeGrowthInside1X128.ToString())

	if tokensOwed0.Gt(zero) || tokensOwed1.Gt(zero) {
		owed0 := gnsmath.SafeAddInt64(position.TokensOwed0(), gnsmath.SafeConvertToInt64(tokensOwed0))
		owed1 := gnsmath.SafeAddInt64(position.TokensOwed1(), gnsmath.SafeConvertToInt64(tokensOwed1))

		position.SetTokensOwed0(owed0)
		position.SetTokensOwed1(owed1)
	}

	return position, nil
}

// calculateToken0Amount calculates the amount of token0 based on price range and liquidity delta.
func calculateToken0Amount(sqrtPriceLower, sqrtPriceUpper *u256.Uint, liquidityDelta *i256.Int) *i256.Int {
	return gnsmath.GetAmount0Delta(sqrtPriceLower, sqrtPriceUpper, liquidityDelta)
}

// calculateToken1Amount calculates the amount of token1 based on price range and liquidity delta.
func calculateToken1Amount(sqrtPriceLower, sqrtPriceUpper *u256.Uint, liquidityDelta *i256.Int) *i256.Int {
	return gnsmath.GetAmount1Delta(sqrtPriceLower, sqrtPriceUpper, liquidityDelta)
}

// positionUpdateWithKey updates a position in the pool and returns the updated position.
func positionUpdateWithKey(
	p *pl.Pool,
	positionKey string,
	liquidityDelta *i256.Int,
	feeGrowthInside0X128, feeGrowthInside1X128 *u256.Uint,
) (pl.PositionInfo, error) {
	// if position does not exist, create a new position
	//
	// Note: The positionUpdate function is designed to handle both new positions and existing positions,
	// so there's no need to check for existence in GetPosition.
	positionToUpdate, err := p.GetPosition(positionKey)
	if err != nil {
		positionToUpdate = pl.NewDefaultPositionInfo()
	}

	positionAfterUpdate, err := positionUpdate(positionToUpdate, liquidityDelta, feeGrowthInside0X128, feeGrowthInside1X128)
	if err != nil {
		return pl.NewDefaultPositionInfo(), err
	}

	setPosition(p, positionKey, positionAfterUpdate)

	return positionAfterUpdate, nil
}

// setPosition sets the position info for a given key.
func setPosition(p *pl.Pool, posKey string, positionInfo pl.PositionInfo) {
	p.SetPosition(posKey, positionInfo)
}

// modifyPosition updates a position in the pool and calculates the amount of tokens
// needed (for minting) or returned (for burning). The calculation depends on the current
// price (tick) relative to the position's price range.
//
// The function handles three cases:
//  1. Current price below range (tick < tickLower): only token0 is used/returned
//  2. Current price in range (tickLower <= tick < tickUpper): both tokens are used/returned
//  3. Current price above range (tick >= tickUpper): only token1 is used/returned
//
// Parameters:
//   - params: ModifyPositionParams containing owner, tickLower, tickUpper, and liquidityDelta
//
// Returns:
//   - PositionInfo: updated position information
//   - *u256.Uint: amount of token0 needed/returned
//   - *u256.Uint: amount of token1 needed/returned
func modifyPosition(p *pl.Pool, observations *pl.ObservationTree, params ModifyPositionParams) (pl.PositionInfo, *u256.Uint, *u256.Uint, error) {
	if err := validateTicks(params.tickLower, params.tickUpper); err != nil {
		return pl.NewDefaultPositionInfo(), zero, zero, err
	}

	// get current state and price bounds
	tick := p.Slot0Tick()
	// update position state
	position, err := updatePosition(p, observations, params, tick)
	if err != nil {
		return pl.NewDefaultPositionInfo(), zero, zero, err
	}

	liqDelta := params.liquidityDelta
	if liqDelta.IsZero() {
		return position, zero, zero, nil
	}

	amount0, amount1 := i256.Zero(), i256.Zero()

	// covert ticks to sqrt price to use in amount calculations
	// price = 1.0001^tick, but we use sqrtPriceX96
	sqrtRatioLower := gnsmath.TickMathGetSqrtRatioAtTick(params.tickLower)
	sqrtRatioUpper := gnsmath.TickMathGetSqrtRatioAtTick(params.tickUpper)
	sqrtPriceX96 := p.Slot0SqrtPriceX96()

	// calculate token amounts based on current price position relative to range
	switch {
	case tick < params.tickLower:
		// case 1
		// full range between lower and upper tick is used for token0
		// current tick is below the passed range; liquidity can only become in range by crossing from left to
		// right, when we'll need _more_ token0 (it's becoming more valuable) so user must provide it
		amount0 = calculateToken0Amount(sqrtRatioLower, sqrtRatioUpper, liqDelta)

	case tick < params.tickUpper:
		// case 2: Current price is within the position range
		liquidityBefore := p.Liquidity()
		currentTime := time.Now().Unix()
		// Update oracle BEFORE liquidity changes
		if observations == nil {
			return pl.NewDefaultPositionInfo(), zero, zero, errors.New("observations not initialized")
		}
		slot0 := p.Slot0()
		observationIndex, observationCardinality, err := writeObservation(
			observations,
			slot0.ObservationIndex(),
			currentTime,
			tick,
			liquidityBefore,
			slot0.ObservationCardinality(),
			slot0.ObservationCardinalityNext(),
		)
		if err != nil {
			return pl.NewDefaultPositionInfo(), zero, zero, err
		}
		slot0.SetObservationIndex(observationIndex)
		slot0.SetObservationCardinality(observationCardinality)
		p.SetSlot0(slot0)

		// token0 used from current price to upper tick
		amount0 = calculateToken0Amount(sqrtPriceX96, sqrtRatioUpper, liqDelta)
		// token1 used from lower tick to current price
		amount1 = calculateToken1Amount(sqrtRatioLower, sqrtPriceX96, liqDelta)
		// update pool's active liquidity since price is in range
		p.SetLiquidity(gnsmath.LiquidityMathAddDelta(liquidityBefore, liqDelta))

	default:
		// case 3
		// full range between lower and upper tick is used for token1
		// current tick is above the passed range; liquidity can only become in range by crossing from right to
		// left, when we'll need _more_ token1 (it's becoming more valuable) so user must provide it
		amount1 = calculateToken1Amount(sqrtRatioLower, sqrtRatioUpper, liqDelta)
	}

	return position, amount0.Abs(), amount1.Abs(), nil
}

// updatePosition modifies the position's liquidity and updates the corresponding tick states.
//
// This function updates the position data based on the specified liquidity delta and tick range.
// It also manages the fee growth, tick state flipping, and cleanup of unused tick data.
//
// Parameters:
//   - positionParams: ModifyPositionParams, the parameters for the position modification, which include:
//   - owner: The address of the position owner.
//   - tickLower: The lower tick boundary of the position.
//   - tickUpper: The upper tick boundary of the position.
//   - liquidityDelta: The change in liquidity (positive or negative).
//   - tick: int32, the current tick position.
//
// Returns:
//   - PositionInfo: The updated position information.
//
// Workflow:
//  1. Clone the global fee growth values (token 0 and token 1).
//  2. If the liquidity delta is non-zero:
//     - Update the lower and upper ticks using `tickUpdate`, flipping their states if necessary.
//     - If a tick's state was flipped, update the tick bitmap to reflect the new state.
//  3. Calculate the fee growth inside the tick range using `getFeeGrowthInside`.
//  4. Generate a unique position key and update the position data using `positionUpdateWithKey`.
//  5. If liquidity is being removed (negative delta), clean up unused tick data by deleting the tick entries.
//  6. Return the updated position.
//
// Notes:
//   - The function flips the tick states and cleans up unused tick data when liquidity is removed.
//   - It ensures fee growth and position data remain accurate after the update.
//
// Example Usage:
//
// ```gno
//
//	updatedPosition := pool.updatePosition(positionParams, currentTick)
//	println("Updated Position Info:", updatedPosition)
//
// ```
func updatePosition(p *pl.Pool, observations *pl.ObservationTree, positionParams ModifyPositionParams, tick int32) (pl.PositionInfo, error) {
	feeGrowthGlobal0X128 := p.FeeGrowthGlobal0X128().Clone()
	feeGrowthGlobal1X128 := p.FeeGrowthGlobal1X128().Clone()
	liquidityDelta := positionParams.liquidityDelta

	var flippedLower, flippedUpper bool
	if !liquidityDelta.IsZero() {
		blockTimestamp := time.Now().Unix()
		if observations == nil {
			return pl.NewDefaultPositionInfo(), errors.New("observations not initialized")
		}
		slot0 := p.Slot0()
		tickCumulative, secondsPerLiquidityStr, err := observeSingle(
			observations,
			blockTimestamp,
			0,
			slot0.Tick(),
			slot0.ObservationIndex(),
			p.Liquidity(),
			slot0.ObservationCardinality(),
		)
		if err != nil {
			return pl.NewDefaultPositionInfo(), err
		}

		secondsPerLiquidityCumulativeX128 := u256.MustFromDecimal(secondsPerLiquidityStr)

		flippedLower = tickUpdate(
			p,
			positionParams.tickLower,
			tick,
			liquidityDelta,
			feeGrowthGlobal0X128,
			feeGrowthGlobal1X128,
			secondsPerLiquidityCumulativeX128,
			tickCumulative,
			blockTimestamp,
			false,
			calculateMaxLiquidityPerTick(p.TickSpacing()),
		)

		flippedUpper = tickUpdate(
			p,
			positionParams.tickUpper,
			tick,
			liquidityDelta,
			feeGrowthGlobal0X128,
			feeGrowthGlobal1X128,
			secondsPerLiquidityCumulativeX128,
			tickCumulative,
			blockTimestamp,
			true,
			calculateMaxLiquidityPerTick(p.TickSpacing()),
		)

		if flippedLower {
			tickBitmapFlipTick(p, positionParams.tickLower, p.TickSpacing())
		}

		if flippedUpper {
			tickBitmapFlipTick(p, positionParams.tickUpper, p.TickSpacing())
		}
	}

	feeGrowthInside0X128, feeGrowthInside1X128 := getFeeGrowthInside(
		p,
		positionParams.tickLower,
		positionParams.tickUpper,
		tick,
		feeGrowthGlobal0X128,
		feeGrowthGlobal1X128,
	)

	positionKey := getPositionKey(positionParams.tickLower, positionParams.tickUpper)

	position, err := positionUpdateWithKey(
		p,
		positionKey,
		liquidityDelta,
		feeGrowthInside0X128.Clone(),
		feeGrowthInside1X128.Clone(),
	)
	if err != nil {
		return pl.NewDefaultPositionInfo(), err
	}

	// clear any tick data that is no longer needed
	if liquidityDelta.IsNeg() {
		if flippedLower {
			deleteTick(p, positionParams.tickLower)
		}
		if flippedUpper {
			deleteTick(p, positionParams.tickUpper)
		}
	}

	return position, nil
}

protocol_fee.gno

package pool

import (
	"chain"
	"errors"

	"gno.land/p/gnoswap/gnsmath/v1"
	prabc "gno.land/p/gnoswap/rbac/v1"
	u256 "gno.land/p/gnoswap/uint256/v1"
	"gno.land/p/gnoswap/utils/v1"
	ufmt "gno.land/p/nt/ufmt/v0"

	"gno.land/r/gnoswap/access/v1"
	"gno.land/r/gnoswap/common"
	"gno.land/r/gnoswap/halt/v1"
	pf "gno.land/r/gnoswap/protocol_fee"
)

const (
	MaxBpsValue = uint64(1000) // 10%
	ZeroBps     = uint64(0)
)

// deductWithdrawalFee splits amount into the fee withheld for the protocol and
// the remainder paid out to the collector.
//
// Rounding favours the collector: the fee is truncated. The two results always
// sum back to amount, so a caller that debits amount and pays out
// amountAfterFee never leaves the pool short.
func deductWithdrawalFee(amount int64, withdrawalFeeBPS uint64) (feeAmount, amountAfterFee int64) {
	if amount <= 0 || withdrawalFeeBPS == ZeroBps {
		return 0, amount
	}

	fee, afterFee := calculateAmountWithFee(
		u256.NewUint(uint64(amount)),
		u256.NewUint(withdrawalFeeBPS),
	)

	return gnsmath.SafeConvertToInt64(fee), gnsmath.SafeConvertToInt64(afterFee)
}

// GetPendingProtocolFees returns the pending protocol fee amount per token path.
//
// Returns:
//   - map[string]int64: Pending protocol fee amounts keyed by token contract
//     path, with values in token base units.
func (i *poolV1) GetPendingProtocolFees() map[string]int64 {
	return i.store.GetPendingProtocolFees()
}

func (i *poolV1) addPendingProtocolFee(_ int, rlm realm, tokenPath string, amount int64) {
	if amount <= 0 {
		return
	}

	pendingAmount := gnsmath.SafeAddInt64(i.store.GetPendingProtocolFee(tokenPath), amount)
	if err := i.store.SetPendingProtocolFee(0, rlm, tokenPath, pendingAmount); err != nil {
		panic(err)
	}
}

// settleProtocolFee forwards amount, plus anything already pending for tokenPath, to
// the protocol fee realm. When collection is halted or the transfer fails, the amount
// is recorded as pending instead and settled by a later call for the same token, which
// every fee path makes even when the fee is zero.
//
// Only tokenPath is touched, so an unrelated token can never block settlement. The
// pending entry is written only when the fee cannot be forwarded, so the common path
// performs no store write at all.
func (i *poolV1) settleProtocolFee(_ int, rlm realm, tokenPath string, amount int64) {
	if halt.IsHaltedProtocolFee() {
		i.addPendingProtocolFee(0, rlm, tokenPath, amount)
		return
	}

	pendingAmount := i.store.GetPendingProtocolFee(tokenPath)
	totalAmount := gnsmath.SafeAddInt64(pendingAmount, amount)

	if totalAmount > 0 {
		protocolFeeAddr := access.MustGetAddress(prabc.ROLE_PROTOCOL_FEE.String())
		common.SafeGRC20Approve(0, rlm, tokenPath, protocolFeeAddr, totalAmount)

		// AddToProtocolFee only reports an error for a halted realm, which is handled
		// above. The branch keeps the amount pending should that ever change, and
		// withdraws the approval so no unspent allowance outlives the call.
		if err := pf.AddToProtocolFee(cross(rlm), tokenPath, totalAmount); err != nil {
			common.SafeGRC20Approve(0, rlm, tokenPath, protocolFeeAddr, 0)
			i.addPendingProtocolFee(0, rlm, tokenPath, amount)
			return
		}
	}

	if err := i.store.RemovePendingProtocolFee(0, rlm, tokenPath); err != nil {
		panic(err)
	}
}

// SetPoolCreationFee sets the poolCreationFee.
// Only admin or governance can call this function.
//
// Parameters:
//   - _: Leading integer discriminator for the forwarded realm call; callers
//     pass 0.
//   - rlm: Propagated realm context validated as current before the fee is
//     written.
//   - fee: New non-negative pool creation fee in configured native-token base
//     units.
func (i *poolV1) SetPoolCreationFee(_ int, rlm realm, fee int64) {
	access.AssertIsRlmCurrent(0, rlm)

	i.assertPoolUnlocked()
	halt.AssertIsNotHaltedPool()

	previousRealm := rlm.Previous()
	caller := previousRealm.Address()
	access.AssertIsAdminOrGovernance(caller)

	i.lockPool(0, rlm)
	defer i.unlockPool(0, rlm)

	prevPoolCreationFee := i.store.GetPoolCreationFee()
	err := i.setPoolCreationFee(0, rlm, fee)
	if err != nil {
		panic(err)
	}

	chain.Emit(
		"SetPoolCreationFee",
		"prevAddr", caller.String(),
		"prevRealm", previousRealm.PkgPath(),
		"prevFee", utils.FormatInt(prevPoolCreationFee),
		"newFee", utils.FormatInt(fee),
	)
}

// SetWithdrawalFee sets the withdrawal fee.
// Only admin or governance can call this function.
//
// Parameters:
//   - _: Leading integer discriminator for the forwarded realm call; callers
//     pass 0.
//   - rlm: Propagated realm context validated as current before the fee is
//     written.
//   - fee: New withdrawal fee in basis points; the setter accepts 0 through
//     1,000 (10%) inclusive.
func (i *poolV1) SetWithdrawalFee(_ int, rlm realm, fee uint64) {
	access.AssertIsRlmCurrent(0, rlm)

	i.assertPoolUnlocked()
	halt.AssertIsNotHaltedPool()

	previousRealm := rlm.Previous()
	caller := previousRealm.Address()
	access.AssertIsAdminOrGovernance(caller)

	i.lockPool(0, rlm)
	defer i.unlockPool(0, rlm)

	prevWithdrawalFee := i.store.GetWithdrawalFeeBPS()

	err := i.setWithdrawalFee(0, rlm, fee)
	if err != nil {
		panic(err)
	}

	chain.Emit(
		"SetWithdrawalFee",
		"prevAddr", caller.String(),
		"prevRealm", previousRealm.PkgPath(),
		"prevFee", utils.FormatUint(prevWithdrawalFee),
		"newFee", utils.FormatUint(fee),
	)
}

// calculateAmountWithFee calculates the fee amount and the amount after the fee
//
// Inputs:
// - amount: the amount before the fee
// - fee: the fee in BPS
//
// Outputs:
// - the fee amount
// - the amount after the fee applied
func calculateAmountWithFee(amount, fee *u256.Uint) (feeAmount, afterAmount *u256.Uint) {
	feeAmount, overflow := u256.Zero().MulOverflow(amount, fee)
	if overflow {
		panic(errors.New(errOverflow))
	}
	feeAmount = u256.Zero().Div(feeAmount, u256.NewUint(10_000))
	afterAmount = u256.Zero().Sub(amount, feeAmount)
	return feeAmount, afterAmount
}

// setPoolCreationFee this function is internal function called by SetPoolCreationFee
// And SetPoolCreationFee
func (i *poolV1) setPoolCreationFee(_ int, rlm realm, fee int64) error {
	if fee < 0 {
		return makeErrorWithDetails(
			errInvalidInput,
			"pool creation fee cannot be negative",
		)
	}

	// update pool creation fee
	err := i.store.SetPoolCreationFee(0, rlm, fee)
	if err != nil {
		return err
	}

	return nil
}

// setWithdrawalFee this function is internal function called by SetWithdrawalFee
// function and SetWithdrawalFee function
func (i *poolV1) setWithdrawalFee(_ int, rlm realm, fee uint64) error {
	if fee > MaxBpsValue {
		return makeErrorWithDetails(
			errInvalidWithdrawalFeePct,
			ufmt.Sprintf("fee(%d) must be in range 0 ~ %d", fee, MaxBpsValue),
		)
	}

	err := i.store.SetWithdrawalFeeBPS(0, rlm, fee)
	if err != nil {
		return err
	}

	return nil
}

render.gno

package pool

import (
	"chain"
	"strings"

	"gno.land/p/moul/md/v0"
	"gno.land/p/moul/mdtable/v0"
	ufmt "gno.land/p/nt/ufmt/v0"

	"gno.land/r/gnoswap/halt/v1"
	poolRoot "gno.land/r/gnoswap/pool"
)

func (p *poolV1) Render(path string) string {
	if path != "" {
		return "404\n"
	}

	feeAmountTickSpacing := p.store.GetFeeAmountTickSpacing()
	protocolFee := p.store.GetSlot0FeeProtocol()
	implementation := poolRoot.GetImplementationPackagePath()
	implementationTable := mdtable.Table{
		Headers: []string{"Field", "Value"},
		Rows: [][]string{
			{"Realm address", md.InlineCode(chain.PackageAddress("gno.land/r/gnoswap/pool").String())},
			{"Active implementation", md.Link(implementation, strings.TrimPrefix(implementation, "gno.land"))},
			{"Pool operations halted", ufmt.Sprintf("%t", halt.IsHaltedPool())},
			{"Protocol-fee operations halted", ufmt.Sprintf("%t", halt.IsHaltedProtocolFee())},
			{"Withdrawals halted", ufmt.Sprintf("%t", halt.IsHaltedWithdraw())},
		},
	}
	feeTable := mdtable.Table{
		Headers: []string{"Field", "Value"},
		Rows: [][]string{
			{"Stored pool records", ufmt.Sprintf("%d", p.store.GetPools().Size())},
			{"Pool creation fee (GNS base units; 6 decimals)", ufmt.Sprintf("%d", p.store.GetPoolCreationFee())},
			{"Withdrawal fee", ufmt.Sprintf("%d bps", p.store.GetWithdrawalFeeBPS())},
			{"Fee tiers (pips)", "100 (0.01%) / 500 (0.05%) / 3000 (0.30%) / 10000 (1.00%)"},
			{"Tick spacing (ticks; same tier order)", ufmt.Sprintf("%d / %d / %d / %d",
				feeAmountTickSpacing[100],
				feeAmountTickSpacing[500],
				feeAmountTickSpacing[3000],
				feeAmountTickSpacing[10000],
			)},
			{"Protocol fee denominators (token0 / token1)", ufmt.Sprintf("%d / %d", protocolFee&15, protocolFee>>4)},
		},
	}

	out := md.H1("Gnoswap Pool") + "\n"
	out += md.Paragraph(`Pool creation fees are charged in GNS. GNS amounts use the token's six-decimal
base units; pool token amounts use each token's own base units. Withdrawal fees
apply to collected swap fees and are expressed in basis points. Protocol fee
denominators apply to swap fees; zero disables the corresponding token's fee.`)
	out += md.H2("Implementation and operation status") + "\n"
	out += implementationTable.String() + "\n"
	out += md.H2("Pools and fee configuration") + "\n"
	out += feeTable.String()
	return out
}

swap.gno

package pool

import (
	"chain"
	"errors"
	"strconv"
	"time"

	ufmt "gno.land/p/nt/ufmt/v0"
	"gno.land/r/gnoswap/access/v1"
	"gno.land/r/gnoswap/halt/v1"

	"gno.land/p/gnoswap/consts/v1"
	"gno.land/p/gnoswap/gnsmath/v1"
	i256 "gno.land/p/gnoswap/int256/v1"
	u256 "gno.land/p/gnoswap/uint256/v1"
	"gno.land/p/gnoswap/utils/v1"

	pl "gno.land/r/gnoswap/pool"
)

// Hook functions allow external contracts to be notified of swap events.
var (
	// MUST BE IMMUTABLE.
	// DO NOT USE THIS VALUE IN ANY ARITHMETIC OPERATIONS' INITIALIZATION
	zero           = u256.Zero()
	zeroI256       = i256.Zero() /* readonly */
	fixedPointQ128 = u256.MustFromDecimal(Q128)

	maxInt256 = u256.MustFromDecimal(MAX_INT256)
	maxInt64  = i256.Zero().SetInt64(INT64_MAX)
	minInt64  = i256.Zero().SetInt64(INT64_MIN)
)

// SetTickCrossHook sets the hook function called when a tick is crossed during swaps.
//
// Allows staker to monitor liquidity changes at price levels.
// Used for reward calculation when positions enter/exit range.
//
// Only callable by staker contract.
// Parameters:
//   - _: Leading integer discriminator for the forwarded realm call; callers
//     pass 0.
//   - rlm: Propagated realm context validated as current before the hook is
//     stored.
//   - hook: Callback invoked after an initialized tick is crossed with the
//     current pool realm, pool path, tick index, swap direction, and timestamp.
func (i *poolV1) SetTickCrossHook(_ int, rlm realm, hook func(cur realm, poolPath string, tickId int32, zeroForOne bool, timestamp int64)) {
	access.AssertIsRlmCurrent(0, rlm)

	i.assertPoolUnlocked()

	caller := rlm.Previous().Address()
	access.AssertIsStaker(caller)

	i.lockPool(0, rlm)
	defer i.unlockPool(0, rlm)

	err := i.store.SetTickCrossHook(0, rlm, hook)
	if err != nil {
		panic(err)
	}
}

// SetSwapStartHook sets the hook function called at the beginning of a swap.
//
// Enables pre-swap state tracking for reward distribution.
// Captures timestamp for time-weighted calculations.
//
// Only callable by staker contract.
//
// Parameters:
//   - _: Leading integer discriminator for the forwarded realm call; callers
//     pass 0.
//   - rlm: Propagated realm context validated as current before the hook is
//     stored.
//   - hook: Callback invoked before swap computation with the current pool
//     realm, pool path, and block timestamp.
func (i *poolV1) SetSwapStartHook(_ int, rlm realm, hook func(cur realm, poolPath string, timestamp int64)) {
	access.AssertIsRlmCurrent(0, rlm)

	i.assertPoolUnlocked()

	caller := rlm.Previous().Address()
	access.AssertIsStaker(caller)

	i.lockPool(0, rlm)
	defer i.unlockPool(0, rlm)

	err := i.store.SetSwapStartHook(0, rlm, hook)
	if err != nil {
		panic(err)
	}
}

// SetSwapEndHook sets the hook function called at the end of a swap.
//
// Finalizes reward calculations after swap completion.
// Allows error propagation to revert invalid swaps.
//
// Only callable by staker contract.
//
// Parameters:
//   - _: Leading integer discriminator for the forwarded realm call; callers
//     pass 0.
//   - rlm: Propagated realm context validated as current before the hook is
//     stored.
//   - hook: Callback invoked after swap settlement with the current pool realm
//     and pool path; a non-nil error aborts the surrounding swap.
func (i *poolV1) SetSwapEndHook(_ int, rlm realm, hook func(cur realm, poolPath string) error) {
	access.AssertIsRlmCurrent(0, rlm)

	i.assertPoolUnlocked()

	caller := rlm.Previous().Address()
	access.AssertIsStaker(caller)

	i.lockPool(0, rlm)
	defer i.unlockPool(0, rlm)

	err := i.store.SetSwapEndHook(0, rlm, hook)
	if err != nil {
		panic(err)
	}
}

// SwapResult encapsulates all state changes from a swap.
// It ensures atomic state transitions that can be applied at once.
type SwapResult struct {
	Amount0              *i256.Int
	Amount1              *i256.Int
	NewSqrtPrice         *u256.Uint
	NewTick              int32
	NewLiquidity         *u256.Uint
	NewProtocolFeeToken0 int64
	NewProtocolFeeToken1 int64
	FeeGrowthGlobal0X128 *u256.Uint
	FeeGrowthGlobal1X128 *u256.Uint
}

// SwapComputation encapsulates the pure computation logic for swaps.
type SwapComputation struct {
	AmountSpecified   *i256.Int
	SqrtPriceLimitX96 *u256.Uint
	ZeroForOne        bool
	ExactInput        bool
	InitialState      SwapState
	Cache             *SwapCache
}

// Swap executes a swap with callback pattern for optimistic transfers.
// This allows flash swaps where tokens are sent before payment is received.
//
// The flow is:
// 1. Pool sends output tokens to recipient
// 2. Pool calls callback on msg.sender
// 3. Callback must ensure pool receives input tokens
// 4. Pool validates its balance increased correctly
//
// Parameters:
//   - _: Leading integer discriminator for the forwarded realm call; callers
//     pass 0.
//   - rlm: Current propagated realm context; it is validated as current and
//     used for token transfers and callbacks.
//   - token0Path: Registered path of token0; it must be the first token in the
//     pool's canonical token ordering.
//   - token1Path: Registered path of token1; it must be the second token in
//     the pool's canonical token ordering.
//   - fee: Fee tier identifying the registered pool to swap against.
//   - recipient: Address that receives the output token transfer.
//   - zeroForOne: Swap direction; true sells token0 for token1, false sells
//     token1 for token0.
//   - amountSpecified: Signed decimal amount; positive values request exact
//     input, negative values request exact output, and zero is invalid.
//   - sqrtPriceLimitX96: Decimal Q96 square-root-price limit that bounds the
//     swap in its direction; an invalid bound causes the call to panic.
//   - swapCallback: Callback that must settle the input delta after output is
//     sent; it receives signed int64 token deltas and a callback marker, and a
//     non-nil error aborts the swap.
//
// Returns:
//   - string: Signed decimal token0 delta from the pool's perspective; a
//     positive value is owed to the pool and a negative value is sent out.
//   - string: Signed decimal token1 delta from the pool's perspective; a
//     positive value is owed to the pool and a negative value is sent out.
func (i *poolV1) Swap(
	_ int,
	rlm realm,
	token0Path string,
	token1Path string,
	fee uint32,
	recipient address,
	zeroForOne bool,
	amountSpecified string,
	sqrtPriceLimitX96 string,
	swapCallback func(cur realm, amount0Delta, amount1Delta int64, _ *pl.CallbackMarker) error,
) (string, string) {
	access.AssertIsRlmCurrent(0, rlm)

	i.assertPoolUnlocked()
	halt.AssertIsNotHaltedPool()

	assertIsNotUserCall(0, rlm)
	assertIsValidTokenOrder(token0Path, token1Path)

	amounts := i256.MustFromDecimal(amountSpecified)
	if amounts.IsZero() {
		panic(newErrorWithDetail(
			errInvalidSwapAmount,
			"amountSpecified == 0",
		))
	}

	pool := i.mustGetPoolBy(token0Path, token1Path, fee)
	observations := i.mustGetObservations(pool.PoolPath())

	slot0Start := pool.Slot0()
	i.lockPool(0, rlm)
	defer i.unlockPool(0, rlm)

	blockTimestamp := time.Now().Unix()

	// Call swap start hook if set
	if i.store.HasSwapStartHook() {
		swapStartHook := i.store.GetSwapStartHook()

		if swapStartHook != nil {
			swapStartHook(cross(rlm), pool.PoolPath(), blockTimestamp)
		}
	}

	sqrtPriceLimit := u256.MustFromDecimal(sqrtPriceLimitX96)
	validatePriceLimits(slot0Start, zeroForOne, sqrtPriceLimit)

	feeGrowthGlobalX128 := getFeeGrowthGlobal(pool, zeroForOne)
	feeProtocol := getFeeProtocol(slot0Start, zeroForOne)
	cache := newSwapCache(feeProtocol, pool.Liquidity().Clone(), blockTimestamp, slot0Start)
	state := newSwapState(amounts, feeGrowthGlobalX128, cache.liquidityStart.Clone(), slot0Start)

	comp := SwapComputation{
		AmountSpecified:   amounts,
		SqrtPriceLimitX96: sqrtPriceLimit,
		ZeroForOne:        zeroForOne,
		ExactInput:        amounts.Gt(zeroI256),
		InitialState:      state,
		Cache:             cache,
	}

	var hook func(cur realm, poolPath string, tickId int32, zeroForOne bool, timestamp int64)
	if i.store.HasTickCrossHook() {
		hook = i.store.GetTickCrossHook()
	}
	onTickCross := func(pool *pl.Pool, tickId int32, zeroForOne bool, timestamp int64) {
		chain.Emit(
			"PoolTickCross",
			"poolPath", pool.PoolPath(),
			"tick", NewTickEventInfo(tickId, *mustGetTick(pool, tickId)).ToString(),
		)
		if hook != nil {
			hook(cross(rlm), pool.PoolPath(), tickId, zeroForOne, timestamp)
		}
	}

	result, err := i.computeSwap(pool, observations, comp, onTickCross)
	if err != nil {
		panic(err)
	}

	// Update oracle BEFORE applying swap result (using pre-swap state)
	if result.NewTick != slot0Start.Tick() {
		observationIndex, observationCardinality, err := writeObservation(
			observations,
			slot0Start.ObservationIndex(),
			cache.blockTimestamp,
			slot0Start.Tick(),
			cache.liquidityStart,
			slot0Start.ObservationCardinality(),
			slot0Start.ObservationCardinalityNext(),
		)
		if err != nil {
			panic(err)
		}
		slot0 := pool.Slot0()
		slot0.SetObservationIndex(observationIndex)
		slot0.SetObservationCardinality(observationCardinality)
		pool.SetSlot0(slot0)
	}

	applySwapResult(pool, result)

	if i.store.HasSwapEndHook() {
		swapEndHook := i.store.GetSwapEndHook()
		if swapEndHook != nil {
			err := swapEndHook(cross(rlm), pool.PoolPath())
			if err != nil {
				panic(err)
			}
		}
	}

	// transfer swap result to recipient then receive input tokens from swap callback
	if zeroForOne {
		// receive token0 from swap callback
		// send token1 to recipient (output)
		if result.Amount1.IsNeg() {
			i.safeTransfer(0, rlm, pool, recipient, token1Path, result.Amount1.Abs(), false)
		}
		i.safeSwapCallback(0, rlm, pool, token0Path, result.Amount0, result.Amount1, zeroForOne, swapCallback)
	} else {
		// receive token1 from swap callback
		// send token0 to recipient (output)
		if result.Amount0.IsNeg() {
			i.safeTransfer(0, rlm, pool, recipient, token0Path, result.Amount0.Abs(), true)
		}
		i.safeSwapCallback(0, rlm, pool, token1Path, result.Amount1, result.Amount0, zeroForOne, swapCallback)
	}

	slot0 := pool.Slot0()
	lastObservation, err := observationAt(observations, slot0.ObservationIndex())
	if err != nil {
		panic(err)
	}

	token0Amount := result.Amount0.ToString()
	token1Amount := result.Amount1.ToString()

	previousRealm := rlm.Previous()

	chain.Emit(
		"Swap",
		"prevAddr", previousRealm.Address().String(),
		"prevRealm", previousRealm.PkgPath(),
		"poolPath", pool.PoolPath(),
		"zeroForOne", utils.FormatBool(zeroForOne),
		"requestAmount", amountSpecified,
		"sqrtPriceLimitX96", sqrtPriceLimitX96,
		"recipient", recipient.String(),
		"token0Amount", token0Amount,
		"token1Amount", token1Amount,
		"protocolFee0", utils.FormatInt(pool.ProtocolFeesToken0()),
		"protocolFee1", utils.FormatInt(pool.ProtocolFeesToken1()),
		"sqrtPriceX96", pool.Slot0SqrtPriceX96().ToString(),
		"exactIn", strconv.FormatBool(comp.ExactInput),
		"currentTick", strconv.FormatInt(int64(pool.Slot0Tick()), 10),
		"liquidity", pool.Liquidity().ToString(),
		"feeGrowthGlobal0X128", pool.FeeGrowthGlobal0X128().ToString(),
		"feeGrowthGlobal1X128", pool.FeeGrowthGlobal1X128().ToString(),
		"balanceToken0", utils.FormatInt(pool.BalanceToken0()),
		"balanceToken1", utils.FormatInt(pool.BalanceToken1()),
		"tickCumulative", utils.FormatInt(lastObservation.TickCumulative()),
		"secondsPerLiquidityCumulativeX128", lastObservation.SecondsPerLiquidityCumulativeX128(),
		"observationTimestamp", utils.FormatInt(lastObservation.BlockTimestamp()),
	)

	return token0Amount, token1Amount
}

// DrySwap simulates a swap against an isolated pool and observation snapshot;
// it never writes stored pool or oracle state.
//
// Parameters:
//   - token0Path: Registered path of token0; it must be the first token in the
//     pool's canonical token ordering.
//   - token1Path: Registered path of token1; it must be the second token in
//     the pool's canonical token ordering.
//   - fee: Fee tier identifying the registered pool to simulate.
//   - zeroForOne: Swap direction; true sells token0 for token1, false sells
//     token1 for token0.
//   - amountSpecified: Signed decimal amount; positive values request exact
//     input, negative values request exact output, and zero is invalid.
//   - sqrtPriceLimitX96: Decimal Q96 square-root-price limit that bounds the
//     simulation in its direction.
//
// Returns:
//   - amount0: Signed decimal token0 delta from the pool's perspective, or
//     "0" when simulation fails.
//   - amount1: Signed decimal token1 delta from the pool's perspective, or
//     "0" when simulation fails.
//   - err: Nil when the simulation succeeds; non-nil for invalid inputs,
//     missing pool state, invalid limits, computation failures, or insufficient
//     pool output balance.
func (i *poolV1) DrySwap(
	token0Path string,
	token1Path string,
	fee uint32,
	zeroForOne bool,
	amountSpecified string,
	sqrtPriceLimitX96 string,
) (amount0, amount1 string, err error) {
	defer func() {
		if r := recover(); r != nil {
			amount0 = "0"
			amount1 = "0"
			if recoveredErr, ok := r.(error); ok {
				err = recoveredErr
			} else {
				err = ufmt.Errorf("%v", r)
			}
		}
	}()

	i.assertPoolUnlocked()

	amounts := i256.MustFromDecimal(amountSpecified)
	if amounts.IsZero() {
		return "0", "0", errors.New(errInvalidSwapAmount)
	}

	pool := i.mustGetPoolBy(token0Path, token1Path, fee)
	blockTimestamp := time.Now().Unix()

	slot0Start := pool.Slot0()
	sqrtPriceLimit := u256.MustFromDecimal(sqrtPriceLimitX96)
	validatePriceLimits(slot0Start, zeroForOne, sqrtPriceLimit)

	feeGrowthGlobalX128 := getFeeGrowthGlobal(pool, zeroForOne)
	feeProtocol := getFeeProtocol(slot0Start, zeroForOne)
	cache := newSwapCache(feeProtocol, pool.Liquidity().Clone(), blockTimestamp, slot0Start)
	cache.readOnly = true
	state := newSwapState(amounts, feeGrowthGlobalX128, cache.liquidityStart, slot0Start)

	comp := SwapComputation{
		AmountSpecified:   amounts,
		SqrtPriceLimitX96: sqrtPriceLimit,
		ZeroForOne:        zeroForOne,
		ExactInput:        amounts.Gt(zeroI256),
		InitialState:      state,
		Cache:             cache,
	}

	result, err := i.computeSwap(pool, nil, comp, nil)
	if err != nil {
		return "0", "0", err
	}

	if zeroForOne {
		if pool.BalanceToken1() < gnsmath.SafeConvertToInt64(result.Amount1.Abs()) {
			return "0", "0", errors.New(errInsufficientPoolBalance)
		}
	} else {
		if pool.BalanceToken0() < gnsmath.SafeConvertToInt64(result.Amount0.Abs()) {
			return "0", "0", errors.New(errInsufficientPoolBalance)
		}
	}

	return result.Amount0.ToString(), result.Amount1.ToString(), nil
}

// tickCrossHookFn is invoked after an initialized tick is crossed. Swap uses it
// for externally visible side effects; DrySwap passes nil.
type tickCrossHookFn func(pool *pl.Pool, tickId int32, zeroForOne bool, timestamp int64)

// computeSwap calculates swap amounts; tick accounting is written unless Cache.readOnly is set.
// The computation continues until either:
// - The entire amount is consumed (amountSpecifiedRemaining = 0)
// - The price limit is reached (sqrtPriceX96 = sqrtPriceLimitX96)
//
// Important: This function is critical for AMM price discovery. It iterates through
// tick ranges, calculating swap amounts and fees for each liquidity segment.
// Returns an error if the computation fails at any step.
//
// The optional `onTickCross` callback is invoked when an initialized tick is
// crossed; Swap supplies a hook that performs a cross-realm call into the
// configured tick-cross hook, while DrySwap passes nil.
func (i *poolV1) computeSwap(pool *pl.Pool, observations *pl.ObservationTree, comp SwapComputation, onTickCross tickCrossHookFn) (*SwapResult, error) {
	state := comp.InitialState
	var err error

	// Compute swap steps until completion
	for shouldContinueSwap(state, comp.SqrtPriceLimitX96) {
		state, err = i.computeSwapStep(state, pool, observations, comp.ZeroForOne, comp.SqrtPriceLimitX96, comp.ExactInput, comp.Cache, onTickCross)
		if err != nil {
			return nil, err
		}
	}

	// Calculate final amounts
	amount0 := state.amountCalculated
	amount1 := i256.Zero().Sub(comp.AmountSpecified, state.amountSpecifiedRemaining)
	if comp.ZeroForOne == comp.ExactInput {
		amount0, amount1 = amount1, amount0
	}

	// Prepare result
	result := &SwapResult{
		Amount0:              amount0,
		Amount1:              amount1,
		NewSqrtPrice:         state.sqrtPriceX96,
		NewTick:              state.tick,
		NewLiquidity:         state.liquidity,
		NewProtocolFeeToken0: pool.ProtocolFeesToken0(),
		NewProtocolFeeToken1: pool.ProtocolFeesToken1(),
		FeeGrowthGlobal0X128: pool.FeeGrowthGlobal0X128(),
		FeeGrowthGlobal1X128: pool.FeeGrowthGlobal1X128(),
	}

	// Update protocol fees if necessary
	if comp.ZeroForOne {
		if state.protocolFee.Gt(zero) {
			result.NewProtocolFeeToken0 = gnsmath.SafeAddInt64(result.NewProtocolFeeToken0, gnsmath.SafeConvertToInt64(state.protocolFee))
		}
		result.FeeGrowthGlobal0X128 = state.feeGrowthGlobalX128.Clone()
	} else {
		if state.protocolFee.Gt(zero) {
			result.NewProtocolFeeToken1 = gnsmath.SafeAddInt64(result.NewProtocolFeeToken1, gnsmath.SafeConvertToInt64(state.protocolFee))
		}
		result.FeeGrowthGlobal1X128 = state.feeGrowthGlobalX128.Clone()
	}

	return result, nil
}

// applySwapResult updates pool state with computed results.
// All state changes are applied at once to maintain consistency
func applySwapResult(pool *pl.Pool, result *SwapResult) {
	slot0 := pool.Slot0()
	slot0.SetSqrtPriceX96(result.NewSqrtPrice)
	slot0.SetTick(result.NewTick)
	pool.SetSlot0(slot0)

	pool.SetLiquidity(result.NewLiquidity)
	pool.SetProtocolFeesToken0(result.NewProtocolFeeToken0)
	pool.SetProtocolFeesToken1(result.NewProtocolFeeToken1)
	pool.SetFeeGrowthGlobal0X128(result.FeeGrowthGlobal0X128)
	pool.SetFeeGrowthGlobal1X128(result.FeeGrowthGlobal1X128)
}

// validatePriceLimits ensures the provided price limit is valid for the swap direction
// The function enforces that:
// For zeroForOne (selling token0):
//   - Price limit must be below current price
//   - Price limit must be above MIN_SQRT_RATIO
//
// For !zeroForOne (selling token1):
//   - Price limit must be above current price
//   - Price limit must be below MAX_SQRT_RATIO
func validatePriceLimits(slot0 pl.Slot0, zeroForOne bool, sqrtPriceLimitX96 *u256.Uint) {
	if zeroForOne {
		cond1 := sqrtPriceLimitX96.Lt(slot0.SqrtPriceX96())
		cond2 := sqrtPriceLimitX96.Gt(consts.MinSqrtRatio())
		if !(cond1 && cond2) {
			panic(newErrorWithDetail(
				errPriceOutOfRange,
				ufmt.Sprintf("sqrtPriceLimitX96(%s) < slot0Start.sqrtPriceX96(%s) && sqrtPriceLimitX96(%s) > MIN_SQRT_RATIO(%s)",
					sqrtPriceLimitX96.ToString(),
					slot0.SqrtPriceX96().ToString(),
					sqrtPriceLimitX96.ToString(),
					MIN_SQRT_RATIO),
			))
		}
	} else {
		cond1 := sqrtPriceLimitX96.Gt(slot0.SqrtPriceX96())
		cond2 := sqrtPriceLimitX96.Lt(consts.MaxSqrtRatio())
		if !(cond1 && cond2) {
			panic(newErrorWithDetail(
				errPriceOutOfRange,
				ufmt.Sprintf("sqrtPriceLimitX96(%s) > slot0Start.sqrtPriceX96(%s) && sqrtPriceLimitX96(%s) < MAX_SQRT_RATIO(%s)",
					sqrtPriceLimitX96.ToString(),
					slot0.SqrtPriceX96().ToString(),
					sqrtPriceLimitX96.ToString(),
					MAX_SQRT_RATIO),
			))
		}
	}
}

// getFeeProtocol returns the appropriate fee protocol based on zero for one.
// When zeroForOne is true, we want the lower 4 bits (% 16).
// Otherwise, we want the upper 4 bits (/ 16).
func getFeeProtocol(slot0 pl.Slot0, zeroForOne bool) uint8 {
	shift := uint8(0)
	if !zeroForOne {
		shift = 4
	}
	return (slot0.FeeProtocol() >> shift) & uint8(0xF)
}

// getFeeGrowthGlobal returns the appropriate fee growth global based on zero for one.
func getFeeGrowthGlobal(pool *pl.Pool, zeroForOne bool) *u256.Uint {
	if zeroForOne {
		return pool.FeeGrowthGlobal0X128().Clone()
	}
	return pool.FeeGrowthGlobal1X128().Clone()
}

// shouldContinueSwap checks if swap should continue based on remaining amount and price limit.
func shouldContinueSwap(state SwapState, sqrtPriceLimitX96 *u256.Uint) bool {
	return !state.amountSpecifiedRemaining.IsZero() && !state.sqrtPriceX96.Eq(sqrtPriceLimitX96)
}

// computeSwapStep executes a single step of swap and returns new state
func (i *poolV1) computeSwapStep(
	state SwapState,
	pool *pl.Pool,
	observations *pl.ObservationTree,
	zeroForOne bool,
	sqrtPriceLimitX96 *u256.Uint,
	exactInput bool,
	cache *SwapCache,
	onTickCross tickCrossHookFn,
) (SwapState, error) {
	step := computeSwapStepInit(state, pool, zeroForOne)

	// determining the price target for this step
	sqrtRatioTargetX96 := computeTargetSqrtRatio(step, sqrtPriceLimitX96, zeroForOne).Clone()

	// computing the amounts to be swapped at this step
	var (
		newState SwapState
		err      error
	)

	newState, step = computeAmounts(state, sqrtRatioTargetX96, pool, step)
	newState, err = updateAmounts(step, newState, exactInput)
	if err != nil {
		return state, err
	}

	// if the protocol fee is on, calculate how much is owed,
	// decrement fee amount, and increment protocol fee
	if cache.feeProtocol > 0 {
		newState, step, err = updateFeeProtocol(step, cache.feeProtocol, newState)
		if err != nil {
			return state, err
		}
	}

	// update global fee tracker
	if newState.liquidity.Gt(u256.Zero()) {
		update := u256.MulDiv(step.feeAmount, fixedPointQ128, newState.liquidity)
		feeGrowthGlobalX128 := u256.Zero().Add(newState.feeGrowthGlobalX128, update)
		newState.setFeeGrowthGlobalX128(feeGrowthGlobalX128)
	}

	// handling tick transitions
	if newState.sqrtPriceX96.Eq(step.sqrtPriceNextX96) {
		newState, err = i.tickTransition(step, zeroForOne, newState, pool, observations, cache, onTickCross)
		if err != nil {
			return state, err
		}
	} else if newState.sqrtPriceX96.Neq(step.sqrtPriceStartX96) {
		newState.setTick(gnsmath.TickMathGetTickAtSqrtRatio(newState.sqrtPriceX96))
	}

	return newState, nil
}

// updateFeeProtocol calculates and updates protocol fees for the current step.
func updateFeeProtocol(step StepComputations, feeProtocol uint8, state SwapState) (SwapState, StepComputations, error) {
	delta := u256.Zero().Div(step.feeAmount, u256.NewUint(uint64(feeProtocol)))

	newFeeAmount, overflow := u256.Zero().SubOverflow(step.feeAmount, delta)
	if overflow {
		return state, step, errors.New(errUnderflow)
	}

	step.feeAmount = newFeeAmount

	newProtocolFee, overflow := u256.Zero().AddOverflow(state.protocolFee, delta)
	if overflow {
		return state, step, errors.New(errOverflow)
	}
	state.protocolFee = newProtocolFee

	return state, step, nil
}

// computeSwapStepInit initializes the computation for a single swap step.
func computeSwapStepInit(state SwapState, pool *pl.Pool, zeroForOne bool) StepComputations {
	var step StepComputations
	step.sqrtPriceStartX96 = state.sqrtPriceX96
	tickNext, initialized := tickBitmapNextInitializedTickWithInOneWord(
		pool,
		state.tick,
		pool.TickSpacing(),
		zeroForOne,
	)

	step.tickNext = tickNext
	step.initialized = initialized

	// prevent overshoot the min/max tick
	step.clampTickNext()
	// get the price for the next tick
	step.sqrtPriceNextX96 = gnsmath.TickMathGetSqrtRatioAtTick(step.tickNext)
	return step
}

// computeTargetSqrtRatio determines the target sqrt price for the current swap step.
func computeTargetSqrtRatio(step StepComputations, sqrtPriceLimitX96 *u256.Uint, zeroForOne bool) *u256.Uint {
	if shouldUsePriceLimit(step.sqrtPriceNextX96, sqrtPriceLimitX96, zeroForOne) {
		return sqrtPriceLimitX96
	}
	return step.sqrtPriceNextX96
}

// shouldUsePriceLimit returns true if the price limit should be used instead of the next tick price
func shouldUsePriceLimit(sqrtPriceNext, sqrtPriceLimit *u256.Uint, zeroForOne bool) bool {
	if zeroForOne {
		return sqrtPriceNext.Lt(sqrtPriceLimit)
	}
	return sqrtPriceNext.Gt(sqrtPriceLimit)
}

// computeAmounts calculates the input and output amounts for the current swap step.
func computeAmounts(state SwapState, sqrtRatioTargetX96 *u256.Uint, pool *pl.Pool, step StepComputations) (SwapState, StepComputations) {
	sqrtPriceX96, amountIn, amountOut, feeAmount := gnsmath.SwapMathComputeSwapStep(
		state.sqrtPriceX96,
		sqrtRatioTargetX96,
		state.liquidity,
		state.amountSpecifiedRemaining,
		uint64(pool.Fee()),
	)

	step.amountIn = amountIn
	step.amountOut = amountOut
	step.feeAmount = feeAmount

	state.setSqrtPriceX96(sqrtPriceX96)

	return state, step
}

// updateAmounts calculates new remaining and calculated amounts based on the swap step.
// For exact input swaps:
//   - Decrements remaining input amount by (amountIn + feeAmount)
//   - Decrements calculated amount by amountOut
//
// For exact output swaps:
//   - Increments remaining output amount by amountOut
//   - Increments calculated amount by (amountIn + feeAmount)
func updateAmounts(step StepComputations, state SwapState, exactInput bool) (SwapState, error) {
	amountInWithFeeU256 := u256.Zero().Add(step.amountIn, step.feeAmount)
	if amountInWithFeeU256.Gt(maxInt256) {
		return state, errors.New(errOverflow)
	}

	amountInWithFee := i256.FromUint256(amountInWithFeeU256)
	if step.amountOut.Gt(maxInt256) {
		return state, errors.New(errOverflow)
	}

	var (
		amountSpecifiedRemaining *i256.Int
		amountCalculated         *i256.Int
		overflow                 bool
	)

	if exactInput {
		amountSpecifiedRemaining, overflow = i256.Zero().SubOverflow(state.amountSpecifiedRemaining, amountInWithFee)
		if overflow {
			return state, errors.New(errUnderflow)
		}
		amountCalculated, overflow = i256.Zero().SubOverflow(state.amountCalculated, i256.FromUint256(step.amountOut))
		if overflow {
			return state, errors.New(errUnderflow)
		}
	} else {
		amountSpecifiedRemaining, overflow = i256.Zero().AddOverflow(state.amountSpecifiedRemaining, i256.FromUint256(step.amountOut))
		if overflow {
			return state, errors.New(errOverflow)
		}
		amountCalculated, overflow = i256.Zero().AddOverflow(state.amountCalculated, amountInWithFee)
		if overflow {
			return state, errors.New(errOverflow)
		}
	}

	// If an overflowed value is stored in state, it may cause problems in the next step
	if amountCalculated.Gt(maxInt64) || amountSpecifiedRemaining.Gt(maxInt64) {
		return state, errors.New(errOverflow)
	}

	// If an underflowed value is stored in state, it may cause problems in the next step
	if amountCalculated.Lt(minInt64) || amountSpecifiedRemaining.Lt(minInt64) {
		return state, errors.New(errUnderflow)
	}

	state.amountSpecifiedRemaining = amountSpecifiedRemaining
	state.amountCalculated = amountCalculated

	return state, nil
}

// tickTransition handles the transition between price ticks during a swap
func (i *poolV1) tickTransition(step StepComputations, zeroForOne bool, state SwapState, pool *pl.Pool, observations *pl.ObservationTree, cache *SwapCache, onTickCross tickCrossHookFn) (SwapState, error) {
	// ensure existing state to keep immutability
	newState := state

	if step.initialized {
		var liquidityNet *i256.Int
		if cache.readOnly {
			// Quotes need only the liquidity delta. Outside fee/oracle accumulators
			// do not affect pricing, and the monotonic path never revisits a tick.
			tick := getTick(pool, step.tickNext)
			liquidityNet = i256.MustFromDecimal(tick.LiquidityNet())
		} else {
			// Compute oracle values on first initialized tick cross.
			if !cache.computedLatestObservation {
				tickCumulative, secondsPerLiquidityStr, err := observeSingle(
					observations,
					cache.blockTimestamp,
					0,
					cache.slot0Start.Tick(),
					cache.slot0Start.ObservationIndex(),
					cache.liquidityStart,
					cache.slot0Start.ObservationCardinality(),
				)
				if err != nil {
					return newState, err
				}

				cache.tickCumulative = tickCumulative
				cache.secondsPerLiquidityCumulativeX128 = u256.MustFromDecimal(secondsPerLiquidityStr)
				cache.computedLatestObservation = true
			}

			fee0, fee1 := u256.Zero(), u256.Zero()
			if zeroForOne {
				fee0 = state.feeGrowthGlobalX128
				fee1 = pool.FeeGrowthGlobal1X128()
			} else {
				fee0 = pool.FeeGrowthGlobal0X128()
				fee1 = state.feeGrowthGlobalX128
			}

			liquidityNet = tickCross(
				pool,
				step.tickNext,
				fee0,
				fee1,
				cache.secondsPerLiquidityCumulativeX128,
				cache.tickCumulative,
				cache.blockTimestamp,
			)
		}

		if zeroForOne {
			liquidityNet = i256.Zero().Neg(liquidityNet)
		}

		newState.liquidity = gnsmath.LiquidityMathAddDelta(state.liquidity, liquidityNet)

		if !cache.readOnly && onTickCross != nil {
			onTickCross(pool, step.tickNext, zeroForOne, cache.blockTimestamp)
		}
	}

	newState.tick = step.tickNext
	if zeroForOne {
		newState.tick = step.tickNext - 1
	}

	return newState, nil
}

tick.gno

package pool

import (
	"gno.land/p/gnoswap/consts/v1"
	"gno.land/p/gnoswap/gnsmath/v1"
	ufmt "gno.land/p/nt/ufmt/v0"

	i256 "gno.land/p/gnoswap/int256/v1"
	u256 "gno.land/p/gnoswap/uint256/v1"
	pl "gno.land/r/gnoswap/pool"
)

// MAX_LIQUIDITY_PER_TICK_* values are spacing-specific limits returned by
// calculateMaxLiquidityPerTick; they are not a universal uint128 maximum.

const (
	MAX_LIQUIDITY_PER_TICK_SPACING_1         = "191757530477355301479181766273477"
	MAX_LIQUIDITY_PER_TICK_SPACING_10        = "1917569901783203986719870431555990"
	MAX_LIQUIDITY_PER_TICK_SPACING_60        = "11505743598341114571880798222544994"
	MAX_LIQUIDITY_PER_TICK_SPACING_200       = "38350317471085141830651933667504588"
	MIN_TICK                           int32 = -887272
	MAX_TICK                           int32 = 887272
)

// maxLiquidityPerTickSpacing* return the precomputed max-liquidity-per-tick for
// each supported tick spacing. They are constructors (not package-level vars) so
// each caller receives a fresh instance — calculateMaxLiquidityPerTick returns
// the value directly to callers, and a shared singleton could otherwise be
// mutated in place and corrupt every caller. Values are built from little-endian
// [4]uint64 literals to avoid runtime decimal parsing.
func maxLiquidityPerTickSpacing1FromDec() *u256.Uint {
	return &u256.Uint{3639524637645646277, 10395196556700, 0, 0} // 191757530477355301479181766273477
}

func maxLiquidityPerTickSpacing10FromDec() *u256.Uint {
	return &u256.Uint{4727306266354938262, 103951672670308, 0, 0} // 1917569901783203986719870431555990
}

func maxLiquidityPerTickSpacing60FromDec() *u256.Uint {
	return &u256.Uint{1428959955126579298, 623727610269131, 0, 0} // 11505743598341114571880798222544994
}

func maxLiquidityPerTickSpacing200FromDec() *u256.Uint {
	return &u256.Uint{6592429331424883148, 2078974875882965, 0, 0} // 38350317471085141830651933667504588
}

// getFeeGrowthInside calculates the fee growth within a specified tick range.
//
// This function computes the accumulated fee growth for token 0 and token 1 inside a given tick range
// (`tickLower` to `tickUpper`) relative to the current tick position (`tickCurrent`). It isolates the fee
// growth within the range by subtracting the fee growth below the lower tick and above the upper tick
// from the global fee growth.
//
// Parameters:
//   - tickLower: int32, the lower tick boundary of the range.
//   - tickUpper: int32, the upper tick boundary of the range.
//   - tickCurrent: int32, the current tick index.
//   - feeGrowthGlobal0X128: *u256.Uint, the global fee growth for token 0 in X128 precision.
//   - feeGrowthGlobal1X128: *u256.Uint, the global fee growth for token 1 in X128 precision.
//
// Returns:
//   - *u256.Uint: Fee growth inside the tick range for token 0.
//   - *u256.Uint: Fee growth inside the tick range for token 1.
//
// Workflow:
//  1. Retrieve the tick information (`lower` and `upper`) for the lower and upper tick boundaries
//     using `p.getTick`.
//  2. Calculate the fee growth below the lower tick using `getFeeGrowthBelowX128`.
//  3. Calculate the fee growth above the upper tick using `getFeeGrowthAboveX128`.
//  4. Subtract the fee growth below and above the range from the global fee growth values:
//     feeGrowthInside = feeGrowthGlobal - feeGrowthBelow - feeGrowthAbove
//  5. Return the computed fee growth values for token 0 and token 1 within the range.
//
// Behavior:
//   - The fee growth is isolated within the range `[tickLower, tickUpper]`.
//   - The function ensures the calculations accurately consider the tick boundaries and the current tick position.
//
// Example:
//
// ```gno
//
//	feeGrowth0, feeGrowth1 := pool.getFeeGrowthInside(
//	    100, 200, 150, globalFeeGrowth0, globalFeeGrowth1,
//	)
//	println("Fee Growth Inside (Token 0):", feeGrowth0)
//	println("Fee Growth Inside (Token 1):", feeGrowth1)
//
// ```
func getFeeGrowthInside(
	p *pl.Pool,
	tickLower int32,
	tickUpper int32,
	tickCurrent int32,
	feeGrowthGlobal0X128 *u256.Uint,
	feeGrowthGlobal1X128 *u256.Uint,
) (*u256.Uint, *u256.Uint) {
	lower := getTick(p, tickLower)
	upper := getTick(p, tickUpper)

	feeGrowthBelow0X128, feeGrowthBelow1X128 := getFeeGrowthBelowX128(tickLower, tickCurrent, feeGrowthGlobal0X128, feeGrowthGlobal1X128, lower)
	feeGrowthAbove0X128, feeGrowthAbove1X128 := getFeeGrowthAboveX128(tickUpper, tickCurrent, feeGrowthGlobal0X128, feeGrowthGlobal1X128, upper)

	feeGrowthInside0X128 := u256.Zero().Sub(u256.Zero().Sub(feeGrowthGlobal0X128, feeGrowthBelow0X128), feeGrowthAbove0X128)
	feeGrowthInside1X128 := u256.Zero().Sub(u256.Zero().Sub(feeGrowthGlobal1X128, feeGrowthBelow1X128), feeGrowthAbove1X128)

	return feeGrowthInside0X128, feeGrowthInside1X128
}

// tickUpdate updates the state of a specific tick.
//
// This function applies a given liquidity change (liquidityDelta) to the specified tick, updates
// the fee growth values if necessary, and adjusts the net liquidity based on whether the tick
// is an upper or lower boundary. It also verifies that the total liquidity does not exceed the
// maximum allowed value and ensures the net liquidity stays within the valid int128 range.
//
// Parameters:
//   - tick:          int32, the index of the tick to update.
//   - tickCurrent:   int32, the current active tick index.
//   - liquidityDelta: *i256.Int, the amount of liquidity to add or remove.
//   - feeGrowthGlobal0X128: *u256.Uint, the global fee growth value for token 0.
//   - feeGrowthGlobal1X128: *u256.Uint, the global fee growth value for token 1.
//   - secondsPerLiquidityCumulativeX128: *u256.Uint, the current oracle accumulator used to
//     seed the outside accumulator of a newly initialized active tick (tick <= tickCurrent).
//   - tickCumulative: int64, the current oracle tick accumulator used for the same seeding.
//   - blockTimestamp: int64, the current block timestamp used for the same seeding.
//   - upper:         bool, indicates if this is the upper boundary (true for upper, false for lower).
//   - maxLiquidity:  *u256.Uint, the maximum allowed liquidity.
//
// Returns:
//   - flipped: bool, indicates if the tick's initialization state has changed.
//     (e.g., liquidity transitioning from zero to non-zero, or vice versa)
//
// Workflow:
// 1. Nil input values are replaced with zero.
// 2. The function retrieves the tick information for the specified tick index.
// 3. Applies the liquidityDelta to compute the new total liquidity (liquidityGross).
//   - If the total liquidity exceeds the maximum allowed value, the function panics.
//     4. Checks whether the tick's initialized state has changed and sets the `flipped` flag.
//     5. If the tick was previously uninitialized and its index is less than or equal to the current tick,
//     the fee growth values are initialized to the current global values.
//     6. Updates the tick's net liquidity:
//   - For an upper boundary, it subtracts liquidityDelta.
//   - For a lower boundary, it adds liquidityDelta.
//   - Ensures the net liquidity remains within the int128 range using `checkOverFlowInt128`.
//     7. Updates the tick's state with the new values.
//     8. Returns whether the tick's initialized state has flipped.
//
// Panic Conditions:
// - The total liquidity (liquidityGross) exceeds the maximum allowed liquidity (maxLiquidity).
// - The net liquidity (liquidityNet) exceeds the int128 range.
//
// Example:
//
// ```gno
//
//	flipped := pool.tickUpdate(10, 5, liquidityDelta, feeGrowth0, feeGrowth1, secondsPerLiquidityCumulativeX128, tickCumulative, blockTimestamp, true, maxLiquidity)
//	println("Tick flipped:", flipped)
//
// ```
func tickUpdate(
	p *pl.Pool,
	tick int32,
	tickCurrent int32,
	liquidityDelta *i256.Int,
	feeGrowthGlobal0X128 *u256.Uint,
	feeGrowthGlobal1X128 *u256.Uint,
	secondsPerLiquidityCumulativeX128 *u256.Uint,
	tickCumulative int64,
	blockTimestamp int64,
	upper bool,
	maxLiquidity *u256.Uint,
) (flipped bool) {
	tickInfo := getTick(p, tick)

	liquidityGrossBefore := u256.MustFromDecimal(tickInfo.LiquidityGross())
	liquidityGrossAfter := gnsmath.LiquidityMathAddDelta(liquidityGrossBefore, liquidityDelta)

	if !liquidityGrossAfter.Lte(maxLiquidity) {
		panic(newErrorWithDetail(
			errLiquidityCalculation,
			ufmt.Sprintf("liquidityGrossAfter(%s) overflows maxLiquidity(%s)", liquidityGrossAfter.ToString(), maxLiquidity.ToString()),
		))
	}

	flipped = liquidityGrossAfter.IsZero() != liquidityGrossBefore.IsZero()

	if liquidityGrossBefore.IsZero() {
		if tick <= tickCurrent {
			tickInfo.SetFeeGrowthOutside0X128(feeGrowthGlobal0X128.ToString())
			tickInfo.SetFeeGrowthOutside1X128(feeGrowthGlobal1X128.ToString())
			tickInfo.SetSecondsPerLiquidityOutsideX128(secondsPerLiquidityCumulativeX128.ToString())
			tickInfo.SetTickCumulativeOutside(tickCumulative)
			tickInfo.SetSecondsOutside(uint32(blockTimestamp))
		}
		tickInfo.SetInitialized(true)
	}

	tickInfo.SetLiquidityGross(liquidityGrossAfter.ToString())

	liquidityNet := i256.MustFromDecimal(tickInfo.LiquidityNet())
	if upper {
		newLiquidityNet := i256.Zero().Sub(liquidityNet, liquidityDelta)
		checkOverFlowInt128(newLiquidityNet)
		tickInfo.SetLiquidityNet(newLiquidityNet.ToString())
	} else {
		newLiquidityNet := i256.Zero().Add(liquidityNet, liquidityDelta)
		checkOverFlowInt128(newLiquidityNet)
		tickInfo.SetLiquidityNet(newLiquidityNet.ToString())
	}

	setTick(p, tick, tickInfo)

	return flipped
}

// tickCross updates a tick's state when it is crossed and returns the liquidity net.
// Updates fee growth and oracle accumulator values for the tick.
func tickCross(
	p *pl.Pool,
	tick int32,
	feeGrowthGlobal0X128 *u256.Uint,
	feeGrowthGlobal1X128 *u256.Uint,
	secondsPerLiquidityCumulativeX128 *u256.Uint,
	tickCumulative int64,
	blockTimestamp int64,
) *i256.Int {
	thisTick := getTick(p, tick)

	feeOutside0 := u256.MustFromDecimal(thisTick.FeeGrowthOutside0X128())
	feeOutside1 := u256.MustFromDecimal(thisTick.FeeGrowthOutside1X128())
	thisTick.SetFeeGrowthOutside0X128(u256.Zero().Sub(feeGrowthGlobal0X128, feeOutside0).ToString())
	thisTick.SetFeeGrowthOutside1X128(u256.Zero().Sub(feeGrowthGlobal1X128, feeOutside1).ToString())

	tickSecondsPerLiquidity := u256.MustFromDecimal(thisTick.SecondsPerLiquidityOutsideX128())
	thisTick.SetSecondsPerLiquidityOutsideX128(u256.Zero().Sub(secondsPerLiquidityCumulativeX128, tickSecondsPerLiquidity).ToString())
	thisTick.SetTickCumulativeOutside(tickCumulative - thisTick.TickCumulativeOutside())
	thisTick.SetSecondsOutside(uint32(blockTimestamp) - thisTick.SecondsOutside())

	setTick(p, tick, thisTick)

	return i256.MustFromDecimal(thisTick.LiquidityNet())
}

// setTick updates the tick data for the specified tick index in the pool.
func setTick(p *pl.Pool, tick int32, newTickInfo pl.TickInfo) {
	p.SetTick(tick, newTickInfo)
}

// deleteTick deletes the tick data for the specified tick index in the pool.
func deleteTick(p *pl.Pool, tick int32) {
	p.DeleteTick(tick)
}

// getTick retrieves the TickInfo associated with the specified tick index from the pool.
// If the TickInfo contains any nil fields, they are replaced with zero values using valueOrZero.
//
// Parameters:
// - tick: The tick index (int32) for which the TickInfo is to be retrieved.
//
// Behavior:
// - Retrieves the TickInfo for the given tick from the pool's tick map.
// - Ensures that all fields of TickInfo are non-nil by calling valueOrZero, which replaces nil values with zero.
// - Returns the updated TickInfo.
//
// Returns:
// - TickInfo: The tick data with all fields guaranteed to have valid values (nil fields are set to zero).
//
// Use Case:
// This function ensures the retrieved tick data is always valid and safe for further operations,
// such as calculations or updates, by sanitizing nil fields in the TickInfo structure.
func getTick(p *pl.Pool, tick int32) pl.TickInfo {
	tickInfo, err := p.GetTick(tick)
	if err != nil {
		return pl.NewTickInfo()
	}

	return tickInfo
}

// mustGetTick retrieves the TickInfo for a specific tick, panicking if the tick does not exist.
//
// This function ensures that the requested tick data exists in the pool's tick mapping.
// If the tick does not exist, it panics with an appropriate error message.
//
// Parameters:
//   - tick: int32, the index of the tick to retrieve.
//
// Returns:
//   - TickInfo: The information associated with the specified tick.
//
// Behavior:
//   - Checks if the tick exists in the pool's tick mapping (`p.ticks`).
//   - If the tick exists, it returns the corresponding `TickInfo`.
//   - If the tick does not exist, the function panics with a descriptive error.
//
// Panic Conditions:
//   - The specified tick does not exist in the pool's mapping.
//
// Example:
//
// ```gno
//
//	tickInfo := pool.mustGetTick(10)
//	ufmt.Println("Tick Info:", tickInfo)
//
// ```
func mustGetTick(p *pl.Pool, tick int32) *pl.TickInfo {
	tickInfo, err := p.GetTick(tick)
	if err != nil {
		panic(err)
	}

	return &tickInfo
}

// calculateMaxLiquidityPerTick calculates the maximum liquidity
// per tick for a given tick spacing.
func calculateMaxLiquidityPerTick(tickSpacing int32) *u256.Uint {
	switch tickSpacing {
	case 1:
		return maxLiquidityPerTickSpacing1FromDec()
	case 10:
		return maxLiquidityPerTickSpacing10FromDec()
	case 60:
		return maxLiquidityPerTickSpacing60FromDec()
	case 200:
		return maxLiquidityPerTickSpacing200FromDec()
	default:
		minTick := (MIN_TICK / tickSpacing) * tickSpacing
		maxTick := (MAX_TICK / tickSpacing) * tickSpacing
		numTicks := uint64((maxTick-minTick)/tickSpacing) + 1

		return u256.Zero().Div(consts.MaxUint128(), u256.NewUint(numTicks))
	}
}

// getFeeGrowthBelowX128 calculates the fee growth below a specified tick.
//
// This function computes the fee growth for token 0 and token 1 below a given tick (`tickLower`)
// relative to the current tick (`tickCurrent`). The fee growth values are adjusted based on whether
// the `tickCurrent` is above or below the `tickLower`.
//
// Parameters:
//   - tickLower: int32, the lower tick boundary for fee calculation.
//   - tickCurrent: int32, the current tick index.
//   - feeGrowthGlobal0X128: *u256.Uint, the global fee growth for token 0 in X128 precision.
//   - feeGrowthGlobal1X128: *u256.Uint, the global fee growth for token 1 in X128 precision.
//   - lowerTick: TickInfo, the fee growth and liquidity details for the lower tick.
//
// Returns:
//   - *u256.Uint: Fee growth below `tickLower` for token 0.
//   - *u256.Uint: Fee growth below `tickLower` for token 1.
//
// Workflow:
//  1. If `tickCurrent` is greater than or equal to `tickLower`:
//     - Return the `feeGrowthOutside0X128` and `feeGrowthOutside1X128` values of the `lowerTick`.
//  2. If `tickCurrent` is below `tickLower`:
//     - Compute the fee growth below the lower tick by subtracting `feeGrowthOutside` values
//     from the global fee growth values (`feeGrowthGlobal0X128` and `feeGrowthGlobal1X128`).
//  3. Return the calculated fee growth values for both tokens.
//
// Behavior:
//   - If `tickCurrent >= tickLower`, the fee growth outside the lower tick is returned as-is.
//   - If `tickCurrent < tickLower`, the fee growth is calculated as:
//     feeGrowthBelow = feeGrowthGlobal - feeGrowthOutside
//
// Example:
//
// ```gno
//
//	feeGrowth0, feeGrowth1 := getFeeGrowthBelowX128(
//	    100, 150, globalFeeGrowth0, globalFeeGrowth1, lowerTickInfo,
//	)
//	println("Fee Growth Below:", feeGrowth0, feeGrowth1)
func getFeeGrowthBelowX128(
	tickLower, tickCurrent int32,
	feeGrowthGlobal0X128, feeGrowthGlobal1X128 *u256.Uint,
	lowerTick pl.TickInfo,
) (*u256.Uint, *u256.Uint) {
	feeOutside0 := u256.MustFromDecimal(lowerTick.FeeGrowthOutside0X128())
	feeOutside1 := u256.MustFromDecimal(lowerTick.FeeGrowthOutside1X128())

	if tickCurrent >= tickLower {
		return feeOutside0, feeOutside1
	}

	feeGrowthBelow0X128 := u256.Zero().Sub(feeGrowthGlobal0X128, feeOutside0)
	feeGrowthBelow1X128 := u256.Zero().Sub(feeGrowthGlobal1X128, feeOutside1)

	return feeGrowthBelow0X128, feeGrowthBelow1X128
}

// getFeeGrowthAboveX128 calculates the fee growth above a specified tick.
//
// This function computes the fee growth for token 0 and token 1 above a given tick (`tickUpper`)
// relative to the current tick (`tickCurrent`). The fee growth values are adjusted based on whether
// the `tickCurrent` is above or below the `tickUpper`.
//
// Parameters:
//   - tickUpper: int32, the upper tick boundary for fee calculation.
//   - tickCurrent: int32, the current tick index.
//   - feeGrowthGlobal0X128: *u256.Uint, the global fee growth for token 0 in X128 precision.
//   - feeGrowthGlobal1X128: *u256.Uint, the global fee growth for token 1 in X128 precision.
//   - upperTick: TickInfo, the fee growth and liquidity details for the upper tick.
//
// Returns:
//   - *u256.Uint: Fee growth above `tickUpper` for token 0.
//   - *u256.Uint: Fee growth above `tickUpper` for token 1.
//
// Workflow:
//  1. If `tickCurrent` is less than `tickUpper`:
//     - Return the `feeGrowthOutside0X128` and `feeGrowthOutside1X128` values of the `upperTick`.
//  2. If `tickCurrent` is greater than or equal to `tickUpper`:
//     - Compute the fee growth above the upper tick by subtracting `feeGrowthOutside` values
//     from the global fee growth values (`feeGrowthGlobal0X128` and `feeGrowthGlobal1X128`).
//  3. Return the calculated fee growth values for both tokens.
//
// Behavior:
//   - If `tickCurrent < tickUpper`, the fee growth outside the upper tick is returned as-is.
//   - If `tickCurrent >= tickUpper`, the fee growth is calculated as:
//     feeGrowthAbove = feeGrowthGlobal - feeGrowthOutside
//
// Example:
//
//	feeGrowth0, feeGrowth1 := getFeeGrowthAboveX128(
//	    200, 150, globalFeeGrowth0, globalFeeGrowth1, upperTickInfo,
//	)
//	println("Fee Growth Above:", feeGrowth0, feeGrowth1)
//
// ```
func getFeeGrowthAboveX128(
	tickUpper, tickCurrent int32,
	feeGrowthGlobal0X128, feeGrowthGlobal1X128 *u256.Uint,
	upperTick pl.TickInfo,
) (*u256.Uint, *u256.Uint) {
	feeOutside0 := u256.MustFromDecimal(upperTick.FeeGrowthOutside0X128())
	feeOutside1 := u256.MustFromDecimal(upperTick.FeeGrowthOutside1X128())

	if tickCurrent < tickUpper {
		return feeOutside0, feeOutside1
	}

	feeGrowthAbove0X128 := u256.Zero().Sub(feeGrowthGlobal0X128, feeOutside0)
	feeGrowthAbove1X128 := u256.Zero().Sub(feeGrowthGlobal1X128, feeOutside1)

	return feeGrowthAbove0X128, feeGrowthAbove1X128
}

// validateTicks validates the tick range for a liquidity position.
//
// This function performs three essential checks to ensure the provided
// tick values are valid before creating or modifying a liquidity position.
func validateTicks(tickLower, tickUpper int32) error {
	if tickLower >= tickUpper {
		return makeErrorWithDetails(
			errInvalidTickRange,
			ufmt.Sprintf("tickLower(%d), tickUpper(%d)", tickLower, tickUpper),
		)
	}

	if tickLower < MIN_TICK {
		return makeErrorWithDetails(
			errTickLowerInvalid,
			ufmt.Sprintf("tickLower(%d) < MIN_TICK(%d)", tickLower, MIN_TICK),
		)
	}

	if tickUpper > MAX_TICK {
		return makeErrorWithDetails(
			errTickUpperInvalid,
			ufmt.Sprintf("tickUpper(%d) > MAX_TICK(%d)", tickUpper, MAX_TICK),
		)
	}

	return nil
}

tick_bitmap.gno

package pool

import (
	"gno.land/p/gnoswap/gnsmath/v1"
	u256 "gno.land/p/gnoswap/uint256/v1"
	pl "gno.land/r/gnoswap/pool"
)

// bitMask8 is used for efficient modulo 256 operations
const bitMask8 = 0xff // 256 - 1

// tickBitmapFlipTick flips the state of a tick in the tick bitmap.
//
// This function toggles the "initialized" state of a tick in the tick bitmap.
// It ensures that the tick aligns with the specified tick spacing and then
// flips the corresponding bit in the bitmap representation.
//
// Parameters:
//   - tick: int32, the tick index to toggle.
//   - tickSpacing: int32, the spacing between valid ticks.
//     The tick must align with this spacing.
//
// Workflow:
//  1. Validates that the `tick` aligns with `tickSpacing` using `checkTickSpacing`.
//  2. Computes the position of the bit in the tick bitmap:
//     - `wordPos`: Determines which word in the bitmap contains the bit.
//     - `bitPos`: Identifies the position of the bit within the word.
//  3. Creates a bitmask using `Lsh` (Left Shift) to target the bit at `bitPos`.
//  4. Toggles (flips) the bit using XOR with the current value of the tick bitmap.
//  5. Updates the tick bitmap with the modified word.
//
// Behavior:
//   - If the bit is `0` (uninitialized), it will be flipped to `1` (initialized).
//   - If the bit is `1` (initialized), it will be flipped to `0` (uninitialized).
//
// Example:
//
//	pool.tickBitmapFlipTick(120, 60)
//	// This flips the bit for tick 120 with a tick spacing of 60.
//
// Notes:
//   - The `tick` must be divisible by `tickSpacing`. If not, the function will panic.
func tickBitmapFlipTick(
	p *pl.Pool,
	tick int32,
	tickSpacing int32,
) {
	checkTickSpacing(tick, tickSpacing)
	wordPos, bitPos := tickBitmapPosition(tick / tickSpacing)

	mask := u256.Zero().Lsh(u256.One(), uint(bitPos))
	current := getTickBitmap(p, wordPos)
	next := u256.Zero().Xor(current, mask)
	if next.IsZero() {
		deleteTickBitmap(p, wordPos)
		return
	}

	setTickBitmap(p, wordPos, next)
}

// tickBitmapNextInitializedTickWithInOneWord finds the next initialized tick within
// one word of the bitmap.
func tickBitmapNextInitializedTickWithInOneWord(
	p *pl.Pool,
	tick int32,
	tickSpacing int32,
	lte bool,
) (int32, bool) {
	compress := tick / tickSpacing
	// Round towards negative infinity for negative ticks
	if tick < 0 && tick%tickSpacing != 0 {
		compress--
	}

	wordPos, bitPos := getWordAndBitPos(compress, lte)
	mask := getMaskBit(uint(bitPos), lte)
	masked := u256.Zero().And(getTickBitmap(p, wordPos), mask)
	initialized := !masked.IsZero()

	nextTick := getNextTick(lte, initialized, compress, bitPos, tickSpacing, masked)
	return nextTick, initialized
}

// getTickBitmap gets the tick bitmap for the given word position.
// Missing words are implicit zeroes.
func getTickBitmap(p *pl.Pool, wordPos int16) *u256.Uint {
	value, exist := p.TickBitmaps()[wordPos]
	if !exist {
		return u256.Zero()
	}

	return u256.MustFromDecimal(value)
}

// setTickBitmap sets the tick bitmap for the given word position.
func setTickBitmap(p *pl.Pool, wordPos int16, tickBitmap *u256.Uint) {
	p.SetTickBitmap(wordPos, tickBitmap.ToString())
}

// deleteTickBitmap deletes the tick bitmap for the given word position.
func deleteTickBitmap(p *pl.Pool, wordPos int16) {
	p.DeleteTickBitmap(wordPos)
}

// tickBitmapPosition calculates the word and bit position for a given tick
func tickBitmapPosition(tick int32) (int16, uint8) {
	return int16(tick >> 8), uint8(tick) & bitMask8
}

// getWordAndBitPos gets tick's wordPos and bitPos depending on the swap direction
func getWordAndBitPos(tick int32, lte bool) (int16, uint8) {
	if !lte {
		tick++
	}
	return tickBitmapPosition(tick)
}

// getMaskBit generates a mask based on the provided bit position (bitPos) and a boolean flag (lte).
// The function constructs a bitmask with a shift depending on the bit position and the boolean value.
// It either returns the mask or its negation, based on the value of 'lte' (swap direction).
//
// NOTE: should always use a newly created `u256.One()` object.
func getMaskBit(bitPos uint, lte bool) *u256.Uint {
	if lte {
		if bitPos == bitMask8 {
			return u256.Zero().SetAllOne()
		}
		return u256.Zero().Sub(u256.Zero().Lsh(u256.One(), bitPos+1), u256.One())
	}
	if bitPos == 0 {
		return u256.Zero().SetAllOne()
	}
	return u256.Zero().Not(u256.Zero().Sub(u256.Zero().Lsh(u256.One(), bitPos), u256.One()))
}

// getNextTick gets the next tick depending on the initialized state and the swap direction
func getNextTick(lte, initialized bool, compress int32, bitPos uint8, tickSpacing int32, masked *u256.Uint) int32 {
	if initialized {
		return getTickIfInitialized(compress, tickSpacing, bitPos, masked, lte)
	}
	return getTickIfNotInitialized(compress, tickSpacing, bitPos, lte)
}

// getTickIfInitialized gets the next tick if the tick bitmap is initialized
func getTickIfInitialized(compress, tickSpacing int32, bitPos uint8, masked *u256.Uint, lte bool) int32 {
	if lte {
		return (compress - int32(bitPos-gnsmath.BitMathMostSignificantBit(masked))) * tickSpacing
	}
	return (compress + 1 + int32(gnsmath.BitMathLeastSignificantBit(masked)-bitPos)) * tickSpacing
}

// getTickIfNotInitialized gets the next tick if the tick bitmap is not initialized
func getTickIfNotInitialized(compress, tickSpacing int32, bitPos uint8, lte bool) int32 {
	if lte {
		return (compress - int32(bitPos)) * tickSpacing
	}
	return (compress + 1 + int32(bitMask8-bitPos)) * tickSpacing
}

transfer.gno

package pool

import (
	ufmt "gno.land/p/nt/ufmt/v0"

	prabc "gno.land/p/gnoswap/rbac/v1"

	"gno.land/r/gnoswap/access/v1"
	"gno.land/r/gnoswap/common"
	pl "gno.land/r/gnoswap/pool"

	"gno.land/p/gnoswap/gnsmath/v1"
	i256 "gno.land/p/gnoswap/int256/v1"
	u256 "gno.land/p/gnoswap/uint256/v1"
)

// safeTransfer performs a token transfer out of the pool while ensuring
// the pool has sufficient balance and updating internal accounting.
// This function is typically used during swaps and liquidity removals.
//
// Important requirements:
//   - The amount must be a positive value representing tokens to transfer out
//   - The pool must have sufficient balance for the transfer
//   - The transfer amount must fit within int64 range
//
// Parameters:
//   - p: the pool instance
//   - to: destination address for the transfer
//   - tokenPath: path identifier of the token to transfer
//   - amount: amount to transfer (positive u256.Uint value)
//   - isToken0: true if transferring token0, false for token1
//
// The function will:
//  1. Check pool has sufficient balance
//  2. Execute the transfer
//  3. Subtract the amount from pool's internal balance
//
// Panics if any validation fails or if the transfer fails
func (i *poolV1) safeTransfer(
	_ int,
	rlm realm,
	p *pl.Pool,
	to address,
	tokenPath string,
	amount *u256.Uint,
	isToken0 bool,
) {
	token0 := p.BalanceToken0()
	token1 := p.BalanceToken1()
	amountInt64 := gnsmath.SafeConvertToInt64(amount)

	if err := validatePoolBalance(token0, token1, amountInt64, isToken0); err != nil {
		panic(err)
	}

	common.SafeGRC20Transfer(0, rlm, tokenPath, to, amountInt64)

	newBalance, err := updatePoolBalance(token0, token1, amountInt64, isToken0)
	if err != nil {
		panic(err)
	}

	poolBalances := p.Balances()

	if isToken0 {
		poolBalances.SetToken0(newBalance)
	} else {
		poolBalances.SetToken1(newBalance)
	}

	p.SetBalances(poolBalances)
}

// safeTransferFrom securely transfers tokens into the pool while ensuring balance consistency.
//
// This function performs the following steps:
// 1. Validates and converts the transfer amount to `int64` using `gnsmath.SafeConvertToInt64`.
// 2. Executes the token transfer using `TransferFrom` via the token teller contract.
// 3. Verifies that the destination balance reflects the correct amount after transfer.
// 4. Updates the pool's internal balances (`token0` or `token1`) and validates the updated state.
//
// Parameters:
// - p (*pl.Pool): The pool instance to transfer tokens into.
// - from (address): Source address for the token transfer.
// - to (address): Destination address, typically the pool address.
// - tokenPath (string): Path identifier for the token being transferred.
// - amount (*u256.Uint): The amount of tokens to transfer (must be a positive value).
// - isToken0 (bool): A flag indicating whether the token being transferred is token0 (`true`) or token1 (`false`).
//
// Panics:
// - If the `amount` exceeds the int64 range during conversion.
// - If the token transfer (`TransferFrom`) fails.
// - If the destination balance after the transfer does not match the expected amount.
// - If the pool's internal balances (`token0` or `token1`) overflow or become inconsistent.
//
// Notes:
// - The function assumes that the sender (`from`) has approved the pool to spend the specified tokens.
// - The balance consistency check ensures that no tokens are lost or double-counted during the transfer.
// - Pool balance updates are performed atomically to ensure internal consistency.
func (i *poolV1) safeTransferFrom(
	_ int,
	rlm realm,
	p *pl.Pool,
	from, to address,
	tokenPath string,
	amount *u256.Uint,
	isToken0 bool,
) {
	amountInt64 := gnsmath.SafeConvertToInt64(amount)

	beforeBalance := common.BalanceOf(tokenPath, to)

	common.SafeGRC20TransferFrom(0, rlm, tokenPath, from, to, amountInt64)

	afterBalance := common.BalanceOf(tokenPath, to)
	if gnsmath.SafeAddInt64(beforeBalance, amountInt64) != afterBalance {
		panic(ufmt.Sprintf(
			"%v. beforeBalance(%d) + amount(%d) != afterBalance(%d)",
			errTransferFailed, beforeBalance, amountInt64, afterBalance,
		))
	}

	poolBalances := p.Balances()

	// update pool balances
	if isToken0 {
		poolBalances.SetToken0(gnsmath.SafeAddInt64(poolBalances.Token0(), amountInt64))
	} else {
		poolBalances.SetToken1(gnsmath.SafeAddInt64(poolBalances.Token1(), amountInt64))
	}

	p.SetBalances(poolBalances)
}

// safeSwapCallback executes a swap callback and validates the token payment.
//
// This function implements the flash swap pattern where the pool first sends output tokens
// to the recipient, then invokes the callback to receive input tokens from the caller.
// The callback is responsible for transferring the required input tokens to the pool.
//
// Callback Signature:
//
//	func(cur realm, amount0Delta, amount1Delta int64, _ *pool.CallbackMarker) error
//
// Delta Convention (following Uniswap V3 standard):
//   - Positive delta: Amount the pool must RECEIVE (input token)
//   - Negative delta: Amount the pool has SENT (output token)
//
// For zeroForOne swaps (token0 → token1):
//   - amount0Delta > 0: Pool receives token0 (input)
//   - amount1Delta < 0: Pool sends token1 (output)
//
// For oneForZero swaps (token1 → token0):
//   - amount0Delta < 0: Pool sends token0 (output)
//   - amount1Delta > 0: Pool receives token1 (input)
//
// Parameters:
//   - p: The pool instance
//   - tokenPath: Path of the input token that pool must receive
//   - amountInInt256: Amount pool must receive (positive i256.Int)
//   - amountOutInt256: Amount pool has sent (negative i256.Int)
//   - zeroForOne: Swap direction (true = token0 to token1)
//   - swapCallback: Callback function that must transfer input tokens to pool
//
// The callback needed:
//  1. Verify the caller is the legitimate pool contract address to prevent unauthorized invocations
//  2. Transfer at least `amountIn` of input tokens to the pool
//  3. Return nil on success, or an error to revert the swap
//
// Example callback implementation:
//
//	func(cur realm, amount0Delta, amount1Delta int64, _ *pool.CallbackMarker) error {
//	    // Security check: ensure this callback is invoked by the legitimate pool
//	    caller := runtime.PreviousRealm().Address()
//	    poolAddr := chain.PackageAddress("gno.land/r/gnoswap/pool")
//
//	    if caller != poolAddr {
//	        panic("unauthorized caller")
//	    }
//
//	    if amount0Delta > 0 {
//	        // Transfer token0 to pool
//	        token0.Transfer(cross, poolAddr, amount0Delta)
//	    }
//	    if amount1Delta > 0 {
//	        // Transfer token1 to pool
//	        token1.Transfer(cross, poolAddr, amount1Delta)
//	    }
//	    return nil
//	}
func (i *poolV1) safeSwapCallback(
	_ int,
	rlm realm,
	p *pl.Pool,
	tokenPath string,
	amountInInt256 *i256.Int,
	amountOutInt256 *i256.Int,
	zeroForOne bool,
	swapCallback func(cur realm, amount0Delta, amount1Delta int64, _ *pl.CallbackMarker) error,
) {
	if swapCallback == nil {
		panic(makeErrorWithDetails(
			errInvalidInput,
			"swapCallback is nil",
		))
	}

	currentAddress := access.MustGetAddress(prabc.ROLE_POOL.String())

	amountIn := amountInInt256.Int64()
	amountOut := amountOutInt256.Int64()
	balanceBefore := common.BalanceOf(tokenPath, currentAddress)

	// Make callback to the calling contract
	// The contract should transfer tokens to pool within this callback
	// Following Uniswap V3 convention:
	// - Positive delta: amount the pool must receive (input token)
	// - Negative delta: amount the pool has sent (output token)
	var amount0Delta, amount1Delta, beforeTokenBalance int64

	if zeroForOne {
		// zeroForOne: pool receives token0 (positive), sends token1 (negative)
		amount0Delta = amountIn
		amount1Delta = amountOut
		beforeTokenBalance = p.BalanceToken0()
	} else {
		// !zeroForOne: pool receives token1 (positive), sends token0 (negative)
		amount0Delta = amountOut
		amount1Delta = amountIn
		beforeTokenBalance = p.BalanceToken1()
	}

	// execute swap callback
	// CallbackMarker is created by the pool module to enforce type-system level validation.
	// Allocation goes through pl.NewCallbackMarker so the alloc happens in pool realm
	// (interrealm v2 forbids /r/-declared types being constructed outside their owner).
	err := swapCallback(cross(rlm), amount0Delta, amount1Delta, pl.NewCallbackMarker())
	if err != nil {
		panic(err)
	}

	balanceAfter := common.BalanceOf(tokenPath, currentAddress)
	balanceIncrease := gnsmath.SafeSubInt64(balanceAfter, balanceBefore)

	// check insufficient payment by swap callback
	if balanceIncrease < amountIn {
		panic(makeErrorWithDetails(
			errInsufficientPayment,
			ufmt.Sprintf("insufficient payment: expected %d, received %d", amountIn, balanceIncrease),
		))
	}

	// check overflow update pool balance
	resultTokenBalance := gnsmath.SafeAddInt64(beforeTokenBalance, amountIn)

	poolBalances := p.Balances()

	if zeroForOne {
		poolBalances.SetToken0(resultTokenBalance)
	} else {
		poolBalances.SetToken1(resultTokenBalance)
	}

	p.SetBalances(poolBalances)
}

// validatePoolBalance checks if the pool has sufficient balance of either token0 and token1
// before proceeding with a transfer. This prevents the pool won't go into a negative balance.
func validatePoolBalance(token0, token1, amount int64, isToken0 bool) error {
	if amount < 0 {
		return ufmt.Errorf("%v. amount(%d) must be positive", errTransferFailed, amount)
	}

	if isToken0 {
		if token0 < amount {
			return ufmt.Errorf(
				"%v. token0(%d) >= amount(%d)",
				errTransferFailed, token0, amount,
			)
		}
		return nil
	}
	if token1 < amount {
		return ufmt.Errorf(
			"%v. token1(%d) >= amount(%d)",
			errTransferFailed, token1, amount,
		)
	}
	return nil
}

// updatePoolBalance calculates the new balance after a transfer and validate.
// It ensures the resulting balance won't be negative or overflow.
func updatePoolBalance(
	token0, token1, amount int64,
	isToken0 bool,
) (int64, error) {
	if amount < 0 {
		return 0, ufmt.Errorf("%v. amount(%d) must be positive", errBalanceUpdateFailed, amount)
	}

	if isToken0 {
		if token0 < amount {
			return 0, ufmt.Errorf(
				"%v. cannot decrease, token0(%d) - amount(%d)",
				errBalanceUpdateFailed, token0, amount,
			)
		}
		return gnsmath.SafeSubInt64(token0, amount), nil
	}

	if token1 < amount {
		return 0, ufmt.Errorf(
			"%v. cannot decrease, token1(%d) - amount(%d)",
			errBalanceUpdateFailed, token1, amount,
		)
	}
	return gnsmath.SafeSubInt64(token1, amount), nil
}

type.gno

package pool

import (
	"gno.land/p/gnoswap/gnsmath/v1"
	i256 "gno.land/p/gnoswap/int256/v1"
	u256 "gno.land/p/gnoswap/uint256/v1"

	pl "gno.land/r/gnoswap/pool"
)

// ModifyPositionParams repersents the parameters for modifying a liquidity position.
// This structure is used internally both `Mint` and `Burn` operation to manage
// the liquidity positions.
type ModifyPositionParams struct {
	// owner is the address that owns the position
	owner address

	// tickLower and atickUpper define the price range
	// The actual price range is calculated as 1.0001^tick
	// This allows for precision in price range while using integer math.

	tickLower int32 // lower tick of the position
	tickUpper int32 // upper tick of the position

	// liquidityDelta represents the change in liquidity
	// Positive for minting, negative for burning
	liquidityDelta *i256.Int
}

// newModifyPositionParams creates a new `ModifyPositionParams` instance.
// This is used to preare parameters for the `modifyPosition` function,
// which handles both minting and burning of liquidity positions.
//
// Parameters:
//   - owner: address that will own (or owns) the position
//   - tickLower: lower tick bound of the position
//   - tickUpper: upper tick bound of the position
//   - liquidityDelta: amount of liquidity to add (positive) or remove (negative)
//
// The tick parameters represent prices as powers of 1.0001:
// - actual_price = 1.0001^tick
// - For example, tick = 100 means price = 1.0001^100
//
// Returns:
//   - ModifyPositionParams: a new instance of ModifyPositionParams
func newModifyPositionParams(
	owner address,
	tickLower int32,
	tickUpper int32,
	liquidityDelta *i256.Int,
) ModifyPositionParams {
	return ModifyPositionParams{
		owner:          owner,
		tickLower:      tickLower,
		tickUpper:      tickUpper,
		liquidityDelta: liquidityDelta,
	}
}

// SwapCache holds immutable swap-start inputs and oracle cumulatives that are
// populated lazily when the swap first crosses an initialized tick.
type SwapCache struct {
	feeProtocol                       uint8      // protocol fee for the input token
	liquidityStart                    *u256.Uint // liquidity at the beginning of the swap
	blockTimestamp                    int64      // current block timestamp
	tickCumulative                    int64      // current tick accumulator value
	secondsPerLiquidityCumulativeX128 *u256.Uint // current seconds per liquidity accumulator
	computedLatestObservation         bool       // whether we've computed the above accumulators
	slot0Start                        pl.Slot0   // immutable Slot0 snapshot captured at swap start
	readOnly                          bool       // quote without tick accounting or hooks
}

func newSwapCache(
	feeProtocol uint8,
	liquidityStart *u256.Uint,
	blockTimestamp int64,
	slot0Start pl.Slot0,
) *SwapCache {
	return &SwapCache{
		feeProtocol:                       feeProtocol,
		liquidityStart:                    liquidityStart,
		blockTimestamp:                    blockTimestamp,
		tickCumulative:                    0,
		secondsPerLiquidityCumulativeX128: u256.Zero(),
		computedLatestObservation:         false,
		slot0Start:                        slot0Start.Clone(),
	}
}

// SwapState tracks the changing values during a swap.
// This type helps manage the state transitions that occur as the swap progresses
// across different price ranges.
type SwapState struct {
	amountSpecifiedRemaining *i256.Int  // amount remaining to be swapped in/out of the input/output token
	amountCalculated         *i256.Int  // amount already swapped out/in of the output/input token
	sqrtPriceX96             *u256.Uint // current sqrt(price)
	tick                     int32      // tick associated with the current sqrt(price)
	feeGrowthGlobalX128      *u256.Uint // global fee growth of the input token
	protocolFee              *u256.Uint // amount of input token paid as protocol fee
	liquidity                *u256.Uint // current liquidity in range
}

func newSwapState(
	amountSpecifiedRemaining *i256.Int,
	feeGrowthGlobalX128 *u256.Uint,
	liquidity *u256.Uint,
	slot0 pl.Slot0,
) SwapState {
	return SwapState{
		amountSpecifiedRemaining: amountSpecifiedRemaining,
		amountCalculated:         i256.Zero(),
		sqrtPriceX96:             slot0.SqrtPriceX96(),
		tick:                     slot0.Tick(),
		feeGrowthGlobalX128:      feeGrowthGlobalX128,
		protocolFee:              u256.Zero(),
		liquidity:                liquidity,
	}
}

func (s *SwapState) setSqrtPriceX96(sqrtPriceX96 *u256.Uint) {
	s.sqrtPriceX96 = sqrtPriceX96.Clone()
}

func (s *SwapState) setTick(tick int32) {
	s.tick = tick
}

func (s *SwapState) setFeeGrowthGlobalX128(feeGrowthGlobalX128 *u256.Uint) {
	s.feeGrowthGlobalX128 = feeGrowthGlobalX128
}

func (s *SwapState) setProtocolFee(fee *u256.Uint) {
	s.protocolFee = fee
}

// StepComputations holds intermediate values used during a single step of a swap.
// Each step represents movement from the current tick to the next initialized tick
// or the target price, whichever comes first.
type StepComputations struct {
	sqrtPriceStartX96 *u256.Uint // price at the beginning of the step
	tickNext          int32      // next tick to swap to from the current tick in the swap direction
	initialized       bool       // whether tickNext is initialized
	sqrtPriceNextX96  *u256.Uint // sqrt(price) for the next tick (token1/token0) Q96
	amountIn          *u256.Uint // how much being swapped in this step
	amountOut         *u256.Uint // how much is being swapped out in this step
	feeAmount         *u256.Uint // how much fee is being paid in this step
}

// init initializes the computation for a single swap step
func (step *StepComputations) initSwapStep(state SwapState, p *pl.Pool, zeroForOne bool) {
	step.sqrtPriceStartX96 = state.sqrtPriceX96
	step.tickNext, step.initialized = tickBitmapNextInitializedTickWithInOneWord(
		p,
		state.tick,
		p.TickSpacing(),
		zeroForOne,
	)

	// prevent overshoot the min/max tick
	step.clampTickNext()

	// get the price for the next tick
	step.sqrtPriceNextX96 = gnsmath.TickMathGetSqrtRatioAtTick(step.tickNext)
}

// clampTickNext ensures that `tickNext` stays within the min, max tick boundaries
// as the tick bitmap is not aware of these bounds
func (step *StepComputations) clampTickNext() {
	if step.tickNext < MIN_TICK {
		step.tickNext = MIN_TICK
	} else if step.tickNext > MAX_TICK {
		step.tickNext = MAX_TICK
	}
}

func newPool(poolInfo *poolCreateConfig) *pl.Pool {
	tick := gnsmath.TickMathGetTickAtSqrtRatio(poolInfo.SqrtPriceX96())

	return pl.NewPool(
		poolInfo.Token0Path(),
		poolInfo.Token1Path(),
		poolInfo.Fee(),
		poolInfo.SqrtPriceX96(),
		poolInfo.TickSpacing(),
		tick,
		poolInfo.slot0FeeProtocol,
	)
}

utils.gno

package pool

import (
	i256 "gno.land/p/gnoswap/int256/v1"
	u256 "gno.land/p/gnoswap/uint256/v1"
	ufmt "gno.land/p/nt/ufmt/v0"
)

const (
	MAX_UINT64  string = "18446744073709551615"
	MAX_INT64   string = "9223372036854775807"
	MAX_INT128  string = "170141183460469231731687303715884105727"
	MIN_INT128  string = "-170141183460469231731687303715884105728"
	MAX_UINT128 string = "340282366920938463463374607431768211455"
	MAX_INT256  string = "57896044618658097711785492504343953926634992332820282019728792003956564819967"

	INT64_MIN int64 = -9223372036854775808
	INT64_MAX int64 = 9223372036854775807

	Q96_RESOLUTION  uint = 96
	Q128_RESOLUTION uint = 128

	Q64  string = "18446744073709551616"                    // 2 ** 64
	Q96  string = "79228162514264337593543950336"           // 2 ** 96
	Q128 string = "340282366920938463463374607431768211456" // 2 ** 128
)

var (
	maxInt128FromDecimal  = i256.MustFromDecimal(MAX_INT128)
	minInt128FromDecimal  = i256.MustFromDecimal(MIN_INT128)
	maxUint128FromDecimal = u256.MustFromDecimal(MAX_UINT128)
	q128FromDecimal       = u256.MustFromDecimal(Q128)
)

var uint128Mask = func() *u256.Uint {
	m := u256.Zero().Lsh(u256.One(), Q128_RESOLUTION)
	return m.Sub(m, u256.One())
}()

// toUint128 ensures a *u256.Uint value fits within the uint128 range.
//
// This function validates that the given `value` is properly initialized and checks whether
// it exceeds the maximum value of uint128. If the value exceeds the uint128 range,
// it applies a masking operation to truncate the value to fit within the uint128 limit.
//
// Parameters:
//   - value: *u256.Uint, the value to be checked and possibly truncated.
//
// Returns:
//   - *u256.Uint: A value guaranteed to fit within the uint128 range.
//
// Notes:
//   - The function first checks if the value is not nil to avoid potential runtime errors.
//   - The mask ensures that only the lower 128 bits of the value are retained.
//   - If the input value is already within the uint128 range, it is returned unchanged.
//   - If masking is required, a new instance is returned without modifying the input.
//   - MAX_UINT128 is a constant representing `2^128 - 1`.
func toUint128(value *u256.Uint) *u256.Uint {
	if value == nil {
		panic(newErrorWithDetail(errInvalidInput, "value is nil"))
	}

	if value.Gt(maxUint128FromDecimal) {
		return u256.Zero().And(value, uint128Mask)
	}
	return value
}

// u256Min returns the smaller of two *u256.Uint values.
//
// This function compares two unsigned 256-bit integers and returns the smaller of the two.
// If `num1` is less than `num2`, it returns `num1`; otherwise, it returns `num2`.
//
// Parameters:
// - num1 (*u256.Uint): The first unsigned 256-bit integer.
// - num2 (*u256.Uint): The second unsigned 256-bit integer.
//
// Returns:
// - *u256.Uint: The smaller of `num1` and `num2`.
//
// Notes:
//   - This function uses the `Lt` (less than) method of `*u256.Uint` to perform the comparison.
//   - The function assumes both input values are non-nil. If nil inputs are possible in the usage context,
//     additional validation may be needed.
//
// Example:
// smaller := u256Min(u256.MustFromDecimal("10"), u256.MustFromDecimal("20")) // Returns 10
// smaller := u256Min(u256.MustFromDecimal("30"), u256.MustFromDecimal("20")) // Returns 20
func u256Min(num1, num2 *u256.Uint) *u256.Uint {
	if num1.Lt(num2) {
		return num1
	}
	return num2
}

// checkOverFlowInt128 checks if the value overflows the int128 range.
func checkOverFlowInt128(value *i256.Int) {
	if value.Gt(maxInt128FromDecimal) || value.Lt(minInt128FromDecimal) {
		panic(ufmt.Sprintf(
			"%v: amount(%s) overflows int128 range",
			errOverflow, value.ToString(),
		))
	}
}

// checkTickSpacing checks if the tick is divisible by the tickSpacing.
func checkTickSpacing(tick, tickSpacing int32) {
	if tick%tickSpacing != 0 {
		panic(newErrorWithDetail(
			errInvalidTickAndTickSpacing,
			ufmt.Sprintf("tick(%d) MOD tickSpacing(%d) != 0(%d)", tick, tickSpacing, tick%tickSpacing),
		))
	}
}