forked from rocket-pool/rocketpool-go
/
balances.go
97 lines (81 loc) · 2.4 KB
/
balances.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
package multicall
import (
"context"
"fmt"
"math/big"
"strings"
"github.com/RedDuck-Software/poolsea-go/rocketpool"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"golang.org/x/sync/errgroup"
)
const (
balanceBatchSize int = 1000
threadLimit int = 6
)
type BalanceBatcher struct {
Client rocketpool.ExecutionClient
ABI abi.ABI
ContractAddress common.Address
}
func NewBalanceBatcher(client rocketpool.ExecutionClient, address common.Address) (*BalanceBatcher, error) {
abi, err := abi.JSON(strings.NewReader(BalancesABI))
if err != nil {
return nil, err
}
return &BalanceBatcher{
Client: client,
ContractAddress: address,
ABI: abi,
}, nil
}
func (b *BalanceBatcher) GetEthBalances(addresses []common.Address, opts *bind.CallOpts) ([]*big.Int, error) {
// Sync
count := len(addresses)
var wg errgroup.Group
wg.SetLimit(threadLimit)
balances := make([]*big.Int, count)
// Run the getters in batches
for i := 0; i < count; i += balanceBatchSize {
i := i
max := i + balanceBatchSize
if max > count {
max = count
}
wg.Go(func() error {
subAddresses := addresses[i:max]
tokens := []common.Address{
{}, // Empty token for ETH balance
}
callData, err := b.ABI.Pack("balances", subAddresses, tokens)
if err != nil {
return fmt.Errorf("error creating calldata for balances: %w", err)
}
response, err := b.Client.CallContract(context.Background(), ethereum.CallMsg{To: &b.ContractAddress, Data: callData}, opts.BlockNumber)
if err != nil {
return fmt.Errorf("error calling balances: %w", err)
}
var subBalances []*big.Int
err = b.ABI.UnpackIntoInterface(&subBalances, "balances", response)
if err != nil {
return fmt.Errorf("error unpacking balances response: %w", err)
}
if len(subBalances) != len(subAddresses) {
return fmt.Errorf("received %d balances which mismatches query batch size %d", len(subBalances), len(subAddresses))
}
for j, balance := range subBalances {
if balance == nil {
return fmt.Errorf("received nil balance for address %s", subAddresses[j].String())
}
balances[i+j] = balance
}
return nil
})
}
if err := wg.Wait(); err != nil {
return nil, fmt.Errorf("error getting balances: %w", err)
}
return balances, nil
}