So, you got some standard ERC20 token from wherever, be it a popular one like Golem (GNT) or a more obscure one like the infamous yet entirely unknown Kekel, and you want to check your balance. How do you do that? Mist offers a simple UI for that, but when you are a real crack, you are of course using only geth console. Here’s what you need.
Checking Token Balance – Basic Way
You’re going to need three things:
- The token contract address
- Your account address
- The token contract’s ABI
You need to figure out the first two yourself. You can use a generic ABI to check token balance. We instantiate the contract ABI as follows:
> var tokenContract = eth.contract([{ "type":"function", "name":"balanceOf", "constant":true, "payable":false, "inputs":[{"name":"","type":"address"}], "outputs":[{"name":"","type":"uint256","value":"0"}] }]);
Now we have the contract’s interface. Next we use it to check our balance. The following example will show my account’s Golem balance:
> var golemContractAddress = "0xa74476443119A942dE498590Fe1f2454d7D4aC0d"; > var account = "0x27f8a692b3c8279fce29f2629b8d87ac717300f8"; > tokenContract.at(golemContractAddress).balanceOf(account); 678633655750000000000
This outputs the token balance in plain tokens, i.e. without showing a decimal point.
Human Standard Token ABI
For a more thorough solution, I found the Human Standard Token ABI by Dan Finley on github. It is a node.js module which provides an API to standard tokens. I changed it a little so I can run it from the geth console. Install token.js in a local folder on the machine where you run geth, such as /home/user/geth/token.js, and run the geth console with
geth console --preload /home/user/geth/token.js
Now you have the full functionality of a token contracts in the variable “tokenContract”:
> var golemContractAddress = "0xa74476443119A942dE498590Fe1f2454d7D4aC0d"; > var account = "0x27f8a692b3c8279fce29f2629b8d87ac717300f8"; > var golem = tokenContract.at(golemContractAddress); > golem.symbol(); "GNT" > golem.name(); "Golem Network Token" > golem.balanceOf(account); 678633655750000000000 > golem.decimals() 18
The ABI also supports sending tokens as follows:
var value = '100' // Base 10, accounts for decimals. golem.transfer(toAddress, value, { from: addr }, function (err, txHash) { if (err) console.error(err) if (txHash) { console.log('Transaction sent') console.dir(txHash) } })
Please refer to the readme on github.
I hope this was helpful and wish you a nice day 🙂