Playground
assert.gno
package router
import (
"errors"
"strings"
"time"
ufmt "gno.land/p/nt/ufmt/v0"
u256 "gno.land/p/gnoswap/uint256/v1"
"gno.land/r/gnoswap/pool"
"gno.land/r/gnoswap/common"
)
// assertIsNotExpired ensures the transaction deadline has not passed.
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),
))
}
}
func assertSingleSwap(p *SingleSwapParams) {
if p.tokenIn == p.tokenOut {
panic(errors.New(errSameTokenSwap))
}
common.MustRegistered(p.tokenIn, p.tokenOut)
}
func assertIsValidSqrtPriceLimitX96(sqrtPriceLimitX96 string) {
if sqrtPriceLimitX96 == "" {
panic(makeErrorWithDetails(
errInvalidInput,
ufmt.Sprintf("invalid sqrtPriceLimitX96: %s", sqrtPriceLimitX96),
))
}
_, err := u256.FromDecimal(sqrtPriceLimitX96)
if err != nil {
panic(makeErrorWithDetails(
errInvalidInput,
ufmt.Sprintf("invalid sqrtPriceLimitX96: %s", sqrtPriceLimitX96),
))
}
}
func assertIsValidSingleSwapRouteArrPath(routePaths, inputToken, outputToken string) {
if routePaths == "" {
panic(makeErrorWithDetails(
errInvalidInput,
ufmt.Sprintf("invalid route: %s", routePaths),
))
}
if strings.Count(routePaths, ",") > 0 {
panic(makeErrorWithDetails(
errInvalidInput,
ufmt.Sprintf("invalid routePaths: %s", routePaths),
))
}
if strings.Count(routePaths, POOL_SEPARATOR) > 0 {
panic(makeErrorWithDetails(
errInvalidInput,
ufmt.Sprintf("invalid routePaths: %s", routePaths),
))
}
assertIsValidRoutePaths(routePaths, inputToken, outputToken)
}
func assertIsValidRoutePaths(routePaths, inputToken, outputToken string) {
err := validateRoutePaths(routePaths, inputToken, outputToken)
if err != nil {
panic(err)
}
}
func assertIsExistsPools(routePathArr string) {
poolPaths, err := parsePoolPathsByRoutePathArr(routePathArr)
if err != nil {
panic(err)
}
for _, poolPath := range poolPaths {
if !pool.ExistsPoolPath(poolPath) {
panic(makeErrorWithDetails(
errInvalidInput,
ufmt.Sprintf("pool does not exist: %s", poolPath),
))
}
}
}
func assertIsRouterImplementation(caller address) {
if caller != routerImplAddr {
panic(makeErrorWithDetails(
errUnAuthorizedCaller,
ufmt.Sprintf("caller %s is not router implementation(%s)", caller, routerImplAddr),
))
}
}
// assertIsRouterProxyRealm ensures the swap context was forwarded by the router proxy.
func assertIsRouterProxyRealm(_ int, rlm realm) {
if rlm.PkgPath() != routerProxyPkgPath {
panic(makeErrorWithDetails(
errUnAuthorizedCaller,
ufmt.Sprintf("swap context %s is not router proxy(%s)", rlm.PkgPath(), routerProxyPkgPath),
))
}
}
// assertHopFullyConsumed reverts when an exact-in hop consumed less input than specified.
func assertHopFullyConsumed(hopIndex int, specifiedAmount, consumedAmount int64) {
err := validateHopFullyConsumed(hopIndex, specifiedAmount, consumedAmount)
if err != nil {
panic(err)
}
}
func validateHopFullyConsumed(hopIndex int, specifiedAmount, consumedAmount int64) error {
if consumedAmount != specifiedAmount {
return makeErrorWithDetails(
errInsufficientLiquidity,
ufmt.Sprintf("partial fill on hop(%d): requested=%d, consumed=%d", hopIndex, specifiedAmount, consumedAmount),
)
}
return nil
}
base.gno
package router
import (
"errors"
"strings"
gnsmath "gno.land/p/gnoswap/gnsmath/v1"
prbac "gno.land/p/gnoswap/rbac/v1"
u256 "gno.land/p/gnoswap/uint256/v1"
ufmt "gno.land/p/nt/ufmt/v0"
"gno.land/r/gnoswap/access/v1"
)
const (
SINGLE_HOP_ROUTE int = 1
)
// swap can be done by multiple pools
// to separate each pool, we use POOL_SEPARATOR
const (
POOL_SEPARATOR = "*POOL*"
)
type RouterOperation interface {
// Validate checks operation parameters before processing.
//
// Returns:
// - err: nil when operation input is valid; validation error otherwise
Validate() error
// Process executes the operation in the propagated realm context.
//
// Parameters:
// - _: leading operation discriminator; callers pass 0
// - rlm: propagated current realm context used for pool interaction
//
// Returns:
// - result: swap amounts and route metadata, or nil when processing fails
// - err: nil on success; execution error otherwise
Process(_ int, rlm realm) (*SwapResult, error)
}
// executeSwapOperation validates and processes a swap operation.
func executeSwapOperation(_ int, rlm realm, op RouterOperation) (*SwapResult, error) {
if err := op.Validate(); err != nil {
return nil, err
}
result, err := op.Process(0, rlm)
if err != nil {
return nil, err
}
return result, nil
}
type BaseSwapParams struct {
InputToken string
OutputToken string
RouteArr string
QuoteArr string
SqrtPriceLimitX96 *u256.Uint
Deadline int64
}
// common swap operation
type baseSwapOperation struct {
sqrtPriceLimitX96 *u256.Uint
routes []string
quotes []string
amountSpecified int64
}
// processRoutes processes all swap routes and returns total amounts.
func (op *baseSwapOperation) processRoutes(_ int, rlm realm, r *routerV1, swapType SwapType) (int64, int64, error) {
resultAmountIn, resultAmountOut := int64(0), int64(0)
remainRequestAmount := op.amountSpecified
for i, route := range op.routes {
toSwapAmount := int64(0)
// if it's the last route, use the remaining amount
isLastRoute := i == len(op.routes)-1
if !isLastRoute {
// calculate the amount to swap for this route
swapAmount, err := calculateSwapAmountByQuote(op.amountSpecified, op.quotes[i])
if err != nil {
return 0, 0, err
}
// update the remaining amount
remainRequestAmount = gnsmath.SafeSubInt64(remainRequestAmount, swapAmount)
toSwapAmount = swapAmount
} else {
toSwapAmount = remainRequestAmount
}
amountIn, amountOut, err := op.processRoute(0, rlm, r, route, toSwapAmount, swapType)
if err != nil {
return 0, 0, err
}
resultAmountIn = gnsmath.SafeAddInt64(resultAmountIn, amountIn)
resultAmountOut = gnsmath.SafeAddInt64(resultAmountOut, amountOut)
}
return resultAmountIn, resultAmountOut, nil
}
// processRoute processes a single route with specified swap amount.
func (op *baseSwapOperation) processRoute(
_ int,
rlm realm,
r *routerV1,
route string,
toSwap int64,
swapType SwapType,
) (amountIn, amountOut int64, err error) {
numHops := strings.Count(route, POOL_SEPARATOR) + 1
assertHopsInRange(numHops)
switch numHops {
case SINGLE_HOP_ROUTE:
amountIn, amountOut = r.handleSingleSwap(0, rlm, route, toSwap, op.sqrtPriceLimitX96)
default:
amountIn, amountOut = r.handleMultiSwap(0, rlm, swapType, route, numHops, toSwap)
}
return amountIn, amountOut, nil
}
// handleSingleSwap executes a single-hop swap with the specified amount.
func (r *routerV1) handleSingleSwap(_ int, rlm realm, route string, amountSpecified int64, sqrtPriceLimitX96 *u256.Uint) (int64, int64) {
input, output, fee := getDataForSinglePath(route)
singleParams := SingleSwapParams{
tokenIn: input,
tokenOut: output,
fee: fee,
amountSpecified: amountSpecified,
sqrtPriceLimitX96: sqrtPriceLimitX96,
}
return r.singleSwap(0, rlm, &singleParams)
}
// handleMultiSwap processes multi-hop swaps across multiple pools.
func (r *routerV1) handleMultiSwap(
_ int,
rlm realm,
swapType SwapType,
route string,
numHops int,
amountSpecified int64,
) (int64, int64) {
recipient := access.MustGetAddress(prbac.ROLE_ROUTER.String())
switch swapType {
case ExactIn:
input, output, fee := getDataForMultiPath(route, 0) // first data
sp := newSwapParams(input, output, fee, recipient, amountSpecified)
return r.multiSwap(0, rlm, *sp, numHops, route)
case ExactOut:
input, output, fee := getDataForMultiPath(route, numHops-1) // last data
sp := newSwapParams(input, output, fee, recipient, amountSpecified)
return r.multiSwapNegative(0, rlm, *sp, numHops, route)
default:
panic(errors.New(errInvalidSwapType))
}
}
// SwapRouteParams contains all parameters needed for swap route execution
type SwapRouteParams struct {
inputToken string
outputToken string
routeArr string
quoteArr string
deadline int64
typ SwapType
exactAmount int64 // amountIn for ExactIn, amountOut for ExactOut
limitAmount int64 // amountOutMin for ExactIn, amountInMax for ExactOut
sqrtPriceLimitX96 *u256.Uint // if sqrtPriceLimitX96 is zero string, it will be set to MIN_PRICE or MAX_PRICE
}
// ExactAmount returns the requested exact input or output amount.
//
// Returns:
// - amount: exactAmount configured for the route
func (p *SwapRouteParams) ExactAmount() int64 {
return p.exactAmount
}
// ExpectedExactAmountByFee returns the amount needed by pool execution after router-fee adjustment.
//
// Parameters:
// - feeBps: router fee in basis points
//
// Returns:
// - amount: exact input amount for ExactIn, or gross pool amount for ExactOut
func (p *SwapRouteParams) ExpectedExactAmountByFee(feeBps uint64) int64 {
if p.typ == ExactIn {
return p.exactAmount
}
return calculateExactOutWithRouterFee(p.exactAmount, feeBps)
}
// SwapCount counts pool hops across all comma-separated routes.
//
// Returns:
// - count: total number of pool swaps represented by routeArr
func (p *SwapRouteParams) SwapCount() int64 {
swapCount := int64(0)
for _, route := range strings.Split(p.routeArr, ",") {
swapCount += int64(strings.Count(route, POOL_SEPARATOR) + 1)
}
return swapCount
}
func buildRouteEventAttrs(routeArr string) []string {
routes := strings.Split(routeArr, ",")
routeEventAttrs := make([]string, 0, len(routes)*2)
for index, route := range routes {
routeEventAttrs = append(routeEventAttrs, ufmt.Sprintf("routes[%d]", index))
routeEventAttrs = append(routeEventAttrs, route)
}
return routeEventAttrs
}
// IsSetSqrtPriceLimitX96 reports whether a nonzero caller price limit is configured.
//
// Returns:
// - set: true when sqrtPriceLimitX96 is non-nil and nonzero
func (p *SwapRouteParams) IsSetSqrtPriceLimitX96() bool {
return p.sqrtPriceLimitX96 != nil && !p.sqrtPriceLimitX96.IsZero()
}
// createSwapOperation creates the appropriate swap operation based on swap type.
func createSwapOperation(r *routerV1, params SwapRouteParams) (RouterOperation, error) {
baseParams := BaseSwapParams{
InputToken: params.inputToken,
OutputToken: params.outputToken,
RouteArr: params.routeArr,
QuoteArr: params.quoteArr,
SqrtPriceLimitX96: params.sqrtPriceLimitX96,
Deadline: params.deadline,
}
switch params.typ {
case ExactIn:
pp := NewExactInParams(baseParams, params.ExactAmount(), params.limitAmount)
return NewExactInSwapOperation(r, pp), nil
case ExactOut:
routerFee := r.store.GetSwapFee()
pp := NewExactOutParams(baseParams, params.ExpectedExactAmountByFee(routerFee), params.limitAmount)
return NewExactOutSwapOperation(r, pp), nil
default:
msg := addDetailToError(errInvalidSwapType, "unknown swap type")
return nil, errors.New(msg)
}
}
// commonSwapRoute handles the common logic for both ExactIn and ExactOut swaps.
func (r *routerV1) commonSwapRoute(_ int, rlm realm, params SwapRouteParams) (int64, int64, error) {
op, err := createSwapOperation(r, params)
if err != nil {
return 0, 0, err
}
result, err := executeSwapOperation(0, rlm, op)
if err != nil {
msg := addDetailToError(
errInvalidInput,
ufmt.Sprintf("invalid %s SwapOperation: %s", params.typ.String(), err.Error()),
)
return 0, 0, errors.New(msg)
}
inputAmount, outputAmount := r.finalizeSwap(
0,
rlm,
params.inputToken,
params.outputToken,
result.AmountIn,
result.AmountOut,
params.typ,
params.limitAmount,
params.ExactAmount(),
params.SwapCount(),
params.IsSetSqrtPriceLimitX96(),
)
return inputAmount, outputAmount, nil
}
consts.gno
package router
const routerProxyPkgPath = "gno.land/r/gnoswap/router"
var routerImplAddr address
func init(cur realm) {
routerImplAddr = cur.Address()
}
doc.gno
// package router handles token swaps through GnoSwap liquidity pools. // // The router provides user-facing swap functions with slippage protection, // multi-hop routing, and both exact-input and exact-output swap modes. // // Live exact-input calls enforce a minimum output and deadline. Live // exact-output calls enforce a maximum input and deadline. DrySwapRoute is // read-only and has no deadline or transfer. package router
errors.gno
package router
import (
ufmt "gno.land/p/nt/ufmt/v0"
)
const (
errSlippage = "[GNOSWAP-ROUTER-001] slippage check failed"
errInvalidRoutesAndQuotes = "[GNOSWAP-ROUTER-002] invalid routes and quotes"
errExpired = "[GNOSWAP-ROUTER-003] transaction expired"
errInvalidInput = "[GNOSWAP-ROUTER-004] invalid input data"
errInvalidPoolFeeTier = "[GNOSWAP-ROUTER-005] invalid pool fee tier"
errInvalidSwapFee = "[GNOSWAP-ROUTER-006] invalid swap fee"
errInvalidSwapType = "[GNOSWAP-ROUTER-007] invalid swap type"
errInvalidPoolPath = "[GNOSWAP-ROUTER-008] invalid pool path"
errUnAuthorizedCaller = "[GNOSWAP-ROUTER-009] unauthorized caller"
errHopsOutOfRange = "[GNOSWAP-ROUTER-010] number of hops must be 1~3"
errSameTokenSwap = "[GNOSWAP-ROUTER-011] cannot swap same token"
errInvalidRoutePath = "[GNOSWAP-ROUTER-013] invalid route path"
errInvalidRouteFirstToken = "[GNOSWAP-ROUTER-014] invalid route first token"
errInvalidRouteLastToken = "[GNOSWAP-ROUTER-015] invalid route last token"
errInvalidSwapAmount = "[GNOSWAP-ROUTER-016] invalid swap amount"
errRouteHopDisconnected = "[GNOSWAP-ROUTER-017] route hop disconnected"
errInsufficientBalance = "[GNOSWAP-ROUTER-018] insufficient balance for swap"
errSpoofedRealm = "[GNOSWAP-ROUTER-019] rlm does not match the current crossing frame"
errInsufficientLiquidity = "[GNOSWAP-ROUTER-020] insufficient liquidity for swap"
)
// addDetailToError adds detail to an error message.
func addDetailToError(message string, detail string) string {
finalErr := ufmt.Errorf("%s || %s", message, detail)
return finalErr.Error()
}
// makeErrorWithDetails creates an error with additional context.
func makeErrorWithDetails(message string, detail string) error {
return ufmt.Errorf("%s || %s", message, detail)
}
exact_in.gno
package router
import (
"chain"
"gno.land/r/gnoswap/access/v1"
ufmt "gno.land/p/nt/ufmt/v0"
u256 "gno.land/p/gnoswap/uint256/v1"
"gno.land/p/gnoswap/utils/v1"
"gno.land/r/gnoswap/common"
"gno.land/r/gnoswap/emission"
"gno.land/r/gnoswap/halt/v1"
"gno.land/r/gnoswap/referral/v1"
)
// ExactInSwapRoute swaps an exact amount of input tokens for output tokens.
//
// Executes multi-hop swaps through specified route.
// Supports splitting across multiple paths for price optimization.
// Applies slippage protection via minimum output amount.
//
// Parameters:
// - _: leading implementation discriminator; callers pass 0
// - rlm: propagated current realm context; this implementation validates and forwards it
// - inputToken: Input token contract path
// - outputToken: Output token contract path
// - amountIn: Exact input amount to swap
// - routeArr: Swap route (max 3 hops per path, multiple paths separated by comma)
// - quoteArr: Split percentages "70,30" (must sum to 100)
// - amountOutMin: Minimum acceptable output (slippage protection)
// - deadline: Unix timestamp for expiration
// - referrer: Optional referral address
//
// Route format:
// - Single-hop: "TOKEN0:TOKEN1:FEE"
// - Multi-hop: "TOKEN0:TOKEN1:FEE*POOL*TOKEN1:TOKEN2:FEE" (use *POOL* separator)
// - Multi-path: "route1,route2" (use comma separator between different routes)
//
// Returns:
// - amountIn: Actual input consumed
// - amountOut: Actual output received after the router fee
//
// Reverts if output < amountOutMin or deadline passed.
func (r *routerV1) ExactInSwapRoute(
_ int,
rlm realm,
inputToken string,
outputToken string,
amountIn string,
routeArr string,
quoteArr string,
amountOutMin string,
deadline int64,
referrer string,
) (string, string) {
access.AssertIsRlmCurrent(0, rlm)
halt.AssertIsNotHaltedRouter()
common.AssertIsNotHandleNativeCoin()
assertIsValidRoutePaths(routeArr, inputToken, outputToken)
assertIsNotExpired(deadline)
assertIsExistsPools(routeArr)
emission.MintAndDistributeGns(cross(rlm))
params := SwapRouteParams{
inputToken: inputToken,
outputToken: outputToken,
routeArr: routeArr,
quoteArr: quoteArr,
deadline: deadline,
typ: ExactIn,
exactAmount: utils.SafeParseInt64(amountIn),
limitAmount: utils.SafeParseInt64(amountOutMin),
sqrtPriceLimitX96: u256.Zero(), // multi-hop swap is not allowed to set sqrtPriceLimitX96
}
inputAmount, outputAmount := r.exactInSwapRoute(0, rlm, params, referrer)
return utils.FormatInt(inputAmount), utils.FormatInt(outputAmount)
}
// ExactInSingleSwapRoute swaps an exact amount of input tokens for output tokens through a single route.
//
// Executes a single-hop swap through a single specified route.
// Allows price limit control via sqrtPriceLimitX96 parameter.
// Applies slippage protection via minimum output amount.
//
// Parameters:
// - _: leading implementation discriminator; callers pass 0
// - rlm: propagated current realm context; this implementation validates and forwards it
// - inputToken: Input token contract path
// - outputToken: Output token contract path
// - amountIn: Exact input amount to swap
// - routeArr: Single-hop route path
// - amountOutMin: Minimum acceptable output (slippage protection)
// - sqrtPriceLimitX96: Price limit for swap execution (0 for no limit)
// - deadline: Unix timestamp for expiration
// - referrer: Optional referral address
//
// Route format:
// - Single-hop: "INPUT_TOKEN:OUTPUT_TOKEN:FEE"
//
// Returns:
// - amountIn: Actual input consumed
// - amountOut: Actual output received after the router fee
//
// With a nonzero price limit, the swap may stop at the limit after consuming
// less than amountIn; amountOutMin and the deadline are still enforced.
func (r *routerV1) ExactInSingleSwapRoute(
_ int,
rlm realm,
inputToken string,
outputToken string,
amountIn string,
routeArr string,
amountOutMin string,
sqrtPriceLimitX96 string,
deadline int64,
referrer string,
) (string, string) {
access.AssertIsRlmCurrent(0, rlm)
halt.AssertIsNotHaltedRouter()
common.AssertIsNotHandleNativeCoin()
assertIsValidSingleSwapRouteArrPath(routeArr, inputToken, outputToken)
assertIsValidSqrtPriceLimitX96(sqrtPriceLimitX96)
assertIsNotExpired(deadline)
assertIsExistsPools(routeArr)
emission.MintAndDistributeGns(cross(rlm))
params := SwapRouteParams{
inputToken: inputToken,
outputToken: outputToken,
routeArr: routeArr,
quoteArr: "100",
deadline: deadline,
typ: ExactIn,
exactAmount: utils.SafeParseInt64(amountIn),
limitAmount: utils.SafeParseInt64(amountOutMin),
sqrtPriceLimitX96: u256.MustFromDecimal(sqrtPriceLimitX96), // single swap is allowed to set sqrtPriceLimitX96
}
inputAmount, outputAmount := r.exactInSwapRoute(0, rlm, params, referrer)
return utils.FormatInt(inputAmount), utils.FormatInt(outputAmount)
}
// exactInSwapRoute executes the swap operation and handles token transfers and referral registration.
//
// Performs the actual swap operation using commonSwapRoute and handles:
// - Safe token transfers to the caller
// - Referral registration and tracking
// - Event emission for swap completion
//
// Parameters:
// - params: SwapRouteParams containing all swap configuration
// - referrer: Referral address for registration
//
// Returns:
// - inputAmount: Actual input amount consumed as string
// - outputAmount: Actual output amount received as string
//
// Panics if swap execution fails or token transfer fails.
func (r *routerV1) exactInSwapRoute(
_ int,
rlm realm,
params SwapRouteParams,
referrer string,
) (int64, int64) {
inputAmount, outputAmount, err := r.commonSwapRoute(0, rlm, params)
if err != nil {
panic(err)
}
previousRealm := rlm.Previous()
caller := previousRealm.Address()
common.SafeGRC20Transfer(0, rlm, params.outputToken, caller, outputAmount)
// handle referral registration
actualReferrer := referral.TryRegister(cross(rlm), caller, referrer)
eventAttrs := append([]string{
"prevAddr", caller.String(),
"prevRealm", previousRealm.PkgPath(),
"input", params.inputToken,
"output", params.outputToken,
"exactAmount", utils.FormatInt(params.exactAmount),
"quote", params.quoteArr,
"resultInputAmount", utils.FormatInt(inputAmount),
"resultOutputAmount", utils.FormatInt(outputAmount),
"referrer", actualReferrer,
}, buildRouteEventAttrs(params.routeArr)...)
chain.Emit(
"ExactInSwap",
eventAttrs...,
)
return inputAmount, outputAmount
}
type ExactInSwapOperation struct {
baseSwapOperation
params ExactInParams
router *routerV1
}
// NewExactInSwapOperation creates an exact-input operation for router execution.
//
// Parameters:
// - r: router implementation used to execute pool swaps
// - pp: exact-input amount and route settings
//
// Returns:
// - operation: initialized ExactInSwapOperation
func NewExactInSwapOperation(r *routerV1, pp ExactInParams) *ExactInSwapOperation {
return &ExactInSwapOperation{
router: r,
params: pp,
baseSwapOperation: baseSwapOperation{
sqrtPriceLimitX96: pp.SqrtPriceLimitX96,
},
}
}
// Validate checks the exact-input amount and parses route/quote allocations.
//
// Returns:
// - err: nil when amount, routes, and quotes are valid; validation error otherwise
func (op *ExactInSwapOperation) Validate() error {
amountIn := op.params.AmountIn
if amountIn <= 0 {
return ufmt.Errorf("invalid amountIn(%d), must be positive", amountIn)
}
// when `SwapType` is `ExactIn`, assign `amountSpecified` the `amountIn`
// obtained from above.
op.amountSpecified = amountIn
routes, quotes, err := validateRoutesAndQuotes(op.params.RouteArr, op.params.QuoteArr)
if err != nil {
return err
}
op.routes = routes
op.quotes = quotes
return nil
}
// Process executes the validated exact-input operation in the propagated realm.
//
// Parameters:
// - _: leading operation discriminator; callers pass 0
// - rlm: propagated current realm context used for pool swaps
//
// Returns:
// - result: aggregate swap amounts and route metadata, or nil on processing error
// - err: nil on success; pool or route execution error otherwise
func (op *ExactInSwapOperation) Process(_ int, rlm realm) (*SwapResult, error) {
resultAmountIn, resultAmountOut, err := op.processRoutes(0, rlm, op.router, ExactIn)
if err != nil {
return nil, err
}
return &SwapResult{
AmountIn: resultAmountIn,
AmountOut: resultAmountOut,
Routes: op.routes,
Quotes: op.quotes,
AmountSpecified: op.amountSpecified,
}, nil
}
exact_out.gno
package router
import (
"chain"
"gno.land/r/gnoswap/access/v1"
ufmt "gno.land/p/nt/ufmt/v0"
u256 "gno.land/p/gnoswap/uint256/v1"
"gno.land/p/gnoswap/utils/v1"
"gno.land/r/gnoswap/common"
"gno.land/r/gnoswap/emission"
"gno.land/r/gnoswap/halt/v1"
"gno.land/r/gnoswap/referral/v1"
)
// ExactOutSwapRoute swaps tokens for a requested post-router-fee output target.
//
// Executes a swap to receive the requested net output tokens.
// Calculates the required gross pool output and input working backwards
// through the route.
//
// Parameters:
// - _: leading implementation discriminator; callers pass 0
// - rlm: propagated current realm context; this implementation validates and forwards it
// - inputToken: Input token contract path
// - outputToken: Output token contract path
// - amountOut: Requested net output target
// - routeArr: Swap routes separated by comma; each route may contain up to 3 hops joined by *POOL*
// - quoteArr: Split percentages "70,30" (must sum to 100)
// - amountInMax: Maximum input to spend (slippage protection)
// - deadline: Unix timestamp for expiration
// - referrer: Optional referral address
//
// Route calculation:
// - Works backwards from output to input
// - Each hop increases required input
// - Multi-path aggregates total input
//
// Returns:
// - amountIn: Actual input consumed
// - amountOut: Net output delivered after the router fee
//
// Reverts if input > amountInMax or deadline passed.
func (r *routerV1) ExactOutSwapRoute(
_ int,
rlm realm,
inputToken string,
outputToken string,
amountOut string,
routeArr string,
quoteArr string,
amountInMax string,
deadline int64,
referrer string,
) (string, string) {
access.AssertIsRlmCurrent(0, rlm)
halt.AssertIsNotHaltedRouter()
common.AssertIsNotHandleNativeCoin()
assertIsValidRoutePaths(routeArr, inputToken, outputToken)
assertIsNotExpired(deadline)
assertIsExistsPools(routeArr)
emission.MintAndDistributeGns(cross(rlm))
params := SwapRouteParams{
inputToken: inputToken,
outputToken: outputToken,
routeArr: routeArr,
quoteArr: quoteArr,
deadline: deadline,
typ: ExactOut,
exactAmount: utils.SafeParseInt64(amountOut),
limitAmount: utils.SafeParseInt64(amountInMax),
sqrtPriceLimitX96: u256.Zero(), // multi-hop swap is not allowed to set sqrtPriceLimitX96
}
inputAmount, outputAmount := r.exactOutSwapRoute(0, rlm, params, referrer)
return utils.FormatInt(inputAmount), utils.FormatInt(outputAmount)
}
// ExactOutSingleSwapRoute swaps tokens for a requested post-router-fee output
// target through a single route.
//
// Executes a single-hop swap through a single specified route.
// Allows price limit control via sqrtPriceLimitX96.
// Applies slippage protection via maximum input amount.
//
// Parameters:
// - _: leading implementation discriminator; callers pass 0
// - rlm: propagated current realm context; this implementation validates and forwards it
// - inputToken: Input token contract path
// - outputToken: Output token contract path
// - amountOut: Requested net output target
// - routeArr: Single-hop route path
// - amountInMax: Maximum input to spend (slippage protection)
// - sqrtPriceLimitX96: Price limit for swap execution (0 for no limit)
// - deadline: Unix timestamp for expiration
// - referrer: Optional referral address
//
// Route format:
// - Single-hop: "INPUT_TOKEN:OUTPUT_TOKEN:FEE"
//
// Returns:
// - amountIn: Actual input consumed
// - amountOut: Net output delivered after the router fee
//
// With a nonzero price limit, the swap may stop at the limit and deliver less
// than amountOut; amountInMax and the deadline are still enforced.
func (r *routerV1) ExactOutSingleSwapRoute(
_ int,
rlm realm,
inputToken string,
outputToken string,
amountOut string,
routeArr string,
amountInMax string,
sqrtPriceLimitX96 string,
deadline int64,
referrer string,
) (string, string) {
access.AssertIsRlmCurrent(0, rlm)
halt.AssertIsNotHaltedRouter()
common.AssertIsNotHandleNativeCoin()
assertIsValidSingleSwapRouteArrPath(routeArr, inputToken, outputToken)
assertIsValidSqrtPriceLimitX96(sqrtPriceLimitX96)
assertIsNotExpired(deadline)
assertIsExistsPools(routeArr)
emission.MintAndDistributeGns(cross(rlm))
params := SwapRouteParams{
inputToken: inputToken,
outputToken: outputToken,
routeArr: routeArr,
quoteArr: "100",
deadline: deadline,
typ: ExactOut,
exactAmount: utils.SafeParseInt64(amountOut),
limitAmount: utils.SafeParseInt64(amountInMax),
sqrtPriceLimitX96: u256.MustFromDecimal(sqrtPriceLimitX96), // single swap is allowed to set sqrtPriceLimitX96
}
inputAmount, outputAmount := r.exactOutSwapRoute(0, rlm, params, referrer)
return utils.FormatInt(inputAmount), utils.FormatInt(outputAmount)
}
// exactOutSwapRoute executes the swap operation and handles token transfers and referral registration.
//
// Performs the actual swap operation using commonSwapRoute and handles:
// - Safe token transfers to the caller
// - Referral registration and tracking
// - Event emission for swap completion
//
// Parameters:
// - params: SwapRouteParams containing all swap configuration
// - referrer: Referral address for registration
//
// Returns:
// - inputAmount: Actual input amount consumed as string
// - outputAmount: Actual output amount received as string
//
// Panics if swap execution fails or token transfer fails.
func (r *routerV1) exactOutSwapRoute(
_ int,
rlm realm,
params SwapRouteParams,
referrer string,
) (int64, int64) {
inputAmount, outputAmount, err := r.commonSwapRoute(0, rlm, params)
if err != nil {
panic(err)
}
previousRealm := rlm.Previous()
caller := previousRealm.Address()
common.SafeGRC20Transfer(0, rlm, params.outputToken, caller, outputAmount)
// handle referral registration
actualReferrer := referral.TryRegister(cross(rlm), caller, referrer)
eventAttrs := append([]string{
"prevAddr", caller.String(),
"prevRealm", previousRealm.PkgPath(),
"input", params.inputToken,
"output", params.outputToken,
"exactAmount", utils.FormatInt(params.exactAmount),
"quote", params.quoteArr,
"resultInputAmount", utils.FormatInt(inputAmount),
"resultOutputAmount", utils.FormatInt(outputAmount),
"referrer", actualReferrer,
}, buildRouteEventAttrs(params.routeArr)...)
chain.Emit(
"ExactOutSwap",
eventAttrs...,
)
return inputAmount, outputAmount
}
// ExactOutSwapOperation handles swaps where the output amount is specified.
type ExactOutSwapOperation struct {
router *routerV1
baseSwapOperation
params ExactOutParams
}
// NewExactOutSwapOperation creates an exact-output operation for router execution.
//
// Parameters:
// - r: router implementation used to execute pool swaps
// - pp: exact-output amount and route settings
//
// Returns:
// - operation: initialized ExactOutSwapOperation
func NewExactOutSwapOperation(r *routerV1, pp ExactOutParams) *ExactOutSwapOperation {
return &ExactOutSwapOperation{
router: r,
params: pp,
baseSwapOperation: baseSwapOperation{
sqrtPriceLimitX96: pp.SqrtPriceLimitX96,
},
}
}
// Validate checks the exact-output amount and parses route/quote allocations.
//
// Returns:
// - err: nil when amount, routes, and quotes are valid; validation error otherwise
func (op *ExactOutSwapOperation) Validate() error {
amountOut := op.params.AmountOut
if amountOut <= 0 {
return ufmt.Errorf("invalid amountOut(%d), must be positive", amountOut)
}
// assign a signed reversed `amountOut` to `amountSpecified`
// when it's an ExactOut
op.amountSpecified = -amountOut
routes, quotes, err := validateRoutesAndQuotes(op.params.RouteArr, op.params.QuoteArr)
if err != nil {
return err
}
op.routes = routes
op.quotes = quotes
return nil
}
// Process executes the validated exact-output operation in the propagated realm.
//
// Parameters:
// - _: leading operation discriminator; callers pass 0
// - rlm: propagated current realm context used for pool swaps
//
// Returns:
// - result: aggregate swap amounts and route metadata, or nil on processing error
// - err: nil on success; pool or route execution error otherwise
func (op *ExactOutSwapOperation) Process(_ int, rlm realm) (*SwapResult, error) {
resultAmountIn, resultAmountOut, err := op.processRoutes(0, rlm, op.router, ExactOut)
if err != nil {
return nil, err
}
return &SwapResult{
AmountIn: resultAmountIn,
AmountOut: resultAmountOut,
Routes: op.routes,
Quotes: op.quotes,
AmountSpecified: op.amountSpecified,
}, nil
}
gnomod.toml
module = "gno.land/r/gnoswap/router/v2" gno = "0.9" [addpkg] creator = "g1q5tjjv3kkslzwf2na9y9wk7e5a8ugph8xfsk04" height = 1108594 max_deposit = "100000000ugnot"
init.gno
package router
import (
"gno.land/r/gnoswap/router"
)
const (
defaultSwapFeeBPS = uint64(15) // 0.15%
)
func init(cur realm) {
registerRouterV1(cur)
}
func registerRouterV1(cur realm) {
router.RegisterInitializer(cross(cur), func(_ int, rlm realm, routerStore router.IRouterStore) router.IRouter {
err := initStoreData(0, rlm, routerStore)
if err != nil {
panic(err)
}
return NewRouterV1(routerStore)
})
}
func initStoreData(_ int, rlm realm, routerStore router.IRouterStore) error {
if !routerStore.HasSwapFeeKey() {
err := routerStore.SetSwapFee(0, rlm, defaultSwapFeeBPS)
if err != nil {
return err
}
}
pendingProtocolFees := make(map[string]int64)
if routerStore.HasPendingProtocolFeesKey() {
pendingProtocolFees = routerStore.GetPendingProtocolFees()
}
if err := routerStore.SetPendingProtocolFees(0, rlm, pendingProtocolFees); err != nil {
return err
}
return nil
}
instance.gno
package router
import (
"gno.land/r/gnoswap/router"
)
type routerV1 struct {
store router.IRouterStore
}
// NewRouterV1 creates a router v1 implementation backed by routerStore.
//
// Parameters:
// - routerStore: storage implementation used for swap-fee and pending protocol-fee state
//
// Returns:
// - router: initialized IRouter implementation backed by routerStore
func NewRouterV1(
routerStore router.IRouterStore,
) router.IRouter {
instance := &routerV1{
store: routerStore,
}
return instance
}
protocol_fee_swap.gno
package router
import (
"chain"
ufmt "gno.land/p/nt/ufmt/v0"
gnsmath "gno.land/p/gnoswap/gnsmath/v1"
prbac "gno.land/p/gnoswap/rbac/v1"
u256 "gno.land/p/gnoswap/uint256/v1"
"gno.land/p/gnoswap/utils/v1"
"gno.land/r/gnoswap/access/v1"
"gno.land/r/gnoswap/common"
"gno.land/r/gnoswap/halt/v1"
pf "gno.land/r/gnoswap/protocol_fee"
_ "gno.land/r/gnoswap/protocol_fee/v1"
)
// GetSwapFee returns the current router fee rate in basis points.
//
// Returns:
// - fee: configured router fee in basis points
func (r *routerV1) GetSwapFee() uint64 {
return r.store.GetSwapFee()
}
// SetSwapFee sets the protocol swap fee rate.
//
// Fee is deducted from swap output and sent to protocol fee contract.
// Only callable by admin or governance.
//
// Parameters:
// - _: leading call discriminator; callers pass 0
// - rlm: propagated current realm context; it must be current for the authorized storage write
// - fee: new protocol fee rate in basis points, bounded to 0 through 1000
//
// Access:
// - Requires: Admin or Governance role
// - Halt check: Router and ProtocolFee must not be halted
//
// Events:
// - SetSwapFee: Emits previous and new fee values
//
// Reverts if:
// - Caller is not admin/governance
// - Fee > 1000 bps (10%)
// - Router or ProtocolFee is halted
func (r *routerV1) SetSwapFee(_ int, rlm realm, fee uint64) {
access.AssertIsRlmCurrent(0, rlm)
halt.AssertIsNotHaltedRouter()
halt.AssertIsNotHaltedProtocolFee()
previousRealm := rlm.Previous()
caller := previousRealm.Address()
access.AssertIsAdminOrGovernance(caller)
// max swap fee is 1000 (bps)
if fee > 1000 {
panic(ufmt.Errorf(
"%s: fee must be in range 0 to 1000 (10%). got %d",
errInvalidSwapFee, fee,
))
}
prevSwapFee := r.store.GetSwapFee()
if err := r.store.SetSwapFee(0, rlm, fee); err != nil {
panic(err)
}
chain.Emit(
"SetSwapFee",
"prevAddr", previousRealm.Address().String(),
"prevRealm", previousRealm.PkgPath(),
"newFee", utils.FormatUint(fee),
"prevFee", utils.FormatUint(prevSwapFee),
)
}
// handleSwapFee deducts the protocol fee from the swap amount and transfers it to the protocol fee contract.
func (r *routerV1) handleSwapFee(
_ int,
rlm realm,
outputToken string,
amount int64,
) int64 {
currentTokenPath := outputToken
swapFee := r.store.GetSwapFee()
if swapFee <= 0 {
r.settleProtocolFee(0, rlm, currentTokenPath, 0)
return amount
}
feeAmountInt64 := calculateRouterFee(amount, swapFee)
r.settleProtocolFee(0, rlm, currentTokenPath, feeAmountInt64)
previousRealm := rlm.Previous()
chain.Emit(
"SwapRouteFee",
"prevAddr", previousRealm.Address().String(),
"prevRealm", previousRealm.PkgPath(),
"tokenPath", currentTokenPath,
"amount", utils.FormatInt(feeAmountInt64),
)
return gnsmath.SafeSubInt64(amount, feeAmountInt64)
}
// GetPendingProtocolFees returns pending protocol fee amounts keyed by token path.
//
// Returns:
// - fees: token-path to pending amount map held by the router
func (r *routerV1) GetPendingProtocolFees() map[string]int64 {
return r.store.GetPendingProtocolFees()
}
func (r *routerV1) addPendingProtocolFee(_ int, rlm realm, tokenPath string, amount int64) {
if amount <= 0 {
return
}
pendingAmount := gnsmath.SafeAddInt64(r.store.GetPendingProtocolFee(tokenPath), amount)
if err := r.store.SetPendingProtocolFee(0, rlm, tokenPath, pendingAmount); err != nil {
panic(err)
}
}
// settleProtocolFee forwards amount, plus anything already pending for tokenPath, to
// the protocol fee realm. When collection is halted or the transfer fails, the amount
// is recorded as pending instead and settled by a later call for the same token, which
// every fee path makes even when the fee is zero.
//
// Only tokenPath is touched, so an unrelated token can never block settlement. The
// pending entry is written only when the fee cannot be forwarded, so the common path
// performs no store write at all.
func (r *routerV1) settleProtocolFee(_ int, rlm realm, tokenPath string, amount int64) {
if halt.IsHaltedProtocolFee() {
r.addPendingProtocolFee(0, rlm, tokenPath, amount)
return
}
pendingAmount := r.store.GetPendingProtocolFee(tokenPath)
totalAmount := gnsmath.SafeAddInt64(pendingAmount, amount)
if totalAmount > 0 {
protocolFeeAddr := access.MustGetAddress(prbac.ROLE_PROTOCOL_FEE.String())
common.SafeGRC20Approve(0, rlm, tokenPath, protocolFeeAddr, totalAmount)
// AddToProtocolFee only reports an error for a halted realm, which is handled
// above. The branch keeps the amount pending should that ever change, and
// withdraws the approval so no unspent allowance outlives the call.
if err := pf.AddToProtocolFee(cross(rlm), tokenPath, totalAmount); err != nil {
common.SafeGRC20Approve(0, rlm, tokenPath, protocolFeeAddr, 0)
r.addPendingProtocolFee(0, rlm, tokenPath, amount)
return
}
}
if err := r.store.RemovePendingProtocolFee(0, rlm, tokenPath); err != nil {
panic(err)
}
}
func calculateRouterFee(amount int64, swapFee uint64) int64 {
if swapFee <= 0 {
return 0
}
feeAmount := u256.MulDiv(u256.NewUintFromInt64(amount), u256.NewUint(swapFee), u256.NewUint(10000))
return gnsmath.SafeConvertToInt64(feeAmount)
}
// calculate amount to fetch from pool including router fee
// poolAmount = userAmount / (1 - feeRate)
// = userAmount * 10000 / (10000 - swapFeeBPS)
func calculateExactOutWithRouterFee(amount int64, swapFee uint64) int64 {
if amount == 0 {
return amount
}
if swapFee > 0 {
// Use MulDiv to prevent overflow and maintain precision
poolAmount := u256.MulDiv(
u256.NewUintFromInt64(amount),
u256.NewUint(10000),
u256.NewUint(10000-swapFee),
)
return gnsmath.SafeConvertToInt64(poolAmount)
}
return amount
}
render.gno
package router
import (
"chain"
"strings"
"gno.land/p/moul/md/v0"
"gno.land/p/moul/mdtable/v0"
ufmt "gno.land/p/nt/ufmt/v0"
"gno.land/r/gnoswap/halt/v1"
"gno.land/r/gnoswap/router"
)
const maxSwapFeeBPS uint64 = 1000
func (r *routerV1) Render(path string) string {
var action string
switch path {
case "":
action = md.H3("Exact-input single-route swap") + "\n" +
"<gno-form exec=\"ExactInSingleSwapRoute\">\n" +
" <gno-input name=\"inputToken\" type=\"text\" placeholder=\"Approved input: gno.land/r/gnoland/wugnot.wugnot\" required=\"true\" />\n" +
" <gno-input name=\"outputToken\" type=\"text\" placeholder=\"Output: gno.land/r/gnoswap/gns.GNS\" required=\"true\" />\n" +
" <gno-input name=\"amountIn\" type=\"text\" placeholder=\"Exact input amount (base units)\" required=\"true\" />\n" +
" <gno-input name=\"routeArr\" type=\"text\" placeholder=\"Route: inputToken:outputToken:500\" required=\"true\" />\n" +
" <gno-input name=\"amountOutMin\" type=\"text\" placeholder=\"Minimum output amount (base units)\" required=\"true\" />\n" +
" <gno-input name=\"sqrtPriceLimitX96\" type=\"text\" placeholder=\"Q64.96 sqrt-price limit (0 = no limit)\" required=\"true\" />\n" +
" <gno-input name=\"deadline\" type=\"number\" placeholder=\"Future Unix timestamp (seconds)\" required=\"true\" />\n" +
" <gno-input name=\"referrer\" type=\"text\" placeholder=\"Optional referrer address\" />\n" +
"</gno-form>\n"
case "swap/exact-in":
action = md.H3("Exact-input multi-route swap") + "\n" +
"<gno-form exec=\"ExactInSwapRoute\">\n" +
" <gno-input name=\"inputToken\" type=\"text\" placeholder=\"Approved input: gno.land/r/gnoland/wugnot.wugnot\" required=\"true\" />\n" +
" <gno-input name=\"outputToken\" type=\"text\" placeholder=\"Output: gno.land/r/gnoswap/gns.GNS\" required=\"true\" />\n" +
" <gno-input name=\"amountIn\" type=\"text\" placeholder=\"Exact input amount (base units)\" required=\"true\" />\n" +
" <gno-input name=\"routeArr\" type=\"text\" placeholder=\"Routes: A:C:500,A:B:500*POOL*B:C:3000 (A/B/C = token keys)\" required=\"true\" />\n" +
" <gno-input name=\"quoteArr\" type=\"text\" placeholder=\"Route percentages: 100 or 70,30 (total 100)\" required=\"true\" />\n" +
" <gno-input name=\"amountOutMin\" type=\"text\" placeholder=\"Minimum output amount (base units)\" required=\"true\" />\n" +
" <gno-input name=\"deadline\" type=\"number\" placeholder=\"Future Unix timestamp (seconds)\" required=\"true\" />\n" +
" <gno-input name=\"referrer\" type=\"text\" placeholder=\"Optional referrer address\" />\n" +
"</gno-form>\n"
case "swap/exact-out":
action = md.H3("Exact-output multi-route swap") + "\n" +
"<gno-form exec=\"ExactOutSwapRoute\">\n" +
" <gno-input name=\"inputToken\" type=\"text\" placeholder=\"Approved input: gno.land/r/gnoland/wugnot.wugnot\" required=\"true\" />\n" +
" <gno-input name=\"outputToken\" type=\"text\" placeholder=\"Output: gno.land/r/gnoswap/gns.GNS\" required=\"true\" />\n" +
" <gno-input name=\"amountOut\" type=\"text\" placeholder=\"Exact output amount (base units)\" required=\"true\" />\n" +
" <gno-input name=\"routeArr\" type=\"text\" placeholder=\"Routes: A:C:500,A:B:500*POOL*B:C:3000 (A/B/C = token keys)\" required=\"true\" />\n" +
" <gno-input name=\"quoteArr\" type=\"text\" placeholder=\"Route percentages: 100 or 70,30 (total 100)\" required=\"true\" />\n" +
" <gno-input name=\"amountInMax\" type=\"text\" placeholder=\"Maximum input amount (base units)\" required=\"true\" />\n" +
" <gno-input name=\"deadline\" type=\"number\" placeholder=\"Future Unix timestamp (seconds)\" required=\"true\" />\n" +
" <gno-input name=\"referrer\" type=\"text\" placeholder=\"Optional referrer address\" />\n" +
"</gno-form>\n"
case "swap/exact-out-single":
action = md.H3("Exact-output single-route swap") + "\n" +
"<gno-form exec=\"ExactOutSingleSwapRoute\">\n" +
" <gno-input name=\"inputToken\" type=\"text\" placeholder=\"Approved input: gno.land/r/gnoland/wugnot.wugnot\" required=\"true\" />\n" +
" <gno-input name=\"outputToken\" type=\"text\" placeholder=\"Output: gno.land/r/gnoswap/gns.GNS\" required=\"true\" />\n" +
" <gno-input name=\"amountOut\" type=\"text\" placeholder=\"Exact output amount (base units)\" required=\"true\" />\n" +
" <gno-input name=\"routeArr\" type=\"text\" placeholder=\"Route: inputToken:outputToken:500\" required=\"true\" />\n" +
" <gno-input name=\"amountInMax\" type=\"text\" placeholder=\"Maximum input amount (base units)\" required=\"true\" />\n" +
" <gno-input name=\"sqrtPriceLimitX96\" type=\"text\" placeholder=\"Q64.96 sqrt-price limit (0 = no limit)\" required=\"true\" />\n" +
" <gno-input name=\"deadline\" type=\"number\" placeholder=\"Future Unix timestamp (seconds)\" required=\"true\" />\n" +
" <gno-input name=\"referrer\" type=\"text\" placeholder=\"Optional referrer address\" />\n" +
"</gno-form>\n"
default:
return "404\n"
}
swapFee := r.GetSwapFee()
implementation := router.GetImplementationPackagePath()
statusTable := mdtable.Table{
Headers: []string{"Field", "Value"},
Rows: [][]string{
{"Router package", md.Link("gno.land/r/gnoswap/router", "/r/gnoswap/router")},
{"Realm address", md.InlineCode(chain.PackageAddress("gno.land/r/gnoswap/router").String())},
{"Active implementation", md.Link(implementation, strings.TrimPrefix(implementation, "gno.land"))},
{"Router halted", ufmt.Sprintf("%t", halt.IsHaltedRouter())},
},
}
feeTable := mdtable.Table{
Headers: []string{"Field", "Value"},
Rows: [][]string{
{"Swap fee", ufmt.Sprintf("%d bps", swapFee)},
{"Maximum swap fee", ufmt.Sprintf("%d bps (10%%)", maxSwapFeeBPS)},
{"Fee unit", "1 bps = 0.01% of the output-token amount"},
{"Amount unit", "Integer token base units; decimals are token-specific"},
},
}
out := md.H1("Gnoswap Router") + "\n"
out += md.H2("Router status") + "\n"
out += statusTable.String() + "\n"
out += md.H2("Swap fee configuration") + "\n"
out += feeTable.String() + "\n"
out += md.H2("Swap") + "\n"
out += md.Paragraph(
md.Link("Exact input: single route", "/r/gnoswap/router") + " · " +
md.Link("Exact input: multiple routes", "/r/gnoswap/router:swap/exact-in") + " · " +
md.Link("Exact output: single route", "/r/gnoswap/router:swap/exact-out-single") + " · " +
md.Link("Exact output: multiple routes", "/r/gnoswap/router:swap/exact-out"),
)
out += action
return out
}
router.gno
package router
import (
"errors"
"strconv"
ufmt "gno.land/p/nt/ufmt/v0"
)
// ErrorMessages define all error message templates used throughout the router
const (
// slippage validation
errExactInAmountMismatch = "consumed input does not match requested (requested=%d, consumed=%d)"
errExactOutAmountExceeded = "received more than requested in requested=%d, actual=%d"
// route validation
errInvalidRouteLength = "route length(%d) must be 1~7"
// quote validation
errRoutesQuotesMismatch = "mismatch between routes(%d) and quotes(%d) length"
errInvalidQuote = "invalid quote(%s) at index(%d)"
errInvalidQuoteValue = "quote(%s) at index(%d) must be positive value"
errQuoteExceedsMax = "quote(%s) at index(%d) must be less than or equal to %d"
errQuoteSumExceedsMax = "quote sum exceeds 100 at index(%d)"
errInvalidQuoteSum = "quote sum(%d) must be 100"
// swap type validation
errExactInTooFewReceived = "ExactIn: too few received (min:%d, got:%d)"
errExactOutTooMuchSpent = "ExactOut: too much spent (max:%d, used:%d)"
// route parsing validation
errEmptyRoutes = "routes cannot be empty"
)
// SwapValidator provides validation methods for swap operations
type SwapValidator struct{}
// exactOutAmount checks if output amount meets specified requirements.
// For exact-out swaps, the output must be exactly the specified amount with tolerance up to swapCount units for rounding.
func (v *SwapValidator) exactOutAmount(resultAmount, specifiedAmount int64, swapCount int64) error {
diff := int64(0)
if resultAmount >= specifiedAmount {
diff = resultAmount - specifiedAmount
} else {
diff = specifiedAmount - resultAmount
}
if diff > swapCount {
return ufmt.Errorf(errExactOutAmountExceeded, specifiedAmount, resultAmount)
}
return nil
}
// exactInAmount checks that the swap consumed exactly the requested input amount.
func (v *SwapValidator) exactInAmount(resultAmount, specifiedAmount int64) error {
if resultAmount != specifiedAmount {
return ufmt.Errorf(errExactInAmountMismatch, specifiedAmount, resultAmount)
}
return nil
}
// slippage ensures swap amounts meet slippage requirements.
func (v *SwapValidator) slippage(swapType SwapType, amountIn, amountOut, limit int64) error {
switch swapType {
case ExactIn:
if amountOut < limit {
return ufmt.Errorf(errExactInTooFewReceived, limit, amountOut)
}
case ExactOut:
if amountIn > limit {
return ufmt.Errorf(errExactOutTooMuchSpent, limit, amountIn)
}
default:
return errors.New(errInvalidSwapType)
}
return nil
}
// swapType ensures the swap type string is valid.
func (v *SwapValidator) swapType(swapTypeStr string) (SwapType, error) {
swapType, err := trySwapTypeFromStr(swapTypeStr)
if err != nil {
return Unknown, errors.New(errInvalidSwapType)
}
return swapType, nil
}
// amount ensures the amount is properly formatted and positive.
func (v *SwapValidator) amount(amount int64) (int64, error) {
if amount <= 0 {
return 0, ufmt.Errorf(ErrInvalidPositiveAmount, amount)
}
return amount, nil
}
// RouteParser handles parsing and validation of routes and quotes
type RouteParser struct{}
// NewRouteParser creates a parser for comma-separated route and quote strings.
//
// Returns:
// - parser: new RouteParser instance
func NewRouteParser() *RouteParser {
return &RouteParser{}
}
// ParseRoutes splits route and quote strings and validates their pairing.
//
// Parameters:
// - routes: comma-separated route paths
// - quotes: comma-separated route allocation percentages
//
// Returns:
// - routePaths: parsed route path strings
// - quoteValues: parsed quote strings corresponding one-to-one with routePaths
// - err: nil when routes, counts, and quote sum are valid; validation error otherwise
func (p *RouteParser) ParseRoutes(routes, quotes string) ([]string, []string, error) {
// Check for empty routes
if routes == "" || quotes == "" {
return nil, nil, errors.New(errEmptyRoutes)
}
routesArr := splitSingleChar(routes, ',')
quotesArr := splitSingleChar(quotes, ',')
if err := p.ValidateRoutesAndQuotes(routesArr, quotesArr); err != nil {
return nil, nil, err
}
return routesArr, quotesArr, nil
}
// ValidateRoutesAndQuotes checks route count, route/quote cardinality, and quote sum.
//
// Parameters:
// - routes: parsed route path strings
// - quotes: parsed quote percentage strings
//
// Returns:
// - err: nil when one to seven routes match quote count and quotes sum to 100; validation error otherwise
func (p *RouteParser) ValidateRoutesAndQuotes(routes, quotes []string) error {
rr := len(routes)
qq := len(quotes)
if rr < 1 || rr > 7 {
return ufmt.Errorf(errInvalidRouteLength, rr)
}
if rr != qq {
return ufmt.Errorf(errRoutesQuotesMismatch, rr, qq)
}
return p.ValidateQuoteSum(quotes)
}
// ValidateQuoteSum verifies that each quote is positive, at most 100, and totals 100.
//
// Parameters:
// - quotes: route allocation percentage strings
//
// Returns:
// - err: nil when all quotes parse and total 100; invalid value or sum error otherwise
func (p *RouteParser) ValidateQuoteSum(quotes []string) error {
const (
maxQuote int8 = 100
minQuote int8 = 0
)
var sum int8
for i, quote := range quotes {
qt, err := strconv.ParseInt(quote, 10, 8)
if err != nil {
return ufmt.Errorf(errInvalidQuote, quote, i)
}
intQuote := int8(qt)
// Quote must be positive (> 0) as each route needs a non-zero allocation.
// A quote of 0 would mean no swap through that route, which is invalid.
if intQuote <= minQuote { // minQuote = 0, so this rejects quote = 0
return ufmt.Errorf(errInvalidQuoteValue, quote, i)
}
if intQuote > maxQuote {
return ufmt.Errorf(errQuoteExceedsMax, quote, i, maxQuote)
}
if sum > maxQuote-intQuote {
return ufmt.Errorf(errQuoteSumExceedsMax, i)
}
sum += intQuote
}
if sum != maxQuote {
return ufmt.Errorf(errInvalidQuoteSum, sum)
}
return nil
}
// finalizeSwap handles post-swap operations and validations.
func (r *routerV1) finalizeSwap(
_ int,
rlm realm,
inputToken, outputToken string,
resultAmountIn, resultAmountOut int64,
swapType SwapType,
tokenAmountLimit int64,
amountSpecified int64,
swapCount int64,
isSetSqrtPriceLimitX96 bool,
) (int64, int64) {
validator := &SwapValidator{}
// Handle swap fee
resultAmountOutWithoutFee := r.handleSwapFee(0, rlm, outputToken, resultAmountOut)
// Validate the exact-out target when no caller price limit is set. A
// nonzero single-hop limit permits partial output, so only the max-input
// slippage check below remains applicable.
if swapType == ExactOut && !isSetSqrtPriceLimitX96 {
if err := validator.exactOutAmount(resultAmountOutWithoutFee, amountSpecified, swapCount); err != nil {
panic(addDetailToError(errSlippage, err.Error()))
}
}
// Validate exact in amount if applicable
// If sqrtPriceLimitX96 is set, partial consumption up to the price limit is intended
if swapType == ExactIn && !isSetSqrtPriceLimitX96 {
if err := validator.exactInAmount(resultAmountIn, amountSpecified); err != nil {
panic(addDetailToError(errInsufficientLiquidity, err.Error()))
}
}
if err := validator.slippage(swapType, resultAmountIn, resultAmountOutWithoutFee, tokenAmountLimit); err != nil {
panic(addDetailToError(errSlippage, err.Error()))
}
return resultAmountIn, resultAmountOutWithoutFee
}
// validateRoutesAndQuotes is a convenience function that parses and validates routes in one call.
func validateRoutesAndQuotes(routes, quotes string) ([]string, []string, error) {
return NewRouteParser().ParseRoutes(routes, quotes)
}
router_dry.gno
package router
import (
"errors"
"strings"
"gno.land/p/gnoswap/gnsmath/v1"
"gno.land/p/gnoswap/utils/v1"
ufmt "gno.land/p/nt/ufmt/v0"
"gno.land/r/gnoswap/common"
)
// QuoteConstraints defines the valid range for swap quote percentages
const (
MaxQuotePercentage = 100
MinQuotePercentage = 0
PERCENTAGE_DENOMINATOR = int64(100)
)
// ErrorMessages for DrySwapRoute operations
const (
ErrUnknownSwapType = "unknown swapType(%s)"
ErrInvalidPositiveAmount = "invalid amount(%s), must be positive"
ErrInvalidQuoteRange = "quote(%d) must be %d~%d"
)
// SwapProcessor handles the execution of swap operations
type SwapProcessor struct {
router *routerV1
}
// ProcessSingleSwap simulates one pool hop without executing transfers.
//
// Parameters:
// - route: single pool path formatted as TOKEN0:TOKEN1:FEE
// - amountSpecified: signed input or output amount for the hop
//
// Returns:
// - amountIn: input amount the pool would receive
// - amountOut: output amount the pool would send
// - err: always nil when the dry pool call returns; malformed paths or pool failures panic in the underlying helpers
func (p *SwapProcessor) ProcessSingleSwap(route string, amountSpecified int64) (amountIn, amountOut int64, err error) {
input, output, fee := getDataForSinglePath(route)
singleParams := SingleSwapParams{
tokenIn: input,
tokenOut: output,
fee: fee,
amountSpecified: amountSpecified,
}
amountIn, amountOut = p.router.singleDrySwap(&singleParams)
return amountIn, amountOut, nil
}
// ProcessMultiSwap simulates a multi-hop route in the requested direction.
//
// Parameters:
// - swapType: ExactIn for forward execution or ExactOut for backward quoting
// - route: multi-hop path with POOL_SEPARATOR between hops
// - numHops: number of pools in route
// - amountSpecified: signed input or output amount for the route
//
// Returns:
// - amountIn: input amount the route would consume
// - amountOut: output amount the route would produce
// - err: nil on successful simulation; invalid swap-type error or downstream dry-swap validation error otherwise (pool query failures panic)
func (p *SwapProcessor) ProcessMultiSwap(
swapType SwapType,
route string,
numHops int,
amountSpecified int64,
) (int64, int64, error) {
pathIndex := getPathIndex(swapType, numHops)
input, output, fee := getDataForMultiPath(route, pathIndex)
singleParams := SingleSwapParams{
tokenIn: input,
tokenOut: output,
fee: fee,
amountSpecified: amountSpecified,
}
switch swapType {
case ExactIn:
return p.router.multiDrySwap(singleParams, numHops, route)
case ExactOut:
return p.router.multiDrySwapNegative(singleParams, numHops, route)
default:
return 0, 0, ufmt.Errorf(ErrUnknownSwapType, swapType)
}
}
// ValidateSwapResults checks simulated amounts against exactness and slippage constraints.
//
// Parameters:
// - swapType: ExactIn or ExactOut validation direction
// - resultAmountIn: simulated aggregate input amount
// - resultAmountOut: simulated aggregate output amount after router fee
// - amountSpecified: caller's exact input or output target
// - amountLimit: minimum output or maximum input slippage bound
// - swapCount: number of pool hops used for exact-output tolerance
//
// Returns:
// - amountIn: resultAmountIn when validation reaches the return path
// - amountOut: resultAmountOut when validation reaches the return path
// - err: nil when liquidity, exactness, and slippage checks pass; relevant validation error otherwise
func (p *SwapProcessor) ValidateSwapResults(
swapType SwapType,
resultAmountIn, resultAmountOut int64,
amountSpecified, amountLimit int64,
swapCount int64,
) (amountIn, amountOut int64, err error) {
if resultAmountIn == 0 || resultAmountOut == 0 {
return 0, 0, errors.New(errInsufficientLiquidity)
}
validator := &SwapValidator{}
if swapType == ExactOut {
absSpecified := gnsmath.SafeAbsInt64(amountSpecified)
if err := validator.exactOutAmount(resultAmountOut, absSpecified, swapCount); err != nil {
return resultAmountIn, resultAmountOut, err
}
}
if swapType == ExactIn {
if err := validator.exactInAmount(resultAmountIn, amountSpecified); err != nil {
return resultAmountIn, resultAmountOut, err
}
}
if err := validator.slippage(swapType, resultAmountIn, resultAmountOut, amountLimit); err != nil {
return resultAmountIn, resultAmountOut, err
}
return resultAmountIn, resultAmountOut, nil
}
// AddSwapResults adds one route's amounts to accumulated totals using overflow-safe arithmetic.
//
// Parameters:
// - resultAmountIn: accumulated input before this route
// - resultAmountOut: accumulated output before this route
// - amountIn: current route input amount
// - amountOut: current route output amount
//
// Returns:
// - newAmountIn: accumulated input after adding amountIn
// - newAmountOut: accumulated output after adding amountOut
// - err: always nil; overflow is raised by safe arithmetic rather than returned
func (p *SwapProcessor) AddSwapResults(
resultAmountIn, resultAmountOut, amountIn, amountOut int64,
) (int64, int64, error) {
newAmountIn := gnsmath.SafeAddInt64(resultAmountIn, amountIn)
newAmountOut := gnsmath.SafeAddInt64(resultAmountOut, amountOut)
return newAmountIn, newAmountOut, nil
}
// DrySwapRoute simulates a token swap route without executing transfers or changing state.
//
// Parameters:
// - inputToken: input token contract path
// - outputToken: output token contract path
// - specifiedAmount: exact input amount for EXACT_IN or exact output amount for EXACT_OUT
// - swapTypeStr: EXACT_IN or EXACT_OUT
// - strRouteArr: comma-separated route paths, with at most seven route entries
// - quoteArr: comma-separated route allocation percentages summing to 100
// - tokenAmountLimit: minimum output for EXACT_IN or maximum input for EXACT_OUT
//
// Returns:
// - amountIn: simulated input amount encoded as a decimal string
// - amountOut: simulated net output amount encoded as a decimal string
// - err: nil on success; validation, liquidity, parsing, or slippage error otherwise
func (r *routerV1) DrySwapRoute(
inputToken, outputToken string,
specifiedAmount string,
swapTypeStr string,
strRouteArr, quoteArr string,
tokenAmountLimit string,
) (amountIn, amountOut string, err error) {
defer func() {
if r := recover(); r != nil {
amountIn = "0"
amountOut = "0"
if recoveredErr, ok := r.(error); ok {
err = recoveredErr
} else {
err = ufmt.Errorf("%v", r)
}
}
}()
inputAmount, outputAmount, err := r.drySwapRoute(
inputToken,
outputToken,
utils.SafeParseInt64(specifiedAmount),
swapTypeStr,
strRouteArr,
quoteArr,
utils.SafeParseInt64(tokenAmountLimit),
)
return utils.FormatInt(inputAmount), utils.FormatInt(outputAmount), err
}
// drySwapRoute is the internal dry-run swap simulation that returns errors
// instead of panicking on validation or liquidity failures.
func (r *routerV1) drySwapRoute(
inputToken, outputToken string,
specifiedAmount int64,
swapTypeStr string,
strRouteArr, quoteArr string,
tokenAmountLimit int64,
) (int64, int64, error) {
if err := common.ValidateRegistered(inputToken, outputToken); err != nil {
return 0, 0, err
}
assertIsValidRoutePaths(strRouteArr, inputToken, outputToken)
assertIsExistsPools(strRouteArr)
// initialize components
validator := &SwapValidator{}
processor := &SwapProcessor{router: r}
// validate and parse inputs
swapType, err := validator.swapType(swapTypeStr)
if err != nil {
return 0, 0, makeErrorWithDetails(errInvalidSwapType, err.Error())
}
amountSpecified, err := validator.amount(specifiedAmount)
if err != nil {
return 0, 0, makeErrorWithDetails(errInvalidInput, err.Error())
}
routes, quotes, err := NewRouteParser().ParseRoutes(strRouteArr, quoteArr)
if err != nil {
return 0, 0, makeErrorWithDetails(errInvalidRoutesAndQuotes, err.Error())
}
swapFee := r.store.GetSwapFee()
// Store original amount for validation (before router fee adjustment)
originalAmountSpecified := amountSpecified
// adjust amount sign for exact out swaps
if swapType == ExactOut {
absSpecified := gnsmath.SafeAbsInt64(amountSpecified)
amountSpecifiedWithRouterFee := calculateExactOutWithRouterFee(absSpecified, swapFee)
amountSpecified = -amountSpecifiedWithRouterFee
}
// initialize accumulators for swap results
resultAmountIn, resultAmountOut := int64(0), int64(0)
remainRequestAmount := amountSpecified
swapCount := int64(0)
// Process each route
for i, route := range routes {
toSwapAmount := int64(0)
// if it's the last route, use the remaining amount
isLastRoute := i == len(routes)-1
if !isLastRoute {
// calculate the amount to swap for this route
swapAmount, err := calculateSwapAmountByQuote(amountSpecified, quotes[i])
if err != nil {
return 0, 0, err
}
// update the remaining amount
resultRemainRequestAmount := gnsmath.SafeSubInt64(remainRequestAmount, swapAmount)
remainRequestAmount = resultRemainRequestAmount
toSwapAmount = swapAmount
} else {
toSwapAmount = remainRequestAmount
}
// determine the number of hops and validate
numHops := strings.Count(route, POOL_SEPARATOR) + 1
assertHopsInRange(numHops)
// accumulate total swap count for validation
swapCount += int64(numHops)
// execute the appropriate swap type
var amountIn, amountOut int64
if numHops == 1 {
amountIn, amountOut, err = processor.ProcessSingleSwap(route, toSwapAmount)
} else {
amountIn, amountOut, err = processor.ProcessMultiSwap(swapType, route, numHops, toSwapAmount)
}
if err != nil {
return 0, 0, err
}
if amountIn == 0 || amountOut == 0 {
return 0, 0, errors.New(errInsufficientLiquidity)
}
// update accumulated results
resultAmountIn, resultAmountOut, err = processor.AddSwapResults(resultAmountIn, resultAmountOut, amountIn, amountOut)
if err != nil {
return 0, 0, err
}
}
// simulate deduct router fee
feeAmountInt64 := calculateRouterFee(resultAmountOut, swapFee)
resultAmountOut = gnsmath.SafeSubInt64(resultAmountOut, feeAmountInt64)
return processor.ValidateSwapResults(swapType, resultAmountIn, resultAmountOut, originalAmountSpecified, tokenAmountLimit, swapCount)
}
// getPathIndex returns the path index based on swap type and number of hops.
func getPathIndex(swapType SwapType, numHops int) int {
switch swapType {
case ExactIn:
// first data for exact input swaps
return 0
case ExactOut:
// last data for exact output swaps
return numHops - 1
default:
panic("should not happen")
}
}
swap_callback.gno
package router
import (
"errors"
prbac "gno.land/p/gnoswap/rbac/v1"
u256 "gno.land/p/gnoswap/uint256/v1"
ufmt "gno.land/p/nt/ufmt/v0"
"gno.land/r/gnoswap/access/v1"
"gno.land/r/gnoswap/common"
"gno.land/r/gnoswap/halt/v1"
)
// SwapCallback implements the pool's SwapCallback interface.
// The pool invokes it after sending output tokens; the router then transfers the
// positive input delta to the pool.
//
// Parameters:
// - _: leading callback discriminator; callers pass 0
// - rlm: propagated current realm context; must remain the current crossing frame
// - token0Path: token-0 contract path in canonical pool order
// - token1Path: token-1 contract path in canonical pool order
// - amount0Delta: signed token-0 delta; positive means the pool is owed this amount
// - amount1Delta: signed token-1 delta; positive means the pool is owed this amount
// - payer: address whose balance supplies the positive input delta
//
// Returns:
// - err: nil after the owed input transfer; an error for spoofed realm, invalid liquidity delta, or failed payment
//
// Positive deltas are tokens the pool must receive; negative deltas are tokens
// the pool has sent to the recipient.
func (r *routerV1) SwapCallback(
_ int,
rlm realm,
token0Path, token1Path string,
amount0Delta, amount1Delta int64,
payer address,
) error {
if !rlm.IsCurrent() {
return errors.New(errSpoofedRealm)
}
if amount0Delta <= 0 && amount1Delta <= 0 {
return makeErrorWithDetails(
errInsufficientLiquidity,
"swap entirely within 0-liquidity region",
)
}
halt.AssertIsNotHaltedRouter()
caller := rlm.Previous().Address()
assertIsRouterImplementation(caller)
var tokenToPay string
var amountToPay int64
// amount0Delta > 0 means pool wants token0
// amount1Delta > 0 means pool wants token1
if amount0Delta > 0 {
amountToPay = amount0Delta
tokenToPay = token0Path
} else {
amountToPay = amount1Delta
tokenToPay = token1Path
}
// Transfer tokens from router to pool
// The router should already have the tokens from the user
r.transferToPool(0, rlm, tokenToPay, u256.NewUintFromInt64(amountToPay), payer)
return nil
}
// transferToPool transfers tokens from router to pool
func (r *routerV1) transferToPool(_ int, rlm realm, token string, amount *u256.Uint, payer address) {
balance := common.BalanceOf(token, payer)
if u256.NewUintFromInt64(balance).Lt(amount) {
panic(makeErrorWithDetails(
errInsufficientBalance,
ufmt.Sprintf("token=%s, required=%d, available=%d, payer=%s", token, amount.Int64(), balance, payer.String()),
))
}
poolAddr := access.MustGetAddress(prbac.ROLE_POOL.String())
routerAddr := access.MustGetAddress(prbac.ROLE_ROUTER.String())
if payer == routerAddr {
common.SafeGRC20Transfer(0, rlm, token, poolAddr, amount.Int64())
} else {
common.SafeGRC20TransferFrom(0, rlm, token, payer, poolAddr, amount.Int64())
}
}
swap_inner.gno
package router
import (
"gno.land/r/gnoswap/access/v1"
"gno.land/r/gnoswap/router"
i256 "gno.land/p/gnoswap/int256/v1"
u256 "gno.land/p/gnoswap/uint256/v1"
"gno.land/p/gnoswap/utils/v1"
pl "gno.land/r/gnoswap/pool"
)
const (
MIN_SQRT_RATIO_PLUS_ONE string = "4295128740"
MAX_SQRT_RATIO_MINUS_ONE string = "1461446703485210103287273052203988822378723970341"
)
// swapInner executes the core swap logic by interacting with the pool contract.
// Returns poolRecv (tokens received by pool) and poolOut (tokens sent by pool).
func (r *routerV1) swapInner(
_ int,
rlm realm,
amountSpecified int64,
recipient address,
sqrtPriceLimitX96 *u256.Uint,
data SwapCallbackData,
) (int64, int64) {
assertIsRouterProxyRealm(0, rlm)
token0Path, token1Path := data.tokenIn, data.tokenOut
zeroForOne := data.tokenIn < data.tokenOut
if !zeroForOne {
token0Path, token1Path = token1Path, token0Path
}
sqrtPriceLimitStr := calculateSqrtPriceLimitToStr(zeroForOne, sqrtPriceLimitX96)
amount0Str, amount1Str := pl.Swap(
cross(rlm),
token0Path,
token1Path,
data.fee,
recipient,
zeroForOne,
utils.FormatInt(amountSpecified),
sqrtPriceLimitStr,
func(cur realm, amount0Delta, amount1Delta int64, _ *pl.CallbackMarker) error {
// assert is pool to prevent unauthorized callback
caller := cur.Previous().Address()
access.AssertIsPool(caller)
return router.SwapCallback(cross(cur), token0Path, token1Path, amount0Delta, amount1Delta, data.payer)
},
)
amount0 := i256.MustFromDecimal(amount0Str)
amount1 := i256.MustFromDecimal(amount1Str)
poolOut, poolRecv := i256MinMax(amount0, amount1)
if poolRecv.IsOverflow() || poolOut.IsOverflow() {
panic("overflow in swapInner")
}
return poolRecv.Int64(), poolOut.Int64()
}
// swapDryInner performs a dry-run of a swap operation without executing it.
func (r *routerV1) swapDryInner(
amountSpecified int64,
sqrtPriceLimitX96 *u256.Uint,
data SwapCallbackData,
) (int64, int64) {
token0Path, token1Path := data.tokenIn, data.tokenOut
zeroForOne := data.tokenIn < data.tokenOut
if !zeroForOne {
token0Path, token1Path = token1Path, token0Path
}
sqrtPriceLimitStr := calculateSqrtPriceLimitToStr(zeroForOne, sqrtPriceLimitX96)
// check possible
amount0Str, amount1Str, err := pl.DrySwap(
token0Path,
token1Path,
data.fee,
zeroForOne,
utils.FormatInt(amountSpecified),
sqrtPriceLimitStr,
)
if err != nil {
panic(err)
}
amount0 := i256.MustFromDecimal(amount0Str)
amount1 := i256.MustFromDecimal(amount1Str)
if amount0.Sign() <= 0 && amount1.Sign() <= 0 {
panic(makeErrorWithDetails(
errInsufficientLiquidity,
"swap entirely within 0-liquidity region",
))
}
poolOut, poolRecv := i256MinMax(amount0, amount1)
if poolRecv.IsOverflow() || poolOut.IsOverflow() {
panic("overflow in swapDryInner")
}
return poolRecv.Int64(), poolOut.Int64()
}
// calculateSqrtPriceLimitToStr returns the price-limit string for a swap operation.
// A non-zero caller limit is formatted as-is; a zero limit uses the global
// TickMath boundary for the swap direction.
func calculateSqrtPriceLimitToStr(zeroForOne bool, sqrtPriceLimitX96 *u256.Uint) string {
if !sqrtPriceLimitX96.IsZero() {
return sqrtPriceLimitX96.ToString()
}
if zeroForOne {
return MIN_SQRT_RATIO_PLUS_ONE
}
return MAX_SQRT_RATIO_MINUS_ONE
}
swap_multi.gno
package router
import (
prbac "gno.land/p/gnoswap/rbac/v1"
u256 "gno.land/p/gnoswap/uint256/v1"
"gno.land/r/gnoswap/access/v1"
)
// multiSwap performs a multi-hop exact-input swap in forward order.
func (r *routerV1) multiSwap(_ int, rlm realm, sp SwapParams, numPools int, swapPath string) (int64, int64) {
payer := rlm.Previous().Address()
routerAddr := access.MustGetAddress(prbac.ROLE_ROUTER.String())
firstAmountIn := int64(0)
for currentPoolIndex := 0; ; currentPoolIndex++ {
callbackData := newSwapCallbackData(sp, payer)
amountIn, amountOut := r.swapInner(
0,
rlm,
sp.amountSpecified,
sp.recipient,
u256.Zero(),
callbackData,
)
// every hop of a forward multi-hop swap is exact-in
assertHopFullyConsumed(currentPoolIndex, sp.amountSpecified, amountIn)
if currentPoolIndex == 0 {
firstAmountIn = amountIn
}
nextPoolIndex := currentPoolIndex + 1
if nextPoolIndex >= numPools {
return firstAmountIn, amountOut
}
payer = routerAddr
nextInput, nextOutput, nextFee := getDataForMultiPath(swapPath, nextPoolIndex)
sp.tokenIn = nextInput
sp.tokenOut = nextOutput
sp.fee = nextFee
sp.amountSpecified = amountOut
}
}
// multiSwapNegative performs a multi-hop exact-output swap. It first quotes
// every hop backward, then executes the collected swaps forward.
func (r *routerV1) multiSwapNegative(_ int, rlm realm, sp SwapParams, numPools int, swapPath string) (int64, int64) {
swapInfo := r.collectBackwardDrySwapInfo(sp.SingleSwapParams, numPools, swapPath)
return r.executeCollectedSwaps(0, rlm, swapInfo, sp.recipient)
}
// multiDrySwap simulates a multi-hop exact-input swap in forward order.
func (r *routerV1) multiDrySwap(sp SingleSwapParams, numPools int, swapPath string) (int64, int64, error) {
firstAmountIn := int64(0)
for currentPoolIndex := 0; ; currentPoolIndex++ {
amountIn, amountOut := r.swapDryInner(
sp.amountSpecified,
u256.Zero(),
newDrySwapCallbackData(sp),
)
// mirror the real-swap full-consumption guard so dry runs predict reverts
err := validateHopFullyConsumed(currentPoolIndex, sp.amountSpecified, amountIn)
if err != nil {
return 0, 0, err
}
if currentPoolIndex == 0 {
firstAmountIn = amountIn
}
nextPoolIndex := currentPoolIndex + 1
if nextPoolIndex >= numPools {
return firstAmountIn, amountOut, nil
}
nextInput, nextOutput, nextFee := getDataForMultiPath(swapPath, nextPoolIndex)
sp.tokenIn = nextInput
sp.tokenOut = nextOutput
sp.fee = nextFee
sp.amountSpecified = amountOut
}
}
// multiDrySwapNegative simulates a multi-hop exact-output swap.
// It first quotes every hop backward, then simulates the collected swaps forward.
func (r *routerV1) multiDrySwapNegative(sp SingleSwapParams, numPools int, swapPath string) (int64, int64, error) {
swapInfo := r.collectBackwardDrySwapInfo(sp, numPools, swapPath)
return r.executeCollectedDrySwaps(swapInfo)
}
// collectBackwardDrySwapInfo quotes an exact-output route backward before real execution.
func (r *routerV1) collectBackwardDrySwapInfo(sp SingleSwapParams, numPools int, swapPath string) []SingleSwapParams {
swapInfo := make([]SingleSwapParams, 0, numPools)
for currentPoolIndex := numPools - 1; currentPoolIndex >= 0; currentPoolIndex-- {
amountIn, _ := r.singleDrySwap(&sp)
swapInfo = append(swapInfo, sp)
if currentPoolIndex == 0 {
break
}
nextPoolIndex := currentPoolIndex - 1
nextInput, nextOutput, nextFee := getDataForMultiPath(swapPath, nextPoolIndex)
sp.tokenIn = nextInput
sp.tokenOut = nextOutput
sp.fee = nextFee
sp.amountSpecified = -amountIn
}
return swapInfo
}
// executeCollectedSwaps executes the backward-quoted exact-output swaps in forward order.
func (r *routerV1) executeCollectedSwaps(_ int, rlm realm, swapInfo []SingleSwapParams, recipient address) (int64, int64) {
payer := rlm.Previous().Address()
routerAddr := access.MustGetAddress(prbac.ROLE_ROUTER.String())
firstAmountIn := int64(0)
for currentPoolIndex := len(swapInfo) - 1; currentPoolIndex >= 0; currentPoolIndex-- {
amountIn, amountOut := r.swapInner(
0,
rlm,
swapInfo[currentPoolIndex].amountSpecified,
recipient,
u256.Zero(),
newSwapCallbackData(swapInfo[currentPoolIndex], payer),
)
// hops re-specified from the previous hop's actual output run as exact-in
// (positive amountSpecified) and must consume that amount entirely
if spec := swapInfo[currentPoolIndex].amountSpecified; spec > 0 {
assertHopFullyConsumed(currentPoolIndex, spec, amountIn)
}
if currentPoolIndex == len(swapInfo)-1 {
firstAmountIn = amountIn
}
if currentPoolIndex == 0 {
return firstAmountIn, amountOut
}
nextPoolIndex := currentPoolIndex - 1
swapInfo[nextPoolIndex].amountSpecified = amountOut
payer = routerAddr
}
return firstAmountIn, 0
}
func (r *routerV1) executeCollectedDrySwaps(swapInfo []SingleSwapParams) (int64, int64, error) {
firstAmountIn := int64(0)
for currentPoolIndex := len(swapInfo) - 1; currentPoolIndex >= 0; currentPoolIndex-- {
amountIn, amountOut := r.swapDryInner(
swapInfo[currentPoolIndex].amountSpecified,
u256.Zero(),
newDrySwapCallbackData(swapInfo[currentPoolIndex]),
)
// mirror the real-swap full-consumption guard so dry runs predict reverts
if spec := swapInfo[currentPoolIndex].amountSpecified; spec > 0 {
err := validateHopFullyConsumed(currentPoolIndex, spec, amountIn)
if err != nil {
return 0, 0, err
}
}
if currentPoolIndex == len(swapInfo)-1 {
firstAmountIn = amountIn
}
if currentPoolIndex == 0 {
return firstAmountIn, amountOut, nil
}
nextPoolIndex := currentPoolIndex - 1
swapInfo[nextPoolIndex].amountSpecified = amountOut
}
return firstAmountIn, 0, nil
}
swap_single.gno
package router
import (
prbac "gno.land/p/gnoswap/rbac/v1"
u256 "gno.land/p/gnoswap/uint256/v1"
"gno.land/r/gnoswap/access/v1"
)
// singleSwap executes a swap within a single pool using the provided parameters.
// It processes a token swap within two assets using a specific fee tier and
// automatically sets the recipient to the caller's address.
func (r *routerV1) singleSwap(_ int, rlm realm, p *SingleSwapParams) (int64, int64) {
assertSingleSwap(p)
caller := rlm.Previous().Address()
recipient := access.MustGetAddress(prbac.ROLE_ROUTER.String())
return r.swapInner(
0,
rlm,
p.amountSpecified,
recipient,
p.SqrtPriceLimitX96(),
newSwapCallbackData(p, caller),
)
}
// singleDrySwap simulates a single-token swap operation without executing it.
func (r *routerV1) singleDrySwap(p *SingleSwapParams) (int64, int64) {
assertSingleSwap(p)
return r.swapDryInner(
p.amountSpecified,
u256.Zero(),
newDrySwapCallbackData(p),
)
}
type.gno
package router
import (
u256 "gno.land/p/gnoswap/uint256/v1"
ufmt "gno.land/p/nt/ufmt/v0"
)
const (
rawUnknown = "UNKNOWN"
rawExactIn = "EXACT_IN"
rawExactOut = "EXACT_OUT"
zeroAddress = address("")
)
type SwapType string
const (
Unknown SwapType = rawUnknown
// ExactIn represents a swap type where the input amount is exact and the output amount may vary.
// Used when a user wants to swap a specific amount of input tokens.
ExactIn SwapType = rawExactIn
// ExactOut represents a swap type where the output amount is exact and the input amount may vary.
// Used when a user wants to swap a specific amount of output tokens.
ExactOut SwapType = rawExactOut
)
// trySwapTypeFromStr attempts to convert a string into a SwapType.
// It validates and converts string representations of swap types into their corresponding enum values.
func trySwapTypeFromStr(swapType string) (SwapType, error) {
switch swapType {
case rawExactIn:
return ExactIn, nil
case rawExactOut:
return ExactOut, nil
default:
return "", ufmt.Errorf("unknown swapType: expected ExactIn or ExactOut, got %s", swapType)
}
}
// String returns the wire-format string for a SwapType.
//
// Returns:
// - swapType: EXACT_IN or EXACT_OUT for known values, or an empty string for Unknown
func (s SwapType) String() string {
switch s {
case ExactIn:
return rawExactIn
case ExactOut:
return rawExactOut
default:
return ""
}
}
// SingleSwapParams contains parameters for executing a single pool swap.
// It represents the simplest form of swap that occurs within a single liquidity pool.
type SingleSwapParams struct {
tokenIn string // token to spend
tokenOut string // token to receive
fee uint32 // fee of the pool used to swap
// Amount specified for the swap:
// - Positive: exact input amount (tokenIn)
// - Negative: exact output amount (tokenOut)
amountSpecified int64
sqrtPriceLimitX96 *u256.Uint // sqrtPriceLimitX96 for the swap, empty string or zero string means no limit
}
// TokenIn returns the input token contract path.
//
// Returns:
// - tokenIn: token spent by this single-pool swap
func (p SingleSwapParams) TokenIn() string { return p.tokenIn }
// TokenOut returns the output token contract path.
//
// Returns:
// - tokenOut: token received by this single-pool swap
func (p SingleSwapParams) TokenOut() string { return p.tokenOut }
// Fee returns the pool fee tier.
//
// Returns:
// - fee: fee tier encoded as the pool's uint32 fee value
func (p SingleSwapParams) Fee() uint32 { return p.fee }
// SqrtPriceLimitX96 returns the optional Q64.96 square-root price limit.
// A nil stored limit is normalized to the zero value, which callers interpret as no explicit limit.
//
// Returns:
// - limit: configured Q64.96 price limit, or a zero uint when no limit was supplied
func (p SingleSwapParams) SqrtPriceLimitX96() *u256.Uint {
if p.sqrtPriceLimitX96 == nil {
return u256.Zero()
}
return p.sqrtPriceLimitX96
}
// SwapParams contains parameters for executing a multi-hop swap operation.
type SwapParams struct {
SingleSwapParams
recipient address // address to receive the token
}
// TokenIn returns the input token contract path.
//
// Returns:
// - tokenIn: token spent by this multi-hop swap parameters object
func (p SwapParams) TokenIn() string { return p.tokenIn }
// TokenOut returns the output token contract path.
//
// Returns:
// - tokenOut: token received by this multi-hop swap parameters object
func (p SwapParams) TokenOut() string { return p.tokenOut }
// Fee returns the pool fee tier.
//
// Returns:
// - fee: fee tier encoded as the pool's uint32 fee value
func (p SwapParams) Fee() uint32 { return p.fee }
// Recipient returns the address that receives swap output.
//
// Returns:
// - recipient: configured output recipient address
func (p SwapParams) Recipient() address { return p.recipient }
// newSwapParams creates a new SwapParams instance with the provided parameters.
func newSwapParams(tokenIn, tokenOut string, fee uint32, recipient address, amountSpecified int64) *SwapParams {
return &SwapParams{
SingleSwapParams: SingleSwapParams{
tokenIn: tokenIn,
tokenOut: tokenOut,
fee: fee,
amountSpecified: amountSpecified,
},
recipient: recipient,
}
}
// SwapResult encapsulates the outcome of a swap operation.
type SwapResult struct {
Routes []string
Quotes []string
AmountIn int64
AmountOut int64
AmountSpecified int64
}
// SwapParamsI defines the common interface for swap parameters.
type SwapParamsI interface {
// TokenIn returns the input token path required by swap processing.
//
// Returns:
// - tokenIn: token spent by the swap
TokenIn() string
// TokenOut returns the output token path required by swap processing.
//
// Returns:
// - tokenOut: token received by the swap
TokenOut() string
// Fee returns the pool fee tier required by swap processing.
//
// Returns:
// - fee: pool fee tier
Fee() uint32
}
// 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 SwapCallbackData struct {
tokenIn string // token to spend
tokenOut string // token to receive
fee uint32 // fee of the pool used to swap
payer address // address to spend the token
}
// newSwapCallbackData creates a new SwapCallbackData from a SwapParamsI.
func newSwapCallbackData(params SwapParamsI, payer address) SwapCallbackData {
return SwapCallbackData{
tokenIn: params.TokenIn(),
tokenOut: params.TokenOut(),
fee: params.Fee(),
payer: payer,
}
}
// newDrySwapCallbackData creates callback data for a dry swap. The payer is
// deliberately the zero address because dry swaps do not execute callbacks or
// token transfers.
func newDrySwapCallbackData(params SwapParamsI) SwapCallbackData {
return SwapCallbackData{
tokenIn: params.TokenIn(),
tokenOut: params.TokenOut(),
fee: params.Fee(),
payer: zeroAddress,
}
}
// ExactInParams contains parameters for exact input swaps.
type ExactInParams struct {
BaseSwapParams
AmountIn int64
AmountOutMin int64
}
// NewExactInParams creates parameters for an exact-input swap.
//
// Parameters:
// - baseParams: shared token, route, quote, price-limit, and deadline settings
// - amountIn: exact input amount in token units; must be positive before execution
// - amountOutMin: minimum acceptable output amount in token units
//
// Returns:
// - params: exact-input parameters combining baseParams and amount limits
func NewExactInParams(
baseParams BaseSwapParams,
amountIn int64,
amountOutMin int64,
) ExactInParams {
return ExactInParams{
BaseSwapParams: baseParams,
AmountIn: amountIn,
AmountOutMin: amountOutMin,
}
}
// ExactOutParams contains parameters for exact output swaps.
type ExactOutParams struct {
BaseSwapParams
AmountOut int64
AmountInMax int64
}
// NewExactOutParams creates parameters for an exact-output swap.
//
// Parameters:
// - baseParams: shared token, route, quote, price-limit, and deadline settings
// - amountOut: requested output amount in token units; must be positive before execution
// - amountInMax: maximum acceptable input amount in token units
//
// Returns:
// - params: exact-output parameters combining baseParams and amount limits
func NewExactOutParams(
baseParams BaseSwapParams,
amountOut int64,
amountInMax int64,
) ExactOutParams {
return ExactOutParams{
BaseSwapParams: baseParams,
AmountOut: amountOut,
AmountInMax: amountInMax,
}
}
utils.gno
package router
import (
"bytes"
"errors"
"strconv"
"strings"
gnsmath "gno.land/p/gnoswap/gnsmath/v1"
"gno.land/p/gnoswap/utils/v1"
ufmt "gno.land/p/nt/ufmt/v0"
"gno.land/r/gnoswap/pool"
i256 "gno.land/p/gnoswap/int256/v1"
u256 "gno.land/p/gnoswap/uint256/v1"
)
// calculateSwapAmountByQuote calculates swap amount based on quote percentage.
func calculateSwapAmountByQuote(amountSpecified int64, quote string) (int64, error) {
quoteInt, err := strconv.ParseInt(quote, 10, 64)
if err != nil {
return 0, ufmt.Errorf("invalid quote(%s)", quote)
}
if quoteInt < MinQuotePercentage || quoteInt > MaxQuotePercentage {
return 0, ufmt.Errorf(ErrInvalidQuoteRange, quoteInt, MinQuotePercentage, MaxQuotePercentage)
}
toSwap := gnsmath.SafeMulDivInt64(amountSpecified, quoteInt, PERCENTAGE_DENOMINATOR)
if toSwap == 0 {
return 0, errors.New(errInvalidSwapAmount)
}
return toSwap, nil
}
// assertHopsInRange ensures the number of hops is within the valid range of 1-3.
func assertHopsInRange(hops int) {
switch hops {
case 1, 2, 3:
return
default:
panic(errors.New(errHopsOutOfRange))
}
}
// getDataForSinglePath extracts token addresses and fee from a single pool path.
//
// IMPORTANT: This function returns tokens in the order they appear in the route string,
// which represents the swap direction (tokenIn:tokenOut:fee), NOT the canonical pool ordering.
func getDataForSinglePath(poolPath string) (token0, token1 string, fee uint32) {
token0, token1, fee, err := getDataForSinglePathWithError(poolPath)
if err != nil {
panic(err)
}
return token0, token1, fee
}
// getDataForSinglePathWithError extracts token addresses and fee from a single pool path with error handling.
func getDataForSinglePathWithError(poolPath string) (string, string, uint32, error) {
poolPathSplit := strings.Split(poolPath, ":")
if len(poolPathSplit) != 3 {
return "", "", 0, makeErrorWithDetails(
errInvalidPoolPath,
ufmt.Sprintf("len(poolPathSplit) != 3, poolPath: %s", poolPath),
)
}
poolPathSplit[0] = strings.TrimSpace(poolPathSplit[0])
poolPathSplit[1] = strings.TrimSpace(poolPathSplit[1])
if poolPathSplit[0] == "" || poolPathSplit[1] == "" {
return "", "", 0, makeErrorWithDetails(
errInvalidPoolPath,
ufmt.Sprintf("token addresses cannot be empty: %s", poolPath),
)
}
f, err := strconv.Atoi(poolPathSplit[2])
if err != nil {
return "", "", 0, makeErrorWithDetails(
errInvalidPoolPath,
ufmt.Sprintf("invalid fee: %s", poolPathSplit[2]),
)
}
return poolPathSplit[0], poolPathSplit[1], uint32(f), nil
}
// getDataForMultiPath extracts token addresses and fee from a multi-hop path at specified index.
func getDataForMultiPath(possiblePath string, poolIdx int) (token0, token1 string, fee uint32) {
pools := strings.Split(possiblePath, POOL_SEPARATOR)
switch poolIdx {
case 0:
return getDataForSinglePath(pools[0])
case 1:
return getDataForSinglePath(pools[1])
case 2:
return getDataForSinglePath(pools[2])
default:
return "", "", uint32(0)
}
}
// i256MinMax returns the absolute values of x and y in min-max order.
func i256MinMax(x, y *i256.Int) (min, max *u256.Uint) {
if x.Lt(y) || x.Eq(y) {
return x.Abs(), y.Abs()
}
return y.Abs(), x.Abs()
}
// validateRoutePaths validates multiple route paths to ensure they all start with inputToken and end with outputToken.
// This function processes comma-separated route paths and validates each path individually.
//
// Validates:
// - Each route path starts with the specified inputToken
// - Each route path ends with the specified outputToken
// - Route path format consistency (prevents swap-direction vs alphabetical pool ordering confusion)
//
// Parameters:
// - routePathArrString: comma-separated route paths (e.g., "gno.land/r/gnoland/wugnot.wugnot:gno.land/r/gnoswap/gns.GNS:500,gno.land/r/gnoland/wugnot.wugnot:gno.land/r/gnoswap/gns.GNS:3000")
// - inputToken: expected first token in all route paths
// - outputToken: expected last token in all route paths
//
// Examples:
// - Single route: "tokenA:tokenB:500" with inputToken="tokenA", outputToken="tokenB"
// - Multi-route: "tokenA:tokenB:500,tokenA:tokenC:3000*POOL*tokenC:tokenB:500" with inputToken="tokenA", outputToken="tokenB"
//
// Returns error if any route path validation fails.
func validateRoutePaths(routePathArrString, inputToken, outputToken string) error {
routePaths := strings.Split(routePathArrString, ",")
for _, routePath := range routePaths {
if err := validateRoutePath(routePath, inputToken, outputToken); err != nil {
return err
}
}
return nil
}
// validateRoutePath validates a single route path to ensure it starts with inputToken and ends with outputToken.
// This function handles both single-hop and multi-hop route paths.
//
// Validates:
// - Route path starts with the specified inputToken
// - Route path ends with the specified outputToken
// - Proper token ordering in swap direction (not alphabetical pool ordering)
//
// Route Path Formats:
// - single-hop: "tokenA:tokenB:fee" (direct swap between two tokens)
// - multi-hop: "tokenA:tokenB:fee1*POOL*tokenB:tokenC:fee2" (swap through intermediate tokens)
//
// Parameters:
// - routePath: single route path string (e.g., "gno.land/r/gnoland/wugnot.wugnot:gno.land/r/gnoswap/gns.GNS:500")
// - inputToken: expected first token in the route path
// - outputToken: expected last token in the route path
//
// Examples:
// - single-hop: "tokenA:tokenB:500" with inputToken="tokenA", outputToken="tokenB"
// - multi-hop: "tokenA:tokenB:3000*POOL*tokenB:tokenC:500" with inputToken="tokenA", outputToken="tokenC"
//
// Returns error with specific details if validation fails.
func validateRoutePath(routePath, inputToken, outputToken string) error {
// Extract first and last tokens from the routePath
var (
firstToken, lastToken string
err error
)
// multi-hop routePath
if strings.Contains(routePath, POOL_SEPARATOR) {
pools := strings.Split(routePath, POOL_SEPARATOR)
// Get first token from first pool
firstPool := pools[0]
firstToken, _, _, err = getDataForSinglePathWithError(firstPool)
if err != nil {
return err
}
// Validate hop-to-hop continuity: output token of hop N must equal input token of hop N+1
err = validatePoolPathHopContinuity(pools)
if err != nil {
return err
}
// Get last token from last pool
lastPool := pools[len(pools)-1]
_, lastToken, _, err = getDataForSinglePathWithError(lastPool)
if err != nil {
return err
}
} else {
// single-hop routePath
firstToken, lastToken, _, err = getDataForSinglePathWithError(routePath)
if err != nil {
return err
}
}
if firstToken == "" || lastToken == "" {
return makeErrorWithDetails(errInvalidRoutePath, ufmt.Sprintf("firstToken: %s, lastToken: %s", firstToken, lastToken))
}
// Validate consistency
if firstToken != inputToken {
return makeErrorWithDetails(errInvalidRouteFirstToken, ufmt.Sprintf("firstToken: %s, inputToken: %s", firstToken, inputToken))
}
if lastToken != outputToken {
return makeErrorWithDetails(errInvalidRouteLastToken, ufmt.Sprintf("lastToken: %s, outputToken: %s", lastToken, outputToken))
}
return nil
}
func validatePoolPathHopContinuity(routePoolPaths []string) error {
if len(routePoolPaths) < 2 {
return nil
}
_, previousOut, _, pErr := getDataForSinglePathWithError(routePoolPaths[0])
if pErr != nil {
return pErr
}
for i := 1; i < len(routePoolPaths); i++ {
nextIn, nextOut, _, nErr := getDataForSinglePathWithError(routePoolPaths[i])
if nErr != nil {
return nErr
}
if previousOut != nextIn {
return makeErrorWithDetails(
errRouteHopDisconnected,
ufmt.Sprintf("hop %d output(%s) != hop %d input(%s)", i-1, previousOut, i, nextIn),
)
}
previousOut = nextOut
}
return nil
}
// splitSingleChar splits a string by a single character separator.
// This function is optimized for splitting strings with a single-byte separator
// and is more memory efficient than strings.Split for this use case.
func splitSingleChar(s string, sep byte) []string {
if s == "" {
return []string{""}
}
result := make([]string, 0, bytes.Count([]byte(s), []byte{sep})+1)
start := 0
for i := range s {
if s[i] == sep {
result = append(result, s[start:i])
start = i + 1
}
}
result = append(result, s[start:])
return result
}
// parsePoolPathsByRoutePathArr parses route path array string and returns a slice of pool paths.
// This function converts route paths (which maintain swap direction) into canonical pool paths
// (which use alphabetical token ordering).
//
// The function processes comma-separated route paths and extracts individual pool information
// from each route, ensuring tokens are ordered alphabetically for consistent pool identification.
//
// Parameters:
// - routePathArr: comma-separated route paths string containing single or multi-hop routes
// Format examples:
// - Single route: "tokenA:tokenB:500"
// - Multiple routes: "tokenA:tokenB:500,tokenC:tokenD:3000"
// - Multi-hop routes: "tokenA:tokenB:500*POOL*tokenB:tokenC:3000"
//
// Returns:
// - []string: slice of canonical pool paths with alphabetically ordered tokens
// - error: parsing error if any route path is invalid
//
// Example:
//
// input: "gno.land/r/gnoland/wugnot.wugnot:gno.land/r/gnoswap/gns.GNS:500,gno.land/r/gnoland/wugnot.wugnot:gno.land/r/gnoswap/gns.GNS:3000"
// output: ["gno.land/r/gnoswap/gns.GNS:gno.land/r/gnoland/wugnot.wugnot:500", "gno.land/r/gnoswap/gns.GNS:gno.land/r/gnoland/wugnot.wugnot:3000"]
func parsePoolPathsByRoutePathArr(routePathArr string) ([]string, error) {
poolPaths := make([]string, 0)
for _, routePaths := range strings.Split(routePathArr, ",") {
for _, routePath := range strings.Split(routePaths, POOL_SEPARATOR) {
token0Path, token1Path, fee, err := getDataForSinglePathWithError(routePath)
if err != nil {
return []string{}, err
}
if token0Path > token1Path {
token0Path, token1Path = token1Path, token0Path
}
poolPath := pool.GetPoolPath(token0Path, token1Path, fee)
poolPaths = append(poolPaths, poolPath)
}
}
return poolPaths, nil
}
// BuildSingleHopRoutePath formats one route-direction single-hop path.
//
// Parameters:
// - tokenA: input token contract path
// - tokenB: output token contract path
// - fee: pool fee tier appended as a decimal value
//
// Returns:
// - routePath: tokenA:tokenB:fee formatted route string; panics for empty or identical tokens
func BuildSingleHopRoutePath(tokenA, tokenB string, fee uint32) string {
if tokenA == "" || tokenB == "" {
panic("token addresses cannot be empty")
}
if tokenA == tokenB {
panic("tokenA and tokenB cannot be the same")
}
return tokenA + ":" + tokenB + ":" + utils.FormatUint(fee)
}