Skip to content

Modernize the codebase #851

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions chains/evm/gobindings/generation/abigen.go
Original file line number Diff line number Diff line change
Expand Up @@ -387,32 +387,32 @@ func writeAdditionalMethods(contractName string, logNames []string, abi abi.ABI,
`, contractName, logName, contractName, logName)
}

bs = append(bs, []byte(fmt.Sprintf(`
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to revert this file

bs = append(bs, fmt.Appendf(nil, `
func (_%v *%v) ParseLog(log types.Log) (generated.AbigenLog, error) {
switch log.Topics[0] {
%v
default:
return nil, fmt.Errorf("abigen wrapper received unknown log topic: %%v", log.Topics[0])
}
}
`, contractName, contractName, logSwitchBody))...)
`, contractName, contractName, logSwitchBody)...)
}

// Write the Topic method
for _, logName := range logNames {
bs = append(bs, []byte(fmt.Sprintf(`
bs = append(bs, fmt.Appendf(nil, `
func (%v%v) Topic() common.Hash {
return common.HexToHash("%v")
}
`, contractName, logName, abi.Events[logName].ID.Hex()))...)
`, contractName, logName, abi.Events[logName].ID.Hex())...)
}

// Write the Address method to the bottom of the file
bs = append(bs, []byte(fmt.Sprintf(`
bs = append(bs, fmt.Appendf(nil, `
func (_%v *%v) Address() common.Address {
return _%v.address
}
`, contractName, contractName, contractName))...)
`, contractName, contractName, contractName)...)

return bs
}
Expand Down
2 changes: 1 addition & 1 deletion commit/chainfee/observation.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ func feeUpdatesFromTimestampedBig(
// packedFee = (dataAvFeeUSD << 112) | executionFeeUSD
func fromPackedFee(packedFee *big.Int) ComponentsUSDPrices {
ones112 := big.NewInt(0)
for i := 0; i < 112; i++ {
for i := range 112 {
ones112 = ones112.SetBit(ones112, i, 1)
}

Expand Down
3 changes: 2 additions & 1 deletion commit/chainfee/observation_async.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/smartcontractkit/chainlink-ccip/pkg/logutil"
ccipreader "github.com/smartcontractkit/chainlink-ccip/pkg/reader"
cciptypes "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3"
"slices"
)

type observer interface {
Expand Down Expand Up @@ -101,7 +102,7 @@ func (o *baseObserver) getSupportedChains(
}

supportedChainsSlice := supportedChains.ToSlice()
sort.Slice(supportedChainsSlice, func(i, j int) bool { return supportedChainsSlice[i] < supportedChainsSlice[j] })
slices.Sort(supportedChainsSlice)

return supportedChainsSlice, nil
}
Expand Down
5 changes: 3 additions & 2 deletions commit/chainfee/observation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
reader2 "github.com/smartcontractkit/chainlink-ccip/mocks/internal_/reader"
"github.com/smartcontractkit/chainlink-ccip/mocks/pkg/reader"
"github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3"
"slices"
)

func Test_processor_Observation(t *testing.T) {
Expand Down Expand Up @@ -134,7 +135,7 @@ func Test_processor_Observation(t *testing.T) {

supportedSet.Remove(tc.dstChain)
slicesWithoutDst := supportedSet.ToSlice()
sort.Slice(slicesWithoutDst, func(i, j int) bool { return slicesWithoutDst[i] < slicesWithoutDst[j] })
slices.Sort(slicesWithoutDst)

if len(slicesWithoutDst) == 0 {
slicesWithoutDst = []ccipocr3.ChainSelector(nil)
Expand Down Expand Up @@ -333,7 +334,7 @@ func Test_unique_chain_filter_in_Observation(t *testing.T) {

supportedSet.Remove(tc.dstChain)
slicesWithoutDst := supportedSet.ToSlice()
sort.Slice(slicesWithoutDst, func(i, j int) bool { return slicesWithoutDst[i] < slicesWithoutDst[j] })
slices.Sort(slicesWithoutDst)

ccipReader.EXPECT().GetChainsFeeComponents(ctx, slicesWithoutDst).
Return(tc.chainFeeComponents).Maybe()
Expand Down
2 changes: 1 addition & 1 deletion commit/chainfee/outcome_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ var defaultChainConfig = reader.ChainConfig{
// sameObs returns n observations with the same observation but from different oracle ids
func sameObs(n int, obs Observation) []plugincommon.AttributedObservation[Observation] {
aos := make([]plugincommon.AttributedObservation[Observation], n)
for i := 0; i < n; i++ {
for i := range n {
aos[i] = plugincommon.AttributedObservation[Observation]{OracleID: commontypes.OracleID(i), Observation: obs}
}
return aos
Expand Down
5 changes: 1 addition & 4 deletions commit/factory_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,10 +168,7 @@ func Test_maxObservationLength(t *testing.T) {
// Generate a string with a counter and fill the rest with 'x's
func generateStringWithCounter(counter, length int) string {
counterStr := fmt.Sprintf("%d", counter)
paddingLength := length - len(counterStr)
if paddingLength < 0 {
paddingLength = 0
}
paddingLength := max(length-len(counterStr), 0)
return counterStr + strings.Repeat("x", paddingLength)
}

Expand Down
5 changes: 3 additions & 2 deletions commit/merkleroot/outcome_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"github.com/smartcontractkit/chainlink-ccip/internal/plugintypes"
cciptypes "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3"
"github.com/smartcontractkit/chainlink-ccip/pluginconfig"
"slices"
)

var rmnRemoteCfg = testhelpers.CreateRMNRemoteCfg()
Expand Down Expand Up @@ -401,7 +402,7 @@ func Test_Processor_Outcome(t *testing.T) {
func(tc testCase) Observation { return tc.observations[0](tc) },
func(tc testCase) Observation {
baseObs := tc.observations[0](tc)
baseObs.MerkleRoots = append(baseObs.MerkleRoots[:1], baseObs.MerkleRoots[2:]...) // skip chainB
baseObs.MerkleRoots = slices.Delete(baseObs.MerkleRoots, 1, 2) // skip chainB

// report a different onRamp address for chainC this leads to no consensus for chainC merkle roots
baseObs.MerkleRoots[1].OnRampAddress = []byte{0xd}
Expand Down Expand Up @@ -699,7 +700,7 @@ func Test_buildMerkleRootsOutcome(t *testing.T) {
}

lggr := logger.Test(t)
for i := 0; i < rounds; i++ {
for range rounds {
report1, err := buildMerkleRootsOutcome(Query{}, false, lggr, obs, Outcome{}, mockAddrCodec)
require.NoError(t, err)
report2, err := buildMerkleRootsOutcome(Query{}, false, lggr, obs, Outcome{}, mockAddrCodec)
Expand Down
13 changes: 6 additions & 7 deletions commit/merkleroot/rmn/controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import (

rmntypes "github.com/smartcontractkit/chainlink-ccip/commit/merkleroot/rmn/types"
cciptypes "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3"
"maps"
)

var (
Expand Down Expand Up @@ -415,7 +416,7 @@ func TestClient_ComputeReportSignatures(t *testing.T) {

const numNodes = 8
rmnNodes := make([]rmntypes.HomeNodeInfo, numNodes)
for i := 0; i < numNodes; i++ {
for i := range numNodes {
rmnNodes[i] = rmntypes.HomeNodeInfo{
ID: rmntypes.NodeID(i + 1),
PeerID: [32]byte{1, 2, 3},
Expand Down Expand Up @@ -733,7 +734,7 @@ func Test_controller_validateSignedObservationResponse(t *testing.T) {

func Test_newRequestID(t *testing.T) {
ids := map[uint64]struct{}{}
for i := 0; i < 1000; i++ {
for range 1000 {
id := newRequestID(logger.Test(t))
_, ok := ids[id]
assert.False(t, ok)
Expand Down Expand Up @@ -913,11 +914,11 @@ func (ts *testSetup) nodesRespondToTheObservationRequests(
laneUpdates := make([]*rmnpb.FixedDestLaneUpdate, 0)
for _, laneUpdate := range allLaneUpdates {
if requestedChains[nodeID].Contains(laneUpdate.LaneSource.SourceChainSelector) {
root := sha256.Sum256([]byte(fmt.Sprintf("%d[%d,%d]",
root := sha256.Sum256(fmt.Appendf(nil, "%d[%d,%d]",
laneUpdate.LaneSource.SourceChainSelector,
laneUpdate.ClosedInterval.MinMsgNr,
laneUpdate.ClosedInterval.MaxMsgNr,
)))
))
laneUpdates = append(laneUpdates, &rmnpb.FixedDestLaneUpdate{
LaneSource: laneUpdate.LaneSource,
ClosedInterval: laneUpdate.ClosedInterval,
Expand Down Expand Up @@ -1054,9 +1055,7 @@ func (m *mockPeerClient) getReceivedRequests() map[rmntypes.NodeID][]*rmnpb.Requ
cp := make(map[rmntypes.NodeID][]*rmnpb.Request)
m.mu.RLock()
defer m.mu.RUnlock()
for k, v := range m.receivedRequests {
cp[k] = v
}
maps.Copy(cp, m.receivedRequests)
return cp
}

Expand Down
2 changes: 1 addition & 1 deletion commit/merkleroot/rmn/streamconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ func bytesLimit(roundInterval time.Duration) ragep2p.TokenBucketParams {
// compute max observation request size and max report signatures request size
func init() {
fixedDestLaneUpdates := make([]*rmnpb.FixedDestLaneUpdate, 0, estimatedMaxNumberOfSourceChains)
for i := 0; i < estimatedMaxNumberOfSourceChains; i++ {
for range estimatedMaxNumberOfSourceChains {
fixedDestLaneUpdates = append(fixedDestLaneUpdates, &rmnpb.FixedDestLaneUpdate{
LaneSource: &rmnpb.LaneSource{
SourceChainSelector: math.MaxUint64,
Expand Down
3 changes: 2 additions & 1 deletion commit/merkleroot/transmission_checks.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/smartcontractkit/chainlink-ccip/internal/libs/slicelib"
"github.com/smartcontractkit/chainlink-ccip/pkg/reader"
cciptypes "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3"
"slices"
)

// ValidateMerkleRootsState validates the proposed merkle roots against the current on-chain state.
Expand Down Expand Up @@ -38,7 +39,7 @@ func ValidateMerkleRootsState(
}

chainSlice := chainSet.ToSlice()
sort.Slice(chainSlice, func(i, j int) bool { return chainSlice[i] < chainSlice[j] })
slices.Sort(chainSlice)

offRampExpNextSeqNums, err := reader.NextSeqNum(ctx, chainSlice)
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions commit/metrics/prom_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ func Test_LatencyAndErrors(t *testing.T) {
method := "observation"

passCounter := 10
for i := 0; i < passCounter; i++ {
for range passCounter {
reporter.TrackProcessorLatency(processor, method, time.Second, nil)
}
l2 := internal.CounterFromHistogramByLabels(t, reporter.processorLatencyHistogram, chainID, processor, method)
Expand All @@ -404,7 +404,7 @@ func Test_LatencyAndErrors(t *testing.T) {
method := "outcome"

errCounter := 5
for i := 0; i < errCounter; i++ {
for range errCounter {
reporter.TrackProcessorLatency(processor, method, time.Second, fmt.Errorf("error"))
}
errs := testutil.ToFloat64(
Expand Down
5 changes: 3 additions & 2 deletions commit/plugin_e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import (
reader2 "github.com/smartcontractkit/chainlink-ccip/pkg/reader"
"github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3"
"github.com/smartcontractkit/chainlink-ccip/pluginconfig"
"slices"
)

const (
Expand Down Expand Up @@ -847,7 +848,7 @@ func setupNode(params SetupNodeParams) nodeSetup {
for chainSel := range params.offRampNextSeqNum {
sourceChains = append(sourceChains, chainSel)
}
sort.Slice(sourceChains, func(i, j int) bool { return sourceChains[i] < sourceChains[j] })
slices.Sort(sourceChains)

offRampNextSeqNums := make(map[ccipocr3.ChainSelector]ccipocr3.SeqNum, 0)
chainsWithNewMsgs := make([]ccipocr3.ChainSelector, 0)
Expand All @@ -859,7 +860,7 @@ func setupNode(params SetupNodeParams) nodeSetup {
newMsgs := make([]ccipocr3.Message, 0)
numNewMsgs := (params.onRampLastSeqNum[sourceChain] - offRampNextSeqNum) + 1
for i := uint64(0); i < uint64(numNewMsgs); i++ {
messageID := sha256.Sum256([]byte(fmt.Sprintf("%d", uint64(offRampNextSeqNum)+i)))
messageID := sha256.Sum256(fmt.Appendf(nil, "%d", uint64(offRampNextSeqNum)+i))
newMsgs = append(newMsgs, ccipocr3.Message{
Header: ccipocr3.RampMessageHeader{
MessageID: messageID,
Expand Down
3 changes: 2 additions & 1 deletion commit/tokenprice/observation.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
pkgreader "github.com/smartcontractkit/chainlink-ccip/pkg/reader"
cciptypes "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3"
"github.com/smartcontractkit/chainlink-ccip/pluginconfig"
"slices"
)

func (p *processor) Observation(
Expand Down Expand Up @@ -139,7 +140,7 @@ func (b *baseObserver) observeFeeQuoterTokenUpdates(

tokensToQuery := maps.Keys(b.offChainCfg.TokenInfo)
// sort tokens to query to ensure deterministic order
sort.Slice(tokensToQuery, func(i, j int) bool { return tokensToQuery[i] < tokensToQuery[j] })
slices.Sort(tokensToQuery)
lggr.Infow("observing fee quoter token updates")
priceUpdates, err := b.tokenPriceReader.GetFeeQuoterTokenUpdates(ctx, tokensToQuery, b.destChain)
if err != nil {
Expand Down
7 changes: 4 additions & 3 deletions execute/exectypes/commit_data.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"time"

cciptypes "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3"
"slices"
)

// CommitData is the data that is committed to the chain.
Expand Down Expand Up @@ -54,9 +55,9 @@ func (cd CommitData) CopyNoMsgData() CommitData {
BlockNum: cd.BlockNum,
MerkleRoot: cd.MerkleRoot,
SequenceNumberRange: cd.SequenceNumberRange,
ExecutedMessages: append([]cciptypes.SeqNum{}, cd.ExecutedMessages...),
ExecutedMessages: slices.Clone(cd.ExecutedMessages),
Messages: msgsWitoutData,
Hashes: append([]cciptypes.Bytes32{}, cd.Hashes...),
MessageTokenData: append([]MessageTokenData{}, cd.MessageTokenData...),
Hashes: slices.Clone(cd.Hashes),
MessageTokenData: slices.Clone(cd.MessageTokenData),
}
}
5 changes: 3 additions & 2 deletions execute/exectypes/outcome.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"sort"

cciptypes "github.com/smartcontractkit/chainlink-ccip/pkg/types/ccipocr3"
"slices"
)

type PluginState string
Expand Down Expand Up @@ -119,8 +120,8 @@ func NewSortedOutcome(
pendingCommits []CommitData,
report cciptypes.ExecutePluginReport,
) Outcome {
pendingCommitsCP := append([]CommitData{}, pendingCommits...)
reportCP := append([]cciptypes.ExecutePluginReportSingleChain{}, report.ChainReports...)
pendingCommitsCP := slices.Clone(pendingCommits)
reportCP := slices.Clone(report.ChainReports)
sort.Slice(
pendingCommitsCP,
func(i, j int) bool {
Expand Down
2 changes: 1 addition & 1 deletion execute/exectypes/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ func NotReadyToken() TokenData {
// It intentionally skips the fields that are not relevant for the consensus process and are
// not serialized when nodes gossiping
func TokenDataHash(td TokenData) [32]byte {
return sha3.Sum256([]byte(fmt.Sprintf("%v_%v", td.Ready, td.Data)))
return sha3.Sum256(fmt.Appendf(nil, "%v_%v", td.Ready, td.Data))
}

func (td TokenData) IsReady() bool {
Expand Down
2 changes: 1 addition & 1 deletion execute/exectypes/token_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ func Test_MessageTokenData_Append(t *testing.T) {
assert.False(t, msg.IsReady())
assert.Nil(t, msg.Error())

for i := 0; i < 10; i++ {
for i := range 10 {
assert.Nil(t, msg.TokenData[i].Data)
msg = msg.Append(i, NewSuccessTokenData([]byte{byte(i)}))
}
Expand Down
10 changes: 5 additions & 5 deletions execute/factory_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ func TestObservationSize(t *testing.T) {

commitObs := make(exectypes.CommitObservations, estimatedMaxNumberOfSourceChains)
bigSeqNum := ccipocr3.SeqNum(100000)
for i := 0; i < maxCommitReports; i++ {
for i := range maxCommitReports {
idx := ccipocr3.ChainSelector(i % estimatedMaxNumberOfSourceChains)
seqNum := bigSeqNum + ccipocr3.SeqNum(i)
commitObs[idx] = append(commitObs[idx], exectypes.CommitData{
Expand All @@ -100,7 +100,7 @@ func TestObservationSize(t *testing.T) {
}

msgObs := make(exectypes.MessageObservations, estimatedMaxNumberOfSourceChains)
for i := 0; i < maxMessages; i++ {
for i := range maxMessages {
idx := ccipocr3.ChainSelector(i % estimatedMaxNumberOfSourceChains % maxCommitReports)
if nil == msgObs[idx] {
msgObs[idx] = make(map[ccipocr3.SeqNum]ccipocr3.Message)
Expand Down Expand Up @@ -130,7 +130,7 @@ func TestObservationSize(t *testing.T) {

// This could be bigger, since each message could send multiple tokens.
tokenDataObs := make(exectypes.TokenDataObservations, estimatedMaxNumberOfSourceChains)
for i := 0; i < maxMessages; i++ {
for i := range maxMessages {
idx := ccipocr3.ChainSelector(i % estimatedMaxNumberOfSourceChains)
if nil == tokenDataObs[idx] {
tokenDataObs[idx] = make(map[ccipocr3.SeqNum]exectypes.MessageTokenData)
Expand All @@ -151,7 +151,7 @@ func TestObservationSize(t *testing.T) {
// separate sender for each message
noncesObs := make(exectypes.NonceObservations, maxMessages)
mockAddrCodec := internal.NewMockAddressCodecHex(t)
for i := 0; i < maxMessages; i++ {
for i := range maxMessages {
idx := ccipocr3.ChainSelector(i % estimatedMaxNumberOfSourceChains)
if nil == noncesObs[idx] {
noncesObs[idx] = make(map[string]uint64)
Expand All @@ -178,7 +178,7 @@ func TestObservationSize(t *testing.T) {
//type ContractAddresses map[string]map[cciptypes.ChainSelector]cciptypes.UnknownAddress
discoveryObs.Addresses[contract] =
make(map[ccipocr3.ChainSelector]ccipocr3.UnknownAddress, estimatedMaxNumberOfSourceChains)
for i := 0; i < estimatedMaxNumberOfSourceChains; i++ {
for i := range estimatedMaxNumberOfSourceChains {
discoveryObs.Addresses[contract][ccipocr3.ChainSelector(i)] = addr[:]
}
}
Expand Down
4 changes: 2 additions & 2 deletions execute/internal/cache/commit_root_cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -763,7 +763,7 @@ func TestCommitRootsCache_AdditionalEdgeCases(t *testing.T) {
allReports := make(map[ccipocr3.ChainSelector][]exectypes.CommitData)
allReports[selector] = make([]exectypes.CommitData, 0, 20)

for i := 0; i < 20; i++ {
for i := range 20 {
root := ccipocr3.Bytes32{byte(i)}
timestamp := now.Add(time.Duration(-100+i*5) * time.Minute)
report := createCommitData(timestamp, selector, root)
Expand All @@ -778,7 +778,7 @@ func TestCommitRootsCache_AdditionalEdgeCases(t *testing.T) {
"Initial earliest should be first root")

// Execute roots one by one from first to last
for i := 0; i < 20; i++ {
for i := range 20 {
cache.MarkAsExecuted(selector, allReports[selector][i].MerkleRoot)

// Create remaining reports
Expand Down
Loading
Loading