Skip to content
This repository has been archived by the owner on Feb 17, 2025. It is now read-only.

Commit

Permalink
chore: remove unnecessary conversions (#2960)
Browse files Browse the repository at this point in the history
  • Loading branch information
estensen authored Dec 21, 2023
1 parent c310795 commit 42a711e
Show file tree
Hide file tree
Showing 23 changed files with 42 additions and 41 deletions.
1 change: 1 addition & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ linters:
- gofmt
- goimports
- revive
- unconvert

linters-settings:
revive:
Expand Down
2 changes: 1 addition & 1 deletion config/types/duration.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func (d *Duration) UnmarshalText(data []byte) error {

// NewDuration returns Duration wrapper
func NewDuration(duration time.Duration) Duration {
return Duration{time.Duration(duration)}
return Duration{duration}
}

// JSONSchema returns a custom schema to be used for the JSON Schema generation of this type
Expand Down
2 changes: 1 addition & 1 deletion ethtxmanager/ethtxmanager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -763,7 +763,7 @@ func TestGasPriceMarginAndLimit(t *testing.T) {

gasOffset := uint64(1)

suggestedGasPrice := big.NewInt(int64(tc.suggestedGasPrice))
suggestedGasPrice := big.NewInt(tc.suggestedGasPrice)
etherman.
On("SuggestedGasPrice", ctx).
Return(suggestedGasPrice, nil).
Expand Down
4 changes: 2 additions & 2 deletions jsonrpc/types/codec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ func TestResponseMarshal(t *testing.T) {
res := NewResponse(req, result, testCase.Error)
bytes, err := json.Marshal(res)
require.NoError(t, err)
assert.Equal(t, string(testCase.ExpectedJSON), string(bytes))
assert.Equal(t, testCase.ExpectedJSON, string(bytes))
})
}
}
Expand All @@ -375,7 +375,7 @@ func TestIndexUnmarshalJSON(t *testing.T) {
for _, testCase := range testCases {
var i Index
err := json.Unmarshal(testCase.input, &i)
assert.Equal(t, int64(testCase.expectedIndex), int64(i))
assert.Equal(t, testCase.expectedIndex, int64(i))
assert.IsType(t, testCase.expectedError, err)
}
}
Expand Down
2 changes: 1 addition & 1 deletion jsonrpc/types/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ func NewBlock(hash *common.Hash, b *state.L2Block, receipts []types.Receipt, ful
TxRoot: h.TxHash,
ReceiptsRoot: h.ReceiptHash,
LogsBloom: h.Bloom,
Difficulty: ArgUint64(difficulty),
Difficulty: difficulty,
TotalDifficulty: totalDifficulty,
Size: ArgUint64(b.Size()),
Number: ArgUint64(b.Number().Uint64()),
Expand Down
2 changes: 1 addition & 1 deletion sequencer/batch.go
Original file line number Diff line number Diff line change
Expand Up @@ -537,7 +537,7 @@ func (f *finalizer) getConstraintThresholdUint64(input uint64) uint64 {

// getConstraintThresholdUint32 returns the threshold for the given input
func (f *finalizer) getConstraintThresholdUint32(input uint32) uint32 {
return uint32(input*f.cfg.ResourcePercentageToCloseBatch) / 100 //nolint:gomnd
return input * f.cfg.ResourcePercentageToCloseBatch / 100 //nolint:gomnd
}

// getUsedBatchResources returns the max resources that can be used in a batch
Expand Down
2 changes: 1 addition & 1 deletion sequencer/finalizer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2166,7 +2166,7 @@ func TestFinalizer_getConstraintThresholdUint32(t *testing.T) {
// arrange
f = setupFinalizer(false)
input := uint32(100)
expect := uint32(input * f.cfg.ResourcePercentageToCloseBatch / 100)
expect := input * f.cfg.ResourcePercentageToCloseBatch / 100

// act
result := f.getConstraintThresholdUint32(input)
Expand Down
4 changes: 2 additions & 2 deletions sequencer/worker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ func processWorkerAddTxTestCases(ctx context.Context, t *testing.T, worker *Work
t.Fatalf("Error txSortedList.len(%d) != expectedTxSortedList.len(%d)", el.len(), len(testCase.expectedTxSortedList))
}
for i := 0; i < el.len(); i++ {
if el.getByIndex(i).HashStr != string(testCase.expectedTxSortedList[i].String()) {
if el.getByIndex(i).HashStr != testCase.expectedTxSortedList[i].String() {
t.Fatalf("Error txSortedList(%d). Expected=%s, Actual=%s", i, testCase.expectedTxSortedList[i].String(), el.getByIndex(i).HashStr)
}
}
Expand Down Expand Up @@ -268,7 +268,7 @@ func TestWorkerGetBestTx(t *testing.T) {
if ct >= len(expectedGetBestTx) {
t.Fatalf("Error getting more best tx than expected. Expected=%d, Actual=%d", len(expectedGetBestTx), ct+1)
}
if tx.HashStr != string(expectedGetBestTx[ct].String()) {
if tx.HashStr != expectedGetBestTx[ct].String() {
t.Fatalf("Error GetBestFittingTx(%d). Expected=%s, Actual=%s", ct, expectedGetBestTx[ct].String(), tx.HashStr)
}
err := rc.Sub(tx.BatchResources)
Expand Down
10 changes: 5 additions & 5 deletions state/datastream.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,8 @@ type DSL2Transaction struct {
// Encode returns the encoded DSL2Transaction as a byte slice
func (l DSL2Transaction) Encode() []byte {
bytes := make([]byte, 0)
bytes = append(bytes, byte(l.EffectiveGasPricePercentage))
bytes = append(bytes, byte(l.IsValid))
bytes = append(bytes, l.EffectiveGasPricePercentage)
bytes = append(bytes, l.IsValid)
bytes = append(bytes, l.StateRoot[:]...)
bytes = binary.LittleEndian.AppendUint32(bytes, l.EncodedLength)
bytes = append(bytes, l.Encoded...)
Expand All @@ -119,8 +119,8 @@ func (l DSL2Transaction) Encode() []byte {

// Decode decodes the DSL2Transaction from a byte slice
func (l DSL2Transaction) Decode(data []byte) DSL2Transaction {
l.EffectiveGasPricePercentage = uint8(data[0])
l.IsValid = uint8(data[1])
l.EffectiveGasPricePercentage = data[0]
l.IsValid = data[1]
l.StateRoot = common.BytesToHash(data[2:34])
l.EncodedLength = binary.LittleEndian.Uint32(data[34:38])
l.Encoded = data[38:]
Expand Down Expand Up @@ -167,7 +167,7 @@ func (b DSBookMark) Encode() []byte {

// Decode decodes the DSBookMark from a byte slice
func (b DSBookMark) Decode(data []byte) DSBookMark {
b.Type = byte(data[0])
b.Type = data[0]
b.L2BlockNumber = binary.LittleEndian.Uint64(data[1:9])
return b
}
Expand Down
2 changes: 1 addition & 1 deletion state/encoding_batch_v2.go
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ func decodeRLPListLengthFromOffset(txsData []byte, offset int) (uint64, error) {
log.Debugf("error num < c0 : %d, %d", num, c0)
return 0, fmt.Errorf("first byte of tx (%x) is < 0xc0: %w", num, ErrInvalidRLP)
}
length := uint64(num - c0)
length := num - c0
if length > shortRlp { // If rlp is bigger than length 55
// n is the length of the rlp data without the header (1 byte) for example "0xf7"
pos64 := uint64(offset)
Expand Down
4 changes: 2 additions & 2 deletions state/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ func DecodeTxs(txsData []byte, forkID uint64) ([]types.Transaction, []byte, []ui
log.Debugf("error num < c0 : %d, %d", num, c0)
return []types.Transaction{}, txsData, []uint8{}, ErrInvalidData
}
length := uint64(num - c0)
length := num - c0
if length > shortRlp { // If rlp is bigger than length 55
// n is the length of the rlp data without the header (1 byte) for example "0xf7"
if (pos + 1 + num - f7) > txDataLength {
Expand Down Expand Up @@ -237,7 +237,7 @@ func DecodeTxs(txsData []byte, forkID uint64) ([]types.Transaction, []byte, []ui

if forkID >= FORKID_DRAGONFRUIT {
efficiencyPercentage := txsData[dataStart+rLength+sLength+vLength : endPos]
efficiencyPercentages = append(efficiencyPercentages, uint8(efficiencyPercentage[0]))
efficiencyPercentages = append(efficiencyPercentages, efficiencyPercentage[0])
}

pos = endPos
Expand Down
2 changes: 1 addition & 1 deletion state/metrics/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,5 @@ func Register() {
// and for the given label.
func ExecutorProcessingTime(caller string, lastExecutionTime time.Duration) {
execTimeInSeconds := float64(lastExecutionTime) / float64(time.Second)
metrics.HistogramVecObserve(ExecutorProcessingTimeName, string(caller), execTimeInSeconds)
metrics.HistogramVecObserve(ExecutorProcessingTimeName, caller, execTimeInSeconds)
}
2 changes: 1 addition & 1 deletion state/pgstatestorage/batch.go
Original file line number Diff line number Diff line change
Expand Up @@ -932,7 +932,7 @@ func (p *PostgresStorage) BuildChangeL2Block(deltaTimestamp uint32, l1InfoTreeIn
changeL2Block = append(changeL2Block, deltaTimestampBytes...)
// changeL2Block l1InfoTreeIndexBytes
l1InfoTreeIndexBytes := make([]byte, 4) //nolint:gomnd
binary.BigEndian.PutUint32(l1InfoTreeIndexBytes, uint32(l1InfoTreeIndex))
binary.BigEndian.PutUint32(l1InfoTreeIndexBytes, l1InfoTreeIndex)
changeL2Block = append(changeL2Block, l1InfoTreeIndexBytes...)

return changeL2Block
Expand Down
10 changes: 5 additions & 5 deletions state/pgstatestorage/pgstatestorage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ func TestGetBatchByL2BlockNumber(t *testing.T) {
})

receipt := &types.Receipt{
Type: uint8(tx.Type()),
Type: tx.Type(),
PostState: state.ZeroHash.Bytes(),
CumulativeGasUsed: 0,
EffectiveGasPrice: big.NewInt(0),
Expand Down Expand Up @@ -716,7 +716,7 @@ func TestGetLastVerifiedL2BlockNumberUntilL1Block(t *testing.T) {

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
batchNumber, err := testState.GetLastVerifiedL2BlockNumberUntilL1Block(ctx, uint64(tc.l1BlockNumber), dbTx)
batchNumber, err := testState.GetLastVerifiedL2BlockNumberUntilL1Block(ctx, tc.l1BlockNumber, dbTx)
require.NoError(t, err)

assert.Equal(t, tc.expectedBatchNumber, batchNumber)
Expand Down Expand Up @@ -770,7 +770,7 @@ func TestGetLastVerifiedBatchNumberUntilL1Block(t *testing.T) {

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
batchNumber, err := testState.GetLastVerifiedBatchNumberUntilL1Block(ctx, uint64(tc.l1BlockNumber), dbTx)
batchNumber, err := testState.GetLastVerifiedBatchNumberUntilL1Block(ctx, tc.l1BlockNumber, dbTx)
require.NoError(t, err)

assert.Equal(t, tc.expectedBatchNumber, batchNumber)
Expand Down Expand Up @@ -875,7 +875,7 @@ func TestGetLogs(t *testing.T) {
}

receipt := &types.Receipt{
Type: uint8(tx.Type()),
Type: tx.Type(),
PostState: state.ZeroHash.Bytes(),
CumulativeGasUsed: 0,
EffectiveGasPrice: big.NewInt(0),
Expand Down Expand Up @@ -1003,7 +1003,7 @@ func TestGetNativeBlockHashesInRange(t *testing.T) {
})

receipt := &types.Receipt{
Type: uint8(tx.Type()),
Type: tx.Type(),
PostState: state.ZeroHash.Bytes(),
CumulativeGasUsed: 0,
EffectiveGasPrice: big.NewInt(0),
Expand Down
4 changes: 2 additions & 2 deletions state/test/forkid_dragonfruit/dragonfruit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1417,7 +1417,7 @@ func TestExecutorRevert(t *testing.T) {

// Unsigned
receipt := &types.Receipt{
Type: uint8(signedTx0.Type()),
Type: signedTx0.Type(),
PostState: processBatchResponse.Responses[0].StateRoot,
CumulativeGasUsed: processBatchResponse.Responses[0].GasUsed,
BlockNumber: big.NewInt(0),
Expand All @@ -1428,7 +1428,7 @@ func TestExecutorRevert(t *testing.T) {
}

receipt1 := &types.Receipt{
Type: uint8(signedTx1.Type()),
Type: signedTx1.Type(),
PostState: processBatchResponse.Responses[1].StateRoot,
CumulativeGasUsed: processBatchResponse.Responses[0].GasUsed + processBatchResponse.Responses[1].GasUsed,
BlockNumber: big.NewInt(0),
Expand Down
2 changes: 1 addition & 1 deletion state/test/forkid_independent/independent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -621,7 +621,7 @@ func TestAddGetL2Block(t *testing.T) {
})

receipt := &types.Receipt{
Type: uint8(tx.Type()),
Type: tx.Type(),
PostState: state.ZeroHash.Bytes(),
CumulativeGasUsed: 0,
BlockNumber: blockNumber,
Expand Down
12 changes: 6 additions & 6 deletions state/transaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -460,13 +460,13 @@ func (s *State) internalProcessUnsignedTransactionV1(ctx context.Context, tx *ty
// Send Batch to the Executor
processBatchResponse, err := s.executorClient.ProcessBatch(ctx, processBatchRequestV1)
if err != nil {
if status.Code(err) == codes.ResourceExhausted || (processBatchResponse != nil && processBatchResponse.Error == executor.ExecutorError(executor.ExecutorError_EXECUTOR_ERROR_DB_ERROR)) {
if status.Code(err) == codes.ResourceExhausted || (processBatchResponse != nil && processBatchResponse.Error == executor.ExecutorError_EXECUTOR_ERROR_DB_ERROR) {
log.Errorf("error processing unsigned transaction ", err)
for attempts < s.cfg.MaxResourceExhaustedAttempts {
time.Sleep(s.cfg.WaitOnResourceExhaustion.Duration)
log.Errorf("retrying to process unsigned transaction")
processBatchResponse, err = s.executorClient.ProcessBatch(ctx, processBatchRequestV1)
if status.Code(err) == codes.ResourceExhausted || (processBatchResponse != nil && processBatchResponse.Error == executor.ExecutorError(executor.ExecutorError_EXECUTOR_ERROR_DB_ERROR)) {
if status.Code(err) == codes.ResourceExhausted || (processBatchResponse != nil && processBatchResponse.Error == executor.ExecutorError_EXECUTOR_ERROR_DB_ERROR) {
log.Errorf("error processing unsigned transaction ", err)
attempts++
continue
Expand All @@ -476,7 +476,7 @@ func (s *State) internalProcessUnsignedTransactionV1(ctx context.Context, tx *ty
}

if err != nil {
if status.Code(err) == codes.ResourceExhausted || (processBatchResponse != nil && processBatchResponse.Error == executor.ExecutorError(executor.ExecutorError_EXECUTOR_ERROR_DB_ERROR)) {
if status.Code(err) == codes.ResourceExhausted || (processBatchResponse != nil && processBatchResponse.Error == executor.ExecutorError_EXECUTOR_ERROR_DB_ERROR) {
log.Error("reporting error as time out")
return nil, runtime.ErrGRPCResourceExhaustedAsTimeout
}
Expand Down Expand Up @@ -589,13 +589,13 @@ func (s *State) internalProcessUnsignedTransactionV2(ctx context.Context, tx *ty
// Send Batch to the Executor
processBatchResponseV2, err := s.executorClient.ProcessBatchV2(ctx, processBatchRequestV2)
if err != nil {
if status.Code(err) == codes.ResourceExhausted || (processBatchResponseV2 != nil && processBatchResponseV2.Error == executor.ExecutorError(executor.ExecutorError_EXECUTOR_ERROR_DB_ERROR)) {
if status.Code(err) == codes.ResourceExhausted || (processBatchResponseV2 != nil && processBatchResponseV2.Error == executor.ExecutorError_EXECUTOR_ERROR_DB_ERROR) {
log.Errorf("error processing unsigned transaction ", err)
for attempts < s.cfg.MaxResourceExhaustedAttempts {
time.Sleep(s.cfg.WaitOnResourceExhaustion.Duration)
log.Errorf("retrying to process unsigned transaction")
processBatchResponseV2, err = s.executorClient.ProcessBatchV2(ctx, processBatchRequestV2)
if status.Code(err) == codes.ResourceExhausted || (processBatchResponseV2 != nil && processBatchResponseV2.Error == executor.ExecutorError(executor.ExecutorError_EXECUTOR_ERROR_DB_ERROR)) {
if status.Code(err) == codes.ResourceExhausted || (processBatchResponseV2 != nil && processBatchResponseV2.Error == executor.ExecutorError_EXECUTOR_ERROR_DB_ERROR) {
log.Errorf("error processing unsigned transaction ", err)
attempts++
continue
Expand All @@ -605,7 +605,7 @@ func (s *State) internalProcessUnsignedTransactionV2(ctx context.Context, tx *ty
}

if err != nil {
if status.Code(err) == codes.ResourceExhausted || (processBatchResponseV2 != nil && processBatchResponseV2.Error == executor.ExecutorError(executor.ExecutorError_EXECUTOR_ERROR_DB_ERROR)) {
if status.Code(err) == codes.ResourceExhausted || (processBatchResponseV2 != nil && processBatchResponseV2.Error == executor.ExecutorError_EXECUTOR_ERROR_DB_ERROR) {
log.Error("reporting error as time out")
return nil, runtime.ErrGRPCResourceExhaustedAsTimeout
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ func newDataPackageWithData(fromBlock, toBlock uint64, blockWithData uint64) *L1
fromBlock: fromBlock,
toBlock: toBlock,
},
blocks: []etherman.Block{{BlockNumber: uint64(blockWithData)}},
blocks: []etherman.Block{{BlockNumber: blockWithData}},
},
dataIsValid: true,
ctrlIsValid: false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func (l *l1RollupInfoProducerStatistics) onResponseRollupInfo(result responseRol
isOk := (result.generic.err == nil)
if isOk {
l.numRollupInfoOk++
l.numRetrievedBlocks += uint64(result.result.blockRange.len())
l.numRetrievedBlocks += result.result.blockRange.len()
l.accumulatedTimeProcessingRollup += result.generic.duration
} else {
l.numRollupInfoErrors++
Expand Down Expand Up @@ -86,6 +86,6 @@ func (l *l1RollupInfoProducerStatistics) getPercent() float64 {
}

func (l *l1RollupInfoProducerStatistics) getBlocksPerSecond(elapsedTime time.Duration) float64 {
blocksPerSeconds := float64(l.numRetrievedBlocks) / float64(elapsedTime.Seconds())
blocksPerSeconds := float64(l.numRetrievedBlocks) / elapsedTime.Seconds()
return blocksPerSeconds
}
2 changes: 1 addition & 1 deletion synchronizer/synchronizer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -782,7 +782,7 @@ func expectedCallsForsyncTrustedState(t *testing.T, m *mocks, sync *ClientSynchr
Once()

m.State.
On("StoreTransaction", sync.ctx, uint64(stateBatchInTrustedNode.BatchNumber), mock.Anything, stateBatchInTrustedNode.Coinbase, uint64(batchInTrustedNode.Timestamp), mock.Anything, m.DbTx).
On("StoreTransaction", sync.ctx, stateBatchInTrustedNode.BatchNumber, mock.Anything, stateBatchInTrustedNode.Coinbase, uint64(batchInTrustedNode.Timestamp), mock.Anything, m.DbTx).
Return(&state.L2Header{}, nil).
Once()

Expand Down
4 changes: 2 additions & 2 deletions tools/datastreamer/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -709,7 +709,7 @@ func printEntry(entry datastreamer.FileEntry) {
printColored(color.FgGreen, "L2 Block Number.: ")
printColored(color.FgHiWhite, fmt.Sprintf("%d\n", blockStart.L2BlockNumber))
printColored(color.FgGreen, "Timestamp.......: ")
printColored(color.FgHiWhite, fmt.Sprintf("%v (%d)\n", time.Unix(int64(blockStart.Timestamp), 0), blockStart.Timestamp))
printColored(color.FgHiWhite, fmt.Sprintf("%v (%d)\n", time.Unix(blockStart.Timestamp, 0), blockStart.Timestamp))
printColored(color.FgGreen, "Global Exit Root: ")
printColored(color.FgHiWhite, fmt.Sprintf("%s\n", blockStart.GlobalExitRoot))
printColored(color.FgGreen, "Coinbase........: ")
Expand Down Expand Up @@ -771,7 +771,7 @@ func printEntry(entry datastreamer.FileEntry) {
printColored(color.FgGreen, "Batch Number....: ")
printColored(color.FgHiWhite, fmt.Sprintf("%d\n", updateGer.BatchNumber))
printColored(color.FgGreen, "Timestamp.......: ")
printColored(color.FgHiWhite, fmt.Sprintf("%v (%d)\n", time.Unix(int64(updateGer.Timestamp), 0), updateGer.Timestamp))
printColored(color.FgHiWhite, fmt.Sprintf("%v (%d)\n", time.Unix(updateGer.Timestamp, 0), updateGer.Timestamp))
printColored(color.FgGreen, "Global Exit Root: ")
printColored(color.FgHiWhite, fmt.Sprintf("%s\n", updateGer.GlobalExitRoot))
printColored(color.FgGreen, "Coinbase........: ")
Expand Down
2 changes: 1 addition & 1 deletion tools/state/estimated_time.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func (e *estimatedTimeOfArrival) step(itemsProcessedInthisStep int) (time.Durati
elapsedTime := curentTime.Sub(e.startTime)
eta := time.Duration(float64(elapsedTime) / float64(e.processedItems) * float64(e.totalItems-e.processedItems))
percent := float64(e.processedItems) / float64(e.totalItems) * conversionFactorPercentage
itemsPerSecond := float64(e.processedItems) / float64(elapsedTime.Seconds())
itemsPerSecond := float64(e.processedItems) / elapsedTime.Seconds()
e.previousStepTime = curentTime
return eta, percent, itemsPerSecond
}
2 changes: 1 addition & 1 deletion tools/state/reprocess_action.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ func (r *reprocessAction) start() error {
oldStateRoot := batch.StateRoot
oldAccInputHash := batch.AccInputHash

for i := uint64(firstBatchNumber); i < lastBatch; i++ {
for i := firstBatchNumber; i < lastBatch; i++ {
r.output.startProcessingBatch(i)
batchOnDB, response, err := r.stepWithFlushId(i, oldStateRoot, oldAccInputHash)
if response != nil {
Expand Down

0 comments on commit 42a711e

Please sign in to comment.