Skip to content

Instantly share code, notes, and snippets.

@2-am-zzz
Forked from danfinlay/ethjs-token-example.js
Last active January 28, 2017 08:28
Show Gist options
  • Save 2-am-zzz/3edf41613eecfa5f8f3ab86d1f9da2a9 to your computer and use it in GitHub Desktop.
Save 2-am-zzz/3edf41613eecfa5f8f3ab86d1f9da2a9 to your computer and use it in GitHub Desktop.
ethjs token example
var Eth = require('ethjs')
var tokenAbi = require('human-standard-token-abi')
var tokenAddress = '0x48ff0cbac0acefedf152281ee80e9a0a01d5da63'
var secondAddress = '0xC5b8dBAc4c1d3F152cDeb400E2313F309c410aCb'
var eth, token
window.addEventListener('load', function() {
if (typeof window.web3 !== 'undefined') {
eth = new Eth(web3.currentProvider)
// Now enjoy! Use it!
window.eth = eth
startApp()
} else {
console.log('Better install MetaMask!')
}
})
function startApp() {
const token = eth.contract(tokenAbi).at(tokenAddress)
window.token = token
console.log('fetching name')
token.name().then(function(results) {
var name = results[0]
console.log('Coin is named ' + name)
})
token.totalSupply()
.then((results) => {
var supply = results[0]
console.log(`There are ${supply.toString()} tokens.`)
})
.catch(console.error)
token.transfer(secondAddress, '10', { from: web3.eth.accounts[0] })
.then((hash) => {
console.log('returned!')
console.dir(hash)
pollForReceipt(hash)
})
token.balanceOf(web3.eth.accounts[0])
.then((result) => {
var balance = result[0]
console.log(`The balance of account ${web3.eth.accounts[0]} is ${balance.toString()}`)
})
.catch((error) => {
})
}
function pollForReceipt(hash, freq) {
return new Promise((res, rej) => {
var interval = setInterval(() => {
eth.getTransactionReceipt(hash)
.then((receipt) => {
if (!receipt) return
clearInterval(interval)
res(receipt)
})
.catch((reason) => {
clearInterval(interval)
rej(reason)
})
}, freq || 1000)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment