-
Notifications
You must be signed in to change notification settings - Fork 1
/
router.gno
225 lines (191 loc) · 7.5 KB
/
router.gno
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package router
import (
"std"
"strconv"
"strings"
"gno.land/p/demo/ufmt"
"gno.land/r/demo/gnoswap/common"
"gno.land/r/demo/gnoswap/consts"
i256 "gno.land/p/demo/gnoswap/int256"
u256 "gno.land/p/demo/gnoswap/uint256"
"gno.land/r/demo/wugnot"
)
// SwapRoute swaps the input token to the output token and returns the result amount
// If swapType is EXACT_IN, it returns the amount of output token ≈ amount of user to receive
// If swapType is EXACT_OUT, it returns the amount of input token ≈ amount of user to pay
//
// Panics if any of the following conditions are met:
// - amountSpecified is zero or is not numeric
// - swapType is not EXACT_IN or EXACT_OUT
// - length of route and quotes are not the same
// - length of routes is not 1 ~ 7
// - sum of quotes is not 100
// - number of hops is not 1 ~ 3
// - too many token spend or too few token received
func SwapRoute(
inputToken string,
outputToken string,
_amountSpecified string, // int256
swapType string,
strRouteArr string, // []string
quoteArr string, // []int
_tokenAmountLimit string, // uint256
) (string, string) { // tokneIn, tokenOut
if common.GetLimitCaller() {
isUserCalled := std.PrevRealm().PkgPath() == ""
if !isUserCalled {
panic("[ROUTER] router.gno__SwapRoute() || only user can call this function")
}
}
amountSpecified := i256.MustFromDecimal(_amountSpecified)
if amountSpecified.IsZero() {
panic("[ROUTER] router.gno__SwapRoute() || amountSpecified == 0")
}
if amountSpecified.IsNeg() {
panic("[ROUTER] router.gno__SwapRoute() || amountSpecified < 0")
}
tokenAmountLimit := u256.MustFromDecimal(_tokenAmountLimit)
switch swapType {
case "EXACT_IN":
// do nothing
case "EXACT_OUT":
amountSpecified = i256.Zero().Neg(amountSpecified)
default:
panic("[ROUTER] router.gno__SwapRoute() || unknown swapType")
}
// check route length ( should be 1 ~ 7 )
routes := strings.Split(strRouteArr, ",")
isValidRouteLength := (1 <= len(routes)) && (len(routes) <= 7)
if !isValidRouteLength {
panic(ufmt.Sprintf("[ROUTER] router.gno__SwapRoute() || len(routes) should be 1 ~ 7 (len(routes)[%d])", len(routes)))
}
// check if routes length and quotes length are same
quotes := strings.Split(quoteArr, ",")
if len(routes) != len(quotes) {
panic(ufmt.Sprintf("[ROUTER] router.gno__SwapRoute() || len(routes[%d]) != len(quotes[%d])", len(routes), len(quotes)))
}
// check if quotes are up to 100%
quotesSum := int64(0)
for _, quote := range quotes {
intQuote, _ := strconv.Atoi(quote)
quotesSum += int64(intQuote)
}
if quotesSum != 100 {
panic(ufmt.Sprintf("[ROUTER] router.gno__SwapRoute() || quotesSum != 100 (quotesSum)[%d]", quotesSum))
}
// if input is gnot, wrap it
userOldWugnotBalance := uint64(0)
if inputToken == consts.GNOT {
sent := std.GetOrigSend()
ugnotSentByUser := uint64(sent.AmountOf("ugnot"))
wrap(ugnotSentByUser)
userOldWugnotBalance = wugnot.BalanceOf(a2u(std.GetOrigCaller()))
} else if outputToken == consts.GNOT { // if output is gnot unwrap later (save user's current wugnot balance)
userOldWugnotBalance = wugnot.BalanceOf(a2u(std.GetOrigCaller()))
}
resultAmountIn := u256.Zero()
resultAmountOut := u256.Zero()
for i, route := range routes {
numHops := strings.Count(route, "*POOL*") + 1
quote, _ := strconv.Atoi(quotes[i])
if numHops < 1 || numHops > 3 {
panic(ufmt.Sprintf("[ROUTER] router.gno__SwapRoute() || numHops should be 1 ~ 3 (numHops)[%d]", numHops))
}
toSwap := i256.Zero().Mul(amountSpecified, i256.NewInt(int64(quote)))
toSwap = toSwap.Div(toSwap, i256.NewInt(100))
if numHops == 1 { // SINGLE
amountIn, amountOut := handleSingleSwap(route, toSwap, false)
resultAmountIn = new(u256.Uint).Add(resultAmountIn, amountIn)
resultAmountOut = new(u256.Uint).Add(resultAmountOut, amountOut)
} else if numHops == 2 || numHops == 3 { // MULTI
amountIn, amountOut := handleMultiSwap(swapType, route, numHops, toSwap, false)
resultAmountIn = new(u256.Uint).Add(resultAmountIn, amountIn)
resultAmountOut = new(u256.Uint).Add(resultAmountOut, amountOut)
} else {
panic("[ROUTER] router.gno__SwapRoute() || numHops should be 1 ~ 3")
}
}
// PROTOCOL FEE
resultAmountOut = handleProtocolFee(outputToken, resultAmountOut, false)
// UNWRAP IF NECESSARY
// if input was gnot, refund left over wugnot
if inputToken == consts.GNOT {
userNewWugnotBalance := wugnot.BalanceOf(a2u(std.GetOrigCaller()))
unwrap(userNewWugnotBalance)
} else if outputToken == consts.GNOT { // if output was gnot, unwrap result
userNewWugnotBalance := wugnot.BalanceOf(a2u(std.GetOrigCaller()))
userRecvWugnot := uint64(userNewWugnotBalance - userOldWugnotBalance) // received wugnot
unwrap(userRecvWugnot)
}
if swapType == "EXACT_IN" {
if !(tokenAmountLimit.Lte(resultAmountOut)) {
panic(ufmt.Sprintf("[ROUTER] router.gno__SwapRoute() || too few received for user (expected minimum received:%s, actual received:%s)", _tokenAmountLimit, resultAmountOut.ToString()))
}
} else { // EXACT_OUT
if !(resultAmountIn.Lte(tokenAmountLimit)) {
panic(ufmt.Sprintf("[ROUTER] router.gno__SwapRoute() || too much spend for user (expected maximum spend:%s, actual spend:%s)", _tokenAmountLimit, resultAmountIn.ToString()))
}
}
//return resultAmountIn.ToString(), resultAmountOut.ToString()
intAmountOut := i256.FromUint256(resultAmountOut)
return resultAmountIn.ToString(), i256.Zero().Neg(intAmountOut).ToString()
}
func handleSingleSwap(route string, amountSpecified *i256.Int, isDry bool) (*u256.Uint, *u256.Uint) {
input, output, fee := getDataForSinglePath(route)
singleParams := SingleSwapParams{
tokenIn: input,
tokenOut: output,
fee: fee,
amountSpecified: amountSpecified,
}
if isDry {
return singleSwapDry(singleParams)
}
return singleSwap(singleParams)
}
func handleMultiSwap(swapType string, route string, numHops int, amountSpecified *i256.Int, isDry bool) (*u256.Uint, *u256.Uint) {
switch swapType {
case "EXACT_IN":
input, output, fee := getDataForMultiPath(route, 0) // first data
swapParams := SwapParams{
tokenIn: input,
tokenOut: output,
fee: fee,
recipient: std.GetOrigCaller(),
amountSpecified: amountSpecified,
}
if isDry {
return multiSwapDry(swapParams, 0, numHops, route) // iterate here
}
return multiSwap(swapParams, 0, numHops, route) // iterate here
case ExactOut:
input, output, fee := getDataForMultiPath(route, numHops-1) // last data
swapParams := SwapParams{
tokenIn: input,
tokenOut: output,
fee: fee,
recipient: std.GetOrigCaller(),
amountSpecified: amountSpecified,
}
if isDry {
return multiSwapNegativeDry(swapParams, numHops-1, route) // iterate here
}
return multiSwapNegative(swapParams, numHops-1, route) // iterate here
default:
panic("[ROUTER] router.gno__handleMultiSwap() || unknown swapType")
}
}
func handleProtocolFee(outputToken string, amount *u256.Uint, isDry bool) *u256.Uint {
if consts.PROTOCOL_FEE_ROUTER <= 0 { // r3v4_xxx: CHANGABLE BY GOV
return amount
}
feeAmount := new(u256.Uint).Mul(amount, u256.NewUint(consts.PROTOCOL_FEE_ROUTER))
feeAmount.Div(feeAmount, u256.NewUint(10000))
if !isDry {
ok := transferFromByRegisterCall(outputToken, std.GetOrigCaller(), consts.FEE_COLLECTOR, feeAmount.Uint64())
if !ok {
panic(ufmt.Sprintf("[ROUTER] router.gno__handleProtocolFee() || expected transferFromByRegisterCall(%s, %s, %s, %s) == true", outputToken, std.GetOrigCaller(), consts.FEE_COLLECTOR, feeAmount.ToString()))
}
}
return new(u256.Uint).Sub(amount, feeAmount)
}