-
Notifications
You must be signed in to change notification settings - Fork 126
/
syncswap.go
240 lines (207 loc) · 7.51 KB
/
syncswap.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
package quotes
import (
"fmt"
"math/big"
"time"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/layer-3/clearsync/pkg/debounce"
"github.com/layer-3/clearsync/pkg/safe"
"github.com/ethereum/go-ethereum/common"
"github.com/ipfs/go-log/v2"
"github.com/shopspring/decimal"
"github.com/layer-3/clearsync/pkg/abi/isyncswap_factory"
"github.com/layer-3/clearsync/pkg/abi/isyncswap_pool"
)
var loggerSyncswap = log.Logger("syncswap")
type syncswap struct {
stablePoolMarkets map[Market]struct{}
classicPoolFactoryAddress common.Address
stablePoolFactoryAddress common.Address
classicFactory *isyncswap_factory.ISyncSwapFactory
stableFactory *isyncswap_factory.ISyncSwapFactory
assets *safe.Map[string, poolToken]
client *ethclient.Client
}
func newSyncswap(config SyncswapConfig, outbox chan<- TradeEvent) Driver {
stablePoolMarkets := make(map[Market]struct{})
for _, rawMarket := range config.StablePoolMarkets {
market, ok := NewMarketFromString(rawMarket)
if !ok {
loggerSyncswap.Errorw("failed to parse stable pool from market", "market", rawMarket)
continue
}
stablePoolMarkets[market] = struct{}{}
}
loggerSyncswap.Debugw("configured stable pool markets", "markets", stablePoolMarkets)
hooks := &syncswap{
stablePoolMarkets: stablePoolMarkets,
classicPoolFactoryAddress: common.HexToAddress(config.ClassicPoolFactoryAddress),
stablePoolFactoryAddress: common.HexToAddress(config.StablePoolFactoryAddress),
}
params := baseDexConfig[
isyncswap_pool.ISyncSwapPoolSwap,
isyncswap_pool.ISyncSwapPool,
]{
// Params
DriverType: DriverSyncswap,
URL: config.URL,
AssetsURL: config.AssetsURL,
MappingURL: config.MappingURL,
// Hooks
PostStartHook: hooks.postStart,
PoolGetter: hooks.getPool,
EventParser: hooks.parseSwap,
// State
Outbox: outbox,
Logger: loggerSyncswap,
Filter: config.Filter,
}
return newBaseDEX(params)
}
func (s *syncswap) postStart(driver *baseDEX[isyncswap_pool.ISyncSwapPoolSwap, isyncswap_pool.ISyncSwapPool]) (err error) {
s.client = driver.Client()
s.assets = driver.Assets()
// Check addresses here: https://syncswap.gitbook.io/syncswap/smart-contracts/smart-contracts
s.classicFactory, err = isyncswap_factory.NewISyncSwapFactory(s.classicPoolFactoryAddress, s.client)
if err != nil {
return fmt.Errorf("failed to instantiate a Quickswap classic pool factory contract: %w", err)
}
s.stableFactory, err = isyncswap_factory.NewISyncSwapFactory(s.stablePoolFactoryAddress, s.client)
if err != nil {
return fmt.Errorf("failed to instantiate a Quickswap stable pool factory contract: %w", err)
}
return nil
}
func (s *syncswap) getPool(market Market) ([]*dexPool[isyncswap_pool.ISyncSwapPoolSwap], error) {
baseToken, quoteToken, err := getTokens(s.assets, market, loggerSyncswap)
if err != nil {
return nil, fmt.Errorf("failed to get tokens: %w", err)
}
var poolAddress common.Address
if _, ok := s.stablePoolMarkets[market]; ok {
loggerSyncswap.Infow("searching for stable pool", "market", market, "address", poolAddress)
err = debounce.Debounce(loggerSyncswap, func() error {
poolAddress, err = s.stableFactory.GetPool(nil, baseToken.Address, quoteToken.Address)
return err
})
loggerSyncswap.Infow("found stable pool", "market", market)
} else {
loggerSyncswap.Infow("searching for classic pool", "market", market)
err = debounce.Debounce(loggerSyncswap, func() error {
poolAddress, err = s.classicFactory.GetPool(nil, baseToken.Address, quoteToken.Address)
return err
})
loggerSyncswap.Infow("found classic pool", "market", market, "address", poolAddress)
}
if err != nil {
return nil, fmt.Errorf("failed to get classic pool address: %w", err)
}
zeroAddress := common.HexToAddress("0x0")
if poolAddress == zeroAddress {
return nil, fmt.Errorf("classic pool for market %s does not exist", market)
}
loggerSyncswap.Infow("pool found", "market", market, "address", poolAddress)
poolContract, err := isyncswap_pool.NewISyncSwapPool(poolAddress, s.client)
if err != nil {
return nil, fmt.Errorf("failed to build Syncswap pool contract: %w", err)
}
var basePoolToken common.Address
err = debounce.Debounce(loggerSyncswap, func() error {
basePoolToken, err = poolContract.Token0(nil)
return err
})
if err != nil {
return nil, fmt.Errorf("failed to get base token address for Syncswap pool: %w", err)
}
var quotePoolToken common.Address
err = debounce.Debounce(loggerSyncswap, func() error {
quotePoolToken, err = poolContract.Token1(nil)
return err
})
if err != nil {
return nil, fmt.Errorf("failed to get quote token address for Syncswap pool: %w", err)
}
isReversed := quoteToken.Address == basePoolToken && baseToken.Address == quotePoolToken
pools := []*dexPool[isyncswap_pool.ISyncSwapPoolSwap]{{
Contract: poolContract,
Address: poolAddress,
BaseToken: baseToken,
QuoteToken: quoteToken,
Market: market,
Reversed: isReversed,
}}
// Return pools if the token addresses match direct or reversed configurations
if (baseToken.Address == basePoolToken && quoteToken.Address == quotePoolToken) || isReversed {
return pools, nil
}
return nil, fmt.Errorf("failed to build Syncswap pool for market %s: %w", market, err)
}
func (s *syncswap) parseSwap(
swap *isyncswap_pool.ISyncSwapPoolSwap,
pool *dexPool[isyncswap_pool.ISyncSwapPoolSwap],
) (trade TradeEvent, err error) {
defer func() {
if r := recover(); r != nil {
loggerSyncswap.Errorw(ErrSwapParsing.Error(), "swap", swap, "pool", pool)
err = fmt.Errorf("%s: %s", ErrSwapParsing, r)
}
}()
return buildV2Trade(
DriverSyncswap,
swap.Amount0In,
swap.Amount0Out,
swap.Amount1In,
swap.Amount1Out,
pool,
)
}
func buildV2Trade[Event any](
driver DriverType,
rawAmount0In, rawAmount0Out, rawAmount1In, rawAmount1Out *big.Int,
pool *dexPool[Event],
) (TradeEvent, error) {
if pool.Reversed {
copyAmount0In, copyAmount0Out := rawAmount0In, rawAmount0Out
rawAmount0In, rawAmount0Out = rawAmount1In, rawAmount1Out
rawAmount1In, rawAmount1Out = copyAmount0In, copyAmount0Out
}
var takerType TakerType
var price decimal.Decimal
var amount decimal.Decimal
var total decimal.Decimal
baseDecimals := pool.BaseToken.Decimals
quoteDecimals := pool.QuoteToken.Decimals
switch {
case isValidNonZero(rawAmount0In) && isValidNonZero(rawAmount1Out):
amount1Out := decimal.NewFromBigInt(rawAmount1Out, 0).Div(decimal.NewFromInt(10).Pow(quoteDecimals))
amount0In := decimal.NewFromBigInt(rawAmount0In, 0).Div(decimal.NewFromInt(10).Pow(baseDecimals))
takerType = TakerTypeSell
price = amount1Out.Div(amount0In) // NOTE: may panic here if `amount0In` is zero
total = amount1Out
amount = amount0In
case isValidNonZero(rawAmount0Out) && isValidNonZero(rawAmount1In):
amount0Out := decimal.NewFromBigInt(rawAmount0Out, 0).Div(decimal.NewFromInt(10).Pow(baseDecimals))
amount1In := decimal.NewFromBigInt(rawAmount1In, 0).Div(decimal.NewFromInt(10).Pow(quoteDecimals))
takerType = TakerTypeBuy
price = amount1In.Div(amount0Out) // NOTE: may panic here if `amount0Out` is zero
total = amount1In
amount = amount0Out
default:
return TradeEvent{}, fmt.Errorf("market %s: unknown swap type", pool.Market)
}
trade := TradeEvent{
Source: driver,
Market: pool.Market,
Price: price,
Amount: amount.Abs(),
Total: total,
TakerType: takerType,
CreatedAt: time.Now(),
}
return trade, nil
}
func isValidNonZero(x *big.Int) bool {
// Note that negative values are allowed
// as they represent a reduction in the balance of the pool.
return x != nil && x.Sign() != 0
}