Refactoring, functions comments

This commit is contained in:
viktor 2017-06-28 16:42:40 +03:00
parent de7f7aa6c0
commit b67b42362f
4 changed files with 261 additions and 196 deletions

File diff suppressed because one or more lines are too long

View File

@ -8,6 +8,10 @@ function checkInitialKey(web3, func, initialKey, contractAddr, cb) {
var data = funcEncodePart var data = funcEncodePart
+ toUnifiedLengthLeft(initialKey); + toUnifiedLengthLeft(initialKey);
console.log(data);
console.log("0x" + initialKey);
console.log(contractAddr);
call(web3, "0x" + initialKey, contractAddr, data, function(respHex) { call(web3, "0x" + initialKey, contractAddr, data, function(respHex) {
console.log(respHex); console.log(respHex);
cb(parseInt(respHex, 16)); cb(parseInt(respHex, 16));

View File

@ -1,3 +1,4 @@
//gets web3 object from MetaMask or Parity
function getWeb3(callback) { function getWeb3(callback) {
if (typeof window.web3 === 'undefined') { if (typeof window.web3 === 'undefined') {
// no web3, use fallback // no web3, use fallback
@ -20,6 +21,7 @@ function getWeb3(callback) {
} }
} }
//check current network page is connected to. Alerts, if not Oracles network
function checkNetworkVersion(web3, cb) { function checkNetworkVersion(web3, cb) {
var msgNotOracles = "You aren't connected to Oracles network. Please, switch on Parity or MetaMask client and choose Oracles network. Check Oracles network <a href='https://github.com/oraclesorg/oracles-wiki' target='blank'>wiki</a> for more info."; var msgNotOracles = "You aren't connected to Oracles network. Please, switch on Parity or MetaMask client and choose Oracles network. Check Oracles network <a href='https://github.com/oraclesorg/oracles-wiki' target='blank'>wiki</a> for more info.";
web3.version.getNetwork(function(err, netId) { web3.version.getNetwork(function(err, netId) {
@ -55,6 +57,7 @@ function checkNetworkVersion(web3, cb) {
}) })
} }
//launches main application
function startDapp(web3, isOraclesNetwork) { function startDapp(web3, isOraclesNetwork) {
$(function() { $(function() {
$(".loading-container").hide(); $(".loading-container").hide();
@ -64,132 +67,169 @@ function startDapp(web3, isOraclesNetwork) {
"payoutKey": {}, "payoutKey": {},
"votingKey": {} "votingKey": {}
}; };
var config;
web3.eth.getAccounts(function(error, accounts) { //get current account chosen in MetaMask or opened at Parity
console.log(accounts); web3.eth.getAccounts(function(err, accounts) {
if (err) {
$(".loading-container").hide();
swal("Error", err.message, "error");
return;
}
getConfig(err, function(config) {
getConfigCallBack(web3, accounts, config);
});
});
//gets config file with address of Oracles contract
function getConfig(err, cb) {
$.getJSON("./assets/javascripts/config.json", function(_config) { $.getJSON("./assets/javascripts/config.json", function(_config) {
config = _config; cb(_config);
});
}
if (accounts.length == 1) { //getting of config callback
var possibleInitialKey = accounts[0].substr(2); function getConfigCallBack(web3, accounts, config) {
checkInitialKey(web3, //checks if chosen account is valid initial key
if (accounts.length == 1) {
var possibleInitialKey = accounts[0].substr(2);
checkInitialKey(web3,
"checkInitialKey(address)",
possibleInitialKey,
config.Ethereum[config.environment].contractAddress,
function(_isNew) {
_isNew = !!+_isNew;
if (!_isNew) swal("Warning", "Current key isn't valid initial key. Please, choose your initial key in MetaMask and reload the page. Check Oracles network <a href='https://github.com/oraclesorg/oracles-wiki' target='blank'>wiki</a> for more info.", "warning");
});
} else if (accounts.length == 0) {
swal("Warning", "You haven't chosen any account in MetaMask. Please, choose your initial key in MetaMask and reload the page. Check Oracles network <a href='https://github.com/oraclesorg/oracles-wiki' target='blank'>wiki</a> for more info.", "warning");
}
$(".create-keys-button").click(function() {
$("#initialKeySource").click();
})
$("#initialKeySource").change(function() {
initialKeyChosen(this, config, function(address) {
checkInitialKeyCallBack(keys, function(_keys) {
addressesGeneratedCallBack(config, _keys, address, function(err, address) {
addressesAddedToContractCallBack(err, address, _keys);
})
});
});
});
}
//triggers, if initial key is chosen
function initialKeyChosen(el, config, cb) {
$(el).remove();
$("<input type='file' id='initialKeySource' />").change(initialKeyChosen).appendTo($(".create-keys"));
var file = $(el).prop('files')[0];
var reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function (evt) {
try {
a = JSON.parse(evt.target.result);
} catch(e) {
return swal("Error", "Invalid key file", "error");
}
var keyJSON = JSON.parse(evt.target.result);
var address = keyJSON.address;
if (!address) return swal("Error", "No address in key file", "error");
checkInitialKey(web3,
"checkInitialKey(address)", "checkInitialKey(address)",
possibleInitialKey, address,
config.Ethereum[config.environment].contractAddress, config.Ethereum[config.environment].contractAddress,
function(_isNew) { function(_isNew) {
_isNew = !!+_isNew; _isNew = !!+_isNew;
if (!_isNew) swal("Warning", "Current key isn't valid initial key. Please, choose your initial key in MetaMask and reload the page. Check Oracles network <a href='https://github.com/oraclesorg/oracles-wiki' target='blank'>wiki</a> for more info.", "warning");
});
} else if (accounts.length == 0) {
swal("Warning", "You haven't chosen any account in MetaMask. Please, choose your initial key in MetaMask and reload the page. Check Oracles network <a href='https://github.com/oraclesorg/oracles-wiki' target='blank'>wiki</a> for more info.", "warning");
}
$(".create-keys-button").click(function() { if (!_isNew) return swal("Error", "Initial key is already activated or isn't valid", "error");
$("#initialKeySource").click();
})
$("#initialKeySource").change(initialKeyChosen); $(".loading-container").show();
function initialKeyChosen() { setTimeout(function() {
$(this).remove(); cb(address);
$("<input type='file' id='initialKeySource' />").change(initialKeyChosen).appendTo($(".create-keys")); }, 500)
var file = $(this).prop('files')[0];
var reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function (evt) {
try {
a = JSON.parse(evt.target.result);
} catch(e) {
return swal("Error", "Invalid key file", "error");
}
var keyJSON = JSON.parse(evt.target.result);
var address = keyJSON.address;
if (!address) return swal("Error", "No address in key file", "error");
checkInitialKey(web3,
"checkInitialKey(address)",
address,
config.Ethereum[config.environment].contractAddress,
function(_isNew) {
_isNew = !!+_isNew;
if (!_isNew) return swal("Error", "Initial key is already activated or isn't valid", "error");
$(".loading-container").show();
setTimeout(function() {
if (!config) {
$.getJSON("./assets/javascripts/config.json", function(_config) {
config = _config;
configLoadedCallBack(web3, config, address);
});
} else configLoadedCallBack(web3, config, address);
}, 500)
}
);
}
reader.onerror = function (evt) {
swal("Error", "Error in reading file", "error");
}
}
function configLoadedCallBack(web3, config, address) {
var keysCount = 0;
for (var i in keys) {
keysCount++;
} }
var keysIterator = 0; );
}
reader.onerror = function (evt) {
swal("Error", "Error in reading file", "error");
}
}
generateAddress(function(_miningKeyObject, password) { //validating of initial key callback: async generates 3 addresses: mining, payout, voting
keysIterator++; function checkInitialKeyCallBack(keys, cb) {
keys.miningKey = {}; var keysCount = 0;
_miningKeyObject.name = "miningKey"; for (var i in keys) {
keys.miningKey.miningKeyObject = _miningKeyObject; keysCount++;
keys.miningKey.password = password; }
var keysIterator = 0;
if (keysIterator == keysCount) addressesGeneratedCallBack(keys, address); generateAddress(function(_miningKeyObject, password) {
}); keysIterator++;
generateAddress(function(_payoutKeyObject, password) { keys.miningKey = {};
keysIterator++; _miningKeyObject.name = "miningKey";
keys.payoutKey = {}; keys.miningKey.miningKeyObject = _miningKeyObject;
_payoutKeyObject.name = "payoutKey"; keys.miningKey.password = password;
keys.payoutKey.payoutKeyObject = _payoutKeyObject;
keys.payoutKey.password = password;
if (keysIterator == keysCount) addressesGeneratedCallBack(keys, address); if (keysIterator == keysCount) cb(keys);
}); });
generateAddress(function(_votingKeyObject, password) { generateAddress(function(_payoutKeyObject, password) {
keysIterator++; keysIterator++;
keys.votingKey = {}; keys.payoutKey = {};
_votingKeyObject.name = "votingKey"; _payoutKeyObject.name = "payoutKey";
keys.votingKey.votingKeyObject = _votingKeyObject; keys.payoutKey.payoutKeyObject = _payoutKeyObject;
keys.votingKey.password = password; keys.payoutKey.password = password;
if (keysIterator == keysCount) addressesGeneratedCallBack(keys, address); if (keysIterator == keysCount) cb(keys);
}); });
} generateAddress(function(_votingKeyObject, password) {
keysIterator++;
keys.votingKey = {};
_votingKeyObject.name = "votingKey";
keys.votingKey.votingKeyObject = _votingKeyObject;
keys.votingKey.password = password;
function addressesGeneratedCallBack(keys, address) { if (keysIterator == keysCount) cb(keys);
var validatorViewObj = { });
miningKey: "0x" + keys.miningKey.miningKeyObject.address, }
fullName: $("#full-name").val(),
streetName: $("#address").val(), //Geeneration of all 3 addresses callback
state: $("#state").val(), function addressesGeneratedCallBack(config, keys, address, cb) {
zip: $("#zip").val(), var validatorViewObj = {
licenseID: $("#license-id").val(), miningKey: "0x" + keys.miningKey.miningKeyObject.address,
licenseExpiredAt: new Date($("#license-expiration").val()).getTime() / 1000, fullName: $("#full-name").val(),
}; streetName: $("#address").val(),
addValidator(web3, state: $("#state").val(),
"addValidator(address,uint256,uint256,uint256,string,string,string)", zip: $("#zip").val(),
validatorViewObj, licenseID: $("#license-id").val(),
licenseExpiredAt: new Date($("#license-expiration").val()).getTime() / 1000,
};
//adds notary personal data to contract
addValidator(web3,
"addValidator(address,uint256,uint256,uint256,string,string,string)",
validatorViewObj,
address,
config.Ethereum[config.environment].contractAddress,
function(txHash, err) {
if (err) {
$(".loading-container").hide();
console.log(err.message);
if (err.type != "REQUEST_REJECTED") swal("Error", "Error in addresses addition to contract", "error");
return;
}
//activate generated production keys
createKeys(web3,
"createKeys(address,address,address)",
keys,
address, address,
config.Ethereum[config.environment].contractAddress, config.Ethereum[config.environment].contractAddress,
function(txHash, err) { function(res, err) {
if (err) { if (err) {
$(".loading-container").hide(); $(".loading-container").hide();
console.log(err.message); console.log(err.message);
@ -197,97 +237,118 @@ function startDapp(web3, isOraclesNetwork) {
return; return;
} }
createKeys(web3, cb(err, address);
"createKeys(address,address,address)",
keys,
address,
config.Ethereum[config.environment].contractAddress,
function(res, err) {
if (err) {
$(".loading-container").hide();
console.log(err.message);
if (err.type != "REQUEST_REJECTED") swal("Error", "Error in addresses addition to contract", "error");
return;
}
addressesAddedToContractCallBack(address, err);
}
);
} }
); );
} }
);
}
function addressesAddedToContractCallBack(address, error) { //Production keys addition to contract callback
if (error) { function addressesAddedToContractCallBack(err, address, keys) {
$(".loading-container").hide(); if (err) {
swal("Error", error.message, "error"); $(".loading-container").hide();
return; swal("Error", err.message, "error");
} return;
}
//send ether to payoutKey //chain:sends ether to payoutKey
web3.eth.getBalance(address, function(err, balance){ var to = "0x" + keys.payoutKey.payoutKeyObject.address;
if (err) { //gets balance of initial key
console.log(err); getBalance(address, function(balance) {
$(".loading-container").hide(); //gets gas price
return; getGasPrice(function(gasPrice) {
} //estimates gas
estimateGasForTx(address, to, balance, function(estimatedGas) {
var to = "0x" + keys.payoutKey.payoutKeyObject.address; //calculates how many coins we can send from initial key to payout key
web3.eth.getGasPrice(function(err, gasPriceObj) { calculateAmmountToSend(estimatedGas, gasPrice, balance, function(ammountToSend) {
if (err) { transferCoinsToPayoutKey(estimatedGas, gasPrice, address, to, ammountToSend);
console.log(err); });
$(".loading-container").hide(); });
return; });
} });
}
var gasPrice = gasPriceObj.c[0]; function getBalance(address, cb) {
web3.eth.getBalance(address, function(err, balance) {
if (err) {
console.log(err);
$(".loading-container").hide();
return;
}
estimateGas(web3, address, to, null, parseInt(balance/2), function(estimatedGas, err) { cb(balance);
if (err) { });
console.log(err); }
$(".loading-container").hide();
return;
}
var ammountToSend = balance - 20 * estimatedGas * gasPrice; function getGasPrice(cb) {
console.log("ammountToSend: " + ammountToSend); web3.eth.getGasPrice(function(err, gasPriceObj) {
web3.eth.sendTransaction({gas: estimatedGas, from: address, to: to, value: ammountToSend}, function(err, txHash) { if (err) {
if (err) { console.log(err);
console.log(err); $(".loading-container").hide();
$(".loading-container").hide(); return;
return; }
} var gasPrice = gasPriceObj.c[0];
$(".loading-container").hide();
swal("Sucess", "Keys are created", "success");
$('.content').empty();
$('.content').load("./keys.html", function() {
$("#miningKey").text("0x" + keys.miningKey.miningKeyObject.address);
$("#payoutKey").text("0x" + keys.payoutKey.payoutKeyObject.address);
$("#votingKey").text("0x" + keys.votingKey.votingKeyObject.address);
$("#miningKeyPass").text(keys.miningKey.password); cb(gasPrice);
$("#payoutKeyPass").text(keys.payoutKey.password); });
$("#votingKeyPass").text(keys.votingKey.password); }
$("#miningKeyDownload").click(function() { function estimateGasForTx(address, to, balance, cb) {
download("key_" + keys.miningKey.miningKeyObject.address, JSON.stringify(keys.miningKey.miningKeyObject)); estimateGas(web3, address, to, null, parseInt(balance/2), function(estimatedGas, err) {
}); if (err) {
console.log(err);
$(".loading-container").hide();
return;
}
$("#payoutKeyDownload").click(function() { cb(estimatedGas);
download("key_" + keys.payoutKey.payoutKeyObject.address, JSON.stringify(keys.payoutKey.payoutKeyObject)); });
}); }
$("#votingKeyDownload").click(function() { function calculateAmmountToSend(estimatedGas, gasPrice, balance, cb) {
download("key_" + keys.votingKey.votingKeyObject.address, JSON.stringify(keys.votingKey.votingKeyObject)); var ammountToSend = balance - 20 * estimatedGas * gasPrice;
}); console.log("ammountToSend: " + ammountToSend);
}); cb(ammountToSend);
}); }
});
}); function transferCoinsToPayoutKey(estimatedGas, gasPrice, address, to, ammountToSend) {
}); web3.eth.sendTransaction({
} "gas": estimatedGas,
}); "from": address,
}); "to": to,
"value": ammountToSend}, function(err, txHash) {
if (err) {
console.log(err);
$(".loading-container").hide();
return;
}
$(".loading-container").hide();
swal("Sucess", "Keys are created", "success");
$('.content').empty();
$('.content').load("./keys.html", function() {
$("#miningKey").text("0x" + keys.miningKey.miningKeyObject.address);
$("#payoutKey").text("0x" + keys.payoutKey.payoutKeyObject.address);
$("#votingKey").text("0x" + keys.votingKey.votingKeyObject.address);
$("#miningKeyPass").text(keys.miningKey.password);
$("#payoutKeyPass").text(keys.payoutKey.password);
$("#votingKeyPass").text(keys.votingKey.password);
$("#miningKeyDownload").click(function() {
download("key_" + keys.miningKey.miningKeyObject.address, JSON.stringify(keys.miningKey.miningKeyObject));
});
$("#payoutKeyDownload").click(function() {
download("key_" + keys.payoutKey.payoutKeyObject.address, JSON.stringify(keys.payoutKey.payoutKeyObject));
});
$("#votingKeyDownload").click(function() {
download("key_" + keys.votingKey.votingKeyObject.address, JSON.stringify(keys.votingKey.votingKeyObject));
});
});
});
}
}); });
} }

View File

@ -77,7 +77,7 @@
</div> </div>
</footer> </footer>
<script src="./assets/javascripts/sweetalert2.min.js" type="text/javascript"></script> <script src="./assets/javascripts/sweetalert2.min.js" type="text/javascript"></script>
<script src="./assets/javascripts/application.js?v=1.22" type="text/javascript"></script> <script src="./assets/javascripts/application.js?v=1.23" type="text/javascript"></script>
<script src="./assets/javascripts/keythereum.min.js" type="text/javascript"></script> <script src="./assets/javascripts/keythereum.min.js" type="text/javascript"></script>
</body> </body>
</html> </html>