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

2.41 Kb · 67 lines
 1package dca
 2
 3import (
 4	prbac "gno.land/p/gnoswap/rbac/v1"
 5	ufmt "gno.land/p/nt/ufmt/v0"
 6
 7	"gno.land/r/gnoswap/access/v1"
 8	"gno.land/r/gnoswap/common"
 9	"gno.land/r/gnoswap/pool"
10)
11
12// NewSwapCallback returns the callback of one round's pool.Swap. It pays the
13// pool the round input, at most maxAmountIn of tokenIn, from the escrow.
14//
15// The callback is declared in this realm, so it transfers as the escrow
16// itself: the escrow never grants an allowance for a swap. That makes the
17// callback a payment capability, so it is guarded on creation and on use:
18//
19//   - only the escrow's own current realm can create one, so only code the
20//     proxy hands its realm to (the active implementation) can;
21//   - only the pool can invoke it (cur.Previous()); the pool's swap lock
22//     admits no other swap while a round's swap runs;
23//   - it pays only while a round is executing, once, and only an exact-input
24//     delta of the sold token: positive input, no positive output, at most
25//     maxAmountIn.
26//
27// zeroForOne is the swap direction: it selects which pool delta is tokenIn.
28func NewSwapCallback(_ int, rlm realm, tokenIn string, zeroForOne bool, maxAmountIn int64) func(cur realm, amount0Delta, amount1Delta int64, _ *pool.CallbackMarker) error {
29	if !rlm.IsCurrent() || rlm.Address() != Address() {
30		panic(ErrSpoofedRealm)
31	}
32
33	if maxAmountIn <= 0 {
34		panic(makeErrorWithDetails(ErrInvalidSwapCallback, ufmt.Sprintf("maxAmountIn(%d)", maxAmountIn)).Error())
35	}
36
37	poolAddress := access.MustGetAddress(prbac.ROLE_POOL.String())
38	paid := false
39
40	// The marker is not checked: pool.NewCallbackMarker is public, so it
41	// proves nothing about the caller. The caller check below does.
42	return func(cur realm, amount0Delta, amount1Delta int64, _ *pool.CallbackMarker) error {
43		if cur.Previous().Address() != poolAddress {
44			return makeErrorWithDetails(ErrInvalidSwapCallback, "caller is not the pool")
45		}
46
47		if paid || !NewDCAOrderStore(kvStore).IsExecuting() {
48			return makeErrorWithDetails(ErrInvalidSwapCallback, "no round swap awaits payment")
49		}
50
51		input, output := amount0Delta, amount1Delta
52		if !zeroForOne {
53			input, output = amount1Delta, amount0Delta
54		}
55
56		if input <= 0 || output > 0 || input > maxAmountIn {
57			return makeErrorWithDetails(
58				ErrInvalidSwapCallback,
59				ufmt.Sprintf("input(%d) output(%d) maxAmountIn(%d)", input, output, maxAmountIn),
60			)
61		}
62
63		paid = true
64
65		return common.Transfer(0, cur, tokenIn, poolAddress, input)
66	}
67}