Skip to content

Commit

Permalink
feat: add tokens balance scanner
Browse files Browse the repository at this point in the history
  • Loading branch information
kamikazechaser committed Apr 11, 2024
1 parent d57fd10 commit 143e0a1
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 0 deletions.
51 changes: 51 additions & 0 deletions balances_scanner.go
Original file line number Diff line number Diff line change
@@ -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
}
33 changes: 33 additions & 0 deletions balances_scanner_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}

0 comments on commit 143e0a1

Please sign in to comment.