This is a playground to test JavaScript. It runs a completely standard copy of Node.js on a virtual server created just for you. Every one of npm’s 300,000+ packages are pre-installed, so try it out:
/**
* Welcome to the AppliedBlockchain test!
* Clone this notebook before writing anything
*
* The script should be able to:
* - Receive an ethereum address from the query (eg: ?address=0xc96b5bf11d1bceaff8646b37a7f83d1be878bae5)
* - Validate if the address is valid, otherwise return this json { "error:": "Invalid ETH address." }
* - If valid
* - Check its balance via etherscan api
* - Convert from wei to eth
* - Return the balance in json format
*
* Infos:
* An ETH address always begins with `0x` and has 42 characters
* You can use the apiKey "testKey" for Etherscan
*
* Constraints:
* - The node version used should be v6.12.2
* - The `endpoint` function will be the main function called
* - JSON response expected
*
* Response expected:
* {
* "author": {
* "name": "Your name",
* "email": "Your e-mail"
* },
* "address": "Address sent to the script",
* "valid": "boolean expected",
* // The below part is only visible if the address is valid
* "balance": {
* "wei": "balance in wei",
* "eth": "balance in eth"
* }
* }
*
* When the test is finish, please send us the endpoint url by email to: blockchainweek2018@appliedblockchain.com
* eg: https://runkit.io/oktapodia/5a5f67829fbc9a001258e093/branches/master
*
*/
require("fast-json-stable-stringify");
var endpoint = require("@runkit/runkit/json-endpoint/1.0.0");
var etherscan = require("etherscan-api").init('testKey');
var extend = require('node.extend');
endpoint(module.exports, function(req, done) {
// The ethereum address provided
const ethAddress = req.query.address;
// Your code should be written here
let balance;
let wei;
let eth;
let isAddressInvalid = !ethAddress || !ethAddress.startsWith("0x") || ethAddress.length !== 42;
let response = {
"author": {
"name": "Miguel Coelho Ribeiro",
"email": "miguel.rib.20@gmail.com"
},
"address": ethAddress,
"valid": !isAddressInvalid
};
if (isAddressInvalid) {
response = extend(response, { "error:": "Invalid ETH address." });
return done(response);
}
balance = etherscan.account.balance(ethAddress);
balance.then(function (balanceData) {
wei = balanceData.result;
eth = balanceData.result / Math.pow(10, 18);
})
.then(function () {
response = extend(response, {
"balance": {
"wei": wei,
"eth": eth
}
});
})
.then(function () {
return done(response);
});
})