diff --git a/client/webserver/jsintl.go b/client/webserver/jsintl.go index 2a33a92c50..acc13a4ae8 100644 --- a/client/webserver/jsintl.go +++ b/client/webserver/jsintl.go @@ -86,6 +86,7 @@ const ( limitOrderID = "LIMIT_ORDER" limitOrderImmediateTifID = "LIMIT_ORDER_IMMEDIATE_TIF" marketOrderID = "MARKET_ORDER" + cancelOrderID = "CANCEL_ORDER" matchStatusNewlyMatchedID = "MATCH_STATUS_NEWLY_MATCHED" matchStatusMakerSwapCastID = "MATCH_STATUS_MAKER_SWAP_CAST" matchStatusTakerSwapCastID = "MATCH_STATUS_TAKER_SWAP_CAST" @@ -304,6 +305,7 @@ var enUS = map[string]*intl.Translation{ limitOrderID: {T: "limit"}, limitOrderImmediateTifID: {T: "limit (i)", Notes: "i = immediate"}, marketOrderID: {T: "market"}, + cancelOrderID: {T: "cancel"}, matchStatusNewlyMatchedID: {T: "Newly Matched"}, matchStatusMakerSwapCastID: {T: "Maker Swap Sent"}, matchStatusTakerSwapCastID: {T: "Taker Swap Sent"}, @@ -525,6 +527,9 @@ var zhCN = map[string]*intl.Translation{ createID: {T: "创建"}, availableID: {T: "可用"}, immatureID: {T: "不成"}, + limitOrderID: {T: "限价单"}, + marketOrderID: {T: "市价单"}, + cancelOrderID: {T: "取消单"}, } var plPL = map[string]*intl.Translation{ diff --git a/client/webserver/site/dist/entry.js b/client/webserver/site/dist/entry.js index 5d9449bf3d..e949669756 100644 --- a/client/webserver/site/dist/entry.js +++ b/client/webserver/site/dist/entry.js @@ -1,3 +1,21554 @@ -/*! For license information please see entry.js.LICENSE.txt */ -(()=>{var e={61:(e,t,n)=>{var r=n(698).default;function a(){"use strict";e.exports=a=function(){return t},e.exports.__esModule=!0,e.exports.default=e.exports;var t={},n=Object.prototype,o=n.hasOwnProperty,s=Object.defineProperty||function(e,t,n){e[t]=n.value},i="function"==typeof Symbol?Symbol:{},c=i.iterator||"@@iterator",l=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function d(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{d({},"")}catch(e){d=function(e,t,n){return e[t]=n}}function h(e,t,n,r){var a=t&&t.prototype instanceof v?t:v,o=Object.create(a.prototype),i=new I(r||[]);return s(o,"_invoke",{value:C(e,n,i)}),o}function p(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}t.wrap=h;var f={};function v(){}function m(){}function g(){}var y={};d(y,c,(function(){return this}));var b=Object.getPrototypeOf,x=b&&b(b(A([])));x&&x!==n&&o.call(x,c)&&(y=x);var k=g.prototype=v.prototype=Object.create(y);function w(e){["next","throw","return"].forEach((function(t){d(e,t,(function(e){return this._invoke(t,e)}))}))}function S(e,t){function n(a,s,i,c){var l=p(e[a],e,s);if("throw"!==l.type){var u=l.arg,d=u.value;return d&&"object"==r(d)&&o.call(d,"__await")?t.resolve(d.__await).then((function(e){n("next",e,i,c)}),(function(e){n("throw",e,i,c)})):t.resolve(d).then((function(e){u.value=e,i(u)}),(function(e){return n("throw",e,i,c)}))}c(l.arg)}var a;s(this,"_invoke",{value:function(e,r){function o(){return new t((function(t,a){n(e,r,t,a)}))}return a=a?a.then(o,o):o()}})}function C(e,t,n){var r="suspendedStart";return function(a,o){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===a)throw o;return{value:void 0,done:!0}}for(n.method=a,n.arg=o;;){var s=n.delegate;if(s){var i=F(s,n);if(i){if(i===f)continue;return i}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if("suspendedStart"===r)throw r="completed",n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r="executing";var c=p(e,t,n);if("normal"===c.type){if(r=n.done?"completed":"suspendedYield",c.arg===f)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(r="completed",n.method="throw",n.arg=c.arg)}}}function F(e,t){var n=t.method,r=e.iterator[n];if(void 0===r)return t.delegate=null,"throw"===n&&e.iterator.return&&(t.method="return",t.arg=void 0,F(e,t),"throw"===t.method)||"return"!==n&&(t.method="throw",t.arg=new TypeError("The iterator does not provide a '"+n+"' method")),f;var a=p(r,e.iterator,t.arg);if("throw"===a.type)return t.method="throw",t.arg=a.arg,t.delegate=null,f;var o=a.arg;return o?o.done?(t[e.resultName]=o.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,f):o:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,f)}function T(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function D(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function I(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(T,this),this.reset(!0)}function A(e){if(e){var t=e[c];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var n=-1,r=function t(){for(;++n=0;--r){var a=this.tryEntries[r],s=a.completion;if("root"===a.tryLoc)return n("end");if(a.tryLoc<=this.prev){var i=o.call(a,"catchLoc"),c=o.call(a,"finallyLoc");if(i&&c){if(this.prev=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&o.call(r,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),D(n),f}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var a=r.arg;D(n)}return a}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:A(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),f}},t}e.exports=a,e.exports.__esModule=!0,e.exports.default=e.exports},698:e=>{function t(n){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(n)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},687:(e,t,n)=>{var r=n(61)();e.exports=r;try{regeneratorRuntime=r}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=r:Function("r","regeneratorRuntime = r")(r)}}},t={};function n(r){var a=t[r];if(void 0!==a)return a.exports;var o=t[r]={exports:{}};return e[r](o,o.exports,n),o.exports}n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";function e(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);n=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,i=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){i=!0,o=e},f:function(){try{s||null==n.return||n.return()}finally{if(i)throw o}}}}(document.cookie.split(";"));try{for(n.s();!(t=n.n()).done;){var r=a(t.value.split("="),2),o=r[0],s=r[1];if(o.trim()===e)return s}}catch(e){n.e(e)}finally{n.f()}return null}},{key:"removeCookie",value:function(e){document.cookie="".concat(e,"=;expires=Thu, 01 Jan 1970 00:00:01 GMT;")}},{key:"isDark",value:function(){return"1"===e.fetchLocal(e.darkModeLK)}},{key:"storeLocal",value:function(e,t){window.localStorage.setItem(e,JSON.stringify(t))}},{key:"fetchLocal",value:function(e){var t=window.localStorage.getItem(e);return null!==t?JSON.parse(t):null}},{key:"removeLocal",value:function(e){window.localStorage.removeItem(e)}}]),e}();function w(e,t,n){return S.apply(this,arguments)}function S(){return(S=s(f().mark((function e(t,n,r){var a,o;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,window.fetch(n,{method:t,headers:new window.Headers({"content-type":"application/json"}),body:r});case 3:if(200===(a=e.sent).status){e.next=6;break}throw a;case 6:return e.next=8,a.json();case 8:return(o=e.sent).requestSuccessful=!0,e.abrupt("return",o);case 13:return e.prev=13,e.t0=e.catch(0),e.t0.requestSuccessful=!1,e.next=18,e.t0.text();case 18:return e.t0.msg=e.sent,e.abrupt("return",e.t0);case 20:case"end":return e.stop()}}),e,null,[[0,13]])})))).apply(this,arguments)}function C(e,t){return F.apply(this,arguments)}function F(){return(F=s(f().mark((function e(t,n){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",w("POST",t,JSON.stringify(n)));case 1:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function T(e){return D.apply(this,arguments)}function D(){return(D=s(f().mark((function e(t){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",w("GET",t));case 1:case"end":return e.stop()}}),e)})))).apply(this,arguments)}h(k,"darkModeLK","darkMode"),h(k,"authCK","dexauth"),h(k,"pwKeyCK","sessionkey"),h(k,"popupsLK","popups"),h(k,"loggersLK","loggers"),h(k,"recordersLK","recorders"),h(k,"lastMarketLK","selectedMarket"),h(k,"depthZoomLK","depthZoom"),h(k,"lastMMMarketLK","mmMarket"),h(k,"optionsExpansionLK","mmOptsExpand"),h(k,"leftMarketDockLK","leftmarketdock"),h(k,"selectedAssetLK","selectedasset"),h(k,"notificationsLK","notifications"),h(k,"orderDisclaimerAckedLK","ordAck"),h(k,"lastCandleDurationLK","lastCandleDuration"),h(k,"localeSpecsKey","localeSpecsLK"),h(k,"localeKey","localeLK"),null===k.fetchLocal(k.darkModeLK)&&k.storeLocal(k.darkModeLK,"1"),null===k.fetchLocal(k.popupsLK)&&k.storeLocal(k.popupsLK,"1"),null===k.fetchLocal(k.leftMarketDockLK)&&k.storeLocal(k.leftMarketDockLK,"1");var I,A=function(e){return e[e.walletErr=0]="walletErr",e[e.walletAuthErr=1]="walletAuthErr",e[e.walletBalanceErr=2]="walletBalanceErr",e[e.dupeDEXErr=3]="dupeDEXErr",e[e.assetSupportErr=4]="assetSupportErr",e[e.registerErr=5]="registerErr",e[e.signatureErr=6]="signatureErr",e[e.zeroFeeErr=7]="zeroFeeErr",e[e.feeMismatchErr=8]="feeMismatchErr",e[e.feeSendErr=9]="feeSendErr",e[e.passwordErr=10]="passwordErr",e[e.emptyHostErr=11]="emptyHostErr",e[e.connectionErr=12]="connectionErr",e[e.acctKeyErr=13]="acctKeyErr",e[e.unknownOrderErr=14]="unknownOrderErr",e[e.orderParamsErr=15]="orderParamsErr",e[e.dbErr=16]="dbErr",e[e.authErr=17]="authErr",e[e.connectWalletErr=18]="connectWalletErr",e[e.missingWalletErr=19]="missingWalletErr",e[e.encryptionErr=20]="encryptionErr",e[e.decodeErr=21]="decodeErr",e[e.accountVerificationErr=22]="accountVerificationErr",e[e.accountProofErr=23]="accountProofErr",e[e.parseKeyErr=24]="parseKeyErr",e[e.marketErr=25]="marketErr",e[e.addressParseErr=26]="addressParseErr",e[e.addrErr=27]="addrErr",e[e.fileReadErr=28]="fileReadErr",e[e.unknownDEXErr=29]="unknownDEXErr",e[e.accountRetrieveErr=30]="accountRetrieveErr",e[e.accountDisableErr=31]="accountDisableErr",e[e.suspendedAcctErr=32]="suspendedAcctErr",e[e.existenceCheckErr=33]="existenceCheckErr",e[e.createWalletErr=34]="createWalletErr",e[e.activeOrdersErr=35]="activeOrdersErr",e[e.newAddrErr=36]="newAddrErr",e}({}),R="NO_PASS_ERROR_MSG",E="BUY",B="SELL",P="VERSION_NOT_SUPPORTED",L="NO_ASSET_WALLET",O="EXECUTED",M="BOOKED",q="CANCELING",N="PASSWORD_NOT_MATCH",W="UNKNOWN",V="SETTLING",U="CANCELED",_="REVOKED",j="NONE_SELECTED",H="API_ERROR",z="LOCKED",G="INVALID_ADDRESS_MSG",X="MARKET_ORDER",K="MATCH_STATUS_REDEMPTION_SENT",Q="MATCH_REDEMPTION_CONFIRMED",Y="MATCH_STATUS_REFUND_PENDING",J="ORDER_ACCELERATION_ERR_MSG",Z="DISCONNECTED",$="BROWSER_NTFN_ENABLED",ee="ORDER_BUTTON_BUY_BALANCE_ERROR",te="ORDER_BUTTON_SELL_BALANCE_ERROR",ne="ORDER_BUTTON_QTY_ERROR",re="ORDER_BUTTON_QTY_RATE_ERROR",ae="CREATE_ASSET_WALLET_MSG",oe="TRADING_TIER_UPDATED",se="INVALID_TIER_VALUE",ie="MATCH_BUFFER",ce="NO_PLACEMENTS",le="INVALID_VALUE",ue="NO_ZERO",de="BOTTYPE_BASIC_MM",he="BOTTYPE_ARB_MM",pe="BOTTYPE_SIMPLE_ARB",fe="CEXBALANCE_ERR",ve="PENDING",me="COMPLETE";function ge(e,t,n){return ye.apply(this,arguments)}function ye(){return(ye=s(f().mark((function e(t,n,r){var a;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r){e.next=5;break}if(!(a=k.fetchLocal(k.localeSpecsKey))||a.lang!==t||a.commitHash!==n){e.next=5;break}return I=k.fetchLocal(k.localeKey),e.abrupt("return");case 5:return e.next=7,C("/api/locale",t);case 7:I=e.sent,k.storeLocal(k.localeSpecsKey,{lang:t,commitHash:n}),k.storeLocal(k.localeKey,I);case 10:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function be(e,t){return function(e,t){return e.replace(/{{\s?([^{}\s]*)\s?}}/g,(function(e,n){return t[n]}))}(I[e],t||{})}function xe(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return ke(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ke(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e){throw e})),f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,i=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e){i=!0,o=e})),f:function(){try{s||null==n.return||n.return()}finally{if(i)throw o}}}}function ke(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=n.left&&e.pageX<=n.right&&e.pageY>=n.top&&e.pageY<=n.bottom}},{key:"layoutMetrics",value:function(e){var t=e.getBoundingClientRect(),n=document.documentElement,r=t.top+n.scrollTop,a=t.left+n.scrollLeft,o=e.offsetWidth,s=e.offsetHeight;return{bodyTop:r,bodyLeft:a,width:o,height:s,centerX:a+o/2,centerY:r+s/2}}},{key:"descendentMetrics",value:function(t,n){var r=e.layoutMetrics(t),a=e.layoutMetrics(n);return{bodyTop:a.bodyTop-r.bodyTop,bodyLeft:a.bodyLeft-r.bodyLeft,width:a.width,height:a.height,centerX:a.centerX-r.bodyLeft,centerY:a.centerY-r.bodyTop}}},{key:"empty",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n1?n-1:0),a=1;a1?n-1:0),a=1;a"),e),document.createElement("div"))}},{key:"idDescendants",value:function(t){var n,r={},a=xe(e.applySelector(t,"[id]"));try{for(a.s();!(n=a.n()).done;){var o=n.value;r[o.id]=o}}catch(e){a.e(e)}finally{a.f()}return r}},{key:"formatCoinValue",value:function(e,t){var n=a(Oe(e,t),2),r=n[0],o=n[1];return Number.isInteger(r)?Ae.format(r):function(e){return Le(Ee,2,e)}(o).format(r)}},{key:"conventionalCoinValue",value:function(e,t){return a(Oe(e,t),1)[0]}},{key:"formatRateFullPrecision",value:function(e,t,n,r){var a=e*(t.conventional.conversionFactor/n.conventional.conversionFactor)/Te,o=De-Math.floor(Math.log10(r))-Math.floor(Math.log10(t.conventional.conversionFactor)-Math.log10(n.conventional.conversionFactor));return o<=0?Ae.format(a):Pe(o).format(a)}},{key:"formatFourSigFigs",value:function(e,t){return function(e,t,n,r,a){var o,s;if(n>=1e3)return e.format(n);var i=t.format(n);return"number"!=typeof r||(null!==(o=null===(s=t.formatToParts(n).filter((function(e){return"fraction"===e.type}))[0])||void 0===s?void 0:s.value)&&void 0!==o?o:"").length<=r?i:Pe(r,void 0).format(n)}(Ae,Re,e,t)}},{key:"formatInt",value:function(e){return Ae.format(e)}},{key:"formatFullPrecision",value:function(e,t){var n=a(Oe(e,t),2),r=n[0];return Pe(n[1]).format(r)}},{key:"formatFiatConversion",value:function(e,t,n){if(!t||0===t)return be("UNAVAILABLE");var r=a(Oe(e,n),1)[0]*t;return Pe(2).format(r)}},{key:"languages",value:function(){return Ie}},{key:"formatFiatValue",value:function(e){return Pe(2).format(e)}},{key:"bestConversion",value:function(e,t,n){for(var r=function(e,t){var n,r=(h(n={},e.atomicUnit,1),h(n,e.conventional.unit,e.conventional.conversionFactor),n);if(e.denominations&&t){var a,o=xe(e.denominations);try{for(o.s();!(a=o.n()).done;){var s=a.value;t[s.unit]&&(r[s.unit]=s.conversionFactor)}}catch(e){o.e(e)}finally{o.f()}}return r}(t,n),a=[],o=function(t){return Math.abs(Math.log10(e/t[1])-1)},s=0,i=Object.entries(r);s0||u>0)&&u++,e>0&&(l+="".concat(e," ").concat(t," ")),u>=2},h=a(Xe(c,_e),2);if(t=h[0],c=h[1],d(t,"y"))return l;var p=a(Xe(c,je),2);if(n=p[0],c=p[1],d(n,"mo"))return l;var f=a(Xe(c,He),2);if(r=f[0],c=f[1],d(r,"d"))return l;var v=a(Xe(c,ze),2);if(o=v[0],c=v[1],d(o,"h"))return l;var m=a(Xe(c,Ge),2);if(s=m[0],c=m[1],d(s,"m"))return l;var g=a(Xe(c,1e3),2);return i=g[0],c=g[1],d(i,"s"),l||"0 s"}},{key:"disableMouseWheel",value:function(){for(var t=arguments.length,n=new Array(t),r=0;r=0?n:31536e7,o=a?Ne[a]:Ne.linear,s=(new Date).getTime(),i=n===e.Forever?Number.MAX_SAFE_INTEGER:s+n,c=i-s,l=1e3/30,u=s,this.endAnimation=!1;case 8:if(!(u0){for(;r.endsWith("0");)r=r.substring(0,r.length-1);r.endsWith(".")&&(r=r.substring(0,r.length-1))}return[e,r]}function Ze(e,t){var n=Math.floor(Math.log10(Math.abs(e)));return n>=3?[Math.round(e),e.toFixed(0)]:Je(e,Math.min(4-n,t))}function $e(e,t){var n=parseFloat((null!=e?e:"").replace(/,/g,""));return isNaN(n)?null!=t?t:0:n}function et(e,t,n){return en?n:e}function tt(e,t,n,r){return nt.apply(this,arguments)}function nt(){return(nt=s(f().mark((function e(t,n,r,a){var o,s;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,navigator.clipboard.writeText(t);case 3:e.next=8;break;case 5:e.prev=5,e.t0=e.catch(0),console.error("Unable to copy: ",e.t0);case 8:o=n.style.color,s=r.style.color,n.style.color=a,r.style.color=a,setTimeout((function(){n.style.color=o,r.style.color=s}),350);case 13:case"end":return e.stop()}}),e,null,[[0,5]])})))).apply(this,arguments)}var rt,at,ot,st,it=function(){function e(){i(this,e)}return d(e,[{key:"unload",value:function(){}}]),e}(),ct=function(e){return e[e.Disconnected=0]="Disconnected",e[e.Connected=1]="Connected",e[e.InvalidCert=2]="InvalidCert",e}({}),lt=function(e){return e[e.Approved=0]="Approved",e[e.Pending=1]="Pending",e[e.NotApproved=2]="NotApproved",e}({}),ut=function(e){return e[e.WalletDefault=0]="WalletDefault",e[e.UserAdded=1]="UserAdded",e[e.Discovered=2]="Discovered",e}({}),dt=2147483647;function ht(){return rt}function pt(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=b(e);if(t){var a=b(this).constructor;n=Reflect.construct(r,arguments,a)}else n=r.apply(this,arguments);return y(this,n)}}function ft(e){var t=[e.booleanOptTmpl,e.rangeOptTmpl,e.orderOptTmpl];ot=t[0],st=t[1],at=t[2]}var vt=new Intl.NumberFormat(Me.languages(),{minimumSignificantDigits:3,maximumSignificantDigits:3}),mt=d((function e(t,n,r){var a=this;i(this,e),h(this,"opt",void 0),h(this,"node",void 0),h(this,"tmpl",void 0),h(this,"on",void 0),this.opt=t;var o=this.node=at.cloneNode(!0),s=this.tmpl=Me.parseTemplate(o);s.optName.textContent=t.displayname,s.tooltip.dataset.tooltip=t.description,n?s.chainIcon.src=Me.logoPath(n):Me.hide(s.chainIcon),this.on=!1,Me.bind(o,"click",(function(){a.on||(a.on=!0,o.classList.add("selected"),r.enable())})),Me.bind(s.toggle,"click",(function(e){a.on&&(e.stopPropagation(),a.on=!1,o.classList.remove("selected"),r.disable())}))})),gt=function(e){g(n,e);var t=pt(n);function n(e,r,a,o){var s;if(i(this,n),h(v(s=t.call(this,e,r,{enable:function(){return s.enable()},disable:function(){return s.disable()}})),"control",void 0),h(v(s),"changed",void 0),h(v(s),"dict",void 0),s.dict=a,s.changed=function(){return o()},void 0===e.boolean)throw Error("not a boolean opt");var c=e.boolean,l=s.control=ot.cloneNode(!0);return s.tmpl.controls.appendChild(l),Me.parseTemplate(l).reason.textContent=c.reason,s.on=void 0!==a[e.key]?a[e.key]:e.default,s.on&&s.node.classList.add("selected"),s}return d(n,[{key:"store",value:function(){this.on===this.opt.default?delete this.dict[this.opt.key]:this.dict[this.opt.key]=this.on,this.changed()}},{key:"enable",value:function(){this.store()}},{key:"disable",value:function(){this.store()}}]),n}(mt),yt=function(e){g(n,e);var t=pt(n);function n(e,r,a,o){var s;if(i(this,n),h(v(s=t.call(this,e,r,{enable:function(){return s.enable()},disable:function(){return s.disable()}})),"handler",void 0),h(v(s),"x",void 0),h(v(s),"changed",void 0),h(v(s),"dict",void 0),s.dict=a,s.changed=o,void 0===e.xyRange)throw Error("not an xy range opt");var c=e.xyRange,l=a[e.key];return s.on=void 0!==l,s.on?(s.node.classList.add("selected"),s.x=l):s.x=e.default,s.handler=new bt(c,s.x,{changed:o,selected:function(){s.node.classList.add("selected")},settingsDict:a,settingsKey:e.key}),s.tmpl.controls.appendChild(s.handler.control),s}return d(n,[{key:"enable",value:function(){this.dict[this.opt.key]=this.x,this.changed()}},{key:"disable",value:function(){delete this.dict[this.opt.key],this.changed()}},{key:"setValue",value:function(e){this.handler.setValue(e),this.on=!0,this.node.classList.add("selected")}}]),n}(mt),bt=function(){function e(t,n,r){var a,o,s,c,l=this;i(this,e),h(this,"control",void 0),h(this,"range",void 0),h(this,"tmpl",void 0),h(this,"initVal",void 0),h(this,"settingsDict",void 0),h(this,"settingsKey",void 0),h(this,"x",void 0),h(this,"scrollingX",void 0),h(this,"y",void 0),h(this,"r",void 0),h(this,"roundX",void 0),h(this,"roundY",void 0),h(this,"disabled",void 0),h(this,"updated",void 0),h(this,"changed",void 0),h(this,"selected",void 0),h(this,"convert",void 0);var u=this.control=st.cloneNode(!0),d=this.tmpl=Me.parseTemplate(u);d.rangeLblStart.textContent=t.start.label,d.rangeLblEnd.textContent=t.end.label,d.xUnit.textContent=t.xUnit,d.yUnit.textContent=t.yUnit,this.range=t,this.initVal=n,this.settingsDict=r.settingsDict,this.settingsKey=null!==(a=r.settingsKey)&&void 0!==a?a:"",this.roundX=Boolean(r.roundX),this.roundY=Boolean(r.roundY),this.setDisabled(Boolean(r.disabled)),this.changed=null!==(o=r.changed)&&void 0!==o?o:function(){},this.selected=null!==(s=r.selected)&&void 0!==s?s:function(){},this.updated=null!==(c=r.updated)&&void 0!==c?c:function(){},this.convert=r.convert||function(e){return e};var p=d.slider,f=d.handle,v=t.end.x-t.start.x,m=t.end.y-t.start.y,g=function(e){return(e-t.start.x)/v};this.r=g(n),this.scrollingX=this.x=n,this.y=this.r*m+t.start.y,this.accept(this.scrollingX,{skipUpdate:!0});var y=function e(n){if(!l.disabled&&("change"===n.type||n.target!==d.xInput)){var r=d.xInput.value;if(r){var a=parseFloat(r);isNaN(a)||(l.scrollingX=xt(a,t.start.x,t.end.x),l.r=g(l.scrollingX),l.y=l.r*m+t.start.y,l.accept(l.scrollingX))}Me.hide(d.xInput),Me.show(d.x),Me.unbind(document,"click",e),l.changed()}};Me.bind(d.x,"click",(function(e){l.disabled||(Me.hide(d.x),Me.show(d.xInput),d.xInput.focus(),d.xInput.value=vt.format(l.scrollingX),Me.bind(document,"click",y),e.stopPropagation())})),Me.bind(d.xInput,"change",y);var b=function e(n){if(!l.disabled&&("change"===n.type||n.target!==d.yInput)){var r=d.yInput.value;if(r){var a=parseFloat(r);isNaN(a)||(l.y=xt(a,t.start.y,t.end.y),l.r=(l.y-t.start.y)/m,l.scrollingX=t.start.x+l.r*v,l.accept(l.scrollingX))}Me.hide(d.yInput),Me.show(d.y),Me.unbind(document,"click",e),l.changed()}};Me.bind(d.y,"click",(function(e){l.disabled||(Me.hide(d.y),Me.show(d.yInput),d.yInput.focus(),d.yInput.value=vt.format(l.y),Me.bind(document,"click",b),e.stopPropagation())})),Me.bind(d.yInput,"change",b),Me.bind(f,"mousedown",(function(e){if(!l.disabled&&0===e.button){e.preventDefault(),e.stopPropagation(),l.selected();var n=e.pageX,r=p.clientWidth-f.offsetWidth,a=g(l.scrollingX)*r,o=function(e,o){e.preventDefault(),l.r=function(e){return Math.max(Math.min(a+(e.pageX-n),r),0)}(e)/r,l.scrollingX=l.r*v+t.start.x,l.y=l.r*m+t.start.y,l.accept(l.scrollingX,{skipChange:!o})};Me.bind(document,"mousemove",o),Me.bind(document,"mouseup",(function e(t){o(t,!0),Me.unbind(document,"mousemove",o),Me.unbind(document,"mouseup",e),l.changed()}))}})),Me.bind(d.sliderBox,"click",(function(e){if(!l.disabled&&0===e.button){var n=e.pageX,r=Me.layoutMetrics(d.slider);l.r=xt((n-r.bodyLeft)/r.width,0,1),l.scrollingX=l.r*v+t.start.x,l.y=l.r*m+t.start.y,l.accept(l.scrollingX)}}))}return d(e,[{key:"setDisabled",value:function(e){this.control.classList.toggle("disabled",e),this.disabled=e}},{key:"setXLabel",value:function(e){this.tmpl.x.textContent=e}},{key:"setYLabel",value:function(e){this.tmpl.y.textContent=e}},{key:"accept",value:function(e,t){var n,r=this.tmpl;this.roundX&&(e=Math.round(e)),this.roundY&&(this.y=Math.round(this.y)),r.x.textContent=vt.format(e),r.y.textContent=vt.format(this.y),this.roundY&&(r.y.textContent="".concat(this.y));var a=xt(this.r,0,1);r.handle.style.left="calc(".concat(100*a,"% - ").concat(14*a,"px)"),this.x=e,this.scrollingX=e,t=null!==(n=t)&&void 0!==n?n:{},this.settingsDict&&(this.settingsDict[this.settingsKey]=this.convert(this.x,this.y)),t.skipUpdate||(this.updated(e,this.y),t.skipChange||this.changed())}},{key:"setValue",value:function(e,t){var n=this.range;this.r=(e-n.start.x)/(n.end.x-n.start.x),this.y=n.start.y+this.r*(n.end.y-n.start.y),this.accept(e,{skipUpdate:t})}},{key:"modified",value:function(){return this.x!==this.initVal}},{key:"reset",value:function(){this.setValue(this.initVal,!0)}}]),e}(),xt=function(e,t,n){return en?n:e};function kt(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return wt(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?wt(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,i=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){i=!0,o=e},f:function(){try{s||null==n.return||n.return()}finally{if(i)throw o}}}}function wt(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=Et||n.side===Lt&&n.status>=Bt?e+t(n):e}),0)}function Ht(e){var t;if(null===(t=e.matches)||void 0===t||!t.length)return be(X);var n=Me.formatCoinValue(ht().conventionalRate(e.baseID,e.quoteID,zt(e)));return e.matches.length>1&&(n="~ "+n),n}function zt(e){var t;if(null===(t=e.matches)||void 0===t||!t.length)return 0;var n,r=0,a=0,o=kt(e.matches);try{for(o.s();!(n=o.n()).done;){var s=n.value;a+=s.qty,r+=s.rate*s.qty}}catch(e){o.e(e)}finally{o.f()}return r/a}function Gt(e,t){return e*t/Mt}function Xt(e){return be("MATCH_STATUS_REVOKED",{status:be(e)})}function Kt(e){return e.type===St&&1===e.tif&&e.status=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e){throw e})),f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,i=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e){i=!0,o=e})),f:function(){try{s||null==n.return||n.return()}finally{if(i)throw o}}}}function Jt(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);nh||(o.fillText(e.txt,n,p),i>=c&&ii.y(t)-3-7)){var a=o.measureText(e.txt);s(o,d,r-7-3,a.width+6,23,3),o.fillText(e.txt,d+3,r+2),c>=l&&c=h&&g.push([C.rate,w]),!C.epoch)for(k+=C.qty,m.push([C.rate,k]),x.buyBase+=C.qty,x.buyQuote+=C.qty*C.rate;p.length&&mn(p[0].rate,C.rate);){var F=p.shift();F&&v.push({rate:F.rate,qty:C.epoch?w:k,sell:C.sell,active:F.active})}}var T=m.length?pn(m)[1]:0;m.push([h,T]);var D=g.length?pn(g)[1]:0;g.push([h,D]),w=k=0;for(var I=0;I=A},B=e.theme.sellLine;Ad||Pthis.data.candles.length)return;this.numToShow=this.zoomLevels[t+1]}this.draw()}},{key:"render",value:function(){var e,t=this,n=this.data;if(n&&this.visible&&0!==this.canvas.width){var r=n.ms,a=this.mousePos,o=n.candles||[],s=Math.min(this.numToShow,o.length),i=o.slice(o.length-s);if(this.clear(),0!==s){var c,l=function(e){return yn(e.endStamp,r)},u=function(e){return l(e)+r},d=function(e){return l(e)+.2*r},h=.6*r,p=i[0],f=i[s-1],v=[p.highRate,p.lowRate,p.matchVolume],m=v[0],g=v[1],y=v[2],b=Yt(i);try{for(b.s();!(c=b.n()).done;){var x=c.value;x.highRate>m&&(m=x.highRate),x.lowRatey&&(y=x.matchVolume)}}catch(e){b.e(e)}finally{b.f()}m+=.1*(m-g);var k=l(p),w=u(f);w+=.05*(w-k);var S=this.market.ratestep,C=new ln(k,w,g,m);g===m&&(C.y.min-=S,C.y.max+=S),this.dataExtents=C;var F=null;a&&this.plotRegion.plot(new ln(C.x.min,C.x.max,0,1),(function(e,n){var o,s=yn(n.unx(a.x),r),c=Yt(i);try{for(c.s();!(o=c.n()).done;){var u=o.value;if(l(u)===s){F=u,e.fillStyle=t.theme.gridLines,e.fillRect(n.x(l(u)),n.y(0),n.w(r),n.h(1));break}}}catch(e){c.e(e)}finally{c.f()}}));var T=this.rateConversionFactor,D=(null===(e=ht().assets[this.market.baseid])||void 0===e?void 0:e.unitInfo.conventional.unit)||this.market.basesymbol.toUpperCase(),I=function(e,t,n,r){var a=e[0],o=e[e.length-1],s=yn(a.endStamp,t),i=yn(o.endStamp,t)+t,c=i-s,l=Math.min(e.length,n/100),u=yn(c/l,t);if(0===u)return console.error("zero tick",t,c,l),{lbls:[]};var d=s,h=(new Date).getTimezoneOffset(),p=function(e){return(e-=6e4*h)-e%864e5},f=p(s),v=0;p(a.endStamp)===p(o.endStamp)&&(f=0);var m,g=[];for(m=t<864e5?function(e,t){return p(t)!==f?"".concat(hn[e.getMonth()]).concat(e.getDate()," ").concat(e.getHours(),":").concat(String(e.getMinutes()).padStart(2,"0")):"".concat(e.getHours(),":").concat(String(e.getMinutes()).padStart(2,"0"))}:function(e){var t=e.getFullYear();return t!==v?"".concat(hn[e.getMonth()]).concat(e.getDate()," '").concat(String(t).slice(2,4)):"".concat(hn[e.getMonth()]).concat(e.getDate())};d<=i;){var y=new Date(d);g.push({val:d,txt:m(y,d)}),f=p(d),v=y.getFullYear(),d+=u}return{lbls:g}}(i,r,this.plotRegion.width());this.plotXGrid(I,k,w);var A=this.makeYLabels(this.candleRegion,S,D,(function(e){return Me.formatFourSigFigs(e/T)}));this.plotYGrid(this.candleRegion,A,this.dataExtents.y.min,this.dataExtents.y.max);var R=new ln(k,w,0,y);if(this.volumeRegion.plot(R,(function(e,n){e.fillStyle=t.theme.gridBorder;var r,a=Yt(i);try{for(a.s();!(r=a.n()).done;){var o=r.value;e.fillRect(n.x(d(o)),n.y(0),n.w(h),n.h(o.matchVolume))}}catch(e){a.e(e)}finally{a.f()}})),this.candleRegion.plot(C,(function(e,n){e.lineWidth=1;var r,a=Yt(i);try{for(a.s();!(r=a.n()).done;){var o=r.value,s=o.startRate>o.endRate,c=[n.x(d(o)),n.y(o.startRate),n.w(h),n.h(o.endRate-o.startRate)],l=c[0],u=c[1],p=c[2],f=c[3],v=[n.y(o.highRate),n.y(o.lowRate),p/2+l],m=v[0],g=v[1],y=v[2];e.strokeStyle=s?t.theme.sellLine:t.theme.buyLine,e.fillStyle=s?t.theme.sellFill:t.theme.buyFill,e.beginPath(),e.moveTo(y,m),e.lineTo(y,g),e.stroke(),e.fillRect(l,u,p,f),e.strokeRect(l,u,p,f)}}catch(e){a.e(e)}finally{a.f()}})),this.plotXLabels(I,k,w,[]),this.plotYLabels(A,this.dataExtents.y.min,this.dataExtents.y.max,D),F){var E=this.xRegion.extents.y;this.xRegion.plot(new ln(C.x.min,C.x.max,E.min,E.max),(function(e,n){if(F){t.applyLabelStyle();var r="".concat(new Date(l(F)).toLocaleString()," - ").concat(new Date(u(F)).toLocaleString()),a=e.measureText(r).width+50,o=n.x((l(F)+u(F))/2),s=o-a/2,i=t.xRegion.extents.x;si.max&&(s=i.max-a),o=s+a/2;var c=E.min+(t.xRegion.height()-16)/2;e.fillStyle=t.theme.legendFill,e.strokeStyle=t.theme.gridBorder;var d=[s-25,c-2,a+50,20];e.fillRect.apply(e,d),e.strokeRect.apply(e,d),t.applyLabelStyle(),e.fillText(r,o,t.xRegion.extents.midY,a)}}))}this.reporters.mouse(F)}}else this.renderScheduled=!0}},{key:"setCandles",value:function(e,t,n,r){if(this.data=e,e.candles){this.market=t;var a=[r.conventional.conversionFactor,n.conventional.conversionFactor],o=a[0],s=a[1];this.rateConversionFactor=Mt*o/s;var i=25;this.zoomLevels=[];for(var c=Math.max(e.candles.length,1e3);i150&&(a=150),o>100&&(o=100);var s=(n-a)/2,i=(r-o)/2;if(e.message){this.fontSize=et(.15*o,10,14),this.applyLabelStyle(this.fontSize);var c=.5*this.fontSize,l=this.fontSize/2+c;i-=l,this.msgRegion=new un(this.ctx,new ln(0,n,i+o,i+o+2*l))}this.region=new un(this.ctx,new ln(s,s+a,i,i+o))}},{key:"drawValues",value:function(e){var t=this;if(this.region){this.clear();var n=function(e){return"hsl(".concat(e,", 35%, 50%)")},r=this.region,a=this.msgRegion,o=this.canvas,s=o.width,i=o.height,c=this.opts,l=c.backgroundColor,u=c.message,d=this.colorShift,h=this.ctx;l&&(h.fillStyle=!0===l?k.isDark()?"#0a1e34":"#f0f0f0":l,h.fillRect(0,0,s,i)),r.plot(new ln(0,1,-1,1),(function(t,r){t.lineWidth=4,t.lineCap="round";var a=d+(new Date).getTime()%2e3/2e3*360,o=t.createLinearGradient(r.x(0),0,r.x(1),0);o.addColorStop(0,n(a)),t.strokeStyle=o,t.beginPath(),t.moveTo(r.x(0),r.y(e[0]));for(var s=1;sn.x.min&&tn.y.min}},{key:"translator",value:function(e){var t=this.extents,n=e.x.min,r=e.y.min,a=e.yRange,o=e.xRange,s=t.x.min,i=t.x.max-s,c=t.y.max,l=c-t.y.min,u=i/o,d=l/a;return{x:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e){return(e-n)*u+s})),y:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e){return c-(e-r)*d})),unx:function(e){return(e-s)/u+n},uny:function(e){return r-(e-c)/d},w:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e){return e/o*i})),h:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e){return-e/a*l}))}}},{key:"clear",value:function(){var e=this.extents;this.context.clearRect(e.x.min,e.y.min,e.xRange,e.yRange)}},{key:"plot",value:function(e,t,n){var r=this.context,a=this.extents;r.save(),n||(r.beginPath(),r.rect(a.x.min,a.y.min,a.xRange,a.yRange),r.clip());var o=this.translator(e);t(this.context,o),r.restore()}}]),e}();function dn(e,t,n,r,a,o,s,i){i=i||Me.formatFourSigFigs;var c=t/a,l=r-n;if(c<1||l<=0)return{lbls:[]};for(var u=l/c,d=u+o-u%o,h=n+d-n%d,p=Math.max(Math.abs(r),Math.abs(n)),f=Math.round(Math.log10(p/d))+2,v=[],m=0;hm&&(m=y),{widest:m,lbls:v}}var hn=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"];function pn(e){return e[e.length-1]}function fn(e,t,n,r,a,o){e.beginPath(),e.moveTo(t,n),e.lineTo(r,a),o||e.stroke()}function vn(e,t,n,r,a){e.fillStyle=r,e.beginPath(),e.arc(t,n,a,0,$t),e.fill()}function mn(e,t){return gn(e,t,1e-8)}function gn(e,t,n){return Math.abs(e-t)=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,i=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){i=!0,o=e},f:function(){try{s||null==n.return||n.return()}finally{if(i)throw o}}}}function xn(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=0?l+s/a*75:l-Math.min(l,s/c*l);e.scorePointer.style.left="".concat(u,"%"),e.scoreMin.textContent=String(c),e.scoreMax.textContent=String(a);var d=Nn(s,a);e.limitBonus.textContent=d.toFixed(1);var h,p=bn(Me.applySelector(e.scoreTray,".penalty-marker"));try{for(p.s();!(h=p.n()).done;)h.value.remove()}catch(e){p.e(e)}finally{p.f()}if(i>1)for(var f=l/i,v=1;v0?e.scoreData.classList.add("positive"):e.scoreData.classList.add("negative")}}]),e}();function Sn(e){var t=e.weakStrength,n=e.targetTier,r=e.effectiveTier;if(r>n){var a=r-n;return t>=a?n:n+(a-t)}return r}var Cn,Fn,Tn,Dn,In,An,Rn,En,Bn,Pn,Ln,On,Mn=function(e,t,n){var r,a,o=e.qty-e.filled;if(1===e.type)return o;if(e.sell)return o*e.rate/Mt;var s=n||(null==t||null===(r=t.spot)||void 0===r?void 0:r.rate)||0;return t?s&&((null==t||null===(a=t.spot)||void 0===a?void 0:a.bookVolume)||0)>0?o*Mt/s:t.lotsize:0};function qn(e,t,n){return 3===e.type?0:function(e,t,n){var r;if(e.status!==Dt)return 0;var a=Mn(e,t,n);return function(e,t){return e.type===Ft||e.tif===Tt||0!==t&&(e.sell?e.ratet)}(e,n||(null===(r=t.spot)||void 0===r?void 0:r.rate)||0)?2*a:a}(e,t,n)+function(e){return e.status!==It?0:Mn(e)}(e)+function(e){var t,n=0,r=bn(e.matches||[]);try{for(r.s();!(t=r.n()).done;){var a=t.value;if(a.side===Ot){if(a.status>Et)continue}else if(a.status>Rt)continue;n+=a.qty}}catch(e){r.e(e)}finally{r.f()}return n}(e)}function Nn(e,t){return e>0?1+e/t*(kn-1):1}var Wn="TakerFoundMakerRedemption:";function Vn(e){return e.startsWith(Wn)?[e.substring(Wn.length),!0]:42===e.length?[e,!0]:[e,!1]}var Un=(h(Cn={},0,(function(e){var t=a(Vn(e),2),n=t[0];return t[1]?"https://etherscan.io/address/".concat(n):"https://etherscan.io/tx/".concat(n)})),h(Cn,1,(function(e){var t=a(Vn(e),2),n=t[0];return t[1]?"https://sepolia.etherscan.io/address/".concat(n):"https://sepolia.etherscan.io/tx/".concat(n)})),h(Cn,2,(function(e){var t=a(Vn(e),2),n=t[0];return t[1]?"https://etherscan.io/address/".concat(n):"https://etherscan.io/tx/".concat(n)})),Cn),_n=(h(Fn={},0,(function(e){var t=a(Vn(e),2),n=t[0];return t[1]?"https://polygonscan.com/address/".concat(n):"https://polygonscan.com/tx/".concat(n)})),h(Fn,1,(function(e){var t=a(Vn(e),2),n=t[0];return t[1]?"https://amoy.polygonscan.com/address/".concat(n):"https://amoy.polygonscan.com/tx/".concat(n)})),h(Fn,2,(function(e){var t=a(Vn(e),2),n=t[0];return t[1]?"https://polygonscan.com/address/".concat(n):"https://polygonscan.com/tx/".concat(n)})),Fn),jn={42:(Tn={},h(Tn,0,(function(e){var t=a(e.split(":"),2),n=t[0],r=t[1];return void 0!==r?"https://explorer.dcrdata.org/tx/".concat(n,"/out/").concat(r):"https://explorer.dcrdata.org/tx/".concat(n)})),h(Tn,1,(function(e){var t=a(e.split(":"),2),n=t[0],r=t[1];return void 0!==r?"https://testnet.dcrdata.org/tx/".concat(n,"/out/").concat(r):"https://testnet.dcrdata.org/tx/".concat(n)})),h(Tn,2,(function(e){var t=a(e.split(":"),2),n=t[0],r=t[1];return void 0!==r?"http://127.0.0.1:17779/tx/".concat(n,"/out/").concat(r):"https://127.0.0.1:17779/tx/".concat(n)})),Tn),0:(Dn={},h(Dn,0,(function(e){return"https://mempool.space/tx/".concat(e.split(":")[0])})),h(Dn,1,(function(e){return"https://mempool.space/testnet/tx/".concat(e.split(":")[0])})),h(Dn,2,(function(e){return"https://mempool.space/tx/".concat(e.split(":")[0])})),Dn),2:(In={},h(In,0,(function(e){return"https://ltc.bitaps.com/".concat(e.split(":")[0])})),h(In,1,(function(e){return"https://sochain.com/tx/LTCTEST/".concat(e.split(":")[0])})),h(In,2,(function(e){return"https://ltc.bitaps.com/".concat(e.split(":")[0])})),In),20:(An={},h(An,0,(function(e){return"https://digiexplorer.info/tx/".concat(e.split(":")[0])})),h(An,1,(function(e){return"https://testnetexplorer.digibyteservers.io/tx/".concat(e.split(":")[0])})),h(An,2,(function(e){return"https://digiexplorer.info/tx/".concat(e.split(":")[0])})),An),60:Un,60001:Un,60002:Un,3:(Rn={},h(Rn,0,(function(e){return"https://dogeblocks.com/tx/".concat(e.split(":")[0])})),h(Rn,1,(function(e){return"https://blockexplorer.one/dogecoin/testnet/tx/".concat(e.split(":")[0])})),h(Rn,2,(function(e){return"https://dogeblocks.com/tx/".concat(e.split(":")[0])})),Rn),5:(En={},h(En,0,(function(e){return"https://blockexplorer.one/dash/mainnet/tx/".concat(e.split(":")[0])})),h(En,1,(function(e){return"https://blockexplorer.one/dash/testnet/tx/".concat(e.split(":")[0])})),h(En,2,(function(e){return"https://blockexplorer.one/dash/mainnet/tx/".concat(e.split(":")[0])})),En),133:(Bn={},h(Bn,0,(function(e){return"https://zcashblockexplorer.com/transactions/".concat(e.split(":")[0])})),h(Bn,1,(function(e){return"https://blockexplorer.one/zcash/testnet/tx/".concat(e.split(":")[0])})),h(Bn,2,(function(e){return"https://zcashblockexplorer.com/transactions/".concat(e.split(":")[0])})),Bn),147:(Pn={},h(Pn,0,(function(e){return"https://explorer.zcl.zelcore.io/tx/".concat(e.split(":")[0])})),h(Pn,2,(function(e){return"https://explorer.zcl.zelcore.io/tx/".concat(e.split(":")[0])})),Pn),136:(Ln={},h(Ln,0,(function(e){return"https://explorer.firo.org/tx/".concat(e.split(":")[0])})),h(Ln,1,(function(e){return"https://testexplorer.firo.org/tx/".concat(e.split(":")[0])})),h(Ln,2,(function(e){return"https://explorer.firo.org/tx/".concat(e.split(":")[0])})),Ln),145:(On={},h(On,0,(function(e){return"https://bch.loping.net/tx/".concat(e.split(":")[0])})),h(On,1,(function(e){return"https://tbch4.loping.net/tx/".concat(e.split(":")[0])})),h(On,2,(function(e){return"https://bch.loping.net/tx/".concat(e.split(":")[0])})),On),966:_n,966001:_n,966002:_n,966003:_n,966004:_n};function Hn(e){return e.startsWith(Wn)?be("TAKER_FOUND_MAKER_REDEMPTION",{makerAddr:e.substring(Wn.length)}):e}function zn(e,t){var n=ht().user.net,r=jn[function(e){var t=ht().user.assets[e];return t.token?t.token.parentID:e}(e)];if(r){var a=r[n];a&&(t.classList.remove("plainlink"),t.classList.add("subtlelink"),t.href=a(t.dataset.explorerCoin||""))}}function Gn(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function Xn(e){for(var t=1;te.length)&&(t=e.length);for(var n=0,r=new Array(t);n=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,i=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){i=!0,o=e},f:function(){try{s||null==n.return||n.return()}finally{if(i)throw o}}}}(Me.applySelector(e,"[data-cex-logo]"));try{for(a.s();!(r=a.n()).done;){var o=r.value;Me.show(o)}}catch(e){a.e(e)}finally{a.f()}}function cr(e,t,n,r){var a=ht().fiatRatesMap[t],o=ht().fiatRatesMap[n],s=ht().assets[t].unitInfo.conventional.conversionFactor,i=ht().assets[n].unitInfo.conventional.conversionFactor;return a&&o?e*a/o*i/s:r?e*r.rate/Mt:i}var lr=function(e){g(s,e);var t,n,o=(t=s,n=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}(),function(){var e,r=b(t);if(n){var a=b(this).constructor;e=Reflect.construct(r,arguments,a)}else e=r.apply(this,arguments);return y(this,e)});function s(e){var t;return i(this,s),h(v(t=o.call(this,e,{resize:function(){return t.resized()},click:function(){},zoom:function(){}})),"cfg",void 0),h(v(t),"loadedCEX",void 0),h(v(t),"cexLogo",void 0),t}return d(s,[{key:"resized",value:function(){this.render()}},{key:"draw",value:function(){}},{key:"setMarket",value:function(e){var t=this;this.cfg=e;var n=this.loadedCEX,r=this.cfg.cexName;r&&r!==n&&(this.loadedCEX=r,this.cexLogo=new Image,Me.bind(this.cexLogo,"load",(function(){t.render()})),this.cexLogo.src=rr[r||""].logo),this.render()}},{key:"render",value:function(){var e=this,t=this.ctx,n=this.canvas,o=this.theme,s=this.cfg;if(0!==n.width&&s){var i=s.dict,c=i.buyPlacements,l=i.sellPlacements,u=i.profit,d=s.baseFiatRate,h=s.botType;if(h!==nr){this.clear();var p=function(n,r,a,o,s){t.save(),t.setLineDash([3,5]),t.lineWidth=1.5,t.strokeStyle=s,e.line(n,r,a,o),t.restore()},f=h===er,v=n.width/2,m=a(f?[v,v]:[.48*n.width,.52*n.width],2),g=m[0],y=m[1],b=c.reduce((function(e,t){return e+t.lots}),0),x=l.reduce((function(e,t){return e+t.lots}),0),k=Math.max(b,x),w=0,S=0;if(f){var C=c.reduce((function(e,t){return Math.max(e,t.gapFactor)}),0),F=l.reduce((function(e,t){return Math.max(e,t.gapFactor)}),0);w=Math.max(C,F)}else{var T=[].concat(r(c),r(l)),D=T.reduce((function(e,t){return e+t.gapFactor}),0)/T.length;S=.01*(1+D),w=Math.min(10,Math.max(c.length,l.length))*S}var I=u+w,A=Math.max(1.05*I,.155),R=k*d,E=.2+.7*Math.log(et(R,0,1e6))/Math.log(1e6),B=new un(t,new ln(0,n.width,0,n.height));f?p(v,0,v,n.height,o.gapLine):B.plot(new ln(0,1,0,1),(function(t,n){var r=[n.y(0),n.y(1)],a=r[0],s=r[1];p(g,a,g,s,o.gapLine),p(y,a,y,s,o.gapLine);var i=n.y(.95);t.drawImage(e.cexLogo,v-8,i,16,16),e.applyLabelStyle(18),t.fillText("δ",v,i+29)}));var P=function(e,r){if(null!=r&&r.length){var s=a(e?[0,g]:[y,n.width],2),i=s[0],c=s[1],l=new un(t,new ln(i,c,n.height*(1-E),n.height)),d=a(e?[-A,0]:[0,A],2),h=d[0],p=d[1];l.plot(new ln(h,p,0,k),(function(t,a){t.lineWidth=2.5,t.strokeStyle=e?o.buyLine:o.sellLine,t.fillStyle=e?o.buyFill:o.sellFill,t.beginPath();var s=e?-1:1,i=r[0],c=a.y(0),l=a.x((f?i.gapFactor:u+S)*s);t.moveTo(l,c);for(var d=0,h=0;h0,this.baseFeeUI=f,this.baseFeeTicker=f.conventional.unit,this.baseFeeSymbol=v,this.baseFeeFactor=this.baseFeeUI.conventional.conversionFactor;var g=ht().assets[a],y=g.token,b=g.symbol,x=g.unitInfo;this.quoteSymbol=b,this.quoteTicker=x.conventional.unit,this.qui=x,this.quoteFactor=x.conventional.conversionFactor,this.quoteToken=y;var k=this.quoteFeeID=y?y.parentID:a,w=ht().assets[this.quoteFeeID],S=w.unitInfo,C=w.symbol,F=w.wallet;this.quoteIsAccountLocker=(16384&F.traits)>0,this.quoteFeeUI=S,this.quoteFeeTicker=S.conventional.unit,this.quoteFeeSymbol=C,this.quoteFeeFactor=this.quoteFeeUI.conventional.conversionFactor,this.id=ur(n,r,a),this.mktID="".concat(l,"_").concat(b);var T=ht().exchanges[n].markets[this.mktID].lotsize;this.lotSize=T,this.lotSizeConv=T/u.conventional.conversionFactor,this.quoteLot=cr(T,r,a),this.quoteLotConv=this.quoteLot/x.conventional.conversionFactor,this.baseFeeFiatRate=ht().fiatRatesMap[d],this.quoteFeeFiatRate=ht().fiatRatesMap[k],t.arbMarketMakingConfig?(this.botType=tr,this.baseLots=t.arbMarketMakingConfig.sellPlacements.reduce(pr,0),this.quoteLots=t.arbMarketMakingConfig.buyPlacements.reduce(pr,0),this.nBuyPlacements=t.arbMarketMakingConfig.buyPlacements.length,this.nSellPlacements=t.arbMarketMakingConfig.sellPlacements.length):t.simpleArbConfig?(this.botType=nr,this.baseLots=t.uiConfig.simpleArbLots,this.quoteLots=t.uiConfig.simpleArbLots):t.basicMarketMakingConfig&&(this.botType=er,this.baseLots=t.basicMarketMakingConfig.sellPlacements.reduce(pr,0),this.quoteLots=t.basicMarketMakingConfig.buyPlacements.reduce(pr,0),this.nBuyPlacements=t.basicMarketMakingConfig.buyPlacements.length,this.nSellPlacements=t.basicMarketMakingConfig.sellPlacements.length)}var t;return d(e,[{key:"initialize",value:(t=s(f().mark((function e(t){var n,r,a,o,s,i,c,l,u,d;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=this.host,r=this.baseID,a=this.quoteID,o=this.lotSizeConv,s=this.quoteLotConv,i=this.cexName,e.next=3,ar.report(n,r,a);case 3:if(c=e.sent,l=this.marketReport=c.report,this.lotSizeUSD=o*l.baseFiatRate,this.quoteLotUSD=s*l.quoteFiatRate,this.proj=this.projectedAllocations(),!i){e.next=17;break}return u=t[r]=t[r]||ar.cexBalance(i,r),d=t[a]=t[a]||ar.cexBalance(i,a),e.next=13,u;case 13:return this.cexBaseBalance=e.sent,e.next=16,d;case 16:this.cexQuoteBalance=e.sent;case 17:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})},{key:"status",value:function(){var e=this.baseID,t=this.quoteID,n=ht().mmStatus.bots.find((function(n){return n.config.baseID===e&&n.config.quoteID===t}));return n?{botCfg:n.config,running:n.running,runStats:n.runStats}:{botCfg:{},running:!1,runStats:{}}}},{key:"adjustedBalances",value:function(){var e=this.baseID,t=this.quoteID,n=this.baseFeeID,r=this.quoteFeeID,a=this.cexBaseBalance,o=this.cexQuoteBalance,s=this.baseFactor,i=this.quoteFactor,c=this.baseFeeFactor,l=this.quoteFeeFactor,u=[ht().walletMap[e],ht().walletMap[t]],d=u[0],h=u[1],p=[or(e),or(t)],f=p[0],v=p[1],m=((null==a?void 0:a.available)||0)-f.cex.avail,g=((null==o?void 0:o.available)||0)-v.cex.avail,y=d.balance.available-f.dex.avail,b=h.balance.available-v.dex.avail,x=y+m,k=b+g,w=n===e?d:ht().walletMap[n],S=r===t?h:ht().walletMap[r],C=x,F=y,T=m;if(n!==e){var D=or(e);C=(F=w.balance.available-D.dex.total)+(T=((null==a?void 0:a.available)||0)-D.cex.total)}var I=k,A=b,R=g;if(r!==t){var E=or(t);I=(A=S.balance.available-E.dex.total)+(R=((null==o?void 0:o.available)||0)-E.cex.total)}return{baseAvail:x/s,quoteAvail:k/i,dexBaseAvail:y/s,dexQuoteAvail:b/i,cexBaseAvail:m/s,cexQuoteAvail:g/i,baseFeeAvail:C/c,quoteFeeAvail:I/l,dexBaseFeeAvail:F/c,dexQuoteFeeAvail:A/l,cexBaseFeeAvail:T/c,cexQuoteFeeAvail:R/l}}},{key:"feesAndCommit",value:function(){var e=this.baseID,t=this.quoteID,n=this.marketReport,r=n.baseFees,a=n.quoteFees,o=this.lotSize,s=this.baseLots,i=this.quoteLots,c=this.baseFeeID,l=this.quoteFeeID,u=this.baseIsAccountLocker,d=this.quoteIsAccountLocker,h=this.cfg.uiConfig,p=h.baseConfig,f=h.quoteConfig;return gr(e,t,r,a,o,s,i,c,l,u,d,p.orderReservesFactor,f.orderReservesFactor)}},{key:"projectedAllocations",value:function(){var e=this.cfg.uiConfig,t=e.quoteConfig,n=e.baseConfig,r=this.baseFactor,a=this.quoteFactor,o=this.baseID,s=this.quoteID,i=this.lotSizeConv,c=this.quoteLotConv,l=this.baseFeeFactor,u=this.quoteFeeFactor,d=this.baseFeeID,h=this.quoteFeeID,p=this.baseToken,f=this.quoteToken,v=this.cexName,m=this.feesAndCommit(),g=m.commit,y=m.fees,b={book:0,bookingFees:0,swapFeeReserves:0,cex:0,orderReserves:0,slippageBuffer:0},x={book:0,bookingFees:0,swapFeeReserves:0,cex:0,orderReserves:0,slippageBuffer:0};b.book=g.dex.base.lots*i,x.book=g.cex.base.lots*c,b.orderReserves=Math.max(g.cex.base.val,g.dex.base.val)*n.orderReservesFactor/r,x.orderReserves=Math.max(g.cex.quote.val,g.dex.quote.val)*t.orderReservesFactor/a,v&&(b.cex=g.cex.base.lots*i,x.cex=g.cex.quote.lots*c),b.bookingFees=y.base.bookingFees/l,x.bookingFees=y.quote.bookingFees/u,p&&(b.swapFeeReserves=y.base.tokenFeesPerSwap*n.swapFeeN/l),f&&(x.swapFeeReserves=y.quote.tokenFeesPerSwap*t.swapFeeN/u),x.slippageBuffer=(x.book+x.cex+x.orderReserves)*t.slippageBufferFactor;var k={},w=function(e,t){var n;k[e]=(null!==(n=k[e])&&void 0!==n?n:0)+t};return w(o,Math.round((b.book+b.cex+b.orderReserves)*r)),w(d,Math.round((b.bookingFees+b.swapFeeReserves)*l)),w(s,Math.round((x.book+x.cex+x.orderReserves+x.slippageBuffer)*a)),w(h,Math.round((x.bookingFees+x.swapFeeReserves)*u)),{qProj:x,bProj:b,alloc:k}}},{key:"fundingState",value:function(){var e=this.proj,t=e.bProj,n=e.qProj,r=this.baseID,a=this.quoteID,o=this.baseFeeID,s=this.quoteFeeID,i=this.cfg.uiConfig.cexRebalance,c=this.cexName,l=this.adjustedBalances(),u=l.baseAvail,d=l.quoteAvail,h=l.dexBaseAvail,p=l.dexQuoteAvail,f=l.cexBaseAvail,v=l.cexQuoteAvail,m=l.dexBaseFeeAvail,g=l.dexQuoteFeeAvail,y=Boolean(c&&i),b=t.cex,x=[t.book,0,0],k=x[0],w=x[1],S=x[2];r===o?k+=t.bookingFees:S+=t.bookingFees+t.swapFeeReserves,y?w+=t.orderReserves:k+=t.orderReserves,r===s&&(y?w+=n.bookingFees+n.swapFeeReserves:k+=n.bookingFees+n.swapFeeReserves);var C=[n.book,n.cex,0,0],F=C[0],T=C[1],D=C[2],I=C[3];if(a===s?F+=n.bookingFees:I+=n.bookingFees+n.swapFeeReserves,y)D+=n.orderReserves+n.slippageBuffer;else{F+=n.orderReserves;var A=n.book+n.cex+n.orderReserves;F+=(n.book+n.orderReserves)/A*n.slippageBuffer,T+=n.cex/A*n.slippageBuffer}a===o&&(y?D+=t.bookingFees+t.swapFeeReserves:F+=t.bookingFees+t.swapFeeReserves);var R=h>=k,E=f>=b,B=p>=F,P=v>=T,L=k+b+w,O=F+T+D,M=R&&E&&u>=L,q=B&&P&&d>=O,N=m>=S,W=g>=I,V=M&&q&&N&&W,U=!V;return V||(U=u>=L&&d>=O&&N&&W&&y),{base:{dex:{avail:h,req:k,funded:R},cex:{avail:f,req:b,funded:E},transferable:w,fees:{avail:m,req:S,funded:N},fundedAndBalanced:M,fundedAndNotBalanced:!M&&u>=L&&y},quote:{dex:{avail:p,req:F,funded:B},cex:{avail:v,req:T,funded:P},transferable:D,fees:{avail:g,req:I,funded:W},fundedAndBalanced:q,fundedAndNotBalanced:!q&&d>=O&&y},fundedAndBalanced:V,fundedAndNotBalanced:U,starved:!V&&!U}}}]),e}(),vr=function(){function e(t,n){var r=this;i(this,e),h(this,"div",void 0),h(this,"page",void 0),h(this,"mkt",void 0),h(this,"startTime",void 0),h(this,"ticker",void 0),this.div=t,this.page=Me.parseTemplate(t),Me.bind(this.page.stopBttn,"click",(function(){return r.stop()})),Me.bind(this.page.runLogsBttn,"click",(function(){var e=r.mkt,t=e.baseID,a=e.quoteID,o=e.host,s=r.startTime;ht().loadPage("mmlogs",{baseID:t,quoteID:a,host:o,startTime:s,returnPage:n})}))}var t,n,a;return d(e,[{key:"stop",value:(a=s(f().mark((function e(){var t,n,r,a,o,s;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.page,n=this.mkt,r=n.host,a=n.baseID,o=n.quoteID,s=ht().loading(t.stopBttn),e.next=4,ar.stopBot({host:r,baseID:a,quoteID:o});case 4:s();case 5:case"end":return e.stop()}}),e,this)}))),function(){return a.apply(this,arguments)})},{key:"setMarket",value:(n=s(f().mark((function e(t,n,r){var a,o;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(a=ht().mmStatus.bots.find((function(e){var a=e.config;return a.baseID===n&&a.quoteID===r&&a.host===t}))){e.next=3;break}return e.abrupt("return");case 3:return o=new fr(a.config),e.next=6,o.initialize({});case 6:this.setBotMarket(o);case 7:case"end":return e.stop()}}),e,this)}))),function(e,t,r){return n.apply(this,arguments)})},{key:"setBotMarket",value:(t=s(f().mark((function e(t){var n,a,o,s,i,c,l,u,d,h,p,v,m,g,y,b,x,k,w,S,C,F,T,D,I,A;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:this.mkt=t,c=this.page,l=this.div,u=this.mkt,d=u.host,h=u.baseID,p=u.quoteID,v=u.baseFeeID,m=u.quoteFeeID,g=u.cexName,y=u.baseFeeSymbol,b=u.quoteFeeSymbol,x=u.baseFeeTicker,k=u.quoteFeeTicker,w=u.cfg,S=u.baseFactor,C=u.quoteFactor,sr(l,h,p,d),Me.setVis(v!==h,c.baseFeeReservesBox),Me.setVis(m!==p,c.quoteFeeReservesBox),Me.setVis.apply(Me,[Boolean(g)].concat(r(Me.applySelector(l,"[data-cex-show]")))),c.baseFeeLogo.src=Me.logoPath(y),c.baseFeeTicker.textContent=x,c.quoteFeeLogo.src=Me.logoPath(b),c.quoteFeeTicker.textContent=k,F=w.basicMarketMakingConfig,T=null!==(n=null==F?void 0:F.gapStrategy)&&void 0!==n?n:Zn,D=null!==(a=null!==(o=null===(s=w.arbMarketMakingConfig)||void 0===s?void 0:s.profit)&&void 0!==o?o:null===(i=w.simpleArbConfig)||void 0===i?void 0:i.profitTrigger)&&void 0!==a?a:0,F&&(I=r(F.buyPlacements).sort((function(e,t){return e.gapFactor-t.gapFactor})),A=r(F.sellPlacements).sort((function(e,t){return e.gapFactor-t.gapFactor})),D=I.length>0?A.length>0?(I[0].gapFactor+A[0].gapFactor)/2:I[0].gapFactor:A[0].gapFactor),Me.hide(c.profitLabel,c.gapLabel,c.multiplierLabel,c.profitUnit,c.gapUnit,c.multiplierUnit),e.t0=T,e.next=e.t0===Zn||e.t0===$n?18:e.t0===Qn?21:24;break;case 18:return Me.show(c.profitLabel,c.profitUnit),c.gapFactor.textContent=(100*D).toFixed(2),e.abrupt("break",25);case 21:return Me.show(c.multiplierLabel,c.multiplierUnit),c.gapFactor.textContent=(100*D).toFixed(2),e.abrupt("break",25);case 24:c.gapFactor.textContent=Me.formatFourSigFigs(D/Mt*S/C);case 25:this.update(),this.readBook();case 27:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})},{key:"handleBalanceNote",value:function(e){if(this.mkt){var t=this.mkt,n=t.baseID,r=t.quoteID,a=t.baseFeeID,o=t.quoteFeeID;e.assetID!==n&&e.assetID!==a&&e.assetID!==r&&e.assetID!==o||this.update()}}},{key:"setTicker",value:function(){this.page.runTime.textContent=Me.hmsSince(this.startTime)}},{key:"update",value:function(){var e,t,n,r=this,a=this.div,o=this.page,s=this.mkt,i=s.baseID,c=s.quoteID,l=s.baseFeeID,u=s.quoteFeeID,d=s.baseFactor,h=s.quoteFactor,p=s.baseFeeFactor,f=s.quoteFeeFactor,v=s.marketReport,m=v.baseFiatRate,g=v.quoteFiatRate,y=this.mkt.status(),b=y.botCfg,x=b.cexName,k=b.basicMarketMakingConfig,w=y.runStats;if(Me.hide(o.stats,o.cexRow,o.pendingDepositBox,o.pendingWithdrawalBox),w){this.ticker||(this.startTime=w.startTime,this.setTicker(),this.ticker=setInterval((function(){return r.setTicker()}),1e3)),Me.show(o.stats),mr(100*w.profitLoss.profitRatio,o.profit,o.profitSign,2),mr(w.profitLoss.profit,o.profitLoss,o.plSign,2),this.startTime=w.startTime;var S=function(e){return e?e.available+e.locked+e.pending+e.reserved:0},C=S(w.dexBalances[i])/d;o.walletBaseInventory.textContent=Me.formatFourSigFigs(C),o.walletBaseInvFiat.textContent=Me.formatFourSigFigs(C*m,2);var F=S(w.dexBalances[c])/h;if(o.walletQuoteInventory.textContent=Me.formatFourSigFigs(F),o.walletQuoteInvFiat.textContent=Me.formatFourSigFigs(F*g,2),Me.setVis(x,o.cexRow),x){Me.show(o.pendingDepositBox,o.pendingWithdrawalBox),ir(a,x);var T=S(w.cexBalances[i])/d;o.cexBaseInventory.textContent=Me.formatFourSigFigs(T),o.cexBaseInventoryFiat.textContent=Me.formatFourSigFigs(T*m,2);var D=S(w.cexBalances[c])/h;o.cexQuoteInventory.textContent=Me.formatFourSigFigs(D),o.cexQuoteInventoryFiat.textContent=Me.formatFourSigFigs(D*g,2)}if(l!==i){var I=S(w.dexBalances[l])/p;o.baseFeeReserves.textContent=Me.formatFourSigFigs(I)}if(u!==c){var A=S(w.dexBalances[u])/f;o.quoteFeeReserves.textContent=Me.formatFourSigFigs(A)}o.pendingDeposits.textContent=String(Math.round(w.pendingDeposits)),o.pendingWithdrawals.textContent=String(Math.round(w.pendingWithdrawals)),o.completedMatches.textContent=String(Math.round(w.completedMatches)),Me.setVis(w.tradedUSD,o.tradedUSDBox),w.tradedUSD>0&&(o.tradedUSD.textContent=Me.formatFourSigFigs(w.tradedUSD)),Me.setVis(m,o.roundTripFeesBox),m&&(o.roundTripFeesUSD.textContent=Me.formatFourSigFigs((null===(e=w.feeGap)||void 0===e?void 0:e.roundTripFees)/d*m||0));var R=ht().conventionalRate(i,c,(null===(t=w.feeGap)||void 0===t?void 0:t.basisPrice)||0);o.basisPrice.textContent=Me.formatFourSigFigs(R);var E=!k||k.gapStrategy===Jn||k.gapStrategy===$n;if(Me.setVis(E,o.feeGapBox),E){var B,P=ht().conventionalRate(i,c,(null===(B=w.feeGap)||void 0===B?void 0:B.feeGap)||0);o.feeGap.textContent=Me.formatFourSigFigs(P),o.feeGapPct.textContent=(P/R*100||0).toFixed(2)}Me.setVis(k,o.gapStrategyBox),k&&(o.gapStrategy.textContent=k.gapStrategy);var L=ht().conventionalRate(i,c,(null===(n=w.feeGap)||void 0===n?void 0:n.remoteGap)||0);Me.setVis(L,o.remoteGapBox),L&&(o.remoteGap.textContent=Me.formatFourSigFigs(L),o.remoteGapPct.textContent=(L/R*100||0).toFixed(2))}else this.ticker&&(clearInterval(this.ticker),this.ticker=void 0)}},{key:"readBook",value:function(){if(this.mkt){var e=this.page,t=this.mkt,n=t.host,r=t.mktID,a=ht().exchanges[n].markets[r].orders||[];e.nBookedOrders.textContent=String(a.filter((function(e){return e.status===It})).length)}}}]),e}();function mr(e,t,n,r){t.textContent=Me.formatFourSigFigs(e,r),n.classList.toggle("ico-plus",e>0),n.classList.toggle("text-good",e>0)}function gr(e,t,n,r,a,o,s,i,c,l,u,d,h){var p=cr(a,e,t),f={dex:{base:{lots:o,val:o*a},quote:{lots:s,val:s*p}},cex:{base:{lots:s,val:s*a},quote:{lots:o,val:o*p}}},v=0,m=0;e!==i&&(v+=n.estimated.swap,i===c&&(v+=r.estimated.redeem));var g=n.max.swap;e===c&&(g+=r.max.redeem),l&&(g+=n.max.refund,u||i===c||(m=n.max.redeem));var y=0,b=0;t!==c&&(y+=r.estimated.swap,c===i&&(y+=n.estimated.redeem));var x=r.max.swap;t===i&&(x+=n.max.redeem),u&&(x+=r.max.refund,l||c===i||(b=r.max.redeem));var k=1+d,w=1+h,S=g*o*k,C=m*s*w,F=x*s*w,T=b*o*k;return{commit:f,fees:{base:Xn(Xn({},n),{},{bookingFeesPerLot:g,bookingFeesPerCounterLot:m,bookingFees:S+C,swapReservesFactor:k,redeemReservesFactor:w,tokenFeesPerSwap:v}),quote:Xn(Xn({},r),{},{bookingFeesPerLot:x,bookingFeesPerCounterLot:b,bookingFees:F+T,swapReservesFactor:w,redeemReservesFactor:k,tokenFeesPerSwap:y})}}}function yr(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return br(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?br(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e){throw e})),f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,i=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e){i=!0,o=e})),f:function(){try{s||null==n.return||n.return()}finally{if(i)throw o}}}}function br(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n1)){e.next=34;break}Me.show(r),u=yr(l),e.prev=16,h=f().mark((function e(){var t,a;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=d.value,(a=n.walletTabTmpl.cloneNode(!0)).dataset.tooltip=t.description,a.textContent=t.tab,r.appendChild(a),Me.bind(a,"click",(function(){var e,n=yr(Me.kids(r));try{for(n.s();!(e=n.n()).done;)e.value.classList.remove("selected")}catch(e){n.e(e)}finally{n.f()}a.classList.add("selected"),p.update(t)}));case 6:case"end":return e.stop()}}),e)})),u.s();case 19:if((d=u.n()).done){e.next=23;break}return e.delegateYield(h(),"t0",21);case 21:e.next=19;break;case 23:e.next=28;break;case 25:e.prev=25,e.t1=e.catch(16),u.e(e.t1);case 28:return e.prev=28,u.f(),e.finish(28);case 31:ht().bindTooltips(r),r.firstChild.classList.add("selected");case 34:return e.next=36,this.update(this.current.selectedDef);case 36:if(!s.walletCreationPending){e.next=39;break}return e.next=39,this.runParentSync();case 39:case"end":return e.stop()}}),e,this,[[16,25,28,31]])}))),function(e){return o.apply(this,arguments)})},{key:"parseAsset",value:function(e){if(this.current&&this.current.asset.id===e)return!1;var t=ht().assets[e],n=t.token;if(!n){if(!t.info)throw Error("this non-token asset has no wallet info!");return this.current={asset:t,winfo:t.info,selectedDef:t.info.availablewallets[0]},!0}var r=ht().user.assets[n.parentID];if(r.wallet)return this.current={asset:t,winfo:n,selectedDef:n.definition},!0;if(!r.info)throw Error("this parent has no wallet info!");return this.current={asset:t,parentAsset:r,winfo:n,selectedDef:r.info.availablewallets[0]},!0}},{key:"update",value:(a=s(f().mark((function e(t){var n,a,o,s,i,c,l,u,d,h,p,v,m,g,y,b,x,k;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=this.page,this.current.selectedDef=t,Me.hide(n.walletPassAndSubmitBttn,n.oneBttnBox,n.newWalletPassBox),a=t.guidelink,(o=t.configopts||[]).map((function(e){return e.isBirthdayConfig&&ht().seedGenTime>0&&(e.default=Ur(new Date)),e})),s=!1,i=yr(o),e.prev=8,i.s();case 10:if((c=i.n()).done){e.next=17;break}if(!c.value.required){e.next=15;break}return s=!0,e.abrupt("break",17);case 15:e.next=10;break;case 17:e.next=22;break;case 19:e.prev=19,e.t0=e.catch(8),i.e(e.t0);case 22:return e.prev=22,i.f(),e.finish(22);case 25:if(l=this.current,u=l.asset,d=l.parentAsset,h=l.winfo,(p=t.seeded||Boolean(u.token))&&!s?(Me.hide(n.walletSettingsHeader),Me.show(n.oneBttnBox)):p?(Me.show(n.walletPassAndSubmitBttn,n.walletSettingsHeader),n.newWalletPass.value="",n.submitAdd.textContent=be("CREATE")):(Me.show(n.walletPassAndSubmitBttn,n.walletSettingsHeader),t.noauth||Me.show(n.newWalletPassBox),n.submitAdd.textContent=be("ADD")),d){v=JSON.parse(JSON.stringify(o)),m=yr(v);try{for(m.s();!(g=m.n()).done;)g.value.regAsset=d.id}catch(e){m.e(e)}finally{m.f()}if((y=h.definition.configopts||[]).length>0){b=JSON.parse(JSON.stringify(y)),x=yr(b);try{for(x.s();!(k=x.n()).done;)k.value.regAsset=u.id}catch(e){x.e(e)}finally{x.f()}v.push.apply(v,r(b))}this.subform.update(u.id,v,!1)}else this.subform.update(u.id,o,!1);return this.setGuideLink(a),t.seeded||Boolean(this.current.asset.token)?Me.hide(this.subform.fileSelector):Me.show(this.subform.fileSelector),e.next=33,this.loadDefaults();case 33:case"end":return e.stop()}}),e,this,[[8,19,22,25]])}))),function(e){return a.apply(this,arguments)})},{key:"setGuideLink",value:function(e){Me.hide(this.walletCfgGuide),""!==e&&(this.walletCfgGuide.href=e,Me.show(this.walletCfgGuide))}},{key:"setError",value:(n=s(f().mark((function e(t){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:this.page.newWalletErr.textContent=t,Me.show(this.page.newWalletErr);case 2:case"end":return e.stop()}}),e,this)}))),function(e){return n.apply(this,arguments)})},{key:"loadDefaults",value:(t=s(f().mark((function e(){var t,n,r,a,o,s,i;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=this.current,n=t.asset,r=t.parentAsset,(a=t.selectedDef).configpath){e.next=3;break}return e.abrupt("return");case 3:if(o=n.id,!r){e.next=8;break}if(!a.seeded){e.next=7;break}return e.abrupt("return");case 7:o=r.id;case 8:return s=ht().loading(this.form),e.next=11,C("/api/defaultwalletcfg",{assetID:o,type:a.type});case 11:if(i=e.sent,s(),ht().checkResponse(i)){e.next=16;break}return this.setError(i.msg),e.abrupt("return");case 16:this.subform.setLoadedConfig(i.config);case 17:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})}]),e}(),wr=0,Sr=function(){function e(t,n){var r=this;i(this,e),h(this,"page",void 0),h(this,"form",void 0),h(this,"configElements",void 0),h(this,"configOpts",void 0),h(this,"sectionize",void 0),h(this,"allSettings",void 0),h(this,"dynamicOpts",void 0),h(this,"textInputTmpl",void 0),h(this,"dateInputTmpl",void 0),h(this,"checkboxTmpl",void 0),h(this,"repeatableTmpl",void 0),h(this,"fileSelector",void 0),h(this,"fileInput",void 0),h(this,"errMsg",void 0),h(this,"showOther",void 0),h(this,"showIcon",void 0),h(this,"hideIcon",void 0),h(this,"showHideMsg",void 0),h(this,"otherSettings",void 0),h(this,"loadedSettingsMsg",void 0),h(this,"loadedSettings",void 0),h(this,"defaultSettingsMsg",void 0),h(this,"defaultSettings",void 0),h(this,"assetHasActiveOrders",void 0),h(this,"assetID",void 0),this.page=Me.idDescendants(t),this.form=t,this.configElements=[],this.configOpts=[],this.sectionize=n,this.allSettings=Me.tmplElement(t,"allSettings"),this.dynamicOpts=Me.tmplElement(t,"dynamicOpts"),this.textInputTmpl=Me.tmplElement(t,"textInput"),this.textInputTmpl.remove(),this.dateInputTmpl=Me.tmplElement(t,"dateInput"),this.dateInputTmpl.remove(),this.checkboxTmpl=Me.tmplElement(t,"checkbox"),this.checkboxTmpl.remove(),this.repeatableTmpl=Me.tmplElement(t,"repeatableInput"),this.repeatableTmpl.remove(),this.fileSelector=Me.tmplElement(t,"fileSelector"),this.fileInput=Me.tmplElement(t,"fileInput"),this.errMsg=Me.tmplElement(t,"errMsg"),this.showOther=Me.tmplElement(t,"showOther"),this.showIcon=Me.tmplElement(t,"showIcon"),this.hideIcon=Me.tmplElement(t,"hideIcon"),this.showHideMsg=Me.tmplElement(t,"showHideMsg"),this.otherSettings=Me.tmplElement(t,"otherSettings"),this.loadedSettingsMsg=Me.tmplElement(t,"loadedSettingsMsg"),this.loadedSettings=Me.tmplElement(t,"loadedSettings"),this.defaultSettingsMsg=Me.tmplElement(t,"defaultSettingsMsg"),this.defaultSettings=Me.tmplElement(t,"defaultSettings"),n||Me.hide(this.showOther),Me.bind(this.fileSelector,"click",(function(){return r.fileInput.click()})),Me.bind(this.fileInput,"change",s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",r.fileInputChanged());case 1:case"end":return e.stop()}}),e)})))),Me.bind(this.showOther,"click",(function(){r.setOtherSettingsViz(r.hideIcon.classList.contains("d-hide"))}))}var t;return d(e,[{key:"fileInputChanged",value:(t=s(f().mark((function e(){var t,n,a,o,s,i,c,l;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(Me.hide(this.errMsg),this.fileInput.value){e.next=3;break}return e.abrupt("return");case 3:if((n=this.fileInput.files)&&0!==n.length){e.next=6;break}return e.abrupt("return");case 6:return a=ht().loading(this.form),e.next=9,n[0].text();case 9:if(o=e.sent){e.next=12;break}return e.abrupt("return");case 12:return e.next=14,C("/api/parseconfig",{configtext:o});case 14:if(s=e.sent,a(),ht().checkResponse(s)){e.next=20;break}return this.errMsg.textContent=s.msg,Me.show(this.errMsg),e.abrupt("return");case 20:if(0!==Object.keys(s.map).length){e.next=22;break}return e.abrupt("return");case 22:(t=this.dynamicOpts).append.apply(t,r(this.setConfig(s.map))),this.reorder(this.dynamicOpts),i=[this.loadedSettings.children.length,this.defaultSettings.children.length],l=i[1],0===(c=i[0])&&Me.hide(this.loadedSettings,this.loadedSettingsMsg),0===l&&Me.hide(this.defaultSettings,this.defaultSettingsMsg),c+l===0&&Me.hide(this.showOther,this.otherSettings);case 28:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})},{key:"addOpt",value:function(e,t,n,r){var a,o,s=this;if(t.isboolean)o=this.checkboxTmpl.cloneNode(!0);else if(t.isdate)o=this.dateInputTmpl.cloneNode(!0);else if(t.repeatable){if((o=this.repeatableTmpl.cloneNode(!0)).classList.add("repeatable"),Me.bind(Me.tmplElement(o,"add"),"click",(function(){s.addOpt(e,t,o,!0)})),!r)for(var i=0;i<(t.repeatN?t.repeatN-1:0);i++)this.addOpt(e,t,n,!0)}else o=this.textInputTmpl.cloneNode(!0);-1!==((null===(a=ht().extensionWallet(this.assetID))||void 0===a?void 0:a.hiddenFields)||[]).indexOf(t.key)&&Me.hide(o),this.configElements.push([t,o]);var c=o.querySelector("input");c.dataset.configKey=t.key,wr++;var l="wcfg-"+String(wr);c.id=l;var u=Me.safeSelector(o,"label");if(u.htmlFor=l,u.prepend(t.displayname),void 0!==t.regAsset){var d=new window.Image(15,15);d.src=Me.logoPathFromID(t.regAsset||-1),u.prepend(d)}if(n?n.after(o):e.appendChild(o),t.noecho&&(c.type="password",c.autocomplete="off"),t.description&&(u.dataset.tooltip=t.description),t.isboolean)c.checked=t.default;else if(t.isdate){var h=function(e){return e?_r("now"===e?new Date:new Date(1e3*e)):""};c.max=h(t.max),c.min=h(t.min);var p=t.default?new Date(1e3*t.default):new Date;c.value=_r(p)}else c.value=null!==t.default?t.default:"";return c.disabled=Boolean(t.disablewhenactive&&this.assetHasActiveOrders),o}},{key:"update",value:function(e,t,n){if(this.assetHasActiveOrders=n,this.configElements=[],this.configOpts=t||[],this.assetID=e,Me.empty(this.dynamicOpts,this.defaultSettings,this.loadedSettings),0===this.configOpts.length)return Me.hide(this.form);Me.show(this.form),this.setOtherSettingsViz(!1),Me.hide(this.loadedSettingsMsg,this.loadedSettings,this.defaultSettingsMsg,this.defaultSettings,this.errMsg);var r,a=[],o=yr(this.configOpts);try{for(o.s();!(r=o.n()).done;){var s=r.value;this.sectionize&&null!==s.default?a.push(s):this.addOpt(this.dynamicOpts,s)}}catch(e){o.e(e)}finally{o.f()}if(a.length){var i,c=yr(a);try{for(c.s();!(i=c.n()).done;){var l=i.value;this.addOpt(this.defaultSettings,l)}}catch(e){c.e(e)}finally{c.f()}Me.show(this.showOther,this.defaultSettingsMsg,this.defaultSettings)}else Me.hide(this.showOther);ht().bindTooltips(this.allSettings),this.dynamicOpts.children.length?Me.show(this.dynamicOpts):Me.hide(this.dynamicOpts)}},{key:"setOtherSettingsViz",value:function(e){if(e)return Me.hide(this.showIcon),Me.show(this.hideIcon,this.otherSettings),void(this.showHideMsg.textContent=be("HIDE_ADDITIONAL_SETTINGS"));Me.hide(this.hideIcon,this.otherSettings),Me.show(this.showIcon),this.showHideMsg.textContent=be("SHOW_ADDITIONAL_SETTINGS")}},{key:"setConfig",value:function(e){for(var t,n=[],o={},s=[],i=0,c=r(this.configElements);i=0&&this.configElements.splice(S,1)}return n}},{key:"setLoadedConfig",value:function(e){var t,n=this.setConfig(e);this.sectionize&&0!==n.length&&((t=this.loadedSettings).append.apply(t,r(n)),this.reorder(this.loadedSettings),Me.show(this.loadedSettings,this.loadedSettingsMsg),0===this.defaultSettings.children.length&&Me.hide(this.defaultSettings,this.defaultSettingsMsg))}},{key:"map",value:function(e){var t,n={},r=yr(this.configElements);try{for(r.s();!(t=r.n()).done;){var o=a(t.value,2),s=o[0],i=o[1],c=Me.safeSelector(i,"input");if(void 0===s.regAsset||s.regAsset===e)if(s.isboolean&&s.key)n[s.key]=c.checked?"1":"0";else if(s.isdate&&s.key){var l=c.min?Ur(new Date(c.min+"T00:00")):Number.MIN_SAFE_INTEGER,u=c.max?Ur(new Date(c.max+"T00:00")):Number.MAX_SAFE_INTEGER,d=c.value?Ur(new Date(c.value+"T00:00")):0;du&&(d=u),n[s.key]=String(d)}else c.value&&(s.repeatable&&n[s.key]?n[s.key]+=s.repeatable+c.value:n[s.key]=c.value)}}catch(e){r.e(e)}finally{r.f()}return n}},{key:"reorder",value:function(e){var t=this,n={};e.querySelectorAll("input").forEach((function(e){var r=e.dataset.configKey;if(r){var o,s=[],i=yr(t.configElements);try{for(i.s();!(o=i.n()).done;){var c=a(o.value,2),l=c[0],u=c[1];l.key===r&&s.push(u)}}catch(e){i.e(e)}finally{i.f()}n[r]=s}}));var r,o=yr(this.configOpts);try{for(o.s();!(r=o.n()).done;){var s,i=r.value,c=yr(n[i.key]||[]);try{for(c.s();!(s=c.n()).done;){var l=s.value;e.append(l)}}catch(e){c.e(e)}finally{c.f()}}}catch(e){o.e(e)}finally{o.f()}}}]),e}(),Cr=function(){function e(t,n,r){var a=this;i(this,e),h(this,"form",void 0),h(this,"success",void 0),h(this,"page",void 0),h(this,"xc",void 0),h(this,"certFile",void 0),h(this,"bondAssetID",void 0),h(this,"tier",void 0),h(this,"fees",void 0),this.form=t,this.success=n,this.page=Me.parseTemplate(t),this.certFile="",Me.bind(this.page.goBack,"click",(function(){return r()})),Vr(t,this.page.submit,(function(){return a.submitForm()}))}var t,n;return d(e,[{key:"setExchange",value:function(e,t){this.xc=e,this.certFile=t,this.page.host.textContent=e.host}},{key:"setAsset",value:function(e,t,n){var r=ht().assets[e],a=r.unitInfo.conventional,o=a.conversionFactor,s=a.unit;this.bondAssetID=r.id,this.tier=t,this.fees=n;var i=this.page,c=this.xc.bondAssets[r.symbol].amount*t*2/o;i.tradingTier.textContent=String(t),i.logo.src=Me.logoPath(r.symbol),i.bondLock.textContent=Me.formatFourSigFigs(c),i.bondUnit.textContent=s;var l=ht().fiatRatesMap[e];Me.show(i.bondLockUSDBox),l?i.bondLockUSD.textContent=Me.formatFourSigFigs(c*l):Me.hide(i.bondLockUSDBox),n&&(i.feeReserves.textContent=Me.formatFourSigFigs(n/o)),i.reservesUnit.textContent=s}},{key:"setFees",value:function(e,t){this.fees=t;var n=ht().assets[e].unitInfo.conventional.conversionFactor;this.page.feeReserves.textContent=Me.formatFourSigFigs(t/n)}},{key:"animate",value:(n=s(f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=this.form,Me.animate(400,(function(e){t.style.transform="scale(".concat(e,")"),t.style.opacity=String(Math.pow(e,4));var n="".concat(500*(1-e),"px");t.style.top=n,t.style.left=n}));case 2:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"submitForm",value:(t=s(f().mark((function e(){var t,n,r,a,o,s,i,c,l,u,d,h;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=this.page,n=this.bondAssetID,r=this.xc,a=this.certFile,o=this.tier,s=ht().assets[n]){e.next=6;break}return t.regErr.innerText=be("SELECT_WALLET_FOR_FEE_PAYMENT"),Me.show(t.regErr),e.abrupt("return");case 6:return Me.hide(t.regErr),i=r.bondAssets[s.wallet.symbol],c=r.host,!ht().exchanges[r.host]||ht().exchanges[r.host].viewOnly?(l={addr:c,cert:a,bond:i.amount*o,asset:i.id},u="/api/postbond"):(l={host:c,targetTier:o,bondAssetID:n},u="/api/updatebondoptions"),d=ht().loading(this.form),e.next=13,C(u,l);case 13:if(h=e.sent,d(),ht().checkResponse(h)){e.next=19;break}return t.regErr.textContent=h.msg,Me.show(t.regErr),e.abrupt("return");case 19:this.success();case 20:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})}]),e}(),Fr=function(){function e(t,n){var r=this;i(this,e),h(this,"form",void 0),h(this,"success",void 0),h(this,"xc",void 0),h(this,"selectedAssetID",void 0),h(this,"certFile",void 0),h(this,"page",void 0),h(this,"assetRows",void 0),h(this,"marketRows",void 0),this.form=t,this.certFile="",this.success=n;var a=this.page=Me.parseTemplate(t);Me.cleanTemplates(a.currentBondTmpl,a.bondAssetTmpl,a.marketTmpl),Me.bind(a.tradingTierInput,"input",(function(){r.setTier()})),Me.bind(a.tradingTierInput,"keyup",(function(e){"Enter"===e.key&&r.acceptTier()})),Me.bind(a.submitTradingTier,"click",(function(){r.acceptTier()})),Me.bind(a.tierUp,"click",(function(){r.incrementTier(!0)})),Me.bind(a.tierDown,"click",(function(){r.incrementTier(!1)})),Me.bind(a.goBackToAssets,"click",(function(){Me.hide(a.tradingTierForm),Me.show(a.assetForm)})),Me.bind(a.whatsABond,"click",(function(){Me.hide(a.assetForm),Me.show(a.whatsABondPanel)}));var o=function(){Me.show(a.assetForm),Me.hide(a.whatsABondPanel)};Me.bind(a.bondGotIt,"click",(function(){o()})),Me.bind(a.whatsABondBack,"click",(function(){o()})),Me.bind(a.usePrepaidBond,"click",(function(){r.showPrepaidBondForm()})),Me.bind(a.ppbGoBack,"click",(function(){r.hidePrepaidBondForm()})),Me.bind(a.submitPrepaidBond,"click",(function(){r.submitPrepaidBond()})),ht().registerNoteFeeder({createwallet:function(e){"QueuedCreationSuccess"===e.topic&&r.walletCreated(e.assetID)}})}var t,n;return d(e,[{key:"setTierError",value:function(e){this.page.tradingTierErr.textContent=e,Me.show(this.page.tradingTierErr)}},{key:"setAssetError",value:function(e){this.page.regAssetErr.textContent=e,Me.show(this.page.regAssetErr)}},{key:"clearErrors",value:function(){Me.hide(this.page.regAssetErr,this.page.tradingTierErr)}},{key:"setExchange",value:function(e,t){var n=this;this.xc=e,this.certFile=t,this.assetRows={},this.marketRows=[];var r=this.page;Me.hide(r.assetForm,r.tradingTierForm,r.whatsABondPanel,r.prepaidBonds),Me.empty(r.bondAssets,r.markets),this.clearErrors();for(var a=function(e,t){var a=ht().assets[e];if(a){var o=a.unitInfo.conventional,s=o.unit,i=o.conversionFactor,c=a.name,l=a.symbol,u=r.bondAssetTmpl.cloneNode(!0);r.bondAssets.appendChild(u);var d=Me.parseTemplate(u);d.logo.src=Me.logoPath(l),d.name.textContent=c,Me.bind(u,"click",(function(){n.assetSelected(e)})),d.feeSymbol.textContent=s;var h=t.amount/i;d.feeAmt.textContent=Me.formatFourSigFigs(h);var p=ht().fiatRatesMap[e];Me.setVis(p,d.fiatBox),p&&(d.fiatBondAmount.textContent=Me.formatFourSigFigs(h*p)),n.assetRows[e]={ready:d.ready}}},o=function(t){var a=t.baseid,o=t.quoteid,s=[ht().assets[a],ht().assets[o]];if(s[0]&&s[1]){var i=r.marketTmpl.cloneNode(!0);r.markets.appendChild(i);var c,l=e.assets[a],u=l.symbol,d=l.unitInfo,h=e.assets[o],p=h.symbol,f=h.unitInfo,v=yr(Me.applySelector(i,"[data-base-ticker]"));try{for(v.s();!(c=v.n()).done;)c.value.textContent=d.conventional.unit}catch(e){v.e(e)}finally{v.f()}var m,g=yr(Me.applySelector(i,"[data-quote-ticker]"));try{for(g.s();!(m=g.n()).done;)m.value.textContent=f.conventional.unit}catch(e){g.e(e)}finally{g.f()}var y=Me.parseTemplate(i);y.baseLogo.src=Me.logoPath(u),y.quoteLogo.src=Me.logoPath(p);var b=function(e){var n=t.parcelsize,o=t.lotsize/d.conventional.conversionFactor,s=o*n*2*e,i=o*n*2*kn*e;y.tradeLimitLow.textContent=Me.formatFourSigFigs(s),y.tradeLimitHigh.textContent=Me.formatFourSigFigs(i);var c=ht().fiatRatesMap[a];c&&(y.fiatTradeLimitLow.textContent=Me.formatFourSigFigs(s*c),y.fiatTradeLimitHigh.textContent=Me.formatFourSigFigs(i*c)),Me.setVis(c,r.fiatTradeLowBox,r.fiatTradeHighBox)};b(Sn(e.auth)||1),n.marketRows.push({mkt:t,tmpl:y,setTier:b})}},s=0,i=Object.values(e.assets||{});s0&&(w[parseInt(T)]=A)}}var R=Object.keys(w).length>0;if(Me.setVis(R,t.currentBondBox),R){Me.empty(t.currentBonds);for(var E=0,B=Object.entries(w);E0){Me.show(r.bondCostBreakdown),r.bondLockNoFees.textContent=Me.formatCoinValue(g,s),r.bondLockFees.textContent=Me.formatCoinValue(t,s),g+=t;var y=Math.max(g-c.available+c.reservesDeficit,0);if(r.totalForBond.textContent=Me.formatCoinValue(y,s),Me.hide(r.sendEnough),Me.hide(r.txFeeBox,r.sendEnoughForToken,r.txFeeBalanceBox),Me.hide(r.sendEnoughWithEst),h){Me.show(r.txFeeBox,r.sendEnoughForToken,r.txFeeBalanceBox);var b=ht().assets[h.parentID];r.txFee.textContent=Me.formatCoinValue(t,b.unitInfo),r.parentFees.textContent=Me.formatCoinValue(t,b.unitInfo),r.tokenFees.textContent=Me.formatCoinValue(y,s),v(r.txFeeUnit,b),v(r.parentUnit,b),v(r.parentBalUnit,b),r.parentBal.textContent=b.wallet?Me.formatCoinValue(b.wallet.balance.available,b.unitInfo):"0"}else Me.show(r.sendEnoughWithEst);r.fee.textContent=Me.formatCoinValue(g,s)}else Me.show(r.sendEnough);Me.show(u?r.syncCheck:d>=1?r.syncSpinner:r.syncUncheck),Me.show(c.available>=2*f.amount+t?r.balCheck:r.balUncheck),r.progress.textContent=(100*d).toFixed(1),u&&(this.progressed=!0),this.reportBalance(e)}},{key:"reportWalletState",value:function(e){this.progressed&&this.funded||(e.assetID===this.assetID&&this.reportProgress(e.synced,e.syncProgress),this.reportBalance(e.assetID))}},{key:"reportBalance",value:function(e){if(!this.funded&&-1!==this.assetID&&(e===this.assetID||e===this.parentID)){var t=this.page,n=ht().assets[this.assetID],r=n.wallet.balance.available;if(t.balance.textContent=Me.formatCoinValue(r,n.unitInfo),n.token){var a=ht().assets[n.token.parentID],o=a.wallet.balance.available;if(t.parentBal.textContent=Me.formatCoinValue(o,a.unitInfo),o=.999)return Me.hide(n.syncRemaining),Me.show(n.syncFinishingUp),Me.show(n.syncRemainBox),void(n.syncFinishingUp.textContent=be("WALLET_SYNC_FINISHING_UP"));var r=this.progressCache;if(r.push({stamp:(new Date).getTime(),progress:t}),!(r.length<2)){for(;r.length>20;)r.shift();var a=[r[0],r[r.length-1]],o=a[0],s=a[1],i=s.progress-o.progress;if(0!==i){Me.hide(n.syncFinishingUp),Me.show(n.syncRemaining),Me.show(n.syncRemainBox);var c=i/(s.stamp-o.stamp),l=(1-s.progress)/c;n.syncRemain.textContent=Me.formatDuration(l)}}}}]),e}(),Dr=function(){function e(t,n){var r=this;i(this,e),h(this,"form",void 0),h(this,"page",void 0),h(this,"order",void 0),h(this,"acceleratedRate",void 0),h(this,"earlyAcceleration",void 0),h(this,"currencyUnit",void 0),h(this,"success",void 0),this.form=t,this.success=n;var a=this.page=Me.idDescendants(t);Me.bind(a.accelerateSubmit,"click",(function(){r.submit()})),Me.bind(a.submitEarlyConfirm,"click",(function(){r.sendAccelerateRequest()}))}var t,n,r,a;return d(e,[{key:"displayEarlyAccelerationMsg",value:function(){var e=this.page;this.earlyAcceleration&&(e.recentAccelerationTime.textContent="".concat(Math.floor(this.earlyAcceleration.timePast/60)),e.recentSwapTime.textContent="".concat(Math.floor(this.earlyAcceleration.timePast/60)),this.earlyAcceleration.wasAcceleration?(Me.show(e.recentAccelerationMsg),Me.hide(e.recentSwapMsg),e.recentAccelerationTime.textContent="".concat(Math.floor(this.earlyAcceleration.timePast/60))):(Me.show(e.recentSwapMsg),Me.hide(e.recentAccelerationMsg),e.recentSwapTime.textContent="".concat(Math.floor(this.earlyAcceleration.timePast/60))),Me.hide(e.configureAccelerationDiv,e.accelerateErr),Me.show(e.earlyAccelerationDiv))}},{key:"sendAccelerateRequest",value:(a=s(f().mark((function e(){var t,n,r,a,o;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.order,n=this.page,r={orderID:t.id,newRate:this.acceleratedRate},a=ht().loading(n.accelerateMainDiv),e.next=6,C("/api/accelerateorder",r);case 6:o=e.sent,a(),ht().checkResponse(o)?(n.accelerateTxID.textContent=o.txID,Me.hide(n.accelerateMainDiv,n.preAccelerateErr,n.accelerateErr),Me.show(n.accelerateMsgDiv,n.accelerateSuccess),this.success()):(n.accelerateErr.textContent=be(J,{msg:o.msg}),Me.hide(n.earlyAccelerationDiv),Me.show(n.accelerateErr,n.configureAccelerationDiv));case 9:case"end":return e.stop()}}),e,this)}))),function(){return a.apply(this,arguments)})},{key:"submit",value:(r=s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:this.earlyAcceleration?this.displayEarlyAccelerationMsg():this.sendAccelerateRequest();case 1:case"end":return e.stop()}}),e,this)}))),function(){return r.apply(this,arguments)})},{key:"refresh",value:(n=s(f().mark((function e(t){var n,r,a,o,s,i,c=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=this.page,this.order=t,e.next=4,C("/api/preaccelerate",t.id);case 4:if(r=e.sent,ht().checkResponse(r)){e.next=10;break}return n.preAccelerateErr.textContent=be(J,{msg:r.msg}),Me.hide(n.accelerateMainDiv,n.accelerateSuccess),Me.show(n.accelerateMsgDiv,n.preAccelerateErr),e.abrupt("return");case 10:Me.hide(n.accelerateMsgDiv,n.preAccelerateErr,n.accelerateErr,n.feeEstimateDiv,n.earlyAccelerationDiv),Me.show(n.accelerateMainDiv,n.accelerateSuccess,n.configureAccelerationDiv),a=r.preAccelerate,this.earlyAcceleration=a.earlyAcceleration,this.currencyUnit=a.suggestedRange.yUnit,n.accelerateAvgFeeRate.textContent="".concat(a.swapRate," ").concat(a.suggestedRange.yUnit),n.accelerateCurrentFeeRate.textContent="".concat(a.suggestedRate," ").concat(a.suggestedRange.yUnit),this.acceleratedRate=a.suggestedRange.start.y,o=function(){},s=function(e,t){c.acceleratedRate=t},i=new bt(a.suggestedRange,a.suggestedRange.start.x,{updated:s,changed:function(){return c.updateAccelerationEstimate()},selected:o,roundY:!0}),Me.empty(n.sliderContainer),n.sliderContainer.appendChild(i.control),this.updateAccelerationEstimate();case 25:case"end":return e.stop()}}),e,this)}))),function(e){return n.apply(this,arguments)})},{key:"updateAccelerationEstimate",value:(t=s(f().mark((function e(){var t,n,r,a,o,s,i,c;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.page,n=this.order,r={orderID:n.id,newRate:this.acceleratedRate},a=ht().loading(t.sliderContainer),e.next=6,C("/api/accelerationestimate",r);case 6:if(o=e.sent,a(),ht().checkResponse(o)){e.next=12;break}return t.accelerateErr.textContent=be("ORDER_ACCELERATION_FEE_ERR_MSG",{msg:o.msg}),Me.show(t.accelerateErr),e.abrupt("return");case 12:t.feeRateEstimate.textContent="".concat(this.acceleratedRate," ").concat(this.currencyUnit),n.sell?(s=n.baseID,i=n.baseSymbol):(s=n.quoteID,i=n.quoteSymbol),c=ht().unitInfo(s),t.feeEstimate.textContent="".concat(o.fee/c.conventional.conversionFactor," ").concat(i),Me.show(t.feeEstimateDiv);case 17:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})}]),e}(),Ir=function(){function e(t,n,r){var a=this;i(this,e),h(this,"form",void 0),h(this,"success",void 0),h(this,"page",void 0),h(this,"knownExchanges",void 0),h(this,"dexToUpdate",void 0),h(this,"certPicker",void 0),this.form=t,this.success=n;var o=this.page=Me.parseTemplate(t);this.certPicker=new Pr(t),Me.bind(o.skipRegistration,"change",(function(){return a.showOrHideSubmitBttn()})),Me.bind(o.showCustom,"click",(function(){Me.hide(o.showCustom),Me.show(o.customBox,o.auth)})),this.knownExchanges=Array.from(o.knownXCs.querySelectorAll(".known-exchange"));var s,c=yr(this.knownExchanges);try{var l=function(){var e=s.value;Me.bind(e,"click",(function(){var t,n=e.dataset.host,r=yr(a.knownExchanges);try{for(r.s();!(t=r.n()).done;)t.value.classList.remove("selected")}catch(e){r.e(e)}finally{r.f()}return a.checkDEX(n)}))};for(c.s();!(s=c.n()).done;)l()}catch(e){c.e(e)}finally{c.f()}Vr(t,o.submit,(function(){return a.checkDEX()})),r&&(Me.hide(o.addDexHdr,o.skipRegistrationBox),Me.show(o.updateDexHdr),this.dexToUpdate=r),this.refresh()}var t,n;return d(e,[{key:"refresh",value:function(){var e=this.page;e.addr.value="",this.certPicker.clearCertFile(),Me.hide(e.err),0===this.knownExchanges.length||this.dexToUpdate?(Me.show(e.customBox,e.auth),Me.hide(e.showCustom,e.knownXCs,e.pickServerMsg,e.addCustomMsg)):(Me.hide(e.customBox),Me.show(e.showCustom));var t,n=yr(this.knownExchanges);try{for(n.s();!(t=n.n()).done;)t.value.classList.remove("selected")}catch(e){n.e(e)}finally{n.f()}this.showOrHideSubmitBttn()}},{key:"showOrHideSubmitBttn",value:function(){var e=this.page;Me.setVis(Me.isDisplayed(e.customBox),e.auth)}},{key:"skipRegistration",value:function(){var e;return null!==(e=this.page.skipRegistration.checked)&&void 0!==e&&e}},{key:"animate",value:(n=s(f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=this.form,Me.animate(550,(function(e){t.style.transform="scale(".concat(.9+.1*e,")"),t.style.opacity=String(Math.pow(e,4))}),"easeOut");case 2:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"checkDEX",value:(t=s(f().mark((function e(t){var n,r,a,o,s,i,c;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=this.page,Me.hide(n.err),""!==(t=t||n.addr.value)){e.next=7;break}return n.err.textContent=be("EMPTY_DEX_ADDRESS_MSG"),Me.show(n.err),e.abrupt("return");case 7:return e.next=9,this.certPicker.file();case 9:return r=e.sent,a=this.skipRegistration(),this.dexToUpdate?(o="/api/updatedexhost",s={newHost:t,cert:r,oldHost:this.dexToUpdate}):(o=a?"/api/adddex":"/api/discoveracct",s={addr:t,cert:r}),i=ht().loading(this.form),e.next=15,C(o,s);case 15:if(c=e.sent,i(),ht().checkResponse(c)){e.next=20;break}return String(c.msg).includes("certificate required")?Me.show(n.needCert):(n.err.textContent=c.msg,Me.show(n.err)),e.abrupt("return");case 20:return e.next=22,ht().fetchUser();case 22:if(this.dexToUpdate||!(a||c.paid||Object.keys(c.xc.auth.pendingBonds).length>0)){e.next=26;break}return e.next=25,ht().loadPage("markets");case 25:return e.abrupt("return");case 26:this.success(c.xc,r);case 27:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})}]),e}(),Ar=function(){function e(t,n,r){var a=this;i(this,e),h(this,"form",void 0),h(this,"addr",void 0),h(this,"success",void 0),h(this,"page",void 0),this.form=t,this.addr=n,this.success=r;var o=this.page=Me.parseTemplate(t);o.dexHost.textContent=n,Vr(t,o.submit,(function(){return a.checkDEX()}))}var t,n;return d(e,[{key:"animate",value:(n=s(f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=this.form,Me.animate(550,(function(e){t.style.transform="scale(".concat(.9+.1*e,")"),t.style.opacity=String(Math.pow(e,4))}),"easeOut");case 2:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"checkDEX",value:(t=s(f().mark((function e(){var t,n,r,a;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.page,Me.hide(t.err),n={addr:this.addr},r=ht().loading(this.form),e.next=6,C("/api/discoveracct",n);case 6:if(a=e.sent,r(),ht().checkResponse(a)){e.next=12;break}return t.err.textContent=a.msg,Me.show(t.err),e.abrupt("return");case 12:if(!a.paid){e.next=18;break}return e.next=15,ht().fetchUser();case 15:return e.next=17,ht().loadPage("markets");case 17:return e.abrupt("return");case 18:this.success(a.xc);case 19:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})}]),e}(),Rr=function(){function e(t,n){var r=this;i(this,e),h(this,"form",void 0),h(this,"success",void 0),h(this,"page",void 0),this.success=n,this.form=t,Vr(t,(this.page=Me.parseTemplate(t)).submit,(function(){r.submit()})),ht().registerNoteFeeder({login:function(e){r.handleLoginNote(e)}})}var t,n;return d(e,[{key:"handleLoginNote",value:function(e){if(""!==e.details){var t=Me.idel(this.form,"loaderMsg");Me.show(t),t&&(t.textContent=e.details)}}},{key:"focus",value:function(){this.page.pw.focus()}},{key:"refresh",value:function(){Me.hide(this.page.errMsg),this.page.pw.value=""}},{key:"submit",value:(n=s(f().mark((function e(){var t,n,r,a;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=this.page,Me.hide(t.errMsg),""!==(n=t.pw.value||"")){e.next=6;break}return Me.showFormError(t.errMsg,be(R)),e.abrupt("return");case 6:return r=ht().loading(this.form),e.next=9,C("/api/login",{pass:n});case 9:if(a=e.sent,r(),t.pw.value="",ht().checkResponse(a)){e.next=15;break}return Me.showFormError(t.errMsg,a.msg),e.abrupt("return");case 15:return e.next=17,ht().fetchUser();case 17:a.notes=a.notes||[],a.notes.reverse(),a.pokes=a.pokes||[],ht().loggedIn(a.notes,a.pokes),this.success();case 22:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"animate",value:(t=s(f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=this.form,Me.animate(550,(function(e){t.style.transform="scale(".concat(.9+.1*e,")"),t.style.opacity=String(Math.pow(e,4))}),"easeOut");case 2:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})}]),e}(),Er=function(){function e(t){var n=this;i(this,e),h(this,"form",void 0),h(this,"page",void 0),h(this,"assetID",void 0),this.form=t;var r=this.page=Me.idDescendants(t);Me.cleanTemplates(r.unifiedReceiverTmpl),Me.bind(r.newDepAddrBttn,"click",s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n.newDepositAddress();case 1:case"end":return e.stop()}}),e)})))),Me.bind(r.copyAddressBtn,"click",(function(){n.copyAddress()}))}var t,n,r;return d(e,[{key:"setAsset",value:(r=s(f().mark((function e(t){var n,r,a,o;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:this.assetID=t,n=this.page,Me.hide(n.depositErr,n.depositTokenMsgBox),r=ht().assets[t],n.depositLogo.src=Me.logoPath(r.symbol),a=ht().walletMap[t],n.depositName.textContent=r.unitInfo.conventional.unit,r.token&&(o=ht().assets[r.token.parentID],n.depositTokenParentLogo.src=Me.logoPath(o.symbol),n.depositTokenParentName.textContent=o.name,Me.show(n.depositTokenMsgBox)),Me.setVis(0!=(2&a.traits),n.newDepAddrBttnBox),this.setAddress(a.address);case 10:case"end":return e.stop()}}),e,this)}))),function(e){return r.apply(this,arguments)})},{key:"setAddress",value:function(e){var t=this,n=this.page;if(Me.hide(n.unifiedReceivers),e.startsWith("unified:")){var r=JSON.parse(e.substring(8));Me.empty(n.unifiedReceivers),Me.show(n.unifiedReceivers);for(var o=function(){var e=a(i[s],2),r=e[0],o=e[1],c=n.unifiedReceiverTmpl.cloneNode(!0);n.unifiedReceivers.appendChild(c),c.textContent=r,c.dataset.type=r,"unified"===r&&c.classList.add("selected"),Me.bind(c,"click",(function(){for(var e=0,a=Array.from(n.unifiedReceivers.children);e=r?Me.hide(t.addressBox):Me.hide(t.errMsg))}}]),e}(),Or=function(){function e(t,n){var r=this;i(this,e),h(this,"form",void 0),h(this,"page",void 0),h(this,"success",void 0),h(this,"cexName",void 0),this.form=t,this.success=n,this.page=Me.parseTemplate(t),Me.bind(this.page.cexSubmit,"click",(function(){return r.submit()}))}var t;return d(e,[{key:"setCEX",value:function(e){this.cexName=e,ir(this.form,e);var t=this.page;Me.hide(t.cexConfigPrompt,t.cexConnectErrBox,t.cexFormErr),t.cexApiKeyInput.value="",t.cexSecretInput.value="";var n=ht().mmStatus.cexes[e],r=null==n?void 0:n.connectErr;r?(Me.show(t.cexConnectErrBox),t.cexConnectErr.textContent=r,t.cexApiKeyInput.value=n.config.apiKey,t.cexSecretInput.value=n.config.apiSecret):Me.show(t.cexConfigPrompt)}},{key:"submit",value:(t=s(f().mark((function e(){var t,n,r,a,o,s,i,c;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=this.page,n=this.cexName,r=this.form,Me.hide(t.cexFormErr),a=t.cexApiKeyInput.value,o=t.cexSecretInput.value,a&&o){e.next=8;break}return Me.show(t.cexFormErr),t.cexFormErr.textContent=be(R),e.abrupt("return");case 8:return s=ht().loading(r),e.prev=9,e.next=12,ar.updateCEXConfig({name:n,apiKey:a,apiSecret:o});case 12:if(i=e.sent,ht().checkResponse(i)){e.next=15;break}throw i;case 15:return e.next=17,ht().fetchMMStatus();case 17:this.success(n),e.next=25;break;case 20:return e.prev=20,e.t0=e.catch(9),Me.show(t.cexFormErr),t.cexFormErr.textContent=be(H,{msg:null!==(c=e.t0.msg)&&void 0!==c?c:String(e.t0)}),e.abrupt("return");case 25:return e.prev=25,s(),e.finish(25);case 28:case"end":return e.stop()}}),e,this,[[9,20,25,28]])}))),function(){return t.apply(this,arguments)})}]),e}(),Mr=300;function qr(e,t){return Nr.apply(this,arguments)}function Nr(){return(Nr=s(f().mark((function e(t,n){var r;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=document.body.offsetWidth/2,e.next=3,Me.animate(Mr,(function(e){t.style.right="".concat(e*r,"px")}),"easeInHard");case 3:return Me.hide(t),t.style.right="0",n.style.right=String(-r),Me.show(n),n.querySelector("input")&&Me.safeSelector(n,"input").focus(),e.next=10,Me.animate(Mr,(function(e){n.style.right="".concat(e*r-r,"px")}),"easeOutHard");case 10:n.style.right="0";case 11:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function Wr(e,t){e.successMessage.textContent=t,Me.show(e.forms,e.checkmarkForm),e.checkmarkForm.style.right="0",e.checkmark.style.fontSize="0px";var n=a(k.isDark()?[223,226,225]:[51,51,51],3),r=n[0],o=n[1],s=n[2],i=16-r,c=163-o,l=16-s;return new qe(1200,(function(t){e.checkmark.style.fontSize="".concat(80*t,"px"),e.checkmark.style.color="rgb(".concat(r+t*i,", ").concat(o+t*c,", ").concat(s+t*l,")")}),"easeOutElastic")}function Vr(e,t,n){var r=function(e){e.preventDefault&&e.preventDefault(),n(e)};Me.bind(t,"click",r),Me.bind(e,"submit",r)}function Ur(e){return Math.floor(e.getTime()/1e3)}function _r(e){return function(e){return new Date(e.getTime()-60*e.getTimezoneOffset()*1e3)}(e).toISOString().split("T")[0]}function jr(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,i=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){i=!0,o=e},f:function(){try{s||null==n.return||n.return()}finally{if(i)throw o}}}}(e.querySelectorAll(".form-closer"));try{for(o.s();!(a=o.n()).done;){var c=a.value;c!==r.resetPassFormCloser&&Me.hide(c)}}catch(e){o.e(e)}finally{o.f()}n.newWalletForm=new kr(r.newWalletForm,(function(e){return n.newWalletCreated(e,n.confirmRegisterForm.tier)}),(function(){return n.animateRegAsset(r.newWalletForm)})),n.dexAddrForm=new Ir(r.dexAddrForm,function(){var e=s(f().mark((function e(t,a){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n.requestFeepayment(r.dexAddrForm,t,a);case 1:case"end":return e.stop()}}),e)})));return function(t,n){return e.apply(this,arguments)}}());var l=r.discoverAcctForm.dataset.host;l&&(n.discoverAcctForm=new Ar(r.discoverAcctForm,l,function(){var e=s(f().mark((function e(t){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n.requestFeepayment(r.discoverAcctForm,t,"");case 1:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}())),n.regAssetForm=new Fr(r.regAssetForm,function(){var e=s(f().mark((function e(t,a){var o,s,i,c;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t!==dt){e.next=3;break}return n.registerDEXSuccess(),e.abrupt("return");case 3:if(o=ht().assets[t],!(s=o.wallet)){e.next=17;break}return i=n.xc.bondAssets[o.symbol],e.next=9,n.getBondsFeeBuffer(t,r.regAssetForm);case 9:if(c=e.sent,n.confirmRegisterForm.setAsset(t,a,c),!(s.synced&&s.balance.available>=2*i.amount+c)){e.next=14;break}return n.animateConfirmForm(r.regAssetForm),e.abrupt("return");case 14:return n.walletWaitForm.setWallet(t,c,a),qr(r.regAssetForm,r.walletWait),e.abrupt("return");case 17:n.confirmRegisterForm.tier=a,n.newWalletForm.setAsset(t),qr(r.regAssetForm,r.newWalletForm);case 20:case"end":return e.stop()}}),e)})));return function(t,n){return e.apply(this,arguments)}}()),n.walletWaitForm=new Tr(r.walletWait,(function(){n.animateConfirmForm(r.walletWait)}),(function(){n.animateRegAsset(r.walletWait)})),n.confirmRegisterForm=new Cr(r.confirmRegForm,(function(){n.registerDEXSuccess()}),(function(){n.animateRegAsset(r.confirmRegForm)}));var u=Me.safeSelector(r.forms,":scope > form.selected");switch(u.classList.remove("selected"),u){case r.dexAddrForm:n.dexAddrForm.animate();break;case r.discoverAcctForm:n.discoverAcctForm.animate()}return Me.show(u),u===r.discoverAcctForm&&n.discoverAcctForm.page.submit.click(),ht().authed&&n.auth(),n}return d(k,[{key:"auth",value:(u=s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,ht().fetchUser();case 2:case"end":return e.stop()}}),e)}))),function(){return u.apply(this,arguments)})},{key:"requestFeepayment",value:(l=s(f().mark((function e(t,n,r){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:this.xc=n,this.confirmRegisterForm.setExchange(n,r),this.walletWaitForm.setExchange(n),this.regAssetForm.setExchange(n,r),this.animateRegAsset(t);case 5:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return l.apply(this,arguments)})},{key:"animateRegAsset",value:(c=s(f().mark((function e(t){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:Me.hide(t),this.regAssetForm.animate(),Me.show(this.page.regAssetForm);case 3:case"end":return e.stop()}}),e,this)}))),function(e){return c.apply(this,arguments)})},{key:"animateConfirmForm",value:(o=s(f().mark((function e(t){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:this.confirmRegisterForm.animate(),Me.hide(t),Me.show(this.page.confirmRegForm);case 3:case"end":return e.stop()}}),e,this)}))),function(e){return o.apply(this,arguments)})},{key:"getBondsFeeBuffer",value:(a=s(f().mark((function e(t,n){var r,a;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=ht().loading(n),e.next=3,C("/api/bondsfeebuffer",{assetID:t});case 3:if(a=e.sent,r(),ht().checkResponse(a)){e.next=7;break}return e.abrupt("return",0);case 7:return e.abrupt("return",a.feeBuffer);case 8:case"end":return e.stop()}}),e)}))),function(e,t){return a.apply(this,arguments)})},{key:"getCertFile",value:(r=s(f().mark((function e(){var t,n;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t="",!this.dexAddrForm.page.certFile.value){e.next=7;break}if(!(n=this.dexAddrForm.page.certFile.files)||!n.length){e.next=7;break}return e.next=6,n[0].text();case 6:t=e.sent;case 7:return e.abrupt("return",t);case 8:case"end":return e.stop()}}),e,this)}))),function(){return r.apply(this,arguments)})},{key:"registerDEXSuccess",value:(n=s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,ht().fetchUser();case 2:return ht().updateMenuItemsDisplay(),e.next=5,ht().loadPage(this.data.backTo||"markets");case 5:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"newWalletCreated",value:(t=s(f().mark((function e(t,n){var r,a,o,s,i,c;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.regAssetForm.refresh(),e.next=3,ht().fetchUser();case 3:if(r=e.sent){e.next=6;break}return e.abrupt("return");case 6:return a=this.page,o=r.assets[t],s=o.wallet,i=this.xc.bondAssets[o.symbol].amount,e.next=12,this.getBondsFeeBuffer(t,a.newWalletForm);case 12:if(c=e.sent,this.walletWaitForm.setWallet(t,c,n),this.confirmRegisterForm.setAsset(t,n,c),!(s.synced&&s.balance.available>=2*i+c)){e.next=19;break}return e.next=18,this.animateConfirmForm(a.newWalletForm);case 18:return e.abrupt("return");case 19:return e.next=21,qr(a.newWalletForm,a.walletWait);case 21:case"end":return e.stop()}}),e,this)}))),function(e,n){return t.apply(this,arguments)})}]),k}(it);var zr=function(e){g(o,e);var t,n,r,a=(n=o,r=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}(),function(){var e,t=b(n);if(r){var a=b(this).constructor;e=Reflect.construct(t,arguments,a)}else e=t.apply(this,arguments);return y(this,e)});function o(e){var t;i(this,o),h(v(t=a.call(this)),"loginForm",void 0),h(v(t),"page",void 0),h(v(t),"appPassResetForm",void 0);var n=t.page=Me.idDescendants(e);t.loginForm=new Rr(n.loginForm,(function(){t.loggedIn()}));var r=function(){Me.hide(n.resetAppPWForm),t.loginForm.refresh(),Me.show(n.loginForm),t.loginForm.focus()};return r(),t.appPassResetForm=new Br(n.resetAppPWForm,(function(){r()})),Me.bind(n.forgotPassBtn,"click",(function(){t.appPassResetForm.refresh(),qr(n.loginForm,n.resetAppPWForm)})),Me.bind(n.resetPassFormCloser,"click",(function(){r()})),Me.bind(n.forms,"mousedown",(function(e){!Me.mouseInElement(e,n.resetAppPWForm)&&Me.isDisplayed(n.resetAppPWForm)&&r()})),t}return d(o,[{key:"loggedIn",value:(t=s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,ht().loadPage("wallets");case 2:case"end":return e.stop()}}),e)}))),function(){return t.apply(this,arguments)})}]),o}(it);function Gr(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return Xr(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Xr(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e){throw e})),f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,i=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e){i=!0,o=e})),f:function(){try{s||null==n.return||n.return()}finally{if(i)throw o}}}}function Xr(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n form"),r.forms.querySelectorAll(".form-closer").forEach((function(e){Me.bind(e,"click",(function(){n.closePopups()}))})),Me.bind(r.cancelForce,"click",(function(){n.closePopups()})),n.selectedAssetID=-1,Me.cleanTemplates(r.iconSelectTmpl,r.balanceDetailRow,r.recentOrderTmpl,r.vspRowTmpl,r.ticketHistoryRowTmpl,r.votingChoiceTmpl,r.votingAgendaTmpl,r.tspendTmpl,r.tkeyTmpl,r.txHistoryRowTmpl,r.txHistoryDateRowTmpl),Me.bind(r.createWallet,"click",(function(){return n.showNewWallet(n.selectedAssetID)})),Me.bind(r.connectBttn,"click",(function(){return n.doConnect(n.selectedAssetID)})),Me.bind(r.send,"click",(function(){return n.showSendForm(n.selectedAssetID)})),Me.bind(r.receive,"click",(function(){return n.showDeposit(n.selectedAssetID)})),Me.bind(r.unlockBttn,"click",(function(){return n.openWallet(n.selectedAssetID)})),Me.bind(r.lockBttn,"click",(function(){return n.lock(n.selectedAssetID)})),Me.bind(r.reconfigureBttn,"click",(function(){return n.showReconfig(n.selectedAssetID)})),Me.bind(r.needsProviderBttn,"click",(function(){return n.showReconfig(n.selectedAssetID)})),Me.bind(r.rescanWallet,"click",(function(){return n.rescanWallet(n.selectedAssetID)})),Me.bind(r.earlierTxs,"click",(function(){return n.loadEarlierTxs()})),Me.bind(r.copyTxIDBtn,"click",(function(){var e;tt((null===(e=n.currTx)||void 0===e?void 0:e.id)||"",r.txDetailsID,r.copyTxIDBtn,"#1e7d11")})),Me.bind(r.copyRecipientBtn,"click",(function(){var e;tt((null===(e=n.currTx)||void 0===e?void 0:e.recipient)||"",r.txDetailsRecipient,r.copyRecipientBtn,"#1e7d11")})),Me.bind(r.copyBondIDBtn,"click",(function(){var e,t;tt((null===(e=n.currTx)||void 0===e||null===(t=e.bondInfo)||void 0===t?void 0:t.bondID)||"",r.txDetailsBondID,r.copyBondIDBtn,"#1e7d11")})),Me.bind(r.copyBondAccountIDBtn,"click",(function(){var e,t;tt((null===(e=n.currTx)||void 0===e||null===(t=e.bondInfo)||void 0===t?void 0:t.accountID)||"",r.txDetailsBondAccountID,r.copyBondAccountIDBtn,"#1e7d11")})),Me.bind(r.hideMixTxsCheckbox,"change",(function(){n.showTxHistory(n.selectedAssetID)})),n.newWalletForm=new kr(r.newWalletForm,(function(e){var t={assetName:ht().assets[e].name};n.assetUpdated(e,r.newWalletForm,be("NEW_WALLET_SUCCESS",t)),n.sortAssetButtons(),n.updateTicketBuyer(e),n.updatePrivacy(e)})),n.reconfigForm=new Sr(r.reconfigInputs,!1),n.walletCfgGuide=Me.tmplElement(r.reconfigForm,"walletCfgGuide"),Vr(r.sendForm,r.submitSendForm,s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n.stepSend();case 1:case"end":return e.stop()}}),e)})))),Vr(r.vSendForm,r.vSend,s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n.send();case 1:case"end":return e.stop()}}),e)})))),Vr(r.reconfigForm,r.submitReconfig,(function(){return n.reconfig()})),r.forms.querySelectorAll(".form-closer").forEach((function(e){Me.bind(e,"click",(function(){return n.closePopups()}))})),Me.bind(r.forms,"mousedown",(function(e){Me.mouseInElement(e,n.currentForm)||n.closePopups()})),n.mixerToggle=new Ve(r.toggleMixer,r.mixingErr,!1,(function(e){return n.updateMixerState(e)})),n.keyup=function(e){"Escape"===e.key&&Me.isDisplayed(n.page.forms)&&n.closePopups()},Me.bind(document,"keyup",n.keyup),Me.bind(r.downloadLogs,"click",s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n.downloadLogs();case 1:case"end":return e.stop()}}),e)})))),Me.bind(r.exportWallet,"click",s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n.displayExportWalletAuth();case 1:case"end":return e.stop()}}),e)})))),Me.bind(r.recoverWallet,"click",s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n.showRecoverWallet();case 1:case"end":return e.stop()}}),e)})))),Vr(r.exportWalletAuth,r.exportWalletAuthSubmit,s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n.exportWalletAuthSubmit();case 1:case"end":return e.stop()}}),e)})))),Vr(r.recoverWalletConfirm,r.recoverWalletSubmit,(function(){n.recoverWallet()})),Vr(r.confirmForce,r.confirmForceSubmit,s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n.confirmForceSubmit();case 1:case"end":return e.stop()}}),e)})))),Me.bind(r.disableWallet,"click",s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n.showToggleWalletStatus(!0);case 1:case"end":return e.stop()}}),e)})))),Me.bind(r.enableWallet,"click",s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n.showToggleWalletStatus(!1);case 1:case"end":return e.stop()}}),e)})))),Vr(r.toggleWalletStatusConfirm,r.toggleWalletStatusSubmit,s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n.toggleWalletStatus();case 1:case"end":return e.stop()}}),e)})))),Me.bind(r.managePeers,"click",s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n.showManagePeersForm();case 1:case"end":return e.stop()}}),e)})))),Me.bind(r.addPeerSubmit,"click",s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n.submitAddPeer();case 1:case"end":return e.stop()}}),e)})))),Me.bind(r.unapproveTokenAllowance,"click",s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n.showUnapproveTokenAllowanceTableForm();case 1:case"end":return e.stop()}}),e)})))),Me.bind(r.unapproveTokenSubmit,"click",s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n.submitUnapproveTokenAllowance();case 1:case"end":return e.stop()}}),e)})))),Me.bind(r.showVSPs,"click",(function(){n.showVSPPicker()})),Me.bind(r.vspDisplay,"click",(function(){n.showVSPPicker()})),Vr(r.vspPicker,r.customVspSubmit,s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n.setCustomVSP();case 1:case"end":return e.stop()}}),e)})))),Me.bind(r.purchaseTicketsBttn,"click",(function(){n.showPurchaseTicketsDialog()})),Vr(r.purchaseTicketsForm,r.purchaserSubmit,(function(){n.purchaseTickets()})),Me.bind(r.purchaserInput,"change",(function(){n.purchaserInputChanged()})),Me.bind(r.ticketHistory,"click",(function(){n.showTicketHistory()})),Me.bind(r.ticketHistoryNextPage,"click",(function(){n.nextTicketPage()})),Me.bind(r.ticketHistoryPrevPage,"click",(function(){n.prevTicketPage()})),Me.bind(r.setVotes,"click",(function(){n.showSetVotesDialog()})),Me.bind(r.purchaseTicketsErrCloser,"click",(function(){Me.hide(r.purchaseTicketsErrBox)})),Me.bind(r.privacyInfoBttn,"click",(function(){n.showForm(r.mixingInfo)})),n.depositAddrForm=new Er(r.deposit),Me.bind(r.walletBal,"click",(function(){n.populateMaxSend()})),Me.bind(r.sendAmt,"input",(function(){var e=ht().assets[n.selectedAssetID].unitInfo,t=$e(r.sendAmt.value),a=e.conventional.conversionFactor;Me.showFiatValue(r.sendValue,t*a,ht().fiatRatesMap[n.selectedAssetID],e)})),Me.bind(r.maxSend,"click",(function(){n.populateMaxSend()})),Me.bind(r.sendAddr,"input",s(f().mark((function e(){var t,a;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=ht().assets[n.selectedAssetID],Me.hide(r.validAddr),r.sendAddr.classList.remove("is-invalid"),a=r.sendAddr.value||"",t&&""!==a){e.next=6;break}return e.abrupt("return");case 6:return e.next=8,n.validateSendAddress(a,t.id);case 8:e.sent?Me.show(r.validAddr):r.sendAddr.classList.add("is-invalid");case 10:case"end":return e.stop()}}),e)})))),Me.bind(r.showChangePW,"click",(function(){n.changeWalletPW=!n.changeWalletPW,n.setPWSettingViz(n.changeWalletPW)})),Me.bind(r.changeWalletTypeSelect,"change",(function(){n.changeWalletType()})),Me.bind(r.showChangeType,"click",(function(){Me.isHidden(r.changeWalletType)?(Me.show(r.changeWalletType,r.changeTypeHideIcon),Me.hide(r.changeTypeShowIcon),r.changeTypeMsg.textContent=be("KEEP_WALLET_TYPE")):n.showReconfig(n.selectedAssetID,{skipAnimation:!0})})),ht().registerNoteFeeder({fiatrateupdate:function(e){n.handleRatesNote(e)},balance:function(e){n.handleBalanceNote(e)},walletstate:function(e){n.handleWalletStateNote(e)},walletconfig:function(e){n.handleWalletStateNote(e)},walletsync:function(e){n.updateSyncAndPeers(e.assetID)},createwallet:function(e){n.handleCreateWalletNote(e)},walletnote:function(e){n.handleCustomWalletNote(e)}});var a=n.sortAssetButtons().id,o=k.fetchLocal(k.selectedAssetLK);return o&&(a=Number(o)),n.setSelectedAsset(a),setInterval((function(){var e,t=Gr(n.page.txHistoryTableBody.children);try{for(t.s();!(e=t.n()).done;){var r=e.value,a=Me.tmplElement(r,"age");a.textContent=Me.timeSince(parseInt(a.dataset.timestamp))}}catch(e){t.e(e)}finally{t.f()}}),5e3),n}return d(ve,[{key:"closePopups",value:function(){Me.hide(this.page.forms),this.currTx=void 0,this.animation&&this.animation.stop()}},{key:"safePost",value:(de=s(f().mark((function e(t,n){var r,a;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.selectedAssetID,e.next=3,C(t,n);case 3:if(a=e.sent,r===this.selectedAssetID){e.next=6;break}throw Error("asset changed during request. aborting");case 6:return e.abrupt("return",a);case 7:case"end":return e.stop()}}),e,this)}))),function(e,t){return de.apply(this,arguments)})},{key:"stepSend",value:(ue=s(f().mark((function e(){var t,n,r,a,o,s,i,c,l,u,d,h,p,v,m,g,y,b,x,k,w,S;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=this.page,Me.hide(t.vSendErr,t.sendErr,t.vSendEstimates,t.txFeeNotAvailable),n=parseInt(t.sendForm.dataset.assetID||""),r=ht().assets[n].token,a=t.subtractCheckBox.checked||!1,o=ht().unitInfo(n).conventional.conversionFactor,s=Math.round($e(t.sendAmt.value,0)*o),""!==(i=t.sendAddr.value||"")){e.next=10;break}return e.abrupt("return",Me.showFormError(t.sendErr,be(G,{address:i})));case 10:if(c=ht().assets[n],l=c.wallet,u=c.unitInfo,d=c.symbol,h=0,0==(512&l.traits)){e.next=36;break}return p={addr:t.sendAddr.value,assetID:n,subtract:a,value:s},v=ht().loading(t.sendForm),e.next=17,C("/api/txfee",p);case 17:if(m=e.sent,v(),ht().checkResponse(m)){e.next=29;break}return t.txFeeNotAvailable.dataset.tooltip=be("TXFEE_ERR_MSG",{err:m.msg}),Me.show(t.txFeeNotAvailable),e.next=24,this.validateSendAddress(i,n);case 24:if(e.sent){e.next=27;break}return e.abrupt("return",Me.showFormError(t.sendErr,be(G,{address:i||""})));case 27:e.next=34;break;case 29:if(!m.ok){e.next=34;break}if(m.validaddress){e.next=32;break}return e.abrupt("return",Me.showFormError(t.sendErr,be(G,{address:t.sendAddr.value||""})));case 32:h=m.txfee,Me.show(t.vSendEstimates);case 34:e.next=41;break;case 36:return e.next=38,this.validateSendAddress(i,n);case 38:if(e.sent){e.next=41;break}return e.abrupt("return",Me.showFormError(t.sendErr,be(G,{address:i||""})));case 41:return t.vSendSymbol.textContent=d.toUpperCase(),t.vSendLogo.src=Me.logoPath(d),r?(g=ht().assets[r.parentID],y=g.unitInfo,b=g.symbol,t.vSendFee.textContent=Me.formatFullPrecision(h,y)+" "+b):t.vSendFee.textContent=Me.formatFullPrecision(h,u),x=ht().fiatRatesMap[n],Me.showFiatValue(t.vSendFeeFiat,h,x,u),t.vSendDestinationAmt.textContent=Me.formatFullPrecision(s-h,u),t.vTotalSend.textContent=Me.formatFullPrecision(s,u),Me.showFiatValue(t.vTotalSendFiat,s,x,u),t.vSendAddr.textContent=t.sendAddr.value||"",k=l.balance.available-s,t.balanceAfterSend.textContent=Me.formatFullPrecision(k,u),Me.showFiatValue(t.balanceAfterSendFiat,k,x,u),Me.show(t.approxSign),a||(Me.hide(t.approxSign),t.vSendDestinationAmt.textContent=Me.formatFullPrecision(s,u),w=s,r||(w+=h),t.vTotalSend.textContent=Me.formatFullPrecision(w,u),Me.showFiatValue(t.vTotalSendFiat,w,x,u),S=l.balance.available-s,r||(S-=h),S<=0?(t.balanceAfterSend.textContent=Me.formatFullPrecision(0,u),Me.showFiatValue(t.balanceAfterSendFiat,0,x,u)):(t.balanceAfterSend.textContent=Me.formatFullPrecision(S,u),Me.showFiatValue(t.balanceAfterSendFiat,S,x,u))),Me.hide(t.sendForm),e.next=58,this.showForm(t.vSendForm);case 58:case"end":return e.stop()}}),e,this)}))),function(){return ue.apply(this,arguments)})},{key:"cancelSend",value:(le=s(f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.page,Me.hide(t.vSendForm,t.sendErr),e.next=4,this.showForm(t.sendForm);case 4:case"end":return e.stop()}}),e,this)}))),function(){return le.apply(this,arguments)})},{key:"validateSendAddress",value:(ce=s(f().mark((function e(t,n){var r;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,C("/api/validateaddress",{addr:t,assetID:n});case 2:return r=e.sent,e.abrupt("return",ht().checkResponse(r));case 4:case"end":return e.stop()}}),e)}))),function(e,t){return ce.apply(this,arguments)})},{key:"setPWSettingViz",value:function(e){var t=this.page;if(e)return Me.hide(t.showIcon),Me.show(t.hideIcon,t.changePW),void(t.switchPWMsg.textContent=be("KEEP_WALLET_PASS"));Me.hide(t.hideIcon,t.changePW),Me.show(t.showIcon),t.switchPWMsg.textContent=be("NEW_WALLET_PASS")}},{key:"assetVersionUsedByDEXes",value:function(){var e=this.selectedAssetID,t={},n=ht().exchanges;for(var r in n){var a=n[r],o=a.assets[e];o&&(t[o.version]||(t[o.version]=[]),t[o.version].push(a.host))}return t}},{key:"submitUnapproveTokenAllowance",value:(ie=s(f().mark((function e(){var t,n,r;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.page,e.next=4,C("/api/unapprovetoken",{assetID:this.selectedAssetID,version:this.unapprovingTokenVersion});case 4:if(n=e.sent,ht().checkResponse(n)){e.next=9;break}return t.unapproveTokenErr.textContent=n.msg,Me.show(t.unapproveTokenErr),e.abrupt("return");case 9:(r=jn[this.selectedAssetID])&&r[oa]&&(t.unapproveTokenTxID.href=r[oa](n.txID)),t.unapproveTokenTxID.textContent=n.txID,Me.hide(t.unapproveTokenSubmissionElements,t.unapproveTokenErr),Me.show(t.unapproveTokenTxMsg);case 14:case"end":return e.stop()}}),e,this)}))),function(){return ie.apply(this,arguments)})},{key:"showUnapproveTokenAllowanceForm",value:(se=s(f().mark((function e(t){var n,r,a,o,s,i;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=this.page,this.unapprovingTokenVersion=t,Me.show(n.unapproveTokenSubmissionElements),Me.hide(n.unapproveTokenTxMsg,n.unapproveTokenErr),(r=ht().assets[this.selectedAssetID])&&r.token){e.next=7;break}return e.abrupt("return");case 7:if(a=ht().assets[r.token.parentID]){e.next=10;break}return e.abrupt("return");case 10:return Me.empty(n.tokenAllowanceRemoveSymbol),n.tokenAllowanceRemoveSymbol.appendChild(Me.symbolize(r,!0)),n.tokenAllowanceRemoveVersion.textContent=t.toString(),e.next=16,C("/api/approvetokenfee",{assetID:this.selectedAssetID,version:t,approving:!1});case 16:o=e.sent,ht().checkResponse(o)?(s="".concat(Me.formatCoinValue(o.txFee,a.unitInfo)," ").concat(a.unitInfo.conventional.unit),(i=ht().fiatRatesMap[a.id])&&(s+=" (".concat(Me.formatFiatConversion(o.txFee,i,a.unitInfo)," USD)")),n.unapprovalFeeEstimate.textContent=s):(n.unapproveTokenErr.textContent=o.msg,Me.show(n.unapproveTokenErr)),this.showForm(n.unapproveTokenForm);case 19:case"end":return e.stop()}}),e,this)}))),function(e){return se.apply(this,arguments)})},{key:"showUnapproveTokenAllowanceTableForm",value:(oe=s(f().mark((function e(){var t,n,r,a,o,s,i=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=this.page,(n=ht().assets[this.selectedAssetID])&&n.wallet&&n.wallet.approved){e.next=4;break}return e.abrupt("return");case 4:for(;t.tokenVersionBody.firstChild;)t.tokenVersionBody.removeChild(t.tokenVersionBody.firstChild);Me.empty(t.tokenVersionTableAssetSymbol),t.tokenVersionTableAssetSymbol.appendChild(Me.symbolize(n,!0)),r=this.assetVersionUsedByDEXes(),a=!1,o=f().mark((function e(o){var s,c,l,u;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(void 0!==(s=n.wallet.approved[o])&&s===lt.Approved){e.next=3;break}return e.abrupt("return","continue");case 3:a=!0,c=t.tokenVersionRow.cloneNode(!0),(l=Me.parseTemplate(c)).version.textContent=o.toString(),r[o]&&(l.usedBy.textContent=r[o].join(", ")),u=i.page.removeIconTmpl.cloneNode(!0),Me.bind(u,"click",(function(){i.showUnapproveTokenAllowanceForm(o)})),l.remove.appendChild(u),t.tokenVersionBody.appendChild(c);case 12:case"end":return e.stop()}}),e)})),s=0;case 11:if(!(s<=n.wallet.version)){e.next=19;break}return e.delegateYield(o(s),"t0",13);case 13:if("continue"!==e.t0){e.next=16;break}return e.abrupt("continue",16);case 16:s++,e.next=11;break;case 19:Me.setVis(a,t.tokenVersionTable),Me.setVis(!a,t.tokenVersionNone),this.showForm(t.unapproveTokenTableForm);case 22:case"end":return e.stop()}}),e,this)}))),function(){return oe.apply(this,arguments)})},{key:"updateWalletPeersTable",value:(ae=s(f().mark((function e(){var t,n,r,a,o,i,c=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.page,Me.hide(t.peerSpinner),e.next=4,C("/api/getwalletpeers",{assetID:this.selectedAssetID});case 4:if(n=e.sent,ht().checkResponse(n)){e.next=9;break}return t.managePeersErr.textContent=n.msg,Me.show(t.managePeersErr),e.abrupt("return");case 9:for(;t.peersTableBody.firstChild;)t.peersTableBody.removeChild(t.peersTableBody.firstChild);(r=n.peers||[]).sort((function(e,t){return e.source-t.source})),a=be("DEFAULT"),o=be("ADDED"),i=be("DISCOVERED"),r.forEach((function(e){var n,r=t.peerTableRow.cloneNode(!0),l=Me.parseTemplate(r);switch(l.addr.textContent=e.addr,e.source){case ut.WalletDefault:l.source.textContent=a;break;case ut.UserAdded:l.source.textContent=o;break;case ut.Discovered:l.source.textContent=i}if(n=e.connected?c.page.connectedIconTmpl.cloneNode(!0):c.page.disconnectedIconTmpl.cloneNode(!0),l.connected.appendChild(n),e.source===ut.UserAdded){var u=c.page.removeIconTmpl.cloneNode(!0);Me.bind(u,"click",s(f().mark((function n(){var r;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return Me.hide(t.managePeersErr),n.next=3,C("/api/removewalletpeer",{assetID:c.selectedAssetID,addr:e.addr});case 3:if(r=n.sent,ht().checkResponse(r)){n.next=8;break}return t.managePeersErr.textContent=r.msg,Me.show(t.managePeersErr),n.abrupt("return");case 8:c.spinUntilPeersUpdate();case 9:case"end":return n.stop()}}),n)})))),l.remove.appendChild(u)}t.peersTableBody.appendChild(r)}));case 16:case"end":return e.stop()}}),e,this)}))),function(){return ae.apply(this,arguments)})},{key:"showManagePeersForm",value:(re=s(f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.page,e.next=3,this.updateWalletPeersTable();case 3:Me.hide(t.managePeersErr),this.showForm(t.managePeersForm);case 5:case"end":return e.stop()}}),e,this)}))),function(){return re.apply(this,arguments)})},{key:"submitAddPeer",value:(ne=s(f().mark((function e(){var t,n;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.page,Me.hide(t.managePeersErr),e.next=4,C("/api/addwalletpeer",{assetID:this.selectedAssetID,addr:t.addPeerInput.value});case 4:if(n=e.sent,ht().checkResponse(n)){e.next=9;break}return t.managePeersErr.textContent=n.msg,Me.show(t.managePeersErr),e.abrupt("return");case 9:this.spinUntilPeersUpdate(),t.addPeerInput.value="";case 11:case"end":return e.stop()}}),e,this)}))),function(){return ne.apply(this,arguments)})},{key:"spinUntilPeersUpdate",value:(te=s(f().mark((function e(){var t,n=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=this.page,Me.show(t.peerSpinner),setTimeout((function(){Me.isDisplayed(t.peerSpinner)&&n.updateWalletPeersTable()}),1e4);case 3:case"end":return e.stop()}}),e,this)}))),function(){return te.apply(this,arguments)})},{key:"showToggleWalletStatus",value:function(e){var t=this.page;Me.hide(t.toggleWalletStatusErr,t.walletStatusDisable,t.disableWalletMsg,t.walletStatusEnable,t.enableWalletMsg),e?Me.show(t.walletStatusDisable,t.disableWalletMsg):Me.show(t.walletStatusEnable,t.enableWalletMsg),this.showForm(t.toggleWalletStatusConfirm)}},{key:"toggleWalletStatus",value:(ee=s(f().mark((function e(){var t,n,r,a,o,s,i,c;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.page,Me.hide(t.toggleWalletStatusErr),n=ht().assets[this.selectedAssetID],r=!n.wallet.disabled,a={assetID:this.selectedAssetID,disable:r},o={assetName:n.name},s=ht().loading(t.toggleWalletStatusConfirm),e.next=10,C("/api/togglewalletstatus",a);case 10:if(i=e.sent,s(),ht().checkResponse(i)){e.next=16;break}return i.code===A.activeOrdersErr?t.toggleWalletStatusErr.textContent=be("ACTIVE_ORDERS_ERR_MSG",o):t.toggleWalletStatusErr.textContent=i.msg,Me.show(t.toggleWalletStatusErr),e.abrupt("return");case 16:c=be("WALLET_DISABLED",o),r||(c=be("WALLET_ENABLED",o)),this.assetUpdated(this.selectedAssetID,t.toggleWalletStatusConfirm,c);case 19:case"end":return e.stop()}}),e,this)}))),function(){return ee.apply(this,arguments)})},{key:"showBox",value:($=s(f().mark((function e(t,n){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t.style.opacity="0",Me.show(t),n&&n.focus(),e.next=5,Me.animate(300,(function(e){t.style.opacity="".concat(e)}),"easeOut");case 5:t.style.opacity="1",this.displayed=t;case 7:case"end":return e.stop()}}),e,this)}))),function(e,t){return $.apply(this,arguments)})},{key:"showForm",value:(Z=s(f().mark((function e(t){var n,r;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=this.page,this.currentForm=t,this.forms.forEach((function(e){return Me.hide(e)})),t.style.right="10000px",Me.show(n.forms,t),r=(n.forms.offsetWidth+t.offsetWidth)/2,e.next=8,Me.animate(300,(function(e){t.style.right="".concat((1-e)*r,"px")}),"easeOutHard");case 8:t.style.right="0";case 9:case"end":return e.stop()}}),e,this)}))),function(e){return Z.apply(this,arguments)})},{key:"showSuccess",value:(J=s(f().mark((function e(t){var n=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.forms.forEach((function(e){return Me.hide(e)})),this.currentForm=this.page.checkmarkForm,this.animation=Wr(this.page,t),e.next=5,this.animation.wait();case 5:this.animation=new qe(1500,(function(){}),"",(function(){n.currentForm===n.page.checkmarkForm&&n.closePopups()}));case 6:case"end":return e.stop()}}),e,this)}))),function(e){return J.apply(this,arguments)})},{key:"showNewWallet",value:(Y=s(f().mark((function e(t){var n,r,a;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=this.page,r=n.newWalletForm,this.newWalletForm.setAsset(t),a=this.newWalletForm.loadDefaults(),e.next=6,this.showForm(r);case 6:return e.next=8,a;case 8:case"end":return e.stop()}}),e,this)}))),function(e){return Y.apply(this,arguments)})},{key:"sortAssetButtons",value:function(){var e=this,t=this.page;this.assetButtons={},Me.empty(t.assetSelect);var n=r(Object.values(ht().assets));n.sort((function(e,t){if(e.wallet&&!t.wallet)return-1;if(!e.wallet&&t.wallet)return 1;if(!e.wallet&&!t.wallet)return"dcr"===e.symbol?-1:1;var n=[e.wallet.balance,t.wallet.balance],r=n[0],a=n[1],o=r.available+r.immature+r.locked,s=a.available+a.immature+a.locked;if(0===o&&0===s)return e.symbol.localeCompare(t.symbol);if(0===o)return 1;if(0===o)return-1;var i=[ht().fiatRatesMap[e.id],ht().fiatRatesMap[t.id]],c=i[0],l=i[1];return c&&!l?-1:!c&&l?1:l*s-c*o}));var a,o=Gr(n);try{var s=function(){var n=a.value,r=t.iconSelectTmpl.cloneNode(!0);t.assetSelect.appendChild(r);var o=Me.parseTemplate(r);e.assetButtons[n.id]={tmpl:o,bttn:r},e.updateAssetButton(n.id),Me.bind(r,"click",(function(){e.setSelectedAsset(n.id),k.storeLocal(k.selectedAssetLK,String(n.id))}))};for(o.s();!(a=o.n()).done;)s()}catch(e){o.e(e)}finally{o.f()}return t.assetSelect.classList.remove("invisible"),n[0]}},{key:"updateAssetButton",value:function(e){var t,n=ht().assets[e],r=this.assetButtons[e],o=r.bttn,s=r.tmpl;Me.hide(s.fiatBox,s.noWallet),o.classList.add("nowallet"),(t=s.img).src||(t.src=Me.logoPath(n.symbol));var i=n.symbol.split(".");if(2===i.length){var c,l=i[1];s.parentImg.classList.remove("d-hide"),(c=s.parentImg).src||(c.src=Me.logoPath(l))}if(this.selectedAssetID===e&&o.classList.add("selected"),s.name.textContent=n.name,n.wallet){o.classList.remove("nowallet");var u=n.wallet.balance,d=n.unitInfo,h=u.available+u.locked+u.immature,p=a(Me.formatBestUnitsFourSigFigs(h,d),2),f=p[0],v=p[1];s.balance.textContent=f,s.unit.textContent=v,Me.show(s.balanceBox);var m=ht().fiatRatesMap[n.id];m&&(Me.show(s.fiatBox),s.fiat.textContent=Me.formatFourSigFigs(h/d.conventional.conversionFactor*m))}else Me.show(s.noWallet)}},{key:"setSelectedAsset",value:(Q=s(f().mark((function e(t){var n,r,a,o,s,i,c,l,u,d;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=this.page.assetSelect,r=Gr(n.children);try{for(r.s();!(a=r.n()).done;)a.value.classList.remove("selected")}catch(e){r.e(e)}finally{r.f()}this.assetButtons[t].bttn.classList.add("selected"),this.selectedAssetID=t,this.page.hideMixTxsCheckbox.checked=!0,this.updateDisplayedAsset(t),this.showAvailableMarkets(t),o=this.showRecentActivity(t),s=this.showTxHistory(t),i=this.updateTicketBuyer(t),c=this.updatePrivacy(t),l=0,u=[o,s,i,c];case 13:if(!(l=o.targetHeight)Me.show(t.txFindingAddrs);else{Me.show(t.txProgress);var c=o.txs/o.targetHeight;t.txProgress.textContent="".concat((100*c).toFixed(1),"%")}}}},{key:"updateFeeState",value:function(e){var t=this.page,n=this.selectedAssetID;Me.hide(t.feeStateBox);var r=ht().assets[n],a=r.unitInfo,o=r.token,s=ht().fiatRatesMap[n];if(s){var i=o?o.parentID:n,c=ht().fiatRatesMap[i];if(!o||c){Me.show(t.feeStateBox);var l=o?ht().assets[o.parentID].unitInfo:a;Me.formatBestRateElement(t.feeStateNetRate,i,e.rate,l),Me.formatBestValueElement(t.feeStateSendFees,i,e.send,l),Me.formatBestValueElement(t.feeStateSwapFees,i,e.swap,l),Me.formatBestValueElement(t.feeStateRedeemFees,i,e.redeem,l),t.feeStateXcRate.textContent=Me.formatFourSigFigs(s);var u=e.send/l.conventional.conversionFactor*c;t.feeStateSendFiat.textContent=Me.formatFourSigFigs(u);var d=e.swap/l.conventional.conversionFactor*c;t.feeStateSwapFiat.textContent=Me.formatFourSigFigs(d);var h=e.redeem/l.conventional.conversionFactor*c;t.feeStateRedeemFiat.textContent=Me.formatFourSigFigs(h),Me.show(t.feeStateBox)}}}},{key:"checkNeedsProvider",value:(K=s(f().mark((function e(t){var n,r,a,o;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,ht().needsCustomProvider(t);case 2:if(n=e.sent,r=this.page,a=r.needsProviderBox,o=r.needsProviderBttn,Me.setVis(n,a),n){e.next=7;break}return e.abrupt("return");case 7:Me.blink(o);case 8:case"end":return e.stop()}}),e,this)}))),function(e){return K.apply(this,arguments)})},{key:"updateTicketBuyer",value:(X=s(f().mark((function e(t){var n,r,a,o,s,i,c,l;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.ticketPage={number:0,history:[],scanned:!1},r=ht().assets[t],a=r.wallet,o=r.unitInfo,s=this.page,Me.hide(s.stakingBox,s.pickVSP,s.stakingSummary,s.stakingErr,s.vspDisplayBox,s.ticketPriceBox,s.purchaseTicketsBox,s.stakingRpcSpvMsg,s.ticketsDisabled),null!=a&&a.running&&0!=(32768&a.traits)){e.next=6;break}return e.abrupt("return");case 6:return Me.show(s.stakingBox),i=ht().loading(s.stakingBox),e.next=10,this.safePost("/api/stakestatus",t);case 10:if(c=e.sent,i(),ht().checkResponse(c)){e.next=19;break}if(!c.msg.includes("disconnected from consensus RPC")){e.next=16;break}return Me.show(s.stakingRpcSpvMsg),e.abrupt("return");case 16:return Me.show(s.stakingErr),s.stakingErr.textContent=c.msg,e.abrupt("return");case 19:if(Me.show(s.stakingSummary,s.ticketPriceBox),l=c.status,this.stakeStatus=l,s.stakingAgendaCount.textContent=String(l.stances.agendas.length),s.stakingTspendCount.textContent=String(l.stances.tspends.length),s.purchaserCurrentPrice.textContent=Me.formatFourSigFigs(l.ticketPrice/o.conventional.conversionFactor),s.purchaserBal.textContent=Me.formatCoinValue(a.balance.available,o),this.updateTicketStats(l.stats,o,l.ticketPrice,l.votingSubsidy),!(null===(n=ht().extensionWallet(this.selectedAssetID))||void 0===n?void 0:n.disableStaking)){e.next=33;break}return Me.hide(s.setVotes,s.showVSPs),Me.show(s.ticketsDisabled),s.extensionModeAppName.textContent=ht().user.extensionModeConfig.name,e.abrupt("return");case 33:this.setVSPViz(l.vsp);case 34:case"end":return e.stop()}}),e,this)}))),function(e){return X.apply(this,arguments)})},{key:"setVSPViz",value:function(e){var t=this.page,n=this.stakeStatus;if(Me.hide(t.vspDisplayBox),e)return Me.show(t.vspDisplayBox,t.purchaseTicketsBox),Me.hide(t.pickVSP),void(t.vspURL.textContent=e);Me.setVis(!n.isRPC,t.pickVSP),Me.setVis(n.isRPC,t.purchaseTicketsBox)}},{key:"updateTicketStats",value:function(e,t,n,r){var a=this.page,o=this.stakeStatus;o.stats=e,n&&(o.ticketPrice=n),r&&(o.votingSubsidy=r);var s=o.tickets.filter((function(e){return e.status<=3&&e.status>=1})).length;a.stakingTicketCount.textContent=String(s),a.immatureTicketCount.textContent=String(e.mempool),Me.setVis(e.mempool>0,a.immatureTicketCountBox),a.queuedTicketCount.textContent=String(e.queued),a.formQueuedTix.textContent=String(e.queued),Me.setVis(e.queued>0,a.formQueueTixBox,a.queuedTicketCountBox),a.totalTicketCount.textContent=String(e.ticketCount),a.totalTicketRewards.textContent=Me.formatFourSigFigs(e.totalRewards/t.conventional.conversionFactor),a.totalTicketVotes.textContent=String(e.votes),n&&(a.ticketPrice.textContent=Me.formatFourSigFigs(n/t.conventional.conversionFactor)),r&&(a.votingSubsidy.textContent=Me.formatFourSigFigs(r/t.conventional.conversionFactor))}},{key:"showVSPPicker",value:(z=s(f().mark((function e(){var t,n,r,a,o,s,i,c,l=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.selectedAssetID,n=this.page,this.showForm(n.vspPicker),Me.empty(n.vspPickerList),Me.hide(n.stakingErr),r=ht().loading(n.vspPicker),e.next=8,this.safePost("/api/listvsps",t);case 8:if(a=e.sent,r(),ht().checkResponse(a)){e.next=14;break}return Me.show(n.stakingErr),n.stakingErr.textContent=a.msg,e.abrupt("return");case 14:o=a.vsps,s=Gr(o),e.prev=16,c=f().mark((function e(){var r,a,o;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:r=i.value,a=n.vspRowTmpl.cloneNode(!0),n.vspPickerList.appendChild(a),(o=Me.parseTemplate(a)).url.textContent=r.url,o.feeRate.textContent=r.feePercentage.toFixed(2),o.voting.textContent=String(r.voting),Me.bind(a,"click",(function(){Me.hide(n.stakingErr),l.setVSP(t,r)}));case 8:case"end":return e.stop()}}),e)})),s.s();case 19:if((i=s.n()).done){e.next=23;break}return e.delegateYield(c(),"t0",21);case 21:e.next=19;break;case 23:e.next=28;break;case 25:e.prev=25,e.t1=e.catch(16),s.e(e.t1);case 28:return e.prev=28,s.f(),e.finish(28);case 31:case"end":return e.stop()}}),e,this,[[16,25,28,31]])}))),function(){return z.apply(this,arguments)})},{key:"showPurchaseTicketsDialog",value:function(){var e=this.page;e.purchaserInput.value="",Me.hide(e.purchaserErr),this.showForm(this.page.purchaseTicketsForm),e.purchaserInput.focus()}},{key:"purchaserInputChanged",value:function(){var e=this.page,t=parseInt(e.purchaserInput.value||"0");e.purchaserInput.value=t<=1?"1":String(t)}},{key:"purchaseTickets",value:(j=s(f().mark((function e(){var t,n,r,a,o;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=this.page,n=this.selectedAssetID,!((r=parseInt(t.purchaserInput.value||"0"))<1)){e.next=4;break}return e.abrupt("return");case 4:return a=ht().loading(t.purchaseTicketsForm),e.next=7,this.safePost("/api/purchasetickets",{assetID:n,n:r});case 7:if(o=e.sent,a(),ht().checkResponse(o)){e.next=13;break}return t.purchaserErr.textContent=o.msg,Me.show(t.purchaserErr),e.abrupt("return");case 13:this.showSuccess(be("TICKETS_PURCHASED",{n:r.toLocaleString(Me.languages())}));case 14:case"end":return e.stop()}}),e,this)}))),function(){return j.apply(this,arguments)})},{key:"processTicketPurchaseUpdate",value:function(e){var t=this.stakeStatus,n=this.selectedAssetID,r=this.page,a=e.assetID,o=e.payload,s=o.err,i=o.remaining,c=o.tickets,l=o.stats;if(a===n){if(s)return Me.show(r.purchaseTicketsErrBox),void(r.purchaseTicketsErr.textContent=s);c&&(t.tickets=c.concat(t.tickets)),l&&this.updateTicketStats(l,ht().assets[a].unitInfo),t.stats.queued=i,r.queuedTicketCount.textContent=String(i),r.formQueuedTix.textContent=String(i),Me.setVis(i>0,r.queuedTicketCountBox)}}},{key:"setVSP",value:(_=s(f().mark((function e(t,n){var r,a,o;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.closePopups(),r=this.page,a=ht().loading(r.stakingBox),e.next=5,this.safePost("/api/setvsp",{assetID:t,url:n.url});case 5:if(o=e.sent,a(),ht().checkResponse(o)){e.next=11;break}return Me.show(r.stakingErr),r.stakingErr.textContent=o.msg,e.abrupt("return");case 11:this.setVSPViz(n.url);case 12:case"end":return e.stop()}}),e,this)}))),function(e,t){return _.apply(this,arguments)})},{key:"setCustomVSP",value:function(){var e=this.selectedAssetID,t={url:this.page.customVspUrl.value};this.setVSP(e,t)}},{key:"pageOfTickets",value:function(e){var t=this.stakeStatus,n=this.ticketPage,a=e*aa,o=[];if(a0?o.history:a.tickets,d=u.length>0?u[u.length-1].tx.blockHeight:-1,h=u.filter((function(e){return e.tx.blockHeight===d})).length,p=ht().loading(n.ticketHistoryForm),e.next=10,this.safePost("/api/ticketpage",{assetID:s,scanStart:d,n:l,skipN:h});case 10:if(v=e.sent,p(),ht().checkResponse(v)){e.next=15;break}return console.error("error fetching ticket page",v.msg),e.abrupt("return");case 15:(c=this.ticketPage.history).push.apply(c,r(v.tickets)),i.push.apply(i,r(v.tickets)),v.tickets.length=aa,n.ticketHistoryPagination),Me.setVis(m>0,n.ticketHistoryTable),Me.setVis(0===m,n.noTicketsMessage),0!==i.length){e.next=25;break}return Me.hide(n.ticketHistoryNextPage),e.abrupt("return");case 25:this.displayTicketPage(t,i),o.number=t,g=t*aa+i.length===m,Me.setVis(!g||!o.scanned,n.ticketHistoryNextPage),Me.setVis(t>0,n.ticketHistoryPrevPage);case 30:case"end":return e.stop()}}),e,this)}))),function(e){return U.apply(this,arguments)})},{key:"showTicketHistory",value:(V=s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.showForm(this.page.ticketHistoryForm),e.next=3,this.ticketPageN(this.ticketPage.number);case 3:case"end":return e.stop()}}),e,this)}))),function(){return V.apply(this,arguments)})},{key:"nextTicketPage",value:(W=s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.ticketPageN(this.ticketPage.number+1);case 2:case"end":return e.stop()}}),e,this)}))),function(){return W.apply(this,arguments)})},{key:"prevTicketPage",value:(N=s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.ticketPageN(this.ticketPage.number-1);case 2:case"end":return e.stop()}}),e,this)}))),function(){return N.apply(this,arguments)})},{key:"showSetVotesDialog",value:function(){var e,t=this,n=this.page,r=this.stakeStatus,a=this.selectedAssetID,o=ht().unitInfo(a);Me.hide(n.votingFormErr);var i=jn[a][ht().user.net],c=function(){var e=s(f().mark((function e(r){var a,o;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return Me.hide(n.votingFormErr),a=ht().loading(n.votingForm),e.next=4,t.safePost("/api/setvotes",r);case 4:if(o=e.sent,a(),ht().checkResponse(o)){e.next=10;break}throw Me.show(n.votingFormErr),n.votingFormErr.textContent=o.msg,Error(o.msg);case 10:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),l=function(){var e=s(f().mark((function e(t,n){var o,s,i;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,c({assetID:a,choices:h({},t,n)});case 2:o=Gr(r.stances.agendas);try{for(o.s();!(s=o.n()).done;)(i=s.value).id===t&&(i.currentChoice=n)}catch(e){o.e(e)}finally{o.f()}case 4:case"end":return e.stop()}}),e)})));return function(t,n){return e.apply(this,arguments)}}();Me.empty(n.votingAgendas);var u,d=Gr(r.stances.agendas);try{var p=function(){var e=u.value,t=n.votingAgendaTmpl.cloneNode(!0);n.votingAgendas.appendChild(t);var r=Me.parseTemplate(t);r.description.textContent=e.description;var a,o=Gr(e.choices);try{var s=function(){var t=a.value,o=n.votingChoiceTmpl.cloneNode(!0);r.choices.appendChild(o);var s,i=Me.parseTemplate(o);i.id.textContent=(s=t.id).charAt(0).toUpperCase()+s.slice(1),i.id.dataset.tooltip=t.description,i.radio.value=t.id,i.radio.name=e.id,Me.bind(i.radio,"change",(function(){i.radio.checked&&l(e.id,t.id)})),t.id===e.currentChoice&&(i.radio.checked=!0)};for(o.s();!(a=o.n()).done;)s()}catch(e){o.e(e)}finally{o.f()}ht().bindTooltips(r.choices)};for(d.s();!(u=d.n()).done;)p()}catch(e){d.e(e)}finally{d.f()}var v=function(){var e=s(f().mark((function e(t,n){var o,s,i;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,c({assetID:a,tSpendPolicy:h({},t,n)});case 2:o=Gr(r.stances.tspends);try{for(o.s();!(s=o.n()).done;)(i=s.value).hash===t&&(i.currentPolicy=n)}catch(e){o.e(e)}finally{o.f()}case 4:case"end":return e.stop()}}),e)})));return function(t,n){return e.apply(this,arguments)}}();Me.empty(n.votingTspends);var m,g=Gr(r.stances.tspends);try{var y=function(){var e=m.value,t=n.tspendTmpl.cloneNode(!0);n.votingTspends.appendChild(t),ht().bindUrlHandlers(t);for(var r=Me.parseTemplate(t),a=function(){var t=c[s];t.name=e.hash,e.currentPolicy===t.value&&(t.checked=!0),Me.bind(t,"change",(function(){var n;t.checked&&v(e.hash,null!==(n=t.value)&&void 0!==n?n:"")}))},s=0,c=[r.yes,r.no];s0?r.value.textContent=Me.formatFourSigFigs(e.value/o.conventional.conversionFactor):Me.hide(r.value),r.hash.textContent=e.hash,r.explorerLink.setAttribute("href",i(e.hash))};for(g.s();!(m=g.n()).done;)y()}catch(e){g.e(e)}finally{g.f()}var b=function(){var e=s(f().mark((function e(t,n){var o,s,i;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,c({assetID:a,treasuryPolicy:h({},t,n)});case 2:o=Gr(r.stances.treasuryKeys);try{for(o.s();!(s=o.n()).done;)(i=s.value).key===t&&(i.policy=n)}catch(e){o.e(e)}finally{o.f()}case 4:case"end":return e.stop()}}),e)})));return function(t,n){return e.apply(this,arguments)}}();Me.empty(n.votingTKeys);var x,k=Gr(null!==(e=r.stances.treasuryKeys)&&void 0!==e?e:[]);try{var w=function(){var e=x.value,t=n.tkeyTmpl.cloneNode(!0);n.votingTKeys.appendChild(t);for(var r=Me.parseTemplate(t),a=function(){var t=s[o];t.name=e.key,e.policy===t.value&&(t.checked=!0),Me.bind(t,"change",(function(){var n;t.checked&&b(e.key,null!==(n=t.value)&&void 0!==n?n:"")}))},o=0,s=[r.yes,r.no];o0&&m(be("ORDER"),c.orderlocked,be("LOCKED_ORDER_BAL_MSG")),c.contractlocked>0&&m(be("SWAPPING"),c.contractlocked,be("LOCKED_SWAPPING_BAL_MSG")),c.bondlocked>0&&m(be("BONDED"),c.bondlocked,be("LOCKED_BOND_BAL_MSG")),c.bondReserves>0&&m(be("BOND_RESERVES"),c.bondReserves,be("BOND_RESERVES_MSG")),void 0!==(null==c||null===(t=c.other)||void 0===t?void 0:t.Staked)&&m("Staked",c.other.Staked.amt),g(),c.immature&&v(be("IMMATURE_TITLE"),c.immature,be("IMMATURE_BAL_MSG")),void 0!==(null==c||null===(n=c.other)||void 0===n?void 0:n.Unmixed)&&m("Unmixed",c.other.Unmixed.amt),g(),r.purchaserBal.textContent=Me.formatFourSigFigs(c.available/s.conventional.conversionFactor),ht().bindTooltips(r.balanceDetailBox)}},{key:"showAvailableMarkets",value:function(e){for(var t=this.page,n=ht().user.exchanges,r=[],o=0,s=Object.values(n);o0&&(r.age.dataset.stamp=String(t.timestamp));var u=ta(t.type);if(t.tokenID&&t.tokenID!==n){var d=ht().assets[t.tokenID].unitInfo.conventional.unit;u="".concat(d," ").concat(u)}if(r.type.textContent=u,r.id.textContent=ia(t.id,12),r.id.setAttribute("title",t.id),r.fees.textContent=Me.formatCoinValue(t.fees,l),Zr.includes(t.type))r.amount.textContent="-";else{var h=a($r(t.type),2),p=h[0],f=h[1],v=Me.formatCoinValue(t.amount,c);r.amount.textContent="".concat(p).concat(v),""!==f&&r.amount.classList.add(f)}}},{key:"txHistoryRow",value:function(e,t){var n=this,r=this.page.txHistoryRowTmpl.cloneNode(!0);r.dataset.txid=e.id,Me.bind(r,"click",(function(){return n.showTxDetailsPopup(e.id)})),this.updateTxHistoryRow(r,e,t);var a=Me.parseTemplate(r);return this.stampers.push(a.age),r}},{key:"txHistoryDateRow",value:function(e){var t=this.page.txHistoryDateRowTmpl.cloneNode(!0);return Me.parseTemplate(t).date.textContent=e,t}},{key:"setTxDetailsPopupElements",value:function(e){var t=this.page,n=jn[this.selectedAssetID];n&&n[oa]&&(t.txViewBlockExplorer.href=n[oa](e.id));var r=ta(e.type);if(e.tokenID&&e.tokenID!==this.selectedAssetID){var o=ht().assets[e.tokenID].symbol.split(".")[0].toUpperCase();r="".concat(o," ").concat(r)}if(t.txDetailsType.textContent=r,Me.setVis(16===e.type,t.txTypeTooltip),t.txTypeTooltip.dataset.tooltip=be("SWAP_OR_SEND_TOOLTIP"),Zr.includes(e.type))Me.hide(t.txDetailsAmtSection);else{var s=this.selectedAssetID;e.tokenID&&(s=e.tokenID),Me.show(t.txDetailsAmtSection);var i=ht().unitInfo(s),c=Me.formatCoinValue(e.amount,i),l=a($r(e.type),2),u=l[0],d=l[1];t.txDetailsAmount.textContent="".concat(u).concat(c," ").concat(i.conventional.unit),""!==d&&t.txDetailsAmount.classList.add(d)}var h=this.selectedAssetID;if(void 0!==e.tokenID){var p=ht().assets[e.tokenID];p.token?h=p.token.parentID:console.error("wallet transaction ".concat(e.id," is supposed to be a token tx, but asset ").concat(e.tokenID," is not a token"))}var f=ht().unitInfo(h),v=Me.formatCoinValue(e.fees,f);t.txDetailsFee.textContent="".concat(v," ").concat(f.conventional.unit),t.txDetailsBlockNumber.textContent="".concat(e.blockNumber);var m=new Date(1e3*e.timestamp),g=m.toLocaleDateString(),y=m.toLocaleTimeString();if(t.txDetailsTimestamp.textContent="".concat(g," ").concat(y),Me.setVis(0===e.blockNumber,t.timestampPending,t.blockNumberPending),Me.setVis(0!==e.blockNumber,t.txDetailsBlockNumber,t.txDetailsTimestamp),t.txDetailsID.textContent=ia(e.id,20),t.txDetailsID.setAttribute("title",e.id),e.recipient?(Me.show(t.txDetailsRecipientSection),t.txDetailsRecipient.textContent=ia(e.recipient,20),t.txDetailsRecipient.setAttribute("title",e.recipient)):Me.hide(t.txDetailsRecipientSection),e.bondInfo){Me.show(t.txDetailsBondIDSection,t.txDetailsBondLocktimeSection),Me.setVis(""!==e.bondInfo.accountID,t.txDetailsBondAccountIDSection),t.txDetailsBondID.textContent=ia(e.bondInfo.bondID,20),t.txDetailsBondID.setAttribute("title",e.bondInfo.bondID);var b=new Date(1e3*e.bondInfo.lockTime),x=b.toLocaleDateString(),k=b.toLocaleTimeString();t.txDetailsBondLocktime.textContent="".concat(x," ").concat(k),t.txDetailsBondAccountID.textContent=ia(e.bondInfo.accountID,20),t.txDetailsBondAccountID.setAttribute("title",e.bondInfo.accountID)}else Me.hide(t.txDetailsBondIDSection,t.txDetailsBondLocktimeSection,t.txDetailsBondAccountIDSection);e.additionalData&&e.additionalData.Nonce?(Me.show(t.txDetailsNonceSection),t.txDetailsNonce.textContent="".concat(e.additionalData.Nonce)):Me.hide(t.txDetailsNonceSection)}},{key:"showTxDetailsPopup",value:function(e){var t=ht().getWalletTx(this.selectedAssetID,e);t?(this.currTx=t,this.setTxDetailsPopupElements(t),this.showForm(this.page.txDetails)):console.error("wallet transaction ".concat(e," not found"))}},{key:"txHistoryTableNewestDate",value:function(){return this.page.txHistoryTableBody.children.length>=1&&Me.parseTemplate(this.page.txHistoryTableBody.children[0]).date.textContent||""}},{key:"txDate",value:function(e){return 0===e.timestamp?(new Date).toLocaleDateString():new Date(1e3*e.timestamp).toLocaleDateString()}},{key:"handleTxNote",value:function(e,t){var n;if(0==(ht().assets[this.selectedAssetID].wallet.traits&Kr)||!this.page.hideMixTxs.checked||17!==e.type)if(t)this.oldestTx?this.txDate(e)!==this.txHistoryTableNewestDate()?(this.page.txHistoryTableBody.insertBefore(this.txHistoryRow(e,this.selectedAssetID),this.page.txHistoryTableBody.children[0]),this.page.txHistoryTableBody.insertBefore(this.txHistoryDateRow(this.txDate(e)),this.page.txHistoryTableBody.children[0])):this.page.txHistoryTableBody.insertBefore(this.txHistoryRow(e,this.selectedAssetID),this.page.txHistoryTableBody.children[1]):(Me.show(this.page.txHistoryTable),Me.hide(this.page.noTxHistory),this.page.txHistoryTableBody.appendChild(this.txHistoryDateRow(this.txDate(e))),this.page.txHistoryTableBody.appendChild(this.txHistoryRow(e,this.selectedAssetID)),this.oldestTx=e);else{var r,a=Gr(this.page.txHistoryTableBody.children);try{for(a.s();!(r=a.n()).done;){var o=r.value;if(o.dataset.txid===e.id){this.updateTxHistoryRow(o,e,this.selectedAssetID);break}}}catch(e){a.e(e)}finally{a.f()}e.id===(null===(n=this.currTx)||void 0===n?void 0:n.id)&&this.setTxDetailsPopupElements(e)}}},{key:"getTxHistory",value:(L=s(f().mark((function e(t,n,a){var o,s,i,c,l,u,d,h,p;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:o=10,n&&(o=15),s={txs:[],lastTx:!1},i=a,c=0;case 5:if(!(c<40)){e.next=18;break}return e.next=8,ht().txHistory(t,o,i);case 8:if((l=e.sent).txs.length>0&&(i=l.txs[l.txs.length-1].id),u=l.txs,n&&(u=u.filter((function(e){return 17!==e.type}))),s.txs.length+u.length>10?(h=10-s.txs.length,(d=s.txs).push.apply(d,r(u.slice(0,h)))):(l.lastTx&&(s.lastTx=!0),(p=s.txs).push.apply(p,r(u))),!(s.txs.length>=10||l.lastTx)){e.next=15;break}return e.abrupt("break",18);case 15:c++,e.next=5;break;case 18:return e.abrupt("return",s);case 19:case"end":return e.stop()}}),e)}))),function(e,t,n){return L.apply(this,arguments)})},{key:"showTxHistory",value:(P=s(f().mark((function e(t){var n,r,a,o,s,i,c,l,u,d,h;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=this.page,Me.hide(n.txHistoryTable,n.txHistoryBox,n.noTxHistory,n.earlierTxs,n.txHistoryNotAvailable,n.hideMixTxs),Me.empty(n.txHistoryTableBody),(a=ht().assets[t].wallet)&&!a.disabled&&0!=(65536&a.traits)){e.next=7;break}return Me.show(n.txHistoryNotAvailable),e.abrupt("return");case 7:return this.oldestTx=void 0,o=0!=(a.traits&Kr),Me.setVis(o,n.hideMixTxs),Me.show(n.txHistoryBox),e.prev=11,s=o&&!!n.hideMixTxsCheckbox.checked,e.next=15,this.getTxHistory(t,s);case 15:r=e.sent,e.next=22;break;case 18:return e.prev=18,e.t0=e.catch(11),Me.show(n.noTxHistory),e.abrupt("return");case 22:if(0!==r.txs.length){e.next=25;break}return Me.show(n.noTxHistory),e.abrupt("return");case 25:i=this.txDate(r.txs[0]),n.txHistoryTableBody.appendChild(this.txHistoryDateRow(i)),c=Gr(r.txs);try{for(c.s();!(l=c.n()).done;)u=l.value,(d=this.txDate(u))!==i&&(i=d,n.txHistoryTableBody.appendChild(this.txHistoryDateRow(d))),h=this.txHistoryRow(u,t),n.txHistoryTableBody.appendChild(h)}catch(e){c.e(e)}finally{c.f()}this.oldestTx=r.txs[r.txs.length-1],Me.show(n.txHistoryTable),Me.setVis(!r.lastTx,n.earlierTxs);case 32:case"end":return e.stop()}}),e,this,[[11,18]])}))),function(e){return P.apply(this,arguments)})},{key:"loadEarlierTxs",value:(B=s(f().mark((function e(){var t,n,r,a,o,s,i,c,l,u;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.oldestTx){e.next=2;break}return e.abrupt("return");case 2:return t=this.page,r=ht().assets[this.selectedAssetID].wallet,a=0!=(r.traits&Kr)&&!!t.hideMixTxsCheckbox.checked,e.prev=5,e.next=8,this.getTxHistory(this.selectedAssetID,a,this.oldestTx.id);case 8:n=e.sent,e.next=15;break;case 11:return e.prev=11,e.t0=e.catch(5),console.error(e.t0),e.abrupt("return");case 15:o=this.txDate(this.oldestTx),s=Gr(n.txs);try{for(s.s();!(i=s.n()).done;)c=i.value,(l=this.txDate(c))!==o&&(o=l,t.txHistoryTableBody.appendChild(this.txHistoryDateRow(l))),u=this.txHistoryRow(c,this.selectedAssetID),t.txHistoryTableBody.appendChild(u)}catch(e){s.e(e)}finally{s.f()}Me.setVis(!n.lastTx,t.earlierTxs),n.txs.length>0&&(this.oldestTx=n.txs[n.txs.length-1]);case 20:case"end":return e.stop()}}),e,this,[[5,11]])}))),function(){return B.apply(this,arguments)})},{key:"rescanWallet",value:(E=s(f().mark((function e(t){var n,r,a,o,s;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=this.page,Me.hide(n.reconfigErr),r="/api/rescanwallet",a={assetID:t},o=ht().loading(this.body),e.next=7,C(r,a);case 7:if(s=e.sent,o(),s.code!==A.activeOrdersErr){e.next=14;break}return this.forceUrl=r,this.forceReq=a,this.showConfirmForce(),e.abrupt("return");case 14:if(ht().checkResponse(s)){e.next=17;break}return Me.showFormError(n.reconfigErr,s.msg),e.abrupt("return");case 17:this.assetUpdated(t,n.reconfigForm,be("RESCAN_STARTED"));case 18:case"end":return e.stop()}}),e,this)}))),function(e){return E.apply(this,arguments)})},{key:"showConfirmForce",value:function(){Me.hide(this.page.confirmForceErr),this.showForm(this.page.confirmForce)}},{key:"showRecoverWallet",value:function(){Me.hide(this.page.recoverWalletErr),this.showForm(this.page.recoverWalletConfirm)}},{key:"openWallet",value:(I=s(f().mark((function e(t){var n,r;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n={assetID:t},e.next=3,C("/api/openwallet",n);case 3:if(r=e.sent,ht().checkResponse(r)){e.next=7;break}return console.error("openwallet error",r),e.abrupt("return");case 7:this.assetUpdated(t,void 0,be("WALLET_UNLOCKED"));case 8:case"end":return e.stop()}}),e,this)}))),function(e){return I.apply(this,arguments)})},{key:"showReconfig",value:(D=s(f().mark((function e(t,n){var r,a,o,s,i,c,l,u,d,h,p,v,m,g,y,b,x;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(a=this.page,Me.hide(a.changeWalletType,a.changeTypeHideIcon,a.reconfigErr,a.showChangeType,a.changeTypeHideIcon,a.reconfigErr,a.enableWallet,a.disableWallet),this.changeWalletPW=!1,this.setPWSettingViz(this.changeWalletPW),o=ht().assets[t],s=ht().currentWalletDefinition(t),i=o.token?[o.token.definition]:o.info?o.info.availablewallets:[],c=null===(r=ht().extensionWallet(t))||void 0===r?void 0:r.disableWalletType,i.length>1&&!c){Me.empty(a.changeWalletTypeSelect),Me.show(a.showChangeType,a.changeTypeShowIcon),a.changeTypeMsg.textContent=be("CHANGE_WALLET_TYPE"),l=Gr(i);try{for(l.s();!(u=l.n()).done;)d=u.value,h=document.createElement("option"),d.type===s.type&&(h.selected=!0),h.value=h.textContent=d.type,a.changeWalletTypeSelect.appendChild(h)}catch(e){l.e(e)}finally{l.f()}}if(null!=n&&n.elevateProviders){p=Gr(s.configopts);try{for(p.s();!(v=p.n()).done;)"providers"===(m=v.value).key&&(m.required=!0)}catch(e){p.e(e)}finally{p.f()}}return g=ht().walletMap[t],Me.setVis(4&g.traits,a.downloadLogs),Me.setVis(32&g.traits,a.recoverWallet),Me.setVis(256&g.traits,a.exportWallet),Me.setVis(1&g.traits,a.rescanWallet),Me.setVis(1024&g.traits&&!g.disabled,a.managePeers),Me.setVis(8192&g.traits&&!g.disabled,a.unapproveTokenAllowance),Me.setVis(9509&g.traits,a.otherActionsLabel),g.disabled?Me.show(a.enableWallet):Me.show(a.disableWallet),this.showOrHideRecoverySupportMsg(g,s.seeded),a.recfgAssetLogo.src=Me.logoPath(o.symbol),a.recfgAssetName.textContent=o.name,null!=n&&n.skipAnimation||this.showForm(a.reconfigForm),y=ht().loading(a.reconfigForm),e.next=26,C("/api/walletsettings",{assetID:t});case 26:if(b=e.sent,y(),ht().checkResponse(b)){e.next=31;break}return Me.showFormError(a.reconfigErr,b.msg),e.abrupt("return");case 31:x=ht().haveActiveOrders(t),this.reconfigForm.update(o.id,s.configopts||[],x),this.setGuideLink(s.guidelink),this.reconfigForm.setConfig(b.map),this.updateDisplayedReconfigFields(s);case 36:case"end":return e.stop()}}),e,this)}))),function(e,t){return D.apply(this,arguments)})},{key:"showOrHideRecoverySupportMsg",value:function(e,t){this.setRecoverySupportMsgViz(t&&!e.running&&!e.disabled&&Boolean(32&e.traits),e.symbol)}},{key:"setRecoverySupportMsgViz",value:function(e,t){var n=this.page;if(e)return n.reconfigSupportMsg.textContent=be("WALLET_RECOVERY_SUPPORT_MSG",{walletSymbol:t.toLocaleUpperCase()}),Me.show(n.reconfigSupportMsg),n.submitReconfig.setAttribute("disabled",""),void n.submitReconfig.classList.add("grey");n.submitReconfig.removeAttribute("disabled"),n.submitReconfig.classList.remove("grey"),Me.empty(n.reconfigSupportMsg),Me.hide(n.reconfigSupportMsg)}},{key:"changeWalletType",value:function(){var e=this.page.changeWalletTypeSelect.value||"",t=ht().walletDefinition(this.selectedAssetID,e);this.reconfigForm.update(this.selectedAssetID,t.configopts||[],!1);var n=ht().walletMap[this.selectedAssetID],r=ht().currentWalletDefinition(this.selectedAssetID);t.type!==r.type?this.setRecoverySupportMsgViz(!1,n.symbol):this.showOrHideRecoverySupportMsg(n,t.seeded),this.setGuideLink(t.guidelink),this.updateDisplayedReconfigFields(t)}},{key:"setGuideLink",value:function(e){Me.hide(this.walletCfgGuide),""!==e&&(this.walletCfgGuide.href=e,Me.show(this.walletCfgGuide))}},{key:"updateDisplayedReconfigFields",value:function(e){var t,n=null===(t=ht().extensionWallet(this.selectedAssetID))||void 0===t?void 0:t.disablePassword;e.seeded||"token"===e.type||n?(Me.hide(this.page.showChangePW,this.reconfigForm.fileSelector),this.changeWalletPW=!1,this.setPWSettingViz(!1)):Me.show(this.page.showChangePW,this.reconfigForm.fileSelector)}},{key:"showDeposit",value:(T=s(f().mark((function e(t){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:this.depositAddrForm.setAsset(t),this.showForm(this.page.deposit);case 2:case"end":return e.stop()}}),e,this)}))),function(e){return T.apply(this,arguments)})},{key:"showSendForm",value:(F=s(f().mark((function e(t){var n,r,a,o,s,i,c,l,u,d,h,p,v,m,g;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=this.page,r=n.sendForm,a=ht().assets[t],o=a.wallet,s=a.unitInfo,i=a.symbol,c=a.token,Me.hide(n.toggleSubtract),n.subtractCheckBox.checked=!1,(l=0!=(64&o.traits))&&Me.show(n.toggleSubtract),Me.hide(n.validAddr,n.sendErr,n.maxSendDisplay,n.sendTokenMsgBox),n.sendAddr.classList.remove("invalid"),n.sendAddr.value="",n.sendAmt.value="",u=ht().fiatRatesMap[t],Me.showFiatValue(n.sendValue,0,u,s),n.walletBal.textContent=Me.formatFullPrecision(o.balance.available,s),n.sendLogo.src=Me.logoPath(i),n.sendName.textContent=s.conventional.unit,c&&(d=ht().assets[c.parentID],n.sendTokenParentLogo.src=Me.logoPath(d.symbol),n.sendTokenParentName.textContent=d.name,Me.show(n.sendTokenMsgBox)),!(o.balance.available>0&&0!=(512&o.traits))){e.next=25;break}return h={assetID:t,subtract:l,maxWithdraw:!0,value:o.balance.available},p=ht().loading(this.body),e.next=22,C("/api/txfee",h);case 22:v=e.sent,p(),ht().checkResponse(v)&&(m=o.balance.available,c||(m-=v.txfee)<0&&(m=0),this.maxSend=m,n.maxSend.textContent=Me.formatFullPrecision(m,s),Me.showFiatValue(n.maxSendFiat,m,u,s),c?(g=ht().assets[c.parentID].unitInfo,n.maxSendFee.textContent=Me.formatFullPrecision(v.txfee,g)+" "+g.conventional.unit,Me.showFiatValue(n.maxSendFeeFiat,v.txfee,ht().fiatRatesMap[c.parentID],g)):(n.maxSendFee.textContent=Me.formatFullPrecision(v.txfee,s),Me.showFiatValue(n.maxSendFeeFiat,v.txfee,u,s)),Me.show(n.maxSendDisplay));case 25:Me.showFiatValue(n.sendValue,0,u,s),n.walletBal.textContent=Me.formatFullPrecision(o.balance.available,s),r.dataset.assetID=String(t),this.showForm(r);case 29:case"end":return e.stop()}}),e,this)}))),function(e){return F.apply(this,arguments)})},{key:"doConnect",value:(S=s(f().mark((function e(t){var n,r,a,o;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=ht().loading(this.body),e.next=3,C("/api/connectwallet",{assetID:t});case 3:r=e.sent,n(),ht().checkResponse(r)||(a=ht().assets[t].symbol,(o=this.page).errorModalMsg.textContent=be("CONNECTING_WALLET_ERR_MSG",{assetName:a,errMsg:r.msg}),this.showForm(o.errorModal)),this.updateDisplayedAsset(t);case 7:case"end":return e.stop()}}),e,this)}))),function(e){return S.apply(this,arguments)})},{key:"assetUpdated",value:function(e,t,n){e===this.selectedAssetID&&(this.updateDisplayedAsset(e),t&&Object.is(this.currentForm,t)&&(n?this.showSuccess(n):this.closePopups()))}},{key:"populateMaxSend",value:(w=s(f().mark((function e(){var t,n,r,a,o,s,i;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=this.page,n=ht().assets[this.selectedAssetID],r=n.id,a=n.unitInfo,o=n.wallet,s=ht().fiatRatesMap[r],0==(64&o.traits)?(t.sendAmt.value=String(this.maxSend/a.conventional.conversionFactor),Me.showFiatValue(t.sendValue,this.maxSend,s,a),t.subtractCheckBox.checked=!1):(i=o.balance.available,t.sendAmt.value=String(i/a.conventional.conversionFactor),Me.showFiatValue(t.sendValue,i,s,a),t.subtractCheckBox.checked=!0);case 4:case"end":return e.stop()}}),e,this)}))),function(){return w.apply(this,arguments)})},{key:"send",value:(x=s(f().mark((function e(){var t,n,r,a,o,s,i,c,l,u,d;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=this.page,a=parseInt(null!==(t=r.sendForm.dataset.assetID)&&void 0!==t?t:""),o=null!==(n=r.subtractCheckBox.checked)&&void 0!==n&&n,s=ht().unitInfo(a).conventional.conversionFactor,i=r.vSendPw.value||"",r.vSendPw.value="",""!==i){e.next=9;break}return Me.showFormError(r.vSendErr,be(R)),e.abrupt("return");case 9:return c={assetID:a,address:r.sendAddr.value,subtract:o,value:Math.round($e(r.sendAmt.value)*s),pw:i},l=ht().loading(r.vSendForm),e.next=13,C("/api/send",c);case 13:if(u=e.sent,l(),ht().checkResponse(u)){e.next=18;break}return Me.showFormError(r.vSendErr,u.msg),e.abrupt("return");case 18:d=ht().assets[a].name,this.assetUpdated(a,r.vSendForm,be("SEND_SUCCESS",{assetName:d}));case 20:case"end":return e.stop()}}),e,this)}))),function(){return x.apply(this,arguments)})},{key:"reconfig",value:(m=s(f().mark((function e(){var t,n,r,a,o,s,i;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=this.page,r=this.selectedAssetID,Me.hide(n.reconfigErr),a=ht().currentWalletDefinition(r).type,Me.isHidden(n.changeWalletType)||(a=n.changeWalletTypeSelect.value||""),o=ht().loading(n.reconfigForm),s={assetID:r,config:this.reconfigForm.map(r),walletType:a},this.changeWalletPW&&(s.newWalletPW=n.newPW.value),e.next=10,this.safePost("/api/reconfigurewallet",s);case 10:if(i=e.sent,n.newPW.value="",o(),ht().checkResponse(i)){e.next=16;break}return Me.showFormError(n.reconfigErr,i.msg),e.abrupt("return");case 16:if(null===(t=this.data)||void 0===t||!t.goBack){e.next=19;break}return ht().loadPage(this.data.goBack),e.abrupt("return");case 19:this.assetUpdated(r,n.reconfigForm,be("RECONFIG_SUCCESS")),this.updateTicketBuyer(r),ht().clearTxHistory(r),this.showTxHistory(r),this.updatePrivacy(r),this.checkNeedsProvider(r);case 25:case"end":return e.stop()}}),e,this)}))),function(){return m.apply(this,arguments)})},{key:"lock",value:(p=s(f().mark((function e(t){var n,r,a;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=this.page,r=ht().loading(n.newWalletForm),e.next=4,C("/api/closewallet",{assetID:t});case 4:if(a=e.sent,r(),ht().checkResponse(a)){e.next=8;break}return e.abrupt("return");case 8:this.updateDisplayedAsset(t),this.updatePrivacy(t);case 10:case"end":return e.stop()}}),e,this)}))),function(e){return p.apply(this,arguments)})},{key:"downloadLogs",value:(u=s(f().mark((function e(){var t,n;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:(t=new URLSearchParams("")).append("assetid","".concat(this.selectedAssetID)),(n=new URL(window.location.href)).search=t.toString(),n.pathname="/wallets/logfile",window.open(n.toString());case 6:case"end":return e.stop()}}),e,this)}))),function(){return u.apply(this,arguments)})},{key:"displayExportWalletAuth",value:(l=s(f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=this.page,Me.hide(t.exportWalletErr),t.exportWalletPW.value="",this.showForm(t.exportWalletAuth);case 4:case"end":return e.stop()}}),e,this)}))),function(){return l.apply(this,arguments)})},{key:"exportWalletAuthSubmit",value:(c=s(f().mark((function e(){var t,n,r,a;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.page,n={assetID:this.selectedAssetID,pass:t.exportWalletPW.value},r=ht().loading(t.forms),e.next=6,C("/api/restorewalletinfo",n);case 6:a=e.sent,r(),ht().checkResponse(a)?(t.exportWalletPW.value="",this.displayRestoreWalletInfo(a.restorationinfo)):Me.showFormError(t.exportWalletErr,a.msg);case 9:case"end":return e.stop()}}),e,this)}))),function(){return c.apply(this,arguments)})},{key:"displayRestoreWalletInfo",value:(o=s(f().mark((function e(t){var n,r,a,o,s,i;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=this.page,Me.empty(n.restoreInfoCardsList),r=Gr(t);try{for(r.s();!(a=r.n()).done;)o=a.value,s=this.restoreInfoCard.cloneNode(!0),(i=Me.parseTemplate(s)).name.textContent=o.target,i.seed.textContent=o.seed,i.seedName.textContent="".concat(o.seedName,":"),i.instructions.textContent=o.instructions,n.restoreInfoCardsList.appendChild(s)}catch(e){r.e(e)}finally{r.f()}this.showForm(n.restoreWalletInfo);case 5:case"end":return e.stop()}}),e,this)}))),function(e){return o.apply(this,arguments)})},{key:"recoverWallet",value:(n=s(f().mark((function e(){var t,n,r,a,o;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.page,Me.hide(t.recoverWalletErr),n={assetID:this.selectedAssetID},r="/api/recoverwallet",a=ht().loading(t.forms),e.next=7,C(r,n);case 7:o=e.sent,a(),o.code===A.activeOrdersErr?(this.forceUrl=r,this.forceReq=n,this.showConfirmForce()):ht().checkResponse(o)?this.closePopups():Me.showFormError(t.recoverWalletErr,o.msg);case 10:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"confirmForceSubmit",value:(t=s(f().mark((function e(){var t,n,r;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.page,this.forceReq.force=!0,n=ht().loading(t.forms),e.next=5,C(this.forceUrl,this.forceReq);case 5:r=e.sent,n(),ht().checkResponse(r)?this.closePopups():Me.showFormError(t.confirmForceErr,r.msg);case 8:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})},{key:"handleBalanceNote",value:function(e){this.updateAssetButton(e.assetID),e.assetID===this.selectedAssetID&&this.updateDisplayedAssetBalance()}},{key:"handleRatesNote",value:function(e){if(this.updateAssetButton(this.selectedAssetID),e.fiatRates[this.selectedAssetID]){this.updateDisplayedAssetBalance();var t=ht().walletMap[this.selectedAssetID].feeState;t&&this.updateFeeState(t)}}},{key:"handleWalletStateNote",value:function(e){var t=e.wallet,n=t.assetID,r=t.feeState;this.updateAssetButton(n),this.assetUpdated(n),"WalletPeersUpdate"===e.topic&&n===this.selectedAssetID&&Me.isDisplayed(this.page.managePeersForm)&&this.updateWalletPeersTable(),r&&n===this.selectedAssetID&&this.updateFeeState(r)}},{key:"handleCreateWalletNote",value:function(e){this.updateAssetButton(e.assetID),this.assetUpdated(e.assetID),this.showTxHistory(e.assetID)}},{key:"handleCustomWalletNote",value:function(e){var t=e.payload;switch(t.route){case"tipChange":var n=t;if(42===n.assetID){if(!this.stakeStatus)return;var r=n.data;if(ht().walletMap[n.assetID].synced){var a=ht().unitInfo(n.assetID);this.updateTicketStats(r.stats,a,r.ticketPrice,r.votingSubsidy)}}break;case"ticketPurchaseUpdate":this.processTicketPurchaseUpdate(t);break;case"transaction":var o=t;o.assetID===this.selectedAssetID&&this.handleTxNote(o.transaction,o.new);break;case"transactionHistorySynced":var s=t;s.assetID===this.selectedAssetID&&this.showTxHistory(s.assetID)}}},{key:"unload",value:function(){clearInterval(this.secondTicker),Me.unbind(document,"keyup",this.keyup)}}]),ve}(it);function ia(e,t){return e.length<=t?e:"".concat(e.substring(0,t/2),"...").concat(e.substring(e.length-t/2))}function ca(e,t){if(null==e)return{};var n,r,a=function(e,t){if(null==e)return{};var n,r,a={},o=Object.keys(e);for(r=0;r=0||(a[n]=e[n]);return a}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}var la="order",ua="match",da="bondpost",ha="conn";function pa(){return"desktop_notifications-".concat(window.location.host)}var fa,va=(h(na={},la,"BROWSER_NTFN_ORDERS"),h(na,ua,"BROWSER_NTFN_MATCHES"),h(na,da,"BROWSER_NTFN_BONDS"),h(na,ha,"BROWSER_NTFN_CONNECTIONS"),na),ma=(h(ra={},la,!0),h(ra,ua,!0),h(ra,da,!0),h(ra,ha,!0),function(){function e(){i(this,e)}var t,n;return d(e,null,[{key:"ntfnPermissionGranted",value:function(){return"granted"===window.Notification.permission}},{key:"ntfnPermissionDenied",value:function(){return"denied"===window.Notification.permission}},{key:"requestNtfnPermission",value:(n=s(f().mark((function t(){return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if("Notification"in window){t.next=2;break}return t.abrupt("return");case 2:if(!e.ntfnPermissionGranted()){t.next=6;break}e.sendDesktopNotification(be($)),t.next=10;break;case 6:if(e.ntfnPermissionDenied()){t.next=10;break}return t.next=9,Notification.requestPermission();case 9:e.sendDesktopNotification(be($));case 10:case"end":return t.stop()}}),t)}))),function(){return n.apply(this,arguments)})},{key:"sendDesktopNotification",value:(t=s(f().mark((function t(n,r){var a;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(e.ntfnPermissionGranted()){t.next=2;break}return t.abrupt("return");case 2:return a=new window.Notification(n,{body:r,icon:"/img/softened-icon.png"}),t.abrupt("return",a);case 4:case"end":return t.stop()}}),t)}))),function(e,n){return t.apply(this,arguments)})}]),e}()),ga=function(){function e(){i(this,e)}var t,n;return d(e,null,[{key:"ntfnPermissionGranted",value:function(){return!0}},{key:"ntfnPermissionDenied",value:function(){return!1}},{key:"requestNtfnPermission",value:(n=s(f().mark((function t(){return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,e.sendDesktopNotification(be($));case 2:return t.abrupt("return",Promise.resolve());case 3:case"end":return t.stop()}}),t)}))),function(){return n.apply(this,arguments)})},{key:"sendDesktopNotification",value:(t=s(f().mark((function e(t,n){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!ya()){e.next=5;break}return e.next=3,window.sendOSNotification(t,n);case 3:e.next=11;break;case 5:if(!ba()){e.next=10;break}return e.next=8,window.webkit.messageHandlers.bwHandler.postMessage(["sendOSNotification",t,n]);case 8:e.next=11;break;case 10:console.error("sendDesktopNotification: unknown environment");case 11:case"end":return e.stop()}}),e)}))),function(e,n){return t.apply(this,arguments)})}]),e}();function ya(){return void 0!==window.isWebview}function ba(){var e,t;return void 0!==(null===(e=window.webkit)||void 0===e||null===(t=e.messageHandlers)||void 0===t?void 0:t.bwHandler)}var xa=ya()||ba()?ga:ma;function ka(){return(ka=s(f().mark((function e(t){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(fa.browserNtfnEnabled&&fa[t.type]){e.next=2;break}return e.abrupt("return");case 2:return e.next=4,xa.sendDesktopNotification(t.subject,Ta(t.details));case 4:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function wa(){var e;if(void 0!==fa)return fa;var t=pa();return fa=null!==(e=k.fetchLocal(t))&&void 0!==e?e:{}}var Sa=/\{\{\{([^|]+)\|([^}]+)\}\}\}/g,Ca=/\{\{\{order\|([^}]+)\}\}\}/g;function Fa(e,t){for(var n=t.replace(Ca,(function(e,t){var n=document.createElement("a");return n.setAttribute("href","/order/"+t),n.setAttribute("class","subtlelink"),n.textContent=t.slice(0,8),n.outerHTML})).replace(Sa,(function(e,t,n){var r=document.createElement("a");return r.setAttribute("data-explorer-coin",n),r.setAttribute("target","_blank"),r.textContent=n.slice(0,8),zn(t,r),r.outerHTML})),r=Me.noderize(n).body;r.firstChild;)e.appendChild(r.firstChild)}function Ta(e){return e.replace(Sa,(function(e,t,n){return n.slice(0,8)}))}var Da=["bonds"];var Ia=function(e){g(A,e);var t,n,r,a,o,c,l,u,p,m,x,w,S,F,T,D,I=(T=A,D=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}(),function(){var e,t=b(T);if(D){var n=b(this).constructor;e=Reflect.construct(t,arguments,n)}else e=t.apply(this,arguments);return y(this,e)});function A(e){var t;i(this,A),h(v(t=I.call(this)),"body",void 0),h(v(t),"currentDEX",void 0),h(v(t),"page",void 0),h(v(t),"forms",void 0),h(v(t),"fiatRateSources",void 0),h(v(t),"regAssetForm",void 0),h(v(t),"confirmRegisterForm",void 0),h(v(t),"newWalletForm",void 0),h(v(t),"walletWaitForm",void 0),h(v(t),"dexAddrForm",void 0),h(v(t),"appPassResetForm",void 0),h(v(t),"currentForm",void 0),h(v(t),"keyup",void 0),t.body=e;var n=t.page=Me.idDescendants(e);t.forms=Me.applySelector(n.forms,":scope > form"),t.fiatRateSources=Me.applySelector(n.fiatRateSources,"input[type=checkbox]"),n.darkMode.checked="1"===k.fetchLocal(k.darkModeLK),Me.bind(n.darkMode,"click",(function(){k.storeLocal(k.darkModeLK,n.darkMode.checked?"1":"0"),n.darkMode.checked?document.body.classList.add("dark"):document.body.classList.remove("dark")})),n.showPokes.checked="1"===k.fetchLocal(k.popupsLK),Me.bind(n.showPokes,"click",(function(){var e=n.showPokes.checked||!1;k.storeLocal(k.popupsLK,e?"1":"0"),ht().showPopups=e})),n.commitHash.textContent=ht().commitHash.substring(0,7),Me.bind(n.addADex,"click",(function(){t.dexAddrForm.refresh(),t.showForm(n.dexAddrForm)})),t.fiatRateSources.forEach((function(e){Me.bind(e,"change",s(f().mark((function t(){var n;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,C("/api/toggleratesource",{disable:!e.checked,source:e.value});case 2:return n=t.sent,ht().checkResponse(n)||(e.checked=!e.checked),t.next=6,ht().fetchUser();case 6:case"end":return t.stop()}}),t)}))))})),t.regAssetForm=new Fr(n.regAssetForm,function(){var e=s(f().mark((function e(r,a){var o,s,i,c;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r!==dt){e.next=5;break}return e.next=3,ht().fetchUser();case 3:return window.location.reload(),e.abrupt("return");case 5:if(o=ht().assets[r],!(s=o.wallet)){e.next=19;break}return i=t.currentDEX.bondAssets[o.symbol],e.next=11,t.getBondsFeeBuffer(r,n.regAssetForm);case 11:if(c=e.sent,t.confirmRegisterForm.setAsset(r,a,c),!(s.synced&&s.balance.available>=2*i.amount+c)){e.next=16;break}return t.animateConfirmForm(n.regAssetForm),e.abrupt("return");case 16:return t.walletWaitForm.setWallet(r,c,a),t.slideSwap(n.walletWait),e.abrupt("return");case 19:t.confirmRegisterForm.setAsset(r,a,0),t.newWalletForm.setAsset(r),t.slideSwap(n.newWalletForm);case 22:case"end":return e.stop()}}),e)})));return function(t,n){return e.apply(this,arguments)}}()),t.confirmRegisterForm=new Cr(n.confirmRegForm,(function(){t.registerDEXSuccess()}),(function(){t.animateRegAsset(n.confirmRegForm)})),t.newWalletForm=new kr(n.newWalletForm,(function(e){return t.newWalletCreated(e,t.confirmRegisterForm.tier)}),(function(){return t.animateRegAsset(n.newWalletForm)})),t.walletWaitForm=new Tr(n.walletWait,(function(){t.animateConfirmForm(n.walletWait)}),(function(){t.animateRegAsset(n.walletWait)})),t.dexAddrForm=new Ir(n.dexAddrForm,function(){var e=s(f().mark((function e(r,a){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t.currentDEX=r,t.confirmRegisterForm.setExchange(r,a),t.walletWaitForm.setExchange(r),t.regAssetForm.setExchange(r,a),t.animateRegAsset(n.dexAddrForm);case 5:case"end":return e.stop()}}),e)})));return function(t,n){return e.apply(this,arguments)}}()),Me.bind(n.importAccount,"click",(function(){return t.prepareAccountImport(n.authorizeAccountImportForm)})),Vr(n.authorizeAccountImportForm,n.authorizeImportAccountConfirm,(function(){return t.importAccount()})),Me.bind(n.changeAppPW,"click",(function(){return t.showForm(n.changeAppPWForm)})),Vr(n.changeAppPWForm,n.submitNewPW,(function(){return t.changeAppPW()})),t.appPassResetForm=new Br(n.resetAppPWForm,s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,ht().loadPage("login");case 2:Me.hide(n.forms);case 3:case"end":return e.stop()}}),e)})))),Me.bind(n.resetAppPW,"click",(function(){t.appPassResetForm.refresh(),t.showForm(n.resetAppPWForm),t.appPassResetForm.focus()})),Me.bind(n.accountFile,"change",(function(){return t.onAccountFileChange()})),Me.bind(n.removeAccount,"click",(function(){return t.clearAccountFile()})),Me.bind(n.addAccount,"click",(function(){return n.accountFile.click()})),Me.bind(n.exportSeed,"click",(function(){Me.hide(n.exportSeedErr),t.showForm(n.exportSeedAuth)})),Vr(n.exportSeedAuth,n.exportSeedSubmit,(function(){return t.submitExportSeedReq()})),Me.bind(n.gameCodeLink,"click",(function(){return t.showForm(n.gameCodeForm)})),Me.bind(n.gameCodeSubmit,"click",(function(){return t.submitGameCode()}));var r=function(){Me.hide(n.forms),n.exportSeedPW.value="",n.legacySeed.textContent="",n.mnemonic.textContent=""};return Me.bind(n.forms,"mousedown",(function(e){Me.mouseInElement(e,t.currentForm)||r()})),t.keyup=function(e){"Escape"===e.key&&r()},Me.bind(document,"keyup",t.keyup),n.forms.querySelectorAll(".form-closer").forEach((function(e){Me.bind(e,"click",(function(){r()}))})),t.renderDesktopNtfnSettings(),t}return d(A,[{key:"updateNtfnSetting",value:function(e){var t=e.target,n=t.getAttribute("name");null!==n&&function(e,t){wa(),fa[e]=t,k.storeLocal(pa(),fa)}(n,t.checked)}},{key:"getBrowserNtfnSettings",value:function(){return wa()}},{key:"renderDesktopNtfnSettings",value:(F=s(f().mark((function e(){var t,n,r,a,o,i,c=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=this.page,n=this.getBrowserNtfnSettings(),r=va,(a=t.browserNtfnCheckboxTemplate).removeAttribute("id"),o=t.browserNtfnCheckboxContainer,Me.empty(t.browserNtfnCheckboxContainer),Object.keys(r).forEach((function(e){var t=a.cloneNode(!0),s=n[e],i=Me.tmplElement(t,"checkbox");Me.tmplElement(t,"label").textContent=be(r[e]),i.setAttribute("name",e),s&&i.setAttribute("checked","checked"),o.appendChild(t),Me.bind(i,"click",c.updateNtfnSetting)})),i=t.browserNtfnEnabled,Me.bind(i,"click",function(){var e=s(f().mark((function e(t){var n;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!xa.ntfnPermissionDenied()){e.next=2;break}return e.abrupt("return");case 2:if(!(n=t.target).checked){e.next=7;break}return e.next=6,xa.requestNtfnPermission();case 6:n.checked=!xa.ntfnPermissionDenied();case 7:c.updateNtfnSetting(t),n.dispatchEvent(new Event("change"));case 9:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()),Me.bind(i,"change",(function(e){var n=e.target,r=xa.ntfnPermissionDenied();Me.setVis(n.checked,t.browserNtfnCheckboxContainer),Me.setVis(r,t.browserNtfnBlockedMsg),n.disabled=r})),i.checked=xa.ntfnPermissionGranted()&&n.browserNtfnEnabled,i.dispatchEvent(new Event("change"));case 13:case"end":return e.stop()}}),e,this)}))),function(){return F.apply(this,arguments)})},{key:"slideSwap",value:function(e){qr(this.currentForm,e),this.currentForm=e}},{key:"getBondsFeeBuffer",value:(S=s(f().mark((function e(t,n){var r,a;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=ht().loading(n),e.next=3,C("/api/bondsfeebuffer",{assetID:t});case 3:if(a=e.sent,r(),ht().checkResponse(a)){e.next=7;break}return e.abrupt("return",0);case 7:return e.abrupt("return",a.feeBuffer);case 8:case"end":return e.stop()}}),e)}))),function(e,t){return S.apply(this,arguments)})},{key:"newWalletCreated",value:(w=s(f().mark((function e(t,n){var r,a,o,s,i,c;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,ht().fetchUser();case 2:if(r=e.sent){e.next=5;break}return e.abrupt("return");case 5:return a=this.page,o=r.assets[t],s=o.wallet,i=this.currentDEX.bondAssets[o.symbol].amount,e.next=11,this.getBondsFeeBuffer(t,a.newWalletForm);case 11:if(c=e.sent,this.confirmRegisterForm.setFees(t,c),!(s.synced&&s.balance.available>=2*i+c)){e.next=17;break}return e.next=16,this.animateConfirmForm(a.newWalletForm);case 16:return e.abrupt("return");case 17:this.walletWaitForm.setWallet(t,c,n),this.slideSwap(a.walletWait);case 19:case"end":return e.stop()}}),e,this)}))),function(e,t){return w.apply(this,arguments)})},{key:"onAccountFileChange",value:(x=s(f().mark((function e(){var t,n;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=this.page,(n=t.accountFile.files)&&n.length){e.next=4;break}return e.abrupt("return");case 4:t.selectedAccount.textContent=n[0].name,Me.show(t.removeAccount),Me.hide(t.addAccount);case 7:case"end":return e.stop()}}),e,this)}))),function(){return x.apply(this,arguments)})},{key:"clearAccountFile",value:function(){var e=this.page;e.accountFile.value="",e.selectedAccount.textContent=be(j),Me.hide(e.removeAccount),Me.show(e.addAccount)}},{key:"prepareAccountImport",value:(m=s(f().mark((function e(t){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:this.page.importAccountErr.textContent="",this.showForm(t);case 3:case"end":return e.stop()}}),e,this)}))),function(e){return m.apply(this,arguments)})},{key:"importAccount",value:(p=s(f().mark((function e(){var t,n,r,a,o,s,i,c,l,u,d;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=this.page,n="",!t.accountFile.value){e.next=10;break}if((r=t.accountFile.files)&&r.length){e.next=7;break}return console.error("importAccount: no file specified"),e.abrupt("return");case 7:return e.next=9,r[0].text();case 9:n=e.sent;case 10:e.prev=10,a=JSON.parse(n),e.next=19;break;case 14:return e.prev=14,e.t0=e.catch(10),t.importAccountErr.textContent=e.t0.message,Me.show(t.importAccountErr),e.abrupt("return");case 19:if(void 0!==a){e.next=22;break}return Me.showFormError(t.importAccountErr,be("ACCT_UNDEFINED")),e.abrupt("return");case 22:return s=(o=a).bonds,i=void 0===s?[]:s,c=ca(o,Da),l={account:c,bonds:i},u=ht().loading(this.body),e.next=27,C("/api/importaccount",l);case 27:if(d=e.sent,u(),ht().checkResponse(d)){e.next=32;break}return Me.showFormError(t.importAccountErr,d.msg),e.abrupt("return");case 32:return e.next=34,ht().fetchUser();case 34:Me.hide(t.forms),window.location.reload();case 36:case"end":return e.stop()}}),e,this,[[10,14]])}))),function(){return p.apply(this,arguments)})},{key:"submitExportSeedReq",value:(u=s(f().mark((function e(){var t,n,r,a;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.page,n=t.exportSeedPW.value,r=ht().loading(this.body),e.next=5,C("/api/exportseed",{pass:n});case 5:if(a=e.sent,r(),ht().checkResponse(a)){e.next=10;break}return Me.showFormError(t.exportSeedErr,a.msg),e.abrupt("return");case 10:t.exportSeedPW.value="",128===a.seed.length&&1===a.seed.split(" ").length?t.legacySeed.textContent=a.seed.match(/.{1,32}/g).map((function(e){var t;return null===(t=e.match(/.{1,8}/g))||void 0===t?void 0:t.join(" ")})).join("\n"):t.mnemonic.textContent=a.seed,this.showForm(t.authorizeSeedDisplay);case 13:case"end":return e.stop()}}),e,this)}))),function(){return u.apply(this,arguments)})},{key:"showForm",value:(l=s(f().mark((function e(t){var n,r;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=this.page,this.currentForm=t,this.forms.forEach((function(e){return Me.hide(e)})),t.style.right="10000px",Me.show(n.forms,t),r=(n.forms.offsetWidth+t.offsetWidth)/2,e.next=8,Me.animate(300,(function(e){t.style.right="".concat((1-e)*r,"px")}),"easeOutHard");case 8:t.style.right="0";case 9:case"end":return e.stop()}}),e,this)}))),function(e){return l.apply(this,arguments)})},{key:"getCertFile",value:(c=s(f().mark((function e(){var t,n;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t="",!this.dexAddrForm.page.certFile.value){e.next=7;break}if(!(n=this.dexAddrForm.page.certFile.files)||!n.length){e.next=7;break}return e.next=6,n[0].text();case 6:t=e.sent;case 7:return e.abrupt("return",t);case 8:case"end":return e.stop()}}),e,this)}))),function(){return c.apply(this,arguments)})},{key:"registerDEXSuccess",value:(o=s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:window.location.reload();case 1:case"end":return e.stop()}}),e)}))),function(){return o.apply(this,arguments)})},{key:"changeAppPW",value:(a=s(f().mark((function e(){var t,n,r,a,o;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=this.page,Me.hide(t.changePWErrMsg),n=function(){t.appPW.value="",t.newAppPW.value="",t.confirmNewPW.value=""},t.appPW.value&&t.newAppPW.value&&t.confirmNewPW.value){e.next=7;break}return Me.showFormError(t.changePWErrMsg,be("NO_APP_PASS_ERROR_MSG")),n(),e.abrupt("return");case 7:if(t.newAppPW.value===t.confirmNewPW.value){e.next=11;break}return Me.showFormError(t.changePWErrMsg,be(N)),n(),e.abrupt("return");case 11:return r=ht().loading(t.changeAppPW),a={appPW:t.appPW.value,newAppPW:t.newAppPW.value},n(),e.next=16,C("/api/changeapppass",a);case 16:if(o=e.sent,r(),ht().checkResponse(o)){e.next=21;break}return Me.showFormError(t.changePWErrMsg,o.msg),e.abrupt("return");case 21:Me.hide(t.forms);case 22:case"end":return e.stop()}}),e,this)}))),function(){return a.apply(this,arguments)})},{key:"unload",value:function(){Me.unbind(document,"keyup",this.keyup)}},{key:"animateRegAsset",value:(r=s(f().mark((function e(t){var n;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:Me.hide(t),n=this.page.regAssetForm,this.currentForm=n,this.regAssetForm.animate(),Me.show(n);case 5:case"end":return e.stop()}}),e,this)}))),function(e){return r.apply(this,arguments)})},{key:"animateConfirmForm",value:(n=s(f().mark((function e(t){var n;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:this.confirmRegisterForm.animate(),n=this.page.confirmRegForm,this.currentForm=n,Me.hide(t),Me.show(n);case 5:case"end":return e.stop()}}),e,this)}))),function(e){return n.apply(this,arguments)})},{key:"submitGameCode",value:(t=s(f().mark((function e(){var t,n,r,a,o,s;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=this.page,Me.hide(t.gameCodeErr),n=t.gameCodeInput.value){e.next=7;break}return t.gameCodeErr.textContent=be("NO_CODE_PROVIDED"),Me.show(t.gameCodeErr),e.abrupt("return");case 7:return r=t.gameCodeMsg.value||"",a=ht().loading(t.gameCodeForm),e.next=11,C("/api/redeemgamecode",{code:n,msg:r});case 11:if(o=e.sent,a(),ht().checkResponse(o)){e.next=17;break}return t.gameCodeErr.textContent=be(H,{msg:o.msg}),Me.show(t.gameCodeErr),e.abrupt("return");case 17:Me.show(t.gameCodeSuccess),t.gameRedeemTx.dataset.explorerCoin=o.coinString,zn(42,t.gameRedeemTx),t.gameRedeemTx.textContent=o.coinString,s=ht().unitInfo(42),t.gameRedeemValue.textContent=Me.formatCoinValue(o.win,s);case 24:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})}]),A}(it);function Aa(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,i=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){i=!0,o=e},f:function(){try{s||null==n.return||n.return()}finally{if(i)throw o}}}}(e);try{for(r.s();!(t=r.n()).done;){var a=t.value;if(!a.epoch)return a;n||(n=a)}}catch(e){r.e(e)}finally{r.f()}return n}},{key:"bestGapBuy",value:function(){return this.bestGapOrder(this.buys)}},{key:"bestGapSell",value:function(){return this.bestGapOrder(this.sells)}}]),e}();function Ea(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);nthis.maxQlength-1;)this.queue.shift();this.queue.push([e,t])}}},{key:"close",value:function(e){window.log("ws","close, reason:",e,this.handlers),this.handlers={},this.connection&&this.connection.close()}},{key:"connect",value:function(e,t){var n=this;this.uri=e,this.reloader=t;var r=0;!function o(){window.log("ws","connecting to ".concat(e));var s=n.connection=new window.WebSocket(e);if(s){var i=setTimeout((function(){s&&s.close()}),500);s.onmessage=function(e){var t=JSON.parse(e.data);Ba(t.route,t.payload,n.handlers)},s.onclose=function(e){window.log("ws","onclose"),clearTimeout(i),s=n.connection=null,Ba("close",null,n.handlers),r++;var t=Math.min(Math.pow(1.25,r),10);console.error("websocket disconnected (".concat(e.code,"), trying again in ").concat(t.toFixed(1)," seconds")),setTimeout((function(){o()}),1e3*t)},s.onopen=function(){window.log("ws","onopen"),clearTimeout(i),r>0&&(r=0,t()),Ba("open",null,n.handlers);var e=n.queue;n.queue=[];var o,s=function(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return Ea(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ea(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,i=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){i=!0,o=e},f:function(){try{s||null==n.return||n.return()}finally{if(i)throw o}}}}(e);try{for(s.s();!(o=s.n()).done;){var c=a(o.value,2),l=c[0],u=c[1];n.request(l,u)}}catch(e){s.e(e)}finally{s.f()}},s.onerror=function(e){window.log("ws","onerror:",e),Ba("error",e,n.handlers)}}}()}}]),e}());function Oa(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function Ma(e){for(var t=1;t=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e){throw e})),f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,i=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e){i=!0,o=e})),f:function(){try{s||null==n.return||n.return()}finally{if(i)throw o}}}}function Na(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n0}},{key:"setCurrMarketPrice",value:function(){var e=this.market;if(e){var t=ht().exchanges[e.dex.host],n=t.markets[e.cfg.name];if(n.spot){var r,a=qa(this.stats);try{for(a.s();!(r=a.n()).done;){var o=r.value,s=t.assets[n.baseid].unitInfo.conventional,i=s.conversionFactor,c=s.unit,l=ht().fiatRatesMap[n.baseid];l?(o.tmpl.volume.textContent=Me.formatFourSigFigs(n.spot.vol24/i*l),o.tmpl.volUnit.textContent="USD"):(o.tmpl.volume.textContent=Me.formatFourSigFigs(n.spot.vol24/i),o.tmpl.volUnit.textContent=c),co(o.tmpl,t,n)}}catch(e){a.e(e)}finally{a.f()}this.page.obPrice.textContent=Me.formatFourSigFigs(n.spot.rate/this.market.rateConversionFactor),this.page.obPrice.classList.remove("sellcolor","buycolor"),this.page.obPrice.classList.add(n.spot.change24>=0?"buycolor":"sellcolor"),Me.setVis(n.spot.change24>=0,this.page.obUp),Me.setVis(n.spot.change24<0,this.page.obDown)}}}},{key:"setMarketDetails",value:function(){if(this.market){var e,t=qa(this.stats);try{for(t.s();!(e=t.n()).done;){var n=e.value,r=this.market,a=r.baseCfg,o=r.quoteCfg;n.tmpl.baseIcon.src=Me.logoPath(a.symbol),n.tmpl.quoteIcon.src=Me.logoPath(o.symbol),Me.empty(n.tmpl.baseSymbol,n.tmpl.quoteSymbol),n.tmpl.baseSymbol.appendChild(Me.symbolize(a,!0)),n.tmpl.quoteSymbol.appendChild(Me.symbolize(o,!0))}}catch(e){t.e(e)}finally{t.f()}}}},{key:"setHighLow",value:function(){var e=0,t=0,n=this.market.cfg.spot;if(n&&n.low24&&n.high24)e=n.high24,t=n.low24;else{var r,a=null===(r=this.market)||void 0===r?void 0:r.candleCaches[Qa];if(!a){if(this.candleDur!==Qa)return void this.requestCandles(Qa);var o,s=qa(this.stats);try{for(s.s();!(o=s.n()).done;){var i=o.value;i.tmpl.high.textContent="-",i.tmpl.low.textContent="-"}}catch(e){s.e(e)}finally{s.f()}return}for(var c=(new Date).getTime()-864e5,l=a.candles.length-1;l>=0;l--){var u=a.candles[l];if(u.endStamp0&&u.lowRatee&&(e=u.highRate)}}var d,h=this.market.base.id,p=this.market.quote.id,f=this.market.dex,v=qa(this.stats);try{for(v.s();!(d=v.n()).done;){var m=d.value;m.tmpl.high.textContent=e>0?Me.formatFourSigFigs(ht().conventionalRate(h,p,e,f)):"-",m.tmpl.low.textContent=t>0?Me.formatFourSigFigs(ht().conventionalRate(h,p,t,f)):"-"}}catch(e){v.e(e)}finally{v.f()}}},{key:"assetsAreSupported",value:function(){var e,t,n,r,a=this.market,o=a.base,s=a.quote,i=a.baseCfg,c=a.quoteCfg;if(!o||!s)return{isSupported:!1,text:be("NOT_SUPPORTED",{asset:(o?c.symbol:i.symbol).toUpperCase()})};var l=o.token?null===(e=ht().assets[o.token.parentID].info)||void 0===e?void 0:e.versions:null===(t=o.info)||void 0===t?void 0:t.versions,u=s.token?null===(n=ht().assets[s.token.parentID].info)||void 0===n?void 0:n.versions:null===(r=s.info)||void 0===r?void 0:r.versions,d="";return l.includes(i.version)?u.includes(c.version)||(d=be(P,{asset:s.symbol.toUpperCase(),version:c.version+""})):d=be(P,{asset:o.symbol.toUpperCase(),version:i.version+""}),{isSupported:l.includes(i.version)&&u.includes(c.version),text:d}}},{key:"setOrderVisibility",value:function(){var e=this.page;this.isLimit()?(Me.show(e.priceBox,e.tifBox,e.qtyBox,e.maxBox),Me.hide(e.mktBuyBox),this.previewQuoteAmt(!0)):(Me.hide(e.tifBox,e.maxBox,e.priceBox),this.isSell()?(Me.hide(e.mktBuyBox),Me.show(e.qtyBox),this.previewQuoteAmt(!0)):(Me.show(e.mktBuyBox),Me.hide(e.qtyBox),this.previewQuoteAmt(!1))),this.updateOrderBttnState()}},{key:"resolveOrderFormVisibility",value:(N=s(f().mark((function e(){var t,n,r,a,o,i,c,l,u,d,h,p=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.page,n=function(){var e=s(f().mark((function e(){var t,n,r,a,o,s;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(p.assetsAreSupported().isSupported){e.next=2;break}return e.abrupt("return",!1);case 2:if(p.market&&!(p.market.dex.auth.effectiveTier<1)){e.next=4;break}return e.abrupt("return",!1);case 4:if(t=p.tokenAssetApprovalStatuses(),n=t.baseAssetApprovalStatus,r=t.quoteAssetApprovalStatus,n===lt.Approved&&r===lt.Approved){e.next=7;break}return e.abrupt("return",!1);case 7:if(a=p.market,o=a.base,s=a.quote,o&&ht().assets[o.id].wallet&&s&&ht().assets[s.id].wallet){e.next=11;break}return e.abrupt("return",!1);case 11:if(!p.mmRunning){e.next=13;break}return e.abrupt("return",!1);case 13:return e.abrupt("return",!0);case 14:case"end":return e.stop()}}),e)})));return function(){return e.apply(this,arguments)}}(),e.t0=Me,e.next=5,n();case 5:e.t1=e.sent,e.t2=t.orderForm,e.t3=t.orderTypeBttns,e.t0.setVis.call(e.t0,e.t1,e.t2,e.t3),this.market&&(r=this.market.dex.auth,a=r.effectiveTier,o=r.pendingStrength,Me.setVis(a>0||o>0,t.reputationAndTradingTierBox)),(i=ht().mmStatus)&&void 0===this.mmRunning&&this.market.base&&this.market.quote&&(c=this.market,l=c.base.id,u=c.quote.id,d=c.dex.host,h=i.bots.find((function(e){var t=e.config;return t.baseID===l&&t.quoteID===u&&t.host===d})),this.mmRunning=Boolean(null==h?void 0:h.running)),Me.setVis(this.mmRunning,t.mmRunning),this.mmRunning&&Me.hide(t.orderForm,t.orderTypeBttns);case 14:case"end":return e.stop()}}),e,this)}))),function(){return N.apply(this,arguments)})},{key:"setLoaderMsgVisibility",value:function(){var e=this.page,t=this.assetsAreSupported(),n=t.isSupported,r=t.text;n?Me.hide(e.loaderMsg):(e.loaderMsg.textContent=r,Me.show(e.loaderMsg),Me.hide(e.notRegistered),Me.hide(e.noWallet))}},{key:"showTokenApprovalForm",value:(q=s(f().mark((function e(t){var n;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=t?this.market.base.id:this.market.quote.id,this.approveTokenForm.setAsset(n,this.market.dex.host),this.showForm(this.page.approveTokenForm);case 3:case"end":return e.stop()}}),e,this)}))),function(e){return q.apply(this,arguments)})},{key:"tokenAssetApprovalStatuses",value:function(){var e=this.market,t=e.base,n=e.quote,r=lt.Approved,a=lt.Approved;if(null!=t&&t.token){var o,s=ht().assets[t.id],i=this.market.dex.assets[t.id].version;null!=s&&null!==(o=s.wallet)&&void 0!==o&&o.approved&&void 0!==s.wallet.approved[i]&&(r=s.wallet.approved[i])}if(null!=n&&n.token){var c,l=ht().assets[n.id],u=this.market.dex.assets[n.id].version;null!=l&&null!==(c=l.wallet)&&void 0!==c&&c.approved&&void 0!==l.wallet.approved[u]&&(a=l.wallet.approved[u])}return{baseAssetApprovalStatus:r,quoteAssetApprovalStatus:a}}},{key:"setTokenApprovalVisibility",value:function(){var e=this.page,t=this.tokenAssetApprovalStatuses(),n=t.baseAssetApprovalStatus,r=t.quoteAssetApprovalStatus;if(n===lt.Approved&&r===lt.Approved)return Me.hide(e.tokenApproval),e.sellBttn.removeAttribute("disabled"),void e.buyBttn.removeAttribute("disabled");n!==lt.Approved&&r===lt.Approved&&(e.sellBttn.setAttribute("disabled","disabled"),e.buyBttn.removeAttribute("disabled"),this.setBuy(),Me.show(e.approvalRequiredSell),Me.hide(e.approvalRequiredBuy,e.approvalRequiredBoth)),n===lt.Approved&&r!==lt.Approved&&(e.buyBttn.setAttribute("disabled","disabled"),e.sellBttn.removeAttribute("disabled"),this.setSell(),Me.show(e.approvalRequiredBuy),Me.hide(e.approvalRequiredSell,e.approvalRequiredBoth)),n!==lt.Approved&&r!==lt.Approved&&(Me.show(e.approvalRequiredBoth),Me.hide(e.approvalRequiredSell,e.approvalRequiredBuy)),Me.show(e.tokenApproval),e.approvalPendingBaseSymbol.textContent=e.baseTokenAsset.textContent=this.market.base.symbol.toUpperCase(),e.approvalPendingQuoteSymbol.textContent=e.quoteTokenAsset.textContent=this.market.quote.symbol.toUpperCase(),Me.setVis(n===lt.NotApproved,e.approveBaseBttn),Me.setVis(r===lt.NotApproved,e.approveQuoteBttn),Me.setVis(n===lt.Pending,e.approvalPendingBase),Me.setVis(r===lt.Pending,e.approvalPendingQuote)}},{key:"setRegistrationStatusView",value:function(e,t,n){var r=this.page;r.regStatusTitle.textContent=e,r.regStatusConfsDisplay.textContent=t,r.registrationStatus.classList.remove("completed","error","waiting"),r.registrationStatus.classList.add(n)}},{key:"updateRegistrationStatusView",value:function(){var e=this.page,t=this.market.dex;if(e.regStatusDex.textContent=t.host,e.postingBondsDex.textContent=t.host,t.auth.effectiveTier>=1)this.setRegistrationStatusView(be("REGISTRATION_FEE_SUCCESS"),"","completed");else{var n=(t.auth.pendingBonds||[]).map((function(e){var n=t.bondAssets[e.symbol].confs;return"".concat(e.confs," / ").concat(n)})).join(", ");this.setRegistrationStatusView(be("WAITING_FOR_CONFS"),n,"waiting")}}},{key:"setRegistrationStatusVisibility",value:function(){var e=this,t=this.page,n=this.market;if(n&&n.dex&&n.dex.connectionStatus===ct.Connected){this.updateRegistrationStatusView();var r=function(e){for(var n=0,r=[t.registrationStatus,t.bondRequired,t.bondCreationPending,t.notRegistered];n=1){var a=function(){var t=s(f().mark((function t(){return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:r(void 0),e.resolveOrderFormVisibility();case 2:case"end":return t.stop()}}),t)})));return function(){return t.apply(this,arguments)}}();if(Me.isHidden(t.orderForm))return void setTimeout(a,5e3);a()}else n.dex.viewOnly?(t.unregisteredDex.textContent=n.dex.host,r(t.notRegistered)):this.hasPendingBonds()?r(t.registrationStatus):n.dex.auth.targetTier>0?r(t.bondCreationPending):(t.acctTier.textContent="".concat(n.dex.auth.effectiveTier),t.dexSettingsLink.href="/dexsettings/".concat(n.dex.host),r(t.bondRequired))}}},{key:"setOrderBttnText",value:function(){this.isSell()?this.page.submitBttn.textContent=be("SET_BUTTON_SELL",{asset:Me.shortSymbol(this.market.baseCfg.unitInfo.conventional.unit)}):this.page.submitBttn.textContent=be("SET_BUTTON_BUY",{asset:Me.shortSymbol(this.market.baseCfg.unitInfo.conventional.unit)})}},{key:"setOrderBttnEnabled",value:function(e,t){var n=this.page.submitBttn;e?(n.removeAttribute("disabled"),n.removeAttribute("title")):(n.setAttribute("disabled","true"),t&&n.setAttribute("title",t))}},{key:"updateOrderBttnState",value:function(){var e=this.market,t=this.currentOrder,n=t.qty,r=t.rate,a=t.isLimit,o=t.sell,s=ht().assets[this.market.base.id].wallet,i=ht().assets[e.quote.id].wallet;if(s&&i)if(n<=0||n-1&&(o.classList.add("hover"),this.hovers.push(o))}t.hoverPrice.textContent=Me.formatCoinValue(e.rate),t.hoverVolume.textContent=Me.formatCoinValue(e.depth),t.hoverVolume.style.color=e.dotColor}else Me.hide(t.depthLegend)}},{key:"reportDepthZoom",value:function(e){k.storeLocal(k.depthZoomLK,e)}},{key:"reportMouseCandle",value:function(e){var t=this.page;e?(Me.show(t.candlesLegend),t.candleStart.textContent=Me.formatCoinValue(e.startRate/this.market.rateConversionFactor),t.candleEnd.textContent=Me.formatCoinValue(e.endRate/this.market.rateConversionFactor),t.candleHigh.textContent=Me.formatCoinValue(e.highRate/this.market.rateConversionFactor),t.candleLow.textContent=Me.formatCoinValue(e.lowRate/this.market.rateConversionFactor),t.candleVol.textContent=Me.formatCoinValue(e.matchVolume,this.market.baseUnitInfo)):Me.hide(t.candlesLegend)}},{key:"parseOrder",value:function(){var e=this.page,t=e.qtyField,n=this.isLimit(),r=this.isSell(),a=this.market,o=a.baseUnitInfo.conventional.conversionFactor;return n||r||(t=e.mktBuyField,o=a.quoteUnitInfo.conventional.conversionFactor),{host:a.dex.host,isLimit:n,sell:r,base:a.base.id,quote:a.quote.id,qty:ao(t.value||"",o),rate:ao(e.rateField.value||"",a.rateConversionFactor),tifnow:e.tifNow.checked||!1,options:{}}}},{key:"previewQuoteAmt",value:function(e){var t=this.page;if(this.market.base&&this.market.quote){var n=this.currentOrder=this.parseOrder(),r=this.adjustedRate();if(t.orderErr.textContent="",r&&(n.sell?this.preSell():this.preBuy()),this.depthLines.input=[],r&&this.isLimit()&&(this.depthLines.input=[{rate:n.rate/this.market.rateConversionFactor,color:n.sell?this.depthChart.theme.sellLine:this.depthChart.theme.buyLine}]),this.drawChartLines(),!e||!r||!n.qty)return t.orderPreview.textContent="",void this.drawChartLines();var a=ht().assets[n.quote].unitInfo.conventional.unit,o=n.qty*n.rate/Mt,s=Me.formatCoinValue(o,this.market.quoteUnitInfo);t.orderPreview.textContent=be("ORDER_PREVIEW",{total:s,asset:a}),this.isSell()?this.preSell():this.preBuy()}}},{key:"preSell",value:function(){var e=this,t=this.market,n=ht().assets[t.base.id].wallet;return n.balance.available0){if(a.token){var i=ht().assets[a.token.parentID],c=i.wallet.balance.available,l=i.unitInfo;return void(c0)return}return Me.show(t.maxZeroNoBal),void(t.maxZeroNoBalTicker.textContent=a.unitInfo.conventional.unit)}Me.show(t.maxAboveZero),t.maxFromAmt.textContent=Me.formatCoinValue(e.value||0,a.unitInfo),t.maxFromTicker.textContent=a.unitInfo.conventional.unit}}},{key:"validateOrder",value:function(e){var t=this.page,n=this.market,r=n.cfg.minimumRate,a=n.rateConversionFactor;if(e.isLimit){if(!e.rate)return Me.show(t.orderErr),t.orderErr.textContent=be("NO_ZERO_RATE"),!1;if(e.rate0&&this.book.add(u),this.addTableOrder(u)}}catch(e){l.e(e)}finally{l.f()}if(!this.book)return this.depthChart.clear(),Me.empty(this.page.buyRows),void Me.empty(this.page.sellRows);Me.show(this.page.epochLine),this.loadingAnimations.depth&&this.loadingAnimations.depth.stop(),this.depthChart.canvas.classList.remove("invisible"),this.depthChart.set(this.book,r.lotsize,r.ratestep,a,o),this.recentMatches=null!==(t=e.book.recentMatches)&&void 0!==t?t:[],this.refreshRecentMatchesTable()}},{key:"midGapConventional",value:function(){var e=this.midGap();if(!e)return e;var t=this.market,n=t.baseUnitInfo,r=t.quoteUnitInfo;return e*n.conventional.conversionFactor/r.conventional.conversionFactor}},{key:"midGap",value:function(){var e=this.book;if(e)return e.buys&&e.buys.length?e.sells&&e.sells.length?(e.buys[0].msgRate+e.sells[0].msgRate)/2/Mt:e.buys[0].msgRate/Mt:e.sells&&e.sells.length?e.sells[0].msgRate/Mt:null}},{key:"setMarketBuyOrderEstimate",value:function(){var e=this.market,t=e.cfg.lotsize,n=ht().user.exchanges[e.dex.host].markets[e.sid].buybuffer,r=this.midGapConventional();r&&(this.page.minMktBuy.textContent=Me.formatCoinValue(t*n*r,e.baseUnitInfo))}},{key:"maxUserOrderCount",value:function(){var e=this.market,t=e.dex.host,n=e.cfg.name;return Math.max(10,ht().orders(t,n).length)}},{key:"loadUserOrders",value:(A=s(f().mark((function e(){var t,n,r,a,o,s,i,c,l,u,d,h,p;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:for(s in t=this.market,n=t.base,r=t.quote,a=t.dex.host,o=t.cfg.name,this.metaOrders)delete this.metaOrders[s];if(n&&r){e.next=4;break}return e.abrupt("return",this.resolveUserOrders([]));case 4:if(!((i=ht().orders(a,o)).length>=10)){e.next=7;break}return e.abrupt("return",this.resolveUserOrders(i));case 7:return c={hosts:[a],market:{baseID:n.id,quoteID:r.id},n:this.maxUserOrderCount()},e.next=10,C("/api/orders",c);case 10:l=e.sent,u=l.orders||[],d=qa(i),e.prev=13,p=f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=h.value,u.some((function(e){return e.id===t.id}))||u.push(t);case 2:case"end":return e.stop()}}),e)})),d.s();case 16:if((h=d.n()).done){e.next=20;break}return e.delegateYield(p(),"t0",18);case 18:e.next=16;break;case 20:e.next=25;break;case 22:e.prev=22,e.t1=e.catch(13),d.e(e.t1);case 25:return e.prev=25,d.f(),e.finish(25);case 28:return e.abrupt("return",this.resolveUserOrders(l.orders||[]));case 29:case"end":return e.stop()}}),e,this,[[13,22,25,28]])}))),function(){return A.apply(this,arguments)})},{key:"refreshActiveOrders",value:function(){var e=ht().orders(this.market.dex.host,ro(this.market.baseCfg.symbol,this.market.quoteCfg.symbol));return this.resolveUserOrders(e)}},{key:"resolveUserOrders",value:function(e){var t,n,r,a=this,o=this.page,s=this.metaOrders,i=this.market,c=i.cfg,l=function(e){return e.statusp&&(h=h.slice(0,p)),s)delete s[f];Me.empty(o.userOrders),Me.setVis(null===(t=h)||void 0===t?void 0:t.length,o.userOrders),Me.setVis(!(null!==(n=h)&&void 0!==n&&n.length),o.userNoOrders);var v,m=!1,g=qa(h);try{var y=function(){var e=v.value,t=o.userOrderTmpl.cloneNode(!0);o.userOrders.appendChild(t);var n=Me.parseTemplate(t),r=Me.parseTemplate(n.header),u=Me.parseTemplate(n.details);e.div=t,e.header=r,e.details=u;var d,h=e.ord,p=h.id,f=l(h);p&&(s[p]=e),!h.readyToTick&&Vt(h)&&(n.header.classList.add("unready-user-order"),m=!0),r.sideLight.classList.add(h.sell?"sell":"buy"),f||r.sideLight.classList.add("inactive"),u.side.textContent=e.header.side.textContent=qt(h),u.side.classList.add(h.sell?"sellcolor":"buycolor"),r.side.classList.add(h.sell?"sellcolor":"buycolor"),u.qty.textContent=e.header.qty.textContent=Me.formatCoinValue(h.qty,i.baseUnitInfo),d=h.type===Ct?a.marketOrderRateString(h,i):Me.formatRateFullPrecision(h.rate,i.baseUnitInfo,i.quoteUnitInfo,c.ratestep),u.rate.textContent=e.header.rate.textContent=d,r.baseSymbol.textContent=i.baseUnitInfo.conventional.unit,u.type.textContent=i.quoteUnitInfo.conventional.unit,a.updateMetaOrder(e),Me.bind(t,"mouseenter",(function(){a.activeMarkerRate=h.rate,a.setDepthMarkers()}));var g,y=function(e){e.stopPropagation(),a.showCancel(t,p)},b=function(e){e.stopPropagation(),a.showAccelerate(h)};p?(Kt(h)&&(Me.show(u.cancelBttn),Wa(u.cancelBttn,"click",(function(e){y(e)}))),Wa(u.accelerateBttn,"click",(function(e){b(e)})),ht().canAccelerateOrder(h)&&Me.show(u.accelerateBttn),u.link.href="order/".concat(p),ht().bindInternalNavigation(t)):(Me.hide(u.accelerateBttn),Me.hide(u.cancelBttn),Me.hide(u.link)),Me.bind(n.header,"click",(function(){if(Me.isDisplayed(n.details))return Me.hide(n.details),r.expander.classList.add("ico-arrowdown"),void r.expander.classList.remove("ico-arrowup");Me.show(n.details),r.expander.classList.remove("ico-arrowdown"),r.expander.classList.add("ico-arrowup"),g&&g.remove()})),Me.bind(n.header,"mouseenter",(function(){if(!Me.isDisplayed(n.details)){g&&g.remove();var e=document.createElement("div");g=e,document.body.appendChild(e),e.className="user-order-floaty-menu";var r=Me.layoutMetrics(n.header),s=r.bodyTop+r.height;e.style.top="".concat(s-1,"px"),e.style.left="".concat(r.bodyLeft,"px");var i=a.metaOrders[p].ord,c=function(t,n){var r=t.cloneNode(!0);e.appendChild(r),Me.show(r),Me.bind(r,"click",(function(e){n(e)}))};Kt(i)&&c(u.cancelBttn,(function(e){y(e)})),ht().canAccelerateOrder(i)&&c(u.accelerateBttn,(function(e){b(e)})),e.appendChild(u.link.cloneNode(!0));var l=o.orderScroller.scrollTop,d=function n(r){var a=o.orderScroller.scrollTop-l;e.style.top="".concat(s+a,"px"),Me.mouseInElement(r,e)||Me.mouseInElement(r,t)||(e.remove(),g=null,document.removeEventListener("mousemove",n),o.orderScroller.removeEventListener("scroll",n))};document.addEventListener("mousemove",d),o.orderScroller.addEventListener("scroll",d)}})),ht().bindTooltips(t)};for(g.s();!(v=g.n()).done;)y()}catch(e){g.e(e)}finally{g.f()}Me.setVis(m,o.unreadyOrdersMsg),this.setDepthMarkers()}},{key:"marketOrderRateString",value:function(e,t){var n;if(null===(n=e.matches)||void 0===n||!n.length)return be(X);var r=Me.formatRateFullPrecision(zt(e),t.baseUnitInfo,t.quoteUnitInfo,t.cfg.ratestep);return e.matches.length>1&&(r="~ "+r),r}},{key:"updateMetaOrder",value:function(e){var t=e.header,n=e.details,r=e.ord;r.status<=It||Vt(r)?t.activeLight.classList.add("active"):t.activeLight.classList.remove("active"),n.status.textContent=t.status.textContent=Ut(r),n.age.textContent=Me.timeSince(r.submitTime),n.filled.textContent="".concat((_t(r)/r.qty*100).toFixed(1),"%"),n.settled.textContent="".concat((jt(r)/r.qty*100).toFixed(1),"%")}},{key:"setDepthMarkers",value:function(){for(var e={buys:[],sells:[]},t=this.market.rateConversionFactor,n=0,r=Object.values(this.metaOrders);n0&&this.book.add(t),this.addTableOrder(t),this.updateTitle(),this.depthChart.draw()}}},{key:"handleUnbookOrderRoute",value:function(e){if(ht().log("book","handleUnbookOrderRoute:",e),e.host===this.market.dex.host&&e.marketID===this.market.sid){var t=e.payload;this.book.remove(t.token),this.removeTableOrder(t),this.updateTitle(),this.depthChart.draw()}}},{key:"handleUpdateRemainingRoute",value:function(e){if(ht().log("book","handleUpdateRemainingRoute:",e),e.host===this.market.dex.host&&e.marketID===this.market.sid){var t=e.payload;this.book.updateRemaining(t.token,t.qty,t.qtyAtomic),this.updateTableOrder(t),this.depthChart.draw()}}},{key:"handleEpochOrderRoute",value:function(e){if(ht().log("book","handleEpochOrderRoute:",e),e.host===this.market.dex.host&&e.marketID===this.market.sid){var t=e.payload;t.msgRate>0&&this.book.add(t),t.qtyAtomic>0&&this.addTableOrder(t),this.depthChart.draw()}}},{key:"handleCandlesRoute",value:function(e){if(this.candlesLoading&&(clearTimeout(this.candlesLoading.timer),this.candlesLoading.loaded(),this.candlesLoading=null),e.host===this.market.dex.host&&e.marketID===this.market.cfg.name){var t=e.payload.dur;this.market.candleCaches[t]=e.payload,this.setHighLow(),this.candleDur===t&&(this.loadingAnimations.candles&&this.loadingAnimations.candles.stop(),this.candleChart.canvas.classList.remove("invisible"),this.candleChart.setCandles(e.payload,this.market.cfg,this.market.baseUnitInfo,this.market.quoteUnitInfo))}}},{key:"handleEpochMatchSummary",value:function(e){this.addRecentMatches(e.payload.matchSummaries),this.refreshRecentMatchesTable()}},{key:"handleCandleUpdateRoute",value:function(e){if(e.host===this.market.dex.host){var t=e.payload,n=t.dur,r=t.candle,a=this.market.candleCaches[n];if(a){var o=a.candles;0===o.length?o.push(r):o[o.length-1].startStamp===r.startStamp?o[o.length-1]=r:o.push(r),this.candleDur===n&&this.candleChart.draw()}}}},{key:"showForm",value:(I=s(f().mark((function e(t){var n,a;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.currentForm=t,n=this.page,Me.hide.apply(Me,r(Array.from(n.forms.children))),t.style.right="10000px",Me.show(n.forms,t),a=(n.forms.offsetWidth+t.offsetWidth)/2,e.next=8,Me.animate(500,(function(e){t.style.right="".concat((1-e)*a,"px")}),"easeOutHard");case 8:t.style.right="0";case 9:case"end":return e.stop()}}),e,this)}))),function(e){return I.apply(this,arguments)})},{key:"showToggleWalletStatus",value:function(e){var t=this.page;this.openAsset=e,Me.hide(t.toggleWalletStatusErr,t.walletStatusDisable,t.disableWalletMsg),Me.show(t.walletStatusEnable,t.enableWalletMsg),this.showForm(t.toggleWalletStatusConfirm)}},{key:"toggleWalletStatus",value:(D=s(f().mark((function e(){var t,n,r,a;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.page,Me.hide(t.toggleWalletStatusErr),n={assetID:this.openAsset.id,disable:!1},r=ht().loading(t.toggleWalletStatusConfirm),e.next=7,C("/api/togglewalletstatus",n);case 7:if(a=e.sent,r(),ht().checkResponse(a)){e.next=13;break}return t.toggleWalletStatusErr.textContent=a.msg,Me.show(t.toggleWalletStatusErr),e.abrupt("return");case 13:Me.hide(this.page.forms),this.balanceWgt.updateAsset(this.openAsset.id);case 15:case"end":return e.stop()}}),e,this)}))),function(){return D.apply(this,arguments)})},{key:"showVerify",value:function(){this.preorderCache={};var e,t=this.page,n=this.currentOrder=this.parseOrder(),r=n.sell,a=ht().assets[n.base],o=ht().assets[n.quote],s=r?o:a,i=r?a:o,c=function(e){switch(e.dataset.icon){case"from":if(i.token){var t=ht().assets[i.token.parentID];e.src=Me.logoPath(t.symbol)}else e.src=Me.logoPath(i.symbol);break;case"to":if(s.token){var n=ht().assets[s.token.parentID];e.src=Me.logoPath(n.symbol)}else e.src=Me.logoPath(s.symbol)}},l=qa(Me.applySelector(t.vDetailPane,"[data-icon]"));try{for(l.s();!(e=l.n()).done;)c(e.value)}catch(e){l.e(e)}finally{l.f()}var u,d=qa(Me.applySelector(t.vFeeSummary,"[data-icon]"));try{for(d.s();!(u=d.n()).done;)c(u.value)}catch(e){d.e(e)}finally{d.f()}Me.hide(t.vPreorderErr),Me.show(t.vPreorder),t.vBuySell.textContent=be(r?"SELLING":"BUYING");var h=be(r?B:E);if(t.vSideSubmit.textContent=h,t.vOrderHost.textContent=n.host,n.isLimit){Me.show(t.verifyLimit),Me.hide(t.verifyMarket);var p="Limit ".concat(h," Order");t.vOrderType.textContent=n.tifnow?p+" (immediate)":p,t.vRate.textContent=Me.formatCoinValue(n.rate/this.market.rateConversionFactor),t.vQty.textContent=Me.formatCoinValue(n.qty,a.unitInfo);var f=n.rate/Mt*n.qty;t.vTotal.textContent=Me.formatCoinValue(f,o.unitInfo),this.showFiatValue(o.id,f,t.vFiatTotal)}else{Me.hide(t.verifyLimit),Me.show(t.verifyMarket),t.vOrderType.textContent="Market ".concat(h," Order");var v=n.sell?this.market.baseUnitInfo:this.market.quoteUnitInfo;t.vmFromTotal.textContent=Me.formatCoinValue(n.qty,v),t.vmFromAsset.textContent=i.symbol.toUpperCase(),this.showFiatValue(i.id,n.qty,t.vmFromTotalFiat);var m=this.midGap();if(m){Me.show(t.vMarketEstimate);var g=n.sell?n.qty*m:n.qty/m;t.vmToTotal.textContent=Me.formatCoinValue(g,s.unitInfo),t.vmToAsset.textContent=s.symbol.toUpperCase(),this.showFiatValue(s.id,g,t.vmTotalFiat)}else Me.hide(t.vMarketEstimate)}r?(t.vHeader.classList.add(Ka),t.vHeader.classList.remove(Xa),t.vSubmit.classList.add(Ka),t.vSubmit.classList.remove(Xa)):(t.vHeader.classList.add(Xa),t.vHeader.classList.remove(Ka),t.vSubmit.classList.add(Xa),t.vSubmit.classList.remove(Ka)),this.showVerifyForm(),a.wallet.open&&o.wallet.open?this.preOrder(n):(Me.hide(t.vPreorder),this.unlockWalletsForEstimates())}},{key:"showFiatValue",value:function(e,t,n){if(n){var r=ht().fiatRatesMap[e];n.textContent=Me.formatFiatConversion(t,r,ht().unitInfo(e)),r?Me.show(n.parentElement):Me.hide(n.parentElement)}}},{key:"showVerifyForm",value:(T=s(f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=this.page,Me.hide(t.vErr),this.showForm(t.verifyForm);case 3:case"end":return e.stop()}}),e,this)}))),function(){return T.apply(this,arguments)})},{key:"unlockWalletsForEstimates",value:(F=s(f().mark((function e(){var t,n;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.page,n=ht().loading(t.verifyForm),e.next=4,this.unlockMarketWallets();case 4:n(),Me.show(t.vPreorder),this.preOrder(this.parseOrder());case 7:case"end":return e.stop()}}),e,this)}))),function(){return F.apply(this,arguments)})},{key:"unlockWallet",value:(S=s(f().mark((function e(t){var n;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,C("/api/openwallet",{assetID:t});case 2:if(n=e.sent,ht().checkResponse(n)){e.next=5;break}throw Error("error unlocking wallet "+n.msg);case 5:this.balanceWgt.updateAsset(t);case 6:case"end":return e.stop()}}),e,this)}))),function(e){return S.apply(this,arguments)})},{key:"unlockMarketWallets",value:(w=s(f().mark((function e(){var t,n,r,a,o,s,i;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:for(t=this.market,n=t.base,r=t.quote,a=[],n.wallet.open||a.push(n.id),r.wallet.open||a.push(r.id),o=0,s=a;o0?F/w:F,D=e.estimate.realisticBestCase/T*100;r.vSwapFeesLowPct.textContent=w<=0?"":"(".concat(c(D),"%)"),r.vSwapFeesLow.textContent=Me.formatCoinValue(e.estimate.realisticBestCase,x);var I=e.estimate.realisticWorstCase/T*100;r.vSwapFeesHighPct.textContent=w<=0?"":"(".concat(c(I),"%)"),r.vSwapFeesHigh.textContent=Me.formatCoinValue(e.estimate.realisticWorstCase,x);var A=e.estimate.maxFees/T*100;r.vSwapFeesMaxPct.textContent=w<=0?"":"(".concat(c(A),"%)"),r.vSwapFeesMax.textContent=Me.formatCoinValue(e.estimate.maxFees,x);var R=this.midGap()||n.rate/i,E=n.sell?F*R:F/R,B=k>0?E/k:E,P=t.estimate.realisticBestCase/B*100;r.vRedeemFeesLowPct.textContent=k<=0?"":"(".concat(c(P),"%)"),r.vRedeemFeesLow.textContent=Me.formatCoinValue(t.estimate.realisticBestCase,b);var L=t.estimate.realisticWorstCase/B*100;r.vRedeemFeesHighPct.textContent=k<=0?"":"(".concat(c(L),"%)"),r.vRedeemFeesHigh.textContent=Me.formatCoinValue(t.estimate.realisticWorstCase,b),l&&u?(Me.show(r.vFeeSummaryPct),Me.hide(r.vFeeSummary),r.vFeeSummaryLow.textContent=c(D+P),r.vFeeSummaryHigh.textContent=c(I+L)):(Me.hide(r.vFeeSummaryPct),Me.show(r.vFeeSummary),r.summarySwapFeesLow.textContent=r.vSwapFeesLow.textContent,r.summarySwapFeesHigh.textContent=r.vSwapFeesHigh.textContent,r.summaryRedeemFeesLow.textContent=r.vRedeemFeesLow.textContent,r.summaryRedeemFeesHigh.textContent=r.vRedeemFeesHigh.textContent)}else Me.hide(r.vPreorderEstimates)}},{key:"submitCancel",value:(p=s(f().mark((function e(){var t,n,r,a,o,s;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.page,n=this.cancelData,r=n.order,a={orderID:r.id},o=ht().loading(t.cancelSubmit),e.next=7,C("/api/cancel",a);case 7:if(s=e.sent,o(),ht().checkResponse(s)){e.next=13;break}return t.cancelErr.textContent=s.msg,Me.show(t.cancelErr),e.abrupt("return");case 13:Me.hide(n.bttn,t.forms),r.cancelling=!0;case 15:case"end":return e.stop()}}),e,this)}))),function(){return p.apply(this,arguments)})},{key:"showCancel",value:function(e,t){var n=this.metaOrders[t].ord,r=this.page,a=n.qty-n.filled,o=Wt(n)?this.market.quote:this.market.base;r.cancelRemain.textContent=Me.formatCoinValue(a,o.unitInfo),r.cancelUnit.textContent=o.symbol.toUpperCase(),Me.hide(r.cancelErr),this.showForm(r.cancelForm),this.cancelData={bttn:Me.tmplElement(e,"cancelBttn"),order:n}}},{key:"showAccelerate",value:function(e){var t=ht().loading(this.main);this.accelerateOrderForm.refresh(e),t(),this.showForm(this.page.accelerateForm)}},{key:"showCreate",value:function(e){var t=this.page;this.currentCreate=e,this.newWalletForm.setAsset(e.id),this.showForm(t.newWalletForm)}},{key:"stepSubmit",value:function(){var e=this.page,t=this.market;if(Me.hide(e.orderErr),this.validateOrder(this.parseOrder())){var n=ht().walletMap[t.base.id],r=ht().walletMap[t.quote.id];return n?r?void this.showVerify():(e.orderErr.textContent=be(L,{asset:t.quote.symbol}),void Me.show(e.orderErr)):(e.orderErr.textContent=be(L,{asset:t.base.symbol}),void Me.show(e.orderErr))}}},{key:"showDeposit",value:(u=s(f().mark((function e(t){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:this.depositAddrForm.setAsset(t),this.showForm(this.page.deposit);case 2:case"end":return e.stop()}}),e,this)}))),function(e){return u.apply(this,arguments)})},{key:"showCustomProviderDialog",value:function(e){ht().loadPage("wallets",{promptProvider:e,goBack:"markets"})}},{key:"handlePriceUpdate",value:function(e){this.market&&(e.host===this.market.dex.host&&e.spots[this.market.cfg.name]&&this.setCurrMarketPrice(),this.marketList.updateSpots(e))}},{key:"handleWalletState",value:(l=s(f().mark((function e(t){var n,r;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.market){e.next=2;break}return e.abrupt("return");case 2:if(t.wallet.assetID===(null===(n=this.market.base)||void 0===n?void 0:n.id)||t.wallet.assetID===(null===(r=this.market.quote)||void 0===r?void 0:r.id)){e.next=4;break}return e.abrupt("return");case 4:this.setTokenApprovalVisibility(),this.resolveOrderFormVisibility();case 6:case"end":return e.stop()}}),e,this)}))),function(e){return l.apply(this,arguments)})},{key:"handleBondUpdate",value:(c=s(f().mark((function e(t){var n;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=t.dex,this.market){e.next=3;break}return e.abrupt("return");case 3:if(n===this.market.dex.host){e.next=5;break}return e.abrupt("return");case 5:if("AccountRegistered"!==t.topic){e.next=8;break}return e.next=8,ht().fetchUser();case 8:this.market.dex=ht().exchanges[n],this.setRegistrationStatusVisibility(),this.updateReputation();case 11:case"end":return e.stop()}}),e,this)}))),function(e){return c.apply(this,arguments)})},{key:"updateReputation",value:function(){var e=this.page,t=this.market,n=t.dex.host,r=t.cfg,o=t.baseCfg.unitInfo,s=t.quoteCfg.unitInfo,i=ht().exchanges[n].auth;e.parcelSizeLots.textContent=String(r.parcelsize),e.marketLimitBase.textContent=Me.formatFourSigFigs(r.parcelsize*r.lotsize/o.conventional.conversionFactor),e.marketLimitBaseUnit.textContent=o.conventional.unit,e.marketLimitQuoteUnit.textContent=s.conventional.unit;var c=this.anyRate()[1];if(c){var l=r.lotsize*c;e.marketLimitQuote.textContent=Me.formatFourSigFigs(r.parcelsize*l/s.conventional.conversionFactor)}else e.marketLimitQuote.textContent="-";var u=Sn(i);e.tradingTier.textContent=String(u);var d=function(e){for(var t=ht().exchanges[e],n=t.auth,r=t.maxScore,a=t.markets,o=n.rep.score,s=Sn(n),i=0,c=0,l=Object.values(a);c0?(p/f*100).toFixed(1):"0",e.orderLimitRemain.textContent=((f-p)*r.parcelsize).toFixed(1),e.orderTradingTier.textContent=String(u),this.reputationMeter.update()}},{key:"anyRate",value:function(){var e=this.market,t=e.cfg.spot,n=e.baseCfg.id,r=e.quoteCfg.id,a=e.rateConversionFactor;if(e.bookLoaded){var o=this.midGap();if(o)return[o*Mt,o,this.midGapConventional()||0]}if(t&&t.rate)return[t.rate,t.rate/Mt,t.rate/a];var s=[ht().fiatRatesMap[n],ht().fiatRatesMap[r]],i=s[0],c=s[1];if(i&&c){var l=i/c,u=l*a;return[u,u/Mt,l]}return[0,0,0]}},{key:"handleMatchNote",value:function(e){var t=this.metaOrders[e.orderID],n=e.match;if(!t)return this.refreshActiveOrders();if(t.ord.type===Ct&&0===n.status){var r=ht().order(e.orderID);r&&(t.details.rate.textContent=t.header.rate.textContent=this.marketOrderRateString(r,this.market))}(n.side===Ot&&n.status===Et||1===n.side&&n.status===Bt)&&this.updateReputation(),ht().canAccelerateOrder(t.ord)?Me.show(t.details.accelerateBttn):Me.hide(t.details.accelerateBttn)}},{key:"handleOrderNote",value:function(e){var t=e.order,n=this.metaOrders[t.id],r="AsyncOrderFailure"===e.topic||"AsyncOrderSubmitted"===e.topic;if(!n||r||"OrderLoaded"===e.topic&&t.readyToTick)return this.refreshActiveOrders();var a=n.ord.status;n.ord=t,"MissedCancel"===e.topic&&Me.show(n.details.cancelBttn),t.filled===t.qty&&Me.hide(n.details.cancelBttn),ht().canAccelerateOrder(t)?Me.show(n.details.accelerateBttn):Me.hide(n.details.accelerateBttn),this.updateMetaOrder(n),(a===Dt&&t.status===It||a===It&&t.status>It)&&(this.setDepthMarkers(),this.updateReputation(),this.mm.readBook())}},{key:"handleEpochNote",value:function(e){if(ht().log("book","handleEpochNote:",e),this.market&&e.host===this.market.dex.host&&e.marketID===this.market.sid){this.book&&(this.book.setEpoch(e.epoch),this.depthChart.draw()),this.clearOrderTableEpochs();for(var t=0,n=Object.values(this.metaOrders);ta.epoch;switch(!0){case a.type===St&&a.status===Dt&&i:var c=a.tif===Tt?be(O):be(M);o.status.textContent=s.status.textContent=c,a.status=a.tif===Tt?At:It;break;case a.type===Ct&&a.status===Dt:o.status.textContent=s.status.textContent=be(O),a.status=At}}}}},{key:"recentMatchesSortCompare",value:function(){var e=this;switch(this.recentMatchesSortKey){case"rate":return function(t,n){return e.recentMatchesSortDirection*(t.rate-n.rate)};case"qty":return function(t,n){return e.recentMatchesSortDirection*(t.qty-n.qty)};case"age":return function(t,n){return e.recentMatchesSortDirection*(t.stamp-n.stamp)}}}},{key:"refreshRecentMatchesTable",value:function(){var e=this.page,t=this.recentMatches;if(Me.empty(e.recentMatchesLiveList),t){var n=this.recentMatchesSortCompare();t.sort(n);var r,a=qa(t);try{for(a.s();!(r=a.n()).done;){var o=r.value,s=e.recentMatchesTemplate.cloneNode(!0),i=Me.parseTemplate(s);ht().bindTooltips(s),i.rate.textContent=Me.formatCoinValue(o.rate/this.market.rateConversionFactor),i.qty.textContent=Me.formatCoinValue(o.qty,this.market.baseUnitInfo),i.age.textContent=Me.timeSince(o.stamp),i.age.dataset.sinceStamp=String(o.stamp),s.classList.add(o.sell?"sellcolor":"buycolor"),e.recentMatchesLiveList.append(s)}}catch(e){a.e(e)}finally{a.f()}}}},{key:"addRecentMatches",value:function(e){this.recentMatches=[].concat(r(e),r(this.recentMatches)).slice(0,100)}},{key:"handleBalanceNote",value:function(e){this.approveTokenForm.handleBalanceNote(e),this.preorderCache={};var t=this.market;if(t&&t.dex&&t.dex.connectionStatus===ct.Connected){this.mm.handleBalanceNote(e);var n=this.balanceWgt;e.assetID!==n.base.id&&e.assetID!==n.quote.id||n.setBalanceVisibility(!0);var r=e.balance.available;switch(e.assetID){case t.baseCfg.id:if(!t.maxSell)break;"number"==typeof t.sellBalance&&t.sellBalance!==r&&(t.maxSell=null),this.isSell()&&this.preSell();break;case t.quoteCfg.id:if(!Object.keys(t.maxBuys).length)break;"number"==typeof t.buyBalance&&t.buyBalance!==r&&(t.maxBuys={}),this.isSell()||this.preBuy()}}}},{key:"submitOrder",value:(o=s(f().mark((function e(){var t,n,r,a;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=this.page,Me.hide(t.orderErr,t.vErr),n=this.currentOrder,r={order:so(n)},this.validateOrder(n)){e.next=6;break}return e.abrupt("return");case 6:return t.vSubmit.classList.add("d-hide"),t.vLoader.classList.remove("d-hide"),e.next=10,C("/api/tradeasync",r);case 10:if(a=e.sent,t.vSubmit.classList.remove("d-hide"),t.vLoader.classList.add("d-hide"),ht().checkResponse(a)){e.next=17;break}return t.vErr.textContent=a.msg,Me.show(t.vErr),e.abrupt("return");case 17:Me.hide(t.forms),this.refreshActiveOrders();case 19:case"end":return e.stop()}}),e,this)}))),function(){return o.apply(this,arguments)})},{key:"createWallet",value:(n=s(f().mark((function e(){var t,n,r;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,ht().fetchUser();case 2:if(t=e.sent){e.next=5;break}return e.abrupt("return");case 5:n=t.assets[this.currentCreate.id],Me.hide(this.page.forms),(r=this.market).baseCfg.id===n.id?r.base=n:r.quoteCfg.id===n.id&&(r.quote=n),this.balanceWgt.updateAsset(n.id),this.displayMessageIfMissingWallet(),this.resolveOrderFormVisibility();case 12:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"lotChanged",value:function(){var e=this.page,t=parseInt(e.lotField.value||"0");if(t<=0)return e.lotField.value=""===e.lotField.value?"":"0",e.qtyField.value="",this.previewQuoteAmt(!1),void this.setOrderBttnEnabled(!1,be(ne));var n=t*this.market.cfg.lotsize;if(e.lotField.value=String(t),e.qtyField.value=String(n/this.market.baseUnitInfo.conventional.conversionFactor),!this.isLimit()&&this.isSell()){var r=ht().assets[this.market.base.id].wallet;this.setOrderBttnEnabled(n<=r.balance.available,be(te))}this.previewQuoteAmt(!0)}},{key:"quantityChanged",value:function(e){var t=this.page,n=this.currentOrder=this.parseOrder();if(n.qty<0)return t.lotField.value="0",t.qtyField.value="",void this.previewQuoteAmt(!1);var r=this.market.cfg.lotsize,a=Math.floor(n.qty/r),o=n.qty=this.currentOrder.qty=a*r;t.lotField.value=String(a),(n.isLimit||n.sell)&&(e&&(t.qtyField.value=String(o/this.market.baseUnitInfo.conventional.conversionFactor)),this.previewQuoteAmt(!0))}},{key:"marketBuyChanged",value:function(){var e=this.page,t=ao(e.mktBuyField.value||"",this.market.quoteUnitInfo.conventional.conversionFactor),n=this.midGap();if(t>0){var r=ht().assets[this.market.quote.id].wallet;this.setOrderBttnEnabled(t<=r.balance.available,be(ee))}else this.setOrderBttnEnabled(!1,be(ne));if(!n||!t)return e.mktBuyLots.textContent="0",void(e.mktBuyScore.textContent="0");var a=t/n,o=a/this.market.cfg.lotsize;e.mktBuyLots.textContent=o.toFixed(1),e.mktBuyScore.textContent=Me.formatCoinValue(a,this.market.baseUnitInfo)}},{key:"rateFieldChanged",value:function(){var e=this.adjustedRate();if(e<=0)return this.depthLines.input=[],this.drawChartLines(),this.page.rateField.value="0",this.previewQuoteAmt(!0),void this.updateOrderBttnState();var t=this.currentOrder=this.parseOrder(),n=e/this.market.rateConversionFactor;this.page.rateField.value=String(n),this.depthLines.input=[{rate:n,color:t.sell?this.depthChart.theme.sellLine:this.depthChart.theme.buyLine}],this.drawChartLines(),this.previewQuoteAmt(!0),this.updateOrderBttnState()}},{key:"adjustedRate",value:function(){var e=this.page.rateField.value;if(!e)return NaN;var t=ao(e,this.market.rateConversionFactor);return t-t%this.market.cfg.ratestep}},{key:"loadTable",value:function(){this.loadTableSide(!0),this.loadTableSide(!1)}},{key:"binOrdersByRateAndEpoch",value:function(e){if(!e||!e.length)return[];var t=[],n=[],r=[],a=e[0].msgRate;e[0].epoch?n.push(e[0]):r.push(e[0]);for(var o=1;o0}))}},{key:"loadTableSide",value:function(e){var t=this,n=e?this.book.sells:this.book.buys,r=e?this.page.sellRows:this.page.buyRows;Me.empty(r),n&&n.length&&this.binOrdersByRateAndEpoch(n).forEach((function(e){r.appendChild(t.orderTableRow(e))}))}},{key:"addTableOrder",value:function(e){var t=e.sell?this.page.sellRows:this.page.buyRows,n=t.firstChild;if(0!==e.rate){for(n&&0===n.manager.getRate()&&(n=n.nextSibling);n;){if(0===n.manager.compare(e))return void n.manager.insertOrder(e);if(n.manager.compare(e)>0){var r=this.orderTableRow([e]);return void t.insertBefore(r,n)}n=n.nextSibling}var a=this.orderTableRow([e]);t.appendChild(a)}else{if(0===e.qtyAtomic)return;n&&0===n.manager.getRate()?n.manager.insertOrder(e):(n=this.orderTableRow([e]),t.insertBefore(n,t.firstChild))}}},{key:"removeTableOrder",value:function(e){for(var t=e.token,n=0,r=[this.page.sellRows,this.page.buyRows];n36e5&&!i.disabled?(Me.show(n.expired),i.running&&ht().fetchBalance(o)):Me.hide(n.expired)}else Me.show(n.connect)}else Me.show(n.unsupported)}}},{key:"checkNeedsProvider",value:(t=s(f().mark((function e(t,n){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.t0=Me,e.next=3,ht().needsCustomProvider(t);case 3:e.t1=e.sent,e.t2=n,e.t0.setVis.call(e.t0,e.t1,e.t2);case 6:case"end":return e.stop()}}),e)}))),function(e,n){return t.apply(this,arguments)})},{key:"updateParent",value:function(e){var t,n=ht().assets[e.parentID],r=n.wallet.balance,a=n.unitInfo;null!==(t=e.parentBal)&&void 0!==t&&t.firstChild&&(e.parentBal.firstChild.textContent=Me.formatCoinValue(r.available,a))}},{key:"updateAsset",value:function(e){e===this.base.id?this.updateWallet(this.base):e===this.quote.id&&this.updateWallet(this.quote),e===this.base.parentID&&this.updateParent(this.base),e===this.quote.parentID&&this.updateParent(this.quote)}}]),e}();function no(e,t,n){return{host:e,base:t,quote:n}}function ro(e,t){return"".concat(e,"_").concat(t)}function ao(e,t){return e?Math.round(parseFloat(e)*t):0}function oo(e,t){e.classList.remove("selected"),t.classList.add("selected")}function so(e){for(var t={},n=0,r=Object.entries(e.options);n1?(e.numOrders.removeAttribute("hidden"),e.numOrders.innerText=String(r),e.numOrders.title="quantity is comprised of ".concat(r," orders")):e.numOrders.setAttribute("hidden","true")}},{key:"insertOrder",value:function(e){this.orderBin.push(e),this.updateQtyNumOrdersEl()}},{key:"updateOrderQty",value:function(e){for(var t=e.token,n=e.qty,r=e.qtyAtomic,a=0;ae.msgRate===e.sell?1:-1:this.isEpoch()?1:-1}}]),e}();function co(e,t,n){if(n.spot){e.price.textContent=Me.formatFourSigFigs(ht().conventionalRate(n.baseid,n.quoteid,n.spot.rate,t));var r=n.spot.change24>0?"+":"";e.change.classList.remove("buycolor","sellcolor"),e.change.classList.add(n.spot.change24>=0?"buycolor":"sellcolor"),e.change.textContent="".concat(r).concat((100*n.spot.change24).toFixed(1),"%")}}var lo=[.5,1/4,3/4,1/8,5/8,3/8,7/8];function uo(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return ho(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ho(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,i=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){i=!0,o=e},f:function(){try{s||null==n.return||n.return()}finally{if(i)throw o}}}}function ho(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=0&&(e.checked=!0)}))}};o(n.hostFilter,"hosts"),o(n.assetFilter,"assets"),o(n.statusFilter,"statuses");var s=[],c=function(e,n){var a=e.querySelector(".apply-bttn");s.push(a),Me.bind(a,"click",(function(){t.submitFilter(),s.forEach((function(e){return Me.hide(e)}))})),e.querySelectorAll("input").forEach((function(t){Me.bind(t,"change",(function(){!function(e,t){if(e.length!==t.length)return!1;var n,r=uo(e);try{for(r.s();!(n=r.n()).done;){var a=n.value;if(-1===t.indexOf(a))return!1}}catch(e){r.e(e)}finally{r.f()}return!0}(fo(e),r[n])?Me.show(a):Me.hide(a)}))}))};return c(n.hostFilter,"hosts"),c(n.assetFilter,"assets"),c(n.statusFilter,"statuses"),Me.bind(t.main,"scroll",(function(){t.loading||n.ordersTable.offsetHeight-t.main.offsetHeight-t.main.scrollTop<0&&t.nextPage()})),n.forms.querySelectorAll(".form-closer").forEach((function(e){Me.bind(e,"click",(function(){Me.hide(n.forms)}))})),Me.bind(n.forms,"mousedown",(function(e){Me.mouseInElement(e,t.currentForm)||Me.hide(n.forms)})),Me.bind(n.exportOrders,"click",(function(){t.exportOrders()})),n.showArchivedDateField.addEventListener("change",(function(){n.showArchivedDateField.checked?Me.show(n.archivedDateField):Me.hide(n.archivedDateField,n.deleteArchivedRecordsErr)})),Me.bind(n.deleteArchivedRecords,"click",(function(){var e=t.page;e.showArchivedDateField.checked=!1,e.saveMatchesToFile.checked=!1,e.saveOrdersToFile.checked=!1,e.deleteArchivedRecordsErr.textContent="",e.archivedRecordsLocation.textContent="",e.deleteArchivedRecordsMsg.textContent="",Me.hide(e.deleteArchivedResult,e.deleteArchivedRecordsErr,e.deleteArchivedRecordsMsg,e.archivedRecordsLocation,e.archivedDateField),t.showForm(e.deleteArchivedRecordsForm)})),Me.bind(n.deleteArchivedRecordsSubmit,"click",(function(){var e=0;n.showArchivedDateField.checked&&(e=Date.parse(n.olderThan.value||""),isNaN(e)||e<=0)?Me.showFormError(n.deleteArchivedRecordsErr,be("INVALID_DATE_ERR_MSG")):t.deleteArchivedRecords(e)})),t.submitFilter(),t}return d(p,[{key:"showForm",value:(o=s(f().mark((function e(t){var n,r;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.currentForm=t,n=this.page,Me.hide(n.deleteArchivedRecordsForm),t.style.right="10000px",Me.show(n.forms,t),r=(n.forms.offsetWidth+t.offsetWidth)/2,e.next=8,Me.animate(500,(function(e){t.style.right="".concat((1-e)*r,"px")}),"easeOutHard");case 8:t.style.right="0px";case 9:case"end":return e.stop()}}),e,this)}))),function(e){return o.apply(this,arguments)})},{key:"setOrders",value:function(e){Me.empty(this.page.tableBody),this.appendOrders(e)}},{key:"appendOrders",value:function(e){var t,n=this.page.tableBody,r=uo(e);try{for(r.s();!(t=r.n()).done;){var a=t.value,o=this.orderTmpl.cloneNode(!0),s=Me.parseTemplate(o),i=void 0,c=void 0,l=void 0,u=void 0,d=void 0,h="",p=ht().exchanges[a.host]||void 0;if((ht().assets[a.baseID]||p.assets[a.baseID])&&(ht().assets[a.quoteID]||p.assets[a.quoteID])){var f=[ht().unitInfo(a.baseID,p),ht().unitInfo(a.quoteID,p)],v=f[0],m=f[1];if(a.sell){var g=[a.baseSymbol,a.quoteSymbol];i=g[0],c=g[1];var y=[v.conventional.unit,m.conventional.unit];l=y[0],u=y[1],d=Me.formatCoinValue(a.qty,v),a.type===St&&(h=Me.formatCoinValue(a.qty/Mt*a.rate,m))}else{var b=[a.quoteSymbol,a.baseSymbol];i=b[0],c=b[1];var x=[m.conventional.unit,v.conventional.unit];l=x[0],u=x[1],a.type===Ct?d=Me.formatCoinValue(a.qty,v):(d=Me.formatCoinValue(a.qty/Mt*a.rate,m),h=Me.formatCoinValue(a.qty,v))}var k="".concat(v.conventional.unit,"-").concat(m.conventional.unit);s.host.textContent="".concat(k," @ ").concat(a.host),s.fromQty.textContent=d,s.fromLogo.src=Me.logoPath(i),s.fromSymbol.textContent=l,s.toQty.textContent=h,s.toLogo.src=Me.logoPath(c),s.toSymbol.textContent=u,s.type.textContent="".concat(Nt(a)," ").concat(qt(a));var w=Me.formatCoinValue(ht().conventionalRate(a.baseID,a.quoteID,a.rate,p));a.type===Ct&&(w=Ht(a)),s.rate.textContent=w,s.status.textContent=Ut(a),s.filled.textContent="".concat((_t(a)/a.qty*100).toFixed(1),"%"),s.settled.textContent="".concat((jt(a)/a.qty*100).toFixed(1),"%");var S=new Date(a.submitTime).toLocaleString();s.timeAgo.textContent="".concat(Me.timeSince(a.submitTime)," ago"),s.time.textContent=S,Me.tmplElement(o,"link").href="order/".concat(a.id),ht().bindInternalNavigation(o),n.appendChild(o)}}}catch(e){r.e(e)}finally{r.f()}50===e.length?this.offset=e[e.length-1].id:this.offset=""}},{key:"submitFilter",value:(a=s(f().mark((function e(){var t,n;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.page,this.offset="",(n=this.filterState).hosts=fo(t.hostFilter),n.assets=fo(t.assetFilter).map((function(e){return parseInt(e)})),n.statuses=fo(t.statusFilter).map((function(e){return parseInt(e)})),e.t0=this,e.next=9,this.fetchOrders();case 9:e.t1=e.sent,e.t0.setOrders.call(e.t0,e.t1);case 11:case"end":return e.stop()}}),e,this)}))),function(){return a.apply(this,arguments)})},{key:"fetchOrders",value:(r=s(f().mark((function e(){var t,n;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=ht().loading(this.main),e.next=3,C("/api/orders",this.currentFilter());case 3:return n=e.sent,t(),e.abrupt("return",n.orders);case 6:case"end":return e.stop()}}),e,this)}))),function(){return r.apply(this,arguments)})},{key:"exportOrders",value:function(){this.offset="";var e=this.currentFilter(),t=new URL(window.location.href),n=new URLSearchParams(""),r=function(t){e[t].forEach((function(e){n.append(t,e)}))};r("hosts"),r("assets"),r("statuses"),t.search=n.toString(),t.pathname="/orders/export",window.open(t.toString())}},{key:"deleteArchivedRecords",value:(n=s(f().mark((function e(t){var n,r,a,o,s,i;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=this.page,r=n.saveMatchesToFile.checked||!1,a=n.saveOrdersToFile.checked||!1,o={olderThanMs:t,saveMatchesToFile:r,saveOrdersToFile:a},s=ht().loading(this.main),e.next=7,C("/api/deletearchivedrecords",o);case 7:if(i=e.sent,s(),ht().checkResponse(i)){e.next=11;break}return e.abrupt("return",Me.showFormError(n.deleteArchivedRecordsErr,i.msg));case 11:i.archivedRecordsDeleted>0?(n.deleteArchivedRecordsMsg.textContent=be("DELETE_ARCHIVED_RECORDS_RESULT",{nRecords:i.archivedRecordsDeleted}),(r||a)&&(n.archivedRecordsLocation.textContent=be("ARCHIVED_RECORDS_PATH",{path:i.archivedRecordsPath}),Me.show(n.archivedRecordsLocation)),this.submitFilter()):n.deleteArchivedRecordsMsg.textContent=be("NO_ARCHIVED_RECORDS"),Me.show(n.deleteArchivedResult,n.deleteArchivedRecordsMsg);case 13:case"end":return e.stop()}}),e,this)}))),function(e){return n.apply(this,arguments)})},{key:"currentFilter",value:function(){var e,t,n=this.filterState;return{hosts:n.hosts,assets:null===(e=n.assets)||void 0===e?void 0:e.map((function(e){return parseInt(e)})),statuses:null===(t=n.statuses)||void 0===t?void 0:t.map((function(e){return parseInt(e)})),n:50,offset:this.offset}}},{key:"nextPage",value:(t=s(f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(""!==this.offset&&!this.loading){e.next=2;break}return e.abrupt("return");case 2:return this.loading=!0,Me.show(this.page.orderLoader),e.next=6,this.fetchOrders();case 6:t=e.sent,this.loading=!1,Me.hide(this.page.orderLoader),this.appendOrders(t);case 10:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})}]),p}(it);function fo(e){var t=[];return e.querySelectorAll("input").forEach((function(e){e.checked&&t.push(e.value)})),t}function vo(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return mo(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?mo(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,i=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){i=!0,o=e},f:function(){try{s||null==n.return||n.return()}finally{if(i)throw o}}}}function mo(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);no.getTime())n.refundPending.textContent=be("REFUND_IMMINENT");else{var s=o.toLocaleTimeString(Me.languages(),{year:"numeric",month:"short",day:"numeric"});n.refundPending.textContent=be("REFUND_WILL_HAPPEN_AFTER",{refundAfterTime:s})}Me.hide(n.refundCoin),Me.show(n.refundPending)}if(1!==t.status||t.revoked||t.refund)if(t.status!==Rt||t.revoked||t.refund)!function(e){return e.status<5&&e.side===Pt&&e.status>=Et}(t)||t.revoked||t.refund?!function(e){return e.status<5&&e.side===Lt&&e.status>=Bt}(t)||t.revoked||t.refund?Me.hide(n.makerSwapMsg,n.takerSwapMsg,n.makerRedeemMsg,n.takerRedeemMsg):(n.takerRedeemMsg.textContent=bo(t.redeem),Me.hide(n.makerSwapMsg,n.takerSwapMsg,n.makerRedeemMsg),Me.show(n.takerRedeemMsg)):(n.makerRedeemMsg.textContent=bo(t.redeem),Me.hide(n.makerSwapMsg,n.takerSwapMsg,n.takerRedeemMsg),Me.show(n.makerRedeemMsg));else{var i=ko(t);n.takerSwapMsg.textContent=bo(i),Me.hide(n.makerSwapMsg,n.makerRedeemMsg,n.takerRedeemMsg),Me.show(n.takerSwapMsg)}else{var c=xo(t);n.makerSwapMsg.textContent=bo(c),Me.hide(n.takerSwapMsg,n.makerRedeemMsg,n.takerRedeemMsg),Me.show(n.makerSwapMsg)}if(t.revoked){Me.setVis(xo(t),n.makerSwap),Me.setVis(ko(t),n.takerSwap);var l=new Date(t.stamp+go),u=Date.now()>l.getTime();Me.setVis(wo(t)||ko(t)&&t.active&&!t.refund&&!u,n.makerRedeem),Me.setVis(So(t)||wo(t)&&t.active&&!t.refund,n.takerRedeem);var d=Boolean(ko(t));t.side===Pt&&(d=Boolean(xo(t)),ko(t)&&(d=d&&u)),Me.setVis(t.refund||t.active&&!t.redeem&&!t.counterRedeem&&d,n.refund)}else Me.setVis(xo(t)||t.active,n.makerSwap),Me.setVis(ko(t)||t.active,n.takerSwap),Me.setVis(wo(t)||t.active,n.makerRedeem),Me.setVis(So(t)||t.active,n.takerRedeem),Me.setVis(t.refund,n.refund)}}},{key:"addNewMatchCard",value:function(e){var t=this.page,n=t.matchCardTmpl.cloneNode(!0);ht().bindUrlHandlers(n),n.dataset.matchID=e.matchID,this.setImmutableMatchCardElements(n,e),this.setMutableMatchCardElements(n,e),t.matchBox.appendChild(n)}},{key:"showMatchCards",value:function(){var e=this,t=this.order;t&&t.matches&&(t.matches.sort((function(e,t){return e.stamp-t.stamp})),t.matches.forEach((function(t){return e.addNewMatchCard(t)})))}},{key:"showCancel",value:function(){var e=this.order,t=this.page,n=e.qty-e.filled,r=Wt(e)?ht().assets[e.quoteID]:ht().assets[e.baseID];t.cancelRemain.textContent=Me.formatCoinValue(n,r.unitInfo),t.cancelUnit.textContent=r.unitInfo.conventional.unit.toUpperCase(),this.showForm(t.cancelForm)}},{key:"showForm",value:(r=s(f().mark((function e(t){var n,r;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.currentForm=t,n=this.page,Me.hide(n.cancelForm,n.accelerateForm),t.style.right="10000px",Me.show(n.forms,t),r=(n.forms.offsetWidth+t.offsetWidth)/2,e.next=8,Me.animate(500,(function(e){t.style.right="".concat((1-e)*r,"px")}),"easeOutHard");case 8:t.style.right="0px";case 9:case"end":return e.stop()}}),e,this)}))),function(e){return r.apply(this,arguments)})},{key:"submitCancel",value:(n=s(f().mark((function e(){var t,n,r,a,o;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.page,n=this.order,r={orderID:n.id},a=ht().loading(t.cancelForm),e.next=6,C("/api/cancel",r);case 6:if(o=e.sent,a(),ht().checkResponse(o)){e.next=10;break}return e.abrupt("return");case 10:t.status.textContent=be(q),Me.hide(t.forms),n.cancelling=!0;case 13:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"setAccelerationButtonVis",value:function(){var e=this.order;if(e){var t=this.page;Me.setVis(ht().canAccelerateOrder(e),t.accelerateBttn,t.actionsLabel)}}},{key:"showAccelerateForm",value:(t=s(f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=ht().loading(this.page.accelerateBttn),this.accelerateOrderForm.refresh(this.order),t(),this.showForm(this.page.accelerateForm);case 4:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})},{key:"handleOrderNote",value:function(e){var t=this.page,n=e.order;if(n.id===this.orderID){this.order=n;var r=t.cancelBttn;r&&n.status>It&&Me.hide(r),t.status.textContent=Ut(n);var a,o=vo(n.matches||[]);try{for(o.s();!(a=o.n()).done;){var s=a.value;this.processMatch(s)}}catch(e){o.e(e)}finally{o.f()}this.setAccelerationButtonVis()}}},{key:"handleMatchNote",value:function(e){e.orderID===this.orderID&&(this.processMatch(e.match),this.setAccelerationButtonVis())}},{key:"processMatch",value:function(e){var t,n=null,r=vo(Me.applySelector(this.page.matchBox,".match-card"));try{for(r.s();!(t=r.n()).done;){var a=t.value;if(a.dataset.matchID===e.matchID){n=a;break}}}catch(e){r.e(e)}finally{r.f()}n?this.setMutableMatchCardElements(n,e):this.addNewMatchCard(e)}}]),p}(it);function bo(e){return e.confs&&0!==e.confs.required?"".concat(e.confs.count," / ").concat(e.confs.required," ").concat(be("CONFIRMATIONS")):""}function xo(e){return e.side===Pt?e.swap:e.counterSwap}function ko(e){return e.side===Pt?e.counterSwap:e.swap}function wo(e){return e.side===Pt?e.redeem:e.counterRedeem}function So(e){return e.side===Pt?e.counterRedeem:e.redeem}function Co(){return Co="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,n){var r=function(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=b(e)););return e}(e,t);if(r){var a=Object.getOwnPropertyDescriptor(r,t);return a.get?a.get.call(arguments.length<3?e:n):a.value}},Co.apply(this,arguments)}function Fo(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return To(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?To(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e){throw e})),f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,i=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e){i=!0,o=e})),f:function(){try{s||null==n.return||n.return()}finally{if(i)throw o}}}}function To(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);ni){var d=a-r;if(s-i0){var p=s-i,f=r-a;t={left:{cex:0,dex:0},right:{cex:0,dex:0},cexRange:0,dexRange:0},f>c&&p>c?(t.left.cex=c+a,t.left.dex=i,t.right.cex=a,t.right.dex=c+i):pc?(t.left.cex=a,t.left.dex=c+i,t.right.cex=f+a,t.right.dex=c-f+i):(t.left.cex=c-p+a,t.left.dex=p+i,t.right.cex=c+a,t.right.dex=i),t.cexRange=t.right.cex-t.left.cex,t.dexRange=t.right.dex-t.left.dex,l=t.left.dex+t.dexRange/2,u=t.left.cex+t.cexRange/2}}else r=768,new ResizeObserver((function(){t.resized()})).observe(e);for(var r=function(){var e=a(s[o],2),r=e[0],i=e[1],c=n.exchangeRowTmpl.cloneNode(!0);n.cexRows.appendChild(c);var l=Me.parseTemplate(c),u=function(){t.cexConfigForm.setCEX(r),t.forms.show(n.cexConfigForm)};Me.bind(l.configureBttn,"click",u),Me.bind(l.reconfigBttn,"click",u),Me.bind(l.errConfigureBttn,"click",u);var d=t.cexes[r]={tr:c,tmpl:l,dinfo:i,cexName:r};t.updateCexRow(d)},o=0,s=Object.entries(rr);o=768;if(e!==this.twoColumn){this.twoColumn=e,this.clearBotBoxes();var t,n=Fo(this.sortedBots);try{for(n.s();!(t=n.n()).done;){var r=t.value.div;this.appendBotBox(r)}}catch(e){n.e(e)}finally{n.f()}}}},{key:"setup",value:(l=s(f().mark((function e(){var t,n,a,o,s,i,c,l,u,d=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=this.page,n=ht().mmStatus,a=n.bots.map((function(e){return e.config})),ht().registerNoteFeeder({runstats:function(e){d.handleRunStatsNote(e)},runevent:function(e){var t=d.bots[ur(e.host,e.baseID,e.quoteID)];if(t)return t.handleRunStats()},cexnote:function(e){d.handleCEXNote(e)}}),o=!a||0===a.length,Me.setVis(o,t.noBots),!o){e.next=8;break}return e.abrupt("return");case 8:t.noBots.remove(),s=r(n.bots).sort((function(e,t){var n,r,a,o;return e.running&&!t.running?-1:t.running&&!e.running?1:e.running||t.running?(null!==(n=null===(r=t.runStats)||void 0===r?void 0:r.startTime)&&void 0!==n?n:0)-(null!==(a=null===(o=e.runStats)||void 0===o?void 0:o.startTime)&&void 0!==a?a:0):e.config.baseID+e.config.quoteID-(t.config.baseID+t.config.quoteID)})),i={},c=Fo(s);try{for(c.s();!(l=c.n()).done;)u=l.value,this.addBot(u,i)}catch(e){c.e(e)}finally{c.f()}case 13:case"end":return e.stop()}}),e,this)}))),function(){return l.apply(this,arguments)})},{key:"handleCEXNote",value:(c=s(f().mark((function e(t){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:e.t0=t.topic,e.next="BalanceUpdate"===e.t0?3:4;break;case 3:return e.abrupt("return",this.handleCEXBalanceUpdate(t.cexName));case 4:case"end":return e.stop()}}),e,this)}))),function(e){return c.apply(this,arguments)})},{key:"handleCEXBalanceUpdate",value:(o=s(f().mark((function e(t){var n;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:(n=this.cexes[t])&&this.updateCexRow(n);case 2:case"end":return e.stop()}}),e,this)}))),function(e){return o.apply(this,arguments)})},{key:"handleRunStatsNote",value:(n=s(f().mark((function e(t){var n,r,a,o;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=t.baseID,r=t.quoteID,a=t.host,!(o=this.bots[ur(a,n,r)])){e.next=4;break}return e.abrupt("return",o.handleRunStats());case 4:this.addBot(ht().botStatus(a,n,r));case 5:case"end":return e.stop()}}),e,this)}))),function(e){return n.apply(this,arguments)})},{key:"unload",value:function(){Me.unbind(document,"keyup",this.keyup)}},{key:"addBot",value:function(e,t){var n,r=this.page,a=this.bots,o=this.sortedBots,s=e.config,i=s.baseID,c=s.quoteID,l=s.host,u=[ht().assets[i].symbol,ht().assets[c].symbol],d=u[1],h="".concat(u[0],"_").concat(d);if(null!==(n=ht().exchanges[l])&&void 0!==n&&n.markets[h]){var p=new Ro(this,e,t);r.botRows.appendChild(p.row.tr),o.push(p),a[p.id]=p,this.appendBotBox(p.div)}}},{key:"appendBotBox",value:function(e){var t=this.page,n=t.boxZero,r=t.boxOne;(this.twoColumn&&(n.children.length+r.children.length)%2!=0?r:n).append(e)}},{key:"clearBotBoxes",value:function(){for(var e=this.page,t=e.boxOne,n=e.boxZero;n.children.length>1;)n.removeChild(n.lastChild);for(;t.children.length>0;)t.removeChild(t.lastChild)}},{key:"showBot",value:function(e){var t=this.sortedBots,n=t.findIndex((function(t){return t.id===e}));t.splice(n,1),t.unshift(this.bots[e]),this.clearBotBoxes();var r,a=Fo(t);try{for(a.s();!(r=a.n()).done;){var o=r.value.div;this.appendBotBox(o)}}catch(e){a.e(e)}finally{a.f()}var s=this.bots[e].div;Me.animate(250,(function(e){s.style.opacity="".concat(e),s.style.transform="scale(".concat(.8+.2*e,")")}))}},{key:"newBot",value:function(){ht().loadPage("mmsettings")}},{key:"cexConfigured",value:(t=s(f().mark((function e(t){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,ht().fetchMMStatus();case 2:this.updateCexRow(this.cexes[t]),this.forms.close();case 4:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})},{key:"updateCexRow",value:function(e){var t=e.tmpl,n=e.dinfo,r=e.cexName;t.logo.src=n.logo,t.name.textContent=n.name;var o=ht().mmStatus.cexes[r];if(Me.setVis(!o,t.unconfigured),Me.setVis(o&&!o.connectErr,t.configured),Me.setVis(null==o?void 0:o.connectErr,t.connectErrBox),null!=o&&o.connectErr&&(t.connectErr.textContent="connection error",t.connectErr.dataset.tooltip=o.connectErr),t.logo.classList.toggle("greyscale",!o),o){for(var s=0,i={},c=0,l=Object.entries(o.balances);c0&&(k=g.reduce((function(e,t){return t.gapFactor0&&(w=y.reduce((function(e,t){return t.gapFactor0,l.hasTransferable),Me.setVis(c.fundedAndNotBalanced,l.fundedAndNotBalancedBox),Me.setVis(c.starved,l.starvedBox),l.startBttn.classList.toggle("go",c.fundedAndBalanced),l.startBttn.classList.toggle("warning",!c.fundedAndBalanced),l.proposedDexBaseAlloc.classList.toggle("text-warning",!(c.base.fundedAndBalanced||c.base.fundedAndNotBalanced)),l.proposedDexQuoteAlloc.classList.toggle("text-warning",!(c.quote.fundedAndBalanced||c.quote.fundedAndNotBalanced));var q=function(e,t){l.proposedDexBaseAlloc.textContent=Me.formatFourSigFigs(e),l.proposedDexBaseAllocUSD.textContent=Me.formatFourSigFigs(e*d),l.proposedCexBaseAlloc.textContent=Me.formatFourSigFigs(t),l.proposedCexBaseAllocUSD.textContent=Me.formatFourSigFigs(t*d)};if(q(I,A),Me.setVis(R,l.baseAllocSlider),R){var N=R.right.dex-R.left.dex,W=R.right.cex-R.left.cex;this.baseAllocSlider.setValue(.5),this.baseAllocSlider.changed=function(e){var t=R.left.dex+e*N,n=R.left.cex+e*W;O.dex[f]=t*k,O.cex[f]=n*k,q(t,n)}}var V=function(e,t){l.proposedDexQuoteAlloc.textContent=Me.formatFourSigFigs(e),l.proposedDexQuoteAllocUSD.textContent=Me.formatFourSigFigs(e*p),l.proposedCexQuoteAlloc.textContent=Me.formatFourSigFigs(t),l.proposedCexQuoteAllocUSD.textContent=Me.formatFourSigFigs(t*p)};if(V(B,P),Me.setVis(L,l.quoteAllocSlider),L){var U=L.right.dex-L.left.dex,_=L.right.cex-L.left.cex;this.quoteAllocSlider.setValue(.5),this.quoteAllocSlider.changed=function(e){var t=L.left.dex+e*U,n=L.left.cex+e*_;O.dex[v]=t*w,O.cex[v]=n*w,V(t,n)}}if(Me.setVis.apply(Me,[m!==f].concat(r(Me.applySelector(l.allocationDialog,"[data-base-token-fees]")))),m!==f){var j=c.base.fees.req+(m===g?c.quote.fees.req:0),H=Math.min(j,c.base.fees.avail);l.proposedDexBaseFeeAlloc.textContent=Me.formatFourSigFigs(H),l.proposedDexBaseFeeAllocUSD.textContent=Me.formatFourSigFigs(H*y),l.proposedDexBaseFeeAlloc.classList.toggle("text-warning",!c.base.fees.funded)}var z=g!==v&&g!==m;if(Me.setVis.apply(Me,[z].concat(r(Me.applySelector(l.allocationDialog,"[data-quote-token-fees]")))),z){var G=Math.min(c.quote.fees.req,c.quote.fees.avail);l.proposedDexQuoteFeeAlloc.textContent=Me.formatFourSigFigs(G),l.proposedDexQuoteFeeAllocUSD.textContent=Me.formatFourSigFigs(G*b),l.proposedDexQuoteFeeAlloc.classList.toggle("text-warning",!c.quote.fees.funded)}var X=null===(s=ht().exchanges[F])||void 0===s?void 0:s.markets[T],K=!1;if(X&&X.orders)for(var Q=0;Q=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,i=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){i=!0,o=e},f:function(){try{s||null==n.return||n.return()}finally{if(i)throw o}}}}function Lo(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n0,quoteIsAccountLocker:(16384&o.traits)>0},this.adjustedBalances(a,o))}},{key:"showAdvancedConfig",value:function(){var e=this.page;Me.show(e.advancedConfig),Me.hide(e.quickConfig),this.placementsChart.render()}},{key:"isQuickPlacements",value:function(e,t){if(0===e.length||e.length!==t.length)return!1;for(var n=0;n0&&o.length>0){var s=a.reduce((function(e,t){return t.gapFactore.gapFactor?t:e})),d=o.reduce((function(e,t){return t.gapFactor>e.gapFactor?t:e})),h=(u.gapFactor-s.gapFactor+(d.gapFactor-i.gapFactor))/2/(l-1);this.qcProfit.setValue(100*t.profit),this.qcProfitSlider.setValue((t.profit-Wo)/Vo),this.qcLevelSpacing.setValue(100*h),this.qcLevelSpacingSlider.setValue((h-Uo)/_o)}else if(n===tr){var p=(a.reduce((function(e,t){return e+t.gapFactor}),0)+o.reduce((function(e,t){return e+t.gapFactor}),0))/c-1||0;this.qcMatchBuffer.setValue(100*p),this.qcMatchBufferSlider.setValue((p-0)/1)}var f=a.reduce((function(e,t){return e+t.lots}),0)+o.reduce((function(e,t){return e+t.lots}),0),v=Math.max(1,Math.round(f/2/l));this.qcLotsPerLevel.setValue(v),this.qcUSDPerSide.setValue(v*l*r),this.qcLevelsPerSide.setValue(l)}else n===nr&&this.qcLotsPerLevel.setValue(t.simpleArbLots);this.showQuickConfig(),this.quickConfigUpdated()}},{key:"showQuickConfig",value:function(){var e=this.marketStuff(),t=e.page,n=e.lotSizeUSD,r=e.botType,a=e.lotsPerLevelIncrement;this.qcLevelsPerSide.input.value||(this.qcLevelsPerSide.setValue(1),this.qcUSDPerSide.setValue(1*(this.qcLotsPerLevel.value()||a)*n)),this.qcLotsPerLevel.input.value||(this.qcLotsPerLevel.setValue(a),this.qcUSDPerSide.setValue(n*a*this.qcLevelsPerSide.value())),t.qcLevelSpacing.value||(this.qcLevelSpacing.setValue(.5),this.qcLevelSpacingSlider.setValue(.20100502512562812)),t.qcMatchBuffer.value||(t.qcMatchBuffer.value=String(0)),Me.hide(t.advancedConfig),Me.show(t.quickConfig),this.showInputsForBot(r)}},{key:"showInputsForBot",value:function(e){var t=this.page,n=this.opts.usingUSDPerSide;switch(Me.hide(t.matchMultiplierBox,t.placementsChartBox,t.placementChartLegend,t.lotsPerLevelLabel,t.levelSpacingBox,t.arbLotsLabel,t.qcLevelPerSideBox),Me.setVis(n,t.qcUSDPerSideBox),Me.setVis(!n,t.qcLotsBox),e){case tr:Me.show(t.qcLevelPerSideBox,t.matchMultiplierBox,t.placementsChartBox,t.placementChartLegend,t.lotsPerLevelLabel);break;case er:Me.show(t.qcLevelPerSideBox,t.levelSpacingBox,t.placementsChartBox,t.lotsPerLevelLabel);break;case nr:Me.show(t.arbLotsLabel)}}},{key:"quickConfigUpdated",value:function(){var e,t,n,r=this.marketStuff(),a=r.page,o=r.cfg,s=r.botType,i=r.cexName;Me.hide(a.qcError);var c=function(e){a.qcError.textContent=e,Me.show(a.qcError)},l=s===nr?1:this.qcLevelsPerSide.value();isNaN(l)&&c("invalid value for levels per side");var u=this.qcLotsPerLevel.value();isNaN(u)&&c("invalid value for lots per level");var d=parseFloat(null!==(e=a.qcProfit.value)&&void 0!==e?e:"")/100;isNaN(d)&&c("invalid value for profit");var h=s===er?parseFloat(null!==(t=a.qcLevelSpacing.value)&&void 0!==t?t:"")/100:0;isNaN(h)&&c("invalid value for level spacing");var p=s===tr?parseFloat(null!==(n=a.qcMatchBuffer.value)&&void 0!==n?n:"")/100:0;isNaN(p)&&c("invalid value for match buffer");var f=p+1,v=1===l;if(a.levelSpacingBox.classList.toggle("disabled",v),a.qcLevelSpacing.disabled=v,o.simpleArbLots=u,s!==nr){this.clearPlacements(i?No:o.gapStrategy);for(var m=0;m0,F=Po(this.botTypeSelectors);try{for(F.s();!(T=F.n()).done;)(D=T.value).classList.toggle("disabled",D.dataset.botType!==er&&!C)}catch(e){F.e(e)}finally{F.f()}0===Object.keys(ht().mmStatus.cexes).length?(Me.show(s.noCexesConfigured),this.setBotTypeSelected(er)):(A=k.fetchLocal(Mo)||{},R=A["".concat(n,"_").concat(r,"_").concat(t)],(a=null!==(I=a)&&void 0!==I?I:R?R.botType:tr)!==er&&(o&&(E=y[o]),!E&&R&&(E=y[null!==(B=R.cexName)&&void 0!==B?B:""]),E||(P=k.fetchLocal(qo))&&(E=y[P]),!E&&S>0&&(E=Object.values(y)[0])),E?(s.cexSelection.classList.remove("disabled"),this.setBotTypeSelected(null!==(L=a)&&void 0!==L?L:R?R.botType:tr),this.selectFormCEX(E.name)):(s.cexSelection.classList.add("disabled"),Me.show(s.noCexMarket),this.setBotTypeSelected(er),0===(O=Object.keys(rr).filter((function(e){return!ht().mmStatus.cexes[e]}))).length||1===O.length&&("Binance"===O[0]||"BinanceUS"===O[0])||Me.show(s.noCexMarketConfigureMore))),Me.show(s.cexSelection),this.forms.show(s.botTypeForm);case 41:case"end":return e.stop()}}),e,this)}))),function(e,t,n,r,a){return x.apply(this,arguments)})},{key:"reshowBotTypeForm",value:function(){Go(this.specs,ht().mmStatus)&&this.showMarketSelectForm();var e=this.specs,t=e.baseID,n=e.quoteID,r=e.host,a=e.cexName,o=e.botType;this.showBotTypeForm(r,t,n,o,a)}},{key:"setBotTypeSelected",value:function(e){var t,n=this.formSpecs,r=n.baseID,a=n.quoteID,o=n.host,s=this.botTypeSelectors,i=this.formCexes,c=Po(s);try{for(c.s();!(t=c.n()).done;){var l=t.value,u=l.classList,d=l.dataset.botType;u.toggle("selected",d===e)}}catch(e){c.e(e)}finally{c.f()}if(e!==er){var h=ht().mmStatus;if(0!==Object.keys(h.cexes).length){var p=this.cexMarketSupportFilter(r,a),f=Object.values(i).filter((function(e){return e.div.classList.contains("selected")}));if(!f.length||!p(f[0].name)){var v=(k.fetchLocal(Mo)||{})["".concat(r,"_").concat(a,"_").concat(o)];if(v){var m,g=h.cexes[null!==(m=v.cexName)&&void 0!==m?m:""];if(g&&p(g.config.name))return void this.selectFormCEX(g.config.name)}var y=k.fetchLocal(qo);if(y){var b=h.cexes[y];if(b&&p(b.config.name))return void this.selectFormCEX(b.config.name)}var x=Object.values(h.cexes).filter((function(e){return p(e.config.name)}));x.length&&this.selectFormCEX(x[0].config.name)}}}}},{key:"showMarketSelectForm",value:function(){this.page.marketFilterInput.value="",this.sortMarketRows(),this.forms.show(this.page.marketSelectForm)}},{key:"sortMarketRows",value:function(){var e,t=this.page,n=null===(e=t.marketFilterInput.value)||void 0===e?void 0:e.toLowerCase();Me.empty(t.marketSelect);var r,a=Po(this.marketRows);try{for(a.s();!(r=a.n()).done;){var o=r.value;o.tr.classList.remove("selected"),n&&!o.name.includes(n)||t.marketSelect.appendChild(o.tr)}}catch(e){a.e(e)}finally{a.f()}}},{key:"handleBalanceNote",value:function(e){if(this.approveTokenForm.handleBalanceNote(e),this.marketReport){var t=this.marketStuff(),n=t.baseID,r=t.quoteID,a=t.quoteToken,o=t.baseToken;e.assetID===n||e.assetID===(null==o?void 0:o.parentID)?this.basePane.updateBalances():e.assetID!==r&&e.assetID!==(null==a?void 0:a.parentID)||this.quotePane.updateBalances()}}},{key:"autoRebalanceChanged",value:function(){var e,t,n=this.page;this.updatedConfig.cexRebalance=null!==(e=null===(t=n.cexRebalanceCheckbox)||void 0===t?void 0:t.checked)&&void 0!==e&&e,this.updateAllocations()}},{key:"submitBotType",value:(m=s(f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=ht().loading(this.page.botTypeForm),e.prev=1,e.next=4,this.submitBotWithValidation();case 4:return e.prev=4,t(),e.finish(4);case 7:case"end":return e.stop()}}),e,this,[[1,,4,7]])}))),function(){return m.apply(this,arguments)})},{key:"submitBotWithValidation",value:(p=s(f().mark((function e(){var t,n,r,o,s,i,c,l,u,d,h,p,v,m,g;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=this.page,r=this.forms,o=this.formSpecs,s=o.baseID,i=o.quoteID,c=o.host,ht().walletMap[s]){e.next=5;break}return this.newWalletForm.setAsset(s),r.show(this.page.newWalletForm),e.abrupt("return");case 5:if(ht().walletMap[i]){e.next=9;break}return this.newWalletForm.setAsset(i),r.show(this.page.newWalletForm),e.abrupt("return");case 9:if(l=Ko(c,ht().assets[s],ht().assets[i]),u=a(l,2),d=u[0],h=u[1],d!==lt.NotApproved){e.next=14;break}return this.approveTokenForm.setAsset(s,c),r.show(n.approveTokenForm),e.abrupt("return");case 14:if(h!==lt.NotApproved){e.next=18;break}return this.approveTokenForm.setAsset(i,c),r.show(n.approveTokenForm),e.abrupt("return");case 18:if(p=this.botTypeSelectors,!((v=p.filter((function(e){return e.classList.contains("selected")}))).length<1)){e.next=24;break}return n.botTypeErr.textContent=be("NO_BOTTYPE"),Me.show(n.botTypeErr),e.abrupt("return");case 24:if((this.formSpecs.botType=null!==(t=v[0].dataset.botType)&&void 0!==t?t:"")===er){e.next=35;break}if(!((m=Object.values(this.formCexes).filter((function(e){return e.div.classList.contains("selected")}))).length<1)){e.next=31;break}return n.botTypeErr.textContent=be("NO_CEX"),Me.show(n.botTypeErr),e.abrupt("return");case 31:return g=m[0].name,this.formSpecs.cexName=g,e.next=35,this.fetchCEXBalances(this.formSpecs);case 35:this.specs=this.formSpecs,this.configureUI(),this.forms.close();case 38:case"end":return e.stop()}}),e,this)}))),function(){return p.apply(this,arguments)})},{key:"fetchCEXBalances",value:(u=s(f().mark((function e(t){var n,r,a,o;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=this.page,r=t.baseID,a=t.quoteID,o=t.cexName,t.botType!==er&&o){e.next=4;break}return e.abrupt("return");case 4:return e.prev=4,e.next=7,ar.cexBalance(o,r);case 7:this.cexBaseBalance=e.sent,e.next=15;break;case 10:throw e.prev=10,e.t0=e.catch(4),n.botTypeErr.textContent=be(fe,{cexName:o,assetID:String(r),err:String(e.t0)}),Me.show(n.botTypeErr),e.t0;case 15:return e.prev=15,e.next=18,ar.cexBalance(o,a);case 18:this.cexQuoteBalance=e.sent,e.next=26;break;case 21:throw e.prev=21,e.t1=e.catch(15),n.botTypeErr.textContent=be(fe,{cexName:o,assetID:String(a),err:String(e.t1)}),Me.show(n.botTypeErr),e.t1;case 26:case"end":return e.stop()}}),e,this,[[4,10],[15,21]])}))),function(e){return u.apply(this,arguments)})},{key:"defaultWalletOptions",value:function(e){var t=ht().currentWalletDefinition(e);if(!t.multifundingopts)return{};var n,r={},a=Po(t.multifundingopts);try{for(a.s();!(n=a.n()).done;){var o=n.value;o.quoteAssetOnly&&e!==this.specs.quoteID||(r[o.key]="".concat(o.default))}}catch(e){a.e(e)}finally{a.f()}return r}},{key:"updateModifiedMarkers",value:function(){if(!this.creatingNewBot){var e=this.page,t=this.originalConfig,n=this.updatedConfig,r=t.gapStrategy!==n.gapStrategy;e.gapStrategySelect.classList.toggle("modified",r);var a=t.profit!==n.profit;e.profitInput.classList.toggle("modified",a);var o=!1;if(t.buyPlacements.length!==n.buyPlacements.length)o=!0;else for(var s=0;s100?"Multiplier must be between 1 and 100":null;case Yn:case Jn:return t<=0?"Rate must be greater than 0":null;case Zn:case $n:return t<=0||t>10?"Percent must be between 0 and 10":null;default:throw new Error("Unknown gap factor ".concat(e))}}},{key:"convertGapFactor",value:function(e,t,n){switch(t){case Qn:case Yn:case Jn:return e;case Zn:case $n:return n?100*e:e/100;default:throw new Error("Unknown gap factor ".concat(t))}}},{key:"addPlacement",value:function(e,t,n){var r=this,a=this.page,o=this.updatedConfig,s=a.sellPlacementsTableBody,i=a.addSellPlacementRow,c=a.addSellPlacementLots,l=a.addSellPlacementGapFactor,u=a.sellPlacementsErr;e&&(s=a.buyPlacementsTableBody,i=a.addBuyPlacementRow,c=a.addBuyPlacementLots,l=a.addBuyPlacementGapFactor,u=a.buyPlacementsErr),Me.hide(u);var d=function(){for(var e=0;e1;)t.buyPlacementsTableBody.children[0].remove();for(;t.sellPlacementsTableBody.children.length>1;)t.sellPlacementsTableBody.children[0].remove();this.placementsCache[e]=[n.buyPlacements,n.sellPlacements],n.buyPlacements.splice(0,n.buyPlacements.length),n.sellPlacements.splice(0,n.sellPlacements.length)}},{key:"loadCachedPlacements",value:function(e){var t,n,a=this.placementsCache[e];if(a){var o=this.updatedConfig;o.buyPlacements.splice(0,o.buyPlacements.length),o.sellPlacements.splice(0,o.sellPlacements.length),(t=o.buyPlacements).push.apply(t,r(a[0])),(n=o.sellPlacements).push.apply(n,r(a[1]));var s,i=e===No?Qn:e,c=Po(o.buyPlacements);try{for(c.s();!(s=c.n()).done;){var l=s.value;this.addPlacement(!0,l,i)}}catch(e){c.e(e)}finally{c.f()}var u,d=Po(o.sellPlacements);try{for(d.s();!(u=d.n()).done;){var h=u.value;this.addPlacement(!1,h,i)}}catch(e){d.e(e)}finally{d.f()}}}},{key:"setOriginalValues",value:function(){var e,t,n,r=this,o=this.page,s=this.originalConfig,i=this.updatedConfig,l=this.specs,u=l.cexName,d=l.botType;this.clearPlacements(u?No:i.gapStrategy),function(e,t){for(var n=0,r=Object.entries(t);n0?t.baseFiatRate.textContent=Me.formatFourSigFigs(i.baseFiatRate):t.baseFiatRate.textContent="N/A",i.quoteFiatRate>0?t.quoteFiatRate.textContent=Me.formatFourSigFigs(i.quoteFiatRate):t.quoteFiatRate.textContent="N/A",Me.show(t.fiatRates);case 14:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"cexConfigured",value:(t=s(f().mark((function e(t){var n,r,a,o,s,i,c,l,u,d,h,p,v,m;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=this.page,r=this.formSpecs,a=r.host,o=r.baseID,s=r.quoteID,i=rr[t],c=Po(this.marketRows),e.prev=3,c.s();case 5:if((l=c.n()).done){e.next=13;break}if(u=l.value,d=u.baseID,h=u.quoteID,p=u.tmpl,-1===(v=u.arbs).indexOf(t)){e.next=9;break}return e.abrupt("continue",11);case 9:this.cexMarketSupportFilter(d,h)(t)&&((m=n.arbBttnTmpl.cloneNode(!0)).src=i.logo,p.arbs.appendChild(m),v.push(t));case 11:e.next=5;break;case 13:e.next=18;break;case 15:e.prev=15,e.t0=e.catch(3),c.e(e.t0);case 18:return e.prev=18,c.f(),e.finish(18);case 21:this.setCEXAvailability(o,s,t),this.showBotTypeForm(a,o,s,tr,t);case 23:case"end":return e.stop()}}),e,this,[[3,15,18,21]])}))),function(e){return t.apply(this,arguments)})},{key:"setupCEXes",value:function(){this.formCexes={};for(var e=0,t=Object.keys(rr);e0,s.redemptionFeesBox),o.bookingFeesPerCounterLot>0){var w=o.bookingFeesPerCounterLot/d.conventional.conversionFactor;s.redemptionFeesPerLot.textContent=Me.formatFourSigFigs(w),s.redemptionFeesLots.textContent=String(t),s.redeemReservesFactor.textContent=o.redeemReservesFactor.toFixed(2)}this.updateCommitTotal(),this.updateTokenFees(),this.updateRebalance()}},{key:"updateCommitTotal",value:function(){var e=this.page,t=this.assetID,n=this.ui,r=this.commit();e.commitTotal.textContent=Me.formatCoinValue(Math.round(r*n.conventional.conversionFactor),n),e.commitTotalFiat.textContent=Me.formatFourSigFigs(r*ht().fiatRatesMap[t])}},{key:"updateTokenFees",value:function(){var e=this.page,t=this.inv,n=this.feeAssetID,r=this.feeUI;if(this.isToken){var a=t.bookingFees+t.swapFeeReserves;e.feeTotal.textContent=Me.formatCoinValue(a*r.conventional.conversionFactor,r),e.feeTotalFiat.textContent=Me.formatFourSigFigs(a*ht().fiatRatesMap[n])}}},{key:"updateRebalance",value:function(){var e=this.page,t=this.cfg,n=this.pg,r=n.updatedConfig.cexRebalance,a=n.specs.cexName&&r;if(Me.setVis(a,e.rebalanceOpts),a){var o=this.commit(),s=[this.minTransfer.min,Math.max(2*this.minTransfer.min,o)],i=s[0],c=s[1]-i;this.minTransfer.setValue(i+t.transferFactor*c),this.minTransferSlider.setValue((t.transferFactor-0)/1)}}},{key:"setupWalletSettings",value:function(){var e=this,t=this.page,n=this.assetID,r=this.walletConfig,o=ht().currentWalletDefinition(n);if(Me.empty(t.walletSettings),Me.setVis(!o.multifundingopts,t.walletSettingsNone),o.multifundingopts){var s={},i={},c=function(n){if(!n.quoteAssetOnly||e.isQuote){var o,c,l,u,d=r[n.key];if(n.isboolean){o=t.boolSettingTmpl.cloneNode(!0);var h=Me.parseTemplate(o);h.name.textContent=n.displayname,h.input.checked="true"===d,Me.bind(h.input,"change",(function(){r[n.key]=h.input.checked?"true":"false",function(e,t){var n=i[e];if(n){var r,a=Po(n);try{for(a.s();!(r=a.n()).done;){var o=r.value;Me.setVis(t,s[o])}}catch(e){a.e(e)}finally{a.f()}}}(n.key,Boolean(h.input.checked))})),n.description&&(h.tooltip.dataset.tooltip=n.description)}else if(n.xyRange){var p=n.xyRange,f=p.start,v=p.end,m=p.xUnit,g=v.x-f.x;o=t.rangeSettingTmpl.cloneNode(!0);var y=Me.parseTemplate(o);y.name.textContent=n.displayname,n.description&&(y.tooltip.dataset.tooltip=n.description),m?y.unit.textContent=m:Me.hide(y.unit);var b=new Ke(y.value,{prec:1,changed:function(e){var t=a(Ze(e,1),2),o=t[0],s=t[1];r[n.key]=s,x.setValue((o-f.x)/g)}}),x=new Ye(y.slider,(function(e){var t=a(Ze(f.x+e*g,1),2),o=t[0],s=t[1];r[n.key]=s,b.setValue(o)})),k=a(Ze($e(d,f.x),3),2),w=k[0],S=k[1];r[n.key]=S,x.setValue((w-f.x)/g),b.setValue(w),y.value.textContent=S}if(!o)return console.error("don't know how to handle opt",n);if(t.walletSettings.appendChild(o),n.dependsOn){c=n.key,l=o,u=n.dependsOn,i[u]||(i[u]=[]),i[u].push(c),s[c]=l;var C=r[n.dependsOn];Me.setVis("true"===C,o)}}};if(o.multifundingopts&&o.multifundingopts.length>0){var l,u=Po(o.multifundingopts);try{for(u.s();!(l=u.n()).done;)c(l.value)}catch(e){u.e(e)}finally{u.f()}}ht().bindTooltips(t.walletSettings)}}},{key:"updateBalances",value:function(){var e=this.page,t=this.assetID,n=this.ui,r=this.feeAssetID,a=this.feeUI,o=this.pg,s=o.specs,i=s.cexName,c=s.baseID,l=o.cexBaseBalance,u=o.cexQuoteBalance,d=ht().walletMap[t].balance.available,h=this.pg.runningBotInventory(t),p=d-h.dex.total,f=0;if(Me.setVis(i,e.balanceBreakdown),i&&(e.dexAvail.textContent=Me.formatFourSigFigs(p/n.conventional.conversionFactor),f=(t===c?l:u).available-h.cex.total,e.cexAvail.textContent=Me.formatFourSigFigs(f/n.conventional.conversionFactor)),e.avail.textContent=Me.formatFourSigFigs((p+f)/n.conventional.conversionFactor),t!==r){var v=ht().walletMap[r].balance.available;e.feeAvail.textContent=Me.formatFourSigFigs(v/a.conventional.conversionFactor)}}}]),e}();var Yo=function(e){g(I,e);var t,n,r,a,o,c,l,u,p,m,x,k,w,S,F,T,D=(F=I,T=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}(),function(){var e,t=b(F);if(T){var n=b(this).constructor;e=Reflect.construct(t,arguments,n)}else e=t.apply(this,arguments);return y(this,e)});function I(e){var t;i(this,I),h(v(t=D.call(this)),"body",void 0),h(v(t),"forms",void 0),h(v(t),"currentForm",void 0),h(v(t),"page",void 0),h(v(t),"host",void 0),h(v(t),"accountDisabled",void 0),h(v(t),"keyup",void 0),h(v(t),"dexAddrForm",void 0),h(v(t),"bondFeeBufferCache",void 0),h(v(t),"newWalletForm",void 0),h(v(t),"regAssetForm",void 0),h(v(t),"walletWaitForm",void 0),h(v(t),"confirmRegisterForm",void 0),h(v(t),"reputationMeter",void 0),h(v(t),"animation",void 0),h(v(t),"renewToggle",void 0),t.body=e;var n=t.host=e.dataset.host?e.dataset.host:"",r=ht().exchanges[n],a=t.page=Me.idDescendants(e);t.forms=Me.applySelector(a.forms,":scope > form"),t.confirmRegisterForm=new Cr(a.confirmRegForm,s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t.showSuccess(be(oe)),t.renewToggle.setState(t.confirmRegisterForm.tier>0),e.next=4,ht().fetchUser();case 4:ht().updateMenuItemsDisplay();case 5:case"end":return e.stop()}}),e)}))),(function(){t.runAnimation(t.regAssetForm,a.regAssetForm)})),t.confirmRegisterForm.setExchange(r,""),t.walletWaitForm=new Tr(a.walletWait,(function(){t.runAnimation(t.confirmRegisterForm,a.confirmRegForm)}),(function(){t.runAnimation(t.regAssetForm,a.regAssetForm)})),t.walletWaitForm.setExchange(r),t.newWalletForm=new kr(a.newWalletForm,(function(e){return t.newWalletCreated(e,t.confirmRegisterForm.tier)}),(function(){return t.runAnimation(t.regAssetForm,a.regAssetForm)})),t.regAssetForm=new Fr(a.regAssetForm,function(){var e=s(f().mark((function e(n,r){var o,s,i,c;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n!==dt){e.next=6;break}return e.next=3,ht().fetchUser();case 3:return t.updateReputation(),t.showSuccess(be(oe)),e.abrupt("return");case 6:if(o=ht().assets[n],!(s=o.wallet)){e.next=17;break}return i=ht().loading(a.regAssetForm),e.next=12,t.getBondsFeeBuffer(n,a.regAssetForm);case 12:return c=e.sent,t.confirmRegisterForm.setAsset(n,r,c),i(),t.progressTierFormsWithWallet(n,s),e.abrupt("return");case 17:t.confirmRegisterForm.setAsset(n,r,0),t.newWalletForm.setAsset(n),t.showForm(a.newWalletForm);case 20:case"end":return e.stop()}}),e)})));return function(t,n){return e.apply(this,arguments)}}()),t.regAssetForm.setExchange(r,""),t.reputationMeter=new wn(a.repMeter),t.reputationMeter.setHost(n),Me.bind(a.exportDexBtn,"click",(function(){return t.exportAccount()})),t.accountDisabled="true"===e.dataset.disabled,Me.bind(a.toggleAccountStatusBtn,"click",(function(){t.accountDisabled?t.toggleAccountStatus(!1):t.prepareAccountDisable(a.disableAccountForm)})),Me.bind(a.updateCertBtn,"click",(function(){return a.certFileInput.click()})),Me.bind(a.updateHostBtn,"click",(function(){return t.prepareUpdateHost()})),Me.bind(a.certFileInput,"change",(function(){return t.onCertFileChange()})),Me.bind(a.goBackToSettings,"click",(function(){return ht().loadPage("settings")}));var o=function(){t.regAssetForm.setExchange(ht().exchanges[n],""),t.showForm(a.regAssetForm)};Me.bind(a.changeTier,"click",(function(){o()}));var c=r.auth.targetTier>0;t.renewToggle=new Ve(a.toggleAutoRenew,a.renewErr,c,function(){var e=s(f().mark((function e(n){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.accountDisabled){e.next=2;break}return e.abrupt("return");case 2:if(!n){e.next=6;break}o(),e.next=7;break;case 6:return e.abrupt("return",t.disableAutoRenew());case 7:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()),Me.bind(a.autoRenewBox,"click",(function(e){e.stopPropagation(),t.accountDisabled||a.toggleAutoRenew.click()})),a.penaltyComps.textContent=String(r.auth.penaltyComps);var l=function(){Me.hide(a.penaltyCompInput),Me.show(a.penaltyComps)};return Me.bind(a.penaltyCompBox,"click",(function(e){e.stopPropagation();var n=ht().exchanges[t.host];a.penaltyCompInput.value=String(n.auth.penaltyComps),Me.hide(a.penaltyComps),Me.show(a.penaltyCompInput),a.penaltyCompInput.focus(),Me.bind(document,"click",(function e(t){Me.mouseInElement(t,a.penaltyCompBox)||(l(),Me.unbind(document,"click",e))}))})),Me.bind(a.penaltyCompInput,"keyup",function(){var e=s(f().mark((function e(n){var r,o;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(Me.hide(a.penaltyCompsErr),"Escape"!==n.key){e.next=4;break}return l(),e.abrupt("return");case 4:if("Enter"===n.key){e.next=6;break}return e.abrupt("return");case 6:if(r=parseInt(a.penaltyCompInput.value||""),!isNaN(r)){e.next=11;break}return Me.show(a.penaltyCompsErr),a.penaltyCompsErr.textContent=be("INVALID_COMPS_VALUE"),e.abrupt("return");case 11:return o=ht().loading(a.otherBondSettings),e.prev=12,e.next=15,t.updateBondOptions({penaltyComps:r});case 15:o(),a.penaltyComps.textContent=String(r),e.next=24;break;case 19:e.prev=19,e.t0=e.catch(12),o(),Me.show(a.penaltyCompsErr),a.penaltyCompsErr.textContent=be(H,{msg:e.t0.msg});case 24:l();case 25:case"end":return e.stop()}}),e,null,[[12,19]])})));return function(t){return e.apply(this,arguments)}}()),t.dexAddrForm=new Ir(a.dexAddrForm,function(){var e=s(f().mark((function e(t){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:ht().loadPage("/dexsettings/".concat(t.host));case 1:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),t.host),Vr(a.disableAccountForm,a.disableAccountConfirm,(function(){return t.toggleAccountStatus(!0)})),Me.bind(a.forms,"mousedown",(function(e){Me.mouseInElement(e,t.currentForm)||t.closePopups()})),t.keyup=function(e){"Escape"===e.key&&t.closePopups()},Me.bind(document,"keyup",t.keyup),Me.applySelector(a.forms,".form-closer").forEach((function(e){Me.bind(e,"click",(function(){t.closePopups()}))})),ht().registerNoteFeeder({conn:function(){t.setConnectionStatus()},reputation:function(){t.updateReputation()},feepayment:function(){t.updateReputation()},bondpost:function(){t.updateReputation()}}),t.setConnectionStatus(),t.updateReputation(),t}return d(I,[{key:"unload",value:function(){Me.unbind(document,"keyup",this.keyup)}},{key:"progressTierFormsWithWallet",value:(S=s(f().mark((function e(t,n){var r,a,o,s,i,c,l;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=this.page,a=this.confirmRegisterForm.fees,o=ht().assets[t],s=this.regAssetForm.xc.bondAssets,i=s[o.symbol],n.open){e.next=12;break}return c=ht().loading(r.forms),e.next=8,C("/api/openwallet",{assetID:t});case 8:return l=e.sent,c(),ht().checkResponse(l)||(this.regAssetForm.setAssetError("error unlocking wallet: ".concat(l.msg)),this.runAnimation(this.regAssetForm,r.regAssetForm)),e.abrupt("return");case 12:if(!(n.synced&&n.balance.available>=2*i.amount+a)){e.next=15;break}return this.progressTierFormWithSyncedFundedWallet(t),e.abrupt("return");case 15:this.walletWaitForm.setWallet(t,a,this.confirmRegisterForm.tier),this.showForm(r.walletWait);case 17:case"end":return e.stop()}}),e,this)}))),function(e,t){return S.apply(this,arguments)})},{key:"progressTierFormWithSyncedFundedWallet",value:(w=s(f().mark((function e(t){var n,r,a,o,s;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=ht().exchanges[this.host],r=this.confirmRegisterForm.tier,a=this.page,o=n.auth.liveStrength+n.auth.pendingStrength-n.auth.weakStrength,!(r>n.auth.targetTier&&r>o)){e.next=7;break}return this.runAnimation(this.confirmRegisterForm,a.confirmRegForm),e.abrupt("return");case 7:return s=ht().loading(this.body),e.prev=8,e.next=11,this.updateBondOptions({bondAssetID:t,targetTier:r});case 11:s(),e.next=19;break;case 14:return e.prev=14,e.t0=e.catch(8),s(),this.regAssetForm.setTierError(e.t0.msg),e.abrupt("return");case 19:this.showSuccess(be(oe));case 20:case"end":return e.stop()}}),e,this,[[8,14]])}))),function(e){return w.apply(this,arguments)})},{key:"updateReputation",value:function(){var e=this.page,t=ht().exchanges[this.host].auth,n=t.rep.penalties,r=t.targetTier,a=t.expiredBonds,o=Sn(t);e.targetTier.textContent=String(r),e.effectiveTier.textContent=String(o),e.penalties.textContent=String(n),e.bondsPendingRefund.textContent="".concat((null==a?void 0:a.length)||0),this.reputationMeter.update()}},{key:"showForm",value:(k=s(f().mark((function e(t){var n,r;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=this.page,this.currentForm=t,this.forms.forEach((function(e){return Me.hide(e)})),t.style.right="10000px",Me.show(n.forms,t),r=(n.forms.offsetWidth+t.offsetWidth)/2,e.next=8,Me.animate(300,(function(e){t.style.right="".concat((1-e)*r,"px")}),"easeOutHard");case 8:t.style.right="0";case 9:case"end":return e.stop()}}),e,this)}))),function(e){return k.apply(this,arguments)})},{key:"runAnimation",value:(x=s(f().mark((function e(t,n){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return Me.hide(this.currentForm),e.next=3,t.animate();case 3:this.currentForm=n,Me.show(n);case 5:case"end":return e.stop()}}),e,this)}))),function(e,t){return x.apply(this,arguments)})},{key:"closePopups",value:function(){Me.hide(this.page.forms),this.animation&&this.animation.stop()}},{key:"showSuccess",value:(m=s(f().mark((function e(t){var n=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.forms.forEach((function(e){return Me.hide(e)})),this.currentForm=this.page.checkmarkForm,this.animation=Wr(this.page,t),e.next=5,this.animation.wait();case 5:this.animation=new qe(1500,(function(){}),"",(function(){n.currentForm===n.page.checkmarkForm&&n.closePopups()}));case 6:case"end":return e.stop()}}),e,this)}))),function(e){return m.apply(this,arguments)})},{key:"exportAccount",value:(p=s(f().mark((function e(){var t,n,r,a,o,s,i;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.page,n=this.host,r={host:n},a=ht().loading(this.body),e.next=5,C("/api/exportaccount",r);case 5:if(o=e.sent,a(),ht().checkResponse(o)){e.next=11;break}return t.exportAccountErr.textContent=o.msg,Me.show(t.exportAccountErr),e.abrupt("return");case 11:o.account.bonds=o.bonds,s=JSON.parse(JSON.stringify(o.account)),(i=document.createElement("a")).setAttribute("download","dcrAccount-"+n+".json"),i.setAttribute("href","data:text/json,"+JSON.stringify(s,null,2)),i.click(),Me.hide(t.forms);case 18:case"end":return e.stop()}}),e,this)}))),function(){return p.apply(this,arguments)})},{key:"toggleAccountStatus",value:(u=s(f().mark((function e(t){var n,r,a,o,s;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=this.page,Me.hide(n.errMsg),r=this.host,t&&(r=n.disableAccountHost.textContent),a={host:r,disable:t},o=ht().loading(this.body),e.next=8,C("/api/toggleaccountstatus",a);case 8:if(s=e.sent,o(),ht().checkResponse(s)){e.next=13;break}return t?(n.disableAccountErr.textContent=s.msg,Me.show(n.disableAccountErr)):(n.errMsg.textContent=s.msg,Me.show(n.errMsg)),e.abrupt("return");case 13:t?(this.page.toggleAccountStatusBtn.textContent=be("ENABLE_ACCOUNT"),Me.hide(n.forms)):this.page.toggleAccountStatusBtn.textContent=be("DISABLE_ACCOUNT"),this.accountDisabled=t,ht().loadPage("dexsettings/".concat(r));case 16:case"end":return e.stop()}}),e,this)}))),function(e){return u.apply(this,arguments)})},{key:"prepareAccountDisable",value:(l=s(f().mark((function e(t){var n;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:(n=this.page).disableAccountHost.textContent=this.host,n.disableAccountErr.textContent="",this.showForm(t);case 4:case"end":return e.stop()}}),e,this)}))),function(e){return l.apply(this,arguments)})},{key:"getBondsFeeBuffer",value:(c=s(f().mark((function e(t,n){var r,a;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=ht().loading(n),e.next=3,C("/api/bondsfeebuffer",{assetID:t});case 3:if(a=e.sent,r(),ht().checkResponse(a)){e.next=7;break}return e.abrupt("return",0);case 7:return e.abrupt("return",a.feeBuffer);case 8:case"end":return e.stop()}}),e)}))),function(e,t){return c.apply(this,arguments)})},{key:"prepareUpdateHost",value:(o=s(f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=this.page,this.dexAddrForm.refresh(),this.showForm(t.dexAddrForm);case 3:case"end":return e.stop()}}),e,this)}))),function(){return o.apply(this,arguments)})},{key:"onCertFileChange",value:(a=s(f().mark((function e(){var t,n,r,a,o,s;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=this.page,Me.hide(t.errMsg),!(n=t.certFileInput.files)||!n.length){e.next=7;break}return e.next=6,n[0].text();case 6:r=e.sent;case 7:if(r){e.next=9;break}return e.abrupt("return");case 9:return a={host:this.host,cert:r},o=ht().loading(this.body),e.next=13,C("/api/updatecert",a);case 13:s=e.sent,o(),ht().checkResponse(s)?(Me.show(t.updateCertMsg),setTimeout((function(){Me.hide(t.updateCertMsg)}),5e3)):(t.errMsg.textContent=s.msg,Me.show(t.errMsg));case 16:case"end":return e.stop()}}),e,this)}))),function(){return a.apply(this,arguments)})},{key:"setConnectionStatus",value:function(){var e=this.page,t=ht().user.exchanges[this.host],n=function(t){t?(Me.hide(e.disconnectedIcon),Me.show(e.connectedIcon)):(Me.show(e.disconnectedIcon),Me.hide(e.connectedIcon))};if(t)switch(t.connectionStatus){case ct.Connected:n(!0),e.connectionStatus.textContent=be("CONNECTED");break;case ct.Disconnected:n(!1),this.accountDisabled?e.connectionStatus.textContent=be("ACCOUNT_DISABLED_MSG"):e.connectionStatus.textContent=be(Z);break;case ct.InvalidCert:n(!1),e.connectionStatus.textContent="".concat(be(Z)," - ").concat(be("INVALID_CERTIFICATE"))}}},{key:"disableAutoRenew",value:(r=s(f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=ht().loading(this.page.otherBondSettings),e.prev=1,this.updateBondOptions({targetTier:0}),t(),e.next=10;break;case 6:throw e.prev=6,e.t0=e.catch(1),t(),e.t0;case 10:case"end":return e.stop()}}),e,this,[[1,6]])}))),function(){return r.apply(this,arguments)})},{key:"updateBondOptions",value:(n=s(f().mark((function e(t){var n,r;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t.host=this.host,e.next=3,C("/api/updatebondoptions",t);case 3:r=null!==(n=t.targetTier)&&void 0!==n?n:ht().exchanges[this.host].auth.targetTier,this.renewToggle.setState(r>0);case 5:case"end":return e.stop()}}),e,this)}))),function(e){return n.apply(this,arguments)})},{key:"newWalletCreated",value:(t=s(f().mark((function e(t,n){var r,a,o,s,i,c,l;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.regAssetForm.refresh(),e.next=3,ht().fetchUser();case 3:if(r=e.sent){e.next=6;break}return e.abrupt("return");case 6:return a=this.page,o=r.assets[t],s=o.wallet,i=ht().exchanges[this.host],c=i.bondAssets[o.symbol].amount,e.next=13,this.getBondsFeeBuffer(t,a.newWalletForm);case 13:if(l=e.sent,this.confirmRegisterForm.setFees(t,l),!(s.synced&&s.balance.available>=2*c+l)){e.next=18;break}return this.progressTierFormWithSyncedFundedWallet(t),e.abrupt("return");case 18:return this.walletWaitForm.setWallet(t,l,n),e.next=21,this.showForm(a.walletWait);case 21:case"end":return e.stop()}}),e,this)}))),function(e,n){return t.apply(this,arguments)})}]),I}(it);var Jo=function(e){g(o,e);var t,n,r,a=(n=o,r=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}(),function(){var e,t=b(n);if(r){var a=b(this).constructor;e=Reflect.construct(t,arguments,a)}else e=t.apply(this,arguments);return y(this,e)});function o(e){var t;i(this,o),h(v(t=a.call(this)),"page",void 0),h(v(t),"base",void 0),h(v(t),"quote",void 0),h(v(t),"host",void 0);var n=t.page=Me.idDescendants(e);return Me.cleanTemplates(n.runTableRowTmpl),Me.bind(n.backButton,"click",(function(){ht().loadPage("mm")})),t.setup(),t}return d(o,[{key:"setup",value:(t=s(f().mark((function e(){var t,n,r,a,o=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,T("/api/archivedmmruns");case 2:if(t=e.sent,ht().checkResponse(t)){e.next=6;break}return console.error("failed to get archived mm runs",t),e.abrupt("return");case 6:n=t.runs,r=f().mark((function e(){var t,r,s,i,c,l,u,d;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=n[a],r=t.startTime,s=t.market,i=s.baseID,c=s.quoteID,l=s.host,u=o.page.runTableRowTmpl.cloneNode(!0),(d=Me.parseTemplate(u)).startTime.textContent=new Date(1e3*r).toLocaleString(),sr(u,i,c,l),Me.bind(d.logs,"click",(function(){ht().loadPage("mmlogs",{baseID:i,quoteID:c,host:l,startTime:r,returnPage:"mmarchives"})})),Me.bind(d.settings,"click",(function(){ht().loadPage("mmsettings",{host:l,baseID:i,quoteID:c})})),o.page.runTableBody.appendChild(u);case 8:case"end":return e.stop()}}),e)})),a=0;case 9:if(!(a=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,i=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){i=!0,o=e},f:function(){try{s||null==n.return||n.return()}finally{if(i)throw o}}}}function $o(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n0&&(this.refID=a.logs[a.logs.length-1].id),e.abrupt("return",[a.logs,a.updatedLogs||[],a.overview]);case 9:case"end":return e.stop()}}),e,this)}))),function(){return r.apply(this,arguments)})},{key:"applyFilters",value:(n=s(f().mark((function e(){var t,n,r,o,s;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.page,this.filters={dexSells:!!t.dexSellsCheckbox.checked,dexBuys:!!t.dexBuysCheckbox.checked,cexSells:!!t.cexSellsCheckbox.checked,cexBuys:!!t.cexBuysCheckbox.checked,deposits:!!t.depositsCheckbox.checked,withdrawals:!!t.withdrawalsCheckbox.checked},this.refID=void 0,e.next=5,this.getRunLogs();case 5:n=e.sent,r=a(n,3),o=r[0],s=r[2],this.populateTable(o),this.populateStats(s.profitLoss,s.endTime);case 11:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"setFilters",value:function(){var e=this.page;e.dexSellsCheckbox.checked=!0,e.dexBuysCheckbox.checked=!0,e.cexSellsCheckbox.checked=!0,e.cexBuysCheckbox.checked=!0,e.depositsCheckbox.checked=!0,e.withdrawalsCheckbox.checked=!0,this.filters={dexSells:!0,dexBuys:!0,cexSells:!0,cexBuys:!0,deposits:!0,withdrawals:!0}}},{key:"setup",value:(t=s(f().mark((function e(t,n,r){var o,s,i,c,l,u,d,h,p,v,m,g,y,b,x,k,w=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return s=this.page,this.setFilters(),i=this.startTime,l=0,u=hr(t,n,r),e.next=7,this.getRunLogs();case 7:d=e.sent,h=a(d,3),p=h[0],v=h[2],(null==u||null===(o=u.runStats)||void 0===o?void 0:o.startTime)===i?(this.liveBot=!0,this.fiatRates=ht().fiatRatesMap,c=u.runStats.profitLoss):(this.fiatRates=v.finalState.fiatRates,c=v.profitLoss,l=v.endTime),this.populateStats(c,l),m=this.mktAssets(),g=s.sumUSDHeader.parentElement,y=Zo(m);try{for(y.s();!(b=y.n()).done;)x=b.value,(k=document.createElement("th")).textContent="".concat(x.symbol.toUpperCase()," Delta"),g&&g.insertBefore(k,s.sumUSDHeader)}catch(e){y.e(e)}finally{y.f()}this.populateTable(p),ht().registerNoteFeeder({runevent:function(e){w.handleRunEventNote(e)},runstats:function(e){w.handleRunStatsNote(e)}});case 19:case"end":return e.stop()}}),e,this)}))),function(e,n,r){return t.apply(this,arguments)})},{key:"handleRunEventNote",value:function(e){var t=this.mkt,n=t.baseID,r=t.quoteID,a=t.host;if(e.host===a&&e.baseID===n&&e.quoteID===r&&(o=e.event,s=this.filters,o.dexOrderEvent?o.dexOrderEvent.sell?s.dexSells:s.dexBuys:o.cexOrderEvent?o.cexOrderEvent.sell?s.cexSells:s.cexBuys:o.depositEvent?s.deposits:o.withdrawalEvent&&s.withdrawals)){var o,s,i=e.event,c=this.events[i.id];if(c)return this.setRowContents(c[1],i,this.mktAssets()),void(c[0]=i);var l=this.newEventRow(i,!0,this.mktAssets());this.events[i.id]=[i,l]}}},{key:"handleRunStatsNote",value:function(e){var t=this.mkt,n=t.baseID,r=t.quoteID,a=t.host,o=this.startTime;e.host===a&&e.baseID===n&&e.quoteID===r&&e.stats&&e.stats.startTime===o&&this.populateStats(e.stats.profitLoss,0)}},{key:"populateStats",value:function(e,t){var n=this.page;for(var r in n.startTime.textContent=new Date(1e3*this.startTime).toLocaleString(),0===t?Me.hide(n.endTimeRow):n.endTime.textContent=new Date(1e3*t).toLocaleString(),e.diffs){var a=ht().assets[parseInt(r)],o=this.statsRows[r];if(!o){o=n.performanceTableRowTmpl.cloneNode(!0);var s=Me.parseTemplate(o);s.logo.src=Me.logoPath(a.symbol),s.ticker.textContent=a.symbol.toUpperCase(),this.statsRows[r]=o,n.performanceTableBody.appendChild(o)}var i=e.diffs[r],c=Me.parseTemplate(o);c.diff.textContent=i.fmt,c.usdDiff.textContent=i.fmtUSD,c.fiatRate.textContent="".concat(Me.formatFiatValue(this.fiatRates[a.id])," USD")}n.profitLoss.textContent="".concat(Me.formatFiatValue(e.profit)," USD")}},{key:"mktAssets",value:function(){var e,t=ht().assets[this.mkt.baseID],n=ht().assets[this.mkt.quoteID],r=[t,n],a=(h(e={},t.id,!0),h(e,n.id,!0),e);if(t.token&&!a[t.token.parentID]){var o=ht().assets[t.token.parentID];a[o.id]=!0,r.push(o)}if(n.token&&!a[n.token.parentID]){var s=ht().assets[n.token.parentID];r.push(s)}return r}},{key:"updateExistingRows",value:function(e){var t,n=Zo(e);try{for(n.s();!(t=n.n()).done;){var r=t.value,a=this.events[r.id];a&&(this.setRowContents(a[1],r,this.mktAssets()),a[0]=r)}}catch(e){n.e(e)}finally{n.f()}}},{key:"populateTable",value:function(e){var t=this.page;Me.empty(t.eventsTableBody),this.events={},this.doneScrolling=!1;var n,r=this.mktAssets(),a=Zo(e);try{for(a.s();!(n=a.n()).done;){var o=n.value,s=this.newEventRow(o,!1,r);this.events[o.id]=[o,s]}}catch(e){a.e(e)}finally{a.f()}}},{key:"setRowContents",value:function(e,t,n){var r,a=this,o=Me.parseTemplate(e);o.time.textContent=new Date(1e3*t.timestamp).toLocaleString(),o.eventType.textContent=this.eventType(t),t.depositEvent?r=t.depositEvent.transaction.id:t.withdrawalEvent?r=t.withdrawalEvent.id:t.dexOrderEvent?r=t.dexOrderEvent.id:t.cexOrderEvent&&(r=t.cexOrderEvent.id),r&&(o.eventID.textContent=rs(r,30),o.eventID.setAttribute("title",r));var s,i=0,c=Zo(n);try{for(c.s();!(s=c.n()).done;){var l,u=s.value,d=t.balanceEffects,h=as(u.id,d),p="sum".concat(u.symbol.toUpperCase()),f=void 0;if(o[p])f=o[p];else{(f=document.createElement("td")).dataset.tmpl=p;var v=o.sumUSD.parentElement;v&&v.insertBefore(f,o.sumUSD)}f.textContent=Me.formatCoinValue(h,u.unitInfo),i+=null!==(l=h/u.unitInfo.conventional.conversionFactor*this.fiatRates[u.id])&&void 0!==l?l:0}}catch(e){c.e(e)}finally{c.f()}o.sumUSD.textContent=Me.formatFourSigFigs(i),Me.bind(o.details,"click",(function(){a.showEventDetails(t.id)}))}},{key:"newEventRow",value:function(e,t,n){var r=this.page,a=r.eventTableRowTmpl.cloneNode(!0);return a.id=e.id.toString(),this.setRowContents(a,e,n),t?r.eventsTableBody.insertBefore(a,r.eventsTableBody.firstChild):r.eventsTableBody.appendChild(a),a}},{key:"eventType",value:function(e){return e.depositEvent?"Deposit":e.withdrawalEvent?"Withdrawal":e.dexOrderEvent?e.dexOrderEvent.sell?"DEX Sell":"DEX Buy":e.cexOrderEvent?e.cexOrderEvent.sell?"CEX Sell":"CEX Buy":""}},{key:"showDexOrderEventDetails",value:function(e){var t=this.page,n=this.mkt,r=n.baseID,a=n.quoteID,o=ht().assets[r],s=ht().assets[a],i=[o.unitInfo,s.unitInfo],c=i[0],l=i[1],u=[c.conventional.unit,l.conventional.unit],d=u[0],h=u[1];void 0!==this.dexOrderIDCopyListener&&t.copyDexOrderID.removeEventListener("click",this.dexOrderIDCopyListener),this.dexOrderIDCopyListener=function(){tt(e.id,t.dexOrderID,t.copyDexOrderID,"#1e7d11")},t.copyDexOrderID.addEventListener("click",this.dexOrderIDCopyListener),t.dexOrderID.textContent=rs(e.id,20),t.dexOrderID.setAttribute("title",e.id);var p=ht().conventionalRate(r,a,e.rate);t.dexOrderRate.textContent="".concat(p," ").concat(d,"/").concat(h),t.dexOrderQty.textContent="".concat(e.qty/c.conventional.conversionFactor," ").concat(d),e.sell?t.dexOrderSide.textContent=be(B):t.dexOrderSide.textContent=be(E),Me.empty(t.dexOrderTxsTableBody),Me.setVis(e.transactions&&e.transactions.length>0,t.dexOrderTxsTable);for(var f=function(e,t){switch(e){case 3:case 5:case 6:return t?o:s;case 4:return t?s:o}},v=0;e.transactions&&v=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,i=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){i=!0,o=e},f:function(){try{s||null==n.return||n.return()}finally{if(i)throw o}}}}function ss(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,i=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){i=!0,o=e},f:function(){try{s||null==n.return||n.return()}finally{if(i)throw o}}}}function ms(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n1?n-1:0),a=1;adocument.body.offsetWidth&&(r=document.body.offsetWidth-t.tooltip.offsetWidth-5),t.tooltip.style.left="".concat(r,"px"),t.tooltip.style.top="".concat(n.bodyTop-t.tooltip.offsetHeight-5,"px")})),ys(e,"mouseleave",(function(){t.tooltip.style.left="-10000px"}))}))}},{key:"bindUnits",value:function(e){var t=this,n=document.createElement("div");n.classList.add("position-absolute","p-3");var r=document.createElement("div");n.appendChild(r),r.classList.add("body-bg","border");var a,o=function(e,t,n){var a=Me.safeSelector(e,"[data-unit-box]"),o=parseInt(a.dataset.atoms),s=document.createElement("div");s.textContent=t,r.appendChild(s),s.classList.add("p-2","hoverbg","pointer"),Me.bind(s,"click",(function(){Me.setText(e,"[data-value]",Me.formatFourSigFigs(o/n,Math.round(Math.log10(n)))),Me.setText(e,"[data-unit]",t)}))},s=vs(Me.applySelector(e,"[data-conversion-value]"));try{var i=function(){var e=a.value,s=Me.safeSelector(e,"[data-unit-box]");Me.bind(s,"mouseenter",(function(){Me.empty(r),s.appendChild(n);var a=Me.layoutMetrics(s),i=parseInt(s.dataset.assetID),c=t.assets[i].unitInfo;o(e,c.conventional.unit,c.conventional.conversionFactor);var l,u=vs(c.denominations);try{for(u.s();!(l=u.n()).done;){var d=l.value,h=d.unit,p=d.conversionFactor;o(e,h,p)}}catch(e){u.e(e)}finally{u.f()}o(e,c.atomicUnit,1),a.bodyTop>n.offsetHeight+t.header.offsetHeight?(n.style.bottom="calc(100% - 1rem)",n.style.top="auto"):(n.style.top="calc(100% - 1rem)",n.style.bottom="auto")})),Me.bind(s,"mouseleave",(function(){return n.remove()}))};for(s.s();!(a=s.n()).done;)i()}catch(e){s.e(e)}finally{s.f()}}},{key:"bindUrlHandlers",value:function(e){if(window.openUrl){var t,n=vs(Me.applySelector(e,"a[target=_blank]"));try{var r=function(){var e=t.value;Me.bind(e,"click",(function(t){var n;t.preventDefault(),window.openUrl(null!==(n=e.href)&&void 0!==n?n:"")}))};for(n.s();!(t=n.n()).done;)r()}catch(e){n.e(e)}finally{n.f()}}}},{key:"attachHeader",value:function(){var e=this;this.header=gs(document.body,"header");var t=this.page=Me.idDescendants(this.header);this.headerSpace=t.headerSpace,this.popupNotes=gs(document.body,"popupNotes"),this.popupTmpl=Me.tmplElement(this.popupNotes,"note"),this.popupTmpl?this.popupTmpl.remove():console.error("popupTmpl element not found"),this.tooltip=gs(document.body,"tooltip"),t.noteTmpl.removeAttribute("id"),t.noteTmpl.remove(),t.pokeTmpl.removeAttribute("id"),t.pokeTmpl.remove(),t.loader.remove(),Me.show(t.loader),ys(t.noteBell,"click",s(f().mark((function n(){var r,a,o;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:Me.hide(t.pokeList),Me.show(t.noteList),e.ackNotes(),t.noteCat.classList.add("active"),t.pokeCat.classList.remove("active"),e.showDropdown(t.noteBell,t.noteBox),Me.hide(t.noteIndicator),r=vs(e.notes);try{for(r.s();!(a=r.n()).done;)(o=a.value).acked&&o.el.classList.remove("firstview")}catch(e){r.e(e)}finally{r.f()}e.setNoteTimes(t.noteList),e.setNoteTimes(t.pokeList);case 11:case"end":return n.stop()}}),n)})))),ys(t.burgerIcon,"click",(function(){Me.hide(t.logoutErr),e.showDropdown(t.burgerIcon,t.profileBox)})),ys(t.innerNoteIcon,"click",(function(){Me.hide(t.noteBox)})),ys(t.innerBurgerIcon,"click",(function(){Me.hide(t.profileBox)})),ys(t.profileSignout,"click",s(f().mark((function t(){return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,e.signOut();case 2:return t.abrupt("return",t.sent);case 3:case"end":return t.stop()}}),t)})))),ys(t.pokeCat,"click",(function(){e.setNoteTimes(t.pokeList),t.pokeCat.classList.add("active"),t.noteCat.classList.remove("active"),Me.hide(t.noteList),Me.show(t.pokeList),e.ackNotes()})),ys(t.noteCat,"click",(function(){e.setNoteTimes(t.noteList),t.noteCat.classList.add("active"),t.pokeCat.classList.remove("active"),Me.hide(t.pokeList),Me.show(t.noteList),e.ackNotes()})),Me.cleanTemplates(t.langBttnTmpl);var n=ks[this.lang],r=n.name,a=n.flag;t.langFlag.textContent=a,t.langName.textContent=r;var o,i=vs(this.langs);try{var c=function(){var n=o.value;if(n===e.lang)return"continue";var r=t.langBttnTmpl.cloneNode(!0),a=ks[n],s=a.name,i=a.flag;r.textContent=i,r.title=s,Me.bind(r,"click",(function(){return e.setLanguage(n)})),t.langBttns.appendChild(r)};for(i.s();!(o=i.n()).done;)c()}catch(e){i.e(e)}finally{i.f()}}},{key:"attachActions",value:function(){var e=this,t=this.page;Object.assign(t,Me.idDescendants(Me.idel(document.body,"requiredActions"))),Me.cleanTemplates(t.missingNoncesTmpl,t.actionTxTableTmpl,t.tooCheapTmpl,t.lostNonceTmpl),Me.bind(t.actionsCollapse,"click",(function(){Me.hide(t.actionDialog),Me.show(t.actionDialogCollapsed)})),Me.bind(t.actionDialogCollapsed,"click",(function(){Me.hide(t.actionDialogCollapsed),Me.show(t.actionDialog),0===t.actionDialogContent.children.length&&e.showOldestAction()}));var n=function(t){var n=Object.values(e.requiredActions).filter((function(e){return e.selected}))[0],r=e.sortedActions(),a=r.indexOf(n);e.showRequestedAction(r[a+t].uniqueID)};Me.bind(t.prevAction,"click",(function(){return n(-1)})),Me.bind(t.nextAction,"click",(function(){return n(1)}))}},{key:"setRequiredActions",value:function(){var e=this.user.actions,t=this.requiredActions;if(e){var n,r=vs(e);try{for(r.s();!(n=r.n()).done;){var a=n.value;this.addAction(a)}}catch(e){r.e(e)}finally{r.f()}Object.keys(t).length&&(this.showOldestAction(),this.blinkAction())}}},{key:"sortedActions",value:function(){var e=Object.values(this.requiredActions);return e.sort((function(e,t){return e.stamp-t.stamp})),e}},{key:"showOldestAction",value:function(){this.showRequestedAction(this.sortedActions()[0].uniqueID)}},{key:"addAction",value:function(e){var t=this.page,n=this.requiredActions,r=n[e.uniqueID];if(!r||r.actionID!==e.actionID){var a=this.actionForm(e);if(r)r.selected&&r.div.replaceWith(a),r.div=a;else{n[e.uniqueID]={div:a,stamp:(new Date).getTime(),uniqueID:e.uniqueID,actionID:e.actionID,selected:!1};var o=Object.keys(n).length;t.actionDialogCount.textContent=String(o),t.actionCount.textContent=String(o),Me.isHidden(t.actionDialog)&&this.showRequestedAction(e.uniqueID)}}}},{key:"blinkAction",value:function(){Me.blink(this.page.actionDialog),Me.blink(this.page.actionDialogCollapsed)}},{key:"resolveAction",value:function(e){this.resolveActionWithID(e.uniqueID)}},{key:"resolveActionWithID",value:function(e){var t=this.page,n=this.requiredActions,r=n[e];if(r){delete n[e];var a=Object.keys(n).length;r.div.remove(),0!==a?(t.actionDialogCount.textContent=String(a),t.actionCount.textContent=String(a),r.selected&&this.showOldestAction()):Me.hide(t.actionDialog,t.actionDialogCollapsed)}}},{key:"actionForm",value:function(e){switch(e.actionID){case"tooCheap":return this.tooCheapAction(e);case"missingNonces":return this.missingNoncesAction(e);case"lostNonce":return this.lostNonceAction(e);case"redeemRejected":return this.redeemRejectedAction(e)}throw Error("unknown required action ID "+e.actionID)}},{key:"actionTxTable",value:function(e){var t=e.assetID,n=e.payload,r=this.assets[t],a=r.unitInfo,o=r.token,s=this.page.actionTxTableTmpl.cloneNode(!0),i=Me.parseTemplate(s);i.lostTxID.textContent=n.tx.id,i.lostTxID.dataset.explorerCoin=n.tx.id,zn(o?o.parentID:t,i.lostTxID),i.txAmt.textContent=Me.formatCoinValue(n.tx.amount,a),i.amtUnit.textContent=a.conventional.unit;var c=o?this.unitInfo(o.parentID):a;return i.type.textContent=ta(n.tx.type),i.feeAmount.textContent=Me.formatCoinValue(n.tx.fees,c),i.feeUnit.textContent=c.conventional.unit,"tooCheap"===e.actionID&&(Me.show(i.newFeesRow),i.newFees.textContent=Me.formatCoinValue(n.tx.fees,c),i.newFeesUnit.textContent=c.conventional.unit),s}},{key:"submitAction",value:(p=s(f().mark((function e(t,n,r){var a,o;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return Me.hide(r),a=this.loading(this.page.actionDialog),e.next=4,C("/api/takeaction",{assetID:t.assetID,actionID:t.actionID,action:n});case 4:if(o=e.sent,a(),this.checkResponse(o)){e.next=10;break}return r.textContent=o.msg,Me.show(r),e.abrupt("return");case 10:this.resolveActionWithID(t.uniqueID);case 11:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return p.apply(this,arguments)})},{key:"missingNoncesAction",value:function(e){var t=this,n=e.assetID,r=this.page.missingNoncesTmpl.cloneNode(!0),a=Me.parseTemplate(r),o=this.assets[n].name;return a.assetName.textContent=o,Me.bind(a.doNothingBttn,"click",(function(){t.submitAction(e,{recover:!1},a.errMsg)})),Me.bind(a.recoverBttn,"click",(function(){t.submitAction(e,{recover:!0},a.errMsg)})),r}},{key:"tooCheapAction",value:function(e){var t=this,n=e.assetID,r=e.payload,a=this.page.tooCheapTmpl.cloneNode(!0),o=Me.parseTemplate(a),s=this.assets[n].name;o.assetName.textContent=s,o.txTable.appendChild(this.actionTxTable(e));var i=function(n){t.submitAction(e,{txID:r.tx.id,bump:n},o.errMsg)};return Me.bind(o.keepWaitingBttn,"click",(function(){return i(!1)})),Me.bind(o.addFeesBttn,"click",(function(){return i(!0)})),a}},{key:"lostNonceAction",value:function(e){var t=this,n=e.assetID,r=e.payload,a=this.page.lostNonceTmpl.cloneNode(!0),o=Me.parseTemplate(a),s=this.assets[n].name;return o.assetName.textContent=s,o.nonce.textContent=String(r.nonce),o.txTable.appendChild(this.actionTxTable(e)),Me.bind(o.abandonBttn,"click",(function(){t.submitAction(e,{txID:r.tx.id,abandon:!0},o.errMsg)})),Me.bind(o.keepWaitingBttn,"click",(function(){t.submitAction(e,{txID:r.tx.id,abandon:!1},o.errMsg)})),Me.bind(o.replaceBttn,"click",(function(){var n=o.idInput.value;if(!n)return o.idInput.focus(),void Me.blink(o.idInput);t.submitAction(e,{txID:r.tx.id,abandon:!1,replacementID:n},o.errMsg)})),a}},{key:"redeemRejectedAction",value:function(e){var t=this,n=e.payload,r=n.orderID,a=n.coinID,o=n.coinFmt,s=n.assetID,i=this.page.rejectedRedemptionTmpl.cloneNode(!0),c=Me.parseTemplate(i),l=this.assets[s],u=l.name,d=l.token;return c.assetName.textContent=u,c.txid.textContent=o,c.txid.dataset.explorerCoin=a,zn(d?d.parentID:s,c.txid),Me.bind(c.doNothingBttn,"click",(function(){t.submitAction(e,{orderID:r,coinID:a,retry:!1},c.errMsg)})),Me.bind(c.tryAgainBttn,"click",(function(){t.submitAction(e,{orderID:r,coinID:a,retry:!0},c.errMsg)})),i}},{key:"showRequestedAction",value:function(e){var t=this.page,n=this.requiredActions;Me.hide(t.actionDialogCollapsed);for(var r=0,a=Object.values(n);r2&&t.push(r.id))}}catch(e){n.e(e)}finally{n.f()}t.length&&La.request("acknotes",t),Me.hide(this.page.noteIndicator)}},{key:"setNoteTimes",value:function(e){for(var t=0,n=Array.from(e.children);t0,e.marketsMenuEntry,e.mmLink),e.profileBox.classList.add("authed"),Me.show(e.noteBell,e.walletsMenuEntry,e.marketsMenuEntry),Me.setVis(n,e.mmLink)}}},{key:"fetchNotes",value:(l=s(f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,T("/api/notes");case 2:if(t=e.sent,this.checkResponse(t)){e.next=5;break}return e.abrupt("return",console.error("failed to fetch notes:",(null==t?void 0:t.msg)||String(t)));case 5:t.notes.reverse(),this.setNotes(t.notes),this.setPokes(t.pokes),this.setRequiredActions();case 9:case"end":return e.stop()}}),e,this)}))),function(){return l.apply(this,arguments)})},{key:"attachCommon",value:function(e){this.bindInternalNavigation(e)}},{key:"updateBondConfs",value:function(e,t,n){var r,a=vs(this.exchanges[e].auth.pendingBonds);try{for(a.s();!(r=a.n()).done;){var o=r.value;o.coinID===t&&(o.confs=n)}}catch(e){a.e(e)}finally{a.f()}}},{key:"updateTier",value:function(e,t){this.exchanges[e].auth.rep.bondedTier=t}},{key:"handleBondNote",value:function(e){switch(e.auth&&(this.exchanges[e.dex].auth=e.auth),e.topic){case"RegUpdate":null!==e.coinID&&this.updateBondConfs(e.dex,e.coinID,e.confirmations);break;case"BondConfirmed":null!==e.tier&&this.updateTier(e.dex,e.tier)}}},{key:"handleTransactionNote",value:function(e,t){var n=this.txHistoryMap[e];if(n)if(t.new)n.txs.unshift(t.transaction);else for(var r=0;r5;)o.removeChild(o.firstChild);setTimeout(s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,Me.animate(500,(function(e){i.style.opacity=String(1-e)}));case 2:i.remove(),0===o.children.length&&Me.hide(o);case 4:case"end":return e.stop()}}),e)}))),6e3)}2===e.severity?this.prependPokeElement(e):this.prependNoteElement(e),function(e){ka.apply(this,arguments)}(e)}}},{key:"registerNoteFeeder",value:function(e){this.noteReceivers.push(e)}},{key:"log",value:function(e){for(var t,n=arguments.length,r=new Array(n>1?n-1:0),a=1;a100;)this.pokes.shift();this.prependListElement(this.page.pokeList,r,n)}},{key:"prependNoteElement",value:function(e){var t=a(this.makeNote(e),2),n=t[0],r=t[1];for(this.notes.push(r);this.notes.length>100;)this.notes.shift();var o=this.page.noteList;if(this.prependListElement(o,r,n),this.bindUrlHandlers(n),!(0===this.notes.length||Me.isDisplayed(this.page.noteBox)&&Me.isDisplayed(o))){var s=0,i=this.notes.reduce((function(e,t){return t.acked||s++,!t.acked&&t.severity>e?t.severity:e}),0),c=this.page.noteIndicator;Ts(c,i),s?(c.textContent=String(s>99?"".concat(99,"+"):s),Me.show(c)):Me.hide(c)}}},{key:"prependListElement",value:function(e,t,n){for(n.note=t,e.prepend(n);e.children.length>100;)e.removeChild(e.lastChild);this.setNoteTimes(e)}},{key:"makeNote",value:function(e){var t=this.page.noteTmpl.cloneNode(!0);if(e.severity>2){var n=3===e.severity?"good":4===e.severity?"warn":"bad";Me.safeSelector(t,"div.note-indicator").classList.add(n)}return Me.safeSelector(t,"div.note-subject").textContent=e.subject,Fa(Me.safeSelector(t,"div.note-details"),e.details),[t,fs({el:t},e)]}},{key:"makePoke",value:function(e){var t=this.page.pokeTmpl.cloneNode(!0);return Me.tmplElement(t,"subject").textContent="".concat(e.subject,":"),Fa(Me.tmplElement(t,"details"),e.details),[t,fs({el:t},e)]}},{key:"loading",value:function(e){var t=this.page.loader.cloneNode(!0);return e.appendChild(t),function(){t.remove()}}},{key:"orders",value:function(e,t){var n=[],r=this.user.exchanges[e].markets[t];return r.orders&&(n=n.concat(r.orders)),r.inflight&&(n=n.concat(r.inflight)),n}},{key:"haveActiveOrders",value:function(e){for(var t=0,n=Object.values(this.user.exchanges);t0&&a&&(g[0].id===a?g.shift():console.error("First tx history element != refID")),s.lastTx=g.length { // webpackBootstrap +/******/ "use strict"; +/******/ var __webpack_modules__ = ({ + +/***/ "./src/css/application.scss": +/*!**********************************!*\ + !*** ./src/css/application.scss ***! + \**********************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.r(__webpack_exports__); +// extracted by mini-css-extract-plugin + + +/***/ }), + +/***/ "./src/css/bootstrap.scss": +/*!********************************!*\ + !*** ./src/css/bootstrap.scss ***! + \********************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.r(__webpack_exports__); +// extracted by mini-css-extract-plugin + + +/***/ }), + +/***/ "./src/js/account.ts": +/*!***************************!*\ + !*** ./src/js/account.ts ***! + \***************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "ReputationMeter": () => (/* binding */ ReputationMeter), +/* harmony export */ "bondReserveMultiplier": () => (/* binding */ bondReserveMultiplier), +/* harmony export */ "epochWeight": () => (/* binding */ epochWeight), +/* harmony export */ "likelyTaker": () => (/* binding */ likelyTaker), +/* harmony export */ "parcelLimitScoreMultiplier": () => (/* binding */ parcelLimitScoreMultiplier), +/* harmony export */ "perTierBaseParcelLimit": () => (/* binding */ perTierBaseParcelLimit), +/* harmony export */ "strongTier": () => (/* binding */ strongTier), +/* harmony export */ "tradingLimits": () => (/* binding */ tradingLimits) +/* harmony export */ }); +/* harmony import */ var _doc__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./doc */ "./src/js/doc.ts"); +/* harmony import */ var _orderutil__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./orderutil */ "./src/js/orderutil.ts"); +/* harmony import */ var _registry__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./registry */ "./src/js/registry.ts"); + + + +const bondReserveMultiplier = 2; // Reserves for next bond +const perTierBaseParcelLimit = 2; +const parcelLimitScoreMultiplier = 3; +class ReputationMeter { + constructor(div) { + this.page = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].parseTemplate(div); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].cleanTemplates(this.page.penaltyMarkerTmpl); + } + setHost(host) { + this.host = host; + } + update() { + const { page, host } = this; + const { auth, maxScore, penaltyThreshold } = (0,_registry__WEBPACK_IMPORTED_MODULE_2__.app)().exchanges[host]; + const { rep: { score } } = auth; + const displayTier = strongTier(auth); + const minScore = displayTier ? displayTier * penaltyThreshold * -1 : penaltyThreshold * -1; // Just for looks + const warnPct = 25; + const scorePct = 100 - warnPct; + page.scoreWarn.style.width = `${warnPct}%`; + const pos = score >= 0 ? warnPct + (score / maxScore) * scorePct : warnPct - (Math.min(warnPct, score / minScore * warnPct)); + page.scorePointer.style.left = `${pos}%`; + page.scoreMin.textContent = String(minScore); + page.scoreMax.textContent = String(maxScore); + const bonus = limitBonus(score, maxScore); + page.limitBonus.textContent = bonus.toFixed(1); + for (const m of _doc__WEBPACK_IMPORTED_MODULE_0__["default"].applySelector(page.scoreTray, '.penalty-marker')) + m.remove(); + if (displayTier > 1) { + const markerPct = warnPct / displayTier; + for (let i = 1; i < displayTier; i++) { + const div = page.penaltyMarkerTmpl.cloneNode(true); + page.scoreTray.appendChild(div); + div.style.left = `${markerPct * i}%`; + } + } + page.score.textContent = String(score); + page.scoreData.classList.remove('negative', 'positive'); + if (score > 0) + page.scoreData.classList.add('positive'); + else + page.scoreData.classList.add('negative'); + } +} +/* + * strongTier is the effective tier, with some respect for bond overlap, such + * that we don't count weak bonds that have already had their replacements + * confirmed. + */ +function strongTier(auth) { + const { weakStrength, targetTier, effectiveTier } = auth; + if (effectiveTier > targetTier) { + const diff = effectiveTier - targetTier; + if (weakStrength >= diff) + return targetTier; + return targetTier + (diff - weakStrength); + } + return effectiveTier; +} +function likelyTaker(ord, rate) { + if (ord.type === _orderutil__WEBPACK_IMPORTED_MODULE_1__.OrderTypeMarket || ord.tif === _orderutil__WEBPACK_IMPORTED_MODULE_1__.ImmediateTiF) + return true; + // Must cross the spread to be a taker (not so conservative). + if (rate === 0) + return false; + if (ord.sell) + return ord.rate < rate; + return ord.rate > rate; +} +const preparcelQuantity = (ord, mkt, midGap) => { + var _a, _b; + const qty = ord.qty - ord.filled; + if (ord.type === _orderutil__WEBPACK_IMPORTED_MODULE_1__.OrderTypeLimit) + return qty; + if (ord.sell) + return qty * ord.rate / _orderutil__WEBPACK_IMPORTED_MODULE_1__.RateEncodingFactor; + const rate = midGap || ((_a = mkt === null || mkt === void 0 ? void 0 : mkt.spot) === null || _a === void 0 ? void 0 : _a.rate) || 0; + // Caller should not call this for market orders without a mkt arg. + if (!mkt) + return 0; + // This is tricky. The server will use the mid-gap rate to convert the + // order qty. We don't have a mid-gap rate, only a spot rate. + if (rate && (((_b = mkt === null || mkt === void 0 ? void 0 : mkt.spot) === null || _b === void 0 ? void 0 : _b.bookVolume) || 0) > 0) + return qty * _orderutil__WEBPACK_IMPORTED_MODULE_1__.RateEncodingFactor / rate; + return mkt.lotsize; // server uses same fallback if book is empty +}; +function epochWeight(ord, mkt, midGap) { + var _a; + if (ord.status !== _orderutil__WEBPACK_IMPORTED_MODULE_1__.StatusEpoch) + return 0; + const qty = preparcelQuantity(ord, mkt, midGap); + const rate = midGap || ((_a = mkt.spot) === null || _a === void 0 ? void 0 : _a.rate) || 0; + if (likelyTaker(ord, rate)) + return qty * 2; + return qty; +} +function bookWeight(ord) { + if (ord.status !== _orderutil__WEBPACK_IMPORTED_MODULE_1__.StatusBooked) + return 0; + return preparcelQuantity(ord); +} +function settlingWeight(ord) { + let sum = 0; + for (const m of (ord.matches || [])) { + if (m.side === _orderutil__WEBPACK_IMPORTED_MODULE_1__.MatchSideMaker) { + if (m.status > _orderutil__WEBPACK_IMPORTED_MODULE_1__.MakerRedeemed) + continue; + } + else if (m.status > _orderutil__WEBPACK_IMPORTED_MODULE_1__.TakerSwapCast) + continue; + sum += m.qty; + } + return sum; +} +function parcelWeight(ord, mkt, midGap) { + if (ord.type === _orderutil__WEBPACK_IMPORTED_MODULE_1__.OrderTypeCancel) + return 0; + return epochWeight(ord, mkt, midGap) + bookWeight(ord) + settlingWeight(ord); +} +// function roundParcels (p: number): number { +// return Math.floor(Math.round((p * 1e8)) / 1e8) +// } +function limitBonus(score, maxScore) { + return score > 0 ? 1 + score / maxScore * (parcelLimitScoreMultiplier - 1) : 1; +} +function tradingLimits(host) { + const { auth, maxScore, markets } = (0,_registry__WEBPACK_IMPORTED_MODULE_2__.app)().exchanges[host]; + const { rep: { score } } = auth; + const tier = strongTier(auth); + let usedParcels = 0; + for (const mkt of Object.values(markets)) { + let mktWeight = 0; + for (const ord of (mkt.inflight || [])) + mktWeight += parcelWeight(ord, mkt); + for (const ord of (mkt.orders || [])) + mktWeight += parcelWeight(ord, mkt); + usedParcels += (mktWeight / (mkt.parcelsize * mkt.lotsize)); + } + const parcelLimit = perTierBaseParcelLimit * limitBonus(score, maxScore) * tier; + return [usedParcels, parcelLimit]; +} + + +/***/ }), + +/***/ "./src/js/app.ts": +/*!***********************!*\ + !*** ./src/js/app.ts ***! + \***********************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ Application) +/* harmony export */ }); +/* harmony import */ var _doc__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./doc */ "./src/js/doc.ts"); +/* harmony import */ var _state__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./state */ "./src/js/state.ts"); +/* harmony import */ var _register__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./register */ "./src/js/register.ts"); +/* harmony import */ var _login__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./login */ "./src/js/login.ts"); +/* harmony import */ var _wallets__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./wallets */ "./src/js/wallets.ts"); +/* harmony import */ var _settings__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./settings */ "./src/js/settings.ts"); +/* harmony import */ var _markets__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./markets */ "./src/js/markets.ts"); +/* harmony import */ var _orders__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./orders */ "./src/js/orders.ts"); +/* harmony import */ var _order__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./order */ "./src/js/order.ts"); +/* harmony import */ var _mm__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./mm */ "./src/js/mm.ts"); +/* harmony import */ var _mmsettings__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./mmsettings */ "./src/js/mmsettings.ts"); +/* harmony import */ var _dexsettings__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./dexsettings */ "./src/js/dexsettings.ts"); +/* harmony import */ var _mmarchives__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./mmarchives */ "./src/js/mmarchives.ts"); +/* harmony import */ var _mmlogs__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./mmlogs */ "./src/js/mmlogs.ts"); +/* harmony import */ var _init__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./init */ "./src/js/init.ts"); +/* harmony import */ var _mmutil__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./mmutil */ "./src/js/mmutil.ts"); +/* harmony import */ var _orderutil__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./orderutil */ "./src/js/orderutil.ts"); +/* harmony import */ var _http__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./http */ "./src/js/http.ts"); +/* harmony import */ var _notifications__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./notifications */ "./src/js/notifications.ts"); +/* harmony import */ var _ws__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./ws */ "./src/js/ws.ts"); +/* harmony import */ var _locales__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./locales */ "./src/js/locales.ts"); +/* harmony import */ var _coinexplorers__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./coinexplorers */ "./src/js/coinexplorers.ts"); +var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; + + + + + + + + + + + + + + + + + + + + + + +const idel = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].idel; // = element by id +const bind = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind; +const unbind = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].unbind; +const notificationRoute = 'notify'; +const noteCacheSize = 100; +/* constructors is a map to page constructors. */ +const constructors = { + login: _login__WEBPACK_IMPORTED_MODULE_3__["default"], + register: _register__WEBPACK_IMPORTED_MODULE_2__["default"], + markets: _markets__WEBPACK_IMPORTED_MODULE_6__["default"], + wallets: _wallets__WEBPACK_IMPORTED_MODULE_4__["default"], + settings: _settings__WEBPACK_IMPORTED_MODULE_5__["default"], + orders: _orders__WEBPACK_IMPORTED_MODULE_7__["default"], + order: _order__WEBPACK_IMPORTED_MODULE_8__["default"], + dexsettings: _dexsettings__WEBPACK_IMPORTED_MODULE_11__["default"], + init: _init__WEBPACK_IMPORTED_MODULE_14__["default"], + mm: _mm__WEBPACK_IMPORTED_MODULE_9__["default"], + mmsettings: _mmsettings__WEBPACK_IMPORTED_MODULE_10__["default"], + mmarchives: _mmarchives__WEBPACK_IMPORTED_MODULE_12__["default"], + mmlogs: _mmlogs__WEBPACK_IMPORTED_MODULE_13__["default"] +}; +const languageData = { + 'en-US': { + name: 'English', + flag: '🇺🇸' // Not 🇬🇧. MURICA! + }, + 'pt-BR': { + name: 'Portugese', + flag: '🇧🇷' + }, + 'zh-CN': { + name: 'Chinese', + flag: '🇨🇳' + }, + 'pl-PL': { + name: 'Polish', + flag: '🇵🇱' + }, + 'de-DE': { + name: 'German', + flag: '🇩🇪' + }, + 'ar': { + name: 'Arabic', + flag: '🇪🇬' // Egypt I guess + } +}; +// Application is the main javascript web application for Bison Wallet. +class Application { + constructor() { + this.notes = []; + this.pokes = []; + this.seedGenTime = 0; + this.commitHash = "017099c1a5be1062de357cc615e25b563a1d76ed" || 0; + this.noteReceivers = []; + this.fiatRatesMap = {}; + this.showPopups = _state__WEBPACK_IMPORTED_MODULE_1__["default"].fetchLocal(_state__WEBPACK_IMPORTED_MODULE_1__["default"].popupsLK) === '1'; + this.txHistoryMap = {}; + this.requiredActions = {}; + console.log('Bison Wallet, Build', this.commitHash.substring(0, 7)); + // Set Bootstrap dark theme attribute if dark mode is enabled. + if (_state__WEBPACK_IMPORTED_MODULE_1__["default"].isDark()) { + document.body.classList.add('dark'); + } + // Loggers can be enabled by setting a truthy value to the loggerID using + // enableLogger. Settings are stored across sessions. See docstring for the + // log method for more info. + this.loggers = _state__WEBPACK_IMPORTED_MODULE_1__["default"].fetchLocal(_state__WEBPACK_IMPORTED_MODULE_1__["default"].loggersLK) || {}; + window.enableLogger = (loggerID, state) => { + if (state) + this.loggers[loggerID] = true; + else + delete this.loggers[loggerID]; + _state__WEBPACK_IMPORTED_MODULE_1__["default"].storeLocal(_state__WEBPACK_IMPORTED_MODULE_1__["default"].loggersLK, this.loggers); + return `${loggerID} logger ${state ? 'enabled' : 'disabled'}`; + }; + // Enable logging from anywhere. + window.log = (loggerID, ...a) => { this.log(loggerID, ...a); }; + window.mmStatus = () => this.mmStatus; + // Recorders can record log messages, and then save them to file on request. + const recorderKeys = _state__WEBPACK_IMPORTED_MODULE_1__["default"].fetchLocal(_state__WEBPACK_IMPORTED_MODULE_1__["default"].recordersLK) || []; + this.recorders = {}; + for (const loggerID of recorderKeys) { + console.log('recording', loggerID); + this.recorders[loggerID] = []; + } + window.recordLogger = (loggerID, on) => { + if (on) + this.recorders[loggerID] = []; + else + delete this.recorders[loggerID]; + _state__WEBPACK_IMPORTED_MODULE_1__["default"].storeLocal(_state__WEBPACK_IMPORTED_MODULE_1__["default"].recordersLK, Object.keys(this.recorders)); + return `${loggerID} recorder ${on ? 'enabled' : 'disabled'}`; + }; + window.dumpLogger = loggerID => { + const record = this.recorders[loggerID]; + if (!record) + return `no recorder for logger ${loggerID}`; + const a = document.createElement('a'); + a.href = `data:application/octet-stream;base64,${window.btoa(JSON.stringify(record, null, 4))}`; + a.download = `${loggerID}.json`; + document.body.appendChild(a); + a.click(); + setTimeout(() => { + document.body.removeChild(a); + }, 0); + }; + window.user = () => this.user; + } + /** + * Start the application. This is the only thing done from the index.js entry + * point. Read the id = main element and attach handlers. + */ + start() { + return __awaiter(this, void 0, void 0, function* () { + // Handle back navigation from the browser. + bind(window, 'popstate', (e) => { + var _a; + const page = (_a = e.state) === null || _a === void 0 ? void 0 : _a.page; + if (!page && page !== '') + return; + this.loadPage(page, e.state.data, true); + }); + // The main element is the interchangeable part of the page that doesn't + // include the header. Main should define a data-handler attribute + // associated with one of the available constructors. + this.main = idel(document, 'main'); + const handler = this.main.dataset.handler; + // Don't fetch the user until we know what page we're on. + yield this.fetchUser(); + const ignoreCachedLocale = "development" === 'development'; + yield _locales__WEBPACK_IMPORTED_MODULE_20__.loadLocale(this.lang, this.commitHash, ignoreCachedLocale); + // The application is free to respond with a page that differs from the + // one requested in the omnibox, e.g. routing though a login page. Set the + // current URL state based on the actual page. + const url = new URL(window.location.href); + if (handlerFromPath(url.pathname) !== handler) { + url.pathname = `/${handler}`; + url.search = ''; + window.history.replaceState({ page: handler }, '', url); + } + // Attach stuff. + this.attachHeader(); + this.attachActions(); + this.attachCommon(this.header); + this.attach({}); + // If we are authed, populate notes, otherwise get we'll them from the login + // response. + if (this.authed) + yield this.fetchNotes(); + this.updateMenuItemsDisplay(); + // initialize desktop notifications + _notifications__WEBPACK_IMPORTED_MODULE_18__.fetchDesktopNtfnSettings(); + // Connect the websocket and register the notification route. + _ws__WEBPACK_IMPORTED_MODULE_19__["default"].connect(getSocketURI(), () => this.reconnected()); + _ws__WEBPACK_IMPORTED_MODULE_19__["default"].registerRoute(notificationRoute, (note) => { + this.notify(note); + }); + }); + } + /* + * reconnected is called by the websocket client when a reconnection is made. + */ + reconnected() { + var _a; + if (((_a = this.main) === null || _a === void 0 ? void 0 : _a.dataset.handler) === 'settings') + window.location.assign('/'); + else + window.location.reload(); // This triggers another websocket disconnect/connect (!) + // a fetchUser() and loadPage(window.history.state.page) might work + } + /* + * Fetch and save the user, which is the primary core state that must be + * maintained by the Application. + */ + fetchUser() { + return __awaiter(this, void 0, void 0, function* () { + const resp = yield (0,_http__WEBPACK_IMPORTED_MODULE_17__.getJSON)('/api/user'); + if (!this.checkResponse(resp)) + return; + this.inited = resp.inited; + this.authed = Boolean(resp.user); + this.lang = resp.lang; + this.langs = resp.langs; + this.mmStatus = resp.mmStatus; + if (!resp.user) + return; + const user = resp.user; + this.seedGenTime = user.seedgentime; + this.user = user; + this.assets = user.assets; + this.exchanges = user.exchanges; + this.walletMap = {}; + this.fiatRatesMap = user.fiatRates; + for (const [assetID, asset] of Object.entries(user.assets)) { + if (asset.wallet) { + this.walletMap[assetID] = asset.wallet; + } + } + this.updateMenuItemsDisplay(); + return user; + }); + } + fetchMMStatus() { + return __awaiter(this, void 0, void 0, function* () { + this.mmStatus = yield _mmutil__WEBPACK_IMPORTED_MODULE_15__.MM.status(); + }); + } + /* Load the page from the server. Insert and bind the DOM. */ + loadPage(page, data, skipPush) { + return __awaiter(this, void 0, void 0, function* () { + // Close some menus and tooltips. + this.tooltip.style.left = '-10000px'; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(this.page.noteBox, this.page.profileBox); + // Parse the request. + const url = new URL(`/${page}`, window.location.origin); + const requestedHandler = handlerFromPath(page); + // Fetch and parse the page. + const response = yield window.fetch(url.toString()); + if (!response.ok) + return false; + const html = yield response.text(); + const doc = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].noderize(html); + const main = idel(doc, 'main'); + const delivered = main.dataset.handler; + // Append the request to the page history. + if (!skipPush) { + const path = delivered === requestedHandler ? url.toString() : `/${delivered}`; + window.history.pushState({ page: page, data: data }, '', path); + } + // Insert page and attach handlers. + document.title = doc.title; + this.main.replaceWith(main); + this.main = main; + this.noteReceivers = []; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].empty(this.headerSpace); + this.attach(data); + return true; + }); + } + /* attach binds the common handlers and calls the page constructor. */ + attach(data) { + const handlerID = this.main.dataset.handler; + if (!handlerID) { + console.error('cannot attach to content with no specified handler'); + return; + } + this.attachCommon(this.main); + if (this.loadedPage) + this.loadedPage.unload(); + const constructor = constructors[handlerID]; + if (constructor) + this.loadedPage = new constructor(this.main, data); + else + this.loadedPage = null; + // Bind the tooltips. + this.bindTooltips(this.main); + if (window.isWebview) { + // Bind webview URL handlers + this.bindUrlHandlers(this.main); + } + this.bindUnits(this.main); + } + bindTooltips(ancestor) { + ancestor.querySelectorAll('[data-tooltip]').forEach((el) => { + bind(el, 'mouseenter', () => { + this.tooltip.textContent = el.dataset.tooltip || ''; + const lyt = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].layoutMetrics(el); + let left = lyt.centerX - this.tooltip.offsetWidth / 2; + if (left < 0) + left = 5; + if (left + this.tooltip.offsetWidth > document.body.offsetWidth) { + left = document.body.offsetWidth - this.tooltip.offsetWidth - 5; + } + this.tooltip.style.left = `${left}px`; + this.tooltip.style.top = `${lyt.bodyTop - this.tooltip.offsetHeight - 5}px`; + }); + bind(el, 'mouseleave', () => { + this.tooltip.style.left = '-10000px'; + }); + }); + } + /* + * bindUnits binds a hovering unit selection menu to the value or rate + * display elements. The menu gives users an option to convert the value + * to their preferred units. + */ + bindUnits(main) { + const div = document.createElement('div'); + div.classList.add('position-absolute', 'p-3'); + // div.style.backgroundColor = 'yellow' + const rows = document.createElement('div'); + div.appendChild(rows); + rows.classList.add('body-bg', 'border'); + const addRow = (el, unit, cFactor) => { + const box = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].safeSelector(el, '[data-unit-box]'); + const atoms = parseInt(box.dataset.atoms); + const row = document.createElement('div'); + row.textContent = unit; + rows.appendChild(row); + row.classList.add('p-2', 'hoverbg', 'pointer'); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(row, 'click', () => { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].setText(el, '[data-value]', _doc__WEBPACK_IMPORTED_MODULE_0__["default"].formatFourSigFigs(atoms / cFactor, Math.round(Math.log10(cFactor)))); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].setText(el, '[data-unit]', unit); + }); + }; + for (const el of _doc__WEBPACK_IMPORTED_MODULE_0__["default"].applySelector(main, '[data-conversion-value]')) { + const box = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].safeSelector(el, '[data-unit-box]'); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(box, 'mouseenter', () => { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].empty(rows); + box.appendChild(div); + const lyt = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].layoutMetrics(box); + const assetID = parseInt(box.dataset.assetID); + const { unitInfo: ui } = this.assets[assetID]; + addRow(el, ui.conventional.unit, ui.conventional.conversionFactor); + for (const { unit, conversionFactor } of ui.denominations) + addRow(el, unit, conversionFactor); + addRow(el, ui.atomicUnit, 1); + if (lyt.bodyTop > (div.offsetHeight + this.header.offsetHeight)) { + div.style.bottom = 'calc(100% - 1rem)'; + div.style.top = 'auto'; + } + else { + div.style.top = 'calc(100% - 1rem)'; + div.style.bottom = 'auto'; + } + }); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(box, 'mouseleave', () => div.remove()); + } + } + bindUrlHandlers(ancestor) { + if (!window.openUrl) + return; + for (const link of _doc__WEBPACK_IMPORTED_MODULE_0__["default"].applySelector(ancestor, 'a[target=_blank]')) { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(link, 'click', (e) => { + var _a; + e.preventDefault(); + window.openUrl((_a = link.href) !== null && _a !== void 0 ? _a : ''); + }); + } + } + /* attachHeader attaches the header element, which unlike the main element, + * isn't replaced during page navigation. + */ + attachHeader() { + this.header = idel(document.body, 'header'); + const page = this.page = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].idDescendants(this.header); + this.headerSpace = page.headerSpace; + this.popupNotes = idel(document.body, 'popupNotes'); + this.popupTmpl = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].tmplElement(this.popupNotes, 'note'); + if (this.popupTmpl) + this.popupTmpl.remove(); + else + console.error('popupTmpl element not found'); + this.tooltip = idel(document.body, 'tooltip'); + page.noteTmpl.removeAttribute('id'); + page.noteTmpl.remove(); + page.pokeTmpl.removeAttribute('id'); + page.pokeTmpl.remove(); + page.loader.remove(); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.loader); + bind(page.noteBell, 'click', () => __awaiter(this, void 0, void 0, function* () { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.pokeList); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.noteList); + this.ackNotes(); + page.noteCat.classList.add('active'); + page.pokeCat.classList.remove('active'); + this.showDropdown(page.noteBell, page.noteBox); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.noteIndicator); + for (const note of this.notes) { + if (note.acked) { + note.el.classList.remove('firstview'); + } + } + this.setNoteTimes(page.noteList); + this.setNoteTimes(page.pokeList); + })); + bind(page.burgerIcon, 'click', () => { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.logoutErr); + this.showDropdown(page.burgerIcon, page.profileBox); + }); + bind(page.innerNoteIcon, 'click', () => { _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.noteBox); }); + bind(page.innerBurgerIcon, 'click', () => { _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.profileBox); }); + bind(page.profileSignout, 'click', () => __awaiter(this, void 0, void 0, function* () { return yield this.signOut(); })); + bind(page.pokeCat, 'click', () => { + this.setNoteTimes(page.pokeList); + page.pokeCat.classList.add('active'); + page.noteCat.classList.remove('active'); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.noteList); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.pokeList); + this.ackNotes(); + }); + bind(page.noteCat, 'click', () => { + this.setNoteTimes(page.noteList); + page.noteCat.classList.add('active'); + page.pokeCat.classList.remove('active'); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.pokeList); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.noteList); + this.ackNotes(); + }); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].cleanTemplates(page.langBttnTmpl); + const { name, flag } = languageData[this.lang]; + page.langFlag.textContent = flag; + page.langName.textContent = name; + for (const lang of this.langs) { + if (lang === this.lang) + continue; + const div = page.langBttnTmpl.cloneNode(true); + const { name, flag } = languageData[lang]; + div.textContent = flag; + div.title = name; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(div, 'click', () => this.setLanguage(lang)); + page.langBttns.appendChild(div); + } + } + attachActions() { + const { page } = this; + Object.assign(page, _doc__WEBPACK_IMPORTED_MODULE_0__["default"].idDescendants(_doc__WEBPACK_IMPORTED_MODULE_0__["default"].idel(document.body, 'requiredActions'))); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].cleanTemplates(page.missingNoncesTmpl, page.actionTxTableTmpl, page.tooCheapTmpl, page.lostNonceTmpl); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(page.actionsCollapse, 'click', () => { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.actionDialog); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.actionDialogCollapsed); + }); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(page.actionDialogCollapsed, 'click', () => { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.actionDialogCollapsed); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.actionDialog); + if (page.actionDialogContent.children.length === 0) + this.showOldestAction(); + }); + const showAdjacentAction = (dir) => { + const selected = Object.values(this.requiredActions).filter((r) => r.selected)[0]; + const actions = this.sortedActions(); + const idx = actions.indexOf(selected); + this.showRequestedAction(actions[idx + dir].uniqueID); + }; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(page.prevAction, 'click', () => showAdjacentAction(-1)); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(page.nextAction, 'click', () => showAdjacentAction(1)); + } + setRequiredActions() { + const { user: { actions }, requiredActions } = this; + if (!actions) + return; + for (const a of actions) + this.addAction(a); + if (Object.keys(requiredActions).length) { + this.showOldestAction(); + this.blinkAction(); + } + } + sortedActions() { + const actions = Object.values(this.requiredActions); + actions.sort((a, b) => a.stamp - b.stamp); + return actions; + } + showOldestAction() { + this.showRequestedAction(this.sortedActions()[0].uniqueID); + } + addAction(req) { + const { page, requiredActions } = this; + const existingAction = requiredActions[req.uniqueID]; + if (existingAction && existingAction.actionID === req.actionID) + return; + const div = this.actionForm(req); + if (existingAction) { + if (existingAction.selected) + existingAction.div.replaceWith(div); + existingAction.div = div; + } + else { + requiredActions[req.uniqueID] = { + div, + stamp: (new Date()).getTime(), + uniqueID: req.uniqueID, + actionID: req.actionID, + selected: false + }; + const n = Object.keys(requiredActions).length; + page.actionDialogCount.textContent = String(n); + page.actionCount.textContent = String(n); + if (_doc__WEBPACK_IMPORTED_MODULE_0__["default"].isHidden(page.actionDialog)) { + this.showRequestedAction(req.uniqueID); + } + } + } + blinkAction() { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].blink(this.page.actionDialog); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].blink(this.page.actionDialogCollapsed); + } + resolveAction(req) { + this.resolveActionWithID(req.uniqueID); + } + resolveActionWithID(uniqueID) { + const { page, requiredActions } = this; + const existingAction = requiredActions[uniqueID]; + if (!existingAction) + return; + delete requiredActions[uniqueID]; + const rem = Object.keys(requiredActions).length; + existingAction.div.remove(); + if (rem === 0) { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.actionDialog, page.actionDialogCollapsed); + return; + } + page.actionDialogCount.textContent = String(rem); + page.actionCount.textContent = String(rem); + if (existingAction.selected) + this.showOldestAction(); + } + actionForm(req) { + switch (req.actionID) { + case 'tooCheap': + return this.tooCheapAction(req); + case 'missingNonces': + return this.missingNoncesAction(req); + case 'lostNonce': + return this.lostNonceAction(req); + case 'redeemRejected': + return this.redeemRejectedAction(req); + } + throw Error('unknown required action ID ' + req.actionID); + } + actionTxTable(req) { + const { assetID, payload } = req; + const n = payload; + const { unitInfo: ui, token } = this.assets[assetID]; + const table = this.page.actionTxTableTmpl.cloneNode(true); + const tmpl = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].parseTemplate(table); + tmpl.lostTxID.textContent = n.tx.id; + tmpl.lostTxID.dataset.explorerCoin = n.tx.id; + (0,_coinexplorers__WEBPACK_IMPORTED_MODULE_21__.setCoinHref)(token ? token.parentID : assetID, tmpl.lostTxID); + tmpl.txAmt.textContent = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].formatCoinValue(n.tx.amount, ui); + tmpl.amtUnit.textContent = ui.conventional.unit; + const parentUI = token ? this.unitInfo(token.parentID) : ui; + tmpl.type.textContent = (0,_wallets__WEBPACK_IMPORTED_MODULE_4__.txTypeString)(n.tx.type); + tmpl.feeAmount.textContent = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].formatCoinValue(n.tx.fees, parentUI); + tmpl.feeUnit.textContent = parentUI.conventional.unit; + switch (req.actionID) { + case 'tooCheap': { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(tmpl.newFeesRow); + tmpl.newFees.textContent = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].formatCoinValue(n.tx.fees, parentUI); + tmpl.newFeesUnit.textContent = parentUI.conventional.unit; + break; + } + } + return table; + } + submitAction(req, action, errMsg) { + return __awaiter(this, void 0, void 0, function* () { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(errMsg); + const loading = this.loading(this.page.actionDialog); + const res = yield (0,_http__WEBPACK_IMPORTED_MODULE_17__.postJSON)('/api/takeaction', { + assetID: req.assetID, + actionID: req.actionID, + action + }); + loading(); + if (!this.checkResponse(res)) { + errMsg.textContent = res.msg; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(errMsg); + return; + } + this.resolveActionWithID(req.uniqueID); + }); + } + missingNoncesAction(req) { + const { assetID } = req; + const div = this.page.missingNoncesTmpl.cloneNode(true); + const tmpl = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].parseTemplate(div); + const { name } = this.assets[assetID]; + tmpl.assetName.textContent = name; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(tmpl.doNothingBttn, 'click', () => { + this.submitAction(req, { recover: false }, tmpl.errMsg); + }); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(tmpl.recoverBttn, 'click', () => { + this.submitAction(req, { recover: true }, tmpl.errMsg); + }); + return div; + } + tooCheapAction(req) { + const { assetID, payload } = req; + const n = payload; + const div = this.page.tooCheapTmpl.cloneNode(true); + const tmpl = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].parseTemplate(div); + const { name } = this.assets[assetID]; + tmpl.assetName.textContent = name; + tmpl.txTable.appendChild(this.actionTxTable(req)); + const act = (bump) => { + this.submitAction(req, { + txID: n.tx.id, + bump + }, tmpl.errMsg); + }; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(tmpl.keepWaitingBttn, 'click', () => act(false)); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(tmpl.addFeesBttn, 'click', () => act(true)); + return div; + } + lostNonceAction(req) { + const { assetID, payload } = req; + const n = payload; + const div = this.page.lostNonceTmpl.cloneNode(true); + const tmpl = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].parseTemplate(div); + const { name } = this.assets[assetID]; + tmpl.assetName.textContent = name; + tmpl.nonce.textContent = String(n.nonce); + tmpl.txTable.appendChild(this.actionTxTable(req)); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(tmpl.abandonBttn, 'click', () => { + this.submitAction(req, { txID: n.tx.id, abandon: true }, tmpl.errMsg); + }); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(tmpl.keepWaitingBttn, 'click', () => { + this.submitAction(req, { txID: n.tx.id, abandon: false }, tmpl.errMsg); + }); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(tmpl.replaceBttn, 'click', () => { + const replacementID = tmpl.idInput.value; + if (!replacementID) { + tmpl.idInput.focus(); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].blink(tmpl.idInput); + return; + } + this.submitAction(req, { txID: n.tx.id, abandon: false, replacementID }, tmpl.errMsg); + }); + return div; + } + redeemRejectedAction(req) { + const { orderID, coinID, coinFmt, assetID } = req.payload; + const div = this.page.rejectedRedemptionTmpl.cloneNode(true); + const tmpl = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].parseTemplate(div); + const { name, token } = this.assets[assetID]; + tmpl.assetName.textContent = name; + tmpl.txid.textContent = coinFmt; + tmpl.txid.dataset.explorerCoin = coinID; + (0,_coinexplorers__WEBPACK_IMPORTED_MODULE_21__.setCoinHref)(token ? token.parentID : assetID, tmpl.txid); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(tmpl.doNothingBttn, 'click', () => { + this.submitAction(req, { orderID, coinID, retry: false }, tmpl.errMsg); + }); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(tmpl.tryAgainBttn, 'click', () => { + this.submitAction(req, { orderID, coinID, retry: true }, tmpl.errMsg); + }); + return div; + } + showRequestedAction(uniqueID) { + const { page, requiredActions } = this; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.actionDialogCollapsed); + for (const r of Object.values(requiredActions)) + r.selected = r.uniqueID === uniqueID; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].empty(page.actionDialogContent); + const action = requiredActions[uniqueID]; + page.actionDialogContent.appendChild(action.div); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.actionDialog); + const actions = this.sortedActions(); + if (actions.length === 1) { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.actionsNavigator); + return; + } + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.actionsNavigator); + const idx = actions.indexOf(action); + page.currentAction.textContent = String(idx + 1); + page.prevAction.classList.toggle('invisible', idx === 0); + page.nextAction.classList.toggle('invisible', idx === actions.length - 1); + } + /* + * updateMarketElements sets the textContent for any ticker or asset name + * elements or any asset logo src attributes for descendents of ancestor. + */ + updateMarketElements(ancestor, baseID, quoteID, xc) { + const getAsset = (assetID) => { + const a = this.assets[assetID]; + if (a) + return a; + if (!xc) + throw Error(`no asset found for asset ID ${assetID}`); + const xcAsset = xc.assets[assetID]; + return { unitInfo: xcAsset.unitInfo, name: xcAsset.symbol, symbol: xcAsset.symbol }; + }; + const { unitInfo: bui, name: baseName, symbol: baseSymbol } = getAsset(baseID); + for (const el of _doc__WEBPACK_IMPORTED_MODULE_0__["default"].applySelector(ancestor, '[data-base-name')) + el.textContent = baseName; + for (const img of _doc__WEBPACK_IMPORTED_MODULE_0__["default"].applySelector(ancestor, '[data-base-logo]')) + img.src = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].logoPath(baseSymbol); + for (const el of _doc__WEBPACK_IMPORTED_MODULE_0__["default"].applySelector(ancestor, '[data-base-ticker]')) + el.textContent = bui.conventional.unit; + const { unitInfo: qui, name: quoteName, symbol: quoteSymbol } = getAsset(quoteID); + for (const el of _doc__WEBPACK_IMPORTED_MODULE_0__["default"].applySelector(ancestor, '[data-quote-name')) + el.textContent = quoteName; + for (const img of _doc__WEBPACK_IMPORTED_MODULE_0__["default"].applySelector(ancestor, '[data-quote-logo]')) + img.src = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].logoPath(quoteSymbol); + for (const el of _doc__WEBPACK_IMPORTED_MODULE_0__["default"].applySelector(ancestor, '[data-quote-ticker]')) + el.textContent = qui.conventional.unit; + } + setLanguage(lang) { + return __awaiter(this, void 0, void 0, function* () { + yield (0,_http__WEBPACK_IMPORTED_MODULE_17__.postJSON)('/api/setlocale', lang); + window.location.reload(); + }); + } + /* + * showDropdown sets the position and visibility of the specified dropdown + * dialog according to the position of its icon button. + */ + showDropdown(icon, dialog) { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(this.page.noteBox, this.page.profileBox); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(dialog); + if (window.innerWidth < 500) + Object.assign(dialog.style, { left: '0', right: '0', top: '0' }); + else { + const ico = icon.getBoundingClientRect(); + const right = `${window.innerWidth - ico.left - ico.width + 5}px`; + Object.assign(dialog.style, { left: 'auto', right, top: `${ico.top - 4}px` }); + } + const hide = (e) => { + if (!_doc__WEBPACK_IMPORTED_MODULE_0__["default"].mouseInElement(e, dialog)) { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(dialog); + unbind(document, 'click', hide); + if (dialog === this.page.noteBox && _doc__WEBPACK_IMPORTED_MODULE_0__["default"].isDisplayed(this.page.noteList)) { + this.ackNotes(); + } + } + }; + bind(document, 'click', hide); + } + ackNotes() { + const acks = []; + for (const note of this.notes) { + if (note.acked) { + note.el.classList.remove('firstview'); + } + else { + note.acked = true; + if (note.id && note.severity > _notifications__WEBPACK_IMPORTED_MODULE_18__.POKE) + acks.push(note.id); + } + } + if (acks.length) + _ws__WEBPACK_IMPORTED_MODULE_19__["default"].request('acknotes', acks); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(this.page.noteIndicator); + } + setNoteTimes(noteList) { + for (const el of Array.from(noteList.children)) { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].safeSelector(el, 'span.note-time').textContent = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].timeSince(el.note.stamp); + } + } + /* + * bindInternalNavigation hijacks navigation by click on any local links that + * are descendants of ancestor. + */ + bindInternalNavigation(ancestor) { + const pageURL = new URL(window.location.href); + ancestor.querySelectorAll('a').forEach(a => { + if (!a.href) + return; + const url = new URL(a.href); + if (url.origin === pageURL.origin) { + const token = url.pathname.substring(1); + const params = {}; + if (url.search) { + url.searchParams.forEach((v, k) => { + params[k] = v; + }); + } + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(a, 'click', (e) => { + e.preventDefault(); + this.loadPage(token, params); + }); + } + }); + } + /* + * updateMenuItemsDisplay should be called when the user has signed in or out, + * and when the user registers a DEX. + */ + updateMenuItemsDisplay() { + const { page, authed, mmStatus } = this; + if (!page) { + // initial page load, header elements not yet attached but menu items + // would already be hidden/displayed as appropriate. + return; + } + if (!authed) { + page.profileBox.classList.remove('authed'); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.noteBell, page.walletsMenuEntry, page.marketsMenuEntry); + return; + } + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].setVis(Object.keys(this.exchanges).length > 0, page.marketsMenuEntry, page.mmLink); + page.profileBox.classList.add('authed'); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.noteBell, page.walletsMenuEntry, page.marketsMenuEntry); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].setVis(mmStatus, page.mmLink); + } + fetchNotes() { + return __awaiter(this, void 0, void 0, function* () { + const res = yield (0,_http__WEBPACK_IMPORTED_MODULE_17__.getJSON)('/api/notes'); + if (!this.checkResponse(res)) + return console.error('failed to fetch notes:', (res === null || res === void 0 ? void 0 : res.msg) || String(res)); + res.notes.reverse(); + this.setNotes(res.notes); + this.setPokes(res.pokes); + this.setRequiredActions(); + }); + } + /* attachCommon scans the provided node and handles some common bindings. */ + attachCommon(node) { + this.bindInternalNavigation(node); + } + /* + * updateBondConfs updates the information for a pending bond. + */ + updateBondConfs(dexAddr, coinID, confs) { + const dex = this.exchanges[dexAddr]; + for (const bond of dex.auth.pendingBonds) + if (bond.coinID === coinID) + bond.confs = confs; + } + updateTier(host, bondedTier) { + this.exchanges[host].auth.rep.bondedTier = bondedTier; + } + /* + * handleBondNote is the handler for the 'bondpost'-type notification, which + * is used to update the dex tier and registration status. + */ + handleBondNote(note) { + if (note.auth) + this.exchanges[note.dex].auth = note.auth; + switch (note.topic) { + case 'RegUpdate': + if (note.coinID !== null) { // should never be null for RegUpdate + this.updateBondConfs(note.dex, note.coinID, note.confirmations); + } + break; + case 'BondConfirmed': + if (note.tier !== null) { // should never be null for BondConfirmed + this.updateTier(note.dex, note.tier); + } + break; + default: + break; + } + } + /* + * handleTransaction either adds a new transaction to the transaction history + * or updates an existing transaction. + */ + handleTransactionNote(assetID, note) { + const txHistory = this.txHistoryMap[assetID]; + if (!txHistory) + return; + if (note.new) { + txHistory.txs.unshift(note.transaction); + return; + } + for (let i = 0; i < txHistory.txs.length; i++) { + if (txHistory.txs[i].id === note.transaction.id) { + txHistory.txs[i] = note.transaction; + break; + } + } + } + handleTxHistorySyncedNote(assetID) { + delete this.txHistoryMap[assetID]; + } + loggedIn(notes, pokes) { + this.setNotes(notes); + this.setPokes(pokes); + this.setRequiredActions(); + } + /* + * setNotes sets the current notification cache and populates the notification + * display. + */ + setNotes(notes) { + this.log('notes', 'setNotes', notes); + this.notes = []; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].empty(this.page.noteList); + for (let i = 0; i < notes.length; i++) { + this.prependNoteElement(notes[i]); + } + } + /* + * setPokes sets the current poke cache and populates the pokes display. + */ + setPokes(pokes) { + this.log('pokes', 'setPokes', pokes); + this.pokes = []; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].empty(this.page.pokeList); + for (let i = 0; i < pokes.length; i++) { + this.prependPokeElement(pokes[i]); + } + } + botStatus(host, baseID, quoteID) { + var _a, _b; + for (const bot of ((_b = (_a = this.mmStatus) === null || _a === void 0 ? void 0 : _a.bots) !== null && _b !== void 0 ? _b : [])) { + const { config: c } = bot; + if (host === c.host && baseID === c.baseID && quoteID === c.quoteID) { + return bot; + } + } + } + updateUser(note) { + const { user, assets, walletMap } = this; + if (note.type === 'fiatrateupdate') { + this.fiatRatesMap = note.fiatRates; + return; + } + // Some notes can be received before we get a User during login. + if (!user) + return; + switch (note.type) { + case 'order': { + const orderNote = note; + const order = orderNote.order; + const mkt = user.exchanges[order.host].markets[order.market]; + const tempID = orderNote.tempID; + // Ensure market's inflight orders list is updated. + if (note.topic === 'AsyncOrderSubmitted') { + const inFlight = order; + inFlight.tempID = tempID; + if (!mkt.inflight) + mkt.inflight = [inFlight]; + else + mkt.inflight.push(inFlight); + break; + } + else if (note.topic === 'AsyncOrderFailure') { + mkt.inflight = mkt.inflight.filter(ord => ord.tempID !== tempID); + break; + } + else { + for (const i in mkt.inflight || []) { + if (!(mkt.inflight[i].tempID === tempID)) + continue; + mkt.inflight = mkt.inflight.filter(ord => ord.tempID !== tempID); + break; + } + } + // Updates given order in market's orders list if it finds it. + // Returns a bool which indicates if order was found. + mkt.orders = mkt.orders || []; + const updateOrder = (mkt, ord) => { + const i = mkt.orders.findIndex((o) => o.id === ord.id); + if (i === -1) + return false; + if (note.topic === 'OrderRetired') + mkt.orders.splice(i, 1); + else + mkt.orders[i] = ord; + return true; + }; + // If the notification order already exists we update it. + // In case market's orders list is empty or the notification order isn't + // part of it we add it manually as this means the order was + // just placed. + if (!updateOrder(mkt, order)) + mkt.orders.push(order); + break; + } + case 'balance': { + const n = note; + const asset = user.assets[n.assetID]; + // Balance updates can come before the user is fetched after login. + if (!asset) + break; + const w = asset.wallet; + if (w) + w.balance = n.balance; + break; + } + case 'bondpost': + this.handleBondNote(note); + break; + case 'reputation': { + const n = note; + this.exchanges[n.host].auth.rep = n.rep; + break; + } + case 'walletstate': + case 'walletconfig': { + // assets can be null if failed to connect to dex server. + if (!assets) + return; + const wallet = note === null || note === void 0 ? void 0 : note.wallet; + if (!wallet) + return; + const asset = assets[wallet.assetID]; + asset.wallet = wallet; + walletMap[wallet.assetID] = wallet; + break; + } + case 'walletsync': { + const n = note; + const w = this.walletMap[n.assetID]; + if (w) { + w.syncStatus = n.syncStatus; + w.synced = w.syncStatus.synced; + w.syncProgress = n.syncProgress; + } + break; + } + case 'match': { + const n = note; + const ord = this.order(n.orderID); + if (ord) + updateMatch(ord, n.match); + break; + } + case 'conn': { + const n = note; + const xc = user.exchanges[n.host]; + if (xc) + xc.connectionStatus = n.connectionStatus; + break; + } + case 'spots': { + const n = note; + const xc = user.exchanges[n.host]; + // Spots can come before the user is fetched after login and before/while the + // markets page reload when it receives a dex conn note. + if (!xc || !xc.markets) + break; + for (const [mktName, spot] of Object.entries(n.spots)) + xc.markets[mktName].spot = spot; + break; + } + case 'fiatrateupdate': { + this.fiatRatesMap = note.fiatRates; + break; + } + case 'actionrequired': { + const n = note; + this.addAction(n.payload); + break; + } + case 'walletnote': { + const n = note; + switch (n.payload.route) { + case 'transaction': { + const txNote = n.payload; + this.handleTransactionNote(n.payload.assetID, txNote); + break; + } + case 'actionRequired': { + const req = n.payload; + this.addAction(req); + this.blinkAction(); + break; + } + case 'actionResolved': { + this.resolveAction(n.payload); + } + } + if (n.payload.route === 'transactionHistorySynced') { + this.handleTxHistorySyncedNote(n.payload.assetID); + } + break; + } + case 'runstats': { + this.log('mm', { runstats: note }); + const n = note; + const bot = this.botStatus(n.host, n.baseID, n.quoteID); + if (bot) { + bot.runStats = n.stats; + bot.running = Boolean(n.stats); + if (!n.stats) { + bot.latestEpoch = undefined; + bot.cexProblems = undefined; + } + } + break; + } + case 'cexnote': { + const n = note; + switch (n.topic) { + case 'BalanceUpdate': { + const u = n.note; + this.mmStatus.cexes[n.cexName].balances[u.assetID] = u.balance; + } + } + break; + } + case 'epochreport': { + const n = note; + const bot = this.botStatus(n.host, n.baseID, n.quoteID); + if (bot) + bot.latestEpoch = n.report; + break; + } + case 'cexproblems': { + const n = note; + const bot = this.botStatus(n.host, n.baseID, n.quoteID); + if (bot) + bot.cexProblems = n.problems; + break; + } + } + } + /* + * notify is the top-level handler for notifications received from the client. + * Notifications are propagated to the loadedPage. + */ + notify(note) { + // Handle type-specific updates. + this.log('notes', 'notify', note); + this.updateUser(note); + // Inform the page. + for (const feeder of this.noteReceivers) { + const f = feeder[note.type]; + if (!f) + continue; + try { + f(note); + } + catch (error) { + console.error('note feeder error:', error.message ? error.message : error); + console.log(note); + console.log(error.stack); + } + } + // Discard data notifications. + if (note.severity < _notifications__WEBPACK_IMPORTED_MODULE_18__.POKE) + return; + // Poke notifications have their own display. + const { popupTmpl, popupNotes, showPopups } = this; + if (showPopups) { + const span = popupTmpl.cloneNode(true); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].tmplElement(span, 'text').textContent = `${note.subject}: ${_notifications__WEBPACK_IMPORTED_MODULE_18__.plainNote(note.details)}`; + const indicator = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].tmplElement(span, 'indicator'); + if (note.severity === _notifications__WEBPACK_IMPORTED_MODULE_18__.POKE) { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(indicator); + } + else + setSeverityClass(indicator, note.severity); + popupNotes.appendChild(span); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(popupNotes); + // These take up screen space. Only show max 5 at a time. + while (popupNotes.children.length > 5) + popupNotes.removeChild(popupNotes.firstChild); + setTimeout(() => __awaiter(this, void 0, void 0, function* () { + yield _doc__WEBPACK_IMPORTED_MODULE_0__["default"].animate(500, (progress) => { + span.style.opacity = String(1 - progress); + }); + span.remove(); + if (popupNotes.children.length === 0) + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(popupNotes); + }), 6000); + } + // Success and higher severity go to the bell dropdown. + if (note.severity === _notifications__WEBPACK_IMPORTED_MODULE_18__.POKE) + this.prependPokeElement(note); + else + this.prependNoteElement(note); + // show desktop notification + _notifications__WEBPACK_IMPORTED_MODULE_18__.desktopNotify(note); + } + /* + * registerNoteFeeder registers a feeder for core notifications. The feeder + * will be de-registered when a new page is loaded. + */ + registerNoteFeeder(receivers) { + this.noteReceivers.push(receivers); + } + /* + * log prints to the console if a logger has been enabled. Loggers are created + * implicitly by passing a loggerID to log. i.e. you don't create a logger, + * you just log to it. Loggers are enabled by invoking a global function, + * enableLogger(loggerID, onOffBoolean), from the browser's js console. Your + * choices are stored across sessions. Some common and useful loggers are + * listed below, but this list is not meant to be comprehensive. + * + * LoggerID Description + * -------- ----------- + * notes Notifications of all levels. + * book Order book feed. + * ws.........Websocket connection status changes. + */ + log(loggerID, ...msg) { + if (this.loggers[loggerID]) + console.log(`${nowString()}[${loggerID}]:`, ...msg); + if (this.recorders[loggerID]) { + this.recorders[loggerID].push({ + time: nowString(), + msg: msg + }); + } + } + prependPokeElement(cn) { + const [el, note] = this.makePoke(cn); + this.pokes.push(note); + while (this.pokes.length > noteCacheSize) + this.pokes.shift(); + this.prependListElement(this.page.pokeList, note, el); + } + prependNoteElement(cn) { + const [el, note] = this.makeNote(cn); + this.notes.push(note); + while (this.notes.length > noteCacheSize) + this.notes.shift(); + const noteList = this.page.noteList; + this.prependListElement(noteList, note, el); + this.bindUrlHandlers(el); + // Set the indicator color. + if (this.notes.length === 0 || (_doc__WEBPACK_IMPORTED_MODULE_0__["default"].isDisplayed(this.page.noteBox) && _doc__WEBPACK_IMPORTED_MODULE_0__["default"].isDisplayed(noteList))) + return; + let unacked = 0; + const severity = this.notes.reduce((s, note) => { + if (!note.acked) + unacked++; + if (!note.acked && note.severity > s) + return note.severity; + return s; + }, _notifications__WEBPACK_IMPORTED_MODULE_18__.IGNORE); + const ni = this.page.noteIndicator; + setSeverityClass(ni, severity); + if (unacked) { + ni.textContent = String((unacked > noteCacheSize - 1) ? `${noteCacheSize - 1}+` : unacked); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(ni); + } + else + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(ni); + } + prependListElement(noteList, note, el) { + el.note = note; + noteList.prepend(el); + while (noteList.children.length > noteCacheSize) + noteList.removeChild(noteList.lastChild); + this.setNoteTimes(noteList); + } + /* + * makeNote constructs a single notification element for the drop-down + * notification list. + */ + makeNote(note) { + const el = this.page.noteTmpl.cloneNode(true); + if (note.severity > _notifications__WEBPACK_IMPORTED_MODULE_18__.POKE) { + const cls = note.severity === _notifications__WEBPACK_IMPORTED_MODULE_18__.SUCCESS ? 'good' : note.severity === _notifications__WEBPACK_IMPORTED_MODULE_18__.WARNING ? 'warn' : 'bad'; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].safeSelector(el, 'div.note-indicator').classList.add(cls); + } + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].safeSelector(el, 'div.note-subject').textContent = note.subject; + _notifications__WEBPACK_IMPORTED_MODULE_18__.insertRichNote(_doc__WEBPACK_IMPORTED_MODULE_0__["default"].safeSelector(el, 'div.note-details'), note.details); + const np = Object.assign({ el }, note); + return [el, np]; + } + makePoke(note) { + const el = this.page.pokeTmpl.cloneNode(true); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].tmplElement(el, 'subject').textContent = `${note.subject}:`; + _notifications__WEBPACK_IMPORTED_MODULE_18__.insertRichNote(_doc__WEBPACK_IMPORTED_MODULE_0__["default"].tmplElement(el, 'details'), note.details); + const np = Object.assign({ el }, note); + return [el, np]; + } + /* + * loading appends the loader to the specified element and displays the + * loading icon. The loader will block all interaction with the specified + * element until Application.loaded is called. + */ + loading(el) { + const loader = this.page.loader.cloneNode(true); + el.appendChild(loader); + return () => { loader.remove(); }; + } + /* orders retrieves a list of orders for the specified dex and market + * including inflight orders. + */ + orders(host, mktID) { + let orders = []; + const mkt = this.user.exchanges[host].markets[mktID]; + if (mkt.orders) + orders = orders.concat(mkt.orders); + if (mkt.inflight) + orders = orders.concat(mkt.inflight); + return orders; + } + /* + * haveActiveOrders returns whether or not there are active orders involving a + * certain asset. + */ + haveActiveOrders(assetID) { + for (const xc of Object.values(this.user.exchanges)) { + if (!xc.markets) + continue; + for (const market of Object.values(xc.markets)) { + if (!market.orders) + continue; + for (const ord of market.orders) { + if ((ord.baseID === assetID || ord.quoteID === assetID) && + (ord.status < _orderutil__WEBPACK_IMPORTED_MODULE_16__.StatusExecuted || (0,_orderutil__WEBPACK_IMPORTED_MODULE_16__.hasActiveMatches)(ord))) + return true; + } + } + } + return false; + } + /* order attempts to locate an order by order ID. */ + order(oid) { + for (const xc of Object.values(this.user.exchanges)) { + if (!xc || !xc.markets) + continue; + for (const market of Object.values(xc.markets)) { + if (!market.orders) + continue; + for (const ord of market.orders) { + if (ord.id === oid) + return ord; + } + } + } + return null; + } + /* + * canAccelerateOrder returns true if the "from" wallet of the order + * supports acceleration, and if the order has unconfirmed swap + * transactions. + */ + canAccelerateOrder(order) { + var _a; + const walletTraitAccelerator = 1 << 4; + let fromAssetID; + if (order.sell) + fromAssetID = order.baseID; + else + fromAssetID = order.quoteID; + const wallet = this.walletMap[fromAssetID]; + if (!wallet || !(wallet.traits & walletTraitAccelerator)) + return false; + if (order.matches) { + for (let i = 0; i < ((_a = order.matches) === null || _a === void 0 ? void 0 : _a.length); i++) { + const match = order.matches[i]; + if (match.swap && match.swap.confs && match.swap.confs.count === 0 && !match.revoked) { + return true; + } + } + } + return false; + } + /* + * unitInfo fetches unit info [dex.UnitInfo] for the asset. If xc + * [core.Exchange] is provided, and this is not a SupportedAsset, the UnitInfo + * sent from the exchange's assets map [dex.Asset] will be used. + */ + unitInfo(assetID, xc) { + const supportedAsset = this.assets[assetID]; + if (supportedAsset) + return supportedAsset.unitInfo; + if (!xc || !xc.assets) { + throw Error(_locales__WEBPACK_IMPORTED_MODULE_20__.prep(_locales__WEBPACK_IMPORTED_MODULE_20__.ID_UNSUPPORTED_ASSET_INFO_ERR_MSG, { assetID: `${assetID}` })); + } + return xc.assets[assetID].unitInfo; + } + parentAsset(assetID) { + const asset = this.assets[assetID]; + if (!asset.token) + return asset; + return this.assets[asset.token.parentID]; + } + /* + * baseChainSymbol returns the symbol for the asset's parent if the asset is a + * token, otherwise the symbol for the asset itself. + */ + baseChainSymbol(assetID) { + const asset = this.user.assets[assetID]; + return asset.token ? this.user.assets[asset.token.parentID].symbol : asset.symbol; + } + /* + * extensionWallet returns the ExtensionConfiguredWallet for the asset, if + * it exists. + */ + extensionWallet(assetID) { + var _a; + return (_a = this.user.extensionModeConfig) === null || _a === void 0 ? void 0 : _a.restrictedWallets[this.baseChainSymbol(assetID)]; + } + /* conventionalRate converts the encoded atomic rate to a conventional rate */ + conventionalRate(baseID, quoteID, encRate, xc) { + const [b, q] = [this.unitInfo(baseID, xc), this.unitInfo(quoteID, xc)]; + const r = b.conventional.conversionFactor / q.conventional.conversionFactor; + return encRate * r / _orderutil__WEBPACK_IMPORTED_MODULE_16__.RateEncodingFactor; + } + walletDefinition(assetID, walletType) { + const asset = this.assets[assetID]; + if (asset.token) + return asset.token.definition; + if (!asset.info) + throw Error('where\'s the wallet info?'); + if (walletType === '') + return asset.info.availablewallets[asset.info.emptyidx]; + return asset.info.availablewallets.filter(def => def.type === walletType)[0]; + } + currentWalletDefinition(assetID) { + const asset = this.assets[assetID]; + if (asset.token) { + return asset.token.definition; + } + return this.walletDefinition(assetID, this.assets[assetID].wallet.type); + } + /* + * fetchBalance requests a balance update from the API. The API response does + * include the balance, but we're ignoring it, since a balance update + * notification is received via the Application anyways. + */ + fetchBalance(assetID) { + return __awaiter(this, void 0, void 0, function* () { + const res = yield (0,_http__WEBPACK_IMPORTED_MODULE_17__.postJSON)('/api/balance', { assetID: assetID }); + if (!this.checkResponse(res)) { + throw new Error(`failed to fetch balance for asset ID ${assetID}`); + } + return res.balance; + }); + } + /* + * checkResponse checks the response object as returned from the functions in + * the http module. If the response indicates that the request failed, it + * returns false, otherwise, true. + */ + checkResponse(resp) { + return (resp.requestSuccessful && resp.ok); + } + /** + * signOut call to /api/logout, if response with no errors occurred remove auth + * and other privacy-critical cookies/locals and reload the page, otherwise + * show a notification. + */ + signOut() { + return __awaiter(this, void 0, void 0, function* () { + const res = yield (0,_http__WEBPACK_IMPORTED_MODULE_17__.postJSON)('/api/logout'); + if (!this.checkResponse(res)) { + if (res.code === _http__WEBPACK_IMPORTED_MODULE_17__.Errors.activeOrdersErr) { + this.page.logoutErr.textContent = _locales__WEBPACK_IMPORTED_MODULE_20__.prep(_locales__WEBPACK_IMPORTED_MODULE_20__.ID_ACTIVE_ORDERS_LOGOUT_ERR_MSG); + } + else { + this.page.logoutErr.textContent = res.msg; + } + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(this.page.logoutErr); + return; + } + _state__WEBPACK_IMPORTED_MODULE_1__["default"].removeCookie(_state__WEBPACK_IMPORTED_MODULE_1__["default"].authCK); + _state__WEBPACK_IMPORTED_MODULE_1__["default"].removeCookie(_state__WEBPACK_IMPORTED_MODULE_1__["default"].pwKeyCK); + _state__WEBPACK_IMPORTED_MODULE_1__["default"].removeLocal(_state__WEBPACK_IMPORTED_MODULE_1__["default"].notificationsLK); // Notification storage was DEPRECATED pre-v1. + window.location.href = '/login'; + }); + } + /* + * txHistory loads the tx history for an asset. If the results are not + * already cached, they are cached. If we have reached the oldest tx, + * this fact is also cached. If the exact amount of transactions as have been + * made are requested, we will not know if we have reached the last tx until + * a subsequent call. + */ + txHistory(assetID, n, after) { + return __awaiter(this, void 0, void 0, function* () { + const url = '/api/txhistory'; + const cachedTxHistory = this.txHistoryMap[assetID]; + if (!cachedTxHistory) { + const res = yield (0,_http__WEBPACK_IMPORTED_MODULE_17__.postJSON)(url, { + n: n, + assetID: assetID + }); + if (!this.checkResponse(res)) { + throw new Error(res.msg); + } + let txs = res.txs; + if (!txs) { + txs = []; + } + this.txHistoryMap[assetID] = { + txs: txs, + lastTx: txs.length < n + }; + return this.txHistoryMap[assetID]; + } + const txs = []; + let lastTx = false; + const startIndex = after ? cachedTxHistory.txs.findIndex(tx => tx.id === after) + 1 : 0; + if (after && startIndex === -1) { + throw new Error('invalid after tx ' + after); + } + let lastIndex = startIndex; + for (let i = startIndex; i < cachedTxHistory.txs.length && txs.length < n; i++) { + txs.push(cachedTxHistory.txs[i]); + lastIndex = i; + after = cachedTxHistory.txs[i].id; + } + if (cachedTxHistory.lastTx && lastIndex === cachedTxHistory.txs.length - 1) { + lastTx = true; + } + if (txs.length < n && !cachedTxHistory.lastTx) { + const res = yield (0,_http__WEBPACK_IMPORTED_MODULE_17__.postJSON)(url, { + n: n - txs.length + 1, + assetID: assetID, + refID: after, + past: true + }); + if (!this.checkResponse(res)) { + throw new Error(res.msg); + } + let resTxs = res.txs; + if (!resTxs) { + resTxs = []; + } + if (resTxs.length > 0 && after) { + if (resTxs[0].id === after) { + resTxs.shift(); + } + else { + // Implies a bug in the client + console.error('First tx history element != refID'); + } + } + cachedTxHistory.lastTx = resTxs.length < n - txs.length; + lastTx = cachedTxHistory.lastTx; + txs.push(...resTxs); + cachedTxHistory.txs.push(...resTxs); + } + return { txs, lastTx }; + }); + } + getWalletTx(assetID, txID) { + const cachedTxHistory = this.txHistoryMap[assetID]; + if (!cachedTxHistory) + return undefined; + return cachedTxHistory.txs.find(tx => tx.id === txID); + } + clearTxHistory(assetID) { + delete this.txHistoryMap[assetID]; + } + needsCustomProvider(assetID) { + var _a, _b, _c; + return __awaiter(this, void 0, void 0, function* () { + const baseChainID = (_c = (_b = (_a = this.assets[assetID]) === null || _a === void 0 ? void 0 : _a.token) === null || _b === void 0 ? void 0 : _b.parentID) !== null && _c !== void 0 ? _c : assetID; + if (!baseChainID) + return false; + const w = this.walletMap[baseChainID]; + if (!w) + return false; + const traitAccountLocker = 1 << 14; + if ((w.traits & traitAccountLocker) === 0) + return false; + const res = yield (0,_http__WEBPACK_IMPORTED_MODULE_17__.postJSON)('/api/walletsettings', { assetID: baseChainID }); + if (!this.checkResponse(res)) { + console.error(res.msg); + return false; + } + const settings = res.map; + return !settings.providers; + }); + } +} +/* getSocketURI returns the websocket URI for the client. */ +function getSocketURI() { + const protocol = (window.location.protocol === 'https:') ? 'wss' : 'ws'; + return `${protocol}://${window.location.host}/ws`; +} +/* + * severityClassMap maps a notification severity level to a CSS class that + * assigns a background color. + */ +const severityClassMap = { + [_notifications__WEBPACK_IMPORTED_MODULE_18__.SUCCESS]: 'good', + [_notifications__WEBPACK_IMPORTED_MODULE_18__.ERROR]: 'bad', + [_notifications__WEBPACK_IMPORTED_MODULE_18__.WARNING]: 'warn' +}; +/* handlerFromPath parses the handler name from the path. */ +function handlerFromPath(path) { + return path.replace(/^\//, '').split('/')[0].split('?')[0].split('#')[0]; +} +/* nowString creates a string formatted like HH:MM:SS.xxx */ +function nowString() { + const stamp = new Date(); + const h = stamp.getHours().toString().padStart(2, '0'); + const m = stamp.getMinutes().toString().padStart(2, '0'); + const s = stamp.getSeconds().toString().padStart(2, '0'); + const ms = stamp.getMilliseconds().toString().padStart(3, '0'); + return `${h}:${m}:${s}.${ms}`; +} +function setSeverityClass(el, severity) { + el.classList.remove('bad', 'warn', 'good'); + el.classList.add(severityClassMap[severity]); +} +/* updateMatch updates the match in or adds the match to the order. */ +function updateMatch(order, match) { + for (const i in order.matches) { + const m = order.matches[i]; + if (m.matchID === match.matchID) { + order.matches[i] = match; + return; + } + } + order.matches = order.matches || []; + order.matches.push(match); +} + + +/***/ }), + +/***/ "./src/js/basepage.ts": +/*!****************************!*\ + !*** ./src/js/basepage.ts ***! + \****************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ BasePage) +/* harmony export */ }); +class BasePage { + /* unload is called when the user navigates away from the page. */ + unload() { + // should be implemented by inheriting class. + } +} + + +/***/ }), + +/***/ "./src/js/charts.ts": +/*!**************************!*\ + !*** ./src/js/charts.ts ***! + \**************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "CandleChart": () => (/* binding */ CandleChart), +/* harmony export */ "Chart": () => (/* binding */ Chart), +/* harmony export */ "DepthChart": () => (/* binding */ DepthChart), +/* harmony export */ "Extents": () => (/* binding */ Extents), +/* harmony export */ "Region": () => (/* binding */ Region), +/* harmony export */ "Wave": () => (/* binding */ Wave) +/* harmony export */ }); +/* harmony import */ var _doc__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./doc */ "./src/js/doc.ts"); +/* harmony import */ var _orderutil__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./orderutil */ "./src/js/orderutil.ts"); +/* harmony import */ var _state__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./state */ "./src/js/state.ts"); +/* harmony import */ var _registry__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./registry */ "./src/js/registry.ts"); + + + + +const bind = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind; +const PIPI = 2 * Math.PI; +const plusChar = String.fromCharCode(59914); +const minusChar = String.fromCharCode(59915); +const darkTheme = { + body: '#0b2031', + axisLabel: '#b1b1b1', + gridBorder: '#383f4b', + gridLines: '#383f4b', + gapLine: '#6b6b6b', + value: '#9a9a9a', + zoom: '#5b5b5b', + zoomHover: '#aaa', + sellLine: '#ae3333', + buyLine: '#05a35a', + sellFill: '#591a1a', + buyFill: '#02572f', + crosshairs: '#888', + legendFill: 'black', + legendText: '#d5d5d5' +}; +const lightTheme = { + body: '#f4f4f4', + axisLabel: '#1b1b1b', + gridBorder: '#ddd', + gridLines: '#ddd', + gapLine: '#595959', + value: '#4d4d4d', + zoom: '#777', + zoomHover: '#333', + sellLine: '#99302b', + buyLine: '#207a46', + sellFill: '#bd5959', + buyFill: '#4cad75', + crosshairs: '#595959', + legendFill: '#e6e6e6', + legendText: '#1b1b1b' +}; +// Chart is the base class for charts. +class Chart { + constructor(parent, reporters) { + this.parent = parent; + this.report = reporters; + this.theme = _state__WEBPACK_IMPORTED_MODULE_2__["default"].isDark() ? darkTheme : lightTheme; + this.canvas = document.createElement('canvas'); + this.visible = true; + parent.appendChild(this.canvas); + const ctx = this.canvas.getContext('2d'); + if (!ctx) { + console.error('error getting canvas context'); + return; + } + this.ctx = ctx; + this.ctx.textAlign = 'center'; + this.ctx.textBaseline = 'middle'; + // Mouse handling + this.mousePos = null; + bind(this.canvas, 'mousemove', (e) => { + // this.rect will be set in resize(). + if (!this.rect) + return; + this.mousePos = { + x: e.clientX - this.rect.left, + y: e.clientY - this.rect.y + }; + this.draw(); + }); + bind(this.canvas, 'mouseleave', () => { + this.mousePos = null; + this.draw(); + }); + // Bind resize. + const resizeObserver = new ResizeObserver(() => this.resize()); + resizeObserver.observe(this.parent); + // Scrolling by wheel is smoother when the rate is slightly limited. + this.wheelLimiter = null; + bind(this.canvas, 'wheel', (e) => { this.wheel(e); }, { passive: true }); + bind(this.canvas, 'click', (e) => { this.click(e); }); + const setVis = () => { + this.visible = document.visibilityState !== 'hidden'; + if (this.visible && this.renderScheduled) { + this.renderScheduled = false; + this.draw(); + } + }; + bind(document, 'visibilitychange', setVis); + this.unattachers = [() => { _doc__WEBPACK_IMPORTED_MODULE_0__["default"].unbind(document, 'visibilitychange', setVis); }]; + } + wheeled() { + this.wheelLimiter = window.setTimeout(() => { this.wheelLimiter = null; }, 100); + } + /* clear the canvas. */ + clear() { + this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); + } + /* draw calls the child class's render method. */ + draw() { + this.render(); + } + /* click is the handler for a click event on the canvas. */ + click(e) { + this.report.click(e); + } + /* wheel is a mousewheel event handler. */ + wheel(e) { + this.zoom(e.deltaY < 0); + } + /* + * resize updates the chart size. The parentHeight is an argument to support + * updating the height programmatically after the caller sets a style.height + * but before the clientHeight has been updated. + */ + resize() { + this.canvas.width = this.parent.clientWidth; + this.canvas.height = this.parent.clientHeight; + const xLblHeight = 30; + const yGuess = 40; // y label width guess. Will be adjusted when drawn. + const plotExtents = new Extents(0, this.canvas.width, 0, this.canvas.height - xLblHeight); + const xLblExtents = new Extents(0, this.canvas.width, this.canvas.height - xLblHeight, this.canvas.height); + const yLblExtents = new Extents(0, yGuess, 0, this.canvas.height - xLblHeight); + this.plotRegion = new Region(this.ctx, plotExtents); + this.xRegion = new Region(this.ctx, xLblExtents); + this.yRegion = new Region(this.ctx, yLblExtents); + // After changing the visibility, this.canvas.getBoundingClientRect will + // return nonsense until a render. + window.requestAnimationFrame(() => { + this.rect = this.canvas.getBoundingClientRect(); + this.report.resize(); + }); + } + /* zoom is called when the user scrolls the mouse wheel on the canvas. */ + zoom(bigger) { + if (this.wheelLimiter) + return; + this.report.zoom(bigger); + } + /* The market handler will call unattach when the markets page is unloaded. */ + unattach() { + for (const u of this.unattachers) + u(); + this.unattachers = []; + } + /* render must be implemented by the child class. */ + render() { + console.error('child class must override render method'); + } + /* applyLabelStyle applies the style used for axis tick labels. */ + applyLabelStyle(fontSize) { + this.ctx.textAlign = 'center'; + this.ctx.textBaseline = 'middle'; + this.ctx.font = `${fontSize !== null && fontSize !== void 0 ? fontSize : '14'}px 'sans', sans-serif`; + this.ctx.fillStyle = this.theme.axisLabel; + } + /* plotXLabels applies the provided labels to the x axis and draws the grid. */ + plotXLabels(labels, minX, maxX, unitLines) { + const extents = new Extents(minX, maxX, 0, 1); + this.xRegion.plot(extents, (ctx, tools) => { + this.applyLabelStyle(); + const centerX = (maxX + minX) / 2; + let lastX = minX; + let unitCenter = centerX; + const [leftEdge, rightEdge] = [tools.x(minX), tools.x(maxX)]; + const centerY = tools.y(0.5); + labels.lbls.forEach(lbl => { + const m = ctx.measureText(lbl.txt); + const x = tools.x(lbl.val); + if (x - m.width / 2 < leftEdge || x + m.width / 2 > rightEdge) + return; + ctx.fillText(lbl.txt, x, centerY); + if (centerX >= lastX && centerX < lbl.val) { + unitCenter = (lastX + lbl.val) / 2; + } + lastX = lbl.val; + }); + ctx.font = '11px \'sans\', sans-serif'; + if (unitLines.length === 2) { + ctx.fillText(unitLines[0], tools.x(unitCenter), tools.y(0.63)); + ctx.fillText(unitLines[1], tools.x(unitCenter), tools.y(0.23)); + } + else if (unitLines.length === 1) { + ctx.fillText(unitLines[0], tools.x(unitCenter), centerY); + } + }, true); + } + plotXGrid(labels, minX, maxX) { + const extents = new Extents(minX, maxX, 0, 1); + this.plotRegion.plot(extents, (ctx, tools) => { + ctx.lineWidth = 1; + ctx.strokeStyle = this.theme.gridLines; + labels.lbls.forEach(lbl => { + line(ctx, tools.x(lbl.val), tools.y(0), tools.x(lbl.val), tools.y(1)); + }); + }, true); + } + /* + * plotYLabels applies the y labels based on the provided plot region, and + * draws the grid. + */ + plotYLabels(labels, minY, maxY, unit) { + const extents = new Extents(0, 1, minY, maxY); + const fillRect = (ctx, x, y, w, h, r) => { + ctx.save(); + ctx.fillStyle = this.theme.body; + ctx.beginPath(); + if (ctx.roundRect) + ctx.roundRect(x, y, w, h, r); // Safari < 16 doesn't support + else + ctx.rect(x, y, w, h); + ctx.fill(); + ctx.restore(); + }; + this.yRegion.plot(extents, (ctx, tools) => { + this.applyLabelStyle(); + this.ctx.textAlign = 'left'; + const centerY = maxY / 2; + let lastY = 0; + let unitCenter = centerY; + const x = tools.x(0); + const [xPad, yPad] = [3, 3]; + labels.lbls.forEach(lbl => { + const y = tools.y(lbl.val); + if (y < tools.y(maxY) + yPad + 7 || y > tools.y(minY) - yPad - 7) + return; + const m = ctx.measureText(lbl.txt); + fillRect(ctx, x, y - 7 - yPad, m.width + xPad * 2, 14 + yPad * 3, 3); + ctx.fillText(lbl.txt, x + xPad, y + 2); + if (centerY >= lastY && centerY < lbl.val) { + unitCenter = (lastY + lbl.val) / 2; + } + lastY = lbl.val; + }); + const m = ctx.measureText(unit); + const y = tools.y(unitCenter); + fillRect(ctx, x, y - yPad - 7, m.width + xPad * 2, 14 + yPad * 2, 3); + ctx.fillText(unit, x + xPad, tools.y(unitCenter)); + }, true); + } + plotYGrid(region, labels, minY, maxY) { + const extents = new Extents(0, 1, minY, maxY); + region.plot(extents, (ctx, tools) => { + ctx.lineWidth = 1; + ctx.strokeStyle = this.theme.gridLines; + labels.lbls.forEach(lbl => { + line(ctx, tools.x(0), tools.y(lbl.val), tools.x(1), tools.y(lbl.val)); + }); + }, true); + } + /* + * doYLabels generates and applies the y-axis labels, based upon the + * provided plot region. + */ + makeYLabels(region, step, unit, valFmt) { + this.applyLabelStyle(); + const yLabels = makeLabels(this.ctx, region.height(), this.dataExtents.y.min, this.dataExtents.y.max, 50, step, unit, valFmt); + // Reassign the width of the y-label column to accommodate the widest text. + const yAxisWidth = (yLabels.widest || 0) + 20; /* x padding */ + this.yRegion.extents.x.max = yAxisWidth; + this.yRegion.extents.y.max = region.extents.y.max; + return yLabels; + } + line(x0, y0, x1, y1, skipStroke) { + line(this.ctx, x0, y0, x1, y1, skipStroke); + } + /* dot draws a circle with the provided context. */ + dot(x, y, color, radius) { + dot(this.ctx, x, y, color, radius); + } +} +/* DepthChart is a javascript Canvas-based depth chart renderer. */ +class DepthChart extends Chart { + constructor(parent, reporters, zoom) { + super(parent, { + resize: () => this.resized(), + click: (e) => this.clicked(e), + zoom: (bigger) => this.zoomed(bigger) + }); + this.reporters = reporters; + this.zoomLevel = zoom; + this.lines = []; + this.markers = { + buys: [], + sells: [] + }; + this.setZoomBttns(); // can't wait for requestAnimationFrame -> resized + this.resize(); + } + // setZoomBttns creates new regions for zoom in and zoom out buttons. It is + // used in initiation of the buttons and resizing. + setZoomBttns() { + this.zoomInBttn = new Region(this.ctx, new Extents(0, 0, 0, 0)); + this.zoomOutBttn = new Region(this.ctx, new Extents(0, 0, 0, 0)); + } + /* resized is called when the window or parent element are resized. */ + resized() { + // The button region extents are set during drawing. + this.setZoomBttns(); + if (this.book) + this.draw(); + } + /* zoomed zooms the current view in or out. bigger=true is zoom in. */ + zoomed(bigger) { + if (!this.zoomLevel) + return; + if (!this.book.buys || !this.book.sells) + return; + this.wheeled(); + // Zoom in to 66%, but out to 150% = 1 / (2/3) so that the same zoom levels + // are hit when reversing direction. + this.zoomLevel *= bigger ? 2 / 3 : 3 / 2; + this.zoomLevel = (0,_doc__WEBPACK_IMPORTED_MODULE_0__.clamp)(this.zoomLevel, 0.005, 2); + this.draw(); + this.reporters.zoom(this.zoomLevel); + } + /* clicked is the canvas 'click' event handler. */ + clicked(e) { + if (!this.dataExtents) + return; + const x = e.clientX - this.rect.left; + const y = e.clientY - this.rect.y; + if (this.zoomInBttn.contains(x, y)) { + this.zoom(true); + return; + } + if (this.zoomOutBttn.contains(x, y)) { + this.zoom(false); + return; + } + const translator = this.plotRegion.translator(this.dataExtents); + this.reporters.click(translator.unx(x)); + } + // set sets the current data set and draws. + set(book, lotSize, rateStepEnc, baseUnitInfo, quoteUnitInfo) { + this.book = book; + this.lotSize = lotSize / baseUnitInfo.conventional.conversionFactor; + this.conventionalRateStep = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].conventionalRateStep(rateStepEnc, baseUnitInfo, quoteUnitInfo); + this.baseUnit = baseUnitInfo.conventional.unit; + this.quoteUnit = quoteUnitInfo.conventional.unit; + if (!this.zoomLevel) { + const [midGap, gapWidth] = this.gap(); + // Default to 5% zoom, but with a minimum of 5 * midGap, but still observing + // the hard cap of 200%. + const minZoom = Math.max(gapWidth / midGap * 5, 0.05); + this.zoomLevel = Math.min(minZoom, 2); + } + this.draw(); + } + /* + * render draws the chart. + * 1. Calculate the data extents and translate the order book data to a + * cumulative form. + * 2. Draw axis ticks and grid, mid-gap line and value, zoom buttons, mouse + * position indicator... + * 4. Tick labels. + * 5. Data. + * 6. Epoch line legend. + * 7. Hover legend. + */ + render() { + // if connection fails it is not possible to get book. + if (!this.book || !this.visible || this.canvas.width === 0) { + this.renderScheduled = true; + return; + } + this.clear(); + // if (!this.book || this.book.empty()) return + const ctx = this.ctx; + const mousePos = this.mousePos; + const buys = this.book.buys; + const sells = this.book.sells; + const [midGap, gapWidth] = this.gap(); + const halfWindow = this.zoomLevel * midGap / 2; + const high = midGap + halfWindow; + const low = midGap - halfWindow; + // Get a sorted copy of the markers list. + const buyMarkers = [...this.markers.buys]; + const sellMarkers = [...this.markers.sells]; + buyMarkers.sort((a, b) => b.rate - a.rate); + sellMarkers.sort((a, b) => a.rate - b.rate); + const markers = []; + const buyDepth = []; + const buyEpoch = []; + const sellDepth = []; + const sellEpoch = []; + const volumeReport = { + buyBase: 0, + buyQuote: 0, + sellBase: 0, + sellQuote: 0 + }; + let sum = 0; + // The epoch line is above the non-epoch region, so the epochSum y value + // must account for non-epoch orders too. + let epochSum = 0; + for (let i = 0; i < buys.length; i++) { + const ord = buys[i]; + epochSum += ord.qty; + if (ord.rate >= low) + buyEpoch.push([ord.rate, epochSum]); + if (ord.epoch) + continue; + sum += ord.qty; + buyDepth.push([ord.rate, sum]); + volumeReport.buyBase += ord.qty; + volumeReport.buyQuote += ord.qty * ord.rate; + while (buyMarkers.length && floatCompare(buyMarkers[0].rate, ord.rate)) { + const mark = buyMarkers.shift(); + if (!mark) + continue; + markers.push({ + rate: mark.rate, + qty: ord.epoch ? epochSum : sum, + sell: ord.sell, + active: mark.active + }); + } + } + const buySum = buyDepth.length ? last(buyDepth)[1] : 0; + buyDepth.push([low, buySum]); + const epochBuySum = buyEpoch.length ? last(buyEpoch)[1] : 0; + buyEpoch.push([low, epochBuySum]); + epochSum = sum = 0; + for (let i = 0; i < sells.length; i++) { + const ord = sells[i]; + epochSum += ord.qty; + if (ord.rate <= high) + sellEpoch.push([ord.rate, epochSum]); + if (ord.epoch) + continue; + sum += ord.qty; + sellDepth.push([ord.rate, sum]); + volumeReport.sellBase += ord.qty; + volumeReport.sellQuote += ord.qty * ord.rate; + while (sellMarkers.length && floatCompare(sellMarkers[0].rate, ord.rate)) { + const mark = sellMarkers.shift(); + if (!mark) + continue; + markers.push({ + rate: mark.rate, + qty: ord.epoch ? epochSum : sum, + sell: ord.sell, + active: mark.active + }); + } + } + // Add a data point going to the left so that the data doesn't end with a + // vertical line. + const sellSum = sellDepth.length ? last(sellDepth)[1] : 0; + sellDepth.push([high, sellSum]); + const epochSellSum = sellEpoch.length ? last(sellEpoch)[1] : 0; + sellEpoch.push([high, epochSellSum]); + // Add ~30px padding to the top of the chart. + const h = this.xRegion.extents.y.min; + const growthFactor = (h + 40) / h; + const maxY = (epochSellSum && epochBuySum ? Math.max(epochBuySum, epochSellSum) : epochSellSum || epochBuySum || 1) * growthFactor; + const dataExtents = new Extents(low, high, 0, maxY); + this.dataExtents = dataExtents; + // A function to be run at the end if there is legend data to display. + let mouseData = null; + // Draw the grid. + const xLabels = makeLabels(ctx, this.plotRegion.width(), dataExtents.x.min, dataExtents.x.max, 100, this.conventionalRateStep, ''); + this.plotXGrid(xLabels, low, high); + const yLabels = this.makeYLabels(this.plotRegion, this.lotSize, this.baseUnit); + this.plotYGrid(this.plotRegion, yLabels, this.dataExtents.y.min, this.dataExtents.y.max); + this.plotRegion.plot(dataExtents, (ctx, tools) => { + ctx.lineWidth = 1; + // first, a square around the plot area. + ctx.strokeStyle = this.theme.gridBorder; + // draw a line to indicate mid-gap + ctx.lineWidth = 2.5; + ctx.strokeStyle = this.theme.gapLine; + line(ctx, tools.x(midGap), tools.y(0), tools.x(midGap), tools.y(0.3 * dataExtents.y.max)); + ctx.font = '30px \'demi-sans\', sans-serif'; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = this.theme.value; + const y = 0.5 * dataExtents.y.max; + ctx.fillText(_doc__WEBPACK_IMPORTED_MODULE_0__["default"].formatFourSigFigs(midGap), tools.x(midGap), tools.y(y)); + ctx.font = '12px \'sans\', sans-serif'; + // ctx.fillText('mid-market price', tools.x(midGap), tools.y(y) + 24) + ctx.fillText(`${(gapWidth / midGap * 100).toFixed(2)}% spread`, tools.x(midGap), tools.y(y) + 24); + // Draw zoom buttons. + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + const topCenterX = this.plotRegion.extents.midX; + const topCenterY = tools.y(maxY * 0.9); + const zoomPct = dataExtents.xRange / midGap * 100; + const zoomText = `${zoomPct.toFixed(1)}%`; + const w = ctx.measureText(zoomText).width; + ctx.font = '13px \'sans\', sans-serif'; + ctx.fillText(zoomText, topCenterX, topCenterY + 1); + // define the region for the zoom button + const bttnSize = 20; + const xPad = 10; + let bttnLeft = topCenterX - w / 2 - xPad - bttnSize; + const bttnTop = topCenterY - bttnSize / 2; + this.zoomOutBttn.setExtents(bttnLeft, bttnLeft + bttnSize, bttnTop, bttnTop + bttnSize); + let hover = mousePos && this.zoomOutBttn.contains(mousePos.x, mousePos.y); + this.zoomOutBttn.plot(new Extents(0, 1, 0, 1), ctx => { + ctx.font = '12px \'icomoon\''; + ctx.fillStyle = this.theme.zoom; + if (hover) { + ctx.fillStyle = this.theme.zoomHover; + ctx.font = '13px \'icomoon\''; + } + ctx.fillText(minusChar, this.zoomOutBttn.extents.midX, this.zoomOutBttn.extents.midY); + }); + bttnLeft = topCenterX + w / 2 + xPad; + this.zoomInBttn.setExtents(bttnLeft, bttnLeft + bttnSize, bttnTop, bttnTop + bttnSize); + hover = mousePos && this.zoomInBttn.contains(mousePos.x, mousePos.y); + this.zoomInBttn.plot(new Extents(0, 1, 0, 1), ctx => { + ctx.font = '12px \'icomoon\''; + ctx.fillStyle = this.theme.zoom; + if (hover) { + ctx.fillStyle = this.theme.zoomHover; + ctx.font = '14px \'icomoon\''; + } + ctx.fillText(plusChar, this.zoomInBttn.extents.midX, this.zoomInBttn.extents.midY); + }); + // Draw a dotted vertical line where the mouse is, and a dot at the level + // of the depth line. + const drawLine = (x, color) => { + if (x > high || x < low) + return; + ctx.save(); + ctx.setLineDash([3, 5]); + ctx.lineWidth = 1.5; + ctx.strokeStyle = color; + line(ctx, tools.x(x), tools.y(0), tools.x(x), tools.y(maxY)); + ctx.restore(); + }; + // for (const line of this.lines || []) { + // drawLine(line.rate, line.color) + // } + const tolerance = (high - low) * 0.005; + const hoverMarkers = []; + for (const marker of markers || []) { + const hovered = (mousePos && withinTolerance(marker.rate, tools.unx(mousePos.x), tolerance)); + if (hovered) + hoverMarkers.push(marker.rate); + ctx.save(); + ctx.lineWidth = (hovered || marker.active) ? 5 : 3; + ctx.strokeStyle = marker.sell ? this.theme.sellLine : this.theme.buyLine; + ctx.fillStyle = marker.sell ? this.theme.sellFill : this.theme.buyFill; + const size = (hovered || marker.active) ? 10 : 8; + ctx.beginPath(); + const tip = { + x: tools.x(marker.rate), + y: tools.y(marker.qty) - 8 + }; + const top = tip.y - (Math.sqrt(3) * size / 2); // cos(30) + ctx.moveTo(tip.x, tip.y); + ctx.lineTo(tip.x - size / 2, top); + ctx.lineTo(tip.x + size / 2, top); + ctx.closePath(); + ctx.stroke(); + ctx.fill(); + ctx.restore(); + } + // If the mouse is in the chart area, draw the crosshairs. + if (!mousePos) + return; + if (!this.plotRegion.contains(mousePos.x, mousePos.y)) + return; + // The mouse is in the plot region. Get the data coordinates and find the + // side and depth for the x value. + const dataX = tools.unx(mousePos.x); + let evalSide = sellDepth; + let trigger = (ptX) => ptX >= dataX; + let dotColor = this.theme.sellLine; + if (dataX < midGap) { + evalSide = buyDepth; + trigger = (ptX) => ptX <= dataX; + dotColor = this.theme.buyLine; + } + let bestDepth = evalSide[0]; + for (let i = 0; i < evalSide.length; i++) { + const pt = evalSide[i]; + if (trigger(pt[0])) + break; + bestDepth = pt; + } + drawLine(dataX, this.theme.crosshairs); + mouseData = { + rate: dataX, + depth: bestDepth[1], + dotColor: dotColor, + hoverMarkers: hoverMarkers + }; + }); + // Draw the epoch lines + ctx.lineWidth = 1.5; + ctx.setLineDash([3, 3]); + // epoch sells + ctx.fillStyle = this.theme.sellFill; + ctx.strokeStyle = this.theme.sellLine; + this.drawDepth(sellEpoch); + // epoch buys + ctx.fillStyle = this.theme.buyFill; + ctx.strokeStyle = this.theme.buyLine; + this.drawDepth(buyEpoch); + // Draw the book depth. + ctx.lineWidth = 2.5; + ctx.setLineDash([]); + // book sells + ctx.fillStyle = this.theme.sellFill; + ctx.strokeStyle = this.theme.sellLine; + this.drawDepth(sellDepth); + // book buys + ctx.fillStyle = this.theme.buyFill; + ctx.strokeStyle = this.theme.buyLine; + this.drawDepth(buyDepth); + this.plotYLabels(yLabels, this.dataExtents.y.min, this.dataExtents.y.max, this.baseUnit); + this.plotXLabels(xLabels, low, high, [`${this.quoteUnit}/`, this.baseUnit]); + // Display the dot at the intersection of the mouse hover line and the depth + // line. This should be drawn after the depths. + if (mouseData) { + this.plotRegion.plot(dataExtents, (ctx, tools) => { + if (!mouseData) + return; // For TypeScript. Duh. + dot(ctx, tools.x(mouseData.rate), tools.y(mouseData.depth), mouseData.dotColor, 5); + }); + } + // Report the book volumes. + this.reporters.volume(volumeReport); + this.reporters.mouse(mouseData); + } + /* drawDepth draws a single side's depth chart data. */ + drawDepth(depth) { + const firstPt = depth[0]; + let x; + this.plotRegion.plot(this.dataExtents, (ctx, tools) => { + const yZero = tools.y(0); + let y = tools.y(firstPt[1]); + ctx.beginPath(); + ctx.moveTo(tools.x(firstPt[0]), tools.y(firstPt[1])); + for (let i = 0; i < depth.length; i++) { + // Set x, but don't set y until we draw the horizontal line. + x = tools.x(depth[i][0]); + ctx.lineTo(x, y); + // If this is past the render edge, quit drawing. + y = tools.y(depth[i][1]); + ctx.lineTo(x, y); + } + ctx.stroke(); + ctx.lineTo(x, yZero); + ctx.lineTo(tools.x(firstPt[0]), yZero); + ctx.closePath(); + ctx.globalAlpha = 0.25; + ctx.fill(); + }); + } + /* returns the mid-gap rate and gap width as a tuple. */ + gap() { + const [b, s] = [this.book.bestGapBuy(), this.book.bestGapSell()]; + if (!b) { + if (!s) + return [1, 0]; + return [s.rate, 0]; + } + else if (!s) + return [b.rate, 0]; + return [(s.rate + b.rate) / 2, s.rate - b.rate]; + } + /* setLines stores the indicator lines to draw. */ + setLines(lines) { + this.lines = lines; + } + /* setMarkers sets the indicator markers to draw. */ + setMarkers(markers) { + this.markers = markers; + } +} +/* CandleChart is a candlestick data renderer. */ +class CandleChart extends Chart { + constructor(parent, reporters) { + super(parent, { + resize: () => this.resized(), + click: ( /* e: MouseEvent */) => { this.clicked(); }, + zoom: (bigger) => this.zoomed(bigger) + }); + this.reporters = reporters; + this.zoomLevel = 1; + this.numToShow = 100; + this.resize(); + } + /* resized is called when the window or parent element are resized. */ + resized() { + const ext = this.plotRegion.extents; + const candleExtents = new Extents(ext.x.min, ext.x.max, ext.y.min, ext.y.min + ext.yRange * 0.85); + this.candleRegion = new Region(this.ctx, candleExtents); + const volumeExtents = new Extents(ext.x.min, ext.x.max, ext.y.min + 0.85 * ext.yRange, ext.y.max); + this.volumeRegion = new Region(this.ctx, volumeExtents); + // Set a delay on the render to prevent lag. + if (this.resizeTimer) + clearTimeout(this.resizeTimer); + this.resizeTimer = window.setTimeout(() => this.draw(), 100); + } + clicked( /* e: MouseEvent */) { + // handle clicks + } + /* zoomed zooms the current view in or out. bigger=true is zoom in. */ + zoomed(bigger) { + // bigger actually means fewer candles -> reduce zoomLevels index. + const idx = this.zoomLevels.indexOf(this.numToShow); + if (bigger) { + if (idx === 0) + return; + this.numToShow = this.zoomLevels[idx - 1]; + } + else { + if (this.zoomLevels.length <= idx + 1 || this.numToShow > this.data.candles.length) + return; + this.numToShow = this.zoomLevels[idx + 1]; + } + this.draw(); + } + /* render draws the chart */ + render() { + var _a; + const data = this.data; + if (!data || !this.visible || this.canvas.width === 0) { + this.renderScheduled = true; + return; + } + const candleWidth = data.ms; + const mousePos = this.mousePos; + const allCandles = data.candles || []; + const n = Math.min(this.numToShow, allCandles.length); + const candles = allCandles.slice(allCandles.length - n); + this.clear(); + // If there are no candles. just don't draw anything. + if (n === 0) + return; + // padding definition and some helper functions to parse candles. + const candleWidthPadding = 0.2; + const start = (c) => truncate(c.endStamp, candleWidth); + const end = (c) => start(c) + candleWidth; + const paddedStart = (c) => start(c) + candleWidthPadding * candleWidth; + const paddedWidth = (1 - 2 * candleWidthPadding) * candleWidth; + const first = candles[0]; + const last = candles[n - 1]; + let [high, low, highVol] = [first.highRate, first.lowRate, first.matchVolume]; + for (const c of candles) { + if (c.highRate > high) + high = c.highRate; + if (c.lowRate < low) + low = c.lowRate; + if (c.matchVolume > highVol) + highVol = c.matchVolume; + } + high += (high - low) * 0.1; // a little padding + const xStart = start(first); + let xEnd = end(last); + xEnd += (xEnd - xStart) * 0.05; // a little padding + // Calculate data extents and store them. They are used to apply labels. + const rateStep = this.market.ratestep; + const dataExtents = new Extents(xStart, xEnd, low, high); + if (low === high) { + // If there is no price movement at all in the window, show a little more + // top and bottom so things render nicely. + dataExtents.y.min -= rateStep; + dataExtents.y.max += rateStep; + } + this.dataExtents = dataExtents; + let mouseCandle = null; + if (mousePos) { + this.plotRegion.plot(new Extents(dataExtents.x.min, dataExtents.x.max, 0, 1), (ctx, tools) => { + const selectedStartStamp = truncate(tools.unx(mousePos.x), candleWidth); + for (const c of candles) { + if (start(c) === selectedStartStamp) { + mouseCandle = c; + ctx.fillStyle = this.theme.gridLines; + ctx.fillRect(tools.x(start(c)), tools.y(0), tools.w(candleWidth), tools.h(1)); + break; + } + } + }); + } + // Draw the grid + const rFactor = this.rateConversionFactor; + const baseUnit = ((_a = (0,_registry__WEBPACK_IMPORTED_MODULE_3__.app)().assets[this.market.baseid]) === null || _a === void 0 ? void 0 : _a.unitInfo.conventional.unit) || this.market.basesymbol.toUpperCase(); + const xLabels = makeCandleTimeLabels(candles, candleWidth, this.plotRegion.width(), 100); + this.plotXGrid(xLabels, xStart, xEnd); + const yLabels = this.makeYLabels(this.candleRegion, rateStep, baseUnit, v => _doc__WEBPACK_IMPORTED_MODULE_0__["default"].formatFourSigFigs(v / rFactor)); + this.plotYGrid(this.candleRegion, yLabels, this.dataExtents.y.min, this.dataExtents.y.max); + // Draw the volume bars. + const volDataExtents = new Extents(xStart, xEnd, 0, highVol); + this.volumeRegion.plot(volDataExtents, (ctx, tools) => { + ctx.fillStyle = this.theme.gridBorder; + for (const c of candles) { + ctx.fillRect(tools.x(paddedStart(c)), tools.y(0), tools.w(paddedWidth), tools.h(c.matchVolume)); + } + }); + // Draw the candles. + this.candleRegion.plot(dataExtents, (ctx, tools) => { + ctx.lineWidth = 1; + for (const c of candles) { + const desc = c.startRate > c.endRate; + const [x, y, w, h] = [tools.x(paddedStart(c)), tools.y(c.startRate), tools.w(paddedWidth), tools.h(c.endRate - c.startRate)]; + const [high, low, cx] = [tools.y(c.highRate), tools.y(c.lowRate), w / 2 + x]; + ctx.strokeStyle = desc ? this.theme.sellLine : this.theme.buyLine; + ctx.fillStyle = desc ? this.theme.sellFill : this.theme.buyFill; + ctx.beginPath(); + ctx.moveTo(cx, high); + ctx.lineTo(cx, low); + ctx.stroke(); + ctx.fillRect(x, y, w, h); + ctx.strokeRect(x, y, w, h); + } + }); + // Apply labels. + this.plotXLabels(xLabels, xStart, xEnd, []); + this.plotYLabels(yLabels, this.dataExtents.y.min, this.dataExtents.y.max, baseUnit); + // Highlight the candle if the user mouse is over the canvas. + if (mouseCandle) { + const yExt = this.xRegion.extents.y; + this.xRegion.plot(new Extents(dataExtents.x.min, dataExtents.x.max, yExt.min, yExt.max), (ctx, tools) => { + if (!mouseCandle) + return; // For TypeScript. Duh. + this.applyLabelStyle(); + const rangeTxt = `${new Date(start(mouseCandle)).toLocaleString()} - ${new Date(end(mouseCandle)).toLocaleString()}`; + const [xPad, yPad] = [25, 2]; + const rangeWidth = ctx.measureText(rangeTxt).width + 2 * xPad; + const rangeHeight = 16; + let centerX = tools.x((start(mouseCandle) + end(mouseCandle)) / 2); + let left = centerX - rangeWidth / 2; + const xExt = this.xRegion.extents.x; + if (left < xExt.min) + left = xExt.min; + else if (left + rangeWidth > xExt.max) + left = xExt.max - rangeWidth; + centerX = left + rangeWidth / 2; + const top = yExt.min + (this.xRegion.height() - rangeHeight) / 2; + ctx.fillStyle = this.theme.legendFill; + ctx.strokeStyle = this.theme.gridBorder; + const rectArgs = [left - xPad, top - yPad, rangeWidth + 2 * xPad, rangeHeight + 2 * yPad]; + ctx.fillRect(...rectArgs); + ctx.strokeRect(...rectArgs); + this.applyLabelStyle(); + ctx.fillText(rangeTxt, centerX, this.xRegion.extents.midY, rangeWidth); + }); + } + // Report the mouse candle. + this.reporters.mouse(mouseCandle); + } + /* setCandles sets the candle data and redraws the chart. */ + setCandles(data, market, baseUnitInfo, quoteUnitInfo) { + this.data = data; + if (!data.candles) + return; + this.market = market; + const [qFactor, bFactor] = [quoteUnitInfo.conventional.conversionFactor, baseUnitInfo.conventional.conversionFactor]; + this.rateConversionFactor = _orderutil__WEBPACK_IMPORTED_MODULE_1__.RateEncodingFactor * qFactor / bFactor; + let n = 25; + this.zoomLevels = []; + const maxCandles = Math.max(data.candles.length, 1000); + while (n < maxCandles) { + this.zoomLevels.push(n); + n *= 2; + } + this.numToShow = 100; + this.draw(); + } +} +/* Wave is a loading animation that displays a colorful line that oscillates */ +class Wave extends Chart { + constructor(parent, opts) { + super(parent, { + resize: () => this.resized(), + click: ( /* e: MouseEvent */) => { }, + zoom: ( /* bigger: boolean */) => { } + }); + this.canvas.classList.add('fill-abs'); + this.canvas.style.zIndex = '5'; + this.opts = opts !== null && opts !== void 0 ? opts : {}; + const period = 1500; // ms + const start = Math.random() * period; + this.colorShift = Math.random() * 360; + // y = A*cos(k*x + theta*t + c) + // combine three waves with different periods and speeds and phases. + const amplitudes = [1, 0.65, 0.75]; + const ks = [3, 3, 2]; + const speeds = [Math.PI, Math.PI * 10 / 9, Math.PI / 2.5]; + const phases = [0, 0, Math.PI * 1.5]; + const n = 75; + const single = (n, angularX, angularTime) => { + return amplitudes[n] * Math.cos(ks[n] * angularX + speeds[n] * angularTime + phases[n]); + }; + const value = (x, angularTime) => { + const angularX = x * Math.PI * 2; + return (single(0, angularX, angularTime) + single(1, angularX, angularTime) + single(2, angularX, angularTime)) / 3; + }; + this.resize(); + this.ani = new _doc__WEBPACK_IMPORTED_MODULE_0__.Animation(_doc__WEBPACK_IMPORTED_MODULE_0__.Animation.Forever, () => { + const angularTime = (new Date().getTime() - start) / period * Math.PI * 2; + const values = []; + for (let i = 0; i < n; i++) { + values.push(value(i / (n - 1), angularTime)); + } + this.drawValues(values); + }); + } + resized() { + const opts = this.opts; + const [maxW, maxH] = [150, 100]; + const [cw, ch] = [this.canvas.width, this.canvas.height]; + let [w, h] = [cw * 0.8, ch * 0.8]; + if (w > maxW) + w = maxW; + if (h > maxH) + h = maxH; + let [l, t] = [(cw - w) / 2, (ch - h) / 2]; + if (opts.message) { + this.fontSize = (0,_doc__WEBPACK_IMPORTED_MODULE_0__.clamp)(h * 0.15, 10, 14); + this.applyLabelStyle(this.fontSize); + const ypad = this.fontSize * 0.5; + const halfH = (this.fontSize / 2) + ypad; + t -= halfH; + this.msgRegion = new Region(this.ctx, new Extents(0, cw, t + h, t + h + 2 * halfH)); + } + this.region = new Region(this.ctx, new Extents(l, l + w, t, t + h)); + } + drawValues(values) { + if (!this.region) + return; + this.clear(); + const hsl = (h) => `hsl(${h}, 35%, 50%)`; + const { region, msgRegion, canvas: { width: w, height: h }, opts: { backgroundColor: bg, message: msg }, colorShift, ctx } = this; + if (bg) { + if (bg === true) + ctx.fillStyle = _state__WEBPACK_IMPORTED_MODULE_2__["default"].isDark() ? '#0a1e34' : '#f0f0f0'; + else + ctx.fillStyle = bg; + ctx.fillRect(0, 0, w, h); + } + region.plot(new Extents(0, 1, -1, 1), (ctx, t) => { + ctx.lineWidth = 4; + ctx.lineCap = 'round'; + const shift = colorShift + (new Date().getTime() % 2000) / 2000 * 360; // colors move with frequency 1 / 2s + const grad = ctx.createLinearGradient(t.x(0), 0, t.x(1), 0); + grad.addColorStop(0, hsl(shift)); + ctx.strokeStyle = grad; + ctx.beginPath(); + ctx.moveTo(t.x(0), t.y(values[0])); + for (let i = 1; i < values.length; i++) { + const prog = i / (values.length - 1); + grad.addColorStop(prog, hsl(prog * 300 + shift)); + ctx.lineTo(t.x(prog), t.y(values[i])); + } + ctx.stroke(); + }); + if (!msg) + return; + msgRegion.plot(new Extents(0, 1, 0, 1), (ctx, t) => { + this.applyLabelStyle(this.fontSize); + ctx.fillText(msg, t.x(0.5), t.y(0.5), this.msgRegion.width()); + }); + } + render() { } + stop() { + this.ani.stop(); + this.canvas.remove(); + } +} +/* + * Extents holds a min and max in both the x and y directions, and provides + * getters for related data. + */ +class Extents { + constructor(xMin, xMax, yMin, yMax) { + this.setExtents(xMin, xMax, yMin, yMax); + } + setExtents(xMin, xMax, yMin, yMax) { + this.x = { + min: xMin, + max: xMax + }; + this.y = { + min: yMin, + max: yMax + }; + } + get xRange() { + return this.x.max - this.x.min; + } + get midX() { + return (this.x.max + this.x.min) / 2; + } + get yRange() { + return this.y.max - this.y.min; + } + get midY() { + return (this.y.max + this.y.min) / 2; + } +} +/* + * Region applies an Extents to the canvas, providing utilities for coordinate + * transformations and restricting drawing to a specified region of the canvas. + */ +class Region { + constructor(context, extents) { + this.context = context; + this.extents = extents; + } + setExtents(xMin, xMax, yMin, yMax) { + this.extents.setExtents(xMin, xMax, yMin, yMax); + } + width() { + return this.extents.xRange; + } + height() { + return this.extents.yRange; + } + contains(x, y) { + const ext = this.extents; + return (x < ext.x.max && x > ext.x.min && + y < ext.y.max && y > ext.y.min); + } + /* + * A translator provides 4 function for coordinate transformations. x and y + * translate data coordinates to canvas coordinates for the specified data + * Extents. unx and uny translate canvas coordinates to data coordinates. + */ + translator(dataExtents) { + const region = this.extents; + const xMin = dataExtents.x.min; + // const xMax = dataExtents.x.max + const yMin = dataExtents.y.min; + // const yMax = dataExtents.y.max + const yRange = dataExtents.yRange; + const xRange = dataExtents.xRange; + const screenMinX = region.x.min; + const screenW = region.x.max - screenMinX; + const screenMaxY = region.y.max; + const screenH = screenMaxY - region.y.min; + const xFactor = screenW / xRange; + const yFactor = screenH / yRange; + return { + x: (x) => (x - xMin) * xFactor + screenMinX, + y: (y) => screenMaxY - (y - yMin) * yFactor, + unx: (x) => (x - screenMinX) / xFactor + xMin, + uny: (y) => yMin - (y - screenMaxY) / yFactor, + w: (w) => w / xRange * screenW, + h: (h) => -h / yRange * screenH + }; + } + /* clear clears the region. */ + clear() { + const ext = this.extents; + this.context.clearRect(ext.x.min, ext.y.min, ext.xRange, ext.yRange); + } + /* plot prepares tools for drawing using data coordinates. */ + plot(dataExtents, drawFunc, skipMask) { + const ctx = this.context; + const region = this.extents; + ctx.save(); // Save the original state + if (!skipMask) { + ctx.beginPath(); + ctx.rect(region.x.min, region.y.min, region.xRange, region.yRange); + ctx.clip(); + } + // The drawFunc will be passed a set of tool that can be used to assist + // drawing. The tools start with the transformation functions. + const tools = this.translator(dataExtents); + // Create a transformation that allows drawing in data coordinates. It's + // not advisable to stroke or add text with this transform in place, as the + // result will be distorted. You can however use ctx.moveTo and ctx.lineTo + // with this transform in place using data coordinates, and remove the + // transform before stroking. The dataCoords method of the supplied tool + // provides this functionality. + // TODO: Figure out why this doesn't work on WebView. + // const yRange = dataExtents.yRange + // const xFactor = region.xRange / dataExtents.xRange + // const yFactor = region.yRange / yRange + // const xMin = dataExtents.x.min + // const yMin = dataExtents.y.min + // // These translation factors are complicated because the (0, 0) of the + // // region is not necessarily the (0, 0) of the canvas. + // const tx = (region.x.min + xMin) - xMin * xFactor + // const ty = -region.y.min - (yRange - yMin) * yFactor + // const setTransform = () => { + // // Data coordinates are flipped about y. Flip the coordinates and + // // translate top left corner to canvas (0, 0). + // ctx.transform(1, 0, 0, -1, -xMin, yMin) + // // Scale to data coordinates and shift into place for the region's offset + // // on the canvas. + // ctx.transform(xFactor, 0, 0, yFactor, tx, ty) + // } + // // dataCoords allows some drawing to be performed directly in data + // // coordinates. Most actual drawing functions like ctx.stroke and + // // ctx.fillRect should not be called from inside dataCoords, but + // // ctx.moveTo and ctx.LineTo are fine. + // tools.dataCoords = f => { + // ctx.save() + // setTransform() + // f() + // ctx.restore() + // } + drawFunc(this.context, tools); + ctx.restore(); + } +} +/* + * makeLabels attempts to create the appropriate labels for the specified + * screen size, context, and label spacing. + */ +function makeLabels(ctx, screenW, min, max, spacingGuess, step, unit, valFmt) { + valFmt = valFmt || _doc__WEBPACK_IMPORTED_MODULE_0__["default"].formatFourSigFigs; + const n = screenW / spacingGuess; + const diff = max - min; + if (n < 1 || diff <= 0) + return { lbls: [] }; + const tickGuess = diff / n; + // make the tick spacing a multiple of the step + const tick = tickGuess + step - (tickGuess % step); + let x = min + tick - (min % tick); + const absMax = Math.max(Math.abs(max), Math.abs(min)); + // The Math.round part is the minimum precision required to see the change in the numbers. + // The 2 accounts for the precision of the tick. + const sigFigs = Math.round(Math.log10(absMax / tick)) + 2; + const pts = []; + let widest = 0; + while (x < max) { + x = Number(x.toPrecision(sigFigs)); + const lbl = valFmt(x); + widest = Math.max(widest, ctx.measureText(lbl).width); + pts.push({ + val: x, + txt: lbl + }); + x += tick; + } + const unitW = ctx.measureText(unit).width; + if (unitW > widest) + widest = unitW; + return { + widest: widest, + lbls: pts + }; +} +const months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']; +/* makeCandleTimeLabels prepares labels for candlestick data. */ +function makeCandleTimeLabels(candles, dur, screenW, spacingGuess) { + const first = candles[0]; + const last = candles[candles.length - 1]; + const start = truncate(first.endStamp, dur); + const end = truncate(last.endStamp, dur) + dur; + const diff = end - start; + const n = Math.min(candles.length, screenW / spacingGuess); + const tick = truncate(diff / n, dur); + if (tick === 0) { + console.error('zero tick', dur, diff, n); // probably won't happen, but it'd suck if it did + return { lbls: [] }; + } + let x = start; + const zoneOffset = new Date().getTimezoneOffset(); + const dayStamp = (x) => { + x = x - zoneOffset * 60000; + return x - (x % 86400000); + }; + let lastDay = dayStamp(start); + let lastYear = 0; // new Date(start).getFullYear() + if (dayStamp(first.endStamp) === dayStamp(last.endStamp)) + lastDay = 0; // Force at least one day stamp. + const pts = []; + let label; + if (dur < 86400000) { + label = (d, x) => { + const day = dayStamp(x); + if (day !== lastDay) + return `${months[d.getMonth()]}${d.getDate()} ${d.getHours()}:${String(d.getMinutes()).padStart(2, '0')}`; + else + return `${d.getHours()}:${String(d.getMinutes()).padStart(2, '0')}`; + }; + } + else { + label = (d) => { + const year = d.getFullYear(); + if (year !== lastYear) + return `${months[d.getMonth()]}${d.getDate()} '${String(year).slice(2, 4)}`; + else + return `${months[d.getMonth()]}${d.getDate()}`; + }; + } + while (x <= end) { + const d = new Date(x); + pts.push({ + val: x, + txt: label(d, x) + }); + lastDay = dayStamp(x); + lastYear = d.getFullYear(); + x += tick; + } + return { lbls: pts }; +} +/* The last element of an array. */ +function last(arr) { + return arr[arr.length - 1]; +} +/* line draws a line with the provided context. */ +function line(ctx, x0, y0, x1, y1, skipStroke) { + ctx.beginPath(); + ctx.moveTo(x0, y0); + ctx.lineTo(x1, y1); + if (!skipStroke) + ctx.stroke(); +} +/* dot draws a circle with the provided context. */ +function dot(ctx, x, y, color, radius) { + ctx.fillStyle = color; + ctx.beginPath(); + ctx.arc(x, y, radius, 0, PIPI); + ctx.fill(); +} +/* floatCompare compares two floats to within a tolerance of 1e-8. */ +function floatCompare(a, b) { + return withinTolerance(a, b, 1e-8); +} +/* + * withinTolerance returns true if the difference between a and b are with + * the specified tolerance. + */ +function withinTolerance(a, b, tolerance) { + return Math.abs(a - b) < Math.abs(tolerance); +} +function truncate(v, w) { + return v - (v % w); +} + + +/***/ }), + +/***/ "./src/js/coinexplorers.ts": +/*!*********************************!*\ + !*** ./src/js/coinexplorers.ts ***! + \*********************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "CoinExplorers": () => (/* binding */ CoinExplorers), +/* harmony export */ "Mainnet": () => (/* binding */ Mainnet), +/* harmony export */ "Simnet": () => (/* binding */ Simnet), +/* harmony export */ "Testnet": () => (/* binding */ Testnet), +/* harmony export */ "formatCoinID": () => (/* binding */ formatCoinID), +/* harmony export */ "setCoinHref": () => (/* binding */ setCoinHref) +/* harmony export */ }); +/* harmony import */ var _registry__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./registry */ "./src/js/registry.ts"); +/* harmony import */ var _locales__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./locales */ "./src/js/locales.ts"); + + +const Mainnet = 0; +const Testnet = 1; +const Simnet = 2; +const coinIDTakerFoundMakerRedemption = 'TakerFoundMakerRedemption:'; +/* ethBasedExplorerArg returns the explorer argument for ETH, ERC20 and EVM +Compatible assets and whether the return value is an address. */ +function ethBasedExplorerArg(cid) { + if (cid.startsWith(coinIDTakerFoundMakerRedemption)) + return [cid.substring(coinIDTakerFoundMakerRedemption.length), true]; + else if (cid.length === 42) + return [cid, true]; + else + return [cid, false]; +} +const ethExplorers = { + [Mainnet]: (cid) => { + const [arg, isAddr] = ethBasedExplorerArg(cid); + return isAddr ? `https://etherscan.io/address/${arg}` : `https://etherscan.io/tx/${arg}`; + }, + [Testnet]: (cid) => { + const [arg, isAddr] = ethBasedExplorerArg(cid); + return isAddr ? `https://sepolia.etherscan.io/address/${arg}` : `https://sepolia.etherscan.io/tx/${arg}`; + }, + [Simnet]: (cid) => { + const [arg, isAddr] = ethBasedExplorerArg(cid); + return isAddr ? `https://etherscan.io/address/${arg}` : `https://etherscan.io/tx/${arg}`; + } +}; +const polygonExplorers = { + [Mainnet]: (cid) => { + const [arg, isAddr] = ethBasedExplorerArg(cid); + return isAddr ? `https://polygonscan.com/address/${arg}` : `https://polygonscan.com/tx/${arg}`; + }, + [Testnet]: (cid) => { + const [arg, isAddr] = ethBasedExplorerArg(cid); + return isAddr ? `https://amoy.polygonscan.com/address/${arg}` : `https://amoy.polygonscan.com/tx/${arg}`; + }, + [Simnet]: (cid) => { + const [arg, isAddr] = ethBasedExplorerArg(cid); + return isAddr ? `https://polygonscan.com/address/${arg}` : `https://polygonscan.com/tx/${arg}`; + } +}; +const CoinExplorers = { + 42: { + [Mainnet]: (cid) => { + const [txid, vout] = cid.split(':'); + if (vout !== undefined) + return `https://explorer.dcrdata.org/tx/${txid}/out/${vout}`; + return `https://explorer.dcrdata.org/tx/${txid}`; + }, + [Testnet]: (cid) => { + const [txid, vout] = cid.split(':'); + if (vout !== undefined) + return `https://testnet.dcrdata.org/tx/${txid}/out/${vout}`; + return `https://testnet.dcrdata.org/tx/${txid}`; + }, + [Simnet]: (cid) => { + const [txid, vout] = cid.split(':'); + if (vout !== undefined) + return `http://127.0.0.1:17779/tx/${txid}/out/${vout}`; + return `https://127.0.0.1:17779/tx/${txid}`; + } + }, + 0: { + [Mainnet]: (cid) => `https://mempool.space/tx/${cid.split(':')[0]}`, + [Testnet]: (cid) => `https://mempool.space/testnet/tx/${cid.split(':')[0]}`, + [Simnet]: (cid) => `https://mempool.space/tx/${cid.split(':')[0]}` + }, + 2: { + [Mainnet]: (cid) => `https://ltc.bitaps.com/${cid.split(':')[0]}`, + [Testnet]: (cid) => `https://sochain.com/tx/LTCTEST/${cid.split(':')[0]}`, + [Simnet]: (cid) => `https://ltc.bitaps.com/${cid.split(':')[0]}` + }, + 20: { + [Mainnet]: (cid) => `https://digiexplorer.info/tx/${cid.split(':')[0]}`, + [Testnet]: (cid) => `https://testnetexplorer.digibyteservers.io/tx/${cid.split(':')[0]}`, + [Simnet]: (cid) => `https://digiexplorer.info/tx/${cid.split(':')[0]}` + }, + 60: ethExplorers, + 60001: ethExplorers, + 60002: ethExplorers, + 3: { + [Mainnet]: (cid) => `https://dogeblocks.com/tx/${cid.split(':')[0]}`, + [Testnet]: (cid) => `https://blockexplorer.one/dogecoin/testnet/tx/${cid.split(':')[0]}`, + [Simnet]: (cid) => `https://dogeblocks.com/tx/${cid.split(':')[0]}` + }, + 5: { + [Mainnet]: (cid) => `https://blockexplorer.one/dash/mainnet/tx/${cid.split(':')[0]}`, + [Testnet]: (cid) => `https://blockexplorer.one/dash/testnet/tx/${cid.split(':')[0]}`, + [Simnet]: (cid) => `https://blockexplorer.one/dash/mainnet/tx/${cid.split(':')[0]}` + }, + 133: { + [Mainnet]: (cid) => `https://zcashblockexplorer.com/transactions/${cid.split(':')[0]}`, + [Testnet]: (cid) => `https://blockexplorer.one/zcash/testnet/tx/${cid.split(':')[0]}`, + [Simnet]: (cid) => `https://zcashblockexplorer.com/transactions/${cid.split(':')[0]}` + }, + 147: { + [Mainnet]: (cid) => `https://explorer.zcl.zelcore.io/tx/${cid.split(':')[0]}`, + [Simnet]: (cid) => `https://explorer.zcl.zelcore.io/tx/${cid.split(':')[0]}` + }, + 136: { + [Mainnet]: (cid) => `https://explorer.firo.org/tx/${cid.split(':')[0]}`, + [Testnet]: (cid) => `https://testexplorer.firo.org/tx/${cid.split(':')[0]}`, + [Simnet]: (cid) => `https://explorer.firo.org/tx/${cid.split(':')[0]}` + }, + 145: { + [Mainnet]: (cid) => `https://bch.loping.net/tx/${cid.split(':')[0]}`, + [Testnet]: (cid) => `https://tbch4.loping.net/tx/${cid.split(':')[0]}`, + [Simnet]: (cid) => `https://bch.loping.net/tx/${cid.split(':')[0]}` + }, + 966: polygonExplorers, + 966001: polygonExplorers, + 966002: polygonExplorers, + 966003: polygonExplorers, + 966004: polygonExplorers +}; +function formatCoinID(cid) { + if (cid.startsWith(coinIDTakerFoundMakerRedemption)) { + const makerAddr = cid.substring(coinIDTakerFoundMakerRedemption.length); + return _locales__WEBPACK_IMPORTED_MODULE_1__.prep(_locales__WEBPACK_IMPORTED_MODULE_1__.ID_TAKER_FOUND_MAKER_REDEMPTION, { makerAddr: makerAddr }); + } + return cid; +} +/* + * baseChainID returns the asset ID for the asset's parent if the asset is a + * token, otherwise the ID for the asset itself. + */ +function baseChainID(assetID) { + const asset = (0,_registry__WEBPACK_IMPORTED_MODULE_0__.app)().user.assets[assetID]; + return asset.token ? asset.token.parentID : assetID; +} +/* + * setCoinHref sets the hyperlink element's href attribute based on provided + * assetID and data-explorer-coin value present on supplied link element. + */ +function setCoinHref(assetID, link) { + const net = (0,_registry__WEBPACK_IMPORTED_MODULE_0__.app)().user.net; + const assetExplorer = CoinExplorers[baseChainID(assetID)]; + if (!assetExplorer) + return; + const formatter = assetExplorer[net]; + if (!formatter) + return; + link.classList.remove('plainlink'); + link.classList.add('subtlelink'); + link.href = formatter(link.dataset.explorerCoin || ''); +} + + +/***/ }), + +/***/ "./src/js/dexsettings.ts": +/*!*******************************!*\ + !*** ./src/js/dexsettings.ts ***! + \*******************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ DexSettingsPage) +/* harmony export */ }); +/* harmony import */ var _doc__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./doc */ "./src/js/doc.ts"); +/* harmony import */ var _basepage__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./basepage */ "./src/js/basepage.ts"); +/* harmony import */ var _http__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./http */ "./src/js/http.ts"); +/* harmony import */ var _forms__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./forms */ "./src/js/forms.ts"); +/* harmony import */ var _locales__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./locales */ "./src/js/locales.ts"); +/* harmony import */ var _account__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./account */ "./src/js/account.ts"); +/* harmony import */ var _registry__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./registry */ "./src/js/registry.ts"); +var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; + + + + + + + +const animationLength = 300; +class DexSettingsPage extends _basepage__WEBPACK_IMPORTED_MODULE_1__["default"] { + constructor(body) { + super(); + this.body = body; + const host = this.host = body.dataset.host ? body.dataset.host : ''; + const xc = (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().exchanges[host]; + const page = this.page = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].idDescendants(body); + this.forms = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].applySelector(page.forms, ':scope > form'); + this.confirmRegisterForm = new _forms__WEBPACK_IMPORTED_MODULE_3__.ConfirmRegistrationForm(page.confirmRegForm, () => __awaiter(this, void 0, void 0, function* () { + this.showSuccess(_locales__WEBPACK_IMPORTED_MODULE_4__.prep(_locales__WEBPACK_IMPORTED_MODULE_4__.ID_TRADING_TIER_UPDATED)); + this.renewToggle.setState(this.confirmRegisterForm.tier > 0); + yield (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().fetchUser(); + (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().updateMenuItemsDisplay(); + }), () => { + this.runAnimation(this.regAssetForm, page.regAssetForm); + }); + this.confirmRegisterForm.setExchange(xc, ''); + this.walletWaitForm = new _forms__WEBPACK_IMPORTED_MODULE_3__.WalletWaitForm(page.walletWait, () => { + this.runAnimation(this.confirmRegisterForm, page.confirmRegForm); + }, () => { + this.runAnimation(this.regAssetForm, page.regAssetForm); + }); + this.walletWaitForm.setExchange(xc); + this.newWalletForm = new _forms__WEBPACK_IMPORTED_MODULE_3__.NewWalletForm(page.newWalletForm, assetID => this.newWalletCreated(assetID, this.confirmRegisterForm.tier), () => this.runAnimation(this.regAssetForm, page.regAssetForm)); + this.regAssetForm = new _forms__WEBPACK_IMPORTED_MODULE_3__.FeeAssetSelectionForm(page.regAssetForm, (assetID, tier) => __awaiter(this, void 0, void 0, function* () { + if (assetID === _registry__WEBPACK_IMPORTED_MODULE_6__.PrepaidBondID) { + yield (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().fetchUser(); + this.updateReputation(); + this.showSuccess(_locales__WEBPACK_IMPORTED_MODULE_4__.prep(_locales__WEBPACK_IMPORTED_MODULE_4__.ID_TRADING_TIER_UPDATED)); + return; + } + const asset = (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().assets[assetID]; + const wallet = asset.wallet; + if (wallet) { + const loaded = (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().loading(page.regAssetForm); + const bondsFeeBuffer = yield this.getBondsFeeBuffer(assetID, page.regAssetForm); + this.confirmRegisterForm.setAsset(assetID, tier, bondsFeeBuffer); + loaded(); + this.progressTierFormsWithWallet(assetID, wallet); + return; + } + this.confirmRegisterForm.setAsset(assetID, tier, 0); + this.newWalletForm.setAsset(assetID); + this.showForm(page.newWalletForm); + })); + this.regAssetForm.setExchange(xc, ''); + this.reputationMeter = new _account__WEBPACK_IMPORTED_MODULE_5__.ReputationMeter(page.repMeter); + this.reputationMeter.setHost(host); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(page.exportDexBtn, 'click', () => this.exportAccount()); + this.accountDisabled = body.dataset.disabled === 'true'; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(page.toggleAccountStatusBtn, 'click', () => { + if (!this.accountDisabled) + this.prepareAccountDisable(page.disableAccountForm); + else + this.toggleAccountStatus(false); + }); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(page.updateCertBtn, 'click', () => page.certFileInput.click()); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(page.updateHostBtn, 'click', () => this.prepareUpdateHost()); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(page.certFileInput, 'change', () => this.onCertFileChange()); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(page.goBackToSettings, 'click', () => (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().loadPage('settings')); + const showTierForm = () => { + this.regAssetForm.setExchange((0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().exchanges[host], ''); // reset form + this.showForm(page.regAssetForm); + }; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(page.changeTier, 'click', () => { showTierForm(); }); + const willAutoRenew = xc.auth.targetTier > 0; + this.renewToggle = new _doc__WEBPACK_IMPORTED_MODULE_0__.AniToggle(page.toggleAutoRenew, page.renewErr, willAutoRenew, (newState) => __awaiter(this, void 0, void 0, function* () { + if (this.accountDisabled) + return; + if (newState) + showTierForm(); + else + return this.disableAutoRenew(); + })); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(page.autoRenewBox, 'click', (e) => { + e.stopPropagation(); + if (!this.accountDisabled) + page.toggleAutoRenew.click(); + }); + page.penaltyComps.textContent = String(xc.auth.penaltyComps); + const hideCompInput = () => { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.penaltyCompInput); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.penaltyComps); + }; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(page.penaltyCompBox, 'click', (e) => { + e.stopPropagation(); + const xc = (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().exchanges[this.host]; + page.penaltyCompInput.value = String(xc.auth.penaltyComps); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.penaltyComps); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.penaltyCompInput); + page.penaltyCompInput.focus(); + const checkClick = (e) => { + if (_doc__WEBPACK_IMPORTED_MODULE_0__["default"].mouseInElement(e, page.penaltyCompBox)) + return; + hideCompInput(); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].unbind(document, 'click', checkClick); + }; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(document, 'click', checkClick); + }); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(page.penaltyCompInput, 'keyup', (e) => __awaiter(this, void 0, void 0, function* () { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.penaltyCompsErr); + if (e.key === 'Escape') { + hideCompInput(); + return; + } + if (!(e.key === 'Enter')) + return; + const penaltyComps = parseInt(page.penaltyCompInput.value || ''); + if (isNaN(penaltyComps)) { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.penaltyCompsErr); + page.penaltyCompsErr.textContent = _locales__WEBPACK_IMPORTED_MODULE_4__.prep(_locales__WEBPACK_IMPORTED_MODULE_4__.ID_INVALID_COMPS_VALUE); + return; + } + const loaded = (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().loading(page.otherBondSettings); + try { + yield this.updateBondOptions({ penaltyComps }); + loaded(); + page.penaltyComps.textContent = String(penaltyComps); + } + catch (e) { + loaded(); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.penaltyCompsErr); + page.penaltyCompsErr.textContent = _locales__WEBPACK_IMPORTED_MODULE_4__.prep(_locales__WEBPACK_IMPORTED_MODULE_4__.ID_API_ERROR, { msg: e.msg }); + } + hideCompInput(); + })); + this.dexAddrForm = new _forms__WEBPACK_IMPORTED_MODULE_3__.DEXAddressForm(page.dexAddrForm, (xc) => __awaiter(this, void 0, void 0, function* () { + (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().loadPage(`/dexsettings/${xc.host}`); + }), this.host); + // forms.bind(page.bondDetailsForm, page.updateBondOptionsConfirm, () => this.updateBondOptions()) + _forms__WEBPACK_IMPORTED_MODULE_3__.bind(page.disableAccountForm, page.disableAccountConfirm, () => this.toggleAccountStatus(true)); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(page.forms, 'mousedown', (e) => { + if (!_doc__WEBPACK_IMPORTED_MODULE_0__["default"].mouseInElement(e, this.currentForm)) { + this.closePopups(); + } + }); + this.keyup = (e) => { + if (e.key === 'Escape') { + this.closePopups(); + } + }; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(document, 'keyup', this.keyup); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].applySelector(page.forms, '.form-closer').forEach(el => { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(el, 'click', () => { this.closePopups(); }); + }); + (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().registerNoteFeeder({ + conn: () => { this.setConnectionStatus(); }, + reputation: () => { this.updateReputation(); }, + feepayment: () => { this.updateReputation(); }, + bondpost: () => { this.updateReputation(); } + }); + this.setConnectionStatus(); + this.updateReputation(); + } + unload() { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].unbind(document, 'keyup', this.keyup); + } + progressTierFormsWithWallet(assetID, wallet) { + return __awaiter(this, void 0, void 0, function* () { + const { page, confirmRegisterForm: { fees } } = this; + const asset = (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().assets[assetID]; + const { bondAssets } = this.regAssetForm.xc; + const bondAsset = bondAssets[asset.symbol]; + if (!wallet.open) { + const loaded = (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().loading(page.forms); + const res = yield (0,_http__WEBPACK_IMPORTED_MODULE_2__.postJSON)('/api/openwallet', { assetID: assetID }); + loaded(); + if (!(0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().checkResponse(res)) { + this.regAssetForm.setAssetError(`error unlocking wallet: ${res.msg}`); + this.runAnimation(this.regAssetForm, page.regAssetForm); + } + return; + } + if (wallet.synced && wallet.balance.available >= 2 * bondAsset.amount + fees) { + // If we are raising our tier, we'll show a confirmation form + this.progressTierFormWithSyncedFundedWallet(assetID); + return; + } + this.walletWaitForm.setWallet(assetID, fees, this.confirmRegisterForm.tier); + this.showForm(page.walletWait); + }); + } + progressTierFormWithSyncedFundedWallet(bondAssetID) { + return __awaiter(this, void 0, void 0, function* () { + const xc = (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().exchanges[this.host]; + const targetTier = this.confirmRegisterForm.tier; + const page = this.page; + const strongTier = xc.auth.liveStrength + xc.auth.pendingStrength - xc.auth.weakStrength; + if (targetTier > xc.auth.targetTier && targetTier > strongTier) { + this.runAnimation(this.confirmRegisterForm, page.confirmRegForm); + return; + } + // Lowering tier + const loaded = (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().loading(this.body); + try { + yield this.updateBondOptions({ bondAssetID, targetTier }); + loaded(); + } + catch (e) { + loaded(); + this.regAssetForm.setTierError(e.msg); + return; + } + // this.animateConfirmForm(page.regAssetForm) + this.showSuccess(_locales__WEBPACK_IMPORTED_MODULE_4__.prep(_locales__WEBPACK_IMPORTED_MODULE_4__.ID_TRADING_TIER_UPDATED)); + }); + } + updateReputation() { + const page = this.page; + const auth = (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().exchanges[this.host].auth; + const { rep: { penalties }, targetTier, expiredBonds } = auth; + const displayTier = (0,_account__WEBPACK_IMPORTED_MODULE_5__.strongTier)(auth); + page.targetTier.textContent = String(targetTier); + page.effectiveTier.textContent = String(displayTier); + page.penalties.textContent = String(penalties); + page.bondsPendingRefund.textContent = `${(expiredBonds === null || expiredBonds === void 0 ? void 0 : expiredBonds.length) || 0}`; + this.reputationMeter.update(); + } + /* showForm shows a modal form with a little animation. */ + showForm(form) { + return __awaiter(this, void 0, void 0, function* () { + const page = this.page; + this.currentForm = form; + this.forms.forEach(form => _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(form)); + form.style.right = '10000px'; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.forms, form); + const shift = (page.forms.offsetWidth + form.offsetWidth) / 2; + yield _doc__WEBPACK_IMPORTED_MODULE_0__["default"].animate(animationLength, progress => { + form.style.right = `${(1 - progress) * shift}px`; + }, 'easeOutHard'); + form.style.right = '0'; + }); + } + runAnimation(ani, form) { + return __awaiter(this, void 0, void 0, function* () { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(this.currentForm); + yield ani.animate(); + this.currentForm = form; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(form); + }); + } + closePopups() { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(this.page.forms); + if (this.animation) + this.animation.stop(); + } + showSuccess(msg) { + return __awaiter(this, void 0, void 0, function* () { + this.forms.forEach(form => _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(form)); + this.currentForm = this.page.checkmarkForm; + this.animation = _forms__WEBPACK_IMPORTED_MODULE_3__.showSuccess(this.page, msg); + yield this.animation.wait(); + this.animation = new _doc__WEBPACK_IMPORTED_MODULE_0__.Animation(1500, () => { }, '', () => { + if (this.currentForm === this.page.checkmarkForm) + this.closePopups(); + }); + }); + } + // exportAccount exports and downloads the account info. + exportAccount() { + return __awaiter(this, void 0, void 0, function* () { + const { page, host } = this; + const req = { host }; + const loaded = (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().loading(this.body); + const res = yield (0,_http__WEBPACK_IMPORTED_MODULE_2__.postJSON)('/api/exportaccount', req); + loaded(); + if (!(0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().checkResponse(res)) { + page.exportAccountErr.textContent = res.msg; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.exportAccountErr); + return; + } + res.account.bonds = res.bonds; // maintain backward compat of JSON file + const accountForExport = JSON.parse(JSON.stringify(res.account)); + const a = document.createElement('a'); + a.setAttribute('download', 'dcrAccount-' + host + '.json'); + a.setAttribute('href', 'data:text/json,' + JSON.stringify(accountForExport, null, 2)); + a.click(); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.forms); + }); + } + // toggleAccountStatus enables or disables the account associated with the + // provided host. + toggleAccountStatus(disable) { + return __awaiter(this, void 0, void 0, function* () { + const page = this.page; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.errMsg); + let host = this.host; + if (disable) + host = page.disableAccountHost.textContent; + const req = { host, disable: disable }; + const loaded = (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().loading(this.body); + const res = yield (0,_http__WEBPACK_IMPORTED_MODULE_2__.postJSON)('/api/toggleaccountstatus', req); + loaded(); + if (!(0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().checkResponse(res)) { + if (disable) { + page.disableAccountErr.textContent = res.msg; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.disableAccountErr); + } + else { + page.errMsg.textContent = res.msg; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.errMsg); + } + return; + } + if (disable) { + this.page.toggleAccountStatusBtn.textContent = _locales__WEBPACK_IMPORTED_MODULE_4__.prep(_locales__WEBPACK_IMPORTED_MODULE_4__.ID_ENABLE_ACCOUNT); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.forms); + } + else + this.page.toggleAccountStatusBtn.textContent = _locales__WEBPACK_IMPORTED_MODULE_4__.prep(_locales__WEBPACK_IMPORTED_MODULE_4__.ID_DISABLE_ACCOUNT); + this.accountDisabled = disable; + // Refresh exchange information since we've just enabled/disabled the + // exchange. + yield (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().fetchUser(); + (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().loadPage(`dexsettings/${host}`); + }); + } + prepareAccountDisable(disableAccountForm) { + return __awaiter(this, void 0, void 0, function* () { + const page = this.page; + page.disableAccountHost.textContent = this.host; + page.disableAccountErr.textContent = ''; + this.showForm(disableAccountForm); + }); + } + // Retrieve an estimate for the tx fee needed to create new bond reserves. + getBondsFeeBuffer(assetID, form) { + return __awaiter(this, void 0, void 0, function* () { + const loaded = (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().loading(form); + const res = yield (0,_http__WEBPACK_IMPORTED_MODULE_2__.postJSON)('/api/bondsfeebuffer', { assetID }); + loaded(); + if (!(0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().checkResponse(res)) { + return 0; + } + return res.feeBuffer; + }); + } + prepareUpdateHost() { + return __awaiter(this, void 0, void 0, function* () { + const page = this.page; + this.dexAddrForm.refresh(); + this.showForm(page.dexAddrForm); + }); + } + onCertFileChange() { + return __awaiter(this, void 0, void 0, function* () { + const page = this.page; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.errMsg); + const files = page.certFileInput.files; + let cert; + if (files && files.length) + cert = yield files[0].text(); + if (!cert) + return; + const req = { host: this.host, cert: cert }; + const loaded = (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().loading(this.body); + const res = yield (0,_http__WEBPACK_IMPORTED_MODULE_2__.postJSON)('/api/updatecert', req); + loaded(); + if (!(0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().checkResponse(res)) { + page.errMsg.textContent = res.msg; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.errMsg); + } + else { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.updateCertMsg); + setTimeout(() => { _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.updateCertMsg); }, 5000); + } + }); + } + setConnectionStatus() { + const page = this.page; + const exchange = (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().user.exchanges[this.host]; + const displayIcons = (connected) => { + if (connected) { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.disconnectedIcon); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.connectedIcon); + } + else { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.disconnectedIcon); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.connectedIcon); + } + }; + if (exchange) { + switch (exchange.connectionStatus) { + case _registry__WEBPACK_IMPORTED_MODULE_6__.ConnectionStatus.Connected: + displayIcons(true); + page.connectionStatus.textContent = _locales__WEBPACK_IMPORTED_MODULE_4__.prep(_locales__WEBPACK_IMPORTED_MODULE_4__.ID_CONNECTED); + break; + case _registry__WEBPACK_IMPORTED_MODULE_6__.ConnectionStatus.Disconnected: + displayIcons(false); + if (this.accountDisabled) + page.connectionStatus.textContent = _locales__WEBPACK_IMPORTED_MODULE_4__.prep(_locales__WEBPACK_IMPORTED_MODULE_4__.ID_ACCOUNT_DISABLED_MSG); + else + page.connectionStatus.textContent = _locales__WEBPACK_IMPORTED_MODULE_4__.prep(_locales__WEBPACK_IMPORTED_MODULE_4__.ID_DISCONNECTED); + break; + case _registry__WEBPACK_IMPORTED_MODULE_6__.ConnectionStatus.InvalidCert: + displayIcons(false); + page.connectionStatus.textContent = `${_locales__WEBPACK_IMPORTED_MODULE_4__.prep(_locales__WEBPACK_IMPORTED_MODULE_4__.ID_DISCONNECTED)} - ${_locales__WEBPACK_IMPORTED_MODULE_4__.prep(_locales__WEBPACK_IMPORTED_MODULE_4__.ID_INVALID_CERTIFICATE)}`; + } + } + } + disableAutoRenew() { + return __awaiter(this, void 0, void 0, function* () { + const loaded = (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().loading(this.page.otherBondSettings); + try { + this.updateBondOptions({ targetTier: 0 }); + loaded(); + } + catch (e) { + loaded(); + throw e; + } + }); + } + /* + * updateBondOptions is called when the form to update bond options is + * submitted. + */ + updateBondOptions(conf) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + conf.host = this.host; + yield (0,_http__WEBPACK_IMPORTED_MODULE_2__.postJSON)('/api/updatebondoptions', conf); + const targetTier = (_a = conf.targetTier) !== null && _a !== void 0 ? _a : (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().exchanges[this.host].auth.targetTier; + this.renewToggle.setState(targetTier > 0); + }); + } + newWalletCreated(assetID, tier) { + return __awaiter(this, void 0, void 0, function* () { + this.regAssetForm.refresh(); + const user = yield (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().fetchUser(); + if (!user) + return; + const page = this.page; + const asset = user.assets[assetID]; + const wallet = asset.wallet; + const xc = (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().exchanges[this.host]; + const bondAmt = xc.bondAssets[asset.symbol].amount; + const bondsFeeBuffer = yield this.getBondsFeeBuffer(assetID, page.newWalletForm); + this.confirmRegisterForm.setFees(assetID, bondsFeeBuffer); + if (wallet.synced && wallet.balance.available >= 2 * bondAmt + bondsFeeBuffer) { + this.progressTierFormWithSyncedFundedWallet(assetID); + return; + } + this.walletWaitForm.setWallet(assetID, bondsFeeBuffer, tier); + yield this.showForm(page.walletWait); + }); + } +} + + +/***/ }), + +/***/ "./src/js/doc.ts": +/*!***********************!*\ + !*** ./src/js/doc.ts ***! + \***********************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "AniToggle": () => (/* binding */ AniToggle), +/* harmony export */ "Animation": () => (/* binding */ Animation), +/* harmony export */ "Easing": () => (/* binding */ Easing), +/* harmony export */ "IncrementalInput": () => (/* binding */ IncrementalInput), +/* harmony export */ "MiniSlider": () => (/* binding */ MiniSlider), +/* harmony export */ "NumberInput": () => (/* binding */ NumberInput), +/* harmony export */ "WalletIcons": () => (/* binding */ WalletIcons), +/* harmony export */ "clamp": () => (/* binding */ clamp), +/* harmony export */ "default": () => (/* binding */ Doc), +/* harmony export */ "parseFloatDefault": () => (/* binding */ parseFloatDefault), +/* harmony export */ "setupCopyBtn": () => (/* binding */ setupCopyBtn), +/* harmony export */ "toFourSigFigs": () => (/* binding */ toFourSigFigs), +/* harmony export */ "toPrecision": () => (/* binding */ toPrecision) +/* harmony export */ }); +/* harmony import */ var _locales__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./locales */ "./src/js/locales.ts"); +/* harmony import */ var _state__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./state */ "./src/js/state.ts"); +var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; + + +const parser = new window.DOMParser(); +const FPS = 30; +const BipIDs = { + 0: 'btc', + 42: 'dcr', + 2: 'ltc', + 5: 'dash', + 20: 'dgb', + 22: 'mona', + 28: 'vtc', + 3: 'doge', + 145: 'bch', + 60: 'eth', + 60001: 'usdc.eth', + 60002: 'usdt.eth', + 60003: 'matic.eth', + 136: 'firo', + 133: 'zec', + 966: 'polygon', + 966001: 'usdc.polygon', + 966002: 'weth.polygon', + 966003: 'wbtc.polygon', + 966004: 'usdt.polygon', + 147: 'zcl' +}; +const BipSymbolIDs = {}; +(function () { + for (const k of Object.keys(BipIDs)) { + BipSymbolIDs[BipIDs[parseInt(k)]] = parseInt(k); + } +})(); +const BipSymbols = Object.values(BipIDs); +const RateEncodingFactor = 1e8; // same as value defined in ./orderutil +const log10RateEncodingFactor = Math.round(Math.log10(RateEncodingFactor)); +const languages = navigator.languages.filter((locale) => locale !== 'c'); +const intFormatter = new Intl.NumberFormat(languages, { maximumFractionDigits: 0 }); +const fourSigFigs = new Intl.NumberFormat(languages, { + minimumSignificantDigits: 4, + maximumSignificantDigits: 4 +}); +/* A cache for formatters used for Doc.formatCoinValue. */ +const decimalFormatters = {}; +/* + * decimalFormatter gets the formatCoinValue formatter for the specified decimal + * precision. + */ +function decimalFormatter(prec) { + return formatter(decimalFormatters, 2, prec); +} +/* A cache for formatters used for Doc.formatFullPrecision. */ +const fullPrecisionFormatters = {}; +/* + * fullPrecisionFormatter gets the formatFullPrecision formatter for the + * specified decimal precision. + */ +function fullPrecisionFormatter(prec, locales) { + return formatter(fullPrecisionFormatters, prec, prec, locales); +} +/* + * formatter gets the formatter from the supplied cache if it already exists, + * else creates it. + */ +function formatter(formatters, min, max, locales) { + const k = `${min}-${max}`; + let fmt = formatters[k]; + if (!fmt) { + fmt = new Intl.NumberFormat(locales !== null && locales !== void 0 ? locales : languages, { + minimumFractionDigits: min, + maximumFractionDigits: max + }); + formatters[k] = fmt; + } + return fmt; +} +/* + * convertToConventional converts the value in atomic units to conventional + * units. + */ +function convertToConventional(v, unitInfo) { + let prec = 8; + if (unitInfo) { + const f = unitInfo.conventional.conversionFactor; + v /= f; + prec = Math.round(Math.log10(f)); + } + return [v, prec]; +} +/* + * bestDisplayOrder is used in bestConversion, and is the order of magnitude + * that is considered the best for display. For example, if bestDisplayOrder is + * 1, and the choices for display are 1,000 BTC or 0.00001 Sats, the algorithm + * will look at the orders of the conversions, 1000 => 10^3 => order 3, and + * 0.00001 => 10^-5 => order 5, and see which is closest to bestDisplayOrder and + * choose that conversion. In the example, 3 - bestDisplayOrder = 2 and + * 1 - (-5) = 6, so the conversion that has the order closest to + * bestDisplayOrder is the first one, 1,000 BTC. + */ +const bestDisplayOrder = 1; // 10^1 => 1 +/* + * resolveUnitConversions creates a lookup object mapping unit -> conversion + * factor. By default, resolveUnitConversions only maps the atomic and + * conventional units. If a prefs dict is provided, additional units can be + * included. + */ +function resolveUnitConversions(ui, prefs) { + const unitFactors = { + [ui.atomicUnit]: 1, + [ui.conventional.unit]: ui.conventional.conversionFactor + }; + if (ui.denominations && prefs) { + for (const alt of ui.denominations) + if (prefs[alt.unit]) + unitFactors[alt.unit] = alt.conversionFactor; + } + return unitFactors; +} +// Helpers for working with the DOM. +class Doc { + /* + * idel is the element with the specified id that is the descendent of the + * specified node. + */ + static idel(el, id) { + return el.querySelector(`#${id}`); + } + /* bind binds the function to the event for the element. */ + static bind(el, ev, f, opts /* EventListenerOptions */) { + for (const e of (Array.isArray(ev) ? ev : [ev])) + el.addEventListener(e, f, opts); + } + /* unbind removes the handler for the event from the element. */ + static unbind(el, ev, f) { + el.removeEventListener(ev, f); + } + /* noderize creates a Document object from a string of HTML. */ + static noderize(html) { + return parser.parseFromString(html, 'text/html'); + } + /* + * mouseInElement returns true if the position of mouse event, e, is within + * the bounds of the specified element or any of its descendents. + */ + static mouseInElement(e, el) { + if (el.contains(e.target)) + return true; + const rect = el.getBoundingClientRect(); + return e.pageX >= rect.left && e.pageX <= rect.right && + e.pageY >= rect.top && e.pageY <= rect.bottom; + } + /* + * layoutMetrics gets information about the elements position on the page. + */ + static layoutMetrics(el) { + const box = el.getBoundingClientRect(); + const docEl = document.documentElement; + const top = box.top + docEl.scrollTop; + const left = box.left + docEl.scrollLeft; + const w = el.offsetWidth; + const h = el.offsetHeight; + return { + bodyTop: top, + bodyLeft: left, + width: w, + height: h, + centerX: left + w / 2, + centerY: top + h / 2 + }; + } + static descendentMetrics(parent, kid) { + const parentMetrics = Doc.layoutMetrics(parent); + const kidMetrics = Doc.layoutMetrics(kid); + return { + bodyTop: kidMetrics.bodyTop - parentMetrics.bodyTop, + bodyLeft: kidMetrics.bodyLeft - parentMetrics.bodyLeft, + width: kidMetrics.width, + height: kidMetrics.height, + centerX: kidMetrics.centerX - parentMetrics.bodyLeft, + centerY: kidMetrics.centerY - parentMetrics.bodyTop + }; + } + /* empty removes all child nodes from the specified element. */ + static empty(...els) { + for (const el of els) + while (el.firstChild) + el.removeChild(el.firstChild); + } + /* + * setContent removes all child nodes from the specified element and appends + * passed elements. + */ + static setContent(ancestor, ...kids) { + Doc.empty(ancestor); + for (const k of kids) + ancestor.appendChild(k); + } + /* + * hide hides the specified elements. This is accomplished by adding the + * bootstrap d-hide class to the element. Use Doc.show to undo. + */ + static hide(...els) { + for (const el of els) + el.classList.add('d-hide'); + } + /* + * show shows the specified elements. This is accomplished by removing the + * bootstrap d-hide class as added with Doc.hide. + */ + static show(...els) { + for (const el of els) + el.classList.remove('d-hide'); + } + /* + * show or hide the specified elements, based on value of the truthiness of + * vis. + */ + static setVis(vis, ...els) { + if (vis) + Doc.show(...els); + else + Doc.hide(...els); + } + /* isHidden returns true if the specified element is hidden */ + static isHidden(el) { + return el.classList.contains('d-hide'); + } + /* isDisplayed returns true if the specified element is not hidden */ + static isDisplayed(el) { + return !el.classList.contains('d-hide'); + } + /* + * animate runs the supplied function, which should be a "progress" function + * accepting one argument. The progress function will be called repeatedly + * with the argument varying from 0.0 to 1.0. The exact path that animate + * takes from 0.0 to 1.0 will vary depending on the choice of easing + * algorithm. See the Easing object for the available easing algo choices. The + * default easing algorithm is linear. + */ + static animate(duration, f, easingAlgo) { + return __awaiter(this, void 0, void 0, function* () { + yield new Animation(duration, f, easingAlgo).wait(); + }); + } + static blink(el) { + return __awaiter(this, void 0, void 0, function* () { + const [r, g, b] = _state__WEBPACK_IMPORTED_MODULE_1__["default"].isDark() ? [255, 255, 255] : [0, 0, 0]; + const cycles = 2; + Doc.animate(1000, (p) => { + el.style.outline = `2px solid rgba(${r}, ${g}, ${b}, ${(cycles - p * cycles) % 1})`; + }); + }); + } + static applySelector(ancestor, k) { + return Array.from(ancestor.querySelectorAll(k)); + } + static kids(ancestor) { + return Array.from(ancestor.children); + } + static safeSelector(ancestor, k) { + const el = ancestor.querySelector(k); + if (el) + return el; + console.warn(`no element found for selector '${k}' on element ->`, ancestor); + return document.createElement('div'); + } + /* + * idDescendants creates an object mapping to elements which are descendants + * of the ancestor and have id attributes. Elements are keyed by their id + * value. + */ + static idDescendants(ancestor) { + const d = {}; + for (const el of Doc.applySelector(ancestor, '[id]')) + d[el.id] = el; + return d; + } + /* + * formatCoinValue formats the value in atomic units into a string + * representation in conventional units. If the value happens to be an + * integer, no decimals are displayed. Trailing zeros may be truncated. + */ + static formatCoinValue(vAtomic, unitInfo) { + const [v, prec] = convertToConventional(vAtomic, unitInfo); + if (Number.isInteger(v)) + return intFormatter.format(v); + return decimalFormatter(prec).format(v); + } + static conventionalCoinValue(vAtomic, unitInfo) { + const [v] = convertToConventional(vAtomic, unitInfo); + return v; + } + /* + * formatRateFullPrecision formats rate to represent it exactly at rate step + * precision, trimming non-effectual zeros if there are any. + */ + static formatRateFullPrecision(encRate, bui, qui, rateStepEnc) { + const r = bui.conventional.conversionFactor / qui.conventional.conversionFactor; + const convRate = encRate * r / RateEncodingFactor; + const rateStepDigits = log10RateEncodingFactor - Math.floor(Math.log10(rateStepEnc)) - + Math.floor(Math.log10(bui.conventional.conversionFactor) - Math.log10(qui.conventional.conversionFactor)); + if (rateStepDigits <= 0) + return intFormatter.format(convRate); + return fullPrecisionFormatter(rateStepDigits).format(convRate); + } + static formatFourSigFigs(n, maxDecimals) { + return formatSigFigsWithFormatters(intFormatter, fourSigFigs, n, maxDecimals); + } + static formatInt(i) { + return intFormatter.format(i); + } + /* + * formatFullPrecision formats the value in atomic units into a string + * representation in conventional units using the full decimal precision + * associated with the conventional unit's conversion factor. + */ + static formatFullPrecision(vAtomic, unitInfo) { + const [v, prec] = convertToConventional(vAtomic, unitInfo); + return fullPrecisionFormatter(prec).format(v); + } + /* + * formatFiatConversion formats the value in atomic units to its representation in + * conventional units and returns the fiat value as a string. + */ + static formatFiatConversion(vAtomic, rate, unitInfo) { + if (!rate || rate === 0) + return _locales__WEBPACK_IMPORTED_MODULE_0__.prep(_locales__WEBPACK_IMPORTED_MODULE_0__.ID_UNAVAILABLE); + const prec = 2; + const [v] = convertToConventional(vAtomic, unitInfo); + const value = v * rate; + return fullPrecisionFormatter(prec).format(value); + } + static languages() { + return languages; + } + static formatFiatValue(value) { + return fullPrecisionFormatter(2).format(value); + } + /* + * bestConversion picks the best conversion factor for the atomic value. The + * best is the one in which log10(converted_value) is closest to + * bestDisplayOrder. Return: [converted_value, precision, unit]. + */ + static bestConversion(atoms, ui, prefs) { + const unitFactors = resolveUnitConversions(ui, prefs); + const logDiffs = []; + const entryDiff = (entry) => Math.abs(Math.log10(atoms / entry[1]) - bestDisplayOrder); + for (const entry of Object.entries(unitFactors)) + logDiffs.push([entry[0], entryDiff(entry)]); + const best = logDiffs.reduce((best, entry) => entry[1] < best[1] ? entry : best); + const unit = best[0]; + const cFactor = unitFactors[unit]; + const v = atoms / cFactor; + return [v, Math.round(Math.log10(cFactor)), unit]; + } + /* + * formatBestUnitsFullPrecision formats the value with the best choice of + * units, at full precision. + */ + static formatBestUnitsFullPrecision(atoms, ui, prefs) { + const [v, prec, unit] = this.bestConversion(atoms, ui, prefs); + if (Number.isInteger(v)) + return [intFormatter.format(v), unit]; + return [fullPrecisionFormatter(prec).format(v), unit]; + } + /* + * formatBestUnitsFourSigFigs formats the value with the best choice of + * units and rounded to four significant figures. + */ + static formatBestUnitsFourSigFigs(atoms, ui, prefs) { + const [v, prec, unit] = this.bestConversion(atoms, ui, prefs); + return [Doc.formatFourSigFigs(v, prec), unit]; + } + /* + * formatBestRateElement formats a rate using the best available units and + * updates the UI element. The ancestor should have descendents with data + * attributes [best-value, data-unit, data-unit-box, data-denom]. + */ + static formatBestRateElement(ancestor, assetID, atoms, ui, prefs) { + Doc.formatBestValueElement(ancestor, assetID, atoms, ui, prefs); + Doc.setText(ancestor, '[data-denom]', ui.feeRateDenom); + } + /* + * formatBestRateElement formats a value using the best available units and + * updates the UI element. The ancestor should have descendents with data + * attributes [best-value, data-unit, data-unit-box]. + */ + static formatBestValueElement(ancestor, assetID, atoms, ui, prefs) { + const [v, unit] = this.formatBestUnitsFourSigFigs(atoms, ui, prefs); + Doc.setText(ancestor, '[data-value]', v); + Doc.setText(ancestor, '[data-unit]', unit); + const span = Doc.safeSelector(ancestor, '[data-unit-box]'); + span.dataset.atoms = String(atoms); + span.dataset.assetID = String(assetID); + } + static conventionalRateStep(rateStepEnc, baseUnitInfo, quoteUnitInfo) { + const [qFactor, bFactor] = [quoteUnitInfo.conventional.conversionFactor, baseUnitInfo.conventional.conversionFactor]; + return rateStepEnc / RateEncodingFactor * (bFactor / qFactor); + } + /* + * logoPath creates a path to a png logo for the specified ticker symbol. If + * the symbol is not a supported asset, the generic letter logo will be + * requested instead. + */ + static logoPath(symbol) { + if (BipSymbols.indexOf(symbol) === -1) + symbol = symbol.substring(0, 1); + symbol = symbol.split('.')[0]; // e.g. usdc.eth => usdc + return `/img/coins/${symbol}.png`; + } + static bipSymbol(assetID) { + return BipIDs[assetID]; + } + static bipIDFromSymbol(symbol) { + return BipSymbolIDs[symbol]; + } + static bipCEXSymbol(assetID) { + const bipSymbol = BipIDs[assetID]; + if (!bipSymbol || bipSymbol === '') + return ''; + const parts = bipSymbol.split('.'); + if (parts[0] === 'weth') + return 'eth'; + return parts[0]; + } + static logoPathFromID(assetID) { + return Doc.logoPath(BipIDs[assetID]); + } + /* + * symbolize creates a token-aware symbol element for the asset's symbol. For + * non-token assets, this is simply a SYMBOL. For tokens, it'll + * be SYMBOLPARENT. + */ + static symbolize(asset, useLogo) { + const ticker = asset.unitInfo.conventional.unit; + const symbolSpan = document.createElement('span'); + symbolSpan.textContent = ticker.toUpperCase(); + const parts = asset.symbol.split('.'); + const isToken = parts.length === 2; + if (!isToken) + return symbolSpan; + const parentSymbol = parts[1]; + const span = document.createElement('span'); + span.appendChild(symbolSpan); + if (useLogo) { + const parentLogo = document.createElement('img'); + parentLogo.src = Doc.logoPath(parentSymbol); + parentLogo.classList.add('token-parent'); + span.appendChild(parentLogo); + return span; + } + const parentSup = document.createElement('sup'); + parentSup.textContent = parentSymbol.toUpperCase(); + parentSup.classList.add('token-parent'); + span.appendChild(parentSup); + return span; + } + /* + * shortSymbol removes the short format of a symbol, with any parent chain + * identifier removed + */ + static shortSymbol(symbol) { + return symbol.split('.')[0].toUpperCase(); + } + /* + * setText sets the textContent for all descendant elements that match the + * specified CSS selector. + */ + static setText(ancestor, selector, textContent) { + for (const el of Doc.applySelector(ancestor, selector)) + el.textContent = textContent; + } + static setSrc(ancestor, selector, textContent) { + for (const img of Doc.applySelector(ancestor, selector)) + img.src = textContent; + } + /* + * cleanTemplates removes the elements from the DOM and deletes the id + * attribute. + */ + static cleanTemplates(...tmpls) { + tmpls.forEach(tmpl => { + tmpl.remove(); + tmpl.removeAttribute('id'); + }); + } + /* + * tmplElement is a helper function for grabbing sub-elements of the market list + * template. + */ + static tmplElement(ancestor, s) { + return ancestor.querySelector(`[data-tmpl="${s}"]`) || document.createElement('div'); + } + /* + * parseTemplate returns an object of data-tmpl elements, keyed by their + * data-tmpl values. + */ + static parseTemplate(ancestor) { + const d = {}; + for (const el of Doc.applySelector(ancestor, '[data-tmpl]')) + d[el.dataset.tmpl || ''] = el; + return d; + } + /* + * timeSince returns a string representation of the duration since the + * specified unix timestamp (milliseconds). + */ + static timeSince(ms) { + return Doc.formatDuration((new Date().getTime()) - ms); + } + /* + * hmsSince returns a time duration since the specified unix timestamp + * formatted as HH:MM:SS + */ + static hmsSince(secs) { + let r = (new Date().getTime() / 1000) - secs; + const h = String(Math.floor(r / 3600)); + r = r % 3600; + const m = String(Math.floor(r / 60)); + const s = String(Math.floor(r % 60)); + return `${h.padStart(2, '0')}:${m.padStart(2, '0')}:${s.padStart(2, '0')}`; + } + /* formatDuration returns a string representation of the duration */ + static formatDuration(dur) { + let seconds = Math.floor(dur); + let result = ''; + let count = 0; + const add = (n, s) => { + if (n > 0 || count > 0) + count++; + if (n > 0) + result += `${n} ${s} `; + return count >= 2; + }; + let y, mo, d, h, m, s; + [y, seconds] = timeMod(seconds, aYear); + if (add(y, 'y')) { + return result; + } + [mo, seconds] = timeMod(seconds, aMonth); + if (add(mo, 'mo')) { + return result; + } + [d, seconds] = timeMod(seconds, aDay); + if (add(d, 'd')) { + return result; + } + [h, seconds] = timeMod(seconds, anHour); + if (add(h, 'h')) { + return result; + } + [m, seconds] = timeMod(seconds, aMinute); + if (add(m, 'm')) { + return result; + } + [s, seconds] = timeMod(seconds, 1000); + add(s, 's'); + return result || '0 s'; + } + /* + * disableMouseWheel can be used to disable the mouse wheel for any + * input. It is very easy to unknowingly scroll up on a number input + * and then submit an unexpected value. This function prevents the + * scroll increment/decrement behavior for a wheel action on a + * number input. + */ + static disableMouseWheel(...inputFields) { + for (const inputField of inputFields) { + Doc.bind(inputField, 'wheel', () => { }, { passive: true }); + } + } + // showFormError can be used to set and display error message on forms. + static showFormError(el, msg) { + el.textContent = msg; + Doc.show(el); + } + // showFiatValue displays the fiat equivalent for the provided amount. + static showFiatValue(display, amount, rate, ui) { + if (rate) { + display.textContent = Doc.formatFiatConversion(amount, rate, ui); + Doc.show(display.parentElement); + } + else + Doc.hide(display.parentElement); + } +} +/* + * Animation is a handler for starting and stopping animations. + */ +class Animation { + constructor(duration, f, easingAlgo, done) { + this.done = done; + this.thread = this.run(duration, f, easingAlgo); + } + /* + * run runs the animation function, increasing progress from 0 to 1 in a + * manner dictated by easingAlgo. + */ + run(duration, f, easingAlgo) { + return __awaiter(this, void 0, void 0, function* () { + duration = duration >= 0 ? duration : 1000 * 86400 * 365 * 10; // 10 years, in ms + const easer = easingAlgo ? Easing[easingAlgo] : Easing.linear; + const start = new Date().getTime(); + const end = (duration === Animation.Forever) ? Number.MAX_SAFE_INTEGER : start + duration; + const range = end - start; + const frameDuration = 1000 / FPS; + let now = start; + this.endAnimation = false; + while (now < end) { + if (this.endAnimation) + return this.runCompletionFunction(); + f(easer((now - start) / range)); + yield sleep(frameDuration); + now = new Date().getTime(); + } + f(1); + this.runCompletionFunction(); + }); + } + /* wait returns a promise that will resolve when the animation completes. */ + wait() { + return __awaiter(this, void 0, void 0, function* () { + yield this.thread; + }); + } + /* stop schedules the animation to exit at its next frame. */ + stop() { + this.endAnimation = true; + } + /* + * stopAndWait stops the animations and returns a promise that will resolve + * when the animation exits. + */ + stopAndWait() { + return __awaiter(this, void 0, void 0, function* () { + this.stop(); + yield this.wait(); + }); + } + /* runCompletionFunction runs any registered callback function */ + runCompletionFunction() { + if (this.done) + this.done(); + } +} +Animation.Forever = -1; +/* Easing algorithms for animations. */ +const Easing = { + linear: t => t, + easeIn: t => t * t, + easeOut: t => t * (2 - t), + easeInHard: t => t * t * t, + easeOutHard: t => (--t) * t * t + 1, + easeOutElastic: t => { + const c4 = (2 * Math.PI) / 3; + return t === 0 + ? 0 + : t === 1 + ? 1 + : Math.pow(2, -10 * t) * Math.sin((t * 10 - 0.75) * c4) + 1; + } +}; +/* WalletIcons are used for controlling wallets in various places. */ +class WalletIcons { + constructor(box) { + const stateElement = (name) => box.querySelector(`[data-state=${name}]`); + this.icons = {}; + this.icons.sleeping = stateElement('sleeping'); + this.icons.locked = stateElement('locked'); + this.icons.unlocked = stateElement('unlocked'); + this.icons.nowallet = stateElement('nowallet'); + this.icons.syncing = stateElement('syncing'); + this.icons.nopeers = stateElement('nopeers'); + this.icons.disabled = stateElement('disabled'); + this.status = stateElement('status'); + } + /* sleeping sets the icons to indicate that the wallet is not connected. */ + sleeping() { + const i = this.icons; + Doc.hide(i.locked, i.unlocked, i.nowallet, i.syncing, i.disabled); + Doc.show(i.sleeping); + if (this.status) + this.status.textContent = _locales__WEBPACK_IMPORTED_MODULE_0__.prep(_locales__WEBPACK_IMPORTED_MODULE_0__.ID_OFF); + } + /* + * locked sets the icons to indicate that the wallet is connected, but locked. + */ + locked() { + const i = this.icons; + Doc.hide(i.unlocked, i.nowallet, i.sleeping, i.disabled); + Doc.show(i.locked); + if (this.status) + this.status.textContent = _locales__WEBPACK_IMPORTED_MODULE_0__.prep(_locales__WEBPACK_IMPORTED_MODULE_0__.ID_LOCKED); + } + /* + * unlocked sets the icons to indicate that the wallet is connected and + * unlocked. + */ + unlocked() { + const i = this.icons; + Doc.hide(i.locked, i.nowallet, i.sleeping, i.disabled); + Doc.show(i.unlocked); + if (this.status) + this.status.textContent = _locales__WEBPACK_IMPORTED_MODULE_0__.prep(_locales__WEBPACK_IMPORTED_MODULE_0__.ID_READY); + } + /* nowallet sets the icons to indicate that no wallet exists. */ + nowallet() { + const i = this.icons; + Doc.hide(i.locked, i.unlocked, i.sleeping, i.syncing, i.disabled); + Doc.show(i.nowallet); + if (this.status) + this.status.textContent = _locales__WEBPACK_IMPORTED_MODULE_0__.prep(_locales__WEBPACK_IMPORTED_MODULE_0__.ID_NO_WALLET); + } + /* set the icons to indicate that the wallet is disabled */ + disabled() { + const i = this.icons; + Doc.hide(i.locked, i.unlocked, i.sleeping, i.syncing, i.nowallet, i.nopeers); + Doc.show(i.disabled); + i.disabled.dataset.tooltip = _locales__WEBPACK_IMPORTED_MODULE_0__.prep(_locales__WEBPACK_IMPORTED_MODULE_0__.ID_DISABLED_MSG); + } + setSyncing(wallet) { + const syncIcon = this.icons.syncing; + if (!wallet || !wallet.running || wallet.disabled) { + Doc.hide(syncIcon); + return; + } + if (wallet.peerCount === 0) { + Doc.show(this.icons.nopeers); + Doc.hide(syncIcon); // potentially misleading with no peers + return; + } + Doc.hide(this.icons.nopeers); + if (!wallet.synced) { + Doc.show(syncIcon); + syncIcon.dataset.tooltip = _locales__WEBPACK_IMPORTED_MODULE_0__.prep(_locales__WEBPACK_IMPORTED_MODULE_0__.ID_WALLET_SYNC_PROGRESS, { syncProgress: (wallet.syncProgress * 100).toFixed(1) }); + return; + } + Doc.hide(syncIcon); + } + /* reads the core.Wallet state and sets the icon visibility. */ + readWallet(wallet) { + this.setSyncing(wallet); + if (!wallet) + return this.nowallet(); + switch (true) { + case (wallet.disabled): + this.disabled(); + break; + case (!wallet.running): + this.sleeping(); + break; + case (!wallet.open): + this.locked(); + break; + case (wallet.open): + this.unlocked(); + break; + default: + console.error('wallet in unknown state', wallet); + } + } +} +/* + * AniToggle is a small toggle switch, defined in HTML with the element + *
. The animations are defined in the anitoggle + * CSS class. AniToggle triggers the callback on click events, but does not + * update toggle appearance, so the caller must call the setState method from + * the callback or elsewhere if the newState + * is accepted. + */ +class AniToggle { + constructor(toggle, errorEl, initialState, callback) { + this.toggle = toggle; + if (toggle.children.length === 0) + toggle.appendChild(document.createElement('div')); + Doc.bind(toggle, 'click', (e) => __awaiter(this, void 0, void 0, function* () { + e.stopPropagation(); + Doc.hide(errorEl); + const newState = !toggle.classList.contains('on'); + this.toggling = true; + try { + yield callback(newState); + } + catch (e) { + this.toggling = false; + Doc.show(errorEl); + errorEl.textContent = _locales__WEBPACK_IMPORTED_MODULE_0__.prep(_locales__WEBPACK_IMPORTED_MODULE_0__.ID_API_ERROR, { msg: e.msg || String(e) }); + return; + } + this.toggling = false; + })); + this.setState(initialState); + } + setState(state) { + if (state) + this.toggle.classList.add('on'); + else + this.toggle.classList.remove('on'); + } +} +/* sleep can be used by async functions to pause for a specified period. */ +function sleep(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); +} +const aYear = 31536000000; +const aMonth = 2592000000; +const aDay = 86400000; +const anHour = 3600000; +const aMinute = 60000; +/* timeMod returns the quotient and remainder of t / dur. */ +function timeMod(t, dur) { + const n = Math.floor(t / dur); + return [n, t - n * dur]; +} +function formatSigFigsWithFormatters(intFormatter, sigFigFormatter, n, maxDecimals, locales) { + var _a, _b; + if (n >= 1000) + return intFormatter.format(n); + const s = sigFigFormatter.format(n); + if (typeof maxDecimals !== 'number') + return s; + const fractional = (_b = (_a = sigFigFormatter.formatToParts(n).filter((part) => part.type === 'fraction')[0]) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : ''; + if (fractional.length <= maxDecimals) + return s; + return fullPrecisionFormatter(maxDecimals, locales).format(n); +} +if (true) { + // Code will only appear in dev build. + // https://webpack.js.org/guides/production/ + window.testFormatFourSigFigs = () => { + const tests = [ + ['en-US', '1.234567', undefined, '1.235'], + ['en-US', '1.234567', 2, '1.23'], + ['en-US', '1234', undefined, '1,234.0'], + ['en-US', '12', undefined, '12.00'], + ['fr-FR', '123.45678', undefined, '123,5'], + ['fr-FR', '1234.5', undefined, '1 234,5'], + // For Arabic, https://www.saitak.com/number is useful, but seems to use + // slightly different unicode points and no thousands separator. I think + // the Arabic decimal separator is supposed to be more like a point, not + // a comma, but Google Chrome uses U+066B (Arabic Decimal Separator), + // which looks like a comma to me. ¯\_(ツ)_/¯ + ['ar-EG', '123.45678', undefined, '١٢٣٫٥'], + ['ar-EG', '1234', undefined, '١٬٢٣٤٫٠'], + ['ar-EG', '0.12345', 3, '٠٫١٢٣'] + ]; + // Reproduce the NumberFormats with ONLY our desired language. + for (const [code, unformatted, maxDecimals, expected] of tests) { + const intFormatter = new Intl.NumberFormat(code, { + minimumFractionDigits: 1, + maximumFractionDigits: 1 + }); + const sigFigFormatter = new Intl.NumberFormat(code, { + minimumSignificantDigits: 4, + maximumSignificantDigits: 4 + }); + for (const k in decimalFormatters) + delete decimalFormatters[k]; // cleanup + for (const k in fullPrecisionFormatters) + delete fullPrecisionFormatters[k]; // cleanup + const s = formatSigFigsWithFormatters(intFormatter, sigFigFormatter, parseFloatDefault(unformatted), maxDecimals, code); + if (s !== expected) + console.log(`TEST FAILED: f('${code}', ${unformatted}, ${maxDecimals}) => '${s}' != '${expected}'}`); + else + console.log(`✔️ f('${code}', ${unformatted}, ${maxDecimals}) => ${s} ✔️`); + } + }; + window.testFormatRateFullPrecision = () => { + const tests = [ + // Two utxo assets with a conventional rate of 0.15. Conventional rate + // step is 100 / 1e8 = 1e-6, so there should be 6 decimal digits. + [1.5e7, 100, 1e8, 1e8, '0.150000'], + // USDC quote -> utxo base with a rate of $10 / 1 XYZ. USDC has an + // conversion factor of 1e6, so $10 encodes to 1e7, 1 XYZ encodes to 1e8, + // encoded rate is 1e7 / 1e8 * 1e8 = 1e7, bFactor / qFactor is 1e2. + // The conventional rate step is 200 / 1e8 * 1e2 = 2e-4, so using + // rateStepDigits, we should get 4 decimal digits. + [1e7, 200, 1e6, 1e8, '10.0000'], + // Set a rate of 1 atom USDC for 0.01 BTC. That atomic rate will be 1 / + // 1e6 = 1e-6. The encoded rate will be 1e-6 * 1e8 = 1e2. As long as our + // rate step divides evenly into 100, this should work. The conventional + // rate is 1e-6 / 1e-2 = 1e-4, so expect 4 decimal digits. + [1e2, 100, 1e6, 1e8, '0.0001'], + // DCR-ETH, expect 6 decimals. + [1.5e7, 1000, 1e9, 1e8, '0.015000'], + [1e6, 1000, 1e9, 1e8, '0.001000'], + [1e3, 1000, 1e9, 1e8, '0.000001'], + [100001000, 1000, 1e9, 1e8, '0.100001'], + [1000001000, 1000, 1e9, 1e8, '1.000001'], + // DCR-USDC, expect 3 decimals. + [1.5e7, 1000, 1e6, 1e8, '15.000'], + [1e6, 1000, 1e6, 1e8, '1.000'], + [1e3, 1000, 1e6, 1e8, '0.001'], + [101000, 1000, 1e6, 1e8, '0.101'], + [1001000, 1000, 1e6, 1e8, '1.001'], + // UTXO assets but with a rate step that's not a perfect power of 10. + // For a rate step of 500, a min rate would be e.g. rate step = 500. + // 5e2 / 1e8 = 5e-6 = 0.000005 + [5e2, 500, 1e8, 1e8, '0.000005'] + ]; + for (const [encRate, rateStep, qFactor, bFactor, expEncoding] of tests) { + for (const k in fullPrecisionFormatters) + delete fullPrecisionFormatters[k]; // cleanup + const bui = { conventional: { conversionFactor: bFactor } }; + const qui = { conventional: { conversionFactor: qFactor } }; + const enc = Doc.formatRateFullPrecision(encRate, bui, qui, rateStep); + if (enc !== expEncoding) + console.log(`TEST FAILED: f(${encRate}, ${bFactor}, ${qFactor}, ${rateStep}) => ${enc} != ${expEncoding}`); + else + console.log(`✔️ f(${encRate}, ${bFactor}, ${qFactor}, ${rateStep}) => ${enc} ✔️`); + } + }; +} +class NumberInput { + constructor(input, opts) { + var _a, _b, _c; + this.input = input; + this.prec = (_a = opts.prec) !== null && _a !== void 0 ? _a : 0; + this.fmt = opts.sigFigs ? toFourSigFigs : toPrecision; + this.changed = (_b = opts.changed) !== null && _b !== void 0 ? _b : (() => { }); + this.set = opts.set; + this.min = (_c = opts.min) !== null && _c !== void 0 ? _c : 0; + Doc.bind(input, 'change', () => { this.inputChanged(); }); + } + inputChanged() { + const { changed } = this; + if (changed) + changed(this.value()); + } + setValue(v) { + this.input.value = String(v); + v = this.value(); + if (this.set) + this.set(v, this.input.value); + } + value() { + const { input, min, prec, fmt } = this; + const rawV = Math.max(parseFloatDefault(input.value, min !== null && min !== void 0 ? min : 0), min !== null && min !== void 0 ? min : 0); + const [v, s] = fmt(rawV, prec !== null && prec !== void 0 ? prec : 0); + input.value = s; + return v; + } +} +class IncrementalInput extends NumberInput { + constructor(box, opts) { + var _a; + super(Doc.safeSelector(box, 'input'), opts); + this.opts = opts; + this.inc = (_a = opts.inc) !== null && _a !== void 0 ? _a : 1; + const up = Doc.safeSelector(box, '.ico-arrowup'); + const down = Doc.safeSelector(box, '.ico-arrowdown'); + Doc.bind(up, 'click', () => { this.increment(1); }); + Doc.bind(down, 'click', () => { this.increment(-1); }); + } + setIncrementAndMinimum(inc, min) { + this.inc = inc; + this.min = min; + } + increment(sign) { + const { inc, min, input } = this; + input.value = String(Math.max(this.value() + sign * inc, min)); + this.inputChanged(); + } +} +class MiniSlider { + constructor(box, changed) { + this.changed = changed; + this.r = 0; + const color = document.createElement('div'); + color.dataset.tmpl = 'color'; + box.appendChild(color); + const track = this.track = document.createElement('div'); + track.dataset.tmpl = 'track'; + color.appendChild(track); + const ball = this.ball = document.createElement('div'); + ball.dataset.tmpl = 'ball'; + track.appendChild(ball); + Doc.bind(box, 'mousedown', (e) => { + if (e.button !== 0) + return; + e.preventDefault(); + e.stopPropagation(); + const startX = e.pageX; + const w = track.clientWidth; + const startLeft = this.r * w; + const left = (ee) => Math.max(Math.min(startLeft + (ee.pageX - startX), w), 0); + const trackMouse = (ee) => { + ee.preventDefault(); + const l = left(ee); + this.r = l / w; + ball.style.left = `${this.r * 100}%`; + this.changed(this.r); + }; + const mouseUp = (ee) => { + trackMouse(ee); + Doc.unbind(document, 'mousemove', trackMouse); + Doc.unbind(document, 'mouseup', mouseUp); + }; + Doc.bind(document, 'mousemove', trackMouse); + Doc.bind(document, 'mouseup', mouseUp); + }); + Doc.bind(box, 'click', (e) => { + if (e.button !== 0) + return; + const x = e.pageX; + const m = Doc.layoutMetrics(track); + this.r = clamp((x - m.bodyLeft) / m.width, 0, 1); + ball.style.left = `${this.r * m.width}px`; + this.changed(this.r); + }); + } + setValue(r) { + this.r = clamp(r, 0, 1); + this.ball.style.left = `${this.r * 100}%`; + } +} +function toPrecision(v, prec) { + const ord = Math.pow(10, prec !== null && prec !== void 0 ? prec : 0); + v = Math.round(v * ord) / ord; + let s = v.toFixed(prec); + if (prec > 0) { + while (s.endsWith('0')) + s = s.substring(0, s.length - 1); + if (s.endsWith('.')) + s = s.substring(0, s.length - 1); + } + return [v, s]; +} +function toFourSigFigs(v, maxPrec) { + const ord = Math.floor(Math.log10(Math.abs(v))); + if (ord >= 3) + return [Math.round(v), v.toFixed(0)]; + const prec = Math.min(4 - ord, maxPrec); + return toPrecision(v, prec); +} +function parseFloatDefault(inputValue, defaultValue) { + const v = parseFloat((inputValue !== null && inputValue !== void 0 ? inputValue : '').replace(/,/g, '')); + if (!isNaN(v)) + return v; + return defaultValue !== null && defaultValue !== void 0 ? defaultValue : 0; +} +/* clamp returns v if min <= v <= max, else min or max. */ +function clamp(v, min, max) { + if (v < min) + return min; + if (v > max) + return max; + return v; +} +function setupCopyBtn(txt, textEl, btnEl, color) { + return __awaiter(this, void 0, void 0, function* () { + try { + yield navigator.clipboard.writeText(txt); + } + catch (err) { + console.error('Unable to copy: ', err); + } + const textOriginalColor = textEl.style.color; + const btnOriginalColor = btnEl.style.color; + textEl.style.color = color; + btnEl.style.color = color; + setTimeout(() => { + textEl.style.color = textOriginalColor; + btnEl.style.color = btnOriginalColor; + }, 350); + }); +} + + +/***/ }), + +/***/ "./src/js/forms.ts": +/*!*************************!*\ + !*** ./src/js/forms.ts ***! + \*************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "AccelerateOrderForm": () => (/* binding */ AccelerateOrderForm), +/* harmony export */ "AppPassResetForm": () => (/* binding */ AppPassResetForm), +/* harmony export */ "CEXConfigurationForm": () => (/* binding */ CEXConfigurationForm), +/* harmony export */ "CertificatePicker": () => (/* binding */ CertificatePicker), +/* harmony export */ "ConfirmRegistrationForm": () => (/* binding */ ConfirmRegistrationForm), +/* harmony export */ "DEXAddressForm": () => (/* binding */ DEXAddressForm), +/* harmony export */ "DepositAddress": () => (/* binding */ DepositAddress), +/* harmony export */ "DiscoverAccountForm": () => (/* binding */ DiscoverAccountForm), +/* harmony export */ "FeeAssetSelectionForm": () => (/* binding */ FeeAssetSelectionForm), +/* harmony export */ "Forms": () => (/* binding */ Forms), +/* harmony export */ "LoginForm": () => (/* binding */ LoginForm), +/* harmony export */ "NewWalletForm": () => (/* binding */ NewWalletForm), +/* harmony export */ "TokenApprovalForm": () => (/* binding */ TokenApprovalForm), +/* harmony export */ "WalletConfigForm": () => (/* binding */ WalletConfigForm), +/* harmony export */ "WalletWaitForm": () => (/* binding */ WalletWaitForm), +/* harmony export */ "bind": () => (/* binding */ bind), +/* harmony export */ "showSuccess": () => (/* binding */ showSuccess), +/* harmony export */ "slideSwap": () => (/* binding */ slideSwap) +/* harmony export */ }); +/* harmony import */ var _doc__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./doc */ "./src/js/doc.ts"); +/* harmony import */ var _http__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./http */ "./src/js/http.ts"); +/* harmony import */ var _state__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./state */ "./src/js/state.ts"); +/* harmony import */ var _locales__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./locales */ "./src/js/locales.ts"); +/* harmony import */ var _charts__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./charts */ "./src/js/charts.ts"); +/* harmony import */ var _account__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./account */ "./src/js/account.ts"); +/* harmony import */ var _registry__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./registry */ "./src/js/registry.ts"); +/* harmony import */ var _opts__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./opts */ "./src/js/opts.ts"); +/* harmony import */ var _coinexplorers__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./coinexplorers */ "./src/js/coinexplorers.ts"); +/* harmony import */ var _mmutil__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./mmutil */ "./src/js/mmutil.ts"); +var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; + + + + + + + + + + +class Forms { + constructor(formsDiv, cfg) { + this.formsDiv = formsDiv; + this.closed = cfg === null || cfg === void 0 ? void 0 : cfg.closed; + formsDiv.querySelectorAll('.form-closer').forEach(el => { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(el, 'click', () => { this.close(); }); + }); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(formsDiv, 'mousedown', (e) => { + if (!this.currentForm) + return; + if (!_doc__WEBPACK_IMPORTED_MODULE_0__["default"].mouseInElement(e, this.currentForm)) { + this.close(); + } + }); + this.keyup = (e) => { + if (e.key === 'Escape') { + this.close(); + } + }; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(document, 'keyup', this.keyup); + } + /* showForm shows a modal form with a little animation. */ + show(form) { + return __awaiter(this, void 0, void 0, function* () { + this.currentForm = form; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(...Array.from(this.formsDiv.children)); + form.style.right = '10000px'; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(this.formsDiv, form); + const shift = (this.formsDiv.offsetWidth + form.offsetWidth) / 2; + yield _doc__WEBPACK_IMPORTED_MODULE_0__["default"].animate(animationLength, progress => { + form.style.right = `${(1 - progress) * shift}px`; + }, 'easeOutHard'); + form.style.right = '0'; + }); + } + close() { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(this.formsDiv); + if (this.closed) + this.closed(); + this.currentForm = undefined; + } + exit() { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].unbind(document, 'keyup', this.keyup); + } +} +/* + * NewWalletForm should be used with the "newWalletForm" template. The enclosing + *
element should be the first argument of the constructor. + */ +class NewWalletForm { + constructor(form, success, backFunc) { + this.form = form; + this.success = success; + const page = this.page = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].parseTemplate(form); + if (backFunc) { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.goBack); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(page.goBack, 'click', () => { backFunc(); }); + } + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].empty(page.walletTabTmpl); + page.walletTabTmpl.removeAttribute('id'); + // WalletConfigForm will set the global app variable. + this.subform = new WalletConfigForm(page.walletSettings, true); + this.walletCfgGuide = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].tmplElement(form, 'walletCfgGuide'); + bind(form, page.submitAdd, () => this.submit()); + bind(form, page.oneBttn, () => this.submit()); + (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().registerNoteFeeder({ + walletstate: (note) => { this.reportWalletState(note.wallet); }, + walletsync: (note) => { if (this.parentSyncer) + this.parentSyncer((0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().walletMap[note.assetID]); }, + createwallet: (note) => { this.reportCreationUpdate(note); } + }); + } + /* + * reportWalletState should be called when a 'walletstate' notification is + * received. + * TODO: Let form classes register for notifications. + */ + reportWalletState(w) { + if (this.parentSyncer) + this.parentSyncer(w); + } + /* + * reportWalletState should be called when a 'createwallet' notification is + * received. + */ + reportCreationUpdate(note) { + if (this.createUpdater) + this.createUpdater(note); + } + createWallet(assetID, walletType, parentForm) { + return __awaiter(this, void 0, void 0, function* () { + const createForm = { + assetID: assetID, + pass: this.page.newWalletPass.value || '', + config: this.subform.map(assetID), + walletType: walletType, + parentForm: parentForm + }; + const ani = new _charts__WEBPACK_IMPORTED_MODULE_4__.Wave(this.form, { backgroundColor: true }); + const res = yield (0,_http__WEBPACK_IMPORTED_MODULE_1__.postJSON)('/api/newwallet', createForm); + ani.stop(); + return res; + }); + } + submit() { + return __awaiter(this, void 0, void 0, function* () { + const page = this.page; + const newWalletPass = page.newWalletPass; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.newWalletErr); + const { asset, parentAsset } = this.current; + const selectedDef = this.current.selectedDef; + let parentForm; + let walletType = selectedDef.type; + if (parentAsset) { + walletType = asset.token.definition.type; + parentForm = { + assetID: parentAsset.id, + config: this.subform.map(parentAsset.id), + walletType: selectedDef.type + }; + } + // Register the selected asset. + const res = yield this.createWallet(asset.id, walletType, parentForm); + if (!(0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().checkResponse(res)) { + this.setError(res.msg); + return; + } + newWalletPass.value = ''; + if (parentAsset) + yield this.runParentSync(); + else + this.success(this.current.asset.id); + }); + } + /* + * runParentSync shows a syncing sub-dialog that tracks the parent asset's + * syncProgress and informs the user that the token wallet will be created + * after sync is complete. + */ + runParentSync() { + return __awaiter(this, void 0, void 0, function* () { + const { page, current: { parentAsset, asset } } = this; + if (!parentAsset) + return; + page.parentSyncPct.textContent = '0'; + page.parentName.textContent = parentAsset.name; + page.parentLogo.src = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].logoPath(parentAsset.symbol); + page.childName.textContent = asset.name; + page.childLogo.src = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].logoPath(asset.symbol); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.mainForm); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.parentSyncing); + try { + yield this.syncParent(parentAsset); + this.success(this.current.asset.id); + } + catch (error) { + this.setError(error.message || error); + } + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.mainForm); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.parentSyncing); + }); + } + /* + * syncParent monitors the sync progress of a token's parent asset, generating + * an Error if the token wallet creation does not complete successfully. + */ + syncParent(parentAsset) { + const { page, current: { asset } } = this; + return new Promise((resolve, reject) => { + // First, check if it's already synced. + const w = (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().assets[parentAsset.id].wallet; + if (w && w.synced) + return resolve(); + // Not synced, so create a syncer to update the parent sync pane. + this.parentSyncer = (w) => { + if (w.assetID !== parentAsset.id) + return; + page.parentSyncPct.textContent = (w.syncProgress * 100).toFixed(1); + }; + // Handle the async result. + this.createUpdater = (note) => { + if (note.assetID !== asset.id) + return; + switch (note.topic) { + case 'QueuedCreationFailed': + reject(new Error(`${note.subject}: ${note.details}`)); + break; + case 'QueuedCreationSuccess': + resolve(); + break; + default: + return; + } + this.parentSyncer = null; + this.createUpdater = null; + }; + }); + } + /* setAsset sets the current asset of the NewWalletForm */ + setAsset(assetID) { + return __awaiter(this, void 0, void 0, function* () { + if (!this.parseAsset(assetID)) + return; // nothing to change + const page = this.page; + const tabs = page.walletTypeTabs; + const { winfo, asset, parentAsset } = this.current; + page.assetName.textContent = winfo.name; + page.newWalletPass.value = ''; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].empty(tabs); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(tabs, page.newWalletErr, page.tokenMsgBox); + this.page.assetLogo.src = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].logoPath(asset.symbol); + if (parentAsset) { + page.tokenParentLogo.src = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].logoPath(parentAsset.symbol); + page.tokenParentName.textContent = parentAsset.name; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.tokenMsgBox); + } + const pinfo = parentAsset ? parentAsset.info : null; + const walletDefs = pinfo ? pinfo.availablewallets : winfo.availablewallets ? winfo.availablewallets : [winfo.definition]; + if (walletDefs.length > 1) { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(tabs); + for (const wDef of walletDefs) { + const tab = page.walletTabTmpl.cloneNode(true); + tab.dataset.tooltip = wDef.description; + tab.textContent = wDef.tab; + tabs.appendChild(tab); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(tab, 'click', () => { + for (const t of _doc__WEBPACK_IMPORTED_MODULE_0__["default"].kids(tabs)) + t.classList.remove('selected'); + tab.classList.add('selected'); + this.update(wDef); + }); + } + (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().bindTooltips(tabs); + const first = tabs.firstChild; + first.classList.add('selected'); + } + yield this.update(this.current.selectedDef); + if (asset.walletCreationPending) + yield this.runParentSync(); + }); + } + /* + * parseAsset parses the current data for the asset ID. + */ + parseAsset(assetID) { + if (this.current && this.current.asset.id === assetID) + return false; + const asset = (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().assets[assetID]; + const token = asset.token; + if (!token) { + if (!asset.info) + throw Error('this non-token asset has no wallet info!'); + this.current = { asset, winfo: asset.info, selectedDef: asset.info.availablewallets[0] }; + return true; + } + const parentAsset = (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().user.assets[token.parentID]; + if (parentAsset.wallet) { + // If the parent asset already has a wallet, there's no need to configure + // the parent too. Just configure the token. + this.current = { asset, winfo: token, selectedDef: token.definition }; + return true; + } + if (!parentAsset.info) + throw Error('this parent has no wallet info!'); + this.current = { asset, parentAsset, winfo: token, selectedDef: parentAsset.info.availablewallets[0] }; + return true; + } + update(walletDef) { + return __awaiter(this, void 0, void 0, function* () { + const page = this.page; + this.current.selectedDef = walletDef; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.walletPassAndSubmitBttn, page.oneBttnBox, page.newWalletPassBox); + const guideLink = walletDef.guidelink; + const configOpts = walletDef.configopts || []; + // If a config represents a wallet's birthday, we update the default + // selection to the current date if this installation of the client + // generated a seed. + configOpts.map((opt) => { + if (opt.isBirthdayConfig && (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().seedGenTime > 0) { + opt.default = toUnixDate(new Date()); + } + return opt; + }); + // Either this is a walletDef for a token's uncreated parent asset, or this + // is the definition for the token. + let containsRequired = false; + for (const opt of configOpts) { + if (opt.required) { + containsRequired = true; + break; + } + } + const { asset, parentAsset, winfo } = this.current; + const displayCreateBtn = walletDef.seeded || Boolean(asset.token); + if (displayCreateBtn && !containsRequired) { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(page.walletSettingsHeader); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.oneBttnBox); + } + else if (displayCreateBtn) { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.walletPassAndSubmitBttn, page.walletSettingsHeader); + page.newWalletPass.value = ''; + page.submitAdd.textContent = _locales__WEBPACK_IMPORTED_MODULE_3__.prep(_locales__WEBPACK_IMPORTED_MODULE_3__.ID_CREATE); + } + else { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.walletPassAndSubmitBttn, page.walletSettingsHeader); + if (!walletDef.noauth) + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(page.newWalletPassBox); + page.submitAdd.textContent = _locales__WEBPACK_IMPORTED_MODULE_3__.prep(_locales__WEBPACK_IMPORTED_MODULE_3__.ID_ADD); + } + if (parentAsset) { + const parentAndTokenOpts = JSON.parse(JSON.stringify(configOpts)); + // Add the regAsset field to the configurations so proper logos will be displayed + // next to them, and map can filter them out. The opts are copied here so the originals + // do not have the regAsset field added to them. + for (const opt of parentAndTokenOpts) + opt.regAsset = parentAsset.id; + const tokenOpts = winfo.definition.configopts || []; + if (tokenOpts.length > 0) { + const tokenOptsCopy = JSON.parse(JSON.stringify(tokenOpts)); + for (const opt of tokenOptsCopy) + opt.regAsset = asset.id; + parentAndTokenOpts.push(...tokenOptsCopy); + } + this.subform.update(asset.id, parentAndTokenOpts, false); + } + else + this.subform.update(asset.id, configOpts, false); + this.setGuideLink(guideLink); + // A seeded or token wallet is internal to Bison Wallet and as such does + // not have an external config file to select. + if (walletDef.seeded || Boolean(this.current.asset.token)) + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(this.subform.fileSelector); + else + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(this.subform.fileSelector); + yield this.loadDefaults(); + }); + } + setGuideLink(guideLink) { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(this.walletCfgGuide); + if (guideLink !== '') { + this.walletCfgGuide.href = guideLink; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(this.walletCfgGuide); + } + } + /* setError sets and shows the in-form error message. */ + setError(errMsg) { + return __awaiter(this, void 0, void 0, function* () { + this.page.newWalletErr.textContent = errMsg; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(this.page.newWalletErr); + }); + } + /* + * loadDefaults attempts to load the ExchangeWallet configuration from the + * default wallet config path on the server and will auto-fill the page on + * the subform if settings are found. + */ + loadDefaults() { + return __awaiter(this, void 0, void 0, function* () { + // No default config files for seeded assets right now. + const { asset, parentAsset, selectedDef } = this.current; + if (!selectedDef.configpath) + return; + let configID = asset.id; + if (parentAsset) { + if (selectedDef.seeded) + return; + configID = parentAsset.id; + } + const loaded = (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().loading(this.form); + const res = yield (0,_http__WEBPACK_IMPORTED_MODULE_1__.postJSON)('/api/defaultwalletcfg', { + assetID: configID, + type: selectedDef.type + }); + loaded(); + if (!(0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().checkResponse(res)) { + this.setError(res.msg); + return; + } + this.subform.setLoadedConfig(res.config); + }); + } +} +let dynamicInputCounter = 0; +/* + * WalletConfigForm is a dynamically generated sub-form for setting + * asset-specific wallet configuration options. +*/ +class WalletConfigForm { + constructor(form, sectionize) { + this.page = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].idDescendants(form); + this.form = form; + // A configElement is a div containing an input and its label. + this.configElements = []; + // configOpts is the wallet options provided by core. + this.configOpts = []; + this.sectionize = sectionize; + // Get template elements + this.allSettings = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].tmplElement(form, 'allSettings'); + this.dynamicOpts = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].tmplElement(form, 'dynamicOpts'); + this.textInputTmpl = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].tmplElement(form, 'textInput'); + this.textInputTmpl.remove(); + this.dateInputTmpl = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].tmplElement(form, 'dateInput'); + this.dateInputTmpl.remove(); + this.checkboxTmpl = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].tmplElement(form, 'checkbox'); + this.checkboxTmpl.remove(); + this.repeatableTmpl = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].tmplElement(form, 'repeatableInput'); + this.repeatableTmpl.remove(); + this.fileSelector = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].tmplElement(form, 'fileSelector'); + this.fileInput = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].tmplElement(form, 'fileInput'); + this.errMsg = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].tmplElement(form, 'errMsg'); + this.showOther = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].tmplElement(form, 'showOther'); + this.showIcon = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].tmplElement(form, 'showIcon'); + this.hideIcon = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].tmplElement(form, 'hideIcon'); + this.showHideMsg = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].tmplElement(form, 'showHideMsg'); + this.otherSettings = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].tmplElement(form, 'otherSettings'); + this.loadedSettingsMsg = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].tmplElement(form, 'loadedSettingsMsg'); + this.loadedSettings = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].tmplElement(form, 'loadedSettings'); + this.defaultSettingsMsg = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].tmplElement(form, 'defaultSettingsMsg'); + this.defaultSettings = _doc__WEBPACK_IMPORTED_MODULE_0__["default"].tmplElement(form, 'defaultSettings'); + if (!sectionize) + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(this.showOther); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(this.fileSelector, 'click', () => this.fileInput.click()); + // config file upload + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(this.fileInput, 'change', () => __awaiter(this, void 0, void 0, function* () { return this.fileInputChanged(); })); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(this.showOther, 'click', () => { + this.setOtherSettingsViz(this.hideIcon.classList.contains('d-hide')); + }); + } + /* + * fileInputChanged will read the selected file and attempt to load the + * configuration settings. All loaded settings will be made visible for + * inspection by the user. + */ + fileInputChanged() { + return __awaiter(this, void 0, void 0, function* () { + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(this.errMsg); + if (!this.fileInput.value) + return; + const files = this.fileInput.files; + if (!files || files.length === 0) + return; + const loaded = (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().loading(this.form); + const config = yield files[0].text(); + if (!config) + return; + const res = yield (0,_http__WEBPACK_IMPORTED_MODULE_1__.postJSON)('/api/parseconfig', { + configtext: config + }); + loaded(); + if (!(0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().checkResponse(res)) { + this.errMsg.textContent = res.msg; + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].show(this.errMsg); + return; + } + if (Object.keys(res.map).length === 0) + return; + this.dynamicOpts.append(...this.setConfig(res.map)); + this.reorder(this.dynamicOpts); + const [loadedOpts, defaultOpts] = [this.loadedSettings.children.length, this.defaultSettings.children.length]; + if (loadedOpts === 0) + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(this.loadedSettings, this.loadedSettingsMsg); + if (defaultOpts === 0) + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(this.defaultSettings, this.defaultSettingsMsg); + if (loadedOpts + defaultOpts === 0) + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(this.showOther, this.otherSettings); + }); + } + addOpt(box, opt, insertAfter, skipRepeatN) { + var _a; + let el; + if (opt.isboolean) + el = this.checkboxTmpl.cloneNode(true); + else if (opt.isdate) + el = this.dateInputTmpl.cloneNode(true); + else if (opt.repeatable) { + el = this.repeatableTmpl.cloneNode(true); + el.classList.add('repeatable'); + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].bind(_doc__WEBPACK_IMPORTED_MODULE_0__["default"].tmplElement(el, 'add'), 'click', () => { + this.addOpt(box, opt, el, true); + }); + if (!skipRepeatN) + for (let i = 0; i < (opt.repeatN ? opt.repeatN - 1 : 0); i++) + this.addOpt(box, opt, insertAfter, true); + } + else + el = this.textInputTmpl.cloneNode(true); + const hiddenFields = ((_a = (0,_registry__WEBPACK_IMPORTED_MODULE_6__.app)().extensionWallet(this.assetID)) === null || _a === void 0 ? void 0 : _a.hiddenFields) || []; + if (hiddenFields.indexOf(opt.key) !== -1) + _doc__WEBPACK_IMPORTED_MODULE_0__["default"].hide(el); + this.configElements.push([opt, el]); + const input = el.querySelector('input'); + input.dataset.configKey = opt.key; + // We need to generate a unique ID only for the =>