Last active
July 28, 2017 06:32
-
-
Save danfinlay/d55d9f527c38a93a945482c5b700f407 to your computer and use it in GitHub Desktop.
ethjs token example
This file contains hidden or 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
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
Can't make PRs on gists, can only recommend that you change the web3 check to use a string 'undefined' rather than an actual undefined.