/
submit-rpl-price.go
1298 lines (1091 loc) · 35.8 KB
/
submit-rpl-price.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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package watchtower
import (
"bytes"
"context"
"fmt"
"math/big"
"strings"
"sync"
"time"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/Seb369888/poolsea-go/dao/trustednode"
v110_node "github.com/Seb369888/poolsea-go/legacy/v1.1.0/node"
"github.com/Seb369888/poolsea-go/network"
"github.com/Seb369888/poolsea-go/rocketpool"
"github.com/Seb369888/poolsea-go/utils/eth"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/urfave/cli"
v110_network "github.com/Seb369888/poolsea-go/legacy/v1.1.0/network"
"github.com/Seb369888/smartnode/shared/services"
"github.com/Seb369888/smartnode/shared/services/beacon"
"github.com/Seb369888/smartnode/shared/services/config"
"github.com/Seb369888/smartnode/shared/services/contracts"
rpgas "github.com/Seb369888/smartnode/shared/services/gas"
"github.com/Seb369888/smartnode/shared/services/state"
"github.com/Seb369888/smartnode/shared/services/wallet"
"github.com/Seb369888/smartnode/shared/utils/api"
"github.com/Seb369888/smartnode/shared/utils/eth1"
"github.com/Seb369888/smartnode/shared/utils/log"
mathutils "github.com/Seb369888/smartnode/shared/utils/math"
)
const (
OptimismMessengerAbi string = `[
{
"inputs": [],
"name": "rateStale",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "submitRate",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
}
]`
PolygonMessengerAbi string = `[
{
"inputs": [],
"name": "rateStale",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "submitRate",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
}
]`
ArbitrumMessengerAbi string = `[
{
"inputs": [],
"name": "rateStale",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "_maxSubmissionCost",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "_gasLimit",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "_gasPriceBid",
"type": "uint256"
}
],
"name": "submitRate",
"outputs": [],
"stateMutability": "payable",
"type": "function"
}
]`
zkSyncEraMessengerAbi string = `[
{
"inputs": [],
"name": "rateStale",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "_l2GasLimit",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "_l2GasPerPubdataByteLimit",
"type": "uint256"
}
],
"name": "submitRate",
"outputs": [],
"stateMutability": "payable",
"type": "function"
}
]`
RplTwapPoolAbi string = `[
{
"inputs": [{
"internalType": "uint32[]",
"name": "secondsAgos",
"type": "uint32[]"
}],
"name": "observe",
"outputs": [{
"internalType": "int56[]",
"name": "tickCumulatives",
"type": "int56[]"
}, {
"internalType": "uint160[]",
"name": "secondsPerLiquidityCumulativeX128s",
"type": "uint160[]"
}],
"stateMutability": "view",
"type": "function"
}
]`
)
// Settings
const (
SubmissionKey string = "network.prices.submitted.node.key"
BlocksPerTurn uint64 = 75 // Approx. 15 minutes
RplPriceDecreaseDeviationThreshold float64 = 0.5 // Error out if price drops >50%
RplPriceIncreaseDeviationThreshold float64 = 1.6 // Error out if price rises >60%
twapNumberOfSeconds uint32 = 60 * 60 * 12 // 12 hours
)
type poolObserveResponse struct {
TickCumulatives []*big.Int `abi:"tickCumulatives"`
SecondsPerLiquidityCumulativeX128s []*big.Int `abi:"secondsPerLiquidityCumulativeX128s"`
}
// Submit RPL price task
type submitRplPrice struct {
c *cli.Context
log log.ColorLogger
errLog log.ColorLogger
cfg *config.RocketPoolConfig
ec rocketpool.ExecutionClient
w *wallet.Wallet
rp *rocketpool.RocketPool
oio *contracts.OneInchOracle
bc beacon.Client
lock *sync.Mutex
isRunning bool
}
// Create submit RPL price task
func newSubmitRplPrice(c *cli.Context, logger log.ColorLogger, errorLogger log.ColorLogger) (*submitRplPrice, error) {
// Get services
cfg, err := services.GetConfig(c)
if err != nil {
return nil, err
}
w, err := services.GetWallet(c)
if err != nil {
return nil, err
}
ec, err := services.GetEthClient(c)
if err != nil {
return nil, err
}
rp, err := services.GetRocketPool(c)
if err != nil {
return nil, err
}
oio, err := services.GetOneInchOracle(c)
if err != nil {
return nil, err
}
bc, err := services.GetBeaconClient(c)
if err != nil {
return nil, err
}
// Return task
lock := &sync.Mutex{}
return &submitRplPrice{
c: c,
log: logger,
errLog: errorLogger,
cfg: cfg,
ec: ec,
w: w,
rp: rp,
oio: oio,
bc: bc,
lock: lock,
}, nil
}
// Submit RPL price
func (t *submitRplPrice) run(state *state.NetworkState, isAtlasDeployed bool) error {
// Wait for eth client to sync
if err := services.WaitEthClientSynced(t.c, true); err != nil {
return err
}
// Get node account
nodeAccount, err := t.w.GetNodeAccount()
if err != nil {
return err
}
// Check if submission is enabled
if !state.NetworkDetails.SubmitPricesEnabled {
return nil
}
// Check if Optimism rate is stale and submit
err = t.submitOptimismPrice()
if err != nil {
// Error is not fatal for this task so print and continue
t.log.Printlnf("Error submitting Optimism price: %s", err.Error())
}
// Check if Polygon rate is stale and submit
err = t.submitPolygonPrice()
if err != nil {
// Error is not fatal for this task so print and continue
t.log.Printlnf("Error submitting Polygon price: %s", err.Error())
}
// Check if Arbitrum rate is stale and submit
err = t.submitArbitrumPrice()
if err != nil {
// Error is not fatal for this task so print and continue
t.log.Printlnf("Error submitting Arbitrum price: %s", err.Error())
}
// Check if zkSync rate is stale and submit
err = t.submitZkSyncEraPrice()
if err != nil {
// Error is not fatal for this task so print and continue
t.log.Printlnf("Error submitting zkSync Era price: %s", err.Error())
}
// Log
t.log.Println("Checking for RPL price checkpoint...")
// Get block to submit price for
blockNumber := state.NetworkDetails.LatestReportablePricesBlock
// Check if a submission needs to be made
pricesBlock := state.NetworkDetails.PricesBlock
if blockNumber <= pricesBlock {
return nil
}
// Get the time of the block
header, err := t.ec.HeaderByNumber(context.Background(), big.NewInt(0).SetUint64(blockNumber))
if err != nil {
return err
}
blockTime := time.Unix(int64(header.Time), 0)
// Get the Beacon block corresponding to this time
eth2Config := state.BeaconConfig
genesisTime := time.Unix(int64(eth2Config.GenesisTime), 0)
timeSinceGenesis := blockTime.Sub(genesisTime)
slotNumber := uint64(timeSinceGenesis.Seconds()) / eth2Config.SecondsPerSlot
// Check if the targetEpoch is finalized yet
targetEpoch := slotNumber / eth2Config.SlotsPerEpoch
beaconHead, err := t.bc.GetBeaconHead()
if err != nil {
return err
}
finalizedEpoch := beaconHead.FinalizedEpoch
if targetEpoch > finalizedEpoch {
t.log.Printlnf("Prices must be reported for EL block %d, waiting until Epoch %d is finalized (currently %d)", blockNumber, targetEpoch, finalizedEpoch)
return nil
}
// Check if the process is already running
t.lock.Lock()
if t.isRunning {
t.log.Println("Prices report is already running in the background.")
t.lock.Unlock()
return nil
}
t.lock.Unlock()
go func() {
t.lock.Lock()
t.isRunning = true
t.lock.Unlock()
logPrefix := "[Price Report]"
t.log.Printlnf("%s Starting price report in a separate thread.", logPrefix)
// Log
t.log.Printlnf("Getting RPL price for block %d...", blockNumber)
// Get RPL price at block
var rplPrice *big.Int
twapEpoch := t.cfg.Smartnode.RplTwapEpoch.Value.(uint64)
if targetEpoch < twapEpoch {
rplPrice, err = t.getRplPrice(blockNumber)
} else {
rplPrice, err = t.getRplTwap(blockNumber)
}
if err != nil {
t.handleError(fmt.Errorf("%s %w", logPrefix, err))
return
}
// Calculate the total effective RPL stake on the network
zero := new(big.Int).SetUint64(0)
var effectiveRplStake *big.Int
if !isAtlasDeployed {
nodeStakingAddress := t.cfg.Smartnode.GetV110NodeStakingAddress()
effectiveRplStake, err = v110_node.CalculateTotalEffectiveRPLStake(t.rp, zero, zero, rplPrice, nil, &nodeStakingAddress)
if err != nil {
t.handleError(fmt.Errorf("%s error getting total effective RPL stake: %w", logPrefix, err))
return
}
} else {
_, effectiveRplStake, err = state.CalculateTrueEffectiveStakes(false)
if err != nil {
t.handleError(fmt.Errorf("%s error getting total effective RPL stake: %w", logPrefix, err))
return
}
}
// Log
t.log.Printlnf("RPL price: %.6f ETH", mathutils.RoundDown(eth.WeiToEth(rplPrice), 6))
// Check if we have reported these specific values before
hasSubmittedSpecific, err := t.hasSubmittedSpecificBlockPrices(nodeAccount.Address, blockNumber, rplPrice, effectiveRplStake, isAtlasDeployed)
if err != nil {
t.handleError(fmt.Errorf("%s %w", logPrefix, err))
return
}
if hasSubmittedSpecific {
t.lock.Lock()
t.isRunning = false
t.lock.Unlock()
return
}
// We haven't submitted these values, check if we've submitted any for this block so we can log it
hasSubmitted, err := t.hasSubmittedBlockPrices(nodeAccount.Address, blockNumber)
if err != nil {
t.handleError(fmt.Errorf("%s %w", logPrefix, err))
return
}
if hasSubmitted {
t.log.Printlnf("Have previously submitted out-of-date prices for block %d, trying again...", blockNumber)
}
// Log
t.log.Println("Submitting RPL price...")
// Submit RPL price
if err := t.submitRplPrice(blockNumber, rplPrice, effectiveRplStake, isAtlasDeployed); err != nil {
t.handleError(fmt.Errorf("%s could not submit RPL price: %w", logPrefix, err))
return
}
// Log and return
t.log.Printlnf("%s Price report complete.", logPrefix)
t.lock.Lock()
t.isRunning = false
t.lock.Unlock()
}()
// Return
return nil
}
func (t *submitRplPrice) handleError(err error) {
t.errLog.Println(err)
t.errLog.Println("*** Price report failed. ***")
t.lock.Lock()
t.isRunning = false
t.lock.Unlock()
}
// Check whether prices for a block has already been submitted by the node
func (t *submitRplPrice) hasSubmittedBlockPrices(nodeAddress common.Address, blockNumber uint64) (bool, error) {
blockNumberBuf := make([]byte, 32)
big.NewInt(int64(blockNumber)).FillBytes(blockNumberBuf)
return t.rp.RocketStorage.GetBool(nil, crypto.Keccak256Hash([]byte(SubmissionKey), nodeAddress.Bytes(), blockNumberBuf))
}
// Check whether specific prices for a block has already been submitted by the node
func (t *submitRplPrice) hasSubmittedSpecificBlockPrices(nodeAddress common.Address, blockNumber uint64, rplPrice, effectiveRplStake *big.Int, isAtlasDeployed bool) (bool, error) {
if isAtlasDeployed {
blockNumberBuf := make([]byte, 32)
big.NewInt(int64(blockNumber)).FillBytes(blockNumberBuf)
rplPriceBuf := make([]byte, 32)
rplPrice.FillBytes(rplPriceBuf)
return t.rp.RocketStorage.GetBool(nil, crypto.Keccak256Hash([]byte(SubmissionKey), nodeAddress.Bytes(), blockNumberBuf, rplPriceBuf))
} else {
blockNumberBuf := make([]byte, 32)
big.NewInt(int64(blockNumber)).FillBytes(blockNumberBuf)
rplPriceBuf := make([]byte, 32)
rplPrice.FillBytes(rplPriceBuf)
effectiveRplStakeBuf := make([]byte, 32)
effectiveRplStake.FillBytes(effectiveRplStakeBuf)
return t.rp.RocketStorage.GetBool(nil, crypto.Keccak256Hash([]byte(SubmissionKey), nodeAddress.Bytes(), blockNumberBuf, rplPriceBuf, effectiveRplStakeBuf))
}
}
// Get RPL price at block
func (t *submitRplPrice) getRplPrice(blockNumber uint64) (*big.Int, error) {
// Require 1inch oracle contract
if err := services.RequireOneInchOracle(t.c); err != nil {
return nil, err
}
// Get RPL token address
rplAddress := common.HexToAddress(t.cfg.Smartnode.GetRplTokenAddress())
// Initialize call options
opts := &bind.CallOpts{
BlockNumber: big.NewInt(int64(blockNumber)),
}
// Get a client with the block number available
client, err := eth1.GetBestApiClient(t.rp, t.cfg, t.printMessage, opts.BlockNumber)
if err != nil {
return nil, err
}
// Generate an OIO wrapper using the client
oio, err := contracts.NewOneInchOracle(common.HexToAddress(t.cfg.Smartnode.GetOneInchOracleAddress()), client.Client)
if err != nil {
return nil, err
}
// Get RPL price
rplPrice, err := oio.GetRateToEth(opts, rplAddress, true)
if err != nil {
return nil, fmt.Errorf("could not get RPL price at block %d: %w", blockNumber, err)
}
// Get the previously reported price
previousPrice, err := network.GetRPLPrice(t.rp, opts)
if err != nil {
return nil, fmt.Errorf("could not get previous RPL price at block %d: %w", blockNumber, err)
}
// See if the new price is lower than the decrease threshold
one := eth.EthToWei(1)
decreaseThresholdBig := eth.EthToWei(RplPriceDecreaseDeviationThreshold)
oldDecreaseThreshold := big.NewInt(0)
oldDecreaseThreshold.Mul(previousPrice, decreaseThresholdBig).Div(oldDecreaseThreshold, one)
if rplPrice.Cmp(oldDecreaseThreshold) == -1 {
t.log.Println("=== RPL PRICE ANOMALY DETECTED ===")
t.log.Printlnf("Previous RPL Price: %s", previousPrice.String())
t.log.Printlnf("Min Allowed Price: %s", oldDecreaseThreshold.String())
t.log.Printlnf("CURRENT RPL PRICE: %s", rplPrice.String())
t.log.Println("==================================")
return nil, fmt.Errorf("rpl price decreased beyond the allowed threshold")
}
// See if the new price is higher than the increase threshold
increaseThresholdBig := eth.EthToWei(RplPriceIncreaseDeviationThreshold)
oldIncreaseThreshold := big.NewInt(0)
oldIncreaseThreshold.Mul(previousPrice, increaseThresholdBig).Div(oldIncreaseThreshold, one)
if rplPrice.Cmp(oldIncreaseThreshold) == 1 {
t.log.Println("=== RPL PRICE ANOMALY DETECTED ===")
t.log.Printlnf("Previous RPL Price: %s", previousPrice.String())
t.log.Printlnf("Max Allowed Price: %s", oldIncreaseThreshold.String())
t.log.Printlnf("CURRENT RPL PRICE: %s", rplPrice.String())
t.log.Println("==================================")
return nil, fmt.Errorf("rpl price increased beyond the allowed threshold")
}
// Return
return rplPrice, nil
}
// Get RPL price via TWAP at block
func (t *submitRplPrice) getRplTwap(blockNumber uint64) (*big.Int, error) {
// Initialize call options
opts := &bind.CallOpts{
BlockNumber: big.NewInt(int64(blockNumber)),
}
poolAddress := t.cfg.Smartnode.GetRplTwapPoolAddress()
if poolAddress == "" {
return nil, fmt.Errorf("RPL TWAP pool contract not deployed on this network")
}
// Get a client with the block number available
client, err := eth1.GetBestApiClient(t.rp, t.cfg, t.printMessage, opts.BlockNumber)
if err != nil {
return nil, err
}
// Construct the pool contract instance
parsed, err := abi.JSON(strings.NewReader(RplTwapPoolAbi))
if err != nil {
return nil, fmt.Errorf("error decoding RPL TWAP pool ABI: %w", err)
}
addr := common.HexToAddress(poolAddress)
poolContract := bind.NewBoundContract(addr, parsed, client.Client, client.Client, client.Client)
pool := rocketpool.Contract{
Contract: poolContract,
Address: &addr,
ABI: &parsed,
Client: client.Client,
}
// Get RPL price
response := poolObserveResponse{}
interval := twapNumberOfSeconds
args := []uint32{interval, 0}
err = pool.Call(opts, &response, "observe", args)
if err != nil {
return nil, fmt.Errorf("could not get RPL price at block %d: %w", blockNumber, err)
}
tick := big.NewInt(0).Sub(response.TickCumulatives[1], response.TickCumulatives[0])
tick.Div(tick, big.NewInt(int64(interval))) // tick = (cumulative[1] - cumulative[0]) / interval
base := eth.EthToWei(1.0001) // 1.0001e18
one := eth.EthToWei(1) // 1e18
numerator := big.NewInt(0).Exp(base, tick, nil) // 1.0001e18 ^ tick
numerator.Mul(numerator, one)
denominator := big.NewInt(0).Exp(one, tick, nil) // 1e18 ^ tick
denominator.Div(numerator, denominator) // denominator = (1.0001e18^tick / 1e18^tick)
numerator.Mul(one, one) // 1e18 ^ 2
rplPrice := big.NewInt(0).Div(numerator, denominator) // 1e18 ^ 2 / (1.0001e18^tick * 1e18 / 1e18^tick)
// Return
return rplPrice, nil
}
func (t *submitRplPrice) printMessage(message string) {
t.log.Println(message)
}
// Submit RPL price and total effective RPL stake
func (t *submitRplPrice) submitRplPrice(blockNumber uint64, rplPrice, effectiveRplStake *big.Int, isAtlasDeployed bool) error {
// Log
t.log.Printlnf("Submitting RPL price for block %d...", blockNumber)
// Get transactor
opts, err := t.w.GetNodeAccountTransactor()
if err != nil {
return err
}
var hash common.Hash
if isAtlasDeployed {
// Get the gas limit
gasInfo, err := network.EstimateSubmitPricesGas(t.rp, blockNumber, rplPrice, opts)
if err != nil {
return fmt.Errorf("Could not estimate the gas required to submit RPL price: %w", err)
}
// Print the gas info
maxFee := eth.GweiToWei(getWatchtowerMaxFee(t.cfg))
if !api.PrintAndCheckGasInfo(gasInfo, false, 0, t.log, maxFee, 0) {
return nil
}
// Set the gas settings
opts.GasFeeCap = maxFee
opts.GasTipCap = eth.GweiToWei(getWatchtowerPrioFee(t.cfg))
opts.GasLimit = gasInfo.SafeGasLimit
// Submit RPL price
hash, err = network.SubmitPrices(t.rp, blockNumber, rplPrice, opts)
if err != nil {
return err
}
} else {
legacyNetworkPricesAddress := t.cfg.Smartnode.GetV110NetworkPricesAddress()
// Get the gas limit
gasInfo, err := v110_network.EstimateSubmitPricesGas(t.rp, blockNumber, rplPrice, effectiveRplStake, opts, &legacyNetworkPricesAddress)
if err != nil {
return fmt.Errorf("Could not estimate the gas required to submit RPL price: %w", err)
}
// Print the gas info
maxFee := eth.GweiToWei(getWatchtowerMaxFee(t.cfg))
if !api.PrintAndCheckGasInfo(gasInfo, false, 0, t.log, maxFee, 0) {
return nil
}
// Set the gas settings
opts.GasFeeCap = maxFee
opts.GasTipCap = eth.GweiToWei(getWatchtowerPrioFee(t.cfg))
opts.GasLimit = gasInfo.SafeGasLimit
// Submit RPL price
hash, err = v110_network.SubmitPrices(t.rp, blockNumber, rplPrice, effectiveRplStake, opts, &legacyNetworkPricesAddress)
if err != nil {
return err
}
}
// Print TX info and wait for it to be included in a block
err = api.PrintAndWaitForTransaction(t.cfg, hash, t.rp.Client, t.log)
if err != nil {
return err
}
// Log
t.log.Printlnf("Successfully submitted RPL price for block %d.", blockNumber)
// Return
return nil
}
// Checks if Optimism rate is stale and if it's our turn to submit, calls submitRate on the messenger
func (t *submitRplPrice) submitOptimismPrice() error {
priceMessengerAddress := t.cfg.Smartnode.GetOptimismMessengerAddress()
if priceMessengerAddress == "" {
// No price messenger deployed on the current network
return nil
}
// Get transactor
opts, err := t.w.GetNodeAccountTransactor()
if err != nil {
return fmt.Errorf("Failed getting transactor: %q", err)
}
// Construct the price messenger contract instance
parsed, err := abi.JSON(strings.NewReader(OptimismMessengerAbi))
if err != nil {
return fmt.Errorf("Failed decoding ABI: %q", err)
}
addr := common.HexToAddress(priceMessengerAddress)
priceMessengerContract := bind.NewBoundContract(addr, parsed, t.ec, t.ec, t.ec)
priceMessenger := rocketpool.Contract{
Contract: priceMessengerContract,
Address: &addr,
ABI: &parsed,
Client: t.ec,
}
// Check if the rate is stale
var out []interface{}
err = priceMessengerContract.Call(nil, &out, "rateStale")
if err != nil {
return fmt.Errorf("Failed to query rate staleness for Optimism: %q", err)
}
rateStale := *abi.ConvertType(out[0], new(bool)).(*bool)
if !rateStale {
// Nothing to do
return nil
}
// Get total number of ODAO members
count, err := trustednode.GetMemberCount(t.rp, nil)
if err != nil {
return fmt.Errorf("Failed to get member count: %q", err)
}
// Find out which index we are
var index = uint64(0)
for i := uint64(0); i < count; i++ {
addr, err := trustednode.GetMemberAt(t.rp, i, nil)
if err != nil {
return fmt.Errorf("Failed to get member at %d: %q", i, err)
}
if bytes.Compare(addr.Bytes(), opts.From.Bytes()) == 0 {
index = i
break
}
}
// Get current block number
blockNumber, err := t.ec.BlockNumber(context.Background())
if err != nil {
return fmt.Errorf("Failed to get block number: %q", err)
}
// Calculate whose turn it is to submit
indexToSubmit := (blockNumber / BlocksPerTurn) % count
if index == indexToSubmit {
// Temporary gas calculations until this gets put into a binding
input, err := priceMessenger.ABI.Pack("submitRate")
if err != nil {
return fmt.Errorf("Could not encode input data: %w", err)
}
// Estimate gas limit
gasLimit, err := t.rp.Client.EstimateGas(context.Background(), ethereum.CallMsg{
From: opts.From,
To: priceMessenger.Address,
GasPrice: big.NewInt(0), // use 0 gwei for simulation
Value: opts.Value,
Data: input,
})
if err != nil {
return fmt.Errorf("Error estimating gas limit of submitOptimismPrice: %w", err)
}
// Get the safe gas limit
safeGasLimit := uint64(float64(gasLimit) * rocketpool.GasLimitMultiplier)
if gasLimit > rocketpool.MaxGasLimit {
gasLimit = rocketpool.MaxGasLimit
}
if safeGasLimit > rocketpool.MaxGasLimit {
safeGasLimit = rocketpool.MaxGasLimit
}
gasInfo := rocketpool.GasInfo{
EstGasLimit: gasLimit,
SafeGasLimit: safeGasLimit,
}
// Print the gas info
maxFee := eth.GweiToWei(getWatchtowerMaxFee(t.cfg))
if !api.PrintAndCheckGasInfo(gasInfo, false, 0, t.log, maxFee, 0) {
return nil
}
// Set the gas settings
opts.GasFeeCap = maxFee
opts.GasTipCap = eth.GweiToWei(getWatchtowerPrioFee(t.cfg))
opts.GasLimit = gasInfo.SafeGasLimit
t.log.Println("Submitting rate to Optimism...")
// Submit rates
tx, err := priceMessenger.Transact(opts, "submitRate")
if err != nil {
return fmt.Errorf("Failed to submit rate: %q", err)
}
// Print TX info and wait for it to be included in a block
err = api.PrintAndWaitForTransaction(t.cfg, tx.Hash(), t.rp.Client, t.log)
if err != nil {
return err
}
// Log
t.log.Printlnf("Successfully submitted Optimism price for block %d.", blockNumber)
}
return nil
}
// Checks if Polygon rate is stale and if it's our turn to submit, calls submitRate on the messenger
func (t *submitRplPrice) submitPolygonPrice() error {
priceMessengerAddress := t.cfg.Smartnode.GetPolygonMessengerAddress()
if priceMessengerAddress == "" {
// No price messenger deployed on the current network
return nil
}
// Get transactor
opts, err := t.w.GetNodeAccountTransactor()
if err != nil {
return fmt.Errorf("Failed getting transactor: %q", err)
}
// Construct the price messenger contract instance
parsed, err := abi.JSON(strings.NewReader(PolygonMessengerAbi))
if err != nil {
return fmt.Errorf("Failed decoding ABI: %q", err)
}
addr := common.HexToAddress(priceMessengerAddress)
priceMessengerContract := bind.NewBoundContract(addr, parsed, t.ec, t.ec, t.ec)
priceMessenger := rocketpool.Contract{
Contract: priceMessengerContract,
Address: &addr,
ABI: &parsed,
Client: t.ec,
}
// Check if the rate is stale
var out []interface{}
err = priceMessengerContract.Call(nil, &out, "rateStale")
if err != nil {
return fmt.Errorf("Failed to query rate staleness for Polygon: %q", err)
}
rateStale := *abi.ConvertType(out[0], new(bool)).(*bool)
if !rateStale {
// Nothing to do
return nil
}
// Get total number of ODAO members
count, err := trustednode.GetMemberCount(t.rp, nil)
if err != nil {
return fmt.Errorf("Failed to get member count: %q", err)
}
// Find out which index we are
var index = uint64(0)
for i := uint64(0); i < count; i++ {
addr, err := trustednode.GetMemberAt(t.rp, i, nil)
if err != nil {
return fmt.Errorf("Failed to get member at %d: %q", i, err)
}
if bytes.Compare(addr.Bytes(), opts.From.Bytes()) == 0 {
index = i
break
}
}
// Get current block number
blockNumber, err := t.ec.BlockNumber(context.Background())
if err != nil {
return fmt.Errorf("Failed to get block number: %q", err)
}
// Calculate whose turn it is to submit
indexToSubmit := (blockNumber / BlocksPerTurn) % count
if index == indexToSubmit {
// Temporary gas calculations until this gets put into a binding
input, err := priceMessenger.ABI.Pack("submitRate")
if err != nil {
return fmt.Errorf("Could not encode input data for Polygon price submission: %w", err)
}
// Estimate gas limit
gasLimit, err := t.rp.Client.EstimateGas(context.Background(), ethereum.CallMsg{
From: opts.From,
To: priceMessenger.Address,
GasPrice: big.NewInt(0), // use 0 gwei for simulation
Value: opts.Value,
Data: input,
})
if err != nil {
return fmt.Errorf("Error estimating gas limit of submitPolygonPrice: %w", err)
}
// Get the safe gas limit
safeGasLimit := uint64(float64(gasLimit) * rocketpool.GasLimitMultiplier)
if gasLimit > rocketpool.MaxGasLimit {
gasLimit = rocketpool.MaxGasLimit
}
if safeGasLimit > rocketpool.MaxGasLimit {
safeGasLimit = rocketpool.MaxGasLimit
}
gasInfo := rocketpool.GasInfo{
EstGasLimit: gasLimit,
SafeGasLimit: safeGasLimit,
}
// Print the gas info
maxFee := eth.GweiToWei(getWatchtowerMaxFee(t.cfg))
if !api.PrintAndCheckGasInfo(gasInfo, false, 0, t.log, maxFee, 0) {
return nil
}
// Set the gas settings
opts.GasFeeCap = maxFee
opts.GasTipCap = eth.GweiToWei(getWatchtowerPrioFee(t.cfg))
opts.GasLimit = gasInfo.SafeGasLimit
t.log.Println("Submitting rate to Polygon...")
// Submit rates
tx, err := priceMessenger.Transact(opts, "submitRate")
if err != nil {
return fmt.Errorf("Failed to submit rate to Polygon: %q", err)
}
// Print TX info and wait for it to be included in a block
err = api.PrintAndWaitForTransaction(t.cfg, tx.Hash(), t.rp.Client, t.log)
if err != nil {
return err
}
// Log
t.log.Printlnf("Successfully submitted Polygon price for block %d.", blockNumber)
}
return nil
}
// Checks if Arbitrum rate is stale and if it's our turn to submit, calls submitRate on the messenger
func (t *submitRplPrice) submitArbitrumPrice() error {
priceMessengerAddress := t.cfg.Smartnode.GetArbitrumMessengerAddress()
if priceMessengerAddress == "" {
// No price messenger deployed on the current network
return nil
}
// Get transactor
opts, err := t.w.GetNodeAccountTransactor()
if err != nil {
return fmt.Errorf("Failed getting transactor: %q", err)
}
// Construct the price messenger contract instance
parsed, err := abi.JSON(strings.NewReader(ArbitrumMessengerAbi))
if err != nil {
return fmt.Errorf("Failed decoding ABI: %q", err)
}
addr := common.HexToAddress(priceMessengerAddress)
priceMessengerContract := bind.NewBoundContract(addr, parsed, t.ec, t.ec, t.ec)
priceMessenger := rocketpool.Contract{