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

v1 source realm

package v1 handles token swaps through GnoSwap liquidity pools.

Overview

package v1 handles token swaps through GnoSwap liquidity pools.

The router provides user-facing swap functions with slippage protection, multi-hop routing, and automatic GNOT wrapping/unwrapping. It supports both exact input and exact output swap modes.

All swap functions include deadline checks and minimum output validation to protect users from unfavorable price movements.

Constants 7

const MIN_SQRT_RATIO, MAX_SQRT_RATIO

1const (
2	MIN_SQRT_RATIO string = "4295128739"                                        // same as TickMathGetSqrtRatioAtTick(MIN_TICK)
3	MAX_SQRT_RATIO string = "1461446703485210103287273052203988822378723970342" // same as TickMathGetSqrtRatioAtTick(MAX_TICK)
4)
source

const POOL_SEPARATOR

1const (
2	POOL_SEPARATOR = "*POOL*"
3)
source

swap can be done by multiple pools to separate each pool, we use POOL_SEPARATOR

const _, Forward, Backward

 1const (
 2	_ SwapDirection = iota
 3	// Forward indicates a swap processing direction from the first pool to the last pool.
 4	// Used primarily for exactIn swaps where the input amount is known.
 5	Forward
 6
 7	// Backward indicates a swap processing direction from the last pool to the first pool.
 8	// Used primarily for exactOut swaps where the output amount is known and input amounts
 9	// Need to be calculated in reverse order.
10	Backward
11)
source

const Unknown, ExactIn, ExactOut

 1const (
 2	Unknown SwapType = rawUnknown
 3	// ExactIn represents a swap type where the input amount is exact and the output amount may vary.
 4	// Used when a user wants to swap a specific amount of input tokens.
 5	ExactIn SwapType = rawExactIn
 6
 7	// ExactOut represents a swap type where the output amount is exact and the input amount may vary.
 8	// Used when a user wants to swap a specific amount of output tokens.
 9	ExactOut SwapType = rawExactOut
10)
source

Functions 7

func BuildSingleHopRoutePath

Action
1func BuildSingleHopRoutePath(tokenA, tokenB string, fee uint32) string
source

BuildSingleHopPath creates a single-hop route path string. Format: "tokenA:tokenB:fee"

Parameters: - tokenA: input token address - tokenB: output token address - fee: pool fee (e.g., 500, 3000, 10000)

Returns: - string: formatted single-hop route path

Example:

  • BuildSingleHopPath("gno.land/r/demo/wugnot", "gno.land/r/demo/usdc", 500) returns "gno.land/r/demo/wugnot:gno.land/r/demo/usdc:500"

func NewExactInParams

Action
1func NewExactInParams(
2	baseParams BaseSwapParams,
3	amountIn int64,
4	amountOutMin int64,
5) ExactInParams
source

NewExactInParams creates a new ExactInParams instance.

func NewExactOutParams

Action
1func NewExactOutParams(
2	baseParams BaseSwapParams,
3	amountOut int64,
4	amountInMax int64,
5) ExactOutParams
source

NewExactOutParams creates a new ExactOutParams instance.

func NewExactOutSwapOperation

Action
1func NewExactOutSwapOperation(r *routerV1, pp ExactOutParams) *ExactOutSwapOperation
source

NewExactOutSwapOperation creates a new exact-out swap operation.

Types 24

type BaseSwapParams

struct
1type BaseSwapParams struct {
2	InputToken        string
3	OutputToken       string
4	RouteArr          string
5	QuoteArr          string
6	SqrtPriceLimitX96 *u256.Uint
7	Deadline          int64
8}
source

type DryMultiSwapExecutor

struct
1type DryMultiSwapExecutor struct {
2	router *routerV1
3}
source

DryMultiSwapExecutor implements MultiSwapExecutor for dry run simulations.

Methods on DryMultiSwapExecutor

func Run

method on DryMultiSwapExecutor
1func (e *DryMultiSwapExecutor) Run(p SwapParams, data SwapCallbackData, _ address) (int64, int64)
source

Run performs a dry swap operation without changing state.

type DrySwapExecutor

struct
1type DrySwapExecutor struct {
2	router *routerV1
3	// payer is the user's address resolved at the entry point (DrySwapRoute),
4	// since dry-run paths do not have a realm value to read PreviousRealm from.
5	payer address
6}
source

DrySwapExecutor implements SwapExecutor for dry swaps.

type ExactInParams

struct
1type ExactInParams struct {
2	BaseSwapParams
3	AmountIn     int64
4	AmountOutMin int64
5}
source

ExactInParams contains parameters for exact input swaps.

type ExactInSwapOperation

struct
1type ExactInSwapOperation struct {
2	baseSwapOperation
3	params ExactInParams
4	router *routerV1
5}
source

Methods on ExactInSwapOperation

func Process

method on ExactInSwapOperation
1func (op *ExactInSwapOperation) Process(_ int, rlm realm) (*SwapResult, error)
source

Process executes the exact-in swap operation.

func Validate

method on ExactInSwapOperation
1func (op *ExactInSwapOperation) Validate() error
source

Validate validates the exact-in swap operation parameters.

type ExactOutParams

struct
1type ExactOutParams struct {
2	BaseSwapParams
3	AmountOut   int64
4	AmountInMax int64
5}
source

ExactOutParams contains parameters for exact output swaps.

type ExactOutSwapOperation

struct
1type ExactOutSwapOperation struct {
2	router *routerV1
3	baseSwapOperation
4	params ExactOutParams
5}
source

ExactOutSwapOperation handles swaps where the output amount is specified.

Methods on ExactOutSwapOperation

func Process

method on ExactOutSwapOperation
1func (op *ExactOutSwapOperation) Process(_ int, rlm realm) (*SwapResult, error)
source

Process executes the exact-out swap operation.

func Validate

method on ExactOutSwapOperation
1func (op *ExactOutSwapOperation) Validate() error
source

Validate ensures the exact-out swap parameters are valid.

type MultiSwapExecutor

interface
1type MultiSwapExecutor interface {
2	// Run performs the swap operation and returns pool received and pool output amounts.
3	Run(p SwapParams, data SwapCallbackData, recipient address) (int64, int64)
4}
source

MultiSwapExecutor defines the interface for multi-hop swap operation execution.

type MultiSwapProcessor

struct
1type MultiSwapProcessor struct {
2	executor   MultiSwapExecutor
3	direction  SwapDirection
4	router     *routerV1
5	isSimulate bool
6	// payer is the address used to identify the user. For real swaps it is the
7	// PreviousRealm address; for dry-run paths it is resolved at the entry point.
8	payer address
9}
source

MultiSwapProcessor handles the execution flow for multi-hop swaps.

type RealMultiSwapExecutor

struct
1type RealMultiSwapExecutor struct {
2	rlm    realm
3	router *routerV1
4}
source

RealMultiSwapExecutor implements MultiSwapExecutor for actual swap operations.

Methods on RealMultiSwapExecutor

func Run

method on RealMultiSwapExecutor
1func (e *RealMultiSwapExecutor) Run(p SwapParams, data SwapCallbackData, recipient address) (int64, int64)
source

Run performs a real swap operation with state changes.

type RealSwapExecutor

struct
1type RealSwapExecutor struct {
2	rlm    realm
3	router *routerV1
4}
source

RealSwapExecutor implements SwapExecutor for actual swaps.

type RouteParser

struct
1type RouteParser struct{}
source

RouteParser handles parsing and validation of routes and quotes

Methods on RouteParser

func ParseRoutes

method on RouteParser
1func (p *RouteParser) ParseRoutes(routes, quotes string) ([]string, []string, error)
source

ParseRoutes parses route and quote strings into slices and validates them.

func ValidateQuoteSum

method on RouteParser
1func (p *RouteParser) ValidateQuoteSum(quotes []string) error
source

ValidateQuoteSum ensures all quotes add up to 100%.

func ValidateRoutesAndQuotes

method on RouteParser
1func (p *RouteParser) ValidateRoutesAndQuotes(routes, quotes []string) error
source

ValidateRoutesAndQuotes ensures routes and quotes meet required criteria.

type RouterOperation

interface
1type RouterOperation interface {
2	Validate() error
3	Process(_ int, rlm realm) (*SwapResult, error)
4}
source

type SingleSwapParams

struct
 1type SingleSwapParams struct {
 2	tokenIn  string // token to spend
 3	tokenOut string // token to receive
 4	fee      uint32 // fee of the pool used to swap
 5
 6	// Amount specified for the swap:
 7	//  - Positive: exact input amount (tokenIn)
 8	//  - Negative: exact output amount (tokenOut)
 9	amountSpecified int64
10
11	sqrtPriceLimitX96 *u256.Uint // sqrtPriceLimitX96 for the swap, empty string or zero string means no limit
12}
source

SingleSwapParams contains parameters for executing a single pool swap. It represents the simplest form of swap that occurs within a single liquidity pool.

Methods on SingleSwapParams

func Fee

method on SingleSwapParams
1func (p SingleSwapParams) Fee() uint32
source

Fee returns the pool fee tier.

func SqrtPriceLimitX96

method on SingleSwapParams
1func (p SingleSwapParams) SqrtPriceLimitX96() *u256.Uint
source

SqrtPriceLimitX96 returns the sqrtPriceLimitX96 for the swap. If sqrtPriceLimitX96 is empty string, it will return zero.

func TokenIn

method on SingleSwapParams
1func (p SingleSwapParams) TokenIn() string
source

TokenIn returns the input token address.

func TokenOut

method on SingleSwapParams
1func (p SingleSwapParams) TokenOut() string
source

TokenOut returns the output token address.

type SwapCallbackData

struct
1type SwapCallbackData struct {
2	tokenIn  string  // token to spend
3	tokenOut string  // token to receive
4	fee      uint32  // fee of the pool used to swap
5	payer    address // address to spend the token
6}
source

SwapCallbackData contains the callback data required for swap execution. This type is used to pass necessary information during the swap callback process, ensuring proper token transfers and pool data updates.

type SwapDirection

ident
1type SwapDirection int
source

SwapDirection represents the direction of swap execution in multi-hop swaps. It determines whether swaps are processed in forward order (first to last pool) or backward order (last to first pool).

type SwapExecutor

interface
1type SwapExecutor interface {
2	// execute performs the swap operation.
3	execute(p *SingleSwapParams) (int64, int64)
4}
source

SwapExecutor defines the interface for executing swaps.

type SwapParams

struct
1type SwapParams struct {
2	SingleSwapParams
3	recipient address // address to receive the token
4}
source

SwapParams contains parameters for executing a multi-hop swap operation.

Methods on SwapParams

func Fee

method on SwapParams
1func (p SwapParams) Fee() uint32
source

Fee returns the pool fee tier.

func Recipient

method on SwapParams
1func (p SwapParams) Recipient() address
source

Recipient returns the recipient address.

func TokenIn

method on SwapParams
1func (p SwapParams) TokenIn() string
source

TokenIn returns the input token address.

func TokenOut

method on SwapParams
1func (p SwapParams) TokenOut() string
source

TokenOut returns the output token address.

type SwapParamsI

interface
1type SwapParamsI interface {
2	TokenIn() string
3	TokenOut() string
4	Fee() uint32
5}
source

SwapParamsI defines the common interface for swap parameters.

type SwapProcessor

struct
1type SwapProcessor struct {
2	router *routerV1
3	// payer identifies the user for dry-run simulations. It is resolved once at
4	// the entry point via unsafe.PreviousRealm since dry-run paths are
5	// read-only and carry no realm value to thread.
6	payer address
7}
source

SwapProcessor handles the execution of swap operations

Methods on SwapProcessor

func AddSwapResults

method on SwapProcessor
1func (p *SwapProcessor) AddSwapResults(
2	resultAmountIn, resultAmountOut, amountIn, amountOut int64,
3) (int64, int64, error)
source

AddSwapResults safely adds swap result amounts, checking for overflow.

Parameters:

  • resultAmountIn, resultAmountOut: Accumulated results from previous routes
  • amountIn, amountOut: Results from current route

Returns:

  • newAmountIn: resultAmountIn + amountIn
  • newAmountOut: resultAmountOut + amountOut
  • err: Always nil (uses safe addition that panics on overflow)

func ProcessMultiSwap

method on SwapProcessor
1func (p *SwapProcessor) ProcessMultiSwap(
2	swapType SwapType,
3	route string,
4	numHops int,
5	amountSpecified int64,
6) (int64, int64, error)
source

ProcessMultiSwap handles a multi-hop swap simulation.

Parameters:

  • swapType: ExactIn or ExactOut
  • route: Multi-hop route with POOL_SEPARATOR
  • numHops: Number of hops in the route
  • amountSpecified: Input/output amount depending on swap type

Returns:

  • amountIn: Expected input amount
  • amountOut: Expected output amount
  • err: Error if swap simulation fails

func ProcessSingleSwap

method on SwapProcessor
1func (p *SwapProcessor) ProcessSingleSwap(route string, amountSpecified int64) (amountIn, amountOut int64, err error)
source

ProcessSingleSwap handles a single-hop swap simulation.

Parameters:

  • route: Single pool path "TOKEN0:TOKEN1:FEE"
  • amountSpecified: Input/output amount depending on swap type

Returns:

  • amountIn: Expected input amount
  • amountOut: Expected output amount
  • err: Error if swap simulation fails

func ValidateSwapResults

method on SwapProcessor
1func (p *SwapProcessor) ValidateSwapResults(
2	swapType SwapType,
3	resultAmountIn, resultAmountOut int64,
4	amountSpecified, amountLimit int64,
5	swapCount int64,
6) (amountIn, amountOut int64, success bool)
source

ValidateSwapResults checks if the swap results meet the required constraints.

Parameters:

  • swapType: ExactIn or ExactOut
  • resultAmountIn, resultAmountOut: Swap simulation results
  • amountSpecified: User's specified exact amount
  • amountLimit: Slippage protection limit
  • swapCount: Number of swap operations (for tolerance)

Returns:

  • amountIn: Input amount (same as resultAmountIn)
  • amountOut: Output amount (same as resultAmountOut)
  • success: true if slippage constraints are met, false otherwise

type SwapResult

struct
1type SwapResult struct {
2	Routes          []string
3	Quotes          []string
4	AmountIn        int64
5	AmountOut       int64
6	AmountSpecified int64
7}
source

SwapResult encapsulates the outcome of a swap operation.

type SwapRouteParams

struct
 1type SwapRouteParams struct {
 2	inputToken        string
 3	outputToken       string
 4	routeArr          string
 5	quoteArr          string
 6	deadline          int64
 7	typ               SwapType
 8	exactAmount       int64      // amountIn for ExactIn, amountOut for ExactOut
 9	limitAmount       int64      // amountOutMin for ExactIn, amountInMax for ExactOut
10	sqrtPriceLimitX96 *u256.Uint // if sqrtPriceLimitX96 is zero string, it will be set to MIN_PRICE or MAX_PRICE
11}
source

SwapRouteParams contains all parameters needed for swap route execution

Methods on SwapRouteParams

func ExactAmount

method on SwapRouteParams
1func (p *SwapRouteParams) ExactAmount() int64
source

func ExpectedExactAmountByFee

method on SwapRouteParams
1func (p *SwapRouteParams) ExpectedExactAmountByFee(feeBps uint64) int64
source

when exact out, calculate amount to fetch from pool including router fee

func SwapCount

method on SwapRouteParams
1func (p *SwapRouteParams) SwapCount() int64
source

type SwapType

ident
1type SwapType string
source

Methods on SwapType

func String

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

String returns the string representation of SwapType.

type SwapValidator

struct
1type SwapValidator struct{}
source

SwapValidator provides validation methods for swap operations

Imports 23

Source Files 19