fix stuff and move functions to utils

This commit is contained in:
Jonathan Rainville 2018-07-31 10:33:10 -04:00 committed by Iuri Matias
parent 609c050576
commit 25ffd15984
3 changed files with 79 additions and 66 deletions

View File

@ -425,7 +425,7 @@ class Embark {
if(!options.ensDomain) {
return callback(null, hash);
}
engine.plugins.request("storage:ens:associate",
engine.events.request("storage:ens:associate",
{name: options.ensDomain, storageHash: hash}, (err) => {
if (err) {
return callback(err);

View File

@ -22,7 +22,7 @@ class ENS {
registerEvents() {
this.embark.registerActionForEvent("contracts:deploy:afterAll", this.setProviderAndRegisterDomains.bind(this));
this.embark.setCommandHandler("storage:ens:associate", this.associateStorageToEns.bind(this));
this.events.setCommandHandler("storage:ens:associate", this.associateStorageToEns.bind(this));
}
setProviderAndRegisterDomains(cb) {
@ -65,30 +65,21 @@ class ENS {
}
associateStorageToEns(options, cb) {
const self =this;
const self = this;
// Code inspired by https://github.com/monkybrain/ipfs-to-ens
const {name, storageHash} = options;
if (!ENS.isValidDomain(name)) {
if (!utils.isValidEthDomain(name)) {
return cb('Invalid domain name ' + name);
}
let hashedName = namehash.hash(name);
// Convert IPFS multihash to 32 byte hex string
let contentHash;
if (utils.isHex(storageHash)) {
contentHash = storageHash;
} else {
try {
contentHash = ENS.hashTo32ByteHexString(storageHash);
} catch(e) {
contentHash = utils.hashTo32ByteHexString(storageHash);
} catch (e) {
return cb('Invalid IPFS hash');
}
}
if (!contentHash.startsWith('0x')) {
contentHash = '0x' + contentHash;
}
// Set content
async.waterfall([
@ -143,22 +134,6 @@ class ENS {
], cb);
}
static isValidDomain(domain) {
const isValidDomain = require('is-valid-domain');
if (!isValidDomain(domain)) {
return false;
} else {
return domain.substring(domain.lastIndexOf('.'), domain.length) === '.eth';
}
}
static hashTo32ByteHexString(storageHash) {
const multihash = require('multihashes');
let buf = multihash.fromB58String(storageHash);
let digest = multihash.decode(buf).digest;
return '0x' + multihash.toHexString(digest);
}
registerConfigDomains(config, cb) {
const self = this;
const register = require('./register');

View File

@ -38,7 +38,7 @@ function checkIsAvailable(url, callback) {
}
function httpGetRequest(httpObj, url, callback) {
httpObj.get(url, function(res) {
httpObj.get(url, function (res) {
let body = '';
res.on('data', function (d) {
body += d;
@ -60,22 +60,22 @@ function httpsGet(url, callback) {
}
function httpGetJson(url, callback) {
httpGetRequest(http, url, function(err, body) {
httpGetRequest(http, url, function (err, body) {
try {
let parsed = JSON.parse(body);
return callback(err, parsed);
} catch(e) {
} catch (e) {
return callback(e);
}
});
}
function httpsGetJson(url, callback) {
httpGetRequest(https, url, function(err, body) {
httpGetRequest(https, url, function (err, body) {
try {
let parsed = JSON.parse(body);
return callback(err, parsed);
} catch(e) {
} catch (e) {
return callback(e);
}
});
@ -107,7 +107,7 @@ function pingEndpoint(host, port, type, protocol, origin, callback) {
}
let req;
// remove trailing api key from infura, ie rinkeby.infura.io/nmY8WtT4QfEwz2S7wTbl
if (options.host.indexOf('/') > -1){
if (options.host.indexOf('/') > -1) {
options.host = options.host.split('/')[0];
}
if (protocol === 'https') {
@ -159,12 +159,12 @@ function exit(code) {
function downloadFile(url, dest, cb) {
const o_fs = require('fs-extra');
var file = o_fs.createWriteStream(dest);
(url.substring(0,5) === 'https' ? https : http).get(url, function(response) {
(url.substring(0, 5) === 'https' ? https : http).get(url, function (response) {
response.pipe(file);
file.on('finish', function() {
file.on('finish', function () {
file.close(cb);
});
}).on('error', function(err) {
}).on('error', function (err) {
o_fs.unlink(dest);
if (cb) cb(err.message);
});
@ -177,7 +177,7 @@ function extractTar(filename, packageDirectory, cb) {
tar.x({
strip: 1,
C: packageDirectory
}).on('end', function() {
}).on('end', function () {
cb();
})
);
@ -250,17 +250,44 @@ function getExternalContractUrl(file) {
};
}
function hexToNumber(hex){
function hexToNumber(hex) {
const Web3 = require('web3');
return Web3.utils.hexToNumber(hex);
}
function isHex(hex){
function isHex(hex) {
const Web3 = require('web3');
return Web3.utils.isHex(hex);
}
function decodeParams(typesArray, hexString){
function hashTo32ByteHexString(hash) {
if (isHex(hash)) {
if (!hash.startsWith('0x')) {
hash = '0x' + hash;
}
return hash;
}
const multihash = require('multihashes');
let buf = multihash.fromB58String(hash);
let digest = multihash.decode(buf).digest;
return '0x' + multihash.toHexString(digest);
}
function isValidDomain(domain) {
const isValidDomain = require('is-valid-domain');
return isValidDomain(domain);
}
function isValidEthDomain(ethDomain) {
if (!isValidDomain(ethDomain)) {
return false;
} else {
return ethDomain.substring(ethDomain.lastIndexOf('.'), ethDomain.length) === '.eth';
}
}
function decodeParams(typesArray, hexString) {
var Web3EthAbi = require('web3-eth-abi');
return Web3EthAbi.decodeParameters(typesArray, hexString);
}
@ -286,47 +313,55 @@ function normalizeInput(input) {
return "";
}
if (args.length === 1) {
if (Array.isArray(args[0])) { return args[0].join(','); }
if (Array.isArray(args[0])) {
return args[0].join(',');
}
return args[0] || "";
}
return ('[' + args.map((x) => {
if (x === null) { return "null"; }
if (x === undefined) { return "undefined"; }
if (Array.isArray(x)) { return x.join(','); }
if (x === null) {
return "null";
}
if (x === undefined) {
return "undefined";
}
if (Array.isArray(x)) {
return x.join(',');
}
return x;
}).toString() + ']');
}
/**
* Builds a URL
*
* @param {string} protocol
*
* @param {string} protocol
* The URL protocol, defaults to http.
* @param {string} host
* @param {string} host
* The URL host, required.
* @param {string} port
* @param {string} port
* The URL port, default to empty string.
* @returns {string} the constructued URL, with defaults
*/
function buildUrl (protocol, host, port){
if(!host) throw new Error('utils.buildUrl: parameter \'host\' is required');
if(port) port = ':' + port;
function buildUrl(protocol, host, port) {
if (!host) throw new Error('utils.buildUrl: parameter \'host\' is required');
if (port) port = ':' + port;
else port = '';
return `${protocol || 'http'}://${host}${port}`;
}
/**
* Builds a URL
*
*
* @param {object} configObj Object containing protocol, host, and port to be used to construct the url.
* * protocol {String} (optional) The URL protocol, defaults to http.
* * host {String} (required) The URL host.
* * port {String} (optional) The URL port, default to empty string.
* @returns {string} the constructued URL, with defaults
*/
function buildUrlFromConfig (configObj){
if(!configObj) throw new Error('[utils.buildUrlFromConfig]: config object must cannot be null');
if(!configObj.host) throw new Error('[utils.buildUrlFromConfig]: object must contain a \'host\' property');
function buildUrlFromConfig(configObj) {
if (!configObj) throw new Error('[utils.buildUrlFromConfig]: config object must cannot be null');
if (!configObj.host) throw new Error('[utils.buildUrlFromConfig]: object must contain a \'host\' property');
return this.buildUrl(configObj.protocol, canonicalHost(configObj.host), configObj.port);
}
@ -374,7 +409,7 @@ function compact(array) {
}
function groupBy(array, key) {
return array.reduce(function(rv, x) {
return array.reduce(function (rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
@ -392,23 +427,23 @@ function interceptLogs(consoleContext, logger) {
let context = {};
context.console = consoleContext;
context.console.log = function() {
context.console.log = function () {
logger.info(normalizeInput(arguments));
};
context.console.warn = function() {
context.console.warn = function () {
logger.warn(normalizeInput(arguments));
};
context.console.info = function() {
context.console.info = function () {
logger.info(normalizeInput(arguments));
};
context.console.debug = function() {
context.console.debug = function () {
// TODO: ue JSON.stringify
logger.debug(normalizeInput(arguments));
};
context.console.trace = function() {
context.console.trace = function () {
logger.trace(normalizeInput(arguments));
};
context.console.dir = function() {
context.console.dir = function () {
logger.dir(normalizeInput(arguments));
};
}
@ -427,6 +462,9 @@ module.exports = {
getJson,
hexToNumber,
isHex,
hashTo32ByteHexString,
isValidDomain,
isValidEthDomain,
pingEndpoint,
decodeParams,
runCmd,