Playground
assert.gno
package position
import (
"errors"
"time"
u256 "gno.land/p/gnoswap/uint256/v1"
ufmt "gno.land/p/nt/ufmt/v0"
prbac "gno.land/p/gnoswap/rbac/v1"
"gno.land/r/gnoswap/access/v1"
)
// assertIsNotExpired panics if the deadline is expired.
func assertIsNotExpired(deadline int64) {
now := time.Now().Unix()
if now > deadline {
panic(makeErrorWithDetails(
errExpired,
ufmt.Sprintf("transaction too old, now(%d) > deadline(%d)", now, deadline),
))
}
}
// assertValidNumberString panics if the input string does not represent a valid integer.
func assertValidNumberString(input string) {
if len(input) == 0 {
panic(newErrorWithDetail(errInvalidInput, "input is empty"))
}
bytes := []byte(input)
for i, b := range bytes {
if i == 0 && b == '-' {
continue // Allow if the first character is a negative sign (-)
}
if b < '0' || b > '9' {
panic(newErrorWithDetail(
errInvalidInput,
ufmt.Sprintf("input string : %s", input)))
}
}
}
// assertValidLiquidityAmount panics if the liquidity amount is zero.
func assertValidLiquidityAmount(liquidity string) {
if u256.MustFromDecimal(liquidity).IsZero() {
panic(newErrorWithDetail(
errZeroLiquidity,
ufmt.Sprintf("liquidity amount must be greater than 0, got %s", liquidity),
))
}
}
// assertExistsPosition panics if the position does not exist.
func assertExistsPosition(p *positionV1, positionId uint64) {
if !p.exists(positionId) {
panic(newErrorWithDetail(
errPositionDoesNotExist,
ufmt.Sprintf("position with position ID(%d) doesn't exist", positionId),
))
}
}
// assertIsOwnerForToken panics if caller is not the owner of the position.
func assertIsOwnerForToken(p *positionV1, positionId uint64, caller address) {
assertExistsPosition(p, positionId)
if !p.isOwner(positionId, caller) {
panic(newErrorWithDetail(
errNoPermission,
ufmt.Sprintf("caller(%s) is not owner of positionId(%d)", caller, positionId),
))
}
}
// assertIsOwnerOrOperatorForToken panics if caller is not the owner or operator of the position.
func assertIsOwnerOrOperatorForToken(p *positionV1, positionId uint64, caller address) {
assertExistsPosition(p, positionId)
if !p.isOwnerOrOperator(positionId, caller) {
panic(newErrorWithDetail(
errNoPermission,
ufmt.Sprintf("caller(%s) is not owner or approved operator of positionId(%d)", caller, positionId),
))
}
}
// assertEqualsAddress panics if addresses are invalid or not equal.
func assertEqualsAddress(prevAddr, otherAddr address) {
access.AssertIsValidAddress(prevAddr)
access.AssertIsValidAddress(otherAddr)
if prevAddr != otherAddr {
panic(newErrorWithDetail(
errInvalidAddress,
ufmt.Sprintf("(%s, %s)", prevAddr, otherAddr),
))
}
}
// assertValidOperatorAddress validates operator address.
// Empty address is allowed (for operator removal), but non-empty addresses must be valid.
func assertValidOperatorAddress(operator address) {
if operator != address("") && !operator.IsValid() {
panic(newErrorWithDetail(errInvalidAddress, ufmt.Sprintf("operator(%s)", operator)))
}
}
// assertIsNotMintToStaker panics if the mintTo address is staker.
func assertIsNotMintToStaker(mintTo address) {
stakerAddr := access.MustGetAddress(prbac.ROLE_STAKER.String())
if mintTo == stakerAddr {
panic(errors.New(errCannotMintToStaker))
}
}
burn.gno
package position
import (
"errors"
"gno.land/p/gnoswap/consts/v1"
"gno.land/p/gnoswap/gnsmath/v1"
u256 "gno.land/p/gnoswap/uint256/v1"
"gno.land/p/gnoswap/utils/v1"
ufmt "gno.land/p/nt/ufmt/v0"
pl "gno.land/r/gnoswap/pool"
"gno.land/r/gnoswap/position"
)
// decreaseLiquidity reduces position liquidity and collects fees.
// Returns positionId, liquidity, fee0, fee1, amount0, amount1, poolPath.
func (p *positionV1) decreaseLiquidity(_ int, rlm realm, params DecreaseLiquidityParams) (uint64, string, string, string, string, string, string, error) {
caller := params.caller
// before decrease liquidity, collect fee first
_, fee0Str, fee1Str, _, _, _ := p.collectFee(0, rlm, params.positionId, params.caller)
position := p.mustGetPosition(params.positionId)
positionLiquidity := u256.MustFromDecimal(position.Liquidity())
if positionLiquidity.IsZero() {
return params.positionId,
"",
fee0Str,
fee1Str,
"", "",
position.PoolKey(),
makeErrorWithDetails(
errZeroLiquidity,
ufmt.Sprintf("position(position ID:%d) has 0 liquidity", params.positionId),
)
}
liquidityToRemove := u256.MustFromDecimal(params.liquidity)
if liquidityToRemove.Gt(positionLiquidity) {
return params.positionId,
liquidityToRemove.ToString(),
fee0Str,
fee1Str,
"", "",
position.PoolKey(),
makeErrorWithDetails(
errInvalidLiquidity,
ufmt.Sprintf("Liquidity requested(%s) is greater than liquidity held(%s)", liquidityToRemove.ToString(), positionLiquidity.ToString()),
)
}
pToken0, pToken1, pFee := splitOf(position.PoolKey())
burn0, burn1 := pl.Burn(cross(rlm), pToken0, pToken1, pFee, position.TickLower(), position.TickUpper(), liquidityToRemove.ToString(), caller)
burnedAmount0 := utils.SafeParseInt64(burn0)
burnedAmount1 := utils.SafeParseInt64(burn1)
if burnedAmount0 < 0 || burnedAmount1 < 0 {
panic(errors.New(errUnderflow))
}
positionKey := computePositionKey(position.TickLower(), position.TickUpper())
feeGrowthInside0LastX128Str, feeGrowthInside1LastX128Str, err := pl.GetPositionFeeGrowthInsideLastX128(position.PoolKey(), positionKey)
if err != nil {
return 0, "", "", "", "", "", position.PoolKey(), err
}
// Add only burned amounts to tokensOwed since fees were already collected and processed in collectFee
tokensOwed0 := gnsmath.SafeAddInt64(position.TokensOwed0(), burnedAmount0)
tokensOwed1 := gnsmath.SafeAddInt64(position.TokensOwed1(), burnedAmount1)
newLiquidity, underflow := u256.Zero().SubOverflow(positionLiquidity, liquidityToRemove)
if underflow {
panic(newErrorWithDetail(errUnderflow, "positionLiquidity - liquidityToRemove underflow"))
}
position.SetTokensOwed0(tokensOwed0)
position.SetTokensOwed1(tokensOwed1)
position.SetFeeGrowthInside0LastX128(feeGrowthInside0LastX128Str)
position.SetFeeGrowthInside1LastX128(feeGrowthInside1LastX128Str)
position.SetLiquidity(newLiquidity.ToString())
p.mustUpdatePosition(0, rlm, params.positionId, *position)
collect0, collect1 := pl.Collect(
cross(rlm),
pToken0,
pToken1,
pFee,
caller,
position.TickLower(),
position.TickUpper(),
burn0,
burn1,
)
collectAmount0 := u256.MustFromDecimal(collect0)
collectAmount1 := u256.MustFromDecimal(collect1)
// Slippage check on actually collected amounts to ensure user receives minimum expected tokens
if isSlippageExceeded(collectAmount0, collectAmount1, params.amount0Min, params.amount1Min) {
return params.positionId,
liquidityToRemove.ToString(),
fee0Str,
fee1Str,
collect0,
collect1,
position.PoolKey(),
makeErrorWithDetails(
errSlippage,
ufmt.Sprintf("collectAmount0(%s) >= amount0Min(%s) && collectAmount1(%s) >= amount1Min(%s)",
collectAmount0.ToString(),
params.amount0Min.ToString(),
collectAmount1.ToString(),
params.amount1Min.ToString(),
),
)
}
// Check for underflow when subtracting collected amounts from tokens owed
collectAmount0Int64 := gnsmath.SafeConvertToInt64(collectAmount0)
collectAmount1Int64 := gnsmath.SafeConvertToInt64(collectAmount1)
if position.TokensOwed0() < collectAmount0Int64 {
panic(ufmt.Sprintf("[POSITION] burn.gno | collect() | tokensOwed0(%d) < collectAmount0(%d)", position.TokensOwed0(), collectAmount0Int64))
}
position.SetTokensOwed0(gnsmath.SafeSubInt64(position.TokensOwed0(), collectAmount0Int64))
if position.TokensOwed1() < collectAmount1Int64 {
panic(ufmt.Sprintf("[POSITION] burn.gno | collect() | tokensOwed1(%d) < collectAmount1(%d)", position.TokensOwed1(), collectAmount1Int64))
}
position.SetTokensOwed1(gnsmath.SafeSubInt64(position.TokensOwed1(), collectAmount1Int64))
if position.IsClear() {
position.SetBurned(true) // just update flag (we don't want to burn actual position)
}
p.mustUpdatePosition(0, rlm, params.positionId, *position)
return params.positionId, liquidityToRemove.ToString(), fee0Str, fee1Str, collect0, collect1, position.PoolKey(), nil
}
// calculateFees calculates the fees for the current position.
func (p *positionV1) calculateFees(position *position.Position, currentFeeGrowth FeeGrowthInside) (int64, int64) {
posLiquidity := u256.MustFromDecimal(position.Liquidity())
fee0 := calculateTokensOwed(
currentFeeGrowth.feeGrowthInside0LastX128,
u256.MustFromDecimal(position.FeeGrowthInside0LastX128()),
posLiquidity,
)
fee1 := calculateTokensOwed(
currentFeeGrowth.feeGrowthInside1LastX128,
u256.MustFromDecimal(position.FeeGrowthInside1LastX128()),
posLiquidity,
)
return gnsmath.SafeAddInt64(position.TokensOwed0(), gnsmath.SafeConvertToInt64(fee0)), gnsmath.SafeAddInt64(position.TokensOwed1(), gnsmath.SafeConvertToInt64(fee1))
}
func calculateTokensOwed(
feeGrowthInsideLastX128 *u256.Uint,
positionFeeGrowthInsideLastX128 *u256.Uint,
positionLiquidity *u256.Uint,
) *u256.Uint {
diff := u256.Zero().Sub(feeGrowthInsideLastX128, positionFeeGrowthInsideLastX128)
return u256.MulDiv(diff, positionLiquidity, consts.Q128())
}
doc.gno
// package v1 manages liquidity positions as NFTs in GnoSwap pools. // // Each position is represented as a GRC721 NFT with concentrated liquidity // within a specific tick range. Unstaked NFTs follow GRC721 owner/approval/ // operator transfer rules; staked NFTs are locked to staker-mediated transfers. // The package handles minting, liquidity adjustments, fee collection, and // repositioning. package position
errors.gno
package position
import (
ufmt "gno.land/p/nt/ufmt/v0"
)
const (
errNoPermission = "[GNOSWAP-POSITION-001] caller has no permission"
errSlippage = "[GNOSWAP-POSITION-002] slippage failed"
errInvalidTokenPath = "[GNOSWAP-POSITION-003] invalid token address"
errInvalidInput = "[GNOSWAP-POSITION-004] invalid input data"
errDataNotFound = "[GNOSWAP-POSITION-005] requested data not found"
errExpired = "[GNOSWAP-POSITION-006] transaction expired"
errInvalidLiquidity = "[GNOSWAP-POSITION-007] invalid liquidity"
errNotClear = "[GNOSWAP-POSITION-008] position is not clear"
errZeroLiquidity = "[GNOSWAP-POSITION-009] zero liquidity"
errPositionExist = "[GNOSWAP-POSITION-010] position with same positionId already exists"
errInvalidAddress = "[GNOSWAP-POSITION-011] invalid address"
errPositionDoesNotExist = "[GNOSWAP-POSITION-012] position does not exist"
errUnderflow = "[GNOSWAP-POSITION-013] underflow"
errOverflow = "[GNOSWAP-POSITION-014] overflow"
errCannotMintToStaker = "[GNOSWAP-POSITION-015] cannot mint to staker"
errSpoofedRealm = "[GNOSWAP-POSITION-016] rlm does not match the current crossing frame"
)
// newErrorWithDetail appends additional context or details to an existing error message.
func newErrorWithDetail(message string, detail string) string {
return ufmt.Errorf("%s || %s", message, detail).Error()
}
// makeErrorWithDetails creates an error with additional context.
func makeErrorWithDetails(message string, details string) error {
return ufmt.Errorf("%s || %s", message, details)
}
getter.gno
package position
import (
"errors"
"gno.land/p/gnoswap/consts/v1"
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"
"gno.land/r/gnoswap/position"
)
// getPosition returns a position for a given position ID.
// Returns an error if the position doesn't exist.
func (p *positionV1) getPosition(positionId uint64) (position.Position, error) {
pos, exists := p.store.GetPosition(positionId)
if !exists {
return pos, errors.New(newErrorWithDetail(
errPositionDoesNotExist,
ufmt.Sprintf("position with position ID(%d) doesn't exist", positionId),
))
}
return pos, nil
}
// mustGetPosition returns a position for a given position ID.
// panics if position doesn't exist
func (p *positionV1) mustGetPosition(positionId uint64) *position.Position {
position, err := p.getPosition(positionId)
if err != nil {
panic(err.Error())
}
return &position
}
// GetPositions returns a read-only view of every position, keyed by the decimal
// string form of the position ID.
//
// Returns:
// - positions: read-only tree exposing the position store without mutation methods
func (p *positionV1) GetPositions() *rotree.ReadOnlyTree {
// makeEntrySafeFn is a function that makes an entry safe to read.
// But Position is immutable, so we can just return the entry as is.
return rotree.Wrap(p.store.GetPositions(), nil)
}
// ExistPosition reports whether a position exists for a given position ID.
//
// Parameters:
// - positionId: numeric ID to test in the position store
//
// Returns:
// - exists: true when the position store contains positionId
func (p *positionV1) ExistPosition(positionId uint64) bool {
return p.store.HasPosition(positionId)
}
// IsBurned reports the empty-position marker stored for a position.
//
// Parameters:
// - positionId: numeric ID whose burned marker is requested
//
// Returns:
// - burned: true when the position is marked empty; the NFT record itself may still exist
// - err: nil on lookup success; errPositionDoesNotExist when the position is absent
func (p *positionV1) IsBurned(positionId uint64) (bool, error) {
position, err := p.getPosition(positionId)
if err != nil {
return false, err
}
return position.Burned(), nil
}
// IsInRange reports whether the pool's current tick is inside a position's range.
//
// Parameters:
// - positionId: numeric ID whose tick range and pool are inspected
//
// Returns:
// - inRange: true when tickLower <= current pool tick < tickUpper
// - err: nil on success; an error when the position or its pool tick cannot be read
func (p *positionV1) IsInRange(positionId uint64) (bool, error) {
position, err := p.getPosition(positionId)
if err != nil {
return false, err
}
poolPath := position.PoolKey()
poolCurrentTick, err := pl.GetSlot0Tick(poolPath)
if err != nil {
return false, err
}
return position.TickLower() <= poolCurrentTick && poolCurrentTick < position.TickUpper(), nil
}
// GetPositionOperator returns the address approved to operate on a position.
//
// Parameters:
// - positionId: numeric ID whose operator is requested
//
// Returns:
// - operator: approved operator address, or the empty address when none is set
// - err: nil on lookup success; errPositionDoesNotExist when the position is absent
func (p *positionV1) GetPositionOperator(positionId uint64) (address, error) {
position, err := p.getPosition(positionId)
if err != nil {
return address(""), err
}
return position.Operator(), nil
}
// GetPositionPoolKey returns the pool identifier stored on a position.
//
// Parameters:
// - positionId: numeric ID whose pool key is requested
//
// Returns:
// - poolKey: pool key encoding the position's token pair and fee tier
// - err: nil on lookup success; errPositionDoesNotExist when the position is absent
func (p *positionV1) GetPositionPoolKey(positionId uint64) (string, error) {
position, err := p.getPosition(positionId)
if err != nil {
return "", err
}
return position.PoolKey(), nil
}
// GetPositionTickLower returns the lower tick boundary stored on a position.
//
// Parameters:
// - positionId: numeric ID whose lower tick is requested
//
// Returns:
// - tickLower: lower tick boundary, inclusive in range checks
// - err: nil on lookup success; errPositionDoesNotExist when the position is absent
func (p *positionV1) GetPositionTickLower(positionId uint64) (int32, error) {
position, err := p.getPosition(positionId)
if err != nil {
return 0, err
}
return position.TickLower(), nil
}
// GetPositionTickUpper returns the upper tick boundary stored on a position.
//
// Parameters:
// - positionId: numeric ID whose upper tick is requested
//
// Returns:
// - tickUpper: upper tick boundary, exclusive in range checks
// - err: nil on lookup success; errPositionDoesNotExist when the position is absent
func (p *positionV1) GetPositionTickUpper(positionId uint64) (int32, error) {
position, err := p.getPosition(positionId)
if err != nil {
return 0, err
}
return position.TickUpper(), nil
}
// GetPositionLiquidity returns the decimal-encoded liquidity stored on a position.
//
// Parameters:
// - positionId: numeric ID whose liquidity is requested
//
// Returns:
// - liquidity: decimal string representing the position's current liquidity
// - err: nil on lookup success; errPositionDoesNotExist when the position is absent
func (p *positionV1) GetPositionLiquidity(positionId uint64) (string, error) {
position, err := p.getPosition(positionId)
if err != nil {
return "", err
}
return position.Liquidity(), nil
}
// GetPositionTokenBalances returns balances derived from current pool price,
// position range, and liquidity; token balances are not stored snapshots.
//
// Parameters:
// - positionId: numeric ID whose current token balances are calculated
//
// Returns:
// - token0Balance: current token0 amount represented by the position's liquidity and range
// - token1Balance: current token1 amount represented by the position's liquidity and range
// - err: nil when the position exists; errPositionDoesNotExist when it is absent (pool price lookup failures panic during calculation)
func (p *positionV1) GetPositionTokenBalances(positionId uint64) (int64, int64, error) {
position, err := p.getPosition(positionId)
if err != nil {
return 0, 0, err
}
balance0, balance1 := calculatePositionBalances(&position)
return balance0, balance1, nil
}
// GetPositionFeeGrowthInside0LastX128 returns the token0 fee-growth checkpoint
// stored on a position.
//
// Parameters:
// - positionId: numeric ID whose token0 fee-growth checkpoint is requested
//
// Returns:
// - feeGrowthInside0LastX128: decimal-encoded Q128 token0 fee growth inside the position's range at its last update
// - err: nil on lookup success; errPositionDoesNotExist when the position is absent
func (p *positionV1) GetPositionFeeGrowthInside0LastX128(positionId uint64) (string, error) {
position, err := p.getPosition(positionId)
if err != nil {
return "", err
}
return position.FeeGrowthInside0LastX128(), nil
}
// GetPositionFeeGrowthInside1LastX128 returns the token1 fee-growth checkpoint
// stored on a position.
//
// Parameters:
// - positionId: numeric ID whose token1 fee-growth checkpoint is requested
//
// Returns:
// - feeGrowthInside1LastX128: decimal-encoded Q128 token1 fee growth inside the position's range at its last update
// - err: nil on lookup success; errPositionDoesNotExist when the position is absent
func (p *positionV1) GetPositionFeeGrowthInside1LastX128(positionId uint64) (string, error) {
position, err := p.getPosition(positionId)
if err != nil {
return "", err
}
return position.FeeGrowthInside1LastX128(), nil
}
// GetPositionFeeGrowthInsideLastX128 returns both fee-growth checkpoints stored
// on a position, in token0 then token1 order.
//
// Parameters:
// - positionId: numeric ID whose fee-growth checkpoints are requested
//
// Returns:
// - feeGrowthInside0LastX128: decimal-encoded Q128 token0 fee growth checkpoint
// - feeGrowthInside1LastX128: decimal-encoded Q128 token1 fee growth checkpoint
// - err: nil on lookup success; errPositionDoesNotExist when the position is absent
func (p *positionV1) GetPositionFeeGrowthInsideLastX128(positionId uint64) (string, string, error) {
position, err := p.getPosition(positionId)
if err != nil {
return "", "", err
}
return position.FeeGrowthInside0LastX128(), position.FeeGrowthInside1LastX128(), nil
}
// GetPositionTicks returns both tick boundaries stored on a position.
//
// Parameters:
// - positionId: numeric ID whose tick boundaries are requested
//
// Returns:
// - tickLower: lower tick boundary, inclusive in range checks
// - tickUpper: upper tick boundary, exclusive in range checks
// - err: nil on lookup success; errPositionDoesNotExist when the position is absent
func (p *positionV1) GetPositionTicks(positionId uint64) (int32, int32, error) {
position, err := p.getPosition(positionId)
if err != nil {
return 0, 0, err
}
return position.TickLower(), position.TickUpper(), nil
}
// GetPositionTokensOwed0 returns the stored token0 amount owed to a position.
//
// Parameters:
// - positionId: numeric ID whose token0 owed amount is requested
//
// Returns:
// - tokensOwed0: accrued token0 amount awaiting collection, in token units
// - err: nil on lookup success; errPositionDoesNotExist when the position is absent
func (p *positionV1) GetPositionTokensOwed0(positionId uint64) (int64, error) {
position, err := p.getPosition(positionId)
if err != nil {
return 0, err
}
return position.TokensOwed0(), nil
}
// GetPositionTokensOwed1 returns the stored token1 amount owed to a position.
//
// Parameters:
// - positionId: numeric ID whose token1 owed amount is requested
//
// Returns:
// - tokensOwed1: accrued token1 amount awaiting collection, in token units
// - err: nil on lookup success; errPositionDoesNotExist when the position is absent
func (p *positionV1) GetPositionTokensOwed1(positionId uint64) (int64, error) {
position, err := p.getPosition(positionId)
if err != nil {
return 0, err
}
return position.TokensOwed1(), nil
}
// GetPositionTokensOwed returns both stored token amounts owed to a position,
// in token0 then token1 order.
//
// Parameters:
// - positionId: numeric ID whose owed amounts are requested
//
// Returns:
// - tokensOwed0: accrued token0 amount awaiting collection, in token units
// - tokensOwed1: accrued token1 amount awaiting collection, in token units
// - err: nil on lookup success; errPositionDoesNotExist when the position is absent
func (p *positionV1) GetPositionTokensOwed(positionId uint64) (int64, int64, error) {
position, err := p.getPosition(positionId)
if err != nil {
return 0, 0, err
}
return position.TokensOwed0(), position.TokensOwed1(), nil
}
// GetPositionOwner returns the address that owns the position NFT.
//
// Parameters:
// - positionId: numeric ID whose NFT ownership is requested
//
// Returns:
// - owner: current owner address reported by the NFT accessor
// - err: nil when the NFT accessor finds the token; otherwise its ownership lookup error
func (p *positionV1) GetPositionOwner(positionId uint64) (address, error) {
owner, err := p.nftAccessor.OwnerOf(positionIdFrom(positionId))
if err != nil {
return address(""), err
}
return owner, nil
}
// GetUnclaimedFee calculates unclaimed token fees from current in-range
// fee growth, the position's checkpoints, and its liquidity.
//
// Parameters:
// - positionId: numeric ID whose unclaimed token fees are calculated
//
// Returns:
// - unclaimedFee0: token0 fees accrued since the stored checkpoint, scaled by position liquidity
// - unclaimedFee1: token1 fees accrued since the stored checkpoint, scaled by position liquidity
// - err: nil on success; nil fee pointers and the underlying lookup error when position or pool data is unavailable
func (p *positionV1) GetUnclaimedFee(positionId uint64) (*u256.Uint, *u256.Uint, error) {
// ref: https://blog.uniswap.org/uniswap-v3-math-primer-2#calculating-uncollected-fees
position, err := p.getPosition(positionId)
if err != nil {
return nil, nil, err
}
liquidity := u256.MustFromDecimal(position.Liquidity())
tickLower := position.TickLower()
tickUpper := position.TickUpper()
poolKey := position.PoolKey()
currentTick, err := pl.GetSlot0Tick(poolKey)
if err != nil {
return nil, nil, err
}
feeGrowthGlobal0X128Str, feeGrowthGlobal1X128Str, err := pl.GetFeeGrowthGlobalX128(poolKey)
if err != nil {
return nil, nil, err
}
feeGrowthGlobal0X128 := u256.MustFromDecimal(feeGrowthGlobal0X128Str)
feeGrowthGlobal1X128 := u256.MustFromDecimal(feeGrowthGlobal1X128Str)
tickUpperFeeGrowthOutside0X128Str, tickUpperFeeGrowthOutside1X128Str, err := pl.GetTickFeeGrowthOutsideX128(poolKey, tickUpper)
if err != nil {
return nil, nil, err
}
tickUpperFeeGrowthOutside0X128 := u256.MustFromDecimal(tickUpperFeeGrowthOutside0X128Str)
tickUpperFeeGrowthOutside1X128 := u256.MustFromDecimal(tickUpperFeeGrowthOutside1X128Str)
tickLowerFeeGrowthOutside0X128Str, tickLowerFeeGrowthOutside1X128Str, err := pl.GetTickFeeGrowthOutsideX128(poolKey, tickLower)
if err != nil {
return nil, nil, err
}
tickLowerFeeGrowthOutside0X128 := u256.MustFromDecimal(tickLowerFeeGrowthOutside0X128Str)
tickLowerFeeGrowthOutside1X128 := u256.MustFromDecimal(tickLowerFeeGrowthOutside1X128Str)
feeGrowthInside0LastX128 := u256.MustFromDecimal(position.FeeGrowthInside0LastX128())
feeGrowthInside1LastX128 := u256.MustFromDecimal(position.FeeGrowthInside1LastX128())
var tickLowerFeeGrowthBelow0, tickLowerFeeGrowthBelow1, tickUpperFeeGrowthAbove0, tickUpperFeeGrowthAbove1 *u256.Uint
if currentTick >= tickUpper {
tickUpperFeeGrowthAbove0 = u256.Zero().Sub(feeGrowthGlobal0X128, tickUpperFeeGrowthOutside0X128)
tickUpperFeeGrowthAbove1 = u256.Zero().Sub(feeGrowthGlobal1X128, tickUpperFeeGrowthOutside1X128)
} else {
tickUpperFeeGrowthAbove0 = tickUpperFeeGrowthOutside0X128
tickUpperFeeGrowthAbove1 = tickUpperFeeGrowthOutside1X128
}
if currentTick >= tickLower {
tickLowerFeeGrowthBelow0 = tickLowerFeeGrowthOutside0X128
tickLowerFeeGrowthBelow1 = tickLowerFeeGrowthOutside1X128
} else {
tickLowerFeeGrowthBelow0 = u256.Zero().Sub(feeGrowthGlobal0X128, tickLowerFeeGrowthOutside0X128)
tickLowerFeeGrowthBelow1 = u256.Zero().Sub(feeGrowthGlobal1X128, tickLowerFeeGrowthOutside1X128)
}
feeGrowthInside0X128 := u256.Zero().Sub(feeGrowthGlobal0X128, tickLowerFeeGrowthBelow0)
feeGrowthInside0X128 = u256.Zero().Sub(feeGrowthInside0X128, tickUpperFeeGrowthAbove0)
feeGrowthInside1X128 := u256.Zero().Sub(feeGrowthGlobal1X128, tickLowerFeeGrowthBelow1)
feeGrowthInside1X128 = u256.Zero().Sub(feeGrowthInside1X128, tickUpperFeeGrowthAbove1)
diffGrowthInside0X128 := u256.Zero().Sub(feeGrowthInside0X128, feeGrowthInside0LastX128)
unclaimedFee0 := u256.MulDiv(diffGrowthInside0X128, liquidity, consts.Q128())
diffGrowthInside1X128 := u256.Zero().Sub(feeGrowthInside1X128, feeGrowthInside1LastX128)
unclaimedFee1 := u256.MulDiv(diffGrowthInside1X128, liquidity, consts.Q128())
return unclaimedFee0, unclaimedFee1, nil
}
gnomod.toml
module = "gno.land/r/gnoswap/position/v1" gno = "0.9" [addpkg] creator = "g1q5tjjv3kkslzwf2na9y9wk7e5a8ugph8xfsk04" height = 77266 max_deposit = "100000000ugnot"
init.gno
package position
import (
"gno.land/r/gnoswap/access/v1"
"gno.land/r/gnoswap/position"
)
func init(cur realm) {
registerPositionV1(cur)
}
func registerPositionV1(cur realm) {
position.RegisterInitializer(
cross(cur),
func(_ int, rlm realm, positionStore position.IPositionStore) position.IPosition {
access.AssertIsRlmCurrent(0, rlm)
err := initStoreData(0, rlm, positionStore)
if err != nil {
panic(err)
}
return NewPositionV1(positionStore, newGNFTAccessor())
},
)
}
func initStoreData(_ int, rlm realm, positionStore position.IPositionStore) error {
if !positionStore.HasPositionNextIDStoreKey() {
err := positionStore.SetPositionNextID(0, rlm, uint64(1))
if err != nil {
return err
}
}
if !positionStore.HasPositionsStoreKey() {
err := positionStore.SetPositions(0, rlm, position.NewPositionsTree())
if err != nil {
return err
}
}
return nil
}
instance.gno
package position
import (
"errors"
"gno.land/p/nt/grc721/v0"
"gno.land/r/gnoswap/access/v1"
"gno.land/r/gnoswap/gnft"
"gno.land/r/gnoswap/position"
)
type positionV1 struct {
store position.IPositionStore
nftAccessor NFTAccessor
}
// NewPositionV1 constructs a position implementation backed by the supplied
// position store and NFT accessor.
//
// Parameters:
// - positionStore: storage interface used to read and update position records
// - accessor: NFT interface used for position token minting, burning, approval, and ownership
//
// Returns:
// - position: IPosition implementation connected to positionStore and accessor
func NewPositionV1(positionStore position.IPositionStore, accessor NFTAccessor) position.IPosition {
return &positionV1{
store: positionStore,
nftAccessor: accessor,
}
}
type NFTAccessor interface {
// Approve forwards an operator approval for a position NFT.
//
// Parameters:
// - _: leading realm-call discriminator for the forwarded NFT operation; callers pass 0
// - rlm: propagated realm context validated by the concrete accessor before crossing into the NFT realm
// - approved: address to approve for the specified position NFT; the empty address revokes approval
// - tid: position NFT token ID whose operator approval is changed
//
// Returns:
// - err: nil when approval succeeds; otherwise the NFT accessor or realm-validation error
Approve(_ int, rlm realm, approved address, tid grc721.TokenID) error
// Mint creates a position NFT for an address and token ID.
//
// Parameters:
// - _: leading realm-call discriminator for the forwarded NFT operation; callers pass 0
// - rlm: propagated realm context used to cross into the NFT realm
// - to: address that receives the newly minted position NFT
// - tid: requested position NFT token ID
//
// Returns:
// - mintedTid: token ID returned by the NFT realm after minting
Mint(_ int, rlm realm, to address, tid grc721.TokenID) grc721.TokenID
// Burn removes a position NFT from the NFT ledger.
//
// Parameters:
// - _: leading realm-call discriminator for the forwarded NFT operation; callers pass 0
// - rlm: propagated realm context used to cross into the NFT realm
// - tid: position NFT token ID to burn
Burn(_ int, rlm realm, tid grc721.TokenID)
// TotalSupply returns the number of NFTs currently recorded by the ledger.
//
// Returns:
// - totalSupply: current number of position NFTs in the ledger
TotalSupply() int64
// Exists reports whether the NFT ledger contains a token ID.
//
// Parameters:
// - tid: position NFT token ID to test
//
// Returns:
// - exists: true when the NFT ledger contains tid
Exists(tid grc721.TokenID) bool
// OwnerOf returns the current owner of a position NFT.
//
// Parameters:
// - tid: position NFT token ID whose owner is requested
//
// Returns:
// - owner: address recorded as the token owner
// - err: nil when the token exists; otherwise the NFT ledger's ownership lookup error
OwnerOf(tid grc721.TokenID) (address, error)
}
type gnftAccessor struct{}
// Approve forwards an operator approval to the GNFT realm.
//
// Parameters:
// - _: leading realm-call discriminator for the forwarded NFT operation; callers pass 0
// - rlm: propagated realm context that must be current before crossing into GNFT
// - approved: address to approve for the specified position NFT; the empty address revokes approval
// - tid: position NFT token ID whose operator approval is changed
//
// Returns:
// - err: nil when GNFT accepts the approval; errSpoofedRealm when rlm is not current, otherwise the underlying GNFT error
func (n *gnftAccessor) Approve(_ int, rlm realm, approved address, tid grc721.TokenID) error {
if !rlm.IsCurrent() {
return errors.New(errSpoofedRealm)
}
return gnft.Approve(cross(rlm), approved, tid)
}
// Mint forwards position NFT creation to the GNFT realm.
//
// Parameters:
// - _: leading realm-call discriminator for the forwarded NFT operation; callers pass 0
// - rlm: propagated realm context asserted current before crossing into GNFT
// - to: address that receives the newly minted position NFT
// - tid: requested position NFT token ID
//
// Returns:
// - mintedTid: token ID returned by GNFT after minting
func (n *gnftAccessor) Mint(_ int, rlm realm, to address, tid grc721.TokenID) grc721.TokenID {
access.AssertIsRlmCurrent(0, rlm)
return gnft.Mint(cross(rlm), to, tid)
}
// Burn forwards position NFT destruction to the GNFT realm.
//
// Parameters:
// - _: leading realm-call discriminator for the forwarded NFT operation; callers pass 0
// - rlm: propagated realm context asserted current before crossing into GNFT
// - tid: position NFT token ID to burn
func (n *gnftAccessor) Burn(_ int, rlm realm, tid grc721.TokenID) {
access.AssertIsRlmCurrent(0, rlm)
gnft.Burn(cross(rlm), tid)
}
// TotalSupply returns the GNFT ledger's current token count.
//
// Returns:
// - totalSupply: number of NFTs currently recorded by GNFT
func (n *gnftAccessor) TotalSupply() int64 {
return gnft.TotalSupply()
}
// Exists reports whether GNFT contains a position NFT token ID.
//
// Parameters:
// - tid: position NFT token ID to test
//
// Returns:
// - exists: true when GNFT contains tid
func (n *gnftAccessor) Exists(tid grc721.TokenID) bool {
return gnft.Exists(tid)
}
// OwnerOf returns the owner recorded by GNFT for a position NFT.
//
// Parameters:
// - tid: position NFT token ID whose owner is requested
//
// Returns:
// - owner: address recorded as the token owner
// - err: nil when GNFT finds the token; otherwise GNFT's ownership lookup error
func (n *gnftAccessor) OwnerOf(tid grc721.TokenID) (address, error) {
return gnft.OwnerOf(tid)
}
func newGNFTAccessor() NFTAccessor {
return &gnftAccessor{}
}
liquidity_management.gno
package position
import (
"gno.land/p/gnoswap/gnsmath/v1"
u256 "gno.land/p/gnoswap/uint256/v1"
ufmt "gno.land/p/nt/ufmt/v0"
pl "gno.land/r/gnoswap/pool"
)
type AddLiquidityParams struct {
poolKey string // poolPath of the pool which has the position
tickLower int32 // lower end of the tick range for the position
tickUpper int32 // upper end of the tick range for the position
amount0Desired *u256.Uint // desired amount of token0 to be minted
amount1Desired *u256.Uint // desired amount of token1 to be minted
amount0Min *u256.Uint // minimum amount of token0 to be minted
amount1Min *u256.Uint // minimum amount of token1 to be minted
caller address // address to call the function
}
// addLiquidity calculates liquidity amounts and mints position tokens to a pool.
func (p *positionV1) addLiquidity(_ int, rlm realm, params AddLiquidityParams) (*u256.Uint, *u256.Uint, *u256.Uint) {
sqrtPriceX96String, err := pl.GetSlot0SqrtPriceX96(params.poolKey)
if err != nil {
panic(err)
}
sqrtPriceX96 := u256.MustFromDecimal(sqrtPriceX96String)
sqrtRatioAX96 := gnsmath.TickMathGetSqrtRatioAtTick(params.tickLower)
sqrtRatioBX96 := gnsmath.TickMathGetSqrtRatioAtTick(params.tickUpper)
liquidity := gnsmath.GetLiquidityForAmounts(
sqrtPriceX96,
sqrtRatioAX96,
sqrtRatioBX96,
params.amount0Desired,
params.amount1Desired,
)
token0, token1, fee := splitOf(params.poolKey)
amount0Str, amount1Str := pl.Mint(
cross(rlm),
token0,
token1,
fee,
params.tickLower,
params.tickUpper,
liquidity.ToString(),
params.caller,
)
amount0 := u256.MustFromDecimal(amount0Str)
amount1 := u256.MustFromDecimal(amount1Str)
amount0Cond := amount0.Gte(params.amount0Min)
amount1Cond := amount1.Gte(params.amount1Min)
if !(amount0Cond && amount1Cond) {
panic(newErrorWithDetail(
errSlippage,
ufmt.Sprintf(
"Price Slippage Check(amount0(%s) >= amount0Min(%s), amount1(%s) >= amount1Min(%s))",
amount0Str, params.amount0Min.ToString(), amount1Str, params.amount1Min.ToString()),
))
}
return liquidity, amount0, amount1
}
manager.gno
package position
import (
"gno.land/r/gnoswap/position"
)
// GetNextId is the next position ID to be minted
func (p *positionV1) getNextId() uint64 {
return p.store.GetPositionNextID()
}
// incrementNextId increments the next position ID to be minted
func (p *positionV1) incrementNextId(_ int, rlm realm) error {
return p.store.SetPositionNextID(0, rlm, p.getNextId()+1)
}
// setPosition sets a position for a given position ID.
// Returns false if position is newly created, true if position already existed and was updated.
func (p *positionV1) setPosition(_ int, rlm realm, id uint64, pos position.Position) error {
return p.store.SetPosition(0, rlm, id, pos)
}
// mustUpdatePosition updates a position for a given position ID.
func (p *positionV1) mustUpdatePosition(_ int, rlm realm, id uint64, pos position.Position) {
err := p.setPosition(0, rlm, id, pos)
if err != nil {
panic(err)
}
}
mint.gno
package position
import (
"errors"
u256 "gno.land/p/gnoswap/uint256/v1"
ufmt "gno.land/p/nt/ufmt/v0"
"gno.land/r/gnoswap/common"
pl "gno.land/r/gnoswap/pool"
"gno.land/r/gnoswap/position"
)
// mint creates a new liquidity position by adding liquidity to a pool and minting an NFT.
// Panics if position ID already exists or adding liquidity fails.
func (p *positionV1) mint(_ int, rlm realm, params MintParams) (uint64, *u256.Uint, *u256.Uint, *u256.Uint) {
poolKey := pl.GetPoolPath(params.token0, params.token1, params.fee)
liquidity, amount0, amount1 := p.addLiquidity(
0,
rlm,
AddLiquidityParams{
poolKey: poolKey,
tickLower: params.tickLower,
tickUpper: params.tickUpper,
amount0Desired: params.amount0Desired,
amount1Desired: params.amount1Desired,
amount0Min: params.amount0Min,
amount1Min: params.amount1Min,
caller: params.caller,
},
)
// Ensure liquidity is not zero before minting NFT
if liquidity.IsZero() {
panic(newErrorWithDetail(
errZeroLiquidity,
"Liquidity is zero, cannot mint position.",
))
}
id := p.getNextId()
if p.ExistPosition(id) {
panic(newErrorWithDetail(
errPositionExist,
ufmt.Sprintf("positionId(%d)", id),
))
}
p.nftAccessor.Mint(0, rlm, params.mintTo, positionIdFrom(id))
positionKey := computePositionKey(params.tickLower, params.tickUpper)
feeGrowthInside0LastX128, feeGrowthInside1LastX128, err := pl.GetPositionFeeGrowthInsideLastX128(poolKey, positionKey)
if err != nil {
panic(err)
}
position := position.NewPosition(
poolKey,
params.tickLower,
params.tickUpper,
liquidity.ToString(),
feeGrowthInside0LastX128,
feeGrowthInside1LastX128,
0,
0,
false,
zeroAddress,
)
// The position ID should not exist at the time of minting
p.mustUpdatePosition(0, rlm, id, *position)
p.incrementNextId(0, rlm)
return id, liquidity, amount0, amount1
}
// processMintInput processes and validates user input for minting liquidity.
// It handles token ordering and amount validation.
func (p *positionV1) processMintInput(input MintInput) (ProcessedMintInput, error) {
token0, token1 := input.token0, input.token1
if err := validateTokenPath(token0, token1); err != nil {
return ProcessedMintInput{}, makeErrorWithDetails(err.Error(), ufmt.Sprintf("token0(%s), token1(%s)", token0, token1))
}
pair := TokenPair{
token0: token0,
token1: token1,
}
// parse amounts
amount0Desired, amount1Desired, amount0Min, amount1Min := parseAmounts(input.amount0Desired, input.amount1Desired, input.amount0Min, input.amount1Min)
tickLower, tickUpper := input.tickLower, input.tickUpper
// swap if token1 < token0
if token1 < token0 {
pair.token0, pair.token1 = pair.token1, pair.token0
amount0Desired, amount1Desired = amount1Desired, amount0Desired
amount0Min, amount1Min = amount1Min, amount0Min
tickLower, tickUpper = -tickUpper, -tickLower
}
return ProcessedMintInput{
tokenPair: pair,
amount0Desired: amount0Desired,
amount1Desired: amount1Desired,
amount0Min: amount0Min,
amount1Min: amount1Min,
tickLower: tickLower,
tickUpper: tickUpper,
poolPath: pl.GetPoolPath(pair.token0, pair.token1, input.fee),
}, nil
}
// increaseLiquidity increases the liquidity of an existing position.
func (p *positionV1) increaseLiquidity(_ int, rlm realm, params IncreaseLiquidityParams) (uint64, *u256.Uint, *u256.Uint, *u256.Uint, string, error) {
caller := params.caller
position := p.mustGetPosition(params.positionId)
liquidity, amount0, amount1 := p.addLiquidity(
0,
rlm,
AddLiquidityParams{
poolKey: position.PoolKey(),
tickLower: position.TickLower(),
tickUpper: position.TickUpper(),
amount0Desired: params.amount0Desired,
amount1Desired: params.amount1Desired,
amount0Min: params.amount0Min,
amount1Min: params.amount1Min,
caller: caller,
},
)
positionKey := computePositionKey(position.TickLower(), position.TickUpper())
feeGrowthInside0LastX128Str, feeGrowthInside1LastX128Str, err := pl.GetPositionFeeGrowthInsideLastX128(position.PoolKey(), positionKey)
if err != nil {
return 0, nil, nil, nil, "", err
}
feeGrowth := FeeGrowthInside{
feeGrowthInside0LastX128: u256.MustFromDecimal(feeGrowthInside0LastX128Str),
feeGrowthInside1LastX128: u256.MustFromDecimal(feeGrowthInside1LastX128Str),
}
tokensOwed0, tokensOwed1 := p.calculateFees(position, feeGrowth)
posLiquidity := u256.MustFromDecimal(position.Liquidity())
liquidityAmount, overflow := u256.Zero().AddOverflow(posLiquidity, liquidity)
if overflow {
return 0, nil, nil, nil, "", errors.New(errOverflow)
}
position.SetTokensOwed0(tokensOwed0)
position.SetTokensOwed1(tokensOwed1)
position.SetFeeGrowthInside0LastX128(feeGrowthInside0LastX128Str)
position.SetFeeGrowthInside1LastX128(feeGrowthInside1LastX128Str)
position.SetLiquidity(liquidityAmount.ToString())
position.SetBurned(false)
err = p.setPosition(0, rlm, params.positionId, *position)
if err != nil {
return 0, nil, nil, nil, "", makeErrorWithDetails(
errPositionDoesNotExist,
ufmt.Sprintf("cannot increase liquidity for non-existent position(%d)", params.positionId),
)
}
return params.positionId, liquidity, amount0, amount1, position.PoolKey(), nil
}
// validateTokenPath validates token paths are not identical, not conflicting, and in valid format.
func validateTokenPath(token0, token1 string) error {
if token0 == token1 {
return errors.New(errInvalidTokenPath)
}
if !isValidTokenPath(token0) || !isValidTokenPath(token1) {
return errors.New(errInvalidTokenPath)
}
return nil
}
// isValidTokenPath checks if the token path is registered in the system.
func isValidTokenPath(tokenPath string) bool {
return common.IsRegistered(tokenPath) == nil
}
// parseAmounts converts amount strings to u256.Uint values.
func parseAmounts(amount0Desired, amount1Desired, amount0Min, amount1Min string) (*u256.Uint, *u256.Uint, *u256.Uint, *u256.Uint) {
return u256.MustFromDecimal(amount0Desired), u256.MustFromDecimal(amount1Desired), u256.MustFromDecimal(amount0Min), u256.MustFromDecimal(amount1Min)
}
position.gno
package position
import (
"chain"
"gno.land/p/gnoswap/gnsmath/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/emission"
"gno.land/r/gnoswap/halt/v1"
pl "gno.land/r/gnoswap/pool"
pos "gno.land/r/gnoswap/position"
"gno.land/r/gnoswap/referral/v1"
"gno.land/r/gnoswap/staker"
)
// Mint creates a new liquidity position NFT.
//
// Parameters:
// - _: Noncrossing implementation-call discriminator; pass 0.
// - rlm: Current realm context forwarded unchanged by the position proxy.
// - token0: token0 contract path for the pool
// - token1: token1 contract path for the pool
// - fee: pool fee tier used to select the pool
// - tickLower: lower tick boundary of the position's range
// - tickUpper: upper tick boundary of the position's range
// - amount0Desired: desired token0 amount, supplied as a decimal string
// - amount1Desired: desired token1 amount, supplied as a decimal string
// - amount0Min: minimum acceptable token0 amount for slippage protection
// - amount1Min: minimum acceptable token1 amount for slippage protection
// - deadline: Unix timestamp after which the transaction is rejected
// - mintTo: address that receives the newly minted position NFT
// - referrer: referral value submitted for registration with the caller
//
// Returns:
// - positionId: newly minted position NFT ID
// - liquidity: liquidity amount minted for the position
// - amount0: token0 amount actually deposited into the pool
// - amount1: token1 amount actually deposited into the pool
//
// Note: Slippage protection via amount0Min/amount1Min.
func (p *positionV1) Mint(
_ int,
rlm realm,
token0 string,
token1 string,
fee uint32,
tickLower int32,
tickUpper int32,
amount0Desired string,
amount1Desired string,
amount0Min string,
amount1Min string,
deadline int64,
mintTo address,
referrer string,
) (uint64, string, string, string) {
access.AssertIsRlmCurrent(0, rlm)
halt.AssertIsNotHaltedPosition()
access.AssertIsValidAddress(mintTo)
previousRealm := rlm.Previous()
caller := previousRealm.Address()
assertIsNotMintToStaker(mintTo)
assertValidNumberString(amount0Desired)
assertValidNumberString(amount1Desired)
assertValidNumberString(amount0Min)
assertValidNumberString(amount1Min)
// assert that the user has sent the correct amount of native coin
common.AssertIsNotHandleNativeCoin()
assertIsNotExpired(deadline)
actualReferrer := referral.TryRegister(cross(rlm), caller, referrer)
emission.MintAndDistributeGns(cross(rlm))
mintInput := MintInput{
token0: token0,
token1: token1,
fee: fee,
tickLower: tickLower,
tickUpper: tickUpper,
amount0Desired: amount0Desired,
amount1Desired: amount1Desired,
amount0Min: amount0Min,
amount1Min: amount1Min,
deadline: deadline,
mintTo: mintTo,
caller: caller,
}
processedInput, err := p.processMintInput(mintInput)
if err != nil {
panic(newErrorWithDetail(errInvalidInput, err.Error()))
}
// mint liquidity
params := newMintParams(processedInput, mintInput)
id, liquidity, amount0, amount1 := p.mint(0, rlm, params)
pool := mustGetPool(processedInput.poolPath)
positionLiquidity, err := p.GetPositionLiquidity(id)
if err != nil {
panic(err)
}
tickCumulative, secondsPerLiquidityCumulativeX128, observationTimestamp, err := currentPoolObservation(processedInput.poolPath)
if err != nil {
panic(err)
}
chain.Emit(
"Mint",
"prevAddr", caller.String(),
"prevRealm", previousRealm.PkgPath(),
"tickLower", utils.FormatInt(processedInput.tickLower),
"tickUpper", utils.FormatInt(processedInput.tickUpper),
"poolPath", processedInput.poolPath,
"mintTo", mintTo.String(),
"caller", caller.String(),
"lpPositionId", utils.FormatUint(id),
"liquidityDelta", liquidity.ToString(),
"amount0", amount0.ToString(),
"amount1", amount1.ToString(),
"sqrtPriceX96", pool.Slot0SqrtPriceX96().ToString(),
"positionLiquidity", positionLiquidity,
"poolLiquidity", pool.Liquidity().ToString(),
"token0Balance", utils.FormatInt(pool.BalanceToken0()),
"token1Balance", utils.FormatInt(pool.BalanceToken1()),
"tickCumulative", utils.FormatInt(tickCumulative),
"secondsPerLiquidityCumulativeX128", secondsPerLiquidityCumulativeX128,
"observationTimestamp", utils.FormatInt(observationTimestamp),
"referrer", actualReferrer,
)
return id, liquidity.ToString(), amount0.ToString(), amount1.ToString()
}
// IncreaseLiquidity increases liquidity of an existing position.
//
// Adds more liquidity to existing NFT position.
// Maintains same price range as original position.
// Calculates optimal token ratio for current price.
//
// Parameters:
// - _: Noncrossing implementation-call discriminator; pass 0.
// - rlm: Current realm context forwarded unchanged by the position proxy.
// - positionId: NFT token ID to increase
// - amount0DesiredStr: desired token0 amount, supplied as a decimal string
// - amount1DesiredStr: desired token1 amount, supplied as a decimal string
// - amount0MinStr: minimum acceptable token0 amount for slippage protection
// - amount1MinStr: minimum acceptable token1 amount for slippage protection
// - deadline: Unix timestamp after which the transaction is rejected
//
// Returns:
// - positionId: same NFT ID
// - liquidity: liquidity amount added (the delta, not total)
// - amount0: token0 amount actually deposited
// - amount1: token1 amount actually deposited
// - poolPath: pool identifier for the position
//
// Requirements:
// - Caller must own the position NFT
// - Sufficient token balances and approvals
func (p *positionV1) IncreaseLiquidity(
_ int,
rlm realm,
positionId uint64,
amount0DesiredStr string,
amount1DesiredStr string,
amount0MinStr string,
amount1MinStr string,
deadline int64,
) (uint64, string, string, string, string) {
access.AssertIsRlmCurrent(0, rlm)
halt.AssertIsNotHaltedPosition()
previousRealm := rlm.Previous()
caller := previousRealm.Address()
assertIsOwnerForToken(p, positionId, caller)
assertValidNumberString(amount0DesiredStr)
assertValidNumberString(amount1DesiredStr)
assertValidNumberString(amount0MinStr)
assertValidNumberString(amount1MinStr)
assertIsNotExpired(deadline)
emission.MintAndDistributeGns(cross(rlm))
position := p.mustGetPosition(positionId)
token0, token1, _ := splitOf(position.PoolKey())
common.AssertIsNotHandleNativeCoin()
err := validateTokenPath(token0, token1)
if err != nil {
panic(newErrorWithDetail(err.Error(), ufmt.Sprintf("token0(%s), token1(%s)", token0, token1)))
}
amount0Desired, amount1Desired, amount0Min, amount1Min := parseAmounts(amount0DesiredStr, amount1DesiredStr, amount0MinStr, amount1MinStr)
increaseLiquidityParams := IncreaseLiquidityParams{
positionId: positionId,
amount0Desired: amount0Desired,
amount1Desired: amount1Desired,
amount0Min: amount0Min,
amount1Min: amount1Min,
deadline: deadline,
caller: caller,
}
_, liquidity, amount0, amount1, poolPath, err := p.increaseLiquidity(0, rlm, increaseLiquidityParams)
if err != nil {
panic(err)
}
pool := mustGetPool(poolPath)
positionLiquidity, err := p.GetPositionLiquidity(positionId)
if err != nil {
panic(err)
}
tickCumulative, secondsPerLiquidityCumulativeX128, observationTimestamp, err := currentPoolObservation(poolPath)
if err != nil {
panic(err)
}
chain.Emit(
"IncreaseLiquidity",
"prevAddr", previousRealm.Address().String(),
"prevRealm", previousRealm.PkgPath(),
"poolPath", poolPath,
"tickLower", utils.FormatInt(position.TickLower()),
"tickUpper", utils.FormatInt(position.TickUpper()),
"caller", caller.String(),
"lpPositionId", utils.FormatUint(positionId),
"liquidityDelta", liquidity.ToString(),
"amount0", amount0.ToString(),
"amount1", amount1.ToString(),
"sqrtPriceX96", pool.Slot0SqrtPriceX96().ToString(),
"positionLiquidity", positionLiquidity,
"poolLiquidity", pool.Liquidity().ToString(),
"token0Balance", utils.FormatInt(pool.BalanceToken0()),
"token1Balance", utils.FormatInt(pool.BalanceToken1()),
"tickCumulative", utils.FormatInt(tickCumulative),
"secondsPerLiquidityCumulativeX128", secondsPerLiquidityCumulativeX128,
"observationTimestamp", utils.FormatInt(observationTimestamp),
)
return positionId, liquidity.ToString(), amount0.ToString(), amount1.ToString(), poolPath
}
// DecreaseLiquidity decreases liquidity of an existing position.
//
// Removes liquidity but keeps NFT ownership. This is one atomic public
// operation: accrued swap fees are collected first, then liquidity is burned,
// and principal is collected through the pool's fee-free `Collect` path.
//
// Parameters:
// - _: Noncrossing implementation-call discriminator; pass 0.
// - rlm: Current realm context forwarded unchanged by the position proxy.
// - positionId: NFT token ID
// - liquidityStr: amount of liquidity to remove, supplied as a decimal string
// - amount0MinStr: minimum token0 principal to receive, for slippage protection
// - amount1MinStr: minimum token1 principal to receive, for slippage protection
// - deadline: Unix timestamp after which the transaction is rejected
//
// Returns:
// - positionId: same NFT ID
// - liquidity: amount of liquidity removed (the delta)
// - fee0: token0 fee amount returned net of the withdrawal fee
// - fee1: token1 fee amount returned net of the withdrawal fee
// - amount0: token0 principal collected without a withdrawal fee
// - amount1: token1 principal collected without a withdrawal fee
// - poolPath: pool identifier
//
// Amount-minimum checks apply to the principal actually collected.
func (p *positionV1) DecreaseLiquidity(
_ int,
rlm realm,
positionId uint64,
liquidityStr string,
amount0MinStr string,
amount1MinStr string,
deadline int64,
) (uint64, string, string, string, string, string, string) {
access.AssertIsRlmCurrent(0, rlm)
halt.AssertIsNotHaltedWithdraw()
previousRealm := rlm.Previous()
caller := previousRealm.Address()
assertIsOwnerForToken(p, positionId, caller)
assertIsNotExpired(deadline)
assertValidLiquidityAmount(liquidityStr)
emission.MintAndDistributeGns(cross(rlm))
amount0Min := u256.MustFromDecimal(amount0MinStr)
amount1Min := u256.MustFromDecimal(amount1MinStr)
decreaseLiquidityParams := DecreaseLiquidityParams{
positionId: positionId,
liquidity: liquidityStr,
amount0Min: amount0Min,
amount1Min: amount1Min,
deadline: deadline,
caller: caller,
}
position := p.mustGetPosition(positionId)
tickLower := position.TickLower()
tickUpper := position.TickUpper()
positionId, liquidity, fee0, fee1, amount0, amount1, poolPath, err := p.decreaseLiquidity(0, rlm, decreaseLiquidityParams)
if err != nil {
panic(err)
}
pool := mustGetPool(poolPath)
positionLiquidity, err := p.GetPositionLiquidity(positionId)
if err != nil {
panic(err)
}
tickCumulative, secondsPerLiquidityCumulativeX128, observationTimestamp, err := currentPoolObservation(poolPath)
if err != nil {
panic(err)
}
chain.Emit(
"DecreaseLiquidity",
"prevAddr", previousRealm.Address().String(),
"prevRealm", previousRealm.PkgPath(),
"lpPositionId", utils.FormatUint(positionId),
"poolPath", poolPath,
"tickLower", utils.FormatInt(tickLower),
"tickUpper", utils.FormatInt(tickUpper),
"liquidityDelta", liquidity,
"feeAmount0", fee0,
"feeAmount1", fee1,
"amount0", amount0,
"amount1", amount1,
"sqrtPriceX96", pool.Slot0SqrtPriceX96().ToString(),
"positionLiquidity", positionLiquidity,
"poolLiquidity", pool.Liquidity().ToString(),
"token0Balance", utils.FormatInt(pool.BalanceToken0()),
"token1Balance", utils.FormatInt(pool.BalanceToken1()),
"tickCumulative", utils.FormatInt(tickCumulative),
"secondsPerLiquidityCumulativeX128", secondsPerLiquidityCumulativeX128,
"observationTimestamp", utils.FormatInt(observationTimestamp),
)
return positionId, liquidity, fee0, fee1, amount0, amount1, poolPath
}
// CollectFee collects swap fee from the position.
//
// Claims accumulated fees without removing liquidity.
// Useful for active positions earning ongoing fees.
// Applies the configured withdrawal fee to the collected swap fees.
//
// Parameters:
// - _: Noncrossing implementation-call discriminator; pass 0.
// - rlm: Current realm context forwarded unchanged by the position proxy.
// - positionId: NFT token ID whose accrued swap fees are collected
//
// Returns:
// - positionId: same NFT ID
// - tokensCollected0: token0 amount sent to caller after the withdrawal fee
// - tokensCollected1: token1 amount sent to caller after the withdrawal fee
// - poolPath: pool identifier
// - totalAmount0: raw token0 amount collected before the withdrawal fee
// - totalAmount1: raw token1 amount collected before the withdrawal fee
//
// Requirements:
// - Caller must own an unstaked NFT; a staked position uses its configured operator
// - If no fees are owed, the fee amounts returned are zero
func (p *positionV1) CollectFee(_ int, rlm realm, positionId uint64) (uint64, string, string, string, string, string) {
access.AssertIsRlmCurrent(0, rlm)
halt.AssertIsNotHaltedWithdraw()
caller := rlm.Previous().Address()
assertIsOwnerOrOperatorForToken(p, positionId, caller)
emission.MintAndDistributeGns(cross(rlm))
return p.collectFee(0, rlm, positionId, caller)
}
// collectFee performs fee collection and withdrawal fee calculation.
func (p *positionV1) collectFee(_ int, rlm realm, positionId uint64, caller address) (uint64, string, string, string, string, string) {
// verify position
position := p.mustGetPosition(positionId)
token0, token1, fee := splitOf(position.PoolKey())
pl.Burn(
cross(rlm),
token0,
token1,
fee,
position.TickLower(),
position.TickUpper(),
"0", // burn '0' liquidity to collect fee
caller,
)
currentFeeGrowth, err := p.getCurrentFeeGrowth(position, caller)
if err != nil {
panic(newErrorWithDetail(err.Error(), "failed to get current fee growth"))
}
tokensOwed0, tokensOwed1 := p.calculateFees(position, currentFeeGrowth)
position.SetFeeGrowthInside0LastX128(currentFeeGrowth.feeGrowthInside0LastX128.ToString())
position.SetFeeGrowthInside1LastX128(currentFeeGrowth.feeGrowthInside1LastX128.ToString())
// Collect the fee. The pool withholds the withdrawal fee and pays the
// remainder straight to the caller.
amount0, amount1, fee0Str, fee1Str := pl.CollectSwapFee(
cross(rlm),
token0, token1, fee,
caller,
position.TickLower(), position.TickUpper(),
utils.FormatInt(tokensOwed0), utils.FormatInt(tokensOwed1),
)
amount0Uint256 := u256.MustFromDecimal(amount0)
amount1Uint256 := u256.MustFromDecimal(amount1)
amount0Int64 := gnsmath.SafeConvertToInt64(amount0Uint256)
amount1Int64 := gnsmath.SafeConvertToInt64(amount1Uint256)
// sometimes there will be a few less uBase amount than expected due to rounding down in core, but we just subtract the full amount expected
// instead of the actual amount so we can burn the token
if tokensOwed0 < amount0Int64 {
panic(newErrorWithDetail(errUnderflow, "tokensOwed0 - amount0 underflow"))
}
position.SetTokensOwed0(gnsmath.SafeSubInt64(tokensOwed0, amount0Int64))
if tokensOwed1 < amount1Int64 {
panic(newErrorWithDetail(errUnderflow, "tokensOwed1 - amount1 underflow"))
}
position.SetTokensOwed1(gnsmath.SafeSubInt64(tokensOwed1, amount1Int64))
p.mustUpdatePosition(0, rlm, positionId, *position)
// The pool already paid these out; recomputing them here only feeds the
// events and the return value.
amount0WithoutFeeStr := utils.FormatInt(gnsmath.SafeSubInt64(amount0Int64, utils.SafeParseInt64(fee0Str)))
amount1WithoutFeeStr := utils.FormatInt(gnsmath.SafeSubInt64(amount1Int64, utils.SafeParseInt64(fee1Str)))
poolPath := position.PoolKey()
previousRealm := rlm.Previous()
chain.Emit(
"CollectSwapFee",
"prevAddr", previousRealm.Address().String(),
"prevRealm", previousRealm.PkgPath(),
"lpPositionId", utils.FormatUint(positionId),
"feeAmount0", amount0WithoutFeeStr,
"feeAmount1", amount1WithoutFeeStr,
"poolPath", poolPath,
"poolTier", utils.FormatUint(staker.GetPoolTier(poolPath)),
"feeGrowthInside0LastX128", position.FeeGrowthInside0LastX128(),
"feeGrowthInside1LastX128", position.FeeGrowthInside1LastX128(),
)
chain.Emit(
"WithdrawalFee",
"prevAddr", previousRealm.Address().String(),
"prevRealm", previousRealm.PkgPath(),
"lpTokenId", utils.FormatUint(positionId),
"poolPath", poolPath,
"feeAmount0", fee0Str,
"feeAmount1", fee1Str,
"amount0WithoutFee", amount0WithoutFeeStr,
"amount1WithoutFee", amount1WithoutFeeStr,
)
return positionId, amount0WithoutFeeStr, amount1WithoutFeeStr, position.PoolKey(), amount0, amount1
}
// SetPositionOperator sets an operator for a position.
// Only staker can call this function.
//
// Parameters:
// - _: Noncrossing implementation-call discriminator; pass 0.
// - rlm: Current realm context forwarded unchanged by the position proxy.
// - id: position NFT ID whose operator is changed
// - operator: valid address to approve, or the empty address to remove the operator
func (p *positionV1) SetPositionOperator(_ int, rlm realm, id uint64, operator address) {
access.AssertIsRlmCurrent(0, rlm)
previousRealm := rlm.Previous()
access.AssertIsStaker(previousRealm.Address())
assertValidOperatorAddress(operator)
position := p.mustGetPosition(id)
prevOperator := position.Operator()
position.SetOperator(operator)
p.mustUpdatePosition(0, rlm, id, *position)
chain.Emit(
"SetPositionOperator",
"prevAddr", previousRealm.Address().String(),
"prevRealm", previousRealm.PkgPath(),
"lpPositionId", utils.FormatUint(id),
"prevOperator", prevOperator.String(),
"newOperator", operator.String(),
)
}
// getCurrentFeeGrowth retrieves current fee growth values for a position.
func (p *positionV1) getCurrentFeeGrowth(position *pos.Position, owner address) (FeeGrowthInside, error) {
positionKey := computePositionKey(position.TickLower(), position.TickUpper())
feeGrowthInside0LastX128, feeGrowthInside1LastX128, err := pl.GetPositionFeeGrowthInsideLastX128(position.PoolKey(), positionKey)
if err != nil {
return FeeGrowthInside{}, err
}
feeGrowthInside := FeeGrowthInside{
feeGrowthInside0LastX128: u256.MustFromDecimal(feeGrowthInside0LastX128),
feeGrowthInside1LastX128: u256.MustFromDecimal(feeGrowthInside1LastX128),
}
return feeGrowthInside, nil
}
// computePositionKey generates a compact deterministic key for a liquidity position.
func computePositionKey(tickLower, tickUpper int32) string {
return pl.EncodePositionKey(tickLower, tickUpper)
}
// calculatePositionBalances computes token balances for a position at current price.
// Returns calculated token0 and token1 balances based on position liquidity and price range.
func calculatePositionBalances(position *pos.Position) (int64, int64) {
liquidity := u256.MustFromDecimal(position.Liquidity())
if liquidity.IsZero() {
return 0, 0
}
sqrtPriceX96, err := pl.GetSlot0SqrtPriceX96(position.PoolKey())
if err != nil {
panic(err)
}
token0Balance, token1Balance := gnsmath.GetAmountsForLiquidity(
u256.MustFromDecimal(sqrtPriceX96), // currentSqrtPriceX96
gnsmath.TickMathGetSqrtRatioAtTick(position.TickLower()),
gnsmath.TickMathGetSqrtRatioAtTick(position.TickUpper()),
liquidity,
)
return gnsmath.SafeConvertToInt64(token0Balance), gnsmath.SafeConvertToInt64(token1Balance)
}
render.gno
package position
import (
"chain"
"strconv"
"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"
positionRoot "gno.land/r/gnoswap/position"
)
func (p *positionV1) Render(path string) string {
if path == "" {
return p.renderSummary()
}
positionID, ok := parsePositionRenderPath(path)
if !ok {
return "404\n"
}
storedPosition, exists := p.store.GetPosition(positionID)
if !exists {
return "404\n"
}
return p.renderPositionDetail(positionID, storedPosition)
}
func (p *positionV1) renderSummary() string {
out := md.H1("Gnoswap Position")
out += md.Paragraph(
"Position records remain stored after burning. The record count includes burned " +
"positions and is not a count of active liquidity positions. Use " +
md.InlineCode("id/<id>") + " for one stored record, for example " +
md.Link("id/1", "/r/gnoswap/position:id/1") +
". The detail route performs one keyed lookup and does not enumerate positions or recompute claimable values.",
)
runtimeTable := mdtable.Table{
Headers: []string{"Field", "Value"},
Rows: [][]string{
{"Realm address", md.InlineCode(chain.PackageAddress("gno.land/r/gnoswap/position").String())},
{"Active implementation", renderPackageLink(positionRoot.GetImplementationPackagePath())},
{"Position operations halted", ufmt.Sprintf("%t", halt.IsHaltedPosition())},
{"Withdrawals halted", ufmt.Sprintf("%t", halt.IsHaltedWithdraw())},
},
}
out += md.H2("Runtime") + runtimeTable.String()
records := mdtable.Table{
Headers: []string{"Field", "Value"},
Rows: [][]string{
{"Stored position records (including burned)", ufmt.Sprintf("%d", p.store.GetPositions().Size())},
{"Next position ID", ufmt.Sprintf("%d", p.store.GetPositionNextID())},
},
}
return out + md.H2("Stored records") + records.String()
}
func (p *positionV1) renderPositionDetail(positionID uint64, stored positionRoot.Position) string {
status := "Active"
if stored.Burned() {
status = "Burned (record retained)"
}
owner := "unavailable"
ownerAddress, err := p.nftAccessor.OwnerOf(positionIdFrom(positionID))
if err == nil && ownerAddress != "" {
owner = ownerAddress.String()
}
token0, token1, poolFee, validPoolKey := splitPoolKeyForRender(stored.PoolKey())
token0Reference := "unavailable (stored pool key is not token0:token1:fee)"
token1Reference := token0Reference
if validPoolKey {
token0Reference = renderPackageLink(token0)
token1Reference = renderPackageLink(token1)
}
out := md.H1(ufmt.Sprintf("Gnoswap Position %d", positionID))
out += md.Paragraph(
"This page reads one persisted position record. Stored accounting fields are " +
"shown as stored; claimable fees and current token balances are recomputed " +
"values and are intentionally not queried here.",
)
identity := mdtable.Table{
Headers: []string{"Field", "Value"},
Rows: [][]string{
{"Position ID", ufmt.Sprintf("%d", positionID)},
{"Status", status},
{"Owner", owner},
},
}
out += md.H2("Identity") + identity.String()
poolAndRange := mdtable.Table{
Headers: []string{"Field", "Value"},
Rows: [][]string{
{"Pool key", md.InlineCode(stored.PoolKey())},
{"Token 0 reference", token0Reference},
{"Token 1 reference", token1Reference},
{"Pool fee (from stored key)", poolFee},
{"Lower tick (stored)", ufmt.Sprintf("%d", stored.TickLower())},
{"Upper tick (stored)", ufmt.Sprintf("%d", stored.TickUpper())},
},
}
out += md.H2("Pool and range") + poolAndRange.String()
accounting := mdtable.Table{
Headers: []string{"Field", "Value"},
Rows: [][]string{
{"Liquidity (stored)", stored.Liquidity()},
{"Fee growth token 0 inside, last X128 (stored)", stored.FeeGrowthInside0LastX128()},
{"Fee growth token 1 inside, last X128 (stored)", stored.FeeGrowthInside1LastX128()},
{"Token 0 owed (stored accounting)", ufmt.Sprintf("%d", stored.TokensOwed0())},
{"Token 1 owed (stored accounting)", ufmt.Sprintf("%d", stored.TokensOwed1())},
{"Claimable fees / current token balances", "Not rendered; would require recomputation"},
},
}
return out + md.H2("Stored accounting") + accounting.String()
}
func parsePositionRenderPath(path string) (uint64, bool) {
const prefix = "id/"
if len(path) <= len(prefix) || path[:len(prefix)] != prefix {
return 0, false
}
id := path[len(prefix):]
for i := 0; i < len(id); i++ {
if id[i] < '0' || id[i] > '9' {
return 0, false
}
}
positionID, err := strconv.ParseUint(id, 10, 64)
if err != nil {
return 0, false
}
return positionID, true
}
func splitPoolKeyForRender(poolKey string) (string, string, string, bool) {
parts := strings.Split(poolKey, ":")
if len(parts) != 3 || parts[0] == "" || parts[1] == "" || parts[2] == "" {
return "", "", "", false
}
return parts[0], parts[1], parts[2], true
}
func renderPackageLink(path string) string {
if strings.HasPrefix(path, "gno.land/") {
destination := strings.TrimPrefix(path, "gno.land")
// Token references append .SYMBOL; link to the defining realm.
if separator := strings.Index(destination, "."); separator >= 0 {
destination = destination[:separator]
}
return md.Link(path, destination)
}
return md.InlineCode(path)
}
reposition.gno
package position
import (
"chain"
"gno.land/r/gnoswap/access/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/common"
"gno.land/r/gnoswap/emission"
"gno.land/r/gnoswap/halt/v1"
)
// Reposition adjusts the price range and liquidity of an existing position.
//
// Parameters:
// - _: leading integer discriminator; callers pass 0
// - rlm: current realm context forwarded from the public wrapper; the implementation validates it as current
// - positionId: NFT token ID to reposition
// - tickLower: new lower tick boundary of the position's price range
// - tickUpper: new upper tick boundary of the position's price range
// - amount0DesiredStr: desired token0 amount for the new position, represented as a decimal string
// - amount1DesiredStr: desired token1 amount for the new position, represented as a decimal string
// - amount0MinStr: minimum acceptable token0 amount for slippage protection
// - amount1MinStr: minimum acceptable token1 amount for slippage protection
// - deadline: transaction expiration timestamp
//
// Returns:
// - positionId: NFT token ID that was repositioned
// - liquidity: new liquidity amount, represented as a decimal string
// - tickLower: lower tick boundary applied to the position
// - tickUpper: upper tick boundary applied to the position
// - amount0: actual token0 amount added to the new range, represented as a decimal string
// - amount1: actual token1 amount added to the new range, represented as a decimal string
func (p *positionV1) Reposition(
_ int,
rlm realm,
positionId uint64,
tickLower int32,
tickUpper int32,
amount0DesiredStr string,
amount1DesiredStr string,
amount0MinStr string,
amount1MinStr string,
deadline int64,
) (uint64, string, int32, int32, string, string) {
access.AssertIsRlmCurrent(0, rlm)
halt.AssertIsNotHaltedPosition()
previousRealm := rlm.Previous()
caller := previousRealm.Address()
assertIsOwnerForToken(p, positionId, caller)
assertIsNotExpired(deadline)
emission.MintAndDistributeGns(cross(rlm))
// The position must be clear (zero liquidity and zero tokens owed) before
// it can be repositioned.
position := p.mustGetPosition(positionId)
token0, token1, _ := splitOf(position.PoolKey())
common.AssertIsNotHandleNativeCoin()
oldTickLower := position.TickLower()
oldTickUpper := position.TickUpper()
if !position.IsClear() {
panic(newErrorWithDetail(
errNotClear,
ufmt.Sprintf(
"position(%d) isn't clear(liquidity:%s, tokensOwed0:%d, tokensOwed1:%d)",
positionId,
position.Liquidity(),
position.TokensOwed0(),
position.TokensOwed1(),
),
))
}
if err := validateTokenPath(token0, token1); err != nil {
panic(newErrorWithDetail(err.Error(), ufmt.Sprintf("token0(%s), token1(%s)", token0, token1)))
}
poolKey := position.PoolKey()
liquidity, amount0, amount1 := p.addLiquidity(
0,
rlm,
AddLiquidityParams{
poolKey: poolKey,
tickLower: tickLower,
tickUpper: tickUpper,
amount0Desired: u256.MustFromDecimal(amount0DesiredStr),
amount1Desired: u256.MustFromDecimal(amount1DesiredStr),
amount0Min: u256.MustFromDecimal(amount0MinStr),
amount1Min: u256.MustFromDecimal(amount1MinStr),
caller: caller,
},
)
// update position tickLower, tickUpper to new value
// because getCurrentFeeGrowth() uses tickLower, tickUpper
position.SetTickLower(tickLower)
position.SetTickUpper(tickUpper)
currentFeeGrowth, err := p.getCurrentFeeGrowth(position, caller)
if err != nil {
panic(newErrorWithDetail(err.Error(), "failed to get current fee growth"))
}
position.SetFeeGrowthInside0LastX128(currentFeeGrowth.feeGrowthInside0LastX128.ToString())
position.SetFeeGrowthInside1LastX128(currentFeeGrowth.feeGrowthInside1LastX128.ToString())
position.SetLiquidity(liquidity.ToString())
// Do not reset the fee-growth checkpoints: a full decrease followed by
// repositioning must not create an unintended unclaimed-fee balance.
position.SetTokensOwed0(0)
position.SetTokensOwed1(0)
position.SetBurned(false)
p.mustUpdatePosition(0, rlm, positionId, *position)
pool := mustGetPool(poolKey)
positionLiquidity, err := p.GetPositionLiquidity(positionId)
if err != nil {
panic(err)
}
tickCumulative, secondsPerLiquidityCumulativeX128, observationTimestamp, err := currentPoolObservation(poolKey)
if err != nil {
panic(err)
}
chain.Emit(
"Reposition",
"prevAddr", previousRealm.Address().String(),
"prevRealm", previousRealm.PkgPath(),
"lpPositionId", utils.FormatUint(positionId),
"tickLower", utils.FormatInt(tickLower),
"tickUpper", utils.FormatInt(tickUpper),
"liquidityDelta", liquidity.ToString(),
"amount0", amount0.ToString(),
"amount1", amount1.ToString(),
"prevTickLower", utils.FormatInt(oldTickLower),
"prevTickUpper", utils.FormatInt(oldTickUpper),
"poolPath", poolKey,
"sqrtPriceX96", pool.Slot0SqrtPriceX96().ToString(),
"positionLiquidity", positionLiquidity,
"poolLiquidity", pool.Liquidity().ToString(),
"token0Balance", utils.FormatInt(pool.BalanceToken0()),
"token1Balance", utils.FormatInt(pool.BalanceToken1()),
"tickCumulative", utils.FormatInt(tickCumulative),
"secondsPerLiquidityCumulativeX128", secondsPerLiquidityCumulativeX128,
"observationTimestamp", utils.FormatInt(observationTimestamp),
)
return positionId, liquidity.ToString(), tickLower, tickUpper, amount0.ToString(), amount1.ToString()
}
type.gno
package position
import (
u256 "gno.land/p/gnoswap/uint256/v1"
)
// Previously, we used a different zero address ("g1000000..."),
// but we changed the value because using the address
// below appears to have become the de facto standard practice.
const zeroAddress address = address("")
type MintParams struct {
token0 string // token0 path for a specific pool
token1 string // token1 path for a specific pool
fee uint32 // fee for a specific pool
tickLower int32 // lower end of the tick range for the position
tickUpper int32 // upper end of the tick range for the position
amount0Desired *u256.Uint // desired amount of token0 to be minted
amount1Desired *u256.Uint // desired amount of token1 to be minted
amount0Min *u256.Uint // minimum amount of token0 to be minted
amount1Min *u256.Uint // minimum amount of token1 to be minted
deadline int64 // time by which the transaction must be included to effect the change
mintTo address // address to mint lpToken
caller address // address to call the function
}
// newMintParams creates `MintParams` from processed input data.
func newMintParams(input ProcessedMintInput, mintInput MintInput) MintParams {
return MintParams{
token0: input.tokenPair.token0,
token1: input.tokenPair.token1,
fee: mintInput.fee,
tickLower: input.tickLower,
tickUpper: input.tickUpper,
amount0Desired: input.amount0Desired,
amount1Desired: input.amount1Desired,
amount0Min: input.amount0Min,
amount1Min: input.amount1Min,
deadline: mintInput.deadline,
mintTo: mintInput.mintTo,
caller: mintInput.caller,
}
}
type IncreaseLiquidityParams struct {
positionId uint64 // positionId of the position to increase liquidity
amount0Desired *u256.Uint // desired amount of token0 to be minted
amount1Desired *u256.Uint // desired amount of token1 to be minted
amount0Min *u256.Uint // minimum amount of token0 to be minted
amount1Min *u256.Uint // minimum amount of token1 to be minted
deadline int64 // time by which the transaction must be included to effect the change
caller address // address to call the function
}
type DecreaseLiquidityParams struct {
positionId uint64 // positionId of the position to decrease liquidity
liquidity string // amount of liquidity to decrease
amount0Min *u256.Uint // minimum amount of token0 to be minted
amount1Min *u256.Uint // minimum amount of token1 to be minted
deadline int64 // time by which the transaction must be included to effect the change
caller address // address to call the function
}
type MintInput struct {
token0 string
token1 string
fee uint32
tickLower int32
tickUpper int32
amount0Desired string
amount1Desired string
amount0Min string
amount1Min string
deadline int64
mintTo address
caller address
}
type TokenPair struct {
token0 string
token1 string
}
type ProcessedMintInput struct {
tokenPair TokenPair
amount0Desired *u256.Uint
amount1Desired *u256.Uint
amount0Min *u256.Uint
amount1Min *u256.Uint
tickLower int32
tickUpper int32
poolPath string
}
// FeeGrowthInside represents fee growth inside ticks
type FeeGrowthInside struct {
feeGrowthInside0LastX128 *u256.Uint
feeGrowthInside1LastX128 *u256.Uint
}
utils.gno
package position
import (
"strconv"
"strings"
prabc "gno.land/p/gnoswap/rbac/v1"
u256 "gno.land/p/gnoswap/uint256/v1"
"gno.land/p/nt/grc721/v0"
ufmt "gno.land/p/nt/ufmt/v0"
"gno.land/r/gnoswap/access/v1"
pl "gno.land/r/gnoswap/pool"
)
const MAX_UINT256 string = "115792089237316195423570985008687907853269984665640564039457584007913129639935"
func mustGetStakerAddress() address {
return access.MustGetAddress(prabc.ROLE_STAKER.String())
}
// mustGetPool returns the read-only snapshot for poolPath.
// It panics when poolPath does not identify a pool.
func mustGetPool(poolPath string) *pl.Pool {
pool, ok := pl.GetPools().Get(poolPath).(*pl.Pool)
if !ok || pool == nil {
panic(ufmt.Sprintf("expected poolPath(%s) to exist", poolPath))
}
return pool
}
// positionIdFrom converts positionId to grc721.TokenID type
// input: positionId uint64
// output: grc721.TokenID
func positionIdFrom(positionId uint64) grc721.TokenID {
return grc721.TokenID(strconv.FormatUint(positionId, 10))
}
// exists checks whether positionId exists
// If positionId doesn't exist, return false, otherwise return true
// input: positionId uint64
// output: bool
func (p *positionV1) exists(positionId uint64) bool {
return p.nftAccessor.Exists(positionIdFrom(positionId))
}
// isOwner checks whether the caller is the owner of the positionId
// If the caller is the owner of the positionId, return true, otherwise return false
// input: positionId uint64, addr std.Address
// output: bool
func (p *positionV1) isOwner(positionId uint64, addr address) bool {
owner, err := p.nftAccessor.OwnerOf(positionIdFrom(positionId))
if err != nil {
return false
}
return owner == addr
}
// isOperator checks whether the caller is the approved operator of the positionId
// If the caller is the approved operator of the positionId, return true, otherwise return false
// input: positionId uint64, addr std.Address
// output: bool
func (p *positionV1) isOperator(positionId uint64, addr address) bool {
operator, err := p.GetPositionOperator(positionId)
return err == nil && operator == addr
}
// isStaked checks whether positionId is staked
// If positionId is staked, owner of positionId is staker contract
// If positionId is staked, return true, otherwise return false
// input: positionId grc721.TokenID
// output: bool
func (p *positionV1) isStaked(positionId grc721.TokenID) bool {
exist := p.nftAccessor.Exists(positionId)
if !exist {
return false
}
owner, err := p.nftAccessor.OwnerOf(positionId)
if err == nil && owner == mustGetStakerAddress() {
return true
}
return false
}
// isOwnerOrOperator checks whether the caller is the owner or approved operator of the positionId
// If the caller is the owner or approved operator of the positionId, return true, otherwise return false
// input: addr std.Address, positionId uint64
// output: bool
func (p *positionV1) isOwnerOrOperator(positionId uint64, addr address) bool {
if !addr.IsValid() || !p.exists(positionId) {
return false
}
if p.isStaked(positionIdFrom(positionId)) {
return p.isOperator(positionId, addr)
}
return p.isOwner(positionId, addr)
}
// splitOf divides poolKey into pToken0, pToken1, and pFee
// If poolKey is invalid, it will panic
//
// input: poolKey string
// output:
// - token0Path string
// - token1Path string
// - fee uint32
func splitOf(poolKey string) (string, string, uint32) {
res := strings.Split(poolKey, ":")
if len(res) != 3 {
panic(newErrorWithDetail(errInvalidInput, ufmt.Sprintf("invalid poolKey(%s)", poolKey)))
}
pToken0, pToken1, pFeeStr := res[0], res[1], res[2]
pFee, err := strconv.Atoi(pFeeStr)
if err != nil {
panic(newErrorWithDetail(errInvalidInput, ufmt.Sprintf("invalid fee(%s)", pFeeStr)))
}
return pToken0, pToken1, uint32(pFee)
}
func isSlippageExceeded(amount0, amount1, amount0Min, amount1Min *u256.Uint) bool {
return !(amount0.Gte(amount0Min) && amount1.Gte(amount1Min))
}
// currentPoolObservation derives the latest stored observation from the
// Uniswap-V3-aligned Slot0 and observations surfaces.
func currentPoolObservation(poolPath string) (int64, string, int64, error) {
slot0 := pl.GetSlot0(poolPath)
observation, err := pl.GetObservationAt(poolPath, slot0.ObservationIndex())
if err != nil {
return 0, "", 0, err
}
return observation.TickCumulative(), observation.SecondsPerLiquidityCumulativeX128(), observation.BlockTimestamp(), nil
}