-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
383 lines (325 loc) · 9.6 KB
/
main.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
package main
import (
"context"
"fmt"
"log"
lendingPoolBinding "ampl-arb/bindings/ilendingpool"
viewBinding "ampl-arb/bindings/view"
ecdsa "crypto/ecdsa"
"errors"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi"
bind "github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
"github.com/metachris/flashbotsrpc"
"math/big"
"os"
"strings"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/joho/godotenv"
)
var (
MinProfit = big.NewInt(5e17) // .5eth
PreemptRebaseSeconds = big.NewInt(100) // borrow from aave 100 seconds before rebase
viewAddr = common.HexToAddress("0x3fdc08d815cc4ed3b7f69ee246716f2c8bcd6b07") // default deploy addr of first default anvil addr
amplAddr = common.HexToAddress("0xD46bA6D942050d489DBd938a2C909A5d5039A161")
lendingPool = common.HexToAddress("0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9")
policy = common.HexToAddress("0x1B228a749077b8e307C5856cE62Ef35d96Dca2ea")
)
type Bot struct {
Client *ethclient.Client
WsClient *ethclient.Client
SigningKey *ecdsa.PrivateKey // flashbots key
PrivateKey *ecdsa.PrivateKey
EOA *common.Address // EOA holding funds
Addresses *ContractAddresses
}
type ContractAddresses struct {
ViewContractAddr *common.Address // address of view contract
AmplAddr *common.Address // token address
LendingPool *common.Address // aave entry point
Policy *common.Address // aampl rebase contract
}
func main() {
addrs := &ContractAddresses{
ViewContractAddr: &viewAddr,
AmplAddr: &lAddr,
LendingPool: &lendingPool,
Policy: &policy,
}
err := godotenv.Load(".env")
if err != nil {
log.Fatal("Error loading .env file")
}
privateKey := os.Getenv("BOT_PRIVATE_KEY")
if privateKey == "" {
log.Fatal("BOT_PRIVATE_KEY not set")
}
signingKey := os.Getenv("FLASHBOTS_SIGNING_KEY")
if signingKey == "" {
log.Fatal("FLASHBOTS_SIGNING_KEY not set")
}
providerURL := os.Getenv("PROVIDER_URL")
if providerURL == "" {
log.Fatal("PROVIDER_URL not set")
}
wsproviderURL := os.Getenv("WS_PROVIDER_URL")
if providerURL == "" {
log.Fatal("PROVIDER_URL not set")
}
bot, err := NewBot(signingKey, privateKey, providerURL, wsproviderURL, addrs)
if err != nil {
log.Fatalf("Failed to initialize bot: %s\n", err)
}
view, err := viewBinding.NewView(*bot.Addresses.ViewContractAddr, bot.Client)
if err != nil {
log.Fatalf("Failed to initialize view view client: %s\n", err)
}
eventSignature := []byte("LogRebase(uint256,uint256,uint256,int256,uint256)")
rebaseSig := crypto.Keccak256Hash(eventSignature)
query := ethereum.FilterQuery{
Addresses: []common.Address{*bot.Addresses.Policy},
Topics: [][]common.Hash{{rebaseSig}},
}
logs := make(chan types.Log)
sub, err := bot.Client.SubscribeFilterLogs(context.Background(), query, logs)
if err != nil {
log.Fatal(err)
}
// if rebase, repay
go func() {
select {
case err := <-sub.Err():
log.Fatal("sub err", err)
case rebaseLog := <-logs:
fmt.Println("saw rebase", rebaseLog)
debt, err := view.UserDebt(&bind.CallOpts{}, *bot.EOA)
if err != nil {
fmt.Println("Failed to get user debt", err)
} else {
if debt != big.NewInt(0) {
//repay full
bot.repayAave()
}
}
}
}()
// if before rebase, borrow
for {
secondsUntilRebase, err := bot.getSecondsUntilRebase()
fmt.Println(secondsUntilRebase, err)
if err != nil {
fmt.Println(err)
} else {
// if rebasing soon
expectedProfit, borrowAmount, err := bot.getExpectedProfit()
if err != nil {
fmt.Println(err)
}
debt, err := view.UserDebt(&bind.CallOpts{}, *bot.EOA)
if err != nil {
fmt.Println("Failed to get user debt", err)
}
// if right before rebase, expected to be profitable, and not already borrowed
if secondsUntilRebase.Cmp(PreemptRebaseSeconds) < 1 && expectedProfit.Cmp(MinProfit) == 1 && debt == big.NewInt(0) {
bot.borrowAave(borrowAmount)
}
}
// sleep 10 sec before checking again
fmt.Println("... ")
time.Sleep(10 * 1e9)
}
}
func (bot *Bot) getSecondsUntilRebase() (*big.Int, error) {
abi, err := abi.JSON(strings.NewReader(viewBinding.ViewABI))
if err != nil {
return nil, err
}
data, err := abi.Pack("secondsUntilRebase")
if err != nil {
return nil, err
}
callData := ðereum.CallMsg{
From: *bot.EOA,
To: bot.Addresses.ViewContractAddr,
Data: data,
}
rawCallResult, err := bot.Client.CallContract(context.Background(), *callData, nil)
if err != nil {
return nil, err
}
returnValues, err := abi.Unpack("secondsUntilRebase", rawCallResult)
if err != nil {
return nil, err
}
return returnValues[0].(*big.Int), nil
}
func (bot *Bot) getExpectedProfit() (*big.Int, *big.Int, error) {
abi, err := abi.JSON(strings.NewReader(viewBinding.ViewABI))
if err != nil {
return nil, nil, err
}
// data, err := abi.Pack("expectedProfit", common.HexToAddress("0xb394e0a990a577f277ddb65547b6399898d78051"));
data, err := abi.Pack("expectedProfit", *bot.EOA)
if err != nil {
return nil, nil, err
}
callData := ðereum.CallMsg{
From: *bot.EOA,
To: bot.Addresses.ViewContractAddr,
Data: data,
}
rawCallResult, err := bot.Client.CallContract(context.Background(), *callData, nil)
if err != nil {
log.Fatalf("Failed to call contract: %s\n", err)
}
returnValues, err := abi.Unpack("expectedProfit", rawCallResult)
expectedProfit := returnValues[0]
borrowAmount := returnValues[1]
if err != nil {
return nil, nil, err
}
return expectedProfit.(*big.Int), borrowAmount.(*big.Int), nil
}
func (bot *Bot) repayAave() error {
abi, err := abi.JSON(strings.NewReader(lendingPoolBinding.IlendingpoolABI))
if err != nil {
return err
}
// repay max uint to repay all. (1 << 256) - 1
data, err := abi.Pack("repay", bot.Addresses.AmplAddr, maxUint256(), 2, *bot.EOA)
if err != nil {
return err
}
callData := ðereum.CallMsg{
From: *bot.EOA,
To: bot.Addresses.LendingPool,
Data: data,
}
signedTx, err := bot.buildTransaction(bot.Addresses.LendingPool, big.NewInt(0), *callData)
if err != nil {
return err
}
return bot.sendPrivateFlashbotsTransaction(signedTx)
}
func (bot *Bot) borrowAave(amount *big.Int) error {
abi, err := abi.JSON(strings.NewReader(lendingPoolBinding.IlendingpoolABI))
if err != nil {
return err
}
data, err := abi.Pack("borrow", bot.Addresses.AmplAddr, amount, 2, 0, *bot.EOA)
if err != nil {
return err
}
callData := ðereum.CallMsg{
From: *bot.EOA,
To: bot.Addresses.LendingPool,
Data: data,
}
signedTx, err := bot.buildTransaction(bot.Addresses.LendingPool, big.NewInt(0), *callData)
if err != nil {
return err
}
return bot.sendPrivateFlashbotsTransaction(signedTx)
}
func (bot *Bot) buildTransaction(to *common.Address, value *big.Int, callData ethereum.CallMsg) (*types.Transaction, error) {
nonce, err := bot.Client.PendingNonceAt(context.Background(), *bot.EOA)
if err != nil {
return nil, err
}
gasPrice, err := bot.Client.SuggestGasPrice(context.Background())
if err != nil {
return nil, err
}
gasLimit, err := bot.Client.EstimateGas(context.Background(), callData)
if err != nil {
log.Printf("Caught error estimating gas: %s\n", err)
gasLimit = 400000
}
chainID, err := bot.Client.NetworkID(context.Background())
if err != nil {
return nil, err
}
tx := types.NewTx(&types.LegacyTx{
Nonce: nonce,
GasPrice: gasPrice,
Gas: gasLimit * 2,
To: to,
Value: value,
Data: callData.Data,
})
signedTx, err := types.SignTx(tx, types.NewEIP155Signer(chainID), bot.PrivateKey)
if err != nil {
fmt.Println("Error signing transaction: ", err)
return nil, err
}
if err != nil {
return nil, err
}
return signedTx, nil
}
func (bot *Bot) sendPrivateFlashbotsTransaction(signedTx *types.Transaction) error {
data, err := signedTx.MarshalBinary()
if err != nil {
return err
}
txStr := hexutil.Encode(data)
opts := flashbotsrpc.FlashbotsSendPrivateTransactionRequest{
Tx: txStr,
Preferences: &flashbotsrpc.FlashbotsPrivateTxPreferences{
Fast: true,
},
}
rpc := flashbotsrpc.New("https://relay.flashbots.net")
result, err := rpc.FlashbotsSendPrivateTransaction(bot.PrivateKey, opts)
if err != nil {
if errors.Is(err, flashbotsrpc.ErrRelayErrorResponse) { // user/tx error, rather than JSON or network error
fmt.Println(err.Error())
} else {
fmt.Printf("error: %+v\n", err)
}
}
// Print result
fmt.Printf("%+v\n", result)
return nil
}
func NewBot(signingKey string, privateKey string, providerURL string, wsProviderUrl string, addrs *ContractAddresses) (*Bot, error) {
var err error
bot := Bot{}
bot.Client, err = ethclient.Dial(providerURL)
if err != nil {
return nil, err
}
bot.WsClient, err = ethclient.Dial(wsProviderUrl)
if err != nil {
return nil, err
}
bot.SigningKey, err = crypto.HexToECDSA(signingKey)
if err != nil {
return nil, err
}
bot.PrivateKey, bot.EOA, err = wallet(privateKey)
if err != nil {
return nil, err
}
bot.Addresses = addrs
return &bot, nil
}
func wallet(private string) (*ecdsa.PrivateKey, *common.Address, error) {
privateKey, err := crypto.HexToECDSA(private)
if err != nil {
return nil, nil, err
}
fromAddress := crypto.PubkeyToAddress(privateKey.PublicKey)
return privateKey, &fromAddress, nil
}
func maxUint256() *big.Int {
var maxUint *big.Int
maxUint.Lsh(big.NewInt(1), 256)
maxUint.Sub(maxUint, big.NewInt(1))
return maxUint
}