import { Component, OnInit, ViewEncapsulation, AfterViewInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { Helpers } from '../../../../../helpers'; import { ScriptLoaderService } from '../../../../../_services/script-loader.service'; import { DetailsService } from '../../details.service'; import Web3 from 'web3'; import { SafeHtml } from '@angular/platform-browser'; import { MatDialog, MatDialogModule, MatDialogRef } from '@angular/material'; import { DialogComponent } from '../../dialog.component'; import { ToastrService } from 'ngx-toastr'; import { GlobalsComponent } from '../../globals/globals.component'; interface Window { MyNamespace: any; } declare var $: any; @Component({ selector: '.m-grid__item.m-grid__item--fluid.m-wrapper', templateUrl: './configuration.component.html', styleUrls: ['./configuration.component.css'], encapsulation: ViewEncapsulation.None }) export class ConfigurationComponent implements OnInit, AfterViewInit { public web3; public selectedParameter; public selectedParameterId; public contractsArray = []; public categoryDetails = {}; public newValue; public dAppName; public description; public stakeValue; public minStake; public maxStake; public userObj; public loadingSubmit = false; public message; public authMember; public votingWeights = []; public reputationWeights = []; public metamaskLogin = true; public memberAddress; public iframeURl = ''; constructor( private _script: ScriptLoaderService, private route: ActivatedRoute, private router: Router, private detailService: DetailsService, public dialog: MatDialog, private toastr: ToastrService, private globals: GlobalsComponent ) { if (window.location.href.indexOf('iframe') >= 0) { this.iframeURl = '/iframe'; } } openSlide(event) { var data_target = event.target.getAttribute('data-target'); $('.sidebar-overlay').each(function() { $(this).removeClass('open'); if ($(this).attr('id') == data_target) { $(this).addClass('open'); } }); } closeSlide(event) { // var data_dismiss = event.target.getAttribute('data-dismiss'); $('.sidebar-overlay').each(function() { $(this).removeClass('open'); }); } ngOnInit() { this.detailService.setTitle('Configuration'); //--------------------------------- console.log('Init'); let user = localStorage.getItem('currentUser'); this.userObj = JSON.parse(user); console.log(this.userObj); this.authMember = this.userObj.authorized == true ? 1 : 0; console.log(this.authMember); this.dAppName = this.userObj.companyName; this.web3 = new Web3(window['web3'].currentProvider); this.web3.eth.defaultAccount = this.web3.eth.coinbase; if (this.web3.eth.accounts[0] == undefined) { this.metamaskLogin = false; this.memberAddress = '0x0000000000000000000000000000000000000000'; } else { this.memberAddress = this.web3.eth.accounts[0]; } this.indexInitiate(); } indexInitiate() { var urlPath = window.location.href; var index = urlPath.lastIndexOf('/'); var urlCompanyName = urlPath.substring(index + 1, urlPath.length); console.log(urlCompanyName); if (this.userObj.companyName != urlCompanyName) { var data = { masterAddress: '', userName: this.userObj.userName, companyName: urlCompanyName, GBMasterAddress: this.userObj.GBMasterAddress, allAbis: this.userObj.allAbis, email: this.userObj.email, token: 'token', authorized: true }; localStorage.setItem('currentUser', JSON.stringify(data)); import('../../globals/globals.component').then(module => { module.generator(); }); let user1 = localStorage.getItem('currentUser'); this.userObj = JSON.parse(user1); console.log(this.userObj); GlobalsComponent.gbmaster.getdAppDetails( this.userObj.companyName, function(error, result) { this.versionNum = result[5].toNumber(); this.companyMasterAddress = result[1]; this.userObj.masterAddress = this.companyMasterAddress; GlobalsComponent.gbmaster.isMemberAuthorized( this.userObj.companyName, this.memberAddress, function(errorMR1, resultMR1) { var authorized = false; if (resultMR1.authorized) { authorized = true; } this.userObj.authorized = authorized; this.authMember = this.userObj.authorized == true ? 1 : 0; var timeoutVar1 = setInterval( function() { console.log('insideTimeout'); let user = localStorage.getItem('currentUser'); this.userObj = JSON.parse(user); if (this.userObj.companyName in GlobalsComponent.governance) { user = localStorage.getItem('currentUser'); this.userObj = JSON.parse(user); var data = { masterAddress: this.companyMasterAddress, userName: this.userObj.userName, companyName: urlCompanyName, GBMasterAddress: this.userObj.GBMasterAddress, allAbis: this.userObj.allAbis, email: this.userObj.email, token: 'token', authorized: authorized }; localStorage.setItem('currentUser', JSON.stringify(data)); this.getInitialAddress(); clearInterval(timeoutVar1); } }.bind(this), 500 ); }.bind(this) ); }.bind(this) ); } else { import('../../globals/globals.component').then(module => { module.generator(); }); var timeoutVar1 = setInterval( function() { console.log('insideTimeout'); if (this.userObj.companyName in GlobalsComponent.proposalData) { this.getInitialAddress(); clearInterval(timeoutVar1); } }.bind(this), 500 ); } } public tokenAddressDapp; getInitialAddress() { this.detailService.setdAppName(this.userObj.companyName); GlobalsComponent.gbmaster.getdAppContractAddresses( this.userObj.companyName, function(error, result) { this.setContractDetails(result); }.bind(this) ); this.initialCalls(); this.getVotingWeights(); this.getReputationWeights(); this.getProposalLength(); var version; var company = this.userObj.companyName; GlobalsComponent.gbmaster.getdAppTokenAddress( this.userObj.companyName, function(error1, result1) { if (!error1) { this.tokenAddressDapp = result1; } }.bind(this) ); } public canCreateProposal; public reason; public tokensToLock; initialCalls() { GlobalsComponent.governance[this.userObj.companyName].canCreateProposal( this.memberAddress, 7, function(reason, result) { this.canCreateProposal = result; this.reason = reason[0]; this.tokensToLock = reason[1]; }.bind(this) ); GlobalsComponent.categoryData[ this.userObj.companyName ].getCategoryDataBySubCategoryId( 7, function(errCatData, resCatData) { this.categoryDetails = resCatData; this.categoryIncentive = this.categoryDetails.incentives; this.minStake = this.categoryDetails.minStake; this.maxStake = this.categoryDetails.maxStake; }.bind(this) ); } public categoryIncentive; getReputationWeights() { GlobalsComponent.governance[this.userObj.companyName].getReputationWeight( function(errRW, resRW) { this.reputationWeights.push({ id: 'RW', name: 'Reputation weight', desc: 'Reputation is a measurement of a member’s contribution to a network. It is earned when a member’s proposal/solution is accepted, or when a member helps in reaching consensus on a proposal.', value: resRW }); }.bind(this) ); GlobalsComponent.governance[ this.userObj.companyName ].getProposalOwnerPoints( function(errAPO, resAPO) { this.reputationWeights.push({ id: 'APO', name: 'Add Proposal Owner Points', desc: 'Points that needs to be added in Proposal owner reputation after proposal acceptance', value: resAPO }); }.bind(this) ); GlobalsComponent.governance[this.userObj.companyName].getOptionOwnerPoints( function(errAOO, resAOO) { this.reputationWeights.push({ id: 'AOO', name: 'Add Solution Owner Points', desc: 'Points that needs to be added in Solution Owner reputation for providing correct solution against proposal', value: resAOO }); }.bind(this) ); $('#loaderRep').hide(); } getVotingWeights() { GlobalsComponent.governance[this.userObj.companyName].getStakeWeight( function(errGBTS, resGBTS) { this.votingWeights.push({ id: 'SW', name: 'Stake weight', desc: 'The weight given to locked tokens when calculating vote value. You may change one or both of these factors to get the perfect balance for your dApp', value: resGBTS }); }.bind(this) ); // GlobalsComponent.governance[this.userObj.companyName].getGlobalRiskFactor(function(errRF,resRF){ // this.votingWeights.push({id:"RF",name:"Global Risk Factor",desc:"weightage given to proposal and solution initiator. More weightage factor means more incentive distribution to contributors.",value:resRF.toNumber()}) // }.bind(this)); GlobalsComponent.governance[this.userObj.companyName].getBonusReputation( function(errMSF, resMSF) { this.votingWeights.push({ id: 'BR', name: 'Bonus Reputation', desc: 'This is the default amount of reputation to vote value calculation. This can be useful to reduce the relative vote value of high reputation members.', value: resMSF.toNumber() }); }.bind(this) ); GlobalsComponent.governance[this.userObj.companyName].getBonusStake( function(errSW, resSW) { this.votingWeights.push({ id: 'BS', name: 'Bonus Stake', desc: 'This is the default amount of stake added to vote value calculation. This can be useful to reduce the relative vote value of high stake members.', value: resSW.toNumber() }); }.bind(this) ); GlobalsComponent.governance[this.userObj.companyName].getQuorumPercentage( function(errQP, resQP) { this.votingWeights.push({ id: 'QP', name: 'Quorum Percentage', desc: 'It allows people to ensure that financial and legal decisions are always voted on by a good percentage of the members', value: resQP.toNumber() }); }.bind(this) ); $('#loaderVote').hide(); } public proposalLength; getProposalLength() { GlobalsComponent.proposalData[this.userObj.companyName].getProposalLength( function(errPropoLen, resPropLen) { if (!errPropoLen) { this.proposalLength = resPropLen; } else { console.log('Error in getProposalLength'); } }.bind(this) ); } setContractDetails(result) { var contractNames = [ 'Master', 'GovernanceData', 'MemberRoles', 'ProposalCategory', 'SimpleVoting', 'Governance', 'Pool', 'GBTStandardToken' ]; for (let i = 0; i < contractNames.length; i++) { this.contractsArray.push({ id: i + 1, name: contractNames[i], address: result[contractNames[i]] }); if (this.contractsArray.length == 8) this.demo(); } } convertPoolETHtoGBT() { $('#buyGBTPool').modal('show'); } public purchaseGBTpool = false; onClickEdit(i) { this.selectedParameter = this.reputationWeights[i].name; this.selectedParameterId = this.reputationWeights[i].id; this.newValue = null; this.description = ''; this.stakeValue = null; var balance; GlobalsComponent.gbmaster.getBalance_pool( this.userObj.companyName, function(error2, result2) { if (!error2) { if (result2.e < 10) { balance = Math.round(result2 * 100) / 100; } else { balance = Math.round((result2 / 1e18) * 100) / 100; } if (this.categoryIncentive > balance) this.purchaseGBTpool = true; // $('#buyGBTPool').modal('show'); else { this.purchaseGBTpool = false; // $('#buyGBTPool').modal('hide'); // $('#m_modal_1').modal('show'); } } }.bind(this) ); } onClickEdit1(i) { this.selectedParameter = this.votingWeights[i].name; this.selectedParameterId = this.votingWeights[i].id; this.newValue = null; this.description = ''; this.stakeValue = null; var balance; GlobalsComponent.gbmaster.getBalance_pool( this.userObj.companyName, function(error2, result2) { if (!error2) { if (result2.e < 10) { balance = Math.round(result2 * 100) / 100; } else { balance = Math.round((result2 / 1e18) * 100) / 100; } if (this.categoryIncentive > balance) { this.purchaseGBTpool = true; // $('#buyGBTPool').modal('show'); } else { this.purchaseGBTpool = false; // $('#m_modal_4').modal('show'); } } }.bind(this) ); } public ipfs; submit() { if (this.canCreateProposal) { var user = localStorage.getItem('currentUser'); this.userObj = JSON.parse(user); if (this.userObj.email == 'govblocks@govblocks.io') { this.message = 'Please login to your google account in order to create proposal
'; $('#loginModal').modal('show'); $('#m_modal_5').modal('hide'); $('#m_modal_4').modal('hide'); } else { this.loadingSubmit = true; // this.newValue!=null&&(this.stakeValue<=this.maxStake&&this.stakeValue>=this.minStake)&&this.description!="" if (true) { // this.description = $('.summernote').summernote('code'); var optionData = { paramValues: [this.selectedParameterId, this.newValue], apiParamValues: [] }; //[this.selectedParameterId,this.newValue]; this.createProposal(optionData); } } } else { this.loadingSubmit = false; if (this.reason == 'Not Allowed') this.toastr.warning( 'You are not authorized to create proposal under this category' ); else if (this.reason == 'Less Tokens') this.toastr.warning( 'Lock ' + this.tokensToLock + ' token(s) to create a proposal under this category' ); } } createProposal(optionHash) { var proposalData = [ { title: 'Change Configuration Parameter - ' + this.selectedParameter, shortDescription: 'Change Parameter - ' + this.selectedParameter, description: this.description } ]; var data = { proposalData: proposalData, optionData: optionHash, votingType: 0, cId: 7, stakeAmount: this.stakeValue }; GlobalsComponent.governance[ this.userObj.companyName ].createProposalwithOption( data, function(error, result) { if (!error) { this.toastr.info( 'Proposal submitted to ethereum(' + GlobalsComponent.network + '). Awaiting confirmation!' ); this.timeout(result); } else { this.toastr.error('Error executing the operation'); this.loadingSubmit = false; setTimeout(() => { $('#closeConfigureModal').trigger('click'); }, 700); } }.bind(this) ); } timeout(hash) { setTimeout(() => { console.log('Test'); var boundFunction = this.web3.eth.getTransactionReceipt( hash, function(error, result) { if (result != null) { var proposalId = result.logs[0].topics[2]; proposalId = this.web3.toDecimal(proposalId); this.toastr.success('Proposal Added Succesfully!'); this.loadingSubmit = false; $('#button2').trigger('click'); setTimeout(() => { $('#closeConfigureModal').trigger('click'); this.router.navigate([ this.iframeURl + '/components/proposals/' + this.userObj.companyName + '/' + proposalId + '' ]); }, 4000); // this.router.navigate(['/components/configuration']); } else this.timeout(hash); }.bind(this) ); }, 10 * 1000); } ngAfterViewInit() { this.formValidation(); // this._script.load('.m-grid__item.m-grid__item--fluid.m-wrapper', // 'assets/demo/default/custom/components/forms/validation/form-controls.js'); } next() { $('.nav-tabs > li > .active') .next('li') .find('a') .trigger('click'); } hex_to_ascii(str1) { var hex = str1.toString(); var str = ''; for (var n = 0; n < hex.length; n += 2) { str += String.fromCharCode(parseInt(hex.substr(n, 2), 16)); } str1 = ''; for (var i = 0; i < str.length; i++) { if (str.charCodeAt(i) != 0) { str1 += str[i]; } } return str1; } openDialog() { let dialogRef = this.dialog.open(DialogComponent, { height: '400px', width: '600px' }); dialogRef.updatePosition({ top: '50px', left: '500px', bottom: '100px' }); } changePosition() {} predicateBy(prop) { return function(a, b) { if (a[prop] > b[prop]) { return 1; } else if (a[prop] < b[prop]) { return -1; } return 0; }; } demo() { // console.log(this.contractsArray); $('#loader').hide(); var datatable = $('#json_data_contracts').mDatatable({ // datasource definition data: { type: 'local', source: this.contractsArray, pageSize: 10, saveState: { cookie: true, webstorage: true } }, // layout definition layout: { theme: 'default', // datatable theme class: '', // custom wrapper class scroll: false, // enable/disable datatable scroll both horizontal and vertical when needed. height: 550, // datatable's body's fixed height footer: false // display/hide footer }, // column sorting sortable: false, pagination: false, search: { input: $('#generalSearch') }, // columns definition columns: [ { field: 'id', title: 'Sr.no', width: 40, sortable: true, selector: false, textAlign: 'center' }, { field: 'name', title: 'Name', width: 200 }, { field: 'address', title: 'Address', width: 360 } ] }); } formValidation() { $('#votingWeightsForm').validate({ rules: { parameterValue: { required: true }, description: { required: true } } }); $('#reputationWeightsForm').validate({ rules: { parameterValue: { required: true }, description: { required: true } } }); } Reset() { $('div').removeClass('has-success'); $('div').removeClass('has-danger'); $('.form-control-feedback').remove(); } } export class ConfigurationIframeComponent extends ConfigurationComponent {}