UNPKG

sirius-explorer

Version:

An open-source front-end for the Insight API.

3 lines (2 loc) 80.9 kB
/*! sirius-explorer 0.11.6 */ angular.module("insight",["ngResource","ngRoute","ngLodash","ui.bootstrap","ui.route","monospaced.qrcode","gettext","angularMoment","insight.system","insight.socket","insight.blocks","insight.chart","insight.charts","insight.richList","insight.transactions","insight.address","insight.search","insight.statistics","insight.status","insight.markets","insight.connection","insight.currency","insight.messages","insight.siriuscorelib","insight.bignumber","insight.solidity_coder","insight.web3_utils","insight.contracts","insight.opcodes","insight.networks","insight.token"]),angular.module("insight.system",["ngScrollbars","chart.js"]),angular.module("insight.socket",[]),angular.module("insight.blocks",[]),angular.module("insight.charts",[]),angular.module("insight.chart",[]),angular.module("insight.richList",[]),angular.module("insight.transactions",["ngScrollbars","jQueryScrollbar"]),angular.module("insight.address",[]),angular.module("insight.search",[]),angular.module("insight.token",["ngNumeraljs"]),angular.module("insight.statistics",["ngNumeraljs"]),angular.module("insight.status",[]),angular.module("insight.markets",[]),angular.module("insight.connection",[]),angular.module("insight.currency",[]),angular.module("insight.messages",[]),angular.module("insight.messages",[]),angular.module("insight.siriuscorelib",[]),angular.module("insight.contracts",[]),angular.module("insight.opcodes",[]),angular.module("insight.networks",[]),angular.module("insight.solidity_coder",[]),angular.module("insight.web3_utils",[]),angular.module("insight.bignumber",[]),angular.module("insight.address").controller("AddressController",function($scope,$rootScope,$document,$routeParams,$location,$window,Address,getSocket,Constants,ContractsInfo,Contracts,ERC20AddressBalances,ERC20ContractInfo,Web3Utils){var self=this,socket=getSocket($scope),addrStr=$routeParams.addrStr;self.contractAddress=null,Web3Utils.isAddress(addrStr)&&(self.contractAddress=addrStr,addrStr=Contracts.getBitAddressFromContractAddress(addrStr));self.STORAGE_ROWS=Constants.STORAGE_ROWS,self.STORAGE_CONST={STRING:"string",NUMBER:"number",ADDRESS:"address",DATA:"data"},self.storageViews=[self.STORAGE_CONST.DATA,self.STORAGE_CONST.STRING,self.STORAGE_CONST.NUMBER,self.STORAGE_CONST.ADDRESS],self.storage={},self.info=null,self.erc20ContractInfo=null,self.scrollConfig={autoHideScrollbar:!1,theme:"custom",advanced:{updateOnContentResize:!0},scrollInertia:0},self.tooltipOptions={animation:"fade",theme:"tooltipster-black",trigger:"click",interactive:!0},self.qrColors={background:Constants.QRCOLOR.background,color:Constants.QRCOLOR.color},self.balances=[];var _startSocket=function(){socket.on("siriusd/addresstxid",function(data){if(data.address===addrStr){var base=$document.find("base"),beep=new Audio(base[0].href+"/sound/transaction.mp3");$rootScope.$broadcast("tx",data.txid),beep.play()}}),socket.emit("subscribe","siriusd/addresstxid",[addrStr])},_parseStorageRowType=function(hex,type){switch(type){case"string":var str="",i=0,l=hex.length;for("0x"===hex.substring(0,2)&&(i=2);i<l;i+=2){var code=parseInt(hex.substr(i,2),16);if(0===code&&str)break;str+=String.fromCharCode(code)}return str;case"number":return parseInt(hex,16);case"address":return hex.substr(-40);case"data":return"0000000000000000000000000000000000000000000000000000000000000000".substr(hex.length).concat(hex);default:return hex}},_defineDefaultState=function(string,number){var stringMatchUnread=string.match(/[^a-zA-Z0-9;:'".,\/\]\[?!&%#@)(_`><\s]/g)||[],stringMatchRead=string.match(/[a-zA-Z0-9;:'".,\/\]\[?!&%#@)(_`><]/g),isLastSymbolUnread=string[string.length-1]===stringMatchUnread[0];return~number.toString().indexOf("e")?!isLastSymbolUnread&&stringMatchUnread.length||!stringMatchRead?self.STORAGE_CONST.DATA:self.STORAGE_CONST.STRING:self.STORAGE_CONST.NUMBER};socket.on("connect",function(){_startSocket()}),$scope.$on("$destroy",function(){socket.emit("unsubscribe","siriusd/addresstxid",[addrStr])}),self.params=$routeParams,self.findOne=function(){$rootScope.currentAddr=addrStr,_startSocket(),ERC20AddressBalances.query({balanceAddress:addrStr},function(balances){balances&&balances.length&&(self.balances=balances.map(function(balance){return balance.contract&&(balance.contract.contract_address_base=Contracts.getBitAddressFromContractAddress(balance.contract.contract_address)),balance}))}),Address.get({addrStr:addrStr},function(address){$rootScope.titleDetail=address.addrStr.substring(0,7)+"...",$rootScope.flashMessage=null,self.address=address;var ethAddress=Contracts.getEthAddressFromBitAddress(addrStr);ethAddress&&(ERC20ContractInfo.get({contractAddress:ethAddress},function(data){data&&(self.erc20ContractInfo=data)}),ContractsInfo.get({contractAddressStr:ethAddress},function(info){info&&(self.info=info,self.opcodesStr=Contracts.getContractOpcodesString(info.code),self.storage.rows=function(){var rows=[];for(var row in self.info.storage)if(self.info.storage.hasOwnProperty(row))for(var key in self.info.storage[row]){var newRow={values:{},keys:{}};if(self.info.storage[row].hasOwnProperty(key)){for(var CONST in self.STORAGE_CONST){var constName=self.STORAGE_CONST[CONST];newRow.values[constName]=_parseStorageRowType(self.info.storage[row][key],constName),newRow.keys[constName]=_parseStorageRowType(key,constName)}newRow.values.state=_defineDefaultState(newRow.values.string,newRow.values.number,newRow.values.address),newRow.keys.state=_defineDefaultState(newRow.keys.string,newRow.keys.number,newRow.keys.address),rows.push(newRow)}}return rows}(),self.storage.storageLength=Object.keys(info.storage).length,self.storage.viewRows=Constants.STORAGE_ROWS)},function(e){console.log("e",e)}))},function(e){400===e.status?$rootScope.flashMessage="Invalid Address: "+addrStr:503===e.status?$rootScope.flashMessage="Backend Error. "+e.data:$rootScope.flashMessage="Address Not Found",$location.path("/")})},self.toggleStorageRowView=function(index,stateType){var currentStateNumber=self.storageViews.indexOf(self.storage.rows[index][stateType].state);self.storage.rows[index][stateType].state=self.storageViews[(currentStateNumber+1)%self.storageViews.length]},self.showMoreStorageRows=function(limit){self.storage.viewRows=limit},self.tokenDropdownOpen=!1,self.toggleDropdownTokenTracker=function(){self.tokenDropdownOpen=!self.tokenDropdownOpen}}),angular.module("insight.blocks").controller("BlocksController",function($scope,$rootScope,$routeParams,$location,moment,Block,Blocks,BlockByHeight){var self=this;self.loading=!1,self.date=null,self.datepicker={date:null,format:"yyyy-MM-dd",isOpened:!1,dateOptions:{startingDay:1,maxDate:new Date,minDate:new Date(0)}},$routeParams.blockHeight&&BlockByHeight.get({blockHeight:$routeParams.blockHeight},function(hash){$location.path("block/"+hash.blockHash)},function(){$rootScope.flashMessage="Bad Request",$location.path("/")}),$scope.$watch(function(){return self.date},function(newValue,oldValue,scope){newValue!==oldValue&&scope.BC.datepicker.isOpened&&(self.datepicker.date=newValue.getTime(),$location.path("blocks-date/"+moment(newValue).format("YYYY-MM-DD")))}),self.openDatepicker=function(e){e.preventDefault(),e.stopPropagation(),self.datepicker.isOpened=!0},self.disableDatepicker=function(data){var date=data.date;return"day"===data.mode&&(0===date.getDay()||6===date.getDay())},self.loadList=function(){if(self.loading=!0,$routeParams.blockDate&&(self.detail="On "+$routeParams.blockDate),$routeParams.startTimestamp){var d=new Date(1e3*$routeParams.startTimestamp),m=d.getMinutes();m<10&&(m="0"+m),self.before=" before "+d.getHours()+":"+m}$rootScope.titleDetail=self.detail,Blocks.get({blockDate:$routeParams.blockDate,startTimestamp:$routeParams.startTimestamp},function(res){self.loading=!1;var date=new Date(res.pagination.current);self.date=new Date(date.getUTCFullYear(),date.getUTCMonth(),date.getUTCDate(),date.getUTCHours(),date.getUTCMinutes(),date.getUTCSeconds()),self.datepicker.date=self.date.getTime(),self.blocks=res.blocks,self.pagination=res.pagination})},self.findOne=function(){self.loading=!0,Block.get({blockHash:$routeParams.blockHash},function(block){$rootScope.titleDetail=block.height,$rootScope.flashMessage=null,self.loading=!1,self.block=block},function(e){400===e.status?$rootScope.flashMessage="Invalid Transaction ID: "+$routeParams.txId:503===e.status?$rootScope.flashMessage="Backend Error. "+e.data:$rootScope.flashMessage="Block Not Found",$location.path("/")})},self.calcDatesDifference=function(){var present=new Date,presentDate=moment.utc([present.getUTCFullYear(),present.getUTCMonth(),present.getUTCDate()]);return moment.utc(self.pagination.current).from(presentDate)},self.params=$routeParams}),angular.module("insight.charts").controller("ChartsController",function($scope,$routeParams,BigNumber,StatisticsBalanceIntervals,StatisticsByDaysSupply,StatisticsRicherThan,MarketsInfo,getSocket,$q,StatisticChart){var self=this;self.chartDays=$routeParams.days?$routeParams.days:60;var statisticChart=new StatisticChart(self.chartDays);statisticChart.load(StatisticsByDaysSupply,"sum","supply",!1),$scope.$on("chart-create",function(evt,chart){"line"===chart.chart.canvas.id&&(statisticChart.changeChartColor(chart),chart.update())}),self.chartOptions=statisticChart.chartOptions,self.daysButtons=statisticChart.daysButtons,self.balanceIntervals=[],self.marketsInfo=null,self.richerThanIntervals=[];var socket=getSocket($scope);self.init=function(){_getInfo(),_getRicherThan()};var _getRicherThan=function(){return StatisticsRicherThan.query(function(intervals){self.richerThanIntervals=intervals})},_getInfo=function(){return $q.all([StatisticsBalanceIntervals.query().$promise,MarketsInfo.get().$promise]).then(function(results){if(results[0]&&results[1]){self.marketsInfo=results[1];var items=results[0],intervals=[],countAddresses=0,maxCountAddresses=0,sumCoins=new BigNumber(0),maxSumCoins=new BigNumber(0);items.forEach(function(interval){var sumBN=new BigNumber(interval.sum.toString());countAddresses+=interval.count,interval.count>maxCountAddresses&&(maxCountAddresses=interval.count),sumCoins=sumCoins.plus(sumBN),maxSumCoins.lt(sumBN)&&(maxSumCoins=new BigNumber(sumBN))}),items.forEach(function(interval){var addressesPercent=interval.count&&countAddresses?interval.count/countAddresses*100:0,addressesRelativePercent=interval.count&&maxCountAddresses?interval.count/maxCountAddresses*100:0,sumBN=new BigNumber(interval.sum.toString()),coinsPercent=sumBN.gt(0)&&sumCoins.gt(0)?sumBN.dividedBy(sumCoins).mul(100):new BigNumber(0),coinsRelativePercent=sumBN.gt(0)&&maxSumCoins.gt(0)?sumBN.dividedBy(maxSumCoins).mul(100):new BigNumber(0);intervals.push({min:interval.min,max:interval.max,count:interval.count,sum:sumBN.toString(10),addressesPercent:addressesPercent.toFixed(2),addressesRelativePercent:addressesRelativePercent.toFixed(2),coinsPercent:coinsPercent.toNumber().toFixed(2),coinsRelativePercent:coinsRelativePercent.toNumber().toFixed(2)})}),self.balanceIntervals=intervals}})};socket.on("markets_info",function(marketsInfo){self.marketsInfo=marketsInfo})}),angular.module("insight.connection").controller("ConnectionController",function($scope,$window,Status,getSocket,PeerSync){$scope.apiOnline=!0,$scope.serverOnline=!0,$scope.clienteOnline=!0;var socket=getSocket($scope);socket.on("connect",function(){$scope.serverOnline=!0,socket.on("disconnect",function(){$scope.serverOnline=!1})}),$scope.getConnStatus=function(){PeerSync.get({},function(peer){$scope.apiOnline=peer.connected,$scope.host=peer.host,$scope.port=peer.port},function(){$scope.apiOnline=!1})},socket.emit("subscribe","sync"),socket.on("status",function(sync){$scope.sync=sync,$scope.apiOnline="aborted"!==sync.status&&"error"!==sync.status}),$window.addEventListener("offline",function(){$scope.$apply(function(){$scope.clienteOnline=!1})},!0),$window.addEventListener("online",function(){$scope.$apply(function(){$scope.clienteOnline=!0})},!0)}),angular.module("insight.contracts").controller("ContractsController",function($scope,$rootScope,$routeParams,$location,Contracts){try{var addrStr=Contracts.getBitAddressFromContractAddress($routeParams.contractAddressStr);return $location.path("address/"+addrStr),!1}catch(e){return $rootScope.flashMessage="Invalid Address: "+$routeParams.contractAddressStr,$location.path("/"),!1}}),angular.module("insight.currency").controller("CurrencyController",function($scope,$rootScope,Currency,Constants,BigNumber,$filter){$rootScope.currency={symbol:Constants.DEFAULT_CURRENCY,factor:1,bitstamp:0},$rootScope.token={};var _roundFloat=function(x,n){return parseInt(n,10)&&parseFloat(x)||(n=0),Math.round(x*Math.pow(10,n))/Math.pow(10,n)};$rootScope.currency.getConvertion=function(value){var response;return value=Number(value),isNaN(value)||null==value?"value error":0===value?"0 "+$rootScope.currency.symbol:($rootScope.currency.symbol===Constants.CURRENCY.USD?response=_roundFloat(value*$rootScope.currency.factor,2):$rootScope.currency.symbol===Constants.CURRENCY.mBTC?($rootScope.currency.factor=1e3,response=_roundFloat(value*$rootScope.currency.factor,5)):$rootScope.currency.symbol===Constants.CURRENCY.bits?($rootScope.currency.factor=1e6,response=_roundFloat(value*$rootScope.currency.factor,2)):($rootScope.currency.factor=1,response=value),response<1e-7&&(response=response.toFixed(8)),$filter("numeraljs")(response,"0,0[.][00000000]")+" "+$rootScope.currency.symbol)},$rootScope.token.convertDecimals=function(amount,decimals){return amount?new BigNumber(amount).dividedBy("1e"+(decimals||0)).toString(10):0},this.setCurrency=function(currency){$rootScope.currency.symbol=Constants.CURRENCY[currency],localStorage.setItem("insight-currency",Constants.CURRENCY[currency]),"USD"===currency?Currency.get({},function(res){$rootScope.currency.factor=$rootScope.currency.bitstamp=res.data.bitstamp}):$rootScope.currency.factor="mBTC"===currency?1e3:"bits"===currency?1e6:1},Currency.get({},function(res){$rootScope.currency.factor=$rootScope.currency.bitstamp=res.data.bitstamp})}),angular.module("insight.system").controller("FooterController",function($scope,$route,$templateCache,gettextCatalog,amMoment,Version){$scope.version=void Version.get({},function(res){$scope.version=res.version})}),angular.module("insight.system").controller("HeaderController",function($scope,$rootScope,$route,gettextCatalog,amMoment,getSocket,Block,$templateCache,Constants,$location){var self=this,socket=getSocket($scope);function _getMenu(){return[{title:gettextCatalog.getString("Blocks"),link:"blocks",active_part:"/block"},{title:gettextCatalog.getString("Status"),link:"status",active_part:"/status"},{title:gettextCatalog.getString("Stats"),link:"stats",active_part:"/stats"},{title:gettextCatalog.getString("Circulation"),link:"charts",active_part:"/charts"},{title:gettextCatalog.getString("Rich List"),link:"rich-list",active_part:"/rich-list"},{title:gettextCatalog.getString("Tokens"),link:"tokens/search",active_part:"/token"}]}self.defaultLanguage=Constants.DEFAULT_LANGUAGE,self.menu=_getMenu(),self.isActiveMenuItem=function(item){return-1!==$location.path().search(item)?"active":""},self.availableLanguages=[{name:gettextCatalog.getString("Deutsch"),isoCode:"de_DE"},{name:gettextCatalog.getString("English"),isoCode:"en"},{name:gettextCatalog.getString("Spanish"),isoCode:"es"},{name:gettextCatalog.getString("Japanese"),isoCode:"ja"}];socket.on("connect",function(){socket.emit("subscribe","inv"),socket.on("block",function(block){var hash,blockHash=block.toString();hash=blockHash,Block.get({blockHash:hash},function(res){self.totalBlocks=res.height})})}),self.setLanguage=function(isoCode){var currentPageTemplate=$route.current.templateUrl;gettextCatalog.currentLanguage=self.defaultLanguage=isoCode,amMoment.changeLocale(isoCode),localStorage.setItem("insight-language",isoCode),$templateCache.remove(currentPageTemplate),self.menu=_getMenu(),$route.reload()},$rootScope.isCollapsed=!0}),angular.module("insight.system").controller("IndexController",function($scope,$rootScope,$window,$timeout,moment,getSocket,Blocks,TransactionsByDays,Constants,Status,$q,StatisticsTotalSupply,MarketsInfo){var self=this,socket=getSocket($scope);self.blockchainInfo=null,self.marketsInfo={price_usd:0,price_btc:0,market_cap_usd:0},self.txs=[],self.blocks=[],self.chartDays=Constants.CHART_DAYS,self.rewardCurrency=Constants.CURRENCY.SIRX,self.scrollConfig={autoHideScrollbar:!1,axis:"y",theme:"custom",advanced:{updateOnContentResize:!0},scrollInertia:0,callbacks:{onBeforeUpdate:function(){var maxHeight=parseInt($window.getComputedStyle(this).maxHeight),heightList=this.getElementsByClassName("mCSB_container")[0].clientHeight;this.style.height=maxHeight<heightList?maxHeight+"px":heightList+"px"}}},self.chartOptions={series:["Transactions"],datasetOverride:[{yAxisID:"y-axis-1",borderColor:"#2e9ad0",borderWidth:1,fill:!1,pointBorderColor:"#2e9ad0",pointBackgroundColor:"#2e9ad0",pointBorderWidth:1,pointHoverBackgroundColor:"#e75647",pointHoverBorderColor:"#e75647",pointHoverBorderWidth:1,pointHitRadius:10,pointStyle:"rect",lineTension:0}],options:{tooltips:{backgroundColor:"#2e9ad0",titleFontFamily:"SimplonMono",titleFontSize:12,titleFontStyle:"500",titleFontColor:"#232328",bodyFontFamily:"SimplonMono",bodyFontSize:12,bodyFontStyle:"400",bodyFontColor:"#232328",caretSize:5,cornerRadius:0,displayColors:!1},scales:{yAxes:[{id:"y-axis-1",type:"linear",display:!0,position:"left",gridLines:{color:"#26475b",drawBorder:!1,drawTicks:!0,offsetGridLines:!0},ticks:{fontColor:"#2e9ad0",fontFamily:"SimplonMono",fontSize:14,padding:25,callback:function(value){return value+" t"}}}],xAxes:[{gridLines:{color:"#26475b",drawBorder:!1,drawOnChartArea:!1,drawTicks:!0,zeroLineColor:"#26475b"},ticks:{fontColor:"#2e9ad0",fontSize:10,fontFamily:"SimplonMono"}}]}}};var _getBlocks=function(){Blocks.get({limit:Constants.BLOCKS_DISPLAYED},function(res){self.blocks=res.blocks,self.blocksLength=res.length})},socketRequestTimer=null,_startSocket=function(){socket.emit("subscribe","inv"),socket.on("tx",function(tx){tx.createTime=Date.now(),self.txs.unshift(tx),self.txs.length>Constants.TRANSACTION_DISPLAYED&&(self.txs.length=Constants.TRANSACTION_DISPLAYED)}),socket.on("info",function(data){self.blockchainInfo=data.info,self.blockchainInfo.supply=data.supply,self.blockchainInfo.stakingInfo=data.stakingInfo}),socket.on("block",function(){clearTimeout(socketRequestTimer),socketRequestTimer=setTimeout(function(){_getBlocks()},2e3*Math.random())}),socket.on("markets_info",function(marketsInfo){self.marketsInfo=marketsInfo})};socket.on("connect",function(){_startSocket()}),self.getListOfTransactions=function(){TransactionsByDays.query({days:self.chartDays},function(response){for(;response.length<self.chartDays;)response.push({date:moment().subtract(self.chartDays-(self.chartDays-response.length),"days").format("YYYY-MM-DD"),transaction_count:0});self.lastTransactionsList=response.reverse(),self.chartOptions.labels=self.lastTransactionsList.map(function(item){return moment(item.date).format("MM/DD")}),self.chartOptions.data=[self.lastTransactionsList.map(function(item){return item.transaction_count})]})};self.index=function(){$q.all([Status.get({q:"getInfo"}).$promise,StatisticsTotalSupply.get({format:"object"}).$promise,Status.get({q:"getStakingInfo"}).$promise]).then(function(results){results[0]&&results[1]&&results[2]&&(self.blockchainInfo=results[0].info,self.blockchainInfo.stakingInfo=results[2],self.blockchainInfo.supply=results[1].supply)}),MarketsInfo.get({},function(response){response&&(self.marketsInfo=response)}),_getBlocks(),_startSocket()}}),angular.module("insight.messages").controller("VerifyMessageController",function($scope,$http){$scope.message={address:"",signature:"",message:""},$scope.verification={status:"unverified",result:null,error:null,address:""},$scope.verifiable=function(){return $scope.message.address&&$scope.message.signature&&$scope.message.message},$scope.verify=function(){$scope.verification.status="loading",$scope.verification.address=$scope.message.address,$http.post(window.apiPrefix+"/messages/verify",$scope.message).success(function(data,status,headers,config){if("boolean"!=typeof data.result)return $scope.verification.status="error",void($scope.verification.error=null);$scope.verification.status="verified",$scope.verification.result=data.result}).error(function(data,status,headers,config){$scope.verification.status="error",$scope.verification.error=data})};var unverify=function(){$scope.verification.status="unverified"};$scope.$watch("message.address",unverify),$scope.$watch("message.signature",unverify),$scope.$watch("message.message",unverify)}),angular.module("insight.richList").controller("RichListController",function($scope,$routeParams,StatisticsRichestList){var self=this;self.items=[],self.loaded=!1,self.init=function(){StatisticsRichestList.query({},function(items){self.items=items,self.loaded=!0})}}),angular.module("insight.system").controller("ScannerController",function($scope,$rootScope,$modalInstance,Global){$scope.global=Global;var isMobile={Android:function(){return navigator.userAgent.match(/Android/i)},BlackBerry:function(){return navigator.userAgent.match(/BlackBerry/i)},iOS:function(){return navigator.userAgent.match(/iPhone|iPad|iPod/i)},Opera:function(){return navigator.userAgent.match(/Opera Mini/i)},Windows:function(){return navigator.userAgent.match(/IEMobile/i)},any:function(){return isMobile.Android()||isMobile.BlackBerry()||isMobile.iOS()||isMobile.Opera()||isMobile.Windows()}};navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,window.URL=window.URL||window.webkitURL||window.mozURL||window.msURL,$scope.isMobile=isMobile.any(),$scope.scannerLoading=!1;var video,canvas,context,localMediaStream,$searchInput=angular.element(document.getElementById("search")),_scan=function(evt){if($scope.isMobile){$scope.scannerLoading=!0;var files=evt.target.files;if(1===files.length&&0===files[0].type.indexOf("image/")){var file=files[0],reader=new FileReader;reader.onload=function(e){new MegaPixImage(file).render(canvas,{maxWidth:200,maxHeight:200,orientation:6}),setTimeout(function(){qrcode.width=canvas.width,qrcode.height=canvas.height,qrcode.imagedata=context.getImageData(0,0,qrcode.width,qrcode.height);try{qrcode.decode()}catch(e){alert(e)}},1500)},reader.readAsDataURL(file)}}else{if(localMediaStream){context.drawImage(video,0,0,300,225);try{qrcode.decode()}catch(e){}}setTimeout(_scan,500)}},_successCallback=function(stream){video.src=window.URL&&window.URL.createObjectURL(stream)||stream,localMediaStream=stream,video.play(),setTimeout(_scan,1e3)},_scanStop=function(){$scope.scannerLoading=!1,$modalInstance.close(),$scope.isMobile||(localMediaStream.stop&&localMediaStream.stop(),localMediaStream=null,video.src="")},_videoError=function(err){console.log("Video Error: "+JSON.stringify(err)),_scanStop()};qrcode.callback=function(data){_scanStop();var str=0===data.indexOf("sirius:")?data.substring(8):data;console.log("QR code detected: "+str),$searchInput.val(str).triggerHandler("change").triggerHandler("submit")},$scope.cancel=function(){_scanStop()},$modalInstance.opened.then(function(){$rootScope.isCollapsed=!0,setTimeout(function(){canvas=document.getElementById("qr-canvas"),context=canvas.getContext("2d"),$scope.isMobile?document.getElementById("qrcode-camera").addEventListener("change",_scan,!1):(video=document.getElementById("qrcode-scanner-video"),angular.element(video),canvas.width=300,canvas.height=225,context.clearRect(0,0,300,225),navigator.getUserMedia({video:!0},_successCallback,_videoError))},500)})}),angular.module("insight.search").controller("SearchController",function($location,$timeout,Block,Transaction,Address,BlockByHeight,ERC20ContractInfo,Contracts){var self=this;self.loading=!1;var _badQuery=function(){self.badQuery=!0,$timeout(function(){self.badQuery=!1},2e3)},_resetSearch=function(){self.q="",self.loading=!1};self.search=function(){var q=self.q.trim();self.badQuery=!1,self.loading=!0,Block.get({blockHash:q},function(){_resetSearch(),$location.path("block/"+q)},function(){Transaction.get({txId:q},function(){_resetSearch(),$location.path("tx/"+q)},function(){var bitAddress=q;Address.get({addrStr:bitAddress},function(){_resetSearch(),$location.path("address/"+bitAddress)},function(){isFinite(q)?BlockByHeight.get({blockHeight:q},function(hash){_resetSearch(),$location.path("block/"+hash.blockHash)},function(){self.loading=!1,_badQuery()}):ERC20ContractInfo.get({contractAddress:q},function(){_resetSearch(),$location.path("token/"+q)},function(){self.loading=!1,_badQuery()})})})})}}),angular.module("insight.transactions").controller("SendRawTransactionController",function($scope,$http,$filter,SendRawTransaction,lodash){var timeoutId=null;$scope.status="ready",$scope.error=null,$scope.isEmpty=!1,$scope.rawTransaction,$scope.txid="",$scope.jqueryScrollbarOptions={},$scope.send=function(){if(clearState(),validateRawTransaction()){var postData={rawtx:$scope.rawTransaction.trim()};SendRawTransaction.send(postData,function(successfullResponse){if("string"!=typeof successfullResponse.txid)return $scope.status="error",void($scope.error=": the transaction was sent but no transaction id was got back");$scope.status="sent",$scope.txid=successfullResponse.txid,clearDataAfterSuccessfullSend()},function(errorResponse){var data=errorResponse.data;$scope.status="error",$scope.error=data?": "+data:"no error message given (connection error?)"})}},$scope.isStatusError=function(){return"error"===$scope.status},$scope.checkIsEmpty=function(){return $scope.isEmpty},$scope.isStatusSent=function(){return"sent"===$scope.status},$scope.$on("$destroy",function(){clearState()});var clearState=function(){$scope.status="ready",$scope.isEmpty=!1,$scope.error=null,$scope.txid="",clearTimeout(timeoutId)},validateRawTransaction=function(){var rawTrx=$scope.rawTransaction;return rawTrx?!(!lodash.isString(rawTrx)||!/^[0-9a-fA-F]+$/.test(rawTrx))||($scope.status="error",!($scope.error=": the transaction hex is not valid")):!($scope.isEmpty=!0)},clearDataAfterSuccessfullSend=function(){$scope.rawTransaction=null,timeoutId=setTimeout(function(){clearState(),$scope.$apply()},12e4)}}),angular.module("insight.statistics").controller("StatisticsController",function($scope,$routeParams,Statistics,StatisticsByDaysTransactions,StatisticsByDaysOutputs,StatisticsByDaysFees,StatisticsByDaysDifficulty,StatisticsByDaysStakes,Statistics24Hours,gettextCatalog,$filter,Constants,StatisticChart,MarketsInfo){var self=this,factories={transactions:{factory:StatisticsByDaysTransactions,field:"transaction_count"},outputs:{factory:StatisticsByDaysOutputs,field:"sum"},fees:{factory:StatisticsByDaysFees,field:"fee"},difficulty:{factory:StatisticsByDaysDifficulty,field:"sum"},stakes:{factory:StatisticsByDaysStakes,field:"sum"}};self.chartText={fees:gettextCatalog.getString("The total value of all transaction fees paid to miners (not including the coinbase value of block rewards)."),transactions:gettextCatalog.getString("The number of daily confirmed Sirius transactions."),outputs:gettextCatalog.getString("The total value of all transaction outputs per day (includes coins returned to the sender as change)."),difficulty:gettextCatalog.getString("A relative measure of how difficult it is to find a new block. The difficulty is adjusted periodically as a function of how much hashing power has been deployed by the network of miners."),stakes:gettextCatalog.getString("")},self.chartDays=$routeParams.days,self.chartType=$routeParams.type,self.marketCurrency=Constants.CURRENCY.USD,self.marketPrice=0;var statisticChart=new StatisticChart(self.chartDays);self.chartOptions=statisticChart.chartOptions,self.daysButtons=statisticChart.daysButtons,$scope.$on("chart-create",function(evt,chart){"line"===chart.chart.canvas.id&&(statisticChart.changeChartColor(chart),chart.update())}),self.getDifficulties=function(){statisticChart.load(factories[$routeParams.type].factory,factories[$routeParams.type].field,$routeParams.type)},self.get24HoursStats=function(){Statistics24Hours.get(function(response){self.statsTotal24=response}),MarketsInfo.get({},function(response){response&&response.price_usd&&(self.marketPrice=response.price_usd)})}}),angular.module("insight.status").controller("StatusController",function($scope,Status,Sync,getSocket){var self=this,socket=getSocket($scope);self.getStatus=function(q){Status.get({q:"get"+q},function(d){self.loaded=1,angular.extend(self,d)},function(e){self.error="API ERROR: "+e.data})};var _onSyncUpdate=function(sync){sync.startTs||(sync.startTs=Date.now()),self.sync=sync},_startSocket=function(){socket.emit("subscribe","sync"),socket.on("status",function(sync){_onSyncUpdate(sync)})};socket.on("connect",function(){_startSocket()}),self.getSync=function(){_startSocket(),Sync.get({},function(sync){_onSyncUpdate(sync)},function(e){self.sync={error:"Could not get sync information"+e.toString()}})}}),angular.module("insight.token").controller("TokenController",function($routeParams,$rootScope,$location,ERC20ContractInfo,ERC20Transfers,ERC20AddressBalances,ERC20Holders,ContractsRepository,SolidityCoder,Web3Utils,Contracts,BigNumber){if(!Web3Utils.isAddress($routeParams.address)&&!Contracts.isValidSiriusAddress($routeParams.address))return $rootScope.flashMessage="Invalid Address: "+$routeParams.address,$location.path("e404").replace(),!1;var contractEthAddress=$routeParams.address;if(!Web3Utils.isAddress(contractEthAddress))return contractEthAddress=Contracts.getEthAddressFromBitAddress($routeParams.address),$location.path("token/"+contractEthAddress).replace(),!1;Contracts.getBitAddressFromContractAddress($routeParams.address);var self=this;self.tokenInfo={},self.transfers={},self.holders={},self.filterByAddress=null,$routeParams.a&&(Web3Utils.isAddress($routeParams.a)&&(self.filterByAddress=Contracts.getBitAddressFromContractAddress($routeParams.a)),Contracts.isValidSiriusAddress($routeParams.a)&&(self.filterByAddress=$routeParams.a)),self.addressBalance=null,self.readSmartContractTab={balanceOf:{owner_address:"",inProcess:!1,owner_error:"",balance:0,requested_address:"",process_address:""},allowance:{owner_address:"",spender_address:"",inProcess:!1,owner_error:"",spender_error:"",owner_requested_address:"",owner_process_address:"",spender_requested_address:"",spender_process_address:""}},self.contractAddress=$routeParams.address,self.tab=$routeParams.tab&&-1!==["transfers","holders","read-smart-contract"].indexOf($routeParams.tab)?$routeParams.tab:"transfers";var _loadTabContent=function(offset){switch(self.tab){case"transfers":_getTransfers(offset||0);break;case"holders":_getHolders(offset||0)}};self.getPercent=function(total,amount){return new BigNumber(amount).dividedBy(total).mul(100).toString(10)};var _getTransfers=function(offset){ERC20Transfers.get({address:contractEthAddress,offset:offset,"addresses[]":self.filterByAddress?self.filterByAddress:null}).$promise.then(function(trList){self.transfers=trList,self.transfers.pages=self.transfers.count&&self.transfers.limit?Math.ceil(self.transfers.count/self.transfers.limit):0})},_getHolders=function(offset){return ERC20Holders.get({address:contractEthAddress,offset:offset}).$promise.then(function(holderList){self.holders=holderList,self.holders.pages=self.holders.count&&self.holders.limit?Math.ceil(self.holders.count/self.holders.limit):0})};self.init=function(){ERC20ContractInfo.get({contractAddress:contractEthAddress,address:self.filterByAddress?self.filterByAddress:null},function(info){if(info){self.tokenInfo=info;try{self.tokenInfo.contract_address_base=Contracts.getBitAddressFromContractAddress(self.tokenInfo.contract_address)}catch(e){console.log("Error convert",self.tokenInfo)}}}),self.filterByAddress&&ERC20AddressBalances.get({contractAddress:contractEthAddress,balanceAddress:self.filterByAddress}).$promise.then(function(balance){self.addressBalance=balance}).catch(function(err){console.log(err)}),_loadTabContent()},self.paginate=function(offset){self[self.tab].limit&&self[self.tab].pages>offset/self[self.tab].limit&&0<=offset&&self[self.tab].offset!==offset&&_loadTabContent(offset)},self.setTab=function(tabName){self.tab!==tabName&&(self.tab=tabName,$location.path("token/"+$routeParams.address+"/"+tabName,!1),_loadTabContent())};var getEthConvertedAddress=function(address){try{if(Contracts.isValidSiriusAddress(address)){var ethAddress=Contracts.getEthAddressFromBitAddress(address);if(ethAddress)return ethAddress}if(address=address.toLowerCase(),Web3Utils.isAddress(address))return address}catch(e){console.log(e)}return null};self.getAddressBalance=function(){var balanceOfData=self.readSmartContractTab.balanceOf;if(balanceOfData.inProcess)return!1;var userAddress=balanceOfData.owner_address,processAddress=getEthConvertedAddress(userAddress);return processAddress?(balanceOfData.owner_error="",balanceOfData.inProcess=!0,ContractsRepository.call.get({address:contractEthAddress,hash:"70a08231"+SolidityCoder.encodeParam("address",Web3Utils.toAddress(processAddress))}).$promise.then(function(info){if(balanceOfData.requested_address=userAddress,balanceOfData.process_address=processAddress,balanceOfData.owner_address="",balanceOfData.inProcess=!1,info&&info.executionResult)try{var decodedBalance=SolidityCoder.decodeParam("uint256",info.executionResult.output);balanceOfData.balance=decodedBalance.toString(10)}catch(e){balanceOfData.balance=0}})):!(balanceOfData.owner_error="Invalid address")},self.getAllowanceAmount=function(){var allowanceData=self.readSmartContractTab.allowance;if(allowanceData.inProcess)return!1;var userOwnerAddress=allowanceData.owner_address,processOwnerAddress=getEthConvertedAddress(userOwnerAddress);if(!processOwnerAddress)return!(allowanceData.owner_error="Invalid address");allowanceData.owner_error="";var userSpenderAddress=allowanceData.spender_address,processSpenderAddress=getEthConvertedAddress(userSpenderAddress);return processSpenderAddress?(allowanceData.spender_error="",allowanceData.inProcess=!1,ContractsRepository.call.get({address:contractEthAddress,hash:"dd62ed3e"+SolidityCoder.encodeParam("address",Web3Utils.toAddress(processOwnerAddress))+SolidityCoder.encodeParam("address",Web3Utils.toAddress(processSpenderAddress))}).$promise.then(function(info){if(allowanceData.owner_requested_address=allowanceData.owner_address,allowanceData.owner_process_address=processOwnerAddress,allowanceData.spender_requested_address=allowanceData.spender_address,allowanceData.spender_process_address=processSpenderAddress,allowanceData.owner_address="",allowanceData.spender_address="",allowanceData.inProcess=!1,info.executionResult)try{var decodedBalance=SolidityCoder.decodeParam("uint256",info.executionResult.output);allowanceData.balance=decodedBalance.toString(10)}catch(e){allowanceData.balance=0}})):!(allowanceData.spender_error="Invalid address")},self.paginateData={transfers:{paginate_has_error:!1,paginate_page:""},holders:{paginate_has_error:!1,paginate_page:""}},self.setPaginateError=function(hasError){self.paginateData[self.tab].paginate_has_error=hasError},self.resetPaginate=function(){self.paginateData[self.tab].paginate_has_error=!1,self.paginateData[self.tab].paginate_page=""},self.changePage=function(e){var countPages=self[self.tab].count&&self[self.tab].limit?Math.ceil(self[self.tab].count/self[self.tab].limit):0,value=e.target.value;if(!/^\d+$/.test(value))return self.setPaginateError(!0);(value=parseInt(e.target.value,10))&&!isNaN(value)&&value<=countPages?(self.paginate(self[self.tab].limit*(value-1)),this.resetPaginate()):self.setPaginateError(!0)}}),angular.module("insight.system").controller("TokensSearchController",function($scope,$rootScope,$route,gettextCatalog,ContractsRepository,lodash){var currentRequestUniqueId,self=this;self.init=function(){getContractsList()};self.query="",self.error="",self.inProcess=!1,self.searchResult={count:0,items:[]},self.contractsList=[];var getContractsList=function(){ContractsRepository.contractsList.get({},function(res){if(res&&res.count&&res.items){var transformedItems=[];res.items.forEach(function(item){item.exception||!item.name&&!item.symbol||transformedItems.push(item)}),self.contractsList=_.sortBy(transformedItems,function(item){return-item.count_holders})}})},debounced=lodash.debounce(function(requestId){if(currentRequestUniqueId!==requestId)return!1;ContractsRepository.search.get({query:lodash.trim(self.query)},function(res){self.inProcess=!1,currentRequestUniqueId===requestId&&(self.searchResult=res)},function(){self.error="Request Error!"})},550);self.search=function(){lodash.trim(self.query)?self.inProcess||self.changeQuery():self.error="Search field is required!"},self.reset=function(){currentRequestUniqueId=lodash.uniqueId(),self.query="",self.searchResult={count:0,items:[]}},self.changeQuery=function(){self.error="",self.inProcess=!0,currentRequestUniqueId=lodash.uniqueId(),_.trim(self.query)?debounced(currentRequestUniqueId):(self.reset(),self.inProcess=!1)}}),angular.module("insight.transactions").controller("TransactionsController",function($scope,$rootScope,$routeParams,$location,Transaction,TransactionsByBlock,TransactionsByAddress,Contracts,$q,ERC20ContractInfo,Web3Utils){var self=this,pageNum=0,pagesTotal=1;self.loading=!1,self.loadedBy=null,self.isCopied=!1,self.scrollConfig={autoHideScrollbar:!1,theme:"custom",advanced:{updateOnContentResize:!0},scrollInertia:0};var _aggregateItems=function(txId,items){if(!items)return[];for(var l=items.length,ret=[],tmp={},u=0,i=0;i<l;i++){var contractAddress,notAddr=!1;if(items[i].scriptSig&&!items[i].addr&&(items[i].addr="Unparsed address ["+u+++"]",notAddr=items[i].notAddr=!0),items[i].scriptPubKey&&!items[i].scriptPubKey.addresses)items[i].scriptPubKey.hex&&(contractAddress=Contracts.getContractAddressByHex(txId,items[i].n,items[i].scriptPubKey.hex)),contractAddress&&(items[i].contractAddress=contractAddress,items[i].contractAddressBit=Contracts.getBitAddressFromContractAddress(contractAddress)),items[i].scriptPubKey.addresses=["Unparsed address ["+u+++"]"],notAddr=items[i].notAddr=!0;if(items[i].scriptPubKey&&1<items[i].scriptPubKey.addresses.length)items[i].addr=items[i].scriptPubKey.addresses.join(","),ret.push(items[i]);else{var addr=items[i].addr||items[i].scriptPubKey&&items[i].scriptPubKey.addresses[0];tmp[addr]||(tmp[addr]={},tmp[addr].valueSat=0,tmp[addr].count=0,tmp[addr].addr=addr,tmp[addr].items=[]),tmp[addr].isSpent=items[i].spentTxId,tmp[addr].doubleSpentTxID=tmp[addr].doubleSpentTxID||items[i].doubleSpentTxID,tmp[addr].doubleSpentIndex=tmp[addr].doubleSpentIndex||items[i].doubleSpentIndex,tmp[addr].dbError=tmp[addr].dbError||items[i].dbError,tmp[addr].valueSat+=Math.round(1e8*items[i].value),tmp[addr].items.push(items[i]),tmp[addr].notAddr=notAddr,tmp[addr].contractAddress=items[i].contractAddress||null,tmp[addr].contractAddressBit=items[i].contractAddressBit||null,items[i].unconfirmedInput&&(tmp[addr].unconfirmedInput=!0),tmp[addr].count++}}return angular.forEach(tmp,function(v){v.value=v.value||parseInt(v.valueSat)/1e8,ret.push(v)}),ret},contractsInfoCache={},addEvent=function(tx,logItem){return $q(function(resolve){contractsInfoCache[logItem.address]||(contractsInfoCache[logItem.address]=ERC20ContractInfo.get({contractAddress:logItem.address})),contractsInfoCache[logItem.address].$promise.then(function(data){if(data&&data.contract_address){var addressFrom=logItem.topics[1],addressTo=logItem.topics[2],amount=parseInt(logItem.data,16),tokenEvent={addressFrom:Contracts.getBitAddressFromContractAddress(addressFrom.slice(addressFrom.length-40,addressFrom.length)),addressTo:Contracts.getBitAddressFromContractAddress(addressTo.slice(addressTo.length-40,addressTo.length)),amount:amount,contractInfo:data};tx.tokenEvents.push(tokenEvent)}return resolve()}).catch(function(){return resolve()})})},asyncProcessERC20TX=function(tx){var deferred=$q.defer(),tokenPromises=[];if(tx.tokenEvents=[],tx.isErc20Transfer&&tx.receipt&&tx.receipt.length)for(var i=0;i<tx.receipt.length;i++){var receiptItem=tx.receipt[i];if(receiptItem&&receiptItem.log&&receiptItem.log.length)for(var j=0;j<receiptItem.log.length;j++){var logItem=receiptItem.log[j];logItem&&logItem.topics&&3===logItem.topics.length&&"ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"===logItem.topics[0]&&tokenPromises.push(addEvent(tx,logItem))}}return $q.all(tokenPromises).then(function(){deferred.resolve(tx)}),deferred.promise},_processTX=function(tx){var contractBytecodeInfo=function(tx){for(var items=tx.vout,l=items.length,i=0;i<l;i++)if(items[i].scriptPubKey&&items[i].scriptPubKey.hex){var bytecode=Contracts.getContractBytecode(items[i].scriptPubKey.hex);if(bytecode)return bytecode}return null}(tx);tx.vinSimple=_aggregateItems(tx.txid,tx.vin),tx.voutSimple=_aggregateItems(tx.txid,tx.vout),self.loading=!1,contractBytecodeInfo&&(tx.contractBytecode=contractBytecodeInfo.code,tx.contractBytecodeType=contractBytecodeInfo.type,tx.contractAsm=Contracts.getContractOpcodesString(tx.contractBytecode))},_paginate=function(data){pagesTotal=data.pagesTotal,pageNum+=1;var promises=[];data.txs.forEach(function(tx){promises.push(asyncProcessERC20TX(tx))}),$q.all(promises).then(function(results){results.forEach(function(tx){tx.showAdditInfo=!1,_processTX(tx),self.txs.push(tx)}),self.loading=!1})},_findTx=function(txid){Transaction.get({txId:txid},function(tx){$rootScope.titleDetail=tx.txid.substring(0,7)+"...",$rootScope.flashMessage=null,asyncProcessERC20TX(tx).then(function(tx){self.tx=tx,_processTX(tx),self.txs.unshift(tx)})},function(e){400===e.status?$rootScope.flashMessage="Invalid Transaction ID: "+$routeParams.txId:503===e.status?$rootScope.flashMessage="Backend Error. "+e.data:$rootScope.flashMessage="Transaction Not Found",$location.path("/")})};self.findThis=function(){self.loading=!0,_findTx($routeParams.txId)},self.load=function(from){self.loadedBy=from,self.loadMore()},self.loadMore=function(){if(pageNum<pagesTotal&&!self.loading)switch(self.loading=!0,self.loadedBy){case"address":address=$routeParams.addrStr,Web3Utils.isAddress(address)&&(address=Contracts.getBitAddressFromContractAddress(address)),TransactionsByAddress.get({address:address,pageNum:pageNum},function(data){_paginate(data)});break;case"contractAddress":TransactionsByAddress.get({address:Contracts.getBitAddressFromContractAddress($routeParams.contractAddressStr),pageNum:pageNum},function(data){_paginate(data)});break;default:TransactionsByBlock.get({block:$routeParams.blockHash,pageNum:pageNum},function(data){_paginate(data)})}var address},">"!=$routeParams.v_type&&"<"!=$routeParams.v_type||(self.from_vin="<"==$routeParams.v_type,self.from_vout=">"==$routeParams.v_type,self.v_index=parseInt($routeParams.v_index),self.itemsExpanded=!0),self.txs=[],$scope.$on("tx",function(event,txid){_findTx(txid)})}),angular.module("insight.address").factory("Address",function($resource,$window){return $resource($window.apiPrefix+"/addr/:addrStr/?noTxList=1",{addrStr:"@addStr"},{get:{method:"GET",interceptor:{response:function(res){return res.data},responseError:function(res){if(404===res.status)return res}}}})}),angular.module("insight.bignumber").factory("BigNumber",function($window){return $window.eth_libs.BigNumber}),angular.module("insight.siriuscorelib").factory("SiriusCoreLib",function(){return require("siriuscore-lib")}),angular.module("insight.blocks").factory("Block",function($resource){return $resource(window.apiPrefix+"/block/:blockHash",{blockHash:"@blockHash"},{get:{method:"GET",interceptor:{response:function(res){return res.data},responseError:function(res){if(404===res.status)return res}}}})}).factory("Blocks",function($resource){return $resource(window.apiPrefix+"/blocks")}).factory("BlockByHeight",function($resource){return $resource(window.apiPrefix+"/block-index/:blockHeight")}),angular.module("insight.chart").factory("StatisticChart",function(gettextCatalog,$filter){function StatisticChart(days){this.days=days,this.chartOptions={series:["Test"],datasetOverride:[{defaultFontFamily:"SimplonMono",yAxisID:"y-axis-1",borderColor:"#2e9ad0",borderWidth:1,pointBorderColor:"#2e9ad0",pointBackgroundColor:"#2e9ad0",pointBorderWidth:0,pointRadius:0,pointHoverBackgroundColor:"#e75647",pointHoverBorderColor:"#e75647",pointHoverBorderWidth:1,pointHitRadius:10,pointStyle:"rect",lineTension:0}],options:{tooltips:{backgroundColor:"#2e9ad0",titleFontFamily:"SimplonMono",titleFontSize:12,titleFontStyle:"500",titleFontColor:"#232328",bodyFontFamily:"SimplonMono",bodyFontSize:12,bodyFontStyle:"400",bodyFontColor:"#232328",caretSize:5,cornerRadius:3,displayColors:!1,callbacks:{}},layout:{padding:{left:25}},scales:{yAxes:[{id:"y-axis-1",type:"linear",display:!0,position:"left",gridLines:{color:"#26475b",drawBorder:!1,offsetGridLines:!0,zeroLineColor:"#26475b"},ticks:{fontColor:"#2e9ad0",fontFamily:"SimplonMono",fontSize:14,padding:20}}],xAxes:[{type:"time",time:{unit:60<days||"all"==days?"month":"day",displayFormats:{month:"MMM'DD",day:"MMM'DD"},max:Date.now()},gridLines:{color:"#26475b",drawBorder:!1,drawOnChartArea:!1,drawTicks:!0,zeroLineColor:"#26475b"},ticks:{fontColor:"#2e9ad0",fontSize:10,fontFamily:"SimplonMono"}}]}}},this.daysButtons=[{days:30,name:"30 "+gettextCatalog.getString("Days")},{days:60,name:"60 "+gettextCatalog.getString("Days")},{days:180,name:"180 "+gettextCatalog.getString("Days")},{days:365,name:"1 "+gettextCatalog.getString("Year")},{days:730,name:"2 "+gettextCatalog.getString("Years")},{days:"all",name:gettextCatalog.getString("All Time")}],this.chartStats=[]}return StatisticChart.prototype.changeChartColor=function(chart){var gradient=chart.chart.ctx.createLinearGradient(0,0,0,600);gradient.addColorStop(0,"rgba(46, 154, 208,0.5)"),gradient.addColorStop(1,"rgba(0, 0, 0,0.001)"),chart.chart.config.data.datasets[0].backgroundColor=gradient},StatisticChart.prototype.load=function(factory,itemField,itemName,fill){var self=this;factory.query({days:self.days},function(response){if(fill)for(;response.length<self.days;){var emptyItem={};emptyItem.date=moment().subtract(self.days-(self.days-response.length),"days").format("YYYY-MM-DD"),emptyItem[itemField]=0,response.push(emptyItem)}response.reverse(),self.chartOptions.labels=response.map(function(item){return item.date}),self.chartOptions.data=response.map(function(item){return item[itemField]}),self.chartOptions.options.scales.yAxes[0].ticks.callback=function(value){return 999<value?$filter("numeraljs")(value,"0,0"):parseFloat(value.toFixed(6))},self.chartOptions.series=[itemName],self.chartOptions.options.tooltips.callbacks.beforeTitle=function(text){text[0].yLabel=itemName.charAt(0).toUpperCase()+itemName.substr(1)+": "+$filter("numeraljs")(text[0].yLabel,"0,0.[00000000]")},self.chartStats=response})},StatisticChart}),angular.module("insight.contracts").factory("ContractsInfo",function($resource){return $resource(window.apiPrefix+"/contracts/:contractAddressStr/info")}).factory("Contracts",function(SiriusCoreLib,Opcodes,Networks,Constants){var CONTRACT_CALL=194,CONTRACT_CREATE=193;return{isValidSiriusAddress:function(address){return SiriusCoreLib.Address.isValid(address,Constants.NETWORK)},getBitAddressFromContractAddress:function(contractAddress){try{var networkId=Networks.getCurrentNetwork().pubkeyhash.toString(16),hexBitAddress=networkId+contractAddress+SiriusCoreLib.crypto.Hash.sha256sha256(new SiriusCoreLib.deps.Buffer(networkId+contractAddress,"hex")).toString("hex").slice(0,8);return SiriusCoreLib.encoding.Base58.encode(new SiriusCoreLib.deps.Buffer(hexBitAddress,"hex"))}catch(e){return null}},getEthAddressFromBitAddress:function(bitAddress){try{var networkId=Networks.getCurrentNetwork().pubkeyhash.toString(16),hexBitAddress=SiriusCoreLib.encoding.Base58.decode(bitAddress).toString("hex");return hexBitAddress.slice(0,2)!==networkId?null:hexBitAddress.slice(2,-8)}catch(e){return null}},getContractOpcodesString:function(hex){for(var contractCode=new SiriusCoreLib.deps.Buffer(hex,"hex"),ops=[],index=0;index<contractCode.length;index++){var currentOp=Opcodes.lookupOpcode(contractCode[index],!0);if(currentOp.pc=index,ops.push(currentOp),"PUSH"===currentOp.name.slice(0,4)){var pushDataLength=contractCode[index]-95,pushData=contractCode.slice(index+1,index+pushDataLength+1);currentOp.pushData=pushData,index+=pushDataLength}}for(var opcodesStr="",i=0;i<ops.length;i++)ops[i].pushData?opcodesStr+=" "+ops[i].name+(ops[i].pushData?" 0x"+ops[i].pushData.toString("hex"):""):opcodesStr+=" "+ops[i].name;return opcodesStr},getContractBytecode:function(hex){try{var script=SiriusCoreLib.Script(hex);if(script.chunks&&script.chunks.length)for(var k=0;k<script.chunks.length;k++)if(script.chunks[k]&&script.chunks[k].opcodenum&&-1!==[CONTRACT_CALL,CONTRACT_CREATE].indexOf(script.chunks[k].opcodenum))switch(script.chunks[k].opcodenum){case CONTRACT_CALL:return{code:script.chunks[k-2].buf.toString("hex"),type:"Call"};case CONTRACT_CREATE:return{code:script.chunks[k-1].buf.toString("hex"),type:"Create"}}}catch(e){}return null},getContractAddressByHex:function(txid,voutNum,hex){try{var script=SiriusCoreLib.Script(hex);if(script.chunks&&script.chunks.length)for(var k=0;k<script.chunks.length;k++)if(script.chunks[k]&&script.chunks[k].opcodenum&&-1!==[CONTRACT_CALL,CONTRACT_CREATE].indexOf(script.chunks[k].opcodenum))switch(script.chunks[k].opcodenum){case CONTRACT_CALL:case CONTRACT_CREATE:return this.getContractAddress(txid,voutNum)}}catch(e){}return null},getContractAddress:function(txId,num){var reverseTxId=txId.match(/.{2}/g).reverse().join(""),buf=new SiriusCoreLib.deps.Buffer(4);buf.writeUInt32LE(num,0);var addr=reverseTxId+buf.toString("hex");return SiriusCoreLib.crypto.Hash.sha256ripemd160(new SiriusCoreLib.deps.Buffer(addr,"hex")).toString("hex")}}}).factory("StorageByAddress",function($resource,$window){return $resource($window.apiPrefix+"/contracts/:address/info",{address:"@address"},{