-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
actions.go
1338 lines (1192 loc) · 46.7 KB
/
actions.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package actions enables common chainlink interactions
package actions
import (
"context"
"crypto/ecdsa"
"fmt"
"math"
"math/big"
"math/rand"
"strings"
"sync"
"testing"
"time"
"github.com/pelletier/go-toml/v2"
geth "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/rpc"
"go.uber.org/zap/zapcore"
"github.com/smartcontractkit/chainlink-testing-framework/lib/blockchain"
"github.com/smartcontractkit/chainlink-testing-framework/lib/k8s/environment"
"github.com/smartcontractkit/chainlink-testing-framework/lib/logging"
"github.com/smartcontractkit/chainlink-testing-framework/lib/testreporters"
"github.com/smartcontractkit/chainlink-testing-framework/lib/utils/conversions"
"github.com/smartcontractkit/chainlink/integration-tests/contracts"
ethContracts "github.com/smartcontractkit/chainlink/integration-tests/contracts/ethereum"
"github.com/smartcontractkit/chainlink/integration-tests/wrappers"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/rs/zerolog"
"github.com/ethereum/go-ethereum/common"
"github.com/google/uuid"
"github.com/smartcontractkit/chainlink-testing-framework/seth"
gethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/pkg/errors"
"github.com/test-go/testify/require"
ctfconfig "github.com/smartcontractkit/chainlink-testing-framework/lib/config"
"github.com/smartcontractkit/chainlink-testing-framework/lib/utils/testcontext"
"github.com/smartcontractkit/chainlink/integration-tests/client"
"github.com/smartcontractkit/chainlink/integration-tests/testconfig/ocr"
"github.com/smartcontractkit/chainlink/integration-tests/types/config/node"
"github.com/smartcontractkit/chainlink/v2/core/gethwrappers/generated/link_token_interface"
"github.com/smartcontractkit/chainlink/v2/core/gethwrappers/generated/operator_factory"
)
// ChainlinkNodeAddresses will return all the on-chain wallet addresses for a set of Chainlink nodes
func ChainlinkNodeAddresses(nodes []*client.ChainlinkK8sClient) ([]common.Address, error) {
addresses := make([]common.Address, 0)
for _, node := range nodes {
primaryAddress, err := node.PrimaryEthAddress()
if err != nil {
return nil, err
}
addresses = append(addresses, common.HexToAddress(primaryAddress))
}
return addresses, nil
}
// ChainlinkNodeAddressesAtIndex will return all the on-chain wallet addresses for a set of Chainlink nodes
func ChainlinkNodeAddressesAtIndex(nodes []*client.ChainlinkK8sClient, keyIndex int) ([]common.Address, error) {
addresses := make([]common.Address, 0)
for _, node := range nodes {
nodeAddresses, err := node.EthAddresses()
if err != nil {
return nil, err
}
addresses = append(addresses, common.HexToAddress(nodeAddresses[keyIndex]))
}
return addresses, nil
}
// EncodeOnChainVRFProvingKey encodes uncompressed public VRF key to on-chain representation
func EncodeOnChainVRFProvingKey(vrfKey client.VRFKey) ([2]*big.Int, error) {
uncompressed := vrfKey.Data.Attributes.Uncompressed
provingKey := [2]*big.Int{}
var set1 bool
var set2 bool
// strip 0x to convert to int
provingKey[0], set1 = new(big.Int).SetString(uncompressed[2:66], 16)
if !set1 {
return [2]*big.Int{}, fmt.Errorf("can not convert VRF key to *big.Int")
}
provingKey[1], set2 = new(big.Int).SetString(uncompressed[66:], 16)
if !set2 {
return [2]*big.Int{}, fmt.Errorf("can not convert VRF key to *big.Int")
}
return provingKey, nil
}
// EncodeOnChainExternalJobID encodes external job uuid to on-chain representation
func EncodeOnChainExternalJobID(jobID uuid.UUID) [32]byte {
var ji [32]byte
copy(ji[:], strings.Replace(jobID.String(), "-", "", 4))
return ji
}
// todo - move to CTF
func GenerateWallet() (common.Address, error) {
privateKey, err := crypto.GenerateKey()
if err != nil {
return common.Address{}, err
}
publicKey := privateKey.Public()
publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
if !ok {
return common.Address{}, fmt.Errorf("cannot assert type: publicKey is not of type *ecdsa.PublicKey")
}
return crypto.PubkeyToAddress(*publicKeyECDSA), nil
}
// todo - move to CTF
func GetTxFromAddress(tx *types.Transaction) (string, error) {
from, err := types.Sender(types.LatestSignerForChainID(tx.ChainId()), tx)
return from.String(), err
}
// todo - move to CTF
func DecodeTxInputData(abiString string, data []byte) (map[string]interface{}, error) {
jsonABI, err := abi.JSON(strings.NewReader(abiString))
if err != nil {
return nil, err
}
methodSigData := data[:4]
inputsSigData := data[4:]
method, err := jsonABI.MethodById(methodSigData)
if err != nil {
return nil, err
}
inputsMap := make(map[string]interface{})
if err := method.Inputs.UnpackIntoMap(inputsMap, inputsSigData); err != nil {
return nil, err
}
return inputsMap, nil
}
// todo - move to CTF
func WaitForBlockNumberToBe(
ctx context.Context,
waitForBlockNumberToBe uint64,
client *seth.Client,
wg *sync.WaitGroup,
desiredBlockNumberReached chan<- bool,
timeout time.Duration,
l zerolog.Logger,
) (uint64, error) {
blockNumberChannel := make(chan uint64)
errorChannel := make(chan error)
testContext, testCancel := context.WithTimeout(context.Background(), timeout)
defer testCancel()
ticker := time.NewTicker(time.Second * 5)
var latestBlockNumber uint64
for {
select {
case <-testContext.Done():
ticker.Stop()
wg.Done()
return latestBlockNumber,
fmt.Errorf("timeout waiting for Block Number to be: %d. Last recorded block number was: %d",
waitForBlockNumberToBe, latestBlockNumber)
case <-ticker.C:
go func() {
currentBlockNumber, err := client.Client.BlockNumber(ctx)
if err != nil {
errorChannel <- err
}
l.Info().
Uint64("Latest Block Number", currentBlockNumber).
Uint64("Desired Block Number", waitForBlockNumberToBe).
Msg("Waiting for Block Number to be")
blockNumberChannel <- currentBlockNumber
}()
case latestBlockNumber = <-blockNumberChannel:
if latestBlockNumber >= waitForBlockNumberToBe {
ticker.Stop()
wg.Done()
if desiredBlockNumberReached != nil {
desiredBlockNumberReached <- true
}
l.Info().
Uint64("Latest Block Number", latestBlockNumber).
Uint64("Desired Block Number", waitForBlockNumberToBe).
Msg("Desired Block Number reached!")
return latestBlockNumber, nil
}
case err := <-errorChannel:
ticker.Stop()
wg.Done()
return 0, err
}
}
}
var ContractDeploymentInterval = 200
// FundChainlinkNodesFromRootAddress sends native token amount (expressed in human-scale) to each Chainlink Node
// from root private key. It returns an error if any of the transactions failed.
func FundChainlinkNodesFromRootAddress(
logger zerolog.Logger,
client *seth.Client,
nodes []contracts.ChainlinkNodeWithKeysAndAddress,
amount *big.Float,
) error {
if len(client.PrivateKeys) == 0 {
return errors.Wrap(errors.New(seth.ErrNoKeyLoaded), fmt.Sprintf("requested key: %d", 0))
}
return FundChainlinkNodes(logger, client, nodes, client.PrivateKeys[0], amount)
}
// FundChainlinkNodes sends native token amount (expressed in human-scale) to each Chainlink Node
// from private key's address. It returns an error if any of the transactions failed.
func FundChainlinkNodes(
logger zerolog.Logger,
client *seth.Client,
nodes []contracts.ChainlinkNodeWithKeysAndAddress,
privateKey *ecdsa.PrivateKey,
amount *big.Float,
) error {
keyAddressFn := func(cl contracts.ChainlinkNodeWithKeysAndAddress) (string, error) {
return cl.PrimaryEthAddress()
}
return fundChainlinkNodesAtAnyKey(logger, client, nodes, privateKey, amount, keyAddressFn)
}
// FundChainlinkNodesAtKeyIndexFromRootAddress sends native token amount (expressed in human-scale) to each Chainlink Node
// from root private key.It returns an error if any of the transactions failed. It sends the funds to
// node address at keyIndex (as each node can have multiple addresses).
func FundChainlinkNodesAtKeyIndexFromRootAddress(
logger zerolog.Logger,
client *seth.Client,
nodes []contracts.ChainlinkNodeWithKeysAndAddress,
amount *big.Float,
keyIndex int,
) error {
if len(client.PrivateKeys) == 0 {
return errors.Wrap(errors.New(seth.ErrNoKeyLoaded), fmt.Sprintf("requested key: %d", 0))
}
return FundChainlinkNodesAtKeyIndex(logger, client, nodes, client.PrivateKeys[0], amount, keyIndex)
}
// FundChainlinkNodesAtKeyIndex sends native token amount (expressed in human-scale) to each Chainlink Node
// from private key's address. It returns an error if any of the transactions failed. It sends the funds to
// node address at keyIndex (as each node can have multiple addresses).
func FundChainlinkNodesAtKeyIndex(
logger zerolog.Logger,
client *seth.Client,
nodes []contracts.ChainlinkNodeWithKeysAndAddress,
privateKey *ecdsa.PrivateKey,
amount *big.Float,
keyIndex int,
) error {
keyAddressFn := func(cl contracts.ChainlinkNodeWithKeysAndAddress) (string, error) {
toAddress, err := cl.EthAddresses()
if err != nil {
return "", err
}
return toAddress[keyIndex], nil
}
return fundChainlinkNodesAtAnyKey(logger, client, nodes, privateKey, amount, keyAddressFn)
}
func fundChainlinkNodesAtAnyKey(
logger zerolog.Logger,
client *seth.Client,
nodes []contracts.ChainlinkNodeWithKeysAndAddress,
privateKey *ecdsa.PrivateKey,
amount *big.Float,
keyAddressFn func(contracts.ChainlinkNodeWithKeysAndAddress) (string, error),
) error {
for _, cl := range nodes {
toAddress, err := keyAddressFn(cl)
if err != nil {
return err
}
fromAddress, err := PrivateKeyToAddress(privateKey)
if err != nil {
return err
}
receipt, err := SendFunds(logger, client, FundsToSendPayload{
ToAddress: common.HexToAddress(toAddress),
Amount: conversions.EtherToWei(amount),
PrivateKey: privateKey,
})
if err != nil {
logger.Err(err).
Str("From", fromAddress.Hex()).
Str("To", toAddress).
Msg("Failed to fund Chainlink node")
return err
}
txHash := "(none)"
if receipt != nil {
txHash = receipt.TxHash.String()
}
logger.Info().
Str("From", fromAddress.Hex()).
Str("To", toAddress).
Str("TxHash", txHash).
Str("Amount", amount.String()).
Msg("Funded Chainlink node")
}
return nil
}
type FundsToSendPayload struct {
ToAddress common.Address
Amount *big.Int
PrivateKey *ecdsa.PrivateKey
GasLimit *int64
GasPrice *big.Int
GasFeeCap *big.Int
GasTipCap *big.Int
TxTimeout *time.Duration
}
// TODO: move to CTF?
// SendFunds sends native token amount (expressed in human-scale) from address controlled by private key
// to given address. You can override any or none of the following: gas limit, gas price, gas fee cap, gas tip cap.
// Values that are not set will be estimated or taken from config.
func SendFunds(logger zerolog.Logger, client *seth.Client, payload FundsToSendPayload) (*types.Receipt, error) {
fromAddress, err := PrivateKeyToAddress(payload.PrivateKey)
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), client.Cfg.Network.TxnTimeout.Duration())
nonce, err := client.Client.PendingNonceAt(ctx, fromAddress)
defer cancel()
if err != nil {
return nil, err
}
var gasLimit int64
gasLimitRaw, err := client.EstimateGasLimitForFundTransfer(fromAddress, payload.ToAddress, payload.Amount)
if err != nil {
gasLimit = client.Cfg.Network.TransferGasFee
} else {
gasLimit = int64(gasLimitRaw)
}
gasPrice := big.NewInt(0)
gasFeeCap := big.NewInt(0)
gasTipCap := big.NewInt(0)
if payload.GasLimit != nil {
gasLimit = *payload.GasLimit
}
if client.Cfg.Network.EIP1559DynamicFees {
// if any of the dynamic fees are not set, we need to either estimate them or read them from config
if payload.GasFeeCap == nil || payload.GasTipCap == nil {
// estimation or config reading happens here
txOptions := client.NewTXOpts(seth.WithGasLimit(uint64(gasLimit)))
gasFeeCap = txOptions.GasFeeCap
gasTipCap = txOptions.GasTipCap
}
// override with payload values if they are set
if payload.GasFeeCap != nil {
gasFeeCap = payload.GasFeeCap
}
if payload.GasTipCap != nil {
gasTipCap = payload.GasTipCap
}
} else {
if payload.GasPrice == nil {
txOptions := client.NewTXOpts(seth.WithGasLimit(uint64(gasLimit)))
gasPrice = txOptions.GasPrice
} else {
gasPrice = payload.GasPrice
}
}
var rawTx types.TxData
if client.Cfg.Network.EIP1559DynamicFees {
rawTx = &types.DynamicFeeTx{
Nonce: nonce,
To: &payload.ToAddress,
Value: payload.Amount,
Gas: uint64(gasLimit),
GasFeeCap: gasFeeCap,
GasTipCap: gasTipCap,
}
} else {
rawTx = &types.LegacyTx{
Nonce: nonce,
To: &payload.ToAddress,
Value: payload.Amount,
Gas: uint64(gasLimit),
GasPrice: gasPrice,
}
}
signedTx, err := types.SignNewTx(payload.PrivateKey, types.LatestSignerForChainID(big.NewInt(client.ChainID)), rawTx)
if err != nil {
return nil, errors.Wrap(err, "failed to sign tx")
}
txTimeout := client.Cfg.Network.TxnTimeout.Duration()
if payload.TxTimeout != nil {
txTimeout = *payload.TxTimeout
}
logger.Debug().
Str("From", fromAddress.Hex()).
Str("To", payload.ToAddress.Hex()).
Str("Amount (wei/ether)", fmt.Sprintf("%s/%s", payload.Amount, conversions.WeiToEther(payload.Amount).Text('f', -1))).
Uint64("Nonce", nonce).
Int64("Gas Limit", gasLimit).
Str("Gas Price", gasPrice.String()).
Str("Gas Fee Cap", gasFeeCap.String()).
Str("Gas Tip Cap", gasTipCap.String()).
Bool("Dynamic fees", client.Cfg.Network.EIP1559DynamicFees).
Msg("About to send funds")
ctx, cancel = context.WithTimeout(ctx, txTimeout)
defer cancel()
err = client.Client.SendTransaction(ctx, signedTx)
if err != nil {
return nil, errors.Wrap(err, "failed to send transaction")
}
logger.Debug().
Str("From", fromAddress.Hex()).
Str("To", payload.ToAddress.Hex()).
Str("TxHash", signedTx.Hash().String()).
Str("Amount (wei/ether)", fmt.Sprintf("%s/%s", payload.Amount, conversions.WeiToEther(payload.Amount).Text('f', -1))).
Uint64("Nonce", nonce).
Int64("Gas Limit", gasLimit).
Str("Gas Price", gasPrice.String()).
Str("Gas Fee Cap", gasFeeCap.String()).
Str("Gas Tip Cap", gasTipCap.String()).
Bool("Dynamic fees", client.Cfg.Network.EIP1559DynamicFees).
Msg("Sent funds")
receipt, receiptErr := client.WaitMined(ctx, logger, client.Client, signedTx)
if receiptErr != nil {
return nil, errors.Wrap(receiptErr, "failed to wait for transaction to be mined")
}
if receipt.Status == 1 {
return receipt, nil
}
tx, _, err := client.Client.TransactionByHash(ctx, signedTx.Hash())
if err != nil {
return nil, errors.Wrap(err, "failed to get transaction by hash ")
}
_, err = client.Decode(tx, receiptErr)
if err != nil {
return nil, err
}
return receipt, nil
}
// DeployForwarderContracts first deploys Operator Factory and then uses it to deploy given number of
// operator and forwarder pairs. It waits for each transaction to be mined and then extracts operator and
// forwarder addresses from emitted events.
func DeployForwarderContracts(
t *testing.T,
seth *seth.Client,
linkTokenAddress common.Address,
numberOfOperatorForwarderPairs int,
) (operators []common.Address, authorizedForwarders []common.Address, operatorFactoryInstance contracts.OperatorFactory) {
instance, err := contracts.DeployEthereumOperatorFactory(seth, linkTokenAddress)
require.NoError(t, err, "failed to create new instance of operator factory")
operatorFactoryInstance = &instance
for i := 0; i < numberOfOperatorForwarderPairs; i++ {
tx, deployErr := operatorFactoryInstance.DeployNewOperatorAndForwarder()
decodedTx, err := seth.Decode(tx, deployErr)
require.NoError(t, err, "Deploying new operator with proposed ownership with forwarder shouldn't fail")
for i, event := range decodedTx.Events {
require.True(t, len(event.Topics) > 0, fmt.Sprintf("Event %d should have topics", i))
switch event.Topics[0] {
case operator_factory.OperatorFactoryOperatorCreated{}.Topic().String():
if address, ok := event.EventData["operator"]; ok {
operators = append(operators, address.(common.Address))
} else {
require.Fail(t, "Operator address not found in event", event)
}
case operator_factory.OperatorFactoryAuthorizedForwarderCreated{}.Topic().String():
if address, ok := event.EventData["forwarder"]; ok {
authorizedForwarders = append(authorizedForwarders, address.(common.Address))
} else {
require.Fail(t, "Forwarder address not found in event", event)
}
}
}
}
return operators, authorizedForwarders, operatorFactoryInstance
}
// WatchNewOCRRound watches for a new OCR round, similarly to StartNewRound, but it does not explicitly request a new
// round from the contract, as this can cause some odd behavior in some cases. It announces success if latest round
// is >= roundNumber.
func WatchNewOCRRound(
l zerolog.Logger,
seth *seth.Client,
roundNumber int64,
ocrInstances []contracts.OffChainAggregatorWithRounds,
timeout time.Duration,
) error {
confirmed := make(map[string]bool)
timeoutC := time.After(timeout)
ticker := time.NewTicker(time.Millisecond * 200)
defer ticker.Stop()
l.Info().Msgf("Waiting for round %d to be confirmed by all nodes", roundNumber)
for {
select {
case <-timeoutC:
return fmt.Errorf("timeout waiting for round %d to be confirmed. %d/%d nodes confirmed it", roundNumber, len(confirmed), len(ocrInstances))
case <-ticker.C:
for i := 0; i < len(ocrInstances); i++ {
if confirmed[ocrInstances[i].Address()] {
continue
}
ctx, cancel := context.WithTimeout(context.Background(), seth.Cfg.Network.TxnTimeout.Duration())
roundData, err := ocrInstances[i].GetLatestRound(ctx)
if err != nil {
cancel()
return fmt.Errorf("getting latest round from OCR instance %d have failed: %w", i+1, err)
}
cancel()
if roundData.RoundId.Cmp(big.NewInt(roundNumber)) >= 0 {
l.Debug().Msgf("OCR instance %d/%d confirmed round %d", i+1, len(ocrInstances), roundNumber)
confirmed[ocrInstances[i].Address()] = true
}
}
if len(confirmed) == len(ocrInstances) {
return nil
}
}
}
}
// AcceptAuthorizedReceiversOperator sets authorized receivers for each operator contract to
// authorizedForwarder and authorized EA to nodeAddresses. Once done, it confirms that authorizations
// were set correctly.
func AcceptAuthorizedReceiversOperator(
t *testing.T,
logger zerolog.Logger,
seth *seth.Client,
operator common.Address,
authorizedForwarder common.Address,
nodeAddresses []common.Address,
) {
operatorInstance, err := contracts.LoadEthereumOperator(logger, seth, operator)
require.NoError(t, err, "Loading operator contract shouldn't fail")
forwarderInstance, err := contracts.LoadEthereumAuthorizedForwarder(seth, authorizedForwarder)
require.NoError(t, err, "Loading authorized forwarder contract shouldn't fail")
err = operatorInstance.AcceptAuthorizedReceivers([]common.Address{authorizedForwarder}, nodeAddresses)
require.NoError(t, err, "Accepting authorized forwarder shouldn't fail")
senders, err := forwarderInstance.GetAuthorizedSenders(testcontext.Get(t))
require.NoError(t, err, "Getting authorized senders shouldn't fail")
var nodesAddrs []string
for _, o := range nodeAddresses {
nodesAddrs = append(nodesAddrs, o.Hex())
}
require.Equal(t, nodesAddrs, senders, "Senders addresses should match node addresses")
owner, err := forwarderInstance.Owner(testcontext.Get(t))
require.NoError(t, err, "Getting authorized forwarder owner shouldn't fail")
require.Equal(t, operator.Hex(), owner, "Forwarder owner should match operator")
}
// TrackForwarder creates forwarder track for a given Chainlink node
func TrackForwarder(
t *testing.T,
seth *seth.Client,
authorizedForwarder common.Address,
node contracts.ChainlinkNodeWithForwarder,
) {
l := logging.GetTestLogger(t)
chainID := big.NewInt(seth.ChainID)
_, _, err := node.TrackForwarder(chainID, authorizedForwarder)
require.NoError(t, err, "Forwarder track should be created")
l.Info().Str("NodeURL", node.GetConfig().URL).
Str("ForwarderAddress", authorizedForwarder.Hex()).
Str("ChaindID", chainID.String()).
Msg("Forwarder tracked")
}
// SetupOCRv2Contracts deploys a number of OCRv2 contracts and configures them with defaults
func SetupOCRv2Contracts(
l zerolog.Logger,
seth *seth.Client,
ocrContractsConfig ocr.OffChainAggregatorsConfig,
linkTokenAddress common.Address,
transmitters []string,
ocrOptions contracts.OffchainOptions,
) ([]contracts.OffchainAggregatorV2, error) {
var ocrInstances []contracts.OffchainAggregatorV2
if ocrContractsConfig == nil {
return nil, fmt.Errorf("you need to pass non-nil OffChainAggregatorsConfig to setup OCR contracts")
}
if !ocrContractsConfig.UseExistingOffChainAggregatorsContracts() {
for contractCount := 0; contractCount < ocrContractsConfig.NumberOfContractsToDeploy(); contractCount++ {
ocrInstance, err := contracts.DeployOffchainAggregatorV2(
l,
seth,
linkTokenAddress,
ocrOptions,
)
if err != nil {
return nil, fmt.Errorf("OCRv2 instance deployment have failed: %w", err)
}
ocrInstances = append(ocrInstances, &ocrInstance)
if (contractCount+1)%ContractDeploymentInterval == 0 { // For large amounts of contract deployments, space things out some
time.Sleep(2 * time.Second)
}
}
} else {
for _, address := range ocrContractsConfig.OffChainAggregatorsContractsAddresses() {
ocrInstance, err := contracts.LoadOffchainAggregatorV2(l, seth, address)
if err != nil {
return nil, fmt.Errorf("OCRv2 instance loading have failed: %w", err)
}
ocrInstances = append(ocrInstances, &ocrInstance)
}
if !ocrContractsConfig.ConfigureExistingOffChainAggregatorsContracts() {
return ocrInstances, nil
}
}
// Gather address payees
var payees []string
for range transmitters {
payees = append(payees, seth.Addresses[0].Hex())
}
// Set Payees
for contractCount, ocrInstance := range ocrInstances {
err := ocrInstance.SetPayees(transmitters, payees)
if err != nil {
return nil, fmt.Errorf("error settings OCR payees: %w", err)
}
if (contractCount+1)%ContractDeploymentInterval == 0 { // For large amounts of contract deployments, space things out some
time.Sleep(2 * time.Second)
}
}
return ocrInstances, nil
}
// ConfigureOCRv2AggregatorContracts sets configuration for a number of OCRv2 contracts
func ConfigureOCRv2AggregatorContracts(
contractConfig *contracts.OCRv2Config,
ocrv2Contracts []contracts.OffchainAggregatorV2,
) error {
for contractCount, ocrInstance := range ocrv2Contracts {
// Exclude the first node, which will be used as a bootstrapper
err := ocrInstance.SetConfig(contractConfig)
if err != nil {
return fmt.Errorf("error setting OCR config for contract '%s': %w", ocrInstance.Address(), err)
}
if (contractCount+1)%ContractDeploymentInterval == 0 { // For large amounts of contract deployments, space things out some
time.Sleep(2 * time.Second)
}
}
return nil
}
// TeardownSuite tears down networks/clients and environment and creates a logs folder for failed tests in the
// specified path. Can also accept a testreporter (if one was used) to log further results
func TeardownSuite(
t *testing.T,
chainClient *seth.Client,
env *environment.Environment,
chainlinkNodes []*client.ChainlinkK8sClient,
optionalTestReporter testreporters.TestReporter, // Optionally pass in a test reporter to log further metrics
failingLogLevel zapcore.Level, // Examines logs after the test, and fails the test if any Chainlink logs are found at or above provided level
grafnaUrlProvider testreporters.GrafanaURLProvider,
) error {
l := logging.GetTestLogger(t)
if err := testreporters.WriteTeardownLogs(t, env, optionalTestReporter, failingLogLevel, grafnaUrlProvider); err != nil {
return fmt.Errorf("Error dumping environment logs, leaving environment running for manual retrieval, err: %w", err)
}
// Delete all jobs to stop depleting the funds
err := DeleteAllJobs(chainlinkNodes)
if err != nil {
l.Warn().Msgf("Error deleting jobs %+v", err)
}
if chainlinkNodes != nil && chainClient != nil {
if err := ReturnFundsFromNodes(l, chainClient, contracts.ChainlinkK8sClientToChainlinkNodeWithKeysAndAddress(chainlinkNodes)); err != nil {
// This printed line is required for tests that use real funds to propagate the failure
// out to the system running the test. Do not remove
fmt.Println(environment.FAILED_FUND_RETURN)
l.Error().Err(err).Str("Namespace", env.Cfg.Namespace).
Msg("Error attempting to return funds from chainlink nodes to network's default wallet. " +
"Environment is left running so you can try manually!")
}
} else {
l.Info().Msg("Successfully returned funds from chainlink nodes to default network wallets")
}
return env.Shutdown()
}
// TeardownRemoteSuite sends a report and returns funds from chainlink nodes to network's default wallet
func TeardownRemoteSuite(
t *testing.T,
client *seth.Client,
namespace string,
chainlinkNodes []*client.ChainlinkK8sClient,
optionalTestReporter testreporters.TestReporter, // Optionally pass in a test reporter to log further metrics
grafnaUrlProvider testreporters.GrafanaURLProvider,
) error {
l := logging.GetTestLogger(t)
if err := testreporters.SendReport(t, namespace, "./", optionalTestReporter, grafnaUrlProvider); err != nil {
l.Warn().Err(err).Msg("Error writing test report")
}
// Delete all jobs to stop depleting the funds
err := DeleteAllJobs(chainlinkNodes)
if err != nil {
l.Warn().Msgf("Error deleting jobs %+v", err)
}
if err = ReturnFundsFromNodes(l, client, contracts.ChainlinkK8sClientToChainlinkNodeWithKeysAndAddress(chainlinkNodes)); err != nil {
l.Error().Err(err).Str("Namespace", namespace).
Msg("Error attempting to return funds from chainlink nodes to network's default wallet. " +
"Environment is left running so you can try manually!")
}
return err
}
// DeleteAllJobs deletes all jobs from all chainlink nodes
// added here temporarily to avoid circular import
func DeleteAllJobs(chainlinkNodes []*client.ChainlinkK8sClient) error {
for _, node := range chainlinkNodes {
if node == nil {
return fmt.Errorf("found a nil chainlink node in the list of chainlink nodes while tearing down: %v", chainlinkNodes)
}
jobs, _, err := node.ReadJobs()
if err != nil {
return fmt.Errorf("error reading jobs from chainlink node, err: %w", err)
}
for _, maps := range jobs.Data {
if _, ok := maps["id"]; !ok {
return fmt.Errorf("error reading job id from chainlink node's jobs %+v", jobs.Data)
}
id := maps["id"].(string)
_, err := node.DeleteJob(id)
if err != nil {
return fmt.Errorf("error deleting job from chainlink node, err: %w", err)
}
}
}
return nil
}
// StartNewRound requests a new round from the ocr contracts and returns once transaction was mined
func StartNewRound(
ocrInstances []contracts.OffChainAggregatorWithRounds,
) error {
for i := 0; i < len(ocrInstances); i++ {
err := ocrInstances[i].RequestNewRound()
if err != nil {
return fmt.Errorf("requesting new OCR round %d have failed: %w", i+1, err)
}
}
return nil
}
// DeployOCRContractsForwarderFlow deploys and funds a certain number of offchain
// aggregator contracts with forwarders as effectiveTransmitters
func DeployOCRContractsForwarderFlow(
logger zerolog.Logger,
seth *seth.Client,
ocrContractsConfig ocr.OffChainAggregatorsConfig,
linkTokenContractAddress common.Address,
workerNodes []contracts.ChainlinkNodeWithKeysAndAddress,
forwarderAddresses []common.Address,
) ([]contracts.OffchainAggregator, error) {
transmitterPayeesFn := func() (transmitters []string, payees []string, err error) {
transmitters = make([]string, 0)
payees = make([]string, 0)
for _, forwarderCommonAddress := range forwarderAddresses {
forwarderAddress := forwarderCommonAddress.Hex()
transmitters = append(transmitters, forwarderAddress)
payees = append(payees, seth.Addresses[0].Hex())
}
return
}
transmitterAddressesFn := func() ([]common.Address, error) {
return forwarderAddresses, nil
}
return setupAnyOCRv1Contracts(logger, seth, ocrContractsConfig, linkTokenContractAddress, workerNodes, transmitterPayeesFn, transmitterAddressesFn)
}
// SetupOCRv1Contracts deploys and funds a certain number of offchain aggregator contracts or uses existing ones and returns a slice of contract wrappers.
func SetupOCRv1Contracts(
logger zerolog.Logger,
seth *seth.Client,
ocrContractsConfig ocr.OffChainAggregatorsConfig,
linkTokenContractAddress common.Address,
workerNodes []contracts.ChainlinkNodeWithKeysAndAddress,
) ([]contracts.OffchainAggregator, error) {
transmitterPayeesFn := func() (transmitters []string, payees []string, err error) {
transmitters = make([]string, 0)
payees = make([]string, 0)
for _, n := range workerNodes {
var addr string
addr, err = n.PrimaryEthAddress()
if err != nil {
err = fmt.Errorf("error getting node's primary ETH address: %w", err)
return
}
transmitters = append(transmitters, addr)
payees = append(payees, seth.Addresses[0].Hex())
}
return
}
transmitterAddressesFn := func() ([]common.Address, error) {
transmitterAddresses := make([]common.Address, 0)
for _, n := range workerNodes {
primaryAddress, err := n.PrimaryEthAddress()
if err != nil {
return nil, err
}
transmitterAddresses = append(transmitterAddresses, common.HexToAddress(primaryAddress))
}
return transmitterAddresses, nil
}
return setupAnyOCRv1Contracts(logger, seth, ocrContractsConfig, linkTokenContractAddress, workerNodes, transmitterPayeesFn, transmitterAddressesFn)
}
func setupAnyOCRv1Contracts(
logger zerolog.Logger,
seth *seth.Client,
ocrContractsConfig ocr.OffChainAggregatorsConfig,
linkTokenContractAddress common.Address,
workerNodes []contracts.ChainlinkNodeWithKeysAndAddress,
getTransmitterAndPayeesFn func() ([]string, []string, error),
getTransmitterAddressesFn func() ([]common.Address, error),
) ([]contracts.OffchainAggregator, error) {
var ocrInstances []contracts.OffchainAggregator
if ocrContractsConfig == nil {
return nil, fmt.Errorf("you need to pass non-nil OffChainAggregatorsConfig to setup OCR contracts")
}
if !ocrContractsConfig.UseExistingOffChainAggregatorsContracts() {
// Deploy contracts
for contractCount := 0; contractCount < ocrContractsConfig.NumberOfContractsToDeploy(); contractCount++ {
ocrInstance, err := contracts.DeployOffchainAggregator(logger, seth, linkTokenContractAddress, contracts.DefaultOffChainAggregatorOptions())
if err != nil {
return nil, fmt.Errorf("OCR instance deployment have failed: %w", err)
}
ocrInstances = append(ocrInstances, &ocrInstance)
if (contractCount+1)%ContractDeploymentInterval == 0 { // For large amounts of contract deployments, space things out some
time.Sleep(2 * time.Second)
}
}
} else {
// Load contract wrappers
for _, address := range ocrContractsConfig.OffChainAggregatorsContractsAddresses() {
ocrInstance, err := contracts.LoadOffChainAggregator(logger, seth, address)
if err != nil {
return nil, fmt.Errorf("OCR instance loading have failed: %w", err)
}
ocrInstances = append(ocrInstances, &ocrInstance)
}
if !ocrContractsConfig.ConfigureExistingOffChainAggregatorsContracts() {
return ocrInstances, nil
}
}
// Gather transmitter and address payees
var transmitters, payees []string
var err error
transmitters, payees, err = getTransmitterAndPayeesFn()
if err != nil {
return nil, fmt.Errorf("error getting transmitter and payees: %w", err)
}
// Set Payees
for contractCount, ocrInstance := range ocrInstances {
err := ocrInstance.SetPayees(transmitters, payees)
if err != nil {
return nil, fmt.Errorf("error settings OCR payees: %w", err)
}
if (contractCount+1)%ContractDeploymentInterval == 0 { // For large amounts of contract deployments, space things out some
time.Sleep(2 * time.Second)
}
}
// Set Config
transmitterAddresses, err := getTransmitterAddressesFn()
if err != nil {
return nil, fmt.Errorf("getting transmitter addresses should not fail: %w", err)
}
for contractCount, ocrInstance := range ocrInstances {
// Exclude the first node, which will be used as a bootstrapper
err = ocrInstance.SetConfig(
workerNodes,
contracts.DefaultOffChainAggregatorConfig(len(workerNodes)),
transmitterAddresses,
)
if err != nil {
return nil, fmt.Errorf("error setting OCR config for contract '%s': %w", ocrInstance.Address(), err)
}
if (contractCount+1)%ContractDeploymentInterval == 0 { // For large amounts of contract deployments, space things out some
time.Sleep(2 * time.Second)
}
}
return ocrInstances, nil
}
func PrivateKeyToAddress(privateKey *ecdsa.PrivateKey) (common.Address, error) {
publicKey := privateKey.Public()
publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
if !ok {
return common.Address{}, errors.New("error casting public key to ECDSA")
}
return crypto.PubkeyToAddress(*publicKeyECDSA), nil
}
func WatchNewFluxRound(
l zerolog.Logger,
seth *seth.Client,
roundNumber int64,
fluxInstance contracts.FluxAggregator,
timeout time.Duration,
) error {
timeoutC := time.After(timeout)
ticker := time.NewTicker(time.Millisecond * 200)
defer ticker.Stop()
l.Info().Msgf("Waiting for flux round %d to be confirmed by flux aggregator", roundNumber)
for {
select {
case <-timeoutC:
return fmt.Errorf("timeout waiting for round %d to be confirmed", roundNumber)
case <-ticker.C:
ctx, cancel := context.WithTimeout(context.Background(), seth.Cfg.Network.TxnTimeout.Duration())
roundId, err := fluxInstance.LatestRoundID(ctx)
if err != nil {
cancel()
return fmt.Errorf("getting latest round from flux instance has failed: %w", err)
}
cancel()
if roundId.Cmp(big.NewInt(roundNumber)) >= 0 {
l.Debug().Msgf("Flux instance confirmed round %d", roundNumber)
return nil
}
}
}
}
// EstimateCostForChainlinkOperations estimates the cost of running a number of operations on the Chainlink node based on estimated gas costs. It supports
// both legacy and EIP-1559 transactions.
func EstimateCostForChainlinkOperations(l zerolog.Logger, client *seth.Client, network blockchain.EVMNetwork, amountOfOperations int) (*big.Float, error) {
bigAmountOfOperations := big.NewInt(int64(amountOfOperations))
estimations := client.CalculateGasEstimations(client.NewDefaultGasEstimationRequest())