diff --git a/balances_scanner.go b/balances_scanner.go new file mode 100644 index 0000000..28fe8a8 --- /dev/null +++ b/balances_scanner.go @@ -0,0 +1,51 @@ +package celoutils + +import ( + "context" + "math/big" + + "github.com/celo-org/celo-blockchain/common" + "github.com/grassrootseconomics/w3-celo" + "github.com/grassrootseconomics/w3-celo/module/eth" +) + +type ( + TokenBalances map[common.Address]*big.Int + + tokensBalanceResp struct { + Success bool + Data []byte + } +) + +const ( + BalanceScannerContractAddress = "0x7617EEB559D1dF0423a18F0F8D92c608261C026C" +) + +func (p *Provider) TokensBalance(ctx context.Context, owner common.Address, tokenAddresses []common.Address) (TokenBalances, error) { + var ( + resp []tokensBalanceResp + + tokensBalanceFunc = w3.MustNewFunc("tokensBalance(address,address[])", "(bool success, bytes data)[]") + ) + + err := p.Client.CallCtx( + ctx, + eth.CallFunc( + w3.A(BalanceScannerContractAddress), + tokensBalanceFunc, + owner, + tokenAddresses, + ).Returns(&resp), + ) + if err != nil { + return nil, err + } + + tokenBalances := make(TokenBalances) + for i, v := range resp { + tokenBalances[tokenAddresses[i]] = new(big.Int).SetBytes(v.Data) + } + + return tokenBalances, nil +} diff --git a/balances_scanner_test.go b/balances_scanner_test.go new file mode 100644 index 0000000..bc7456f --- /dev/null +++ b/balances_scanner_test.go @@ -0,0 +1,33 @@ +package celoutils + +import ( + "context" + "testing" + + "github.com/celo-org/celo-blockchain/common" + "github.com/grassrootseconomics/w3-celo" +) + +func TestProvider_TokensBalance(t *testing.T) { + // + t.SkipNow() + // + p, err := NewProvider(ProviderOpts{ + ChainId: MainnetChainId, + RpcEndpoint: "https://1rpc.io/celo", + }) + if err != nil { + t.Fatal("RPC endpoint parsing failed") + } + + tokens := []common.Address{ + w3.A("0x02cc0715E844a45bA56Ad391D92DCd6537315177"), + w3.A("0x2105a206B7bec31E2F90acF7385cc8F7F5f9D273"), + w3.A("0x45d747172e77d55575c197CbA9451bC2CD8F4958"), + } + + _, err = p.TokensBalance(context.Background(), w3.A("0x0030cfF17fAf04a4Bb0657d47999099B3cbF9ccc"), tokens) + if err != nil { + t.Fatal(err) + } +}