import { map } from 'rxjs/operators/map'; import { Component, OnInit, ViewEncapsulation, AfterViewInit, OnChanges, DoCheck, AfterContentInit, AfterContentChecked, AfterViewChecked } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { Http, Response, Headers, RequestOptions, Request, RequestMethod } from '@angular/http'; import { DetailsService } from '../../pages/default/details.service'; import Web3 from 'web3'; import { ToastrService } from 'ngx-toastr'; import { GlobalsComponent } from '../../pages/default/globals/globals.component'; // import {GlobalsComponent} from '../../pages/default/globals/globals.component'; declare var $: any; declare let mLayout: any; declare var gapi: any; @Component({ selector: 'app-header-nav', templateUrl: './header-nav.component.html', encapsulation: ViewEncapsulation.None }) export class HeaderNavComponent implements OnChanges, OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewChecked, AfterViewInit { public message; public web3; public accounts; public balance; public gbMasterAddress; public gbMasterAbi; public userObj; public masterAddress; public allAbis; public abiArray = []; public memberAddress; public memberBalance; public network; public networkId; public loggedIn = false; googleLoginButtonId = 'googleBtn'; public metamaskLogin = true; public versionContract = [ 'Master', 'GovernanceData', 'MemberRoles', 'ProposalCategory', 'SimpleVoting', 'RankBasedVoting', 'FeatureWeighted', 'StandardVotingType', 'Governance', 'Pool', 'GBTController', 'GBTStandardToken', 'GovBlocksMaster' ]; public showHeader = true; constructor( private toastr: ToastrService, private http: Http, private router: Router, private route: ActivatedRoute, private detailService: DetailsService ) { if (window.location.href.indexOf('iframe') >= 0) { this.showHeader = false; } } public categories; title = ''; public show: boolean = true; ngOnChanges() {} public tempVar = false; public userTokenbalance; public poolTokenbalance; public tokenName; logout() { var auth2 = gapi.auth2.getAuthInstance(); auth2.signOut().then( function() { this.loggedIn = false; var user = localStorage.getItem('currentUser'); this.userObj = JSON.parse(user); this.userObj.email = ''; // this.userObj.email = 'govblocks@govblocks.io'; this.userObj.userName = 'GovBlocks'; localStorage.setItem('currentUser', JSON.stringify(this.userObj)); }.bind(this) ); } login() { $('#openLoginModal').trigger('click'); gapi.auth2.getAuthInstance(); } googleInit() { gapi.signin2.render(this.googleLoginButtonId, { onSuccess: this.onSignIn.bind(this), scope: 'profile', theme: 'dark', width: 100, height: 30, 'border-radius': 20 }); } public userName; onSignIn(googleUser) { this.web3 = new Web3(window['web3'].currentProvider); this.web3.eth.defaultAccount = this.web3.eth.coinbase; this.loggedIn = true; $('#loginModalClose').trigger('click'); $('#dAppOnboardingLoginModal').trigger('click'); var profile = googleUser.getBasicProfile(); var firstName = profile.getGivenName(); var lastName = profile.getFamilyName(); var email = profile.getEmail(); this.userName = firstName[0] + lastName[0]; var user = localStorage.getItem('currentUser'); this.userObj = JSON.parse(user); this.userObj.email = email; this.userObj.userName = firstName + ' ' + lastName; localStorage.setItem('currentUser', JSON.stringify(this.userObj)); // var url = "https://api.shopfilo.com/api/sfs/onground/post/govBlocks_userlogin"; // var data = { email: email, ethaddress: this.web3.eth.accounts[0], username: this.userObj.userName }; // var result = this.PostRequest(url, data); // console.log(result); } PostRequest(url, data) { var headers = new Headers(); headers.append('Content-Type', 'application/json'); var requestoptions = new RequestOptions({ method: RequestMethod.Post, url: url, headers: headers, body: JSON.stringify(data) }); return this.http.request(new Request(requestoptions)).pipe( map((res: Response) => { if (res) { return [{ status: res.status, json: res.json() }]; } }) ); } public urlCNAME; ngOnInit() { // this.googleInit(); if (window['web3'] == undefined) { var link = 'https://metamask.io/'; var blank = '_blank'; this.message = 'Connection to blockchain could not be established. Please consider using metamask
'; $('#m_modal_2').modal('show'); } let user = localStorage.getItem('currentUser'); this.userObj = JSON.parse(user); this.gbMasterAddress = this.userObj.GBMasterAddress; var urlCompanyName = ''; var urlPath = window.location.href; var index = urlPath.lastIndexOf('/'); var getDataFromUrlIndex: any = ''; getDataFromUrlIndex = urlPath.substring(index + 1, urlPath.length); if (getDataFromUrlIndex.includes('/index/')) { this.getTokenPrice(); } if (getDataFromUrlIndex == 'govblocks-user-dashboard') { this.router.navigate(['/']); } else if (getDataFromUrlIndex == 'dapp-onboarding') { this.router.navigate(['/components/dapp-onboarding']); } else if (getDataFromUrlIndex == 'gbt-balance') { this.router.navigate(['/components/gbt-balance']); } else if (getDataFromUrlIndex == 'rewards-ledger') { this.router.navigate(['/components/rewards-ledger']); } else if (getDataFromUrlIndex == 'proposals-raised') { this.router.navigate(['/components/proposals-raised']); } else if (getDataFromUrlIndex == 'solutions-provided') { this.router.navigate(['/components/solutions-provided']); } else if (getDataFromUrlIndex == 'total-votes-casted') { this.router.navigate(['/components/total-votes-casted']); } else if (getDataFromUrlIndex == 'reputation') { this.router.navigate(['/components/reputation']); } else if (!isNaN(getDataFromUrlIndex)) { for (var arr = [], i = urlPath.length; i--; ) { if (urlPath[i] == '/') { arr.push(i); } } index = arr[1]; urlCompanyName = urlPath.substring(index + 1, arr[0]); this.urlCNAME = urlCompanyName; console.log(urlCompanyName); } else { urlCompanyName = urlPath.substring(index + 1, urlPath.length); this.urlCNAME = urlCompanyName; console.log(urlCompanyName); } this.web3 = new Web3(window['web3'].currentProvider); this.web3.eth.defaultAccount = this.web3.eth.coinbase; this.memberAddress = this.web3.eth.accounts[0]; this.checkMetaMask(); if (this.memberAddress == undefined) { this.metamaskLogin = false; this.memberAddress = '0x0000000000000000000000000000000000000000'; } var userAddress = this.memberAddress; this.memberAddress = this.truncate(this.memberAddress, 14, '...'); this.web3.eth.getBalance(userAddress, (err, balance) => { balance = Math.round((balance / 1e18) * 100) / 100; this.memberBalance = balance + ' ETH'; }); this.web3.version.getNetwork((err, netId) => { this.networkId = netId; switch (netId) { case '1': this.network = 'Main Network'; break; case '2': this.network = 'Ropsten Network'; break; case '42': this.network = 'Kovan Network'; break; case '4': this.network = 'Rinkeby Network'; break; case '31': this.network = 'RSK Network'; break; case '96': this.network = 'Private Network'; break; default: this.network = 'Unknown Network'; } }); this.detailService.title.subscribe(updatedTitle => { this.title = updatedTitle; if ( this.title === 'Dashboard' || this.title === 'GovBlocks User Dashboard' ) { this.show = false; } else { this.show = true; } }); this.detailService.poolAddress.subscribe(updatedPoolAddress => { this.poolAddress = updatedPoolAddress; }); this.detailService.poolETHBalance.subscribe(updatedPoolBalance => { this.poolETHBalance = updatedPoolBalance; }); this.detailService.poolGBTbalance.subscribe(updatedPoolGBTBalance => { this.poolGBTbalance = updatedPoolGBTBalance; }); this.detailService.tokenPrice.subscribe(updatedTokenprice => { this.tokenPrice = updatedTokenprice; }); this.detailService.userTokenbalance.subscribe(userTokenbalance => { this.userTokenbalance = userTokenbalance; }); this.detailService.poolTokenbalance.subscribe(poolTokenbalance => { this.poolTokenbalance = poolTokenbalance; }); this.detailService.tokenName.subscribe(tokenName => { this.tokenName = tokenName; }); var timeoutVar = setInterval( function() { if (GlobalsComponent.gbmaster) { GlobalsComponent.gbmaster.getBalance( userAddress, function(errorUserBal, resUserBal) { this.userBalance = (resUserBal.toNumber() / 1e18).toFixed(2); }.bind(this) ); this.generateAllAbis(); clearInterval(timeoutVar); } }.bind(this), 500 ); var GBMasteAddress = { 4: '0xca27deb069d83629db00579ab0f0d80cd119a79b', 42: '0xfd49ec86aaff8a312273cbebc3f48cc4c067c04a', 31: '0x26847806987d45cdb482987f2027b05eef14d061', 96: '0xd62d9f828928661808a4700ea747e8474b236961' }; this.web3.version.getNetwork((err, netId) => { this.gbMasterAddress = GBMasteAddress[netId]; if (urlCompanyName != '') { GlobalsComponent.gbmaster.getdAppDetails( urlCompanyName, function(errorDesc, resultDesc) { if (resultDesc[6] != '') { if (this.userObj.GBMasterAddress != this.gbMasterAddress) { this.tempVar = true; this.generateAllAbis(); } } else { this.router.navigate(['/not-found']); } }.bind(this) ); } }); // this.checkUserDetails(); // Observable.interval(10000).takeWhile(() => true).subscribe(() => this.checkMetaMask()); } public poolETHBalance; truncate(fullStr, strLen, separator) { if (fullStr.length <= strLen) return fullStr; separator = separator || '...'; var sepLen = separator.length, charsToShow = strLen - sepLen, frontChars = Math.ceil(charsToShow / 2), backChars = Math.floor(charsToShow / 2); return ( fullStr.substr(0, frontChars) + separator + fullStr.substr(fullStr.length - backChars) ); } iframeResize() { import('../../pages/default/globals/globals.component').then(module => { module.iframe_resize(); }); } checkAccounts() { var account = this.web3.eth.accounts[0]; var accountInterval = setInterval( function() { let user = localStorage.getItem('currentUser'); this.userObj = JSON.parse(user); this.iframeResize(); this.web3 = new Web3(window['web3'].currentProvider); this.web3.eth.defaultAccount = this.web3.eth.coinbase; if (this.web3.eth.accounts[0] !== account) { account = this.web3.eth.accounts[0]; var reload = true; this.checkAuthorization(reload); } }.bind(this), 2000 ); } generateAllAbis() { // GlobalsComponent.gbmaster.getABIarray(function(errHash,resHash) // { // if(!errHash) // { // this.abiArray = resHash; var timeoutVar = setInterval( function() { if (GlobalsComponent.gbmaster) { this.checkUserDetails(); clearInterval(timeoutVar); } }.bind(this), 500 ); // this.checkUserDetails(); this.checkAccounts(); // setTimeout(()=>{ this.getTokenPrice(); // },1000); // } // }.bind(this)); } // getAbiFromArray(contractname) // { // for(var i = 0; i { this.getTokenPrice(); }, 1000); }.bind(this) ); } }.bind(this) ); } else { let user = localStorage.getItem('currentUser'); var userObj = JSON.parse(user); var masterAddress = userObj.masterAddress; var data = { masterAddress: userObj.masterAddress, userName: userObj.userName, companyName: userObj.companyName, GBMasterAddress: this.gbMasterAddress, allAbis: this.abiArray, email: userObj.email, authorized: userObj.authorized, token: 'token' }; localStorage.setItem('currentUser', JSON.stringify(data)); } var reload = false; if (this.tempVar) { this.router.navigate(['/govblocks-user-dashboard']); } else { this.checkAuthorization(reload); } // localStorage.removeItem('currentUser'); // window.location.reload(); // } } public poolAddress; public poolAbi; public GBTControllerAddress; public GBTControllerAbi; createProposal() { var amount; GlobalsComponent.governance[this.userObj.companyName].canCreateProposal( this.web3.eth.accounts[0], 18, function(reason, resCanCreate) { if (resCanCreate) { var proposalData = [ { title: 'Buy Pool GBT', description: 'Convert pool ETH to GBT', shortDescription: 'Convert pool ETH to GBT' } ]; var optionData = { paramValues: [amount], apiParamValues: [] }; var data = { proposalData: proposalData, optionData: optionData, votingType: 0, cid: 18 }; GlobalsComponent.governance[ this.userObj.companyName ].createProposalwithOption( data, function(error, result) { if (!error) { this.toastr.info( 'Proposal submitted to ethereum(' + GlobalsComponent.network + '). Awaiting confirmation!' ); this.timeoutProposal(result); } else { this.toastr.error('Error creating proposal'); } }.bind(this) ); } else { this.loading = false; if (reason == 'Not Allowed') this.toastr.warning( 'You are not authorized to create proposal under this category' ); else if (reason == 'Less Tokens') this.toastr.warning( 'Lock more tokens to create a proposal under this category' ); } }.bind(this) ); } timeout(hash) { setTimeout(() => { console.log('Test'); var boundFunction = GlobalsComponent.gbmaster.getTransactionReceipt( hash, function(error, result) { console.log(error); if (result != null) { this.toastr.success('Proposal Created!'); var proposalId = result.logs[0].topics[2]; proposalId = this.web3.toDecimal(proposalId); this.loading = false; } else this.timeout(hash); }.bind(this) ); }, 10 * 1000); } checkAuthorization(reload) { let user = localStorage.getItem('currentUser'); this.userObj = JSON.parse(user); var masterAddress = this.userObj.masterAddress; if ( masterAddress != '' && masterAddress != '0x0000000000000000000000000000000000000000' ) { var masterAbi = this.userObj.allAbis[0]; var governanceDataAbi = this.userObj.allAbis[1]; var memberRoleAbi = this.userObj.allAbis[2]; this.poolAbi = this.userObj.allAbis[8]; this.GBTControllerAbi = this.userObj.allAbis[9]; GlobalsComponent.gbmaster.getdAppContractAddresses( this.userObj.companyName, function(error1, result1) { var gdAddress = result1['GovernanceData']; var mrAddress = result1['MemberRoles']; this.poolAddress = result1['Pool']; GlobalsComponent.gbmaster.isMemberAuthorized( this.userObj.companyName, this.web3.eth.accounts[0], function(errorRoleId, resultRoleId) { var authorized = true; if (!resultRoleId[1]) { authorized = false; } if (this.userObj.GBMasterAddress != this.gbMasterAddress) { this.userObj.companyName = ''; masterAddress = ''; } var data = { masterAddress: masterAddress, userName: this.userObj.userName, companyName: this.userObj.companyName, GBMasterAddress: this.userObj.GBMasterAddress, allAbis: this.userObj.allAbis, email: this.userObj.email, token: 'token', authorized: authorized }; localStorage.setItem('currentUser', JSON.stringify(data)); if (reload) window.location.reload(); }.bind(this) ); }.bind(this) ); } else { if (reload) window.location.reload(); } } checkMetaMask() { this.web3.version.getNetwork((err, netId) => { // if (netId !== "4" && netId !== "42" && netId !== "31" && netId != "96") { if (netId !== '42') { this.message = 'GovBlocks is currently available on Kovan network.
To continue using GovBlocks please switch network'; // this.message = "GovBlocks is currently available on Rinkeby, Kovan and RSK network.
To continue using GovBlocks please switch network" $('#m_modal_2').modal('show'); } else { this.web3.eth.getAccounts((err, accs) => { if (err != null || accs.length === 0) { // var blank = "_blank" // var link = "https://metamask.io/" // this.message = "Unable to fetch user information.
Please Login to MetaMask."; // $('#m_modal_2').modal('show'); } else { this.accounts = accs; this.web3.eth.getBalance(this.accounts[0], (err, resbalance) => { resbalance = Math.round((resbalance / 1e18) * 100) / 100; //(resbalance.toNumber()/1e+18).toFixed(2); this.balance = resbalance; $('#m_modal_2').modal('hide'); }); } }); } }); } refresh(): void { window.location.reload(); } ngDoCheck() {} ngAfterContentInit() {} ngAfterContentChecked() {} ngAfterViewChecked() { $('.open-sidebar').click(function() { var target = $(this).data('target'); $('.open') .add(target) .toggleClass('open'); }); } ngAfterViewInit() { mLayout.initHeader(); } public loadingCreate = false; public actualTokenPrice; public amount; public poolBalance; public tokenPrice; public gbtSTAbi; public gbtSTAddress; public finishEnable1 = true; public transferEnable1 = true; public finishEnable = true; public transferEnable = true; resetValues() { // this.tokenPrice=null; // this.amountPayable=null; // this.amount = null; this.loadingCreate = false; } resetValues1() { this.ethAmount = null; this.transferloading = false; this.tokenAmount = null; } Reset() { $('div').removeClass('has-success'); $('div').removeClass('has-danger'); $('.form-control-feedback').remove(); } public ethAmount; public transferloading = false; transferPoolBalance(): void { this.detailService.poolAddress.subscribe(updatedPoolAddress => { this.poolAddress = updatedPoolAddress; }); this.transferloading = true; this.finishEnable1 = false; let user = localStorage.getItem('currentUser'); this.userObj = JSON.parse(user); GlobalsComponent.gbmaster.getdAppContractAddresses( this.userObj.companyName, function(errAddress, resAddress) { this.poolAddress = resAddress['Pool']; this.web3.eth.sendTransaction( { from: this.web3.eth.coinbase, to: this.poolAddress, value: this.web3.toWei(this.ethAmount, 'ether') }, function(err, transactionHash) { if (!err) { console.log(transactionHash); this.toastr.info( 'Request submitted to ethereum ' + this.networkName + '. Awaiting confirmation' ); this.timeoutTransfer(transactionHash); } else { this.finishEnable1 = false; this.transferloading = false; this.toastr.error('Error in executing the operation!'); setTimeout(() => { this.ethAmount = null; this.transferloading = false; $('#closeBuyTokenModel1').trigger('click'); setTimeout(() => { window.location.reload(); }, 700); }, 700); } }.bind(this) ); }.bind(this) ); } timeoutTransfer(hash) { setTimeout(() => { var boundFunction = this.web3.eth.getTransactionReceipt( hash, function(error, result) { if (result != null) { if (result.status == '0x1') { this.toastr.success('Transfered successfully..'); this.getTokenPrice(); this.transferloading = false; this.finishEnable1 = true; this.transferEnable1 = false; $('#buyETHpool').modal('hide'); setTimeout(() => { window.location.reload(); }, 3000); } else { this.toastr.error('Transfer failed!'); this.transferloading = false; this.finishEnable1 = true; } } else { this.timeoutTransfer(hash); } }.bind(this) ); }, 10 * 1000); } public tokenAmount; transferTokensToPool(tokenName) { var companyName; this.transferloading = true; this.finishEnable1 = false; companyName = tokenName == 'GBT' ? 'GOVBLOCKS' : this.userObj.companyName; if (this.tokenAmount <= this.userTokenbalance) { if (companyName == 'GOVBLOCKS') { GlobalsComponent.gbmaster.transferGBT( this.poolAddress, this.tokenAmount, function(error, result) { if (!error) { this.timeoutTokenTransfer(result); this.toastr.info( 'Request submitted to ethereum ' + this.networkName + '. Awaiting confirmation' ); } else { this.toastr.error('Transaction failed!'); this.transferloading = false; this.finishEnable1 = true; } }.bind(this) ); } else { GlobalsComponent.governance[this.userObj.companyName].transferTokens( companyName, this.poolAddress, this.tokenAmount, function(error, result) { if (!error) { this.timeoutTokenTransfer(result); this.toastr.info( 'Request submitted to ethereum ' + this.networkName + '. Awaiting confirmation' ); } else { this.toastr.error('Transaction failed!'); this.transferloading = false; this.finishEnable1 = true; } }.bind(this) ); } } else { this.toastr.warning('Less token balance..'); this.transferloading = false; this.finishEnable1 = true; } } timeoutTokenTransfer(hash) { setTimeout(() => { var boundFunction = this.web3.eth.getTransactionReceipt( hash, function(error, result) { if (result != null) { if (result.status == '0x1') { this.toastr.success('Transfered successfully..'); this.getTokenPrice(); this.transferloading = false; this.finishEnable1 = true; this.transferEnable1 = false; setTimeout(() => { $('#buyETHpool').modal('hide'); window.location.reload(); }, 3000); } else { this.toastr.error('Transfer failed!'); this.transferloading = false; this.finishEnable1 = true; } } else { this.timeoutTokenTransfer(hash); } }.bind(this) ); }, 10 * 1000); } tranferETHModal() { $('#buyETHpool').modal('show'); } public poolGBTbalance; public poolEtherBalance = false; public userBalance; getTokenPrice() { let user = localStorage.getItem('currentUser'); this.userObj = JSON.parse(user); var GBmasterAddress = this.userObj.GBMasterAddress; var masterAddress = this.userObj.masterAddress; this.amount = 50; // this.web3.eth.contract(this.gbMasterAbi).at(GBmasterAddress,function(errGB,resGB){ // let ans2=resGB.getDappMasterAddress(userObj.companyName,function(error2,result2){ // if(!error2) // masterAddress = result2; if ( masterAddress != '' && masterAddress != '0x0000000000000000000000000000000000000000' ) { var masterAbi = this.userObj.allAbis[0]; this.poolAbi = this.userObj.allAbis[9]; this.GBTControllerAbi = this.userObj.allAbis[10]; this.gbtSTAbi = this.userObj.allAbis[11]; GlobalsComponent.gbmaster.getdAppContractAddresses( this.userObj.companyName, function(error1, result1) { this.poolAddress = result1['Pool']; this.gbtSTAddress = result1['GBTStandardToken']; GlobalsComponent.gbmaster.getGBTokenPrice( function(error1, result1) { if (!error1) this.actualTokenPrice = result1; this.tokenPrice = this.actualTokenPrice / 1e18; this.detailService.setTokenPrice(this.tokenPrice); }.bind(this) ); GlobalsComponent.gbmaster.getPoolBalanceinETH( this.userObj.companyName, function(errorPoolBal, resPoolBal) { this.poolBalance = (resPoolBal.toNumber() / 1e18).toFixed(2); if (this.poolBalance == 0) this.poolEtherBalance = true; this.detailService.setPoolBalance(this.poolBalance); var userAddress = this.web3.eth.accounts[0]; var balance; GlobalsComponent.gbmaster.getBalance_pool( this.userObj.companyName, function(error2, result2) { if (!error2) { if (result2.e < 10) { this.poolGBTbalance = Math.round(result2 * 100) / 100; } else { this.poolGBTbalance = Math.round((result2 / 1e18) * 100) / 100; } } }.bind(this) ); }.bind(this) ); }.bind(this) ); } // }.bind(this)); // }.bind(this)); } buyGBT() { if (this.tokenPrice * this.amount < this.userBalance) { this.loadingCreate = true; this.finishEnable = false; let user = localStorage.getItem('currentUser'); this.userObj = JSON.parse(user); var amountPayable = 1e18 * this.tokenPrice * this.amount; GlobalsComponent.gbmaster.buydAppTokens( 'GOVBLOCKS', amountPayable, function(error, result) { if (!error) { this.toastr.info( 'Submitted to ethereum(' + this.network + '). Awaiting confirmation!' ); this.timeout1(result); } else { this.toastr.error('Error executing the operation'); this.loadingCreate = false; this.finishEnable = true; setTimeout(() => { $('#closeBuyTokenModel').trigger('click'); }, 700); } }.bind(this) ); } else { this.toastr.warning('Insuffient ETH balance'); } } timeout1(hash) { setTimeout(() => { var boundFunction = this.web3.eth.getTransactionReceipt( hash, function(error, result) { if (result != null) { if (result.status == '0x1') { this.toastr.success('GBT Token purchased successfully!'); this.loadingCreate = false; this.finishEnable = true; this.transferEnable = false; setTimeout(() => { $('#closeBuyTokenModel').trigger('click'); window.location.reload(); }, 3000); } else { this.loadingCreate = false; this.finishEnable = true; } } else this.timeout1(hash); }.bind(this) ); }, 10 * 1000); } }