-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathengine.go
More file actions
5387 lines (4728 loc) · 189 KB
/
engine.go
File metadata and controls
5387 lines (4728 loc) · 189 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
// The core package that manage and distribute and execute task
package taskengine
import (
"context"
"encoding/json"
"errors"
"fmt"
"math/big"
"os"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/AvaProtocol/EigenLayer-AVS/core/apqueue"
"github.com/AvaProtocol/EigenLayer-AVS/core/chainio/aa"
"github.com/AvaProtocol/EigenLayer-AVS/core/config"
"github.com/AvaProtocol/EigenLayer-AVS/model"
"github.com/AvaProtocol/EigenLayer-AVS/pkg/gow"
"github.com/AvaProtocol/EigenLayer-AVS/storage"
sdklogging "github.com/Layr-Labs/eigensdk-go/logging"
"github.com/allegro/bigcache/v3"
badger "github.com/dgraph-io/badger/v4"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/math"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/oklog/ulid/v2"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/types/known/structpb"
avsproto "github.com/AvaProtocol/EigenLayer-AVS/protobuf"
)
// getTaskStatusString safely converts a TaskStatus to string, handling edge cases
func getTaskStatusString(status avsproto.TaskStatus) string {
// The crash was caused by calling .String() on an uninitialized enum
// This function provides a safe wrapper that ensures we always get a valid string
return status.String()
}
const (
JobTypeExecuteTask = "execute_task"
DefaultLimit = 50
MaxSecretNameLength = 255
EvmErc20TransferTopic0 = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
)
var (
rpcConn *ethclient.Client
// websocket client used for subscription
wsEthClient *ethclient.Client
wsRpcURL string
globalLogger sdklogging.Logger
// a global variable that we expose to our tasks. User can use `{{name}}` to access them
// These macro are define in our aggregator yaml config file under `macros`
macroVars map[string]string
macroSecrets map[string]string
cache *bigcache.BigCache
// Global token enrichment service for shared token metadata and chain detection
globalTokenService *TokenEnrichmentService
defaultSalt = big.NewInt(0)
)
// Set a global logger for task engine
func SetLogger(mylogger sdklogging.Logger) {
globalLogger = mylogger
}
// Set the global macro system. macros are static, immutable and available to all tasks at runtime
func SetMacroVars(v map[string]string) {
macroVars = v
}
func SetMacroSecrets(v map[string]string) {
macroSecrets = v
}
// GetMacroSecret returns a secret from macros.secrets loaded into the engine.
// Returns empty string if the key is not set or macros were not initialized.
func GetMacroSecret(key string) string {
if macroSecrets == nil || key == "" {
return ""
}
return macroSecrets[key]
}
func SetCache(c *bigcache.BigCache) {
cache = c
}
// SetTokenEnrichmentService sets the global token enrichment service
func SetTokenEnrichmentService(service *TokenEnrichmentService) {
globalTokenService = service
}
// GetTokenEnrichmentService returns the global token enrichment service
func GetTokenEnrichmentService() *TokenEnrichmentService {
return globalTokenService
}
// Initialize a shared rpc client instance
func SetRpc(rpcURL string) {
// Skip RPC initialization for test URLs to avoid external dependencies in CI
if strings.Contains(rpcURL, "localhost") || strings.Contains(rpcURL, "127.0.0.1") || strings.Contains(rpcURL, "mock") {
// For test environments, set rpcConn to nil and continue
// This allows tests to run without external RPC dependencies
rpcConn = nil
return
}
// Enhanced error handling with circuit breaker pattern
if err := rpcCallWithCircuitBreaker(func() error {
conn, err := ethclient.Dial(rpcURL)
if err != nil {
return err
}
rpcConn = conn
return nil
}, "HTTP_RPC"); err != nil {
// In CI environment, if RPC connection fails, set to nil instead of panicking
// This allows tests to run without external dependencies
if os.Getenv("CI") != "" || os.Getenv("GITHUB_ACTIONS") != "" {
fmt.Printf("CI environment detected: Setting rpcConn to nil due to RPC connection failure: %v", err)
rpcConn = nil
return
}
// Log error and report to Sentry
fmt.Printf("Failed to initialize HTTP RPC connection: %v", err)
enhancedPanicRecovery("rpc_connection", "SetRpc", map[string]interface{}{
"connection_type": "HTTP",
"url": rpcURL,
})
panic(fmt.Errorf("HTTP RPC connection failed: %w", err))
}
}
// Initialize a shared websocket rpc client instance
func SetWsRpc(rpcURL string) {
wsRpcURL = rpcURL
// Enhanced error handling with circuit breaker pattern
if err := rpcCallWithCircuitBreaker(retryWsRpc, "WS_RPC"); err != nil {
// Log error instead of panic for better resilience
fmt.Printf("Failed to initialize WebSocket RPC connection: %v", err)
// Report to Sentry
enhancedPanicRecovery("ws_rpc_connection", "SetWsRpc", map[string]interface{}{
"connection_type": "WebSocket",
"url": rpcURL,
})
panic(fmt.Errorf("WebSocket RPC connection failed: %w", err))
}
}
func retryWsRpc() error {
for {
conn, err := ethclient.Dial(wsRpcURL)
if err == nil {
wsEthClient = conn
return nil
}
globalLogger.Errorf("cannot establish websocket client for RPC, retry in 15 seconds", "err", err)
time.Sleep(15 * time.Second)
}
}
// Minimum interval between successive connections from the same operator.
// Connections arriving faster than this are rejected with ResourceExhausted.
const operatorReconnectCooldown = 5 * time.Second
type operatorState struct {
// list of task id that we had synced to this operator
TaskID map[string]bool
MonotonicClock int64
// Operator capabilities
Capabilities *avsproto.SyncMessagesReq_Capabilities
// Context cancellation for managing ticker lifecycle
TickerCancel context.CancelFunc
TickerCtx context.Context
// Rate limiting: track when the operator last connected
LastConnectTime time.Time
}
type PendingNotification struct {
TaskID string
Operation avsproto.MessageOp
Timestamp time.Time
}
// The core datastructure of the task engine
type Engine struct {
db storage.Storage
config *config.Config
queue *apqueue.Queue
// maintain a list of active job that we have to synced to operators
// only task triggers are sent to operator
//
// Lock ordering (acquire outer before inner to avoid deadlock):
// assignmentMutex (outer) → streamsMutex (middle) → lock (inner)
// Never acquire an outer lock while holding an inner lock.
// lock is a leaf lock: critical sections must only do map reads/writes,
// never call functions that acquire streamsMutex or assignmentMutex.
tasks map[string]*model.Task
lock *sync.Mutex
trackSyncedTasks map[string]*operatorState
// operator stream management for real-time notifications
operatorStreams map[string]avsproto.Node_SyncMessagesServer
streamsMutex *sync.RWMutex
// lifecycle tracking for active operator streams
streamsWG sync.WaitGroup
// Round-robin task assignment
taskAssignments map[string]string // taskID -> operatorAddress mapping
assignmentRoundRobin int // index for round-robin assignment
assignmentMutex *sync.RWMutex // protects task assignments
smartWalletConfig *config.SmartWalletConfig
// when shutdown is true, our engine will perform the shutdown
// pending execution will be pushed out before the shutdown completely
// to force shutdown, one can type ctrl+c twice
shutdown bool
// seq is a monotonic number to keep track our task id
seq storage.Sequence
logger sdklogging.Logger
// Token enrichment service for ERC20 transfers
tokenEnrichmentService *TokenEnrichmentService
// Shared clients
tenderlyClient *TenderlyClient
priceService PriceService
// Debouncing for operator approval logging
lastApprovalLogTime map[string]time.Time
approvalLogMutex *sync.RWMutex
// Deduplication for operator trigger notifications (prevents double-firing)
// Maps trigger_request_id -> time when it was processed (for TTL cleanup)
processedTriggerIDs map[string]time.Time
triggerDedupLock *sync.Mutex
// Batched operator notifications
pendingNotifications map[string][]PendingNotification // operatorAddr -> list of notifications
notificationMutex *sync.RWMutex
notificationTicker *time.Ticker
}
// create a new task engine using given storage, config and queue
func New(db storage.Storage, config *config.Config, queue *apqueue.Queue, logger sdklogging.Logger) *Engine {
e := Engine{
db: db,
config: config,
queue: queue,
lock: &sync.Mutex{},
tasks: make(map[string]*model.Task),
trackSyncedTasks: make(map[string]*operatorState),
operatorStreams: make(map[string]avsproto.Node_SyncMessagesServer),
streamsMutex: &sync.RWMutex{},
taskAssignments: make(map[string]string),
assignmentMutex: &sync.RWMutex{},
lastApprovalLogTime: make(map[string]time.Time),
approvalLogMutex: &sync.RWMutex{},
processedTriggerIDs: make(map[string]time.Time),
triggerDedupLock: &sync.Mutex{},
smartWalletConfig: config.SmartWallet,
shutdown: false,
// Initialize batched notifications
pendingNotifications: make(map[string][]PendingNotification),
notificationMutex: &sync.RWMutex{},
notificationTicker: time.NewTicker(3 * time.Second), // Send batched notifications every 3 seconds
logger: logger,
}
// Initialize AI summarizer (global) from aggregator config
// Only context-memory API is supported - all email content generation is delegated to context-memory
// The aggregator acts as a pass-through for the context-memory response to SendGrid
contextMemorySummarizer := NewContextMemorySummarizerFromAggregatorConfig(config)
if contextMemorySummarizer != nil {
SetSummarizer(contextMemorySummarizer)
logger.Info("AI summarizer initialized", "provider", "context-memory", "base_url", config.NotificationsSummary.APIEndpoint)
} else {
// Log why context-memory is not available
if !config.NotificationsSummary.Enabled {
logger.Debug("Context-memory API not available: NotificationsSummary.Enabled is false")
} else if strings.ToLower(config.NotificationsSummary.Provider) != "context-memory" {
logger.Debug("Context-memory API not configured: provider is not 'context-memory'", "provider", config.NotificationsSummary.Provider)
} else if strings.TrimSpace(config.NotificationsSummary.APIEndpoint) == "" {
logger.Debug("Context-memory API not available: api_endpoint not configured in notifications.summary")
} else if strings.TrimSpace(config.NotificationsSummary.APIKey) == "" {
logger.Debug("Context-memory API not available: api_key not configured in notifications.summary")
}
// No summarizer configured - deterministic fallback will be used
logger.Debug("Context-memory API not configured, will use deterministic fallback")
}
// Initialize global macro variables and secrets from config
// This ensures all nodes (BalanceNode, etc.) can access secrets without manual setup
SetMacroVars(config.MacroVars)
SetMacroSecrets(config.MacroSecrets)
SetRpc(config.SmartWallet.EthRpcUrl)
aa.SetFactoryAddress(config.SmartWallet.FactoryAddress)
//SetWsRpc(config.SmartWallet.EthWsUrl)
// Use global TokenEnrichmentService or initialize if not set
if globalTokenService == nil {
logger.Debug("initializing global TokenEnrichmentService", "has_rpc", rpcConn != nil)
tokenService, err := NewTokenEnrichmentService(rpcConn, logger)
if err != nil {
logger.Warn("Failed to initialize TokenEnrichmentService", "error", err)
// Don't fail engine initialization, continue without token enrichment
} else {
globalTokenService = tokenService
// Load token whitelist data into cache
if err := tokenService.LoadWhitelist(); err != nil {
logger.Warn("Failed to load token whitelist", "error", err)
// Don't fail engine initialization, continue with RPC-only token enrichment
}
// Single consolidated log message
if rpcConn != nil {
logger.Info("Global TokenEnrichmentService initialized",
"chainID", tokenService.GetChainID(),
"whitelistTokens", tokenService.GetCacheSize(),
"rpcSupport", true)
} else {
logger.Info("Global TokenEnrichmentService initialized",
"chainID", tokenService.GetChainID(),
"whitelistTokens", tokenService.GetCacheSize(),
"rpcSupport", false)
}
}
} else {
logger.Debug("Using existing global TokenEnrichmentService")
}
e.tokenEnrichmentService = globalTokenService
// Initialize shared Tenderly client from config
e.tenderlyClient = NewTenderlyClient(config, logger)
logger.Info("TenderlyClient initialized", "ready", e.tenderlyClient != nil)
return &e
}
// GetTenderlyClient returns the shared Tenderly client for fee estimation and simulation
func (n *Engine) GetTenderlyClient() *TenderlyClient {
return n.tenderlyClient
}
func (n *Engine) SetPriceService(priceService PriceService) {
n.priceService = priceService
}
func (n *Engine) Stop() {
if n.seq != nil {
if err := n.seq.Release(); err != nil {
n.logger.Error("failed to release sequence", "error", err)
}
}
// mark shutdown and collect cancels without holding locks during cancel
var cancels []context.CancelFunc
n.lock.Lock()
n.shutdown = true
for _, state := range n.trackSyncedTasks {
if state != nil && state.TickerCancel != nil {
cancels = append(cancels, state.TickerCancel)
}
}
n.lock.Unlock()
// cancel all operator tickers to stop their stream loops
for _, cancel := range cancels {
cancel()
}
// wait for all StreamCheckToOperator goroutines to exit
n.streamsWG.Wait()
// Send any remaining notifications before shutting down
if n.notificationTicker != nil {
n.sendBatchedNotifications()
n.notificationTicker.Stop()
}
}
// AddTaskForTesting adds a task directly to the engine's task map for testing purposes
// This bypasses database storage and validation - only use in tests
func (n *Engine) AddTaskForTesting(task *model.Task) {
n.lock.Lock()
defer n.lock.Unlock()
n.tasks[task.Id] = task
}
func (n *Engine) MustStart() error {
var err error
n.seq, err = n.db.GetSequence([]byte("t:seq"), 1000)
if err != nil {
panic(err)
}
// Upon booting we will get all the enabled tasks to sync to operator
kvs, e := n.db.GetByPrefix(TaskByStatusStoragePrefix(avsproto.TaskStatus_Enabled))
if e != nil {
panic(e)
}
loadedCount := 0
for _, item := range kvs {
task := &model.Task{
Task: &avsproto.Task{},
}
err := protojson.Unmarshal(item.Value, task)
if err == nil {
// Ensure task is properly initialized after loading from storage
if initErr := task.EnsureInitialized(); initErr != nil {
n.logger.Warn("Task failed initialization after loading from storage",
"storage_key", string(item.Key),
"task_id", task.Id,
"error", initErr)
continue // Skip this corrupt task
}
n.tasks[task.Id] = task
loadedCount++
} else {
n.logger.Warn("Failed to unmarshal task during startup", "storage_key", string(item.Key), "error", err)
}
}
n.logger.Info("🚀 Engine started successfully", "active_tasks_loaded", loadedCount)
// Detect and handle any invalid tasks that may have been created before validation was fixed
if err := n.DetectAndHandleInvalidTasks(); err != nil {
n.logger.Error("Failed to handle invalid tasks during startup", "error", err)
// Don't fail startup, but log the error
}
// Start the batch notification processor
go n.processBatchedNotifications()
return nil
}
// markPreviousCanonicalStaleIfAny consults the (owner, factory, salt)
// secondary index. If the index already points at a *different* wallet
// address than the freshly derived one, that means the factory's account
// implementation was upgraded between the previous record and now — the
// previously canonical wallet is no longer derivable from this triple.
// Mark the old record as stale so list responses hide it and future
// writes can replace the index entry. Index lookup or marking failures
// are logged but never block the fresh insertion path.
func (n *Engine) markPreviousCanonicalStaleIfAny(owner common.Address, factoryAddr common.Address, salt *big.Int, freshAddress common.Address) {
previousAddr, err := LookupCanonicalWalletAddress(n.db, owner, factoryAddr, salt)
if err == badger.ErrKeyNotFound {
return
}
if err != nil {
n.logger.Warn("Failed to look up canonical wallet address by (owner, factory, salt)", "owner", owner.Hex(), "factory", factoryAddr.Hex(), "salt", salt.String(), "error", err)
return
}
if strings.EqualFold(previousAddr.Hex(), freshAddress.Hex()) {
return
}
n.logger.Error("Stale wallet derivation detected — factory implementation likely upgraded",
"owner", owner.Hex(),
"factory", factoryAddr.Hex(),
"salt", salt.String(),
"previousAddress", previousAddr.Hex(),
"newAddress", freshAddress.Hex(),
)
if markErr := MarkWalletStale(n.db, owner, previousAddr.Hex()); markErr != nil {
n.logger.Warn("Failed to mark previous canonical wallet as stale", "owner", owner.Hex(), "previousAddress", previousAddr.Hex(), "error", markErr)
}
}
// storeDefaultWalletForListWallets creates and stores the default wallet (salt:0) for ListWallets.
// Returns the stored wallet model if successful, or nil if storage failed (but logs the error).
func (n *Engine) storeDefaultWalletForListWallets(owner common.Address, defaultDerivedAddress *common.Address, defaultSystemFactory common.Address, defaultSalt *big.Int) *model.SmartWallet {
n.logger.Info("Default wallet not found in DB for ListWallets, storing it", "owner", owner.Hex(), "walletAddress", defaultDerivedAddress.Hex())
n.markPreviousCanonicalStaleIfAny(owner, defaultSystemFactory, defaultSalt, *defaultDerivedAddress)
newModelWallet := &model.SmartWallet{
Owner: &owner,
Address: defaultDerivedAddress,
Factory: &defaultSystemFactory,
Salt: defaultSalt,
IsHidden: false,
}
if storeErr := StoreWallet(n.db, owner, newModelWallet); storeErr != nil {
n.logger.Error("Error storing default wallet to DB for ListWallets", "owner", owner.Hex(), "walletAddress", defaultDerivedAddress.Hex(), "error", storeErr)
// Continue and return the wallet anyway, but log the error
return nil
}
// Successfully stored, return the wallet model
return newModelWallet
}
// ListWallets corresponds to the ListWallets RPC.
func (n *Engine) ListWallets(owner common.Address, payload *avsproto.ListWalletReq) (*avsproto.ListWalletResp, error) {
walletsToReturnProto := []*avsproto.SmartWallet{}
processedAddresses := make(map[string]bool)
defaultSystemFactory := n.smartWalletConfig.FactoryAddress
var defaultDerivedAddress *common.Address
var deriveErr error
// Only try to derive default address if rpcConn is available
if rpcConn != nil {
defaultDerivedAddress, deriveErr = aa.GetSenderAddressForFactory(rpcConn, owner, defaultSystemFactory, defaultSalt)
} else {
// In test environment or when RPC is unavailable, skip default derivation
n.logger.Debug("Skipping default wallet derivation due to nil rpcConn (test environment)", "owner", owner.Hex())
deriveErr = fmt.Errorf("rpc connection not available")
}
if deriveErr != nil {
n.logger.Warn("Failed to derive default system wallet address for ListWallets", "owner", owner.Hex(), "error", deriveErr, "hasRpcConn", rpcConn != nil)
} else if defaultDerivedAddress == nil || *defaultDerivedAddress == (common.Address{}) {
n.logger.Warn("Derived default system wallet address is nil or zero for ListWallets", "owner", owner.Hex())
} else {
includeThisDefault := true
if payload != nil {
if pfa := payload.GetFactoryAddress(); pfa != "" && !strings.EqualFold(defaultSystemFactory.Hex(), pfa) {
includeThisDefault = false
}
if ps := payload.GetSalt(); ps != "" && defaultSalt.String() != ps {
includeThisDefault = false
}
}
if includeThisDefault {
modelWallet, dbGetErr := GetWallet(n.db, owner, defaultDerivedAddress.Hex())
isHidden := false
actualSalt := defaultSalt.String()
actualFactory := defaultSystemFactory.Hex()
if dbGetErr == nil {
isHidden = modelWallet.IsHidden
actualSalt = modelWallet.Salt.String()
if modelWallet.Factory != nil {
actualFactory = modelWallet.Factory.Hex()
}
} else if dbGetErr == badger.ErrKeyNotFound {
// Wallet not found in DB - we need to store it since we're returning it to the client
// Enforce max smart wallet count per owner before creating a new wallet entry
if n.smartWalletConfig != nil {
maxAllowed := n.smartWalletConfig.MaxWalletsPerOwner
if maxAllowed <= 0 {
maxAllowed = config.DefaultMaxWalletsPerOwner
}
if maxAllowed > config.HardMaxWalletsPerOwner {
maxAllowed = config.HardMaxWalletsPerOwner
}
// Fetch all wallets for this owner and count unique addresses
dbItems, listErr := n.db.GetByPrefix(WalletByOwnerPrefix(owner))
if listErr == nil {
unique := make(map[string]struct{})
for _, item := range dbItems {
storedModelWallet := &model.SmartWallet{}
if err := storedModelWallet.FromStorageData(item.Value); err == nil && storedModelWallet.Address != nil {
unique[strings.ToLower(storedModelWallet.Address.Hex())] = struct{}{}
}
}
// Always store the default wallet even if limit is reached, since it's always returned
// The default wallet (salt:0) is special and should always be available
if len(unique) >= maxAllowed {
n.logger.Warn("Max wallet count reached for owner in ListWallets, but storing default wallet anyway since it's always returned", "owner", owner.Hex(), "limit", maxAllowed, "currentCount", len(unique))
}
// Store the default wallet since we're returning it to the client
if storedWallet := n.storeDefaultWalletForListWallets(owner, defaultDerivedAddress, defaultSystemFactory, defaultSalt); storedWallet != nil {
modelWallet = storedWallet
}
}
} else {
// No config but wallet not in DB - store it anyway
if storedWallet := n.storeDefaultWalletForListWallets(owner, defaultDerivedAddress, defaultSystemFactory, defaultSalt); storedWallet != nil {
modelWallet = storedWallet
}
}
} else {
n.logger.Warn("DB error fetching default derived wallet for ListWallets", "address", defaultDerivedAddress.Hex(), "error", dbGetErr)
}
// Always include the default wallet in the response (even if storage failed)
if modelWallet != nil {
isHidden = modelWallet.IsHidden
actualSalt = modelWallet.Salt.String()
if modelWallet.Factory != nil {
actualFactory = modelWallet.Factory.Hex()
}
}
walletsToReturnProto = append(walletsToReturnProto, &avsproto.SmartWallet{
Address: defaultDerivedAddress.Hex(),
Salt: actualSalt,
Factory: actualFactory,
IsHidden: isHidden,
})
processedAddresses[strings.ToLower(defaultDerivedAddress.Hex())] = true
}
}
dbItems, listErr := n.db.GetByPrefix(WalletByOwnerPrefix(owner))
if listErr != nil && listErr != badger.ErrKeyNotFound {
n.logger.Error("Error fetching wallets by owner prefix for ListWallets", "owner", owner.Hex(), "error", listErr)
if len(walletsToReturnProto) == 0 {
return nil, status.Errorf(codes.Code(avsproto.ErrorCode_STORAGE_UNAVAILABLE), "Error fetching wallets by owner: %v", listErr)
}
}
for _, item := range dbItems {
storedModelWallet := &model.SmartWallet{}
if err := storedModelWallet.FromStorageData(item.Value); err != nil {
n.logger.Error("Failed to parse stored wallet data for ListWallets", "key", string(item.Key), "error", err)
continue
}
// Hard-filter zombies left over from a factory account-implementation
// upgrade. The record is preserved on disk (the on-chain wallet may
// still hold assets), but it is no longer derivable from its
// (owner, factory, salt) and would otherwise show up as a phantom
// salt collision in the response.
if storedModelWallet.StaleDerivation {
continue
}
if processedAddresses[strings.ToLower(storedModelWallet.Address.Hex())] {
continue
}
if pfa := payload.GetFactoryAddress(); pfa != "" {
if storedModelWallet.Factory == nil || !strings.EqualFold(storedModelWallet.Factory.Hex(), pfa) {
continue
}
}
if ps := payload.GetSalt(); ps != "" {
if storedModelWallet.Salt == nil || storedModelWallet.Salt.String() != ps {
continue
}
}
factoryString := ""
if storedModelWallet.Factory != nil {
factoryString = storedModelWallet.Factory.Hex()
}
walletsToReturnProto = append(walletsToReturnProto, &avsproto.SmartWallet{
Address: storedModelWallet.Address.Hex(),
Salt: storedModelWallet.Salt.String(),
Factory: factoryString,
IsHidden: storedModelWallet.IsHidden,
})
}
return &avsproto.ListWalletResp{Items: walletsToReturnProto}, nil
}
// validateNonZeroAddress validates that the factory address is not the zero address
// Returns an error if validation fails, nil if validation passes
func (n *Engine) validateNonZeroAddress(factoryAddr common.Address, methodName, ownerHex, salt string) error {
if factoryAddr == (common.Address{}) {
n.logger.Warn("Attempted to use zero address as factory for "+methodName, "owner", ownerHex, "salt", salt)
return status.Errorf(codes.InvalidArgument, "Factory address cannot be the zero address")
}
return nil
}
// GetWallet is the gRPC handler for the GetWallet RPC.
// It uses the owner (from auth context), salt, and factory_address from payload to derive the wallet address.
func (n *Engine) GetWallet(user *model.User, payload *avsproto.GetWalletReq) (*avsproto.GetWalletResp, error) {
// Allow empty factory address (uses default), but validate non-empty ones
if payload.GetFactoryAddress() != "" && !common.IsHexAddress(payload.GetFactoryAddress()) {
return nil, status.Errorf(codes.InvalidArgument, InvalidFactoryAddressError)
}
saltBig := defaultSalt
if payload.GetSalt() != "" {
var ok bool
saltBig, ok = math.ParseBig256(payload.GetSalt())
if !ok {
return nil, status.Errorf(codes.InvalidArgument, "%s: %s", InvalidSmartAccountSaltError, payload.GetSalt())
}
if saltBig.Sign() < 0 {
return nil, status.Errorf(codes.InvalidArgument, "%s: must be a non-negative integer, got %s", InvalidSmartAccountSaltError, payload.GetSalt())
}
}
factoryAddr := n.smartWalletConfig.FactoryAddress
if payload.GetFactoryAddress() != "" {
factoryAddr = common.HexToAddress(payload.GetFactoryAddress())
}
if err := n.validateNonZeroAddress(factoryAddr, "GetWallet", user.Address.Hex(), saltBig.String()); err != nil {
return nil, err
}
var derivedSenderAddress *common.Address
var err error
// Only try to derive address if rpcConn is available
if rpcConn != nil {
derivedSenderAddress, err = aa.GetSenderAddressForFactory(rpcConn, user.Address, factoryAddr, saltBig)
} else {
// In test environment or when RPC is unavailable, use a deterministic mock address
// This allows tests to run without external dependencies
n.logger.Debug("Using mock address derivation due to nil rpcConn (test environment)", "owner", user.Address.Hex(), "salt", saltBig.String())
// Create a deterministic address based on owner + factory + salt for testing
// Concatenate the bytes, hash with Keccak256, and take the last 20 bytes for the address
concatenated := append(append(user.Address.Bytes(), factoryAddr.Bytes()...), saltBig.Bytes()...)
hash := crypto.Keccak256(concatenated)
mockAddr := common.BytesToAddress(hash[12:]) // Take the last 20 bytes
derivedSenderAddress = &mockAddr
}
if err != nil || derivedSenderAddress == nil || *derivedSenderAddress == (common.Address{}) {
var errMsg string
if err != nil {
errMsg = err.Error()
}
n.logger.Warn("Failed to derive sender address or derived address is nil or zero for GetWallet", "owner", user.Address.Hex(), "factory", factoryAddr.Hex(), "salt", saltBig.String(), "derived", derivedSenderAddress, "error", errMsg, "hasRpcConn", rpcConn != nil)
return nil, status.Errorf(codes.InvalidArgument, "Failed to derive sender address or derived address is nil or zero. Error: %v", err)
}
dbModelWallet, err := GetWallet(n.db, user.Address, derivedSenderAddress.Hex())
if err != nil && err != badger.ErrKeyNotFound {
n.logger.Error("Error fetching wallet from DB for GetWallet", "owner", user.Address.Hex(), "wallet", derivedSenderAddress.Hex(), "error", err)
return nil, status.Errorf(codes.Code(avsproto.ErrorCode_STORAGE_UNAVAILABLE), "Error fetching wallet: %v", err)
}
if err == badger.ErrKeyNotFound {
// Enforce max smart wallet count per owner before creating a new wallet entry
// This check only applies when creating new wallet entries, not accessing existing ones
if n.smartWalletConfig != nil {
maxAllowed := n.smartWalletConfig.MaxWalletsPerOwner
if maxAllowed <= 0 {
maxAllowed = config.DefaultMaxWalletsPerOwner
}
if maxAllowed > config.HardMaxWalletsPerOwner {
maxAllowed = config.HardMaxWalletsPerOwner
}
// Fetch all wallets for this owner and count unique addresses
dbItems, listErr := n.db.GetByPrefix(WalletByOwnerPrefix(user.Address))
if listErr == nil {
unique := make(map[string]struct{})
for _, item := range dbItems {
storedModelWallet := &model.SmartWallet{}
if err := storedModelWallet.FromStorageData(item.Value); err == nil && storedModelWallet.Address != nil {
unique[strings.ToLower(storedModelWallet.Address.Hex())] = struct{}{}
}
}
if len(unique) >= maxAllowed {
return nil, status.Errorf(codes.ResourceExhausted, "max smart wallet count reached for owner (limit=%d)", maxAllowed)
}
}
}
n.logger.Info("Wallet not found in DB for GetWallet, creating new entry", "owner", user.Address.Hex(), "walletAddress", derivedSenderAddress.Hex())
n.markPreviousCanonicalStaleIfAny(user.Address, factoryAddr, saltBig, *derivedSenderAddress)
newModelWallet := &model.SmartWallet{
Owner: &user.Address,
Address: derivedSenderAddress,
Factory: &factoryAddr,
Salt: saltBig,
IsHidden: false,
}
if storeErr := StoreWallet(n.db, user.Address, newModelWallet); storeErr != nil {
n.logger.Error("Error storing new wallet to DB for GetWallet", "owner", user.Address.Hex(), "walletAddress", derivedSenderAddress.Hex(), "error", storeErr)
return nil, status.Errorf(codes.Code(avsproto.ErrorCode_STORAGE_WRITE_ERROR), "Error storing new wallet: %v", storeErr)
}
dbModelWallet = newModelWallet
}
resp := &avsproto.GetWalletResp{
Address: dbModelWallet.Address.Hex(),
Salt: dbModelWallet.Salt.String(),
FactoryAddress: dbModelWallet.Factory.Hex(),
IsHidden: dbModelWallet.IsHidden,
}
statSvc := NewStatService(n.db)
stat, statErr := statSvc.GetTaskCount(dbModelWallet)
if statErr != nil {
n.logger.Warn("Failed to get task count for GetWallet response", "walletAddress", dbModelWallet.Address.Hex(), "error", statErr)
}
resp.TotalTaskCount = stat.Total
resp.EnabledTaskCount = stat.Enabled
resp.CompletedTaskCount = stat.Completed
resp.FailedTaskCount = stat.Failed
resp.DisabledTaskCount = stat.Disabled
return resp, nil
}
// GetWalletFromDB retrieves wallet information from database for validation purposes
func (n *Engine) GetWalletFromDB(owner common.Address, smartWalletAddress string) (*model.SmartWallet, error) {
return GetWallet(n.db, owner, smartWalletAddress)
}
// SetWallet is the gRPC handler for the SetWallet RPC.
// It uses the owner (from auth context), salt, and factory_address from payload to identify/derive the wallet.
// It then sets the IsHidden status for that wallet.
func (n *Engine) SetWallet(owner common.Address, payload *avsproto.SetWalletReq) (*avsproto.GetWalletResp, error) {
// Allow empty factory address (uses default), but validate non-empty ones
if payload.GetFactoryAddress() != "" && !common.IsHexAddress(payload.GetFactoryAddress()) {
return nil, status.Errorf(codes.InvalidArgument, "Invalid factory address format: %s", payload.GetFactoryAddress())
}
saltBig, ok := math.ParseBig256(payload.GetSalt())
if !ok {
return nil, status.Errorf(codes.InvalidArgument, "Invalid salt format: %s", payload.GetSalt())
}
factoryAddr := n.smartWalletConfig.FactoryAddress // Default factory
if payload.GetFactoryAddress() != "" {
factoryAddr = common.HexToAddress(payload.GetFactoryAddress())
}
if err := n.validateNonZeroAddress(factoryAddr, "SetWallet", owner.Hex(), payload.GetSalt()); err != nil {
return nil, err
}
derivedWalletAddress, err := aa.GetSenderAddressForFactory(rpcConn, owner, factoryAddr, saltBig)
if err != nil {
n.logger.Error("Failed to derive wallet address for SetWallet", "owner", owner.Hex(), "salt", payload.GetSalt(), "factory", payload.GetFactoryAddress(), "error", err)
return nil, status.Errorf(codes.Internal, "Failed to derive wallet address: %v", err)
}
if derivedWalletAddress == nil || *derivedWalletAddress == (common.Address{}) {
n.logger.Error("Derived wallet address is nil or zero for SetWallet", "owner", owner.Hex(), "salt", payload.GetSalt(), "factory", payload.GetFactoryAddress())
return nil, status.Errorf(codes.Internal, "Derived wallet address is nil or zero")
}
err = SetWalletHiddenStatus(n.db, owner, derivedWalletAddress.Hex(), payload.GetIsHidden())
if err != nil {
if errors.Is(err, badger.ErrKeyNotFound) {
n.logger.Warn("Wallet not found for SetWallet", "owner", owner.Hex(), "derivedAddress", derivedWalletAddress.Hex(), "salt", payload.GetSalt(), "factory", payload.GetFactoryAddress())
// If wallet doesn't exist, SetWalletHiddenStatus from schema returns a wrapped ErrKeyNotFound.
// The SetWallet RPC is for existing wallets identified by salt/factory.
// So, if not found by identifiers, it's a NotFound error.
return nil, status.Errorf(codes.NotFound, "Wallet not found for the specified salt and factory.")
}
n.logger.Error("Failed to set wallet hidden status via schema.SetWalletHiddenStatus", "owner", owner.Hex(), "wallet", derivedWalletAddress.Hex(), "isHidden", payload.GetIsHidden(), "error", err)
return nil, status.Errorf(codes.Internal, "Failed to update wallet hidden status: %v", err)
}
updatedModelWallet, getErr := GetWallet(n.db, owner, derivedWalletAddress.Hex())
if getErr != nil {
n.logger.Error("Failed to fetch wallet after SetWallet operation", "owner", owner.Hex(), "wallet", derivedWalletAddress.Hex(), "error", getErr)
return nil, status.Errorf(codes.Internal, "Failed to retrieve wallet details after update: %v", getErr)
}
resp := &avsproto.GetWalletResp{
Address: updatedModelWallet.Address.Hex(),
Salt: updatedModelWallet.Salt.String(),
FactoryAddress: updatedModelWallet.Factory.Hex(),
IsHidden: updatedModelWallet.IsHidden,
}
statSvc := NewStatService(n.db)
stat, statErr := statSvc.GetTaskCount(updatedModelWallet)
if statErr != nil {
n.logger.Warn("Failed to get task count for SetWallet response", "walletAddress", updatedModelWallet.Address.Hex(), "error", statErr)
}
resp.TotalTaskCount = stat.Total
resp.EnabledTaskCount = stat.Enabled
resp.CompletedTaskCount = stat.Completed
resp.FailedTaskCount = stat.Failed
resp.DisabledTaskCount = stat.Disabled
return resp, nil
}
// resolveEventTriggerTemplates substitutes {{settings.*}} template literals in
// the EventTrigger queries' addresses and topics, mutating the trigger in place.
//
// Background: the operator subscribes to event filters at task-deploy time using
// the topics/addresses array verbatim from the stored task. It does not run the
// template resolver. If a topic slot contains an unresolved literal like
// "{{settings.runner}}", the operator cannot pad it as an address, the slot
// degenerates to a wildcard, and the filter matches any event on the contract
// instead of the intended `to=runner` constraint. This caused tasks to fire on
// unrelated transfers and exhaust their max_execution budget on noise.
//
// The simulate path (runEventTriggerImmediately in run_node_immediately.go) does
// the same resolution against a temp VM seeded with inputVariables. This helper
// is the equivalent for the persistence path used by CreateTask.
func resolveEventTriggerTemplates(trigger *avsproto.TaskTrigger, inputVariables map[string]*structpb.Value, logger sdklogging.Logger) error {
if trigger == nil {
return nil
}
eventTrigger := trigger.GetEvent()
if eventTrigger == nil || eventTrigger.GetConfig() == nil {
return nil
}
queries := eventTrigger.GetConfig().GetQueries()
if len(queries) == 0 {
return nil
}
tempVM := NewVM()
tempVM.logger = logger
for k, v := range inputVariables {
tempVM.AddVar(k, v.AsInterface())
}
for queryIdx, q := range queries {
for i, addr := range q.Addresses {
if !strings.Contains(addr, "{{") {
continue
}
// Resolve and always validate. If preprocessTextWithVariableMapping
// cannot resolve the template (e.g. inputVariables is missing the
// referenced key), it returns the original "{{...}}" string. That
// fails IsHexAddress and triggers the error below — preventing the
// no-op silent passthrough that would reintroduce the operator
// wildcard bug.
resolved := tempVM.preprocessTextWithVariableMapping(addr)
if !common.IsHexAddress(resolved) {
return fmt.Errorf("query[%d].addresses[%d]: template did not resolve to a valid Ethereum address: %s (original: %s)", queryIdx, i, resolved, addr)
}
q.Addresses[i] = resolved
if logger != nil {
logger.Info("EventTrigger: Resolved template in address (CreateTask)",
"original", addr, "resolved", resolved)
}
}
for i, topic := range q.Topics {
if !strings.Contains(topic, "{{") {
continue
}
// Same rationale: an unresolved "{{...}}" literal will not pass
// validateTopicHexFormat, so a no-op resolution becomes a hard error
// rather than a silently-broken topic filter.
resolved := tempVM.preprocessTextWithVariableMapping(topic)
if err := validateTopicHexFormat(resolved); err != nil {
return fmt.Errorf("query[%d].topics[%d]: %w (original: %s, resolved: %s)", queryIdx, i, err, topic, resolved)
}
q.Topics[i] = resolved
if logger != nil {
logger.Info("EventTrigger: Resolved template in topic value (CreateTask)",
"original", topic, "resolved", resolved)
}
}
}
return nil
}
// CreateTask records submission data
func (n *Engine) CreateTask(user *model.User, taskPayload *avsproto.CreateTaskReq) (*model.Task, error) {
var err error
userAddr := user.Address.Hex()
// Log the create task request with detailed information
n.logger.Info("📥 CreateTask request received",
"user", userAddr,
"smart_wallet_address", taskPayload.SmartWalletAddress,
"trigger_type", func() string {
if taskPayload.Trigger != nil {
return taskPayload.Trigger.Type.String()
}
return "nil"
}(),
"nodes_count", len(taskPayload.Nodes),
"edges_count", len(taskPayload.Edges),
"start_at", taskPayload.StartAt,
"expired_at", taskPayload.ExpiredAt,
"max_execution", taskPayload.MaxExecution,
"name", taskPayload.Name)
// Log node details for debugging serialization issues
if len(taskPayload.Nodes) > 0 {
var nodeTypes []string
for i, node := range taskPayload.Nodes {
nodeType := "unknown"
if node != nil {
nodeType = node.Type.String()