Skip to content

Instantly share code, notes, and snippets.

@arshamalh
Last active February 17, 2024 07:30
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arshamalh/9fe035f7fe18cb5387737546ef84bf6c to your computer and use it in GitHub Desktop.
Save arshamalh/9fe035f7fe18cb5387737546ef84bf6c to your computer and use it in GitHub Desktop.
Finding ETH erc20 tokens balance using golang and infura.io
/// Import on the top of your project
import "github.com/ethereum/go-ethereum/crypto"
type ethHandlerResult struct {
Result string `json:"result"`
Error struct {
Code int64 `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
address := "0x757d576da3fba018b1bd9cdd05fa4ca0261792c8" // Account Address here
contractAddress := "0xdac17f958d2ee523a2206206994597c13d831ec7" // Contract address, for example, it's tether
infuraProjectID := "Write your infura project ID here" // https://infura.io
data := crypto.Keccak256Hash([]byte("balanceOf(address)")).String()[0:10] + "000000000000000000000000" + address[2:]
postBody, _ = json.Marshal(map[string]interface{}{
"id": 1,
"jsonrpc": "2.0",
"method": "eth_call",
"params": []interface{}{
map[string]string{
"to": contractAddress,
"data": data,
},
"latest",
},
})
requestBody := bytes.NewBuffer(postBody)
resp, err := http.Post("https://mainnet.infura.io/v3/" + infuraProjectID, "application/json", requestBody)
if err != nil {
return nil, err
}
ethResult := new(ethHandlerResult)
if err := json.NewDecoder(resp.Body).Decode(&ethResult); err != nil {
return nil, err
}
balance.SetString(ethResult.Result[2:], 16)
fmt.Println(balance)
@dimalinux
Copy link

Where is ethResult used on line 33 declared?

@arshamalh
Copy link
Author

@dimalinux Thanks for your catch, that should be a variable of type ethHandlerResult, I updated the gist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment