forked from daoleno/uniswapv3-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
swaprouter.go
278 lines (249 loc) · 8.25 KB
/
swaprouter.go
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
package periphery
import (
_ "embed"
"errors"
"math/big"
core "github.com/daoleno/uniswap-sdk-core/entities"
"github.com/ethereum/go-ethereum/common"
"github.com/vazha/uniswapv3-sdk/constants"
"github.com/vazha/uniswapv3-sdk/entities"
"github.com/vazha/uniswapv3-sdk/utils"
)
//go:embed contracts/SwapRouter.sol/SwapRouter.json
var swapRouterABI []byte
var (
ErrTokenInDiff = errors.New("TOKEN_IN_DIFF")
ErrTokenOutDiff = errors.New("TOKEN_OUT_DIFF")
ErrNonTokenPermit = errors.New("NON_TOKEN_PERMIT")
ErrMultiHopPriceLimit = errors.New("MULTIHOP_PRICE_LIMIT")
)
// Options for producing the arguments to send calls to the router.
type SwapOptions struct {
SlippageTolerance *core.Percent // How much the execution price is allowed to move unfavorably from the trade execution price.
Recipient common.Address // The account that should receive the output.
Deadline *big.Int // When the transaction expires, in epoch seconds.
InputTokenPermit *PermitOptions // The optional permit parameters for spending the input.
SqrtPriceLimitX96 *big.Int // The optional price limit for the trade.
Fee *FeeOptions // Optional information for taking a fee on output.
}
type ExactInputSingleParams struct {
TokenIn common.Address
TokenOut common.Address
Fee *big.Int
Recipient common.Address
Deadline *big.Int
AmountIn *big.Int
AmountOutMinimum *big.Int
SqrtPriceLimitX96 *big.Int
}
type ExactOutputSingleParams struct {
TokenIn common.Address
TokenOut common.Address
Fee *big.Int
Recipient common.Address
Deadline *big.Int
AmountOut *big.Int
AmountInMaximum *big.Int
SqrtPriceLimitX96 *big.Int
}
type ExactInputParams struct {
Path []byte
Recipient common.Address
Deadline *big.Int
AmountIn *big.Int
AmountOutMinimum *big.Int
}
type ExactOutputParams struct {
Path []byte
Recipient common.Address
Deadline *big.Int
AmountOut *big.Int
AmountInMaximum *big.Int
}
// Represents the Uniswap V3 SwapRouter
/**
* Produces the on-chain method name to call and the hex encoded parameters to pass as arguments for a given trade.
* @param trade to produce call parameters for
* @param options options for the call parameters
*/
func SwapCallParameters(trades []*entities.Trade, options *SwapOptions) (*utils.MethodParameters, error) {
abi := GetABI(swapRouterABI)
sampleTrade := trades[0]
tokenIn := sampleTrade.InputAmount().Currency.Wrapped()
tokenOut := sampleTrade.OutputAmount().Currency.Wrapped()
// All trades should have the same starting and ending token.
for _, trade := range trades {
if !trade.InputAmount().Currency.Wrapped().Equal(tokenIn) {
return nil, ErrTokenInDiff
}
if !trade.OutputAmount().Currency.Wrapped().Equal(tokenOut) {
return nil, ErrTokenOutDiff
}
}
var calldatas [][]byte
ZeroIn := core.FromRawAmount(trades[0].InputAmount().Currency, big.NewInt(0))
ZeroOut := core.FromRawAmount(trades[0].OutputAmount().Currency, big.NewInt(0))
totalAmountOut := ZeroOut
for _, trade := range trades {
minOut, err := trade.MinimumAmountOut(options.SlippageTolerance, nil)
if err != nil {
return nil, err
}
totalAmountOut = totalAmountOut.Add(minOut)
}
// flag for whether a refund needs to happen
mustRefund := sampleTrade.InputAmount().Currency.IsNative() && sampleTrade.TradeType == core.ExactOutput
inputIsNative := sampleTrade.InputAmount().Currency.IsNative()
// flags for whether funds should be send first to the router
outputIsNative := sampleTrade.OutputAmount().Currency.IsNative()
routerMustCustody := outputIsNative || options.Fee != nil
totalValue := ZeroIn
if inputIsNative {
for _, trade := range trades {
maxIn, err := trade.MaximumAmountIn(options.SlippageTolerance, nil)
if err != nil {
return nil, err
}
totalValue = totalValue.Add(maxIn)
}
}
// encode permit if necessary
if options.InputTokenPermit != nil {
if !sampleTrade.InputAmount().Currency.IsToken() {
return nil, ErrNonTokenPermit
}
permit, err := EncodePermit(tokenIn, options.InputTokenPermit)
if err != nil {
return nil, err
}
calldatas = append(calldatas, permit)
}
recipient := options.Recipient
if routerMustCustody {
recipient = constants.AddressZero
}
sqrtPriceLimitX96 := big.NewInt(0)
if options != nil && options.SqrtPriceLimitX96 != nil {
sqrtPriceLimitX96 = options.SqrtPriceLimitX96
}
for _, trade := range trades {
for _, swap := range trade.Swaps {
amountIn, err := trade.MaximumAmountIn(options.SlippageTolerance, swap.InputAmount)
if err != nil {
return nil, err
}
amountOut, err := trade.MinimumAmountOut(options.SlippageTolerance, swap.OutputAmount)
if err != nil {
return nil, err
}
// flag for whether the trade is single hop or not
singleHop := len(swap.Route.Pools) == 1
if singleHop {
if trade.TradeType == core.ExactInput {
exactInputSingleParams := &ExactInputSingleParams{
TokenIn: swap.Route.TokenPath[0].Address,
TokenOut: swap.Route.TokenPath[1].Address,
Fee: big.NewInt(int64(swap.Route.Pools[0].Fee)),
Recipient: recipient,
Deadline: options.Deadline,
AmountIn: amountIn.Quotient(),
AmountOutMinimum: amountOut.Quotient(),
SqrtPriceLimitX96: sqrtPriceLimitX96,
}
calldata, err := abi.Pack("exactInputSingle", exactInputSingleParams)
if err != nil {
return nil, err
}
calldatas = append(calldatas, calldata)
} else {
exactOutputSingleParams := &ExactOutputSingleParams{
TokenIn: swap.Route.TokenPath[0].Address,
TokenOut: swap.Route.TokenPath[1].Address,
Fee: big.NewInt(int64(swap.Route.Pools[0].Fee)),
Recipient: recipient,
Deadline: options.Deadline,
AmountOut: amountOut.Quotient(),
AmountInMaximum: amountIn.Quotient(),
SqrtPriceLimitX96: sqrtPriceLimitX96,
}
calldata, err := abi.Pack("exactOutputSingle", exactOutputSingleParams)
if err != nil {
return nil, err
}
calldatas = append(calldatas, calldata)
}
} else {
if options != nil && options.SqrtPriceLimitX96 != nil {
return nil, ErrMultiHopPriceLimit
}
path, err := EncodeRouteToPath(swap.Route, trade.TradeType == core.ExactOutput)
if err != nil {
return nil, err
}
if trade.TradeType == core.ExactInput {
exactInputParams := &ExactInputParams{
Path: path,
Recipient: recipient,
Deadline: options.Deadline,
AmountIn: amountIn.Quotient(),
AmountOutMinimum: amountOut.Quotient(),
}
calldata, err := abi.Pack("exactInput", exactInputParams)
if err != nil {
return nil, err
}
calldatas = append(calldatas, calldata)
} else {
exactOutputParams := &ExactOutputParams{
Path: path,
Recipient: recipient,
Deadline: options.Deadline,
AmountOut: amountOut.Quotient(),
AmountInMaximum: amountIn.Quotient(),
}
calldata, err := abi.Pack("exactOutput", exactOutputParams)
if err != nil {
return nil, err
}
calldatas = append(calldatas, calldata)
}
}
}
}
// unwrap
if routerMustCustody {
if options.Fee != nil {
if outputIsNative {
calldata, err := EncodeUnwrapWETH9(totalAmountOut.Quotient(), options.Recipient, options.Fee)
if err != nil {
return nil, err
}
calldatas = append(calldatas, calldata)
} else {
calldata, err := EncodeSweepToken(tokenOut, totalAmountOut.Quotient(), options.Recipient, options.Fee)
if err != nil {
return nil, err
}
calldatas = append(calldatas, calldata)
}
} else {
calldata, err := EncodeUnwrapWETH9(totalAmountOut.Quotient(), options.Recipient, nil)
if err != nil {
return nil, err
}
calldatas = append(calldatas, calldata)
}
}
// refund
if mustRefund {
calldatas = append(calldatas, EncodeRefundETH())
}
call, err := EncodeMulticall(calldatas)
if err != nil {
return nil, err
}
return &utils.MethodParameters{
Calldata: call,
Value: totalValue.Quotient(),
}, nil
}