-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbatchmanager.go
More file actions
3325 lines (2820 loc) · 131 KB
/
batchmanager.go
File metadata and controls
3325 lines (2820 loc) · 131 KB
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 main
import (
"context"
"encoding/hex"
"errors"
"fmt"
"gobius/account"
"gobius/bindings/arbiusrouterv1"
"gobius/bindings/bulktasks"
"gobius/bindings/engine"
"gobius/client"
task "gobius/common"
"gobius/config"
"gobius/storage"
"gobius/utils"
"log"
"math"
"math/big"
"math/rand"
"sort"
"strings"
"sync"
"time"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ipfs/go-cid"
mh "github.com/multiformats/go-multihash"
"github.com/rs/zerolog"
)
// Constants for gas calculation and profit estimation
const (
profitEstimateBatchSize = 200
// below values are from onchain analysis using the 99% quantile of the gas used for the various functions
// during very high inflation of gas intrinics out of gas errors are still possible
claimTasksGasPerItem = 100_828
submitTasksGasPerItem = 140_477
signalCommitmentGasPerItem = 64_544
submitSolutionGasPerItem = 202_125
baseGasLimitForClaimTasks = 3_500_000
baseGasLimitForSubmitTasks = 2_500_000
baseGasLimitForSubmitSolutions = 3_500_000
baseGasLimitForSignalCommitments = 1_500_000
gasPriceAdjustmentFactor = 1_000_000_000.0
// BulkClaimIncentiveGasPerItem is an estimated gas cost per task in a bulk claim.
// Needs empirical measurement, starting with a guess based on single claim.
BulkClaimIncentiveGasPerItem = 120000
// BaseGasLimitForBulkClaimIncentive is the base gas limit for a bulk claim transaction.
// Needs empirical measurement, starting with a guess.
BaseGasLimitForBulkClaimIncentive = 400000
)
type CacheItem struct {
Value any
LastUpdate time.Time
}
type BulkClaimData struct {
TaskID task.TaskId
Signatures []arbiusrouterv1.Signature
ClaimAccount *account.Account // Store the account determined for this specific claim
}
type Cache struct {
ttl time.Duration
items map[string]*CacheItem
mu sync.RWMutex
}
func NewCache(ttl time.Duration) *Cache {
return &Cache{
ttl: ttl,
items: make(map[string]*CacheItem),
}
}
func (c *Cache) Get(key string) (any, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
item, found := c.items[key]
if !found { //|| time.Since(item.LastUpdate) > c.ttl {
return nil, false
}
return item.Value, true
}
func (c *Cache) Set(key string, value any) {
c.mu.Lock()
defer c.mu.Unlock()
c.items[key] = &CacheItem{
Value: value,
LastUpdate: time.Now(),
}
}
type BatchSolution struct {
taskID task.TaskId
cid []byte
}
type BatchTransactionManager struct {
services *Services
cumulativeGasUsed *GasMetrics // tracks how much gas we've spent
signalCommitmentEvent common.Hash
solutionSubmittedEvent common.Hash
taskSubmittedEvent common.Hash
solutionClaimedEvent common.Hash
rewardsPaidEvent common.Hash
incentiveClaimedEvent common.Hash
commitments [][32]byte
solutions []BatchSolution
encodedTaskData []byte
taskAccounts []*account.Account
minClaimSolutionTime uint64
minContestationVotePeriodTime uint64
cache *Cache
ipfsClaimBackoff map[task.TaskId]int64 // New: Map to track backoff times
ipfsClaimBackoffMutex sync.Mutex // New: Mutex for the backoff map
goroutineRunner
sync.Mutex
}
func NewBatchTransactionManager(services *Services, ctx context.Context) (*BatchTransactionManager, error) {
// TODO: move these out of here!
engineAbi, err := engine.EngineMetaData.GetAbi()
if err != nil {
panic("error getting engine abi")
}
// Get the event SolutionClaimed topic ID
signalCommitmentEvent := engineAbi.Events["SignalCommitment"].ID
solutionSubmittedEvent := engineAbi.Events["SolutionSubmitted"].ID
taskSubmittedEvent := engineAbi.Events["TaskSubmitted"].ID
// Get the event SolutionClaimed topic ID
solutionClaimedEvent := engineAbi.Events["SolutionClaimed"].ID
rewardsPaidEvent := engineAbi.Events["RewardsPaid"].ID
arbiusRouterAbi, abiErr := arbiusrouterv1.ArbiusRouterV1MetaData.GetAbi()
if abiErr != nil {
panic("error getting arbiusrouterv1 abi")
}
incentiveClaimedEvent := arbiusRouterAbi.Events["IncentiveClaimed"].ID
minClaimSolutionTimeBig, err := services.Engine.Engine.MinClaimSolutionTime(nil)
if err != nil {
return nil, err
}
//fmt.Println("minClaimSolutionTimeBig", minClaimSolutionTimeBig.String())
minContestationVotePeriodTimeBig, err := services.Engine.Engine.MinContestationVotePeriodTime(nil)
if err != nil {
return nil, err
}
sampleRate, err := time.ParseDuration(services.Config.Miner.MetricsSampleRate)
if err != nil {
return nil, err
}
cumulativeGasUsed := NewMetricsManager(ctx, sampleRate)
var encodedData []byte
encodedData, err = engineAbi.Pack("submitTask", services.AutoMineParams.Version, services.AutoMineParams.Owner, services.AutoMineParams.Model, services.AutoMineParams.Fee, services.AutoMineParams.Input)
if err != nil {
return nil, err
}
var accounts []*account.Account
if len(services.Config.BatchTasks.PrivateKeys) > 0 {
for _, pk := range services.Config.BatchTasks.PrivateKeys {
account, err := account.NewAccount(pk, services.OwnerAccount.Client, ctx, services.Config.Blockchain.CacheNonce, services.Logger)
if err != nil {
return nil, err
}
account.UpdateNonce()
accounts = append(accounts, account)
}
} else {
accounts = append(accounts, services.OwnerAccount)
}
cache := NewCache(time.Duration(120) * time.Second)
btm := &BatchTransactionManager{
services: services,
cache: cache,
cumulativeGasUsed: cumulativeGasUsed,
signalCommitmentEvent: signalCommitmentEvent,
solutionSubmittedEvent: solutionSubmittedEvent,
taskSubmittedEvent: taskSubmittedEvent,
solutionClaimedEvent: solutionClaimedEvent,
rewardsPaidEvent: rewardsPaidEvent,
incentiveClaimedEvent: incentiveClaimedEvent,
encodedTaskData: encodedData,
taskAccounts: accounts,
minClaimSolutionTime: minClaimSolutionTimeBig.Uint64(),
minContestationVotePeriodTime: minContestationVotePeriodTimeBig.Uint64(),
ipfsClaimBackoff: make(map[task.TaskId]int64), // Initialize the map
}
return btm, nil
}
// implementation for the metrics interface (WIP/TODO fill out)
func (tm *BatchTransactionManager) GetCurrentReward() float64 {
reward, found := tm.cache.Get("reward")
if !found {
return math.NaN()
}
return reward.(float64)
}
func (tm *BatchTransactionManager) GetTotalTasks() int64 {
return 11111
}
func (tm *BatchTransactionManager) GetClaims() int64 {
return 200
}
func (tm *BatchTransactionManager) GetSolutions() int64 {
return 300
}
func (tm *BatchTransactionManager) GetCommitments() int64 {
return 400
}
func (tm *BatchTransactionManager) GetValidatorInfo() string {
s := ""
for _, v := range tm.services.Validators.validators {
s += v.ValidatorAddress().String() + ": 100Aius\n"
}
return s
}
// TODO: refactor this to be more efficient and not so messy
func (tm *BatchTransactionManager) calcProfit(basefee *big.Int) (float64, float64, float64, float64, float64, error) {
var err error
var basePrice, ethPrice float64
modelId := tm.services.AutoMineParams.Model
taskFee := tm.services.AutoMineParams.Fee
if basefee == nil {
basefee, err = tm.services.OwnerAccount.Client.GetBaseFee()
if err != nil {
tm.services.Logger.Error().Err(err).Msg("could not get basefee!")
return 0, 0, 0, 0, 0, err
}
}
basefeeinEth := Eth.ToFloat(basefee)
basefeeinGwei := basefeeinEth * 1000000000
// Use the PriceOracle interface to get prices
basePrice, ethPrice, err = tm.services.OracleProvider.GetPrices()
if err != nil {
if tm.services.Config.BaseConfig.TestnetType > 0 {
tm.services.Logger.Warn().Msg("oracle failed, using default testnet prices (30, 2000)")
basePrice, ethPrice = 30, 2000
} else {
// TODO:consider uing last known good price
tm.services.Logger.Error().Err(err).Msg("could not get prices from oracle!")
return 0, 0, 0, 0, 0, err
}
err = nil
}
tm.cache.Set("base_price", basePrice)
tm.cache.Set("eth_price", ethPrice)
submitTasksBatchUSD := 0.0
submitTasksBatch := (submitTasksGasPerItem * basefeeinEth * profitEstimateBatchSize)
submitTasksBatchUSD = submitTasksBatch * ethPrice
signalCommitmentBatch := (signalCommitmentGasPerItem * basefeeinEth * profitEstimateBatchSize)
signalCommitmentBatchUSD := signalCommitmentBatch * ethPrice
submitSolutionBatch := (submitSolutionGasPerItem * basefeeinEth * profitEstimateBatchSize)
submitSolutionBatchUSD := submitSolutionBatch * ethPrice
claimTasksUSD := 0.0
claimTasks := (claimTasksGasPerItem * basefeeinEth * profitEstimateBatchSize)
claimTasksUSD = claimTasks * ethPrice
totalCostPerBatchUSD := (submitTasksBatchUSD + signalCommitmentBatchUSD + submitSolutionBatchUSD + claimTasksUSD)
modelReward, err := tm.services.Engine.GetModelReward(modelId)
if err != nil {
tm.services.Logger.Error().Err(err).Msg("could not get model reward!")
return 0, 0, 0, 0, 0, err
}
// for now we are taking 10% of the reward as a fee (this factors in the task owner reward and the treasury reward)
rewardInAIUS := tm.services.Config.BaseConfig.BaseToken.ToFloat(modelReward) * 0.9
//rewardTotal := new(big.Int).Sub(modelReward, taskFee)
rewardInAIUSMinusFee := rewardInAIUS - tm.services.Config.BaseConfig.BaseToken.ToFloat(taskFee)
tm.cache.Set("reward", rewardInAIUS)
rewardsPerBatchUSD := rewardInAIUSMinusFee * basePrice * profitEstimateBatchSize
profit := rewardsPerBatchUSD - totalCostPerBatchUSD
tm.cumulativeGasUsed.profitEMA.Add(profit)
tm.services.Logger.Info().
Str("base_model_reward", fmt.Sprintf("%.8g", rewardInAIUS)).
Str("model_reward_minus_fee", fmt.Sprintf("%.8g", rewardInAIUSMinusFee)).
Str("eth_in_usd", fmt.Sprintf("%.4g$", ethPrice)).
Str("aius_in_usd", fmt.Sprintf("%.4g$", basePrice)).
Msg("💰 model reward and eth/aius price")
tm.services.Logger.Info().
Str("costs_in_usd", fmt.Sprintf("%.4g$", totalCostPerBatchUSD)).
Str("rewards_in_usd", fmt.Sprintf("%.4g$", rewardsPerBatchUSD)).
Str("profit_per_batch", fmt.Sprintf("%.4g$", profit)).
Str("base_fee", fmt.Sprintf("%.8g", basefeeinGwei)).
Str("profit_metrics", tm.cumulativeGasUsed.profitEMA.String()).
Msg("💰 batch profits")
return profit, basefeeinGwei, rewardInAIUSMinusFee, ethPrice, basePrice, nil
}
// This should only be run when not performing other batched operations and just does batch claims
func (tm *BatchTransactionManager) batchClaimPoller(appQuit context.Context, pollingtime time.Duration) {
ticker := time.NewTicker(pollingtime)
defer ticker.Stop()
for {
select {
case <-appQuit.Done():
tm.services.Logger.Info().Msg("batch claimer shutting down")
return
case <-ticker.C:
_, totalClaims, err := tm.services.TaskStorage.TotalSolutionsAndClaims()
if err != nil {
tm.services.Logger.Error().Err(err).Msg("failed to get total solutions")
continue
}
tm.services.Logger.Info().Int64("claims", totalClaims).Msg("claims waiting to be processed")
claimBatchSize := tm.services.Config.Claim.MaxClaims
if claimBatchSize <= 0 {
tm.services.Logger.Warn().Msgf("** claim batch size set to 0 so no claims will be made **")
} else {
claims, _, err := tm.services.TaskStorage.GetClaims(claimBatchSize)
if err != nil {
tm.services.Logger.Error().Err(err).Msg("could not get claims from storage")
continue
}
if len(claims) > 0 {
if tm.services.Config.Claim.MaxGas > 0 {
basefeeBig, err := tm.services.OwnerAccount.Client.GetBaseFee()
if err != nil {
tm.services.Logger.Error().Err(err).Msg("could not get basefee!")
continue
}
// convert basefee to gwei
basefeeinEth := Eth.ToFloat(basefeeBig)
basefeeinGwei := basefeeinEth * 1000000000
if basefeeinGwei > tm.services.Config.Claim.MaxGas {
tm.services.Logger.Warn().Msgf("** base gas is too high to claim **")
continue
}
}
tm.processBulkClaim(tm.services.OwnerAccount, claims, tm.services.Config.Claim.MinClaims, claimBatchSize)
}
}
}
}
}
func (tm *BatchTransactionManager) processBatchBlockTrigger(appQuit context.Context) {
var batchWG sync.WaitGroup
headers := make(chan *types.Header)
var newHeadSub ethereum.Subscription
connectToHeaders := func() {
var err error
newHeadSub, err = tm.services.OwnerAccount.Client.Client.SubscribeNewHead(context.Background(), headers)
if err != nil {
tm.services.Logger.Fatal().Err(err).Msg("Failed to subscribe to new headers")
}
}
connectToHeaders()
maxBackoffHeader := time.Second * 30
currentBackoffHeader := time.Second
for {
select {
case <-appQuit.Done():
tm.services.Logger.Info().Msg("delegated batch processor shutting down")
return
case <-headers:
/*basefee, err := tm.services.OwnerAccount.Client.GetBaseFee()
if err != nil {
tm.services.Logger.Error().Err(err).Msg("could not get basefee!")
continue
}
// convert basefee to gwei
basefeeinEth := tm.services.Eth.ToFloat(basefee)
// convert basefee to gwei
basefeeinGwei := basefeeinEth * 1000000000
minProfit := tm.services.Config.DelegatedMiner.MinProfit
if basefeeinGwei <= minProfit {*/
profitLevel, baseFee, rewardInAIUS, ethPrice, basePrice, err := tm.calcProfit(nil)
if err != nil {
tm.services.Logger.Error().Err(err).Msg("could not calculate profit, skipping batch")
continue
}
//start := time.Now()
tm.processBatch(appQuit, &batchWG, profitLevel, baseFee, rewardInAIUS, ethPrice, basePrice)
batchWG.Wait()
//tm.services.Logger.Warn().Str("duration", time.Since(start).String()).Msg("batch processed")
//}
case err := <-newHeadSub.Err():
if err == nil {
continue
}
log.Printf("Error from newHeadSub: %v - redialling in: %s\n", err, currentBackoffHeader.String())
newHeadSub.Unsubscribe()
time.Sleep(currentBackoffHeader)
currentBackoffHeader *= 2
currentBackoffHeader += time.Duration(rand.Intn(1000)) * time.Millisecond
if currentBackoffHeader > maxBackoffHeader {
currentBackoffHeader = maxBackoffHeader
}
connectToHeaders()
}
}
}
func (tm *BatchTransactionManager) processValidatorStakePoller(appQuit context.Context, pollingtime time.Duration) {
ticker := time.NewTicker(pollingtime)
defer ticker.Stop()
for {
select {
case <-ticker.C:
tm.ProcessValidatorsStakes()
case <-appQuit.Done():
tm.services.Logger.Info().Msg("validator stake processor shutting down")
return
}
}
}
func (tm *BatchTransactionManager) processBatchPoller(appQuit context.Context, pollingtime time.Duration) {
var batchWG sync.WaitGroup
ticker := time.NewTicker(pollingtime)
defer ticker.Stop()
for {
select {
case <-ticker.C:
profitLevel, baseFee, rewardInAIUS, ethPrice, basePrice, err := tm.calcProfit(nil)
if err != nil {
tm.services.Logger.Error().Err(err).Msg("could not calculate profit, skipping batch")
continue
}
start := time.Now()
tm.processBatch(appQuit, &batchWG, profitLevel, baseFee, rewardInAIUS, ethPrice, basePrice)
batchWG.Wait()
tm.services.Logger.Warn().Str("duration", time.Since(start).String()).Msg("batch processed")
case <-appQuit.Done():
tm.services.Logger.Info().Msg("delegated batch processor shutting down")
return
}
}
}
func (tm *BatchTransactionManager) isIntrinsicGasTooHigh(ctx context.Context) (bool, error) {
if !tm.services.Config.Miner.EnableIntrinsicGasCheck {
return false, nil // Check disabled
}
baseline := tm.services.Config.Miner.IntrinsicGasBaseline
if baseline == 0 {
baseline = 22000 // Default baseline if not set
}
thresholdMultiplier := tm.services.Config.Miner.IntrinsicGasThresholdMultiplier
if thresholdMultiplier <= 0 {
thresholdMultiplier = 1.1 // Default multiplier if not set
}
opts := tm.services.OwnerAccount.GetOpts(0, nil, nil, nil)
opts.NoSend = true
opts.Value = big.NewInt(1)
// Estimate gas for a simple transfer
gasEstimate, err := tm.services.OwnerAccount.SendTransactionWithOpts(opts, &common.Address{}, []byte{})
if err != nil {
tm.services.Logger.Error().Err(err).Msg("failed to estimate intrinsic gas cost")
// Decide how to handle errors - fail open (assume normal) or fail closed (assume high)?
// Let's fail open for now to avoid blocking unnecessarily due to transient estimation errors.
return false, fmt.Errorf("failed to estimate intrinsic gas: %w", err)
}
gasLimit := gasEstimate.Gas()
threshold := uint64(float64(baseline) * thresholdMultiplier)
isHigh := gasLimit > threshold
if isHigh {
tm.services.Logger.Warn().
Uint64("estimated_gas", gasLimit).
Uint64("baseline", baseline).
Float64("multiplier", thresholdMultiplier).
Uint64("threshold", threshold).
Msg("🚨 high intrinsic gas detected")
} else {
tm.services.Logger.Debug().
Uint64("estimated_gas", gasLimit).
Uint64("threshold", threshold).
Msg("intrinsic gas check passed")
}
return isHigh, nil
}
func (tm *BatchTransactionManager) processBatch(
appQuit context.Context,
wg *sync.WaitGroup,
profitLevel, baseFee, rewardInAIUS, ethPrice, basePrice float64) {
if err := appQuit.Err(); err != nil {
return
}
paused, err := tm.services.Engine.IsPaused()
if err != nil {
tm.services.Logger.Error().Err(err).Msg("failed to get paused status")
return
}
if paused {
tm.services.Logger.Warn().Msg("engine is paused, skipping batch")
time.Sleep(10 * time.Second)
return
}
if tm.services.Config.Miner.EnableIntrinsicGasCheck {
isHigh, checkErr := tm.isIntrinsicGasTooHigh(appQuit) // Use appQuit context
if checkErr != nil {
// Logged within the check function, decide if we need to return or proceed
tm.services.Logger.Error().Err(checkErr).Msg("error checking intrinsic gas, proceeding cautiously")
// Potentially return here if strict safety is needed
}
if isHigh {
tm.services.Logger.Warn().Msg("intrinsic gas cost too high") //, skipping batch processing")
// Potentially add a short sleep here if desired
// time.Sleep(5 * time.Second)
//return // Skip the rest of the batch processing
}
}
totalTasks, err := tm.services.TaskStorage.TotalTasks()
if err != nil {
tm.services.Logger.Error().Err(err).Msg("failed to get total task count")
return
}
// DEFAULTS:
profitMode := tm.services.Config.Miner.ProfitMode
minProfit := tm.services.Config.Miner.MinProfit
maxProfit := tm.services.Config.Miner.MaxProfit
claimMaxBatchSize := tm.services.Config.Claim.MaxClaims
claimMinBatchSize := tm.services.Config.Claim.MinClaims
minProfitFmt := fmt.Sprintf("%.4g$", minProfit)
isProfitable := true
usegwei := false
switch profitMode {
case "fixed":
// just use a fixed min profit set above in defaults
case "gwei":
profitLevel = baseFee
usegwei = true
minProfitFmt = fmt.Sprintf("%.4g gwei", minProfit)
case "ema":
minProfit = tm.cumulativeGasUsed.profitEMA.Average()
// just take profit at current ema
case "randomauto":
// use the ema and max value to decide a band
maxProfit = tm.cumulativeGasUsed.profitEMA.MaxPrice() * 0.95
minProfit = tm.cumulativeGasUsed.profitEMA.Average() * 0.9 //10% less than ema for breathing room
if maxProfit < minProfit {
maxProfit = minProfit
minProfit = minProfit * 0.9
}
fallthrough
default:
// error
tm.services.Logger.Error().Str("profit_mode", profitMode).Msg("invalid profit mode!")
return
}
if usegwei {
isProfitable = profitLevel <= minProfit
} else {
isProfitable = profitLevel >= minProfit
}
totalSolutions, totalClaims, err := tm.services.TaskStorage.TotalSolutionsAndClaims()
if err != nil {
tm.services.Logger.Error().Err(err).Msg("failed to get total solutions")
return
}
// Task creation decision logic
makeTasks := false
taskBatchCount := 0
taskBatchSize := 0
batchCfg := tm.services.Config.BatchTasks
claimQueuePreventsTasks := false // Initialize here
// 0. Check if Batch Task Creation is enabled globally
if !batchCfg.Enabled {
tm.services.Logger.Info().Msg("batch task creation is globally disabled (batchtasks.enabled=false)")
} else {
// 1. Check if claim queue prevents task creation (only if globally enabled)
claimQueuePreventsTasks = batchCfg.MaxClaimQueue > 0 && totalClaims >= int64(batchCfg.MaxClaimQueue)
if claimQueuePreventsTasks {
tm.services.Logger.Info().Int64("claims", totalClaims).Int("max_claims", batchCfg.MaxClaimQueue).Msg("claim queue is full, task creation disabled")
} else {
// 2. Check standard task creation conditions (only if globally enabled and claim queue allows)
shouldCreateStandardTasks := isProfitable &&
totalTasks < int64(batchCfg.MinTasksInQueue) &&
batchCfg.BatchSize > 0
if shouldCreateStandardTasks {
makeTasks = true
taskBatchCount = batchCfg.NumberOfBatches
taskBatchSize = batchCfg.BatchSize
tm.services.Logger.Info().Msg("standard task creation conditions met")
} else {
// 3. Check hoard mode conditions (only if standard conditions not met, globally enabled, and claim queue allows)
shouldActivateHoardMode := batchCfg.HoardMode &&
baseFee <= batchCfg.HoardMinGasPrice &&
totalTasks < int64(batchCfg.HoardMaxQueueSize)
if shouldActivateHoardMode {
makeTasks = true
taskBatchCount = batchCfg.HoardModeNumberOfBatches
taskBatchSize = batchCfg.HoardModeBatchSize
tm.services.Logger.Warn().Msgf("** task hoard mode activated **")
}
}
}
}
// Log final decision factors
tm.services.Logger.Info().
Bool("make_tasks", makeTasks).
Bool("claim_queue_prevents", claimQueuePreventsTasks).
Bool("is_profitable", isProfitable).
Int64("total_tasks", totalTasks).
Int("min_tasks_in_queue", batchCfg.MinTasksInQueue).
Int("batch_size_to_use", taskBatchSize). // Log the size actually being used
Int("batch_count_to_use", taskBatchCount). // Log the count actually being used
Msg("final task creation decision")
if makeTasks {
sendTasks := func(account *account.Account, wg *sync.WaitGroup) {
defer wg.Done()
// Calculate total fee required for the batch
feePerTask := tm.services.AutoMineParams.Fee
totalFee := new(big.Int).Mul(feePerTask, big.NewInt(int64(taskBatchSize)))
// Get the account's AIUS balance
aiusBalanceAsBig, err := tm.services.Basetoken.BalanceOf(nil, account.Address)
if err != nil {
tm.services.Logger.Error().Err(err).Str("account", account.Address.String()).Msg("failed to get AIUS balance for task submission")
return
}
aiusBalanceAsFloat := tm.services.Config.BaseConfig.BaseToken.ToFloat(aiusBalanceAsBig)
// Check if balance is sufficient
// TODO: make level this configurable e.g. some min balance level
if aiusBalanceAsFloat < tm.services.Config.ValidatorConfig.MinBasetokenThreshold {
tm.services.Logger.Warn().
Str("account", account.Address.String()).
Str("balance", fmt.Sprintf("%.8g", aiusBalanceAsFloat)).
Str("required", fmt.Sprintf("%.8g", tm.services.Config.BaseConfig.BaseToken.ToFloat(totalFee))).
Int("batch_size", taskBatchSize).
Msgf("** task fee will exceed min balance threshold of %.8g, skipping task batch **", tm.services.Config.ValidatorConfig.MinBasetokenThreshold)
return
}
// log the amount of aius reqiured for this batch in a human readable format
feeTransferAsfloat := tm.services.Config.BaseConfig.BaseToken.ToFloat(totalFee)
tm.services.Logger.Warn().Str("fee_transfer", fmt.Sprintf("%.4g", feeTransferAsfloat)).Int("batch_size", taskBatchSize).Str("account", account.Address.String()).Msgf("** task queue is low - sending batch **")
receipt, err := tm.BulkTasks(account, taskBatchSize)
if err != nil {
tm.services.Logger.Error().Err(err).Msg("error sending batch tasks")
} else {
tm.services.Logger.Info().Int("batch_size", taskBatchSize).Str("txhash", receipt.TxHash.String()).Uint64("block", receipt.BlockNumber.Uint64()).Msg("batch tasks tx accepted!")
}
}
switch tm.services.Config.BatchTasks.BatchMode {
case "normal":
// get random index into taskAccounts
accountIndex := rand.Intn(len(tm.taskAccounts))
for i := 0; i < taskBatchCount; i++ {
// get the next available account
account := tm.taskAccounts[accountIndex%len(tm.taskAccounts)]
accountIndex++
wg.Add(1)
if tm.services.Config.Miner.ConcurrentBatches {
go sendTasks(account, wg)
if len(tm.taskAccounts) == 1 {
time.Sleep(500 * time.Millisecond)
}
} else {
//if err := appQuit.Err(); err != nil {
//return
//}
sendTasks(account, wg)
}
}
case "account":
for _, acc := range tm.taskAccounts {
wg.Add(1)
//if tm.services.Config.DelegatedMiner.ConcurrentBatches {
go sendTasks(acc, wg)
//} else {
//sendTasks(acc, wg)
//}
}
default:
tm.services.Logger.Error().Str("batch_mode", tm.services.Config.BatchTasks.BatchMode).Msg("invalid task batch mode")
}
if tm.services.Config.BatchTasks.OnlyTasks {
tm.services.Logger.Info().Msg("only tasks sent, skipping other batch operations")
return
}
}
totalCommitments, err := tm.services.TaskStorage.TotalCommitments()
if err != nil {
tm.services.Logger.Error().Err(err).Msg("failed to get total commitments")
return
}
totalTasksCount, totalTasksGasFloat, err := tm.services.TaskStorage.GetTotalTasksGas()
if err != nil {
tm.services.Logger.Error().Err(err).Msg("failed to get total tasks gas")
return
}
// auto mine fee per task
feePerTaskAsBig := tm.services.AutoMineParams.Fee
feePerTaskAsFloat := tm.services.Config.BaseConfig.BaseToken.ToFloat(feePerTaskAsBig)
totalQueued := float64(totalTasks + totalSolutions + totalCommitments + totalClaims)
totalAiusOnFee := totalQueued * feePerTaskAsFloat
totalAiusEarnings := totalQueued * rewardInAIUS // reward in aius factors in the task fee already duh
totalSpentonGasInUSD := totalTasksGasFloat * ethPrice
totalProfitOfQueueInUsd := totalAiusEarnings*basePrice - totalSpentonGasInUSD
// total queue stats
tm.services.Logger.Info().
Int64("tasks", totalTasks). // total tasks in queue
Int64("tasks_count", totalTasksCount). // total tasks in DB which might be higher due to stale tasks
Int64("solutions", totalSolutions). // total solutions in queue
Int64("commitments", totalCommitments). // total commitments in queue
Int64("claims", totalClaims). // total claims in queue
Msg("pending totals for batch queue")
tm.services.Logger.Info().
Str("total_aius", fmt.Sprintf("%.8g", totalAiusOnFee)).
Str("total_gas_usd", fmt.Sprintf("%.4g$", totalSpentonGasInUSD)).
Msg("total gas and aius spent on tasks in queue")
tm.services.Logger.Info().
Str("profit_aius", fmt.Sprintf("%.8g", totalAiusEarnings)).
Str("profit_usd", fmt.Sprintf("%.4g$", totalProfitOfQueueInUsd)).
Msg("approx total aius and usd profit from pending queue")
if !isProfitable {
tm.services.Logger.Info().Str("profit_mode", profitMode).Str("min_profit", minProfitFmt).Str("max_profit", fmt.Sprintf("%.4g", maxProfit)).Msg("not profitable to process batch")
return
}
tm.services.Logger.Info().Str("profit_mode", profitMode).Str("min_profit", minProfitFmt).Msg("profit criteria met - processing batch")
if claimMinBatchSize <= 0 || !tm.services.Config.Claim.Enabled {
tm.services.Logger.Warn().Msgf("** claim batch disabled or min batch size set to 0 so no claims will be made **")
} else {
noOfClaimBatches := tm.services.Config.Claim.NumberOfBatches
if noOfClaimBatches <= 0 {
noOfClaimBatches = 1
}
claims, averageGas, err := tm.services.TaskStorage.GetClaims(claimMaxBatchSize * noOfClaimBatches)
if err != nil {
tm.services.Logger.Error().Err(err).Msg("could not get keys from storage")
return
}
totalCost := 0.0
for _, task := range claims {
totalCost += task.TotalCost
}
// calculate the cost of the claims in aius using magic numbers
claimTasks := (claimTasksGasPerItem / gasPriceAdjustmentFactor * baseFee * float64(len(claims)))
tm.services.Logger.Warn().Msgf("** CHEAPEST BATCH WE CAN SEND OUT **")
tm.services.Logger.Warn().Msgf("** total cost of %d claims: %f **", len(claims), totalCost)
tm.services.Logger.Warn().Msgf("** average gas per task : %f **", averageGas)
totalCost += claimTasks
totalCostInUSD := totalCost * ethPrice //fmt.Sprintf("%0.4f$", totalCost*ethPrice)
claimValue := rewardInAIUS * float64(len(claims)) * basePrice
actualProfit := claimValue - totalCostInUSD
tm.services.Logger.Warn().Msgf("** total cost of mining batch : %0.4g$ (gas spent: %f)**", totalCostInUSD, totalCost)
tm.services.Logger.Warn().Msgf("** batch value : %0.4g$ **", claimValue)
tm.services.Logger.Warn().Msgf("** profit : %0.4g$ **", claimValue-totalCostInUSD)
tm.services.Logger.Warn().Msgf("** profit/task : %0.4g$ **", (claimValue-totalCostInUSD)/float64(len(claims)))
tm.services.Logger.Warn().Msgf("**********************************************")
claimLen := len(claims)
if claimLen > 0 {
canClaim := false
claimMinReward, err := tm.services.LeverOracle.MinClaimLever()
if err != nil {
tm.services.Logger.Error().Err(err).Msg("could not get minclaim lever from oracle!")
return
}
if claimMinReward > 0 {
if rewardInAIUS >= claimMinReward {
tm.services.Logger.Warn().Msgf("** %.8g reward is >= claim min of reward %.8g, claim **", rewardInAIUS, claimMinReward)
canClaim = true
} else {
tm.services.Logger.Warn().Msgf("** %.8g reward is below claim min reward of %.8g, skipping claim **", rewardInAIUS, claimMinReward)
canClaim = false
}
} else if tm.services.Config.Claim.HoardMode {
if int(totalClaims) < tm.services.Config.Claim.HoardMaxQueueSize {
canClaim = false
tm.services.Logger.Warn().Msgf("** claim hoard mode on, and queue length of %d is below threshold of %d - skipping claim **", int(totalClaims), tm.services.Config.Claim.HoardMaxQueueSize)
} else {
canClaim = true
tm.services.Logger.Warn().Msgf("** claim hoard mode on, and queue length of %d is above threshold of %d - claiming **", int(totalClaims), tm.services.Config.Claim.HoardMaxQueueSize)
}
} else if tm.services.Config.Claim.MinBatchProfit > 0 {
if actualProfit < tm.services.Config.Claim.MinBatchProfit {
tm.services.Logger.Warn().Msgf("** batch profit of %.8g is below claim threshold of %.8g, skipping claim **", actualProfit, tm.services.Config.Claim.MinBatchProfit)
canClaim = false
} else {
canClaim = true
tm.services.Logger.Warn().Msgf("** batch profit of %.8g is above claim threshold of %.8g, claiming **", actualProfit, tm.services.Config.Claim.MinBatchProfit)
}
} else {
canClaim = true
tm.services.Logger.Warn().Msgf("** default claim conditions met, claiming **")
}
// if tm.services.Config.Claim.ClaimOnApproachMinStake && validatorBuffer < tm.services.Config.Claim.MinStakeBufferLevel {
// tm.services.Logger.Warn().Msgf("** claim on approach to min stake enabled and validator buffer is below set min stake level **")
// canClaim = true
// }
if canClaim {
accountIndex := rand.Intn(len(tm.taskAccounts))
sendBulkClaim := func(chunk storage.ClaimTaskSlice, account *account.Account, wg *sync.WaitGroup, batchno int) {
defer wg.Done()
tm.services.Logger.Info().Int("max_batch_size", claimMaxBatchSize).Int("batch_no", batchno+1).Str("address", account.Address.String()).Msgf("preparing claim batch")
tm.processBulkClaim(account, chunk, claimMinBatchSize, claimMaxBatchSize)
}
for i, chunk := range claims.SplitIntoChunks(claimMaxBatchSize) {
if err := appQuit.Err(); err != nil {
return
}
// get the next available account
account := tm.taskAccounts[accountIndex%len(tm.taskAccounts)]
accountIndex++
wg.Add(1)
if tm.services.Config.Miner.ConcurrentBatches {
go sendBulkClaim(chunk, account, wg, i)
//time.Sleep(800 * time.Millisecond)
} else {
sendBulkClaim(chunk, account, wg, i)
}
}
}
}
}
deleteCommitments := func(_commitmentsToDelete []task.TaskId) error {
if len(_commitmentsToDelete) > 0 {
err := tm.services.TaskStorage.DeleteProcessedCommitments(_commitmentsToDelete)
if err != nil {
tm.services.Logger.Error().Err(err).Msg("error deleting commitment(s) from storage")
return err
}
tm.services.Logger.Info().Msgf("deleted %d task commitments from storage that were committed on-chain", len(_commitmentsToDelete))
}
return nil
}
deleteSolutions := func(_solutionsToDelete []task.TaskId) error {
if len(_solutionsToDelete) > 0 {
err := tm.services.TaskStorage.DeleteProcessedSolutions(_solutionsToDelete)
if err != nil {
tm.services.Logger.Error().Err(err).Msg("error deleting solution(s) from storage")
return err
}
tm.services.Logger.Info().Msgf("deleted %d task solutions from storage that were submitted on-chain", len(_solutionsToDelete))
}
return nil
}
// simplified this function and removed solution checks, these are now only done in the getSolutionBatchdata function
// If a commitment is found to be on-chain, it is deleted from storage
getCommitmentBatchdata := func(batchSize int, noChecks bool) (storage.TaskDataSlice, error) {
var tasks storage.TaskDataSlice
var err error
tasks, err = tm.services.TaskStorage.GetPendingCommitments(batchSize)
if err != nil {
tm.services.Logger.Err(err).Msg("failed to get commitments from storage")
return nil, err
}
if noChecks || len(tasks) == 0 { // Also return early if no tasks
return tasks, nil
}
var commitmentsToDelete []task.TaskId
var validTasksForBatch storage.TaskDataSlice
var tasksToUpdateToStatus2 []task.TaskId // New list to track tasks needing status update
// Collect all commitment hashes for a bulk call
collectedCommitmentHashes := make([][32]byte, 0, len(tasks))
taskMapByCommitment := make(map[[32]byte]storage.TaskData) // Helper to map results back
for _, t := range tasks {
// Ensure task has a commitment hash locally before checking on-chain
if t.Commitment == ([32]byte{}) {
tm.services.Logger.Warn().Str("taskid", t.TaskId.String()).Msg("Task in pending commitments has zero commitment hash, skipping.")