-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathchainreader.go
More file actions
1225 lines (1016 loc) · 40.3 KB
/
chainreader.go
File metadata and controls
1225 lines (1016 loc) · 40.3 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 reader
import (
"bytes"
"context"
"encoding/json"
"fmt"
"reflect"
"strconv"
"strings"
"sync"
"github.com/mitchellh/mapstructure"
"github.com/smartcontractkit/chainlink-common/pkg/services"
"github.com/smartcontractkit/chainlink-common/pkg/sqlutil"
"github.com/smartcontractkit/chainlink-aptos/relayer/chainreader/loop"
aptosCRConfig "github.com/smartcontractkit/chainlink-aptos/relayer/chainreader/config"
aptosCRUtils "github.com/smartcontractkit/chainlink-aptos/relayer/chainreader/utils"
"github.com/smartcontractkit/chainlink-sui/bindings/bind"
crUtil "github.com/smartcontractkit/chainlink-sui/relayer/chainreader/chainreader_util"
"github.com/smartcontractkit/chainlink-sui/relayer/chainreader/config"
"github.com/smartcontractkit/chainlink-sui/relayer/chainreader/database"
"github.com/smartcontractkit/chainlink-sui/relayer/chainreader/indexer"
"github.com/smartcontractkit/chainlink-sui/relayer/client"
"github.com/smartcontractkit/chainlink-sui/relayer/codec"
"github.com/smartcontractkit/chainlink-sui/relayer/common"
"github.com/smartcontractkit/chainlink-common/pkg/logger"
pkgtypes "github.com/smartcontractkit/chainlink-common/pkg/types"
"github.com/smartcontractkit/chainlink-common/pkg/types/query"
"github.com/smartcontractkit/chainlink-common/pkg/types/query/primitives"
)
const (
defaultQueryLimit = 25
readIdentifierParts = 3
offrampName = "OffRamp"
ccipPointerKey = "state_object::CCIPObjectRefPointer"
)
type suiChainReader struct {
pkgtypes.UnimplementedContractReader
logger logger.Logger
config config.ChainReaderConfig
starter services.StateMachine
packageResolver *crUtil.PackageResolver
client *client.PTBClient
dbStore *database.DBStore
indexer indexer.IndexerApi
// Cache of parent object IDs for pointer objects
// Key format: "{packageID}::{module}::{pointerName}"
// Value: parent object ID
parentObjectIDs map[string]string
parentObjectIDsMutex sync.RWMutex
}
var _ pkgtypes.ContractTypeProvider = &suiChainReader{}
type ExtendedContractReader interface {
pkgtypes.ContractReader
QueryKeyWithMetadata(ctx context.Context, contract pkgtypes.BoundContract, filter query.KeyFilter, limitAndSort query.LimitAndSort, sequenceDataType any) ([]aptosCRConfig.SequenceWithMetadata, error)
}
// readIdentifier represents the parsed components of a read identifier
type readIdentifier struct {
address string
contractName string
readName string
}
func NewChainReader(
ctx context.Context,
lgr logger.Logger,
ptbClient *client.PTBClient,
configs config.ChainReaderConfig,
db sqlutil.DataSource,
indexer indexer.IndexerApi,
) (pkgtypes.ContractReader, error) {
dbStore := database.NewDBStore(db, lgr)
err := dbStore.EnsureSchema(ctx)
if err != nil {
return nil, fmt.Errorf("failed to ensure database schema: %w", err)
}
return &suiChainReader{
logger: logger.Named(lgr, "SuiChainReader"),
client: ptbClient,
config: configs,
dbStore: dbStore,
packageResolver: crUtil.NewPackageResolver(lgr, ptbClient),
// indexers
indexer: indexer,
parentObjectIDs: make(map[string]string),
}, nil
}
func (s *suiChainReader) Name() string {
return s.logger.Name()
}
func (s *suiChainReader) Ready() error {
if err := s.starter.Ready(); err != nil {
return err
}
return nil
}
func (s *suiChainReader) HealthReport() map[string]error {
report := map[string]error{s.Name(): s.starter.Healthy()}
// Include indexer health status
if s.indexer != nil {
for k, v := range s.indexer.HealthReport() {
report[k] = v
}
}
return report
}
func (s *suiChainReader) Start(ctx context.Context) error {
return s.starter.StartOnce(s.Name(), func() error {
// set the event offset overrides for the event indexer if any
offsetOverrides := make(map[string]client.EventId)
for _, moduleConfig := range s.config.Modules {
for _, eventConfig := range moduleConfig.Events {
if eventConfig.EventSelectorDefaultOffset != nil {
key := fmt.Sprintf("%s::%s", eventConfig.EventSelector.Module, eventConfig.EventSelector.Event)
offsetOverrides[key] = *eventConfig.EventSelectorDefaultOffset
}
}
}
if len(offsetOverrides) > 0 {
// ignore this error to avoid blocking the start of the chain reader
_ = s.indexer.GetEventIndexer().SetEventOffsetOverrides(ctx, offsetOverrides)
}
return nil
})
}
func (s *suiChainReader) Close() error {
return s.starter.StopOnce(s.Name(), func() error {
return nil
})
}
func (s *suiChainReader) Bind(ctx context.Context, bindings []pkgtypes.BoundContract) error {
offrampPackageAddress := ""
for _, binding := range bindings {
err := s.packageResolver.BindPackage(binding.Name, binding.Address)
if err != nil {
return fmt.Errorf("failed to bind package: %w", err)
}
// Pre-load parent object IDs for known pointer types
if err := s.preloadParentObjectIDs(ctx, binding); err != nil {
s.logger.Warnw("Failed to pre-load parent object IDs", "contract", binding.Name, "error", err)
}
if common.NormalizeName(binding.Name) == common.NormalizeName(offrampName) {
offrampPackageAddress = binding.Address
}
}
// If the "OffRamp" package/module is now bound, set the offramp package ID for the tx indexer
if offrampPackageAddress != "" {
// Get the latest package ID for the offramp module. The transaction indexer watches the latest package ID for the offramp module
// to capture failed transactions.
latestPackageID, err := s.client.GetLatestPackageId(ctx, offrampPackageAddress, "offramp")
if err != nil {
s.logger.Errorw("Failed to get latest package ID for OffRamp", "error", err)
// Use the currently available package address for the offramp module as a fallback
s.indexer.GetTransactionIndexer().SetOffRampPackage(offrampPackageAddress, offrampPackageAddress)
} else {
s.indexer.GetTransactionIndexer().SetOffRampPackage(offrampPackageAddress, latestPackageID)
}
// Ensure that the event indexer has the SourceChainConfigSet event selector, this is needed to make sure
// transaction indexer can find the relevant data when inserting synthetic events.
err = s.indexer.GetEventIndexer().AddEventSelector(ctx, &client.EventSelector{
Package: offrampPackageAddress,
Module: "offramp",
Event: "SourceChainConfigSet",
})
if err != nil {
s.logger.Errorw("Failed to update offramp::SourceChainConfigSet event selector when binding OffRamp", "error", err)
}
err = s.indexer.GetEventIndexer().AddEventSelector(ctx, &client.EventSelector{
Package: offrampPackageAddress,
Module: "ocr3_base",
Event: "ConfigSet",
})
if err != nil {
s.logger.Errorw("Failed to update ocr3_base::ConfigSet event selector when binding OffRamp", "error", err)
}
}
return nil
}
func (s *suiChainReader) Unbind(ctx context.Context, bindings []pkgtypes.BoundContract) error {
for _, binding := range bindings {
if err := s.packageResolver.UnbindPackage(binding.Name); err != nil {
return fmt.Errorf("failed to unbind package %s: %w", binding.Name, err)
}
modulePrefix := fmt.Sprintf("%s::%s::", binding.Address, binding.Name)
// Clear cached parent object IDs for this unbound contract
s.parentObjectIDsMutex.Lock()
for key := range s.parentObjectIDs {
if strings.HasPrefix(key, modulePrefix) {
delete(s.parentObjectIDs, key)
}
}
s.parentObjectIDsMutex.Unlock()
}
return nil
}
// preloadParentObjectIDs pre-loads parent object IDs for known pointer types at binding time.
// This reduces RPC calls during GetLatestValue by caching parent IDs upfront.
func (s *suiChainReader) preloadParentObjectIDs(ctx context.Context, binding pkgtypes.BoundContract) error {
pointers := common.GetPointerConfigsByContract(binding.Name)
if len(pointers) == 0 {
return nil
}
// For OffRamp, we also need to load CCIP pointers
// If offramp is being bound
// Fetch the offramp's parent object ID
// From Offramp, we fetch the CCIP package ID
// Fetch CCIP's parent object ID
//
// We need Offramp state pointer too for offramp, not just CCIP
var ccipPackageID string
if strings.EqualFold(binding.Name, offrampName) {
var err error
ccipPackageID, err = s.client.GetCCIPPackageID(ctx, binding.Address, binding.Address)
if err != nil {
s.logger.Warnw("Failed to get CCIP package ID for OffRamp", "error", err)
} else {
// Add CCIP pointers with CCIP package ID
ccipPointers := common.GetPointerConfigsByContract("ccip")
pointers = append(pointers, ccipPointers...)
}
}
// Load each pointer's parent object ID
for _, ptr := range pointers {
packageID := binding.Address
// Use CCIP package ID for CCIP pointers when binding OffRamp
if ptr.Module == "state_object" && ccipPackageID != "" {
packageID = ccipPackageID
}
cacheKey := fmt.Sprintf("%s::%s::%s", packageID, ptr.Module, ptr.Pointer)
s.parentObjectIDsMutex.RLock()
_, exists := s.parentObjectIDs[cacheKey]
s.parentObjectIDsMutex.RUnlock()
if exists {
continue
}
parentObjectID, err := s.client.GetParentObjectID(ctx, packageID, ptr.Module, ptr.Pointer)
if err != nil {
s.logger.Debugw("Could not pre-load parent object ID",
"packageID", packageID,
"module", ptr.Module,
"pointer", ptr.Pointer,
"error", err)
continue // Skip this pointer, will load on-demand if needed
}
s.parentObjectIDsMutex.Lock()
s.parentObjectIDs[cacheKey] = parentObjectID
s.parentObjectIDsMutex.Unlock()
s.logger.Debugw("Pre-loaded parent object ID",
"cacheKey", cacheKey,
"parentObjectID", parentObjectID)
}
return nil
}
// GetLatestValue retrieves the latest value from either an object or function call
func (s *suiChainReader) GetLatestValue(ctx context.Context, readIdentifier string, confidenceLevel primitives.ConfidenceLevel, params, returnVal any) error {
parsed, err := s.parseReadIdentifier(readIdentifier)
if err != nil {
return err
}
_, contractName, method := parsed.address, parsed.contractName, parsed.readName
if err = s.validateContractBindingAndConfig(parsed.contractName, parsed.address); err != nil {
return err
}
if params == nil || reflect.ValueOf(params).IsNil() {
params = make(map[string]any)
}
// this ensures we are using values from chain-reader config set in core
moduleConfig, ok := s.config.Modules[contractName]
if !ok {
return fmt.Errorf("no such contract: %s", contractName)
}
if moduleConfig.Functions == nil {
return fmt.Errorf("no functions for contract: %s", contractName)
}
functionConfig, ok := moduleConfig.Functions[method]
if !ok {
return fmt.Errorf("no such method: %s", method)
}
if moduleConfig.Name != "" {
parsed.contractName = moduleConfig.Name
}
if functionConfig.Name != "" {
parsed.readName = functionConfig.Name
}
s.logger.Debugw("calling function after overwrite",
"address", parsed.address,
"contract", parsed.contractName,
"function", parsed.readName,
)
results, err := s.callFunction(ctx, parsed, params, functionConfig)
if err != nil {
return err
}
if functionConfig.ResultTupleToStruct != nil {
structResult := make(map[string]any)
// Check the length of results to avoid panics
if len(results) < len(functionConfig.ResultTupleToStruct) {
return fmt.Errorf("expected %d results, got %d", len(functionConfig.ResultTupleToStruct), len(results))
}
for i, mapKey := range functionConfig.ResultTupleToStruct {
structResult[mapKey] = results[i]
}
// Apply result field renames if configured
if functionConfig.ResultFieldRenames != nil {
err = aptosCRUtils.MaybeRenameFields(structResult, functionConfig.ResultFieldRenames)
if err != nil {
return fmt.Errorf("failed to rename result fields in GetLatestValue: %w", err)
}
}
// if we are running in loop plugin mode, we will want to encode the result into JSON bytes
if s.config.IsLoopPlugin {
return s.encodeLoopResult(structResult, returnVal)
}
return codec.DecodeSuiJsonValue(structResult, returnVal)
}
// otherwise, no tuple to struct specification, just a slice of values
if s.config.IsLoopPlugin {
// Apply renames to the result slice or contained maps before encoding
var renamed any = results
if functionConfig.ResultFieldRenames != nil {
err = aptosCRUtils.MaybeRenameFields(renamed, functionConfig.ResultFieldRenames)
if err != nil {
return fmt.Errorf("failed to rename result fields in GetLatestValue: %w", err)
}
}
return s.encodeLoopResult(renamed, returnVal)
}
s.logger.Debugw("GLV results before decoding to SUI json", "results", results, "returnVal", returnVal)
// Apply renames (if any) to the primary result element before decoding
responseValues := make([]any, len(results))
for i, result := range results {
current := result
if functionConfig.ResultFieldRenames != nil {
err = aptosCRUtils.MaybeRenameFields(current, functionConfig.ResultFieldRenames)
if err != nil {
return fmt.Errorf("failed to rename result fields in GetLatestValue: %w", err)
}
}
responseValues[i] = current
}
if len(results) > 1 {
return codec.DecodeSuiJsonValue(responseValues, returnVal)
}
return codec.DecodeSuiJsonValue(results[0], returnVal)
}
// QueryKey queries events from the indexer database for events that were populated from the RPC node
func (s *suiChainReader) QueryKey(ctx context.Context, contract pkgtypes.BoundContract, filter query.KeyFilter, limitAndSort query.LimitAndSort, sequenceDataType any) ([]pkgtypes.Sequence, error) {
eventConfig, err := s.updateEventConfigs(ctx, contract, filter)
if err != nil {
return nil, err
}
// Query events from database
eventRecords, err := s.queryEvents(ctx, eventConfig, filter.Expressions, limitAndSort)
if err != nil {
return nil, err
}
// Transform events to sequences
sequences, err := s.transformEventsToSequences(eventRecords, eventConfig.ExpectedEventType, sequenceDataType, false)
if err != nil {
return nil, err
}
transformedSequences := make([]pkgtypes.Sequence, 0)
for _, seq := range sequences {
transformedSequences = append(transformedSequences, seq.Sequence)
}
return transformedSequences, nil
}
type cursor struct {
EventOffset int64 `json:"event_offset"`
}
func (s *suiChainReader) QueryKeyWithMetadata(ctx context.Context, contract pkgtypes.BoundContract, filter query.KeyFilter, limitAndSort query.LimitAndSort, sequenceDataType any) ([]aptosCRConfig.SequenceWithMetadata, error) {
eventConfig, err := s.updateEventConfigs(ctx, contract, filter)
if err != nil {
return nil, err
}
// Query events from database
eventRecords, err := s.queryEvents(ctx, eventConfig, filter.Expressions, limitAndSort)
if err != nil {
return nil, err
}
// Transform events to sequences
sequences, err := s.transformEventsToSequences(eventRecords, eventConfig.ExpectedEventType, sequenceDataType, true)
if err != nil {
return nil, err
}
// Transform events to enriched sequences (include metadata)
transformedSequences := make([]aptosCRConfig.SequenceWithMetadata, 0)
for _, seq := range sequences {
var c cursor
if err := json.Unmarshal([]byte(seq.Sequence.Cursor), &c); err != nil {
return nil, fmt.Errorf("failed to unmarshal cursor: %w", err)
}
seq.Sequence.Cursor = strconv.FormatInt(c.EventOffset, 10)
transformedSequences = append(transformedSequences, aptosCRConfig.SequenceWithMetadata{
Sequence: seq.Sequence,
TxVersion: 0,
TxHash: seq.Record.TxDigest,
})
}
return transformedSequences, nil
}
func (s *suiChainReader) BatchGetLatestValues(ctx context.Context, request pkgtypes.BatchGetLatestValuesRequest) (pkgtypes.BatchGetLatestValuesResult, error) {
result := make(pkgtypes.BatchGetLatestValuesResult)
for contract, batch := range request {
batchResults := make(pkgtypes.ContractBatchResults, len(batch))
resultChan := make(chan struct {
index int
result pkgtypes.BatchReadResult
}, len(batch))
var waitgroup sync.WaitGroup
waitgroup.Add(len(batch))
for i, read := range batch {
go func(index int, read pkgtypes.BatchRead, contract pkgtypes.BoundContract) {
defer waitgroup.Done()
readResult := pkgtypes.BatchReadResult{ReadName: read.ReadName}
err := s.GetLatestValue(ctx, contract.ReadIdentifier(read.ReadName), primitives.Finalized, read.Params, read.ReturnVal)
readResult.SetResult(read.ReturnVal, err)
select {
case resultChan <- struct {
index int
result pkgtypes.BatchReadResult
}{index, readResult}:
case <-ctx.Done():
return
}
}(i, read, contract)
}
// wait for all the results to be processed then close the channel
go func() {
waitgroup.Wait()
close(resultChan)
}()
resultsReceived := 0
for res := range resultChan {
batchResults[res.index] = res.result
resultsReceived++
}
// check if all the results were received
if resultsReceived != len(batch) {
if err := ctx.Err(); err != nil {
return nil, err
}
return nil, fmt.Errorf("batch processing failed: expected %d results, received %d", len(batch), resultsReceived)
}
result[contract] = batchResults
}
return result, nil
}
func (s *suiChainReader) CreateContractType(readName string, forEncoding bool) (any, error) {
// only called when LOOP plugin
// TODO: should something be added to the LOOP plugin?
return &[]byte{}, nil
}
// parseReadIdentifier parses a read identifier string into its components
func (s *suiChainReader) parseReadIdentifier(identifier string) (*readIdentifier, error) {
components := strings.Split(identifier, "-")
if len(components) != readIdentifierParts {
return nil, fmt.Errorf("invalid read identifier format: %s (expected format: address-contract-readName)", identifier)
}
return &readIdentifier{
address: components[0],
contractName: components[1],
readName: components[2],
}, nil
}
func (s *suiChainReader) updateEventConfigs(ctx context.Context, contract pkgtypes.BoundContract, filter query.KeyFilter) (*config.ChainReaderEvent, error) {
// Validate contract binding
if err := s.validateContractBindingAndConfig(contract.Name, contract.Address); err != nil {
return nil, err
}
// Get module and event configuration
moduleConfig := s.config.Modules[contract.Name]
eventConfig, err := s.getEventConfig(moduleConfig, filter.Key)
// No event config found, construct a config
if err == nil && eventConfig == nil {
// construct a new config ad-hoc
eventConfig = &config.ChainReaderEvent{
Name: filter.Key,
EventType: filter.Key,
EventSelector: client.EventSelector{
Package: contract.Address,
Module: contract.Name,
Event: filter.Key,
},
}
} else if err != nil {
return nil, err
}
if moduleConfig.Name != "" && eventConfig.Name == "" {
eventConfig.Name = moduleConfig.Name
} else {
// If the module config has no name, use the module name from the event config
moduleConfig.Name = moduleConfig.Events[filter.Key].Module
}
if eventConfig.EventSelector.Module == "" {
eventConfig.EventSelector.Module = moduleConfig.Name
}
// only write contract address, rest will be handled during chainreader config
eventConfig.Package = contract.Address
evIndexer := s.indexer.GetEventIndexer()
// create a selector for the initial package ID
selector := client.EventSelector{
Package: contract.Address,
Module: eventConfig.EventSelector.Module,
Event: eventConfig.EventType,
}
// ensure that the event selector is included in the indexer's set for upcoming polling loop syncs
err = evIndexer.AddEventSelector(ctx, &selector)
if err != nil {
return nil, fmt.Errorf("failed to add event selector: %w", err)
}
return eventConfig, nil
}
// validateContractBinding validates the contract binding for QueryKey
func (s *suiChainReader) validateContractBindingAndConfig(name string, address string) error {
err := s.packageResolver.ValidateBinding(name, address)
if err != nil {
return fmt.Errorf("invalid binding for contract: %s", name)
}
if _, ok := s.config.Modules[name]; !ok {
return fmt.Errorf("no configuration for contract: %s", name)
}
return nil
}
// callFunction calls a contract function and returns the result
func (s *suiChainReader) callFunction(ctx context.Context, parsed *readIdentifier, params any, functionConfig *config.ChainReaderFunction) ([]any, error) {
argMap, err := s.parseParams(params, functionConfig)
if err != nil {
return nil, fmt.Errorf("failed to parse parameters: %w", err)
}
args, argTypes, err := s.prepareArguments(ctx, argMap, functionConfig, parsed)
if err != nil {
return nil, fmt.Errorf("failed to prepare arguments: %w", err)
}
// Extract generic type tags from function params
typeArgs, err := s.extractGenericTypeTags(ctx, parsed, functionConfig, args)
if err != nil {
return nil, fmt.Errorf("failed to extract generic type tags: %w", err)
}
responseValues, err := s.executeFunction(ctx, parsed, functionConfig, args, argTypes, typeArgs)
if err != nil {
return nil, err
}
return responseValues, nil
}
// Helper function to extract generic type tags
func (s *suiChainReader) extractGenericTypeTags(ctx context.Context, parsed *readIdentifier, functionConfig *config.ChainReaderFunction, args []any) ([]string, error) {
if functionConfig.Params == nil {
return []string{}, nil
}
// Use a map to track unique type tags and preserve order
uniqueTags := make(map[string]struct{})
keyOrder := make([]string, 0)
for paramIndex, param := range functionConfig.Params {
if param.GenericType != nil && *param.GenericType != "" {
genericType := *param.GenericType
// Only add if not already present
if _, exists := uniqueTags[genericType]; !exists {
keyOrder = append(keyOrder, genericType)
uniqueTags[genericType] = struct{}{}
}
} else if param.GenericDependency != nil && *param.GenericDependency != "" && paramIndex < len(args) {
genericType, err := s.fetchGenericDependency(ctx, ¶m, args[paramIndex])
if err != nil {
return nil, fmt.Errorf("failed to fetch generic dependency: %w", err)
}
if _, exists := uniqueTags[genericType]; !exists {
keyOrder = append(keyOrder, genericType)
uniqueTags[genericType] = struct{}{}
}
}
}
return keyOrder, nil
}
func (s *suiChainReader) fetchGenericDependency(
ctx context.Context,
param *codec.SuiFunctionParam,
paramValue any,
) (string, error) {
if param == nil || param.GenericDependency == nil || *param.GenericDependency == "" {
return "", fmt.Errorf("generic dependency is not set")
}
switch *param.GenericDependency {
case "get_token_pool_state_type":
if paramValue == nil || paramValue.(string) == "" {
return "", fmt.Errorf("param value is nil or empty string")
}
// Use the state object ID to deduce the type
stateObject, err := s.client.ReadObjectId(ctx, paramValue.(string))
if err != nil {
return "", fmt.Errorf("failed to read state object: %w", err)
}
s.logger.Debugw("stateObjectType", "stateObjectType", stateObject.Type)
genericType, err := parseGenericTypeFromObjectType(stateObject.Type)
if err != nil {
return "", err
}
return genericType, nil
default:
return "", fmt.Errorf("unknown generic dependency: %s", *param.GenericDependency)
}
}
// parseParams parses input parameters based on whether we're running as a LOOP plugin
func (s *suiChainReader) parseParams(params any, functionConfig *config.ChainReaderFunction) (map[string]any, error) {
argMap := make(map[string]any)
if params == nil {
return argMap, nil
}
if s.config.IsLoopPlugin {
return s.parseLoopParams(params, functionConfig)
}
if err := mapstructure.Decode(params, &argMap); err != nil {
return nil, fmt.Errorf("failed to decode parameters: %w", err)
}
// Ensure that the argMap is not nil
if len(argMap) == 0 {
argMap = make(map[string]any)
}
return argMap, nil
}
// parseLoopParams handles parameter parsing for LOOP plugin mode
func (s *suiChainReader) parseLoopParams(params any, functionConfig *config.ChainReaderFunction) (map[string]any, error) {
paramBytes, ok := params.(*[]byte)
if !ok {
return nil, fmt.Errorf("expected *[]byte for LOOP plugin params, got %T", params)
}
decoder := json.NewDecoder(bytes.NewReader(*paramBytes))
decoder.UseNumber()
var rawArgMap map[string]any
if err := decoder.Decode(&rawArgMap); err != nil {
return nil, fmt.Errorf("failed to unmarshal JSON params: %w", err)
}
// Convert JSON-unmarshaled values to proper Go types
argMap := make(map[string]any)
if functionConfig.Params != nil {
for _, paramConfig := range functionConfig.Params {
if jsonValue, exists := rawArgMap[paramConfig.Name]; exists {
convertedValue, err := codec.EncodeToSuiValue(paramConfig.Type, jsonValue)
if err != nil {
return nil, fmt.Errorf("failed to convert parameter %s of type %s: %w",
paramConfig.Name, paramConfig.Type, err)
}
argMap[paramConfig.Name] = convertedValue
}
}
}
return argMap, nil
}
type pointerMapEntry struct {
derivationKey string // the key used to derive the child object address
paramName string // the parameter name from the function config
}
// prepareArguments prepares function arguments and types for the call.
// For pointer tags, it looks up cached parent object IDs (pre-loaded during Bind) and derives
// child object IDs using the derivation keys specified in the pointer tags.
func (s *suiChainReader) prepareArguments(ctx context.Context, argMap map[string]any, functionConfig *config.ChainReaderFunction, identifier *readIdentifier) ([]any, []string, error) {
if functionConfig.Params == nil {
return []any{}, []string{}, nil
}
// a map of object selector "module::object" to array of fields
pointersMap := make(map[string][]pointerMapEntry)
pointerSelectors := make(map[string]readIdentifier)
// make a set of object pointers that need to fetched
// to read more about pointer tags, see the documentation in "/relayer/documentation/relayer/pointer-tags-in-cr.md"
for _, paramConfig := range functionConfig.Params {
// Skip if no pointer tag configured
if paramConfig.PointerTag == nil {
continue
}
if err := paramConfig.PointerTag.Validate(); err != nil {
return nil, nil, fmt.Errorf("invalid pointer tag for parameter %s: %w", paramConfig.Name, err)
}
pointerTag := paramConfig.PointerTag
// append only the middle 2 parts of the tag to represent the pointer
appendTag := strings.Join([]string{pointerTag.Module, pointerTag.PointerName}, "::")
if _, ok := pointersMap[appendTag]; !ok {
pointersMap[appendTag] = make([]pointerMapEntry, 0)
}
// add the pointer selector to the map which will later be used to fetch the values from the package owned object fields
if _, ok := pointerSelectors[appendTag]; !ok {
readIdentifierForPointer := readIdentifier{
address: identifier.address,
contractName: pointerTag.Module,
readName: pointerTag.PointerName,
}
// If the pointer tag specifies a PackageID, use it (for cross-package dependencies)
// This is needed when the pointer object is owned by a different package than the calling contract.
// e.g. When offramp calls a function that needs CCIPObjectRef from CCIP package,
// We must search for the pointer in CCIP's owned objects, not offramp's owned objects.
if pointerTag.PackageID != "" {
readIdentifierForPointer.address = pointerTag.PackageID
} else if identifier.contractName == strings.ToLower(offrampName) && appendTag == ccipPointerKey {
// Special case for OffRamp->CCIP pointer (legacy behavior)
// This is needed to override the specified address (will be offramp package ID) with the CCIP package ID
// Only handle offRamp case because other modules are within ccip package
ccipPackageID, err := s.client.GetCCIPPackageID(ctx, identifier.address, functionConfig.SignerAddress)
if err != nil {
return nil, nil, fmt.Errorf("failed to get CCIP package ID: %w", err)
}
readIdentifierForPointer.address = ccipPackageID
}
pointerSelectors[appendTag] = readIdentifierForPointer
}
// each entry within the pointersMap contains the derivation key and the (function config) parameter name
// the parent field name is looked up from common.PointerConfigs when fetching the parent object ID
pointersMap[appendTag] = append(pointersMap[appendTag], pointerMapEntry{
derivationKey: pointerTag.DerivationKey,
paramName: paramConfig.Name,
})
}
// fetch pointers
for pointerTag, pointerVals := range pointersMap {
selector := pointerSelectors[pointerTag]
// Try to get parent object ID from cache first
cacheKey := fmt.Sprintf("%s::%s::%s", selector.address, selector.contractName, selector.readName)
s.parentObjectIDsMutex.RLock()
parentObjectID, cached := s.parentObjectIDs[cacheKey]
s.parentObjectIDsMutex.RUnlock()
if !cached {
// Not in cache, fetch from RPC (fallback for on-demand loading)
var err error
parentObjectID, err = s.client.GetParentObjectID(
ctx, selector.address, selector.contractName, selector.readName,
)
if err != nil {
return nil, nil, fmt.Errorf("failed to get parent object ID: %w", err)
}
// Cache it for next time
s.parentObjectIDsMutex.Lock()
s.parentObjectIDs[cacheKey] = parentObjectID
s.parentObjectIDsMutex.Unlock()
s.logger.Debugw("Loaded parent object ID on-demand", "cacheKey", cacheKey, "parentObjectId", parentObjectID)
}
// Derive each field's object ID from parent using derivation key and add to arg map
for _, pointerVal := range pointerVals {
derivedID, err := bind.DeriveObjectIDWithVectorU8Key(parentObjectID, []byte(pointerVal.derivationKey))
if err != nil {
return nil, nil, fmt.Errorf("failed to derive object ID for %s using key %s: %w", pointerVal.paramName, pointerVal.derivationKey, err)
}
argMap[pointerVal.paramName] = derivedID
}
}
args := make([]any, 0, len(functionConfig.Params))
argTypes := make([]string, 0, len(functionConfig.Params))
// ensure that all the required arguments are present
for _, paramConfig := range functionConfig.Params {
argValue, ok := argMap[paramConfig.Name]
if !ok {
if paramConfig.Required {
return nil, nil, fmt.Errorf("missing required argument: %s", paramConfig.Name)
}
argValue = paramConfig.DefaultValue
}
args = append(args, argValue)
argTypes = append(argTypes, paramConfig.Type)
}
return args, argTypes, nil
}
// executeFunction executes the actual function call
func (s *suiChainReader) executeFunction(ctx context.Context, parsed *readIdentifier, functionConfig *config.ChainReaderFunction, args []any, argTypes []string, typeArgs []string) ([]any, error) {
s.logger.Debugw("Calling ReadFunction",
"address", parsed.address,
"module", parsed.contractName,
"method", parsed.readName,
"encodedArgs", args,
"argTypes", argTypes,
"typeArgs", typeArgs,
)
// Override the package ID with the latest package ID of the module being called.
// This ensure we are always using the latestPkgID in case of upgrades.
latestPackageId, err := s.client.GetLatestPackageId(ctx, parsed.address, common.GetModuleForContract(parsed.contractName))
if err != nil {
return []any{}, err
}
// this is the upgraded pkgID
parsed.address = latestPackageId
if len(functionConfig.StaticResponse) > 0 {
return functionConfig.StaticResponse, nil
} else if len(functionConfig.ResponseFromInputs) > 0 {
response := make([]any, 0)
for _, pluckFromInput := range functionConfig.ResponseFromInputs {
pluckParts := strings.Split(pluckFromInput, ".")
// if the pluckFromInput is empty, skip
if len(pluckParts) == 0 {
continue
}
switch pluckParts[0] {
case "package_id":
// if there are no more parts, return the package ID of the module for this function
if len(pluckParts) == 1 {
response = append(response, latestPackageId)
continue
}
// if there are more parts, return the package ID of the module (must be within the same package)
// this is useful in cases where getting the latest package ID is only possible within a single module
// that is different from the current module (e.g. RMNRemote -> CCIP latest package ID from `state_object` module)
moduleName := pluckParts[1]
modulePackageId, err := s.client.GetLatestPackageId(ctx, parsed.address, moduleName)
if err != nil {
s.logger.Debugw("Failed to get latest package ID for module", "moduleName", moduleName, "error", err)
// fallback to the latest package ID of the current module
response = append(response, latestPackageId)
continue
}
response = append(response, modulePackageId)
continue
case "params":
if len(pluckParts) != 2 {
continue
}
// match the param name to the arg index
for i, param := range functionConfig.Params {
if param.Name == pluckParts[1] {
response = append(response, args[i])
}
}
// Not found
continue
default:
return nil, fmt.Errorf("unknown response from inputs selection: %s", pluckFromInput)
}
}
return response, nil
}
values, err := s.client.ReadFunction(ctx, functionConfig.SignerAddress, parsed.address, parsed.contractName, parsed.readName, args, argTypes, typeArgs)
if err != nil {
s.logger.Errorw("ReadFunction failed",
"error", err,
"address", parsed.address,
"module", parsed.contractName,
"method", parsed.readName,
"args", args,
"argTypes", argTypes,
"typeArgs", typeArgs,