Skip to content

Commit

Permalink
Avoid creating useless balance change rows.
Browse files Browse the repository at this point in the history
  • Loading branch information
mcdee committed Jun 7, 2024
1 parent 1f14b78 commit cb25296
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 13 deletions.
2 changes: 1 addition & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ import (
)

// ReleaseVersion is the release version for the code.
var ReleaseVersion = "0.5.1"
var ReleaseVersion = "0.5.2"

func main() {
os.Exit(main2())
Expand Down
37 changes: 25 additions & 12 deletions services/execdb/postgresql/settransactionstatediffs.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright © 2021 Weald Technology Limited.
// Copyright © 2021, 2024 Weald Technology Limited.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
Expand All @@ -15,6 +15,7 @@ package postgresql

import (
"context"
"math/big"

"github.com/jackc/pgx/v5"
"github.com/pkg/errors"
Expand All @@ -32,7 +33,27 @@ func (s *Service) SetTransactionStateDiffs(ctx context.Context, stateDiffs []*ex
// Flatten the balance changes.
balanceChanges := make([]*execdb.TransactionBalanceChange, 0)
for _, stateDiff := range stateDiffs {
balanceChanges = append(balanceChanges, stateDiff.BalanceChanges...)
for i := range stateDiff.BalanceChanges {
// Ensure this is a real balance change entry.
if stateDiff.BalanceChanges[i].Old == nil && stateDiff.BalanceChanges[i].New == nil {
continue
}

// Replace nil balances with 0 for our purposes.
if stateDiff.BalanceChanges[i].Old == nil {
stateDiff.BalanceChanges[i].Old = big.NewInt(0)
}
if stateDiff.BalanceChanges[i].New == nil {
stateDiff.BalanceChanges[i].New = big.NewInt(0)
}

if stateDiff.BalanceChanges[i].Old.Cmp(stateDiff.BalanceChanges[i].New) == 0 {
// The balance is unchanged.
continue
}

balanceChanges = append(balanceChanges, stateDiff.BalanceChanges[i])
}
}

// Create a savepoint in case the copy fails.
Expand All @@ -51,20 +72,12 @@ func (s *Service) SetTransactionStateDiffs(ctx context.Context, stateDiffs []*ex
"f_new",
},
pgx.CopyFromSlice(len(balanceChanges), func(i int) ([]interface{}, error) {
oldBalance := decimal.Zero
if balanceChanges[i].Old != nil {
oldBalance = decimal.NewFromBigInt(balanceChanges[i].Old, 0)
}
newBalance := decimal.Zero
if balanceChanges[i].New != nil {
newBalance = decimal.NewFromBigInt(balanceChanges[i].New, 0)
}
return []interface{}{
balanceChanges[i].TransactionHash,
balanceChanges[i].BlockHeight,
balanceChanges[i].Address,
oldBalance,
newBalance,
decimal.NewFromBigInt(balanceChanges[i].Old, 0),
decimal.NewFromBigInt(balanceChanges[i].New, 0),
}, nil
}))

Expand Down

0 comments on commit cb25296

Please sign in to comment.