<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="../js/web3.min.js"></script> </head> <body>
<h1>Get ERC20-Token Balance</h1>
<h2>Contract Address</h2> <input type="text" id="contract-address" size="80" oninput="onAddressChange()"></input> <p>ex> 0xcd45a142d109bbc8b22ff6028614027d1db4e32f</p>
<h2>Wallet Address</h2> <input type="text" id="wallet-address" size="80" oninput="onAddressChange()"></input> <p>ex> 0x528018c88448f67d2b618a43546cf7e0b026857e</p>
<h2>Result</h2> <span id="result"></span>
<script>
function getERC20TokenBalance(tokenAddress, walletAddress, callback) {
let minABI = [ { "constant":true, "inputs":[{"name":"_owner","type":"address"}], "name":"balanceOf", "outputs":[{"name":"balance","type":"uint256"}], "type":"function" }, // decimals { "constant":true, "inputs":[], "name":"decimals", "outputs":[{"name":"","type":"uint8"}], "type":"function" } ];
let contract = web3.eth.contract(minABI).at(tokenAddress); contract.balanceOf(walletAddress, (error, balance) => { contract.decimals((error, decimals) => { balance = balance.div(10**decimals); console.log(balance.toString()); callback(balance); }); }); }
function onAddressChange(e) { let tokenAddress = document.getElementById('contract-address').value; let walletAddress = document.getElementById('wallet-address').value; if(tokenAddress != "" && walletAddress != "") { getERC20TokenBalance(tokenAddress, walletAddress, (balance) => { document.getElementById('result').innerText = balance.toString(); }); } }
window.onload = function() { if (typeof web3 !== 'undefined') { web3 = new Web3(web3.currentProvider); } else { web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/f76f49a440bf4303ab6d2c1aa21c7537")); } console.log(web3.version); }
</script> <p>ex> https://mainnet.infura.io</p> </body> </html> |