diff --git a/backend/backend.go b/backend/backend.go index 94f696c464..b1ae01c9a7 100644 --- a/backend/backend.go +++ b/backend/backend.go @@ -759,12 +759,15 @@ func (backend *Backend) updateETHAccounts() error { } + var updateErr error for chainID, ethAccounts := range accountsChainID { etherScanClient := etherscan.NewEtherScan(chainID, backend.httpClient, backend.etherScanRateLimiter) - backend.ethupdater.UpdateBalancesAndBlockNumber(ethAccounts, etherScanClient) + if err := backend.ethupdater.UpdateBalancesAndBlockNumber(ethAccounts, etherScanClient); err != nil { + updateErr = err + } } - return nil + return updateErr } // ManualReconnect triggers reconnecting to Electrum servers if their connection is down. diff --git a/backend/coins/eth/etherscan/etherscan.go b/backend/coins/eth/etherscan/etherscan.go index a119762240..2f2ce5d8dc 100644 --- a/backend/coins/eth/etherscan/etherscan.go +++ b/backend/coins/eth/etherscan/etherscan.go @@ -11,7 +11,6 @@ import ( "math/big" "net/http" "net/url" - "slices" "strconv" "strings" "sync" @@ -24,6 +23,7 @@ import ( ethtypes "github.com/BitBoxSwiss/bitbox-wallet-app/backend/coins/eth/types" "github.com/BitBoxSwiss/bitbox-wallet-app/util/errp" ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/core/types" @@ -44,7 +44,6 @@ var historicalBalanceRateLimiter = rate.NewLimiter(2, 1) var requestRateLimitLock sync.Mutex const ( - maxAddressesForBalances = 20 maxGetRequestTargetLength = 6000 maxTokenTransactionsPerQuery = 10000 @@ -53,6 +52,18 @@ const ( mainnetLaunchTimestamp = 1438269973 ) +const ( + multicall3Address = "0xcA11bde05977b3631167028862bE2a173976CA11" + + balancesSnapshotABI = `[ + {"type":"function","name":"tryBlockAndAggregate","stateMutability":"payable", + "inputs":[{"name":"requireSuccess","type":"bool"},{"name":"calls","type":"tuple[]","components":[{"name":"target","type":"address"},{"name":"callData","type":"bytes"}]}], + "outputs":[{"name":"blockNumber","type":"uint256"},{"name":"blockHash","type":"bytes32"},{"name":"returnData","type":"tuple[]","components":[{"name":"success","type":"bool"},{"name":"returnData","type":"bytes"}]}]}, + {"type":"function","name":"getEthBalance","stateMutability":"view", + "inputs":[{"name":"addr","type":"address"}],"outputs":[{"name":"balance","type":"uint256"}]} +]` +) + // ERC20GasErr is the error message returned from etherscan when there is not enough ETH to pay the transaction fee. const ERC20GasErr = "insufficient funds for gas * price + value" @@ -733,58 +744,6 @@ func (etherScan *EtherScan) HistoricalBalanceAt( return etherScan.callNonNegativeInt(ctx, params, "snapshot balance") } -// Balances returns balances at the specified block, or the latest if nil, for multiple addresses. -func (etherScan *EtherScan) Balances(ctx context.Context, accounts []common.Address, blockNumber *big.Int) (map[common.Address]*big.Int, error) { - if len(accounts) == 0 { - return nil, nil - } - - params := url.Values{} - params.Set("module", "account") - params.Set("action", "balancemulti") - if blockNumber == nil { - params.Set("tag", "latest") - } else { - params.Set("tag", hexutil.EncodeBig(blockNumber)) - } - - balances := make(map[common.Address]*big.Int) - - type balancesResult struct { - Status string - Message string - Result []struct { - Account string `json:"account"` - Balance jsonBigInt `json:"balance"` - } `json:"result"` - } - - for addressesChunk := range slices.Chunk(accounts, maxAddressesForBalances) { - - addresses := make([]string, len(addressesChunk)) - for i, account := range addressesChunk { - addresses[i] = account.Hex() - } - - params.Set("address", strings.Join(addresses, ",")) - - result := balancesResult{} - if err := etherScan.call(ctx, params, &result); err != nil { - return nil, err - } - if result.Status != "1" { - return nil, errp.New("unexpected response from EtherScan") - } - - for _, item := range result.Result { - account := common.HexToAddress(item.Account) - balance := item.Balance.BigInt() - balances[account] = balance - } - } - return balances, nil -} - // ERC20Balance implements rpc.Interface. func (etherScan *EtherScan) ERC20Balance(account common.Address, erc20Token *erc20.Token, blockNumber *big.Int) (*big.Int, error) { parsed, err := erc20.IERC20MetaData.GetAbi() @@ -807,6 +766,88 @@ func (etherScan *EtherScan) ERC20Balance(account common.Address, erc20Token *erc return values[0].(*big.Int), nil } +// BalancesSnapshot reads the latest block number, the native balances of addresses and the ERC20 +// balances of tokenHolders ({token contract, holder} pairs) in a single Multicall3 call, so all +// balances belong to the returned block. Balances that could not be read are omitted. +func (etherScan *EtherScan) BalancesSnapshot( + ctx context.Context, + addresses []common.Address, + tokenHolders [][2]common.Address, +) (*big.Int, map[common.Address]*big.Int, map[[2]common.Address]*big.Int, error) { + parsed, err := abi.JSON(strings.NewReader(balancesSnapshotABI)) + if err != nil { + return nil, nil, nil, errp.WithStack(err) + } + erc20ABI, err := erc20.IERC20MetaData.GetAbi() + if err != nil { + return nil, nil, nil, errp.WithStack(err) + } + type call struct { + Target common.Address + CallData []byte + } + multicall3 := common.HexToAddress(multicall3Address) + calls := make([]call, 0, len(addresses)+len(tokenHolders)) + for _, address := range addresses { + data, err := parsed.Pack("getEthBalance", address) + if err != nil { + return nil, nil, nil, errp.WithStack(err) + } + calls = append(calls, call{Target: multicall3, CallData: data}) + } + for _, tokenHolder := range tokenHolders { + data, err := erc20ABI.Pack("balanceOf", tokenHolder[1]) + if err != nil { + return nil, nil, nil, errp.WithStack(err) + } + calls = append(calls, call{Target: tokenHolder[0], CallData: data}) + } + + data, err := parsed.Pack("tryBlockAndAggregate", false, calls) + if err != nil { + return nil, nil, nil, errp.WithStack(err) + } + result, err := etherScan.CallContract(ctx, ethereum.CallMsg{To: &multicall3, Data: data}, nil) + if err != nil { + return nil, nil, nil, err + } + var snapshot struct { + BlockNumber *big.Int + BlockHash [32]byte + ReturnData []struct { + Success bool + ReturnData []byte + } + } + if err := parsed.UnpackIntoInterface(&snapshot, "tryBlockAndAggregate", result); err != nil { + return nil, nil, nil, errp.WithStack(err) + } + if len(snapshot.ReturnData) != len(calls) { + return nil, nil, nil, errp.New("unexpected multicall result length") + } + uint256Result := func(index int) *big.Int { + returned := snapshot.ReturnData[index] + if !returned.Success || len(returned.ReturnData) < 32 { + return nil + } + return new(big.Int).SetBytes(returned.ReturnData[:32]) + } + + balances := make(map[common.Address]*big.Int, len(addresses)) + for i, address := range addresses { + if balance := uint256Result(i); balance != nil { + balances[address] = balance + } + } + tokenBalances := make(map[[2]common.Address]*big.Int, len(tokenHolders)) + for i, tokenHolder := range tokenHolders { + if balance := uint256Result(len(addresses) + i); balance != nil { + tokenBalances[tokenHolder] = balance + } + } + return snapshot.BlockNumber, balances, tokenBalances, nil +} + // CallContract implements rpc.Interface. func (etherScan *EtherScan) CallContract(ctx context.Context, msg ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) { params := url.Values{} diff --git a/backend/coins/eth/etherscan/etherscan_test.go b/backend/coins/eth/etherscan/etherscan_test.go index f914a9c961..fdb54b504a 100644 --- a/backend/coins/eth/etherscan/etherscan_test.go +++ b/backend/coins/eth/etherscan/etherscan_test.go @@ -9,9 +9,11 @@ import ( "errors" "fmt" "io" + "maps" "math/big" "net/http" "net/url" + "slices" "strings" "testing" "testing/synctest" @@ -20,6 +22,7 @@ import ( "github.com/BitBoxSwiss/bitbox-wallet-app/backend/coins/eth/erc20" "github.com/BitBoxSwiss/bitbox-wallet-app/backend/coins/eth/rpcclient" ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/stretchr/testify/require" @@ -289,17 +292,6 @@ func TestTokenTransactionsByContractPaginationDedup(t *testing.T) { func TestBalancesAtBlock(t *testing.T) { address := common.Address{19: 2} client := newTestEtherScan(func(req *http.Request) *http.Response { - params := req.URL.Query() - require.Equal(t, "balancemulti", params.Get("action")) - require.Equal(t, "0x64", params.Get("tag")) - require.Equal(t, address.Hex(), params.Get("address")) - return jsonRPCResponse(t, `{"status":"1","result":[{"account":"`+address.Hex()+`","balance":"20000"}]}`) - }) - balances, err := client.Balances(context.Background(), []common.Address{address}, big.NewInt(100)) - require.NoError(t, err) - require.Equal(t, big.NewInt(20000), balances[address]) - - client = newTestEtherScan(func(req *http.Request) *http.Response { params := req.URL.Query() require.Equal(t, "balance", params.Get("action")) require.Equal(t, address.Hex(), params.Get("address")) @@ -330,6 +322,93 @@ func TestBalancesAtBlock(t *testing.T) { require.Error(t, err) } +func TestBalancesSnapshot(t *testing.T) { + multicall3 := common.HexToAddress("0xcA11bde05977b3631167028862bE2a173976CA11") + token := common.Address{19: 0xa} + holder1, holder2, holder3 := common.Address{19: 1}, common.Address{19: 2}, common.Address{19: 3} + multicallABI, err := abi.JSON(strings.NewReader(balancesSnapshotABI)) + require.NoError(t, err) + erc20ABI, err := erc20.IERC20MetaData.GetAbi() + require.NoError(t, err) + + type result struct { + Success bool + ReturnData []byte + } + uint256 := func(value int64) result { + data, err := multicallABI.Methods["getEthBalance"].Outputs.Pack(big.NewInt(value)) + require.NoError(t, err) + return result{true, data} + } + decodeCall := func(contract *abi.ABI, name string, data []byte) common.Address { + method, err := contract.MethodById(data) + require.NoError(t, err) + require.Equal(t, name, method.Name) + args, err := method.Inputs.Unpack(data[4:]) + require.NoError(t, err) + return args[0].(common.Address) + } + // Sub-calls are keyed by {target, address argument}. + results := map[[2]common.Address]result{ + {multicall3, holder1}: uint256(1), + {multicall3, holder2}: {false, uint256(2).ReturnData}, + {multicall3, holder3}: uint256(3), + {token, holder1}: uint256(4), + {token, holder2}: {true, nil}, + } + + client := newTestEtherScan(func(req *http.Request) *http.Response { + params := formValues(t, req) + require.Equal(t, "eth_call", params.Get("action")) + require.Equal(t, multicall3.Hex(), params.Get("to")) + require.Equal(t, "latest", params.Get("tag")) + data, err := hexutil.Decode(params.Get("data")) + require.NoError(t, err) + method, err := multicallABI.MethodById(data) + require.NoError(t, err) + require.Equal(t, "tryBlockAndAggregate", method.Name) + args, err := method.Inputs.Unpack(data[4:]) + require.NoError(t, err) + var request struct { + RequireSuccess bool + Calls []struct { + Target common.Address + CallData []byte + } + } + require.NoError(t, method.Inputs.Copy(&request, args)) + require.False(t, request.RequireSuccess) + + calls := [][2]common.Address{} + returnData := []result{} + for _, call := range request.Calls { + var key [2]common.Address + if call.Target == multicall3 { + key = [2]common.Address{multicall3, decodeCall(&multicallABI, "getEthBalance", call.CallData)} + } else { + key = [2]common.Address{call.Target, decodeCall(erc20ABI, "balanceOf", call.CallData)} + } + calls = append(calls, key) + returnData = append(returnData, results[key]) + } + require.ElementsMatch(t, slices.Collect(maps.Keys(results)), calls) + + response, err := method.Outputs.Pack(big.NewInt(100), [32]byte{}, returnData) + require.NoError(t, err) + return jsonRPCResponse(t, fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"result":%q}`, hexutil.Encode(response))) + }) + + blockNumber, balances, tokenBalances, err := client.BalancesSnapshot( + context.Background(), + []common.Address{holder1, holder2, holder3}, + [][2]common.Address{{token, holder1}, {token, holder2}}, + ) + require.NoError(t, err) + require.Equal(t, big.NewInt(100), blockNumber) + require.Equal(t, map[common.Address]*big.Int{holder1: big.NewInt(1), holder3: big.NewInt(3)}, balances) + require.Equal(t, map[[2]common.Address]*big.Int{{token, holder1}: big.NewInt(4)}, tokenBalances) +} + func TestSendTransactionPreservesRPCError(t *testing.T) { client := newTestEtherScan(func(*http.Request) *http.Response { return jsonRPCResponse(t, `{"jsonrpc":"2.0","error":{"code":-32000,"message":"insufficient funds"}}`) diff --git a/backend/coins/eth/mocks/balanceandblocknumberfetcher.go b/backend/coins/eth/mocks/balanceandblocknumberfetcher.go index 8efcc2674a..031e4b4673 100644 --- a/backend/coins/eth/mocks/balanceandblocknumberfetcher.go +++ b/backend/coins/eth/mocks/balanceandblocknumberfetcher.go @@ -22,11 +22,8 @@ var _ eth.BalanceAndBlockNumberFetcher = &BalanceAndBlockNumberFetcherMock{} // // // make and configure a mocked eth.BalanceAndBlockNumberFetcher // mockedBalanceAndBlockNumberFetcher := &BalanceAndBlockNumberFetcherMock{ -// BalancesFunc: func(ctx context.Context, addresses []ethcommon.Address, blockNumber *big.Int) (map[ethcommon.Address]*big.Int, error) { -// panic("mock out the Balances method") -// }, -// BlockNumberFunc: func(ctx context.Context) (*big.Int, error) { -// panic("mock out the BlockNumber method") +// BalancesSnapshotFunc: func(ctx context.Context, addresses []ethcommon.Address, tokenHolders [][2]ethcommon.Address) (*big.Int, map[ethcommon.Address]*big.Int, map[[2]ethcommon.Address]*big.Int, error) { +// panic("mock out the BalancesSnapshot method") // }, // } // @@ -35,101 +32,60 @@ var _ eth.BalanceAndBlockNumberFetcher = &BalanceAndBlockNumberFetcherMock{} // // } type BalanceAndBlockNumberFetcherMock struct { - // BalancesFunc mocks the Balances method. - BalancesFunc func(ctx context.Context, addresses []ethcommon.Address, blockNumber *big.Int) (map[ethcommon.Address]*big.Int, error) - - // BlockNumberFunc mocks the BlockNumber method. - BlockNumberFunc func(ctx context.Context) (*big.Int, error) + // BalancesSnapshotFunc mocks the BalancesSnapshot method. + BalancesSnapshotFunc func(ctx context.Context, addresses []ethcommon.Address, tokenHolders [][2]ethcommon.Address) (*big.Int, map[ethcommon.Address]*big.Int, map[[2]ethcommon.Address]*big.Int, error) // calls tracks calls to the methods. calls struct { - // Balances holds details about calls to the Balances method. - Balances []struct { + // BalancesSnapshot holds details about calls to the BalancesSnapshot method. + BalancesSnapshot []struct { // Ctx is the ctx argument value. Ctx context.Context // Addresses is the addresses argument value. Addresses []ethcommon.Address - // BlockNumber is the blockNumber argument value. - BlockNumber *big.Int - } - // BlockNumber holds details about calls to the BlockNumber method. - BlockNumber []struct { - // Ctx is the ctx argument value. - Ctx context.Context + // TokenHolders is the tokenHolders argument value. + TokenHolders [][2]ethcommon.Address } } - lockBalances sync.RWMutex - lockBlockNumber sync.RWMutex -} - -// Balances calls BalancesFunc. -func (mock *BalanceAndBlockNumberFetcherMock) Balances(ctx context.Context, addresses []ethcommon.Address, blockNumber *big.Int) (map[ethcommon.Address]*big.Int, error) { - if mock.BalancesFunc == nil { - panic("BalanceAndBlockNumberFetcherMock.BalancesFunc: method is nil but BalanceAndBlockNumberFetcher.Balances was just called") - } - callInfo := struct { - Ctx context.Context - Addresses []ethcommon.Address - BlockNumber *big.Int - }{ - Ctx: ctx, - Addresses: addresses, - BlockNumber: blockNumber, - } - mock.lockBalances.Lock() - mock.calls.Balances = append(mock.calls.Balances, callInfo) - mock.lockBalances.Unlock() - return mock.BalancesFunc(ctx, addresses, blockNumber) -} - -// BalancesCalls gets all the calls that were made to Balances. -// Check the length with: -// -// len(mockedBalanceAndBlockNumberFetcher.BalancesCalls()) -func (mock *BalanceAndBlockNumberFetcherMock) BalancesCalls() []struct { - Ctx context.Context - Addresses []ethcommon.Address - BlockNumber *big.Int -} { - var calls []struct { - Ctx context.Context - Addresses []ethcommon.Address - BlockNumber *big.Int - } - mock.lockBalances.RLock() - calls = mock.calls.Balances - mock.lockBalances.RUnlock() - return calls + lockBalancesSnapshot sync.RWMutex } -// BlockNumber calls BlockNumberFunc. -func (mock *BalanceAndBlockNumberFetcherMock) BlockNumber(ctx context.Context) (*big.Int, error) { - if mock.BlockNumberFunc == nil { - panic("BalanceAndBlockNumberFetcherMock.BlockNumberFunc: method is nil but BalanceAndBlockNumberFetcher.BlockNumber was just called") +// BalancesSnapshot calls BalancesSnapshotFunc. +func (mock *BalanceAndBlockNumberFetcherMock) BalancesSnapshot(ctx context.Context, addresses []ethcommon.Address, tokenHolders [][2]ethcommon.Address) (*big.Int, map[ethcommon.Address]*big.Int, map[[2]ethcommon.Address]*big.Int, error) { + if mock.BalancesSnapshotFunc == nil { + panic("BalanceAndBlockNumberFetcherMock.BalancesSnapshotFunc: method is nil but BalanceAndBlockNumberFetcher.BalancesSnapshot was just called") } callInfo := struct { - Ctx context.Context + Ctx context.Context + Addresses []ethcommon.Address + TokenHolders [][2]ethcommon.Address }{ - Ctx: ctx, + Ctx: ctx, + Addresses: addresses, + TokenHolders: tokenHolders, } - mock.lockBlockNumber.Lock() - mock.calls.BlockNumber = append(mock.calls.BlockNumber, callInfo) - mock.lockBlockNumber.Unlock() - return mock.BlockNumberFunc(ctx) + mock.lockBalancesSnapshot.Lock() + mock.calls.BalancesSnapshot = append(mock.calls.BalancesSnapshot, callInfo) + mock.lockBalancesSnapshot.Unlock() + return mock.BalancesSnapshotFunc(ctx, addresses, tokenHolders) } -// BlockNumberCalls gets all the calls that were made to BlockNumber. +// BalancesSnapshotCalls gets all the calls that were made to BalancesSnapshot. // Check the length with: // -// len(mockedBalanceAndBlockNumberFetcher.BlockNumberCalls()) -func (mock *BalanceAndBlockNumberFetcherMock) BlockNumberCalls() []struct { - Ctx context.Context +// len(mockedBalanceAndBlockNumberFetcher.BalancesSnapshotCalls()) +func (mock *BalanceAndBlockNumberFetcherMock) BalancesSnapshotCalls() []struct { + Ctx context.Context + Addresses []ethcommon.Address + TokenHolders [][2]ethcommon.Address } { var calls []struct { - Ctx context.Context + Ctx context.Context + Addresses []ethcommon.Address + TokenHolders [][2]ethcommon.Address } - mock.lockBlockNumber.RLock() - calls = mock.calls.BlockNumber - mock.lockBlockNumber.RUnlock() + mock.lockBalancesSnapshot.RLock() + calls = mock.calls.BalancesSnapshot + mock.lockBalancesSnapshot.RUnlock() return calls } diff --git a/backend/coins/eth/mocks/tokentransactionsfetcher.go b/backend/coins/eth/mocks/tokentransactionsfetcher.go index 7321e77990..a671a21a21 100644 --- a/backend/coins/eth/mocks/tokentransactionsfetcher.go +++ b/backend/coins/eth/mocks/tokentransactionsfetcher.go @@ -23,11 +23,8 @@ var _ eth.TokenTransactionsFetcher = &TokenTransactionsFetcherMock{} // // // make and configure a mocked eth.TokenTransactionsFetcher // mockedTokenTransactionsFetcher := &TokenTransactionsFetcherMock{ -// BalancesFunc: func(ctx context.Context, addresses []ethcommon.Address, blockNumber *big.Int) (map[ethcommon.Address]*big.Int, error) { -// panic("mock out the Balances method") -// }, -// BlockNumberFunc: func(ctx context.Context) (*big.Int, error) { -// panic("mock out the BlockNumber method") +// BalancesSnapshotFunc: func(ctx context.Context, addresses []ethcommon.Address, tokenHolders [][2]ethcommon.Address) (*big.Int, map[ethcommon.Address]*big.Int, map[[2]ethcommon.Address]*big.Int, error) { +// panic("mock out the BalancesSnapshot method") // }, // TokenTransactionsByContractFunc: func(blockTipHeight *big.Int, address ethcommon.Address, endBlock *big.Int) (map[ethcommon.Address][]*accounts.TransactionData, error) { // panic("mock out the TokenTransactionsByContract method") @@ -39,30 +36,22 @@ var _ eth.TokenTransactionsFetcher = &TokenTransactionsFetcherMock{} // // } type TokenTransactionsFetcherMock struct { - // BalancesFunc mocks the Balances method. - BalancesFunc func(ctx context.Context, addresses []ethcommon.Address, blockNumber *big.Int) (map[ethcommon.Address]*big.Int, error) - - // BlockNumberFunc mocks the BlockNumber method. - BlockNumberFunc func(ctx context.Context) (*big.Int, error) + // BalancesSnapshotFunc mocks the BalancesSnapshot method. + BalancesSnapshotFunc func(ctx context.Context, addresses []ethcommon.Address, tokenHolders [][2]ethcommon.Address) (*big.Int, map[ethcommon.Address]*big.Int, map[[2]ethcommon.Address]*big.Int, error) // TokenTransactionsByContractFunc mocks the TokenTransactionsByContract method. TokenTransactionsByContractFunc func(blockTipHeight *big.Int, address ethcommon.Address, endBlock *big.Int) (map[ethcommon.Address][]*accounts.TransactionData, error) // calls tracks calls to the methods. calls struct { - // Balances holds details about calls to the Balances method. - Balances []struct { + // BalancesSnapshot holds details about calls to the BalancesSnapshot method. + BalancesSnapshot []struct { // Ctx is the ctx argument value. Ctx context.Context // Addresses is the addresses argument value. Addresses []ethcommon.Address - // BlockNumber is the blockNumber argument value. - BlockNumber *big.Int - } - // BlockNumber holds details about calls to the BlockNumber method. - BlockNumber []struct { - // Ctx is the ctx argument value. - Ctx context.Context + // TokenHolders is the tokenHolders argument value. + TokenHolders [][2]ethcommon.Address } // TokenTransactionsByContract holds details about calls to the TokenTransactionsByContract method. TokenTransactionsByContract []struct { @@ -74,80 +63,47 @@ type TokenTransactionsFetcherMock struct { EndBlock *big.Int } } - lockBalances sync.RWMutex - lockBlockNumber sync.RWMutex + lockBalancesSnapshot sync.RWMutex lockTokenTransactionsByContract sync.RWMutex } -// Balances calls BalancesFunc. -func (mock *TokenTransactionsFetcherMock) Balances(ctx context.Context, addresses []ethcommon.Address, blockNumber *big.Int) (map[ethcommon.Address]*big.Int, error) { - if mock.BalancesFunc == nil { - panic("TokenTransactionsFetcherMock.BalancesFunc: method is nil but TokenTransactionsFetcher.Balances was just called") - } - callInfo := struct { - Ctx context.Context - Addresses []ethcommon.Address - BlockNumber *big.Int - }{ - Ctx: ctx, - Addresses: addresses, - BlockNumber: blockNumber, - } - mock.lockBalances.Lock() - mock.calls.Balances = append(mock.calls.Balances, callInfo) - mock.lockBalances.Unlock() - return mock.BalancesFunc(ctx, addresses, blockNumber) -} - -// BalancesCalls gets all the calls that were made to Balances. -// Check the length with: -// -// len(mockedTokenTransactionsFetcher.BalancesCalls()) -func (mock *TokenTransactionsFetcherMock) BalancesCalls() []struct { - Ctx context.Context - Addresses []ethcommon.Address - BlockNumber *big.Int -} { - var calls []struct { - Ctx context.Context - Addresses []ethcommon.Address - BlockNumber *big.Int - } - mock.lockBalances.RLock() - calls = mock.calls.Balances - mock.lockBalances.RUnlock() - return calls -} - -// BlockNumber calls BlockNumberFunc. -func (mock *TokenTransactionsFetcherMock) BlockNumber(ctx context.Context) (*big.Int, error) { - if mock.BlockNumberFunc == nil { - panic("TokenTransactionsFetcherMock.BlockNumberFunc: method is nil but TokenTransactionsFetcher.BlockNumber was just called") +// BalancesSnapshot calls BalancesSnapshotFunc. +func (mock *TokenTransactionsFetcherMock) BalancesSnapshot(ctx context.Context, addresses []ethcommon.Address, tokenHolders [][2]ethcommon.Address) (*big.Int, map[ethcommon.Address]*big.Int, map[[2]ethcommon.Address]*big.Int, error) { + if mock.BalancesSnapshotFunc == nil { + panic("TokenTransactionsFetcherMock.BalancesSnapshotFunc: method is nil but TokenTransactionsFetcher.BalancesSnapshot was just called") } callInfo := struct { - Ctx context.Context + Ctx context.Context + Addresses []ethcommon.Address + TokenHolders [][2]ethcommon.Address }{ - Ctx: ctx, + Ctx: ctx, + Addresses: addresses, + TokenHolders: tokenHolders, } - mock.lockBlockNumber.Lock() - mock.calls.BlockNumber = append(mock.calls.BlockNumber, callInfo) - mock.lockBlockNumber.Unlock() - return mock.BlockNumberFunc(ctx) + mock.lockBalancesSnapshot.Lock() + mock.calls.BalancesSnapshot = append(mock.calls.BalancesSnapshot, callInfo) + mock.lockBalancesSnapshot.Unlock() + return mock.BalancesSnapshotFunc(ctx, addresses, tokenHolders) } -// BlockNumberCalls gets all the calls that were made to BlockNumber. +// BalancesSnapshotCalls gets all the calls that were made to BalancesSnapshot. // Check the length with: // -// len(mockedTokenTransactionsFetcher.BlockNumberCalls()) -func (mock *TokenTransactionsFetcherMock) BlockNumberCalls() []struct { - Ctx context.Context +// len(mockedTokenTransactionsFetcher.BalancesSnapshotCalls()) +func (mock *TokenTransactionsFetcherMock) BalancesSnapshotCalls() []struct { + Ctx context.Context + Addresses []ethcommon.Address + TokenHolders [][2]ethcommon.Address } { var calls []struct { - Ctx context.Context + Ctx context.Context + Addresses []ethcommon.Address + TokenHolders [][2]ethcommon.Address } - mock.lockBlockNumber.RLock() - calls = mock.calls.BlockNumber - mock.lockBlockNumber.RUnlock() + mock.lockBalancesSnapshot.RLock() + calls = mock.calls.BalancesSnapshot + mock.lockBalancesSnapshot.RUnlock() return calls } diff --git a/backend/coins/eth/outgoing_test.go b/backend/coins/eth/outgoing_test.go index ffdb7a88be..67267fbabc 100644 --- a/backend/coins/eth/outgoing_test.go +++ b/backend/coins/eth/outgoing_test.go @@ -516,12 +516,20 @@ func TestFinalRecordsSkipLookups(t *testing.T) { } type updaterBalanceFetcher struct { - rpcclient.Interface - balances func(context.Context, []common.Address, *big.Int) (map[common.Address]*big.Int, error) + BalanceAndBlockNumberFetcher + balancesSnapshot func([]common.Address, [][2]common.Address) (*big.Int, map[common.Address]*big.Int, map[[2]common.Address]*big.Int, error) } -func (fetcher updaterBalanceFetcher) Balances(ctx context.Context, addresses []common.Address, block *big.Int) (map[common.Address]*big.Int, error) { - return fetcher.balances(ctx, addresses, block) +func (fetcher updaterBalanceFetcher) BalancesSnapshot( + _ context.Context, addresses []common.Address, tokenHolders [][2]common.Address, +) (*big.Int, map[common.Address]*big.Int, map[[2]common.Address]*big.Int, error) { + return fetcher.balancesSnapshot(addresses, tokenHolders) +} + +type transactionsSourceFunc func() ([]*accounts.TransactionData, error) + +func (f transactionsSourceFunc) Transactions(*big.Int, common.Address, *big.Int, *erc20.Token) ([]*accounts.TransactionData, error) { + return f() } func TestUpdateBalanceAtConfirmation(t *testing.T) { @@ -535,7 +543,6 @@ func TestUpdateBalanceAtConfirmation(t *testing.T) { tx.Value = big.NewInt(59000) // 80000 debit including gas. putOutgoingTx(t, native, ðtypes.TransactionWithMetadata{Transaction: types.NewTx(tx)}) tip := int64(99) - client.BlockNumberFunc = func(context.Context) (*big.Int, error) { return big.NewInt(tip), nil } client.NonceAtFunc = func(_ context.Context, _ common.Address, block *big.Int) (uint64, error) { if block.Int64() >= 100 { return 1, nil @@ -545,19 +552,26 @@ func TestUpdateBalanceAtConfirmation(t *testing.T) { client.TransactionReceiptWithBlockNumberFunc = func(context.Context, common.Hash) (*types.Receipt, error) { return &types.Receipt{BlockNumber: big.NewInt(100), GasUsed: 21000, Status: types.ReceiptStatusSuccessful}, nil } - fetcher := updaterBalanceFetcher{Interface: client, balances: func(_ context.Context, _ []common.Address, block *big.Int) (map[common.Address]*big.Int, error) { - tip = 100 // The debit confirms between the tip and balance requests. + fetcher := updaterBalanceFetcher{balancesSnapshot: func( + []common.Address, [][2]common.Address, + ) (*big.Int, map[common.Address]*big.Int, map[[2]common.Address]*big.Int, error) { balance := int64(100000) - if block.Int64() >= 100 { + if tip >= 100 { balance = 20000 } - return map[common.Address]*big.Int{native.address.Address: big.NewInt(balance)}, nil + tokenHolder := [2]common.Address{token.coin.erc20Token.ContractAddress(), token.address.Address} + return big.NewInt(tip), + map[common.Address]*big.Int{native.address.Address: big.NewInt(balance)}, + map[[2]common.Address]*big.Int{tokenHolder: big.NewInt(1000)}, + nil }} - client.ERC20BalanceFunc = func(common.Address, *erc20.Token, *big.Int) (*big.Int, error) { - // A send-time refresh advances the shared state after the updater took its snapshot. + token.coin.TstSetTransactionsSource(transactionsSourceFunc(func() ([]*accounts.TransactionData, error) { + // The debit confirms and a send-time refresh advances the shared state after the + // updater took its snapshot. + tip = 100 reconcileOutgoing(t, native, 100) - return big.NewInt(1000), nil - } + return nil, nil + })) updater := NewUpdater(nil, nil, nil, nil) defer updater.Close() for range 2 { diff --git a/backend/coins/eth/updater.go b/backend/coins/eth/updater.go index 48d498da02..b1815b6418 100644 --- a/backend/coins/eth/updater.go +++ b/backend/coins/eth/updater.go @@ -28,15 +28,17 @@ var activeProbeLeaseDuration = 90 * time.Second var activeProbeRetryDelay = 30 * time.Second var activeProbeBackoffDuration = 5 * time.Minute -// BalanceAndBlockNumberFetcher is an interface that defines a method to fetch balances for a list of addresses, -// as well as the block number for a chain. +// BalanceAndBlockNumberFetcher fetches native and ERC20 balances together with the block number they belong to. // //go:generate moq -pkg mocks -out mocks/balanceandblocknumberfetcher.go . BalanceAndBlockNumberFetcher type BalanceAndBlockNumberFetcher interface { - // Balances returns balances at the specified block, or the latest if nil, for a list of addresses. - Balances(ctx context.Context, addresses []common.Address, blockNumber *big.Int) (map[common.Address]*big.Int, error) - // BlockNumber returns the current latest block number. - BlockNumber(ctx context.Context) (*big.Int, error) + // BalancesSnapshot returns the latest block number with the native balances of addresses and the + // ERC20 balances of {token contract, holder} pairs at that block. Unreadable balances are omitted. + BalancesSnapshot( + ctx context.Context, + addresses []common.Address, + tokenHolders [][2]common.Address, + ) (*big.Int, map[common.Address]*big.Int, map[[2]common.Address]*big.Int, error) } // TokenTransactionsFetcher can prefetch token transactions for an address. @@ -186,6 +188,7 @@ func (u *Updater) probeActiveAccounts() { func (u *Updater) PollBalances() { timer := time.After(0) activeProbeTimer := time.After(activeProbeInterval) + retryDelay := activeProbeRetryDelay for { select { @@ -197,7 +200,7 @@ func (u *Updater) PollBalances() { return case account := <-u.enqueueUpdateForAccount: etherScanClient := etherscan.NewEtherScan(account.ETHCoin().ChainIDstr(), u.etherscanClient, u.etherscanRateLimiter) - u.UpdateBalancesAndBlockNumber([]*Account{account}, etherScanClient) + _ = u.UpdateBalancesAndBlockNumber([]*Account{account}, etherScanClient) continue case <-u.updateETHAccountsCh: case <-timer: @@ -206,19 +209,18 @@ func (u *Updater) PollBalances() { activeProbeTimer = time.After(activeProbeInterval) continue } - u.runUpdate() - timer = time.After(pollInterval) + if err := u.updateAccounts(); err != nil { + timer = time.After(retryDelay) + retryDelay = min(2*retryDelay, pollInterval) + } else { + retryDelay = activeProbeRetryDelay + timer = time.After(pollInterval) + } } } } -func (u *Updater) runUpdate() { - if err := u.updateAccounts(); err != nil { - u.log.WithError(err).Error("could not update ETH accounts") - } -} - func (account *Account) remoteBalance() *big.Int { defer account.updateLock.RLock()() return account.rawBalance.BigInt() @@ -232,15 +234,9 @@ func (u *Updater) probeActiveAccountBalances( return } - nativeAccountsByAddress := map[common.Address][]*Account{} - nativeAddresses := []common.Address{} - changedAccounts := []*Account{} - addChangedAccount := func(account *Account, remoteBalance *big.Int) { - if account.remoteBalance().Cmp(remoteBalance) != 0 { - changedAccounts = append(changedAccounts, account) - } - } - + probedAccounts := []*Account{} + addresses := []common.Address{} + tokenHolders := [][2]common.Address{} for _, account := range ethAccounts { if account.isClosed() { u.SetAccountActivity(account, false) @@ -251,68 +247,65 @@ func (u *Updater) probeActiveAccountBalances( u.log.WithError(err).Errorf("Could not get address for account %s", account.Config().Code) continue } + probedAccounts = append(probedAccounts, account) if IsERC20(account) { - balance, err := account.coin.client.ERC20Balance(account.address.Address, account.coin.erc20Token, nil) - if err != nil { - u.log.WithError(err).Errorf("Could not probe ERC20 balance for address %s", address.Address.Hex()) - u.setActiveProbeBackoff() - continue - } - addChangedAccount(account, balance) - continue - } - if _, ok := nativeAccountsByAddress[address.Address]; !ok { - nativeAddresses = append(nativeAddresses, address.Address) + tokenHolders = append(tokenHolders, [2]common.Address{account.coin.erc20Token.ContractAddress(), address.Address}) + } else { + addresses = append(addresses, address.Address) } - nativeAccountsByAddress[address.Address] = append(nativeAccountsByAddress[address.Address], account) + } + if len(probedAccounts) == 0 { + return } - if len(nativeAddresses) > 0 { - balances, err := etherScanClient.Balances(context.TODO(), nativeAddresses, nil) - if err != nil { - u.log.WithError(err).Error("Could not probe ETH account balances") - u.setActiveProbeBackoff() + _, balances, tokenBalances, err := etherScanClient.BalancesSnapshot(context.TODO(), addresses, tokenHolders) + if err != nil { + u.log.WithError(err).Error("Could not probe ETH account balances") + u.setActiveProbeBackoff() + return + } + changedAccounts := []*Account{} + for _, account := range probedAccounts { + var balance *big.Int + var ok bool + if IsERC20(account) { + balance, ok = tokenBalances[[2]common.Address{account.coin.erc20Token.ContractAddress(), account.address.Address}] } else { - for address, accounts := range nativeAccountsByAddress { - balance, ok := balances[address] - if !ok { - u.log.Errorf("Could not find probed balance for address %s", address.Hex()) - continue - } - for _, account := range accounts { - addChangedAccount(account, balance) - } - } + balance, ok = balances[account.address.Address] + } + if !ok { + u.log.Errorf("Could not find probed balance for address %s", account.address.Address.Hex()) + continue + } + if account.remoteBalance().Cmp(balance) != 0 { + changedAccounts = append(changedAccounts, account) } } if len(changedAccounts) == 0 { return } - // The probed balances are from the latest block. Refresh at a single block so balances and - // outgoing transactions are consistent. - u.UpdateBalancesAndBlockNumber(changedAccounts, etherScanClient) - // Etherscan can report a new balance before indexing the transaction. Refresh again after - // 30 seconds to pick up missing transactions without waiting for the next five-minute poll. - for _, account := range changedAccounts { - u.scheduleAccountUpdate(account, activeProbeRetryDelay) - } + // The probe only reads balances, the full update also refreshes the transactions. + _ = u.UpdateBalancesAndBlockNumber(changedAccounts, etherScanClient) } // UpdateBalancesAndBlockNumber updates the balances of the accounts in the provided slice. -func (u *Updater) UpdateBalancesAndBlockNumber(ethAccounts []*Account, etherScanClient BalanceAndBlockNumberFetcher) { +// It returns an error if the block number and balances could not be read, in which case no account +// was updated. +func (u *Updater) UpdateBalancesAndBlockNumber(ethAccounts []*Account, etherScanClient BalanceAndBlockNumberFetcher) error { if len(ethAccounts) == 0 { - return + return nil } chainId := ethAccounts[0].ETHCoin().ChainID() for _, account := range ethAccounts { if account.ETHCoin().ChainID() != chainId { u.log.Error("Cannot update balances and block number for accounts with different chain IDs") - return + return nil } } ethNonErc20Addresses := make([]common.Address, 0, len(ethAccounts)) + tokenHolders := [][2]common.Address{} for _, account := range ethAccounts { if account.isClosed() { continue @@ -323,21 +316,17 @@ func (u *Updater) UpdateBalancesAndBlockNumber(ethAccounts []*Account, etherScan account.SetOffline(err) continue } - if !IsERC20(account) { + if IsERC20(account) { + tokenHolders = append(tokenHolders, [2]common.Address{account.coin.erc20Token.ContractAddress(), address.Address}) + } else { ethNonErc20Addresses = append(ethNonErc20Addresses, address.Address) } } - blockNumber, err := etherScanClient.BlockNumber(context.TODO()) - if err != nil { - u.log.WithError(err).Error("Could not get block number") - return - } - updateNonERC20 := true - balances, err := etherScanClient.Balances(context.TODO(), ethNonErc20Addresses, blockNumber) + blockNumber, balances, tokenBalances, err := etherScanClient.BalancesSnapshot(context.TODO(), ethNonErc20Addresses, tokenHolders) if err != nil { - u.log.WithError(err).Error("Could not get balances for ETH accounts") - updateNonERC20 = false + u.log.WithError(err).Error("Could not get block number and balances") + return err } reconciled := make(map[senderKey]error) @@ -373,26 +362,14 @@ func (u *Updater) UpdateBalancesAndBlockNumber(ethAccounts []*Account, etherScan } account.SetOffline(nil) var balance *big.Int - switch { - case IsERC20(account): - var err error - balance, err = account.coin.client.ERC20Balance(account.address.Address, account.coin.erc20Token, blockNumber) - if err != nil { - u.log.WithError(err).Errorf("Could not get ERC20 balance for address %s", address.Address.Hex()) - account.SetOffline(err) - } - case updateNonERC20: - var ok bool + var ok bool + if IsERC20(account) { + balance, ok = tokenBalances[[2]common.Address{account.coin.erc20Token.ContractAddress(), address.Address}] + } else { balance, ok = balances[address.Address] - if !ok { - errMsg := fmt.Sprintf("Could not find balance for address %s", address.Address.Hex()) - u.log.Error(errMsg) - account.SetOffline(errp.Newf(errMsg)) - } - default: - // If we get there, this is a non-erc20 account and we failed getting balances. - // If we couldn't get the balances for non-erc20 accounts, we mark them as offline - errMsg := fmt.Sprintf("Could not get balance for address %s", address.Address.Hex()) + } + if !ok { + errMsg := fmt.Sprintf("Could not find balance for address %s", address.Address.Hex()) u.log.Error(errMsg) account.SetOffline(errp.Newf(errMsg)) } @@ -408,13 +385,19 @@ func (u *Updater) UpdateBalancesAndBlockNumber(ethAccounts []*Account, etherScan } confirmedTransactions = prefetched } + wasSynced, previousBalance := account.Synced(), account.remoteBalance() if err := account.Update(balance, blockNumber, confirmedTransactions, outgoingRecords[key]); err != nil { u.log.WithError(err).Errorf("Could not update balance for address %s", address.Address.Hex()) account.SetOffline(err) } else { account.SetOffline(nil) + // Etherscan can report a new balance before indexing its transaction. + if wasSynced && previousBalance.Cmp(balance) != 0 { + u.scheduleAccountUpdate(account, activeProbeRetryDelay) + } } } + return nil } func (u *Updater) prefetchTokenTransactions( diff --git a/backend/coins/eth/updater_internal_test.go b/backend/coins/eth/updater_internal_test.go index b7480913a7..35bbbd09d1 100644 --- a/backend/coins/eth/updater_internal_test.go +++ b/backend/coins/eth/updater_internal_test.go @@ -3,7 +3,6 @@ package eth import ( - "encoding/json" "fmt" "io" "math/big" @@ -14,11 +13,36 @@ import ( "testing/synctest" "time" - gethtypes "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" "github.com/stretchr/testify/require" "golang.org/x/time/rate" ) +func balancesSnapshotResponse(t *testing.T, blockNumber *big.Int, balance *big.Int) *http.Response { + t.Helper() + uint256Type, err := abi.NewType("uint256", "", nil) + require.NoError(t, err) + bytes32Type, err := abi.NewType("bytes32", "", nil) + require.NoError(t, err) + resultsType, err := abi.NewType("tuple[]", "", []abi.ArgumentMarshaling{ + {Name: "success", Type: "bool"}, {Name: "returnData", Type: "bytes"}, + }) + require.NoError(t, err) + result, err := abi.Arguments{{Type: uint256Type}, {Type: bytes32Type}, {Type: resultsType}}.Pack( + blockNumber, + [32]byte{}, + []struct { + Success bool + ReturnData []byte + }{{true, common.BigToHash(balance).Bytes()}}, + ) + require.NoError(t, err) + body := fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"result":%q}`, hexutil.Encode(result)) + return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(body))} +} + func TestActiveAccountLease(t *testing.T) { now := time.Unix(1000, 0) updater := NewUpdater(nil, nil, nil, nil) @@ -40,10 +64,7 @@ func TestActiveAccountBalanceUpdates(t *testing.T) { synctest.Test(t, func(t *testing.T) { account := newAccountWithOptions(t, true, nil) defer account.Close() - address, err := account.Address() - require.NoError(t, err) - header, err := json.Marshal(&gethtypes.Header{Number: big.NewInt(101), Difficulty: big.NewInt(0)}) - require.NoError(t, err) + require.NoError(t, account.Update(big.NewInt(0), big.NewInt(100), nil, nil)) var remoteBalance atomic.Int64 requests := make(chan string, 10) @@ -51,16 +72,10 @@ func TestActiveAccountBalanceUpdates(t *testing.T) { query := request.URL.Query() action := query.Get("action") requests <- action + " " + query.Get("tag") - var body string - switch action { - case "balancemulti": - body = fmt.Sprintf(`{"status":"1","result":[{"account":%q,"balance":"%d"}]}`, address.Address.Hex(), remoteBalance.Load()) - case "eth_getBlockByNumber": - body = fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"result":%s}`, header) - default: + if action != "eth_call" { return nil, fmt.Errorf("unexpected action: %s", action) } - return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(body))}, nil + return balancesSnapshotResponse(t, big.NewInt(101), big.NewInt(remoteBalance.Load())), nil })} updater := NewUpdater(nil, client, rate.NewLimiter(rate.Inf, 1), func() error { return nil }) defer updater.Close() @@ -71,32 +86,33 @@ func TestActiveAccountBalanceUpdates(t *testing.T) { time.Sleep(time.Minute) synctest.Wait() require.Len(t, requests, 1) - require.Equal(t, "balancemulti latest", <-requests) + require.Equal(t, "eth_call latest", <-requests) remoteBalance.Store(1000) updater.SetAccountActivity(account, true) time.Sleep(time.Minute) synctest.Wait() - require.Len(t, requests, 3) - require.Equal(t, "balancemulti latest", <-requests) - require.Equal(t, "eth_getBlockByNumber latest", <-requests) - require.Equal(t, "balancemulti 0x65", <-requests) + require.Len(t, requests, 2) + require.Equal(t, "eth_call latest", <-requests) + require.Equal(t, "eth_call latest", <-requests) require.Equal(t, big.NewInt(1000), account.remoteBalance()) + unlock := account.updateLock.RLock() + require.Equal(t, big.NewInt(101), account.blockNumber) + unlock() time.Sleep(29 * time.Second) synctest.Wait() require.Empty(t, requests) time.Sleep(time.Second) synctest.Wait() - require.Len(t, requests, 2) - require.Equal(t, "eth_getBlockByNumber latest", <-requests) - require.Equal(t, "balancemulti 0x65", <-requests) + require.Len(t, requests, 1) + require.Equal(t, "eth_call latest", <-requests) updater.SetAccountActivity(account, true) time.Sleep(30 * time.Second) synctest.Wait() require.Len(t, requests, 1) - require.Equal(t, "balancemulti latest", <-requests) + require.Equal(t, "eth_call latest", <-requests) }) } @@ -104,8 +120,6 @@ func TestActiveAccountProbesDoNotOverlap(t *testing.T) { synctest.Test(t, func(t *testing.T) { account := newAccountWithOptions(t, true, nil) defer account.Close() - address, err := account.Address() - require.NoError(t, err) release := make(chan struct{}) defer close(release) var calls atomic.Int32 @@ -113,8 +127,7 @@ func TestActiveAccountProbesDoNotOverlap(t *testing.T) { if calls.Add(1) == 1 { <-release } - body := fmt.Sprintf(`{"status":"1","result":[{"account":%q,"balance":"0"}]}`, address.Address.Hex()) - return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(body))}, nil + return balancesSnapshotResponse(t, big.NewInt(100), big.NewInt(0)), nil })} updater := NewUpdater(nil, client, rate.NewLimiter(rate.Inf, 1), func() error { return nil }) defer updater.Close() diff --git a/backend/coins/eth/updater_test.go b/backend/coins/eth/updater_test.go index d1cf4af7ff..2ba1dbad36 100644 --- a/backend/coins/eth/updater_test.go +++ b/backend/coins/eth/updater_test.go @@ -18,7 +18,6 @@ import ( "github.com/BitBoxSwiss/bitbox-wallet-app/backend/coins/eth/mocks" rpcclientmocks "github.com/BitBoxSwiss/bitbox-wallet-app/backend/coins/eth/rpcclient/mocks" "github.com/BitBoxSwiss/bitbox-wallet-app/backend/signing" - "github.com/BitBoxSwiss/bitbox-wallet-app/util/errp" "github.com/BitBoxSwiss/bitbox-wallet-app/util/logging" "github.com/BitBoxSwiss/bitbox-wallet-app/util/test" "github.com/btcsuite/btcd/btcutil/v2/hdkeychain" @@ -52,7 +51,7 @@ func (m *transactionsSourceMock) Transactions( return m.txs, nil } -func newAccount(t *testing.T, erc20Token *erc20.Token, erc20error bool) *eth.Account { +func newAccount(t *testing.T, erc20Token *erc20.Token) *eth.Account { t.Helper() log := logging.Get().WithGroup("updater_test") @@ -87,12 +86,6 @@ func newAccount(t *testing.T, erc20Token *erc20.Token, erc20error bool) *eth.Acc BlockNumberFunc: func(ctx context.Context) (*big.Int, error) { return big.NewInt(100), nil }, - ERC20BalanceFunc: func(address common.Address, token *erc20.Token, blockNumber *big.Int) (*big.Int, error) { - if erc20error { - return nil, errp.New("failed to fetch ERC20 balance") - } - return big.NewInt(1e16), nil // Mock balance for ERC20 token - }, } coin := eth.NewCoin(client, coin.CodeSEPETH, "Sepolia", "SEPETH", "SEPETH", params.SepoliaChainConfig, "", nil, erc20Token) @@ -134,27 +127,27 @@ func TestUpdateBalances(t *testing.T) { }{ { name: "Single account - non erc20", - accounts: []*eth.Account{newAccount(t, nil, false)}, + accounts: []*eth.Account{newAccount(t, nil)}, expectedBalances: []*big.Int{big.NewInt(1000)}, }, { name: "Single account - erc20", - accounts: []*eth.Account{newAccount(t, erc20.NewToken("0x0000000000000000000000000000000000000001", 12), false)}, + accounts: []*eth.Account{newAccount(t, erc20.NewToken("0x0000000000000000000000000000000000000001", 12))}, expectedBalances: []*big.Int{big.NewInt(1e16)}, }, { name: "Multiple accounts - one erc20", accounts: []*eth.Account{ - newAccount(t, nil, false), - newAccount(t, erc20.NewToken("0x0000000000000000000000000000000000000001", 12), false), + newAccount(t, nil), + newAccount(t, erc20.NewToken("0x0000000000000000000000000000000000000001", 12)), }, expectedBalances: []*big.Int{big.NewInt(1000), big.NewInt(1e16)}, // 1e16 is the balance for the erc20 token }, { name: "Multiple accounts - the nonerc20 account is closed", accounts: []*eth.Account{ - newAccount(t, nil, false), - newAccount(t, erc20.NewToken("0x0000000000000000000000000000000000000001", 12), false), + newAccount(t, nil), + newAccount(t, erc20.NewToken("0x0000000000000000000000000000000000000001", 12)), }, expectedBalances: []*big.Int{big.NewInt(1000), big.NewInt(1e16)}, accountsToClose: []int{0}, @@ -162,18 +155,22 @@ func TestUpdateBalances(t *testing.T) { } updatedBalances := []common.Address{} + updatedTokenHolders := [][2]common.Address{} balanceFetcher := mocks.BalanceAndBlockNumberFetcherMock{ - BalancesFunc: func(ctx context.Context, addresses []common.Address, blockNumber *big.Int) (map[common.Address]*big.Int, error) { + BalancesSnapshotFunc: func( + ctx context.Context, addresses []common.Address, tokenHolders [][2]common.Address, + ) (*big.Int, map[common.Address]*big.Int, map[[2]common.Address]*big.Int, error) { updatedBalances = addresses - // We mock the balanceFetcher to always return a balance of 1000. + updatedTokenHolders = tokenHolders balances := make(map[common.Address]*big.Int) for _, address := range addresses { balances[address] = big.NewInt(1000) } - return balances, nil - }, - BlockNumberFunc: func(ctx context.Context) (*big.Int, error) { - return big.NewInt(100), nil + tokenBalances := make(map[[2]common.Address]*big.Int) + for _, tokenHolder := range tokenHolders { + tokenBalances[tokenHolder] = big.NewInt(1e16) + } + return big.NewInt(100), balances, tokenBalances, nil }, } @@ -193,16 +190,21 @@ func TestUpdateBalances(t *testing.T) { accountWasClosed := slices.Contains(tc.accountsToClose, i) address, err := acct.Address() require.NoError(t, err) + var tokenHolder [2]common.Address + if eth.IsERC20(acct) { + tokenHolder = [2]common.Address{acct.ETHCoin().ERC20Token().ContractAddress(), address.Address} + } if accountWasClosed { // If the account was closed, it must not have its balance updated. require.NotContains(t, updatedBalances, address.Address) + require.NotContains(t, updatedTokenHolders, tokenHolder) continue } assertAccountBalance(t, acct, tc.expectedBalances[i]) if eth.IsERC20(acct) { - // ERC20 accounts should not have their balances updated by the balanceFetcher - // since they have their own balance fetching logic. + // ERC20 balances are fetched per token contract, not as native balances. require.NotContains(t, updatedBalances, address.Address) + require.Contains(t, updatedTokenHolders, tokenHolder) } else { // Non-closed, non-erc20 accounts should have their balances updated // by the balanceFetcher. @@ -216,26 +218,22 @@ func TestUpdateBalances(t *testing.T) { func TestUpdateBalancesWithError(t *testing.T) { balanceFetcher := &mocks.BalanceAndBlockNumberFetcherMock{ - BalancesFunc: func(ctx context.Context, addresses []common.Address, blockNumber *big.Int) (map[common.Address]*big.Int, error) { - // We mock the balanceFetcher to always return an error. - // This simulates a failure in fetching balances which should set the account to offline. - return nil, errp.New("balance fetch error") - }, - BlockNumberFunc: func(ctx context.Context) (*big.Int, error) { - return big.NewInt(100), nil + BalancesSnapshotFunc: func( + ctx context.Context, addresses []common.Address, tokenHolders [][2]common.Address, + ) (*big.Int, map[common.Address]*big.Int, map[[2]common.Address]*big.Int, error) { + // No balance could be read, which should set the accounts offline. + return big.NewInt(100), map[common.Address]*big.Int{}, map[[2]common.Address]*big.Int{}, nil }, } updater := eth.NewUpdater(nil, nil, nil, nil) - account := newAccount(t, nil, false) + account := newAccount(t, nil) defer account.Close() updater.UpdateBalancesAndBlockNumber([]*eth.Account{account}, balanceFetcher) require.Error(t, account.Offline()) - // We create an ERC20 account and pass "true" to the "erc20error" parameter to simulate an error. - // This way we expect the account to be set offline as well. - erc20Account := newAccount(t, erc20.NewToken("0x0000000000000000000000000000000000000001", 12), true) + erc20Account := newAccount(t, erc20.NewToken("0x0000000000000000000000000000000000000001", 12)) defer erc20Account.Close() updater.UpdateBalancesAndBlockNumber([]*eth.Account{erc20Account}, balanceFetcher) @@ -262,8 +260,8 @@ func makeConfirmedTx(id string) *accounts.TransactionData { func TestUpdateBalancesPrefetchTokenTransactions(t *testing.T) { tokenA := erc20.NewToken("0x0000000000000000000000000000000000000001", 12) tokenB := erc20.NewToken("0x0000000000000000000000000000000000000002", 12) - accountA := newAccount(t, tokenA, false) - accountB := newAccount(t, tokenB, false) + accountA := newAccount(t, tokenA) + accountB := newAccount(t, tokenB) defer accountA.Close() defer accountB.Close() @@ -280,12 +278,15 @@ func TestUpdateBalancesPrefetchTokenTransactions(t *testing.T) { blockNumber := big.NewInt(100) tokenTxCalls := 0 fetcher := &mocks.TokenTransactionsFetcherMock{ - BalancesFunc: func(ctx context.Context, addresses []common.Address, blockNumber *big.Int) (map[common.Address]*big.Int, error) { + BalancesSnapshotFunc: func( + ctx context.Context, addresses []common.Address, tokenHolders [][2]common.Address, + ) (*big.Int, map[common.Address]*big.Int, map[[2]common.Address]*big.Int, error) { require.Len(t, addresses, 0) - return map[common.Address]*big.Int{}, nil - }, - BlockNumberFunc: func(ctx context.Context) (*big.Int, error) { - return blockNumber, nil + tokenBalances := make(map[[2]common.Address]*big.Int) + for _, tokenHolder := range tokenHolders { + tokenBalances[tokenHolder] = big.NewInt(1e16) + } + return blockNumber, map[common.Address]*big.Int{}, tokenBalances, nil }, TokenTransactionsByContractFunc: func( blockTipHeight *big.Int, @@ -315,12 +316,15 @@ func TestUpdateBalancesPrefetchNilVsEmptyFallback(t *testing.T) { tokenTxCalls := 0 var tokenTxResult map[common.Address][]*accounts.TransactionData fetcher := &mocks.TokenTransactionsFetcherMock{ - BalancesFunc: func(ctx context.Context, addresses []common.Address, blockNumber *big.Int) (map[common.Address]*big.Int, error) { + BalancesSnapshotFunc: func( + ctx context.Context, addresses []common.Address, tokenHolders [][2]common.Address, + ) (*big.Int, map[common.Address]*big.Int, map[[2]common.Address]*big.Int, error) { require.Len(t, addresses, 0) - return map[common.Address]*big.Int{}, nil - }, - BlockNumberFunc: func(ctx context.Context) (*big.Int, error) { - return blockNumber, nil + tokenBalances := make(map[[2]common.Address]*big.Int) + for _, tokenHolder := range tokenHolders { + tokenBalances[tokenHolder] = big.NewInt(1e16) + } + return blockNumber, map[common.Address]*big.Int{}, tokenBalances, nil }, TokenTransactionsByContractFunc: func( blockTipHeight *big.Int, @@ -335,7 +339,7 @@ func TestUpdateBalancesPrefetchNilVsEmptyFallback(t *testing.T) { } t.Run("no-prefetch-falls-back-to-nil", func(t *testing.T) { - account := newAccount(t, erc20.NewToken("0x0000000000000000000000000000000000000001", 12), false) + account := newAccount(t, erc20.NewToken("0x0000000000000000000000000000000000000001", 12)) defer account.Close() txSource := &transactionsSourceMock{} account.ETHCoin().TstSetTransactionsSource(txSource) @@ -353,8 +357,8 @@ func TestUpdateBalancesPrefetchNilVsEmptyFallback(t *testing.T) { }) t.Run("missing-contract-is-empty-no-fallback", func(t *testing.T) { - accountA := newAccount(t, erc20.NewToken("0x0000000000000000000000000000000000000001", 12), false) - accountB := newAccount(t, erc20.NewToken("0x0000000000000000000000000000000000000002", 12), false) + accountA := newAccount(t, erc20.NewToken("0x0000000000000000000000000000000000000001", 12)) + accountB := newAccount(t, erc20.NewToken("0x0000000000000000000000000000000000000002", 12)) defer accountA.Close() defer accountB.Close() txSource := &transactionsSourceMock{}