From 7263fc19509dbcae510c73b841d51e3ce66e6563 Mon Sep 17 00:00:00 2001 From: Mohammed Sohail Date: Tue, 16 Apr 2024 15:59:21 +0800 Subject: [PATCH] feat: add token index fetcher --- internal/chain/token_index.go | 42 +++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 internal/chain/token_index.go diff --git a/internal/chain/token_index.go b/internal/chain/token_index.go new file mode 100644 index 0000000..113aa96 --- /dev/null +++ b/internal/chain/token_index.go @@ -0,0 +1,42 @@ +package chain + +import ( + "context" + "math/big" + + "github.com/celo-org/celo-blockchain/common" + "github.com/grassrootseconomics/w3-celo" + "github.com/grassrootseconomics/w3-celo/module/eth" + "github.com/grassrootseconomics/w3-celo/w3types" +) + +var ( + entryCountFunc = w3.MustNewFunc("entryCount()", "uint256") + entrySig = w3.MustNewFunc("entry(uint256 _idx)", "address") +) + +func (c *Chain) GetAllTokensFromTokenIndex(ctx context.Context, tokenIndex common.Address) ([]common.Address, error) { + var ( + tokenIndexEntryCount big.Int + ) + + if err := c.provider.Client.CallCtx( + ctx, + eth.CallFunc(tokenIndex, entryCountFunc).Returns(&tokenIndexEntryCount), + ); err != nil { + return nil, err + } + + calls := make([]w3types.RPCCaller, tokenIndexEntryCount.Int64()) + tokenAddresses := make([]common.Address, tokenIndexEntryCount.Int64()) + + for i := 0; i < int(tokenIndexEntryCount.Int64()); i++ { + calls[i] = eth.CallFunc(tokenIndex, entrySig, new(big.Int).SetInt64(int64(i))).Returns(&tokenAddresses[i]) + } + + if err := c.provider.Client.CallCtx(ctx, calls...); err != nil { + return nil, err + } + + return tokenAddresses, nil +}