Created
October 6, 2021 15:28
-
-
Save chumaknadya/d350e68defb6918a4b5872d28f949bd7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func (s *ServiceETH) GetBalance(req *WalletBalanceRequest) (*big.Int, error) { | |
client, err := ethclient.Dial(req.GatewayURL) | |
if err != nil { | |
return nil, err | |
} | |
rctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(DefaultTimeout)) | |
defer cancel() | |
walletAddress := common.HexToAddress(req.Address) | |
if req.ContractAddress == "" { | |
log.Infof("Get balance at %s", walletAddress.Hex()) | |
balance, err := client.BalanceAt(rctx, walletAddress, nil) | |
if err != nil { | |
return nil, err | |
} | |
return balance, nil | |
} | |
log.Infof("Call smart-contract %s, balanceOf(%s)", req.ContractAddress, walletAddress.Hex()) | |
// Prepare data | |
hash := sha3.NewLegacyKeccak256() | |
hash.Write([]byte("balanceOf(address)")) | |
methodID := hash.Sum(nil)[:4] | |
paddedAddress := common.LeftPadBytes(walletAddress.Bytes(), 32) | |
var data []byte | |
data = append(data, methodID...) | |
data = append(data, paddedAddress...) | |
contractAddress := common.HexToAddress(req.ContractAddress) | |
msg := ethereum.CallMsg{To: &contractAddress, Data: data} | |
balanceBytes, err := client.CallContract(rctx, msg, nil) | |
if err != nil { | |
return nil, err | |
} | |
balance := new(big.Int) | |
balance.SetBytes(balanceBytes) | |
return balance, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment