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

swap_callback.gno

1.40 Kb · 42 lines
 1package limit
 2
 3import (
 4	"errors"
 5
 6	prbac "gno.land/p/gnoswap/rbac/v1"
 7	"gno.land/r/gnoswap/access/v1"
 8	"gno.land/r/gnoswap/common"
 9	"gno.land/r/gnoswap/pool"
10)
11
12// NewSwapCallback binds payment to this proxy's custody, the order's input
13// token and its input budget. Only code already executing in the proxy's current
14// realm context can create it. The closure is declared here so pool callbacks
15// retain proxy custody rather than paying from an implementation realm.
16func NewSwapCallback(_ int, rlm realm, tokenIn string, zeroForOne bool, maxAmountIn int64) func(cur realm, amount0Delta, amount1Delta int64, marker *pool.CallbackMarker) error {
17	if !rlm.IsCurrent() || rlm.Address() != Address() || tokenIn == "" || maxAmountIn <= 0 {
18		panic(errInvalidSwapCallback)
19	}
20
21	poolAddress := access.MustGetAddress(prbac.ROLE_POOL.String())
22	remaining := maxAmountIn
23
24	return func(cur realm, amount0Delta, amount1Delta int64, marker *pool.CallbackMarker) error {
25		if !cur.IsCurrent() || cur.Address() != Address() || cur.Previous().Address() != poolAddress || marker == nil {
26			return errors.New(errInvalidSwapCallback)
27		}
28
29		input, output := amount0Delta, amount1Delta
30		if !zeroForOne {
31			input, output = amount1Delta, amount0Delta
32		}
33
34		if input <= 0 || output > 0 || input > remaining {
35			return errors.New(errInvalidSwapCallback)
36		}
37
38		remaining -= input
39
40		return common.Transfer(0, cur, tokenIn, poolAddress, input)
41	}
42}