Skip to content

Instantly share code, notes, and snippets.

/nvo loader.js
Created Jun 17, 2017

Embed
What would you like to do?
//Setup base variables
var Prices ={}, Wallets = {}, Value;
var Dialogs = require('dialogs');
var dialogs = Dialogs(opts={})
// Setting up the wallets
Wallets.Bitcoin = JSON.parse(localStorage.getItem('btcWallet'));
Wallets.Ripple = JSON.parse(localStorage.getItem('xrpWallet'));
Wallets.Ethereum = JSON.parse(localStorage.getItem('ethWallet'));
// Get UUID
var userInfo = JSON.parse(localStorage.getItem('userInfo'));
if(!(userInfo)){
// Create Unique User ID
var uuid = guid();
var userInfo = {id: uuid, open: new Boolean};
localStorage.setItem('userInfo', JSON.stringify(userInfo));
}
// Ripple
var {RippleAPI} = require('ripple-lib');
var api = new RippleAPI({
server: 'wss://s1.ripple.com'// Public rippled server
//server: 'wss://54.213.214.68:51233 ' // Public rippled server
});
//Check for Wallets
if (Wallets.Bitcoin == null){
bitcoinAddr();
}
if(Wallets.Ripple == null){
rippleAddr();
}
if(Wallets.Ethereum == null){
ethAddr();
}
function getPrices(){
require('dns').resolve('www.cryptocompare.com', function(err) {
if(!(err)){
$.get("https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH,XRP&tsyms=USD", function(data){
Prices.BTC = data.BTC.USD;
Prices.ETH = data.ETH.USD;
Prices.XRP = data.XRP.USD;
});
}else if(err){
Prices.BTC = 0;
Prices.ETH = 0;
Prices.XRP = 0;
}else{
dialogs.alert('Fatal Error 001');
}
});
}
function getBalance(){
require('dns').resolve('www.cryptocompare.com', function(err) {
if (!(err)){
/*--------------------------- Check Bitcoin wallet ------------------------------*/
if (Wallets.Bitcoin.Address) {
$.ajax({
url: 'https://blockchain.info/rawaddr/'+ Wallets.Bitcoin.Address,
success: function(data) {
Wallets.Bitcoin.Balance = data.final_balance;
localStorage.setItem('btcWallet', JSON.stringify(Wallets.Bitcoin));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.status == 0) {
dialogs.alert('Check Your Network.');
} else if (XMLHttpRequest.status == 404) {
dialogs.alert('Requested URL not found.');
} else if (XMLHttpRequest.status == 500) {
dialogs.alert('Internel Server Error.');
} else {
dialogs.alert('Unknow Error.\n' + XMLHttpRequest.responseText);
}
}
});
}else {dialogs.alert('Error at Bitcoin balance check, please contact support.');}
/*--------------------------- Check Ripple wallet ------------------------------*/
api.connect().then(() => {
var myAddress = Wallets.Ripple.Address;
console.log('getting account info for', myAddress);
return api.getAccountInfo(myAddress);
}).then(info => {
if (parseFloat(info.xrpBalance) !== Wallets.Ripple.Balance){
Wallets.Ripple.Balance = parseFloat(info.xrpBalance);
localStorage.setItem('xrpWallet', JSON.stringify(Wallets.Ripple));
}else if(parseFloat(info.xrpBalance) == Wallets.Ripple.Balance){
console.log('Balance is 0');
}else{
dialogs.alert('Error at Ripple Balance parsing.');
}
}).then(() => {
console.log('done and disconnected.');
}).catch(function(err){
//To be checked
});
/*--------------------------- Check Ethereum wallet ------------------------------*/
if(Wallets.Ethereum.Address){
$.ajax({
url: 'https://mainnet.infura.io/',
data:'{"jsonrpc": "2.0", "id": 1, "method": "eth_getBalance", "params": ["0x'+ Wallets.Ethereum.Address +'", "latest"]}',
type: 'POST',
datatype: 'Application/json',
success: function(data) {
Wallets.Ethereum.Balance = parseInt(data.result);
localStorage.setItem('ethWallet', JSON.stringify(Wallets.Ethereum));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.status == 0) {
dialogs.alert('Check Your Network.');
} else if (XMLHttpRequest.status == 404) {
dialogs.alert('Requested URL not found.');
} else if (XMLHttpRequest.status == 500) {
dialogs.alert('Internel Server Error.');
} else {
dialogs.alert('Unknow Error.\n' + XMLHttpRequest.responseText);
}
}
});
}
}else if(err){
if(!(Wallets.Bitcoin.Balance)){
Wallets.Bitcoin.Balance = 0;
localStorage.setItem('btcWallet', JSON.stringify(Wallets.Bitcoin));
}
if(!(Wallets.Ethereum.Balance)){
Wallets.Ethereum.Balance = 0;
}
if(!(Wallets.Ripple.Balance)){
Wallets.Ripple.Balance = 0;
}
}else{
dialogs.alert('Fatal Error 002');
}
});
}
function getValue(){
//var balanceTables = $('#wallet-balance');
//var btcPrice = balanceTables.find('#wallet-value');
getPrices();
// Security Check
Wallets.Bitcoin = JSON.parse(localStorage.getItem('btcWallet'));
Wallets.Ripple = JSON.parse(localStorage.getItem('xrpWallet'));
Wallets.Ethereum = JSON.parse(localStorage.getItem('ethWallet'));
var interVal = setInterval(function(){
if(!(Prices)){
getPrices();
}else if(Prices){
//Calculate
var btcValue = Prices.BTC * (Wallets.Bitcoin.Balance/100000000);
var xrpValue = Prices.XRP * Wallets.Ripple.Balance;
var ethValue = Prices.ETH * Wallets.Ethereum.Balance;
Wallets.Ethereum.Value = ethValue;
Wallets.Bitcoin.Value = btcValue;
Wallets.Ripple.Value = xrpValue;
//Save
localStorage.setItem('btcWallet', JSON.stringify(Wallets.Bitcoin));
localStorage.setItem('xrpWallet', JSON.stringify(Wallets.Ripple));
localStorage.setItem('ethWallet', JSON.stringify(Wallets.Ethereum));
var Value = btcValue + xrpValue + ethValue;
if(!Value){
if (Value == 0){
Value = 1;
localStorage.setItem('Value', JSON.stringify(Value));
}else{
localStorage.setItem('Value', JSON.stringify(Value));
}
clearInterval(interVal);
}
}
}, 200);
}
// Generate a Bitcoin Address
function bitcoinAddr(){
// Get Library
var bitcoin = require('bitcoinjs-lib');
// Get Private Key bkp
var bkp = bitcoin.ECPair.makeRandom();
// Get Address from bkp
var addressbtc = bkp.getAddress();
// Get PrivateKey in exportable format
var bpk = bkp.toWIF();
// Store in an object
var BTC = {Address: addressbtc, PrivKey: bpk, Balance: 0, Value: 0};
// Store it Locally
localStorage.setItem('btcWallet', JSON.stringify(BTC));
Wallets.Bitcoin = JSON.parse(localStorage.getItem('btcWallet'));
}
// Generate a Ripple Address
function rippleAddr(){
require('dns').resolve('8.8.8.8', function(err) {
if(!(err)){
// OnLine generation
api.connect().then(() => {
return api.generateAddress();
}).then(info => {
//Storing the result in an object, just to respect the nominations for later automation and prototyping
ripp = {Address: info.address, Secret: info.secret, Balance: 0, Value: 0};
localStorage.setItem('xrpWallet', JSON.stringify(ripp));
}).then(() => {
return api.disconnect();
}).then(() => {
Wallets.Ripple = JSON.parse(localStorage.getItem('xrpWallet'));
}).catch(console.error);
}else if(err){
// Offline generation
generate = api.generateAddress();
ripp = {Address: generate.address, Secret: generate.secret, Balance: 0, Value: 0};
localStorage.setItem('xrpWallet', JSON.stringify(ripp));
Wallets.Ripple = JSON.parse(localStorage.getItem('xrpWallet'));
}else{
dialogs.alert('Fatal Error 000');
}
});
}
//Generate an Ethereum Keystore
function ethAddr(){
var lightwallet = require('eth-lightwallet');
var keyStore = lightwallet.keystore;
var seedPhrase = getSeed();
//Get user UUID
var userInfo = JSON.parse(localStorage.getItem('userInfo'));
console.log(userInfo);
// Iniciate the Ethereum Wallet
var Ethereum = {seed: seedPhrase};
keyStore.createVault({
//Set the Vault's password as the user's UUID
password: userInfo.id,
seedPhrase: seedPhrase
}, function (err, ks) {
// Save the KeyStore for later Usage
Ethereum.keystore = ks;
ks.keyFromPassword(userInfo.id, function (err, pwDerivedKey) {
if (err) throw err;
//Generate the first Address
ks.generateNewAddress(pwDerivedKey, 1);
// Get the Address
Ethereum.Address = ks.getAddresses();
//Get the Private Key
Ethereum.PrivKey = ks.exportPrivateKey(Ethereum.Address[0], pwDerivedKey);
// Set the balance
Ethereum.Balance = 0;
// When it is done, Export the wallet
localStorage.setItem('ethWallet', JSON.stringify(Ethereum));
});
});
Wallets.Ethereum = JSON.parse(localStorage.getItem('ethWallet'));
}
//Random seed generation
function getSeed(){
var lightwallet = require('eth-lightwallet');
var keyStore = lightwallet.keystore;
seed = keyStore.generateRandomSeed();
if (keyStore.isSeedValid(seed)){return seed;}
else if (!(keyStore.isSeedValid(seed))) {getSeed();}
else {dialogs.alert('Error at Ethereum seed generation. Please contact support.');}
}
// A way to check for connectivity
function check(){
require('dns').resolve('www.cryptocompare.com', function(err) {
if (err) {
if($("#isConnected").attr('class') === "isOffline"){}
else if($("#isConnected").attr('class') !== "isOffline"){
$("#isConnected").remove();
$('body').append('<div id="isConnected" class="isOffline"</div>');
}
}else {
if($("#isConnected").attr('class') === "isOnline"){}
else if($("#isConnected").attr('class') !== "isOnline"){
$("#isConnected").remove();
$('body').append('<div id="isConnected" class="isOnline"</div>');
}
}
});
}
// UUID functions
function guid() {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
// Check transactions
function getTxs(){
// Bitcoin
if (Wallets.Bitcoin.Address) {
$.ajax({
//url: 'https://blockchain.info/rawaddr/Enter a Bitcoin Address', // For Test
url:'https://blockchain.info/rawaddr/'+ Wallets.Bitcoin.Address,
success: function(data) {
Wallets.Bitcoin.TXS = data.txs;
localStorage.setItem('btcWallet', JSON.stringify(Wallets.Bitcoin));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.status == 0) {
dialogs.alert('Check Your Network.');
} else if (XMLHttpRequest.status == 404) {
dialogs.alert('Requested URL not found.');
} else if (XMLHttpRequest.status == 500) {
dialogs.alert('Internel Server Error.');
} else {
dialogs.alert('Unknow Error.\n' + XMLHttpRequest.responseText);
}
}
});
}else {dialogs.alert('Error at Bitcoin TXs check, please contact support.');}
// Ripple
if (Wallets.Ripple.Address){
//$.get('https://data.ripple.com/v2/accounts/rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn/transactions?type=Payment', function(data){Wallets.Ripple.TXS = data;}); // For Test
$.get('https://data.ripple.com/v2/accounts/'+ Wallets.Ripple.Address +'/transactions?type=Payment', function(data){Wallets.Ripple.TXS = data;});
}else {dialogs.alert('Error at Ripple TXs check, please contact support.');}
// Ethereum
if (Wallets.Ethereum.Address) {
/*$.get('http://api.etherscan.io/api?module=account&action=txlist&address=0xa15E770eB92D585Ce6ef5B0cC00b19cc0Def694b&startblock=0&endblock=99999999&sort=desc', function(data){
Wallets.Ethereum.TXS = data.result;
}); // For test*/
$.get('http://api.etherscan.io/api?module=account&action=txlist&address=0x'+ Wallets.Ethereum.Address +'&startblock=0&endblock=99999999&sort=asc', function(data){
Wallets.Ethereum.TXS = data;
});
}else {dialogs.alert('Error at Ethereum TXs check, please contact support.');}
}
function logTXS(coin){
if($(".table-data").children().length != 0){$(".table-data").html('');}
if($(".table-data").children().length == 0){
if(coin == "Bitcoin"){
leftPanelPrice(coin);
if (Wallets.Bitcoin.TXS.length == 0){
$(".table-data").append('<div style="text-align: center;color:white;"><p>No Transaction history.</p></div>');
}
else if(Wallets.Bitcoin.TXS.length > 0){
for(i = 0; i < Wallets.Bitcoin.TXS.length; i++){
txs = Wallets.Bitcoin.TXS[i];
cTX = {fees: 0};
txIn = {value:0}; txOut = {fees:0, value:0};
address = Wallets.Bitcoin.Address;
//address = "Enter a Bitcoin Address"; // For Test
if (txs.out.length > 0){
for(v = 0; v < txs.out.length; v++){
txout = txs.out[v];
if(txout.addr == address){
txOut.value = (txout.value/100000000);
cTX.type = "Received";
}
}
}else if(txs.out.length == 0){
if(txout.addr == address){
txOut.value = (txout.value/100000000);
cTX.type = "Received";
}
}
if (txs.inputs.length > 0){
for(v = 0; v < txs.inputs.length; v++){
txin = txs.inputs[v];
if(txin.prev_out.addr == address){
txIn.value = (txin.prev_out.value/100000000);
cTX.type = "Sent";
}
}
}else if(txs.inputs.length == 0){
txIn.value = (txin.prev_out.value/100000000);
if(txin.prev_out.addr == address){
cTX.type = "Sent";
}
}
cTX.fees = (txIn.value - txOut.value);
if (cTX.type == "Sent"){
cTX.value = (txin.prev_out.value - cTX.fees)/100000000;
}
if(cTX.type == "Received"){
cTX.value = (txout.value - cTX.fees)/100000000;
}
//console.log(txin.prev_out.value, txout.value, cTX.fees.toFixed(8));
date = new Date(txs.time *1000);
cTX.date = date.toLocaleString();
//Base
$(".table-data").append("<div id='tx"+i+"' class='row-append'></div>");
//First row and Open
$("#tx"+i).append('<div id="1Row'+i+'" class="row-tr row-td clearfix first-row"></div>');
$("#tx"+i).append('<div id="2Row'+i+'" class ="row-tr row-td open-wrapper"></div>');
//Open
open = $("#2Row"+i);
open.append('<div id="openBox'+i+'" class="open-boxs"></div>');
//OpenBox
openBox = $('#openBox'+i);
openBox.append('<div id="fEl'+i+'" class="el-row"></div>');
openBox.append('<div id="sEl'+i+'" class="el-row"></div>');
//First El
fEl = $('#fEl'+i);
fEl.append('<div id="fElfCol'+i+'" class="el-col el-col-8"></div>');
fEl.append('<div id="fElsCol'+i+'" class="el-col el-col-8"></div>');
fEl.append('<div id="fEltCol'+i+'" class="el-col el-col-8"></div>');
//First El First Col
fElfCol = $("#fElfCol"+i);
fElfCol.append('<div id="fElfColGrid'+i+'" class="grid-content"></div>');
//First El First Col Grid
fElfColGrid = $("#fElfColGrid"+i);
fElfColGrid.append('<span id="fElfColGridfSpan'+i+'" class="title-label">Date</span>');
fElfColGrid.append('<span id="fElfColGridsSpan'+i+'" class="color-white value">'+ cTX.date +'</span>');
//First El Second Col
fElsCol = $("#fElsCol"+i);
fElsCol.append('<div id="fElsColGrid'+i+'" class="grid-content"></div>');
//First El Second Col Grid
fElsColGrid = $("#fElsColGrid"+i);
fElsColGrid.append('<span class="title-label">TXID</span>');
fElsColGrid.append('<span href="https://www.blockchain.info/tx/'+ txs.hash +'"class="txid" style="color:#0062ff;">'+ txs.hash.slice(0,10) +'...</span>');
//First El Third Col
fEltCol = $("#fEltCol"+i);
fEltCol.append('<div id="fEltColGrid'+i+'" class="grid-content"></div>');
//First El Third Col Grid
fEltColGrid = $("#fEltColGrid"+i);
fEltColGrid.append('<span class="title-label">Fees</span>');
if(cTX.type == "Sent"){
fEltColGrid.append('<span class="color-white value">'+ cTX.fees.toFixed(8) +' BTC</span>');
}
if(cTX.type == "Received"){
fEltColGrid.append('<span class="color-white value"> --- BTC</span>');
}
// Second El
sEl = $('#sEl'+i);
sEl.append('<div id="sElfCol'+i+'" class="el-col el-col-8"></div>');
// Second El Firs Col
sElfCol = $("#sElfCol"+i);
sElfCol.append('<div id="sElfColGrid'+i+'" class="grid-content"></div>');
//Second El First Col Grid
sElfColGrid = $("#sElfColGrid"+i);
if(cTX.type == "Sent"){
sElfColGrid.append('<span class="title-label">To</span>');
sElfColGrid.append('<span href="https://www.blockchain.info/tx/'+ txout.addr +'" class="color-white value" style="color:#0062ff;">'+ txout.addr +'</span>');
}
if(cTX.type == "Received"){
sElfColGrid.append('<span class="title-label">From</span>');
sElfColGrid.append('<span href="https://www.blockchain.info/tx/'+ txin.prev_out.addr +'" class="color-white value" style="color:#0062ff;">'+ txin.prev_out.addr +'</span>');
}
//
// Step
//
// First Row
firstRow = $("#1Row"+i);
firstRow.append('<div id="1td'+i+'" class="col-td width67"></div>');
firstRow.append('<div id="2td'+i+'" class="col-td width33 text-right"></div>');
// TD 1
td1 = $("#1td"+i);
td1.append('<div id="td1spacing'+i+'" class="spacing"></div>');
// TD 1 Spacing
td1Spacing = $("#td1spacing"+i);
if(cTX.type == "Received"){
td1Spacing.append('<span id="1tdDate'+i+'" class="date"></span>');
td1SpacingDate = $("#1tdDate"+i);
td1SpacingDate.append(toWD(date)+'<span class="number">'+ date.getDate() +'</span>');
td1Spacing.append('<img id="1tdimg'+i+'" src="i/coins.svg" alt="img" class="img-title"></img>');
td1Spacing.append('<span id="1tdtitles'+i+'" class="titles">'+ cTX.type +'</span>');
}
if(cTX.type == "Sent"){
td1Spacing.append('<span id="1tdDate'+i+'" class="date"></span>');
td1SpacingDate = $("#1tdDate"+i);
td1SpacingDate.append(toWD(date)+'<span class="number">'+ date.getDate() +'</span>');
td1Spacing.append('<img id="1tdimg'+i+'" src="i/send.svg" alt="img" class="img-title"></img>');
td1Spacing.append('<span id="1tdtitles'+i+'" class="titles">'+ cTX.type +'</span>');
}
// TD 2
td2 = $("#2td"+i);
td2.append('<div id="td2spacing'+i+'" class="spacing"></div>');
// TD 2 Spacing
td2Spacing = $("#td2spacing"+i);
if(cTX.type == "Received"){
td2Spacing.append('<span class="add-number" style="color:green;">+'+ txOut.value.toFixed(8) +' BTC</span>');
}else if(cTX.type == "Sent"){
td2Spacing.append('<span class="add-number" style="color:red;">-'+ txIn.value.toFixed(8) +' BTC</span>');
}
}
}
}else if(coin == "Ethereum"){
leftPanelPrice(coin);
if (Wallets.Ethereum.TXS.result.length == 0){
$(".table-data").append('<div style="text-align: center;color:white;"><p>No Transaction history.</p></div>');
}
else if(!(Wallets.Ethereum.TXS.result) && !(Wallets.Ethereum.TXS)){
$(".table-data").append('<div style="text-align: center;color:white;"><p>No Transaction history.</p></div>');
}
else if(Wallets.Ethereum.TXS.length > 0){
for(i = 0; i < 10; i++){
txs = Wallets.Ethereum.TXS[i];
address = Wallets.Ethereum.Address;
//address = '0xa15E770eB92D585Ce6ef5B0cC00b19cc0Def694b'; // For Test
address = address.toLowerCase();
cTX = {Fees:0, Type:'', Value:0};
cTX.Fees = (txs.gasPrice / 10e+17) * (txs.gasUsed);
if(txs.from === address){
cTX.Type = 'Sent';
}else if(txs.to === address){
cTX.Type = 'Received';
}
cTX.Value = txs.value / 10e+17;localStorage.setItem('btcWallet', JSON.stringify(Wallets.Bitcoin));
localStorage.setItem('xrpWallet', JSON.stringify(Wallets.Ripple));
localStorage.setItem('ethWallet', JSON.stringify(Wallets.Ethereum));
cTX.Date = new Date(txs.timeStamp * 1000);
//Base
$(".table-data").append("<div id='tx"+i+"' class='row-append'></div>");
//First row and Open
$("#tx"+i).append('<div id="1Row'+i+'" class="row-tr row-td clearfix first-row"></div>');
$("#tx"+i).append('<div id="2Row'+i+'" class ="row-tr row-td open-wrapper"></div>');
//Open
open = $("#2Row"+i);
open.append('<div id="openBox'+i+'" class="open-boxs"></div>');
//OpenBox
openBox = $('#openBox'+i);
openBox.append('<div id="fEl'+i+'" class="el-row"></div>');
openBox.append('<div id="sEl'+i+'" class="el-row"></div>');
//First El
fEl = $('#fEl'+i);
fEl.append('<div id="fElfCol'+i+'" class="el-col el-col-8"></div>');
fEl.append('<div id="fElsCol'+i+'" class="el-col el-col-8"></div>');
fEl.append('<div id="fEltCol'+i+'" class="el-col el-col-8"></div>');
//First El First Col
fElfCol = $("#fElfCol"+i);
fElfCol.append('<div id="fElfColGrid'+i+'" class="grid-content"></div>');
//First El First Col Grid
fElfColGrid = $("#fElfColGrid"+i);
fElfColGrid.append('<span id="fElfColGridfSpan'+i+'" class="title-label">Date</span>');
fElfColGrid.append('<span id="fElfColGridsSpan'+i+'" class="color-white value">'+ cTX.Date.toLocaleDateString() +'</span>');
//First El Second Col
fElsCol = $("#fElsCol"+i);
fElsCol.append('<div id="fElsColGrid'+i+'" class="grid-content"></div>');
//First El Second Col Grid
fElsColGrid = $("#fElsColGrid"+i);
fElsColGrid.append('<span class="title-label">TXID</span>');
fElsColGrid.append('<span href="https://etherscan.io/tx/'+ txs.hash +'"class="txid" style="color:#0062ff;">'+ txs.hash.slice(0,10) +'...</span>');
//First El Third Col
fEltCol = $("#fEltCol"+i);
fEltCol.append('<div id="fEltColGrid'+i+'" class="grid-content"></div>');
//First El Third Col Grid
fEltColGrid = $("#fEltColGrid"+i);
fEltColGrid.append('<span class="title-label">Fees</span>');
if(cTX.Type == "Sent"){
fEltColGrid.append('<span class="color-white value">'+ cTX.Fees.toString() +' ETH</span>');
}
if(cTX.Type == "Received"){
fEltColGrid.append('<span class="color-white value"> --- ETH</span>');
}
// Second El
sEl = $('#sEl'+i);
sEl.append('<div id="sElfCol'+i+'" class="el-col el-col-8"></div>');
// Second El Firs Col
sElfCol = $("#sElfCol"+i);
sElfCol.append('<div id="sElfColGrid'+i+'" class="grid-content"></div>');
//Second El First Col Grid
sElfColGrid = $("#sElfColGrid"+i);
if(cTX.Type == "Sent"){
sElfColGrid.append('<span class="title-label">To</span>');
sElfColGrid.append('<span href="https://etherscan.io/address/'+ txs.to +'" class="color-white value" style="color:#0062ff;">'+ txs.to +'</span>');
}
if(cTX.Type == "Received"){
sElfColGrid.append('<span class="title-label">From</span>');
sElfColGrid.append('<span href="https://etherscan.io/address/'+ txs.from +'" class="color-white value" style="color:#0062ff;">'+ txs.from +'</span>');
}
//
// Step
//
// First Row
firstRow = $("#1Row"+i);
firstRow.append('<div id="1td'+i+'" class="col-td width67"></div>');
firstRow.append('<div id="2td'+i+'" class="col-td width33 text-right"></div>');
// TD 1
td1 = $("#1td"+i);
td1.append('<div id="td1spacing'+i+'" class="spacing"></div>');
// TD 1 Spacing
td1Spacing = $("#td1spacing"+i);
if(cTX.Type == "Received"){
td1Spacing.append('<span id="1tdDate'+i+'" class="date"></span>');
td1SpacingDate = $("#1tdDate"+i);
td1SpacingDate.append(toWD(cTX.Date)+'<span class="number">'+ cTX.Date.getDate() +'</span>');
td1Spacing.append('<img id="1tdimg'+i+'" src="i/coins.svg" alt="img" class="img-title"></img>');
td1Spacing.append('<span id="1tdtitles'+i+'" class="titles">'+ cTX.Type +'</span>');
}
if(cTX.Type == "Sent"){
td1Spacing.append('<span id="1tdDate'+i+'" class="date"></span>');
td1SpacingDate = $("#1tdDate"+i);
td1SpacingDate.append(toWD(cTX.Date)+'<span class="number">'+ cTX.Date.getDate() +'</span>');
td1Spacing.append('<img id="1tdimg'+i+'" src="i/send.svg" alt="img" class="img-title"></img>');
td1Spacing.append('<span id="1tdtitles'+i+'" class="titles">'+ cTX.Type +'</span>');
}
// TD 2
td2 = $("#2td"+i);
td2.append('<div id="td2spacing'+i+'" class="spacing"></div>');
// TD 2 Spacing
td2Spacing = $("#td2spacing"+i);
if(cTX.Type == "Received"){
td2Spacing.append('<span class="add-number" style="color:green;">+'+ cTX.Value.toFixed(8) +' ETH</span>');
}else if(cTX.Type == "Sent"){
td2Spacing.append('<span class="add-number" style="color:red;">-'+ cTX.Value.toFixed(8) +' ETH</span>');
}
}
}
}else if (coin == 'Ripple'){
leftPanelPrice(coin);
if (Wallets.Ripple.TXS.transactions.length == 0){
$(".table-data").append('<div style="text-align: center;color:white;"><p>No Transaction history.</p></div>');
}
else if(Wallets.Ripple.TXS.transactions.length > 0){
for(i = 0; i < Wallets.Ripple.TXS.transactions.length; i++){
txs = Wallets.Ripple.TXS.transactions[i];
if (txs.tx.TransactionType === "Payment" && typeof(txs.tx.Amount) === "string"){
cTX = txs.tx;
address = Wallets.Ripple.Address;
//address = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"; // For Test
date = new Date(txs.date);
//Base
$(".table-data").append("<div id='tx"+i+"' class='row-append'></div>");
//First row and Open
$("#tx"+i).append('<div id="1Row'+i+'" class="row-tr row-td clearfix first-row"></div>');
$("#tx"+i).append('<div id="2Row'+i+'" class ="row-tr row-td open-wrapper"></div>');
//Open
open = $("#2Row"+i);
open.append('<div id="openBox'+i+'" class="open-boxs"></div>');
//OpenBox
openBox = $('#openBox'+i);
openBox.append('<div id="fEl'+i+'" class="el-row"></div>');
openBox.append('<div id="sEl'+i+'" class="el-row"></div>');
//First El
fEl = $('#fEl'+i);
fEl.append('<div id="fElfCol'+i+'" class="el-col el-col-8"></div>');
fEl.append('<div id="fElsCol'+i+'" class="el-col el-col-8"></div>');
fEl.append('<div id="fEltCol'+i+'" class="el-col el-col-8"></div>');
//First El First Col
fElfCol = $("#fElfCol"+i);
fElfCol.append('<div id="fElfColGrid'+i+'" class="grid-content"></div>');
//First El First Col Grid
fElfColGrid = $("#fElfColGrid"+i);
fElfColGrid.append('<span id="fElfColGridfSpan'+i+'" class="title-label">Date</span>');
fElfColGrid.append('<span id="fElfColGridsSpan'+i+'" class="color-white value">'+ date.toLocaleString() +'</span>');
//First El Second Col
fElsCol = $("#fElsCol"+i);
fElsCol.append('<div id="fElsColGrid'+i+'" class="grid-content"></div>');
//First El Second Col Grid
fElsColGrid = $("#fElsColGrid"+i);
fElsColGrid.append('<span class="title-label">TXID</span>');
fElsColGrid.append('<span href="https://charts.ripple.com/#/transactions/'+ txs.hash +'"class="txid" style="color:#0062ff;">'+ txs.hash.slice(0,10) +'...</span>');
//First El Third Col
fEltCol = $("#fEltCol"+i);
fEltCol.append('<div id="fEltColGrid'+i+'" class="grid-content"></div>');
//First El Third Col Grid
fEltColGrid = $("#fEltColGrid"+i);
fEltColGrid.append('<span class="title-label">Fees</span>');
if(cTX.Account == address){
fEltColGrid.append('<span class="color-white value">'+ cTX.Fee * 1000000 +' XRP</span>');
}
if(cTX.Destination == address){
fEltColGrid.append('<span class="color-white value"> --- XRP</span>');
}
// Second El
sEl = $('#sEl'+i);
sEl.append('<div id="sElfCol'+i+'" class="el-col el-col-8"></div>');
// Second El Firs Col
sElfCol = $("#sElfCol"+i);
sElfCol.append('<div id="sElfColGrid'+i+'" class="grid-content"></div>');
//Second El First Col Grid
sElfColGrid = $("#sElfColGrid"+i);
if(cTX.Account == address){
sElfColGrid.append('<span class="title-label">To</span>');
sElfColGrid.append('<span class="color-white value" style="color:#0062ff;">'+ cTX.Destination +'</span>');
}
if(cTX.Destination == address){
sElfColGrid.append('<span class="title-label">From</span>');
sElfColGrid.append('<span class="color-white value" style="color:#0062ff;">'+ cTX.Account +'</span>');
}
//
// Step
//
// First Row
firstRow = $("#1Row"+i);
firstRow.append('<div id="1td'+i+'" class="col-td width67"></div>');
firstRow.append('<div id="2td'+i+'" class="col-td width33 text-right"></div>');
// TD 1
td1 = $("#1td"+i);
td1.append('<div id="td1spacing'+i+'" class="spacing"></div>');
// TD 1 Spacing
td1Spacing = $("#td1spacing"+i);
if(cTX.Destination == address){
td1Spacing.append('<span id="1tdDate'+i+'" class="date"></span>');
td1SpacingDate = $("#1tdDate"+i);
td1SpacingDate.append(toWD(date)+'<span class="number">'+ date.getDate() +'</span>');
td1Spacing.append('<img id="1tdimg'+i+'" src="i/coins.svg" alt="img" class="img-title"></img>');
td1Spacing.append('<span id="1tdtitles'+i+'" class="titles">Received</span>');
}
if(cTX.Account == address){
td1Spacing.append('<span id="1tdDate'+i+'" class="date"></span>');
td1SpacingDate = $("#1tdDate"+i);
td1SpacingDate.append(toWD(date)+'<span class="number">'+ date.getDate() +'</span>');
td1Spacing.append('<img id="1tdimg'+i+'" src="i/send.svg" alt="img" class="img-title"></img>');
td1Spacing.append('<span id="1tdtitles'+i+'" class="titles">Sent</span>');
}
// TD 2
td2 = $("#2td"+i);
td2.append('<div id="td2spacing'+i+'" class="spacing"></div>');
// TD 2 Spacing
td2Spacing = $("#td2spacing"+i);
if(cTX.Destination == address){
td2Spacing.append('<span class="add-number" style="color:green;">+'+ cTX.Amount +' XRP</span>');
}
if(cTX.Account == address){
td2Spacing.append('<span class="add-number" style="color:red;">-'+ cTX.Amount +' XRP</span>');
}
}
}
}
}
$('.row-append .first-row').click(function(){
$(this).parent().toggleClass('open');
});
}
var shell = require('electron').shell;
//$("#tx0").toggleClass('open');
$('.txid').click(function(event){
event.preventDefault();
targ = event.target.attributes[0];
shell.openExternal(targ.value);
});
}
function toWD(date){
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
return weekday[date.getDay()];
}
/*--------------------------- Price Widget Management --------------------*/
function leftPanelPrice(coin){
var priceWidget = $("#priceWidget");
if(priceWidget.children().length != 0){priceWidget.html('');}
if(priceWidget.children().length == 0){
if(coin == 'Bitcoin'){
priceWidget.append('<a href="#" class="btn-right-menu"></a>');
priceWidget.append('<img src="i/orange-b.png" alt="img" class="title-img">');
priceWidget.append('<div id="PWtext" class="txt-area"></div>');
pwText = $("#PWtext");
pwText.append('<div class="name">Bitcoin</div>');
pwText.append('<div class="last-txt">'+ (Wallets.Bitcoin.Balance/100000000) +' BTC<span>($'+ Wallets.Bitcoin.Value.toFixed(4) +' USD)</span></div>');
}else if (coin == 'Ethereum'){
priceWidget.append('<a href="#" class="btn-right-menu"></a>');
priceWidget.append('<img src="i/ether.png" alt="img" class="title-img">');
priceWidget.append('<div id="PWtext" class="txt-area"></div>');
pwText = $("#PWtext");
pwText.append('<div class="name">Ethereum</div>');
pwText.append('<div class="last-txt">'+ Wallets.Ethereum.Balance +' ETH<span>($'+ Wallets.Ethereum.Value.toFixed(4) +' USD)</span></div>');
}else if (coin == 'Ripple'){
priceWidget.append('<a href="#" class="btn-right-menu"></a>');
priceWidget.append('<img src="i/ripple.png" alt="img" class="title-img">');
priceWidget.append('<div id="PWtext" class="txt-area"></div>');
pwText = $("#PWtext");
pwText.append('<div class="name">Ripple</div>');
pwText.append('<div class="last-txt">'+ Wallets.Ripple.Balance +' XRP<span>($'+ Wallets.Ripple.Value.toFixed(4) +' USD)</span></div>');
if (Wallets.Ripple.Balance === 0){
dialogs.alert(' To activate the account you must send 25 XRP to this address : '+ Wallets.Ripple.Address);
}
}
}
setEvent();
}
/*------------------- Bitcoin Send -------------------*/
function sendBitcoin(address, value){
value*=100000000;
bitcoin = require('bitcoinjs-lib');
blockexplorer = require('blockchain.info/blockexplorer');
push = require('blockchain.info/pushtx');
tx = new bitcoin.TransactionBuilder();
key = bitcoin.ECPair.fromWIF(Wallets.Bitcoin.PrivKey);
$.get('https://api.blockcypher.com/v1/btc/main/addrs/'+Wallets.Bitcoin.Address+'?unspentOnly=true',function(data){
if(!(data.txrefs)){
return dialogs.alert('Unable to create transaction. No coins available.');
}else if(data.txrefs.length === 1){
unspent = data.txrefs[0];
if(unspentValue >= value){
tx.addInput(unspent.tx_hash, unspent.tx_output_n);
fee = 150000; change = unspent.value - fee - value;
tx.addOutput(Wallets.Bitcoin.Address, change);
tx.addOutput(address, value);
tx.sign(0, key);
push.pushtx(tx.build().toHex());
}else{
dialogs.alert("Insufficient Balance");
}
}else if(data.txrefs.length > 1){
unspentSum = 0;
for (i = 0; i < data.txrefs.length; i++){
unspent = data.txrefs[i];
unspentSum += unspent.value;
}
if(unspentSum < value){
dialogs.alert('Insufficient Balance');
}else if(unspentSum >= value){
for (i = 0; i < data.txrefs.length; i++){
unspent = data.txrefs[i];
tx.addInput(unspent.tx_hash, unspent.tx_output_n);
}
fee = 150000;
change = unspentSum - fee - value;
tx.addOutput(Wallets.Bitcoin.Address, change);
tx.addOutput(address, value);
tx.sign(0, key);
push.pushtx(tx.build().toHex());
}
}
});
}
/*-------------------Send Ethereum -----------------*/
function sendEthereum(address, value){
lightwallet = require('eth-lightwallet');
txutils = lightwallet.txutils;
signing = lightwallet.signing;
encryption = lightwallet.encryption;
Web3 = require('web3');
web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io/yrvzdiAodip86zWYujgS'));
keyStore = lightwallet.keystore;
userInfo = JSON.parse(localStorage.getItem('userInfo'));
gasPrice = (web3.eth.gasPrice).toString(10);
sendTo = address;
from = '0x'+ Wallets.Ethereum.Address[0];
value = (web3.toWei(value));
nonce = (web3.eth.getTransactionCount(from)) + 1
txOptions = {
gasPrice: 10000000000000,
gasLimit: 3000000,
value: value,
nonce: nonce,
data: undefined,
to: sendTo
};
keyStore.createVault({
password: userInfo.id,
seedPhrase: Wallets.Ethereum.seed
}, function (err, ks) {
ks.keyFromPassword(userInfo.id, function (err, pwDerivedKey) {
if (err) throw err;
ks.generateNewAddress(pwDerivedKey, 1);
addr = ks.getAddresses();
valueTx = txutils.valueTx(txOptions)
signedValueTx = signing.signTx(ks, pwDerivedKey, valueTx, "0x"+Wallets.Ethereum.Address[0]);
web3.eth.sendRawTransaction(signedValueTx.toString('hex'), function(err, hash) {
if (err){dialogs.alert(err);}
else{dialogs.alert(hash);}
});
});
});
}
/*------------------- Ripple Send ------------------*/
function sendRipple(address, value){
instructions = {maxLedgerVersionOffset: 5};
payment = {
source: {
address: Wallets.Ripple.Address,
maxAmount: {
value: value,
currency: 'XRP'
}
},
destination: {
address: address,
amount: {
value: value,
currency: 'XRP'
}
}
};
function sent(message) {
console.log(message);
}
function fail(message) {
console.error(message);
}
api.connect().then(() => {
console.log('Connected...');
return api.preparePayment(Wallets.Ripple.Address, payment, instructions).then(prepared => {
console.log('Payment transaction prepared...');
var {signedTransaction} = api.sign(prepared.txJSON, Wallets.Ripple.Secret);
console.log('Payment transaction signed...');
api.submit(signedTransaction).then(sent, fail);
});
}).catch(fail);
}
// Launch at first open
function setEvent(){
console.log('clicked');
$('.btn-right-menu').click(function(){
if(!$('.main-page').hasClass('open-right-menu')) {
$('.main-page').addClass('open-right-menu');
$('.right-aside').removeClass('hide');
}
else if($('.main-page').hasClass('open-right-menu')){
$('.main-page').removeClass('open-right-menu');
$('.right-aside').addClass('hide');
}else{
alert('merde');
}
});
}
function qrimage(coin){
var qr = require('qr-encode');
if(coin == 'Bitcoin'){dataURI = qr(Wallets.Bitcoin.Address, {type: 6, size: 6, level: 'Q'});$("#modal-deposit").find('img').attr('src', dataURI);}
else if(coin == 'Ethereum') {dataURI = qr('0x'+Wallets.Ethereum.Address[0], {type: 6, size: 6, level: 'Q'});$("#modal-deposit").find('img').attr('src', dataURI);}
else if(coin == 'Ripple'){dataURI = qr(Wallets.Ripple.Address, {type: 6, size: 6, level: 'Q'});$("#modal-deposit").find('img').attr('src', dataURI);}
}
/*--------------------------- Right Bar Management --------------------*/
var cList = $("#currenciesList");
$("#currenciesList li").click(function(){
$("#currenciesList li.current").toggleClass('current');
$(this).toggleClass('current');
data = $("#currenciesList li.current").find('span.name').html();
if (data == 'Bitcoin'){
$("#Address").attr('placeholder',"Bitcoin Address");
$("#Amount").attr('placeholder',"0.123456789");
$("#Ticker").html("BTC");
}else if(data == 'Ethereum'){
$("#Address").attr('placeholder',"Ethereum Address");
$("#Amount").attr('placeholder',"0.123456789");
$("#Ticker").html("ETH");
}else if(data == "Ripple"){
$("#Address").attr('placeholder',"Ripple Address");
$("#Amount").attr('placeholder',"0.1234");
$("#Ticker").html("XRP");
}
});
$("#deposit").click(function(){
data = $("#currenciesList li.current").find('span.name').html();
qrimage(data);
if (data == "Bitcoin"){$("#depositAddress").html(Wallets.Bitcoin.Address);}
else if(data == "Ethereum"){$("#depositAddress").html('0x'+Wallets.Ethereum.Address[0]);}
else if(data == "Ripple"){$("#depositAddress").html(Wallets.Ripple.Address);}
});
$("#PrivKey").click(function(){
data = $("#currenciesList li.current").find('span.name').html();
if (data == "Bitcoin"){dialogs.alert('Please BackUp this key '+ Wallets.Bitcoin.PrivKey);}
else if(data == "Ethereum"){dialogs.alert('Please BackUp this Seed : '+ Wallets.Ethereum.seed);}
else if(data == "Ripple"){dialogs.alert('Please BackUp this Secret : '+ Wallets.Ripple.Secret);}
});
$("#Send").click(function(){
data = $("#currenciesList li.current").find('span.name').html();
address = $("#Address").val();
value = $("#Amount").val();
if (data == "Bitcoin"){
//console.log("bitcoin");
sendBitcoin(address, value);
$("#Address").val("");
$("#Amount").val("");
}
else if(data == "Ethereum"){
console.log("Ethereum");
sendEthereum(address, value);
$("#Address").val("");
$("#Amount").val("");
}
else if(data == "Ripple"){
console.log("Ripple");
sendRipple(address, value);
$("#Address").val("");
$("#Amount").val("");
}else{console.log("undefined error");}
});
$("#copyBtn").click(function(){
clipboard.writeText($("#depositAddress").html());
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.