-
Notifications
You must be signed in to change notification settings - Fork 18
/
dodov2.go
344 lines (278 loc) · 8.75 KB
/
dodov2.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
// Copyright 2022 Fluidity Money. All rights reserved. Use of this
// source code is governed by a GPL-style license that can be found in the
// LICENSE.md file.
package dodo
import (
"fmt"
"math"
"math/big"
"sort"
"github.com/fluidity-money/fluidity-app/common/ethereum"
"github.com/fluidity-money/fluidity-app/lib/log"
"github.com/fluidity-money/fluidity-app/lib/types/applications"
"github.com/fluidity-money/fluidity-app/lib/types/worker"
ethAbi "github.com/ethereum/go-ethereum/accounts/abi"
ethCommon "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
ethTypes "github.com/fluidity-money/fluidity-app/lib/types/ethereum"
)
const dodoV2DODOSwapLogTopic = "0xc2c0245e056d5fb095f04cd6373bc770802ebd1e6c918eb78fdef843cdb37b0f"
const DodoV2SwapAbiString = `[
{
"inputs": [],
"name": "_LP_FEE_RATE_",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "address",
"name": "fromToken",
"type": "address"
},
{
"indexed": false,
"internalType": "address",
"name": "toToken",
"type": "address"
},
{
"indexed": false,
"internalType": "uint256",
"name": "fromAmount",
"type": "uint256"
},
{
"indexed": false,
"internalType": "uint256",
"name": "toAmount",
"type": "uint256"
},
{
"indexed": false,
"internalType": "address",
"name": "trader",
"type": "address"
},
{
"indexed": false,
"internalType": "address",
"name": "receiver",
"type": "address"
}
],
"name": "DODOSwap",
"type": "event"
}]`
const ERC20AbiString = `[
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "from",
"type": "address"
},
{
"indexed": true,
"name": "to",
"type": "address"
},
{
"indexed": false,
"name": "value",
"type": "uint256"
}
],
"name": "Transfer",
"type": "event"
}]`
var dodoV2SwapAbi ethAbi.ABI
var erc20Abi ethAbi.ABI
// GetDodoV2Fees calculates fees from DODOSwap, consisting of LiquidityPool (lp) Fees taken from the
// contract, and Maintenance Fees (mt) sent to the _MAINTAINER_, if any
func GetDodoV2Fees(transfer worker.EthereumApplicationTransfer, client *ethclient.Client, fluidTokenContract ethCommon.Address, tokenDecimals int, txReceipt ethTypes.Receipt) (applications.ApplicationFeeData, error) {
var feeData applications.ApplicationFeeData
if len(transfer.Log.Topics) < 1 {
return feeData, fmt.Errorf("Not enough log topics passed!")
}
logTopic := transfer.Log.Topics[0].String()
if logTopic != dodoV2DODOSwapLogTopic {
return feeData, nil
}
unpacked, err := dodoV2SwapAbi.Unpack("DODOSwap", transfer.Log.Data)
if err != nil {
return feeData, fmt.Errorf(
"Failed to unpack swap log data! %v",
err,
)
}
if len(unpacked) != 6 {
return feeData, fmt.Errorf(
"Unpacked the wrong number of values! Expected %v, got %v",
6,
len(unpacked),
)
}
swapAmounts_ := unpacked[2:4]
swapAmounts, err := ethereum.CoerceBoundContractResultsToRats(swapAmounts_)
if err != nil {
return feeData, fmt.Errorf(
"Failed to coerce swap log data to rats! %v",
err,
)
}
addresses_ := []interface{}{unpacked[0], unpacked[1], unpacked[5]}
addresses, err := ethereum.CoerceBoundContractResultsToAddresses(addresses_)
if err != nil {
return feeData, fmt.Errorf(
"Failed to coerce swap log data to addresses! %v",
err,
)
}
var (
// swap logs
// fromToken is the address of tokenA
fromToken = addresses[0]
// toToken is the address of tokenB
toToken = addresses[1]
// fromAmount is the amount of tokenA swapped
fromAmount = swapAmounts[0]
// toAmount is the amount of tokenB swapped
toAmount = swapAmounts[1]
// receiver is the proxy of the swap maker
receiver = addresses[2]
// whether the token being swapped to is the fluid token
toTokenIsFluid = toToken == fluidTokenContract
// whether the transfer contains any fluid tokens
transferHasFluidToken = toTokenIsFluid || (fromToken == fluidTokenContract)
)
if !transferHasFluidToken {
log.App(func(k *log.Log) {
k.Format(
"Received a Dodo swap in transaction %#v not involving the fluid token - skipping!",
transfer.TransactionHash.String(),
)
})
return feeData, nil
}
if toTokenIsFluid {
feeData.Volume = new(big.Rat).Set(toAmount)
} else {
feeData.Volume = new(big.Rat).Set(fromAmount)
}
// Find lpFeeRate via call to contract
contractAddress := ethereum.ConvertInternalAddress(transfer.Log.Address)
lpFeeRate_, err := ethereum.StaticCall(client, contractAddress, dodoV2SwapAbi, "_LP_FEE_RATE_")
if err != nil {
return feeData, fmt.Errorf(
"Failed to fetch fees! %v",
err,
)
}
lpFeeRate, err := ethereum.CoerceBoundContractResultsToRat(lpFeeRate_)
// Dodo hardcodes denom as 10**18
dodoFeeDecimals := 18
dodoDecimalsAdjusted := math.Pow10(dodoFeeDecimals)
dodoDecimalsRat := new(big.Rat).SetFloat64(dodoDecimalsAdjusted)
// Adjust lpFeeRate by decimals to get rate
lpFeeRate.Quo(lpFeeRate, dodoDecimalsRat)
// Find mtBaseTokenFee by taking last log. If last log was a transfer to
// the sender, mtBaseTokenFee is 0
txHash := ethereum.ConvertInternalHash(transfer.TransactionHash)
txLogs := txReceipt.Logs
// Binary search through logs until we find matching log
swapLogBlockIndex := uint(transfer.Log.Index.Uint64())
swapLogTxIndex := sort.Search(len(txLogs), func(i int) bool {
// txLogs.Index sorted in ascending order, so use >= op
return uint(txLogs[i].Index.Uint64()) >= swapLogBlockIndex
})
if swapLogTxIndex == len(txLogs) {
return feeData, fmt.Errorf(
"failed to find matching log from txHash (%v) at Index (%v)!",
txHash.String(),
swapLogBlockIndex,
)
}
if swapLogTxIndex == 0 {
return feeData, fmt.Errorf(
"found index too small to find matching transfer for DODO (%v)! %v",
txHash.String(),
err,
)
}
// prevTransferLog is a transfer either to the receiver, or maintainer.
// If there are no mtFees, the prev log will be to the receiver
prevTransferLog := txLogs[swapLogTxIndex-1]
// Default mtFees to 0
mtToTokenFee := big.NewRat(0, 1)
prevTransferLogReceiver_ := prevTransferLog.Topics[2].String()
prevTransferLogReceiver := ethCommon.HexToAddress(prevTransferLogReceiver_)
if prevTransferLogReceiver != receiver {
// last transfer were mtFees, update mtFee amount
unpacked, err = erc20Abi.Unpack("Transfer", prevTransferLog.Data)
if err != nil {
return feeData, fmt.Errorf(
"Failed to unpack transfer log data! %v",
err,
)
}
if len(unpacked) != 1 {
return feeData, fmt.Errorf(
"Unpacked the wrong number of values! Expected %v, got %v",
1,
len(unpacked),
)
}
mtToTokenFee, err = ethereum.CoerceBoundContractResultsToRat(unpacked)
if err != nil {
return feeData, fmt.Errorf(
"Failed to coerce transfer log data to rat! %v",
err,
)
}
}
fluidFee := calculateDodoV2Fee(fromAmount, toAmount, lpFeeRate, mtToTokenFee, toTokenIsFluid)
// adjust by decimals to get the price in USD
decimalsAdjusted := math.Pow10(tokenDecimals)
decimalsRat := new(big.Rat).SetFloat64(decimalsAdjusted)
fluidFee.Quo(fluidFee, decimalsRat)
feeData.Volume.Quo(feeData.Volume, decimalsRat)
feeData.Fee = fluidFee
return feeData, nil
}
// DODO calculates fees via dynamic maintenance (mt) and static (lp) fees
// All calculations are wrapped in toToken
//
// getQuote(fromAmount) -> quote - (quote * lpRate) - mtFee -> toAmount
//
// calculateDodoFee performs the reverse operation to get total toTokenFee
//
// toAmount + mtFee -> mtAdjustedAmt / (1 - lpRate) -> getQuote(fromAmount)
//
// If necessary, calculateDodoFee will approximate the conversion from toTokenFee to fromTokenFee
func calculateDodoV2Fee(fromAmount, toAmount, lpFeeRate, mtToTokenFee *big.Rat, toTokenIsFluid bool) *big.Rat {
mtAdjustedToAmount := new(big.Rat).Add(toAmount, mtToTokenFee)
// reverseLpFeeRate = (1 - lpRate)
reverseLpFeeRate := new(big.Rat).Sub(big.NewRat(1, 1), lpFeeRate)
// toTokenQuote is equivalent to fromAmount, ignoring slippage from getQuote
toTokenQuote := new(big.Rat).Quo(mtAdjustedToAmount, reverseLpFeeRate)
lpToTokenFee := new(big.Rat).Sub(toTokenQuote, mtAdjustedToAmount)
totalToTokenFee := new(big.Rat).Add(lpToTokenFee, mtToTokenFee)
if toTokenIsFluid {
return totalToTokenFee
}
toTokenToFromTokenRatio := new(big.Rat).Quo(fromAmount, toTokenQuote)
totalFromTokenFee := new(big.Rat).Mul(totalToTokenFee, toTokenToFromTokenRatio)
return totalFromTokenFee
}