diff --git a/client/webserver/site/dist/entry.js b/client/webserver/site/dist/entry.js index c1370724df..8deb60802f 100644 --- a/client/webserver/site/dist/entry.js +++ b/client/webserver/site/dist/entry.js @@ -1,3 +1,3 @@ /*! 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:S(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 C(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 S(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 C.apply(this,arguments)}function C(){return(C=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 S(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="LIMIT_ORDER",K="MARKET_ORDER",Q="MATCH_STATUS_REDEMPTION_SENT",Y="MATCH_REDEMPTION_CONFIRMED",J="MATCH_STATUS_REFUND_PENDING",Z="ORDER_ACCELERATION_ERR_MSG",$="DISCONNECTED",ee="BROWSER_NTFN_ENABLED",te="ORDER_BUTTON_BUY_BALANCE_ERROR",ne="ORDER_BUTTON_SELL_BALANCE_ERROR",re="ORDER_BUTTON_QTY_ERROR",ae="ORDER_BUTTON_QTY_RATE_ERROR",oe="CREATE_ASSET_WALLET_MSG",se="TRADING_TIER_UPDATED",ie="INVALID_TIER_VALUE",ce="MATCH_BUFFER",le="NO_PLACEMENTS",ue="INVALID_VALUE",de="NO_ZERO",he="BOTTYPE_BASIC_MM",pe="BOTTYPE_ARB_MM",fe="BOTTYPE_SIMPLE_ARB",ve="CEXBALANCE_ERR",me="PENDING",ge="COMPLETE",ye="CEX_NOT_CONNECTED";function be(e,t,n){return xe.apply(this,arguments)}function xe(){return(xe=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,S("/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 ke(e,t){return function(e,t){return e.replace(/{{\s?([^{}\s]*)\s?}}/g,(function(e,n){return t[n]}))}(I[e],t||{})}function we(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 Ce(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)?Ce(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 Ce(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;a1?n-1:0),a=1;a"),e),document.createElement("div"))}},{key:"idDescendants",value:function(t){var n,r={},a=we(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(qe(e,t),2),r=n[0],o=n[1];return Number.isInteger(r)?Ee.format(r):function(e){return Me(Pe,2,e)}(o).format(r)}},{key:"conventionalCoinValue",value:function(e,t){return a(qe(e,t),1)[0]}},{key:"formatRateFullPrecision",value:function(e,t,n,r){var a=e*(t.conventional.conversionFactor/n.conventional.conversionFactor)/Ie,o=Ae-Math.floor(Math.log10(r))-Math.floor(Math.log10(t.conventional.conversionFactor)-Math.log10(n.conventional.conversionFactor));return o<=0?Ee.format(a):Oe(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:Oe(r,void 0).format(n)}(Ee,Be,e,t)}},{key:"formatInt",value:function(e){return Ee.format(e)}},{key:"formatFullPrecision",value:function(e,t){var n=a(qe(e,t),2),r=n[0];return Oe(n[1]).format(r)}},{key:"formatFiatConversion",value:function(e,t,n){if(!t||0===t)return ke("UNAVAILABLE");var r=a(qe(e,n),1)[0]*t;return Oe(2).format(r)}},{key:"languages",value:function(){return Re}},{key:"formatFiatValue",value:function(e){return Oe(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=we(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(Qe(c,He),2);if(t=h[0],c=h[1],d(t,"y"))return l;var p=a(Qe(c,ze),2);if(n=p[0],c=p[1],d(n,"mo"))return l;var f=a(Qe(c,Ge),2);if(r=f[0],c=f[1],d(r,"d"))return l;var v=a(Qe(c,Xe),2);if(o=v[0],c=v[1],d(o,"h"))return l;var m=a(Qe(c,Ke),2);if(s=m[0],c=m[1],d(s,"m"))return l;var g=a(Qe(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?Ve[a]:Ve.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 et(e,t){var n=Math.floor(Math.log10(Math.abs(e)));return n>=3?[Math.round(e),e.toFixed(0)]:$e(e,Math.min(4-n,t))}function tt(e,t){var n=parseFloat((null!=e?e:"").replace(/,/g,""));return isNaN(n)?null!=t?t:0:n}function nt(e,t,n){return en?n:e}function rt(e,t,n,r){return at.apply(this,arguments)}function at(){return(at=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 ot,st,it,ct,lt=function(){function e(){i(this,e)}return d(e,[{key:"unload",value:function(){}}]),e}(),ut=function(e){return e[e.Disconnected=0]="Disconnected",e[e.Connected=1]="Connected",e[e.InvalidCert=2]="InvalidCert",e}({}),dt=function(e){return e[e.Approved=0]="Approved",e[e.Pending=1]="Pending",e[e.NotApproved=2]="NotApproved",e}({}),ht=function(e){return e[e.WalletDefault=0]="WalletDefault",e[e.UserAdded=1]="UserAdded",e[e.Discovered=2]="Discovered",e}({}),pt=2147483647;function ft(){return ot}function vt(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 mt(e){var t=[e.booleanOptTmpl,e.rangeOptTmpl,e.orderOptTmpl];it=t[0],ct=t[1],st=t[2]}var gt=new Intl.NumberFormat(Ne.languages(),{minimumSignificantDigits:3,maximumSignificantDigits:3}),yt=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=st.cloneNode(!0),s=this.tmpl=Ne.parseTemplate(o);s.optName.textContent=t.displayname,s.tooltip.dataset.tooltip=t.description,n?s.chainIcon.src=Ne.logoPath(n):Ne.hide(s.chainIcon),this.on=!1,Ne.bind(o,"click",(function(){a.on||(a.on=!0,o.classList.add("selected"),r.enable())})),Ne.bind(s.toggle,"click",(function(e){a.on&&(e.stopPropagation(),a.on=!1,o.classList.remove("selected"),r.disable())}))})),bt=function(e){g(n,e);var t=vt(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=it.cloneNode(!0);return s.tmpl.controls.appendChild(l),Ne.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}(yt),xt=function(e){g(n,e);var t=vt(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 kt(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}(yt),kt=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=ct.cloneNode(!0),d=this.tmpl=Ne.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=wt(a,t.start.x,t.end.x),l.r=g(l.scrollingX),l.y=l.r*m+t.start.y,l.accept(l.scrollingX))}Ne.hide(d.xInput),Ne.show(d.x),Ne.unbind(document,"click",e),l.changed()}};Ne.bind(d.x,"click",(function(e){l.disabled||(Ne.hide(d.x),Ne.show(d.xInput),d.xInput.focus(),d.xInput.value=gt.format(l.scrollingX),Ne.bind(document,"click",y),e.stopPropagation())})),Ne.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=wt(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))}Ne.hide(d.yInput),Ne.show(d.y),Ne.unbind(document,"click",e),l.changed()}};Ne.bind(d.y,"click",(function(e){l.disabled||(Ne.hide(d.y),Ne.show(d.yInput),d.yInput.focus(),d.yInput.value=gt.format(l.y),Ne.bind(document,"click",b),e.stopPropagation())})),Ne.bind(d.yInput,"change",b),Ne.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})};Ne.bind(document,"mousemove",o),Ne.bind(document,"mouseup",(function e(t){o(t,!0),Ne.unbind(document,"mousemove",o),Ne.unbind(document,"mouseup",e),l.changed()}))}})),Ne.bind(d.sliderBox,"click",(function(e){if(!l.disabled&&0===e.button){var n=e.pageX,r=Ne.layoutMetrics(d.slider);l.r=wt((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=gt.format(e),r.y.textContent=gt.format(this.y),this.roundY&&(r.y.textContent="".concat(this.y));var a=wt(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}(),wt=function(e,t,n){return en?n:e};function Ct(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 St(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)?St(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 St(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=Pt||n.side===Mt&&n.status>=Lt?e+t(n):e}),0)}function Gt(e){var t;if(null===(t=e.matches)||void 0===t||!t.length)return ke(K);var n=Ne.formatCoinValue(ft().conventionalRate(e.baseID,e.quoteID,Xt(e)));return e.matches.length>1&&(n="~ "+n),n}function Xt(e){var t;if(null===(t=e.matches)||void 0===t||!t.length)return 0;var n,r=0,a=0,o=Ct(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 Kt(e,t){return e*t/Nt}function Qt(e){return ke("MATCH_STATUS_REVOKED",{status:ke(e)})}function Yt(e){return e.type===Ft&&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 $t(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([S.rate,w]),!S.epoch)for(k+=S.qty,m.push([S.rate,k]),x.buyBase+=S.qty,x.buyQuote+=S.qty*S.rate;p.length&&yn(p[0].rate,S.rate);){var F=p.shift();F&&v.push({rate:F.rate,qty:S.epoch?w:k,sell:S.sell,active:F.active})}}var T=m.length?vn(m)[1]:0;m.push([h,T]);var D=g.length?vn(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 xn(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=Zt(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 C=this.market.ratestep,S=new dn(k,w,g,m);g===m&&(S.y.min-=C,S.y.max+=C),this.dataExtents=S;var F=null;a&&this.plotRegion.plot(new dn(S.x.min,S.x.max,0,1),(function(e,n){var o,s=xn(n.unx(a.x),r),c=Zt(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=ft().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=xn(a.endStamp,t),i=xn(o.endStamp,t)+t,c=i-s,l=Math.min(e.length,n/100),u=xn(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(fn[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(fn[e.getMonth()]).concat(e.getDate()," '").concat(String(t).slice(2,4)):"".concat(fn[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,C,D,(function(e){return Ne.formatFourSigFigs(e/T)}));this.plotYGrid(this.candleRegion,A,this.dataExtents.y.min,this.dataExtents.y.max);var R=new dn(k,w,0,y);if(this.volumeRegion.plot(R,(function(e,n){e.fillStyle=t.theme.gridBorder;var r,a=Zt(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(S,(function(e,n){e.lineWidth=1;var r,a=Zt(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 dn(S.x.min,S.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=Nt*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=nt(.15*o,10,14),this.applyLabelStyle(this.fontSize);var c=.5*this.fontSize,l=this.fontSize/2+c;i-=l,this.msgRegion=new hn(this.ctx,new dn(0,n,i+o,i+o+2*l))}this.region=new hn(this.ctx,new dn(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 dn(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 pn(e,t,n,r,a,o,s,i){i=i||Ne.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 fn=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"];function vn(e){return e[e.length-1]}function mn(e,t,n,r,a,o){e.beginPath(),e.moveTo(t,n),e.lineTo(r,a),o||e.stroke()}function gn(e,t,n,r,a){e.fillStyle=r,e.beginPath(),e.arc(t,n,a,0,tn),e.fill()}function yn(e,t){return bn(e,t,1e-8)}function bn(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 wn(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=Vn(s,a);e.limitBonus.textContent=d.toFixed(1);var h,p=kn(Ne.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 Fn(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 Tn,Dn,In,An,Rn,En,Bn,Pn,Ln,On,Mn,qn,Nn=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/Nt;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*Nt/s:t.lotsize:0};function Wn(e,t,n){return 3===e.type?0:function(e,t,n){var r;if(e.status!==At)return 0;var a=Nn(e,t,n);return function(e,t){return e.type===Dt||e.tif===It||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!==Rt?0:Nn(e)}(e)+function(e){var t,n=0,r=kn(e.matches||[]);try{for(r.s();!(t=r.n()).done;){var a=t.value;if(a.side===qt){if(a.status>Pt)continue}else if(a.status>Bt)continue;n+=a.qty}}catch(e){r.e(e)}finally{r.f()}return n}(e)}function Vn(e,t){return e>0?1+e/t*(Cn-1):1}var Un="TakerFoundMakerRedemption:";function _n(e){return e.startsWith(Un)?[e.substring(Un.length),!0]:42===e.length?[e,!0]:[e,!1]}var jn=(h(Tn={},0,(function(e){var t=a(_n(e),2),n=t[0];return t[1]?"https://etherscan.io/address/".concat(n):"https://etherscan.io/tx/".concat(n)})),h(Tn,1,(function(e){var t=a(_n(e),2),n=t[0];return t[1]?"https://sepolia.etherscan.io/address/".concat(n):"https://sepolia.etherscan.io/tx/".concat(n)})),h(Tn,2,(function(e){var t=a(_n(e),2),n=t[0];return t[1]?"https://etherscan.io/address/".concat(n):"https://etherscan.io/tx/".concat(n)})),Tn),Hn=(h(Dn={},0,(function(e){var t=a(_n(e),2),n=t[0];return t[1]?"https://polygonscan.com/address/".concat(n):"https://polygonscan.com/tx/".concat(n)})),h(Dn,1,(function(e){var t=a(_n(e),2),n=t[0];return t[1]?"https://amoy.polygonscan.com/address/".concat(n):"https://amoy.polygonscan.com/tx/".concat(n)})),h(Dn,2,(function(e){var t=a(_n(e),2),n=t[0];return t[1]?"https://polygonscan.com/address/".concat(n):"https://polygonscan.com/tx/".concat(n)})),Dn),zn={42:(In={},h(In,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(In,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(In,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)})),In),0:(An={},h(An,0,(function(e){return"https://mempool.space/tx/".concat(e.split(":")[0])})),h(An,1,(function(e){return"https://mempool.space/testnet/tx/".concat(e.split(":")[0])})),h(An,2,(function(e){return"https://mempool.space/tx/".concat(e.split(":")[0])})),An),2:(Rn={},h(Rn,0,(function(e){return"https://ltc.bitaps.com/".concat(e.split(":")[0])})),h(Rn,1,(function(e){return"https://sochain.com/tx/LTCTEST/".concat(e.split(":")[0])})),h(Rn,2,(function(e){return"https://ltc.bitaps.com/".concat(e.split(":")[0])})),Rn),20:(En={},h(En,0,(function(e){return"https://digiexplorer.info/tx/".concat(e.split(":")[0])})),h(En,1,(function(e){return"https://testnetexplorer.digibyteservers.io/tx/".concat(e.split(":")[0])})),h(En,2,(function(e){return"https://digiexplorer.info/tx/".concat(e.split(":")[0])})),En),60:jn,60001:jn,60002:jn,3:(Bn={},h(Bn,0,(function(e){return"https://dogeblocks.com/tx/".concat(e.split(":")[0])})),h(Bn,1,(function(e){return"https://blockexplorer.one/dogecoin/testnet/tx/".concat(e.split(":")[0])})),h(Bn,2,(function(e){return"https://dogeblocks.com/tx/".concat(e.split(":")[0])})),Bn),5:(Pn={},h(Pn,0,(function(e){return"https://blockexplorer.one/dash/mainnet/tx/".concat(e.split(":")[0])})),h(Pn,1,(function(e){return"https://blockexplorer.one/dash/testnet/tx/".concat(e.split(":")[0])})),h(Pn,2,(function(e){return"https://blockexplorer.one/dash/mainnet/tx/".concat(e.split(":")[0])})),Pn),133:(Ln={},h(Ln,0,(function(e){return"https://zcashblockexplorer.com/transactions/".concat(e.split(":")[0])})),h(Ln,1,(function(e){return"https://blockexplorer.one/zcash/testnet/tx/".concat(e.split(":")[0])})),h(Ln,2,(function(e){return"https://zcashblockexplorer.com/transactions/".concat(e.split(":")[0])})),Ln),147:(On={},h(On,0,(function(e){return"https://explorer.zcl.zelcore.io/tx/".concat(e.split(":")[0])})),h(On,2,(function(e){return"https://explorer.zcl.zelcore.io/tx/".concat(e.split(":")[0])})),On),136:(Mn={},h(Mn,0,(function(e){return"https://explorer.firo.org/tx/".concat(e.split(":")[0])})),h(Mn,1,(function(e){return"https://testexplorer.firo.org/tx/".concat(e.split(":")[0])})),h(Mn,2,(function(e){return"https://explorer.firo.org/tx/".concat(e.split(":")[0])})),Mn),145:(qn={},h(qn,0,(function(e){return"https://bch.loping.net/tx/".concat(e.split(":")[0])})),h(qn,1,(function(e){return"https://tbch4.loping.net/tx/".concat(e.split(":")[0])})),h(qn,2,(function(e){return"https://bch.loping.net/tx/".concat(e.split(":")[0])})),qn),966:Hn,966001:Hn,966002:Hn,966003:Hn,966004:Hn};function Gn(e){return e.startsWith(Un)?ke("TAKER_FOUND_MAKER_REDEMPTION",{makerAddr:e.substring(Un.length)}):e}function Xn(e,t){var n=ft().user.net,r=zn[function(e){var t=ft().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 Kn(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 Qn(e){for(var t=1;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 Jn(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n0,this.baseFeeUI=f,this.baseFeeTicker=f.conventional.unit,this.baseFeeSymbol=v,this.baseFeeFactor=this.baseFeeUI.conventional.conversionFactor;var g=ft().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=ft().assets[this.quoteFeeID],C=w.unitInfo,S=w.symbol,F=w.wallet;this.quoteIsAccountLocker=(16384&F.traits)>0,this.quoteFeeUI=C,this.quoteFeeTicker=C.conventional.unit,this.quoteFeeSymbol=S,this.quoteFeeFactor=this.quoteFeeUI.conventional.conversionFactor,this.id=pr(n,r,a),this.mktID="".concat(l,"_").concat(b);var T=ft().exchanges[n].markets[this.mktID],D=T.lotsize,I=T.ratestep;this.lotSize=D,this.lotSizeConv=D/u.conventional.conversionFactor,this.rateStep=I,this.quoteLot=dr(D,r,a),this.quoteLotConv=this.quoteLot/x.conventional.conversionFactor,this.baseFeeFiatRate=ft().fiatRatesMap[d],this.quoteFeeFiatRate=ft().fiatRatesMap[k],t.arbMarketMakingConfig?(this.botType=ar,this.baseLots=t.arbMarketMakingConfig.sellPlacements.reduce(mr,0),this.quoteLots=t.arbMarketMakingConfig.buyPlacements.reduce(mr,0),this.nBuyPlacements=t.arbMarketMakingConfig.buyPlacements.length,this.nSellPlacements=t.arbMarketMakingConfig.sellPlacements.length):t.simpleArbConfig?(this.botType=or,this.baseLots=t.uiConfig.simpleArbLots,this.quoteLots=t.uiConfig.simpleArbLots):t.basicMarketMakingConfig&&(this.botType=rr,this.baseLots=t.basicMarketMakingConfig.sellPlacements.reduce(mr,0),this.quoteLots=t.basicMarketMakingConfig.buyPlacements.reduce(mr,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(){var t,n,r,a,o,s,i;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.host,n=this.baseID,r=this.quoteID,a=this.lotSizeConv,o=this.quoteLotConv,e.next=3,ir.report(t,n,r);case 3:s=e.sent,i=this.marketReport=s.report,this.lotSizeUSD=a*i.baseFiatRate,this.quoteLotUSD=o*i.quoteFiatRate,this.proj=this.projectedAllocations();case 8:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})},{key:"status",value:function(){var e=this.baseID,t=this.quoteID,n=ft().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,latestEpoch:n.latestEpoch,cexProblems:n.cexProblems}:{botCfg:{},running:!1,runStats:{}}}},{key:"adjustedBalances",value:function(){var e,t,n=this.baseID,r=this.quoteID,a=this.baseFeeID,o=this.quoteFeeID,s=this.cexName,i=this.baseFactor,c=this.quoteFactor,l=this.baseFeeFactor,u=this.quoteFeeFactor,d=[ft().walletMap[n],ft().walletMap[r]],h=d[0],p=d[1],f=[cr(n),cr(r)],v=f[0],m=f[1],g=0,y=0;if(s){var b=ft().mmStatus.cexes[s];if(!b)throw Error("where's the cex status?");e=b.balances[n],t=b.balances[r]}e&&(g=(e.available||0)-v.cex.avail),t&&(y=(t.available||0)-m.cex.avail);var x=h.balance.available-v.dex.avail,k=p.balance.available-m.dex.avail,w=x+g,C=k+y,S=a===n?h:ft().walletMap[a],F=o===r?p:ft().walletMap[o],T=w,D=x,I=g;if(a!==n){var A=cr(n);D=S.balance.available-A.dex.total,e&&(I=(e.available||0)-A.cex.total),T=D+I}var R=C,E=k,B=y;if(o!==r){var P=cr(r);E=F.balance.available-P.dex.total,t&&(B=(t.available||0)-P.cex.total),R=E+B}return{baseAvail:w/i,quoteAvail:C/c,dexBaseAvail:x/i,dexQuoteAvail:k/c,cexBaseAvail:g/i,cexQuoteAvail:y/c,baseFeeAvail:T/l,quoteFeeAvail:R/u,dexBaseFeeAvail:D/l,dexQuoteFeeAvail:E/u,cexBaseFeeAvail:I/l,cexQuoteFeeAvail:B/u}}},{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 kr(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],C=x[2];r===o?k+=t.bookingFees:C+=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 S=[n.book,n.cex,0,0],F=S[0],T=S[1],D=S[2],I=S[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>=C,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:C,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}(),yr=function(){function e(t,n,r,a){var o=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),h(this,"currentForm",void 0),h(this,"forms",void 0),h(this,"latestEpoch",void 0),h(this,"cexProblems",void 0),h(this,"orderReportFormEl",void 0),h(this,"orderReportForm",void 0),h(this,"displayedOrderReportFormSide",void 0),h(this,"dexBalancesRowTmpl",void 0),h(this,"placementRowTmpl",void 0),h(this,"placementAmtRowTmpl",void 0),this.div=t,this.page=Ne.parseTemplate(t),this.orderReportFormEl=r.orderReportForm,this.orderReportForm=Ne.idDescendants(r.orderReportForm),this.dexBalancesRowTmpl=r.dexBalancesRowTmpl,this.placementRowTmpl=r.placementRowTmpl,this.placementAmtRowTmpl=r.placementAmtRowTmpl,Ne.cleanTemplates(this.dexBalancesRowTmpl,this.placementRowTmpl,this.placementAmtRowTmpl),this.forms=n,Ne.bind(this.page.stopBttn,"click",(function(){return o.stop()})),Ne.bind(this.page.runLogsBttn,"click",(function(){var e=o.mkt,t=e.baseID,n=e.quoteID,r=e.host,s=o.startTime;ft().loadPage("mmlogs",{baseID:t,quoteID:n,host:r,startTime:s,returnPage:a})})),Ne.bind(this.page.buyOrdersBttn,"click",(function(){return o.showOrderReport("buys")})),Ne.bind(this.page.sellOrdersBttn,"click",(function(){return o.showOrderReport("sells")}))}var t,n,o;return d(e,[{key:"stop",value:(o=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=ft().loading(t.stopBttn),e.next=4,ir.stopBot({host:r,baseID:a,quoteID:o});case 4:s();case 5:case"end":return e.stop()}}),e,this)}))),function(){return o.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=ft().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 gr(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,C,S,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,C=u.baseFactor,S=u.quoteFactor,lr(l,h,p,d),Ne.setVis(v!==h,c.baseFeeReservesBox),Ne.setVis(m!==p,c.quoteFeeReservesBox),Ne.setVis.apply(Ne,[Boolean(g)].concat(r(Ne.applySelector(l,"[data-cex-show]")))),c.baseFeeLogo.src=Ne.logoPath(y),c.baseFeeTicker.textContent=x,c.quoteFeeLogo.src=Ne.logoPath(b),c.quoteFeeTicker.textContent=k,F=w.basicMarketMakingConfig,T=null!==(n=null==F?void 0:F.gapStrategy)&&void 0!==n?n:tr,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),Ne.hide(c.profitLabel,c.gapLabel,c.multiplierLabel,c.profitUnit,c.gapUnit,c.multiplierUnit),e.t0=T,e.next=e.t0===tr||e.t0===nr?18:e.t0===Zn?21:24;break;case 18:return Ne.show(c.profitLabel,c.profitUnit),c.gapFactor.textContent=(100*D).toFixed(2),e.abrupt("break",25);case 21:return Ne.show(c.multiplierLabel,c.multiplierUnit),c.gapFactor.textContent=(100*D).toFixed(2),e.abrupt("break",25);case 24:c.gapFactor.textContent=Ne.formatFourSigFigs(D/Nt*C/S);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:"handleEpochReportNote",value:function(e){if(this.mkt){var t=this.mkt,n=t.baseID,r=t.quoteID,a=t.host;if(e.baseID===n&&e.quoteID===r&&e.host===a&&e.report){if(this.latestEpoch=e.report,this.forms.currentForm===this.orderReportFormEl&&this.forms.currentFormID===this.mkt.id){var o="buys"===this.displayedOrderReportFormSide?e.report.buysReport:e.report.sellsReport;o?this.updateOrderReport(o,this.displayedOrderReportFormSide,e.report.epochNum):this.forms.close()}this.update()}}}},{key:"handleCexProblemsNote",value:function(e){if(this.mkt){var t=this.mkt,n=t.baseID,r=t.quoteID,a=t.host;e.baseID===n&&e.quoteID===r&&e.host===a&&(this.cexProblems=e.problems,this.update())}}},{key:"setTicker",value:function(){this.page.runTime.textContent=Ne.hmsSince(this.startTime)}},{key:"update",value:function(){var e,t,n,r=this,o=this.div,s=this.page,i=this.mkt,c=i.baseID,l=i.quoteID,u=i.baseFeeID,d=i.quoteFeeID,h=i.baseFactor,p=i.quoteFactor,f=i.baseFeeFactor,v=i.quoteFeeFactor,m=i.marketReport,g=m.baseFiatRate,y=m.quoteFiatRate,b=this.mkt.status(),x=b.botCfg,k=x.cexName,w=x.basicMarketMakingConfig,C=b.runStats,S=b.latestEpoch,F=b.cexProblems;if(this.latestEpoch=S,this.cexProblems=F,Ne.hide(s.stats,s.cexRow,s.pendingDepositBox,s.pendingWithdrawalBox),C){this.ticker||(this.startTime=C.startTime,this.setTicker(),this.ticker=setInterval((function(){return r.setTicker()}),1e3)),Ne.show(s.stats),xr(100*C.profitLoss.profitRatio,s.profit,s.profitSign,2),xr(C.profitLoss.profit,s.profitLoss,s.plSign,2),this.startTime=C.startTime;var T=function(e){return e?e.available+e.locked+e.pending+e.reserved:0},D=T(C.dexBalances[c])/h;s.walletBaseInventory.textContent=Ne.formatFourSigFigs(D),s.walletBaseInvFiat.textContent=Ne.formatFourSigFigs(D*g,2);var I=T(C.dexBalances[l])/p;if(s.walletQuoteInventory.textContent=Ne.formatFourSigFigs(I),s.walletQuoteInvFiat.textContent=Ne.formatFourSigFigs(I*y,2),Ne.setVis(k,s.cexRow),k){Ne.show(s.pendingDepositBox,s.pendingWithdrawalBox),ur(o,k);var A=T(C.cexBalances[c])/h;s.cexBaseInventory.textContent=Ne.formatFourSigFigs(A),s.cexBaseInventoryFiat.textContent=Ne.formatFourSigFigs(A*g,2);var R=T(C.cexBalances[l])/p;s.cexQuoteInventory.textContent=Ne.formatFourSigFigs(R),s.cexQuoteInventoryFiat.textContent=Ne.formatFourSigFigs(R*y,2)}if(u!==c){var E=T(C.dexBalances[u])/f;s.baseFeeReserves.textContent=Ne.formatFourSigFigs(E)}if(d!==l){var B=T(C.dexBalances[d])/v;s.quoteFeeReserves.textContent=Ne.formatFourSigFigs(B)}s.pendingDeposits.textContent=String(Math.round(C.pendingDeposits)),s.pendingWithdrawals.textContent=String(Math.round(C.pendingWithdrawals)),s.completedMatches.textContent=String(Math.round(C.completedMatches)),Ne.setVis(C.tradedUSD,s.tradedUSDBox),C.tradedUSD>0&&(s.tradedUSD.textContent=Ne.formatFourSigFigs(C.tradedUSD)),Ne.setVis(g,s.roundTripFeesBox),g&&(s.roundTripFeesUSD.textContent=Ne.formatFourSigFigs((null===(e=C.feeGap)||void 0===e?void 0:e.roundTripFees)/h*g||0));var P=ft().conventionalRate(c,l,(null===(t=C.feeGap)||void 0===t?void 0:t.basisPrice)||0);s.basisPrice.textContent=Ne.formatFourSigFigs(P);var L=!w||w.gapStrategy===er||w.gapStrategy===nr;if(Ne.setVis(L,s.feeGapBox),L){var O,M=ft().conventionalRate(c,l,(null===(O=C.feeGap)||void 0===O?void 0:O.feeGap)||0);s.feeGap.textContent=Ne.formatFourSigFigs(M),s.feeGapPct.textContent=(M/P*100||0).toFixed(2)}Ne.setVis(w,s.gapStrategyBox),w&&(s.gapStrategy.textContent=w.gapStrategy);var q=ft().conventionalRate(c,l,(null===(n=C.feeGap)||void 0===n?void 0:n.remoteGap)||0);if(Ne.setVis(q,s.remoteGapBox),q&&(s.remoteGap.textContent=Ne.formatFourSigFigs(q),s.remoteGapPct.textContent=(q/P*100||0).toFixed(2)),Ne.setVis(null==S?void 0:S.buysReport,s.buyOrdersReportBox),null!=S&&S.buysReport){var N=br(S.buysReport);Ne.setVis(N,s.buyOrdersSuccess),Ne.setVis(!N,s.buyOrdersFailed)}if(Ne.setVis(null==S?void 0:S.sellsReport,s.sellOrdersReportBox),null!=S&&S.sellsReport){var W=br(S.sellsReport);Ne.setVis(W,s.sellOrdersSuccess),Ne.setVis(!W,s.sellOrdersFailed)}var V=wr(null==S?void 0:S.preOrderProblems,this.mkt.cexName,this.mkt.host),U=function(e){if(!e)return[];var t=[];if(e.depositErr)for(var n=0,r=Object.entries(e.depositErr);n0,s.preOrderProblemsBox),Ne.empty(s.preOrderProblemsBox);var j,H=Yn(_);try{for(H.s();!(j=H.n()).done;){var z=j.value,G=document.createElement("span");G.textContent="- ".concat(z),s.preOrderProblemsBox.appendChild(G)}}catch(e){H.e(e)}finally{H.f()}}else this.ticker&&(clearInterval(this.ticker),this.ticker=void 0)}},{key:"updateOrderReport",value:function(e,t,n){var r=this,o=this.orderReportForm,s=ke("buys"===t?E:B);if(o.orderReportTitle.textContent=ke("ORDER_REPORT_TITLE",{side:s,epochNum:"".concat(n)}),Ne.setVis(e.error,o.orderReportError),Ne.setVis(!e.error,o.orderReportDetails),e.error){var i=wr(e.error,this.mkt.cexName,this.mkt.host);Ne.empty(o.orderReportError);for(var c=0,l=i;c0&&a.deficiency.classList.add("text-warning");var f=Cr(p,u);return a.deficiencyWithPending.textContent=Ne.formatCoinValue(f,s),f>0&&a.deficiencyWithPending.classList.add("text-warning"),[n,p]},p=[this.mkt.baseID,this.mkt.quoteID];p.includes(this.mkt.baseFeeID)||p.push(this.mkt.baseFeeID),p.includes(this.mkt.quoteFeeID)||p.push(this.mkt.quoteFeeID);for(var f,v=0,m=[],g=0,y=p;g0,m),Ne.setVis(this.mkt.cexName,o.cexSection,o.counterTradeRateHeader,o.requiredCEXHeader,o.usedCEXHeader),this.mkt.cexName){var k=sr[this.mkt.cexName];k?(o.cexLogo.src=k.logo,o.cexBalancesTitle.textContent=ke("CEX_BALANCES",{cexName:k.name})):console.error("CEXDisplayInfo not found for ".concat(this.mkt.cexName));var w="buys"===t?this.mkt.baseID:this.mkt.quoteID;f=ft().assets[w],o.cexAsset.textContent=f.symbol.toUpperCase(),o.cexAssetLogo.src=Ne.logoPath(f.symbol);var C=e.availableCexBal?e.availableCexBal.available:0,S=e.requiredCexBal?e.requiredCexBal:0,F=e.remainingCexBal?e.remainingCexBal:0,T=e.availableCexBal?e.availableCexBal.pending:0,D=e.availableCexBal?e.availableCexBal.reserved:0,I=e.usedCexBal?e.usedCexBal:0,A=Cr(S,C),R=Cr(A,T);o.cexAvailable.textContent=Ne.formatCoinValue(C,f.unitInfo),o.cexLocked.textContent=Ne.formatCoinValue(D,f.unitInfo),o.cexRequired.textContent=Ne.formatCoinValue(S,f.unitInfo),o.cexRemaining.textContent=Ne.formatCoinValue(F,f.unitInfo),o.cexPending.textContent=Ne.formatCoinValue(T,f.unitInfo),o.cexUsed.textContent=Ne.formatCoinValue(I,f.unitInfo);var P=A>0;Ne.setVis(P,o.cexDeficiencyHeader,o.cexDeficiencyWithPendingHeader,o.cexDeficiency,o.cexDeficiencyWithPending),P&&(o.cexDeficiency.textContent=Ne.formatCoinValue(A,f.unitInfo),o.cexDeficiencyWithPending.textContent=Ne.formatCoinValue(R,f.unitInfo),R>0?o.cexDeficiencyWithPending.classList.add("text-warning"):o.cexDeficiencyWithPending.classList.remove("text-warning"))}var L,O=!1,M=Yn(e.placements);try{for(M.s();!(L=M.n()).done;)if(L.value.error){O=!0;break}}catch(e){M.e(e)}finally{M.f()}Ne.setVis(O,o.errorHeader);for(var q=function(e,t){var n=r.placementRowTmpl.cloneNode(!0),a=Ne.parseTemplate(n),o=ft().assets[r.mkt.baseID].unitInfo,s=ft().assets[r.mkt.quoteID].unitInfo;a.priority.textContent=String(t),a.rate.textContent=Ne.formatRateFullPrecision(e.rate,o,s,r.mkt.rateStep),a.lots.textContent=String(e.lots),a.standingLots.textContent=String(e.standingLots),a.orderedLots.textContent=String(e.orderedLots),e.standingLots+e.orderedLots0,a.counterTradeRate),a.counterTradeRate.textContent=Ne.formatRateFullPrecision(e.counterTradeRate,o,s,r.mkt.rateStep);for(var i=0,c=p;i0),n.classList.toggle("text-good",e>0)}function kr(e,t,n,r,a,o,s,i,c,l,u,d,h){var p=dr(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,C=g*o*k,S=m*s*w,F=x*s*w,T=b*o*k;return{commit:f,fees:{base:Qn(Qn({},n),{},{bookingFeesPerLot:g,bookingFeesPerCounterLot:m,bookingFees:C+S,swapReservesFactor:k,redeemReservesFactor:w,tokenFeesPerSwap:v}),quote:Qn(Qn({},r),{},{bookingFeesPerLot:x,bookingFeesPerCounterLot:b,bookingFees:F+T,swapReservesFactor:w,redeemReservesFactor:k,tokenFeesPerSwap:y})}}}function wr(e,t,n){if(!e)return[];var r=[];if(e.walletNotSynced)for(var o=0,s=Object.entries(e.walletNotSynced);o0?e-t:0}function Sr(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 Fr(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)?Fr(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 Fr(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n1)){e.next=34;break}Ne.show(r),u=Sr(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),Ne.bind(a,"click",(function(){var e,n=Sr(Ne.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:ft().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=ft().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=ft().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,Ne.hide(n.walletPassAndSubmitBttn,n.oneBttnBox,n.newWalletPassBox),a=t.guidelink,(o=t.configopts||[]).map((function(e){return e.isBirthdayConfig&&ft().seedGenTime>0&&(e.default=Xr(new Date)),e})),s=!1,i=Sr(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?(Ne.hide(n.walletSettingsHeader),Ne.show(n.oneBttnBox)):p?(Ne.show(n.walletPassAndSubmitBttn,n.walletSettingsHeader),n.newWalletPass.value="",n.submitAdd.textContent=ke("CREATE")):(Ne.show(n.walletPassAndSubmitBttn,n.walletSettingsHeader),t.noauth||Ne.show(n.newWalletPassBox),n.submitAdd.textContent=ke("ADD")),d){v=JSON.parse(JSON.stringify(o)),m=Sr(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=Sr(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)?Ne.hide(this.subform.fileSelector):Ne.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){Ne.hide(this.walletCfgGuide),""!==e&&(this.walletCfgGuide.href=e,Ne.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,Ne.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=ft().loading(this.form),e.next=11,S("/api/defaultwalletcfg",{assetID:o,type:a.type});case 11:if(i=e.sent,s(),ft().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}(),Ir=0,Ar=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=Ne.idDescendants(t),this.form=t,this.configElements=[],this.configOpts=[],this.sectionize=n,this.allSettings=Ne.tmplElement(t,"allSettings"),this.dynamicOpts=Ne.tmplElement(t,"dynamicOpts"),this.textInputTmpl=Ne.tmplElement(t,"textInput"),this.textInputTmpl.remove(),this.dateInputTmpl=Ne.tmplElement(t,"dateInput"),this.dateInputTmpl.remove(),this.checkboxTmpl=Ne.tmplElement(t,"checkbox"),this.checkboxTmpl.remove(),this.repeatableTmpl=Ne.tmplElement(t,"repeatableInput"),this.repeatableTmpl.remove(),this.fileSelector=Ne.tmplElement(t,"fileSelector"),this.fileInput=Ne.tmplElement(t,"fileInput"),this.errMsg=Ne.tmplElement(t,"errMsg"),this.showOther=Ne.tmplElement(t,"showOther"),this.showIcon=Ne.tmplElement(t,"showIcon"),this.hideIcon=Ne.tmplElement(t,"hideIcon"),this.showHideMsg=Ne.tmplElement(t,"showHideMsg"),this.otherSettings=Ne.tmplElement(t,"otherSettings"),this.loadedSettingsMsg=Ne.tmplElement(t,"loadedSettingsMsg"),this.loadedSettings=Ne.tmplElement(t,"loadedSettings"),this.defaultSettingsMsg=Ne.tmplElement(t,"defaultSettingsMsg"),this.defaultSettings=Ne.tmplElement(t,"defaultSettings"),n||Ne.hide(this.showOther),Ne.bind(this.fileSelector,"click",(function(){return r.fileInput.click()})),Ne.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)})))),Ne.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(Ne.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=ft().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,S("/api/parseconfig",{configtext:o});case 14:if(s=e.sent,a(),ft().checkResponse(s)){e.next=20;break}return this.errMsg.textContent=s.msg,Ne.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])&&Ne.hide(this.loadedSettings,this.loadedSettingsMsg),0===l&&Ne.hide(this.defaultSettings,this.defaultSettingsMsg),c+l===0&&Ne.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"),Ne.bind(Ne.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=ft().extensionWallet(this.assetID))||void 0===a?void 0:a.hiddenFields)||[]).indexOf(t.key)&&Ne.hide(o),this.configElements.push([t,o]);var c=o.querySelector("input");c.dataset.configKey=t.key,Ir++;var l="wcfg-"+String(Ir);c.id=l;var u=Ne.safeSelector(o,"label");if(u.htmlFor=l,u.prepend(t.displayname),void 0!==t.regAsset){var d=new window.Image(15,15);d.src=Ne.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?Kr("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=Kr(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,Ne.empty(this.dynamicOpts,this.defaultSettings,this.loadedSettings),0===this.configOpts.length)return Ne.hide(this.form);Ne.show(this.form),this.setOtherSettingsViz(!1),Ne.hide(this.loadedSettingsMsg,this.loadedSettings,this.defaultSettingsMsg,this.defaultSettings,this.errMsg);var r,a=[],o=Sr(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=Sr(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()}Ne.show(this.showOther,this.defaultSettingsMsg,this.defaultSettings)}else Ne.hide(this.showOther);ft().bindTooltips(this.allSettings),this.dynamicOpts.children.length?Ne.show(this.dynamicOpts):Ne.hide(this.dynamicOpts)}},{key:"setOtherSettingsViz",value:function(e){if(e)return Ne.hide(this.showIcon),Ne.show(this.hideIcon,this.otherSettings),void(this.showHideMsg.textContent=ke("HIDE_ADDITIONAL_SETTINGS"));Ne.hide(this.hideIcon,this.otherSettings),Ne.show(this.showIcon),this.showHideMsg.textContent=ke("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(C,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),Ne.show(this.loadedSettings,this.loadedSettingsMsg),0===this.defaultSettings.children.length&&Ne.hide(this.defaultSettings,this.defaultSettingsMsg))}},{key:"map",value:function(e){var t,n={},r=Sr(this.configElements);try{for(r.s();!(t=r.n()).done;){var o=a(t.value,2),s=o[0],i=o[1],c=Ne.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?Xr(new Date(c.min+"T00:00")):Number.MIN_SAFE_INTEGER,u=c.max?Xr(new Date(c.max+"T00:00")):Number.MAX_SAFE_INTEGER,d=c.value?Xr(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=Sr(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=Sr(this.configOpts);try{for(o.s();!(r=o.n()).done;){var s,i=r.value,c=Sr(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}(),Rr=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=Ne.parseTemplate(t),this.certFile="",Ne.bind(this.page.goBack,"click",(function(){return r()})),Gr(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=ft().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=Ne.logoPath(r.symbol),i.bondLock.textContent=Ne.formatFourSigFigs(c),i.bondUnit.textContent=s;var l=ft().fiatRatesMap[e];Ne.show(i.bondLockUSDBox),l?i.bondLockUSD.textContent=Ne.formatFourSigFigs(c*l):Ne.hide(i.bondLockUSDBox),n&&(i.feeReserves.textContent=Ne.formatFourSigFigs(n/o)),i.reservesUnit.textContent=s}},{key:"setFees",value:function(e,t){this.fees=t;var n=ft().assets[e].unitInfo.conventional.conversionFactor;this.page.feeReserves.textContent=Ne.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,Ne.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=ft().assets[n]){e.next=6;break}return t.regErr.innerText=ke("SELECT_WALLET_FOR_FEE_PAYMENT"),Ne.show(t.regErr),e.abrupt("return");case 6:return Ne.hide(t.regErr),i=r.bondAssets[s.wallet.symbol],c=r.host,!ft().exchanges[r.host]||ft().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=ft().loading(this.form),e.next=13,S(u,l);case 13:if(h=e.sent,d(),ft().checkResponse(h)){e.next=19;break}return t.regErr.textContent=h.msg,Ne.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}(),Er=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=Ne.parseTemplate(t);Ne.cleanTemplates(a.currentBondTmpl,a.bondAssetTmpl,a.marketTmpl),Ne.bind(a.tradingTierInput,"input",(function(){r.setTier()})),Ne.bind(a.tradingTierInput,"keyup",(function(e){"Enter"===e.key&&r.acceptTier()})),Ne.bind(a.submitTradingTier,"click",(function(){r.acceptTier()})),Ne.bind(a.tierUp,"click",(function(){r.incrementTier(!0)})),Ne.bind(a.tierDown,"click",(function(){r.incrementTier(!1)})),Ne.bind(a.goBackToAssets,"click",(function(){Ne.hide(a.tradingTierForm),Ne.show(a.assetForm)})),Ne.bind(a.whatsABond,"click",(function(){Ne.hide(a.assetForm),Ne.show(a.whatsABondPanel)}));var o=function(){Ne.show(a.assetForm),Ne.hide(a.whatsABondPanel)};Ne.bind(a.bondGotIt,"click",(function(){o()})),Ne.bind(a.whatsABondBack,"click",(function(){o()})),Ne.bind(a.usePrepaidBond,"click",(function(){r.showPrepaidBondForm()})),Ne.bind(a.ppbGoBack,"click",(function(){r.hidePrepaidBondForm()})),Ne.bind(a.submitPrepaidBond,"click",(function(){r.submitPrepaidBond()})),ft().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,Ne.show(this.page.tradingTierErr)}},{key:"setAssetError",value:function(e){this.page.regAssetErr.textContent=e,Ne.show(this.page.regAssetErr)}},{key:"clearErrors",value:function(){Ne.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;Ne.hide(r.assetForm,r.tradingTierForm,r.whatsABondPanel,r.prepaidBonds),Ne.empty(r.bondAssets,r.markets),this.clearErrors();for(var a=function(e,t){var a=ft().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=Ne.parseTemplate(u);d.logo.src=Ne.logoPath(l),d.name.textContent=c,Ne.bind(u,"click",(function(){n.assetSelected(e)})),d.feeSymbol.textContent=s;var h=t.amount/i;d.feeAmt.textContent=Ne.formatFourSigFigs(h);var p=ft().fiatRatesMap[e];Ne.setVis(p,d.fiatBox),p&&(d.fiatBondAmount.textContent=Ne.formatFourSigFigs(h*p)),n.assetRows[e]={ready:d.ready}}},o=function(t){var a=t.baseid,o=t.quoteid,s=[ft().assets[a],ft().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=Sr(Ne.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=Sr(Ne.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=Ne.parseTemplate(i);y.baseLogo.src=Ne.logoPath(u),y.quoteLogo.src=Ne.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*Cn*e;y.tradeLimitLow.textContent=Ne.formatFourSigFigs(s),y.tradeLimitHigh.textContent=Ne.formatFourSigFigs(i);var c=ft().fiatRatesMap[a];c&&(y.fiatTradeLimitLow.textContent=Ne.formatFourSigFigs(s*c),y.fiatTradeLimitHigh.textContent=Ne.formatFourSigFigs(i*c)),Ne.setVis(c,r.fiatTradeLowBox,r.fiatTradeHighBox)};b(Fn(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(Ne.setVis(R,t.currentBondBox),R){Ne.empty(t.currentBonds);for(var E=0,B=Object.entries(w);E0){Ne.show(r.bondCostBreakdown),r.bondLockNoFees.textContent=Ne.formatCoinValue(g,s),r.bondLockFees.textContent=Ne.formatCoinValue(t,s),g+=t;var y=Math.max(g-c.available+c.reservesDeficit,0);if(r.totalForBond.textContent=Ne.formatCoinValue(y,s),Ne.hide(r.sendEnough),Ne.hide(r.txFeeBox,r.sendEnoughForToken,r.txFeeBalanceBox),Ne.hide(r.sendEnoughWithEst),h){Ne.show(r.txFeeBox,r.sendEnoughForToken,r.txFeeBalanceBox);var b=ft().assets[h.parentID];r.txFee.textContent=Ne.formatCoinValue(t,b.unitInfo),r.parentFees.textContent=Ne.formatCoinValue(t,b.unitInfo),r.tokenFees.textContent=Ne.formatCoinValue(y,s),v(r.txFeeUnit,b),v(r.parentUnit,b),v(r.parentBalUnit,b),r.parentBal.textContent=b.wallet?Ne.formatCoinValue(b.wallet.balance.available,b.unitInfo):"0"}else Ne.show(r.sendEnoughWithEst);r.fee.textContent=Ne.formatCoinValue(g,s)}else Ne.show(r.sendEnough);Ne.show(u?r.syncCheck:d>=1?r.syncSpinner:r.syncUncheck),Ne.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=ft().assets[this.assetID],r=n.wallet.balance.available;if(t.balance.textContent=Ne.formatCoinValue(r,n.unitInfo),n.token){var a=ft().assets[n.token.parentID],o=a.wallet.balance.available;if(t.parentBal.textContent=Ne.formatCoinValue(o,a.unitInfo),o=.999)return Ne.hide(n.syncRemaining),Ne.show(n.syncFinishingUp),Ne.show(n.syncRemainBox),void(n.syncFinishingUp.textContent=ke("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){Ne.hide(n.syncFinishingUp),Ne.show(n.syncRemaining),Ne.show(n.syncRemainBox);var c=i/(s.stamp-o.stamp),l=(1-s.progress)/c;n.syncRemain.textContent=Ne.formatDuration(l)}}}}]),e}(),Pr=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=Ne.idDescendants(t);Ne.bind(a.accelerateSubmit,"click",(function(){r.submit()})),Ne.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?(Ne.show(e.recentAccelerationMsg),Ne.hide(e.recentSwapMsg),e.recentAccelerationTime.textContent="".concat(Math.floor(this.earlyAcceleration.timePast/60))):(Ne.show(e.recentSwapMsg),Ne.hide(e.recentAccelerationMsg),e.recentSwapTime.textContent="".concat(Math.floor(this.earlyAcceleration.timePast/60))),Ne.hide(e.configureAccelerationDiv,e.accelerateErr),Ne.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=ft().loading(n.accelerateMainDiv),e.next=6,S("/api/accelerateorder",r);case 6:o=e.sent,a(),ft().checkResponse(o)?(n.accelerateTxID.textContent=o.txID,Ne.hide(n.accelerateMainDiv,n.preAccelerateErr,n.accelerateErr),Ne.show(n.accelerateMsgDiv,n.accelerateSuccess),this.success()):(n.accelerateErr.textContent=ke(Z,{msg:o.msg}),Ne.hide(n.earlyAccelerationDiv),Ne.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,S("/api/preaccelerate",t.id);case 4:if(r=e.sent,ft().checkResponse(r)){e.next=10;break}return n.preAccelerateErr.textContent=ke(Z,{msg:r.msg}),Ne.hide(n.accelerateMainDiv,n.accelerateSuccess),Ne.show(n.accelerateMsgDiv,n.preAccelerateErr),e.abrupt("return");case 10:Ne.hide(n.accelerateMsgDiv,n.preAccelerateErr,n.accelerateErr,n.feeEstimateDiv,n.earlyAccelerationDiv),Ne.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 kt(a.suggestedRange,a.suggestedRange.start.x,{updated:s,changed:function(){return c.updateAccelerationEstimate()},selected:o,roundY:!0}),Ne.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=ft().loading(t.sliderContainer),e.next=6,S("/api/accelerationestimate",r);case 6:if(o=e.sent,a(),ft().checkResponse(o)){e.next=12;break}return t.accelerateErr.textContent=ke("ORDER_ACCELERATION_FEE_ERR_MSG",{msg:o.msg}),Ne.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=ft().unitInfo(s),t.feeEstimate.textContent="".concat(o.fee/c.conventional.conversionFactor," ").concat(i),Ne.show(t.feeEstimateDiv);case 17:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})}]),e}(),Lr=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=Ne.parseTemplate(t);this.certPicker=new Wr(t),Ne.bind(o.skipRegistration,"change",(function(){return a.showOrHideSubmitBttn()})),Ne.bind(o.showCustom,"click",(function(){Ne.hide(o.showCustom),Ne.show(o.customBox,o.auth)})),this.knownExchanges=Array.from(o.knownXCs.querySelectorAll(".known-exchange"));var s,c=Sr(this.knownExchanges);try{var l=function(){var e=s.value;Ne.bind(e,"click",(function(){var t,n=e.dataset.host,r=Sr(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()}Gr(t,o.submit,(function(){return a.checkDEX()})),r&&(Ne.hide(o.addDexHdr,o.skipRegistrationBox),Ne.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(),Ne.hide(e.err),0===this.knownExchanges.length||this.dexToUpdate?(Ne.show(e.customBox,e.auth),Ne.hide(e.showCustom,e.knownXCs,e.pickServerMsg,e.addCustomMsg)):(Ne.hide(e.customBox),Ne.show(e.showCustom));var t,n=Sr(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;Ne.setVis(Ne.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,Ne.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,Ne.hide(n.err),""!==(t=t||n.addr.value)){e.next=7;break}return n.err.textContent=ke("EMPTY_DEX_ADDRESS_MSG"),Ne.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=ft().loading(this.form),e.next=15,S(o,s);case 15:if(c=e.sent,i(),ft().checkResponse(c)){e.next=20;break}return String(c.msg).includes("certificate required")?Ne.show(n.needCert):(n.err.textContent=c.msg,Ne.show(n.err)),e.abrupt("return");case 20:return e.next=22,ft().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,ft().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}(),Or=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=Ne.parseTemplate(t);o.dexHost.textContent=n,Gr(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,Ne.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,Ne.hide(t.err),n={addr:this.addr},r=ft().loading(this.form),e.next=6,S("/api/discoveracct",n);case 6:if(a=e.sent,r(),ft().checkResponse(a)){e.next=12;break}return t.err.textContent=a.msg,Ne.show(t.err),e.abrupt("return");case 12:if(!a.paid){e.next=18;break}return e.next=15,ft().fetchUser();case 15:return e.next=17,ft().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}(),Mr=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,Gr(t,(this.page=Ne.parseTemplate(t)).submit,(function(){r.submit()})),ft().registerNoteFeeder({login:function(e){r.handleLoginNote(e)}})}var t,n;return d(e,[{key:"handleLoginNote",value:function(e){if(""!==e.details){var t=Ne.idel(this.form,"loaderMsg");Ne.show(t),t&&(t.textContent=e.details)}}},{key:"focus",value:function(){this.page.pw.focus()}},{key:"refresh",value:function(){Ne.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,Ne.hide(t.errMsg),""!==(n=t.pw.value||"")){e.next=6;break}return Ne.showFormError(t.errMsg,ke(R)),e.abrupt("return");case 6:return r=ft().loading(this.form),e.next=9,S("/api/login",{pass:n});case 9:if(a=e.sent,r(),t.pw.value="",ft().checkResponse(a)){e.next=15;break}return Ne.showFormError(t.errMsg,a.msg),e.abrupt("return");case 15:return e.next=17,ft().fetchUser();case 17:a.notes=a.notes||[],a.notes.reverse(),a.pokes=a.pokes||[],ft().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,Ne.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}(),qr=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=Ne.idDescendants(t);Ne.cleanTemplates(r.unifiedReceiverTmpl),Ne.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)})))),Ne.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,Ne.hide(n.depositErr,n.depositTokenMsgBox),r=ft().assets[t],n.depositLogo.src=Ne.logoPath(r.symbol),a=ft().walletMap[t],n.depositName.textContent=r.unitInfo.conventional.unit,r.token&&(o=ft().assets[r.token.parentID],n.depositTokenParentLogo.src=Ne.logoPath(o.symbol),n.depositTokenParentName.textContent=o.name,Ne.show(n.depositTokenMsgBox)),Ne.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(Ne.hide(n.unifiedReceivers),e.startsWith("unified:")){var r=JSON.parse(e.substring(8));Ne.empty(n.unifiedReceivers),Ne.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"),Ne.bind(c,"click",(function(){for(var e=0,a=Array.from(n.unifiedReceivers.children);e=r?Ne.hide(t.addressBox):Ne.hide(t.errMsg))}}]),e}(),Ur=function(){function e(t,n){var r=this;i(this,e),h(this,"form",void 0),h(this,"page",void 0),h(this,"updated",void 0),h(this,"cexName",void 0),this.form=t,this.updated=n,this.page=Ne.parseTemplate(t),Ne.bind(this.page.cexSubmit,"click",(function(){return r.submit()}))}var t;return d(e,[{key:"setCEX",value:function(e){this.cexName=e,ur(this.form,e);var t=this.page;Ne.hide(t.cexConfigPrompt,t.cexConnectErrBox,t.cexFormErr),t.cexApiKeyInput.value="",t.cexSecretInput.value="";var n=ft().mmStatus.cexes[e],r=null==n?void 0:n.connectErr;r?(Ne.show(t.cexConnectErrBox),t.cexConnectErr.textContent=r,t.cexApiKeyInput.value=n.config.apiKey,t.cexSecretInput.value=n.config.apiSecret):Ne.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,Ne.hide(t.cexFormErr),a=t.cexApiKeyInput.value,o=t.cexSecretInput.value,a&&o){e.next=8;break}return Ne.show(t.cexFormErr),t.cexFormErr.textContent=ke(R),e.abrupt("return");case 8:return s=ft().loading(r),e.prev=9,e.next=12,ir.updateCEXConfig({name:n,apiKey:a,apiSecret:o});case 12:if(i=e.sent,ft().checkResponse(i)){e.next=15;break}throw i;case 15:this.updated(n,!0),e.next=23;break;case 18:e.prev=18,e.t0=e.catch(9),Ne.show(t.cexFormErr),t.cexFormErr.textContent=ke(H,{msg:null!==(c=e.t0.msg)&&void 0!==c?c:String(e.t0)}),this.updated(n,!1);case 23:return e.prev=23,s(),e.finish(23);case 26:case"end":return e.stop()}}),e,this,[[9,18,23,26]])}))),function(){return t.apply(this,arguments)})}]),e}(),_r=300;function jr(e,t){return Hr.apply(this,arguments)}function Hr(){return(Hr=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,Ne.animate(_r,(function(e){t.style.right="".concat(e*r,"px")}),"easeInHard");case 3:return Ne.hide(t),t.style.right="0",n.style.right=String(-r),Ne.show(n),n.querySelector("input")&&Ne.safeSelector(n,"input").focus(),e.next=10,Ne.animate(_r,(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 zr(e,t){e.successMessage.textContent=t,Ne.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 We(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 Gr(e,t,n){var r=function(e){e.preventDefault&&e.preventDefault(),n(e)};Ne.bind(t,"click",r),Ne.bind(e,"submit",r)}function Xr(e){return Math.floor(e.getTime()/1e3)}function Kr(e){return function(e){return new Date(e.getTime()-60*e.getTimezoneOffset()*1e3)}(e).toISOString().split("T")[0]}function Qr(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&&Ne.hide(c)}}catch(e){o.e(e)}finally{o.f()}n.newWalletForm=new Dr(r.newWalletForm,(function(e){return n.newWalletCreated(e,n.confirmRegisterForm.tier)}),(function(){return n.animateRegAsset(r.newWalletForm)})),n.dexAddrForm=new Lr(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 Or(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 Er(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!==pt){e.next=3;break}return n.registerDEXSuccess(),e.abrupt("return");case 3:if(o=ft().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),jr(r.regAssetForm,r.walletWait),e.abrupt("return");case 17:n.confirmRegisterForm.tier=a,n.newWalletForm.setAsset(t),jr(r.regAssetForm,r.newWalletForm);case 20:case"end":return e.stop()}}),e)})));return function(t,n){return e.apply(this,arguments)}}()),n.walletWaitForm=new Br(r.walletWait,(function(){n.animateConfirmForm(r.walletWait)}),(function(){n.animateRegAsset(r.walletWait)})),n.confirmRegisterForm=new Rr(r.confirmRegForm,(function(){n.registerDEXSuccess()}),(function(){n.animateRegAsset(r.confirmRegForm)}));var u=Ne.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 Ne.show(u),u===r.discoverAcctForm&&n.discoverAcctForm.page.submit.click(),ft().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,ft().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:Ne.hide(t),this.regAssetForm.animate(),Ne.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(),Ne.hide(t),Ne.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=ft().loading(n),e.next=3,S("/api/bondsfeebuffer",{assetID:t});case 3:if(a=e.sent,r(),ft().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,ft().fetchUser();case 2:return ft().updateMenuItemsDisplay(),e.next=5,ft().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,ft().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,jr(a.newWalletForm,a.walletWait);case 21:case"end":return e.stop()}}),e,this)}))),function(e,n){return t.apply(this,arguments)})}]),k}(lt);var Jr=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=Ne.idDescendants(e);t.loginForm=new Mr(n.loginForm,(function(){t.loggedIn()}));var r=function(){Ne.hide(n.resetAppPWForm),t.loginForm.refresh(),Ne.show(n.loginForm),t.loginForm.focus()};return r(),t.appPassResetForm=new Nr(n.resetAppPWForm,(function(){r()})),Ne.bind(n.forgotPassBtn,"click",(function(){t.appPassResetForm.refresh(),jr(n.loginForm,n.resetAppPWForm)})),Ne.bind(n.resetPassFormCloser,"click",(function(){r()})),Ne.bind(n.forms,"mousedown",(function(e){!Ne.mouseInElement(e,n.resetAppPWForm)&&Ne.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,ft().loadPage("wallets");case 2:case"end":return e.stop()}}),e)}))),function(){return t.apply(this,arguments)})}]),o}(lt);function Zr(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 $r(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)?$r(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 $r(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){Ne.bind(e,"click",(function(){n.closePopups()}))})),Ne.bind(r.cancelForce,"click",(function(){n.closePopups()})),n.selectedAssetID=-1,Ne.cleanTemplates(r.iconSelectTmpl,r.balanceDetailRow,r.recentOrderTmpl,r.vspRowTmpl,r.ticketHistoryRowTmpl,r.votingChoiceTmpl,r.votingAgendaTmpl,r.tspendTmpl,r.tkeyTmpl,r.txHistoryRowTmpl,r.txHistoryDateRowTmpl),Ne.bind(r.createWallet,"click",(function(){return n.showNewWallet(n.selectedAssetID)})),Ne.bind(r.connectBttn,"click",(function(){return n.doConnect(n.selectedAssetID)})),Ne.bind(r.send,"click",(function(){return n.showSendForm(n.selectedAssetID)})),Ne.bind(r.receive,"click",(function(){return n.showDeposit(n.selectedAssetID)})),Ne.bind(r.unlockBttn,"click",(function(){return n.openWallet(n.selectedAssetID)})),Ne.bind(r.lockBttn,"click",(function(){return n.lock(n.selectedAssetID)})),Ne.bind(r.reconfigureBttn,"click",(function(){return n.showReconfig(n.selectedAssetID)})),Ne.bind(r.needsProviderBttn,"click",(function(){return n.showReconfig(n.selectedAssetID)})),Ne.bind(r.rescanWallet,"click",(function(){return n.rescanWallet(n.selectedAssetID)})),Ne.bind(r.earlierTxs,"click",(function(){return n.loadEarlierTxs()})),Ne.bind(r.copyTxIDBtn,"click",(function(){var e;rt((null===(e=n.currTx)||void 0===e?void 0:e.id)||"",r.txDetailsID,r.copyTxIDBtn,"#1e7d11")})),Ne.bind(r.copyRecipientBtn,"click",(function(){var e;rt((null===(e=n.currTx)||void 0===e?void 0:e.recipient)||"",r.txDetailsRecipient,r.copyRecipientBtn,"#1e7d11")})),Ne.bind(r.copyBondIDBtn,"click",(function(){var e,t;rt((null===(e=n.currTx)||void 0===e||null===(t=e.bondInfo)||void 0===t?void 0:t.bondID)||"",r.txDetailsBondID,r.copyBondIDBtn,"#1e7d11")})),Ne.bind(r.copyBondAccountIDBtn,"click",(function(){var e,t;rt((null===(e=n.currTx)||void 0===e||null===(t=e.bondInfo)||void 0===t?void 0:t.accountID)||"",r.txDetailsBondAccountID,r.copyBondAccountIDBtn,"#1e7d11")})),Ne.bind(r.hideMixTxsCheckbox,"change",(function(){n.showTxHistory(n.selectedAssetID)})),n.newWalletForm=new Dr(r.newWalletForm,(function(e){var t={assetName:ft().assets[e].name};n.assetUpdated(e,r.newWalletForm,ke("NEW_WALLET_SUCCESS",t)),n.sortAssetButtons(),n.updateTicketBuyer(e),n.updatePrivacy(e)})),n.reconfigForm=new Ar(r.reconfigInputs,!1),n.walletCfgGuide=Ne.tmplElement(r.reconfigForm,"walletCfgGuide"),Gr(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)})))),Gr(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)})))),Gr(r.reconfigForm,r.submitReconfig,(function(){return n.reconfig()})),r.forms.querySelectorAll(".form-closer").forEach((function(e){Ne.bind(e,"click",(function(){return n.closePopups()}))})),Ne.bind(r.forms,"mousedown",(function(e){Ne.mouseInElement(e,n.currentForm)||n.closePopups()})),n.mixerToggle=new _e(r.toggleMixer,r.mixingErr,!1,(function(e){return n.updateMixerState(e)})),n.keyup=function(e){"Escape"===e.key&&Ne.isDisplayed(n.page.forms)&&n.closePopups()},Ne.bind(document,"keyup",n.keyup),Ne.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)})))),Ne.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)})))),Ne.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)})))),Gr(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)})))),Gr(r.recoverWalletConfirm,r.recoverWalletSubmit,(function(){n.recoverWallet()})),Gr(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)})))),Ne.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)})))),Ne.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)})))),Gr(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)})))),Ne.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)})))),Ne.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)})))),Ne.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)})))),Ne.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)})))),Ne.bind(r.showVSPs,"click",(function(){n.showVSPPicker()})),Ne.bind(r.vspDisplay,"click",(function(){n.showVSPPicker()})),Gr(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)})))),Ne.bind(r.purchaseTicketsBttn,"click",(function(){n.showPurchaseTicketsDialog()})),Gr(r.purchaseTicketsForm,r.purchaserSubmit,(function(){n.purchaseTickets()})),Ne.bind(r.purchaserInput,"change",(function(){n.purchaserInputChanged()})),Ne.bind(r.ticketHistory,"click",(function(){n.showTicketHistory()})),Ne.bind(r.ticketHistoryNextPage,"click",(function(){n.nextTicketPage()})),Ne.bind(r.ticketHistoryPrevPage,"click",(function(){n.prevTicketPage()})),Ne.bind(r.setVotes,"click",(function(){n.showSetVotesDialog()})),Ne.bind(r.purchaseTicketsErrCloser,"click",(function(){Ne.hide(r.purchaseTicketsErrBox)})),Ne.bind(r.privacyInfoBttn,"click",(function(){n.showForm(r.mixingInfo)})),n.depositAddrForm=new qr(r.deposit),Ne.bind(r.walletBal,"click",(function(){n.populateMaxSend()})),Ne.bind(r.sendAmt,"input",(function(){var e=ft().assets[n.selectedAssetID].unitInfo,t=tt(r.sendAmt.value),a=e.conventional.conversionFactor;Ne.showFiatValue(r.sendValue,t*a,ft().fiatRatesMap[n.selectedAssetID],e)})),Ne.bind(r.maxSend,"click",(function(){n.populateMaxSend()})),Ne.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=ft().assets[n.selectedAssetID],r.sendAddr.classList.remove("border-danger","border-success"),a=r.sendAddr.value||"",t&&""!==a){e.next=5;break}return e.abrupt("return");case 5:return e.next=7,n.validateSendAddress(a,t.id);case 7:e.sent?r.sendAddr.classList.add("border-success"):r.sendAddr.classList.add("border-danger");case 9:case"end":return e.stop()}}),e)})))),Ne.bind(r.showChangePW,"click",(function(){n.changeWalletPW=!n.changeWalletPW,n.setPWSettingViz(n.changeWalletPW)})),Ne.bind(r.changeWalletTypeSelect,"change",(function(){n.changeWalletType()})),Ne.bind(r.showChangeType,"click",(function(){Ne.isHidden(r.changeWalletType)?(Ne.show(r.changeWalletType,r.changeTypeHideIcon),Ne.hide(r.changeTypeShowIcon),r.changeTypeMsg.textContent=ke("KEEP_WALLET_TYPE")):n.showReconfig(n.selectedAssetID,{skipAnimation:!0})})),ft().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=Zr(n.page.txHistoryTableBody.children);try{for(t.s();!(e=t.n()).done;){var r=e.value,a=Ne.tmplElement(r,"age");a.textContent=Ne.timeSince(parseInt(a.dataset.timestamp))}}catch(e){t.e(e)}finally{t.f()}}),5e3),n}return d(ve,[{key:"closePopups",value:function(){Ne.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,S(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,C;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=this.page,Ne.hide(t.vSendErr,t.sendErr,t.vSendEstimates,t.txFeeNotAvailable),n=parseInt(t.sendForm.dataset.assetID||""),r=ft().assets[n].token,a=t.subtractCheckBox.checked||!1,o=ft().unitInfo(n).conventional.conversionFactor,s=Math.round(tt(t.sendAmt.value,0)*o),""!==(i=t.sendAddr.value||"")){e.next=10;break}return e.abrupt("return",Ne.showFormError(t.sendErr,ke(G,{address:i})));case 10:if(c=ft().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=ft().loading(t.sendForm),e.next=17,S("/api/txfee",p);case 17:if(m=e.sent,v(),ft().checkResponse(m)){e.next=29;break}return t.txFeeNotAvailable.dataset.tooltip=ke("TXFEE_ERR_MSG",{err:m.msg}),Ne.show(t.txFeeNotAvailable),e.next=24,this.validateSendAddress(i,n);case 24:if(e.sent){e.next=27;break}return e.abrupt("return",Ne.showFormError(t.sendErr,ke(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",Ne.showFormError(t.sendErr,ke(G,{address:t.sendAddr.value||""})));case 32:h=m.txfee,Ne.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",Ne.showFormError(t.sendErr,ke(G,{address:i||""})));case 41:return t.vSendSymbol.textContent=d.toUpperCase(),t.vSendLogo.src=Ne.logoPath(d),r?(g=ft().assets[r.parentID],y=g.unitInfo,b=g.symbol,t.vSendFee.textContent=Ne.formatFullPrecision(h,y)+" "+b):t.vSendFee.textContent=Ne.formatFullPrecision(h,u),x=ft().fiatRatesMap[n],Ne.showFiatValue(t.vSendFeeFiat,h,x,u),t.vSendDestinationAmt.textContent=Ne.formatFullPrecision(s-h,u),t.vTotalSend.textContent=Ne.formatFullPrecision(s,u),Ne.showFiatValue(t.vTotalSendFiat,s,x,u),t.vSendAddr.textContent=t.sendAddr.value||"",k=l.balance.available-s,t.balanceAfterSend.textContent=Ne.formatFullPrecision(k,u),Ne.showFiatValue(t.balanceAfterSendFiat,k,x,u),Ne.show(t.approxSign),a||(Ne.hide(t.approxSign),t.vSendDestinationAmt.textContent=Ne.formatFullPrecision(s,u),w=s,r||(w+=h),t.vTotalSend.textContent=Ne.formatFullPrecision(w,u),Ne.showFiatValue(t.vTotalSendFiat,w,x,u),C=l.balance.available-s,r||(C-=h),C<=0?(t.balanceAfterSend.textContent=Ne.formatFullPrecision(0,u),Ne.showFiatValue(t.balanceAfterSendFiat,0,x,u)):(t.balanceAfterSend.textContent=Ne.formatFullPrecision(C,u),Ne.showFiatValue(t.balanceAfterSendFiat,C,x,u))),Ne.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,Ne.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,S("/api/validateaddress",{addr:t,assetID:n});case 2:return r=e.sent,e.abrupt("return",ft().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 Ne.hide(t.showIcon),Ne.show(t.hideIcon,t.changePW),void(t.switchPWMsg.textContent=ke("KEEP_WALLET_PASS"));Ne.hide(t.hideIcon,t.changePW),Ne.show(t.showIcon),t.switchPWMsg.textContent=ke("NEW_WALLET_PASS")}},{key:"assetVersionUsedByDEXes",value:function(){var e=this.selectedAssetID,t={},n=ft().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,S("/api/unapprovetoken",{assetID:this.selectedAssetID,version:this.unapprovingTokenVersion});case 4:if(n=e.sent,ft().checkResponse(n)){e.next=9;break}return t.unapproveTokenErr.textContent=n.msg,Ne.show(t.unapproveTokenErr),e.abrupt("return");case 9:(r=zn[this.selectedAssetID])&&r[da]&&(t.unapproveTokenTxID.href=r[da](n.txID)),t.unapproveTokenTxID.textContent=n.txID,Ne.hide(t.unapproveTokenSubmissionElements,t.unapproveTokenErr),Ne.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,Ne.show(n.unapproveTokenSubmissionElements),Ne.hide(n.unapproveTokenTxMsg,n.unapproveTokenErr),(r=ft().assets[this.selectedAssetID])&&r.token){e.next=7;break}return e.abrupt("return");case 7:if(a=ft().assets[r.token.parentID]){e.next=10;break}return e.abrupt("return");case 10:return Ne.empty(n.tokenAllowanceRemoveSymbol),n.tokenAllowanceRemoveSymbol.appendChild(Ne.symbolize(r,!0)),n.tokenAllowanceRemoveVersion.textContent=t.toString(),e.next=16,S("/api/approvetokenfee",{assetID:this.selectedAssetID,version:t,approving:!1});case 16:o=e.sent,ft().checkResponse(o)?(s="".concat(Ne.formatCoinValue(o.txFee,a.unitInfo)," ").concat(a.unitInfo.conventional.unit),(i=ft().fiatRatesMap[a.id])&&(s+=" (".concat(Ne.formatFiatConversion(o.txFee,i,a.unitInfo)," USD)")),n.unapprovalFeeEstimate.textContent=s):(n.unapproveTokenErr.textContent=o.msg,Ne.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=ft().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);Ne.empty(t.tokenVersionTableAssetSymbol),t.tokenVersionTableAssetSymbol.appendChild(Ne.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===dt.Approved){e.next=3;break}return e.abrupt("return","continue");case 3:a=!0,c=t.tokenVersionRow.cloneNode(!0),(l=Ne.parseTemplate(c)).version.textContent=o.toString(),r[o]&&(l.usedBy.textContent=r[o].join(", ")),u=i.page.removeIconTmpl.cloneNode(!0),Ne.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:Ne.setVis(a,t.tokenVersionTable),Ne.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,Ne.hide(t.peerSpinner),e.next=4,S("/api/getwalletpeers",{assetID:this.selectedAssetID});case 4:if(n=e.sent,ft().checkResponse(n)){e.next=9;break}return t.managePeersErr.textContent=n.msg,Ne.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=ke("DEFAULT"),o=ke("ADDED"),i=ke("DISCOVERED"),r.forEach((function(e){var n,r=t.peerTableRow.cloneNode(!0),l=Ne.parseTemplate(r);switch(l.addr.textContent=e.addr,e.source){case ht.WalletDefault:l.source.textContent=a;break;case ht.UserAdded:l.source.textContent=o;break;case ht.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===ht.UserAdded){var u=c.page.removeIconTmpl.cloneNode(!0);Ne.bind(u,"click",s(f().mark((function n(){var r;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return Ne.hide(t.managePeersErr),n.next=3,S("/api/removewalletpeer",{assetID:c.selectedAssetID,addr:e.addr});case 3:if(r=n.sent,ft().checkResponse(r)){n.next=8;break}return t.managePeersErr.textContent=r.msg,Ne.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:Ne.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,Ne.hide(t.managePeersErr),e.next=4,S("/api/addwalletpeer",{assetID:this.selectedAssetID,addr:t.addPeerInput.value});case 4:if(n=e.sent,ft().checkResponse(n)){e.next=9;break}return t.managePeersErr.textContent=n.msg,Ne.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,Ne.show(t.peerSpinner),setTimeout((function(){Ne.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;Ne.hide(t.toggleWalletStatusErr,t.walletStatusDisable,t.disableWalletMsg,t.walletStatusEnable,t.enableWalletMsg),e?Ne.show(t.walletStatusDisable,t.disableWalletMsg):Ne.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,Ne.hide(t.toggleWalletStatusErr),n=ft().assets[this.selectedAssetID],r=!n.wallet.disabled,a={assetID:this.selectedAssetID,disable:r},o={assetName:n.name},s=ft().loading(t.toggleWalletStatusConfirm),e.next=10,S("/api/togglewalletstatus",a);case 10:if(i=e.sent,s(),ft().checkResponse(i)){e.next=16;break}return i.code===A.activeOrdersErr?t.toggleWalletStatusErr.textContent=ke("ACTIVE_ORDERS_ERR_MSG",o):t.toggleWalletStatusErr.textContent=i.msg,Ne.show(t.toggleWalletStatusErr),e.abrupt("return");case 16:c=ke("WALLET_DISABLED",o),r||(c=ke("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",Ne.show(t),n&&n.focus(),e.next=5,Ne.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 Ne.hide(e)})),t.style.right="10000px",Ne.show(n.forms,t),r=(n.forms.offsetWidth+t.offsetWidth)/2,e.next=8,Ne.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 Ne.hide(e)})),this.currentForm=this.page.checkmarkForm,this.animation=zr(this.page,t),e.next=5,this.animation.wait();case 5:this.animation=new We(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={},Ne.empty(t.assetSelect);var n=r(Object.values(ft().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=[ft().fiatRatesMap[e.id],ft().fiatRatesMap[t.id]],c=i[0],l=i[1];return c&&!l?-1:!c&&l?1:l*s-c*o}));var a,o=Zr(n);try{var s=function(){var n=a.value,r=t.iconSelectTmpl.cloneNode(!0);t.assetSelect.appendChild(r);var o=Ne.parseTemplate(r);e.assetButtons[n.id]={tmpl:o,bttn:r},e.updateAssetButton(n.id),Ne.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=ft().assets[e],r=this.assetButtons[e],o=r.bttn,s=r.tmpl;Ne.hide(s.fiatBox,s.noWallet),o.classList.add("nowallet"),(t=s.img).src||(t.src=Ne.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=Ne.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(Ne.formatBestUnitsFourSigFigs(h,d),2),f=p[0],v=p[1];s.balance.textContent=f,s.unit.textContent=v,Ne.show(s.balanceBox);var m=ft().fiatRatesMap[n.id];m&&(Ne.show(s.fiatBox),s.fiat.textContent=Ne.formatFourSigFigs(h/d.conventional.conversionFactor*m))}else Ne.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=Zr(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)Ne.show(t.txFindingAddrs);else{Ne.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;Ne.hide(t.feeStateBox);var r=ft().assets[n],a=r.unitInfo,o=r.token,s=ft().fiatRatesMap[n];if(s){var i=o?o.parentID:n,c=ft().fiatRatesMap[i];if(!o||c){Ne.show(t.feeStateBox);var l=o?ft().assets[o.parentID].unitInfo:a;Ne.formatBestRateElement(t.feeStateNetRate,i,e.rate,l),Ne.formatBestValueElement(t.feeStateSendFees,i,e.send,l),Ne.formatBestValueElement(t.feeStateSwapFees,i,e.swap,l),Ne.formatBestValueElement(t.feeStateRedeemFees,i,e.redeem,l),t.feeStateXcRate.textContent=Ne.formatFourSigFigs(s);var u=e.send/l.conventional.conversionFactor*c;t.feeStateSendFiat.textContent=Ne.formatFourSigFigs(u);var d=e.swap/l.conventional.conversionFactor*c;t.feeStateSwapFiat.textContent=Ne.formatFourSigFigs(d);var h=e.redeem/l.conventional.conversionFactor*c;t.feeStateRedeemFiat.textContent=Ne.formatFourSigFigs(h),Ne.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,ft().needsCustomProvider(t);case 2:if(n=e.sent,r=this.page,a=r.needsProviderBox,o=r.needsProviderBttn,Ne.setVis(n,a),n){e.next=7;break}return e.abrupt("return");case 7:Ne.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=ft().assets[t],a=r.wallet,o=r.unitInfo,s=this.page,Ne.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 Ne.show(s.stakingBox),i=ft().loading(s.stakingBox),e.next=10,this.safePost("/api/stakestatus",t);case 10:if(c=e.sent,i(),ft().checkResponse(c)){e.next=19;break}if(!c.msg.includes("disconnected from consensus RPC")){e.next=16;break}return Ne.show(s.stakingRpcSpvMsg),e.abrupt("return");case 16:return Ne.show(s.stakingErr),s.stakingErr.textContent=c.msg,e.abrupt("return");case 19:if(Ne.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=Ne.formatFourSigFigs(l.ticketPrice/o.conventional.conversionFactor),s.purchaserBal.textContent=Ne.formatCoinValue(a.balance.available,o),this.updateTicketStats(l.stats,o,l.ticketPrice,l.votingSubsidy),!(null===(n=ft().extensionWallet(this.selectedAssetID))||void 0===n?void 0:n.disableStaking)){e.next=33;break}return Ne.hide(s.setVotes,s.showVSPs),Ne.show(s.ticketsDisabled),s.extensionModeAppName.textContent=ft().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(Ne.hide(t.vspDisplayBox),e)return Ne.show(t.vspDisplayBox,t.purchaseTicketsBox),Ne.hide(t.pickVSP),void(t.vspURL.textContent=e);Ne.setVis(!n.isRPC,t.pickVSP),Ne.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),Ne.setVis(e.mempool>0,a.immatureTicketCountBox),a.queuedTicketCount.textContent=String(e.queued),a.formQueuedTix.textContent=String(e.queued),Ne.setVis(e.queued>0,a.formQueueTixBox,a.queuedTicketCountBox),a.totalTicketCount.textContent=String(e.ticketCount),a.totalTicketRewards.textContent=Ne.formatFourSigFigs(e.totalRewards/t.conventional.conversionFactor),a.totalTicketVotes.textContent=String(e.votes),n&&(a.ticketPrice.textContent=Ne.formatFourSigFigs(n/t.conventional.conversionFactor)),r&&(a.votingSubsidy.textContent=Ne.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),Ne.empty(n.vspPickerList),Ne.hide(n.stakingErr),r=ft().loading(n.vspPicker),e.next=8,this.safePost("/api/listvsps",t);case 8:if(a=e.sent,r(),ft().checkResponse(a)){e.next=14;break}return Ne.show(n.stakingErr),n.stakingErr.textContent=a.msg,e.abrupt("return");case 14:o=a.vsps,s=Zr(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=Ne.parseTemplate(a)).url.textContent=r.url,o.feeRate.textContent=r.feePercentage.toFixed(2),o.voting.textContent=String(r.voting),Ne.bind(a,"click",(function(){Ne.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="",Ne.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=ft().loading(t.purchaseTicketsForm),e.next=7,this.safePost("/api/purchasetickets",{assetID:n,n:r});case 7:if(o=e.sent,a(),ft().checkResponse(o)){e.next=13;break}return t.purchaserErr.textContent=o.msg,Ne.show(t.purchaserErr),e.abrupt("return");case 13:this.showSuccess(ke("TICKETS_PURCHASED",{n:r.toLocaleString(Ne.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 Ne.show(r.purchaseTicketsErrBox),void(r.purchaseTicketsErr.textContent=s);c&&(t.tickets=c.concat(t.tickets)),l&&this.updateTicketStats(l,ft().assets[a].unitInfo),t.stats.queued=i,r.queuedTicketCount.textContent=String(i),r.formQueuedTix.textContent=String(i),Ne.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=ft().loading(r.stakingBox),e.next=5,this.safePost("/api/setvsp",{assetID:t,url:n.url});case 5:if(o=e.sent,a(),ft().checkResponse(o)){e.next=11;break}return Ne.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*ua,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=ft().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(),ft().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=ua,n.ticketHistoryPagination),Ne.setVis(m>0,n.ticketHistoryTable),Ne.setVis(0===m,n.noTicketsMessage),0!==i.length){e.next=25;break}return Ne.hide(n.ticketHistoryNextPage),e.abrupt("return");case 25:this.displayTicketPage(t,i),o.number=t,g=t*ua+i.length===m,Ne.setVis(!g||!o.scanned,n.ticketHistoryNextPage),Ne.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=ft().unitInfo(a);Ne.hide(n.votingFormErr);var i=zn[a][ft().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 Ne.hide(n.votingFormErr),a=ft().loading(n.votingForm),e.next=4,t.safePost("/api/setvotes",r);case 4:if(o=e.sent,a(),ft().checkResponse(o)){e.next=10;break}throw Ne.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=Zr(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)}}();Ne.empty(n.votingAgendas);var u,d=Zr(r.stances.agendas);try{var p=function(){var e=u.value,t=n.votingAgendaTmpl.cloneNode(!0);n.votingAgendas.appendChild(t);var r=Ne.parseTemplate(t);r.description.textContent=e.description;var a,o=Zr(e.choices);try{var s=function(){var t=a.value,o=n.votingChoiceTmpl.cloneNode(!0);r.choices.appendChild(o);var s,i=Ne.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,Ne.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()}ft().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=Zr(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)}}();Ne.empty(n.votingTspends);var m,g=Zr(r.stances.tspends);try{var y=function(){var e=m.value,t=n.tspendTmpl.cloneNode(!0);n.votingTspends.appendChild(t),ft().bindUrlHandlers(t);for(var r=Ne.parseTemplate(t),a=function(){var t=c[s];t.name=e.hash,e.currentPolicy===t.value&&(t.checked=!0),Ne.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=Ne.formatFourSigFigs(e.value/o.conventional.conversionFactor):Ne.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=Zr(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)}}();Ne.empty(n.votingTKeys);var x,k=Zr(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=Ne.parseTemplate(t),a=function(){var t=s[o];t.name=e.key,e.policy===t.value&&(t.checked=!0),Ne.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(ke("ORDER"),c.orderlocked,ke("LOCKED_ORDER_BAL_MSG")),c.contractlocked>0&&m(ke("SWAPPING"),c.contractlocked,ke("LOCKED_SWAPPING_BAL_MSG")),c.bondlocked>0&&m(ke("BONDED"),c.bondlocked,ke("LOCKED_BOND_BAL_MSG")),c.bondReserves>0&&m(ke("BOND_RESERVES"),c.bondReserves,ke("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(ke("IMMATURE_TITLE"),c.immature,ke("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=Ne.formatFourSigFigs(c.available/s.conventional.conversionFactor),ft().bindTooltips(r.balanceDetailBox)}},{key:"showAvailableMarkets",value:function(e){for(var t=this.page,n=ft().user.exchanges,r=[],o=0,s=Object.values(n);o0&&(r.age.dataset.stamp=String(t.timestamp));var u=ia(t.type);if(t.tokenID&&t.tokenID!==n){var d=ft().assets[t.tokenID].unitInfo.conventional.unit;u="".concat(d," ").concat(u)}if(r.type.textContent=u,r.id.textContent=pa(t.id,12),r.id.setAttribute("title",t.id),r.fees.textContent=Ne.formatCoinValue(t.fees,l),aa.includes(t.type))r.amount.textContent="-";else{var h=a(oa(t.type),2),p=h[0],f=h[1],v=Ne.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,Ne.bind(r,"click",(function(){return n.showTxDetailsPopup(e.id)})),this.updateTxHistoryRow(r,e,t);var a=Ne.parseTemplate(r);return this.stampers.push(a.age),r}},{key:"txHistoryDateRow",value:function(e){var t=this.page.txHistoryDateRowTmpl.cloneNode(!0);return Ne.parseTemplate(t).date.textContent=e,t}},{key:"setTxDetailsPopupElements",value:function(e){var t=this.page,n=zn[this.selectedAssetID];n&&n[da]&&(t.txViewBlockExplorer.href=n[da](e.id));var r=ia(e.type);if(e.tokenID&&e.tokenID!==this.selectedAssetID){var o=ft().assets[e.tokenID].symbol.split(".")[0].toUpperCase();r="".concat(o," ").concat(r)}if(t.txDetailsType.textContent=r,Ne.setVis(16===e.type,t.txTypeTooltip),t.txTypeTooltip.dataset.tooltip=ke("SWAP_OR_SEND_TOOLTIP"),aa.includes(e.type))Ne.hide(t.txDetailsAmtSection);else{var s=this.selectedAssetID;e.tokenID&&(s=e.tokenID),Ne.show(t.txDetailsAmtSection);var i=ft().unitInfo(s),c=Ne.formatCoinValue(e.amount,i),l=a(oa(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=ft().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=ft().unitInfo(h),v=Ne.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),Ne.setVis(0===e.blockNumber,t.timestampPending,t.blockNumberPending),Ne.setVis(0!==e.blockNumber,t.txDetailsBlockNumber,t.txDetailsTimestamp),t.txDetailsID.textContent=pa(e.id,20),t.txDetailsID.setAttribute("title",e.id),e.recipient?(Ne.show(t.txDetailsRecipientSection),t.txDetailsRecipient.textContent=pa(e.recipient,20),t.txDetailsRecipient.setAttribute("title",e.recipient)):Ne.hide(t.txDetailsRecipientSection),e.bondInfo){Ne.show(t.txDetailsBondIDSection,t.txDetailsBondLocktimeSection),Ne.setVis(""!==e.bondInfo.accountID,t.txDetailsBondAccountIDSection),t.txDetailsBondID.textContent=pa(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=pa(e.bondInfo.accountID,20),t.txDetailsBondAccountID.setAttribute("title",e.bondInfo.accountID)}else Ne.hide(t.txDetailsBondIDSection,t.txDetailsBondLocktimeSection,t.txDetailsBondAccountIDSection);e.additionalData&&e.additionalData.Nonce?(Ne.show(t.txDetailsNonceSection),t.txDetailsNonce.textContent="".concat(e.additionalData.Nonce)):Ne.hide(t.txDetailsNonceSection)}},{key:"showTxDetailsPopup",value:function(e){var t=ft().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&&Ne.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==(ft().assets[this.selectedAssetID].wallet.traits&ea)||!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]):(Ne.show(this.page.txHistoryTable),Ne.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=Zr(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,ft().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,Ne.hide(n.txHistoryTable,n.txHistoryBox,n.noTxHistory,n.earlierTxs,n.txHistoryNotAvailable,n.hideMixTxs),Ne.empty(n.txHistoryTableBody),(a=ft().assets[t].wallet)&&!a.disabled&&0!=(65536&a.traits)){e.next=7;break}return Ne.show(n.txHistoryNotAvailable),e.abrupt("return");case 7:return this.oldestTx=void 0,o=0!=(a.traits&ea),Ne.setVis(o,n.hideMixTxs),Ne.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),Ne.show(n.noTxHistory),e.abrupt("return");case 22:if(0!==r.txs.length){e.next=25;break}return Ne.show(n.noTxHistory),e.abrupt("return");case 25:i=this.txDate(r.txs[0]),n.txHistoryTableBody.appendChild(this.txHistoryDateRow(i)),c=Zr(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],Ne.show(n.txHistoryTable),Ne.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=ft().assets[this.selectedAssetID].wallet,a=0!=(r.traits&ea)&&!!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=Zr(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()}Ne.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,Ne.hide(n.reconfigErr),r="/api/rescanwallet",a={assetID:t},o=ft().loading(this.body),e.next=7,S(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(ft().checkResponse(s)){e.next=17;break}return Ne.showFormError(n.reconfigErr,s.msg),e.abrupt("return");case 17:this.assetUpdated(t,n.reconfigForm,ke("RESCAN_STARTED"));case 18:case"end":return e.stop()}}),e,this)}))),function(e){return E.apply(this,arguments)})},{key:"showConfirmForce",value:function(){Ne.hide(this.page.confirmForceErr),this.showForm(this.page.confirmForce)}},{key:"showRecoverWallet",value:function(){Ne.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,S("/api/openwallet",n);case 3:if(r=e.sent,ft().checkResponse(r)){e.next=7;break}return console.error("openwallet error",r),e.abrupt("return");case 7:this.assetUpdated(t,void 0,ke("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,Ne.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=ft().assets[t],s=ft().currentWalletDefinition(t),i=o.token?[o.token.definition]:o.info?o.info.availablewallets:[],c=null===(r=ft().extensionWallet(t))||void 0===r?void 0:r.disableWalletType,i.length>1&&!c){Ne.empty(a.changeWalletTypeSelect),Ne.show(a.showChangeType,a.changeTypeShowIcon),a.changeTypeMsg.textContent=ke("CHANGE_WALLET_TYPE"),l=Zr(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=Zr(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=ft().walletMap[t],Ne.setVis(4&g.traits,a.downloadLogs),Ne.setVis(32&g.traits,a.recoverWallet),Ne.setVis(256&g.traits,a.exportWallet),Ne.setVis(1&g.traits,a.rescanWallet),Ne.setVis(1024&g.traits&&!g.disabled,a.managePeers),Ne.setVis(8192&g.traits&&!g.disabled,a.unapproveTokenAllowance),Ne.setVis(9509&g.traits,a.otherActionsLabel),g.disabled?Ne.show(a.enableWallet):Ne.show(a.disableWallet),this.showOrHideRecoverySupportMsg(g,s.seeded),a.recfgAssetLogo.src=Ne.logoPath(o.symbol),a.recfgAssetName.textContent=o.name,null!=n&&n.skipAnimation||this.showForm(a.reconfigForm),y=ft().loading(a.reconfigForm),e.next=26,S("/api/walletsettings",{assetID:t});case 26:if(b=e.sent,y(),ft().checkResponse(b)){e.next=31;break}return Ne.showFormError(a.reconfigErr,b.msg),e.abrupt("return");case 31:x=ft().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=ke("WALLET_RECOVERY_SUPPORT_MSG",{walletSymbol:t.toLocaleUpperCase()}),Ne.show(n.reconfigSupportMsg),n.submitReconfig.setAttribute("disabled",""),void n.submitReconfig.classList.add("grey");n.submitReconfig.removeAttribute("disabled"),n.submitReconfig.classList.remove("grey"),Ne.empty(n.reconfigSupportMsg),Ne.hide(n.reconfigSupportMsg)}},{key:"changeWalletType",value:function(){var e=this.page.changeWalletTypeSelect.value||"",t=ft().walletDefinition(this.selectedAssetID,e);this.reconfigForm.update(this.selectedAssetID,t.configopts||[],!1);var n=ft().walletMap[this.selectedAssetID],r=ft().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){Ne.hide(this.walletCfgGuide),""!==e&&(this.walletCfgGuide.href=e,Ne.show(this.walletCfgGuide))}},{key:"updateDisplayedReconfigFields",value:function(e){var t,n=null===(t=ft().extensionWallet(this.selectedAssetID))||void 0===t?void 0:t.disablePassword;e.seeded||"token"===e.type||n?(Ne.hide(this.page.showChangePW,this.reconfigForm.fileSelector),this.changeWalletPW=!1,this.setPWSettingViz(!1)):Ne.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=ft().assets[t],o=a.wallet,s=a.unitInfo,i=a.symbol,c=a.token,Ne.hide(n.toggleSubtract),n.subtractCheckBox.checked=!1,(l=0!=(64&o.traits))&&Ne.show(n.toggleSubtract),Ne.hide(n.sendErr,n.maxSendDisplay,n.sendTokenMsgBox),n.sendAddr.classList.remove("border-danger","border-success"),n.sendAddr.value="",n.sendAmt.value="",u=ft().fiatRatesMap[t],Ne.showFiatValue(n.sendValue,0,u,s),n.walletBal.textContent=Ne.formatFullPrecision(o.balance.available,s),n.sendLogo.src=Ne.logoPath(i),n.sendName.textContent=s.conventional.unit,c&&(d=ft().assets[c.parentID],n.sendTokenParentLogo.src=Ne.logoPath(d.symbol),n.sendTokenParentName.textContent=d.name,Ne.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=ft().loading(this.body),e.next=22,S("/api/txfee",h);case 22:v=e.sent,p(),ft().checkResponse(v)&&(m=o.balance.available,c||(m-=v.txfee)<0&&(m=0),this.maxSend=m,n.maxSend.textContent=Ne.formatFullPrecision(m,s),Ne.showFiatValue(n.maxSendFiat,m,u,s),c?(g=ft().assets[c.parentID].unitInfo,n.maxSendFee.textContent=Ne.formatFullPrecision(v.txfee,g)+" "+g.conventional.unit,Ne.showFiatValue(n.maxSendFeeFiat,v.txfee,ft().fiatRatesMap[c.parentID],g)):(n.maxSendFee.textContent=Ne.formatFullPrecision(v.txfee,s),Ne.showFiatValue(n.maxSendFeeFiat,v.txfee,u,s)),Ne.show(n.maxSendDisplay));case 25:Ne.showFiatValue(n.sendValue,0,u,s),n.walletBal.textContent=Ne.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:(C=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=ft().loading(this.body),e.next=3,S("/api/connectwallet",{assetID:t});case 3:r=e.sent,n(),ft().checkResponse(r)||(a=ft().assets[t].symbol,(o=this.page).errorModalMsg.textContent=ke("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 C.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=ft().assets[this.selectedAssetID],r=n.id,a=n.unitInfo,o=n.wallet,s=ft().fiatRatesMap[r],0==(64&o.traits)?(t.sendAmt.value=String(this.maxSend/a.conventional.conversionFactor),Ne.showFiatValue(t.sendValue,this.maxSend,s,a),t.subtractCheckBox.checked=!1):(i=o.balance.available,t.sendAmt.value=String(i/a.conventional.conversionFactor),Ne.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=ft().unitInfo(a).conventional.conversionFactor,i=r.vSendPw.value||"",r.vSendPw.value="",""!==i){e.next=9;break}return Ne.showFormError(r.vSendErr,ke(R)),e.abrupt("return");case 9:return c={assetID:a,address:r.sendAddr.value,subtract:o,value:Math.round(tt(r.sendAmt.value)*s),pw:i},l=ft().loading(r.vSendForm),e.next=13,S("/api/send",c);case 13:if(u=e.sent,l(),ft().checkResponse(u)){e.next=18;break}return Ne.showFormError(r.vSendErr,u.msg),e.abrupt("return");case 18:d=ft().assets[a].name,this.assetUpdated(a,r.vSendForm,ke("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,Ne.hide(n.reconfigErr),a=ft().currentWalletDefinition(r).type,Ne.isHidden(n.changeWalletType)||(a=n.changeWalletTypeSelect.value||""),o=ft().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(),ft().checkResponse(i)){e.next=16;break}return Ne.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 ft().loadPage(this.data.goBack),e.abrupt("return");case 19:this.assetUpdated(r,n.reconfigForm,ke("RECONFIG_SUCCESS")),this.updateTicketBuyer(r),ft().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=ft().loading(n.newWalletForm),e.next=4,S("/api/closewallet",{assetID:t});case 4:if(a=e.sent,r(),ft().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,Ne.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=ft().loading(t.forms),e.next=6,S("/api/restorewalletinfo",n);case 6:a=e.sent,r(),ft().checkResponse(a)?(t.exportWalletPW.value="",this.displayRestoreWalletInfo(a.restorationinfo)):Ne.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,Ne.empty(n.restoreInfoCardsList),r=Zr(t);try{for(r.s();!(a=r.n()).done;)o=a.value,s=this.restoreInfoCard.cloneNode(!0),(i=Ne.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,Ne.hide(t.recoverWalletErr),n={assetID:this.selectedAssetID},r="/api/recoverwallet",a=ft().loading(t.forms),e.next=7,S(r,n);case 7:o=e.sent,a(),o.code===A.activeOrdersErr?(this.forceUrl=r,this.forceReq=n,this.showConfirmForce()):ft().checkResponse(o)?this.closePopups():Ne.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=ft().loading(t.forms),e.next=5,S(this.forceUrl,this.forceReq);case 5:r=e.sent,n(),ft().checkResponse(r)?this.closePopups():Ne.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=ft().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&&Ne.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(ft().walletMap[n.assetID].synced){var a=ft().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),Ne.unbind(document,"keyup",this.keyup)}}]),ve}(lt);function pa(e,t){return e.length<=t?e:"".concat(e.substring(0,t/2),"...").concat(e.substring(e.length-t/2))}function fa(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 va="order",ma="match",ga="bondpost",ya="conn";function ba(){return"desktop_notifications-".concat(window.location.host)}var xa,ka=(h(ca={},va,"BROWSER_NTFN_ORDERS"),h(ca,ma,"BROWSER_NTFN_MATCHES"),h(ca,ga,"BROWSER_NTFN_BONDS"),h(ca,ya,"BROWSER_NTFN_CONNECTIONS"),ca),wa=(h(la={},va,!0),h(la,ma,!0),h(la,ga,!0),h(la,ya,!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(ke(ee)),t.next=10;break;case 6:if(e.ntfnPermissionDenied()){t.next=10;break}return t.next=9,Notification.requestPermission();case 9:e.sendDesktopNotification(ke(ee));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}()),Ca=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(ke(ee));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(!Sa()){e.next=5;break}return e.next=3,window.sendOSNotification(t,n);case 3:e.next=11;break;case 5:if(!Fa()){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 Sa(){return void 0!==window.isWebview}function Fa(){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 Ta=Sa()||Fa()?Ca:wa;function Da(){return(Da=s(f().mark((function e(t){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(xa.browserNtfnEnabled&&xa[t.type]){e.next=2;break}return e.abrupt("return");case 2:return e.next=4,Ta.sendDesktopNotification(t.subject,Ba(t.details));case 4:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function Ia(){var e;if(void 0!==xa)return xa;var t=ba();return xa=null!==(e=k.fetchLocal(t))&&void 0!==e?e:{}}var Aa=/\{\{\{([^|]+)\|([^}]+)\}\}\}/g,Ra=/\{\{\{order\|([^}]+)\}\}\}/g;function Ea(e,t){for(var n=t.replace(Ra,(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(Aa,(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),Xn(t,r),r.outerHTML})),r=Ne.noderize(n).body;r.firstChild;)e.appendChild(r.firstChild)}function Ba(e){return e.replace(Aa,(function(e,t,n){return n.slice(0,8)}))}var Pa=["bonds"];var La=function(e){g(A,e);var t,n,r,a,o,c,l,u,p,m,x,w,C,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=Ne.idDescendants(e);t.forms=Ne.applySelector(n.forms,":scope > form"),t.fiatRateSources=Ne.applySelector(n.fiatRateSources,"input[type=checkbox]"),n.darkMode.checked="1"===k.fetchLocal(k.darkModeLK),Ne.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),Ne.bind(n.showPokes,"click",(function(){var e=n.showPokes.checked||!1;k.storeLocal(k.popupsLK,e?"1":"0"),ft().showPopups=e})),n.commitHash.textContent=ft().commitHash.substring(0,7),Ne.bind(n.addADex,"click",(function(){t.dexAddrForm.refresh(),t.showForm(n.dexAddrForm)})),t.fiatRateSources.forEach((function(e){Ne.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,S("/api/toggleratesource",{disable:!e.checked,source:e.value});case 2:return n=t.sent,ft().checkResponse(n)||(e.checked=!e.checked),t.next=6,ft().fetchUser();case 6:case"end":return t.stop()}}),t)}))))})),t.regAssetForm=new Er(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!==pt){e.next=5;break}return e.next=3,ft().fetchUser();case 3:return window.location.reload(),e.abrupt("return");case 5:if(o=ft().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 Rr(n.confirmRegForm,(function(){t.registerDEXSuccess()}),(function(){t.animateRegAsset(n.confirmRegForm)})),t.newWalletForm=new Dr(n.newWalletForm,(function(e){return t.newWalletCreated(e,t.confirmRegisterForm.tier)}),(function(){return t.animateRegAsset(n.newWalletForm)})),t.walletWaitForm=new Br(n.walletWait,(function(){t.animateConfirmForm(n.walletWait)}),(function(){t.animateRegAsset(n.walletWait)})),t.dexAddrForm=new Lr(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)}}()),Ne.bind(n.importAccount,"click",(function(){return t.prepareAccountImport(n.authorizeAccountImportForm)})),Gr(n.authorizeAccountImportForm,n.authorizeImportAccountConfirm,(function(){return t.importAccount()})),Ne.bind(n.changeAppPW,"click",(function(){return t.showForm(n.changeAppPWForm)})),Gr(n.changeAppPWForm,n.submitNewPW,(function(){return t.changeAppPW()})),t.appPassResetForm=new Nr(n.resetAppPWForm,s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,ft().loadPage("login");case 2:Ne.hide(n.forms);case 3:case"end":return e.stop()}}),e)})))),Ne.bind(n.resetAppPW,"click",(function(){t.appPassResetForm.refresh(),t.showForm(n.resetAppPWForm),t.appPassResetForm.focus()})),Ne.bind(n.accountFile,"change",(function(){return t.onAccountFileChange()})),Ne.bind(n.removeAccount,"click",(function(){return t.clearAccountFile()})),Ne.bind(n.addAccount,"click",(function(){return n.accountFile.click()})),Ne.bind(n.exportSeed,"click",(function(){Ne.hide(n.exportSeedErr),t.showForm(n.exportSeedAuth)})),Gr(n.exportSeedAuth,n.exportSeedSubmit,(function(){return t.submitExportSeedReq()})),Ne.bind(n.gameCodeLink,"click",(function(){return t.showForm(n.gameCodeForm)})),Ne.bind(n.gameCodeSubmit,"click",(function(){return t.submitGameCode()}));var r=function(){Ne.hide(n.forms),n.exportSeedPW.value="",n.legacySeed.textContent="",n.mnemonic.textContent=""};return Ne.bind(n.forms,"mousedown",(function(e){Ne.mouseInElement(e,t.currentForm)||r()})),t.keyup=function(e){"Escape"===e.key&&r()},Ne.bind(document,"keyup",t.keyup),n.forms.querySelectorAll(".form-closer").forEach((function(e){Ne.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){Ia(),xa[e]=t,k.storeLocal(ba(),xa)}(n,t.checked)}},{key:"getBrowserNtfnSettings",value:function(){return Ia()}},{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=ka,(a=t.browserNtfnCheckboxTemplate).removeAttribute("id"),o=t.browserNtfnCheckboxContainer,Ne.empty(t.browserNtfnCheckboxContainer),Object.keys(r).forEach((function(e){var t=a.cloneNode(!0),s=n[e],i=Ne.tmplElement(t,"checkbox");Ne.tmplElement(t,"label").textContent=ke(r[e]),i.setAttribute("name",e),s&&i.setAttribute("checked","checked"),o.appendChild(t),Ne.bind(i,"click",c.updateNtfnSetting)})),i=t.browserNtfnEnabled,Ne.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(!Ta.ntfnPermissionDenied()){e.next=2;break}return e.abrupt("return");case 2:if(!(n=t.target).checked){e.next=7;break}return e.next=6,Ta.requestNtfnPermission();case 6:n.checked=!Ta.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)}}()),Ne.bind(i,"change",(function(e){var n=e.target,r=Ta.ntfnPermissionDenied();Ne.setVis(n.checked,t.browserNtfnCheckboxContainer),Ne.setVis(r,t.browserNtfnBlockedMsg),n.disabled=r})),i.checked=Ta.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){jr(this.currentForm,e),this.currentForm=e}},{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=ft().loading(n),e.next=3,S("/api/bondsfeebuffer",{assetID:t});case 3:if(a=e.sent,r(),ft().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:"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,ft().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,Ne.show(t.removeAccount),Ne.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=ke(j),Ne.hide(e.removeAccount),Ne.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,Ne.show(t.importAccountErr),e.abrupt("return");case 19:if(void 0!==a){e.next=22;break}return Ne.showFormError(t.importAccountErr,ke("ACCT_UNDEFINED")),e.abrupt("return");case 22:return s=(o=a).bonds,i=void 0===s?[]:s,c=fa(o,Pa),l={account:c,bonds:i},u=ft().loading(this.body),e.next=27,S("/api/importaccount",l);case 27:if(d=e.sent,u(),ft().checkResponse(d)){e.next=32;break}return Ne.showFormError(t.importAccountErr,d.msg),e.abrupt("return");case 32:return e.next=34,ft().fetchUser();case 34:Ne.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=ft().loading(this.body),e.next=5,S("/api/exportseed",{pass:n});case 5:if(a=e.sent,r(),ft().checkResponse(a)){e.next=10;break}return Ne.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 Ne.hide(e)})),t.style.right="10000px",Ne.show(n.forms,t),r=(n.forms.offsetWidth+t.offsetWidth)/2,e.next=8,Ne.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,Ne.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 Ne.showFormError(t.changePWErrMsg,ke("NO_APP_PASS_ERROR_MSG")),n(),e.abrupt("return");case 7:if(t.newAppPW.value===t.confirmNewPW.value){e.next=11;break}return Ne.showFormError(t.changePWErrMsg,ke(N)),n(),e.abrupt("return");case 11:return r=ft().loading(t.changeAppPW),a={appPW:t.appPW.value,newAppPW:t.newAppPW.value},n(),e.next=16,S("/api/changeapppass",a);case 16:if(o=e.sent,r(),ft().checkResponse(o)){e.next=21;break}return Ne.showFormError(t.changePWErrMsg,o.msg),e.abrupt("return");case 21:Ne.hide(t.forms);case 22:case"end":return e.stop()}}),e,this)}))),function(){return a.apply(this,arguments)})},{key:"unload",value:function(){Ne.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:Ne.hide(t),n=this.page.regAssetForm,this.currentForm=n,this.regAssetForm.animate(),Ne.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,Ne.hide(t),Ne.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,Ne.hide(t.gameCodeErr),n=t.gameCodeInput.value){e.next=7;break}return t.gameCodeErr.textContent=ke("NO_CODE_PROVIDED"),Ne.show(t.gameCodeErr),e.abrupt("return");case 7:return r=t.gameCodeMsg.value||"",a=ft().loading(t.gameCodeForm),e.next=11,S("/api/redeemgamecode",{code:n,msg:r});case 11:if(o=e.sent,a(),ft().checkResponse(o)){e.next=17;break}return t.gameCodeErr.textContent=ke(H,{msg:o.msg}),Ne.show(t.gameCodeErr),e.abrupt("return");case 17:Ne.show(t.gameCodeSuccess),t.gameRedeemTx.dataset.explorerCoin=o.coinString,Xn(42,t.gameRedeemTx),t.gameRedeemTx.textContent=o.coinString,s=ft().unitInfo(42),t.gameRedeemValue.textContent=Ne.formatCoinValue(o.win,s);case 24:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})}]),A}(lt);function Oa(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 qa(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);Na(t.route,t.payload,n.handlers)},s.onclose=function(e){window.log("ws","onclose"),clearTimeout(i),s=n.connection=null,Na("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()),Na("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 qa(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)?qa(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),Na("error",e,n.handlers)}}}()}}]),e}());function Ua(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 _a(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 Ha(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=ft().exchanges[e.dex.host],n=t.markets[e.cfg.name];if(n.spot){var r,a=ja(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=ft().fiatRatesMap[n.baseid];l?(o.tmpl.volume.textContent=Ne.formatFourSigFigs(n.spot.vol24/i*l),o.tmpl.volUnit.textContent="USD"):(o.tmpl.volume.textContent=Ne.formatFourSigFigs(n.spot.vol24/i),o.tmpl.volUnit.textContent=c),vo(o.tmpl,t,n)}}catch(e){a.e(e)}finally{a.f()}this.page.obPrice.textContent=Ne.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"),Ne.setVis(n.spot.change24>=0,this.page.obUp),Ne.setVis(n.spot.change24<0,this.page.obDown)}}}},{key:"setMarketDetails",value:function(){if(this.market){var e,t=ja(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=Ne.logoPath(a.symbol),n.tmpl.quoteIcon.src=Ne.logoPath(o.symbol),Ne.empty(n.tmpl.baseSymbol,n.tmpl.quoteSymbol),n.tmpl.baseSymbol.appendChild(Ne.symbolize(a,!0)),n.tmpl.quoteSymbol.appendChild(Ne.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[to];if(!a){if(this.candleDur!==to)return void this.requestCandles(to);var o,s=ja(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=ja(this.stats);try{for(v.s();!(d=v.n()).done;){var m=d.value;m.tmpl.high.textContent=e>0?Ne.formatFourSigFigs(ft().conventionalRate(h,p,e,f)):"-",m.tmpl.low.textContent=t>0?Ne.formatFourSigFigs(ft().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:ke("NOT_SUPPORTED",{asset:(o?c.symbol:i.symbol).toUpperCase()})};var l=o.token?null===(e=ft().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=ft().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=ke(P,{asset:s.symbol.toUpperCase(),version:c.version+""})):d=ke(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()?(Ne.show(e.priceBox,e.tifBox,e.qtyBox,e.maxBox),Ne.hide(e.mktBuyBox),this.previewQuoteAmt(!0)):(Ne.hide(e.tifBox,e.maxBox,e.priceBox),this.isSell()?(Ne.hide(e.mktBuyBox),Ne.show(e.qtyBox),this.previewQuoteAmt(!0)):(Ne.show(e.mktBuyBox),Ne.hide(e.qtyBox),this.previewQuoteAmt(!1))),this.updateOrderBttnState()}},{key:"resolveOrderFormVisibility",value:(q=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===dt.Approved&&r===dt.Approved){e.next=7;break}return e.abrupt("return",!1);case 7:if(a=p.market,o=a.base,s=a.quote,o&&ft().assets[o.id].wallet&&s&&ft().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=Ne,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,Ne.setVis(a>0||o>0,t.reputationAndTradingTierBox)),(i=ft().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)),Ne.setVis(this.mmRunning,t.mmRunning),this.mmRunning&&Ne.hide(t.orderForm,t.orderTypeBttns);case 14:case"end":return e.stop()}}),e,this)}))),function(){return q.apply(this,arguments)})},{key:"setLoaderMsgVisibility",value:function(){var e=this.page,t=this.assetsAreSupported(),n=t.isSupported,r=t.text;n?Ne.hide(e.loaderMsg):(e.loaderMsg.textContent=r,Ne.show(e.loaderMsg),Ne.hide(e.notRegistered),Ne.hide(e.noWallet))}},{key:"showTokenApprovalForm",value:(R=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.forms.show(this.page.approveTokenForm);case 3:case"end":return e.stop()}}),e,this)}))),function(e){return R.apply(this,arguments)})},{key:"tokenAssetApprovalStatuses",value:function(){var e=this.market,t=e.base,n=e.quote,r=dt.Approved,a=dt.Approved;if(null!=t&&t.token){var o,s=ft().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=ft().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===dt.Approved&&r===dt.Approved)return Ne.hide(e.tokenApproval),e.sellBttn.removeAttribute("disabled"),void e.buyBttn.removeAttribute("disabled");n!==dt.Approved&&r===dt.Approved&&(e.sellBttn.setAttribute("disabled","disabled"),e.buyBttn.removeAttribute("disabled"),this.setBuy(),Ne.show(e.approvalRequiredSell),Ne.hide(e.approvalRequiredBuy,e.approvalRequiredBoth)),n===dt.Approved&&r!==dt.Approved&&(e.buyBttn.setAttribute("disabled","disabled"),e.sellBttn.removeAttribute("disabled"),this.setSell(),Ne.show(e.approvalRequiredBuy),Ne.hide(e.approvalRequiredSell,e.approvalRequiredBoth)),n!==dt.Approved&&r!==dt.Approved&&(Ne.show(e.approvalRequiredBoth),Ne.hide(e.approvalRequiredSell,e.approvalRequiredBuy)),Ne.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(),Ne.setVis(n===dt.NotApproved,e.approveBaseBttn),Ne.setVis(r===dt.NotApproved,e.approveQuoteBttn),Ne.setVis(n===dt.Pending,e.approvalPendingBase),Ne.setVis(r===dt.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(ke("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(ke("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===ut.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(Ne.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=ke("SET_BUTTON_SELL",{asset:Ne.shortSymbol(this.market.baseCfg.unitInfo.conventional.unit)}):this.page.submitBttn.textContent=ke("SET_BUTTON_BUY",{asset:Ne.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=ft().assets[this.market.base.id].wallet,i=ft().assets[e.quote.id].wallet;if(s&&i)if(n<=0||n-1&&(o.classList.add("hover"),this.hovers.push(o))}t.hoverPrice.textContent=Ne.formatCoinValue(e.rate),t.hoverVolume.textContent=Ne.formatCoinValue(e.depth),t.hoverVolume.style.color=e.dotColor}else Ne.hide(t.depthLegend)}},{key:"reportDepthZoom",value:function(e){k.storeLocal(k.depthZoomLK,e)}},{key:"reportMouseCandle",value:function(e){var t=this.page;e?(Ne.show(t.candlesLegend),t.candleStart.textContent=Ne.formatCoinValue(e.startRate/this.market.rateConversionFactor),t.candleEnd.textContent=Ne.formatCoinValue(e.endRate/this.market.rateConversionFactor),t.candleHigh.textContent=Ne.formatCoinValue(e.highRate/this.market.rateConversionFactor),t.candleLow.textContent=Ne.formatCoinValue(e.lowRate/this.market.rateConversionFactor),t.candleVol.textContent=Ne.formatCoinValue(e.matchVolume,this.market.baseUnitInfo)):Ne.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:uo(t.value||"",o),rate:uo(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=ft().assets[n.quote].unitInfo.conventional.unit,o=n.qty*n.rate/Nt,s=Ne.formatCoinValue(o,this.market.quoteUnitInfo);t.orderPreview.textContent=ke("ORDER_PREVIEW",{total:s,asset:a}),this.isSell()?this.preSell():this.preBuy()}}},{key:"preSell",value:function(){var e=this,t=this.market,n=ft().assets[t.base.id].wallet;return n.balance.available0){if(a.token){var i=ft().assets[a.token.parentID],c=i.wallet.balance.available,l=i.unitInfo;return void(c0)return}return Ne.show(t.maxZeroNoBal),void(t.maxZeroNoBalTicker.textContent=a.unitInfo.conventional.unit)}Ne.show(t.maxAboveZero),t.maxFromAmt.textContent=Ne.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 Ne.show(t.orderErr),t.orderErr.textContent=ke("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(),Ne.empty(this.page.buyRows),void Ne.empty(this.page.sellRows);Ne.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/Nt:e.buys[0].msgRate/Nt:e.sells&&e.sells.length?e.sells[0].msgRate/Nt:null}},{key:"setMarketBuyOrderEstimate",value:function(){var e=this.market,t=e.cfg.lotsize,n=ft().user.exchanges[e.dex.host].markets[e.sid].buybuffer,r=this.midGapConventional();r&&(this.page.minMktBuy.textContent=Ne.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,ft().orders(t,n).length)}},{key:"loadUserOrders",value:(I=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=ft().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,S("/api/orders",c);case 10:l=e.sent,u=l.orders||[],d=ja(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 I.apply(this,arguments)})},{key:"refreshActiveOrders",value:function(){var e=ft().orders(this.market.dex.host,lo(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];Ne.empty(o.userOrders),Ne.setVis(null===(t=h)||void 0===t?void 0:t.length,o.userOrders),Ne.setVis(!(null!==(n=h)&&void 0!==n&&n.length),o.userNoOrders);var v,m=!1,g=ja(h);try{var y=function(){var e=v.value,t=o.userOrderTmpl.cloneNode(!0);o.userOrders.appendChild(t);var n=Ne.parseTemplate(t),r=Ne.parseTemplate(n.header),u=Ne.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&&_t(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=Wt(h),u.side.classList.add(h.sell?"sellcolor":"buycolor"),r.side.classList.add(h.sell?"sellcolor":"buycolor"),u.qty.textContent=e.header.qty.textContent=Ne.formatCoinValue(h.qty,i.baseUnitInfo),d=h.type===Tt?a.marketOrderRateString(h,i):Ne.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=function(e){switch(e){case 1:return ke(X);case Dt:return ke(K);default:return ke("CANCEL_ORDER")}}(h.type),a.updateMetaOrder(e),Ne.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?(Yt(h)&&(Ne.show(u.cancelBttn),za(u.cancelBttn,"click",(function(e){y(e)}))),za(u.accelerateBttn,"click",(function(e){b(e)})),ft().canAccelerateOrder(h)&&Ne.show(u.accelerateBttn),u.link.href="order/".concat(p),ft().bindInternalNavigation(t)):(Ne.hide(u.accelerateBttn),Ne.hide(u.cancelBttn),Ne.hide(u.link)),Ne.bind(n.header,"click",(function(){if(Ne.isDisplayed(n.details))return Ne.hide(n.details),r.expander.classList.add("ico-arrowdown"),void r.expander.classList.remove("ico-arrowup");Ne.show(n.details),r.expander.classList.remove("ico-arrowdown"),r.expander.classList.add("ico-arrowup"),g&&g.remove()})),Ne.bind(n.header,"mouseenter",(function(){if(!Ne.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=Ne.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),Ne.show(r),Ne.bind(r,"click",(function(e){n(e)}))};Yt(i)&&c(u.cancelBttn,(function(e){y(e)})),ft().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"),Ne.mouseInElement(r,e)||Ne.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)}})),ft().bindTooltips(t)};for(g.s();!(v=g.n()).done;)y()}catch(e){g.e(e)}finally{g.f()}Ne.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 ke(K);var r=Ne.formatRateFullPrecision(Xt(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<=Rt||_t(r)?t.activeLight.classList.add("active"):t.activeLight.classList.remove("active"),n.status.textContent=t.status.textContent=jt(r),n.age.textContent=Ne.timeSince(r.submitTime),n.filled.textContent="".concat((Ht(r)/r.qty*100).toFixed(1),"%"),n.settled.textContent="".concat((zt(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(ft().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(ft().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(ft().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:"showToggleWalletStatus",value:function(e){var t=this.page;this.openAsset=e,Ne.hide(t.toggleWalletStatusErr,t.walletStatusDisable,t.disableWalletMsg),Ne.show(t.walletStatusEnable,t.enableWalletMsg),this.forms.show(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,Ne.hide(t.toggleWalletStatusErr),n={assetID:this.openAsset.id,disable:!1},r=ft().loading(t.toggleWalletStatusConfirm),e.next=7,S("/api/togglewalletstatus",n);case 7:if(a=e.sent,r(),ft().checkResponse(a)){e.next=13;break}return t.toggleWalletStatusErr.textContent=a.msg,Ne.show(t.toggleWalletStatusErr),e.abrupt("return");case 13:Ne.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=ft().assets[n.base],o=ft().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=ft().assets[i.token.parentID];e.src=Ne.logoPath(t.symbol)}else e.src=Ne.logoPath(i.symbol);break;case"to":if(s.token){var n=ft().assets[s.token.parentID];e.src=Ne.logoPath(n.symbol)}else e.src=Ne.logoPath(s.symbol)}},l=ja(Ne.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=ja(Ne.applySelector(t.vFeeSummary,"[data-icon]"));try{for(d.s();!(u=d.n()).done;)c(u.value)}catch(e){d.e(e)}finally{d.f()}Ne.hide(t.vPreorderErr),Ne.show(t.vPreorder),t.vBuySell.textContent=ke(r?"SELLING":"BUYING");var h=ke(r?B:E);if(t.vSideSubmit.textContent=h,t.vOrderHost.textContent=n.host,n.isLimit){Ne.show(t.verifyLimit),Ne.hide(t.verifyMarket);var p="Limit ".concat(h," Order");t.vOrderType.textContent=n.tifnow?p+" (immediate)":p,t.vRate.textContent=Ne.formatCoinValue(n.rate/this.market.rateConversionFactor),t.vQty.textContent=Ne.formatCoinValue(n.qty,a.unitInfo);var f=n.rate/Nt*n.qty;t.vTotal.textContent=Ne.formatCoinValue(f,o.unitInfo),this.showFiatValue(o.id,f,t.vFiatTotal)}else{Ne.hide(t.verifyLimit),Ne.show(t.verifyMarket),t.vOrderType.textContent="Market ".concat(h," Order");var v=n.sell?this.market.baseUnitInfo:this.market.quoteUnitInfo;t.vmFromTotal.textContent=Ne.formatCoinValue(n.qty,v),t.vmFromAsset.textContent=i.symbol.toUpperCase(),this.showFiatValue(i.id,n.qty,t.vmFromTotalFiat);var m=this.midGap();if(m){Ne.show(t.vMarketEstimate);var g=n.sell?n.qty*m:n.qty/m;t.vmToTotal.textContent=Ne.formatCoinValue(g,s.unitInfo),t.vmToAsset.textContent=s.symbol.toUpperCase(),this.showFiatValue(s.id,g,t.vmTotalFiat)}else Ne.hide(t.vMarketEstimate)}r?(t.vHeader.classList.add(eo),t.vHeader.classList.remove($a),t.vSubmit.classList.add(eo),t.vSubmit.classList.remove($a)):(t.vHeader.classList.add($a),t.vHeader.classList.remove(eo),t.vSubmit.classList.add($a),t.vSubmit.classList.remove(eo)),this.showVerifyForm(),a.wallet.open&&o.wallet.open?this.preOrder(n):(Ne.hide(t.vPreorder),this.unlockWalletsForEstimates())}},{key:"showFiatValue",value:function(e,t,n){if(n){var r=ft().fiatRatesMap[e];n.textContent=Ne.formatFiatConversion(t,r,ft().unitInfo(e)),r?Ne.show(n.parentElement):Ne.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,Ne.hide(t.vErr),this.forms.show(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=ft().loading(t.verifyForm),e.next=4,this.unlockMarketWallets();case 4:n(),Ne.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:(C=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,S("/api/openwallet",{assetID:t});case 2:if(n=e.sent,ft().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 C.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=Ne.formatCoinValue(e.estimate.realisticBestCase,x);var I=e.estimate.realisticWorstCase/T*100;r.vSwapFeesHighPct.textContent=w<=0?"":"(".concat(c(I),"%)"),r.vSwapFeesHigh.textContent=Ne.formatCoinValue(e.estimate.realisticWorstCase,x);var A=e.estimate.maxFees/T*100;r.vSwapFeesMaxPct.textContent=w<=0?"":"(".concat(c(A),"%)"),r.vSwapFeesMax.textContent=Ne.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=Ne.formatCoinValue(t.estimate.realisticBestCase,b);var L=t.estimate.realisticWorstCase/B*100;r.vRedeemFeesHighPct.textContent=k<=0?"":"(".concat(c(L),"%)"),r.vRedeemFeesHigh.textContent=Ne.formatCoinValue(t.estimate.realisticWorstCase,b),l&&u?(Ne.show(r.vFeeSummaryPct),Ne.hide(r.vFeeSummary),r.vFeeSummaryLow.textContent=c(D+P),r.vFeeSummaryHigh.textContent=c(I+L)):(Ne.hide(r.vFeeSummaryPct),Ne.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 Ne.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=ft().loading(t.cancelSubmit),e.next=7,S("/api/cancel",a);case 7:if(s=e.sent,o(),ft().checkResponse(s)){e.next=13;break}return t.cancelErr.textContent=s.msg,Ne.show(t.cancelErr),e.abrupt("return");case 13:Ne.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=Ut(n)?this.market.quote:this.market.base;r.cancelRemain.textContent=Ne.formatCoinValue(a,o.unitInfo),r.cancelUnit.textContent=o.symbol.toUpperCase(),Ne.hide(r.cancelErr),this.forms.show(r.cancelForm),this.cancelData={bttn:Ne.tmplElement(e,"cancelBttn"),order:n}}},{key:"showAccelerate",value:function(e){var t=ft().loading(this.main);this.accelerateOrderForm.refresh(e),t(),this.forms.show(this.page.accelerateForm)}},{key:"showCreate",value:function(e){var t=this.page;this.currentCreate=e,this.newWalletForm.setAsset(e.id),this.forms.show(t.newWalletForm)}},{key:"stepSubmit",value:function(){var e=this.page,t=this.market;if(Ne.hide(e.orderErr),this.validateOrder(this.parseOrder())){var n=ft().walletMap[t.base.id],r=ft().walletMap[t.quote.id];return n?r?void this.showVerify():(e.orderErr.textContent=ke(L,{asset:t.quote.symbol}),void Ne.show(e.orderErr)):(e.orderErr.textContent=ke(L,{asset:t.base.symbol}),void Ne.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.forms.show(this.page.deposit);case 2:case"end":return e.stop()}}),e,this)}))),function(e){return u.apply(this,arguments)})},{key:"showCustomProviderDialog",value:function(e){ft().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,ft().fetchUser();case 8:this.market.dex=ft().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=ft().exchanges[n].auth;e.parcelSizeLots.textContent=String(r.parcelsize),e.marketLimitBase.textContent=Ne.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=Ne.formatFourSigFigs(r.parcelsize*l/s.conventional.conversionFactor)}else e.marketLimitQuote.textContent="-";var u=Fn(i);e.tradingTier.textContent=String(u);var d=function(e){for(var t=ft().exchanges[e],n=t.auth,r=t.maxScore,a=t.markets,o=n.rep.score,s=Fn(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*Nt,o,this.midGapConventional()||0]}if(t&&t.rate)return[t.rate,t.rate/Nt,t.rate/a];var s=[ft().fiatRatesMap[n],ft().fiatRatesMap[r]],i=s[0],c=s[1];if(i&&c){var l=i/c,u=l*a;return[u,u/Nt,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===Tt&&0===n.status){var r=ft().order(e.orderID);r&&(t.details.rate.textContent=t.header.rate.textContent=this.marketOrderRateString(r,this.market))}(n.side===qt&&n.status===Pt||1===n.side&&n.status===Lt)&&this.updateReputation(),ft().canAccelerateOrder(t.ord)?Ne.show(t.details.accelerateBttn):Ne.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&&Ne.show(n.details.cancelBttn),t.filled===t.qty&&Ne.hide(n.details.cancelBttn),ft().canAccelerateOrder(t)?Ne.show(n.details.accelerateBttn):Ne.hide(n.details.accelerateBttn),this.updateMetaOrder(n),(a===At&&t.status===Rt||a===Rt&&t.status>Rt)&&(this.setDepthMarkers(),this.updateReputation(),this.mm.readBook())}},{key:"handleEpochNote",value:function(e){if(ft().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===Ft&&a.status===At&&i:var c=a.tif===It?ke(O):ke(M);o.status.textContent=s.status.textContent=c,a.status=a.tif===It?Et:Rt;break;case a.type===Tt&&a.status===At:o.status.textContent=s.status.textContent=ke(O),a.status=Et}}}}},{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(Ne.empty(e.recentMatchesLiveList),t){var n=this.recentMatchesSortCompare();t.sort(n);var r,a=ja(t);try{for(a.s();!(r=a.n()).done;){var o=r.value,s=e.recentMatchesTemplate.cloneNode(!0),i=Ne.parseTemplate(s);ft().bindTooltips(s),i.rate.textContent=Ne.formatCoinValue(o.rate/this.market.rateConversionFactor),i.qty.textContent=Ne.formatCoinValue(o.qty,this.market.baseUnitInfo),i.age.textContent=Ne.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===ut.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,Ne.hide(t.orderErr,t.vErr),n=this.currentOrder,r={order:po(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,S("/api/tradeasync",r);case 10:if(a=e.sent,t.vSubmit.classList.remove("d-hide"),t.vLoader.classList.add("d-hide"),ft().checkResponse(a)){e.next=17;break}return t.vErr.textContent=a.msg,Ne.show(t.vErr),e.abrupt("return");case 17:Ne.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,ft().fetchUser();case 2:if(t=e.sent){e.next=5;break}return e.abrupt("return");case 5:n=t.assets[this.currentCreate.id],Ne.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,ke(re));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=ft().assets[this.market.base.id].wallet;this.setOrderBttnEnabled(n<=r.balance.available,ke(ne))}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=uo(e.mktBuyField.value||"",this.market.quoteUnitInfo.conventional.conversionFactor),n=this.midGap();if(t>0){var r=ft().assets[this.market.quote.id].wallet;this.setOrderBttnEnabled(t<=r.balance.available,ke(te))}else this.setOrderBttnEnabled(!1,ke(re));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=Ne.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=uo(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;Ne.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?(Ne.show(n.expired),i.running&&ft().fetchBalance(o)):Ne.hide(n.expired)}else Ne.show(n.connect)}else Ne.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=Ne,e.next=3,ft().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=ft().assets[e.parentID],r=n.wallet.balance,a=n.unitInfo;null!==(t=e.parentBal)&&void 0!==t&&t.firstChild&&(e.parentBal.firstChild.textContent=Ne.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 co(e,t,n){return{host:e,base:t,quote:n}}function lo(e,t){return"".concat(e,"_").concat(t)}function uo(e,t){return e?Math.round(parseFloat(e)*t):0}function ho(e,t){e.classList.remove("selected"),t.classList.add("selected")}function po(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 vo(e,t,n){if(n.spot){e.price.textContent=Ne.formatFourSigFigs(ft().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 mo=[.5,1/4,3/4,1/8,5/8,3/8,7/8];function go(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 yo(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)?yo(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 yo(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),Ne.bind(a,"click",(function(){t.submitFilter(),s.forEach((function(e){return Ne.hide(e)}))})),e.querySelectorAll("input").forEach((function(t){Ne.bind(t,"change",(function(){!function(e,t){if(e.length!==t.length)return!1;var n,r=go(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}(xo(e),r[n])?Ne.show(a):Ne.hide(a)}))}))};return c(n.hostFilter,"hosts"),c(n.assetFilter,"assets"),c(n.statusFilter,"statuses"),Ne.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){Ne.bind(e,"click",(function(){Ne.hide(n.forms)}))})),Ne.bind(n.forms,"mousedown",(function(e){Ne.mouseInElement(e,t.currentForm)||Ne.hide(n.forms)})),Ne.bind(n.exportOrders,"click",(function(){t.exportOrders()})),n.showArchivedDateField.addEventListener("change",(function(){n.showArchivedDateField.checked?Ne.show(n.archivedDateField):Ne.hide(n.archivedDateField,n.deleteArchivedRecordsErr)})),Ne.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="",Ne.hide(e.deleteArchivedResult,e.deleteArchivedRecordsErr,e.deleteArchivedRecordsMsg,e.archivedRecordsLocation,e.archivedDateField),t.showForm(e.deleteArchivedRecordsForm)})),Ne.bind(n.deleteArchivedRecordsSubmit,"click",(function(){var e=0;n.showArchivedDateField.checked&&(e=Date.parse(n.olderThan.value||""),isNaN(e)||e<=0)?Ne.showFormError(n.deleteArchivedRecordsErr,ke("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,Ne.hide(n.deleteArchivedRecordsForm),t.style.right="10000px",Ne.show(n.forms,t),r=(n.forms.offsetWidth+t.offsetWidth)/2,e.next=8,Ne.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){Ne.empty(this.page.tableBody),this.appendOrders(e)}},{key:"appendOrders",value:function(e){var t,n=this.page.tableBody,r=go(e);try{for(r.s();!(t=r.n()).done;){var a=t.value,o=this.orderTmpl.cloneNode(!0),s=Ne.parseTemplate(o),i=void 0,c=void 0,l=void 0,u=void 0,d=void 0,h="",p=ft().exchanges[a.host]||void 0;if((ft().assets[a.baseID]||p.assets[a.baseID])&&(ft().assets[a.quoteID]||p.assets[a.quoteID])){var f=[ft().unitInfo(a.baseID,p),ft().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=Ne.formatCoinValue(a.qty,v),a.type===Ft&&(h=Ne.formatCoinValue(a.qty/Nt*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===Tt?d=Ne.formatCoinValue(a.qty,v):(d=Ne.formatCoinValue(a.qty/Nt*a.rate,m),h=Ne.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=Ne.logoPath(i),s.fromSymbol.textContent=l,s.toQty.textContent=h,s.toLogo.src=Ne.logoPath(c),s.toSymbol.textContent=u,s.type.textContent="".concat(Vt(a)," ").concat(Wt(a));var w=Ne.formatCoinValue(ft().conventionalRate(a.baseID,a.quoteID,a.rate,p));a.type===Tt&&(w=Gt(a)),s.rate.textContent=w,s.status.textContent=jt(a),s.filled.textContent="".concat((Ht(a)/a.qty*100).toFixed(1),"%"),s.settled.textContent="".concat((zt(a)/a.qty*100).toFixed(1),"%");var C=new Date(a.submitTime).toLocaleString();s.timeAgo.textContent="".concat(Ne.timeSince(a.submitTime)," ago"),s.time.textContent=C,Ne.tmplElement(o,"link").href="order/".concat(a.id),ft().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=xo(t.hostFilter),n.assets=xo(t.assetFilter).map((function(e){return parseInt(e)})),n.statuses=xo(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=ft().loading(this.main),e.next=3,S("/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=ft().loading(this.main),e.next=7,S("/api/deletearchivedrecords",o);case 7:if(i=e.sent,s(),ft().checkResponse(i)){e.next=11;break}return e.abrupt("return",Ne.showFormError(n.deleteArchivedRecordsErr,i.msg));case 11:i.archivedRecordsDeleted>0?(n.deleteArchivedRecordsMsg.textContent=ke("DELETE_ARCHIVED_RECORDS_RESULT",{nRecords:i.archivedRecordsDeleted}),(r||a)&&(n.archivedRecordsLocation.textContent=ke("ARCHIVED_RECORDS_PATH",{path:i.archivedRecordsPath}),Ne.show(n.archivedRecordsLocation)),this.submitFilter()):n.deleteArchivedRecordsMsg.textContent=ke("NO_ARCHIVED_RECORDS"),Ne.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,Ne.show(this.page.orderLoader),e.next=6,this.fetchOrders();case 6:t=e.sent,this.loading=!1,Ne.hide(this.page.orderLoader),this.appendOrders(t);case 10:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})}]),p}(lt);function xo(e){var t=[];return e.querySelectorAll("input").forEach((function(e){e.checked&&t.push(e.value)})),t}function ko(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 wo(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)?wo(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 wo(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);no.getTime())n.refundPending.textContent=ke("REFUND_IMMINENT");else{var s=o.toLocaleTimeString(Ne.languages(),{year:"numeric",month:"short",day:"numeric"});n.refundPending.textContent=ke("REFUND_WILL_HAPPEN_AFTER",{refundAfterTime:s})}Ne.hide(n.refundCoin),Ne.show(n.refundPending)}if(1!==t.status||t.revoked||t.refund)if(t.status!==Bt||t.revoked||t.refund)!function(e){return e.status<5&&e.side===Ot&&e.status>=Pt}(t)||t.revoked||t.refund?!function(e){return e.status<5&&e.side===Mt&&e.status>=Lt}(t)||t.revoked||t.refund?Ne.hide(n.makerSwapMsg,n.takerSwapMsg,n.makerRedeemMsg,n.takerRedeemMsg):(n.takerRedeemMsg.textContent=Fo(t.redeem),Ne.hide(n.makerSwapMsg,n.takerSwapMsg,n.makerRedeemMsg),Ne.show(n.takerRedeemMsg)):(n.makerRedeemMsg.textContent=Fo(t.redeem),Ne.hide(n.makerSwapMsg,n.takerSwapMsg,n.takerRedeemMsg),Ne.show(n.makerRedeemMsg));else{var i=Do(t);n.takerSwapMsg.textContent=Fo(i),Ne.hide(n.makerSwapMsg,n.makerRedeemMsg,n.takerRedeemMsg),Ne.show(n.takerSwapMsg)}else{var c=To(t);n.makerSwapMsg.textContent=Fo(c),Ne.hide(n.takerSwapMsg,n.makerRedeemMsg,n.takerRedeemMsg),Ne.show(n.makerSwapMsg)}if(t.revoked){Ne.setVis(To(t),n.makerSwap),Ne.setVis(Do(t),n.takerSwap);var l=new Date(t.stamp+Co),u=Date.now()>l.getTime();Ne.setVis(Io(t)||Do(t)&&t.active&&!t.refund&&!u,n.makerRedeem),Ne.setVis(Ao(t)||Io(t)&&t.active&&!t.refund,n.takerRedeem);var d=Boolean(Do(t));t.side===Ot&&(d=Boolean(To(t)),Do(t)&&(d=d&&u)),Ne.setVis(t.refund||t.active&&!t.redeem&&!t.counterRedeem&&d,n.refund)}else Ne.setVis(To(t)||t.active,n.makerSwap),Ne.setVis(Do(t)||t.active,n.takerSwap),Ne.setVis(Io(t)||t.active,n.makerRedeem),Ne.setVis(Ao(t)||t.active,n.takerRedeem),Ne.setVis(t.refund,n.refund)}}},{key:"addNewMatchCard",value:function(e){var t=this.page,n=t.matchCardTmpl.cloneNode(!0);ft().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=Ut(e)?ft().assets[e.quoteID]:ft().assets[e.baseID];t.cancelRemain.textContent=Ne.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,Ne.hide(n.cancelForm,n.accelerateForm),t.style.right="10000px",Ne.show(n.forms,t),r=(n.forms.offsetWidth+t.offsetWidth)/2,e.next=8,Ne.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=ft().loading(t.cancelForm),e.next=6,S("/api/cancel",r);case 6:if(o=e.sent,a(),ft().checkResponse(o)){e.next=10;break}return e.abrupt("return");case 10:t.status.textContent=ke(q),Ne.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;Ne.setVis(ft().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=ft().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>Rt&&Ne.hide(r),t.status.textContent=jt(n);var a,o=ko(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=ko(Ne.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}(lt);function Fo(e){return e.confs&&0!==e.confs.required?"".concat(e.confs.count," / ").concat(e.confs.required," ").concat(ke("CONFIRMATIONS")):""}function To(e){return e.side===Ot?e.swap:e.counterSwap}function Do(e){return e.side===Ot?e.counterSwap:e.swap}function Io(e){return e.side===Ot?e.redeem:e.counterRedeem}function Ao(e){return e.side===Ot?e.counterRedeem:e.redeem}function Ro(){return Ro="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}},Ro.apply(this,arguments)}function Eo(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 Bo(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)?Bo(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 Bo(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=Ne.parseTemplate(c),u=function(){t.cexConfigForm.setCEX(r),t.forms.show(n.cexConfigForm)};Ne.bind(l.configureBttn,"click",u),Ne.bind(l.reconfigBttn,"click",u),Ne.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(sr);o=768;if(e!==this.twoColumn){this.twoColumn=e,this.clearBotBoxes();var t,n=Eo(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:(u=s(f().mark((function e(){var t,n,a,o,s,i,c,l,u=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=this.page,n=ft().mmStatus,a=n.bots.map((function(e){return e.config})),ft().registerNoteFeeder({runstats:function(e){u.handleRunStatsNote(e)},runevent:function(e){var t=u.bots[pr(e.host,e.baseID,e.quoteID)];if(t)return t.handleRunStats()},epochreport:function(e){var t=u.bots[pr(e.host,e.baseID,e.quoteID)];t&&t.handleEpochReportNote(e)},cexproblems:function(e){var t=u.bots[pr(e.host,e.baseID,e.quoteID)];t&&t.handleCexProblemsNote(e)},cexnote:function(e){u.handleCEXNote(e)}}),o=!a||0===a.length,Ne.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=Eo(s);try{for(i.s();!(c=i.n()).done;)l=c.value,this.addBot(l)}catch(e){i.e(e)}finally{i.f()}case 12:case"end":return e.stop()}}),e,this)}))),function(){return u.apply(this,arguments)})},{key:"handleCEXNote",value:(l=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 l.apply(this,arguments)})},{key:"handleCEXBalanceUpdate",value:(c=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 c.apply(this,arguments)})},{key:"handleRunStatsNote",value:(o=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[pr(a,n,r)])){e.next=4;break}return e.abrupt("return",o.handleRunStats());case 4:this.addBot(ft().botStatus(a,n,r));case 5:case"end":return e.stop()}}),e,this)}))),function(e){return o.apply(this,arguments)})},{key:"unload",value:function(){Ne.unbind(document,"keyup",this.keyup)}},{key:"addBot",value:function(e){var t,n=this.page,r=this.bots,a=this.sortedBots,o=e.config,s=o.baseID,i=o.quoteID,c=o.host,l=[ft().assets[s].symbol,ft().assets[i].symbol],u=l[1],d="".concat(l[0],"_").concat(u);if(null!==(t=ft().exchanges[c])&&void 0!==t&&t.markets[d]){var h=new Mo(this,this.runningMMDisplayElements,e);n.botRows.appendChild(h.row.tr),a.push(h),r[h.id]=h,this.appendBotBox(h.div)}}},{key:"confirmRemoveCfg",value:function(e){var t=this.page;this.removingCfg=e,Ne.hide(t.removeCfgErr);var n=ft().assets[e.baseID].unitInfo.conventional.unit,r=ft().assets[e.quoteID].unitInfo.conventional.unit;t.confirmRemoveCfgMsg.textContent=ke("DELETE_BOT",{host:e.host,baseTicker:n,quoteTicker:r}),this.forms.show(this.page.confirmRemoveForm)}},{key:"removeCfg",value:(n=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,this.removingCfg){e.next=4;break}return this.forms.close(),e.abrupt("return");case 4:return e.next=6,ir.removeBotConfig(this.removingCfg.host,this.removingCfg.baseID,this.removingCfg.quoteID);case 6:if(n=e.sent,ft().checkResponse(n)){e.next=11;break}return t.removeCfgErr.textContent=ke(H,{msg:n.msg}),Ne.show(t.removeCfgErr),e.abrupt("return");case 11:return e.next=13,ft().fetchMMStatus();case 13:ft().loadPage("mm");case 14:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{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=Eo(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;Ne.animate(250,(function(e){s.style.opacity="".concat(e),s.style.transform="scale(".concat(.8+.2*e,")")}))}},{key:"newBot",value:function(){ft().loadPage("mmsettings")}},{key:"cexConfigured",value:(t=s(f().mark((function e(t,n){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,ft().fetchMMStatus();case 2:this.updateCexRow(this.cexes[t]),n&&this.forms.close();case 4:case"end":return e.stop()}}),e,this)}))),function(e,n){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=ft().mmStatus.cexes[r];if(Ne.setVis(!o,t.unconfigured),Ne.setVis(o&&!o.connectErr,t.configured),Ne.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&&(x=m.reduce((function(e,t){return t.gapFactor0&&(k=g.reduce((function(e,t){return t.gapFactor0,c.hasTransferable),Ne.setVis(D.fundedAndNotBalanced,c.fundedAndNotBalancedBox),Ne.setVis(D.starved,c.starvedBox),c.startBttn.classList.toggle("go",D.fundedAndBalanced),c.startBttn.classList.toggle("warning",!D.fundedAndBalanced),c.proposedDexBaseAlloc.classList.toggle("text-warning",!(D.base.fundedAndBalanced||D.base.fundedAndNotBalanced)),c.proposedDexQuoteAlloc.classList.toggle("text-warning",!(D.quote.fundedAndBalanced||D.quote.fundedAndNotBalanced));var N=function(e,t){c.proposedDexBaseAlloc.textContent=Ne.formatFourSigFigs(e),c.proposedDexBaseAllocUSD.textContent=Ne.formatFourSigFigs(e*u),c.proposedCexBaseAlloc.textContent=Ne.formatFourSigFigs(t),c.proposedCexBaseAllocUSD.textContent=Ne.formatFourSigFigs(t*u)};if(N(A,R),Ne.setVis(E,c.baseAllocSlider),E){var W=E.right.dex-E.left.dex,V=E.right.cex-E.left.cex;this.baseAllocSlider.setValue(.5),this.baseAllocSlider.changed=function(e){var t=E.left.dex+e*W,n=E.left.cex+e*V;M.dex[p]=t*x,M.cex[p]=n*x,N(t,n)}}var U=function(e,t){c.proposedDexQuoteAlloc.textContent=Ne.formatFourSigFigs(e),c.proposedDexQuoteAllocUSD.textContent=Ne.formatFourSigFigs(e*d),c.proposedCexQuoteAlloc.textContent=Ne.formatFourSigFigs(t),c.proposedCexQuoteAllocUSD.textContent=Ne.formatFourSigFigs(t*d)};if(U(P,L),Ne.setVis(O,c.quoteAllocSlider),O){var _=O.right.dex-O.left.dex,j=O.right.cex-O.left.cex;this.quoteAllocSlider.setValue(.5),this.quoteAllocSlider.changed=function(e){var t=O.left.dex+e*_,n=O.left.cex+e*j;M.dex[f]=t*k,M.cex[f]=n*k,U(t,n)}}if(Ne.setVis.apply(Ne,[v!==p].concat(r(Ne.applySelector(c.allocationDialog,"[data-base-token-fees]")))),v!==p){var H=D.base.fees.req+(v===m?D.quote.fees.req:0),z=Math.min(H,D.base.fees.avail);c.proposedDexBaseFeeAlloc.textContent=Ne.formatFourSigFigs(z),c.proposedDexBaseFeeAllocUSD.textContent=Ne.formatFourSigFigs(z*g),c.proposedDexBaseFeeAlloc.classList.toggle("text-warning",!D.base.fees.funded)}var G=m!==f&&m!==v;if(Ne.setVis.apply(Ne,[G].concat(r(Ne.applySelector(c.allocationDialog,"[data-quote-token-fees]")))),G){var X=Math.min(D.quote.fees.req,D.quote.fees.avail);c.proposedDexQuoteFeeAlloc.textContent=Ne.formatFourSigFigs(X),c.proposedDexQuoteFeeAllocUSD.textContent=Ne.formatFourSigFigs(X*y),c.proposedDexQuoteFeeAlloc.classList.toggle("text-warning",!D.quote.fees.funded)}var K=null===(s=ft().exchanges[S])||void 0===s?void 0:s.markets[F],Q=!1;if(K&&K.orders)for(var Y=0;Y=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 Vo(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;Ne.show(e.advancedConfig),Ne.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-zo)/Go),this.qcLevelSpacing.setValue(100*h),this.qcLevelSpacingSlider.setValue((h-Xo)/Ko)}else if(n===ar){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===or&&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)),Ne.hide(t.advancedConfig),Ne.show(t.quickConfig),this.showInputsForBot(r)}},{key:"showInputsForBot",value:function(e){var t=this.page,n=this.opts.usingUSDPerSide;switch(Ne.hide(t.matchMultiplierBox,t.placementsChartBox,t.placementChartLegend,t.lotsPerLevelLabel,t.levelSpacingBox,t.arbLotsLabel,t.qcLevelPerSideBox),Ne.setVis(n,t.qcUSDPerSideBox),Ne.setVis(!n,t.qcLotsBox),e){case ar:Ne.show(t.qcLevelPerSideBox,t.matchMultiplierBox,t.placementsChartBox,t.placementChartLegend,t.lotsPerLevelLabel);break;case rr:Ne.show(t.qcLevelPerSideBox,t.levelSpacingBox,t.placementsChartBox,t.lotsPerLevelLabel);break;case or:Ne.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;Ne.hide(a.qcError);var c=function(e){a.qcError.textContent=e,Ne.show(a.qcError)},l=s===or?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===rr?parseFloat(null!==(t=a.qcLevelSpacing.value)&&void 0!==t?t:"")/100:0;isNaN(h)&&c("invalid value for level spacing");var p=s===ar?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!==or){this.clearPlacements(i?Ho:o.gapStrategy);for(var m=0;m0,F=Wo(this.botTypeSelectors);try{for(F.s();!(T=F.n()).done;)(D=T.value).classList.toggle("disabled",D.dataset.botType!==rr&&!S)}catch(e){F.e(e)}finally{F.f()}0===Object.keys(ft().mmStatus.cexes).length?(Ne.show(s.noCexesConfigured),this.setBotTypeSelected(rr)):(A=k.fetchLocal(_o)||{},R=A["".concat(n,"_").concat(r,"_").concat(t)],(a=null!==(I=a)&&void 0!==I?I:R?R.botType:ar)!==rr&&(o&&(E=y[o]),!E&&R&&(E=y[null!==(B=R.cexName)&&void 0!==B?B:""]),E||(P=k.fetchLocal(jo))&&(E=y[P]),!E&&C>0&&(E=Object.values(y)[0])),E?(s.cexSelection.classList.remove("disabled"),this.setBotTypeSelected(null!==(L=a)&&void 0!==L?L:R?R.botType:ar),this.selectFormCEX(E.name)):(s.cexSelection.classList.add("disabled"),Ne.show(s.noCexMarket),this.setBotTypeSelected(rr),0===(O=Object.keys(sr).filter((function(e){return!ft().mmStatus.cexes[e]}))).length||1===O.length&&("Binance"===O[0]||"BinanceUS"===O[0])||Ne.show(s.noCexMarketConfigureMore))),Ne.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(){Zo(this.specs,ft().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=Wo(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!==rr){var h=ft().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(_o)||{})["".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(jo);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();Ne.empty(t.marketSelect);var r,a=Wo(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=ft().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,ft().walletMap[s]){e.next=5;break}return this.newWalletForm.setAsset(s),r.show(this.page.newWalletForm),e.abrupt("return");case 5:if(ft().walletMap[i]){e.next=9;break}return this.newWalletForm.setAsset(i),r.show(this.page.newWalletForm),e.abrupt("return");case 9:if(l=es(c,ft().assets[s],ft().assets[i]),u=a(l,2),d=u[0],h=u[1],d!==dt.NotApproved){e.next=14;break}return this.approveTokenForm.setAsset(s,c),r.show(n.approveTokenForm),e.abrupt("return");case 14:if(h!==dt.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=ke("NO_BOTTYPE"),Ne.show(n.botTypeErr),e.abrupt("return");case 24:if((this.formSpecs.botType=null!==(t=v[0].dataset.botType)&&void 0!==t?t:"")===rr){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=ke("NO_CEX"),Ne.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!==rr&&o){e.next=4;break}return e.abrupt("return");case 4:return e.prev=4,e.next=7,ir.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=ke(ve,{cexName:o,assetID:String(r),err:String(e.t0)}),Ne.show(n.botTypeErr),e.t0;case 15:return e.prev=15,e.next=18,ir.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=ke(ve,{cexName:o,assetID:String(a),err:String(e.t1)}),Ne.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=ft().currentWalletDefinition(e);if(!t.multifundingopts)return{};var n,r={},a=Wo(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 $n:case er:return t<=0?"Rate must be greater than 0":null;case tr:case nr: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 Zn:case $n:case er:return e;case tr:case nr: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),Ne.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===Ho?Zn:e,c=Wo(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=Wo(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?Ho:i.gapStrategy),function(e,t){for(var n=0,r=Object.entries(t);n0?t.baseFiatRate.textContent=Ne.formatFourSigFigs(i.baseFiatRate):t.baseFiatRate.textContent="N/A",i.quoteFiatRate>0?t.quoteFiatRate.textContent=Ne.formatFourSigFigs(i.quoteFiatRate):t.quoteFiatRate.textContent="N/A",Ne.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=sr[t],c=Wo(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,ar,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(sr);e0,s.redemptionFeesBox),o.bookingFeesPerCounterLot>0){var w=o.bookingFeesPerCounterLot/d.conventional.conversionFactor;s.redemptionFeesPerLot.textContent=Ne.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=Ne.formatCoinValue(Math.round(r*n.conventional.conversionFactor),n),e.commitTotalFiat.textContent=Ne.formatFourSigFigs(r*ft().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=Ne.formatCoinValue(a*r.conventional.conversionFactor,r),e.feeTotalFiat.textContent=Ne.formatFourSigFigs(a*ft().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(Ne.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=ft().currentWalletDefinition(n);if(Ne.empty(t.walletSettings),Ne.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=Ne.parseTemplate(o);h.name.textContent=n.displayname,h.input.checked="true"===d,Ne.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=Wo(n);try{for(a.s();!(r=a.n()).done;){var o=r.value;Ne.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=Ne.parseTemplate(o);y.name.textContent=n.displayname,n.description&&(y.tooltip.dataset.tooltip=n.description),m?y.unit.textContent=m:Ne.hide(y.unit);var b=new Ye(y.value,{prec:1,changed:function(e){var t=a(et(e,1),2),o=t[0],s=t[1];r[n.key]=s,x.setValue((o-f.x)/g)}}),x=new Ze(y.slider,(function(e){var t=a(et(f.x+e*g,1),2),o=t[0],s=t[1];r[n.key]=s,b.setValue(o)})),k=a(et(tt(d,f.x),3),2),w=k[0],C=k[1];r[n.key]=C,x.setValue((w-f.x)/g),b.setValue(w),y.value.textContent=C}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 S=r[n.dependsOn];Ne.setVis("true"===S,o)}}};if(o.multifundingopts&&o.multifundingopts.length>0){var l,u=Wo(o.multifundingopts);try{for(u.s();!(l=u.n()).done;)c(l.value)}catch(e){u.e(e)}finally{u.f()}}ft().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=ft().walletMap[t].balance.available,h=this.pg.runningBotInventory(t),p=d-h.dex.total,f=0;if(Ne.setVis(i,e.balanceBreakdown),i&&(e.dexAvail.textContent=Ne.formatFourSigFigs(p/n.conventional.conversionFactor),f=(t===c?l:u).available-h.cex.total,e.cexAvail.textContent=Ne.formatFourSigFigs(f/n.conventional.conversionFactor)),e.avail.textContent=Ne.formatFourSigFigs((p+f)/n.conventional.conversionFactor),t!==r){var v=ft().walletMap[r].balance.available;e.feeAvail.textContent=Ne.formatFourSigFigs(v/a.conventional.conversionFactor)}}}]),e}();var ns=function(e){g(I,e);var t,n,r,a,o,c,l,u,p,m,x,k,w,C,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=ft().exchanges[n],a=t.page=Ne.idDescendants(e);t.forms=Ne.applySelector(a.forms,":scope > form"),t.confirmRegisterForm=new Rr(a.confirmRegForm,s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t.showSuccess(ke(se)),t.renewToggle.setState(t.confirmRegisterForm.tier>0),e.next=4,ft().fetchUser();case 4:ft().updateMenuItemsDisplay();case 5:case"end":return e.stop()}}),e)}))),(function(){t.runAnimation(t.regAssetForm,a.regAssetForm)})),t.confirmRegisterForm.setExchange(r,""),t.walletWaitForm=new Br(a.walletWait,(function(){t.runAnimation(t.confirmRegisterForm,a.confirmRegForm)}),(function(){t.runAnimation(t.regAssetForm,a.regAssetForm)})),t.walletWaitForm.setExchange(r),t.newWalletForm=new Dr(a.newWalletForm,(function(e){return t.newWalletCreated(e,t.confirmRegisterForm.tier)}),(function(){return t.runAnimation(t.regAssetForm,a.regAssetForm)})),t.regAssetForm=new Er(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!==pt){e.next=6;break}return e.next=3,ft().fetchUser();case 3:return t.updateReputation(),t.showSuccess(ke(se)),e.abrupt("return");case 6:if(o=ft().assets[n],!(s=o.wallet)){e.next=17;break}return i=ft().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 Sn(a.repMeter),t.reputationMeter.setHost(n),Ne.bind(a.exportDexBtn,"click",(function(){return t.exportAccount()})),t.accountDisabled="true"===e.dataset.disabled,Ne.bind(a.toggleAccountStatusBtn,"click",(function(){t.accountDisabled?t.toggleAccountStatus(!1):t.prepareAccountDisable(a.disableAccountForm)})),Ne.bind(a.updateCertBtn,"click",(function(){return a.certFileInput.click()})),Ne.bind(a.updateHostBtn,"click",(function(){return t.prepareUpdateHost()})),Ne.bind(a.certFileInput,"change",(function(){return t.onCertFileChange()})),Ne.bind(a.goBackToSettings,"click",(function(){return ft().loadPage("settings")}));var o=function(){t.regAssetForm.setExchange(ft().exchanges[n],""),t.showForm(a.regAssetForm)};Ne.bind(a.changeTier,"click",(function(){o()}));var c=r.auth.targetTier>0;t.renewToggle=new _e(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)}}()),Ne.bind(a.autoRenewBox,"click",(function(e){e.stopPropagation(),t.accountDisabled||a.toggleAutoRenew.click()})),a.penaltyComps.textContent=String(r.auth.penaltyComps);var l=function(){Ne.hide(a.penaltyCompInput),Ne.show(a.penaltyComps)};return Ne.bind(a.penaltyCompBox,"click",(function(e){e.stopPropagation();var n=ft().exchanges[t.host];a.penaltyCompInput.value=String(n.auth.penaltyComps),Ne.hide(a.penaltyComps),Ne.show(a.penaltyCompInput),a.penaltyCompInput.focus(),Ne.bind(document,"click",(function e(t){Ne.mouseInElement(t,a.penaltyCompBox)||(l(),Ne.unbind(document,"click",e))}))})),Ne.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(Ne.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 Ne.show(a.penaltyCompsErr),a.penaltyCompsErr.textContent=ke("INVALID_COMPS_VALUE"),e.abrupt("return");case 11:return o=ft().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(),Ne.show(a.penaltyCompsErr),a.penaltyCompsErr.textContent=ke(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 Lr(a.dexAddrForm,function(){var e=s(f().mark((function e(t){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:ft().loadPage("/dexsettings/".concat(t.host));case 1:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),t.host),Gr(a.disableAccountForm,a.disableAccountConfirm,(function(){return t.toggleAccountStatus(!0)})),Ne.bind(a.forms,"mousedown",(function(e){Ne.mouseInElement(e,t.currentForm)||t.closePopups()})),t.keyup=function(e){"Escape"===e.key&&t.closePopups()},Ne.bind(document,"keyup",t.keyup),Ne.applySelector(a.forms,".form-closer").forEach((function(e){Ne.bind(e,"click",(function(){t.closePopups()}))})),ft().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(){Ne.unbind(document,"keyup",this.keyup)}},{key:"progressTierFormsWithWallet",value:(C=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=ft().assets[t],s=this.regAssetForm.xc.bondAssets,i=s[o.symbol],n.open){e.next=12;break}return c=ft().loading(r.forms),e.next=8,S("/api/openwallet",{assetID:t});case 8:return l=e.sent,c(),ft().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 C.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=ft().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=ft().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(ke(se));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=ft().exchanges[this.host].auth,n=t.rep.penalties,r=t.targetTier,a=t.expiredBonds,o=Fn(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 Ne.hide(e)})),t.style.right="10000px",Ne.show(n.forms,t),r=(n.forms.offsetWidth+t.offsetWidth)/2,e.next=8,Ne.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 Ne.hide(this.currentForm),e.next=3,t.animate();case 3:this.currentForm=n,Ne.show(n);case 5:case"end":return e.stop()}}),e,this)}))),function(e,t){return x.apply(this,arguments)})},{key:"closePopups",value:function(){Ne.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 Ne.hide(e)})),this.currentForm=this.page.checkmarkForm,this.animation=zr(this.page,t),e.next=5,this.animation.wait();case 5:this.animation=new We(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=ft().loading(this.body),e.next=5,S("/api/exportaccount",r);case 5:if(o=e.sent,a(),ft().checkResponse(o)){e.next=11;break}return t.exportAccountErr.textContent=o.msg,Ne.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(),Ne.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,Ne.hide(n.errMsg),r=this.host,t&&(r=n.disableAccountHost.textContent),a={host:r,disable:t},o=ft().loading(this.body),e.next=8,S("/api/toggleaccountstatus",a);case 8:if(s=e.sent,o(),ft().checkResponse(s)){e.next=13;break}return t?(n.disableAccountErr.textContent=s.msg,Ne.show(n.disableAccountErr)):(n.errMsg.textContent=s.msg,Ne.show(n.errMsg)),e.abrupt("return");case 13:return t?(this.page.toggleAccountStatusBtn.textContent=ke("ENABLE_ACCOUNT"),Ne.hide(n.forms)):this.page.toggleAccountStatusBtn.textContent=ke("DISABLE_ACCOUNT"),this.accountDisabled=t,e.next=17,ft().fetchUser();case 17:ft().loadPage("dexsettings/".concat(r));case 18: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=ft().loading(n),e.next=3,S("/api/bondsfeebuffer",{assetID:t});case 3:if(a=e.sent,r(),ft().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,Ne.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=ft().loading(this.body),e.next=13,S("/api/updatecert",a);case 13:s=e.sent,o(),ft().checkResponse(s)?(Ne.show(t.updateCertMsg),setTimeout((function(){Ne.hide(t.updateCertMsg)}),5e3)):(t.errMsg.textContent=s.msg,Ne.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=ft().user.exchanges[this.host],n=function(t){t?(Ne.hide(e.disconnectedIcon),Ne.show(e.connectedIcon)):(Ne.show(e.disconnectedIcon),Ne.hide(e.connectedIcon))};if(t)switch(t.connectionStatus){case ut.Connected:n(!0),e.connectionStatus.textContent=ke("CONNECTED");break;case ut.Disconnected:n(!1),this.accountDisabled?e.connectionStatus.textContent=ke("ACCOUNT_DISABLED_MSG"):e.connectionStatus.textContent=ke($);break;case ut.InvalidCert:n(!1),e.connectionStatus.textContent="".concat(ke($)," - ").concat(ke("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=ft().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,S("/api/updatebondoptions",t);case 3:r=null!==(n=t.targetTier)&&void 0!==n?n:ft().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,ft().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=ft().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}(lt);var rs=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=Ne.idDescendants(e);return Ne.cleanTemplates(n.runTableRowTmpl),Ne.bind(n.backButton,"click",(function(){ft().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,ft().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=Ne.parseTemplate(u)).startTime.textContent=new Date(1e3*r).toLocaleString(),lr(u,i,c,l),Ne.bind(d.logs,"click",(function(){ft().loadPage("mmlogs",{baseID:i,quoteID:c,host:l,startTime:r,returnPage:"mmarchives"})})),Ne.bind(d.settings,"click",(function(){ft().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 os(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=vr(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=ft().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=as(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),ft().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?Ne.hide(n.endTimeRow):n.endTime.textContent=new Date(1e3*t).toLocaleString(),e.diffs){var a=ft().assets[parseInt(r)],o=this.statsRows[r];if(!o){o=n.performanceTableRowTmpl.cloneNode(!0);var s=Ne.parseTemplate(o);s.logo.src=Ne.logoPath(a.symbol),s.ticker.textContent=a.symbol.toUpperCase(),this.statsRows[r]=o,n.performanceTableBody.appendChild(o)}var i=e.diffs[r],c=Ne.parseTemplate(o);c.diff.textContent=i.fmt,c.usdDiff.textContent=i.fmtUSD,c.fiatRate.textContent="".concat(Ne.formatFiatValue(this.fiatRates[a.id])," USD")}n.profitLoss.textContent="".concat(Ne.formatFiatValue(e.profit)," USD")}},{key:"mktAssets",value:function(){var e,t=ft().assets[this.mkt.baseID],n=ft().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=ft().assets[t.token.parentID];a[o.id]=!0,r.push(o)}if(n.token&&!a[n.token.parentID]){var s=ft().assets[n.token.parentID];r.push(s)}return r}},{key:"updateExistingRows",value:function(e){var t,n=as(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;Ne.empty(t.eventsTableBody),this.events={},this.doneScrolling=!1;var n,r=this.mktAssets(),a=as(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=Ne.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=ls(r,30),o.eventID.setAttribute("title",r));var s,i=0,c=as(n);try{for(c.s();!(s=c.n()).done;){var l,u=s.value,d=t.balanceEffects,h=us(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=Ne.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=Ne.formatFourSigFigs(i),Ne.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=ft().assets[r],s=ft().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(){rt(e.id,t.dexOrderID,t.copyDexOrderID,"#1e7d11")},t.copyDexOrderID.addEventListener("click",this.dexOrderIDCopyListener),t.dexOrderID.textContent=ls(e.id,20),t.dexOrderID.setAttribute("title",e.id);var p=ft().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=ke(B):t.dexOrderSide.textContent=ke(E),Ne.empty(t.dexOrderTxsTableBody),Ne.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 hs(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 ws(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")})),Ss(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=Ne.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"),Ne.bind(s,"click",(function(){Ne.setText(e,"[data-value]",Ne.formatFourSigFigs(o/n,Math.round(Math.log10(n)))),Ne.setText(e,"[data-unit]",t)}))},s=ks(Ne.applySelector(e,"[data-conversion-value]"));try{var i=function(){var e=a.value,s=Ne.safeSelector(e,"[data-unit-box]");Ne.bind(s,"mouseenter",(function(){Ne.empty(r),s.appendChild(n);var a=Ne.layoutMetrics(s),i=parseInt(s.dataset.assetID),c=t.assets[i].unitInfo;o(e,c.conventional.unit,c.conventional.conversionFactor);var l,u=ks(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")})),Ne.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=ks(Ne.applySelector(e,"a[target=_blank]"));try{var r=function(){var e=t.value;Ne.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=Cs(document.body,"header");var t=this.page=Ne.idDescendants(this.header);this.headerSpace=t.headerSpace,this.popupNotes=Cs(document.body,"popupNotes"),this.popupTmpl=Ne.tmplElement(this.popupNotes,"note"),this.popupTmpl?this.popupTmpl.remove():console.error("popupTmpl element not found"),this.tooltip=Cs(document.body,"tooltip"),t.noteTmpl.removeAttribute("id"),t.noteTmpl.remove(),t.pokeTmpl.removeAttribute("id"),t.pokeTmpl.remove(),t.loader.remove(),Ne.show(t.loader),Ss(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:Ne.hide(t.pokeList),Ne.show(t.noteList),e.ackNotes(),t.noteCat.classList.add("active"),t.pokeCat.classList.remove("active"),e.showDropdown(t.noteBell,t.noteBox),Ne.hide(t.noteIndicator),r=ks(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)})))),Ss(t.burgerIcon,"click",(function(){Ne.hide(t.logoutErr),e.showDropdown(t.burgerIcon,t.profileBox)})),Ss(t.innerNoteIcon,"click",(function(){Ne.hide(t.noteBox)})),Ss(t.innerBurgerIcon,"click",(function(){Ne.hide(t.profileBox)})),Ss(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)})))),Ss(t.pokeCat,"click",(function(){e.setNoteTimes(t.pokeList),t.pokeCat.classList.add("active"),t.noteCat.classList.remove("active"),Ne.hide(t.noteList),Ne.show(t.pokeList),e.ackNotes()})),Ss(t.noteCat,"click",(function(){e.setNoteTimes(t.noteList),t.noteCat.classList.add("active"),t.pokeCat.classList.remove("active"),Ne.hide(t.pokeList),Ne.show(t.noteList),e.ackNotes()})),Ne.cleanTemplates(t.langBttnTmpl);var n=Ds[this.lang],r=n.name,a=n.flag;t.langFlag.textContent=a,t.langName.textContent=r;var o,i=ks(this.langs);try{var c=function(){var n=o.value;if(n===e.lang)return"continue";var r=t.langBttnTmpl.cloneNode(!0),a=Ds[n],s=a.name,i=a.flag;r.textContent=i,r.title=s,Ne.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,Ne.idDescendants(Ne.idel(document.body,"requiredActions"))),Ne.cleanTemplates(t.missingNoncesTmpl,t.actionTxTableTmpl,t.tooCheapTmpl,t.lostNonceTmpl),Ne.bind(t.actionsCollapse,"click",(function(){Ne.hide(t.actionDialog),Ne.show(t.actionDialogCollapsed)})),Ne.bind(t.actionDialogCollapsed,"click",(function(){Ne.hide(t.actionDialogCollapsed),Ne.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)};Ne.bind(t.prevAction,"click",(function(){return n(-1)})),Ne.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=ks(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),Ne.isHidden(t.actionDialog)&&this.showRequestedAction(e.uniqueID)}}}},{key:"blinkAction",value:function(){Ne.blink(this.page.actionDialog),Ne.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()):Ne.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=Ne.parseTemplate(s);i.lostTxID.textContent=n.tx.id,i.lostTxID.dataset.explorerCoin=n.tx.id,Xn(o?o.parentID:t,i.lostTxID),i.txAmt.textContent=Ne.formatCoinValue(n.tx.amount,a),i.amtUnit.textContent=a.conventional.unit;var c=o?this.unitInfo(o.parentID):a;return i.type.textContent=ia(n.tx.type),i.feeAmount.textContent=Ne.formatCoinValue(n.tx.fees,c),i.feeUnit.textContent=c.conventional.unit,"tooCheap"===e.actionID&&(Ne.show(i.newFeesRow),i.newFees.textContent=Ne.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 Ne.hide(r),a=this.loading(this.page.actionDialog),e.next=4,S("/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,Ne.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=Ne.parseTemplate(r),o=this.assets[n].name;return a.assetName.textContent=o,Ne.bind(a.doNothingBttn,"click",(function(){t.submitAction(e,{recover:!1},a.errMsg)})),Ne.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=Ne.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 Ne.bind(o.keepWaitingBttn,"click",(function(){return i(!1)})),Ne.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=Ne.parseTemplate(a),s=this.assets[n].name;return o.assetName.textContent=s,o.nonce.textContent=String(r.nonce),o.txTable.appendChild(this.actionTxTable(e)),Ne.bind(o.abandonBttn,"click",(function(){t.submitAction(e,{txID:r.tx.id,abandon:!0},o.errMsg)})),Ne.bind(o.keepWaitingBttn,"click",(function(){t.submitAction(e,{txID:r.tx.id,abandon:!1},o.errMsg)})),Ne.bind(o.replaceBttn,"click",(function(){var n=o.idInput.value;if(!n)return o.idInput.focus(),void Ne.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=Ne.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,Xn(d?d.parentID:s,c.txid),Ne.bind(c.doNothingBttn,"click",(function(){t.submitAction(e,{orderID:r,coinID:a,retry:!1},c.errMsg)})),Ne.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;Ne.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&&Va.request("acknotes",t),Ne.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"),Ne.show(e.noteBell,e.walletsMenuEntry,e.marketsMenuEntry),Ne.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=ks(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,Ne.animate(500,(function(e){i.style.opacity=String(1-e)}));case 2:i.remove(),0===o.children.length&&Ne.hide(o);case 4:case"end":return e.stop()}}),e)}))),6e3)}2===e.severity?this.prependPokeElement(e):this.prependNoteElement(e),function(e){Da.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||Ne.isDisplayed(this.page.noteBox)&&Ne.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;Bs(c,i),s?(c.textContent=String(s>99?"".concat(99,"+"):s),Ne.show(c)):Ne.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";Ne.safeSelector(t,"div.note-indicator").classList.add(n)}return Ne.safeSelector(t,"div.note-subject").textContent=e.subject,Ea(Ne.safeSelector(t,"div.note-details"),e.details),[t,xs({el:t},e)]}},{key:"makePoke",value:function(e){var t=this.page.pokeTmpl.cloneNode(!0);return Ne.tmplElement(t,"subject").textContent="".concat(e.subject,":"),Ea(Ne.tmplElement(t,"details"),e.details),[t,xs({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{var e={633:(e,t,n)=>{var r=n(738).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:S(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 C(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 S(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},738: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},756:(e,t,n)=>{var r=n(633)();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 C.apply(this,arguments)}function C(){return(C=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 S(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="LIMIT_ORDER",K="MARKET_ORDER",Q="MATCH_STATUS_REDEMPTION_SENT",Y="MATCH_REDEMPTION_CONFIRMED",J="MATCH_STATUS_REFUND_PENDING",Z="ORDER_ACCELERATION_ERR_MSG",$="DISCONNECTED",ee="BROWSER_NTFN_ENABLED",te="ORDER_BUTTON_BUY_BALANCE_ERROR",ne="ORDER_BUTTON_SELL_BALANCE_ERROR",re="ORDER_BUTTON_QTY_ERROR",ae="ORDER_BUTTON_QTY_RATE_ERROR",oe="CREATE_ASSET_WALLET_MSG",se="TRADING_TIER_UPDATED",ie="INVALID_TIER_VALUE",ce="MATCH_BUFFER",le="NO_PLACEMENTS",ue="INVALID_VALUE",de="NO_ZERO",he="BOTTYPE_BASIC_MM",pe="BOTTYPE_ARB_MM",fe="BOTTYPE_SIMPLE_ARB",ve="CEXBALANCE_ERR",me="PENDING",ge="COMPLETE",ye="CEX_NOT_CONNECTED";function be(e,t,n){return xe.apply(this,arguments)}function xe(){return(xe=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,S("/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 ke(e,t){return function(e,t){return e.replace(/{{\s?([^{}\s]*)\s?}}/g,(function(e,n){return t[n]}))}(I[e],t||{})}function we(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 Ce(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)?Ce(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 Ce(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;a1?n-1:0),a=1;a"),e),document.createElement("div"))}},{key:"idDescendants",value:function(t){var n,r={},a=we(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(qe(e,t),2),r=n[0],o=n[1];return Number.isInteger(r)?Ee.format(r):function(e){return Me(Pe,2,e)}(o).format(r)}},{key:"conventionalCoinValue",value:function(e,t){return a(qe(e,t),1)[0]}},{key:"formatRateFullPrecision",value:function(e,t,n,r){var a=e*(t.conventional.conversionFactor/n.conventional.conversionFactor)/Ie,o=Ae-Math.floor(Math.log10(r))-Math.floor(Math.log10(t.conventional.conversionFactor)-Math.log10(n.conventional.conversionFactor));return o<=0?Ee.format(a):Oe(o).format(a)}},{key:"formatFourSigFigs",value:function(e,t){return function(e,t,n,r){var a,o;if(n>=1e3)return e.format(n);var s=t.format(n);return"number"!=typeof r||(null!==(a=null===(o=t.formatToParts(n).filter((function(e){return"fraction"===e.type}))[0])||void 0===o?void 0:o.value)&&void 0!==a?a:"").length<=r?s:Oe(r,void 0).format(n)}(Ee,Be,e,t)}},{key:"formatInt",value:function(e){return Ee.format(e)}},{key:"formatFullPrecision",value:function(e,t){var n=a(qe(e,t),2),r=n[0];return Oe(n[1]).format(r)}},{key:"formatFiatConversion",value:function(e,t,n){if(!t||0===t)return ke("UNAVAILABLE");var r=a(qe(e,n),1)[0]*t;return Oe(2).format(r)}},{key:"languages",value:function(){return Re}},{key:"formatFiatValue",value:function(e){return Oe(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=we(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(Qe(c,He),2);if(t=h[0],c=h[1],d(t,"y"))return l;var p=a(Qe(c,ze),2);if(n=p[0],c=p[1],d(n,"mo"))return l;var f=a(Qe(c,Ge),2);if(r=f[0],c=f[1],d(r,"d"))return l;var v=a(Qe(c,Xe),2);if(o=v[0],c=v[1],d(o,"h"))return l;var m=a(Qe(c,Ke),2);if(s=m[0],c=m[1],d(s,"m"))return l;var g=a(Qe(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?Ve[a]:Ve.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 et(e,t){var n=Math.floor(Math.log10(Math.abs(e)));return n>=3?[Math.round(e),e.toFixed(0)]:$e(e,Math.min(4-n,t))}function tt(e,t){var n=parseFloat((null!=e?e:"").replace(/,/g,""));return isNaN(n)?null!=t?t:0:n}function nt(e,t,n){return en?n:e}function rt(e,t,n,r){return at.apply(this,arguments)}function at(){return(at=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 ot,st,it,ct,lt=function(){function e(){i(this,e)}return d(e,[{key:"unload",value:function(){}}]),e}(),ut=function(e){return e[e.Disconnected=0]="Disconnected",e[e.Connected=1]="Connected",e[e.InvalidCert=2]="InvalidCert",e}({}),dt=function(e){return e[e.Approved=0]="Approved",e[e.Pending=1]="Pending",e[e.NotApproved=2]="NotApproved",e}({}),ht=function(e){return e[e.WalletDefault=0]="WalletDefault",e[e.UserAdded=1]="UserAdded",e[e.Discovered=2]="Discovered",e}({}),pt=2147483647;function ft(){return ot}function vt(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 mt(e){var t=[e.booleanOptTmpl,e.rangeOptTmpl,e.orderOptTmpl];it=t[0],ct=t[1],st=t[2]}var gt=new Intl.NumberFormat(Ne.languages(),{minimumSignificantDigits:3,maximumSignificantDigits:3}),yt=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=st.cloneNode(!0),s=this.tmpl=Ne.parseTemplate(o);s.optName.textContent=t.displayname,s.tooltip.dataset.tooltip=t.description,n?s.chainIcon.src=Ne.logoPath(n):Ne.hide(s.chainIcon),this.on=!1,Ne.bind(o,"click",(function(){a.on||(a.on=!0,o.classList.add("selected"),r.enable())})),Ne.bind(s.toggle,"click",(function(e){a.on&&(e.stopPropagation(),a.on=!1,o.classList.remove("selected"),r.disable())}))})),bt=function(e){g(n,e);var t=vt(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=it.cloneNode(!0);return s.tmpl.controls.appendChild(l),Ne.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}(yt),xt=function(e){g(n,e);var t=vt(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 kt(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}(yt),kt=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=ct.cloneNode(!0),d=this.tmpl=Ne.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=wt(a,t.start.x,t.end.x),l.r=g(l.scrollingX),l.y=l.r*m+t.start.y,l.accept(l.scrollingX))}Ne.hide(d.xInput),Ne.show(d.x),Ne.unbind(document,"click",e),l.changed()}};Ne.bind(d.x,"click",(function(e){l.disabled||(Ne.hide(d.x),Ne.show(d.xInput),d.xInput.focus(),d.xInput.value=gt.format(l.scrollingX),Ne.bind(document,"click",y),e.stopPropagation())})),Ne.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=wt(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))}Ne.hide(d.yInput),Ne.show(d.y),Ne.unbind(document,"click",e),l.changed()}};Ne.bind(d.y,"click",(function(e){l.disabled||(Ne.hide(d.y),Ne.show(d.yInput),d.yInput.focus(),d.yInput.value=gt.format(l.y),Ne.bind(document,"click",b),e.stopPropagation())})),Ne.bind(d.yInput,"change",b),Ne.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})};Ne.bind(document,"mousemove",o),Ne.bind(document,"mouseup",(function e(t){o(t,!0),Ne.unbind(document,"mousemove",o),Ne.unbind(document,"mouseup",e),l.changed()}))}})),Ne.bind(d.sliderBox,"click",(function(e){if(!l.disabled&&0===e.button){var n=e.pageX,r=Ne.layoutMetrics(d.slider);l.r=wt((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=gt.format(e),r.y.textContent=gt.format(this.y),this.roundY&&(r.y.textContent="".concat(this.y));var a=wt(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}(),wt=function(e,t,n){return en?n:e};function Ct(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 St(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)?St(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 St(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=3||1===n.side&&n.status>=4?e+t(n):e}),0)}function Pt(e){var t;if(null===(t=e.matches)||void 0===t||!t.length)return ke(K);var n=Ne.formatCoinValue(ft().conventionalRate(e.baseID,e.quoteID,Lt(e)));return e.matches.length>1&&(n="~ "+n),n}function Lt(e){var t;if(null===(t=e.matches)||void 0===t||!t.length)return 0;var n,r=0,a=0,o=Ct(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 Ot(e,t){return e*t/Ft}function Mt(e){return ke("MATCH_STATUS_REVOKED",{status:ke(e)})}function qt(e){return 1===e.type&&1===e.tif&&e.status<3}function Nt(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 Wt(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 Vt(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)?Vt(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 Vt(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([S.rate,w]),!S.epoch)for(k+=S.qty,m.push([S.rate,k]),x.buyBase+=S.qty,x.buyQuote+=S.qty*S.rate;p.length&&an(p[0].rate,S.rate);){var F=p.shift();F&&v.push({rate:F.rate,qty:S.epoch?w:k,sell:S.sell,active:F.active})}}var T=m.length?tn(m)[1]:0;m.push([h,T]);var D=g.length?tn(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 sn(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=Wt(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 C=this.market.ratestep,S=new Jt(k,w,g,m);g===m&&(S.y.min-=C,S.y.max+=C),this.dataExtents=S;var F=null;a&&this.plotRegion.plot(new Jt(S.x.min,S.x.max,0,1),(function(e,n){var o,s=sn(n.unx(a.x),r),c=Wt(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=ft().assets[this.market.baseid])||void 0===e?void 0:e.unitInfo.conventional.unit)||this.market.basesymbol.toUpperCase(),I=function(e,t,n){var r=e[0],a=e[e.length-1],o=sn(r.endStamp,t),s=sn(a.endStamp,t)+t,i=s-o,c=Math.min(e.length,n/100),l=sn(i/c,t);if(0===l)return console.error("zero tick",t,i,c),{lbls:[]};var u=o,d=(new Date).getTimezoneOffset(),h=function(e){return(e-=6e4*d)-e%864e5},p=h(o),f=0;h(r.endStamp)===h(a.endStamp)&&(p=0);var v,m=[];for(v=t<864e5?function(e,t){return h(t)!==p?"".concat(en[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!==f?"".concat(en[e.getMonth()]).concat(e.getDate()," '").concat(String(t).slice(2,4)):"".concat(en[e.getMonth()]).concat(e.getDate())};u<=s;){var g=new Date(u);m.push({val:u,txt:v(g,u)}),p=h(u),f=g.getFullYear(),u+=l}return{lbls:m}}(i,r,this.plotRegion.width());this.plotXGrid(I,k,w);var A=this.makeYLabels(this.candleRegion,C,D,(function(e){return Ne.formatFourSigFigs(e/T)}));this.plotYGrid(this.candleRegion,A,this.dataExtents.y.min,this.dataExtents.y.max);var R=new Jt(k,w,0,y);if(this.volumeRegion.plot(R,(function(e,n){e.fillStyle=t.theme.gridBorder;var r,a=Wt(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(S,(function(e,n){e.lineWidth=1;var r,a=Wt(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 Jt(S.x.min,S.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=Ft*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=nt(.15*o,10,14),this.applyLabelStyle(this.fontSize);var c=.5*this.fontSize,l=this.fontSize/2+c;i-=l,this.msgRegion=new Zt(this.ctx,new Jt(0,n,i+o,i+o+2*l))}this.region=new Zt(this.ctx,new Jt(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 Jt(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 $t(e,t,n,r,a,o,s,i){i=i||Ne.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 en=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"];function tn(e){return e[e.length-1]}function nn(e,t,n,r,a,o){e.beginPath(),e.moveTo(t,n),e.lineTo(r,a),o||e.stroke()}function rn(e,t,n,r,a){e.fillStyle=r,e.beginPath(),e.arc(t,n,a,0,_t),e.fill()}function an(e,t){return on(e,t,1e-8)}function on(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 ln(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=Tn(s,a);e.limitBonus.textContent=d.toFixed(1);var h,p=cn(Ne.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 dn(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 hn,pn,fn,vn,mn,gn,yn,bn,xn,kn,wn,Cn,Sn=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/Ft;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*Ft/s:t.lotsize:0};function Fn(e,t,n){return 3===e.type?0:function(e,t,n){var r;if(1!==e.status)return 0;var a=Sn(e,t,n);return function(e,t){return 2===e.type||0===e.tif||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 2!==e.status?0:Sn(e)}(e)+function(e){var t,n=0,r=cn(e.matches||[]);try{for(r.s();!(t=r.n()).done;){var a=t.value;if(0===a.side){if(a.status>3)continue}else if(a.status>2)continue;n+=a.qty}}catch(e){r.e(e)}finally{r.f()}return n}(e)}function Tn(e,t){return e>0?1+e/t*2:1}var Dn="TakerFoundMakerRedemption:";function In(e){return e.startsWith(Dn)?[e.substring(26),!0]:42===e.length?[e,!0]:[e,!1]}var An=(h(hn={},0,(function(e){var t=a(In(e),2),n=t[0];return t[1]?"https://etherscan.io/address/".concat(n):"https://etherscan.io/tx/".concat(n)})),h(hn,1,(function(e){var t=a(In(e),2),n=t[0];return t[1]?"https://sepolia.etherscan.io/address/".concat(n):"https://sepolia.etherscan.io/tx/".concat(n)})),h(hn,2,(function(e){var t=a(In(e),2),n=t[0];return t[1]?"https://etherscan.io/address/".concat(n):"https://etherscan.io/tx/".concat(n)})),hn),Rn=(h(pn={},0,(function(e){var t=a(In(e),2),n=t[0];return t[1]?"https://polygonscan.com/address/".concat(n):"https://polygonscan.com/tx/".concat(n)})),h(pn,1,(function(e){var t=a(In(e),2),n=t[0];return t[1]?"https://amoy.polygonscan.com/address/".concat(n):"https://amoy.polygonscan.com/tx/".concat(n)})),h(pn,2,(function(e){var t=a(In(e),2),n=t[0];return t[1]?"https://polygonscan.com/address/".concat(n):"https://polygonscan.com/tx/".concat(n)})),pn),En={42:(fn={},h(fn,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(fn,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(fn,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)})),fn),0:(vn={},h(vn,0,(function(e){return"https://mempool.space/tx/".concat(e.split(":")[0])})),h(vn,1,(function(e){return"https://mempool.space/testnet/tx/".concat(e.split(":")[0])})),h(vn,2,(function(e){return"https://mempool.space/tx/".concat(e.split(":")[0])})),vn),2:(mn={},h(mn,0,(function(e){return"https://ltc.bitaps.com/".concat(e.split(":")[0])})),h(mn,1,(function(e){return"https://sochain.com/tx/LTCTEST/".concat(e.split(":")[0])})),h(mn,2,(function(e){return"https://ltc.bitaps.com/".concat(e.split(":")[0])})),mn),20:(gn={},h(gn,0,(function(e){return"https://digiexplorer.info/tx/".concat(e.split(":")[0])})),h(gn,1,(function(e){return"https://testnetexplorer.digibyteservers.io/tx/".concat(e.split(":")[0])})),h(gn,2,(function(e){return"https://digiexplorer.info/tx/".concat(e.split(":")[0])})),gn),60:An,60001:An,60002:An,3:(yn={},h(yn,0,(function(e){return"https://dogeblocks.com/tx/".concat(e.split(":")[0])})),h(yn,1,(function(e){return"https://blockexplorer.one/dogecoin/testnet/tx/".concat(e.split(":")[0])})),h(yn,2,(function(e){return"https://dogeblocks.com/tx/".concat(e.split(":")[0])})),yn),5:(bn={},h(bn,0,(function(e){return"https://blockexplorer.one/dash/mainnet/tx/".concat(e.split(":")[0])})),h(bn,1,(function(e){return"https://blockexplorer.one/dash/testnet/tx/".concat(e.split(":")[0])})),h(bn,2,(function(e){return"https://blockexplorer.one/dash/mainnet/tx/".concat(e.split(":")[0])})),bn),133:(xn={},h(xn,0,(function(e){return"https://zcashblockexplorer.com/transactions/".concat(e.split(":")[0])})),h(xn,1,(function(e){return"https://blockexplorer.one/zcash/testnet/tx/".concat(e.split(":")[0])})),h(xn,2,(function(e){return"https://zcashblockexplorer.com/transactions/".concat(e.split(":")[0])})),xn),147:(kn={},h(kn,0,(function(e){return"https://explorer.zcl.zelcore.io/tx/".concat(e.split(":")[0])})),h(kn,2,(function(e){return"https://explorer.zcl.zelcore.io/tx/".concat(e.split(":")[0])})),kn),136:(wn={},h(wn,0,(function(e){return"https://explorer.firo.org/tx/".concat(e.split(":")[0])})),h(wn,1,(function(e){return"https://testexplorer.firo.org/tx/".concat(e.split(":")[0])})),h(wn,2,(function(e){return"https://explorer.firo.org/tx/".concat(e.split(":")[0])})),wn),145:(Cn={},h(Cn,0,(function(e){return"https://bch.loping.net/tx/".concat(e.split(":")[0])})),h(Cn,1,(function(e){return"https://tbch4.loping.net/tx/".concat(e.split(":")[0])})),h(Cn,2,(function(e){return"https://bch.loping.net/tx/".concat(e.split(":")[0])})),Cn),966:Rn,966001:Rn,966002:Rn,966003:Rn,966004:Rn};function Bn(e){return e.startsWith(Dn)?ke("TAKER_FOUND_MAKER_REDEMPTION",{makerAddr:e.substring(26)}):e}function Pn(e,t){var n=ft().user.net,r=En[function(e){var t=ft().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 Ln(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 On(e){for(var t=1;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 qn(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n0,this.baseFeeUI=f,this.baseFeeTicker=f.conventional.unit,this.baseFeeSymbol=v,this.baseFeeFactor=this.baseFeeUI.conventional.conversionFactor;var g=ft().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=ft().assets[this.quoteFeeID],C=w.unitInfo,S=w.symbol,F=w.wallet;this.quoteIsAccountLocker=(16384&F.traits)>0,this.quoteFeeUI=C,this.quoteFeeTicker=C.conventional.unit,this.quoteFeeSymbol=S,this.quoteFeeFactor=this.quoteFeeUI.conventional.conversionFactor,this.id=$n(n,r,a),this.mktID="".concat(l,"_").concat(b);var T=ft().exchanges[n].markets[this.mktID],D=T.lotsize,I=T.ratestep;this.lotSize=D,this.lotSizeConv=D/u.conventional.conversionFactor,this.rateStep=I,this.quoteLot=Jn(D,r,a),this.quoteLotConv=this.quoteLot/x.conventional.conversionFactor,this.baseFeeFiatRate=ft().fiatRatesMap[d],this.quoteFeeFiatRate=ft().fiatRatesMap[k],t.arbMarketMakingConfig?(this.botType=Hn,this.baseLots=t.arbMarketMakingConfig.sellPlacements.reduce(nr,0),this.quoteLots=t.arbMarketMakingConfig.buyPlacements.reduce(nr,0),this.nBuyPlacements=t.arbMarketMakingConfig.buyPlacements.length,this.nSellPlacements=t.arbMarketMakingConfig.sellPlacements.length):t.simpleArbConfig?(this.botType=zn,this.baseLots=t.uiConfig.simpleArbLots,this.quoteLots=t.uiConfig.simpleArbLots):t.basicMarketMakingConfig&&(this.botType=jn,this.baseLots=t.basicMarketMakingConfig.sellPlacements.reduce(nr,0),this.quoteLots=t.basicMarketMakingConfig.buyPlacements.reduce(nr,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(){var t,n,r,a,o,s,i;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.host,n=this.baseID,r=this.quoteID,a=this.lotSizeConv,o=this.quoteLotConv,e.next=3,Xn.report(t,n,r);case 3:s=e.sent,i=this.marketReport=s.report,this.lotSizeUSD=a*i.baseFiatRate,this.quoteLotUSD=o*i.quoteFiatRate,this.proj=this.projectedAllocations();case 8:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})},{key:"status",value:function(){var e=this.baseID,t=this.quoteID,n=ft().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,latestEpoch:n.latestEpoch,cexProblems:n.cexProblems}:{botCfg:{},running:!1,runStats:{}}}},{key:"adjustedBalances",value:function(){var e,t,n=this.baseID,r=this.quoteID,a=this.baseFeeID,o=this.quoteFeeID,s=this.cexName,i=this.baseFactor,c=this.quoteFactor,l=this.baseFeeFactor,u=this.quoteFeeFactor,d=[ft().walletMap[n],ft().walletMap[r]],h=d[0],p=d[1],f=[Kn(n),Kn(r)],v=f[0],m=f[1],g=0,y=0;if(s){var b=ft().mmStatus.cexes[s];if(!b)throw Error("where's the cex status?");e=b.balances[n],t=b.balances[r]}e&&(g=(e.available||0)-v.cex.avail),t&&(y=(t.available||0)-m.cex.avail);var x=h.balance.available-v.dex.avail,k=p.balance.available-m.dex.avail,w=x+g,C=k+y,S=a===n?h:ft().walletMap[a],F=o===r?p:ft().walletMap[o],T=w,D=x,I=g;if(a!==n){var A=Kn(n);D=S.balance.available-A.dex.total,e&&(I=(e.available||0)-A.cex.total),T=D+I}var R=C,E=k,B=y;if(o!==r){var P=Kn(r);E=F.balance.available-P.dex.total,t&&(B=(t.available||0)-P.cex.total),R=E+B}return{baseAvail:w/i,quoteAvail:C/c,dexBaseAvail:x/i,dexQuoteAvail:k/c,cexBaseAvail:g/i,cexQuoteAvail:y/c,baseFeeAvail:T/l,quoteFeeAvail:R/u,dexBaseFeeAvail:D/l,dexQuoteFeeAvail:E/u,cexBaseFeeAvail:I/l,cexQuoteFeeAvail:B/u}}},{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 ir(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],C=x[2];r===o?k+=t.bookingFees:C+=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 S=[n.book,n.cex,0,0],F=S[0],T=S[1],D=S[2],I=S[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>=C,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:C,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}(),ar=function(){function e(t,n,r,a){var o=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),h(this,"currentForm",void 0),h(this,"forms",void 0),h(this,"latestEpoch",void 0),h(this,"cexProblems",void 0),h(this,"orderReportFormEl",void 0),h(this,"orderReportForm",void 0),h(this,"displayedOrderReportFormSide",void 0),h(this,"dexBalancesRowTmpl",void 0),h(this,"placementRowTmpl",void 0),h(this,"placementAmtRowTmpl",void 0),this.div=t,this.page=Ne.parseTemplate(t),this.orderReportFormEl=r.orderReportForm,this.orderReportForm=Ne.idDescendants(r.orderReportForm),this.dexBalancesRowTmpl=r.dexBalancesRowTmpl,this.placementRowTmpl=r.placementRowTmpl,this.placementAmtRowTmpl=r.placementAmtRowTmpl,Ne.cleanTemplates(this.dexBalancesRowTmpl,this.placementRowTmpl,this.placementAmtRowTmpl),this.forms=n,Ne.bind(this.page.stopBttn,"click",(function(){return o.stop()})),Ne.bind(this.page.runLogsBttn,"click",(function(){var e=o.mkt,t=e.baseID,n=e.quoteID,r=e.host,s=o.startTime;ft().loadPage("mmlogs",{baseID:t,quoteID:n,host:r,startTime:s,returnPage:a})})),Ne.bind(this.page.buyOrdersBttn,"click",(function(){return o.showOrderReport("buys")})),Ne.bind(this.page.sellOrdersBttn,"click",(function(){return o.showOrderReport("sells")}))}var t,n,o;return d(e,[{key:"stop",value:(o=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=ft().loading(t.stopBttn),e.next=4,Xn.stopBot({host:r,baseID:a,quoteID:o});case 4:s();case 5:case"end":return e.stop()}}),e,this)}))),function(){return o.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=ft().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 rr(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,C,S,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,C=u.baseFactor,S=u.quoteFactor,Qn(l,h,p,d),Ne.setVis(v!==h,c.baseFeeReservesBox),Ne.setVis(m!==p,c.quoteFeeReservesBox),Ne.setVis.apply(Ne,[Boolean(g)].concat(r(Ne.applySelector(l,"[data-cex-show]")))),c.baseFeeLogo.src=Ne.logoPath(y),c.baseFeeTicker.textContent=x,c.quoteFeeLogo.src=Ne.logoPath(b),c.quoteFeeTicker.textContent=k,F=w.basicMarketMakingConfig,T=null!==(n=null==F?void 0:F.gapStrategy)&&void 0!==n?n:Un,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),Ne.hide(c.profitLabel,c.gapLabel,c.multiplierLabel,c.profitUnit,c.gapUnit,c.multiplierUnit),e.t0=T,e.next=e.t0===Un||e.t0===_n?18:e.t0===Nn?21:24;break;case 18:return Ne.show(c.profitLabel,c.profitUnit),c.gapFactor.textContent=(100*D).toFixed(2),e.abrupt("break",25);case 21:return Ne.show(c.multiplierLabel,c.multiplierUnit),c.gapFactor.textContent=(100*D).toFixed(2),e.abrupt("break",25);case 24:c.gapFactor.textContent=Ne.formatFourSigFigs(D/Ft*C/S);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:"handleEpochReportNote",value:function(e){if(this.mkt){var t=this.mkt,n=t.baseID,r=t.quoteID,a=t.host;if(e.baseID===n&&e.quoteID===r&&e.host===a&&e.report){if(this.latestEpoch=e.report,this.forms.currentForm===this.orderReportFormEl&&this.forms.currentFormID===this.mkt.id){var o="buys"===this.displayedOrderReportFormSide?e.report.buysReport:e.report.sellsReport;o?this.updateOrderReport(o,this.displayedOrderReportFormSide,e.report.epochNum):this.forms.close()}this.update()}}}},{key:"handleCexProblemsNote",value:function(e){if(this.mkt){var t=this.mkt,n=t.baseID,r=t.quoteID,a=t.host;e.baseID===n&&e.quoteID===r&&e.host===a&&(this.cexProblems=e.problems,this.update())}}},{key:"setTicker",value:function(){this.page.runTime.textContent=Ne.hmsSince(this.startTime)}},{key:"update",value:function(){var e,t,n,r=this,o=this.div,s=this.page,i=this.mkt,c=i.baseID,l=i.quoteID,u=i.baseFeeID,d=i.quoteFeeID,h=i.baseFactor,p=i.quoteFactor,f=i.baseFeeFactor,v=i.quoteFeeFactor,m=i.marketReport,g=m.baseFiatRate,y=m.quoteFiatRate,b=this.mkt.status(),x=b.botCfg,k=x.cexName,w=x.basicMarketMakingConfig,C=b.runStats,S=b.latestEpoch,F=b.cexProblems;if(this.latestEpoch=S,this.cexProblems=F,Ne.hide(s.stats,s.cexRow,s.pendingDepositBox,s.pendingWithdrawalBox),C){this.ticker||(this.startTime=C.startTime,this.setTicker(),this.ticker=setInterval((function(){return r.setTicker()}),1e3)),Ne.show(s.stats),sr(100*C.profitLoss.profitRatio,s.profit,s.profitSign,2),sr(C.profitLoss.profit,s.profitLoss,s.plSign,2),this.startTime=C.startTime;var T=function(e){return e?e.available+e.locked+e.pending+e.reserved:0},D=T(C.dexBalances[c])/h;s.walletBaseInventory.textContent=Ne.formatFourSigFigs(D),s.walletBaseInvFiat.textContent=Ne.formatFourSigFigs(D*g,2);var I=T(C.dexBalances[l])/p;if(s.walletQuoteInventory.textContent=Ne.formatFourSigFigs(I),s.walletQuoteInvFiat.textContent=Ne.formatFourSigFigs(I*y,2),Ne.setVis(k,s.cexRow),k){Ne.show(s.pendingDepositBox,s.pendingWithdrawalBox),Yn(o,k);var A=T(C.cexBalances[c])/h;s.cexBaseInventory.textContent=Ne.formatFourSigFigs(A),s.cexBaseInventoryFiat.textContent=Ne.formatFourSigFigs(A*g,2);var R=T(C.cexBalances[l])/p;s.cexQuoteInventory.textContent=Ne.formatFourSigFigs(R),s.cexQuoteInventoryFiat.textContent=Ne.formatFourSigFigs(R*y,2)}if(u!==c){var E=T(C.dexBalances[u])/f;s.baseFeeReserves.textContent=Ne.formatFourSigFigs(E)}if(d!==l){var B=T(C.dexBalances[d])/v;s.quoteFeeReserves.textContent=Ne.formatFourSigFigs(B)}s.pendingDeposits.textContent=String(Math.round(C.pendingDeposits)),s.pendingWithdrawals.textContent=String(Math.round(C.pendingWithdrawals)),s.completedMatches.textContent=String(Math.round(C.completedMatches)),Ne.setVis(C.tradedUSD,s.tradedUSDBox),C.tradedUSD>0&&(s.tradedUSD.textContent=Ne.formatFourSigFigs(C.tradedUSD)),Ne.setVis(g,s.roundTripFeesBox),g&&(s.roundTripFeesUSD.textContent=Ne.formatFourSigFigs((null===(e=C.feeGap)||void 0===e?void 0:e.roundTripFees)/h*g||0));var P=ft().conventionalRate(c,l,(null===(t=C.feeGap)||void 0===t?void 0:t.basisPrice)||0);s.basisPrice.textContent=Ne.formatFourSigFigs(P);var L=!w||w.gapStrategy===Vn||w.gapStrategy===_n;if(Ne.setVis(L,s.feeGapBox),L){var O,M=ft().conventionalRate(c,l,(null===(O=C.feeGap)||void 0===O?void 0:O.feeGap)||0);s.feeGap.textContent=Ne.formatFourSigFigs(M),s.feeGapPct.textContent=(M/P*100||0).toFixed(2)}Ne.setVis(w,s.gapStrategyBox),w&&(s.gapStrategy.textContent=w.gapStrategy);var q=ft().conventionalRate(c,l,(null===(n=C.feeGap)||void 0===n?void 0:n.remoteGap)||0);if(Ne.setVis(q,s.remoteGapBox),q&&(s.remoteGap.textContent=Ne.formatFourSigFigs(q),s.remoteGapPct.textContent=(q/P*100||0).toFixed(2)),Ne.setVis(null==S?void 0:S.buysReport,s.buyOrdersReportBox),null!=S&&S.buysReport){var N=or(S.buysReport);Ne.setVis(N,s.buyOrdersSuccess),Ne.setVis(!N,s.buyOrdersFailed)}if(Ne.setVis(null==S?void 0:S.sellsReport,s.sellOrdersReportBox),null!=S&&S.sellsReport){var W=or(S.sellsReport);Ne.setVis(W,s.sellOrdersSuccess),Ne.setVis(!W,s.sellOrdersFailed)}var V=cr(null==S?void 0:S.preOrderProblems,this.mkt.cexName,this.mkt.host),U=function(e){if(!e)return[];var t=[];if(e.depositErr)for(var n=0,r=Object.entries(e.depositErr);n0,s.preOrderProblemsBox),Ne.empty(s.preOrderProblemsBox);var j,H=Mn(_);try{for(H.s();!(j=H.n()).done;){var z=j.value,G=document.createElement("span");G.textContent="- ".concat(z),s.preOrderProblemsBox.appendChild(G)}}catch(e){H.e(e)}finally{H.f()}}else this.ticker&&(clearInterval(this.ticker),this.ticker=void 0)}},{key:"updateOrderReport",value:function(e,t,n){var r=this,o=this.orderReportForm,s=ke("buys"===t?E:B);if(o.orderReportTitle.textContent=ke("ORDER_REPORT_TITLE",{side:s,epochNum:"".concat(n)}),Ne.setVis(e.error,o.orderReportError),Ne.setVis(!e.error,o.orderReportDetails),e.error){var i=cr(e.error,this.mkt.cexName,this.mkt.host);Ne.empty(o.orderReportError);for(var c=0,l=i;c0&&a.deficiency.classList.add("text-warning");var f=lr(p,u);return a.deficiencyWithPending.textContent=Ne.formatCoinValue(f,s),f>0&&a.deficiencyWithPending.classList.add("text-warning"),[n,p]},p=[this.mkt.baseID,this.mkt.quoteID];p.includes(this.mkt.baseFeeID)||p.push(this.mkt.baseFeeID),p.includes(this.mkt.quoteFeeID)||p.push(this.mkt.quoteFeeID);for(var f,v=0,m=[],g=0,y=p;g0,m),Ne.setVis(this.mkt.cexName,o.cexSection,o.counterTradeRateHeader,o.requiredCEXHeader,o.usedCEXHeader),this.mkt.cexName){var k=Gn[this.mkt.cexName];k?(o.cexLogo.src=k.logo,o.cexBalancesTitle.textContent=ke("CEX_BALANCES",{cexName:k.name})):console.error("CEXDisplayInfo not found for ".concat(this.mkt.cexName));var w="buys"===t?this.mkt.baseID:this.mkt.quoteID;f=ft().assets[w],o.cexAsset.textContent=f.symbol.toUpperCase(),o.cexAssetLogo.src=Ne.logoPath(f.symbol);var C=e.availableCexBal?e.availableCexBal.available:0,S=e.requiredCexBal?e.requiredCexBal:0,F=e.remainingCexBal?e.remainingCexBal:0,T=e.availableCexBal?e.availableCexBal.pending:0,D=e.availableCexBal?e.availableCexBal.reserved:0,I=e.usedCexBal?e.usedCexBal:0,A=lr(S,C),R=lr(A,T);o.cexAvailable.textContent=Ne.formatCoinValue(C,f.unitInfo),o.cexLocked.textContent=Ne.formatCoinValue(D,f.unitInfo),o.cexRequired.textContent=Ne.formatCoinValue(S,f.unitInfo),o.cexRemaining.textContent=Ne.formatCoinValue(F,f.unitInfo),o.cexPending.textContent=Ne.formatCoinValue(T,f.unitInfo),o.cexUsed.textContent=Ne.formatCoinValue(I,f.unitInfo);var P=A>0;Ne.setVis(P,o.cexDeficiencyHeader,o.cexDeficiencyWithPendingHeader,o.cexDeficiency,o.cexDeficiencyWithPending),P&&(o.cexDeficiency.textContent=Ne.formatCoinValue(A,f.unitInfo),o.cexDeficiencyWithPending.textContent=Ne.formatCoinValue(R,f.unitInfo),R>0?o.cexDeficiencyWithPending.classList.add("text-warning"):o.cexDeficiencyWithPending.classList.remove("text-warning"))}var L,O=!1,M=Mn(e.placements);try{for(M.s();!(L=M.n()).done;)if(L.value.error){O=!0;break}}catch(e){M.e(e)}finally{M.f()}Ne.setVis(O,o.errorHeader);for(var q=function(e,t){var n=r.placementRowTmpl.cloneNode(!0),a=Ne.parseTemplate(n),o=ft().assets[r.mkt.baseID].unitInfo,s=ft().assets[r.mkt.quoteID].unitInfo;a.priority.textContent=String(t),a.rate.textContent=Ne.formatRateFullPrecision(e.rate,o,s,r.mkt.rateStep),a.lots.textContent=String(e.lots),a.standingLots.textContent=String(e.standingLots),a.orderedLots.textContent=String(e.orderedLots),e.standingLots+e.orderedLots0,a.counterTradeRate),a.counterTradeRate.textContent=Ne.formatRateFullPrecision(e.counterTradeRate,o,s,r.mkt.rateStep);for(var i=0,c=p;i0),n.classList.toggle("text-good",e>0)}function ir(e,t,n,r,a,o,s,i,c,l,u,d,h){var p=Jn(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,C=g*o*k,S=m*s*w,F=x*s*w,T=b*o*k;return{commit:f,fees:{base:On(On({},n),{},{bookingFeesPerLot:g,bookingFeesPerCounterLot:m,bookingFees:C+S,swapReservesFactor:k,redeemReservesFactor:w,tokenFeesPerSwap:v}),quote:On(On({},r),{},{bookingFeesPerLot:x,bookingFeesPerCounterLot:b,bookingFees:F+T,swapReservesFactor:w,redeemReservesFactor:k,tokenFeesPerSwap:y})}}}function cr(e,t,n){if(!e)return[];var r=[];if(e.walletNotSynced)for(var o=0,s=Object.entries(e.walletNotSynced);o0?e-t:0}function ur(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 dr(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)?dr(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 dr(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n1)){e.next=34;break}Ne.show(r),u=ur(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),Ne.bind(a,"click",(function(){var e,n=ur(Ne.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:ft().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=ft().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=ft().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,Ne.hide(n.walletPassAndSubmitBttn,n.oneBttnBox,n.newWalletPassBox),a=t.guidelink,(o=t.configopts||[]).map((function(e){return e.isBirthdayConfig&&ft().seedGenTime>0&&(e.default=Pr(new Date)),e})),s=!1,i=ur(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?(Ne.hide(n.walletSettingsHeader),Ne.show(n.oneBttnBox)):p?(Ne.show(n.walletPassAndSubmitBttn,n.walletSettingsHeader),n.newWalletPass.value="",n.submitAdd.textContent=ke("CREATE")):(Ne.show(n.walletPassAndSubmitBttn,n.walletSettingsHeader),t.noauth||Ne.show(n.newWalletPassBox),n.submitAdd.textContent=ke("ADD")),d){v=JSON.parse(JSON.stringify(o)),m=ur(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=ur(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)?Ne.hide(this.subform.fileSelector):Ne.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){Ne.hide(this.walletCfgGuide),""!==e&&(this.walletCfgGuide.href=e,Ne.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,Ne.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=ft().loading(this.form),e.next=11,S("/api/defaultwalletcfg",{assetID:o,type:a.type});case 11:if(i=e.sent,s(),ft().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}(),fr=0,vr=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=Ne.idDescendants(t),this.form=t,this.configElements=[],this.configOpts=[],this.sectionize=n,this.allSettings=Ne.tmplElement(t,"allSettings"),this.dynamicOpts=Ne.tmplElement(t,"dynamicOpts"),this.textInputTmpl=Ne.tmplElement(t,"textInput"),this.textInputTmpl.remove(),this.dateInputTmpl=Ne.tmplElement(t,"dateInput"),this.dateInputTmpl.remove(),this.checkboxTmpl=Ne.tmplElement(t,"checkbox"),this.checkboxTmpl.remove(),this.repeatableTmpl=Ne.tmplElement(t,"repeatableInput"),this.repeatableTmpl.remove(),this.fileSelector=Ne.tmplElement(t,"fileSelector"),this.fileInput=Ne.tmplElement(t,"fileInput"),this.errMsg=Ne.tmplElement(t,"errMsg"),this.showOther=Ne.tmplElement(t,"showOther"),this.showIcon=Ne.tmplElement(t,"showIcon"),this.hideIcon=Ne.tmplElement(t,"hideIcon"),this.showHideMsg=Ne.tmplElement(t,"showHideMsg"),this.otherSettings=Ne.tmplElement(t,"otherSettings"),this.loadedSettingsMsg=Ne.tmplElement(t,"loadedSettingsMsg"),this.loadedSettings=Ne.tmplElement(t,"loadedSettings"),this.defaultSettingsMsg=Ne.tmplElement(t,"defaultSettingsMsg"),this.defaultSettings=Ne.tmplElement(t,"defaultSettings"),n||Ne.hide(this.showOther),Ne.bind(this.fileSelector,"click",(function(){return r.fileInput.click()})),Ne.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)})))),Ne.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(Ne.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=ft().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,S("/api/parseconfig",{configtext:o});case 14:if(s=e.sent,a(),ft().checkResponse(s)){e.next=20;break}return this.errMsg.textContent=s.msg,Ne.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])&&Ne.hide(this.loadedSettings,this.loadedSettingsMsg),0===l&&Ne.hide(this.defaultSettings,this.defaultSettingsMsg),c+l===0&&Ne.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"),Ne.bind(Ne.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=ft().extensionWallet(this.assetID))||void 0===a?void 0:a.hiddenFields)||[]).indexOf(t.key)&&Ne.hide(o),this.configElements.push([t,o]);var c=o.querySelector("input");c.dataset.configKey=t.key,fr++;var l="wcfg-"+String(fr);c.id=l;var u=Ne.safeSelector(o,"label");if(u.htmlFor=l,u.prepend(t.displayname),void 0!==t.regAsset){var d=new window.Image(15,15);d.src=Ne.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?Lr("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=Lr(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,Ne.empty(this.dynamicOpts,this.defaultSettings,this.loadedSettings),0===this.configOpts.length)return Ne.hide(this.form);Ne.show(this.form),this.setOtherSettingsViz(!1),Ne.hide(this.loadedSettingsMsg,this.loadedSettings,this.defaultSettingsMsg,this.defaultSettings,this.errMsg);var r,a=[],o=ur(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=ur(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()}Ne.show(this.showOther,this.defaultSettingsMsg,this.defaultSettings)}else Ne.hide(this.showOther);ft().bindTooltips(this.allSettings),this.dynamicOpts.children.length?Ne.show(this.dynamicOpts):Ne.hide(this.dynamicOpts)}},{key:"setOtherSettingsViz",value:function(e){if(e)return Ne.hide(this.showIcon),Ne.show(this.hideIcon,this.otherSettings),void(this.showHideMsg.textContent=ke("HIDE_ADDITIONAL_SETTINGS"));Ne.hide(this.hideIcon,this.otherSettings),Ne.show(this.showIcon),this.showHideMsg.textContent=ke("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(C,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),Ne.show(this.loadedSettings,this.loadedSettingsMsg),0===this.defaultSettings.children.length&&Ne.hide(this.defaultSettings,this.defaultSettingsMsg))}},{key:"map",value:function(e){var t,n={},r=ur(this.configElements);try{for(r.s();!(t=r.n()).done;){var o=a(t.value,2),s=o[0],i=o[1],c=Ne.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?Pr(new Date(c.min+"T00:00")):Number.MIN_SAFE_INTEGER,u=c.max?Pr(new Date(c.max+"T00:00")):Number.MAX_SAFE_INTEGER,d=c.value?Pr(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=ur(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=ur(this.configOpts);try{for(o.s();!(r=o.n()).done;){var s,i=r.value,c=ur(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}(),mr=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=Ne.parseTemplate(t),this.certFile="",Ne.bind(this.page.goBack,"click",(function(){return r()})),Br(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=ft().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=Ne.logoPath(r.symbol),i.bondLock.textContent=Ne.formatFourSigFigs(c),i.bondUnit.textContent=s;var l=ft().fiatRatesMap[e];Ne.show(i.bondLockUSDBox),l?i.bondLockUSD.textContent=Ne.formatFourSigFigs(c*l):Ne.hide(i.bondLockUSDBox),n&&(i.feeReserves.textContent=Ne.formatFourSigFigs(n/o)),i.reservesUnit.textContent=s}},{key:"setFees",value:function(e,t){this.fees=t;var n=ft().assets[e].unitInfo.conventional.conversionFactor;this.page.feeReserves.textContent=Ne.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,Ne.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=ft().assets[n]){e.next=6;break}return t.regErr.innerText=ke("SELECT_WALLET_FOR_FEE_PAYMENT"),Ne.show(t.regErr),e.abrupt("return");case 6:return Ne.hide(t.regErr),i=r.bondAssets[s.wallet.symbol],c=r.host,!ft().exchanges[r.host]||ft().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=ft().loading(this.form),e.next=13,S(u,l);case 13:if(h=e.sent,d(),ft().checkResponse(h)){e.next=19;break}return t.regErr.textContent=h.msg,Ne.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}(),gr=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=Ne.parseTemplate(t);Ne.cleanTemplates(a.currentBondTmpl,a.bondAssetTmpl,a.marketTmpl),Ne.bind(a.tradingTierInput,"input",(function(){r.setTier()})),Ne.bind(a.tradingTierInput,"keyup",(function(e){"Enter"===e.key&&r.acceptTier()})),Ne.bind(a.submitTradingTier,"click",(function(){r.acceptTier()})),Ne.bind(a.tierUp,"click",(function(){r.incrementTier(!0)})),Ne.bind(a.tierDown,"click",(function(){r.incrementTier(!1)})),Ne.bind(a.goBackToAssets,"click",(function(){Ne.hide(a.tradingTierForm),Ne.show(a.assetForm)})),Ne.bind(a.whatsABond,"click",(function(){Ne.hide(a.assetForm),Ne.show(a.whatsABondPanel)}));var o=function(){Ne.show(a.assetForm),Ne.hide(a.whatsABondPanel)};Ne.bind(a.bondGotIt,"click",(function(){o()})),Ne.bind(a.whatsABondBack,"click",(function(){o()})),Ne.bind(a.usePrepaidBond,"click",(function(){r.showPrepaidBondForm()})),Ne.bind(a.ppbGoBack,"click",(function(){r.hidePrepaidBondForm()})),Ne.bind(a.submitPrepaidBond,"click",(function(){r.submitPrepaidBond()})),ft().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,Ne.show(this.page.tradingTierErr)}},{key:"setAssetError",value:function(e){this.page.regAssetErr.textContent=e,Ne.show(this.page.regAssetErr)}},{key:"clearErrors",value:function(){Ne.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;Ne.hide(r.assetForm,r.tradingTierForm,r.whatsABondPanel,r.prepaidBonds),Ne.empty(r.bondAssets,r.markets),this.clearErrors();for(var a=function(e,t){var a=ft().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=Ne.parseTemplate(u);d.logo.src=Ne.logoPath(l),d.name.textContent=c,Ne.bind(u,"click",(function(){n.assetSelected(e)})),d.feeSymbol.textContent=s;var h=t.amount/i;d.feeAmt.textContent=Ne.formatFourSigFigs(h);var p=ft().fiatRatesMap[e];Ne.setVis(p,d.fiatBox),p&&(d.fiatBondAmount.textContent=Ne.formatFourSigFigs(h*p)),n.assetRows[e]={ready:d.ready}}},o=function(t){var a=t.baseid,o=t.quoteid,s=[ft().assets[a],ft().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=ur(Ne.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=ur(Ne.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=Ne.parseTemplate(i);y.baseLogo.src=Ne.logoPath(u),y.quoteLogo.src=Ne.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*3*e;y.tradeLimitLow.textContent=Ne.formatFourSigFigs(s),y.tradeLimitHigh.textContent=Ne.formatFourSigFigs(i);var c=ft().fiatRatesMap[a];c&&(y.fiatTradeLimitLow.textContent=Ne.formatFourSigFigs(s*c),y.fiatTradeLimitHigh.textContent=Ne.formatFourSigFigs(i*c)),Ne.setVis(c,r.fiatTradeLowBox,r.fiatTradeHighBox)};b(dn(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(Ne.setVis(R,t.currentBondBox),R){Ne.empty(t.currentBonds);for(var E=0,B=Object.entries(w);E0){Ne.show(r.bondCostBreakdown),r.bondLockNoFees.textContent=Ne.formatCoinValue(g,s),r.bondLockFees.textContent=Ne.formatCoinValue(t,s),g+=t;var y=Math.max(g-c.available+c.reservesDeficit,0);if(r.totalForBond.textContent=Ne.formatCoinValue(y,s),Ne.hide(r.sendEnough),Ne.hide(r.txFeeBox,r.sendEnoughForToken,r.txFeeBalanceBox),Ne.hide(r.sendEnoughWithEst),h){Ne.show(r.txFeeBox,r.sendEnoughForToken,r.txFeeBalanceBox);var b=ft().assets[h.parentID];r.txFee.textContent=Ne.formatCoinValue(t,b.unitInfo),r.parentFees.textContent=Ne.formatCoinValue(t,b.unitInfo),r.tokenFees.textContent=Ne.formatCoinValue(y,s),v(r.txFeeUnit,b),v(r.parentUnit,b),v(r.parentBalUnit,b),r.parentBal.textContent=b.wallet?Ne.formatCoinValue(b.wallet.balance.available,b.unitInfo):"0"}else Ne.show(r.sendEnoughWithEst);r.fee.textContent=Ne.formatCoinValue(g,s)}else Ne.show(r.sendEnough);Ne.show(u?r.syncCheck:d>=1?r.syncSpinner:r.syncUncheck),Ne.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=ft().assets[this.assetID],r=n.wallet.balance.available;if(t.balance.textContent=Ne.formatCoinValue(r,n.unitInfo),n.token){var a=ft().assets[n.token.parentID],o=a.wallet.balance.available;if(t.parentBal.textContent=Ne.formatCoinValue(o,a.unitInfo),o=.999)return Ne.hide(n.syncRemaining),Ne.show(n.syncFinishingUp),Ne.show(n.syncRemainBox),void(n.syncFinishingUp.textContent=ke("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){Ne.hide(n.syncFinishingUp),Ne.show(n.syncRemaining),Ne.show(n.syncRemainBox);var c=i/(s.stamp-o.stamp),l=(1-s.progress)/c;n.syncRemain.textContent=Ne.formatDuration(l)}}}}]),e}(),br=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=Ne.idDescendants(t);Ne.bind(a.accelerateSubmit,"click",(function(){r.submit()})),Ne.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?(Ne.show(e.recentAccelerationMsg),Ne.hide(e.recentSwapMsg),e.recentAccelerationTime.textContent="".concat(Math.floor(this.earlyAcceleration.timePast/60))):(Ne.show(e.recentSwapMsg),Ne.hide(e.recentAccelerationMsg),e.recentSwapTime.textContent="".concat(Math.floor(this.earlyAcceleration.timePast/60))),Ne.hide(e.configureAccelerationDiv,e.accelerateErr),Ne.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=ft().loading(n.accelerateMainDiv),e.next=6,S("/api/accelerateorder",r);case 6:o=e.sent,a(),ft().checkResponse(o)?(n.accelerateTxID.textContent=o.txID,Ne.hide(n.accelerateMainDiv,n.preAccelerateErr,n.accelerateErr),Ne.show(n.accelerateMsgDiv,n.accelerateSuccess),this.success()):(n.accelerateErr.textContent=ke(Z,{msg:o.msg}),Ne.hide(n.earlyAccelerationDiv),Ne.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,S("/api/preaccelerate",t.id);case 4:if(r=e.sent,ft().checkResponse(r)){e.next=10;break}return n.preAccelerateErr.textContent=ke(Z,{msg:r.msg}),Ne.hide(n.accelerateMainDiv,n.accelerateSuccess),Ne.show(n.accelerateMsgDiv,n.preAccelerateErr),e.abrupt("return");case 10:Ne.hide(n.accelerateMsgDiv,n.preAccelerateErr,n.accelerateErr,n.feeEstimateDiv,n.earlyAccelerationDiv),Ne.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 kt(a.suggestedRange,a.suggestedRange.start.x,{updated:s,changed:function(){return c.updateAccelerationEstimate()},selected:o,roundY:!0}),Ne.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=ft().loading(t.sliderContainer),e.next=6,S("/api/accelerationestimate",r);case 6:if(o=e.sent,a(),ft().checkResponse(o)){e.next=12;break}return t.accelerateErr.textContent=ke("ORDER_ACCELERATION_FEE_ERR_MSG",{msg:o.msg}),Ne.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=ft().unitInfo(s),t.feeEstimate.textContent="".concat(o.fee/c.conventional.conversionFactor," ").concat(i),Ne.show(t.feeEstimateDiv);case 17:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})}]),e}(),xr=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=Ne.parseTemplate(t);this.certPicker=new Fr(t),Ne.bind(o.skipRegistration,"change",(function(){return a.showOrHideSubmitBttn()})),Ne.bind(o.showCustom,"click",(function(){Ne.hide(o.showCustom),Ne.show(o.customBox,o.auth)})),this.knownExchanges=Array.from(o.knownXCs.querySelectorAll(".known-exchange"));var s,c=ur(this.knownExchanges);try{var l=function(){var e=s.value;Ne.bind(e,"click",(function(){var t,n=e.dataset.host,r=ur(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()}Br(t,o.submit,(function(){return a.checkDEX()})),r&&(Ne.hide(o.addDexHdr,o.skipRegistrationBox),Ne.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(),Ne.hide(e.err),0===this.knownExchanges.length||this.dexToUpdate?(Ne.show(e.customBox,e.auth),Ne.hide(e.showCustom,e.knownXCs,e.pickServerMsg,e.addCustomMsg)):(Ne.hide(e.customBox),Ne.show(e.showCustom));var t,n=ur(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;Ne.setVis(Ne.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,Ne.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,Ne.hide(n.err),""!==(t=t||n.addr.value)){e.next=7;break}return n.err.textContent=ke("EMPTY_DEX_ADDRESS_MSG"),Ne.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=ft().loading(this.form),e.next=15,S(o,s);case 15:if(c=e.sent,i(),ft().checkResponse(c)){e.next=20;break}return String(c.msg).includes("certificate required")?Ne.show(n.needCert):(n.err.textContent=c.msg,Ne.show(n.err)),e.abrupt("return");case 20:return e.next=22,ft().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,ft().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}(),kr=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=Ne.parseTemplate(t);o.dexHost.textContent=n,Br(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,Ne.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,Ne.hide(t.err),n={addr:this.addr},r=ft().loading(this.form),e.next=6,S("/api/discoveracct",n);case 6:if(a=e.sent,r(),ft().checkResponse(a)){e.next=12;break}return t.err.textContent=a.msg,Ne.show(t.err),e.abrupt("return");case 12:if(!a.paid){e.next=18;break}return e.next=15,ft().fetchUser();case 15:return e.next=17,ft().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}(),wr=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,Br(t,(this.page=Ne.parseTemplate(t)).submit,(function(){r.submit()})),ft().registerNoteFeeder({login:function(e){r.handleLoginNote(e)}})}var t,n;return d(e,[{key:"handleLoginNote",value:function(e){if(""!==e.details){var t=Ne.idel(this.form,"loaderMsg");Ne.show(t),t&&(t.textContent=e.details)}}},{key:"focus",value:function(){this.page.pw.focus()}},{key:"refresh",value:function(){Ne.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,Ne.hide(t.errMsg),""!==(n=t.pw.value||"")){e.next=6;break}return Ne.showFormError(t.errMsg,ke(R)),e.abrupt("return");case 6:return r=ft().loading(this.form),e.next=9,S("/api/login",{pass:n});case 9:if(a=e.sent,r(),t.pw.value="",ft().checkResponse(a)){e.next=15;break}return Ne.showFormError(t.errMsg,a.msg),e.abrupt("return");case 15:return e.next=17,ft().fetchUser();case 17:a.notes=a.notes||[],a.notes.reverse(),a.pokes=a.pokes||[],ft().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,Ne.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}(),Cr=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=Ne.idDescendants(t);Ne.cleanTemplates(r.unifiedReceiverTmpl),Ne.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)})))),Ne.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,Ne.hide(n.depositErr,n.depositTokenMsgBox),r=ft().assets[t],n.depositLogo.src=Ne.logoPath(r.symbol),a=ft().walletMap[t],n.depositName.textContent=r.unitInfo.conventional.unit,r.token&&(o=ft().assets[r.token.parentID],n.depositTokenParentLogo.src=Ne.logoPath(o.symbol),n.depositTokenParentName.textContent=o.name,Ne.show(n.depositTokenMsgBox)),Ne.setVis(!!(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(Ne.hide(n.unifiedReceivers),e.startsWith("unified:")){var r=JSON.parse(e.substring(8));Ne.empty(n.unifiedReceivers),Ne.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"),Ne.bind(c,"click",(function(){for(var e=0,a=Array.from(n.unifiedReceivers.children);e=r?Ne.hide(t.addressBox):Ne.hide(t.errMsg))}}]),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,"updated",void 0),h(this,"cexName",void 0),this.form=t,this.updated=n,this.page=Ne.parseTemplate(t),Ne.bind(this.page.cexSubmit,"click",(function(){return r.submit()}))}var t;return d(e,[{key:"setCEX",value:function(e){this.cexName=e,Yn(this.form,e);var t=this.page;Ne.hide(t.cexConfigPrompt,t.cexConnectErrBox,t.cexFormErr),t.cexApiKeyInput.value="",t.cexSecretInput.value="";var n=ft().mmStatus.cexes[e],r=null==n?void 0:n.connectErr;r?(Ne.show(t.cexConnectErrBox),t.cexConnectErr.textContent=r,t.cexApiKeyInput.value=n.config.apiKey,t.cexSecretInput.value=n.config.apiSecret):Ne.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,Ne.hide(t.cexFormErr),a=t.cexApiKeyInput.value,o=t.cexSecretInput.value,a&&o){e.next=8;break}return Ne.show(t.cexFormErr),t.cexFormErr.textContent=ke(R),e.abrupt("return");case 8:return s=ft().loading(r),e.prev=9,e.next=12,Xn.updateCEXConfig({name:n,apiKey:a,apiSecret:o});case 12:if(i=e.sent,ft().checkResponse(i)){e.next=15;break}throw i;case 15:this.updated(n,!0),e.next=23;break;case 18:e.prev=18,e.t0=e.catch(9),Ne.show(t.cexFormErr),t.cexFormErr.textContent=ke(H,{msg:null!==(c=e.t0.msg)&&void 0!==c?c:String(e.t0)}),this.updated(n,!1);case 23:return e.prev=23,s(),e.finish(23);case 26:case"end":return e.stop()}}),e,this,[[9,18,23,26]])}))),function(){return t.apply(this,arguments)})}]),e}(),Ir=300;function Ar(e,t){return Rr.apply(this,arguments)}function Rr(){return(Rr=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,Ne.animate(Ir,(function(e){t.style.right="".concat(e*r,"px")}),"easeInHard");case 3:return Ne.hide(t),t.style.right="0",n.style.right=String(-r),Ne.show(n),n.querySelector("input")&&Ne.safeSelector(n,"input").focus(),e.next=10,Ne.animate(Ir,(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 Er(e,t){e.successMessage.textContent=t,Ne.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 We(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 Br(e,t,n){var r=function(e){e.preventDefault&&e.preventDefault(),n(e)};Ne.bind(t,"click",r),Ne.bind(e,"submit",r)}function Pr(e){return Math.floor(e.getTime()/1e3)}function Lr(e){return function(e){return new Date(e.getTime()-60*e.getTimezoneOffset()*1e3)}(e).toISOString().split("T")[0]}function Or(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&&Ne.hide(c)}}catch(e){o.e(e)}finally{o.f()}n.newWalletForm=new pr(r.newWalletForm,(function(e){return n.newWalletCreated(e,n.confirmRegisterForm.tier)}),(function(){return n.animateRegAsset(r.newWalletForm)})),n.dexAddrForm=new xr(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 kr(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 gr(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!==pt){e.next=3;break}return n.registerDEXSuccess(),e.abrupt("return");case 3:if(o=ft().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),Ar(r.regAssetForm,r.walletWait),e.abrupt("return");case 17:n.confirmRegisterForm.tier=a,n.newWalletForm.setAsset(t),Ar(r.regAssetForm,r.newWalletForm);case 20:case"end":return e.stop()}}),e)})));return function(t,n){return e.apply(this,arguments)}}()),n.walletWaitForm=new yr(r.walletWait,(function(){n.animateConfirmForm(r.walletWait)}),(function(){n.animateRegAsset(r.walletWait)})),n.confirmRegisterForm=new mr(r.confirmRegForm,(function(){n.registerDEXSuccess()}),(function(){n.animateRegAsset(r.confirmRegForm)}));var u=Ne.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 Ne.show(u),u===r.discoverAcctForm&&n.discoverAcctForm.page.submit.click(),ft().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,ft().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:Ne.hide(t),this.regAssetForm.animate(),Ne.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(),Ne.hide(t),Ne.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=ft().loading(n),e.next=3,S("/api/bondsfeebuffer",{assetID:t});case 3:if(a=e.sent,r(),ft().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,ft().fetchUser();case 2:return ft().updateMenuItemsDisplay(),e.next=5,ft().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,ft().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,Ar(a.newWalletForm,a.walletWait);case 21:case"end":return e.stop()}}),e,this)}))),function(e,n){return t.apply(this,arguments)})}]),k}(lt);var qr=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=Ne.idDescendants(e);t.loginForm=new wr(n.loginForm,(function(){t.loggedIn()}));var r=function(){Ne.hide(n.resetAppPWForm),t.loginForm.refresh(),Ne.show(n.loginForm),t.loginForm.focus()};return r(),t.appPassResetForm=new Sr(n.resetAppPWForm,(function(){r()})),Ne.bind(n.forgotPassBtn,"click",(function(){t.appPassResetForm.refresh(),Ar(n.loginForm,n.resetAppPWForm)})),Ne.bind(n.resetPassFormCloser,"click",(function(){r()})),Ne.bind(n.forms,"mousedown",(function(e){!Ne.mouseInElement(e,n.resetAppPWForm)&&Ne.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,ft().loadPage("wallets");case 2:case"end":return e.stop()}}),e)}))),function(){return t.apply(this,arguments)})}]),o}(lt);function Nr(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 Wr(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)?Wr(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 Wr(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){Ne.bind(e,"click",(function(){n.closePopups()}))})),Ne.bind(r.cancelForce,"click",(function(){n.closePopups()})),n.selectedAssetID=-1,Ne.cleanTemplates(r.iconSelectTmpl,r.balanceDetailRow,r.recentOrderTmpl,r.vspRowTmpl,r.ticketHistoryRowTmpl,r.votingChoiceTmpl,r.votingAgendaTmpl,r.tspendTmpl,r.tkeyTmpl,r.txHistoryRowTmpl,r.txHistoryDateRowTmpl),Ne.bind(r.createWallet,"click",(function(){return n.showNewWallet(n.selectedAssetID)})),Ne.bind(r.connectBttn,"click",(function(){return n.doConnect(n.selectedAssetID)})),Ne.bind(r.send,"click",(function(){return n.showSendForm(n.selectedAssetID)})),Ne.bind(r.receive,"click",(function(){return n.showDeposit(n.selectedAssetID)})),Ne.bind(r.unlockBttn,"click",(function(){return n.openWallet(n.selectedAssetID)})),Ne.bind(r.lockBttn,"click",(function(){return n.lock(n.selectedAssetID)})),Ne.bind(r.reconfigureBttn,"click",(function(){return n.showReconfig(n.selectedAssetID)})),Ne.bind(r.needsProviderBttn,"click",(function(){return n.showReconfig(n.selectedAssetID)})),Ne.bind(r.rescanWallet,"click",(function(){return n.rescanWallet(n.selectedAssetID)})),Ne.bind(r.earlierTxs,"click",(function(){return n.loadEarlierTxs()})),Ne.bind(r.copyTxIDBtn,"click",(function(){var e;rt((null===(e=n.currTx)||void 0===e?void 0:e.id)||"",r.txDetailsID,r.copyTxIDBtn,"#1e7d11")})),Ne.bind(r.copyRecipientBtn,"click",(function(){var e;rt((null===(e=n.currTx)||void 0===e?void 0:e.recipient)||"",r.txDetailsRecipient,r.copyRecipientBtn,"#1e7d11")})),Ne.bind(r.copyBondIDBtn,"click",(function(){var e,t;rt((null===(e=n.currTx)||void 0===e||null===(t=e.bondInfo)||void 0===t?void 0:t.bondID)||"",r.txDetailsBondID,r.copyBondIDBtn,"#1e7d11")})),Ne.bind(r.copyBondAccountIDBtn,"click",(function(){var e,t;rt((null===(e=n.currTx)||void 0===e||null===(t=e.bondInfo)||void 0===t?void 0:t.accountID)||"",r.txDetailsBondAccountID,r.copyBondAccountIDBtn,"#1e7d11")})),Ne.bind(r.hideMixTxsCheckbox,"change",(function(){n.showTxHistory(n.selectedAssetID)})),n.newWalletForm=new pr(r.newWalletForm,(function(e){var t={assetName:ft().assets[e].name};n.assetUpdated(e,r.newWalletForm,ke("NEW_WALLET_SUCCESS",t)),n.sortAssetButtons(),n.updateTicketBuyer(e),n.updatePrivacy(e)})),n.reconfigForm=new vr(r.reconfigInputs,!1),n.walletCfgGuide=Ne.tmplElement(r.reconfigForm,"walletCfgGuide"),Br(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)})))),Br(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)})))),Br(r.reconfigForm,r.submitReconfig,(function(){return n.reconfig()})),r.forms.querySelectorAll(".form-closer").forEach((function(e){Ne.bind(e,"click",(function(){return n.closePopups()}))})),Ne.bind(r.forms,"mousedown",(function(e){Ne.mouseInElement(e,n.currentForm)||n.closePopups()})),n.mixerToggle=new _e(r.toggleMixer,r.mixingErr,!1,(function(e){return n.updateMixerState(e)})),n.keyup=function(e){"Escape"===e.key&&Ne.isDisplayed(n.page.forms)&&n.closePopups()},Ne.bind(document,"keyup",n.keyup),Ne.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)})))),Ne.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)})))),Ne.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)})))),Br(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)})))),Br(r.recoverWalletConfirm,r.recoverWalletSubmit,(function(){n.recoverWallet()})),Br(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)})))),Ne.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)})))),Ne.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)})))),Br(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)})))),Ne.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)})))),Ne.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)})))),Ne.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)})))),Ne.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)})))),Ne.bind(r.showVSPs,"click",(function(){n.showVSPPicker()})),Ne.bind(r.vspDisplay,"click",(function(){n.showVSPPicker()})),Br(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)})))),Ne.bind(r.purchaseTicketsBttn,"click",(function(){n.showPurchaseTicketsDialog()})),Br(r.purchaseTicketsForm,r.purchaserSubmit,(function(){n.purchaseTickets()})),Ne.bind(r.purchaserInput,"change",(function(){n.purchaserInputChanged()})),Ne.bind(r.ticketHistory,"click",(function(){n.showTicketHistory()})),Ne.bind(r.ticketHistoryNextPage,"click",(function(){n.nextTicketPage()})),Ne.bind(r.ticketHistoryPrevPage,"click",(function(){n.prevTicketPage()})),Ne.bind(r.setVotes,"click",(function(){n.showSetVotesDialog()})),Ne.bind(r.purchaseTicketsErrCloser,"click",(function(){Ne.hide(r.purchaseTicketsErrBox)})),Ne.bind(r.privacyInfoBttn,"click",(function(){n.showForm(r.mixingInfo)})),n.depositAddrForm=new Cr(r.deposit),Ne.bind(r.walletBal,"click",(function(){n.populateMaxSend()})),Ne.bind(r.sendAmt,"input",(function(){var e=ft().assets[n.selectedAssetID].unitInfo,t=tt(r.sendAmt.value),a=e.conventional.conversionFactor;Ne.showFiatValue(r.sendValue,t*a,ft().fiatRatesMap[n.selectedAssetID],e)})),Ne.bind(r.maxSend,"click",(function(){n.populateMaxSend()})),Ne.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=ft().assets[n.selectedAssetID],r.sendAddr.classList.remove("border-danger","border-success"),a=r.sendAddr.value||"",t&&""!==a){e.next=5;break}return e.abrupt("return");case 5:return e.next=7,n.validateSendAddress(a,t.id);case 7:e.sent?r.sendAddr.classList.add("border-success"):r.sendAddr.classList.add("border-danger");case 9:case"end":return e.stop()}}),e)})))),Ne.bind(r.showChangePW,"click",(function(){n.changeWalletPW=!n.changeWalletPW,n.setPWSettingViz(n.changeWalletPW)})),Ne.bind(r.changeWalletTypeSelect,"change",(function(){n.changeWalletType()})),Ne.bind(r.showChangeType,"click",(function(){Ne.isHidden(r.changeWalletType)?(Ne.show(r.changeWalletType,r.changeTypeHideIcon),Ne.hide(r.changeTypeShowIcon),r.changeTypeMsg.textContent=ke("KEEP_WALLET_TYPE")):n.showReconfig(n.selectedAssetID,{skipAnimation:!0})})),ft().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=Nr(n.page.txHistoryTableBody.children);try{for(t.s();!(e=t.n()).done;){var r=e.value,a=Ne.tmplElement(r,"age");a.textContent=Ne.timeSince(parseInt(a.dataset.timestamp))}}catch(e){t.e(e)}finally{t.f()}}),5e3),n}return d(ve,[{key:"closePopups",value:function(){Ne.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,S(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,C;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=this.page,Ne.hide(t.vSendErr,t.sendErr,t.vSendEstimates,t.txFeeNotAvailable),n=parseInt(t.sendForm.dataset.assetID||""),r=ft().assets[n].token,a=t.subtractCheckBox.checked||!1,o=ft().unitInfo(n).conventional.conversionFactor,s=Math.round(tt(t.sendAmt.value,0)*o),""!==(i=t.sendAddr.value||"")){e.next=10;break}return e.abrupt("return",Ne.showFormError(t.sendErr,ke(G,{address:i})));case 10:if(c=ft().assets[n],l=c.wallet,u=c.unitInfo,d=c.symbol,h=0,!(512&l.traits)){e.next=36;break}return p={addr:t.sendAddr.value,assetID:n,subtract:a,value:s},v=ft().loading(t.sendForm),e.next=17,S("/api/txfee",p);case 17:if(m=e.sent,v(),ft().checkResponse(m)){e.next=29;break}return t.txFeeNotAvailable.dataset.tooltip=ke("TXFEE_ERR_MSG",{err:m.msg}),Ne.show(t.txFeeNotAvailable),e.next=24,this.validateSendAddress(i,n);case 24:if(e.sent){e.next=27;break}return e.abrupt("return",Ne.showFormError(t.sendErr,ke(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",Ne.showFormError(t.sendErr,ke(G,{address:t.sendAddr.value||""})));case 32:h=m.txfee,Ne.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",Ne.showFormError(t.sendErr,ke(G,{address:i||""})));case 41:return t.vSendSymbol.textContent=d.toUpperCase(),t.vSendLogo.src=Ne.logoPath(d),r?(g=ft().assets[r.parentID],y=g.unitInfo,b=g.symbol,t.vSendFee.textContent=Ne.formatFullPrecision(h,y)+" "+b):t.vSendFee.textContent=Ne.formatFullPrecision(h,u),x=ft().fiatRatesMap[n],Ne.showFiatValue(t.vSendFeeFiat,h,x,u),t.vSendDestinationAmt.textContent=Ne.formatFullPrecision(s-h,u),t.vTotalSend.textContent=Ne.formatFullPrecision(s,u),Ne.showFiatValue(t.vTotalSendFiat,s,x,u),t.vSendAddr.textContent=t.sendAddr.value||"",k=l.balance.available-s,t.balanceAfterSend.textContent=Ne.formatFullPrecision(k,u),Ne.showFiatValue(t.balanceAfterSendFiat,k,x,u),Ne.show(t.approxSign),a||(Ne.hide(t.approxSign),t.vSendDestinationAmt.textContent=Ne.formatFullPrecision(s,u),w=s,r||(w+=h),t.vTotalSend.textContent=Ne.formatFullPrecision(w,u),Ne.showFiatValue(t.vTotalSendFiat,w,x,u),C=l.balance.available-s,r||(C-=h),C<=0?(t.balanceAfterSend.textContent=Ne.formatFullPrecision(0,u),Ne.showFiatValue(t.balanceAfterSendFiat,0,x,u)):(t.balanceAfterSend.textContent=Ne.formatFullPrecision(C,u),Ne.showFiatValue(t.balanceAfterSendFiat,C,x,u))),Ne.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,Ne.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,S("/api/validateaddress",{addr:t,assetID:n});case 2:return r=e.sent,e.abrupt("return",ft().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 Ne.hide(t.showIcon),Ne.show(t.hideIcon,t.changePW),void(t.switchPWMsg.textContent=ke("KEEP_WALLET_PASS"));Ne.hide(t.hideIcon,t.changePW),Ne.show(t.showIcon),t.switchPWMsg.textContent=ke("NEW_WALLET_PASS")}},{key:"assetVersionUsedByDEXes",value:function(){var e=this.selectedAssetID,t={},n=ft().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,S("/api/unapprovetoken",{assetID:this.selectedAssetID,version:this.unapprovingTokenVersion});case 4:if(n=e.sent,ft().checkResponse(n)){e.next=9;break}return t.unapproveTokenErr.textContent=n.msg,Ne.show(t.unapproveTokenErr),e.abrupt("return");case 9:(r=En[this.selectedAssetID])&&r[Jr]&&(t.unapproveTokenTxID.href=r[Jr](n.txID)),t.unapproveTokenTxID.textContent=n.txID,Ne.hide(t.unapproveTokenSubmissionElements,t.unapproveTokenErr),Ne.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,Ne.show(n.unapproveTokenSubmissionElements),Ne.hide(n.unapproveTokenTxMsg,n.unapproveTokenErr),(r=ft().assets[this.selectedAssetID])&&r.token){e.next=7;break}return e.abrupt("return");case 7:if(a=ft().assets[r.token.parentID]){e.next=10;break}return e.abrupt("return");case 10:return Ne.empty(n.tokenAllowanceRemoveSymbol),n.tokenAllowanceRemoveSymbol.appendChild(Ne.symbolize(r,!0)),n.tokenAllowanceRemoveVersion.textContent=t.toString(),e.next=16,S("/api/approvetokenfee",{assetID:this.selectedAssetID,version:t,approving:!1});case 16:o=e.sent,ft().checkResponse(o)?(s="".concat(Ne.formatCoinValue(o.txFee,a.unitInfo)," ").concat(a.unitInfo.conventional.unit),(i=ft().fiatRatesMap[a.id])&&(s+=" (".concat(Ne.formatFiatConversion(o.txFee,i,a.unitInfo)," USD)")),n.unapprovalFeeEstimate.textContent=s):(n.unapproveTokenErr.textContent=o.msg,Ne.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=ft().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);Ne.empty(t.tokenVersionTableAssetSymbol),t.tokenVersionTableAssetSymbol.appendChild(Ne.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===dt.Approved){e.next=3;break}return e.abrupt("return","continue");case 3:a=!0,c=t.tokenVersionRow.cloneNode(!0),(l=Ne.parseTemplate(c)).version.textContent=o.toString(),r[o]&&(l.usedBy.textContent=r[o].join(", ")),u=i.page.removeIconTmpl.cloneNode(!0),Ne.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:Ne.setVis(a,t.tokenVersionTable),Ne.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,Ne.hide(t.peerSpinner),e.next=4,S("/api/getwalletpeers",{assetID:this.selectedAssetID});case 4:if(n=e.sent,ft().checkResponse(n)){e.next=9;break}return t.managePeersErr.textContent=n.msg,Ne.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=ke("DEFAULT"),o=ke("ADDED"),i=ke("DISCOVERED"),r.forEach((function(e){var n,r=t.peerTableRow.cloneNode(!0),l=Ne.parseTemplate(r);switch(l.addr.textContent=e.addr,e.source){case ht.WalletDefault:l.source.textContent=a;break;case ht.UserAdded:l.source.textContent=o;break;case ht.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===ht.UserAdded){var u=c.page.removeIconTmpl.cloneNode(!0);Ne.bind(u,"click",s(f().mark((function n(){var r;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return Ne.hide(t.managePeersErr),n.next=3,S("/api/removewalletpeer",{assetID:c.selectedAssetID,addr:e.addr});case 3:if(r=n.sent,ft().checkResponse(r)){n.next=8;break}return t.managePeersErr.textContent=r.msg,Ne.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:Ne.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,Ne.hide(t.managePeersErr),e.next=4,S("/api/addwalletpeer",{assetID:this.selectedAssetID,addr:t.addPeerInput.value});case 4:if(n=e.sent,ft().checkResponse(n)){e.next=9;break}return t.managePeersErr.textContent=n.msg,Ne.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,Ne.show(t.peerSpinner),setTimeout((function(){Ne.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;Ne.hide(t.toggleWalletStatusErr,t.walletStatusDisable,t.disableWalletMsg,t.walletStatusEnable,t.enableWalletMsg),e?Ne.show(t.walletStatusDisable,t.disableWalletMsg):Ne.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,Ne.hide(t.toggleWalletStatusErr),n=ft().assets[this.selectedAssetID],r=!n.wallet.disabled,a={assetID:this.selectedAssetID,disable:r},o={assetName:n.name},s=ft().loading(t.toggleWalletStatusConfirm),e.next=10,S("/api/togglewalletstatus",a);case 10:if(i=e.sent,s(),ft().checkResponse(i)){e.next=16;break}return i.code===A.activeOrdersErr?t.toggleWalletStatusErr.textContent=ke("ACTIVE_ORDERS_ERR_MSG",o):t.toggleWalletStatusErr.textContent=i.msg,Ne.show(t.toggleWalletStatusErr),e.abrupt("return");case 16:c=ke("WALLET_DISABLED",o),r||(c=ke("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",Ne.show(t),n&&n.focus(),e.next=5,Ne.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 Ne.hide(e)})),t.style.right="10000px",Ne.show(n.forms,t),r=(n.forms.offsetWidth+t.offsetWidth)/2,e.next=8,Ne.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 Ne.hide(e)})),this.currentForm=this.page.checkmarkForm,this.animation=Er(this.page,t),e.next=5,this.animation.wait();case 5:this.animation=new We(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={},Ne.empty(t.assetSelect);var n=r(Object.values(ft().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=[ft().fiatRatesMap[e.id],ft().fiatRatesMap[t.id]],c=i[0],l=i[1];return c&&!l?-1:!c&&l?1:l*s-c*o}));var a,o=Nr(n);try{var s=function(){var n=a.value,r=t.iconSelectTmpl.cloneNode(!0);t.assetSelect.appendChild(r);var o=Ne.parseTemplate(r);e.assetButtons[n.id]={tmpl:o,bttn:r},e.updateAssetButton(n.id),Ne.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=ft().assets[e],r=this.assetButtons[e],o=r.bttn,s=r.tmpl;Ne.hide(s.fiatBox,s.noWallet),o.classList.add("nowallet"),(t=s.img).src||(t.src=Ne.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=Ne.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(Ne.formatBestUnitsFourSigFigs(h,d),2),f=p[0],v=p[1];s.balance.textContent=f,s.unit.textContent=v,Ne.show(s.balanceBox);var m=ft().fiatRatesMap[n.id];m&&(Ne.show(s.fiatBox),s.fiat.textContent=Ne.formatFourSigFigs(h/d.conventional.conversionFactor*m))}else Ne.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=Nr(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)Ne.show(t.txFindingAddrs);else{Ne.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;Ne.hide(t.feeStateBox);var r=ft().assets[n],a=r.unitInfo,o=r.token,s=ft().fiatRatesMap[n];if(s){var i=o?o.parentID:n,c=ft().fiatRatesMap[i];if(!o||c){Ne.show(t.feeStateBox);var l=o?ft().assets[o.parentID].unitInfo:a;Ne.formatBestRateElement(t.feeStateNetRate,i,e.rate,l),Ne.formatBestValueElement(t.feeStateSendFees,i,e.send,l),Ne.formatBestValueElement(t.feeStateSwapFees,i,e.swap,l),Ne.formatBestValueElement(t.feeStateRedeemFees,i,e.redeem,l),t.feeStateXcRate.textContent=Ne.formatFourSigFigs(s);var u=e.send/l.conventional.conversionFactor*c;t.feeStateSendFiat.textContent=Ne.formatFourSigFigs(u);var d=e.swap/l.conventional.conversionFactor*c;t.feeStateSwapFiat.textContent=Ne.formatFourSigFigs(d);var h=e.redeem/l.conventional.conversionFactor*c;t.feeStateRedeemFiat.textContent=Ne.formatFourSigFigs(h),Ne.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,ft().needsCustomProvider(t);case 2:if(n=e.sent,r=this.page,a=r.needsProviderBox,o=r.needsProviderBttn,Ne.setVis(n,a),n){e.next=7;break}return e.abrupt("return");case 7:Ne.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=ft().assets[t],a=r.wallet,o=r.unitInfo,s=this.page,Ne.hide(s.stakingBox,s.pickVSP,s.stakingSummary,s.stakingErr,s.vspDisplayBox,s.ticketPriceBox,s.purchaseTicketsBox,s.stakingRpcSpvMsg,s.ticketsDisabled),null!=a&&a.running&&32768&a.traits){e.next=6;break}return e.abrupt("return");case 6:return Ne.show(s.stakingBox),i=ft().loading(s.stakingBox),e.next=10,this.safePost("/api/stakestatus",t);case 10:if(c=e.sent,i(),ft().checkResponse(c)){e.next=19;break}if(!c.msg.includes("disconnected from consensus RPC")){e.next=16;break}return Ne.show(s.stakingRpcSpvMsg),e.abrupt("return");case 16:return Ne.show(s.stakingErr),s.stakingErr.textContent=c.msg,e.abrupt("return");case 19:if(Ne.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=Ne.formatFourSigFigs(l.ticketPrice/o.conventional.conversionFactor),s.purchaserBal.textContent=Ne.formatCoinValue(a.balance.available,o),this.updateTicketStats(l.stats,o,l.ticketPrice,l.votingSubsidy),!(null===(n=ft().extensionWallet(this.selectedAssetID))||void 0===n?void 0:n.disableStaking)){e.next=33;break}return Ne.hide(s.setVotes,s.showVSPs),Ne.show(s.ticketsDisabled),s.extensionModeAppName.textContent=ft().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(Ne.hide(t.vspDisplayBox),e)return Ne.show(t.vspDisplayBox,t.purchaseTicketsBox),Ne.hide(t.pickVSP),void(t.vspURL.textContent=e);Ne.setVis(!n.isRPC,t.pickVSP),Ne.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),Ne.setVis(e.mempool>0,a.immatureTicketCountBox),a.queuedTicketCount.textContent=String(e.queued),a.formQueuedTix.textContent=String(e.queued),Ne.setVis(e.queued>0,a.formQueueTixBox,a.queuedTicketCountBox),a.totalTicketCount.textContent=String(e.ticketCount),a.totalTicketRewards.textContent=Ne.formatFourSigFigs(e.totalRewards/t.conventional.conversionFactor),a.totalTicketVotes.textContent=String(e.votes),n&&(a.ticketPrice.textContent=Ne.formatFourSigFigs(n/t.conventional.conversionFactor)),r&&(a.votingSubsidy.textContent=Ne.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),Ne.empty(n.vspPickerList),Ne.hide(n.stakingErr),r=ft().loading(n.vspPicker),e.next=8,this.safePost("/api/listvsps",t);case 8:if(a=e.sent,r(),ft().checkResponse(a)){e.next=14;break}return Ne.show(n.stakingErr),n.stakingErr.textContent=a.msg,e.abrupt("return");case 14:o=a.vsps,s=Nr(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=Ne.parseTemplate(a)).url.textContent=r.url,o.feeRate.textContent=r.feePercentage.toFixed(2),o.voting.textContent=String(r.voting),Ne.bind(a,"click",(function(){Ne.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="",Ne.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=ft().loading(t.purchaseTicketsForm),e.next=7,this.safePost("/api/purchasetickets",{assetID:n,n:r});case 7:if(o=e.sent,a(),ft().checkResponse(o)){e.next=13;break}return t.purchaserErr.textContent=o.msg,Ne.show(t.purchaserErr),e.abrupt("return");case 13:this.showSuccess(ke("TICKETS_PURCHASED",{n:r.toLocaleString(Ne.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 Ne.show(r.purchaseTicketsErrBox),void(r.purchaseTicketsErr.textContent=s);c&&(t.tickets=c.concat(t.tickets)),l&&this.updateTicketStats(l,ft().assets[a].unitInfo),t.stats.queued=i,r.queuedTicketCount.textContent=String(i),r.formQueuedTix.textContent=String(i),Ne.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=ft().loading(r.stakingBox),e.next=5,this.safePost("/api/setvsp",{assetID:t,url:n.url});case 5:if(o=e.sent,a(),ft().checkResponse(o)){e.next=11;break}return Ne.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*Yr,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=ft().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(),ft().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=Yr,n.ticketHistoryPagination),Ne.setVis(m>0,n.ticketHistoryTable),Ne.setVis(0===m,n.noTicketsMessage),0!==i.length){e.next=25;break}return Ne.hide(n.ticketHistoryNextPage),e.abrupt("return");case 25:this.displayTicketPage(t,i),o.number=t,g=t*Yr+i.length===m,Ne.setVis(!g||!o.scanned,n.ticketHistoryNextPage),Ne.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=ft().unitInfo(a);Ne.hide(n.votingFormErr);var i=En[a][ft().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 Ne.hide(n.votingFormErr),a=ft().loading(n.votingForm),e.next=4,t.safePost("/api/setvotes",r);case 4:if(o=e.sent,a(),ft().checkResponse(o)){e.next=10;break}throw Ne.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=Nr(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)}}();Ne.empty(n.votingAgendas);var u,d=Nr(r.stances.agendas);try{var p=function(){var e=u.value,t=n.votingAgendaTmpl.cloneNode(!0);n.votingAgendas.appendChild(t);var r=Ne.parseTemplate(t);r.description.textContent=e.description;var a,o=Nr(e.choices);try{var s=function(){var t=a.value,o=n.votingChoiceTmpl.cloneNode(!0);r.choices.appendChild(o);var s,i=Ne.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,Ne.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()}ft().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=Nr(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)}}();Ne.empty(n.votingTspends);var m,g=Nr(r.stances.tspends);try{var y=function(){var e=m.value,t=n.tspendTmpl.cloneNode(!0);n.votingTspends.appendChild(t),ft().bindUrlHandlers(t);for(var r=Ne.parseTemplate(t),a=function(){var t=c[s];t.name=e.hash,e.currentPolicy===t.value&&(t.checked=!0),Ne.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=Ne.formatFourSigFigs(e.value/o.conventional.conversionFactor):Ne.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=Nr(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)}}();Ne.empty(n.votingTKeys);var x,k=Nr(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=Ne.parseTemplate(t),a=function(){var t=s[o];t.name=e.key,e.policy===t.value&&(t.checked=!0),Ne.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(ke("ORDER"),c.orderlocked,ke("LOCKED_ORDER_BAL_MSG")),c.contractlocked>0&&m(ke("SWAPPING"),c.contractlocked,ke("LOCKED_SWAPPING_BAL_MSG")),c.bondlocked>0&&m(ke("BONDED"),c.bondlocked,ke("LOCKED_BOND_BAL_MSG")),c.bondReserves>0&&m(ke("BOND_RESERVES"),c.bondReserves,ke("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(ke("IMMATURE_TITLE"),c.immature,ke("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=Ne.formatFourSigFigs(c.available/s.conventional.conversionFactor),ft().bindTooltips(r.balanceDetailBox)}},{key:"showAvailableMarkets",value:function(e){for(var t=this.page,n=ft().user.exchanges,r=[],o=0,s=Object.values(n);o0&&(r.age.dataset.stamp=String(t.timestamp));var u=Xr(t.type);if(t.tokenID&&t.tokenID!==n){var d=ft().assets[t.tokenID].unitInfo.conventional.unit;u="".concat(d," ").concat(u)}if(r.type.textContent=u,r.id.textContent=$r(t.id,12),r.id.setAttribute("title",t.id),r.fees.textContent=Ne.formatCoinValue(t.fees,l),Hr.includes(t.type))r.amount.textContent="-";else{var h=a(zr(t.type),2),p=h[0],f=h[1],v=Ne.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,Ne.bind(r,"click",(function(){return n.showTxDetailsPopup(e.id)})),this.updateTxHistoryRow(r,e,t);var a=Ne.parseTemplate(r);return this.stampers.push(a.age),r}},{key:"txHistoryDateRow",value:function(e){var t=this.page.txHistoryDateRowTmpl.cloneNode(!0);return Ne.parseTemplate(t).date.textContent=e,t}},{key:"setTxDetailsPopupElements",value:function(e){var t=this.page,n=En[this.selectedAssetID];n&&n[Jr]&&(t.txViewBlockExplorer.href=n[Jr](e.id));var r=Xr(e.type);if(e.tokenID&&e.tokenID!==this.selectedAssetID){var o=ft().assets[e.tokenID].symbol.split(".")[0].toUpperCase();r="".concat(o," ").concat(r)}if(t.txDetailsType.textContent=r,Ne.setVis(16===e.type,t.txTypeTooltip),t.txTypeTooltip.dataset.tooltip=ke("SWAP_OR_SEND_TOOLTIP"),Hr.includes(e.type))Ne.hide(t.txDetailsAmtSection);else{var s=this.selectedAssetID;e.tokenID&&(s=e.tokenID),Ne.show(t.txDetailsAmtSection);var i=ft().unitInfo(s),c=Ne.formatCoinValue(e.amount,i),l=a(zr(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=ft().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=ft().unitInfo(h),v=Ne.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),Ne.setVis(0===e.blockNumber,t.timestampPending,t.blockNumberPending),Ne.setVis(0!==e.blockNumber,t.txDetailsBlockNumber,t.txDetailsTimestamp),t.txDetailsID.textContent=$r(e.id,20),t.txDetailsID.setAttribute("title",e.id),e.recipient?(Ne.show(t.txDetailsRecipientSection),t.txDetailsRecipient.textContent=$r(e.recipient,20),t.txDetailsRecipient.setAttribute("title",e.recipient)):Ne.hide(t.txDetailsRecipientSection),e.bondInfo){Ne.show(t.txDetailsBondIDSection,t.txDetailsBondLocktimeSection),Ne.setVis(""!==e.bondInfo.accountID,t.txDetailsBondAccountIDSection),t.txDetailsBondID.textContent=$r(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=$r(e.bondInfo.accountID,20),t.txDetailsBondAccountID.setAttribute("title",e.bondInfo.accountID)}else Ne.hide(t.txDetailsBondIDSection,t.txDetailsBondLocktimeSection,t.txDetailsBondAccountIDSection);e.additionalData&&e.additionalData.Nonce?(Ne.show(t.txDetailsNonceSection),t.txDetailsNonce.textContent="".concat(e.additionalData.Nonce)):Ne.hide(t.txDetailsNonceSection)}},{key:"showTxDetailsPopup",value:function(e){var t=ft().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&&Ne.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(!(ft().assets[this.selectedAssetID].wallet.traits&Vr&&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]):(Ne.show(this.page.txHistoryTable),Ne.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=Nr(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,ft().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,Ne.hide(n.txHistoryTable,n.txHistoryBox,n.noTxHistory,n.earlierTxs,n.txHistoryNotAvailable,n.hideMixTxs),Ne.empty(n.txHistoryTableBody),(a=ft().assets[t].wallet)&&!a.disabled&&65536&a.traits){e.next=7;break}return Ne.show(n.txHistoryNotAvailable),e.abrupt("return");case 7:return this.oldestTx=void 0,o=!!(a.traits&Vr),Ne.setVis(o,n.hideMixTxs),Ne.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),Ne.show(n.noTxHistory),e.abrupt("return");case 22:if(0!==r.txs.length){e.next=25;break}return Ne.show(n.noTxHistory),e.abrupt("return");case 25:i=this.txDate(r.txs[0]),n.txHistoryTableBody.appendChild(this.txHistoryDateRow(i)),c=Nr(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],Ne.show(n.txHistoryTable),Ne.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=ft().assets[this.selectedAssetID].wallet,a=!!(r.traits&Vr)&&!!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=Nr(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()}Ne.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,Ne.hide(n.reconfigErr),r="/api/rescanwallet",a={assetID:t},o=ft().loading(this.body),e.next=7,S(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(ft().checkResponse(s)){e.next=17;break}return Ne.showFormError(n.reconfigErr,s.msg),e.abrupt("return");case 17:this.assetUpdated(t,n.reconfigForm,ke("RESCAN_STARTED"));case 18:case"end":return e.stop()}}),e,this)}))),function(e){return E.apply(this,arguments)})},{key:"showConfirmForce",value:function(){Ne.hide(this.page.confirmForceErr),this.showForm(this.page.confirmForce)}},{key:"showRecoverWallet",value:function(){Ne.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,S("/api/openwallet",n);case 3:if(r=e.sent,ft().checkResponse(r)){e.next=7;break}return console.error("openwallet error",r),e.abrupt("return");case 7:this.assetUpdated(t,void 0,ke("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,Ne.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=ft().assets[t],s=ft().currentWalletDefinition(t),i=o.token?[o.token.definition]:o.info?o.info.availablewallets:[],c=null===(r=ft().extensionWallet(t))||void 0===r?void 0:r.disableWalletType,i.length>1&&!c){Ne.empty(a.changeWalletTypeSelect),Ne.show(a.showChangeType,a.changeTypeShowIcon),a.changeTypeMsg.textContent=ke("CHANGE_WALLET_TYPE"),l=Nr(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=Nr(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=ft().walletMap[t],Ne.setVis(4&g.traits,a.downloadLogs),Ne.setVis(32&g.traits,a.recoverWallet),Ne.setVis(256&g.traits,a.exportWallet),Ne.setVis(1&g.traits,a.rescanWallet),Ne.setVis(1024&g.traits&&!g.disabled,a.managePeers),Ne.setVis(8192&g.traits&&!g.disabled,a.unapproveTokenAllowance),Ne.setVis(9509&g.traits,a.otherActionsLabel),g.disabled?Ne.show(a.enableWallet):Ne.show(a.disableWallet),this.showOrHideRecoverySupportMsg(g,s.seeded),a.recfgAssetLogo.src=Ne.logoPath(o.symbol),a.recfgAssetName.textContent=o.name,null!=n&&n.skipAnimation||this.showForm(a.reconfigForm),y=ft().loading(a.reconfigForm),e.next=26,S("/api/walletsettings",{assetID:t});case 26:if(b=e.sent,y(),ft().checkResponse(b)){e.next=31;break}return Ne.showFormError(a.reconfigErr,b.msg),e.abrupt("return");case 31:x=ft().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=ke("WALLET_RECOVERY_SUPPORT_MSG",{walletSymbol:t.toLocaleUpperCase()}),Ne.show(n.reconfigSupportMsg),n.submitReconfig.setAttribute("disabled",""),void n.submitReconfig.classList.add("grey");n.submitReconfig.removeAttribute("disabled"),n.submitReconfig.classList.remove("grey"),Ne.empty(n.reconfigSupportMsg),Ne.hide(n.reconfigSupportMsg)}},{key:"changeWalletType",value:function(){var e=this.page.changeWalletTypeSelect.value||"",t=ft().walletDefinition(this.selectedAssetID,e);this.reconfigForm.update(this.selectedAssetID,t.configopts||[],!1);var n=ft().walletMap[this.selectedAssetID],r=ft().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){Ne.hide(this.walletCfgGuide),""!==e&&(this.walletCfgGuide.href=e,Ne.show(this.walletCfgGuide))}},{key:"updateDisplayedReconfigFields",value:function(e){var t,n=null===(t=ft().extensionWallet(this.selectedAssetID))||void 0===t?void 0:t.disablePassword;e.seeded||"token"===e.type||n?(Ne.hide(this.page.showChangePW,this.reconfigForm.fileSelector),this.changeWalletPW=!1,this.setPWSettingViz(!1)):Ne.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=ft().assets[t],o=a.wallet,s=a.unitInfo,i=a.symbol,c=a.token,Ne.hide(n.toggleSubtract),n.subtractCheckBox.checked=!1,(l=!!(64&o.traits))&&Ne.show(n.toggleSubtract),Ne.hide(n.sendErr,n.maxSendDisplay,n.sendTokenMsgBox),n.sendAddr.classList.remove("border-danger","border-success"),n.sendAddr.value="",n.sendAmt.value="",u=ft().fiatRatesMap[t],Ne.showFiatValue(n.sendValue,0,u,s),n.walletBal.textContent=Ne.formatFullPrecision(o.balance.available,s),n.sendLogo.src=Ne.logoPath(i),n.sendName.textContent=s.conventional.unit,c&&(d=ft().assets[c.parentID],n.sendTokenParentLogo.src=Ne.logoPath(d.symbol),n.sendTokenParentName.textContent=d.name,Ne.show(n.sendTokenMsgBox)),!(o.balance.available>0&&512&o.traits)){e.next=25;break}return h={assetID:t,subtract:l,maxWithdraw:!0,value:o.balance.available},p=ft().loading(this.body),e.next=22,S("/api/txfee",h);case 22:v=e.sent,p(),ft().checkResponse(v)&&(m=o.balance.available,c||(m-=v.txfee)<0&&(m=0),this.maxSend=m,n.maxSend.textContent=Ne.formatFullPrecision(m,s),Ne.showFiatValue(n.maxSendFiat,m,u,s),c?(g=ft().assets[c.parentID].unitInfo,n.maxSendFee.textContent=Ne.formatFullPrecision(v.txfee,g)+" "+g.conventional.unit,Ne.showFiatValue(n.maxSendFeeFiat,v.txfee,ft().fiatRatesMap[c.parentID],g)):(n.maxSendFee.textContent=Ne.formatFullPrecision(v.txfee,s),Ne.showFiatValue(n.maxSendFeeFiat,v.txfee,u,s)),Ne.show(n.maxSendDisplay));case 25:Ne.showFiatValue(n.sendValue,0,u,s),n.walletBal.textContent=Ne.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:(C=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=ft().loading(this.body),e.next=3,S("/api/connectwallet",{assetID:t});case 3:r=e.sent,n(),ft().checkResponse(r)||(a=ft().assets[t].symbol,(o=this.page).errorModalMsg.textContent=ke("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 C.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=ft().assets[this.selectedAssetID],r=n.id,a=n.unitInfo,o=n.wallet,s=ft().fiatRatesMap[r],64&o.traits?(i=o.balance.available,t.sendAmt.value=String(i/a.conventional.conversionFactor),Ne.showFiatValue(t.sendValue,i,s,a),t.subtractCheckBox.checked=!0):(t.sendAmt.value=String(this.maxSend/a.conventional.conversionFactor),Ne.showFiatValue(t.sendValue,this.maxSend,s,a),t.subtractCheckBox.checked=!1);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=ft().unitInfo(a).conventional.conversionFactor,i=r.vSendPw.value||"",r.vSendPw.value="",""!==i){e.next=9;break}return Ne.showFormError(r.vSendErr,ke(R)),e.abrupt("return");case 9:return c={assetID:a,address:r.sendAddr.value,subtract:o,value:Math.round(tt(r.sendAmt.value)*s),pw:i},l=ft().loading(r.vSendForm),e.next=13,S("/api/send",c);case 13:if(u=e.sent,l(),ft().checkResponse(u)){e.next=18;break}return Ne.showFormError(r.vSendErr,u.msg),e.abrupt("return");case 18:d=ft().assets[a].name,this.assetUpdated(a,r.vSendForm,ke("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,Ne.hide(n.reconfigErr),a=ft().currentWalletDefinition(r).type,Ne.isHidden(n.changeWalletType)||(a=n.changeWalletTypeSelect.value||""),o=ft().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(),ft().checkResponse(i)){e.next=16;break}return Ne.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 ft().loadPage(this.data.goBack),e.abrupt("return");case 19:this.assetUpdated(r,n.reconfigForm,ke("RECONFIG_SUCCESS")),this.updateTicketBuyer(r),ft().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=ft().loading(n.newWalletForm),e.next=4,S("/api/closewallet",{assetID:t});case 4:if(a=e.sent,r(),ft().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,Ne.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=ft().loading(t.forms),e.next=6,S("/api/restorewalletinfo",n);case 6:a=e.sent,r(),ft().checkResponse(a)?(t.exportWalletPW.value="",this.displayRestoreWalletInfo(a.restorationinfo)):Ne.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,Ne.empty(n.restoreInfoCardsList),r=Nr(t);try{for(r.s();!(a=r.n()).done;)o=a.value,s=this.restoreInfoCard.cloneNode(!0),(i=Ne.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,Ne.hide(t.recoverWalletErr),n={assetID:this.selectedAssetID},r="/api/recoverwallet",a=ft().loading(t.forms),e.next=7,S(r,n);case 7:o=e.sent,a(),o.code===A.activeOrdersErr?(this.forceUrl=r,this.forceReq=n,this.showConfirmForce()):ft().checkResponse(o)?this.closePopups():Ne.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=ft().loading(t.forms),e.next=5,S(this.forceUrl,this.forceReq);case 5:r=e.sent,n(),ft().checkResponse(r)?this.closePopups():Ne.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=ft().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&&Ne.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(ft().walletMap[n.assetID].synced){var a=ft().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),Ne.unbind(document,"keyup",this.keyup)}}]),ve}(lt);function $r(e,t){return e.length<=t?e:"".concat(e.substring(0,t/2),"...").concat(e.substring(e.length-t/2))}function ea(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 ta="order",na="match",ra="bondpost",aa="conn";function oa(){return"desktop_notifications-".concat(window.location.host)}var sa,ia=(h(Kr={},ta,"BROWSER_NTFN_ORDERS"),h(Kr,na,"BROWSER_NTFN_MATCHES"),h(Kr,ra,"BROWSER_NTFN_BONDS"),h(Kr,aa,"BROWSER_NTFN_CONNECTIONS"),Kr),ca=(h(Qr={},ta,!0),h(Qr,na,!0),h(Qr,ra,!0),h(Qr,aa,!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(ke(ee)),t.next=10;break;case 6:if(e.ntfnPermissionDenied()){t.next=10;break}return t.next=9,Notification.requestPermission();case 9:e.sendDesktopNotification(ke(ee));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}()),la=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(ke(ee));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(!ua()){e.next=5;break}return e.next=3,window.sendOSNotification(t,n);case 3:e.next=11;break;case 5:if(!da()){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 ua(){return void 0!==window.isWebview}function da(){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 ha=ua()||da()?la:ca;function pa(){return(pa=s(f().mark((function e(t){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(sa.browserNtfnEnabled&&sa[t.type]){e.next=2;break}return e.abrupt("return");case 2:return e.next=4,ha.sendDesktopNotification(t.subject,ya(t.details));case 4:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function fa(){var e;if(void 0!==sa)return sa;var t=oa();return sa=null!==(e=k.fetchLocal(t))&&void 0!==e?e:{}}var va=/\{\{\{([^|]+)\|([^}]+)\}\}\}/g,ma=/\{\{\{order\|([^}]+)\}\}\}/g;function ga(e,t){for(var n=t.replace(ma,(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(va,(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),Pn(t,r),r.outerHTML})),r=Ne.noderize(n).body;r.firstChild;)e.appendChild(r.firstChild)}function ya(e){return e.replace(va,(function(e,t,n){return n.slice(0,8)}))}var ba=["bonds"];var xa=function(e){g(A,e);var t,n,r,a,o,c,l,u,p,m,x,w,C,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=Ne.idDescendants(e);t.forms=Ne.applySelector(n.forms,":scope > form"),t.fiatRateSources=Ne.applySelector(n.fiatRateSources,"input[type=checkbox]"),n.darkMode.checked="1"===k.fetchLocal(k.darkModeLK),Ne.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),Ne.bind(n.showPokes,"click",(function(){var e=n.showPokes.checked||!1;k.storeLocal(k.popupsLK,e?"1":"0"),ft().showPopups=e})),n.commitHash.textContent=ft().commitHash.substring(0,7),Ne.bind(n.addADex,"click",(function(){t.dexAddrForm.refresh(),t.showForm(n.dexAddrForm)})),t.fiatRateSources.forEach((function(e){Ne.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,S("/api/toggleratesource",{disable:!e.checked,source:e.value});case 2:return n=t.sent,ft().checkResponse(n)||(e.checked=!e.checked),t.next=6,ft().fetchUser();case 6:case"end":return t.stop()}}),t)}))))})),t.regAssetForm=new gr(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!==pt){e.next=5;break}return e.next=3,ft().fetchUser();case 3:return window.location.reload(),e.abrupt("return");case 5:if(o=ft().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 mr(n.confirmRegForm,(function(){t.registerDEXSuccess()}),(function(){t.animateRegAsset(n.confirmRegForm)})),t.newWalletForm=new pr(n.newWalletForm,(function(e){return t.newWalletCreated(e,t.confirmRegisterForm.tier)}),(function(){return t.animateRegAsset(n.newWalletForm)})),t.walletWaitForm=new yr(n.walletWait,(function(){t.animateConfirmForm(n.walletWait)}),(function(){t.animateRegAsset(n.walletWait)})),t.dexAddrForm=new xr(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)}}()),Ne.bind(n.importAccount,"click",(function(){return t.prepareAccountImport(n.authorizeAccountImportForm)})),Br(n.authorizeAccountImportForm,n.authorizeImportAccountConfirm,(function(){return t.importAccount()})),Ne.bind(n.changeAppPW,"click",(function(){return t.showForm(n.changeAppPWForm)})),Br(n.changeAppPWForm,n.submitNewPW,(function(){return t.changeAppPW()})),t.appPassResetForm=new Sr(n.resetAppPWForm,s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,ft().loadPage("login");case 2:Ne.hide(n.forms);case 3:case"end":return e.stop()}}),e)})))),Ne.bind(n.resetAppPW,"click",(function(){t.appPassResetForm.refresh(),t.showForm(n.resetAppPWForm),t.appPassResetForm.focus()})),Ne.bind(n.accountFile,"change",(function(){return t.onAccountFileChange()})),Ne.bind(n.removeAccount,"click",(function(){return t.clearAccountFile()})),Ne.bind(n.addAccount,"click",(function(){return n.accountFile.click()})),Ne.bind(n.exportSeed,"click",(function(){Ne.hide(n.exportSeedErr),t.showForm(n.exportSeedAuth)})),Br(n.exportSeedAuth,n.exportSeedSubmit,(function(){return t.submitExportSeedReq()})),Ne.bind(n.gameCodeLink,"click",(function(){return t.showForm(n.gameCodeForm)})),Ne.bind(n.gameCodeSubmit,"click",(function(){return t.submitGameCode()}));var r=function(){Ne.hide(n.forms),n.exportSeedPW.value="",n.legacySeed.textContent="",n.mnemonic.textContent=""};return Ne.bind(n.forms,"mousedown",(function(e){Ne.mouseInElement(e,t.currentForm)||r()})),t.keyup=function(e){"Escape"===e.key&&r()},Ne.bind(document,"keyup",t.keyup),n.forms.querySelectorAll(".form-closer").forEach((function(e){Ne.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){fa(),sa[e]=t,k.storeLocal(oa(),sa)}(n,t.checked)}},{key:"getBrowserNtfnSettings",value:function(){return fa()}},{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=ia,(a=t.browserNtfnCheckboxTemplate).removeAttribute("id"),o=t.browserNtfnCheckboxContainer,Ne.empty(t.browserNtfnCheckboxContainer),Object.keys(r).forEach((function(e){var t=a.cloneNode(!0),s=n[e],i=Ne.tmplElement(t,"checkbox");Ne.tmplElement(t,"label").textContent=ke(r[e]),i.setAttribute("name",e),s&&i.setAttribute("checked","checked"),o.appendChild(t),Ne.bind(i,"click",c.updateNtfnSetting)})),i=t.browserNtfnEnabled,Ne.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(!ha.ntfnPermissionDenied()){e.next=2;break}return e.abrupt("return");case 2:if(!(n=t.target).checked){e.next=7;break}return e.next=6,ha.requestNtfnPermission();case 6:n.checked=!ha.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)}}()),Ne.bind(i,"change",(function(e){var n=e.target,r=ha.ntfnPermissionDenied();Ne.setVis(n.checked,t.browserNtfnCheckboxContainer),Ne.setVis(r,t.browserNtfnBlockedMsg),n.disabled=r})),i.checked=ha.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){Ar(this.currentForm,e),this.currentForm=e}},{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=ft().loading(n),e.next=3,S("/api/bondsfeebuffer",{assetID:t});case 3:if(a=e.sent,r(),ft().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:"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,ft().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,Ne.show(t.removeAccount),Ne.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=ke(j),Ne.hide(e.removeAccount),Ne.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,Ne.show(t.importAccountErr),e.abrupt("return");case 19:if(void 0!==a){e.next=22;break}return Ne.showFormError(t.importAccountErr,ke("ACCT_UNDEFINED")),e.abrupt("return");case 22:return s=(o=a).bonds,i=void 0===s?[]:s,c=ea(o,ba),l={account:c,bonds:i},u=ft().loading(this.body),e.next=27,S("/api/importaccount",l);case 27:if(d=e.sent,u(),ft().checkResponse(d)){e.next=32;break}return Ne.showFormError(t.importAccountErr,d.msg),e.abrupt("return");case 32:return e.next=34,ft().fetchUser();case 34:Ne.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=ft().loading(this.body),e.next=5,S("/api/exportseed",{pass:n});case 5:if(a=e.sent,r(),ft().checkResponse(a)){e.next=10;break}return Ne.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 Ne.hide(e)})),t.style.right="10000px",Ne.show(n.forms,t),r=(n.forms.offsetWidth+t.offsetWidth)/2,e.next=8,Ne.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,Ne.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 Ne.showFormError(t.changePWErrMsg,ke("NO_APP_PASS_ERROR_MSG")),n(),e.abrupt("return");case 7:if(t.newAppPW.value===t.confirmNewPW.value){e.next=11;break}return Ne.showFormError(t.changePWErrMsg,ke(N)),n(),e.abrupt("return");case 11:return r=ft().loading(t.changeAppPW),a={appPW:t.appPW.value,newAppPW:t.newAppPW.value},n(),e.next=16,S("/api/changeapppass",a);case 16:if(o=e.sent,r(),ft().checkResponse(o)){e.next=21;break}return Ne.showFormError(t.changePWErrMsg,o.msg),e.abrupt("return");case 21:Ne.hide(t.forms);case 22:case"end":return e.stop()}}),e,this)}))),function(){return a.apply(this,arguments)})},{key:"unload",value:function(){Ne.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:Ne.hide(t),n=this.page.regAssetForm,this.currentForm=n,this.regAssetForm.animate(),Ne.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,Ne.hide(t),Ne.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,Ne.hide(t.gameCodeErr),n=t.gameCodeInput.value){e.next=7;break}return t.gameCodeErr.textContent=ke("NO_CODE_PROVIDED"),Ne.show(t.gameCodeErr),e.abrupt("return");case 7:return r=t.gameCodeMsg.value||"",a=ft().loading(t.gameCodeForm),e.next=11,S("/api/redeemgamecode",{code:n,msg:r});case 11:if(o=e.sent,a(),ft().checkResponse(o)){e.next=17;break}return t.gameCodeErr.textContent=ke(H,{msg:o.msg}),Ne.show(t.gameCodeErr),e.abrupt("return");case 17:Ne.show(t.gameCodeSuccess),t.gameRedeemTx.dataset.explorerCoin=o.coinString,Pn(42,t.gameRedeemTx),t.gameRedeemTx.textContent=o.coinString,s=ft().unitInfo(42),t.gameRedeemValue.textContent=Ne.formatCoinValue(o.win,s);case 24:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})}]),A}(lt);function ka(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 Ca(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);Sa(t.route,t.payload,n.handlers)},s.onclose=function(e){window.log("ws","onclose"),clearTimeout(i),s=n.connection=null,Sa("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()),Sa("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 Ca(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)?Ca(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),Sa("error",e,n.handlers)}}}()}}]),e}());function Da(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 Ia(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 Ra(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=ft().exchanges[e.dex.host],n=t.markets[e.cfg.name];if(n.spot){var r,a=Aa(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=ft().fiatRatesMap[n.baseid];l?(o.tmpl.volume.textContent=Ne.formatFourSigFigs(n.spot.vol24/i*l),o.tmpl.volUnit.textContent="USD"):(o.tmpl.volume.textContent=Ne.formatFourSigFigs(n.spot.vol24/i),o.tmpl.volUnit.textContent=c),eo(o.tmpl,t,n)}}catch(e){a.e(e)}finally{a.f()}this.page.obPrice.textContent=Ne.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"),Ne.setVis(n.spot.change24>=0,this.page.obUp),Ne.setVis(n.spot.change24<0,this.page.obDown)}}}},{key:"setMarketDetails",value:function(){if(this.market){var e,t=Aa(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=Ne.logoPath(a.symbol),n.tmpl.quoteIcon.src=Ne.logoPath(o.symbol),Ne.empty(n.tmpl.baseSymbol,n.tmpl.quoteSymbol),n.tmpl.baseSymbol.appendChild(Ne.symbolize(a,!0)),n.tmpl.quoteSymbol.appendChild(Ne.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[Ua];if(!a){if(this.candleDur!==Ua)return void this.requestCandles(Ua);var o,s=Aa(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=Aa(this.stats);try{for(v.s();!(d=v.n()).done;){var m=d.value;m.tmpl.high.textContent=e>0?Ne.formatFourSigFigs(ft().conventionalRate(h,p,e,f)):"-",m.tmpl.low.textContent=t>0?Ne.formatFourSigFigs(ft().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:ke("NOT_SUPPORTED",{asset:(o?c.symbol:i.symbol).toUpperCase()})};var l=o.token?null===(e=ft().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=ft().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=ke(P,{asset:s.symbol.toUpperCase(),version:c.version+""})):d=ke(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()?(Ne.show(e.priceBox,e.tifBox,e.qtyBox,e.maxBox),Ne.hide(e.mktBuyBox),this.previewQuoteAmt(!0)):(Ne.hide(e.tifBox,e.maxBox,e.priceBox),this.isSell()?(Ne.hide(e.mktBuyBox),Ne.show(e.qtyBox),this.previewQuoteAmt(!0)):(Ne.show(e.mktBuyBox),Ne.hide(e.qtyBox),this.previewQuoteAmt(!1))),this.updateOrderBttnState()}},{key:"resolveOrderFormVisibility",value:(q=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===dt.Approved&&r===dt.Approved){e.next=7;break}return e.abrupt("return",!1);case 7:if(a=p.market,o=a.base,s=a.quote,o&&ft().assets[o.id].wallet&&s&&ft().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=Ne,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,Ne.setVis(a>0||o>0,t.reputationAndTradingTierBox)),(i=ft().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)),Ne.setVis(this.mmRunning,t.mmRunning),this.mmRunning&&Ne.hide(t.orderForm,t.orderTypeBttns);case 14:case"end":return e.stop()}}),e,this)}))),function(){return q.apply(this,arguments)})},{key:"setLoaderMsgVisibility",value:function(){var e=this.page,t=this.assetsAreSupported(),n=t.isSupported,r=t.text;n?Ne.hide(e.loaderMsg):(e.loaderMsg.textContent=r,Ne.show(e.loaderMsg),Ne.hide(e.notRegistered),Ne.hide(e.noWallet))}},{key:"showTokenApprovalForm",value:(R=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.forms.show(this.page.approveTokenForm);case 3:case"end":return e.stop()}}),e,this)}))),function(e){return R.apply(this,arguments)})},{key:"tokenAssetApprovalStatuses",value:function(){var e=this.market,t=e.base,n=e.quote,r=dt.Approved,a=dt.Approved;if(null!=t&&t.token){var o,s=ft().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=ft().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===dt.Approved&&r===dt.Approved)return Ne.hide(e.tokenApproval),e.sellBttn.removeAttribute("disabled"),void e.buyBttn.removeAttribute("disabled");n!==dt.Approved&&r===dt.Approved&&(e.sellBttn.setAttribute("disabled","disabled"),e.buyBttn.removeAttribute("disabled"),this.setBuy(),Ne.show(e.approvalRequiredSell),Ne.hide(e.approvalRequiredBuy,e.approvalRequiredBoth)),n===dt.Approved&&r!==dt.Approved&&(e.buyBttn.setAttribute("disabled","disabled"),e.sellBttn.removeAttribute("disabled"),this.setSell(),Ne.show(e.approvalRequiredBuy),Ne.hide(e.approvalRequiredSell,e.approvalRequiredBoth)),n!==dt.Approved&&r!==dt.Approved&&(Ne.show(e.approvalRequiredBoth),Ne.hide(e.approvalRequiredSell,e.approvalRequiredBuy)),Ne.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(),Ne.setVis(n===dt.NotApproved,e.approveBaseBttn),Ne.setVis(r===dt.NotApproved,e.approveQuoteBttn),Ne.setVis(n===dt.Pending,e.approvalPendingBase),Ne.setVis(r===dt.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(ke("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(ke("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===ut.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(Ne.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=ke("SET_BUTTON_SELL",{asset:Ne.shortSymbol(this.market.baseCfg.unitInfo.conventional.unit)}):this.page.submitBttn.textContent=ke("SET_BUTTON_BUY",{asset:Ne.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=ft().assets[this.market.base.id].wallet,i=ft().assets[e.quote.id].wallet;if(s&&i)if(n<=0||n-1&&(o.classList.add("hover"),this.hovers.push(o))}t.hoverPrice.textContent=Ne.formatCoinValue(e.rate),t.hoverVolume.textContent=Ne.formatCoinValue(e.depth),t.hoverVolume.style.color=e.dotColor}else Ne.hide(t.depthLegend)}},{key:"reportDepthZoom",value:function(e){k.storeLocal(k.depthZoomLK,e)}},{key:"reportMouseCandle",value:function(e){var t=this.page;e?(Ne.show(t.candlesLegend),t.candleStart.textContent=Ne.formatCoinValue(e.startRate/this.market.rateConversionFactor),t.candleEnd.textContent=Ne.formatCoinValue(e.endRate/this.market.rateConversionFactor),t.candleHigh.textContent=Ne.formatCoinValue(e.highRate/this.market.rateConversionFactor),t.candleLow.textContent=Ne.formatCoinValue(e.lowRate/this.market.rateConversionFactor),t.candleVol.textContent=Ne.formatCoinValue(e.matchVolume,this.market.baseUnitInfo)):Ne.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:Ya(t.value||"",o),rate:Ya(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=ft().assets[n.quote].unitInfo.conventional.unit,o=n.qty*n.rate/Ft,s=Ne.formatCoinValue(o,this.market.quoteUnitInfo);t.orderPreview.textContent=ke("ORDER_PREVIEW",{total:s,asset:a}),this.isSell()?this.preSell():this.preBuy()}}},{key:"preSell",value:function(){var e=this,t=this.market,n=ft().assets[t.base.id].wallet;return n.balance.available0){if(a.token){var i=ft().assets[a.token.parentID],c=i.wallet.balance.available,l=i.unitInfo;return void(c0)return}return Ne.show(t.maxZeroNoBal),void(t.maxZeroNoBalTicker.textContent=a.unitInfo.conventional.unit)}Ne.show(t.maxAboveZero),t.maxFromAmt.textContent=Ne.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 Ne.show(t.orderErr),t.orderErr.textContent=ke("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(),Ne.empty(this.page.buyRows),void Ne.empty(this.page.sellRows);Ne.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/Ft:e.buys[0].msgRate/Ft:e.sells&&e.sells.length?e.sells[0].msgRate/Ft:null}},{key:"setMarketBuyOrderEstimate",value:function(){var e=this.market,t=e.cfg.lotsize,n=ft().user.exchanges[e.dex.host].markets[e.sid].buybuffer,r=this.midGapConventional();r&&(this.page.minMktBuy.textContent=Ne.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,ft().orders(t,n).length)}},{key:"loadUserOrders",value:(I=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=ft().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,S("/api/orders",c);case 10:l=e.sent,u=l.orders||[],d=Aa(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 I.apply(this,arguments)})},{key:"refreshActiveOrders",value:function(){var e=ft().orders(this.market.dex.host,Qa(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.status<3||At(e)},u=Aa(e);try{for(u.s();!(r=u.n()).done;){var d=r.value;s[d.id]={ord:d}}}catch(e){u.e(e)}finally{u.f()}var h=Object.keys(s).map((function(e){return s[e]}));h.sort((function(e,t){var n=[l(e.ord),l(t.ord)],r=n[0],a=n[1];return r&&!a?-1:!r&&a?1:t.ord.submitTime-e.ord.submitTime}));var p=this.maxUserOrderCount();for(var f in h.length>p&&(h=h.slice(0,p)),s)delete s[f];Ne.empty(o.userOrders),Ne.setVis(null===(t=h)||void 0===t?void 0:t.length,o.userOrders),Ne.setVis(!(null!==(n=h)&&void 0!==n&&n.length),o.userNoOrders);var v,m=!1,g=Aa(h);try{var y=function(){var e=v.value,t=o.userOrderTmpl.cloneNode(!0);o.userOrders.appendChild(t);var n=Ne.parseTemplate(t),r=Ne.parseTemplate(n.header),u=Ne.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&&At(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=Tt(h),u.side.classList.add(h.sell?"sellcolor":"buycolor"),r.side.classList.add(h.sell?"sellcolor":"buycolor"),u.qty.textContent=e.header.qty.textContent=Ne.formatCoinValue(h.qty,i.baseUnitInfo),d=2===h.type?a.marketOrderRateString(h,i):Ne.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=function(e){switch(e){case 1:return ke(X);case 2:return ke(K);default:return ke("CANCEL_ORDER")}}(h.type),a.updateMetaOrder(e),Ne.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?(qt(h)&&(Ne.show(u.cancelBttn),Ea(u.cancelBttn,"click",(function(e){y(e)}))),Ea(u.accelerateBttn,"click",(function(e){b(e)})),ft().canAccelerateOrder(h)&&Ne.show(u.accelerateBttn),u.link.href="order/".concat(p),ft().bindInternalNavigation(t)):(Ne.hide(u.accelerateBttn),Ne.hide(u.cancelBttn),Ne.hide(u.link)),Ne.bind(n.header,"click",(function(){if(Ne.isDisplayed(n.details))return Ne.hide(n.details),r.expander.classList.add("ico-arrowdown"),void r.expander.classList.remove("ico-arrowup");Ne.show(n.details),r.expander.classList.remove("ico-arrowdown"),r.expander.classList.add("ico-arrowup"),g&&g.remove()})),Ne.bind(n.header,"mouseenter",(function(){if(!Ne.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=Ne.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),Ne.show(r),Ne.bind(r,"click",(function(e){n(e)}))};qt(i)&&c(u.cancelBttn,(function(e){y(e)})),ft().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"),Ne.mouseInElement(r,e)||Ne.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)}})),ft().bindTooltips(t)};for(g.s();!(v=g.n()).done;)y()}catch(e){g.e(e)}finally{g.f()}Ne.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 ke(K);var r=Ne.formatRateFullPrecision(Lt(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<=2||At(r)?t.activeLight.classList.add("active"):t.activeLight.classList.remove("active"),n.status.textContent=t.status.textContent=Rt(r),n.age.textContent=Ne.timeSince(r.submitTime),n.filled.textContent="".concat((Et(r)/r.qty*100).toFixed(1),"%"),n.settled.textContent="".concat((Bt(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(ft().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(ft().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(ft().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:"showToggleWalletStatus",value:function(e){var t=this.page;this.openAsset=e,Ne.hide(t.toggleWalletStatusErr,t.walletStatusDisable,t.disableWalletMsg),Ne.show(t.walletStatusEnable,t.enableWalletMsg),this.forms.show(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,Ne.hide(t.toggleWalletStatusErr),n={assetID:this.openAsset.id,disable:!1},r=ft().loading(t.toggleWalletStatusConfirm),e.next=7,S("/api/togglewalletstatus",n);case 7:if(a=e.sent,r(),ft().checkResponse(a)){e.next=13;break}return t.toggleWalletStatusErr.textContent=a.msg,Ne.show(t.toggleWalletStatusErr),e.abrupt("return");case 13:Ne.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=ft().assets[n.base],o=ft().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=ft().assets[i.token.parentID];e.src=Ne.logoPath(t.symbol)}else e.src=Ne.logoPath(i.symbol);break;case"to":if(s.token){var n=ft().assets[s.token.parentID];e.src=Ne.logoPath(n.symbol)}else e.src=Ne.logoPath(s.symbol)}},l=Aa(Ne.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=Aa(Ne.applySelector(t.vFeeSummary,"[data-icon]"));try{for(d.s();!(u=d.n()).done;)c(u.value)}catch(e){d.e(e)}finally{d.f()}Ne.hide(t.vPreorderErr),Ne.show(t.vPreorder),t.vBuySell.textContent=ke(r?"SELLING":"BUYING");var h=ke(r?B:E);if(t.vSideSubmit.textContent=h,t.vOrderHost.textContent=n.host,n.isLimit){Ne.show(t.verifyLimit),Ne.hide(t.verifyMarket);var p="Limit ".concat(h," Order");t.vOrderType.textContent=n.tifnow?p+" (immediate)":p,t.vRate.textContent=Ne.formatCoinValue(n.rate/this.market.rateConversionFactor),t.vQty.textContent=Ne.formatCoinValue(n.qty,a.unitInfo);var f=n.rate/Ft*n.qty;t.vTotal.textContent=Ne.formatCoinValue(f,o.unitInfo),this.showFiatValue(o.id,f,t.vFiatTotal)}else{Ne.hide(t.verifyLimit),Ne.show(t.verifyMarket),t.vOrderType.textContent="Market ".concat(h," Order");var v=n.sell?this.market.baseUnitInfo:this.market.quoteUnitInfo;t.vmFromTotal.textContent=Ne.formatCoinValue(n.qty,v),t.vmFromAsset.textContent=i.symbol.toUpperCase(),this.showFiatValue(i.id,n.qty,t.vmFromTotalFiat);var m=this.midGap();if(m){Ne.show(t.vMarketEstimate);var g=n.sell?n.qty*m:n.qty/m;t.vmToTotal.textContent=Ne.formatCoinValue(g,s.unitInfo),t.vmToAsset.textContent=s.symbol.toUpperCase(),this.showFiatValue(s.id,g,t.vmTotalFiat)}else Ne.hide(t.vMarketEstimate)}r?(t.vHeader.classList.add(Va),t.vHeader.classList.remove(Wa),t.vSubmit.classList.add(Va),t.vSubmit.classList.remove(Wa)):(t.vHeader.classList.add(Wa),t.vHeader.classList.remove(Va),t.vSubmit.classList.add(Wa),t.vSubmit.classList.remove(Va)),this.showVerifyForm(),a.wallet.open&&o.wallet.open?this.preOrder(n):(Ne.hide(t.vPreorder),this.unlockWalletsForEstimates())}},{key:"showFiatValue",value:function(e,t,n){if(n){var r=ft().fiatRatesMap[e];n.textContent=Ne.formatFiatConversion(t,r,ft().unitInfo(e)),r?Ne.show(n.parentElement):Ne.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,Ne.hide(t.vErr),this.forms.show(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=ft().loading(t.verifyForm),e.next=4,this.unlockMarketWallets();case 4:n(),Ne.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:(C=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,S("/api/openwallet",{assetID:t});case 2:if(n=e.sent,ft().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 C.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=Ne.formatCoinValue(e.estimate.realisticBestCase,x);var I=e.estimate.realisticWorstCase/T*100;r.vSwapFeesHighPct.textContent=w<=0?"":"(".concat(c(I),"%)"),r.vSwapFeesHigh.textContent=Ne.formatCoinValue(e.estimate.realisticWorstCase,x);var A=e.estimate.maxFees/T*100;r.vSwapFeesMaxPct.textContent=w<=0?"":"(".concat(c(A),"%)"),r.vSwapFeesMax.textContent=Ne.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=Ne.formatCoinValue(t.estimate.realisticBestCase,b);var L=t.estimate.realisticWorstCase/B*100;r.vRedeemFeesHighPct.textContent=k<=0?"":"(".concat(c(L),"%)"),r.vRedeemFeesHigh.textContent=Ne.formatCoinValue(t.estimate.realisticWorstCase,b),l&&u?(Ne.show(r.vFeeSummaryPct),Ne.hide(r.vFeeSummary),r.vFeeSummaryLow.textContent=c(D+P),r.vFeeSummaryHigh.textContent=c(I+L)):(Ne.hide(r.vFeeSummaryPct),Ne.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 Ne.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=ft().loading(t.cancelSubmit),e.next=7,S("/api/cancel",a);case 7:if(s=e.sent,o(),ft().checkResponse(s)){e.next=13;break}return t.cancelErr.textContent=s.msg,Ne.show(t.cancelErr),e.abrupt("return");case 13:Ne.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=It(n)?this.market.quote:this.market.base;r.cancelRemain.textContent=Ne.formatCoinValue(a,o.unitInfo),r.cancelUnit.textContent=o.symbol.toUpperCase(),Ne.hide(r.cancelErr),this.forms.show(r.cancelForm),this.cancelData={bttn:Ne.tmplElement(e,"cancelBttn"),order:n}}},{key:"showAccelerate",value:function(e){var t=ft().loading(this.main);this.accelerateOrderForm.refresh(e),t(),this.forms.show(this.page.accelerateForm)}},{key:"showCreate",value:function(e){var t=this.page;this.currentCreate=e,this.newWalletForm.setAsset(e.id),this.forms.show(t.newWalletForm)}},{key:"stepSubmit",value:function(){var e=this.page,t=this.market;if(Ne.hide(e.orderErr),this.validateOrder(this.parseOrder())){var n=ft().walletMap[t.base.id],r=ft().walletMap[t.quote.id];return n?r?void this.showVerify():(e.orderErr.textContent=ke(L,{asset:t.quote.symbol}),void Ne.show(e.orderErr)):(e.orderErr.textContent=ke(L,{asset:t.base.symbol}),void Ne.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.forms.show(this.page.deposit);case 2:case"end":return e.stop()}}),e,this)}))),function(e){return u.apply(this,arguments)})},{key:"showCustomProviderDialog",value:function(e){ft().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,ft().fetchUser();case 8:this.market.dex=ft().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=ft().exchanges[n].auth;e.parcelSizeLots.textContent=String(r.parcelsize),e.marketLimitBase.textContent=Ne.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=Ne.formatFourSigFigs(r.parcelsize*l/s.conventional.conversionFactor)}else e.marketLimitQuote.textContent="-";var u=dn(i);e.tradingTier.textContent=String(u);var d=function(e){for(var t=ft().exchanges[e],n=t.auth,r=t.maxScore,a=t.markets,o=n.rep.score,s=dn(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*Ft,o,this.midGapConventional()||0]}if(t&&t.rate)return[t.rate,t.rate/Ft,t.rate/a];var s=[ft().fiatRatesMap[n],ft().fiatRatesMap[r]],i=s[0],c=s[1];if(i&&c){var l=i/c,u=l*a;return[u,u/Ft,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(2===t.ord.type&&0===n.status){var r=ft().order(e.orderID);r&&(t.details.rate.textContent=t.header.rate.textContent=this.marketOrderRateString(r,this.market))}(0===n.side&&3===n.status||1===n.side&&4===n.status)&&this.updateReputation(),ft().canAccelerateOrder(t.ord)?Ne.show(t.details.accelerateBttn):Ne.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&&Ne.show(n.details.cancelBttn),t.filled===t.qty&&Ne.hide(n.details.cancelBttn),ft().canAccelerateOrder(t)?Ne.show(n.details.accelerateBttn):Ne.hide(n.details.accelerateBttn),this.updateMetaOrder(n),(1===a&&2===t.status||2===a&&t.status>2)&&(this.setDepthMarkers(),this.updateReputation(),this.mm.readBook())}},{key:"handleEpochNote",value:function(e){if(ft().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 1===a.type&&1===a.status&&i:var c=0===a.tif?ke(O):ke(M);o.status.textContent=s.status.textContent=c,a.status=0===a.tif?3:2;break;case 2===a.type&&1===a.status:o.status.textContent=s.status.textContent=ke(O),a.status=3}}}}},{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(Ne.empty(e.recentMatchesLiveList),t){var n=this.recentMatchesSortCompare();t.sort(n);var r,a=Aa(t);try{for(a.s();!(r=a.n()).done;){var o=r.value,s=e.recentMatchesTemplate.cloneNode(!0),i=Ne.parseTemplate(s);ft().bindTooltips(s),i.rate.textContent=Ne.formatCoinValue(o.rate/this.market.rateConversionFactor),i.qty.textContent=Ne.formatCoinValue(o.qty,this.market.baseUnitInfo),i.age.textContent=Ne.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===ut.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,Ne.hide(t.orderErr,t.vErr),n=this.currentOrder,r={order:Za(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,S("/api/tradeasync",r);case 10:if(a=e.sent,t.vSubmit.classList.remove("d-hide"),t.vLoader.classList.add("d-hide"),ft().checkResponse(a)){e.next=17;break}return t.vErr.textContent=a.msg,Ne.show(t.vErr),e.abrupt("return");case 17:Ne.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,ft().fetchUser();case 2:if(t=e.sent){e.next=5;break}return e.abrupt("return");case 5:n=t.assets[this.currentCreate.id],Ne.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,ke(re));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=ft().assets[this.market.base.id].wallet;this.setOrderBttnEnabled(n<=r.balance.available,ke(ne))}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=Ya(e.mktBuyField.value||"",this.market.quoteUnitInfo.conventional.conversionFactor),n=this.midGap();if(t>0){var r=ft().assets[this.market.quote.id].wallet;this.setOrderBttnEnabled(t<=r.balance.available,ke(te))}else this.setOrderBttnEnabled(!1,ke(re));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=Ne.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=Ya(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;Ne.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?(Ne.show(n.expired),i.running&&ft().fetchBalance(o)):Ne.hide(n.expired)}else Ne.show(n.connect)}else Ne.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=Ne,e.next=3,ft().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=ft().assets[e.parentID],r=n.wallet.balance,a=n.unitInfo;null!==(t=e.parentBal)&&void 0!==t&&t.firstChild&&(e.parentBal.firstChild.textContent=Ne.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 Ka(e,t,n){return{host:e,base:t,quote:n}}function Qa(e,t){return"".concat(e,"_").concat(t)}function Ya(e,t){return e?Math.round(parseFloat(e)*t):0}function Ja(e,t){e.classList.remove("selected"),t.classList.add("selected")}function Za(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 eo(e,t,n){if(n.spot){e.price.textContent=Ne.formatFourSigFigs(ft().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 to=[.5,1/4,3/4,1/8,5/8,3/8,7/8];function no(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 ro(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)?ro(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 ro(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),Ne.bind(a,"click",(function(){t.submitFilter(),s.forEach((function(e){return Ne.hide(e)}))})),e.querySelectorAll("input").forEach((function(t){Ne.bind(t,"change",(function(){!function(e,t){if(e.length!==t.length)return!1;var n,r=no(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}(oo(e),r[n])?Ne.show(a):Ne.hide(a)}))}))};return c(n.hostFilter,"hosts"),c(n.assetFilter,"assets"),c(n.statusFilter,"statuses"),Ne.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){Ne.bind(e,"click",(function(){Ne.hide(n.forms)}))})),Ne.bind(n.forms,"mousedown",(function(e){Ne.mouseInElement(e,t.currentForm)||Ne.hide(n.forms)})),Ne.bind(n.exportOrders,"click",(function(){t.exportOrders()})),n.showArchivedDateField.addEventListener("change",(function(){n.showArchivedDateField.checked?Ne.show(n.archivedDateField):Ne.hide(n.archivedDateField,n.deleteArchivedRecordsErr)})),Ne.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="",Ne.hide(e.deleteArchivedResult,e.deleteArchivedRecordsErr,e.deleteArchivedRecordsMsg,e.archivedRecordsLocation,e.archivedDateField),t.showForm(e.deleteArchivedRecordsForm)})),Ne.bind(n.deleteArchivedRecordsSubmit,"click",(function(){var e=0;n.showArchivedDateField.checked&&(e=Date.parse(n.olderThan.value||""),isNaN(e)||e<=0)?Ne.showFormError(n.deleteArchivedRecordsErr,ke("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,Ne.hide(n.deleteArchivedRecordsForm),t.style.right="10000px",Ne.show(n.forms,t),r=(n.forms.offsetWidth+t.offsetWidth)/2,e.next=8,Ne.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){Ne.empty(this.page.tableBody),this.appendOrders(e)}},{key:"appendOrders",value:function(e){var t,n=this.page.tableBody,r=no(e);try{for(r.s();!(t=r.n()).done;){var a=t.value,o=this.orderTmpl.cloneNode(!0),s=Ne.parseTemplate(o),i=void 0,c=void 0,l=void 0,u=void 0,d=void 0,h="",p=ft().exchanges[a.host]||void 0;if((ft().assets[a.baseID]||p.assets[a.baseID])&&(ft().assets[a.quoteID]||p.assets[a.quoteID])){var f=[ft().unitInfo(a.baseID,p),ft().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=Ne.formatCoinValue(a.qty,v),1===a.type&&(h=Ne.formatCoinValue(a.qty/Ft*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],2===a.type?d=Ne.formatCoinValue(a.qty,v):(d=Ne.formatCoinValue(a.qty/Ft*a.rate,m),h=Ne.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=Ne.logoPath(i),s.fromSymbol.textContent=l,s.toQty.textContent=h,s.toLogo.src=Ne.logoPath(c),s.toSymbol.textContent=u,s.type.textContent="".concat(Dt(a)," ").concat(Tt(a));var w=Ne.formatCoinValue(ft().conventionalRate(a.baseID,a.quoteID,a.rate,p));2===a.type&&(w=Pt(a)),s.rate.textContent=w,s.status.textContent=Rt(a),s.filled.textContent="".concat((Et(a)/a.qty*100).toFixed(1),"%"),s.settled.textContent="".concat((Bt(a)/a.qty*100).toFixed(1),"%");var C=new Date(a.submitTime).toLocaleString();s.timeAgo.textContent="".concat(Ne.timeSince(a.submitTime)," ago"),s.time.textContent=C,Ne.tmplElement(o,"link").href="order/".concat(a.id),ft().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=oo(t.hostFilter),n.assets=oo(t.assetFilter).map((function(e){return parseInt(e)})),n.statuses=oo(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=ft().loading(this.main),e.next=3,S("/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=ft().loading(this.main),e.next=7,S("/api/deletearchivedrecords",o);case 7:if(i=e.sent,s(),ft().checkResponse(i)){e.next=11;break}return e.abrupt("return",Ne.showFormError(n.deleteArchivedRecordsErr,i.msg));case 11:i.archivedRecordsDeleted>0?(n.deleteArchivedRecordsMsg.textContent=ke("DELETE_ARCHIVED_RECORDS_RESULT",{nRecords:i.archivedRecordsDeleted}),(r||a)&&(n.archivedRecordsLocation.textContent=ke("ARCHIVED_RECORDS_PATH",{path:i.archivedRecordsPath}),Ne.show(n.archivedRecordsLocation)),this.submitFilter()):n.deleteArchivedRecordsMsg.textContent=ke("NO_ARCHIVED_RECORDS"),Ne.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,Ne.show(this.page.orderLoader),e.next=6,this.fetchOrders();case 6:t=e.sent,this.loading=!1,Ne.hide(this.page.orderLoader),this.appendOrders(t);case 10:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})}]),p}(lt);function oo(e){var t=[];return e.querySelectorAll("input").forEach((function(e){e.checked&&t.push(e.value)})),t}function so(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 io(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)?io(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 io(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);no.getTime())n.refundPending.textContent=ke("REFUND_IMMINENT");else{var s=o.toLocaleTimeString(Ne.languages(),{year:"numeric",month:"short",day:"numeric"});n.refundPending.textContent=ke("REFUND_WILL_HAPPEN_AFTER",{refundAfterTime:s})}Ne.hide(n.refundCoin),Ne.show(n.refundPending)}if(1!==t.status||t.revoked||t.refund)if(2!==t.status||t.revoked||t.refund)!function(e){return e.status<5&&0===e.side&&e.status>=3}(t)||t.revoked||t.refund?!function(e){return e.status<5&&1===e.side&&e.status>=4}(t)||t.revoked||t.refund?Ne.hide(n.makerSwapMsg,n.takerSwapMsg,n.makerRedeemMsg,n.takerRedeemMsg):(n.takerRedeemMsg.textContent=uo(t.redeem),Ne.hide(n.makerSwapMsg,n.takerSwapMsg,n.makerRedeemMsg),Ne.show(n.takerRedeemMsg)):(n.makerRedeemMsg.textContent=uo(t.redeem),Ne.hide(n.makerSwapMsg,n.takerSwapMsg,n.takerRedeemMsg),Ne.show(n.makerRedeemMsg));else{var i=po(t);n.takerSwapMsg.textContent=uo(i),Ne.hide(n.makerSwapMsg,n.makerRedeemMsg,n.takerRedeemMsg),Ne.show(n.takerSwapMsg)}else{var c=ho(t);n.makerSwapMsg.textContent=uo(c),Ne.hide(n.takerSwapMsg,n.makerRedeemMsg,n.takerRedeemMsg),Ne.show(n.makerSwapMsg)}if(t.revoked){Ne.setVis(ho(t),n.makerSwap),Ne.setVis(po(t),n.takerSwap);var l=new Date(t.stamp+co),u=Date.now()>l.getTime();Ne.setVis(fo(t)||po(t)&&t.active&&!t.refund&&!u,n.makerRedeem),Ne.setVis(vo(t)||fo(t)&&t.active&&!t.refund,n.takerRedeem);var d=Boolean(po(t));0===t.side&&(d=Boolean(ho(t)),po(t)&&(d=d&&u)),Ne.setVis(t.refund||t.active&&!t.redeem&&!t.counterRedeem&&d,n.refund)}else Ne.setVis(ho(t)||t.active,n.makerSwap),Ne.setVis(po(t)||t.active,n.takerSwap),Ne.setVis(fo(t)||t.active,n.makerRedeem),Ne.setVis(vo(t)||t.active,n.takerRedeem),Ne.setVis(t.refund,n.refund)}}},{key:"addNewMatchCard",value:function(e){var t=this.page,n=t.matchCardTmpl.cloneNode(!0);ft().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=It(e)?ft().assets[e.quoteID]:ft().assets[e.baseID];t.cancelRemain.textContent=Ne.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,Ne.hide(n.cancelForm,n.accelerateForm),t.style.right="10000px",Ne.show(n.forms,t),r=(n.forms.offsetWidth+t.offsetWidth)/2,e.next=8,Ne.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=ft().loading(t.cancelForm),e.next=6,S("/api/cancel",r);case 6:if(o=e.sent,a(),ft().checkResponse(o)){e.next=10;break}return e.abrupt("return");case 10:t.status.textContent=ke(q),Ne.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;Ne.setVis(ft().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=ft().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>2&&Ne.hide(r),t.status.textContent=Rt(n);var a,o=so(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=so(Ne.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}(lt);function uo(e){return e.confs&&0!==e.confs.required?"".concat(e.confs.count," / ").concat(e.confs.required," ").concat(ke("CONFIRMATIONS")):""}function ho(e){return 0===e.side?e.swap:e.counterSwap}function po(e){return 0===e.side?e.counterSwap:e.swap}function fo(e){return 0===e.side?e.redeem:e.counterRedeem}function vo(e){return 0===e.side?e.counterRedeem:e.redeem}function mo(){return mo="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}},mo.apply(this,arguments)}function go(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 yo(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)?yo(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 yo(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=Ne.parseTemplate(c),u=function(){t.cexConfigForm.setCEX(r),t.forms.show(n.cexConfigForm)};Ne.bind(l.configureBttn,"click",u),Ne.bind(l.reconfigBttn,"click",u),Ne.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(Gn);o=768;if(e!==this.twoColumn){this.twoColumn=e,this.clearBotBoxes();var t,n=go(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:(u=s(f().mark((function e(){var t,n,a,o,s,i,c,l,u=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=this.page,n=ft().mmStatus,a=n.bots.map((function(e){return e.config})),ft().registerNoteFeeder({runstats:function(e){u.handleRunStatsNote(e)},runevent:function(e){var t=u.bots[$n(e.host,e.baseID,e.quoteID)];if(t)return t.handleRunStats()},epochreport:function(e){var t=u.bots[$n(e.host,e.baseID,e.quoteID)];t&&t.handleEpochReportNote(e)},cexproblems:function(e){var t=u.bots[$n(e.host,e.baseID,e.quoteID)];t&&t.handleCexProblemsNote(e)},cexnote:function(e){u.handleCEXNote(e)}}),o=!a||0===a.length,Ne.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=go(s);try{for(i.s();!(c=i.n()).done;)l=c.value,this.addBot(l)}catch(e){i.e(e)}finally{i.f()}case 12:case"end":return e.stop()}}),e,this)}))),function(){return u.apply(this,arguments)})},{key:"handleCEXNote",value:(l=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 l.apply(this,arguments)})},{key:"handleCEXBalanceUpdate",value:(c=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 c.apply(this,arguments)})},{key:"handleRunStatsNote",value:(o=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[$n(a,n,r)])){e.next=4;break}return e.abrupt("return",o.handleRunStats());case 4:this.addBot(ft().botStatus(a,n,r));case 5:case"end":return e.stop()}}),e,this)}))),function(e){return o.apply(this,arguments)})},{key:"unload",value:function(){Ne.unbind(document,"keyup",this.keyup)}},{key:"addBot",value:function(e){var t,n=this.page,r=this.bots,a=this.sortedBots,o=e.config,s=o.baseID,i=o.quoteID,c=o.host,l=[ft().assets[s].symbol,ft().assets[i].symbol],u=l[1],d="".concat(l[0],"_").concat(u);if(null!==(t=ft().exchanges[c])&&void 0!==t&&t.markets[d]){var h=new wo(this,this.runningMMDisplayElements,e);n.botRows.appendChild(h.row.tr),a.push(h),r[h.id]=h,this.appendBotBox(h.div)}}},{key:"confirmRemoveCfg",value:function(e){var t=this.page;this.removingCfg=e,Ne.hide(t.removeCfgErr);var n=ft().assets[e.baseID].unitInfo.conventional.unit,r=ft().assets[e.quoteID].unitInfo.conventional.unit;t.confirmRemoveCfgMsg.textContent=ke("DELETE_BOT",{host:e.host,baseTicker:n,quoteTicker:r}),this.forms.show(this.page.confirmRemoveForm)}},{key:"removeCfg",value:(n=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,this.removingCfg){e.next=4;break}return this.forms.close(),e.abrupt("return");case 4:return e.next=6,Xn.removeBotConfig(this.removingCfg.host,this.removingCfg.baseID,this.removingCfg.quoteID);case 6:if(n=e.sent,ft().checkResponse(n)){e.next=11;break}return t.removeCfgErr.textContent=ke(H,{msg:n.msg}),Ne.show(t.removeCfgErr),e.abrupt("return");case 11:return e.next=13,ft().fetchMMStatus();case 13:ft().loadPage("mm");case 14:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{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=go(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;Ne.animate(250,(function(e){s.style.opacity="".concat(e),s.style.transform="scale(".concat(.8+.2*e,")")}))}},{key:"newBot",value:function(){ft().loadPage("mmsettings")}},{key:"cexConfigured",value:(t=s(f().mark((function e(t,n){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,ft().fetchMMStatus();case 2:this.updateCexRow(this.cexes[t]),n&&this.forms.close();case 4:case"end":return e.stop()}}),e,this)}))),function(e,n){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=ft().mmStatus.cexes[r];if(Ne.setVis(!o,t.unconfigured),Ne.setVis(o&&!o.connectErr,t.configured),Ne.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&&(x=m.reduce((function(e,t){return t.gapFactor0&&(k=g.reduce((function(e,t){return t.gapFactor0,c.hasTransferable),Ne.setVis(D.fundedAndNotBalanced,c.fundedAndNotBalancedBox),Ne.setVis(D.starved,c.starvedBox),c.startBttn.classList.toggle("go",D.fundedAndBalanced),c.startBttn.classList.toggle("warning",!D.fundedAndBalanced),c.proposedDexBaseAlloc.classList.toggle("text-warning",!(D.base.fundedAndBalanced||D.base.fundedAndNotBalanced)),c.proposedDexQuoteAlloc.classList.toggle("text-warning",!(D.quote.fundedAndBalanced||D.quote.fundedAndNotBalanced));var N=function(e,t){c.proposedDexBaseAlloc.textContent=Ne.formatFourSigFigs(e),c.proposedDexBaseAllocUSD.textContent=Ne.formatFourSigFigs(e*u),c.proposedCexBaseAlloc.textContent=Ne.formatFourSigFigs(t),c.proposedCexBaseAllocUSD.textContent=Ne.formatFourSigFigs(t*u)};if(N(A,R),Ne.setVis(E,c.baseAllocSlider),E){var W=E.right.dex-E.left.dex,V=E.right.cex-E.left.cex;this.baseAllocSlider.setValue(.5),this.baseAllocSlider.changed=function(e){var t=E.left.dex+e*W,n=E.left.cex+e*V;M.dex[p]=t*x,M.cex[p]=n*x,N(t,n)}}var U=function(e,t){c.proposedDexQuoteAlloc.textContent=Ne.formatFourSigFigs(e),c.proposedDexQuoteAllocUSD.textContent=Ne.formatFourSigFigs(e*d),c.proposedCexQuoteAlloc.textContent=Ne.formatFourSigFigs(t),c.proposedCexQuoteAllocUSD.textContent=Ne.formatFourSigFigs(t*d)};if(U(P,L),Ne.setVis(O,c.quoteAllocSlider),O){var _=O.right.dex-O.left.dex,j=O.right.cex-O.left.cex;this.quoteAllocSlider.setValue(.5),this.quoteAllocSlider.changed=function(e){var t=O.left.dex+e*_,n=O.left.cex+e*j;M.dex[f]=t*k,M.cex[f]=n*k,U(t,n)}}if(Ne.setVis.apply(Ne,[v!==p].concat(r(Ne.applySelector(c.allocationDialog,"[data-base-token-fees]")))),v!==p){var H=D.base.fees.req+(v===m?D.quote.fees.req:0),z=Math.min(H,D.base.fees.avail);c.proposedDexBaseFeeAlloc.textContent=Ne.formatFourSigFigs(z),c.proposedDexBaseFeeAllocUSD.textContent=Ne.formatFourSigFigs(z*g),c.proposedDexBaseFeeAlloc.classList.toggle("text-warning",!D.base.fees.funded)}var G=m!==f&&m!==v;if(Ne.setVis.apply(Ne,[G].concat(r(Ne.applySelector(c.allocationDialog,"[data-quote-token-fees]")))),G){var X=Math.min(D.quote.fees.req,D.quote.fees.avail);c.proposedDexQuoteFeeAlloc.textContent=Ne.formatFourSigFigs(X),c.proposedDexQuoteFeeAllocUSD.textContent=Ne.formatFourSigFigs(X*y),c.proposedDexQuoteFeeAlloc.classList.toggle("text-warning",!D.quote.fees.funded)}var K=null===(s=ft().exchanges[S])||void 0===s?void 0:s.markets[F],Q=!1;if(K&&K.orders)for(var Y=0;Y=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 To(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;Ne.show(e.advancedConfig),Ne.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-Eo)/Bo),this.qcLevelSpacing.setValue(100*h),this.qcLevelSpacingSlider.setValue((h-Po)/Lo)}else if(n===Hn){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===zn&&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)),Ne.hide(t.advancedConfig),Ne.show(t.quickConfig),this.showInputsForBot(r)}},{key:"showInputsForBot",value:function(e){var t=this.page,n=this.opts.usingUSDPerSide;switch(Ne.hide(t.matchMultiplierBox,t.placementsChartBox,t.placementChartLegend,t.lotsPerLevelLabel,t.levelSpacingBox,t.arbLotsLabel,t.qcLevelPerSideBox),Ne.setVis(n,t.qcUSDPerSideBox),Ne.setVis(!n,t.qcLotsBox),e){case Hn:Ne.show(t.qcLevelPerSideBox,t.matchMultiplierBox,t.placementsChartBox,t.placementChartLegend,t.lotsPerLevelLabel);break;case jn:Ne.show(t.qcLevelPerSideBox,t.levelSpacingBox,t.placementsChartBox,t.lotsPerLevelLabel);break;case zn:Ne.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;Ne.hide(a.qcError);var c=function(e){a.qcError.textContent=e,Ne.show(a.qcError)},l=s===zn?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===jn?parseFloat(null!==(t=a.qcLevelSpacing.value)&&void 0!==t?t:"")/100:0;isNaN(h)&&c("invalid value for level spacing");var p=s===Hn?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!==zn){this.clearPlacements(i?Ro:o.gapStrategy);for(var m=0;m0,F=Fo(this.botTypeSelectors);try{for(F.s();!(T=F.n()).done;)(D=T.value).classList.toggle("disabled",D.dataset.botType!==jn&&!S)}catch(e){F.e(e)}finally{F.f()}0===Object.keys(ft().mmStatus.cexes).length?(Ne.show(s.noCexesConfigured),this.setBotTypeSelected(jn)):(A=k.fetchLocal(Io)||{},R=A["".concat(n,"_").concat(r,"_").concat(t)],(a=null!==(I=a)&&void 0!==I?I:R?R.botType:Hn)!==jn&&(o&&(E=y[o]),!E&&R&&(E=y[null!==(B=R.cexName)&&void 0!==B?B:""]),E||(P=k.fetchLocal(Ao))&&(E=y[P]),!E&&C>0&&(E=Object.values(y)[0])),E?(s.cexSelection.classList.remove("disabled"),this.setBotTypeSelected(null!==(L=a)&&void 0!==L?L:R?R.botType:Hn),this.selectFormCEX(E.name)):(s.cexSelection.classList.add("disabled"),Ne.show(s.noCexMarket),this.setBotTypeSelected(jn),0===(O=Object.keys(Gn).filter((function(e){return!ft().mmStatus.cexes[e]}))).length||1===O.length&&("Binance"===O[0]||"BinanceUS"===O[0])||Ne.show(s.noCexMarketConfigureMore))),Ne.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(){No(this.specs,ft().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=Fo(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!==jn){var h=ft().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(Io)||{})["".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(Ao);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();Ne.empty(t.marketSelect);var r,a=Fo(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=ft().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,ft().walletMap[s]){e.next=5;break}return this.newWalletForm.setAsset(s),r.show(this.page.newWalletForm),e.abrupt("return");case 5:if(ft().walletMap[i]){e.next=9;break}return this.newWalletForm.setAsset(i),r.show(this.page.newWalletForm),e.abrupt("return");case 9:if(l=Vo(c,ft().assets[s],ft().assets[i]),u=a(l,2),d=u[0],h=u[1],d!==dt.NotApproved){e.next=14;break}return this.approveTokenForm.setAsset(s,c),r.show(n.approveTokenForm),e.abrupt("return");case 14:if(h!==dt.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=ke("NO_BOTTYPE"),Ne.show(n.botTypeErr),e.abrupt("return");case 24:if((this.formSpecs.botType=null!==(t=v[0].dataset.botType)&&void 0!==t?t:"")===jn){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=ke("NO_CEX"),Ne.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!==jn&&o){e.next=4;break}return e.abrupt("return");case 4:return e.prev=4,e.next=7,Xn.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=ke(ve,{cexName:o,assetID:String(r),err:String(e.t0)}),Ne.show(n.botTypeErr),e.t0;case 15:return e.prev=15,e.next=18,Xn.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=ke(ve,{cexName:o,assetID:String(a),err:String(e.t1)}),Ne.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=ft().currentWalletDefinition(e);if(!t.multifundingopts)return{};var n,r={},a=Fo(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 Wn:case Vn:return t<=0?"Rate must be greater than 0":null;case Un: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 Nn:case Wn:case Vn:return e;case Un: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),Ne.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===Ro?Nn:e,c=Fo(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=Fo(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?Ro:i.gapStrategy),function(e,t){for(var n=0,r=Object.entries(t);n0?t.baseFiatRate.textContent=Ne.formatFourSigFigs(i.baseFiatRate):t.baseFiatRate.textContent="N/A",i.quoteFiatRate>0?t.quoteFiatRate.textContent=Ne.formatFourSigFigs(i.quoteFiatRate):t.quoteFiatRate.textContent="N/A",Ne.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=Gn[t],c=Fo(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,Hn,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(Gn);e0,s.redemptionFeesBox),o.bookingFeesPerCounterLot>0){var w=o.bookingFeesPerCounterLot/d.conventional.conversionFactor;s.redemptionFeesPerLot.textContent=Ne.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=Ne.formatCoinValue(Math.round(r*n.conventional.conversionFactor),n),e.commitTotalFiat.textContent=Ne.formatFourSigFigs(r*ft().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=Ne.formatCoinValue(a*r.conventional.conversionFactor,r),e.feeTotalFiat.textContent=Ne.formatFourSigFigs(a*ft().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(Ne.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=ft().currentWalletDefinition(n);if(Ne.empty(t.walletSettings),Ne.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=Ne.parseTemplate(o);h.name.textContent=n.displayname,h.input.checked="true"===d,Ne.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=Fo(n);try{for(a.s();!(r=a.n()).done;){var o=r.value;Ne.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=Ne.parseTemplate(o);y.name.textContent=n.displayname,n.description&&(y.tooltip.dataset.tooltip=n.description),m?y.unit.textContent=m:Ne.hide(y.unit);var b=new Ye(y.value,{prec:1,changed:function(e){var t=a(et(e,1),2),o=t[0],s=t[1];r[n.key]=s,x.setValue((o-f.x)/g)}}),x=new Ze(y.slider,(function(e){var t=a(et(f.x+e*g,1),2),o=t[0],s=t[1];r[n.key]=s,b.setValue(o)})),k=a(et(tt(d,f.x),3),2),w=k[0],C=k[1];r[n.key]=C,x.setValue((w-f.x)/g),b.setValue(w),y.value.textContent=C}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 S=r[n.dependsOn];Ne.setVis("true"===S,o)}}};if(o.multifundingopts&&o.multifundingopts.length>0){var l,u=Fo(o.multifundingopts);try{for(u.s();!(l=u.n()).done;)c(l.value)}catch(e){u.e(e)}finally{u.f()}}ft().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=ft().walletMap[t].balance.available,h=this.pg.runningBotInventory(t),p=d-h.dex.total,f=0;if(Ne.setVis(i,e.balanceBreakdown),i&&(e.dexAvail.textContent=Ne.formatFourSigFigs(p/n.conventional.conversionFactor),f=(t===c?l:u).available-h.cex.total,e.cexAvail.textContent=Ne.formatFourSigFigs(f/n.conventional.conversionFactor)),e.avail.textContent=Ne.formatFourSigFigs((p+f)/n.conventional.conversionFactor),t!==r){var v=ft().walletMap[r].balance.available;e.feeAvail.textContent=Ne.formatFourSigFigs(v/a.conventional.conversionFactor)}}}]),e}();var _o=function(e){g(I,e);var t,n,r,a,o,c,l,u,p,m,x,k,w,C,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=ft().exchanges[n],a=t.page=Ne.idDescendants(e);t.forms=Ne.applySelector(a.forms,":scope > form"),t.confirmRegisterForm=new mr(a.confirmRegForm,s(f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t.showSuccess(ke(se)),t.renewToggle.setState(t.confirmRegisterForm.tier>0),e.next=4,ft().fetchUser();case 4:ft().updateMenuItemsDisplay();case 5:case"end":return e.stop()}}),e)}))),(function(){t.runAnimation(t.regAssetForm,a.regAssetForm)})),t.confirmRegisterForm.setExchange(r,""),t.walletWaitForm=new yr(a.walletWait,(function(){t.runAnimation(t.confirmRegisterForm,a.confirmRegForm)}),(function(){t.runAnimation(t.regAssetForm,a.regAssetForm)})),t.walletWaitForm.setExchange(r),t.newWalletForm=new pr(a.newWalletForm,(function(e){return t.newWalletCreated(e,t.confirmRegisterForm.tier)}),(function(){return t.runAnimation(t.regAssetForm,a.regAssetForm)})),t.regAssetForm=new gr(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!==pt){e.next=6;break}return e.next=3,ft().fetchUser();case 3:return t.updateReputation(),t.showSuccess(ke(se)),e.abrupt("return");case 6:if(o=ft().assets[n],!(s=o.wallet)){e.next=17;break}return i=ft().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 un(a.repMeter),t.reputationMeter.setHost(n),Ne.bind(a.exportDexBtn,"click",(function(){return t.exportAccount()})),t.accountDisabled="true"===e.dataset.disabled,Ne.bind(a.toggleAccountStatusBtn,"click",(function(){t.accountDisabled?t.toggleAccountStatus(!1):t.prepareAccountDisable(a.disableAccountForm)})),Ne.bind(a.updateCertBtn,"click",(function(){return a.certFileInput.click()})),Ne.bind(a.updateHostBtn,"click",(function(){return t.prepareUpdateHost()})),Ne.bind(a.certFileInput,"change",(function(){return t.onCertFileChange()})),Ne.bind(a.goBackToSettings,"click",(function(){return ft().loadPage("settings")}));var o=function(){t.regAssetForm.setExchange(ft().exchanges[n],""),t.showForm(a.regAssetForm)};Ne.bind(a.changeTier,"click",(function(){o()}));var c=r.auth.targetTier>0;t.renewToggle=new _e(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)}}()),Ne.bind(a.autoRenewBox,"click",(function(e){e.stopPropagation(),t.accountDisabled||a.toggleAutoRenew.click()})),a.penaltyComps.textContent=String(r.auth.penaltyComps);var l=function(){Ne.hide(a.penaltyCompInput),Ne.show(a.penaltyComps)};return Ne.bind(a.penaltyCompBox,"click",(function(e){e.stopPropagation();var n=ft().exchanges[t.host];a.penaltyCompInput.value=String(n.auth.penaltyComps),Ne.hide(a.penaltyComps),Ne.show(a.penaltyCompInput),a.penaltyCompInput.focus(),Ne.bind(document,"click",(function e(t){Ne.mouseInElement(t,a.penaltyCompBox)||(l(),Ne.unbind(document,"click",e))}))})),Ne.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(Ne.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 Ne.show(a.penaltyCompsErr),a.penaltyCompsErr.textContent=ke("INVALID_COMPS_VALUE"),e.abrupt("return");case 11:return o=ft().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(),Ne.show(a.penaltyCompsErr),a.penaltyCompsErr.textContent=ke(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 xr(a.dexAddrForm,function(){var e=s(f().mark((function e(t){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:ft().loadPage("/dexsettings/".concat(t.host));case 1:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),t.host),Br(a.disableAccountForm,a.disableAccountConfirm,(function(){return t.toggleAccountStatus(!0)})),Ne.bind(a.forms,"mousedown",(function(e){Ne.mouseInElement(e,t.currentForm)||t.closePopups()})),t.keyup=function(e){"Escape"===e.key&&t.closePopups()},Ne.bind(document,"keyup",t.keyup),Ne.applySelector(a.forms,".form-closer").forEach((function(e){Ne.bind(e,"click",(function(){t.closePopups()}))})),ft().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(){Ne.unbind(document,"keyup",this.keyup)}},{key:"progressTierFormsWithWallet",value:(C=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=ft().assets[t],s=this.regAssetForm.xc.bondAssets,i=s[o.symbol],n.open){e.next=12;break}return c=ft().loading(r.forms),e.next=8,S("/api/openwallet",{assetID:t});case 8:return l=e.sent,c(),ft().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 C.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=ft().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=ft().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(ke(se));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=ft().exchanges[this.host].auth,n=t.rep.penalties,r=t.targetTier,a=t.expiredBonds,o=dn(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 Ne.hide(e)})),t.style.right="10000px",Ne.show(n.forms,t),r=(n.forms.offsetWidth+t.offsetWidth)/2,e.next=8,Ne.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 Ne.hide(this.currentForm),e.next=3,t.animate();case 3:this.currentForm=n,Ne.show(n);case 5:case"end":return e.stop()}}),e,this)}))),function(e,t){return x.apply(this,arguments)})},{key:"closePopups",value:function(){Ne.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 Ne.hide(e)})),this.currentForm=this.page.checkmarkForm,this.animation=Er(this.page,t),e.next=5,this.animation.wait();case 5:this.animation=new We(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=ft().loading(this.body),e.next=5,S("/api/exportaccount",r);case 5:if(o=e.sent,a(),ft().checkResponse(o)){e.next=11;break}return t.exportAccountErr.textContent=o.msg,Ne.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(),Ne.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,Ne.hide(n.errMsg),r=this.host,t&&(r=n.disableAccountHost.textContent),a={host:r,disable:t},o=ft().loading(this.body),e.next=8,S("/api/toggleaccountstatus",a);case 8:if(s=e.sent,o(),ft().checkResponse(s)){e.next=13;break}return t?(n.disableAccountErr.textContent=s.msg,Ne.show(n.disableAccountErr)):(n.errMsg.textContent=s.msg,Ne.show(n.errMsg)),e.abrupt("return");case 13:return t?(this.page.toggleAccountStatusBtn.textContent=ke("ENABLE_ACCOUNT"),Ne.hide(n.forms)):this.page.toggleAccountStatusBtn.textContent=ke("DISABLE_ACCOUNT"),this.accountDisabled=t,e.next=17,ft().fetchUser();case 17:ft().loadPage("dexsettings/".concat(r));case 18: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=ft().loading(n),e.next=3,S("/api/bondsfeebuffer",{assetID:t});case 3:if(a=e.sent,r(),ft().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,Ne.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=ft().loading(this.body),e.next=13,S("/api/updatecert",a);case 13:s=e.sent,o(),ft().checkResponse(s)?(Ne.show(t.updateCertMsg),setTimeout((function(){Ne.hide(t.updateCertMsg)}),5e3)):(t.errMsg.textContent=s.msg,Ne.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=ft().user.exchanges[this.host],n=function(t){t?(Ne.hide(e.disconnectedIcon),Ne.show(e.connectedIcon)):(Ne.show(e.disconnectedIcon),Ne.hide(e.connectedIcon))};if(t)switch(t.connectionStatus){case ut.Connected:n(!0),e.connectionStatus.textContent=ke("CONNECTED");break;case ut.Disconnected:n(!1),this.accountDisabled?e.connectionStatus.textContent=ke("ACCOUNT_DISABLED_MSG"):e.connectionStatus.textContent=ke($);break;case ut.InvalidCert:n(!1),e.connectionStatus.textContent="".concat(ke($)," - ").concat(ke("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=ft().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,S("/api/updatebondoptions",t);case 3:r=null!==(n=t.targetTier)&&void 0!==n?n:ft().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,ft().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=ft().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}(lt);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=Ne.idDescendants(e);return Ne.cleanTemplates(n.runTableRowTmpl),Ne.bind(n.backButton,"click",(function(){ft().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,ft().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=Ne.parseTemplate(u)).startTime.textContent=new Date(1e3*r).toLocaleString(),Qn(u,i,c,l),Ne.bind(d.logs,"click",(function(){ft().loadPage("mmlogs",{baseID:i,quoteID:c,host:l,startTime:r,returnPage:"mmarchives"})})),Ne.bind(d.settings,"click",(function(){ft().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 zo(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=tr(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=ft().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=Ho(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),ft().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?Ne.hide(n.endTimeRow):n.endTime.textContent=new Date(1e3*t).toLocaleString(),e.diffs){var a=ft().assets[parseInt(r)],o=this.statsRows[r];if(!o){o=n.performanceTableRowTmpl.cloneNode(!0);var s=Ne.parseTemplate(o);s.logo.src=Ne.logoPath(a.symbol),s.ticker.textContent=a.symbol.toUpperCase(),this.statsRows[r]=o,n.performanceTableBody.appendChild(o)}var i=e.diffs[r],c=Ne.parseTemplate(o);c.diff.textContent=i.fmt,c.usdDiff.textContent=i.fmtUSD,c.fiatRate.textContent="".concat(Ne.formatFiatValue(this.fiatRates[a.id])," USD")}n.profitLoss.textContent="".concat(Ne.formatFiatValue(e.profit)," USD")}},{key:"mktAssets",value:function(){var e,t=ft().assets[this.mkt.baseID],n=ft().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=ft().assets[t.token.parentID];a[o.id]=!0,r.push(o)}if(n.token&&!a[n.token.parentID]){var s=ft().assets[n.token.parentID];r.push(s)}return r}},{key:"updateExistingRows",value:function(e){var t,n=Ho(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;Ne.empty(t.eventsTableBody),this.events={},this.doneScrolling=!1;var n,r=this.mktAssets(),a=Ho(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=Ne.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=Qo(r,30),o.eventID.setAttribute("title",r));var s,i=0,c=Ho(n);try{for(c.s();!(s=c.n()).done;){var l,u=s.value,d=t.balanceEffects,h=Yo(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=Ne.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=Ne.formatFourSigFigs(i),Ne.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=ft().assets[r],s=ft().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(){rt(e.id,t.dexOrderID,t.copyDexOrderID,"#1e7d11")},t.copyDexOrderID.addEventListener("click",this.dexOrderIDCopyListener),t.dexOrderID.textContent=Qo(e.id,20),t.dexOrderID.setAttribute("title",e.id);var p=ft().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=ke(B):t.dexOrderSide.textContent=ke(E),Ne.empty(t.dexOrderTxsTableBody),Ne.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 Zo(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 cs(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")})),us(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=Ne.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"),Ne.bind(s,"click",(function(){Ne.setText(e,"[data-value]",Ne.formatFourSigFigs(o/n,Math.round(Math.log10(n)))),Ne.setText(e,"[data-unit]",t)}))},s=is(Ne.applySelector(e,"[data-conversion-value]"));try{var i=function(){var e=a.value,s=Ne.safeSelector(e,"[data-unit-box]");Ne.bind(s,"mouseenter",(function(){Ne.empty(r),s.appendChild(n);var a=Ne.layoutMetrics(s),i=parseInt(s.dataset.assetID),c=t.assets[i].unitInfo;o(e,c.conventional.unit,c.conventional.conversionFactor);var l,u=is(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")})),Ne.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=is(Ne.applySelector(e,"a[target=_blank]"));try{var r=function(){var e=t.value;Ne.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=ls(document.body,"header");var t=this.page=Ne.idDescendants(this.header);this.headerSpace=t.headerSpace,this.popupNotes=ls(document.body,"popupNotes"),this.popupTmpl=Ne.tmplElement(this.popupNotes,"note"),this.popupTmpl?this.popupTmpl.remove():console.error("popupTmpl element not found"),this.tooltip=ls(document.body,"tooltip"),t.noteTmpl.removeAttribute("id"),t.noteTmpl.remove(),t.pokeTmpl.removeAttribute("id"),t.pokeTmpl.remove(),t.loader.remove(),Ne.show(t.loader),us(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:Ne.hide(t.pokeList),Ne.show(t.noteList),e.ackNotes(),t.noteCat.classList.add("active"),t.pokeCat.classList.remove("active"),e.showDropdown(t.noteBell,t.noteBox),Ne.hide(t.noteIndicator),r=is(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)})))),us(t.burgerIcon,"click",(function(){Ne.hide(t.logoutErr),e.showDropdown(t.burgerIcon,t.profileBox)})),us(t.innerNoteIcon,"click",(function(){Ne.hide(t.noteBox)})),us(t.innerBurgerIcon,"click",(function(){Ne.hide(t.profileBox)})),us(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)})))),us(t.pokeCat,"click",(function(){e.setNoteTimes(t.pokeList),t.pokeCat.classList.add("active"),t.noteCat.classList.remove("active"),Ne.hide(t.noteList),Ne.show(t.pokeList),e.ackNotes()})),us(t.noteCat,"click",(function(){e.setNoteTimes(t.noteList),t.noteCat.classList.add("active"),t.pokeCat.classList.remove("active"),Ne.hide(t.pokeList),Ne.show(t.noteList),e.ackNotes()})),Ne.cleanTemplates(t.langBttnTmpl);var n=ps[this.lang],r=n.name,a=n.flag;t.langFlag.textContent=a,t.langName.textContent=r;var o,i=is(this.langs);try{var c=function(){var n=o.value;if(n===e.lang)return"continue";var r=t.langBttnTmpl.cloneNode(!0),a=ps[n],s=a.name,i=a.flag;r.textContent=i,r.title=s,Ne.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,Ne.idDescendants(Ne.idel(document.body,"requiredActions"))),Ne.cleanTemplates(t.missingNoncesTmpl,t.actionTxTableTmpl,t.tooCheapTmpl,t.lostNonceTmpl),Ne.bind(t.actionsCollapse,"click",(function(){Ne.hide(t.actionDialog),Ne.show(t.actionDialogCollapsed)})),Ne.bind(t.actionDialogCollapsed,"click",(function(){Ne.hide(t.actionDialogCollapsed),Ne.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)};Ne.bind(t.prevAction,"click",(function(){return n(-1)})),Ne.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=is(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),Ne.isHidden(t.actionDialog)&&this.showRequestedAction(e.uniqueID)}}}},{key:"blinkAction",value:function(){Ne.blink(this.page.actionDialog),Ne.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()):Ne.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=Ne.parseTemplate(s);i.lostTxID.textContent=n.tx.id,i.lostTxID.dataset.explorerCoin=n.tx.id,Pn(o?o.parentID:t,i.lostTxID),i.txAmt.textContent=Ne.formatCoinValue(n.tx.amount,a),i.amtUnit.textContent=a.conventional.unit;var c=o?this.unitInfo(o.parentID):a;return i.type.textContent=Xr(n.tx.type),i.feeAmount.textContent=Ne.formatCoinValue(n.tx.fees,c),i.feeUnit.textContent=c.conventional.unit,"tooCheap"===e.actionID&&(Ne.show(i.newFeesRow),i.newFees.textContent=Ne.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 Ne.hide(r),a=this.loading(this.page.actionDialog),e.next=4,S("/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,Ne.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=Ne.parseTemplate(r),o=this.assets[n].name;return a.assetName.textContent=o,Ne.bind(a.doNothingBttn,"click",(function(){t.submitAction(e,{recover:!1},a.errMsg)})),Ne.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=Ne.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 Ne.bind(o.keepWaitingBttn,"click",(function(){return i(!1)})),Ne.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=Ne.parseTemplate(a),s=this.assets[n].name;return o.assetName.textContent=s,o.nonce.textContent=String(r.nonce),o.txTable.appendChild(this.actionTxTable(e)),Ne.bind(o.abandonBttn,"click",(function(){t.submitAction(e,{txID:r.tx.id,abandon:!0},o.errMsg)})),Ne.bind(o.keepWaitingBttn,"click",(function(){t.submitAction(e,{txID:r.tx.id,abandon:!1},o.errMsg)})),Ne.bind(o.replaceBttn,"click",(function(){var n=o.idInput.value;if(!n)return o.idInput.focus(),void Ne.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=Ne.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,Pn(d?d.parentID:s,c.txid),Ne.bind(c.doNothingBttn,"click",(function(){t.submitAction(e,{orderID:r,coinID:a,retry:!1},c.errMsg)})),Ne.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;Ne.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&&Ta.request("acknotes",t),Ne.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"),Ne.show(e.noteBell,e.walletsMenuEntry,e.marketsMenuEntry),Ne.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=is(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,Ne.animate(500,(function(e){i.style.opacity=String(1-e)}));case 2:i.remove(),0===o.children.length&&Ne.hide(o);case 4:case"end":return e.stop()}}),e)}))),6e3)}2===e.severity?this.prependPokeElement(e):this.prependNoteElement(e),function(e){pa.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||Ne.isDisplayed(this.page.noteBox)&&Ne.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;ys(c,i),s?(c.textContent=String(s>99?"".concat(99,"+"):s),Ne.show(c)):Ne.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";Ne.safeSelector(t,"div.note-indicator").classList.add(n)}return Ne.safeSelector(t,"div.note-subject").textContent=e.subject,ga(Ne.safeSelector(t,"div.note-details"),e.details),[t,ss({el:t},e)]}},{key:"makePoke",value:function(e){var t=this.page.pokeTmpl.cloneNode(!0);return Ne.tmplElement(t,"subject").textContent="".concat(e.subject,":"),ga(Ne.tmplElement(t,"details"),e.details),[t,ss({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= 0; --i) {\n var entry = this.tryEntries[i],\n record = entry.completion;\n if (\"root\" === entry.tryLoc) return handle(\"end\");\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\"),\n hasFinally = hasOwn.call(entry, \"finallyLoc\");\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);\n if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);\n } else {\n if (!hasFinally) throw new Error(\"try statement without catch or finally\");\n if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);\n }\n }\n }\n },\n abrupt: function abrupt(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev && hasOwn.call(entry, \"finallyLoc\") && this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n finallyEntry && (\"break\" === type || \"continue\" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);\n var record = finallyEntry ? finallyEntry.completion : {};\n return record.type = type, record.arg = arg, finallyEntry ? (this.method = \"next\", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);\n },\n complete: function complete(record, afterLoc) {\n if (\"throw\" === record.type) throw record.arg;\n return \"break\" === record.type || \"continue\" === record.type ? this.next = record.arg : \"return\" === record.type ? (this.rval = this.arg = record.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;\n },\n finish: function finish(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;\n }\n },\n \"catch\": function _catch(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (\"throw\" === record.type) {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n throw new Error(\"illegal catch attempt\");\n },\n delegateYield: function delegateYield(iterable, resultName, nextLoc) {\n return this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n }, \"next\" === this.method && (this.arg = undefined), ContinueSentinel;\n }\n }, exports;\n}\nmodule.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return (module.exports = _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports), _typeof(obj);\n}\nmodule.exports = _typeof, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","// TODO(Babel 8): Remove this file.\n\nvar runtime = require(\"../helpers/regeneratorRuntime\")();\nmodule.exports = runtime;\n\n// Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n if (typeof globalThis === \"object\") {\n globalThis.regeneratorRuntime = runtime;\n } else {\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n }\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","export default function _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n return arr2;\n}","import arrayLikeToArray from \"./arrayLikeToArray.js\";\nexport default function _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);\n}","import arrayWithoutHoles from \"./arrayWithoutHoles.js\";\nimport iterableToArray from \"./iterableToArray.js\";\nimport unsupportedIterableToArray from \"./unsupportedIterableToArray.js\";\nimport nonIterableSpread from \"./nonIterableSpread.js\";\nexport default function _toConsumableArray(arr) {\n return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();\n}","import arrayLikeToArray from \"./arrayLikeToArray.js\";\nexport default function _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) return arrayLikeToArray(arr);\n}","export default function _iterableToArray(iter) {\n if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter);\n}","export default function _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}","import arrayWithHoles from \"./arrayWithHoles.js\";\nimport iterableToArrayLimit from \"./iterableToArrayLimit.js\";\nimport unsupportedIterableToArray from \"./unsupportedIterableToArray.js\";\nimport nonIterableRest from \"./nonIterableRest.js\";\nexport default function _slicedToArray(arr, i) {\n return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();\n}","export default function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}","export default function _iterableToArrayLimit(arr, i) {\n var _i = null == arr ? null : \"undefined\" != typeof Symbol && arr[Symbol.iterator] || arr[\"@@iterator\"];\n if (null != _i) {\n var _s,\n _e,\n _x,\n _r,\n _arr = [],\n _n = !0,\n _d = !1;\n try {\n if (_x = (_i = _i.call(arr)).next, 0 === i) {\n if (Object(_i) !== _i) return;\n _n = !1;\n } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);\n } catch (err) {\n _d = !0, _e = err;\n } finally {\n try {\n if (!_n && null != _i[\"return\"] && (_r = _i[\"return\"](), Object(_r) !== _r)) return;\n } finally {\n if (_d) throw _e;\n }\n }\n return _arr;\n }\n}","export default function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}","function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n}\nexport default function _asyncToGenerator(fn) {\n return function () {\n var self = this,\n args = arguments;\n return new Promise(function (resolve, reject) {\n var gen = fn.apply(self, args);\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value);\n }\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err);\n }\n _next(undefined);\n });\n };\n}","export default function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}","export default function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, _typeof(obj);\n}","import _typeof from \"./typeof.js\";\nimport toPrimitive from \"./toPrimitive.js\";\nexport default function _toPropertyKey(arg) {\n var key = toPrimitive(arg, \"string\");\n return _typeof(key) === \"symbol\" ? key : String(key);\n}","import _typeof from \"./typeof.js\";\nexport default function _toPrimitive(input, hint) {\n if (_typeof(input) !== \"object\" || input === null) return input;\n var prim = input[Symbol.toPrimitive];\n if (prim !== undefined) {\n var res = prim.call(input, hint || \"default\");\n if (_typeof(res) !== \"object\") return res;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (hint === \"string\" ? String : Number)(input);\n}","import toPropertyKey from \"./toPropertyKey.js\";\nfunction _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, toPropertyKey(descriptor.key), descriptor);\n }\n}\nexport default function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n Object.defineProperty(Constructor, \"prototype\", {\n writable: false\n });\n return Constructor;\n}","import toPropertyKey from \"./toPropertyKey.js\";\nexport default function _defineProperty(obj, key, value) {\n key = toPropertyKey(key);\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n}","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n return self;\n}","export default function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n return _setPrototypeOf(o, p);\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nexport default function _inherits(subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n writable: true,\n configurable: true\n }\n });\n Object.defineProperty(subClass, \"prototype\", {\n writable: false\n });\n if (superClass) setPrototypeOf(subClass, superClass);\n}","import _typeof from \"./typeof.js\";\nimport assertThisInitialized from \"./assertThisInitialized.js\";\nexport default function _possibleConstructorReturn(self, call) {\n if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) {\n return call;\n } else if (call !== void 0) {\n throw new TypeError(\"Derived constructors may only return object or undefined\");\n }\n return assertThisInitialized(self);\n}","export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}","// State is a set of static methods for working with the user state. It has\n// utilities for setting and retrieving cookies and storing user configuration\n// to localStorage.\nexport default class State {\n // Cookie keys.\n static darkModeLK = 'darkMode'\n static authCK = 'dexauth'\n static pwKeyCK = 'sessionkey'\n // Local storage keys (for data that we don't need at the server).\n static popupsLK = 'popups'\n static loggersLK = 'loggers'\n static recordersLK = 'recorders'\n static lastMarketLK = 'selectedMarket'\n static depthZoomLK = 'depthZoom'\n static lastMMMarketLK = 'mmMarket'\n static optionsExpansionLK = 'mmOptsExpand'\n static leftMarketDockLK = 'leftmarketdock'\n static selectedAssetLK = 'selectedasset'\n static notificationsLK = 'notifications' // DEPRECATED before v1\n static orderDisclaimerAckedLK = 'ordAck'\n static lastCandleDurationLK = 'lastCandleDuration'\n static localeSpecsKey = 'localeSpecsLK'\n static localeKey = 'localeLK'\n\n static setCookie (cname: string, cvalue: string) {\n const d = new Date()\n // Set cookie to expire in ten years.\n d.setTime(d.getTime() + (86400 * 365 * 10 * 1000))\n const expires = 'expires=' + d.toUTCString()\n document.cookie = cname + '=' + cvalue + ';' + expires + ';path=/'\n }\n\n /*\n * getCookie returns the value at the specified cookie name, otherwise null.\n */\n static getCookie (cname: string) {\n for (const cstr of document.cookie.split(';')) {\n const [k, v] = cstr.split('=')\n if (k.trim() === cname) return v\n }\n return null\n }\n\n /*\n * removeCookie tells the browser to stop using cookie. It's not enough to simply\n * erase cookie value because browser will still send it to the server (with empty\n * value), and that's not what server expects.\n */\n static removeCookie (cKey: string) {\n document.cookie = `${cKey}=;expires=Thu, 01 Jan 1970 00:00:01 GMT;`\n }\n\n /*\n * isDark returns true if the dark-mode cookie is currently set to '1' = true.\n */\n static isDark (): boolean {\n return State.fetchLocal(State.darkModeLK) === '1'\n }\n\n /* storeLocal puts the key-value pair into Window.localStorage. */\n static storeLocal (k: string, v: any) {\n window.localStorage.setItem(k, JSON.stringify(v))\n }\n\n /*\n * fetchLocal the value associated with the key in Window.localStorage, or\n * null if the no value exists for the key.\n */\n static fetchLocal (k: string) {\n const v = window.localStorage.getItem(k)\n if (v !== null) {\n return JSON.parse(v)\n }\n return null\n }\n\n /* removeLocal removes the key-value pair from Window.localStorage. */\n static removeLocal (k: string) {\n window.localStorage.removeItem(k)\n }\n}\n\n// Setting defaults here, unless specific cookie (or local storage) value was already chosen by the user.\nif (State.fetchLocal(State.darkModeLK) === null) State.storeLocal(State.darkModeLK, '1')\nif (State.fetchLocal(State.popupsLK) === null) State.storeLocal(State.popupsLK, '1')\nif (State.fetchLocal(State.leftMarketDockLK) === null) State.storeLocal(State.leftMarketDockLK, '1')\n","/*\n * requestJSON encodes the object and sends the JSON to the specified address.\n */\nexport async function requestJSON (method: string, addr: string, reqBody?: any): Promise {\n try {\n const response = await window.fetch(addr, {\n method: method,\n headers: new window.Headers({ 'content-type': 'application/json' }),\n // credentials: \"same-origin\",\n body: reqBody\n })\n if (response.status !== 200) { throw response }\n const obj = await response.json()\n obj.requestSuccessful = true\n return obj\n } catch (response) {\n response.requestSuccessful = false\n response.msg = await response.text()\n return response\n }\n}\n\n/*\n * postJSON sends a POST request with JSON-formatted data and returns the\n * response.\n */\nexport async function postJSON (addr: string, data?: any) {\n return requestJSON('POST', addr, JSON.stringify(data))\n}\n\n/*\n * getJSON sends a GET request and returns the response.\n */\nexport async function getJSON (addr: string): Promise {\n return requestJSON('GET', addr)\n}\n\nexport enum Errors {\n walletErr,\n walletAuthErr,\n walletBalanceErr,\n dupeDEXErr,\n assetSupportErr,\n registerErr,\n signatureErr,\n zeroFeeErr,\n feeMismatchErr,\n feeSendErr,\n passwordErr,\n emptyHostErr,\n connectionErr,\n acctKeyErr,\n unknownOrderErr,\n orderParamsErr,\n dbErr,\n authErr,\n connectWalletErr,\n missingWalletErr,\n encryptionErr,\n decodeErr,\n accountVerificationErr,\n accountProofErr,\n parseKeyErr,\n marketErr,\n addressParseErr,\n addrErr,\n fileReadErr,\n unknownDEXErr,\n accountRetrieveErr,\n accountDisableErr,\n suspendedAcctErr,\n existenceCheckErr,\n createWalletErr,\n activeOrdersErr,\n newAddrErr,\n}\n","import State from './state'\nimport { postJSON } from './http'\n\ntype Locale = Record\n\nexport const ID_NO_PASS_ERROR_MSG = 'NO_PASS_ERROR_MSG'\nexport const ID_NO_APP_PASS_ERROR_MSG = 'NO_APP_PASS_ERROR_MSG'\nexport const ID_SET_BUTTON_BUY = 'SET_BUTTON_BUY'\nexport const ID_SET_BUTTON_SELL = 'SET_BUTTON_SELL'\nexport const ID_OFF = 'OFF'\nexport const ID_MAX = 'MAX'\nexport const ID_READY = 'READY'\nexport const ID_NO_WALLET = 'NO_WALLET'\nexport const ID_DISABLED_MSG = 'DISABLED_MSG'\nexport const ID_WALLET_SYNC_PROGRESS = 'WALLET_SYNC_PROGRESS'\nexport const ID_HIDE_ADDITIONAL_SETTINGS = 'HIDE_ADDITIONAL_SETTINGS'\nexport const ID_SHOW_ADDITIONAL_SETTINGS = 'SHOW_ADDITIONAL_SETTINGS'\nexport const ID_BUY = 'BUY'\nexport const ID_SELL = 'SELL'\nexport const ID_NOT_SUPPORTED = 'NOT_SUPPORTED'\nexport const ID_VERSION_NOT_SUPPORTED = 'VERSION_NOT_SUPPORTED'\nexport const ID_CONNECTION_FAILED = 'CONNECTION_FAILED'\nexport const ID_ORDER_PREVIEW = 'ORDER_PREVIEW'\nexport const ID_CALCULATING = 'CALCULATING'\nexport const ID_ESTIMATE_UNAVAILABLE = 'ESTIMATE_UNAVAILABLE'\nexport const ID_NO_ZERO_RATE = 'NO_ZERO_RATE'\nexport const ID_NO_ZERO_QUANTITY = 'NO_ZERO_QUANTITY'\nexport const ID_TRADE = 'TRADE'\nexport const ID_NO_ASSET_WALLET = 'NO_ASSET_WALLET'\nexport const ID_EXECUTED = 'EXECUTED'\nexport const ID_BOOKED = 'BOOKED'\nexport const ID_CANCELING = 'CANCELING'\nexport const ID_PASSWORD_NOT_MATCH = 'PASSWORD_NOT_MATCH'\nexport const ID_ACCT_UNDEFINED = 'ACCT_UNDEFINED'\nexport const ID_KEEP_WALLET_PASS = 'KEEP_WALLET_PASS'\nexport const ID_NEW_WALLET_PASS = 'NEW_WALLET_PASS'\nexport const ID_LOT = 'LOT'\nexport const ID_LOTS = 'LOTS'\nexport const ID_UNKNOWN = 'UNKNOWN'\nexport const ID_EPOCH = 'EPOCH'\nexport const ID_ORDER_SUBMITTING = 'ORDER_SUBMITTING'\nexport const ID_SETTLING = 'SETTLING'\nexport const ID_NO_MATCH = 'NO_MATCH'\nexport const ID_CANCELED = 'CANCELED'\nexport const ID_REVOKED = 'REVOKED'\nexport const ID_WAITING_FOR_CONFS = 'WAITING_FOR_CONFS'\nexport const ID_NONE_SELECTED = 'NONE_SELECTED'\nexport const ID_REGISTRATION_FEE_SUCCESS = 'REGISTRATION_FEE_SUCCESS'\nexport const ID_API_ERROR = 'API_ERROR'\nexport const ID_ADD = 'ADD'\nexport const ID_CREATE = 'CREATE'\nexport const ID_SETUP_WALLET = 'SETUP_WALLET'\nexport const ID_WALLET_READY = 'WALLET_READY'\nexport const ID_CHANGE_WALLET_TYPE = 'CHANGE_WALLET_TYPE'\nexport const ID_KEEP_WALLET_TYPE = 'KEEP_WALLET_TYPE'\nexport const ID_WALLET_PENDING = 'WALLET_PENDING'\nexport const ID_SETUP_NEEDED = 'SETUP_NEEDED'\nexport const ID_SEND_SUCCESS = 'SEND_SUCCESS'\nexport const ID_RECONFIG_SUCCESS = 'RECONFIG_SUCCESS'\nexport const ID_RESCAN_STARTED = 'RESCAN_STARTED'\nexport const ID_NEW_WALLET_SUCCESS = 'NEW_WALLET_SUCCESS'\nexport const ID_WALLET_UNLOCKED = 'WALLET_UNLOCKED'\nexport const ID_SELLING = 'SELLING'\nexport const ID_BUYING = 'BUYING'\nexport const ID_WALLET_DISABLED_MSG = 'WALLET_DISABLED'\nexport const ID_WALLET_ENABLED_MSG = 'WALLET_ENABLED'\nexport const ID_ACTIVE_ORDERS_ERR_MSG = 'ACTIVE_ORDERS_ERR_MSG'\nexport const ID_AVAILABLE = 'AVAILABLE'\nexport const ID_LOCKED = 'LOCKED'\nexport const ID_IMMATURE = 'IMMATURE'\nexport const ID_FEE_BALANCE = 'FEE_BALANCE'\nexport const ID_CANDLES_LOADING = 'CANDLES_LOADING'\nexport const ID_DEPTH_LOADING = 'DEPTH_LOADING'\nexport const ID_INVALID_ADDRESS_MSG = 'INVALID_ADDRESS_MSG'\nexport const ID_TXFEE_UNSUPPORTED = 'TXFEE_UNSUPPORTED'\nexport const ID_TXFEE_ERR_MSG = 'TXFEE_ERR_MSG'\nexport const ID_ACTIVE_ORDERS_LOGOUT_ERR_MSG = 'ACTIVE_ORDERS_LOGOUT_ERR_MSG'\nexport const ID_INVALID_DATE_ERR_MSG = 'INVALID_DATE_ERR_MSG'\nexport const ID_NO_ARCHIVED_RECORDS = 'NO_ARCHIVED_RECORDS'\nexport const ID_DELETE_ARCHIVED_RECORDS_RESULT = 'DELETE_ARCHIVED_RECORDS_RESULT'\nexport const ID_ARCHIVED_RECORDS_PATH = 'ARCHIVED_RECORDS_PATH'\nexport const ID_DEFAULT = 'DEFAULT'\nexport const ID_ADDED = 'ADDED'\nexport const ID_DISCOVERED = 'DISCOVERED'\nexport const ID_UNSUPPORTED_ASSET_INFO_ERR_MSG = 'UNSUPPORTED_ASSET_INFO_ERR_MSG'\nexport const ID_LIMIT_ORDER = 'LIMIT_ORDER'\nexport const ID_LIMIT_ORDER_IMMEDIATE_TIF = 'LIMIT_ORDER_IMMEDIATE_TIF'\nexport const ID_MARKET_ORDER = 'MARKET_ORDER'\nexport const ID_CANCEL_ORDER = 'CANCEL_ORDER'\nexport const ID_MATCH_STATUS_NEWLY_MATCHED = 'MATCH_STATUS_NEWLY_MATCHED'\nexport const ID_MATCH_STATUS_MAKER_SWAP_CAST = 'MATCH_STATUS_MAKER_SWAP_CAST'\nexport const ID_MATCH_STATUS_TAKER_SWAP_CAST = 'MATCH_STATUS_TAKER_SWAP_CAST'\nexport const ID_MATCH_STATUS_MAKER_REDEEMED = 'MATCH_STATUS_MAKER_REDEEMED'\nexport const ID_MATCH_STATUS_REDEMPTION_SENT = 'MATCH_STATUS_REDEMPTION_SENT'\nexport const ID_MATCH_STATUS_REDEMPTION_CONFIRMED = 'MATCH_REDEMPTION_CONFIRMED'\nexport const ID_MATCH_STATUS_REVOKED = 'MATCH_STATUS_REVOKED'\nexport const ID_MATCH_STATUS_REFUNDED = 'MATCH_STATUS_REFUNDED'\nexport const ID_MATCH_STATUS_REFUND_PENDING = 'MATCH_STATUS_REFUND_PENDING'\nexport const ID_MATCH_STATUS_REDEEM_PENDING = 'MATCH_STATUS_REDEEM_PENDING'\nexport const ID_MATCH_STATUS_COMPLETE = 'MATCH_STATUS_COMPLETE'\nexport const ID_TAKER_FOUND_MAKER_REDEMPTION = 'TAKER_FOUND_MAKER_REDEMPTION'\nexport const ID_OPEN_WALLET_ERR_MSG = 'OPEN_WALLET_ERR_MSG'\nexport const ID_ORDER_ACCELERATION_FEE_ERR_MSG = 'ORDER_ACCELERATION_FEE_ERR_MSG'\nexport const ID_ORDER_ACCELERATION_ERR_MSG = 'ORDER_ACCELERATION_ERR_MSG'\nexport const ID_CONNECTED = 'CONNECTED'\nexport const ID_DISCONNECTED = 'DISCONNECTED'\nexport const ID_INVALID_CERTIFICATE = 'INVALID_CERTIFICATE'\nexport const ID_CONFIRMATIONS = 'CONFIRMATIONS'\nexport const ID_TAKER = 'TAKER'\nexport const ID_MAKER = 'MAKER'\nexport const ID_EMPTY_DEX_ADDRESS_MSG = 'EMPTY_DEX_ADDRESS_MSG'\nexport const ID_SELECT_WALLET_FOR_FEE_PAYMENT = 'SELECT_WALLET_FOR_FEE_PAYMENT'\nexport const ID_UNAVAILABLE = 'UNAVAILABLE'\nexport const ID_WALLET_SYNC_FINISHING_UP = 'WALLET_SYNC_FINISHING_UP'\nexport const ID_CONNECT_WALLET_ERR_MSG = 'CONNECTING_WALLET_ERR_MSG'\nexport const ID_REFUND_IMMINENT = 'REFUND_IMMINENT'\nexport const ID_REFUND_WILL_HAPPEN_AFTER = 'REFUND_WILL_HAPPEN_AFTER'\nexport const ID_AVAILABLE_TITLE = 'AVAILABLE_TITLE'\nexport const ID_LOCKED_TITLE = 'LOCKED_TITLE'\nexport const ID_IMMATURE_TITLE = 'IMMATURE_TITLE'\nexport const ID_SWAPPING = 'SWAPPING'\nexport const ID_BONDED = 'BONDED'\nexport const ID_LOCKED_BAL_MSG = 'LOCKED_BAL_MSG'\nexport const ID_IMMATURE_BAL_MSG = 'IMMATURE_BAL_MSG'\nexport const ID_LOCKED_SWAPPING_BAL_MSG = 'LOCKED_SWAPPING_BAL_MSG'\nexport const ID_LOCKED_BOND_BAL_MSG = 'LOCKED_BOND_BAL_MSG'\nexport const ID_RESERVES_DEFICIT = 'RESERVES_DEFICIT'\nexport const ID_RESERVES_DEFICIT_MSG = 'RESERVES_DEFICIT_MSG'\nexport const ID_BOND_RESERVES = 'BOND_RESERVES'\nexport const ID_BOND_RESERVES_MSG = 'BOND_RESERVES_MSG'\nexport const ID_SHIELDED = 'SHIELDED'\nexport const ID_TRANSPARENT = 'TRANSPARENT'\nexport const ID_SHIELDED_MSG = 'SHIELDED_MSG'\nexport const ID_ORDER = 'ORDER'\nexport const ID_LOCKED_ORDER_BAL_MSG = 'LOCKED_ORDER_BAL_MSG'\nexport const ID_CREATING_WALLETS = 'CREATING_WALLETS'\nexport const ID_ADDING_SERVERS = 'ADDING_SERVER'\nexport const ID_WALLET_RECOVERY_SUPPORT_MSG = 'WALLET_RECOVERY_SUPPORT_MSG'\nexport const ID_TICKETS_PURCHASED = 'TICKETS_PURCHASED'\nexport const ID_TICKET_STATUS_UNKNOWN = 'TICKET_STATUS_UNKNOWN'\nexport const ID_TICKET_STATUS_UNMINED = 'TICKET_STATUS_UNMINED'\nexport const ID_TICKET_STATUS_IMMATURE = 'TICKET_STATUS_IMMATURE'\nexport const ID_TICKET_STATUS_LIVE = 'TICKET_STATUS_LIVE'\nexport const ID_TICKET_STATUS_VOTED = 'TICKET_STATUS_VOTED'\nexport const ID_TICKET_STATUS_MISSED = 'TICKET_STATUS_MISSED'\nexport const ID_TICKET_STATUS_EXPIRED = 'TICKET_STATUS_EXPIRED'\nexport const ID_TICKET_STATUS_UNSPENT = 'TICKET_STATUS_UNSPENT'\nexport const ID_TICKET_STATUS_REVOKED = 'TICKET_STATUS_REVOKED'\nexport const ID_PASSWORD_RESET_SUCCESS_MSG = 'PASSWORD_RESET_SUCCESS_MSG'\nexport const ID_BROWSER_NTFN_ENABLED = 'BROWSER_NTFN_ENABLED'\nexport const ID_BROWSER_NTFN_ORDERS = 'BROWSER_NTFN_ORDERS'\nexport const ID_BROWSER_NTFN_MATCHES = 'BROWSER_NTFN_MATCHES'\nexport const ID_BROWSER_NTFN_BONDS = 'BROWSER_NTFN_BONDS'\nexport const ID_BROWSER_NTFN_CONNECTIONS = 'BROWSER_NTFN_CONNECTIONS'\nexport const ID_ORDER_BUTTON_BUY_BALANCE_ERROR = 'ORDER_BUTTON_BUY_BALANCE_ERROR'\nexport const ID_ORDER_BUTTON_SELL_BALANCE_ERROR = 'ORDER_BUTTON_SELL_BALANCE_ERROR'\nexport const ID_ORDER_BUTTON_QTY_ERROR = 'ORDER_BUTTON_QTY_ERROR'\nexport const ID_ORDER_BUTTON_QTY_RATE_ERROR = 'ORDER_BUTTON_QTY_RATE_ERROR'\nexport const ID_CREATE_ASSET_WALLET_MSG = 'CREATE_ASSET_WALLET_MSG'\nexport const ID_NO_WALLET_MSG = 'NO_WALLET_MSG'\nexport const ID_TRADING_TIER_UPDATED = 'TRADING_TIER_UPDATED'\nexport const ID_INVALID_TIER_VALUE = 'INVALID_TIER_VALUE'\nexport const ID_INVALID_COMPS_VALUE = 'INVALID_COMPS_VALUE'\nexport const ID_TX_TYPE_UNKNOWN = 'TX_TYPE_UNKNOWN'\nexport const ID_TX_TYPE_SEND = 'TX_TYPE_SEND'\nexport const ID_TX_TYPE_RECEIVE = 'TX_TYPE_RECEIVE'\nexport const ID_TX_TYPE_SWAP = 'TX_TYPE_SWAP'\nexport const ID_TX_TYPE_REDEEM = 'TX_TYPE_REDEEM'\nexport const ID_TX_TYPE_REFUND = 'TX_TYPE_REFUND'\nexport const ID_TX_TYPE_SPLIT = 'TX_TYPE_SPLIT'\nexport const ID_TX_TYPE_CREATE_BOND = 'TX_TYPE_CREATE_BOND'\nexport const ID_TX_TYPE_REDEEM_BOND = 'TX_TYPE_REDEEM_BOND'\nexport const ID_TX_TYPE_APPROVE_TOKEN = 'TX_TYPE_APPROVE_TOKEN'\nexport const ID_TX_TYPE_ACCELERATION = 'TX_TYPE_ACCELERATION'\nexport const ID_TX_TYPE_SELF_TRANSFER = 'TX_TYPE_SELF_TRANSFER'\nexport const ID_TX_TYPE_REVOKE_TOKEN_APPROVAL = 'TX_TYPE_REVOKE_TOKEN_APPROVAL'\nexport const ID_TX_TYPE_TICKET_PURCHASE = 'TX_TYPE_TICKET_PURCHASE'\nexport const ID_TX_TYPE_TICKET_VOTE = 'TX_TYPE_TICKET_VOTE'\nexport const ID_TX_TYPE_TICKET_REVOCATION = 'TX_TYPE_TICKET_REVOCATION'\nexport const ID_TX_TYPE_SWAP_OR_SEND = 'TX_TYPE_SWAP_OR_SEND'\nexport const ID_TX_TYPE_MIX = 'TX_TYPE_MIX'\nexport const ID_SWAP_OR_SEND_TOOLTIP = 'SWAP_OR_SEND_TOOLTIP'\nexport const ID_MISSING_CEX_CREDS = 'MISSING_CEX_CREDS'\nexport const ID_MATCH_BUFFER = 'MATCH_BUFFER'\nexport const ID_NO_PLACEMENTS = 'NO_PLACEMENTS'\nexport const ID_INVALID_VALUE = 'INVALID_VALUE'\nexport const ID_NO_ZERO = 'NO_ZERO'\nexport const ID_BOTTYPE_BASIC_MM = 'BOTTYPE_BASIC_MM'\nexport const ID_BOTTYPE_ARB_MM = 'BOTTYPE_ARB_MM'\nexport const ID_BOTTYPE_SIMPLE_ARB = 'BOTTYPE_SIMPLE_ARB'\nexport const ID_NO_BOTTYPE = 'NO_BOTTYPE'\nexport const ID_NO_CEX = 'NO_CEX'\nexport const ID_CEXBALANCE_ERR = 'CEXBALANCE_ERR'\nexport const ID_PENDING = 'PENDING'\nexport const ID_COMPLETE = 'COMPLETE'\nexport const ID_ARCHIVED_SETTINGS = 'ARCHIVED_SETTINGS'\nexport const ID_NO_CODE_PROVIDED = 'NO_CODE_PROVIDED'\nexport const ID_ENABLE_ACCOUNT = 'ENABLE_ACCOUNT'\nexport const ID_DISABLE_ACCOUNT = 'DISABLE_ACCOUNT'\nexport const ID_ACCOUNT_DISABLED_MSG = 'ACCOUNT_DISABLED_MSG'\nexport const ID_DEX_DISABLED_MSG = 'DEX_DISABLED_MSG'\nexport const ID_WALLET_NOT_SYNCED = 'WALLET_NOT_SYNCED'\nexport const ID_WALLET_NO_PEERS = 'WALLET_NO_PEERS'\nexport const ID_DEPOSIT_ERROR = 'DEPOSIT_ERROR'\nexport const ID_WITHDRAW_ERROR = 'WITHDRAW_ERROR'\nexport const ID_DEX_UNDERFUNDED = 'DEX_UNDERFUNDED'\nexport const ID_CEX_UNDERFUNDED = 'CEX_UNDERFUNDED'\nexport const ID_CEX_TOO_SHALLOW = 'CEX_TOO_SHALLOW'\nexport const ID_ACCOUNT_SUSPENDED = 'ACCOUNT_SUSPENDED'\nexport const ID_USER_LIMIT_TOO_LOW = 'USER_LIMIT_TOO_LOW'\nexport const ID_NO_PRICE_SOURCE = 'NO_PRICE_SOURCE'\nexport const ID_CEX_ORDERBOOK_UNSYNCED = 'CEX_ORDERBOOK_UNSYNCED'\nexport const ID_DETERMINE_PLACEMENTS_ERROR = 'DETERMINE_PLACEMENTS_ERROR'\nexport const ID_PLACE_BUY_ORDERS_ERROR = 'PLACE_BUY_ORDERS_ERROR'\nexport const ID_PLACE_SELL_ORDERS_ERROR = 'PLACE_SELL_ORDERS_ERROR'\nexport const ID_CEX_TRADE_ERROR = 'CEX_TRADE_ERROR'\nexport const ID_ORDER_REPORT_TITLE = 'ORDER_REPORT_TITLE'\nexport const ID_CEX_BALANCES = 'CEX_BALANCES'\nexport const ID_CAUSES_SELF_MATCH = 'CAUSES_SELF_MATCH'\nexport const ID_CEX_NOT_CONNECTED = 'CEX_NOT_CONNECTED'\nexport const ID_DELETE_BOT = 'DELETE_BOT'\n\nlet locale: Locale\n\nexport async function loadLocale (lang: string, commitHash: string, skipCache: boolean) {\n if (!skipCache) {\n const specs = State.fetchLocal(State.localeSpecsKey)\n if (specs && specs.lang === lang && specs.commitHash === commitHash) {\n locale = State.fetchLocal(State.localeKey)\n return\n }\n }\n locale = await postJSON('/api/locale', lang)\n State.storeLocal(State.localeSpecsKey, { lang, commitHash })\n State.storeLocal(State.localeKey, locale)\n}\n\n/* prep will format the message to the current locale. */\nexport function prep (k: string, args?: Record) {\n return stringTemplateParser(locale[k], args || {})\n}\n\nwindow.clearLocale = () => {\n State.removeLocal(State.localeSpecsKey)\n State.removeLocal(State.localeKey)\n}\n\n/*\n * stringTemplateParser is a template string matcher, where expression is any\n * text. It switches what is inside double brackets (e.g. 'buy {{ asset }}')\n * for the value described into args. args is an object with keys\n * equal to the placeholder keys. (e.g. {\"asset\": \"dcr\"}).\n * So that will be switched for: 'asset dcr'.\n */\nfunction stringTemplateParser (expression: string, args: Record) {\n // templateMatcher matches any text which:\n // is some {{ text }} between two brackets, and a space between them.\n // It is global, therefore it will change all occurrences found.\n // text can be anything, but brackets '{}' and space '\\s'\n const templateMatcher = /{{\\s?([^{}\\s]*)\\s?}}/g\n return expression.replace(templateMatcher, (_, value) => args[value])\n}\n","import * as intl from './locales'\nimport {\n UnitInfo,\n LayoutMetrics,\n WalletState,\n PageElement\n} from './registry'\nimport State from './state'\n\n// Symbolizer is satisfied by both dex.Asset and core.SupportedAsset. Used by\n// Doc.symbolize.\ninterface Symbolizer {\n symbol: string\n unitInfo: UnitInfo\n}\n\nconst parser = new window.DOMParser()\n\nconst FPS = 30\n\nconst BipIDs: Record = {\n 0: 'btc',\n 42: 'dcr',\n 2: 'ltc',\n 5: 'dash',\n 20: 'dgb',\n 22: 'mona',\n 28: 'vtc',\n 3: 'doge',\n 145: 'bch',\n 60: 'eth',\n 60001: 'usdc.eth',\n 60002: 'usdt.eth',\n 60003: 'matic.eth',\n 136: 'firo',\n 133: 'zec',\n 966: 'polygon',\n 966001: 'usdc.polygon',\n 966002: 'weth.polygon',\n 966003: 'wbtc.polygon',\n 966004: 'usdt.polygon',\n 147: 'zcl'\n}\n\nconst BipSymbolIDs: Record = {};\n(function () {\n for (const k of Object.keys(BipIDs)) {\n BipSymbolIDs[BipIDs[parseInt(k)]] = parseInt(k)\n }\n})()\n\nconst BipSymbols = Object.values(BipIDs)\n\nconst RateEncodingFactor = 1e8 // same as value defined in ./orderutil\n\nconst log10RateEncodingFactor = Math.round(Math.log10(RateEncodingFactor))\n\nconst languages = navigator.languages.filter((locale: string) => locale !== 'c')\n\nconst intFormatter = new Intl.NumberFormat(languages, { maximumFractionDigits: 0 })\n\nconst fourSigFigs = new Intl.NumberFormat(languages, {\n minimumSignificantDigits: 4,\n maximumSignificantDigits: 4\n})\n\n/* A cache for formatters used for Doc.formatCoinValue. */\nconst decimalFormatters: Record = {}\n\n/*\n * decimalFormatter gets the formatCoinValue formatter for the specified decimal\n * precision.\n */\nfunction decimalFormatter (prec: number) {\n return formatter(decimalFormatters, 2, prec)\n}\n\n/* A cache for formatters used for Doc.formatFullPrecision. */\nconst fullPrecisionFormatters: Record = {}\n\n/*\n * fullPrecisionFormatter gets the formatFullPrecision formatter for the\n * specified decimal precision.\n */\nfunction fullPrecisionFormatter (prec: number, locales?: string | string[]) {\n return formatter(fullPrecisionFormatters, prec, prec, locales)\n}\n\n/*\n * formatter gets the formatter from the supplied cache if it already exists,\n * else creates it.\n */\nfunction formatter (formatters: Record, min: number, max: number, locales?: string | string[]): Intl.NumberFormat {\n const k = `${min}-${max}`\n let fmt = formatters[k]\n if (!fmt) {\n fmt = new Intl.NumberFormat(locales ?? languages, {\n minimumFractionDigits: min,\n maximumFractionDigits: max\n })\n formatters[k] = fmt\n }\n return fmt\n}\n\n/*\n * convertToConventional converts the value in atomic units to conventional\n * units.\n */\nfunction convertToConventional (v: number, unitInfo?: UnitInfo) {\n let prec = 8\n if (unitInfo) {\n const f = unitInfo.conventional.conversionFactor\n v /= f\n prec = Math.round(Math.log10(f))\n }\n return [v, prec]\n}\n\n/*\n * bestDisplayOrder is used in bestConversion, and is the order of magnitude\n * that is considered the best for display. For example, if bestDisplayOrder is\n * 1, and the choices for display are 1,000 BTC or 0.00001 Sats, the algorithm\n * will look at the orders of the conversions, 1000 => 10^3 => order 3, and\n * 0.00001 => 10^-5 => order 5, and see which is closest to bestDisplayOrder and\n * choose that conversion. In the example, 3 - bestDisplayOrder = 2 and\n * 1 - (-5) = 6, so the conversion that has the order closest to\n * bestDisplayOrder is the first one, 1,000 BTC.\n */\nconst bestDisplayOrder = 1 // 10^1 => 1\n\n/*\n * resolveUnitConversions creates a lookup object mapping unit -> conversion\n * factor. By default, resolveUnitConversions only maps the atomic and\n * conventional units. If a prefs dict is provided, additional units can be\n * included.\n */\nfunction resolveUnitConversions (ui: UnitInfo, prefs?: Record): Record {\n const unitFactors: Record = {\n [ui.atomicUnit]: 1,\n [ui.conventional.unit]: ui.conventional.conversionFactor\n }\n if (ui.denominations && prefs) {\n for (const alt of ui.denominations) if (prefs[alt.unit]) unitFactors[alt.unit] = alt.conversionFactor\n }\n return unitFactors\n}\n\n// Helpers for working with the DOM.\nexport default class Doc {\n /*\n * idel is the element with the specified id that is the descendent of the\n * specified node.\n */\n static idel (el: Document | Element, id: string): HTMLElement {\n return el.querySelector(`#${id}`) as HTMLElement\n }\n\n /* bind binds the function to the event for the element. */\n static bind (el: EventTarget, ev: string | string[], f: EventListenerOrEventListenerObject, opts?: any /* EventListenerOptions */): void {\n for (const e of (Array.isArray(ev) ? ev : [ev])) el.addEventListener(e, f, opts)\n }\n\n /* unbind removes the handler for the event from the element. */\n static unbind (el: EventTarget, ev: string, f: (e: Event) => void): void {\n el.removeEventListener(ev, f)\n }\n\n /* noderize creates a Document object from a string of HTML. */\n static noderize (html: string): Document {\n return parser.parseFromString(html, 'text/html')\n }\n\n /*\n * mouseInElement returns true if the position of mouse event, e, is within\n * the bounds of the specified element or any of its descendents.\n */\n static mouseInElement (e: MouseEvent, el: HTMLElement): boolean {\n if (el.contains(e.target as Node)) return true\n const rect = el.getBoundingClientRect()\n return e.pageX >= rect.left && e.pageX <= rect.right &&\n e.pageY >= rect.top && e.pageY <= rect.bottom\n }\n\n /*\n * layoutMetrics gets information about the elements position on the page.\n */\n static layoutMetrics (el: HTMLElement): LayoutMetrics {\n const box = el.getBoundingClientRect()\n const docEl = document.documentElement\n const top = box.top + docEl.scrollTop\n const left = box.left + docEl.scrollLeft\n const w = el.offsetWidth\n const h = el.offsetHeight\n return {\n bodyTop: top,\n bodyLeft: left,\n width: w,\n height: h,\n centerX: left + w / 2,\n centerY: top + h / 2\n }\n }\n\n static descendentMetrics (parent: PageElement, kid: PageElement): LayoutMetrics {\n const parentMetrics = Doc.layoutMetrics(parent)\n const kidMetrics = Doc.layoutMetrics(kid)\n return {\n bodyTop: kidMetrics.bodyTop - parentMetrics.bodyTop,\n bodyLeft: kidMetrics.bodyLeft - parentMetrics.bodyLeft,\n width: kidMetrics.width,\n height: kidMetrics.height,\n centerX: kidMetrics.centerX - parentMetrics.bodyLeft,\n centerY: kidMetrics.centerY - parentMetrics.bodyTop\n }\n }\n\n /* empty removes all child nodes from the specified element. */\n static empty (...els: Element[]) {\n for (const el of els) while (el.firstChild) el.removeChild(el.firstChild)\n }\n\n /*\n * setContent removes all child nodes from the specified element and appends\n * passed elements.\n */\n static setContent (ancestor: PageElement, ...kids: PageElement[]) {\n Doc.empty(ancestor)\n for (const k of kids) ancestor.appendChild(k)\n }\n\n /*\n * hide hides the specified elements. This is accomplished by adding the\n * bootstrap d-hide class to the element. Use Doc.show to undo.\n */\n static hide (...els: Element[]) {\n for (const el of els) el.classList.add('d-hide')\n }\n\n /*\n * show shows the specified elements. This is accomplished by removing the\n * bootstrap d-hide class as added with Doc.hide.\n */\n static show (...els: Element[]) {\n for (const el of els) el.classList.remove('d-hide')\n }\n\n /*\n * showTemporarily shows the specified elements for the specified time, then\n * hides it again.\n */\n static showTemporarily (timeout: number, ...els: Element[]) {\n this.show(...els)\n setTimeout(() => {\n this.hide(...els)\n }, timeout)\n }\n\n /*\n * show or hide the specified elements, based on value of the truthiness of\n * vis.\n */\n static setVis (vis: any, ...els: Element[]) {\n if (vis) Doc.show(...els)\n else Doc.hide(...els)\n }\n\n /* isHidden returns true if the specified element is hidden */\n static isHidden (el: Element): boolean {\n return el.classList.contains('d-hide')\n }\n\n /* isDisplayed returns true if the specified element is not hidden */\n static isDisplayed (el: Element): boolean {\n return !el.classList.contains('d-hide')\n }\n\n /*\n * animate runs the supplied function, which should be a \"progress\" function\n * accepting one argument. The progress function will be called repeatedly\n * with the argument varying from 0.0 to 1.0. The exact path that animate\n * takes from 0.0 to 1.0 will vary depending on the choice of easing\n * algorithm. See the Easing object for the available easing algo choices. The\n * default easing algorithm is linear.\n */\n static async animate (duration: number, f: (progress: number) => void, easingAlgo?: string) {\n await new Animation(duration, f, easingAlgo).wait()\n }\n\n static async blink (el: PageElement) {\n const [r, g, b] = State.isDark() ? [255, 255, 255] : [0, 0, 0]\n const cycles = 2\n Doc.animate(1000, (p: number) => {\n el.style.outline = `2px solid rgba(${r}, ${g}, ${b}, ${(cycles - p * cycles) % 1})`\n })\n }\n\n static applySelector (ancestor: HTMLElement, k: string): PageElement[] {\n return Array.from(ancestor.querySelectorAll(k)) as PageElement[]\n }\n\n static kids (ancestor: HTMLElement): PageElement[] {\n return Array.from(ancestor.children) as PageElement[]\n }\n\n static safeSelector (ancestor: HTMLElement, k: string): PageElement {\n const el = ancestor.querySelector(k)\n if (el) return el as PageElement\n console.warn(`no element found for selector '${k}' on element ->`, ancestor)\n return document.createElement('div')\n }\n\n /*\n * idDescendants creates an object mapping to elements which are descendants\n * of the ancestor and have id attributes. Elements are keyed by their id\n * value.\n */\n static idDescendants (ancestor: HTMLElement): Record {\n const d: Record = {}\n for (const el of Doc.applySelector(ancestor, '[id]')) d[el.id] = el\n return d\n }\n\n /*\n * formatCoinValue formats the value in atomic units into a string\n * representation in conventional units. If the value happens to be an\n * integer, no decimals are displayed. Trailing zeros may be truncated.\n */\n static formatCoinValue (vAtomic: number, unitInfo?: UnitInfo): string {\n const [v, prec] = convertToConventional(vAtomic, unitInfo)\n if (Number.isInteger(v)) return intFormatter.format(v)\n return decimalFormatter(prec).format(v)\n }\n\n static conventionalCoinValue (vAtomic: number, unitInfo?: UnitInfo): number {\n const [v] = convertToConventional(vAtomic, unitInfo)\n return v\n }\n\n /*\n * formatRateFullPrecision formats rate to represent it exactly at rate step\n * precision, trimming non-effectual zeros if there are any.\n */\n static formatRateFullPrecision (encRate: number, bui: UnitInfo, qui: UnitInfo, rateStepEnc: number) {\n const r = bui.conventional.conversionFactor / qui.conventional.conversionFactor\n const convRate = encRate * r / RateEncodingFactor\n const rateStepDigits = log10RateEncodingFactor - Math.floor(Math.log10(rateStepEnc)) -\n Math.floor(Math.log10(bui.conventional.conversionFactor) - Math.log10(qui.conventional.conversionFactor))\n if (rateStepDigits <= 0) return intFormatter.format(convRate)\n return fullPrecisionFormatter(rateStepDigits).format(convRate)\n }\n\n static formatFourSigFigs (n: number, maxDecimals?: number): string {\n return formatSigFigsWithFormatters(intFormatter, fourSigFigs, n, maxDecimals)\n }\n\n static formatInt (i: number): string {\n return intFormatter.format(i)\n }\n\n /*\n * formatFullPrecision formats the value in atomic units into a string\n * representation in conventional units using the full decimal precision\n * associated with the conventional unit's conversion factor.\n */\n static formatFullPrecision (vAtomic: number, unitInfo?: UnitInfo): string {\n const [v, prec] = convertToConventional(vAtomic, unitInfo)\n return fullPrecisionFormatter(prec).format(v)\n }\n\n /*\n * formatFiatConversion formats the value in atomic units to its representation in\n * conventional units and returns the fiat value as a string.\n */\n static formatFiatConversion (vAtomic: number, rate: number, unitInfo?: UnitInfo): string {\n if (!rate || rate === 0) return intl.prep(intl.ID_UNAVAILABLE)\n const prec = 2\n const [v] = convertToConventional(vAtomic, unitInfo)\n const value = v * rate\n return fullPrecisionFormatter(prec).format(value)\n }\n\n static languages (): string[] {\n return languages\n }\n\n static formatFiatValue (value: number): string {\n return fullPrecisionFormatter(2).format(value)\n }\n\n /*\n * bestConversion picks the best conversion factor for the atomic value. The\n * best is the one in which log10(converted_value) is closest to\n * bestDisplayOrder. Return: [converted_value, precision, unit].\n */\n static bestConversion (atoms: number, ui: UnitInfo, prefs?: Record): [number, number, string] {\n const unitFactors = resolveUnitConversions(ui, prefs)\n const logDiffs: [string, number][] = []\n const entryDiff = (entry: [string, number]) => Math.abs(Math.log10(atoms / entry[1]) - bestDisplayOrder)\n for (const entry of Object.entries(unitFactors)) logDiffs.push([entry[0], entryDiff(entry)])\n const best = logDiffs.reduce((best: [string, number], entry: [string, number]) => entry[1] < best[1] ? entry : best)\n const unit = best[0]\n const cFactor = unitFactors[unit]\n const v = atoms / cFactor\n return [v, Math.round(Math.log10(cFactor)), unit]\n }\n\n /*\n * formatBestUnitsFullPrecision formats the value with the best choice of\n * units, at full precision.\n */\n static formatBestUnitsFullPrecision (atoms: number, ui: UnitInfo, prefs?: Record): [string, string] {\n const [v, prec, unit] = this.bestConversion(atoms, ui, prefs)\n if (Number.isInteger(v)) return [intFormatter.format(v), unit]\n return [fullPrecisionFormatter(prec).format(v), unit]\n }\n\n /*\n * formatBestUnitsFourSigFigs formats the value with the best choice of\n * units and rounded to four significant figures.\n */\n static formatBestUnitsFourSigFigs (atoms: number, ui: UnitInfo, prefs?: Record): [string, string] {\n const [v, prec, unit] = this.bestConversion(atoms, ui, prefs)\n return [Doc.formatFourSigFigs(v, prec), unit]\n }\n\n /*\n * formatBestRateElement formats a rate using the best available units and\n * updates the UI element. The ancestor should have descendents with data\n * attributes [best-value, data-unit, data-unit-box, data-denom].\n */\n static formatBestRateElement (ancestor: PageElement, assetID: number, atoms: number, ui: UnitInfo, prefs?: Record) {\n Doc.formatBestValueElement(ancestor, assetID, atoms, ui, prefs)\n Doc.setText(ancestor, '[data-denom]', ui.feeRateDenom)\n }\n\n /*\n * formatBestRateElement formats a value using the best available units and\n * updates the UI element. The ancestor should have descendents with data\n * attributes [best-value, data-unit, data-unit-box].\n */\n static formatBestValueElement (ancestor: PageElement, assetID: number, atoms: number, ui: UnitInfo, prefs?: Record) {\n const [v, unit] = this.formatBestUnitsFourSigFigs(atoms, ui, prefs)\n Doc.setText(ancestor, '[data-value]', v)\n Doc.setText(ancestor, '[data-unit]', unit)\n const span = Doc.safeSelector(ancestor, '[data-unit-box]')\n span.dataset.atoms = String(atoms)\n span.dataset.assetID = String(assetID)\n }\n\n static conventionalRateStep (rateStepEnc: number, baseUnitInfo: UnitInfo, quoteUnitInfo: UnitInfo) {\n const [qFactor, bFactor] = [quoteUnitInfo.conventional.conversionFactor, baseUnitInfo.conventional.conversionFactor]\n return rateStepEnc / RateEncodingFactor * (bFactor / qFactor)\n }\n\n /*\n * logoPath creates a path to a png logo for the specified ticker symbol. If\n * the symbol is not a supported asset, the generic letter logo will be\n * requested instead.\n */\n static logoPath (symbol: string): string {\n if (BipSymbols.indexOf(symbol) === -1) symbol = symbol.substring(0, 1)\n symbol = symbol.split('.')[0] // e.g. usdc.eth => usdc\n return `/img/coins/${symbol}.png`\n }\n\n static bipSymbol (assetID: number): string {\n return BipIDs[assetID]\n }\n\n static bipIDFromSymbol (symbol: string): number {\n return BipSymbolIDs[symbol]\n }\n\n static bipCEXSymbol (assetID: number): string {\n const bipSymbol = BipIDs[assetID]\n if (!bipSymbol || bipSymbol === '') return ''\n const parts = bipSymbol.split('.')\n if (parts[0] === 'weth') return 'eth'\n return parts[0]\n }\n\n static logoPathFromID (assetID: number): string {\n return Doc.logoPath(BipIDs[assetID])\n }\n\n /*\n * symbolize creates a token-aware symbol element for the asset's symbol. For\n * non-token assets, this is simply a SYMBOL. For tokens, it'll\n * be SYMBOLPARENT.\n */\n static symbolize (asset: Symbolizer, useLogo?: boolean): PageElement {\n const ticker = asset.unitInfo.conventional.unit\n const symbolSpan = document.createElement('span')\n symbolSpan.textContent = ticker.toUpperCase()\n const parts = asset.symbol.split('.')\n const isToken = parts.length === 2\n if (!isToken) return symbolSpan\n const parentSymbol = parts[1]\n const span = document.createElement('span')\n span.appendChild(symbolSpan)\n if (useLogo) {\n const parentLogo = document.createElement('img')\n parentLogo.src = Doc.logoPath(parentSymbol)\n parentLogo.classList.add('token-parent')\n span.appendChild(parentLogo)\n return span\n }\n const parentSup = document.createElement('sup')\n parentSup.textContent = parentSymbol.toUpperCase()\n parentSup.classList.add('token-parent')\n span.appendChild(parentSup)\n return span\n }\n\n /*\n * shortSymbol removes the short format of a symbol, with any parent chain\n * identifier removed\n */\n static shortSymbol (symbol: string): string {\n return symbol.split('.')[0].toUpperCase()\n }\n\n /*\n * setText sets the textContent for all descendant elements that match the\n * specified CSS selector.\n */\n static setText (ancestor: PageElement, selector: string, textContent: string) {\n for (const el of Doc.applySelector(ancestor, selector)) el.textContent = textContent\n }\n\n static setSrc (ancestor: PageElement, selector: string, textContent: string) {\n for (const img of Doc.applySelector(ancestor, selector)) img.src = textContent\n }\n\n /*\n * cleanTemplates removes the elements from the DOM and deletes the id\n * attribute.\n */\n static cleanTemplates (...tmpls: HTMLElement[]) {\n tmpls.forEach(tmpl => {\n tmpl.remove()\n tmpl.removeAttribute('id')\n })\n }\n\n /*\n * tmplElement is a helper function for grabbing sub-elements of the market list\n * template.\n */\n static tmplElement (ancestor: Document | HTMLElement, s: string): PageElement {\n return ancestor.querySelector(`[data-tmpl=\"${s}\"]`) || document.createElement('div')\n }\n\n /*\n * parseTemplate returns an object of data-tmpl elements, keyed by their\n * data-tmpl values.\n */\n static parseTemplate (ancestor: HTMLElement): Record {\n const d: Record = {}\n for (const el of Doc.applySelector(ancestor, '[data-tmpl]')) d[el.dataset.tmpl || ''] = el\n return d\n }\n\n /*\n * timeSince returns a string representation of the duration since the\n * specified unix timestamp (milliseconds).\n */\n static timeSince (ms: number): string {\n return Doc.formatDuration((new Date().getTime()) - ms)\n }\n\n /*\n * hmsSince returns a time duration since the specified unix timestamp\n * formatted as HH:MM:SS\n */\n static hmsSince (secs: number) {\n let r = (new Date().getTime() / 1000) - secs\n const h = String(Math.floor(r / 3600))\n r = r % 3600\n const m = String(Math.floor(r / 60))\n const s = String(Math.floor(r % 60))\n return `${h.padStart(2, '0')}:${m.padStart(2, '0')}:${s.padStart(2, '0')}`\n }\n\n /* formatDuration returns a string representation of the duration */\n static formatDuration (dur: number): string {\n let seconds = Math.floor(dur)\n let result = ''\n let count = 0\n const add = (n: number, s: string) => {\n if (n > 0 || count > 0) count++\n if (n > 0) result += `${n} ${s} `\n return count >= 2\n }\n let y, mo, d, h, m, s\n [y, seconds] = timeMod(seconds, aYear)\n if (add(y, 'y')) { return result }\n [mo, seconds] = timeMod(seconds, aMonth)\n if (add(mo, 'mo')) { return result }\n [d, seconds] = timeMod(seconds, aDay)\n if (add(d, 'd')) { return result }\n [h, seconds] = timeMod(seconds, anHour)\n if (add(h, 'h')) { return result }\n [m, seconds] = timeMod(seconds, aMinute)\n if (add(m, 'm')) { return result }\n [s, seconds] = timeMod(seconds, 1000)\n add(s, 's')\n return result || '0 s'\n }\n\n /*\n * disableMouseWheel can be used to disable the mouse wheel for any\n * input. It is very easy to unknowingly scroll up on a number input\n * and then submit an unexpected value. This function prevents the\n * scroll increment/decrement behavior for a wheel action on a\n * number input.\n */\n static disableMouseWheel (...inputFields: Element[]) {\n for (const inputField of inputFields) {\n Doc.bind(inputField, 'wheel', () => { /* pass */ }, { passive: true })\n }\n }\n\n // showFormError can be used to set and display error message on forms.\n static showFormError (el: PageElement, msg: any) {\n el.textContent = msg\n Doc.show(el)\n }\n\n // showFiatValue displays the fiat equivalent for the provided amount.\n static showFiatValue (display: PageElement, amount: number, rate: number, ui: UnitInfo): void {\n if (rate) {\n display.textContent = Doc.formatFiatConversion(amount, rate, ui)\n Doc.show(display.parentElement as Element)\n } else Doc.hide(display.parentElement as Element)\n }\n}\n\n/*\n * Animation is a handler for starting and stopping animations.\n */\nexport class Animation {\n done: (() => void) | undefined\n endAnimation: boolean\n thread: Promise\n static Forever: number\n\n constructor (duration: number, f: (progress: number) => void, easingAlgo?: string, done?: () => void) {\n this.done = done\n this.thread = this.run(duration, f, easingAlgo)\n }\n\n /*\n * run runs the animation function, increasing progress from 0 to 1 in a\n * manner dictated by easingAlgo.\n */\n async run (duration: number, f: (progress: number) => void, easingAlgo?: string) {\n duration = duration >= 0 ? duration : 1000 * 86400 * 365 * 10 // 10 years, in ms\n const easer = easingAlgo ? Easing[easingAlgo] : Easing.linear\n const start = new Date().getTime()\n const end = (duration === Animation.Forever) ? Number.MAX_SAFE_INTEGER : start + duration\n const range = end - start\n const frameDuration = 1000 / FPS\n let now = start\n this.endAnimation = false\n while (now < end) {\n if (this.endAnimation) return this.runCompletionFunction()\n f(easer((now - start) / range))\n await sleep(frameDuration)\n now = new Date().getTime()\n }\n f(1)\n this.runCompletionFunction()\n }\n\n /* wait returns a promise that will resolve when the animation completes. */\n async wait () {\n await this.thread\n }\n\n /* stop schedules the animation to exit at its next frame. */\n stop () {\n this.endAnimation = true\n }\n\n /*\n * stopAndWait stops the animations and returns a promise that will resolve\n * when the animation exits.\n */\n async stopAndWait () {\n this.stop()\n await this.wait()\n }\n\n /* runCompletionFunction runs any registered callback function */\n runCompletionFunction () {\n if (this.done) this.done()\n }\n}\nAnimation.Forever = -1\n\n/* Easing algorithms for animations. */\nexport const Easing: Record number> = {\n linear: t => t,\n easeIn: t => t * t,\n easeOut: t => t * (2 - t),\n easeInHard: t => t * t * t,\n easeOutHard: t => (--t) * t * t + 1,\n easeOutElastic: t => {\n const c4 = (2 * Math.PI) / 3\n return t === 0\n ? 0\n : t === 1\n ? 1\n : Math.pow(2, -10 * t) * Math.sin((t * 10 - 0.75) * c4) + 1\n }\n}\n\n/* WalletIcons are used for controlling wallets in various places. */\nexport class WalletIcons {\n icons: Record\n status: Element\n\n constructor (box: HTMLElement) {\n const stateElement = (name: string) => box.querySelector(`[data-state=${name}]`) as HTMLElement\n this.icons = {}\n this.icons.sleeping = stateElement('sleeping')\n this.icons.locked = stateElement('locked')\n this.icons.unlocked = stateElement('unlocked')\n this.icons.nowallet = stateElement('nowallet')\n this.icons.syncing = stateElement('syncing')\n this.icons.nopeers = stateElement('nopeers')\n this.icons.disabled = stateElement('disabled')\n this.status = stateElement('status')\n }\n\n /* sleeping sets the icons to indicate that the wallet is not connected. */\n sleeping () {\n const i = this.icons\n Doc.hide(i.locked, i.unlocked, i.nowallet, i.syncing, i.disabled)\n Doc.show(i.sleeping)\n if (this.status) this.status.textContent = intl.prep(intl.ID_OFF)\n }\n\n /*\n * locked sets the icons to indicate that the wallet is connected, but locked.\n */\n locked () {\n const i = this.icons\n Doc.hide(i.unlocked, i.nowallet, i.sleeping, i.disabled)\n Doc.show(i.locked)\n if (this.status) this.status.textContent = intl.prep(intl.ID_LOCKED)\n }\n\n /*\n * unlocked sets the icons to indicate that the wallet is connected and\n * unlocked.\n */\n unlocked () {\n const i = this.icons\n Doc.hide(i.locked, i.nowallet, i.sleeping, i.disabled)\n Doc.show(i.unlocked)\n if (this.status) this.status.textContent = intl.prep(intl.ID_READY)\n }\n\n /* nowallet sets the icons to indicate that no wallet exists. */\n nowallet () {\n const i = this.icons\n Doc.hide(i.locked, i.unlocked, i.sleeping, i.syncing, i.disabled)\n Doc.show(i.nowallet)\n if (this.status) this.status.textContent = intl.prep(intl.ID_NO_WALLET)\n }\n\n /* set the icons to indicate that the wallet is disabled */\n disabled () {\n const i = this.icons\n Doc.hide(i.locked, i.unlocked, i.sleeping, i.syncing, i.nowallet, i.nopeers)\n Doc.show(i.disabled)\n i.disabled.dataset.tooltip = intl.prep(intl.ID_DISABLED_MSG)\n }\n\n setSyncing (wallet: WalletState | null) {\n const syncIcon = this.icons.syncing\n if (!wallet || !wallet.running || wallet.disabled) {\n Doc.hide(syncIcon)\n return\n }\n\n if (wallet.peerCount === 0) {\n Doc.show(this.icons.nopeers)\n Doc.hide(syncIcon) // potentially misleading with no peers\n return\n }\n Doc.hide(this.icons.nopeers)\n\n if (!wallet.synced) {\n Doc.show(syncIcon)\n syncIcon.dataset.tooltip = intl.prep(intl.ID_WALLET_SYNC_PROGRESS, { syncProgress: (wallet.syncProgress * 100).toFixed(1) })\n return\n }\n Doc.hide(syncIcon)\n }\n\n /* reads the core.Wallet state and sets the icon visibility. */\n readWallet (wallet: WalletState | null) {\n this.setSyncing(wallet)\n if (!wallet) return this.nowallet()\n switch (true) {\n case (wallet.disabled):\n this.disabled()\n break\n case (!wallet.running):\n this.sleeping()\n break\n case (!wallet.open):\n this.locked()\n break\n case (wallet.open):\n this.unlocked()\n break\n default:\n console.error('wallet in unknown state', wallet)\n }\n }\n}\n\n/*\n * AniToggle is a small toggle switch, defined in HTML with the element\n *
. The animations are defined in the anitoggle\n * CSS class. AniToggle triggers the callback on click events, but does not\n * update toggle appearance, so the caller must call the setState method from\n * the callback or elsewhere if the newState\n * is accepted.\n */\nexport class AniToggle {\n toggle: PageElement\n toggling: boolean\n\n constructor (toggle: PageElement, errorEl: PageElement, initialState: boolean, callback: (newState: boolean) => Promise) {\n this.toggle = toggle\n if (toggle.children.length === 0) toggle.appendChild(document.createElement('div'))\n\n Doc.bind(toggle, 'click', async (e: MouseEvent) => {\n e.stopPropagation()\n Doc.hide(errorEl)\n const newState = !toggle.classList.contains('on')\n this.toggling = true\n try {\n await callback(newState)\n } catch (e) {\n this.toggling = false\n Doc.show(errorEl)\n errorEl.textContent = intl.prep(intl.ID_API_ERROR, { msg: e.msg || String(e) })\n return\n }\n this.toggling = false\n })\n this.setState(initialState)\n }\n\n setState (state: boolean) {\n if (state) this.toggle.classList.add('on')\n else this.toggle.classList.remove('on')\n }\n}\n\n/* sleep can be used by async functions to pause for a specified period. */\nfunction sleep (ms: number) {\n return new Promise(resolve => setTimeout(resolve, ms))\n}\n\nconst aYear = 31536000000\nconst aMonth = 2592000000\nconst aDay = 86400000\nconst anHour = 3600000\nconst aMinute = 60000\n\n/* timeMod returns the quotient and remainder of t / dur. */\nfunction timeMod (t: number, dur: number) {\n const n = Math.floor(t / dur)\n return [n, t - n * dur]\n}\n\nfunction formatSigFigsWithFormatters (intFormatter: Intl.NumberFormat, sigFigFormatter: Intl.NumberFormat, n: number, maxDecimals?: number, locales?: string | string[]): string {\n if (n >= 1000) return intFormatter.format(n)\n const s = sigFigFormatter.format(n)\n if (typeof maxDecimals !== 'number') return s\n const fractional = sigFigFormatter.formatToParts(n).filter((part: Intl.NumberFormatPart) => part.type === 'fraction')[0]?.value ?? ''\n if (fractional.length <= maxDecimals) return s\n return fullPrecisionFormatter(maxDecimals, locales).format(n)\n}\n\nif (process.env.NODE_ENV === 'development') {\n // Code will only appear in dev build.\n // https://webpack.js.org/guides/production/\n window.testFormatFourSigFigs = () => {\n const tests: [string, string, number | undefined, string][] = [\n ['en-US', '1.234567', undefined, '1.235'], // sigFigFormatter\n ['en-US', '1.234567', 2, '1.23'], // decimalFormatter\n ['en-US', '1234', undefined, '1,234.0'], // oneFractionalDigit\n ['en-US', '12', undefined, '12.00'], // sigFigFormatter\n ['fr-FR', '123.45678', undefined, '123,5'], // oneFractionalDigit\n ['fr-FR', '1234.5', undefined, '1 234,5'], // U+202F for thousands separator\n // For Arabic, https://www.saitak.com/number is useful, but seems to use\n // slightly different unicode points and no thousands separator. I think\n // the Arabic decimal separator is supposed to be more like a point, not\n // a comma, but Google Chrome uses U+066B (Arabic Decimal Separator),\n // which looks like a comma to me. ¯\\_(ツ)_/¯\n ['ar-EG', '123.45678', undefined, '١٢٣٫٥'],\n ['ar-EG', '1234', undefined, '١٬٢٣٤٫٠'],\n ['ar-EG', '0.12345', 3, '٠٫١٢٣']\n ]\n\n // Reproduce the NumberFormats with ONLY our desired language.\n for (const [code, unformatted, maxDecimals, expected] of tests) {\n const intFormatter = new Intl.NumberFormat(code, { // oneFractionalDigit\n minimumFractionDigits: 1,\n maximumFractionDigits: 1\n })\n const sigFigFormatter = new Intl.NumberFormat(code, {\n minimumSignificantDigits: 4,\n maximumSignificantDigits: 4\n })\n for (const k in decimalFormatters) delete decimalFormatters[k] // cleanup\n for (const k in fullPrecisionFormatters) delete fullPrecisionFormatters[k] // cleanup\n const s = formatSigFigsWithFormatters(intFormatter, sigFigFormatter, parseFloatDefault(unformatted), maxDecimals, code)\n if (s !== expected) console.log(`TEST FAILED: f('${code}', ${unformatted}, ${maxDecimals}) => '${s}' != '${expected}'}`)\n else console.log(`✔️ f('${code}', ${unformatted}, ${maxDecimals}) => ${s} ✔️`)\n }\n }\n\n window.testFormatRateFullPrecision = () => {\n const tests: [number, number, number, number, string][] = [\n // Two utxo assets with a conventional rate of 0.15. Conventional rate\n // step is 100 / 1e8 = 1e-6, so there should be 6 decimal digits.\n [1.5e7, 100, 1e8, 1e8, '0.150000'],\n // USDC quote -> utxo base with a rate of $10 / 1 XYZ. USDC has an\n // conversion factor of 1e6, so $10 encodes to 1e7, 1 XYZ encodes to 1e8,\n // encoded rate is 1e7 / 1e8 * 1e8 = 1e7, bFactor / qFactor is 1e2.\n // The conventional rate step is 200 / 1e8 * 1e2 = 2e-4, so using\n // rateStepDigits, we should get 4 decimal digits.\n [1e7, 200, 1e6, 1e8, '10.0000'],\n // Set a rate of 1 atom USDC for 0.01 BTC. That atomic rate will be 1 /\n // 1e6 = 1e-6. The encoded rate will be 1e-6 * 1e8 = 1e2. As long as our\n // rate step divides evenly into 100, this should work. The conventional\n // rate is 1e-6 / 1e-2 = 1e-4, so expect 4 decimal digits.\n [1e2, 100, 1e6, 1e8, '0.0001'],\n // DCR-ETH, expect 6 decimals.\n [1.5e7, 1000, 1e9, 1e8, '0.015000'],\n [1e6, 1000, 1e9, 1e8, '0.001000'],\n [1e3, 1000, 1e9, 1e8, '0.000001'],\n [100001000, 1000, 1e9, 1e8, '0.100001'],\n [1000001000, 1000, 1e9, 1e8, '1.000001'],\n // DCR-USDC, expect 3 decimals.\n [1.5e7, 1000, 1e6, 1e8, '15.000'],\n [1e6, 1000, 1e6, 1e8, '1.000'],\n [1e3, 1000, 1e6, 1e8, '0.001'],\n [101000, 1000, 1e6, 1e8, '0.101'],\n [1001000, 1000, 1e6, 1e8, '1.001'],\n // UTXO assets but with a rate step that's not a perfect power of 10.\n // For a rate step of 500, a min rate would be e.g. rate step = 500.\n // 5e2 / 1e8 = 5e-6 = 0.000005\n [5e2, 500, 1e8, 1e8, '0.000005']\n ]\n\n for (const [encRate, rateStep, qFactor, bFactor, expEncoding] of tests) {\n for (const k in fullPrecisionFormatters) delete fullPrecisionFormatters[k] // cleanup\n const bui = { conventional: { conversionFactor: bFactor } } as any as UnitInfo\n const qui = { conventional: { conversionFactor: qFactor } } as any as UnitInfo\n const enc = Doc.formatRateFullPrecision(encRate, bui, qui, rateStep)\n if (enc !== expEncoding) console.log(`TEST FAILED: f(${encRate}, ${bFactor}, ${qFactor}, ${rateStep}) => ${enc} != ${expEncoding}`)\n else console.log(`✔️ f(${encRate}, ${bFactor}, ${qFactor}, ${rateStep}) => ${enc} ✔️`)\n }\n }\n}\n\nexport interface NumberInputOpts {\n prec?: number\n sigFigs?: boolean\n changed?: (v: number) => void\n min?: number\n set?: (v: number, s: string) => void // called when setValue is called\n}\n\nexport class NumberInput {\n input: PageElement\n prec: number\n fmt: (v: number, prec: number) => [number, string]\n changed: (v: number) => void\n set?: (v: number, s: string) => void\n min: number\n\n constructor (input: PageElement, opts: NumberInputOpts) {\n this.input = input\n this.prec = opts.prec ?? 0\n this.fmt = opts.sigFigs ? toFourSigFigs : toPrecision\n this.changed = opts.changed ?? (() => { /* pass */ })\n this.set = opts.set\n this.min = opts.min ?? 0\n\n Doc.bind(input, 'change', () => { this.inputChanged() })\n }\n\n inputChanged () {\n const { changed } = this\n if (changed) changed(this.value())\n }\n\n setValue (v: number) {\n this.input.value = String(v)\n v = this.value()\n if (this.set) this.set(v, this.input.value)\n }\n\n value () {\n const { input, min, prec, fmt } = this\n const rawV = Math.max(parseFloatDefault(input.value, min ?? 0), min ?? 0)\n const [v, s] = fmt(rawV, prec ?? 0)\n input.value = s\n return v\n }\n}\n\nexport interface IncrementalInputOpts extends NumberInputOpts {\n inc?: number\n}\n\nexport class IncrementalInput extends NumberInput {\n inc: number\n opts: IncrementalInputOpts\n\n constructor (box: PageElement, opts: IncrementalInputOpts) {\n super(Doc.safeSelector(box, 'input'), opts)\n this.opts = opts\n this.inc = opts.inc ?? 1\n\n const up = Doc.safeSelector(box, '.ico-arrowup')\n const down = Doc.safeSelector(box, '.ico-arrowdown')\n\n Doc.bind(up, 'click', () => { this.increment(1) })\n Doc.bind(down, 'click', () => { this.increment(-1) })\n }\n\n setIncrementAndMinimum (inc: number, min: number) {\n this.inc = inc\n this.min = min\n }\n\n increment (sign: number) {\n const { inc, min, input } = this\n input.value = String(Math.max(this.value() + sign * inc, min))\n this.inputChanged()\n }\n}\n\nexport class MiniSlider {\n track: PageElement\n ball: PageElement\n r: number\n changed: (r: number) => void\n\n constructor (box: PageElement, changed: (r: number) => void) {\n this.changed = changed\n this.r = 0\n\n const color = document.createElement('div')\n color.dataset.tmpl = 'color'\n box.appendChild(color)\n const track = this.track = document.createElement('div')\n track.dataset.tmpl = 'track'\n color.appendChild(track)\n const ball = this.ball = document.createElement('div')\n ball.dataset.tmpl = 'ball'\n track.appendChild(ball)\n\n Doc.bind(box, 'mousedown', (e: MouseEvent) => {\n if (e.button !== 0) return\n e.preventDefault()\n e.stopPropagation()\n const startX = e.pageX\n const w = track.clientWidth\n const startLeft = this.r * w\n const left = (ee: MouseEvent) => Math.max(Math.min(startLeft + (ee.pageX - startX), w), 0)\n const trackMouse = (ee: MouseEvent) => {\n ee.preventDefault()\n const l = left(ee)\n this.r = l / w\n ball.style.left = `${this.r * 100}%`\n this.changed(this.r)\n }\n const mouseUp = (ee: MouseEvent) => {\n trackMouse(ee)\n Doc.unbind(document, 'mousemove', trackMouse)\n Doc.unbind(document, 'mouseup', mouseUp)\n }\n Doc.bind(document, 'mousemove', trackMouse)\n Doc.bind(document, 'mouseup', mouseUp)\n })\n\n Doc.bind(box, 'click', (e: MouseEvent) => {\n if (e.button !== 0) return\n const x = e.pageX\n const m = Doc.layoutMetrics(track)\n this.r = clamp((x - m.bodyLeft) / m.width, 0, 1)\n ball.style.left = `${this.r * m.width}px`\n this.changed(this.r)\n })\n }\n\n setValue (r: number) {\n this.r = clamp(r, 0, 1)\n this.ball.style.left = `${this.r * 100}%`\n }\n}\n\nexport function toPrecision (v: number, prec: number): [number, string] {\n const ord = Math.pow(10, prec ?? 0)\n v = Math.round(v * ord) / ord\n let s = v.toFixed(prec)\n if (prec > 0) {\n while (s.endsWith('0')) s = s.substring(0, s.length - 1)\n if (s.endsWith('.')) s = s.substring(0, s.length - 1)\n }\n return [v, s]\n}\n\nexport function toFourSigFigs (v: number, maxPrec: number): [number, string] {\n const ord = Math.floor(Math.log10(Math.abs(v)))\n if (ord >= 3) return [Math.round(v), v.toFixed(0)]\n const prec = Math.min(4 - ord, maxPrec)\n return toPrecision(v, prec)\n}\n\nexport function parseFloatDefault (inputValue: string | undefined, defaultValue?: number) {\n const v = parseFloat((inputValue ?? '').replace(/,/g, ''))\n if (!isNaN(v)) return v\n return defaultValue ?? 0\n}\n\n/* clamp returns v if min <= v <= max, else min or max. */\nexport function clamp (v: number, min: number, max: number): number {\n if (v < min) return min\n if (v > max) return max\n return v\n}\n\nexport async function setupCopyBtn (txt: string, textEl: PageElement, btnEl: PageElement, color: string) {\n try {\n await navigator.clipboard.writeText(txt)\n } catch (err) {\n console.error('Unable to copy: ', err)\n }\n const textOriginalColor = textEl.style.color\n const btnOriginalColor = btnEl.style.color\n textEl.style.color = color\n btnEl.style.color = color\n setTimeout(() => {\n textEl.style.color = textOriginalColor\n btnEl.style.color = btnOriginalColor\n }, 350)\n}\n","declare global {\n interface Window {\n log: (...args: any) => void\n enableLogger: (loggerID: string, enable: boolean) => void\n recordLogger: (loggerID: string, enable: boolean) => void\n dumpLogger: (loggerID: string) => void\n mmstatus: () => Promise\n testFormatFourSigFigs: () => void\n testFormatRateFullPrecision: () => void\n user: () => User\n cexBook: () => Promise\n mmStatus: () => MarketMakingStatus\n isWebview?: () => boolean\n webkit: any | undefined\n openUrl: (url: string) => void\n sendOSNotification (title: string, body?: string): void\n clearLocale (): void\n }\n}\n\nexport enum ConnectionStatus {\n Disconnected = 0,\n Connected = 1,\n InvalidCert = 2,\n}\n\nexport interface BondOptions {\n bondAssetID: number\n targetTier: number\n maxBondedAmt: number\n}\n\nexport interface Reputation {\n bondedTier: number\n penalties: number\n legacyTier: boolean\n score: number\n}\n\nexport interface ExchangeAuth {\n rep: Reputation\n bondAssetID: number\n pendingStrength: number\n weakStrength: number\n liveStrength: number\n targetTier: number\n effectiveTier: number\n maxBondedAmt: number\n penaltyComps: number\n pendingBonds: PendingBondState[]\n expiredBonds: any[]\n compensation: number\n}\n\nexport interface Exchange {\n host: string\n acctID: string\n auth: ExchangeAuth\n markets: Record\n assets: Record\n connectionStatus: ConnectionStatus\n viewOnly: boolean\n bondAssets: Record\n candleDurs: string[]\n maxScore: number\n penaltyThreshold: number\n disabled:boolean\n}\n\nexport interface Candle {\n startStamp: number\n endStamp: number\n matchVolume: number\n quoteVolume: number\n highRate: number\n lowRate: number\n startRate: number\n endRate: number\n}\n\nexport interface CandlesPayload {\n dur: string\n ms: number\n candles: Candle[]\n}\n\nexport interface Market {\n name: string\n baseid: number\n basesymbol: string\n quoteid: number\n quotesymbol: string\n lotsize: number\n parcelsize: number\n ratestep: number\n epochlen: number\n startepoch: number\n buybuffer: number\n orders: Order[]\n spot: Spot | undefined\n atomToConv: number\n inflight: InFlightOrder[]\n minimumRate: number\n}\n\nexport interface InFlightOrder extends Order {\n tempID: number\n}\n\nexport interface Order {\n host: string\n baseID: number\n baseSymbol: string\n quoteID: number\n quoteSymbol: string\n market: string\n type: number\n id: string\n stamp: number\n submitTime: number\n sig: string\n status: number\n epoch: number\n qty: number\n sell: boolean\n filled: number\n matches: Match[]\n cancelling: boolean\n canceled: boolean\n feesPaid: FeeBreakdown\n fundingCoins: Coin[]\n accelerationCoins: Coin[]\n lockedamt: number\n rate: number // limit only\n tif: number // limit only\n targetOrderID: string // cancel only\n readyToTick: boolean\n}\n\nexport interface Match {\n matchID: string\n status: number\n active: boolean\n revoked: boolean\n rate: number\n qty: number\n side: number\n feeRate: number\n swap: Coin\n counterSwap: Coin\n redeem: Coin\n counterRedeem: Coin\n refund: Coin\n stamp: number\n isCancel: boolean\n}\n\nexport interface Spot {\n stamp: number\n baseID: number\n quoteID: number\n rate: number\n bookVolume: number // Unused?\n change24: number\n vol24: number\n low24: number\n high24: number\n}\n\nexport interface Asset {\n id: number\n symbol: string\n version: number\n maxFeeRate: number\n swapSize: number\n swapSizeBase: number\n redeemSize: number\n swapConf: number\n unitInfo: UnitInfo\n}\n\nexport interface BondAsset {\n ver: number\n id: number\n confs: number\n amount: number\n}\n\nexport interface PendingBondState {\n symbol: string\n assetID: number\n coinID: string\n confs: number\n}\n\nexport interface FeeBreakdown {\n swap: number\n redemption: number\n}\n\nexport interface SupportedAsset {\n id: number\n symbol: string\n name: string\n wallet: WalletState\n info?: WalletInfo\n token?: Token\n unitInfo: UnitInfo\n walletCreationPending: boolean\n}\n\nexport interface Token {\n parentID: number\n name: string\n unitInfo: UnitInfo\n contractAddress: string\n definition: WalletDefinition\n}\n\nexport enum ApprovalStatus {\n Approved = 0,\n Pending = 1,\n NotApproved = 2\n}\n\nexport interface FeeState {\n rate: number\n send: number\n swap: number\n redeem: number\n refund: number\n stampMS: number\n}\n\nexport interface SyncStatus {\n synced: boolean\n targetHeight: number\n startingBlocks: number\n blocks: number\n txs: number | undefined\n}\n\nexport interface WalletState {\n symbol: string\n assetID: number\n version: number\n type: string\n traits: number\n open: boolean\n running: boolean\n disabled: boolean\n balance: WalletBalance\n address: string\n units: string\n encrypted: boolean\n peerCount: number\n synced: boolean\n syncProgress: number\n syncStatus: SyncStatus\n approved: Record\n feeState?: FeeState\n}\n\nexport interface WalletInfo {\n name: string\n version: number\n availablewallets: WalletDefinition[]\n versions: number[]\n emptyidx: number\n unitinfo: UnitInfo\n}\n\nexport interface WalletBalance {\n available: number\n immature: number\n locked: number\n stamp: string // time.Time\n orderlocked: number\n contractlocked: number\n bondlocked: number\n bondReserves: number\n reservesDeficit: number\n other: Record\n}\n\nexport interface CustomBalance {\n amt: number\n locked: boolean\n}\n\nexport interface WalletDefinition {\n seeded: boolean\n type: string\n tab: string\n description: string\n configpath: string\n configopts: ConfigOption[]\n multifundingopts: OrderOption[]\n noauth: boolean\n guidelink: string\n}\n\nexport interface ConfigOption {\n key: string\n displayname: string\n description: string\n default: any\n max: any\n min: any\n noecho: boolean\n isboolean: boolean\n isdate: boolean\n disablewhenactive: boolean\n isBirthdayConfig: boolean\n repeatable?: string\n repeatN?: number\n regAsset?: number\n required?: boolean\n dependsOn?: string\n}\n\nexport interface Coin {\n id: string\n stringID: string\n assetID: number\n symbol: string\n confs: Confirmations\n}\n\nexport interface Confirmations {\n required: number\n count: number\n}\n\nexport interface UnitInfo {\n atomicUnit: string\n conventional: Denomination\n denominations: Denomination[]\n feeRateDenom: string\n}\n\nexport interface Denomination {\n unit: string\n conversionFactor: number\n}\n\nexport interface ExtensionConfiguredWallet {\n hiddenFields: string[]\n disableWalletType: boolean\n disablePassword: boolean\n disableStaking: boolean\n disablePrivacy: boolean\n}\n\nexport interface ExtensionModeConfig {\n name: string\n restrictedWallets: Record\n}\n\nexport interface User {\n exchanges: Record\n inited: boolean\n seedgentime: number\n assets: Record\n fiatRates: Record\n bots: BotReport[]\n net: number\n extensionModeConfig: ExtensionModeConfig\n actions: ActionRequiredNote[]\n}\n\nexport interface CoreNote {\n type: string\n topic: string\n subject: string\n details: string\n severity: number\n stamp: number\n acked: boolean\n id: string\n}\n\nexport interface BondNote extends CoreNote {\n asset: number\n confirmations: number\n dex: string\n coinID: string | null\n tier: number | null\n auth: ExchangeAuth | null\n}\n\nexport interface ReputationNote extends CoreNote {\n host: string\n rep: Reputation\n}\n\nexport interface BalanceNote extends CoreNote {\n assetID: number\n balance: WalletBalance\n}\n\nexport interface RateNote extends CoreNote {\n fiatRates: Record\n}\n\nexport interface WalletConfigNote extends CoreNote {\n wallet: WalletState\n}\n\nexport interface WalletSyncNote extends CoreNote {\n assetID: number\n syncStatus: SyncStatus\n syncProgress: number\n}\n\nexport type WalletStateNote = WalletConfigNote\n\nexport interface WalletCreationNote extends CoreNote {\n assetID: number\n}\n\nexport interface BaseWalletNote {\n route: string\n assetID: number\n}\n\nexport interface TipChangeNote extends BaseWalletNote {\n tip: number\n data: any\n}\n\nexport interface CustomWalletNote extends BaseWalletNote {\n payload: any\n}\n\nexport interface TransactionNote extends BaseWalletNote {\n transaction: WalletTransaction\n new: boolean\n}\n\nexport interface ActionRequiredNote extends BaseWalletNote {\n uniqueID: string\n actionID: string\n payload: any\n}\n\nexport interface ActionResolvedNote extends BaseWalletNote {\n uniqueID: string\n}\n\nexport interface TransactionActionNote {\n tx: WalletTransaction\n nonce: number\n newFees: number\n}\n\nexport interface WalletNote extends CoreNote {\n payload: BaseWalletNote\n}\n\nexport interface CoreActionRequiredNote extends CoreNote {\n payload: ActionRequiredNote\n}\n\nexport interface RejectedRedemptionData {\n assetID: number\n orderID: string\n coinID: string\n coinFmt: string\n}\n\nexport interface SpotPriceNote extends CoreNote {\n host: string\n spots: Record\n}\n\nexport interface RunStatsNote extends CoreNote {\n host: string\n baseID: number\n quoteID: number\n stats?: RunStats\n}\n\nexport interface RunEventNote extends CoreNote {\n host: string\n baseID: number\n quoteID: number\n startTime: number\n event: MarketMakingEvent\n}\n\nexport interface MakerProgram {\n host: string\n baseID: number\n quoteID: number\n lots: number\n oracleWeighting: number\n oracleBias: number\n driftTolerance: number\n gapFactor: number\n gapStrategy: string\n}\n\nexport interface BotOrder {\n host: string\n marketID: string\n orderID: string\n}\n\nexport interface BotReport {\n programID: number\n program: MakerProgram\n running: boolean\n orders: BotOrder\n}\n\nexport interface LotFees {\n swap: number\n redeem: number\n refund: number\n}\n\nexport interface LotFeeRange {\n max: LotFees\n estimated: LotFees\n}\n\nexport interface AssetBookingFees extends LotFeeRange {\n bookingFeesPerLot: number\n bookingFeesPerCounterLot: number\n bookingFees: number\n swapReservesFactor: number // (1 + orderReservesFactor)\n redeemReservesFactor: number\n tokenFeesPerSwap: number\n}\n\nexport interface BookingFees {\n base: AssetBookingFees\n quote:AssetBookingFees\n}\n\nexport interface MarketReport {\n price: number\n oracles: OracleReport[]\n baseFiatRate: number\n quoteFiatRate: number\n baseFees: LotFeeRange\n quoteFees: LotFeeRange\n}\n\nexport interface MatchNote extends CoreNote {\n orderID: string\n match: Match\n host: string\n marketID: string\n}\n\nexport interface ConnEventNote extends CoreNote {\n host: string\n connectionStatus: ConnectionStatus\n}\n\nexport interface OrderNote extends CoreNote {\n order: Order\n tempID: number\n}\n\nexport interface RecentMatch {\n rate: number\n qty: number\n stamp: number\n sell: boolean\n}\n\nexport interface EpochNote extends CoreNote {\n host: string\n marketID: string\n epoch: number\n}\n\nexport interface APIResponse {\n requestSuccessful: boolean\n ok: boolean\n msg: string\n err?: string\n}\n\nexport interface LogMessage {\n time: string\n msg: string\n}\n\nexport interface NoteElement extends HTMLElement {\n note: CoreNote\n}\n\nexport interface BalanceResponse extends APIResponse {\n balance: WalletBalance\n}\n\nexport interface LayoutMetrics {\n bodyTop: number\n bodyLeft: number\n width: number\n height: number\n centerX: number\n centerY: number\n}\n\nexport interface PageElement extends HTMLElement {\n value?: string\n src?: string\n files?: FileList\n checked?: boolean\n href?: string\n htmlFor?: string\n name?: string\n options?: HTMLOptionElement[]\n selectedIndex?: number\n disabled?: boolean\n}\n\nexport interface BooleanConfig {\n reason: string\n}\n\nexport interface XYRangePoint {\n label: string\n x: number\n y: number\n}\n\nexport interface XYRange {\n start: XYRangePoint\n end: XYRangePoint\n xUnit: string\n yUnit: string\n roundX?: boolean\n roundY?: boolean\n}\n\nexport interface OrderOption extends ConfigOption {\n boolean?: BooleanConfig\n xyRange?: XYRange\n showByDefault?: boolean\n quoteAssetOnly?: boolean\n}\n\nexport interface SwapEstimate {\n lots: number\n value: number\n maxFees: number\n realisticWorstCase: number\n realisticBestCase: number\n feeReservesPerLot: number\n}\n\nexport interface RedeemEstimate {\n realisticBestCase: number\n realisticWorstCase: number\n}\n\nexport interface PreSwap {\n estimate: SwapEstimate\n options: OrderOption[]\n}\n\nexport interface PreRedeem {\n estimate: RedeemEstimate\n options: OrderOption[]\n}\n\nexport interface OrderEstimate {\n swap: PreSwap\n redeem: PreRedeem\n}\n\nexport interface MaxOrderEstimate {\n swap: SwapEstimate\n redeem: RedeemEstimate\n}\n\nexport interface MaxSell {\n maxSell: MaxOrderEstimate\n}\n\nexport interface MaxBuy {\n maxBuy: MaxOrderEstimate\n}\n\nexport interface TradeForm {\n host: string\n isLimit: boolean\n sell: boolean\n base: number\n quote: number\n qty: number\n rate: number\n tifnow: boolean\n options: Record\n}\n\nexport interface BookUpdate {\n action: string\n host: string\n marketID: string\n matchesSummary: RecentMatch[]\n payload: any\n}\n\nexport interface MiniOrder {\n qty: number\n qtyAtomic: number\n rate: number\n msgRate: number\n epoch: number\n sell: boolean\n token: string\n}\n\nexport interface CoreOrderBook {\n sells: MiniOrder[]\n buys: MiniOrder[]\n epoch: MiniOrder[]\n recentMatches: RecentMatch[]\n}\n\nexport interface MarketOrderBook {\n base: number\n quote: number\n book: CoreOrderBook\n}\n\nexport interface RemainderUpdate {\n token: string\n qty: number\n qtyAtomic: number\n}\n\nexport interface OrderFilterMarket {\n baseID: number\n quoteID: number\n}\n\nexport interface OrderFilter {\n n?: number\n offset?: string\n hosts?: string[]\n assets?: number[]\n market?: OrderFilterMarket\n statuses?: number[]\n}\n\nexport interface OrderPlacement {\n lots: number\n gapFactor: number\n}\n\nexport interface AutoRebalanceConfig {\n minBaseTransfer: number\n minQuoteTransfer: number\n}\n\nexport interface BasicMarketMakingConfig {\n gapStrategy: string\n sellPlacements: OrderPlacement[]\n buyPlacements: OrderPlacement[]\n driftTolerance: number\n}\n\nexport interface ArbMarketMakingPlacement {\n lots: number\n multiplier: number\n}\n\nexport interface ArbMarketMakingConfig {\n buyPlacements: ArbMarketMakingPlacement[]\n sellPlacements: ArbMarketMakingPlacement[]\n profit: number\n driftTolerance: number\n orderPersistence: number\n}\n\nexport interface SimpleArbConfig {\n profitTrigger: number\n maxActiveArbs: number\n numEpochsLeaveOpen: number\n}\n\nexport interface BotCEXCfg {\n name: string\n autoRebalance?: AutoRebalanceConfig\n}\n\nexport interface BotBalanceAllocation {\n dex: Record\n cex: Record\n}\n\nexport interface BotAssetConfig {\n swapFeeN: number\n orderReservesFactor: number\n slippageBufferFactor: number\n transferFactor: number\n}\n\nexport interface UIConfig {\n baseConfig: BotAssetConfig\n quoteConfig: BotAssetConfig\n simpleArbLots?: number\n cexRebalance: boolean\n}\n\nexport interface StartConfig extends MarketWithHost {\n autoRebalance?: AutoRebalanceConfig\n alloc: BotBalanceAllocation\n}\n\nexport interface BotConfig {\n host: string\n baseID: number\n quoteID: number\n baseWalletOptions?: Record\n quoteWalletOptions?: Record\n cexName: string\n uiConfig: UIConfig\n basicMarketMakingConfig?: BasicMarketMakingConfig\n arbMarketMakingConfig?: ArbMarketMakingConfig\n simpleArbConfig?: SimpleArbConfig\n}\n\nexport interface CEXConfig {\n name: string\n apiKey: string\n apiSecret: string\n}\n\nexport interface MarketWithHost {\n host: string\n baseID: number\n quoteID: number\n}\n\nexport interface MMCEXStatus {\n config: CEXConfig\n connected: boolean\n connectErr: string\n markets: Record\n balances: Record\n}\n\nexport interface BotBalance {\n available: number\n locked: number\n pending: number\n reserved: number\n}\n\nexport interface BotBalances {\n dex: BotBalance\n cex: BotBalance\n}\n\nexport interface BotInventory {\n avail: number\n locked: number // includes BotBalance.reserved\n total: number // avail + locked\n}\n\nexport interface RunningBotInventory {\n avail: number\n locked: number\n dex: BotInventory\n cex: BotInventory\n}\n\nexport interface CEXNotification extends CoreNote {\n cexName: string\n note: any\n}\n\nexport interface CEXBalanceUpdate {\n assetID: number\n balance: ExchangeBalance\n}\n\nexport interface EpochReportNote extends CoreNote {\n host: string\n baseID: number\n quoteID: number\n report?: EpochReport\n}\n\nexport interface CEXProblemsNote extends CoreNote {\n host: string\n baseID: number\n quoteID: number\n problems?: CEXProblems\n}\n\nexport interface FeeEstimates extends LotFeeRange {\n bookingFeesPerLot: number\n bookingFees: number\n tokenFeesPerSwap: number\n}\n\nexport interface ProjectedAlloc {\n // book is inventory dedicated either to active orders for basicmm and arbmm,\n // or on reserve for orders in the case of basicarb. book + bookingFees is the\n // starvation threshold for DEX, meaning it's impossible to start a bot\n // unstarved if there no way to get book + bookingFees to Bison Wallet. A user\n // could potentially adjust order reserves or swap fee reserves to free up\n // more funds, but with possible degradation of bot performance.\n book: number\n // booking fees is funding dedicated to covering the fees for funded orders.\n // bookingFees are in the units of the parent chain for token assets.\n bookingFees: number\n // swapFeeReserves is only required for token assets. These are fees\n // reserved for funding swaps. These fees are only debited, so will definitely\n // run out eventually, but we'll get a UI that enabled manual and/or auto\n // refill soon. swapFeeReserves are in the units of the parent chain.\n swapFeeReserves: number\n // cex is the inventory dedicated to funding counter-orders on cex for an\n // arbmm or simplearb bot. cex is the starvation threshold for CEX.\n cex: number\n // orderReserves is inventory reserved for facilitating withdraws and\n // deposits or for replacing matched orders. It's a good idea to have a\n // little extra around, otherwise a trade sequence gone wrong could put\n // the bot in a starved or unbalanced state.\n orderReserves: number\n // slippageBuffer is only required for the quote asset. This accounts for\n // variations in rate, because the quote asset's \"lot size\" varies with\n // rate. If the rate goes down, the quote-converted lot size goes up, so\n // we'll let the user choose to reserve a little extra for this case.\n slippageBuffer: number\n}\n\nexport interface FeeGapStats {\n basisPrice: number\n feeGap: number\n remoteGap: number\n roundTripFees: number\n}\n\nexport interface RunStats {\n initialBalances: Record\n dexBalances: Record\n cexBalances: Record\n profitLoss: ProfitLoss\n startTime: number\n pendingDeposits: number\n pendingWithdrawals: number\n completedMatches: number\n tradedUSD: number\n feeGap: FeeGapStats\n}\n\nexport interface StampedError {\n stamp: number\n error: string\n}\n\nexport interface BotProblems {\n walletNotSynced: Record\n noWalletPeers: Record\n accountSuspended: boolean\n userLimitTooLow: boolean\n noPriceSource: boolean\n oracleFiatMismatch: boolean\n cexOrderbookUnsynced: boolean\n causesSelfMatch: boolean\n unknownError: string\n}\n\nexport interface TradePlacement {\n rate: number\n lots: number\n standingLots: number\n orderedLots: number\n counterTradeRate: number\n requiredDex: Record\n requiredCex: number\n usedDex: Record\n usedCex: number\n error?: BotProblems\n}\n\nexport interface OrderReport {\n placements: TradePlacement[]\n fees: LotFeeRange\n availableDexBals: Record\n requiredDexBals: Record\n remainingDexBals: Record\n usedDexBals: Record\n availableCexBal: BotBalance\n requiredCexBal: number\n remainingCexBal: number\n usedCexBal: number\n error?: BotProblems\n}\n\nexport interface EpochReport {\n epochNum: number\n preOrderProblems?: BotProblems\n buysReport?: OrderReport\n sellsReport?: OrderReport\n}\n\nexport interface CEXProblems {\n depositErr: Record\n withdrawErr: Record\n tradeErr: StampedError\n}\n\nexport interface MMBotStatus {\n config: BotConfig\n running: boolean\n runStats?: RunStats\n latestEpoch?: EpochReport\n cexProblems?: CEXProblems\n}\n\nexport interface MarketMakingStatus {\n cexes: Record\n bots: MMBotStatus[]\n}\n\nexport interface DEXOrderEvent {\n id: string\n rate: number\n qty: number\n sell: boolean\n transactions: WalletTransaction[]\n}\n\nexport interface CEXOrderEvent {\n id: string\n rate: number\n qty: number\n sell: boolean\n baseFilled: number\n quoteFilled: number\n}\n\nexport interface DepositEvent {\n assetID: number\n transaction: WalletTransaction\n cexCredit: number\n}\n\nexport interface WithdrawalEvent {\n id: string\n assetID: number\n transaction: WalletTransaction\n cexDebit: number\n}\n\nexport interface BalanceEffects {\n settled: Record\n pending: Record\n locked: Record\n reserved: Record\n}\n\nexport interface MarketMakingEvent {\n id: number\n timestamp: number\n balanceEffects: BalanceEffects\n pending: boolean\n dexOrderEvent?: DEXOrderEvent\n cexOrderEvent?: CEXOrderEvent\n depositEvent?: DepositEvent\n withdrawalEvent?: WithdrawalEvent\n}\n\ninterface MarketDay {\n vol: number\n quoteVol: number\n priceChange: number\n priceChangePct: number\n avgPrice: number\n lastPrice: number\n openPrice: number\n highPrice: number\n lowPrice: number\n}\n\nexport interface CEXMarket {\n baseID: number\n quoteID: number\n baseMinWithdraw: number\n quoteMinWithdraw: number\n day: MarketDay\n}\n\nexport interface OracleReport {\n host: string\n usdVol: number\n bestBuy: number\n bestSell: number\n}\n\nexport interface ExchangeBalance {\n available: number\n locked: number\n}\n\n// changing the order of the elements in this enum will affect\n// the sorting of the peers table in wallets.ts.\nexport enum PeerSource {\n WalletDefault,\n UserAdded,\n Discovered,\n}\n\nexport interface BalanceState {\n fiatRates: Record\n balances: Record\n invMods: Record\n}\n\nexport interface Amount {\n atoms: number\n conventional: number\n fmt: string\n usd: number\n fmtUSD: string\n}\n\nexport interface ProfitLoss {\n initial: Record\n initialUSD: number\n mods: Record\n modsUSD: number\n final: Record\n finalUSD: number\n diffs: Record\n profit: number\n profitRatio: number\n}\n\nexport interface StampedBotConfig {\n timestamp: number\n cfg: BotConfig\n}\n\nexport interface MarketMakingRunOverview {\n endTime: number\n cfgs: StampedBotConfig[]\n initialBalances: Record\n profitLoss: ProfitLoss\n finalState: BalanceState\n}\n\nexport interface WalletPeer {\n addr: string\n source: PeerSource\n connected: boolean\n}\n\nexport interface TicketTransaction {\n hash: string\n ticketPrice: number\n fees: number\n stamp: number\n blockHeight: number\n}\n\nexport interface Ticket {\n tx: TicketTransaction\n status: number\n spender: string\n}\n\nexport interface TBChoice {\n id: string\n description: string\n}\n\nexport interface TBAgenda {\n id: string\n description: string\n currentChoice: string\n choices: TBChoice[]\n}\n\nexport interface TKeyPolicyResult {\n key: string\n policy: string\n ticket?: string\n}\n\nexport interface TBTreasurySpend {\n hash: string\n value: number\n currentPolicy: string\n}\n\nexport interface Stances {\n agendas: TBAgenda[]\n tspends: TBTreasurySpend[]\n treasuryKeys: TKeyPolicyResult[]\n}\n\nexport interface TicketStats {\n totalRewards: number\n ticketCount: number\n votes: number\n revokes: number\n mempool: number\n queued: number\n}\n\nexport interface TicketStakingStatus {\n ticketPrice: number\n votingSubsidy: number\n vsp: string\n isRPC: boolean\n tickets: Ticket[]\n stances: Stances\n stats: TicketStats\n}\n\n// VotingServiceProvider is information about a voting service provider.\nexport interface VotingServiceProvider {\n url: string\n network: number\n launched: number\n lastUpdated: number\n apiVersions: number[]\n feePercentage: number\n closed: boolean\n voting: number\n voted: number\n revoked: number\n vspdVersion: string\n blockHeight: number\n netShare: number\n}\n\nexport interface BondTxInfo {\n bondID: string\n lockTime: number\n accountID: string\n}\n\nexport interface WalletTransaction {\n type: number\n id: string\n amount: number\n fees: number\n timestamp: number\n blockNumber: number\n tokenID?: number\n recipient?: string\n bondInfo?: BondTxInfo\n additionalData: Record\n}\n\nexport interface TxHistoryResult {\n txs : WalletTransaction[]\n lastTx: boolean\n}\n\nexport const PrepaidBondID = 2147483647\n\nexport interface Application {\n assets: Record\n seedGenTime: number\n user: User\n mmStatus: MarketMakingStatus\n header: HTMLElement\n headerSpace: HTMLElement\n walletMap: Record\n exchanges: Record\n fiatRatesMap: Record\n showPopups: boolean\n commitHash: string\n authed: boolean\n start (): Promise\n reconnected (): void\n fetchUser (): Promise\n fetchMMStatus (): Promise\n loadPage (page: string, data?: any, skipPush?: boolean): Promise\n attach (data: any): void\n bindTooltips (ancestor: HTMLElement): void\n bindUrlHandlers (ancestor: HTMLElement): void\n attachHeader (): void\n updateMarketElements (ancestor: PageElement, baseID: number, quoteID: number, xc?: Exchange): void\n showDropdown (icon: HTMLElement, dialog: HTMLElement): void\n ackNotes (): void\n setNoteTimes (noteList: HTMLElement): void\n bindInternalNavigation (ancestor: HTMLElement): void\n updateMenuItemsDisplay (): void\n attachCommon (node: HTMLElement): void\n updateBondConfs (dexAddr: string, coinID: string, confs: number, assetID: number): void\n handleBondNote (note: BondNote): void\n loggedIn (notes: CoreNote[], pokes: CoreNote[]): void\n setPokes(pokes: CoreNote[]): void\n botStatus (host: string, baseID: number, quoteID: number): MMBotStatus | undefined\n notify (note: CoreNote): void\n log (loggerID: string, ...msg: any): void\n prependPokeElement (note: CoreNote): void\n prependNoteElement (note: CoreNote, skipSave?: boolean): void\n prependListElement (noteList: HTMLElement, note: CoreNote, el: NoteElement): void\n loading (el: HTMLElement): () => void\n orders (host: string, mktID: string): Order[]\n haveActiveOrders (assetID: number): boolean\n order (oid: string): Order | null\n canAccelerateOrder(order: Order): boolean\n unitInfo (assetID: number, xc?: Exchange): UnitInfo\n baseChainSymbol (assetID: number): string\n extensionWallet (assetID: number): ExtensionConfiguredWallet | undefined\n conventionalRate (baseID: number, quoteID: number, encRate: number, xc?: Exchange): number\n walletDefinition (assetID: number, walletType: string): WalletDefinition\n currentWalletDefinition (assetID: number): WalletDefinition\n fetchBalance (assetID: number): Promise\n checkResponse (resp: APIResponse): boolean\n signOut (): Promise\n registerNoteFeeder (receivers: Record void>): void\n txHistory(assetID: number, n: number, after?: string): Promise\n getWalletTx(assetID: number, txid: string): WalletTransaction | undefined\n clearTxHistory(assetID: number): void\n parentAsset(assetID: number): SupportedAsset\n needsCustomProvider (assetID: number): Promise\n}\n\n// TODO: Define an interface for Application?\nlet application: Application\n\nexport function registerApplication (a: Application) {\n application = a\n}\n\nexport function app (): Application {\n return application\n}\n","import Doc from './doc'\nimport {\n PageElement,\n XYRange,\n OrderOption\n} from './registry'\n\ninterface OptionsReporters {\n enable: () => void\n disable: () => void\n}\n\n// Having the caller set these vars on load using an exported function makes\n// life easier.\nlet orderOptTmpl: HTMLElement, booleanOptTmpl: HTMLElement, rangeOptTmpl: HTMLElement\n\n// setOptionTemplates sets the package vars for the templates and application.\nexport function setOptionTemplates (page: Record): void {\n [booleanOptTmpl, rangeOptTmpl, orderOptTmpl] = [page.booleanOptTmpl, page.rangeOptTmpl, page.orderOptTmpl]\n}\n\nconst threeSigFigs = new Intl.NumberFormat(Doc.languages(), {\n minimumSignificantDigits: 3,\n maximumSignificantDigits: 3\n})\n\n/*\n * Option is a base class for option elements. Option stores some common\n * parameters and monitors the toggle switch, calling the child class's\n * enable/disable methods when the user manually turns the option on or off.\n */\nexport class Option {\n opt: OrderOption\n node: HTMLElement\n tmpl: Record\n on: boolean\n\n constructor (opt: OrderOption, symbol: string, report: OptionsReporters) {\n this.opt = opt\n const node = this.node = orderOptTmpl.cloneNode(true) as HTMLElement\n const tmpl = this.tmpl = Doc.parseTemplate(node)\n\n tmpl.optName.textContent = opt.displayname\n tmpl.tooltip.dataset.tooltip = opt.description\n\n // const isBaseChain = (isSwapOption && order.sell) || (!isSwapOption && !order.sell)\n // const symbol = isBaseChain ? this.baseSymbol() : this.quoteSymbol()\n if (symbol) tmpl.chainIcon.src = Doc.logoPath(symbol)\n else Doc.hide(tmpl.chainIcon)\n\n this.on = false\n Doc.bind(node, 'click', () => {\n if (this.on) return\n this.on = true\n node.classList.add('selected')\n report.enable()\n })\n Doc.bind(tmpl.toggle, 'click', e => {\n if (!this.on) return\n e.stopPropagation()\n this.on = false\n node.classList.remove('selected')\n report.disable()\n })\n }\n}\n\n/*\n * BooleanOption is a simple on/off option with a short summary of it's effects.\n * BooleanOrderOption is the handler for a *BooleanConfig from client/asset.\n */\nexport class BooleanOption extends Option {\n control: HTMLElement\n changed: () => void\n dict: Record\n\n constructor (opt: OrderOption, symbol: string, dict: Record, changed: () => void) {\n super(opt, symbol, {\n enable: () => this.enable(),\n disable: () => this.disable()\n })\n this.dict = dict\n this.changed = () => changed()\n if (opt.boolean === undefined) throw Error('not a boolean opt')\n const cfg = opt.boolean\n const control = this.control = booleanOptTmpl.cloneNode(true) as HTMLElement\n // Append to parent's options div.\n this.tmpl.controls.appendChild(control)\n const tmpl = Doc.parseTemplate(control)\n tmpl.reason.textContent = cfg.reason\n this.on = typeof dict[opt.key] !== 'undefined' ? dict[opt.key] : opt.default\n if (this.on) this.node.classList.add('selected')\n }\n\n store (): void {\n if (this.on === this.opt.default) delete this.dict[this.opt.key]\n else this.dict[this.opt.key] = this.on\n this.changed()\n }\n\n enable (): void {\n this.store()\n }\n\n disable (): void {\n this.store()\n }\n}\n\n/*\n * XYRangeOption is an order option that contains an XYRangeHandler. The logic\n * for handling the slider to is defined in XYRangeHandler so that the slider\n * can be used without being contained in an order option.\n */\nexport class XYRangeOption extends Option {\n handler: XYRangeHandler\n x: number\n changed: () => void\n dict: Record\n\n constructor (opt: OrderOption, symbol: string, dict: Record, changed: () => void) {\n super(opt, symbol, {\n enable: () => this.enable(),\n disable: () => this.disable()\n })\n this.dict = dict\n this.changed = changed\n if (opt.xyRange === undefined) throw Error('not an xy range opt')\n const cfg = opt.xyRange\n const setVal = dict[opt.key]\n this.on = typeof setVal !== 'undefined'\n if (this.on) {\n this.node.classList.add('selected')\n this.x = setVal\n } else {\n this.x = opt.default\n }\n const selected = () => { this.node.classList.add('selected') }\n this.handler = new XYRangeHandler(cfg, this.x, { changed, selected, settingsDict: dict, settingsKey: opt.key })\n this.tmpl.controls.appendChild(this.handler.control)\n }\n\n enable (): void {\n this.dict[this.opt.key] = this.x\n this.changed()\n }\n\n disable (): void {\n delete this.dict[this.opt.key]\n this.changed()\n }\n\n setValue (x: number): void {\n this.handler.setValue(x)\n this.on = true\n this.node.classList.add('selected')\n }\n}\n\ninterface AcceptOpts {\n skipChange?: boolean\n skipUpdate?: boolean // Implies skipChange\n}\n\ninterface RangeHandlerOpts {\n roundY?: boolean\n roundX?: boolean\n updated?: (x:number, y:number) => void, // fires while dragging.\n changed?: () => void, // does not fire while dragging but does when dragging ends.\n selected?: () => void,\n disabled?: boolean\n settingsDict?: {[key: string]: any}\n settingsKey?: string\n convert?: (x: number, y: number) => any\n}\n\n/*\n * XYRangeHandler is the handler for an *XYRange from client/asset. XYRange\n * has a slider which allows adjusting the x and y, linearly between two limits.\n * The user can also manually enter values for x or y.\n */\nexport class XYRangeHandler {\n control: HTMLElement\n range: XYRange\n tmpl: Record\n initVal: number\n settingsDict?: {[key: string]: any}\n settingsKey: string\n x: number\n scrollingX: number\n y: number\n r: number\n roundX: boolean\n roundY: boolean\n disabled: boolean\n updated: (x:number, y:number) => void // called while dragging\n changed: () => void // not called while dragging, but called when done dragging\n selected: () => void\n convert: (x: number, y: number) => any\n\n constructor (\n range: XYRange,\n initVal: number,\n opts: RangeHandlerOpts\n ) {\n const control = this.control = rangeOptTmpl.cloneNode(true) as HTMLElement\n const tmpl = this.tmpl = Doc.parseTemplate(control)\n tmpl.rangeLblStart.textContent = range.start.label\n tmpl.rangeLblEnd.textContent = range.end.label\n tmpl.xUnit.textContent = range.xUnit\n tmpl.yUnit.textContent = range.yUnit\n this.range = range\n this.initVal = initVal\n this.settingsDict = opts.settingsDict\n this.settingsKey = opts.settingsKey ?? ''\n this.roundX = Boolean(opts.roundX)\n this.roundY = Boolean(opts.roundY)\n\n this.setDisabled(Boolean(opts.disabled))\n this.changed = opts.changed ?? (() => { /* pass */ })\n this.selected = opts.selected ?? (() => { /* pass */ })\n this.updated = opts.updated ?? (() => { /* pass */ })\n this.convert = opts.convert || ((x: number) => x)\n\n const { slider, handle } = tmpl\n const rangeX = range.end.x - range.start.x\n const rangeY = range.end.y - range.start.y\n const normalizeX = (x: number) => (x - range.start.x) / rangeX\n\n // r, x, and y will be updated by the various input event handlers. r is\n // x (or y) normalized on its range, e.g. [x_min, x_max] -> [0, 1]\n this.r = normalizeX(initVal)\n this.scrollingX = this.x = initVal\n this.y = this.r * rangeY + range.start.y\n this.accept(this.scrollingX, { skipUpdate: true })\n\n // Set up the handlers for the x and y text input fields.\n const clickOutX = (e: MouseEvent) => {\n if (this.disabled) return\n if (e.type !== 'change' && e.target === tmpl.xInput) return\n const s = tmpl.xInput.value\n if (s) {\n const xx = parseFloat(s)\n if (!isNaN(xx)) {\n this.scrollingX = clamp(xx, range.start.x, range.end.x)\n this.r = normalizeX(this.scrollingX)\n this.y = this.r * rangeY + range.start.y\n this.accept(this.scrollingX)\n }\n }\n Doc.hide(tmpl.xInput)\n Doc.show(tmpl.x)\n Doc.unbind(document, 'click', clickOutX)\n this.changed()\n }\n\n Doc.bind(tmpl.x, 'click', e => {\n if (this.disabled) return\n Doc.hide(tmpl.x)\n Doc.show(tmpl.xInput)\n tmpl.xInput.focus()\n tmpl.xInput.value = threeSigFigs.format(this.scrollingX)\n Doc.bind(document, 'click', clickOutX)\n e.stopPropagation()\n })\n\n Doc.bind(tmpl.xInput, 'change', clickOutX)\n\n const clickOutY = (e: MouseEvent) => {\n if (this.disabled) return\n if (e.type !== 'change' && e.target === tmpl.yInput) return\n const s = tmpl.yInput.value\n if (s) {\n const yy = parseFloat(s)\n if (!isNaN(yy)) {\n this.y = clamp(yy, range.start.y, range.end.y)\n this.r = (this.y - range.start.y) / rangeY\n this.scrollingX = range.start.x + this.r * rangeX\n this.accept(this.scrollingX)\n }\n }\n Doc.hide(tmpl.yInput)\n Doc.show(tmpl.y)\n Doc.unbind(document, 'click', clickOutY)\n this.changed()\n }\n\n Doc.bind(tmpl.y, 'click', e => {\n if (this.disabled) return\n Doc.hide(tmpl.y)\n Doc.show(tmpl.yInput)\n tmpl.yInput.focus()\n tmpl.yInput.value = threeSigFigs.format(this.y)\n Doc.bind(document, 'click', clickOutY)\n e.stopPropagation()\n })\n\n Doc.bind(tmpl.yInput, 'change', clickOutY)\n\n // Read the slider.\n Doc.bind(handle, 'mousedown', (e: MouseEvent) => {\n if (this.disabled) return\n if (e.button !== 0) return\n e.preventDefault()\n e.stopPropagation()\n this.selected()\n const startX = e.pageX\n const w = slider.clientWidth - handle.offsetWidth\n const startLeft = normalizeX(this.scrollingX) * w\n const left = (ee: MouseEvent) => Math.max(Math.min(startLeft + (ee.pageX - startX), w), 0)\n const trackMouse = (ee: MouseEvent, emit?: boolean) => {\n ee.preventDefault()\n this.r = left(ee) / w\n this.scrollingX = this.r * rangeX + range.start.x\n this.y = this.r * rangeY + range.start.y\n this.accept(this.scrollingX, { skipChange: !emit })\n }\n const mouseUp = (ee: MouseEvent) => {\n trackMouse(ee, true)\n Doc.unbind(document, 'mousemove', trackMouse)\n Doc.unbind(document, 'mouseup', mouseUp)\n this.changed()\n }\n Doc.bind(document, 'mousemove', trackMouse)\n Doc.bind(document, 'mouseup', mouseUp)\n })\n\n Doc.bind(tmpl.sliderBox, 'click', (e: MouseEvent) => {\n if (this.disabled) return\n if (e.button !== 0) return\n const x = e.pageX\n const m = Doc.layoutMetrics(tmpl.slider)\n this.r = clamp((x - m.bodyLeft) / m.width, 0, 1)\n this.scrollingX = this.r * rangeX + range.start.x\n this.y = this.r * rangeY + range.start.y\n this.accept(this.scrollingX)\n })\n }\n\n setDisabled (disabled: boolean) {\n this.control.classList.toggle('disabled', disabled)\n this.disabled = disabled\n }\n\n setXLabel (s: string) {\n this.tmpl.x.textContent = s\n }\n\n setYLabel (s: string) {\n this.tmpl.y.textContent = s\n }\n\n accept (x: number, cfg?: AcceptOpts): void {\n const tmpl = this.tmpl\n if (this.roundX) x = Math.round(x)\n if (this.roundY) this.y = Math.round(this.y)\n tmpl.x.textContent = threeSigFigs.format(x)\n tmpl.y.textContent = threeSigFigs.format(this.y)\n if (this.roundY) tmpl.y.textContent = `${this.y}`\n const rEffective = clamp(this.r, 0, 1)\n tmpl.handle.style.left = `calc(${rEffective * 100}% - ${rEffective * 14}px)`\n this.x = x\n this.scrollingX = x\n cfg = cfg ?? {}\n if (this.settingsDict) this.settingsDict[this.settingsKey] = this.convert(this.x, this.y)\n if (!cfg.skipUpdate) {\n this.updated(x, this.y)\n if (!cfg.skipChange) this.changed()\n }\n }\n\n setValue (x: number, skipUpdate?: boolean) {\n const range = this.range\n this.r = (x - range.start.x) / (range.end.x - range.start.x)\n this.y = range.start.y + this.r * (range.end.y - range.start.y)\n this.accept(x, { skipUpdate })\n }\n\n modified (): boolean {\n return this.x !== this.initVal\n }\n\n reset () {\n this.setValue(this.initVal, true)\n }\n}\n\nconst clamp = (v: number, min: number, max: number): number => v < min ? min : v > max ? max : v\n","export default class BasePage {\n /* unload is called when the user navigates away from the page. */\n unload () {\n // should be implemented by inheriting class.\n }\n}\n","import * as intl from './locales'\nimport {\n app,\n Order,\n TradeForm,\n OrderOption,\n Match\n} from './registry'\nimport { BooleanOption, XYRangeOption } from './opts'\nimport Doc from './doc'\n\nexport const Limit = 1 // TODO: Delete for the versions below\nexport const Market = 2 // TODO: Delete for the versions below\nexport const Cancel = 3 // TODO: Delete for the versions below\n\nexport const OrderTypeLimit = 1\nexport const OrderTypeMarket = 2\nexport const OrderTypeCancel = 3\n\n/* The time-in-force specifiers are a mirror of dex/order.TimeInForce. */\nexport const ImmediateTiF = 0\nexport const StandingTiF = 1\n\n/* The order statuses are a mirror of dex/order.OrderStatus. */\nexport const StatusUnknown = 0\nexport const StatusEpoch = 1\nexport const StatusBooked = 2\nexport const StatusExecuted = 3\nexport const StatusCanceled = 4\nexport const StatusRevoked = 5\n\n/* The match statuses are a mirror of dex/order.MatchStatus. */\nexport const NewlyMatched = 0\nexport const MakerSwapCast = 1\nexport const TakerSwapCast = 2\nexport const MakerRedeemed = 3\nexport const MatchComplete = 4\nexport const MatchConfirmed = 5\n\n/* The match sides are a mirror of dex/order.MatchSide. */\nexport const Maker = 0 // TODO: Delete for the versions below\nexport const Taker = 1 // TODO: Delete for the versions below\n\nexport const MatchSideMaker = 0\nexport const MatchSideTaker = 1\n\n/*\n * RateEncodingFactor is used when encoding an atomic exchange rate as an\n * integer. See docs on message-rate encoding @\n * https://github.com/decred/dcrdex/blob/master/spec/comm.mediawiki#Rate_Encoding\n */\nexport const RateEncodingFactor = 1e8\n\nexport function sellString (ord: Order) {\n const key = ord.sell ? intl.ID_SELL : intl.ID_BUY\n const lang = document.documentElement.lang.toLowerCase()\n return intl.prep(key).toLocaleLowerCase(lang)\n}\n\nexport function typeString (ord: Order) {\n return ord.type === Limit ? (ord.tif === ImmediateTiF ? intl.prep(intl.ID_LIMIT_ORDER_IMMEDIATE_TIF) : intl.prep(intl.ID_LIMIT_ORDER)) : intl.prep(intl.ID_MARKET_ORDER)\n}\n\n/* isMarketBuy will return true if the order is a market buy order. */\nexport function isMarketBuy (ord: Order) {\n return ord.type === Market && !ord.sell\n}\n\n/*\n * hasActiveMatches returns true if the order has matches that have not completed\n * settlement yet.\n */\nexport function hasActiveMatches (order: Order) {\n if (!order.matches) return false\n for (const match of order.matches) {\n if (match.active) return true\n }\n return false\n}\n\n/**\n * statusString converts the order status to a string.\n *\n * IMPORTANT: we have similar function in Golang, it must match this one exactly,\n * when updating make sure to update both!\n */\nexport function statusString (order: Order): string {\n if (!order.id) return intl.prep(intl.ID_ORDER_SUBMITTING) // order ID is empty.\n const isLive = hasActiveMatches(order)\n switch (order.status) {\n case StatusUnknown: return intl.prep(intl.ID_UNKNOWN)\n case StatusEpoch: return intl.prep(intl.ID_EPOCH)\n case StatusBooked:\n if (order.cancelling) return intl.prep(intl.ID_CANCELING)\n return isLive ? `${intl.prep(intl.ID_BOOKED)}/${intl.prep(intl.ID_SETTLING)}` : intl.prep(intl.ID_BOOKED)\n case StatusExecuted:\n if (isLive) return intl.prep(intl.ID_SETTLING)\n if (order.filled === 0 && order.type !== Cancel) return intl.prep(intl.ID_NO_MATCH)\n return intl.prep(intl.ID_EXECUTED)\n case StatusCanceled:\n return isLive ? `${intl.prep(intl.ID_CANCELED)}/${intl.prep(intl.ID_SETTLING)}` : intl.prep(intl.ID_CANCELED)\n case StatusRevoked:\n return isLive ? `${intl.prep(intl.ID_REVOKED)}/${intl.prep(intl.ID_SETTLING)}` : intl.prep(intl.ID_REVOKED)\n }\n return intl.prep(intl.ID_UNKNOWN)\n}\n\n/* filled sums the quantities of non-cancel matches available. */\nexport function filled (order: Order) {\n if (!order.matches) return 0\n const qty = isMarketBuy(order) ? (m: Match) => m.qty * m.rate / RateEncodingFactor : (m: Match) => m.qty\n return order.matches.reduce((filled, match) => {\n if (match.isCancel) return filled\n return filled + qty(match)\n }, 0)\n}\n\n/* settled sums the quantities of the matches that have completed. */\nexport function settled (order: Order) {\n if (!order.matches) return 0\n const qty = isMarketBuy(order) ? (m: Match) => m.qty * m.rate / RateEncodingFactor : (m: Match) => m.qty\n return order.matches.reduce((settled, match) => {\n if (match.isCancel) return settled\n const redeemed = (match.side === Maker && match.status >= MakerRedeemed) ||\n (match.side === Taker && match.status >= MatchComplete)\n return redeemed ? settled + qty(match) : settled\n }, 0)\n}\n\n/* averageRateString returns a formatting string containing the average rate of\nthe matches that have been filled for a market order. */\nexport function averageMarketOrderRateString (ord: Order): string {\n if (!ord.matches?.length) return intl.prep(intl.ID_MARKET_ORDER)\n let rateStr = Doc.formatCoinValue(app().conventionalRate(ord.baseID, ord.quoteID, averageRate(ord)))\n if (ord.matches.length > 1) rateStr = '~ ' + rateStr // \"~\" only makes sense if the order has more than one match.\n return rateStr\n}\n\n/* averageRate returns a the average rate of the matches that have been filled\nin an order. */\nexport function averageRate (ord: Order): number {\n if (!ord.matches?.length) return 0\n let rateProduct = 0\n let baseQty = 0\n for (const m of ord.matches) {\n baseQty += m.qty\n rateProduct += (m.rate * m.qty) // order ~ 1e16\n }\n return rateProduct / baseQty\n}\n\n/* baseToQuote returns the quantity of the quote asset. */\nexport function baseToQuote (rate: number, base: number) : number {\n return rate * base / RateEncodingFactor\n}\n\n/* orderPortion returns a string stating the percentage of the order a match\n makes up. */\nexport function orderPortion (order: Order, match: Match) : string {\n let matchQty = match.qty\n if (isMarketBuy(order)) {\n matchQty = baseToQuote(match.rate, match.qty)\n }\n return ((matchQty / order.qty) * 100).toFixed(1) + ' %'\n}\n\n/*\n * matchStatusString is a string used to create a displayable string describing\n * describing the match status.\n */\nexport function matchStatusString (m: Match) {\n if (m.revoked) {\n // When revoked, match status is less important than pending action if still\n // active, or the outcome if inactive.\n if (m.active) {\n if (m.redeem) return revokedMatchStatus(intl.ID_MATCH_STATUS_REDEMPTION_SENT) // must require confirmation if active\n // If maker and we have not redeemed, waiting to refund, assuming it's not\n // revoked while waiting for confs on an unspent/unexpired taker swap.\n if (m.side === Maker) return revokedMatchStatus(intl.ID_MATCH_STATUS_REFUND_PENDING)\n // As taker, resolution depends on maker's actions while waiting to refund.\n if (m.counterRedeem) return revokedMatchStatus(intl.ID_MATCH_STATUS_REDEEM_PENDING) // this should be very brief if we see the maker's redeem\n return revokedMatchStatus(intl.ID_MATCH_STATUS_REFUND_PENDING) // may switch to redeem if maker redeems on the sly\n }\n if (m.refund) {\n return revokedMatchStatus(intl.ID_MATCH_STATUS_REFUNDED)\n }\n if (m.redeem) {\n return revokedMatchStatus(intl.ID_MATCH_STATUS_REDEMPTION_CONFIRMED)\n }\n return revokedMatchStatus(intl.ID_MATCH_STATUS_COMPLETE) // i.e. we sent no swap\n }\n\n switch (m.status) {\n case NewlyMatched:\n return intl.prep(intl.ID_MATCH_STATUS_NEWLY_MATCHED)\n case MakerSwapCast:\n return intl.prep(intl.ID_MATCH_STATUS_MAKER_SWAP_CAST)\n case TakerSwapCast:\n return intl.prep(intl.ID_MATCH_STATUS_TAKER_SWAP_CAST)\n case MakerRedeemed:\n if (m.side === Maker) {\n return intl.prep(intl.ID_MATCH_STATUS_REDEMPTION_SENT)\n }\n return intl.prep(intl.ID_MATCH_STATUS_MAKER_REDEEMED)\n case MatchComplete:\n return intl.prep(intl.ID_MATCH_STATUS_REDEMPTION_SENT)\n case MatchConfirmed:\n return intl.prep(intl.ID_MATCH_STATUS_REDEMPTION_CONFIRMED)\n }\n return intl.prep(intl.ID_UNKNOWN)\n}\n\n// revokedMatchStatus is a helper function that returns the revoked match status\n// string.\nfunction revokedMatchStatus (matchStatus: string): string {\n return intl.prep(intl.ID_MATCH_STATUS_REVOKED, { status: intl.prep(matchStatus) })\n}\n\n/*\n * optionElement is a getter for an element matching the *OrderOption from\n * client/asset. change is a function with no arguments that is called when the\n * returned option's value has changed.\n */\nexport function optionElement (opt: OrderOption, order: TradeForm, change: () => void, isSwap: boolean): HTMLElement {\n const isBaseChain = (isSwap && order.sell) || (!isSwap && !order.sell)\n const symbol = isBaseChain ? dexAssetSymbol(order.host, order.base) : dexAssetSymbol(order.host, order.quote)\n\n switch (true) {\n case !!opt.boolean:\n return new BooleanOption(opt, symbol, order.options, change).node\n case !!opt.xyRange:\n return new XYRangeOption(opt, symbol, order.options, change).node\n default:\n console.error('no option type specified', opt)\n }\n console.error('unknown option type', opt)\n return document.createElement('div')\n}\n\nfunction dexAssetSymbol (host: string, assetID: number): string {\n return app().exchanges[host].assets[assetID].symbol\n}\n\nexport function isCancellable (ord: Order): boolean {\n return ord.type === Limit && ord.tif === StandingTiF && ord.status < StatusExecuted\n}\n\nexport function orderTypeText (ordType: number): string {\n switch (ordType) {\n case OrderTypeLimit:\n return intl.prep(intl.ID_LIMIT_ORDER)\n case OrderTypeMarket:\n return intl.prep(intl.ID_MARKET_ORDER)\n default: // OrderTypeCancel\n return intl.prep(intl.ID_CANCEL_ORDER)\n }\n}\n","import Doc, { Animation, clamp } from './doc'\nimport { RateEncodingFactor } from './orderutil'\nimport OrderBook from './orderbook'\nimport State from './state'\nimport { UnitInfo, Market, Candle, CandlesPayload, app } from './registry'\n\nconst bind = Doc.bind\nconst PIPI = 2 * Math.PI\nconst plusChar = String.fromCharCode(59914)\nconst minusChar = String.fromCharCode(59915)\n\ninterface Point {\n x: number\n y: number\n}\n\ninterface MinMax {\n min: number\n max: number\n}\n\ninterface Label {\n val: number\n txt: string\n}\n\ninterface LabelSet {\n widest?: number\n lbls: Label[]\n}\n\nexport interface Translator {\n x: (x: number) => number\n y: (y: number) => number\n unx: (x: number) => number\n uny: (y: number) => number\n w: (w: number) => number\n h: (h: number) => number\n}\n\nexport interface MouseReport {\n rate: number\n depth: number\n dotColor: string\n hoverMarkers: number[]\n}\n\nexport interface VolumeReport {\n buyBase: number\n buyQuote: number\n sellBase: number\n sellQuote: number\n}\n\nexport interface DepthReporters {\n mouse: (r: MouseReport | null) => void\n click: (x: number) => void\n volume: (r: VolumeReport) => void\n zoom: (z: number) => void\n}\n\nexport interface CandleReporters {\n mouse: (r: Candle | null) => void\n}\n\nexport interface ChartReporters {\n resize: () => void,\n click: (e: MouseEvent) => void,\n zoom: (bigger: boolean) => void\n}\n\nexport interface DepthLine {\n rate: number\n color: string\n}\n\nexport interface DepthMarker {\n rate: number\n active: boolean\n}\n\ninterface DepthMark extends DepthMarker {\n qty: number\n sell: boolean\n}\n\ninterface Theme {\n body: string\n axisLabel: string\n gridBorder: string\n gridLines: string\n gapLine: string\n value: string\n zoom: string\n zoomHover: string\n sellLine: string\n buyLine: string\n sellFill: string\n buyFill: string\n crosshairs: string\n legendFill: string\n legendText: string\n}\n\nconst darkTheme: Theme = {\n body: '#0b2031',\n axisLabel: '#b1b1b1',\n gridBorder: '#383f4b',\n gridLines: '#383f4b',\n gapLine: '#6b6b6b',\n value: '#9a9a9a',\n zoom: '#5b5b5b',\n zoomHover: '#aaa',\n sellLine: '#ae3333',\n buyLine: '#05a35a',\n sellFill: '#591a1a',\n buyFill: '#02572f',\n crosshairs: '#888',\n legendFill: 'black',\n legendText: '#d5d5d5'\n}\n\nconst lightTheme: Theme = {\n body: '#f4f4f4',\n axisLabel: '#1b1b1b',\n gridBorder: '#ddd',\n gridLines: '#ddd',\n gapLine: '#595959',\n value: '#4d4d4d',\n zoom: '#777',\n zoomHover: '#333',\n sellLine: '#99302b',\n buyLine: '#207a46',\n sellFill: '#bd5959',\n buyFill: '#4cad75',\n crosshairs: '#595959',\n legendFill: '#e6e6e6',\n legendText: '#1b1b1b'\n}\n\n// Chart is the base class for charts.\nexport class Chart {\n parent: HTMLElement\n report: ChartReporters\n theme: Theme\n canvas: HTMLCanvasElement\n visible: boolean\n renderScheduled: boolean\n ctx: CanvasRenderingContext2D\n mousePos: Point | null\n rect: DOMRect\n wheelLimiter: number | null\n boundResizer: () => void\n plotRegion: Region\n xRegion: Region\n yRegion: Region\n dataExtents: Extents\n unattachers: (() => void)[]\n\n constructor (parent: HTMLElement, reporters: ChartReporters) {\n this.parent = parent\n this.report = reporters\n this.theme = State.isDark() ? darkTheme : lightTheme\n this.canvas = document.createElement('canvas')\n this.visible = true\n parent.appendChild(this.canvas)\n const ctx = this.canvas.getContext('2d')\n if (!ctx) {\n console.error('error getting canvas context')\n return\n }\n this.ctx = ctx\n this.ctx.textAlign = 'center'\n this.ctx.textBaseline = 'middle'\n // Mouse handling\n this.mousePos = null\n bind(this.canvas, 'mousemove', (e: MouseEvent) => {\n // this.rect will be set in resize().\n if (!this.rect) return\n this.mousePos = {\n x: e.clientX - this.rect.left,\n y: e.clientY - this.rect.y\n }\n this.draw()\n })\n bind(this.canvas, 'mouseleave', () => {\n this.mousePos = null\n this.draw()\n })\n\n // Bind resize.\n const resizeObserver = new ResizeObserver(() => this.resize())\n resizeObserver.observe(this.parent)\n\n // Scrolling by wheel is smoother when the rate is slightly limited.\n this.wheelLimiter = null\n bind(this.canvas, 'wheel', (e: WheelEvent) => { this.wheel(e) }, { passive: true })\n bind(this.canvas, 'click', (e: MouseEvent) => { this.click(e) })\n const setVis = () => {\n this.visible = document.visibilityState !== 'hidden'\n if (this.visible && this.renderScheduled) {\n this.renderScheduled = false\n this.draw()\n }\n }\n bind(document, 'visibilitychange', setVis)\n this.unattachers = [() => { Doc.unbind(document, 'visibilitychange', setVis) }]\n }\n\n wheeled () {\n this.wheelLimiter = window.setTimeout(() => { this.wheelLimiter = null }, 100)\n }\n\n /* clear the canvas. */\n clear () {\n this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)\n }\n\n /* draw calls the child class's render method. */\n draw () {\n this.render()\n }\n\n /* click is the handler for a click event on the canvas. */\n click (e: MouseEvent) {\n this.report.click(e)\n }\n\n /* wheel is a mousewheel event handler. */\n wheel (e: WheelEvent) {\n this.zoom(e.deltaY < 0)\n }\n\n /*\n * resize updates the chart size. The parentHeight is an argument to support\n * updating the height programmatically after the caller sets a style.height\n * but before the clientHeight has been updated.\n */\n resize () {\n this.canvas.width = this.parent.clientWidth\n this.canvas.height = this.parent.clientHeight\n const xLblHeight = 30\n const yGuess = 40 // y label width guess. Will be adjusted when drawn.\n const plotExtents = new Extents(0, this.canvas.width, 0, this.canvas.height - xLblHeight)\n const xLblExtents = new Extents(0, this.canvas.width, this.canvas.height - xLblHeight, this.canvas.height)\n const yLblExtents = new Extents(0, yGuess, 0, this.canvas.height - xLblHeight)\n this.plotRegion = new Region(this.ctx, plotExtents)\n this.xRegion = new Region(this.ctx, xLblExtents)\n this.yRegion = new Region(this.ctx, yLblExtents)\n // After changing the visibility, this.canvas.getBoundingClientRect will\n // return nonsense until a render.\n window.requestAnimationFrame(() => {\n this.rect = this.canvas.getBoundingClientRect()\n this.report.resize()\n })\n }\n\n /* zoom is called when the user scrolls the mouse wheel on the canvas. */\n zoom (bigger: boolean) {\n if (this.wheelLimiter) return\n this.report.zoom(bigger)\n }\n\n /* The market handler will call unattach when the markets page is unloaded. */\n unattach () {\n for (const u of this.unattachers) u()\n this.unattachers = []\n }\n\n /* render must be implemented by the child class. */\n render () {\n console.error('child class must override render method')\n }\n\n /* applyLabelStyle applies the style used for axis tick labels. */\n applyLabelStyle (fontSize?: number) {\n this.ctx.textAlign = 'center'\n this.ctx.textBaseline = 'middle'\n this.ctx.font = `${fontSize ?? '14'}px 'sans', sans-serif`\n this.ctx.fillStyle = this.theme.axisLabel\n }\n\n /* plotXLabels applies the provided labels to the x axis and draws the grid. */\n plotXLabels (labels: LabelSet, minX: number, maxX: number, unitLines: string[]) {\n const extents = new Extents(minX, maxX, 0, 1)\n this.xRegion.plot(extents, (ctx: CanvasRenderingContext2D, tools: Translator) => {\n this.applyLabelStyle()\n const centerX = (maxX + minX) / 2\n let lastX = minX\n let unitCenter = centerX\n const [leftEdge, rightEdge] = [tools.x(minX), tools.x(maxX)]\n const centerY = tools.y(0.5)\n labels.lbls.forEach(lbl => {\n const m = ctx.measureText(lbl.txt)\n const x = tools.x(lbl.val)\n if (x - m.width / 2 < leftEdge || x + m.width / 2 > rightEdge) return\n ctx.fillText(lbl.txt, x, centerY)\n if (centerX >= lastX && centerX < lbl.val) {\n unitCenter = (lastX + lbl.val) / 2\n }\n lastX = lbl.val\n })\n ctx.font = '11px \\'sans\\', sans-serif'\n if (unitLines.length === 2) {\n ctx.fillText(unitLines[0], tools.x(unitCenter), tools.y(0.63))\n ctx.fillText(unitLines[1], tools.x(unitCenter), tools.y(0.23))\n } else if (unitLines.length === 1) {\n ctx.fillText(unitLines[0], tools.x(unitCenter), centerY)\n }\n }, true)\n }\n\n plotXGrid (labels: LabelSet, minX: number, maxX: number) {\n const extents = new Extents(minX, maxX, 0, 1)\n this.plotRegion.plot(extents, (ctx: CanvasRenderingContext2D, tools: Translator) => {\n ctx.lineWidth = 1\n ctx.strokeStyle = this.theme.gridLines\n labels.lbls.forEach(lbl => {\n line(ctx, tools.x(lbl.val), tools.y(0), tools.x(lbl.val), tools.y(1))\n })\n }, true)\n }\n\n /*\n * plotYLabels applies the y labels based on the provided plot region, and\n * draws the grid.\n */\n plotYLabels (labels: LabelSet, minY: number, maxY: number, unit: string) {\n const extents = new Extents(0, 1, minY, maxY)\n\n const fillRect = (ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number) => {\n ctx.save()\n ctx.fillStyle = this.theme.body\n ctx.beginPath()\n if (ctx.roundRect) ctx.roundRect(x, y, w, h, r) // Safari < 16 doesn't support\n else ctx.rect(x, y, w, h)\n ctx.fill()\n ctx.restore()\n }\n\n this.yRegion.plot(extents, (ctx: CanvasRenderingContext2D, tools: Translator) => {\n this.applyLabelStyle()\n this.ctx.textAlign = 'left'\n const centerY = maxY / 2\n let lastY = 0\n let unitCenter = centerY\n const x = tools.x(0)\n const [xPad, yPad] = [3, 3]\n labels.lbls.forEach(lbl => {\n const y = tools.y(lbl.val)\n if (y < tools.y(maxY) + yPad + 7 || y > tools.y(minY) - yPad - 7) return\n const m = ctx.measureText(lbl.txt)\n fillRect(ctx, x, y - 7 - yPad, m.width + xPad * 2, 14 + yPad * 3, 3)\n ctx.fillText(lbl.txt, x + xPad, y + 2)\n if (centerY >= lastY && centerY < lbl.val) {\n unitCenter = (lastY + lbl.val) / 2\n }\n lastY = lbl.val\n })\n const m = ctx.measureText(unit)\n const y = tools.y(unitCenter)\n fillRect(ctx, x, y - yPad - 7, m.width + xPad * 2, 14 + yPad * 2, 3)\n ctx.fillText(unit, x + xPad, tools.y(unitCenter))\n }, true)\n }\n\n plotYGrid (region: Region, labels: LabelSet, minY: number, maxY: number) {\n const extents = new Extents(0, 1, minY, maxY)\n region.plot(extents, (ctx: CanvasRenderingContext2D, tools: Translator) => {\n ctx.lineWidth = 1\n ctx.strokeStyle = this.theme.gridLines\n labels.lbls.forEach(lbl => {\n line(ctx, tools.x(0), tools.y(lbl.val), tools.x(1), tools.y(lbl.val))\n })\n }, true)\n }\n\n /*\n * doYLabels generates and applies the y-axis labels, based upon the\n * provided plot region.\n */\n makeYLabels (region: Region, step: number, unit: string, valFmt?: (v: number) => string): LabelSet {\n this.applyLabelStyle()\n const yLabels = makeLabels(this.ctx, region.height(), this.dataExtents.y.min,\n this.dataExtents.y.max, 50, step, unit, valFmt)\n\n // Reassign the width of the y-label column to accommodate the widest text.\n const yAxisWidth = (yLabels.widest || 0) + 20 /* x padding */\n this.yRegion.extents.x.max = yAxisWidth\n this.yRegion.extents.y.max = region.extents.y.max\n\n return yLabels\n }\n\n line (x0: number, y0: number, x1: number, y1: number, skipStroke?: boolean) {\n line(this.ctx, x0, y0, x1, y1, skipStroke)\n }\n\n /* dot draws a circle with the provided context. */\n dot (x: number, y: number, color: string, radius: number) {\n dot(this.ctx, x, y, color, radius)\n }\n}\n\n/* DepthChart is a javascript Canvas-based depth chart renderer. */\nexport class DepthChart extends Chart {\n reporters: DepthReporters\n book: OrderBook\n zoomLevel: number\n lotSize: number\n conventionalRateStep: number\n lines: DepthLine[]\n markers: Record\n zoomInBttn: Region\n zoomOutBttn: Region\n baseUnit: string\n quoteUnit: string\n\n constructor (parent: HTMLElement, reporters: DepthReporters, zoom: number) {\n super(parent, {\n resize: () => this.resized(),\n click: (e: MouseEvent) => this.clicked(e),\n zoom: (bigger: boolean) => this.zoomed(bigger)\n })\n this.reporters = reporters\n this.zoomLevel = zoom\n this.lines = []\n this.markers = {\n buys: [],\n sells: []\n }\n this.setZoomBttns() // can't wait for requestAnimationFrame -> resized\n this.resize()\n }\n\n // setZoomBttns creates new regions for zoom in and zoom out buttons. It is\n // used in initiation of the buttons and resizing.\n setZoomBttns () {\n this.zoomInBttn = new Region(this.ctx, new Extents(0, 0, 0, 0))\n this.zoomOutBttn = new Region(this.ctx, new Extents(0, 0, 0, 0))\n }\n\n /* resized is called when the window or parent element are resized. */\n resized () {\n // The button region extents are set during drawing.\n this.setZoomBttns()\n if (this.book) this.draw()\n }\n\n /* zoomed zooms the current view in or out. bigger=true is zoom in. */\n zoomed (bigger: boolean) {\n if (!this.zoomLevel) return\n if (!this.book.buys || !this.book.sells) return\n this.wheeled()\n // Zoom in to 66%, but out to 150% = 1 / (2/3) so that the same zoom levels\n // are hit when reversing direction.\n this.zoomLevel *= bigger ? 2 / 3 : 3 / 2\n this.zoomLevel = clamp(this.zoomLevel, 0.005, 2)\n this.draw()\n this.reporters.zoom(this.zoomLevel)\n }\n\n /* clicked is the canvas 'click' event handler. */\n clicked (e: MouseEvent) {\n if (!this.dataExtents) return\n const x = e.clientX - this.rect.left\n const y = e.clientY - this.rect.y\n if (this.zoomInBttn.contains(x, y)) { this.zoom(true); return }\n if (this.zoomOutBttn.contains(x, y)) { this.zoom(false); return }\n const translator = this.plotRegion.translator(this.dataExtents)\n this.reporters.click(translator.unx(x))\n }\n\n // set sets the current data set and draws.\n set (book: OrderBook, lotSize: number, rateStepEnc: number, baseUnitInfo: UnitInfo, quoteUnitInfo: UnitInfo) {\n this.book = book\n this.lotSize = lotSize / baseUnitInfo.conventional.conversionFactor\n this.conventionalRateStep = Doc.conventionalRateStep(rateStepEnc, baseUnitInfo, quoteUnitInfo)\n this.baseUnit = baseUnitInfo.conventional.unit\n this.quoteUnit = quoteUnitInfo.conventional.unit\n if (!this.zoomLevel) {\n const [midGap, gapWidth] = this.gap()\n // Default to 5% zoom, but with a minimum of 5 * midGap, but still observing\n // the hard cap of 200%.\n const minZoom = Math.max(gapWidth / midGap * 5, 0.05)\n this.zoomLevel = Math.min(minZoom, 2)\n }\n this.draw()\n }\n\n /*\n * render draws the chart.\n * 1. Calculate the data extents and translate the order book data to a\n * cumulative form.\n * 2. Draw axis ticks and grid, mid-gap line and value, zoom buttons, mouse\n * position indicator...\n * 4. Tick labels.\n * 5. Data.\n * 6. Epoch line legend.\n * 7. Hover legend.\n */\n render () {\n // if connection fails it is not possible to get book.\n if (!this.book || !this.visible || this.canvas.width === 0) {\n this.renderScheduled = true\n return\n }\n\n this.clear()\n // if (!this.book || this.book.empty()) return\n const ctx = this.ctx\n const mousePos = this.mousePos\n const buys = this.book.buys\n const sells = this.book.sells\n\n const [midGap, gapWidth] = this.gap()\n\n const halfWindow = this.zoomLevel * midGap / 2\n const high = midGap + halfWindow\n const low = midGap - halfWindow\n\n // Get a sorted copy of the markers list.\n const buyMarkers = [...this.markers.buys]\n const sellMarkers = [...this.markers.sells]\n buyMarkers.sort((a, b) => b.rate - a.rate)\n sellMarkers.sort((a, b) => a.rate - b.rate)\n const markers: DepthMark[] = []\n\n const buyDepth: [number, number][] = []\n const buyEpoch: [number, number][] = []\n const sellDepth: [number, number][] = []\n const sellEpoch: [number, number][] = []\n const volumeReport = {\n buyBase: 0,\n buyQuote: 0,\n sellBase: 0,\n sellQuote: 0\n }\n let sum = 0\n // The epoch line is above the non-epoch region, so the epochSum y value\n // must account for non-epoch orders too.\n let epochSum = 0\n\n for (let i = 0; i < buys.length; i++) {\n const ord = buys[i]\n epochSum += ord.qty\n if (ord.rate >= low) buyEpoch.push([ord.rate, epochSum])\n if (ord.epoch) continue\n sum += ord.qty\n buyDepth.push([ord.rate, sum])\n volumeReport.buyBase += ord.qty\n volumeReport.buyQuote += ord.qty * ord.rate\n while (buyMarkers.length && floatCompare(buyMarkers[0].rate, ord.rate)) {\n const mark = buyMarkers.shift()\n if (!mark) continue\n markers.push({\n rate: mark.rate,\n qty: ord.epoch ? epochSum : sum,\n sell: ord.sell,\n active: mark.active\n })\n }\n }\n const buySum = buyDepth.length ? last(buyDepth)[1] : 0\n buyDepth.push([low, buySum])\n const epochBuySum = buyEpoch.length ? last(buyEpoch)[1] : 0\n buyEpoch.push([low, epochBuySum])\n\n epochSum = sum = 0\n for (let i = 0; i < sells.length; i++) {\n const ord = sells[i]\n epochSum += ord.qty\n if (ord.rate <= high) sellEpoch.push([ord.rate, epochSum])\n if (ord.epoch) continue\n sum += ord.qty\n sellDepth.push([ord.rate, sum])\n volumeReport.sellBase += ord.qty\n volumeReport.sellQuote += ord.qty * ord.rate\n while (sellMarkers.length && floatCompare(sellMarkers[0].rate, ord.rate)) {\n const mark = sellMarkers.shift()\n if (!mark) continue\n markers.push({\n rate: mark.rate,\n qty: ord.epoch ? epochSum : sum,\n sell: ord.sell,\n active: mark.active\n })\n }\n }\n // Add a data point going to the left so that the data doesn't end with a\n // vertical line.\n const sellSum = sellDepth.length ? last(sellDepth)[1] : 0\n sellDepth.push([high, sellSum])\n const epochSellSum = sellEpoch.length ? last(sellEpoch)[1] : 0\n sellEpoch.push([high, epochSellSum])\n\n // Add ~30px padding to the top of the chart.\n const h = this.xRegion.extents.y.min\n const growthFactor = (h + 40) / h\n const maxY = (epochSellSum && epochBuySum ? Math.max(epochBuySum, epochSellSum) : epochSellSum || epochBuySum || 1) * growthFactor\n\n const dataExtents = new Extents(low, high, 0, maxY)\n this.dataExtents = dataExtents\n\n // A function to be run at the end if there is legend data to display.\n let mouseData: MouseReport | null = null\n\n // Draw the grid.\n const xLabels = makeLabels(ctx, this.plotRegion.width(), dataExtents.x.min, dataExtents.x.max, 100, this.conventionalRateStep, '')\n this.plotXGrid(xLabels, low, high)\n const yLabels = this.makeYLabels(this.plotRegion, this.lotSize, this.baseUnit)\n this.plotYGrid(this.plotRegion, yLabels, this.dataExtents.y.min, this.dataExtents.y.max)\n\n this.plotRegion.plot(dataExtents, (ctx, tools) => {\n ctx.lineWidth = 1\n // first, a square around the plot area.\n ctx.strokeStyle = this.theme.gridBorder\n // draw a line to indicate mid-gap\n ctx.lineWidth = 2.5\n ctx.strokeStyle = this.theme.gapLine\n line(ctx, tools.x(midGap), tools.y(0), tools.x(midGap), tools.y(0.3 * dataExtents.y.max))\n\n ctx.font = '30px \\'demi-sans\\', sans-serif'\n ctx.textAlign = 'center'\n ctx.textBaseline = 'middle'\n ctx.fillStyle = this.theme.value\n const y = 0.5 * dataExtents.y.max\n ctx.fillText(Doc.formatFourSigFigs(midGap), tools.x(midGap), tools.y(y))\n ctx.font = '12px \\'sans\\', sans-serif'\n // ctx.fillText('mid-market price', tools.x(midGap), tools.y(y) + 24)\n ctx.fillText(`${(gapWidth / midGap * 100).toFixed(2)}% spread`,\n tools.x(midGap), tools.y(y) + 24)\n\n // Draw zoom buttons.\n ctx.textAlign = 'center'\n ctx.textBaseline = 'middle'\n const topCenterX = this.plotRegion.extents.midX\n const topCenterY = tools.y(maxY * 0.9)\n const zoomPct = dataExtents.xRange / midGap * 100\n const zoomText = `${zoomPct.toFixed(1)}%`\n const w = ctx.measureText(zoomText).width\n ctx.font = '13px \\'sans\\', sans-serif'\n ctx.fillText(zoomText, topCenterX, topCenterY + 1)\n // define the region for the zoom button\n const bttnSize = 20\n const xPad = 10\n let bttnLeft = topCenterX - w / 2 - xPad - bttnSize\n const bttnTop = topCenterY - bttnSize / 2\n this.zoomOutBttn.setExtents(\n bttnLeft,\n bttnLeft + bttnSize,\n bttnTop,\n bttnTop + bttnSize\n )\n let hover = mousePos && this.zoomOutBttn.contains(mousePos.x, mousePos.y)\n this.zoomOutBttn.plot(new Extents(0, 1, 0, 1), ctx => {\n ctx.font = '12px \\'icomoon\\''\n ctx.fillStyle = this.theme.zoom\n if (hover) {\n ctx.fillStyle = this.theme.zoomHover\n ctx.font = '13px \\'icomoon\\''\n }\n ctx.fillText(minusChar, this.zoomOutBttn.extents.midX, this.zoomOutBttn.extents.midY)\n })\n bttnLeft = topCenterX + w / 2 + xPad\n this.zoomInBttn.setExtents(\n bttnLeft,\n bttnLeft + bttnSize,\n bttnTop,\n bttnTop + bttnSize\n )\n hover = mousePos && this.zoomInBttn.contains(mousePos.x, mousePos.y)\n this.zoomInBttn.plot(new Extents(0, 1, 0, 1), ctx => {\n ctx.font = '12px \\'icomoon\\''\n ctx.fillStyle = this.theme.zoom\n if (hover) {\n ctx.fillStyle = this.theme.zoomHover\n ctx.font = '14px \\'icomoon\\''\n }\n ctx.fillText(plusChar, this.zoomInBttn.extents.midX, this.zoomInBttn.extents.midY)\n })\n\n // Draw a dotted vertical line where the mouse is, and a dot at the level\n // of the depth line.\n const drawLine = (x: number, color: string) => {\n if (x > high || x < low) return\n ctx.save()\n ctx.setLineDash([3, 5])\n ctx.lineWidth = 1.5\n ctx.strokeStyle = color\n line(ctx, tools.x(x), tools.y(0), tools.x(x), tools.y(maxY))\n ctx.restore()\n }\n\n // for (const line of this.lines || []) {\n // drawLine(line.rate, line.color)\n // }\n\n const tolerance = (high - low) * 0.005\n const hoverMarkers = []\n for (const marker of markers || []) {\n const hovered = (mousePos && withinTolerance(marker.rate, tools.unx(mousePos.x), tolerance))\n if (hovered) hoverMarkers.push(marker.rate)\n ctx.save()\n ctx.lineWidth = (hovered || marker.active) ? 5 : 3\n ctx.strokeStyle = marker.sell ? this.theme.sellLine : this.theme.buyLine\n ctx.fillStyle = marker.sell ? this.theme.sellFill : this.theme.buyFill\n const size = (hovered || marker.active) ? 10 : 8\n ctx.beginPath()\n const tip = {\n x: tools.x(marker.rate),\n y: tools.y(marker.qty) - 8\n }\n const top = tip.y - (Math.sqrt(3) * size / 2) // cos(30)\n ctx.moveTo(tip.x, tip.y)\n ctx.lineTo(tip.x - size / 2, top)\n ctx.lineTo(tip.x + size / 2, top)\n ctx.closePath()\n ctx.stroke()\n ctx.fill()\n ctx.restore()\n }\n\n // If the mouse is in the chart area, draw the crosshairs.\n if (!mousePos) return\n if (!this.plotRegion.contains(mousePos.x, mousePos.y)) return\n // The mouse is in the plot region. Get the data coordinates and find the\n // side and depth for the x value.\n const dataX = tools.unx(mousePos.x)\n let evalSide = sellDepth\n let trigger = (ptX: number) => ptX >= dataX\n let dotColor = this.theme.sellLine\n if (dataX < midGap) {\n evalSide = buyDepth\n trigger = (ptX) => ptX <= dataX\n dotColor = this.theme.buyLine\n }\n let bestDepth = evalSide[0]\n for (let i = 0; i < evalSide.length; i++) {\n const pt = evalSide[i]\n if (trigger(pt[0])) break\n bestDepth = pt\n }\n drawLine(dataX, this.theme.crosshairs)\n mouseData = {\n rate: dataX,\n depth: bestDepth[1],\n dotColor: dotColor,\n hoverMarkers: hoverMarkers\n }\n })\n\n // Draw the epoch lines\n ctx.lineWidth = 1.5\n ctx.setLineDash([3, 3])\n // epoch sells\n ctx.fillStyle = this.theme.sellFill\n ctx.strokeStyle = this.theme.sellLine\n this.drawDepth(sellEpoch)\n // epoch buys\n ctx.fillStyle = this.theme.buyFill\n ctx.strokeStyle = this.theme.buyLine\n this.drawDepth(buyEpoch)\n\n // Draw the book depth.\n ctx.lineWidth = 2.5\n ctx.setLineDash([])\n // book sells\n ctx.fillStyle = this.theme.sellFill\n ctx.strokeStyle = this.theme.sellLine\n this.drawDepth(sellDepth)\n // book buys\n ctx.fillStyle = this.theme.buyFill\n ctx.strokeStyle = this.theme.buyLine\n this.drawDepth(buyDepth)\n\n this.plotYLabels(yLabels, this.dataExtents.y.min, this.dataExtents.y.max, this.baseUnit)\n this.plotXLabels(xLabels, low, high, [`${this.quoteUnit}/`, this.baseUnit])\n\n // Display the dot at the intersection of the mouse hover line and the depth\n // line. This should be drawn after the depths.\n if (mouseData) {\n this.plotRegion.plot(dataExtents, (ctx, tools) => {\n if (!mouseData) return // For TypeScript. Duh.\n dot(ctx, tools.x(mouseData.rate), tools.y(mouseData.depth), mouseData.dotColor, 5)\n })\n }\n\n // Report the book volumes.\n this.reporters.volume(volumeReport)\n this.reporters.mouse(mouseData)\n }\n\n /* drawDepth draws a single side's depth chart data. */\n drawDepth (depth: [number, number][]) {\n const firstPt = depth[0]\n let x: number\n this.plotRegion.plot(this.dataExtents, (ctx, tools) => {\n const yZero = tools.y(0)\n let y = tools.y(firstPt[1])\n ctx.beginPath()\n ctx.moveTo(tools.x(firstPt[0]), tools.y(firstPt[1]))\n for (let i = 0; i < depth.length; i++) {\n // Set x, but don't set y until we draw the horizontal line.\n x = tools.x(depth[i][0])\n ctx.lineTo(x, y)\n // If this is past the render edge, quit drawing.\n y = tools.y(depth[i][1])\n ctx.lineTo(x, y)\n }\n ctx.stroke()\n ctx.lineTo(x, yZero)\n ctx.lineTo(tools.x(firstPt[0]), yZero)\n ctx.closePath()\n ctx.globalAlpha = 0.25\n ctx.fill()\n })\n }\n\n /* returns the mid-gap rate and gap width as a tuple. */\n gap () {\n const [b, s] = [this.book.bestGapBuy(), this.book.bestGapSell()]\n if (!b) {\n if (!s) return [1, 0]\n return [s.rate, 0]\n } else if (!s) return [b.rate, 0]\n return [(s.rate + b.rate) / 2, s.rate - b.rate]\n }\n\n /* setLines stores the indicator lines to draw. */\n setLines (lines: DepthLine[]) {\n this.lines = lines\n }\n\n /* setMarkers sets the indicator markers to draw. */\n setMarkers (markers: Record) {\n this.markers = markers\n }\n}\n\n/* CandleChart is a candlestick data renderer. */\nexport class CandleChart extends Chart {\n reporters: CandleReporters\n data: CandlesPayload\n zoomLevel: number\n numToShow: number\n candleRegion: Region\n volumeRegion: Region\n resizeTimer: number\n zoomLevels: number[]\n market: Market\n rateConversionFactor: number\n\n constructor (parent: HTMLElement, reporters: CandleReporters) {\n super(parent, {\n resize: () => this.resized(),\n click: (/* e: MouseEvent */) => { this.clicked() },\n zoom: (bigger: boolean) => this.zoomed(bigger)\n })\n this.reporters = reporters\n this.zoomLevel = 1\n this.numToShow = 100\n this.resize()\n }\n\n /* resized is called when the window or parent element are resized. */\n resized () {\n const ext = this.plotRegion.extents\n const candleExtents = new Extents(ext.x.min, ext.x.max, ext.y.min, ext.y.min + ext.yRange * 0.85)\n this.candleRegion = new Region(this.ctx, candleExtents)\n const volumeExtents = new Extents(ext.x.min, ext.x.max, ext.y.min + 0.85 * ext.yRange, ext.y.max)\n this.volumeRegion = new Region(this.ctx, volumeExtents)\n // Set a delay on the render to prevent lag.\n if (this.resizeTimer) clearTimeout(this.resizeTimer)\n this.resizeTimer = window.setTimeout(() => this.draw(), 100)\n }\n\n clicked (/* e: MouseEvent */) {\n // handle clicks\n }\n\n /* zoomed zooms the current view in or out. bigger=true is zoom in. */\n zoomed (bigger: boolean) {\n // bigger actually means fewer candles -> reduce zoomLevels index.\n const idx = this.zoomLevels.indexOf(this.numToShow)\n if (bigger) {\n if (idx === 0) return\n this.numToShow = this.zoomLevels[idx - 1]\n } else {\n if (this.zoomLevels.length <= idx + 1 || this.numToShow > this.data.candles.length) return\n this.numToShow = this.zoomLevels[idx + 1]\n }\n this.draw()\n }\n\n /* render draws the chart */\n render () {\n const data = this.data\n if (!data || !this.visible || this.canvas.width === 0) {\n this.renderScheduled = true\n return\n }\n const candleWidth = data.ms\n const mousePos = this.mousePos\n const allCandles = data.candles || []\n\n const n = Math.min(this.numToShow, allCandles.length)\n const candles = allCandles.slice(allCandles.length - n)\n\n this.clear()\n\n // If there are no candles. just don't draw anything.\n if (n === 0) return\n\n // padding definition and some helper functions to parse candles.\n const candleWidthPadding = 0.2\n const start = (c: Candle) => truncate(c.endStamp, candleWidth)\n const end = (c: Candle) => start(c) + candleWidth\n const paddedStart = (c: Candle) => start(c) + candleWidthPadding * candleWidth\n const paddedWidth = (1 - 2 * candleWidthPadding) * candleWidth\n\n const first = candles[0]\n const last = candles[n - 1]\n\n let [high, low, highVol] = [first.highRate, first.lowRate, first.matchVolume]\n for (const c of candles) {\n if (c.highRate > high) high = c.highRate\n if (c.lowRate < low) low = c.lowRate\n if (c.matchVolume > highVol) highVol = c.matchVolume\n }\n\n high += (high - low) * 0.1 // a little padding\n const xStart = start(first)\n let xEnd = end(last)\n xEnd += (xEnd - xStart) * 0.05 // a little padding\n\n // Calculate data extents and store them. They are used to apply labels.\n const rateStep = this.market.ratestep\n const dataExtents = new Extents(xStart, xEnd, low, high)\n if (low === high) {\n // If there is no price movement at all in the window, show a little more\n // top and bottom so things render nicely.\n dataExtents.y.min -= rateStep\n dataExtents.y.max += rateStep\n }\n this.dataExtents = dataExtents\n\n let mouseCandle: Candle | null = null\n if (mousePos) {\n this.plotRegion.plot(new Extents(dataExtents.x.min, dataExtents.x.max, 0, 1), (ctx, tools) => {\n const selectedStartStamp = truncate(tools.unx(mousePos.x), candleWidth)\n for (const c of candles) {\n if (start(c) === selectedStartStamp) {\n mouseCandle = c\n ctx.fillStyle = this.theme.gridLines\n ctx.fillRect(tools.x(start(c)), tools.y(0), tools.w(candleWidth), tools.h(1))\n break\n }\n }\n })\n }\n\n // Draw the grid\n const rFactor = this.rateConversionFactor\n const baseUnit = app().assets[this.market.baseid]?.unitInfo.conventional.unit || this.market.basesymbol.toUpperCase()\n const xLabels = makeCandleTimeLabels(candles, candleWidth, this.plotRegion.width(), 100)\n this.plotXGrid(xLabels, xStart, xEnd)\n const yLabels = this.makeYLabels(this.candleRegion, rateStep, baseUnit, v => Doc.formatFourSigFigs(v / rFactor))\n this.plotYGrid(this.candleRegion, yLabels, this.dataExtents.y.min, this.dataExtents.y.max)\n\n // Draw the volume bars.\n const volDataExtents = new Extents(xStart, xEnd, 0, highVol)\n this.volumeRegion.plot(volDataExtents, (ctx, tools) => {\n ctx.fillStyle = this.theme.gridBorder\n for (const c of candles) {\n ctx.fillRect(tools.x(paddedStart(c)), tools.y(0), tools.w(paddedWidth), tools.h(c.matchVolume))\n }\n })\n\n // Draw the candles.\n this.candleRegion.plot(dataExtents, (ctx, tools) => {\n ctx.lineWidth = 1\n for (const c of candles) {\n const desc = c.startRate > c.endRate\n const [x, y, w, h] = [tools.x(paddedStart(c)), tools.y(c.startRate), tools.w(paddedWidth), tools.h(c.endRate - c.startRate)]\n const [high, low, cx] = [tools.y(c.highRate), tools.y(c.lowRate), w / 2 + x]\n ctx.strokeStyle = desc ? this.theme.sellLine : this.theme.buyLine\n ctx.fillStyle = desc ? this.theme.sellFill : this.theme.buyFill\n\n ctx.beginPath()\n ctx.moveTo(cx, high)\n ctx.lineTo(cx, low)\n ctx.stroke()\n\n ctx.fillRect(x, y, w, h)\n ctx.strokeRect(x, y, w, h)\n }\n })\n\n // Apply labels.\n this.plotXLabels(xLabels, xStart, xEnd, [])\n this.plotYLabels(yLabels, this.dataExtents.y.min, this.dataExtents.y.max, baseUnit)\n\n // Highlight the candle if the user mouse is over the canvas.\n if (mouseCandle) {\n const yExt = this.xRegion.extents.y\n this.xRegion.plot(new Extents(dataExtents.x.min, dataExtents.x.max, yExt.min, yExt.max), (ctx, tools) => {\n if (!mouseCandle) return // For TypeScript. Duh.\n this.applyLabelStyle()\n const rangeTxt = `${new Date(start(mouseCandle)).toLocaleString()} - ${new Date(end(mouseCandle)).toLocaleString()}`\n const [xPad, yPad] = [25, 2]\n const rangeWidth = ctx.measureText(rangeTxt).width + 2 * xPad\n const rangeHeight = 16\n let centerX = tools.x((start(mouseCandle) + end(mouseCandle)) / 2)\n let left = centerX - rangeWidth / 2\n const xExt = this.xRegion.extents.x\n if (left < xExt.min) left = xExt.min\n else if (left + rangeWidth > xExt.max) left = xExt.max - rangeWidth\n centerX = left + rangeWidth / 2\n const top = yExt.min + (this.xRegion.height() - rangeHeight) / 2\n ctx.fillStyle = this.theme.legendFill\n ctx.strokeStyle = this.theme.gridBorder\n const rectArgs: [number, number, number, number] = [left - xPad, top - yPad, rangeWidth + 2 * xPad, rangeHeight + 2 * yPad]\n ctx.fillRect(...rectArgs)\n ctx.strokeRect(...rectArgs)\n this.applyLabelStyle()\n ctx.fillText(rangeTxt, centerX, this.xRegion.extents.midY, rangeWidth)\n })\n }\n\n // Report the mouse candle.\n this.reporters.mouse(mouseCandle)\n }\n\n /* setCandles sets the candle data and redraws the chart. */\n setCandles (data: CandlesPayload, market: Market, baseUnitInfo: UnitInfo, quoteUnitInfo: UnitInfo) {\n this.data = data\n if (!data.candles) return\n this.market = market\n const [qFactor, bFactor] = [quoteUnitInfo.conventional.conversionFactor, baseUnitInfo.conventional.conversionFactor]\n this.rateConversionFactor = RateEncodingFactor * qFactor / bFactor\n let n = 25\n this.zoomLevels = []\n const maxCandles = Math.max(data.candles.length, 1000)\n while (n < maxCandles) {\n this.zoomLevels.push(n)\n n *= 2\n }\n this.numToShow = 100\n this.draw()\n }\n}\n\ninterface WaveOpts {\n message?: string\n backgroundColor?: string | boolean // true for background color\n}\n\n/* Wave is a loading animation that displays a colorful line that oscillates */\nexport class Wave extends Chart {\n ani: Animation\n size: [number, number]\n region: Region\n colorShift: number\n opts: WaveOpts\n msgRegion: Region\n fontSize: number\n\n constructor (parent: HTMLElement, opts?: WaveOpts) {\n super(parent, {\n resize: () => this.resized(),\n click: (/* e: MouseEvent */) => { /* pass */ },\n zoom: (/* bigger: boolean */) => { /* pass */ }\n })\n this.canvas.classList.add('fill-abs')\n this.canvas.style.zIndex = '5'\n\n this.opts = opts ?? {}\n\n const period = 1500 // ms\n const start = Math.random() * period\n this.colorShift = Math.random() * 360\n\n // y = A*cos(k*x + theta*t + c)\n // combine three waves with different periods and speeds and phases.\n const amplitudes = [1, 0.65, 0.75]\n const ks = [3, 3, 2]\n const speeds = [Math.PI, Math.PI * 10 / 9, Math.PI / 2.5]\n const phases = [0, 0, Math.PI * 1.5]\n const n = 75\n const single = (n: number, angularX: number, angularTime: number): number => {\n return amplitudes[n] * Math.cos(ks[n] * angularX + speeds[n] * angularTime + phases[n])\n }\n const value = (x: number, angularTime: number): number => {\n const angularX = x * Math.PI * 2\n return (single(0, angularX, angularTime) + single(1, angularX, angularTime) + single(2, angularX, angularTime)) / 3\n }\n this.resize()\n this.ani = new Animation(Animation.Forever, () => {\n const angularTime = (new Date().getTime() - start) / period * Math.PI * 2\n const values = []\n for (let i = 0; i < n; i++) {\n values.push(value(i / (n - 1), angularTime))\n }\n this.drawValues(values)\n })\n }\n\n resized () {\n const opts = this.opts\n const [maxW, maxH] = [150, 100]\n const [cw, ch] = [this.canvas.width, this.canvas.height]\n let [w, h] = [cw * 0.8, ch * 0.8]\n if (w > maxW) w = maxW\n if (h > maxH) h = maxH\n let [l, t] = [(cw - w) / 2, (ch - h) / 2]\n if (opts.message) {\n this.fontSize = clamp(h * 0.15, 10, 14)\n this.applyLabelStyle(this.fontSize)\n const ypad = this.fontSize * 0.5\n const halfH = (this.fontSize / 2) + ypad\n t -= halfH\n this.msgRegion = new Region(this.ctx, new Extents(0, cw, t + h, t + h + 2 * halfH))\n }\n this.region = new Region(this.ctx, new Extents(l, l + w, t, t + h))\n }\n\n drawValues (values: number[]) {\n if (!this.region) return\n this.clear()\n const hsl = (h: number) => `hsl(${h}, 35%, 50%)`\n\n const { region, msgRegion, canvas: { width: w, height: h }, opts: { backgroundColor: bg, message: msg }, colorShift, ctx } = this\n\n if (bg) {\n if (bg === true) ctx.fillStyle = State.isDark() ? '#0a1e34' : '#f0f0f0'\n else ctx.fillStyle = bg\n ctx.fillRect(0, 0, w, h)\n }\n\n region.plot(new Extents(0, 1, -1, 1), (ctx: CanvasRenderingContext2D, t: Translator) => {\n ctx.lineWidth = 4\n ctx.lineCap = 'round'\n\n const shift = colorShift + (new Date().getTime() % 2000) / 2000 * 360 // colors move with frequency 1 / 2s\n const grad = ctx.createLinearGradient(t.x(0), 0, t.x(1), 0)\n grad.addColorStop(0, hsl(shift))\n ctx.strokeStyle = grad\n\n ctx.beginPath()\n ctx.moveTo(t.x(0), t.y(values[0]))\n for (let i = 1; i < values.length; i++) {\n const prog = i / (values.length - 1)\n grad.addColorStop(prog, hsl(prog * 300 + shift))\n ctx.lineTo(t.x(prog), t.y(values[i]))\n }\n ctx.stroke()\n })\n if (!msg) return\n msgRegion.plot(new Extents(0, 1, 0, 1), (ctx: CanvasRenderingContext2D, t: Translator) => {\n this.applyLabelStyle(this.fontSize)\n ctx.fillText(msg, t.x(0.5), t.y(0.5), this.msgRegion.width())\n })\n }\n\n render () { /* pass */ }\n\n stop () {\n this.ani.stop()\n this.canvas.remove()\n }\n}\n\n/*\n * Extents holds a min and max in both the x and y directions, and provides\n * getters for related data.\n */\nexport class Extents {\n x: MinMax\n y: MinMax\n\n constructor (xMin: number, xMax: number, yMin: number, yMax: number) {\n this.setExtents(xMin, xMax, yMin, yMax)\n }\n\n setExtents (xMin: number, xMax: number, yMin: number, yMax: number) {\n this.x = {\n min: xMin,\n max: xMax\n }\n this.y = {\n min: yMin,\n max: yMax\n }\n }\n\n get xRange (): number {\n return this.x.max - this.x.min\n }\n\n get midX (): number {\n return (this.x.max + this.x.min) / 2\n }\n\n get yRange (): number {\n return this.y.max - this.y.min\n }\n\n get midY (): number {\n return (this.y.max + this.y.min) / 2\n }\n}\n\n/*\n * Region applies an Extents to the canvas, providing utilities for coordinate\n * transformations and restricting drawing to a specified region of the canvas.\n */\nexport class Region {\n context: CanvasRenderingContext2D\n extents: Extents\n\n constructor (context: CanvasRenderingContext2D, extents: Extents) {\n this.context = context\n this.extents = extents\n }\n\n setExtents (xMin: number, xMax: number, yMin: number, yMax: number) {\n this.extents.setExtents(xMin, xMax, yMin, yMax)\n }\n\n width (): number {\n return this.extents.xRange\n }\n\n height (): number {\n return this.extents.yRange\n }\n\n contains (x: number, y: number): boolean {\n const ext = this.extents\n return (x < ext.x.max && x > ext.x.min &&\n y < ext.y.max && y > ext.y.min)\n }\n\n /*\n * A translator provides 4 function for coordinate transformations. x and y\n * translate data coordinates to canvas coordinates for the specified data\n * Extents. unx and uny translate canvas coordinates to data coordinates.\n */\n translator (dataExtents: Extents): Translator {\n const region = this.extents\n const xMin = dataExtents.x.min\n // const xMax = dataExtents.x.max\n const yMin = dataExtents.y.min\n // const yMax = dataExtents.y.max\n const yRange = dataExtents.yRange\n const xRange = dataExtents.xRange\n const screenMinX = region.x.min\n const screenW = region.x.max - screenMinX\n const screenMaxY = region.y.max\n const screenH = screenMaxY - region.y.min\n const xFactor = screenW / xRange\n const yFactor = screenH / yRange\n return {\n x: (x: number) => (x - xMin) * xFactor + screenMinX,\n y: (y: number) => screenMaxY - (y - yMin) * yFactor,\n unx: (x: number) => (x - screenMinX) / xFactor + xMin,\n uny: (y: number) => yMin - (y - screenMaxY) / yFactor,\n w: (w: number) => w / xRange * screenW,\n h: (h: number) => -h / yRange * screenH\n }\n }\n\n /* clear clears the region. */\n clear () {\n const ext = this.extents\n this.context.clearRect(ext.x.min, ext.y.min, ext.xRange, ext.yRange)\n }\n\n /* plot prepares tools for drawing using data coordinates. */\n plot (dataExtents: Extents, drawFunc: (ctx: CanvasRenderingContext2D, tools: Translator) => void, skipMask?: boolean) {\n const ctx = this.context\n const region = this.extents\n ctx.save() // Save the original state\n if (!skipMask) {\n ctx.beginPath()\n ctx.rect(region.x.min, region.y.min, region.xRange, region.yRange)\n ctx.clip()\n }\n\n // The drawFunc will be passed a set of tool that can be used to assist\n // drawing. The tools start with the transformation functions.\n const tools = this.translator(dataExtents)\n\n // Create a transformation that allows drawing in data coordinates. It's\n // not advisable to stroke or add text with this transform in place, as the\n // result will be distorted. You can however use ctx.moveTo and ctx.lineTo\n // with this transform in place using data coordinates, and remove the\n // transform before stroking. The dataCoords method of the supplied tool\n // provides this functionality.\n\n // TODO: Figure out why this doesn't work on WebView.\n // const yRange = dataExtents.yRange\n // const xFactor = region.xRange / dataExtents.xRange\n // const yFactor = region.yRange / yRange\n // const xMin = dataExtents.x.min\n // const yMin = dataExtents.y.min\n // // These translation factors are complicated because the (0, 0) of the\n // // region is not necessarily the (0, 0) of the canvas.\n // const tx = (region.x.min + xMin) - xMin * xFactor\n // const ty = -region.y.min - (yRange - yMin) * yFactor\n // const setTransform = () => {\n // // Data coordinates are flipped about y. Flip the coordinates and\n // // translate top left corner to canvas (0, 0).\n // ctx.transform(1, 0, 0, -1, -xMin, yMin)\n // // Scale to data coordinates and shift into place for the region's offset\n // // on the canvas.\n // ctx.transform(xFactor, 0, 0, yFactor, tx, ty)\n // }\n // // dataCoords allows some drawing to be performed directly in data\n // // coordinates. Most actual drawing functions like ctx.stroke and\n // // ctx.fillRect should not be called from inside dataCoords, but\n // // ctx.moveTo and ctx.LineTo are fine.\n // tools.dataCoords = f => {\n // ctx.save()\n // setTransform()\n // f()\n // ctx.restore()\n // }\n\n drawFunc(this.context, tools)\n ctx.restore()\n }\n}\n\n/*\n * makeLabels attempts to create the appropriate labels for the specified\n * screen size, context, and label spacing.\n */\nfunction makeLabels (\n ctx: CanvasRenderingContext2D,\n screenW: number,\n min: number,\n max: number,\n spacingGuess: number,\n step: number,\n unit: string,\n valFmt?: (v: number) => string\n): LabelSet {\n valFmt = valFmt || Doc.formatFourSigFigs\n const n = screenW / spacingGuess\n const diff = max - min\n if (n < 1 || diff <= 0) return { lbls: [] }\n const tickGuess = diff / n\n // make the tick spacing a multiple of the step\n const tick = tickGuess + step - (tickGuess % step)\n let x = min + tick - (min % tick)\n const absMax = Math.max(Math.abs(max), Math.abs(min))\n // The Math.round part is the minimum precision required to see the change in the numbers.\n // The 2 accounts for the precision of the tick.\n const sigFigs = Math.round(Math.log10(absMax / tick)) + 2\n const pts: Label[] = []\n let widest = 0\n while (x < max) {\n x = Number(x.toPrecision(sigFigs))\n const lbl = valFmt(x)\n widest = Math.max(widest, ctx.measureText(lbl).width)\n pts.push({\n val: x,\n txt: lbl\n })\n x += tick\n }\n const unitW = ctx.measureText(unit).width\n if (unitW > widest) widest = unitW\n return {\n widest: widest,\n lbls: pts\n }\n}\n\nconst months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']\n\n/* makeCandleTimeLabels prepares labels for candlestick data. */\nfunction makeCandleTimeLabels (candles: Candle[], dur: number, screenW: number, spacingGuess: number): LabelSet {\n const first = candles[0]\n const last = candles[candles.length - 1]\n const start = truncate(first.endStamp, dur)\n const end = truncate(last.endStamp, dur) + dur\n const diff = end - start\n const n = Math.min(candles.length, screenW / spacingGuess)\n const tick = truncate(diff / n, dur)\n if (tick === 0) {\n console.error('zero tick', dur, diff, n) // probably won't happen, but it'd suck if it did\n return { lbls: [] }\n }\n let x = start\n const zoneOffset = new Date().getTimezoneOffset()\n const dayStamp = (x: number) => {\n x = x - zoneOffset * 60000\n return x - (x % 86400000)\n }\n let lastDay = dayStamp(start)\n let lastYear = 0 // new Date(start).getFullYear()\n if (dayStamp(first.endStamp) === dayStamp(last.endStamp)) lastDay = 0 // Force at least one day stamp.\n const pts = []\n let label\n if (dur < 86400000) {\n label = (d: Date, x: number) => {\n const day = dayStamp(x)\n if (day !== lastDay) return `${months[d.getMonth()]}${d.getDate()} ${d.getHours()}:${String(d.getMinutes()).padStart(2, '0')}`\n else return `${d.getHours()}:${String(d.getMinutes()).padStart(2, '0')}`\n }\n } else {\n label = (d: Date) => {\n const year = d.getFullYear()\n if (year !== lastYear) return `${months[d.getMonth()]}${d.getDate()} '${String(year).slice(2, 4)}`\n else return `${months[d.getMonth()]}${d.getDate()}`\n }\n }\n while (x <= end) {\n const d = new Date(x)\n pts.push({\n val: x,\n txt: label(d, x)\n })\n lastDay = dayStamp(x)\n lastYear = d.getFullYear()\n x += tick\n }\n return { lbls: pts }\n}\n\n/* The last element of an array. */\nfunction last (arr: any[]): any {\n return arr[arr.length - 1]\n}\n\n/* line draws a line with the provided context. */\nfunction line (ctx: CanvasRenderingContext2D, x0: number, y0: number, x1: number, y1: number, skipStroke?: boolean) {\n ctx.beginPath()\n ctx.moveTo(x0, y0)\n ctx.lineTo(x1, y1)\n if (!skipStroke) ctx.stroke()\n}\n\n/* dot draws a circle with the provided context. */\nfunction dot (ctx: CanvasRenderingContext2D, x: number, y: number, color: string, radius: number) {\n ctx.fillStyle = color\n ctx.beginPath()\n ctx.arc(x, y, radius, 0, PIPI)\n ctx.fill()\n}\n\n/* floatCompare compares two floats to within a tolerance of 1e-8. */\nfunction floatCompare (a: number, b: number) {\n return withinTolerance(a, b, 1e-8)\n}\n\n/*\n * withinTolerance returns true if the difference between a and b are with\n * the specified tolerance.\n */\nfunction withinTolerance (a: number, b: number, tolerance: number) {\n return Math.abs(a - b) < Math.abs(tolerance)\n}\n\nfunction truncate (v: number, w: number): number {\n return v - (v % w)\n}\n","import Doc from './doc'\nimport {\n OrderTypeLimit,\n OrderTypeMarket,\n OrderTypeCancel,\n StatusEpoch,\n StatusBooked,\n RateEncodingFactor,\n MatchSideMaker,\n MakerRedeemed,\n TakerSwapCast,\n ImmediateTiF\n} from './orderutil'\nimport {\n app,\n PageElement,\n ExchangeAuth,\n Order,\n Market\n} from './registry'\n\nexport const bondReserveMultiplier = 2 // Reserves for next bond\nexport const perTierBaseParcelLimit = 2\nexport const parcelLimitScoreMultiplier = 3\n\nexport class ReputationMeter {\n page: Record\n host: string\n\n constructor (div: PageElement) {\n this.page = Doc.parseTemplate(div)\n Doc.cleanTemplates(this.page.penaltyMarkerTmpl)\n }\n\n setHost (host: string) {\n this.host = host\n }\n\n update () {\n const { page, host } = this\n const { auth, maxScore, penaltyThreshold } = app().exchanges[host]\n const { rep: { score } } = auth\n\n const displayTier = strongTier(auth)\n\n const minScore = displayTier ? displayTier * penaltyThreshold * -1 : penaltyThreshold * -1 // Just for looks\n const warnPct = 25\n const scorePct = 100 - warnPct\n page.scoreWarn.style.width = `${warnPct}%`\n const pos = score >= 0 ? warnPct + (score / maxScore) * scorePct : warnPct - (Math.min(warnPct, score / minScore * warnPct))\n\n page.scorePointer.style.left = `${pos}%`\n page.scoreMin.textContent = String(minScore)\n page.scoreMax.textContent = String(maxScore)\n const bonus = limitBonus(score, maxScore)\n page.limitBonus.textContent = bonus.toFixed(1)\n for (const m of Doc.applySelector(page.scoreTray, '.penalty-marker')) m.remove()\n if (displayTier > 1) {\n const markerPct = warnPct / displayTier\n for (let i = 1; i < displayTier; i++) {\n const div = page.penaltyMarkerTmpl.cloneNode(true) as PageElement\n page.scoreTray.appendChild(div)\n div.style.left = `${markerPct * i}%`\n }\n }\n page.score.textContent = String(score)\n page.scoreData.classList.remove('negative', 'positive')\n if (score > 0) page.scoreData.classList.add('positive')\n else page.scoreData.classList.add('negative')\n }\n}\n\n/*\n * strongTier is the effective tier, with some respect for bond overlap, such\n * that we don't count weak bonds that have already had their replacements\n * confirmed.\n */\nexport function strongTier (auth: ExchangeAuth): number {\n const { weakStrength, targetTier, effectiveTier } = auth\n if (effectiveTier > targetTier) {\n const diff = effectiveTier - targetTier\n if (weakStrength >= diff) return targetTier\n return targetTier + (diff - weakStrength)\n }\n return effectiveTier\n}\n\nexport function likelyTaker (ord: Order, rate: number): boolean {\n if (ord.type === OrderTypeMarket || ord.tif === ImmediateTiF) return true\n // Must cross the spread to be a taker (not so conservative).\n if (rate === 0) return false\n if (ord.sell) return ord.rate < rate\n return ord.rate > rate\n}\n\nconst preparcelQuantity = (ord: Order, mkt?: Market, midGap?: number) => {\n const qty = ord.qty - ord.filled\n if (ord.type === OrderTypeLimit) return qty\n if (ord.sell) return qty * ord.rate / RateEncodingFactor\n const rate = midGap || mkt?.spot?.rate || 0\n // Caller should not call this for market orders without a mkt arg.\n if (!mkt) return 0\n // This is tricky. The server will use the mid-gap rate to convert the\n // order qty. We don't have a mid-gap rate, only a spot rate.\n if (rate && (mkt?.spot?.bookVolume || 0) > 0) return qty * RateEncodingFactor / rate\n return mkt.lotsize // server uses same fallback if book is empty\n}\n\nexport function epochWeight (ord: Order, mkt: Market, midGap?: number) {\n if (ord.status !== StatusEpoch) return 0\n const qty = preparcelQuantity(ord, mkt, midGap)\n const rate = midGap || mkt.spot?.rate || 0\n if (likelyTaker(ord, rate)) return qty * 2\n return qty\n}\n\nfunction bookWeight (ord: Order) {\n if (ord.status !== StatusBooked) return 0\n return preparcelQuantity(ord)\n}\n\nfunction settlingWeight (ord: Order) {\n let sum = 0\n for (const m of (ord.matches || [])) {\n if (m.side === MatchSideMaker) {\n if (m.status > MakerRedeemed) continue\n } else if (m.status > TakerSwapCast) continue\n sum += m.qty\n }\n return sum\n}\n\nfunction parcelWeight (ord: Order, mkt: Market, midGap?: number) {\n if (ord.type === OrderTypeCancel) return 0\n return epochWeight(ord, mkt, midGap) + bookWeight(ord) + settlingWeight(ord)\n}\n\n// function roundParcels (p: number): number {\n// return Math.floor(Math.round((p * 1e8)) / 1e8)\n// }\n\nfunction limitBonus (score: number, maxScore: number): number {\n return score > 0 ? 1 + score / maxScore * (parcelLimitScoreMultiplier - 1) : 1\n}\n\nexport function tradingLimits (host: string): [number, number] { // [usedParcels, parcelLimit]\n const { auth, maxScore, markets } = app().exchanges[host]\n const { rep: { score } } = auth\n const tier = strongTier(auth)\n\n let usedParcels = 0\n for (const mkt of Object.values(markets)) {\n let mktWeight = 0\n for (const ord of (mkt.inflight || [])) mktWeight += parcelWeight(ord, mkt)\n for (const ord of (mkt.orders || [])) mktWeight += parcelWeight(ord, mkt)\n usedParcels += (mktWeight / (mkt.parcelsize * mkt.lotsize))\n }\n const parcelLimit = perTierBaseParcelLimit * limitBonus(score, maxScore) * tier\n return [usedParcels, parcelLimit]\n}\n","import {\n app,\n PageElement\n} from './registry'\nimport * as intl from './locales'\n\nexport const Mainnet = 0\nexport const Testnet = 1\nexport const Simnet = 2\n\nconst coinIDTakerFoundMakerRedemption = 'TakerFoundMakerRedemption:'\n\n/* ethBasedExplorerArg returns the explorer argument for ETH, ERC20 and EVM\nCompatible assets and whether the return value is an address. */\nfunction ethBasedExplorerArg (cid: string): [string, boolean] {\n if (cid.startsWith(coinIDTakerFoundMakerRedemption)) return [cid.substring(coinIDTakerFoundMakerRedemption.length), true]\n else if (cid.length === 42) return [cid, true]\n else return [cid, false]\n}\n\nconst ethExplorers: Record string> = {\n [Mainnet]: (cid: string) => {\n const [arg, isAddr] = ethBasedExplorerArg(cid)\n return isAddr ? `https://etherscan.io/address/${arg}` : `https://etherscan.io/tx/${arg}`\n },\n [Testnet]: (cid: string) => {\n const [arg, isAddr] = ethBasedExplorerArg(cid)\n return isAddr ? `https://sepolia.etherscan.io/address/${arg}` : `https://sepolia.etherscan.io/tx/${arg}`\n },\n [Simnet]: (cid: string) => {\n const [arg, isAddr] = ethBasedExplorerArg(cid)\n return isAddr ? `https://etherscan.io/address/${arg}` : `https://etherscan.io/tx/${arg}`\n }\n}\n\nconst polygonExplorers: Record string> = {\n [Mainnet]: (cid: string) => {\n const [arg, isAddr] = ethBasedExplorerArg(cid)\n return isAddr ? `https://polygonscan.com/address/${arg}` : `https://polygonscan.com/tx/${arg}`\n },\n [Testnet]: (cid: string) => {\n const [arg, isAddr] = ethBasedExplorerArg(cid)\n return isAddr ? `https://amoy.polygonscan.com/address/${arg}` : `https://amoy.polygonscan.com/tx/${arg}`\n },\n [Simnet]: (cid: string) => {\n const [arg, isAddr] = ethBasedExplorerArg(cid)\n return isAddr ? `https://polygonscan.com/address/${arg}` : `https://polygonscan.com/tx/${arg}`\n }\n}\n\nexport const CoinExplorers: Record string>> = {\n 42: { // dcr\n [Mainnet]: (cid: string) => {\n const [txid, vout] = cid.split(':')\n if (vout !== undefined) return `https://explorer.dcrdata.org/tx/${txid}/out/${vout}`\n return `https://explorer.dcrdata.org/tx/${txid}`\n },\n [Testnet]: (cid: string) => {\n const [txid, vout] = cid.split(':')\n if (vout !== undefined) return `https://testnet.dcrdata.org/tx/${txid}/out/${vout}`\n return `https://testnet.dcrdata.org/tx/${txid}`\n },\n [Simnet]: (cid: string) => {\n const [txid, vout] = cid.split(':')\n if (vout !== undefined) return `http://127.0.0.1:17779/tx/${txid}/out/${vout}`\n return `https://127.0.0.1:17779/tx/${txid}`\n }\n },\n 0: { // btc\n [Mainnet]: (cid: string) => `https://mempool.space/tx/${cid.split(':')[0]}`,\n [Testnet]: (cid: string) => `https://mempool.space/testnet/tx/${cid.split(':')[0]}`,\n [Simnet]: (cid: string) => `https://mempool.space/tx/${cid.split(':')[0]}`\n },\n 2: { // ltc\n [Mainnet]: (cid: string) => `https://ltc.bitaps.com/${cid.split(':')[0]}`,\n [Testnet]: (cid: string) => `https://sochain.com/tx/LTCTEST/${cid.split(':')[0]}`,\n [Simnet]: (cid: string) => `https://ltc.bitaps.com/${cid.split(':')[0]}`\n },\n 20: { // dgb\n [Mainnet]: (cid: string) => `https://digiexplorer.info/tx/${cid.split(':')[0]}`,\n [Testnet]: (cid: string) => `https://testnetexplorer.digibyteservers.io/tx/${cid.split(':')[0]}`,\n [Simnet]: (cid: string) => `https://digiexplorer.info/tx/${cid.split(':')[0]}`\n },\n 60: ethExplorers,\n 60001: ethExplorers,\n 60002: ethExplorers,\n 3: { // doge\n [Mainnet]: (cid: string) => `https://dogeblocks.com/tx/${cid.split(':')[0]}`,\n [Testnet]: (cid: string) => `https://blockexplorer.one/dogecoin/testnet/tx/${cid.split(':')[0]}`,\n [Simnet]: (cid: string) => `https://dogeblocks.com/tx/${cid.split(':')[0]}`\n },\n 5: { // dash\n [Mainnet]: (cid: string) => `https://blockexplorer.one/dash/mainnet/tx/${cid.split(':')[0]}`,\n [Testnet]: (cid: string) => `https://blockexplorer.one/dash/testnet/tx/${cid.split(':')[0]}`,\n [Simnet]: (cid: string) => `https://blockexplorer.one/dash/mainnet/tx/${cid.split(':')[0]}`\n },\n 133: { // zec\n [Mainnet]: (cid: string) => `https://zcashblockexplorer.com/transactions/${cid.split(':')[0]}`,\n [Testnet]: (cid: string) => `https://blockexplorer.one/zcash/testnet/tx/${cid.split(':')[0]}`,\n [Simnet]: (cid: string) => `https://zcashblockexplorer.com/transactions/${cid.split(':')[0]}`\n },\n 147: { // zcl\n [Mainnet]: (cid: string) => `https://explorer.zcl.zelcore.io/tx/${cid.split(':')[0]}`,\n [Simnet]: (cid: string) => `https://explorer.zcl.zelcore.io/tx/${cid.split(':')[0]}`\n },\n 136: { // firo\n [Mainnet]: (cid: string) => `https://explorer.firo.org/tx/${cid.split(':')[0]}`,\n [Testnet]: (cid: string) => `https://testexplorer.firo.org/tx/${cid.split(':')[0]}`,\n [Simnet]: (cid: string) => `https://explorer.firo.org/tx/${cid.split(':')[0]}`\n },\n 145: { // bch\n [Mainnet]: (cid: string) => `https://bch.loping.net/tx/${cid.split(':')[0]}`,\n [Testnet]: (cid: string) => `https://tbch4.loping.net/tx/${cid.split(':')[0]}`,\n [Simnet]: (cid: string) => `https://bch.loping.net/tx/${cid.split(':')[0]}`\n },\n 966: polygonExplorers,\n 966001: polygonExplorers,\n 966002: polygonExplorers,\n 966003: polygonExplorers,\n 966004: polygonExplorers\n}\n\nexport function formatCoinID (cid: string) {\n if (cid.startsWith(coinIDTakerFoundMakerRedemption)) {\n const makerAddr = cid.substring(coinIDTakerFoundMakerRedemption.length)\n return intl.prep(intl.ID_TAKER_FOUND_MAKER_REDEMPTION, { makerAddr: makerAddr })\n }\n return cid\n}\n\n/*\n * baseChainID returns the asset ID for the asset's parent if the asset is a\n * token, otherwise the ID for the asset itself.\n */\nfunction baseChainID (assetID: number) {\n const asset = app().user.assets[assetID]\n return asset.token ? asset.token.parentID : assetID\n}\n\n/*\n * setCoinHref sets the hyperlink element's href attribute based on provided\n * assetID and data-explorer-coin value present on supplied link element.\n */\nexport function setCoinHref (assetID: number, link: PageElement) {\n const net = app().user.net\n const assetExplorer = CoinExplorers[baseChainID(assetID)]\n if (!assetExplorer) return\n const formatter = assetExplorer[net]\n if (!formatter) return\n link.classList.remove('plainlink')\n link.classList.add('subtlelink')\n link.href = formatter(link.dataset.explorerCoin || '')\n}\n","import {\n app,\n PageElement,\n BotConfig,\n MMBotStatus,\n CEXConfig,\n MarketMakingStatus,\n ExchangeBalance,\n RunStats,\n StartConfig,\n MarketWithHost,\n RunningBotInventory,\n Spot,\n OrderPlacement,\n Token,\n UnitInfo,\n MarketReport,\n BotBalanceAllocation,\n ProjectedAlloc,\n BalanceNote,\n BotBalance,\n Order,\n LotFeeRange,\n BookingFees,\n BotProblems,\n EpochReportNote,\n OrderReport,\n EpochReport,\n TradePlacement,\n SupportedAsset,\n CEXProblemsNote,\n CEXProblems\n} from './registry'\nimport { getJSON, postJSON } from './http'\nimport Doc, { clamp } from './doc'\nimport * as OrderUtil from './orderutil'\nimport { Chart, Region, Extents, Translator } from './charts'\nimport * as intl from './locales'\nimport { Forms } from './forms'\n\nexport const GapStrategyMultiplier = 'multiplier'\nexport const GapStrategyAbsolute = 'absolute'\nexport const GapStrategyAbsolutePlus = 'absolute-plus'\nexport const GapStrategyPercent = 'percent'\nexport const GapStrategyPercentPlus = 'percent-plus'\n\nexport const botTypeBasicMM = 'basicMM'\nexport const botTypeArbMM = 'arbMM'\nexport const botTypeBasicArb = 'basicArb'\n\nexport interface CEXDisplayInfo {\n name: string\n logo: string\n}\n\nexport const CEXDisplayInfos: Record = {\n 'Binance': {\n name: 'Binance',\n logo: '/img/binance.com.png'\n },\n 'BinanceUS': {\n name: 'Binance U.S.',\n logo: '/img/binance.us.png'\n }\n}\n\n/*\n * MarketMakerBot is the front end representation of the server's\n * mm.MarketMaker. MarketMakerBot is a singleton assigned to MM below.\n */\nclass MarketMakerBot {\n cexBalanceCache: Record> = {}\n\n /*\n * updateBotConfig appends or updates the specified BotConfig.\n */\n async updateBotConfig (cfg: BotConfig) {\n return postJSON('/api/updatebotconfig', cfg)\n }\n\n /*\n * updateCEXConfig appends or updates the specified CEXConfig.\n */\n async updateCEXConfig (cfg: CEXConfig) {\n return postJSON('/api/updatecexconfig', cfg)\n }\n\n async removeBotConfig (host: string, baseID: number, quoteID: number) {\n return postJSON('/api/removebotconfig', { host, baseID, quoteID })\n }\n\n async report (host: string, baseID: number, quoteID: number) {\n return postJSON('/api/marketreport', { host, baseID, quoteID })\n }\n\n async startBot (config: StartConfig) {\n return await postJSON('/api/startmarketmakingbot', { config })\n }\n\n async stopBot (market: MarketWithHost) : Promise {\n await postJSON('/api/stopmarketmakingbot', { market })\n }\n\n async status () : Promise {\n return (await getJSON('/api/marketmakingstatus')).status\n }\n\n // botStats returns the RunStats for a running bot with the specified parameters.\n botStats (baseID: number, quoteID: number, host: string, startTime: number): RunStats | undefined {\n for (const botStatus of Object.values(app().mmStatus.bots)) {\n if (!botStatus.runStats) continue\n const runStats = botStatus.runStats\n const cfg = botStatus.config\n if (cfg.baseID === baseID && cfg.quoteID === quoteID && cfg.host === host && runStats.startTime === startTime) {\n return runStats\n }\n }\n }\n\n cachedCexBalance (cexName: string, assetID: number): ExchangeBalance | undefined {\n return this.cexBalanceCache[cexName]?.[assetID]\n }\n\n async cexBalance (cexName: string, assetID: number): Promise {\n if (!this.cexBalanceCache[cexName]) this.cexBalanceCache[cexName] = {}\n const cexBalance = (await postJSON('/api/cexbalance', { cexName, assetID })).cexBalance\n this.cexBalanceCache[cexName][assetID] = cexBalance\n return cexBalance\n }\n}\n\n// MM is the front end representation of the server's mm.MarketMaker.\nexport const MM = new MarketMakerBot()\n\nexport function runningBotInventory (assetID: number): RunningBotInventory {\n return app().mmStatus.bots.reduce((v, { runStats, running }) => {\n if (!running || !runStats) return v\n const { dexBalances: d, cexBalances: c } = runStats\n v.cex.locked += c[assetID]?.locked ?? 0\n v.cex.locked += c[assetID]?.reserved ?? 0\n v.cex.avail += c[assetID]?.available ?? 0\n v.cex.total = v.cex.avail + v.cex.locked\n v.dex.locked += d[assetID]?.locked ?? 0\n v.dex.locked += d[assetID]?.reserved ?? 0\n v.dex.avail += d[assetID]?.available ?? 0\n v.dex.total = v.dex.avail + v.dex.locked\n v.avail += (d[assetID]?.available ?? 0) + (c[assetID]?.available ?? 0)\n v.locked += (d[assetID]?.locked ?? 0) + (c[assetID]?.locked ?? 0)\n return v\n }, { avail: 0, locked: 0, cex: { avail: 0, locked: 0, total: 0 }, dex: { avail: 0, locked: 0, total: 0 } })\n}\n\nexport function setMarketElements (ancestor: PageElement, baseID: number, quoteID: number, host: string) {\n Doc.setText(ancestor, '[data-host]', host)\n const { unitInfo: bui, name: baseName, symbol: baseSymbol, token: baseToken } = app().assets[baseID]\n Doc.setText(ancestor, '[data-base-name]', baseName)\n Doc.setSrc(ancestor, '[data-base-logo]', Doc.logoPath(baseSymbol))\n Doc.setText(ancestor, '[data-base-ticker]', bui.conventional.unit)\n const { unitInfo: baseFeeUI, name: baseFeeName, symbol: baseFeeSymbol } = app().assets[baseToken ? baseToken.parentID : baseID]\n Doc.setText(ancestor, '[data-base-fee-name]', baseFeeName)\n Doc.setSrc(ancestor, '[data-base-fee-logo]', Doc.logoPath(baseFeeSymbol))\n Doc.setText(ancestor, '[data-base-fee-ticker]', baseFeeUI.conventional.unit)\n const { unitInfo: qui, name: quoteName, symbol: quoteSymbol, token: quoteToken } = app().assets[quoteID]\n Doc.setText(ancestor, '[data-quote-name]', quoteName)\n Doc.setSrc(ancestor, '[data-quote-logo]', Doc.logoPath(quoteSymbol))\n Doc.setText(ancestor, '[data-quote-ticker]', qui.conventional.unit)\n const { unitInfo: quoteFeeUI, name: quoteFeeName, symbol: quoteFeeSymbol } = app().assets[quoteToken ? quoteToken.parentID : quoteID]\n Doc.setText(ancestor, '[data-quote-fee-name]', quoteFeeName)\n Doc.setSrc(ancestor, '[data-quote-fee-logo]', Doc.logoPath(quoteFeeSymbol))\n Doc.setText(ancestor, '[data-quote-fee-ticker]', quoteFeeUI.conventional.unit)\n}\n\nexport function setCexElements (ancestor: PageElement, cexName: string) {\n const dinfo = CEXDisplayInfos[cexName]\n Doc.setText(ancestor, '[data-cex-name]', dinfo.name)\n Doc.setSrc(ancestor, '[data-cex-logo]', dinfo.logo)\n for (const img of Doc.applySelector(ancestor, '[data-cex-logo]')) Doc.show(img)\n}\n\nexport function calculateQuoteLot (lotSize: number, baseID: number, quoteID: number, spot?: Spot) {\n const baseRate = app().fiatRatesMap[baseID]\n const quoteRate = app().fiatRatesMap[quoteID]\n const { unitInfo: { conventional: { conversionFactor: bFactor } } } = app().assets[baseID]\n const { unitInfo: { conventional: { conversionFactor: qFactor } } } = app().assets[quoteID]\n if (baseRate && quoteRate) {\n return lotSize * baseRate / quoteRate * qFactor / bFactor\n } else if (spot) {\n return lotSize * spot.rate / OrderUtil.RateEncodingFactor\n }\n return qFactor\n}\n\nexport interface PlacementChartConfig {\n cexName: string\n botType: string\n baseFiatRate: number\n dict: {\n profit: number\n buyPlacements: OrderPlacement[]\n sellPlacements: OrderPlacement[]\n }\n}\n\nexport class PlacementsChart extends Chart {\n cfg: PlacementChartConfig\n loadedCEX: string\n cexLogo: HTMLImageElement\n\n constructor (parent: PageElement) {\n super(parent, {\n resize: () => this.resized(),\n click: (/* e: MouseEvent */) => { /* pass */ },\n zoom: (/* bigger: boolean */) => { /* pass */ }\n })\n }\n\n resized () {\n this.render()\n }\n\n draw () { /* pass */ }\n\n setMarket (cfg: PlacementChartConfig) {\n this.cfg = cfg\n const { loadedCEX, cfg: { cexName } } = this\n if (cexName && cexName !== loadedCEX) {\n this.loadedCEX = cexName\n this.cexLogo = new Image()\n Doc.bind(this.cexLogo, 'load', () => { this.render() })\n this.cexLogo.src = CEXDisplayInfos[cexName || ''].logo\n }\n this.render()\n }\n\n render () {\n const { ctx, canvas, theme, cfg } = this\n if (canvas.width === 0 || !cfg) return\n const { dict: { buyPlacements, sellPlacements, profit }, baseFiatRate, botType } = cfg\n if (botType === botTypeBasicArb) return\n\n this.clear()\n\n const drawDashedLine = (x0: number, y0: number, x1: number, y1: number, color: string) => {\n ctx.save()\n ctx.setLineDash([3, 5])\n ctx.lineWidth = 1.5\n ctx.strokeStyle = color\n this.line(x0, y0, x1, y1)\n ctx.restore()\n }\n\n const isBasicMM = botType === botTypeBasicMM\n const cx = canvas.width / 2\n const [cexGapL, cexGapR] = isBasicMM ? [cx, cx] : [0.48 * canvas.width, 0.52 * canvas.width]\n\n const buyLots = buyPlacements.reduce((v: number, p: OrderPlacement) => v + p.lots, 0)\n const sellLots = sellPlacements.reduce((v: number, p: OrderPlacement) => v + p.lots, 0)\n const maxLots = Math.max(buyLots, sellLots)\n\n let widest = 0\n let fauxSpacer = 0\n if (isBasicMM) {\n const leftmost = buyPlacements.reduce((v: number, p: OrderPlacement) => Math.max(v, p.gapFactor), 0)\n const rightmost = sellPlacements.reduce((v: number, p: OrderPlacement) => Math.max(v, p.gapFactor), 0)\n widest = Math.max(leftmost, rightmost)\n } else {\n // For arb-mm, we don't know how the orders will be spaced because it\n // depends on the vwap. But we're just trying to capture the general sense\n // of how the parameters will affect order placement, so we'll fake it.\n // Higher match buffer values will lead to orders with less favorable\n // rates, e.g. the spacing will be larger.\n const ps = [...buyPlacements, ...sellPlacements]\n const matchBuffer = ps.reduce((sum: number, p: OrderPlacement) => sum + p.gapFactor, 0) / ps.length\n fauxSpacer = 0.01 * (1 + matchBuffer)\n widest = Math.min(10, Math.max(buyPlacements.length, sellPlacements.length)) * fauxSpacer // arb-mm\n }\n\n // Make the range 15% on each side, which will include profit + placements,\n // unless they have orders with larger gap factors.\n const minRange = profit + widest\n const defaultRange = 0.155\n const range = Math.max(minRange * 1.05, defaultRange)\n\n // Increase data height logarithmically up to 1,000,000 USD.\n const maxCommitUSD = maxLots * baseFiatRate\n const regionHeight = 0.2 + 0.7 * Math.log(clamp(maxCommitUSD, 0, 1e6)) / Math.log(1e6)\n\n // Draw a region in the middle representing the cex gap.\n const plotRegion = new Region(ctx, new Extents(0, canvas.width, 0, canvas.height))\n\n if (isBasicMM) {\n drawDashedLine(cx, 0, cx, canvas.height, theme.gapLine)\n } else { // arb-mm\n plotRegion.plot(new Extents(0, 1, 0, 1), (ctx: CanvasRenderingContext2D, tools: Translator) => {\n const [y0, y1] = [tools.y(0), tools.y(1)]\n drawDashedLine(cexGapL, y0, cexGapL, y1, theme.gapLine)\n drawDashedLine(cexGapR, y0, cexGapR, y1, theme.gapLine)\n const y = tools.y(0.95)\n ctx.drawImage(this.cexLogo, cx - 8, y, 16, 16)\n this.applyLabelStyle(18)\n ctx.fillText('δ', cx, y + 29)\n })\n }\n\n const plotSide = (isBuy: boolean, placements: OrderPlacement[]) => {\n if (!placements?.length) return\n const [xMin, xMax] = isBuy ? [0, cexGapL] : [cexGapR, canvas.width]\n const reg = new Region(ctx, new Extents(xMin, xMax, canvas.height * (1 - regionHeight), canvas.height))\n const [l, r] = isBuy ? [-range, 0] : [0, range]\n reg.plot(new Extents(l, r, 0, maxLots), (ctx: CanvasRenderingContext2D, tools: Translator) => {\n ctx.lineWidth = 2.5\n ctx.strokeStyle = isBuy ? theme.buyLine : theme.sellLine\n ctx.fillStyle = isBuy ? theme.buyFill : theme.sellFill\n ctx.beginPath()\n const sideFactor = isBuy ? -1 : 1\n const firstPt = placements[0]\n const y0 = tools.y(0)\n const firstX = tools.x((isBasicMM ? firstPt.gapFactor : profit + fauxSpacer) * sideFactor)\n ctx.moveTo(firstX, y0)\n let cumulativeLots = 0\n for (let i = 0; i < placements.length; i++) {\n const p = placements[i]\n // For arb-mm, we don't know exactly\n const rawX = isBasicMM ? p.gapFactor : profit + (i + 1) * fauxSpacer\n const x = tools.x(rawX * sideFactor)\n ctx.lineTo(x, tools.y(cumulativeLots))\n cumulativeLots += p.lots\n ctx.lineTo(x, tools.y(cumulativeLots))\n }\n const xInfinity = isBuy ? canvas.width * -0.1 : canvas.width * 1.1\n ctx.lineTo(xInfinity, tools.y(cumulativeLots))\n ctx.stroke()\n ctx.lineTo(xInfinity, y0)\n ctx.lineTo(firstX, y0)\n ctx.closePath()\n ctx.globalAlpha = 0.25\n ctx.fill()\n }, true)\n }\n\n plotSide(false, sellPlacements)\n plotSide(true, buyPlacements)\n }\n}\n\nexport function hostedMarketID (host: string, baseID: number, quoteID: number) {\n return `${host}-${baseID}-${quoteID}` // same as MarketWithHost.String()\n}\n\nexport function liveBotConfig (host: string, baseID: number, quoteID: number): BotConfig | undefined {\n const s = liveBotStatus(host, baseID, quoteID)\n if (s) return s.config\n}\n\nexport function liveBotStatus (host: string, baseID: number, quoteID: number): MMBotStatus | undefined {\n const statuses = (app().mmStatus.bots || []).filter((s: MMBotStatus) => {\n return s.config.baseID === baseID && s.config.quoteID === quoteID && s.config.host === host\n })\n if (statuses.length) return statuses[0]\n}\n\ninterface Lotter {\n lots: number\n}\n\nfunction sumLots (lots: number, p: Lotter) {\n return lots + p.lots\n}\n\ninterface AllocationProjection {\n bProj: ProjectedAlloc\n qProj: ProjectedAlloc\n alloc: Record\n}\n\nfunction emptyProjection (): ProjectedAlloc {\n return { book: 0, bookingFees: 0, swapFeeReserves: 0, cex: 0, orderReserves: 0, slippageBuffer: 0 }\n}\n\nexport class BotMarket {\n cfg: BotConfig\n host: string\n baseID: number\n baseSymbol: string\n baseTicker: string\n baseFeeID: number\n baseIsAccountLocker: boolean\n baseFeeSymbol: string\n baseFeeTicker: string\n baseToken?: Token\n quoteID: number\n quoteSymbol: string\n quoteTicker: string\n quoteFeeID: number\n quoteIsAccountLocker: boolean\n quoteFeeSymbol: string\n quoteFeeTicker: string\n quoteToken?: Token\n botType: string\n cexName: string\n dinfo: CEXDisplayInfo\n alloc: BotBalanceAllocation\n proj: AllocationProjection\n bui: UnitInfo\n baseFactor: number\n baseFeeUI: UnitInfo\n baseFeeFactor: number\n qui: UnitInfo\n quoteFactor: number\n quoteFeeUI: UnitInfo\n quoteFeeFactor: number\n id: string // includes host\n mktID: string\n lotSize: number\n lotSizeConv: number\n lotSizeUSD: number\n quoteLot: number\n quoteLotConv: number\n quoteLotUSD: number\n rateStep: number\n baseFeeFiatRate: number\n quoteFeeFiatRate: number\n baseLots: number\n quoteLots: number\n marketReport: MarketReport\n nBuyPlacements: number\n nSellPlacements: number\n\n constructor (cfg: BotConfig) {\n const host = this.host = cfg.host\n const baseID = this.baseID = cfg.baseID\n const quoteID = this.quoteID = cfg.quoteID\n this.cexName = cfg.cexName\n const status = app().mmStatus.bots.find(({ config: c }: MMBotStatus) => c.baseID === baseID && c.quoteID === quoteID && c.host === host)\n if (!status) throw Error('where\\'s the bot status?')\n this.cfg = status.config\n\n const { token: baseToken, symbol: baseSymbol, unitInfo: bui } = app().assets[baseID]\n this.baseSymbol = baseSymbol\n this.baseTicker = bui.conventional.unit\n this.bui = bui\n this.baseFactor = bui.conventional.conversionFactor\n this.baseToken = baseToken\n const baseFeeID = this.baseFeeID = baseToken ? baseToken.parentID : baseID\n const { unitInfo: baseFeeUI, symbol: baseFeeSymbol, wallet: baseWallet } = app().assets[this.baseFeeID]\n const traitAccountLocker = 1 << 14\n this.baseIsAccountLocker = (baseWallet.traits & traitAccountLocker) > 0\n this.baseFeeUI = baseFeeUI\n this.baseFeeTicker = baseFeeUI.conventional.unit\n this.baseFeeSymbol = baseFeeSymbol\n this.baseFeeFactor = this.baseFeeUI.conventional.conversionFactor\n\n const { token: quoteToken, symbol: quoteSymbol, unitInfo: qui } = app().assets[quoteID]\n this.quoteSymbol = quoteSymbol\n this.quoteTicker = qui.conventional.unit\n this.qui = qui\n this.quoteFactor = qui.conventional.conversionFactor\n this.quoteToken = quoteToken\n const quoteFeeID = this.quoteFeeID = quoteToken ? quoteToken.parentID : quoteID\n const { unitInfo: quoteFeeUI, symbol: quoteFeeSymbol, wallet: quoteWallet } = app().assets[this.quoteFeeID]\n this.quoteIsAccountLocker = (quoteWallet.traits & traitAccountLocker) > 0\n this.quoteFeeUI = quoteFeeUI\n this.quoteFeeTicker = quoteFeeUI.conventional.unit\n this.quoteFeeSymbol = quoteFeeSymbol\n this.quoteFeeFactor = this.quoteFeeUI.conventional.conversionFactor\n\n this.id = hostedMarketID(host, baseID, quoteID)\n this.mktID = `${baseSymbol}_${quoteSymbol}`\n\n const { markets } = app().exchanges[host]\n const { lotsize: lotSize, ratestep: rateStep } = markets[this.mktID]\n this.lotSize = lotSize\n this.lotSizeConv = lotSize / bui.conventional.conversionFactor\n this.rateStep = rateStep\n this.quoteLot = calculateQuoteLot(lotSize, baseID, quoteID)\n this.quoteLotConv = this.quoteLot / qui.conventional.conversionFactor\n\n this.baseFeeFiatRate = app().fiatRatesMap[baseFeeID]\n this.quoteFeeFiatRate = app().fiatRatesMap[quoteFeeID]\n\n if (cfg.arbMarketMakingConfig) {\n this.botType = botTypeArbMM\n this.baseLots = cfg.arbMarketMakingConfig.sellPlacements.reduce(sumLots, 0)\n this.quoteLots = cfg.arbMarketMakingConfig.buyPlacements.reduce(sumLots, 0)\n this.nBuyPlacements = cfg.arbMarketMakingConfig.buyPlacements.length\n this.nSellPlacements = cfg.arbMarketMakingConfig.sellPlacements.length\n } else if (cfg.simpleArbConfig) {\n this.botType = botTypeBasicArb\n this.baseLots = cfg.uiConfig.simpleArbLots as number\n this.quoteLots = cfg.uiConfig.simpleArbLots as number\n } else if (cfg.basicMarketMakingConfig) { // basicmm\n this.botType = botTypeBasicMM\n this.baseLots = cfg.basicMarketMakingConfig.sellPlacements.reduce(sumLots, 0)\n this.quoteLots = cfg.basicMarketMakingConfig.buyPlacements.reduce(sumLots, 0)\n this.nBuyPlacements = cfg.basicMarketMakingConfig.buyPlacements.length\n this.nSellPlacements = cfg.basicMarketMakingConfig.sellPlacements.length\n }\n }\n\n async initialize () {\n const { host, baseID, quoteID, lotSizeConv, quoteLotConv } = this\n const res = await MM.report(host, baseID, quoteID)\n const r = this.marketReport = res.report as MarketReport\n this.lotSizeUSD = lotSizeConv * r.baseFiatRate\n this.quoteLotUSD = quoteLotConv * r.quoteFiatRate\n this.proj = this.projectedAllocations()\n }\n\n status () {\n const { baseID, quoteID } = this\n const botStatus = app().mmStatus.bots.find((s: MMBotStatus) => s.config.baseID === baseID && s.config.quoteID === quoteID)\n if (!botStatus) return { botCfg: {} as BotConfig, running: false, runStats: {} as RunStats }\n const { config: botCfg, running, runStats, latestEpoch, cexProblems } = botStatus\n return { botCfg, running, runStats, latestEpoch, cexProblems }\n }\n\n /*\n * adjustedBalances calculates the user's available balances and fee-asset\n * balances for a market, with consideration for currently running bots.\n */\n adjustedBalances () {\n const {\n baseID, quoteID, baseFeeID, quoteFeeID, cexName,\n baseFactor, quoteFactor, baseFeeFactor, quoteFeeFactor\n } = this\n const [baseWallet, quoteWallet] = [app().walletMap[baseID], app().walletMap[quoteID]]\n const [bInv, qInv] = [runningBotInventory(baseID), runningBotInventory(quoteID)]\n\n // In these available balance calcs, only subtract the available balance of\n // running bots, since the locked/reserved/immature is already subtracted\n // from the wallet's total available balance.\n let cexBaseAvail = 0\n let cexQuoteAvail = 0\n let cexBaseBalance: ExchangeBalance | undefined\n let cexQuoteBalance: ExchangeBalance | undefined\n if (cexName) {\n const cex = app().mmStatus.cexes[cexName]\n if (!cex) throw Error('where\\'s the cex status?')\n cexBaseBalance = cex.balances[baseID]\n cexQuoteBalance = cex.balances[quoteID]\n }\n if (cexBaseBalance) cexBaseAvail = (cexBaseBalance.available || 0) - bInv.cex.avail\n if (cexQuoteBalance) cexQuoteAvail = (cexQuoteBalance.available || 0) - qInv.cex.avail\n const [dexBaseAvail, dexQuoteAvail] = [baseWallet.balance.available - bInv.dex.avail, quoteWallet.balance.available - qInv.dex.avail]\n const baseAvail = dexBaseAvail + cexBaseAvail\n const quoteAvail = dexQuoteAvail + cexQuoteAvail\n const baseFeeWallet = baseFeeID === baseID ? baseWallet : app().walletMap[baseFeeID]\n const quoteFeeWallet = quoteFeeID === quoteID ? quoteWallet : app().walletMap[quoteFeeID]\n\n let [baseFeeAvail, dexBaseFeeAvail, cexBaseFeeAvail] = [baseAvail, dexBaseAvail, cexBaseAvail]\n if (baseFeeID !== baseID) {\n const bFeeInv = runningBotInventory(baseID)\n dexBaseFeeAvail = baseFeeWallet.balance.available - bFeeInv.dex.total\n if (cexBaseBalance) cexBaseFeeAvail = (cexBaseBalance.available || 0) - bFeeInv.cex.total\n baseFeeAvail = dexBaseFeeAvail + cexBaseFeeAvail\n }\n let [quoteFeeAvail, dexQuoteFeeAvail, cexQuoteFeeAvail] = [quoteAvail, dexQuoteAvail, cexQuoteAvail]\n if (quoteFeeID !== quoteID) {\n const qFeeInv = runningBotInventory(quoteID)\n dexQuoteFeeAvail = quoteFeeWallet.balance.available - qFeeInv.dex.total\n if (cexQuoteBalance) cexQuoteFeeAvail = (cexQuoteBalance.available || 0) - qFeeInv.cex.total\n quoteFeeAvail = dexQuoteFeeAvail + cexQuoteFeeAvail\n }\n return { // convert to conventioanl.\n baseAvail: baseAvail / baseFactor,\n quoteAvail: quoteAvail / quoteFactor,\n dexBaseAvail: dexBaseAvail / baseFactor,\n dexQuoteAvail: dexQuoteAvail / quoteFactor,\n cexBaseAvail: cexBaseAvail / baseFactor,\n cexQuoteAvail: cexQuoteAvail / quoteFactor,\n baseFeeAvail: baseFeeAvail / baseFeeFactor,\n quoteFeeAvail: quoteFeeAvail / quoteFeeFactor,\n dexBaseFeeAvail: dexBaseFeeAvail / baseFeeFactor,\n dexQuoteFeeAvail: dexQuoteFeeAvail / quoteFeeFactor,\n cexBaseFeeAvail: cexBaseFeeAvail / baseFeeFactor,\n cexQuoteFeeAvail: cexQuoteFeeAvail / quoteFeeFactor\n }\n }\n\n /*\n * feesAndCommit generates a snapshot of current market fees, as well as a\n * \"commit\", which is the funding dedicated to being on order. The commit\n * values do not include booking fees, order reserves, etc. just the order\n * quantity.\n */\n feesAndCommit () {\n const {\n baseID, quoteID, marketReport: { baseFees, quoteFees }, lotSize,\n baseLots, quoteLots, baseFeeID, quoteFeeID, baseIsAccountLocker, quoteIsAccountLocker,\n cfg: { uiConfig: { baseConfig, quoteConfig } }\n } = this\n\n return feesAndCommit(\n baseID, quoteID, baseFees, quoteFees, lotSize, baseLots, quoteLots,\n baseFeeID, quoteFeeID, baseIsAccountLocker, quoteIsAccountLocker,\n baseConfig.orderReservesFactor, quoteConfig.orderReservesFactor\n )\n }\n\n /*\n * projectedAllocations calculates the required asset allocations from the\n * user's configuration settings and the current market state.\n */\n projectedAllocations () {\n const {\n cfg: { uiConfig: { quoteConfig, baseConfig } },\n baseFactor, quoteFactor, baseID, quoteID, lotSizeConv, quoteLotConv,\n baseFeeFactor, quoteFeeFactor, baseFeeID, quoteFeeID, baseToken,\n quoteToken, cexName\n } = this\n const { commit, fees } = this.feesAndCommit()\n\n const bProj = emptyProjection()\n const qProj = emptyProjection()\n\n bProj.book = commit.dex.base.lots * lotSizeConv\n qProj.book = commit.cex.base.lots * quoteLotConv\n\n bProj.orderReserves = Math.max(commit.cex.base.val, commit.dex.base.val) * baseConfig.orderReservesFactor / baseFactor\n qProj.orderReserves = Math.max(commit.cex.quote.val, commit.dex.quote.val) * quoteConfig.orderReservesFactor / quoteFactor\n\n if (cexName) {\n bProj.cex = commit.cex.base.lots * lotSizeConv\n qProj.cex = commit.cex.quote.lots * quoteLotConv\n }\n\n bProj.bookingFees = fees.base.bookingFees / baseFeeFactor\n qProj.bookingFees = fees.quote.bookingFees / quoteFeeFactor\n\n if (baseToken) bProj.swapFeeReserves = fees.base.tokenFeesPerSwap * baseConfig.swapFeeN / baseFeeFactor\n if (quoteToken) qProj.swapFeeReserves = fees.quote.tokenFeesPerSwap * quoteConfig.swapFeeN / quoteFeeFactor\n qProj.slippageBuffer = (qProj.book + qProj.cex + qProj.orderReserves) * quoteConfig.slippageBufferFactor\n\n const alloc: Record = {}\n const addAlloc = (assetID: number, amt: number) => { alloc[assetID] = (alloc[assetID] ?? 0) + amt }\n addAlloc(baseID, Math.round((bProj.book + bProj.cex + bProj.orderReserves) * baseFactor))\n addAlloc(baseFeeID, Math.round((bProj.bookingFees + bProj.swapFeeReserves) * baseFeeFactor))\n addAlloc(quoteID, Math.round((qProj.book + qProj.cex + qProj.orderReserves + qProj.slippageBuffer) * quoteFactor))\n addAlloc(quoteFeeID, Math.round((qProj.bookingFees + qProj.swapFeeReserves) * quoteFeeFactor))\n\n return { qProj, bProj, alloc }\n }\n\n /*\n * fundingState examines the projected allocations and the user's wallet\n * balances to determine whether the user can fund the bot fully, unbalanced,\n * or starved, and what funding source options might be available.\n */\n fundingState () {\n const {\n proj: { bProj, qProj }, baseID, quoteID, baseFeeID, quoteFeeID,\n cfg: { uiConfig: { cexRebalance } }, cexName\n } = this\n const {\n baseAvail, quoteAvail, dexBaseAvail, dexQuoteAvail, cexBaseAvail, cexQuoteAvail,\n dexBaseFeeAvail, dexQuoteFeeAvail\n } = this.adjustedBalances()\n\n const canRebalance = Boolean(cexName && cexRebalance)\n\n // Three possible states.\n // 1. We have the funding in the projection, and its in the right places.\n // Give them some options for which wallet to pull order reserves from,\n // but they can start immediately..\n // 2. We have the funding, but it's in the wrong place or the wrong asset,\n // but we have deposits and withdraws enabled. We can offer them the\n // option to start in an unbalanced state.\n // 3. We don't have the funds. We offer them an option to start in a\n // starved state.\n const cexMinBaseAlloc = bProj.cex\n let [dexMinBaseAlloc, transferableBaseAlloc, dexBaseFeeReq] = [bProj.book, 0, 0]\n // Only add booking fees if this is the fee asset.\n if (baseID === baseFeeID) dexMinBaseAlloc += bProj.bookingFees\n // Base asset is a token.\n else dexBaseFeeReq += bProj.bookingFees + bProj.swapFeeReserves\n // If we can rebalance, the order reserves could potentially be withdrawn.\n if (canRebalance) transferableBaseAlloc += bProj.orderReserves\n // If we can't rebalance, order reserves are required in dex balance.\n else dexMinBaseAlloc += bProj.orderReserves\n // Handle the special case where the base asset it the quote asset's fee\n // asset.\n if (baseID === quoteFeeID) {\n if (canRebalance) transferableBaseAlloc += qProj.bookingFees + qProj.swapFeeReserves\n else dexMinBaseAlloc += qProj.bookingFees + qProj.swapFeeReserves\n }\n\n let [dexMinQuoteAlloc, cexMinQuoteAlloc, transferableQuoteAlloc, dexQuoteFeeReq] = [qProj.book, qProj.cex, 0, 0]\n if (quoteID === quoteFeeID) dexMinQuoteAlloc += qProj.bookingFees\n else dexQuoteFeeReq += qProj.bookingFees + qProj.swapFeeReserves\n if (canRebalance) transferableQuoteAlloc += qProj.orderReserves + qProj.slippageBuffer\n else {\n // The slippage reserves reserves should be split between cex and dex.\n dexMinQuoteAlloc += qProj.orderReserves\n const basis = qProj.book + qProj.cex + qProj.orderReserves\n dexMinQuoteAlloc += (qProj.book + qProj.orderReserves) / basis * qProj.slippageBuffer\n cexMinQuoteAlloc += qProj.cex / basis * qProj.slippageBuffer\n }\n if (quoteID === baseFeeID) {\n if (canRebalance) transferableQuoteAlloc += bProj.bookingFees + bProj.swapFeeReserves\n else dexMinQuoteAlloc += bProj.bookingFees + bProj.swapFeeReserves\n }\n\n const dexBaseFunded = dexBaseAvail >= dexMinBaseAlloc\n const cexBaseFunded = cexBaseAvail >= cexMinBaseAlloc\n const dexQuoteFunded = dexQuoteAvail >= dexMinQuoteAlloc\n const cexQuoteFunded = cexQuoteAvail >= cexMinQuoteAlloc\n const totalBaseReq = dexMinBaseAlloc + cexMinBaseAlloc + transferableBaseAlloc\n const totalQuoteReq = dexMinQuoteAlloc + cexMinQuoteAlloc + transferableQuoteAlloc\n const baseFundedAndBalanced = dexBaseFunded && cexBaseFunded && baseAvail >= totalBaseReq\n const quoteFundedAndBalanced = dexQuoteFunded && cexQuoteFunded && quoteAvail >= totalQuoteReq\n const baseFeesFunded = dexBaseFeeAvail >= dexBaseFeeReq\n const quoteFeesFunded = dexQuoteFeeAvail >= dexQuoteFeeReq\n\n const fundedAndBalanced = baseFundedAndBalanced && quoteFundedAndBalanced && baseFeesFunded && quoteFeesFunded\n\n // Are we funded but not balanced, but able to rebalance with a cex?\n let fundedAndNotBalanced = !fundedAndBalanced\n if (!fundedAndBalanced) {\n const ordersFunded = baseAvail >= totalBaseReq && quoteAvail >= totalQuoteReq\n const feesFunded = baseFeesFunded && quoteFeesFunded\n fundedAndNotBalanced = ordersFunded && feesFunded && canRebalance\n }\n\n return {\n base: {\n dex: {\n avail: dexBaseAvail,\n req: dexMinBaseAlloc,\n funded: dexBaseFunded\n },\n cex: {\n avail: cexBaseAvail,\n req: cexMinBaseAlloc,\n funded: cexBaseFunded\n },\n transferable: transferableBaseAlloc,\n fees: {\n avail: dexBaseFeeAvail,\n req: dexBaseFeeReq,\n funded: baseFeesFunded\n },\n fundedAndBalanced: baseFundedAndBalanced,\n fundedAndNotBalanced: !baseFundedAndBalanced && baseAvail >= totalBaseReq && canRebalance\n },\n quote: {\n dex: {\n avail: dexQuoteAvail,\n req: dexMinQuoteAlloc,\n funded: dexQuoteFunded\n },\n cex: {\n avail: cexQuoteAvail,\n req: cexMinQuoteAlloc,\n funded: cexQuoteFunded\n },\n transferable: transferableQuoteAlloc,\n fees: {\n avail: dexQuoteFeeAvail,\n req: dexQuoteFeeReq,\n funded: quoteFeesFunded\n },\n fundedAndBalanced: quoteFundedAndBalanced,\n fundedAndNotBalanced: !quoteFundedAndBalanced && quoteAvail >= totalQuoteReq && canRebalance\n },\n fundedAndBalanced,\n fundedAndNotBalanced,\n starved: !fundedAndBalanced && !fundedAndNotBalanced\n }\n }\n}\n\nexport type RunningMMDisplayElements = {\n orderReportForm: PageElement\n dexBalancesRowTmpl: PageElement\n placementRowTmpl: PageElement\n placementAmtRowTmpl: PageElement\n}\n\nexport class RunningMarketMakerDisplay {\n div: PageElement\n page: Record\n mkt: BotMarket\n startTime: number\n ticker: any\n currentForm: PageElement\n forms: Forms\n latestEpoch?: EpochReport\n cexProblems?: CEXProblems\n orderReportFormEl: PageElement\n orderReportForm: Record\n displayedOrderReportFormSide: 'buys' | 'sells'\n dexBalancesRowTmpl: PageElement\n placementRowTmpl: PageElement\n placementAmtRowTmpl: PageElement\n\n constructor (div: PageElement, forms: Forms, elements: RunningMMDisplayElements, page: string) {\n this.div = div\n this.page = Doc.parseTemplate(div)\n this.orderReportFormEl = elements.orderReportForm\n this.orderReportForm = Doc.idDescendants(elements.orderReportForm)\n this.dexBalancesRowTmpl = elements.dexBalancesRowTmpl\n this.placementRowTmpl = elements.placementRowTmpl\n this.placementAmtRowTmpl = elements.placementAmtRowTmpl\n Doc.cleanTemplates(this.dexBalancesRowTmpl, this.placementRowTmpl, this.placementAmtRowTmpl)\n this.forms = forms\n Doc.bind(this.page.stopBttn, 'click', () => this.stop())\n Doc.bind(this.page.runLogsBttn, 'click', () => {\n const { mkt: { baseID, quoteID, host }, startTime } = this\n app().loadPage('mmlogs', { baseID, quoteID, host, startTime, returnPage: page })\n })\n Doc.bind(this.page.buyOrdersBttn, 'click', () => this.showOrderReport('buys'))\n Doc.bind(this.page.sellOrdersBttn, 'click', () => this.showOrderReport('sells'))\n }\n\n async stop () {\n const { page, mkt: { host, baseID, quoteID } } = this\n const loaded = app().loading(page.stopBttn)\n await MM.stopBot({ host, baseID: baseID, quoteID: quoteID })\n loaded()\n }\n\n async setMarket (host: string, baseID: number, quoteID: number) {\n const botStatus = app().mmStatus.bots.find(({ config: c }: MMBotStatus) => c.baseID === baseID && c.quoteID === quoteID && c.host === host)\n if (!botStatus) return\n const mkt = new BotMarket(botStatus.config)\n await mkt.initialize()\n this.setBotMarket(mkt)\n }\n\n async setBotMarket (mkt: BotMarket) {\n this.mkt = mkt\n const {\n page, div, mkt: {\n host, baseID, quoteID, baseFeeID, quoteFeeID, cexName, baseFeeSymbol,\n quoteFeeSymbol, baseFeeTicker, quoteFeeTicker, cfg, baseFactor, quoteFactor\n }\n } = this\n setMarketElements(div, baseID, quoteID, host)\n Doc.setVis(baseFeeID !== baseID, page.baseFeeReservesBox)\n Doc.setVis(quoteFeeID !== quoteID, page.quoteFeeReservesBox)\n Doc.setVis(Boolean(cexName), ...Doc.applySelector(div, '[data-cex-show]'))\n page.baseFeeLogo.src = Doc.logoPath(baseFeeSymbol)\n page.baseFeeTicker.textContent = baseFeeTicker\n page.quoteFeeLogo.src = Doc.logoPath(quoteFeeSymbol)\n page.quoteFeeTicker.textContent = quoteFeeTicker\n\n const basicCfg = cfg.basicMarketMakingConfig\n const gapStrategy = basicCfg?.gapStrategy ?? GapStrategyPercent\n let gapFactor = cfg.arbMarketMakingConfig?.profit ?? cfg.simpleArbConfig?.profitTrigger ?? 0\n if (basicCfg) {\n const buys = [...basicCfg.buyPlacements].sort((a: OrderPlacement, b: OrderPlacement) => a.gapFactor - b.gapFactor)\n const sells = [...basicCfg.sellPlacements].sort((a: OrderPlacement, b: OrderPlacement) => a.gapFactor - b.gapFactor)\n if (buys.length > 0) {\n if (sells.length > 0) {\n gapFactor = (buys[0].gapFactor + sells[0].gapFactor) / 2\n } else {\n gapFactor = buys[0].gapFactor\n }\n } else gapFactor = sells[0].gapFactor\n }\n Doc.hide(page.profitLabel, page.gapLabel, page.multiplierLabel, page.profitUnit, page.gapUnit, page.multiplierUnit)\n switch (gapStrategy) {\n case GapStrategyPercent:\n case GapStrategyPercentPlus:\n Doc.show(page.profitLabel, page.profitUnit)\n page.gapFactor.textContent = (gapFactor * 100).toFixed(2)\n break\n case GapStrategyMultiplier:\n Doc.show(page.multiplierLabel, page.multiplierUnit)\n page.gapFactor.textContent = (gapFactor * 100).toFixed(2)\n break\n default:\n page.gapFactor.textContent = Doc.formatFourSigFigs(gapFactor / OrderUtil.RateEncodingFactor * baseFactor / quoteFactor)\n }\n\n this.update()\n this.readBook()\n }\n\n handleBalanceNote (n: BalanceNote) {\n if (!this.mkt) return\n const { baseID, quoteID, baseFeeID, quoteFeeID } = this.mkt\n if (n.assetID !== baseID && n.assetID !== baseFeeID && n.assetID !== quoteID && n.assetID !== quoteFeeID) return\n this.update()\n }\n\n handleEpochReportNote (n: EpochReportNote) {\n if (!this.mkt) return\n const { baseID, quoteID, host } = this.mkt\n if (n.baseID !== baseID || n.quoteID !== quoteID || n.host !== host) return\n if (!n.report) return\n this.latestEpoch = n.report\n if (this.forms.currentForm === this.orderReportFormEl && this.forms.currentFormID === this.mkt.id) {\n const orderReport = this.displayedOrderReportFormSide === 'buys' ? n.report.buysReport : n.report.sellsReport\n if (orderReport) this.updateOrderReport(orderReport, this.displayedOrderReportFormSide, n.report.epochNum)\n else this.forms.close()\n }\n this.update()\n }\n\n handleCexProblemsNote (n: CEXProblemsNote) {\n if (!this.mkt) return\n const { baseID, quoteID, host } = this.mkt\n if (n.baseID !== baseID || n.quoteID !== quoteID || n.host !== host) return\n this.cexProblems = n.problems\n this.update()\n }\n\n setTicker () {\n this.page.runTime.textContent = Doc.hmsSince(this.startTime)\n }\n\n update () {\n const {\n div, page, mkt: {\n baseID, quoteID, baseFeeID, quoteFeeID, baseFactor, quoteFactor, baseFeeFactor,\n quoteFeeFactor, marketReport: { baseFiatRate, quoteFiatRate }\n }\n } = this\n // Get fresh stats\n const { botCfg: { cexName, basicMarketMakingConfig: bmmCfg }, runStats, latestEpoch, cexProblems } = this.mkt.status()\n this.latestEpoch = latestEpoch\n this.cexProblems = cexProblems\n\n Doc.hide(page.stats, page.cexRow, page.pendingDepositBox, page.pendingWithdrawalBox)\n\n if (!runStats) {\n if (this.ticker) {\n clearInterval(this.ticker)\n this.ticker = undefined\n }\n return\n } else if (!this.ticker) {\n this.startTime = runStats.startTime\n this.setTicker()\n this.ticker = setInterval(() => this.setTicker(), 1000)\n }\n\n Doc.show(page.stats)\n setSignedValue(runStats.profitLoss.profitRatio * 100, page.profit, page.profitSign, 2)\n setSignedValue(runStats.profitLoss.profit, page.profitLoss, page.plSign, 2)\n this.startTime = runStats.startTime\n\n const summedBalance = (b: BotBalance) => {\n if (!b) return 0\n return b.available + b.locked + b.pending + b.reserved\n }\n\n const dexBaseInv = summedBalance(runStats.dexBalances[baseID]) / baseFactor\n page.walletBaseInventory.textContent = Doc.formatFourSigFigs(dexBaseInv)\n page.walletBaseInvFiat.textContent = Doc.formatFourSigFigs(dexBaseInv * baseFiatRate, 2)\n const dexQuoteInv = summedBalance(runStats.dexBalances[quoteID]) / quoteFactor\n page.walletQuoteInventory.textContent = Doc.formatFourSigFigs(dexQuoteInv)\n page.walletQuoteInvFiat.textContent = Doc.formatFourSigFigs(dexQuoteInv * quoteFiatRate, 2)\n\n Doc.setVis(cexName, page.cexRow)\n if (cexName) {\n Doc.show(page.pendingDepositBox, page.pendingWithdrawalBox)\n setCexElements(div, cexName)\n const cexBaseInv = summedBalance(runStats.cexBalances[baseID]) / baseFactor\n page.cexBaseInventory.textContent = Doc.formatFourSigFigs(cexBaseInv)\n page.cexBaseInventoryFiat.textContent = Doc.formatFourSigFigs(cexBaseInv * baseFiatRate, 2)\n const cexQuoteInv = summedBalance(runStats.cexBalances[quoteID]) / quoteFactor\n page.cexQuoteInventory.textContent = Doc.formatFourSigFigs(cexQuoteInv)\n page.cexQuoteInventoryFiat.textContent = Doc.formatFourSigFigs(cexQuoteInv * quoteFiatRate, 2)\n }\n\n if (baseFeeID !== baseID) {\n const feeBalance = summedBalance(runStats.dexBalances[baseFeeID]) / baseFeeFactor\n page.baseFeeReserves.textContent = Doc.formatFourSigFigs(feeBalance)\n }\n if (quoteFeeID !== quoteID) {\n const feeBalance = summedBalance(runStats.dexBalances[quoteFeeID]) / quoteFeeFactor\n page.quoteFeeReserves.textContent = Doc.formatFourSigFigs(feeBalance)\n }\n\n page.pendingDeposits.textContent = String(Math.round(runStats.pendingDeposits))\n page.pendingWithdrawals.textContent = String(Math.round(runStats.pendingWithdrawals))\n page.completedMatches.textContent = String(Math.round(runStats.completedMatches))\n Doc.setVis(runStats.tradedUSD, page.tradedUSDBox)\n if (runStats.tradedUSD > 0) page.tradedUSD.textContent = Doc.formatFourSigFigs(runStats.tradedUSD)\n Doc.setVis(baseFiatRate, page.roundTripFeesBox)\n if (baseFiatRate) page.roundTripFeesUSD.textContent = Doc.formatFourSigFigs((runStats.feeGap?.roundTripFees / baseFactor * baseFiatRate) || 0)\n const basisPrice = app().conventionalRate(baseID, quoteID, runStats.feeGap?.basisPrice || 0)\n page.basisPrice.textContent = Doc.formatFourSigFigs(basisPrice)\n\n const displayFeeGap = !bmmCfg || bmmCfg.gapStrategy === GapStrategyAbsolutePlus || bmmCfg.gapStrategy === GapStrategyPercentPlus\n Doc.setVis(displayFeeGap, page.feeGapBox)\n if (displayFeeGap) {\n const feeGap = app().conventionalRate(baseID, quoteID, runStats.feeGap?.feeGap || 0)\n page.feeGap.textContent = Doc.formatFourSigFigs(feeGap)\n page.feeGapPct.textContent = (feeGap / basisPrice * 100 || 0).toFixed(2)\n }\n Doc.setVis(bmmCfg, page.gapStrategyBox)\n if (bmmCfg) page.gapStrategy.textContent = bmmCfg.gapStrategy\n\n const remoteGap = app().conventionalRate(baseID, quoteID, runStats.feeGap?.remoteGap || 0)\n Doc.setVis(remoteGap, page.remoteGapBox)\n if (remoteGap) {\n page.remoteGap.textContent = Doc.formatFourSigFigs(remoteGap)\n page.remoteGapPct.textContent = (remoteGap / basisPrice * 100 || 0).toFixed(2)\n }\n\n Doc.setVis(latestEpoch?.buysReport, page.buyOrdersReportBox)\n if (latestEpoch?.buysReport) {\n const allPlaced = allOrdersPlaced(latestEpoch.buysReport)\n Doc.setVis(allPlaced, page.buyOrdersSuccess)\n Doc.setVis(!allPlaced, page.buyOrdersFailed)\n }\n\n Doc.setVis(latestEpoch?.sellsReport, page.sellOrdersReportBox)\n if (latestEpoch?.sellsReport) {\n const allPlaced = allOrdersPlaced(latestEpoch.sellsReport)\n Doc.setVis(allPlaced, page.sellOrdersSuccess)\n Doc.setVis(!allPlaced, page.sellOrdersFailed)\n }\n\n const preOrderProblemMessages = botProblemMessages(latestEpoch?.preOrderProblems, this.mkt.cexName, this.mkt.host)\n const cexErrorMessages = cexProblemMessages(this.cexProblems)\n const allMessages = [...preOrderProblemMessages, ...cexErrorMessages]\n Doc.setVis(allMessages.length > 0, page.preOrderProblemsBox)\n Doc.empty(page.preOrderProblemsBox)\n for (const msg of allMessages) {\n const spanEl = document.createElement('span') as PageElement\n spanEl.textContent = `- ${msg}`\n page.preOrderProblemsBox.appendChild(spanEl)\n }\n }\n\n updateOrderReport (report: OrderReport, side: 'buys' | 'sells', epochNum: number) {\n const form = this.orderReportForm\n const sideTxt = side === 'buys' ? intl.prep(intl.ID_BUY) : intl.prep(intl.ID_SELL)\n form.orderReportTitle.textContent = intl.prep(intl.ID_ORDER_REPORT_TITLE, { side: sideTxt, epochNum: `${epochNum}` })\n\n Doc.setVis(report.error, form.orderReportError)\n Doc.setVis(!report.error, form.orderReportDetails)\n if (report.error) {\n const problemMessages = botProblemMessages(report.error, this.mkt.cexName, this.mkt.host)\n Doc.empty(form.orderReportError)\n for (const msg of problemMessages) {\n const spanEl = document.createElement('span') as PageElement\n spanEl.textContent = `- ${msg}`\n form.orderReportError.appendChild(spanEl)\n }\n return\n }\n\n Doc.empty(form.dexBalancesBody, form.placementsBody)\n const createRow = (assetID: number): [PageElement, number] => {\n const row = this.dexBalancesRowTmpl.cloneNode(true) as HTMLElement\n const rowTmpl = Doc.parseTemplate(row)\n const asset = app().assets[assetID]\n rowTmpl.asset.textContent = asset.symbol.toUpperCase()\n rowTmpl.assetLogo.src = Doc.logoPath(asset.symbol)\n const unitInfo = asset.unitInfo\n const available = report.availableDexBals[assetID] ? report.availableDexBals[assetID].available : 0\n const required = report.requiredDexBals[assetID] ? report.requiredDexBals[assetID] : 0\n const remaining = report.remainingDexBals[assetID] ? report.remainingDexBals[assetID] : 0\n const pending = report.availableDexBals[assetID] ? report.availableDexBals[assetID].pending : 0\n const locked = report.availableDexBals[assetID] ? report.availableDexBals[assetID].locked : 0\n const used = report.usedDexBals[assetID] ? report.usedDexBals[assetID] : 0\n rowTmpl.available.textContent = Doc.formatCoinValue(available, unitInfo)\n rowTmpl.locked.textContent = Doc.formatCoinValue(locked, unitInfo)\n rowTmpl.required.textContent = Doc.formatCoinValue(required, unitInfo)\n rowTmpl.remaining.textContent = Doc.formatCoinValue(remaining, unitInfo)\n rowTmpl.pending.textContent = Doc.formatCoinValue(pending, unitInfo)\n rowTmpl.used.textContent = Doc.formatCoinValue(used, unitInfo)\n const deficiency = safeSub(required, available)\n rowTmpl.deficiency.textContent = Doc.formatCoinValue(deficiency, unitInfo)\n if (deficiency > 0) rowTmpl.deficiency.classList.add('text-warning')\n const deficiencyWithPending = safeSub(deficiency, pending)\n rowTmpl.deficiencyWithPending.textContent = Doc.formatCoinValue(deficiencyWithPending, unitInfo)\n if (deficiencyWithPending > 0) rowTmpl.deficiencyWithPending.classList.add('text-warning')\n return [row, deficiency]\n }\n const setDeficiencyVisibility = (deficiency: boolean, rows: HTMLElement[]) => {\n Doc.setVis(deficiency, form.dexDeficiencyHeader, form.dexDeficiencyWithPendingHeader)\n for (const row of rows) {\n const rowTmpl = Doc.parseTemplate(row)\n Doc.setVis(deficiency, rowTmpl.deficiency, rowTmpl.deficiencyWithPending)\n }\n }\n const assetIDs = [this.mkt.baseID, this.mkt.quoteID]\n if (!assetIDs.includes(this.mkt.baseFeeID)) assetIDs.push(this.mkt.baseFeeID)\n if (!assetIDs.includes(this.mkt.quoteFeeID)) assetIDs.push(this.mkt.quoteFeeID)\n let totalDeficiency = 0\n const rows : PageElement[] = []\n for (const assetID of assetIDs) {\n const [row, deficiency] = createRow(assetID)\n totalDeficiency += deficiency\n form.dexBalancesBody.appendChild(row)\n rows.push(row)\n }\n setDeficiencyVisibility(totalDeficiency > 0, rows)\n\n Doc.setVis(this.mkt.cexName, form.cexSection, form.counterTradeRateHeader, form.requiredCEXHeader, form.usedCEXHeader)\n let cexAsset: SupportedAsset\n if (this.mkt.cexName) {\n const cexDisplayInfo = CEXDisplayInfos[this.mkt.cexName]\n if (cexDisplayInfo) {\n form.cexLogo.src = cexDisplayInfo.logo\n form.cexBalancesTitle.textContent = intl.prep(intl.ID_CEX_BALANCES, { cexName: cexDisplayInfo.name })\n } else {\n console.error(`CEXDisplayInfo not found for ${this.mkt.cexName}`)\n }\n const cexAssetID = side === 'buys' ? this.mkt.baseID : this.mkt.quoteID\n cexAsset = app().assets[cexAssetID]\n form.cexAsset.textContent = cexAsset.symbol.toUpperCase()\n form.cexAssetLogo.src = Doc.logoPath(cexAsset.symbol)\n const availableCexBal = report.availableCexBal ? report.availableCexBal.available : 0\n const requiredCexBal = report.requiredCexBal ? report.requiredCexBal : 0\n const remainingCexBal = report.remainingCexBal ? report.remainingCexBal : 0\n const pendingCexBal = report.availableCexBal ? report.availableCexBal.pending : 0\n const reservedCexBal = report.availableCexBal ? report.availableCexBal.reserved : 0\n const usedCexBal = report.usedCexBal ? report.usedCexBal : 0\n const deficiencyCexBal = safeSub(requiredCexBal, availableCexBal)\n const deficiencyWithPendingCexBal = safeSub(deficiencyCexBal, pendingCexBal)\n form.cexAvailable.textContent = Doc.formatCoinValue(availableCexBal, cexAsset.unitInfo)\n form.cexLocked.textContent = Doc.formatCoinValue(reservedCexBal, cexAsset.unitInfo)\n form.cexRequired.textContent = Doc.formatCoinValue(requiredCexBal, cexAsset.unitInfo)\n form.cexRemaining.textContent = Doc.formatCoinValue(remainingCexBal, cexAsset.unitInfo)\n form.cexPending.textContent = Doc.formatCoinValue(pendingCexBal, cexAsset.unitInfo)\n form.cexUsed.textContent = Doc.formatCoinValue(usedCexBal, cexAsset.unitInfo)\n const deficient = deficiencyCexBal > 0\n Doc.setVis(deficient, form.cexDeficiencyHeader, form.cexDeficiencyWithPendingHeader,\n form.cexDeficiency, form.cexDeficiencyWithPending)\n if (deficient) {\n form.cexDeficiency.textContent = Doc.formatCoinValue(deficiencyCexBal, cexAsset.unitInfo)\n form.cexDeficiencyWithPending.textContent = Doc.formatCoinValue(deficiencyWithPendingCexBal, cexAsset.unitInfo)\n if (deficiencyWithPendingCexBal > 0) form.cexDeficiencyWithPending.classList.add('text-warning')\n else form.cexDeficiencyWithPending.classList.remove('text-warning')\n }\n }\n\n let anyErrors = false\n for (const placement of report.placements) if (placement.error) { anyErrors = true; break }\n Doc.setVis(anyErrors, form.errorHeader)\n const createPlacementRow = (placement: TradePlacement, priority: number): PageElement => {\n const row = this.placementRowTmpl.cloneNode(true) as HTMLElement\n const rowTmpl = Doc.parseTemplate(row)\n const baseUI = app().assets[this.mkt.baseID].unitInfo\n const quoteUI = app().assets[this.mkt.quoteID].unitInfo\n rowTmpl.priority.textContent = String(priority)\n rowTmpl.rate.textContent = Doc.formatRateFullPrecision(placement.rate, baseUI, quoteUI, this.mkt.rateStep)\n rowTmpl.lots.textContent = String(placement.lots)\n rowTmpl.standingLots.textContent = String(placement.standingLots)\n rowTmpl.orderedLots.textContent = String(placement.orderedLots)\n if (placement.standingLots + placement.orderedLots < placement.lots) {\n rowTmpl.lots.classList.add('text-warning')\n rowTmpl.standingLots.classList.add('text-warning')\n rowTmpl.orderedLots.classList.add('text-warning')\n }\n Doc.setVis(placement.counterTradeRate > 0, rowTmpl.counterTradeRate)\n rowTmpl.counterTradeRate.textContent = Doc.formatRateFullPrecision(placement.counterTradeRate, baseUI, quoteUI, this.mkt.rateStep)\n for (const assetID of assetIDs) {\n const asset = app().assets[assetID]\n const unitInfo = asset.unitInfo\n const requiredAmt = placement.requiredDex[assetID] ? placement.requiredDex[assetID] : 0\n const usedAmt = placement.usedDex[assetID] ? placement.usedDex[assetID] : 0\n const requiredRow = this.placementAmtRowTmpl.cloneNode(true) as HTMLElement\n const requiredRowTmpl = Doc.parseTemplate(requiredRow)\n const usedRow = this.placementAmtRowTmpl.cloneNode(true) as HTMLElement\n const usedRowTmpl = Doc.parseTemplate(usedRow)\n requiredRowTmpl.amt.textContent = Doc.formatCoinValue(requiredAmt, unitInfo)\n requiredRowTmpl.assetLogo.src = Doc.logoPath(asset.symbol)\n requiredRowTmpl.assetSymbol.textContent = asset.symbol.toUpperCase()\n usedRowTmpl.amt.textContent = Doc.formatCoinValue(usedAmt, unitInfo)\n usedRowTmpl.assetLogo.src = Doc.logoPath(asset.symbol)\n usedRowTmpl.assetSymbol.textContent = asset.symbol.toUpperCase()\n rowTmpl.requiredDEX.appendChild(requiredRow)\n rowTmpl.usedDEX.appendChild(usedRow)\n }\n Doc.setVis(this.mkt.cexName, rowTmpl.requiredCEX, rowTmpl.usedCEX)\n if (this.mkt.cexName) {\n const requiredAmt = Doc.formatCoinValue(placement.requiredCex, cexAsset.unitInfo)\n rowTmpl.requiredCEX.textContent = `${requiredAmt} ${cexAsset.symbol.toUpperCase()}`\n const usedAmt = Doc.formatCoinValue(placement.usedCex, cexAsset.unitInfo)\n rowTmpl.usedCEX.textContent = `${usedAmt} ${cexAsset.symbol.toUpperCase()}`\n }\n Doc.setVis(anyErrors, rowTmpl.error)\n if (placement.error) {\n const errMessages = botProblemMessages(placement.error, this.mkt.cexName, this.mkt.host)\n rowTmpl.error.textContent = errMessages.join('\\n')\n }\n return row\n }\n for (let i = 0; i < report.placements.length; i++) {\n form.placementsBody.appendChild(createPlacementRow(report.placements[i], i + 1))\n }\n }\n\n showOrderReport (side: 'buys' | 'sells') {\n if (!this.latestEpoch) return\n const report = side === 'buys' ? this.latestEpoch.buysReport : this.latestEpoch.sellsReport\n if (!report) return\n this.updateOrderReport(report, side, this.latestEpoch.epochNum)\n this.displayedOrderReportFormSide = side\n this.forms.show(this.orderReportFormEl, this.mkt.id)\n }\n\n readBook () {\n if (!this.mkt) return\n const { page, mkt: { host, mktID } } = this\n const orders = app().exchanges[host].markets[mktID].orders || []\n page.nBookedOrders.textContent = String(orders.filter((ord: Order) => ord.status === OrderUtil.StatusBooked).length)\n }\n}\n\nfunction allOrdersPlaced (report: OrderReport) {\n if (report.error) return false\n for (let i = 0; i < report.placements.length; i++) {\n const placement = report.placements[i]\n if (placement.orderedLots + placement.standingLots < placement.lots) return false\n if (placement.error) return false\n }\n return true\n}\n\nfunction setSignedValue (v: number, vEl: PageElement, signEl: PageElement, maxDecimals?: number) {\n vEl.textContent = Doc.formatFourSigFigs(v, maxDecimals)\n signEl.classList.toggle('ico-plus', v > 0)\n signEl.classList.toggle('text-good', v > 0)\n // signEl.classList.toggle('ico-minus', v < 0)\n}\n\nexport function feesAndCommit (\n baseID: number, quoteID: number, baseFees: LotFeeRange, quoteFees: LotFeeRange,\n lotSize: number, baseLots: number, quoteLots: number, baseFeeID: number, quoteFeeID: number,\n baseIsAccountLocker: boolean, quoteIsAccountLocker: boolean, baseOrderReservesFactor: number,\n quoteOrderReservesFactor: number\n) {\n const quoteLot = calculateQuoteLot(lotSize, baseID, quoteID)\n const [cexBaseLots, cexQuoteLots] = [quoteLots, baseLots]\n const commit = {\n dex: {\n base: {\n lots: baseLots,\n val: baseLots * lotSize\n },\n quote: {\n lots: quoteLots,\n val: quoteLots * quoteLot\n }\n },\n cex: {\n base: {\n lots: cexBaseLots,\n val: cexBaseLots * lotSize\n },\n quote: {\n lots: cexQuoteLots,\n val: cexQuoteLots * quoteLot\n }\n }\n }\n\n let baseTokenFeesPerSwap = 0\n let baseRedeemReservesPerLot = 0\n if (baseID !== baseFeeID) { // token\n baseTokenFeesPerSwap += baseFees.estimated.swap\n if (baseFeeID === quoteFeeID) baseTokenFeesPerSwap += quoteFees.estimated.redeem\n }\n let baseBookingFeesPerLot = baseFees.max.swap\n if (baseID === quoteFeeID) baseBookingFeesPerLot += quoteFees.max.redeem\n if (baseIsAccountLocker) {\n baseBookingFeesPerLot += baseFees.max.refund\n if (!quoteIsAccountLocker && baseFeeID !== quoteFeeID) baseRedeemReservesPerLot = baseFees.max.redeem\n }\n\n let quoteTokenFeesPerSwap = 0\n let quoteRedeemReservesPerLot = 0\n if (quoteID !== quoteFeeID) {\n quoteTokenFeesPerSwap += quoteFees.estimated.swap\n if (quoteFeeID === baseFeeID) quoteTokenFeesPerSwap += baseFees.estimated.redeem\n }\n let quoteBookingFeesPerLot = quoteFees.max.swap\n if (quoteID === baseFeeID) quoteBookingFeesPerLot += baseFees.max.redeem\n if (quoteIsAccountLocker) {\n quoteBookingFeesPerLot += quoteFees.max.refund\n if (!baseIsAccountLocker && quoteFeeID !== baseFeeID) quoteRedeemReservesPerLot = quoteFees.max.redeem\n }\n\n const baseReservesFactor = 1 + baseOrderReservesFactor\n const quoteReservesFactor = 1 + quoteOrderReservesFactor\n\n const baseBookingFees = (baseBookingFeesPerLot * baseLots) * baseReservesFactor\n const baseRedeemFees = (baseRedeemReservesPerLot * quoteLots) * quoteReservesFactor\n const quoteBookingFees = (quoteBookingFeesPerLot * quoteLots) * quoteReservesFactor\n const quoteRedeemFees = (quoteRedeemReservesPerLot * baseLots) * baseReservesFactor\n\n const fees: BookingFees = {\n base: {\n ...baseFees,\n bookingFeesPerLot: baseBookingFeesPerLot,\n bookingFeesPerCounterLot: baseRedeemReservesPerLot,\n bookingFees: baseBookingFees + baseRedeemFees,\n swapReservesFactor: baseReservesFactor,\n redeemReservesFactor: quoteReservesFactor,\n tokenFeesPerSwap: baseTokenFeesPerSwap\n },\n quote: {\n ...quoteFees,\n bookingFeesPerLot: quoteBookingFeesPerLot,\n bookingFeesPerCounterLot: quoteRedeemReservesPerLot,\n bookingFees: quoteBookingFees + quoteRedeemFees,\n swapReservesFactor: quoteReservesFactor,\n redeemReservesFactor: baseReservesFactor,\n tokenFeesPerSwap: quoteTokenFeesPerSwap\n }\n }\n\n return { commit, fees }\n}\n\nfunction botProblemMessages (problems: BotProblems | undefined, cexName: string, dexHost: string): string[] {\n if (!problems) return []\n const msgs: string[] = []\n\n if (problems.walletNotSynced) {\n for (const [assetID, notSynced] of Object.entries(problems.walletNotSynced)) {\n if (notSynced) {\n msgs.push(intl.prep(intl.ID_WALLET_NOT_SYNCED, { assetSymbol: app().assets[Number(assetID)].symbol.toUpperCase() }))\n }\n }\n }\n\n if (problems.noWalletPeers) {\n for (const [assetID, noPeers] of Object.entries(problems.noWalletPeers)) {\n if (noPeers) {\n msgs.push(intl.prep(intl.ID_WALLET_NO_PEERS, { assetSymbol: app().assets[Number(assetID)].symbol.toUpperCase() }))\n }\n }\n }\n\n if (problems.accountSuspended) {\n msgs.push(intl.prep(intl.ID_ACCOUNT_SUSPENDED, { dexHost: dexHost }))\n }\n\n if (problems.userLimitTooLow) {\n msgs.push(intl.prep(intl.ID_USER_LIMIT_TOO_LOW, { dexHost: dexHost }))\n }\n\n if (problems.noPriceSource) {\n msgs.push(intl.prep(intl.ID_NO_PRICE_SOURCE))\n }\n\n if (problems.cexOrderbookUnsynced) {\n msgs.push(intl.prep(intl.ID_CEX_ORDERBOOK_UNSYNCED, { cexName: cexName }))\n }\n\n if (problems.causesSelfMatch) {\n msgs.push(intl.prep(intl.ID_CAUSES_SELF_MATCH))\n }\n\n return msgs\n}\n\nfunction cexProblemMessages (problems: CEXProblems | undefined): string[] {\n if (!problems) return []\n const msgs: string[] = []\n if (problems.depositErr) {\n for (const [assetID, depositErr] of Object.entries(problems.depositErr)) {\n msgs.push(intl.prep(intl.ID_DEPOSIT_ERROR,\n {\n assetSymbol: app().assets[Number(assetID)].symbol.toUpperCase(),\n time: new Date(depositErr.stamp * 1000).toLocaleString(),\n error: depositErr.error\n }))\n }\n }\n if (problems.withdrawErr) {\n for (const [assetID, withdrawErr] of Object.entries(problems.withdrawErr)) {\n msgs.push(intl.prep(intl.ID_WITHDRAW_ERROR,\n {\n assetSymbol: app().assets[Number(assetID)].symbol.toUpperCase(),\n time: new Date(withdrawErr.stamp * 1000).toLocaleString(),\n error: withdrawErr.error\n }))\n }\n }\n if (problems.tradeErr) {\n msgs.push(intl.prep(intl.ID_CEX_TRADE_ERROR,\n {\n time: new Date(problems.tradeErr.stamp * 1000).toLocaleString(),\n error: problems.tradeErr.error\n }))\n }\n return msgs\n}\n\nfunction safeSub (a: number, b: number) {\n return a - b > 0 ? a - b : 0\n}\n\nwindow.mmstatus = function () : Promise {\n return MM.status()\n}\n","import Doc, { Animation } from './doc'\nimport { postJSON } from './http'\nimport State from './state'\nimport * as intl from './locales'\nimport { Wave } from './charts'\nimport {\n bondReserveMultiplier,\n perTierBaseParcelLimit,\n parcelLimitScoreMultiplier,\n strongTier\n} from './account'\nimport {\n app,\n SupportedAsset,\n PageElement,\n WalletDefinition,\n ConfigOption,\n Exchange,\n Market,\n BondAsset,\n WalletState,\n BalanceNote,\n Order,\n XYRange,\n WalletStateNote,\n WalletSyncNote,\n WalletInfo,\n Token,\n WalletCreationNote,\n CoreNote,\n PrepaidBondID\n} from './registry'\nimport { XYRangeHandler } from './opts'\nimport { CoinExplorers } from './coinexplorers'\nimport { MM, setCexElements } from './mmutil'\n\ninterface ConfigOptionInput extends HTMLInputElement {\n configOpt: ConfigOption\n}\n\ninterface ProgressPoint {\n stamp: number\n progress: number\n}\n\ninterface CurrentAsset {\n asset: SupportedAsset\n parentAsset?: SupportedAsset\n winfo: WalletInfo | Token\n // selectedDef is used in a strange way for tokens. If a token's parent wallet\n // already exists, then selectedDef is going to be the Token.definition.\n // BUT, if the token's parent wallet doesn't exist yet, the NewWalletForm\n // operates in a combined configuration mode, and the selectedDef will be the\n // currently selected parent asset definition. There is no loss of info\n // in such a case, because the token wallet only has one definition.\n selectedDef: WalletDefinition\n}\n\ninterface WalletConfig {\n assetID: number\n config: Record\n walletType: string\n}\n\ninterface FormsConfig {\n closed?: (closedForm: PageElement | undefined) => void\n}\n\nexport class Forms {\n formsDiv: PageElement\n currentForm: PageElement | undefined\n currentFormID: string | undefined\n keyup: (e: KeyboardEvent) => void\n closed?: (closedForm: PageElement | undefined) => void\n\n constructor (formsDiv: PageElement, cfg?: FormsConfig) {\n this.formsDiv = formsDiv\n this.closed = cfg?.closed\n\n formsDiv.querySelectorAll('.form-closer').forEach(el => {\n Doc.bind(el, 'click', () => { this.close() })\n })\n\n Doc.bind(formsDiv, 'mousedown', (e: MouseEvent) => {\n if (!this.currentForm) return\n if (!Doc.mouseInElement(e, this.currentForm)) { this.close() }\n })\n\n this.keyup = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n this.close()\n }\n }\n Doc.bind(document, 'keyup', this.keyup)\n }\n\n /* showForm shows a modal form with a little animation. */\n async show (form: HTMLElement, id?: string): Promise {\n this.currentForm = form\n this.currentFormID = id\n Doc.hide(...Array.from(this.formsDiv.children))\n form.style.right = '10000px'\n Doc.show(this.formsDiv, form)\n const shift = (this.formsDiv.offsetWidth + form.offsetWidth) / 2\n await Doc.animate(animationLength, progress => {\n form.style.right = `${(1 - progress) * shift}px`\n }, 'easeOutHard')\n form.style.right = '0'\n }\n\n close (): void {\n Doc.hide(this.formsDiv)\n const closedForm = this.currentForm\n this.currentForm = undefined\n this.currentFormID = undefined\n if (this.closed) this.closed(closedForm)\n }\n\n exit () {\n Doc.unbind(document, 'keyup', this.keyup)\n }\n}\n\n/*\n * NewWalletForm should be used with the \"newWalletForm\" template. The enclosing\n *
element should be the first argument of the constructor.\n */\nexport class NewWalletForm {\n page: Record\n form: HTMLElement\n success: (assetID: number) => void\n current: CurrentAsset\n subform: WalletConfigForm\n walletCfgGuide: PageElement\n parentSyncer: null | ((w: WalletState) => void)\n createUpdater: null | ((note: WalletCreationNote) => void)\n\n constructor (form: HTMLElement, success: (assetID: number) => void, backFunc?: () => void) {\n this.form = form\n this.success = success\n const page = this.page = Doc.parseTemplate(form)\n\n if (backFunc) {\n Doc.show(page.goBack)\n Doc.bind(page.goBack, 'click', () => { backFunc() })\n }\n\n Doc.empty(page.walletTabTmpl)\n page.walletTabTmpl.removeAttribute('id')\n\n // WalletConfigForm will set the global app variable.\n this.subform = new WalletConfigForm(page.walletSettings, true)\n\n this.walletCfgGuide = Doc.tmplElement(form, 'walletCfgGuide')\n\n bind(form, page.submitAdd, () => this.submit())\n bind(form, page.oneBttn, () => this.submit())\n\n app().registerNoteFeeder({\n walletstate: (note: WalletStateNote) => { this.reportWalletState(note.wallet) },\n walletsync: (note: WalletSyncNote) => { if (this.parentSyncer) this.parentSyncer(app().walletMap[note.assetID]) },\n createwallet: (note: WalletCreationNote) => { this.reportCreationUpdate(note) }\n })\n }\n\n /*\n * reportWalletState should be called when a 'walletstate' notification is\n * received.\n * TODO: Let form classes register for notifications.\n */\n reportWalletState (w: WalletState): void {\n if (this.parentSyncer) this.parentSyncer(w)\n }\n\n /*\n * reportWalletState should be called when a 'createwallet' notification is\n * received.\n */\n reportCreationUpdate (note: WalletCreationNote) {\n if (this.createUpdater) this.createUpdater(note)\n }\n\n async createWallet (assetID: number, walletType: string, parentForm?: WalletConfig) {\n const createForm = {\n assetID: assetID,\n pass: this.page.newWalletPass.value || '',\n config: this.subform.map(assetID),\n walletType: walletType,\n parentForm: parentForm\n }\n\n const ani = new Wave(this.form, { backgroundColor: true })\n const res = await postJSON('/api/newwallet', createForm)\n ani.stop()\n return res\n }\n\n async submit () {\n const page = this.page\n const newWalletPass = page.newWalletPass as HTMLInputElement\n Doc.hide(page.newWalletErr)\n\n const { asset, parentAsset } = this.current\n const selectedDef = this.current.selectedDef\n let parentForm\n let walletType = selectedDef.type\n if (parentAsset) {\n walletType = (asset.token as Token).definition.type\n parentForm = {\n assetID: parentAsset.id,\n config: this.subform.map(parentAsset.id),\n walletType: selectedDef.type\n }\n }\n // Register the selected asset.\n const res = await this.createWallet(asset.id, walletType, parentForm)\n if (!app().checkResponse(res)) {\n this.setError(res.msg)\n return\n }\n newWalletPass.value = ''\n if (parentAsset) await this.runParentSync()\n else this.success(this.current.asset.id)\n }\n\n /*\n * runParentSync shows a syncing sub-dialog that tracks the parent asset's\n * syncProgress and informs the user that the token wallet will be created\n * after sync is complete.\n */\n async runParentSync () {\n const { page, current: { parentAsset, asset } } = this\n if (!parentAsset) return\n\n page.parentSyncPct.textContent = '0'\n page.parentName.textContent = parentAsset.name\n page.parentLogo.src = Doc.logoPath(parentAsset.symbol)\n page.childName.textContent = asset.name\n page.childLogo.src = Doc.logoPath(asset.symbol)\n Doc.hide(page.mainForm)\n Doc.show(page.parentSyncing)\n\n try {\n await this.syncParent(parentAsset)\n this.success(this.current.asset.id)\n } catch (error) {\n this.setError(error.message || error)\n }\n Doc.show(page.mainForm)\n Doc.hide(page.parentSyncing)\n }\n\n /*\n * syncParent monitors the sync progress of a token's parent asset, generating\n * an Error if the token wallet creation does not complete successfully.\n */\n syncParent (parentAsset: SupportedAsset): Promise {\n const { page, current: { asset } } = this\n return new Promise((resolve, reject) => {\n // First, check if it's already synced.\n const w = app().assets[parentAsset.id].wallet\n if (w && w.synced) return resolve()\n // Not synced, so create a syncer to update the parent sync pane.\n this.parentSyncer = (w: WalletState) => {\n if (w.assetID !== parentAsset.id) return\n page.parentSyncPct.textContent = (w.syncProgress * 100).toFixed(1)\n }\n // Handle the async result.\n this.createUpdater = (note: WalletCreationNote) => {\n if (note.assetID !== asset.id) return\n switch (note.topic) {\n case 'QueuedCreationFailed':\n reject(new Error(`${note.subject}: ${note.details}`))\n break\n case 'QueuedCreationSuccess':\n resolve()\n break\n default:\n return\n }\n this.parentSyncer = null\n this.createUpdater = null\n }\n })\n }\n\n /* setAsset sets the current asset of the NewWalletForm */\n async setAsset (assetID: number) {\n if (!this.parseAsset(assetID)) return // nothing to change\n const page = this.page\n const tabs = page.walletTypeTabs\n const { winfo, asset, parentAsset } = this.current\n page.assetName.textContent = winfo.name\n page.newWalletPass.value = ''\n\n Doc.empty(tabs)\n Doc.hide(tabs, page.newWalletErr, page.tokenMsgBox)\n this.page.assetLogo.src = Doc.logoPath(asset.symbol)\n if (parentAsset) {\n page.tokenParentLogo.src = Doc.logoPath(parentAsset.symbol)\n page.tokenParentName.textContent = parentAsset.name\n Doc.show(page.tokenMsgBox)\n }\n\n const pinfo = parentAsset ? parentAsset.info : null\n const walletDefs = pinfo ? pinfo.availablewallets : (winfo as WalletInfo).availablewallets ? (winfo as WalletInfo).availablewallets : [(winfo as Token).definition]\n\n if (walletDefs.length > 1) {\n Doc.show(tabs)\n for (const wDef of walletDefs) {\n const tab = page.walletTabTmpl.cloneNode(true) as HTMLElement\n tab.dataset.tooltip = wDef.description\n tab.textContent = wDef.tab\n tabs.appendChild(tab)\n Doc.bind(tab, 'click', () => {\n for (const t of Doc.kids(tabs)) t.classList.remove('selected')\n tab.classList.add('selected')\n this.update(wDef)\n })\n }\n app().bindTooltips(tabs)\n const first = tabs.firstChild as HTMLElement\n first.classList.add('selected')\n }\n\n await this.update(this.current.selectedDef)\n if (asset.walletCreationPending) await this.runParentSync()\n }\n\n /*\n * parseAsset parses the current data for the asset ID.\n */\n parseAsset (assetID: number) {\n if (this.current && this.current.asset.id === assetID) return false\n const asset = app().assets[assetID]\n const token = asset.token\n if (!token) {\n if (!asset.info) throw Error('this non-token asset has no wallet info!')\n this.current = { asset, winfo: asset.info, selectedDef: asset.info.availablewallets[0] }\n return true\n }\n const parentAsset = app().user.assets[token.parentID]\n if (parentAsset.wallet) {\n // If the parent asset already has a wallet, there's no need to configure\n // the parent too. Just configure the token.\n this.current = { asset, winfo: token, selectedDef: token.definition }\n return true\n }\n if (!parentAsset.info) throw Error('this parent has no wallet info!')\n this.current = { asset, parentAsset, winfo: token, selectedDef: parentAsset.info.availablewallets[0] }\n return true\n }\n\n async update (walletDef: WalletDefinition) {\n const page = this.page\n this.current.selectedDef = walletDef\n Doc.hide(page.walletPassAndSubmitBttn, page.oneBttnBox, page.newWalletPassBox)\n const guideLink = walletDef.guidelink\n const configOpts = walletDef.configopts || []\n // If a config represents a wallet's birthday, we update the default\n // selection to the current date if this installation of the client\n // generated a seed.\n configOpts.map((opt) => {\n if (opt.isBirthdayConfig && app().seedGenTime > 0) {\n opt.default = toUnixDate(new Date())\n }\n return opt\n })\n // Either this is a walletDef for a token's uncreated parent asset, or this\n // is the definition for the token.\n let containsRequired = false\n for (const opt of configOpts) {\n if (opt.required) {\n containsRequired = true\n break\n }\n }\n const { asset, parentAsset, winfo } = this.current\n const displayCreateBtn = walletDef.seeded || Boolean(asset.token)\n if (displayCreateBtn && !containsRequired) {\n Doc.hide(page.walletSettingsHeader)\n Doc.show(page.oneBttnBox)\n } else if (displayCreateBtn) {\n Doc.show(page.walletPassAndSubmitBttn, page.walletSettingsHeader)\n page.newWalletPass.value = ''\n page.submitAdd.textContent = intl.prep(intl.ID_CREATE)\n } else {\n Doc.show(page.walletPassAndSubmitBttn, page.walletSettingsHeader)\n if (!walletDef.noauth) Doc.show(page.newWalletPassBox)\n page.submitAdd.textContent = intl.prep(intl.ID_ADD)\n }\n\n if (parentAsset) {\n const parentAndTokenOpts = JSON.parse(JSON.stringify(configOpts))\n // Add the regAsset field to the configurations so proper logos will be displayed\n // next to them, and map can filter them out. The opts are copied here so the originals\n // do not have the regAsset field added to them.\n for (const opt of parentAndTokenOpts) opt.regAsset = parentAsset.id\n const tokenOpts = (winfo as Token).definition.configopts || []\n if (tokenOpts.length > 0) {\n const tokenOptsCopy = JSON.parse(JSON.stringify(tokenOpts))\n for (const opt of tokenOptsCopy) opt.regAsset = asset.id\n parentAndTokenOpts.push(...tokenOptsCopy)\n }\n this.subform.update(asset.id, parentAndTokenOpts, false)\n } else this.subform.update(asset.id, configOpts, false)\n this.setGuideLink(guideLink)\n\n // A seeded or token wallet is internal to Bison Wallet and as such does\n // not have an external config file to select.\n if (walletDef.seeded || Boolean(this.current.asset.token)) Doc.hide(this.subform.fileSelector)\n else Doc.show(this.subform.fileSelector)\n\n await this.loadDefaults()\n }\n\n setGuideLink (guideLink: string) {\n Doc.hide(this.walletCfgGuide)\n if (guideLink !== '') {\n this.walletCfgGuide.href = guideLink\n Doc.show(this.walletCfgGuide)\n }\n }\n\n /* setError sets and shows the in-form error message. */\n async setError (errMsg: string) {\n this.page.newWalletErr.textContent = errMsg\n Doc.show(this.page.newWalletErr)\n }\n\n /*\n * loadDefaults attempts to load the ExchangeWallet configuration from the\n * default wallet config path on the server and will auto-fill the page on\n * the subform if settings are found.\n */\n async loadDefaults () {\n // No default config files for seeded assets right now.\n const { asset, parentAsset, selectedDef } = this.current\n if (!selectedDef.configpath) return\n let configID = asset.id\n if (parentAsset) {\n if (selectedDef.seeded) return\n configID = parentAsset.id\n }\n const loaded = app().loading(this.form)\n const res = await postJSON('/api/defaultwalletcfg', {\n assetID: configID,\n type: selectedDef.type\n })\n loaded()\n if (!app().checkResponse(res)) {\n this.setError(res.msg)\n return\n }\n this.subform.setLoadedConfig(res.config)\n }\n}\n\nlet dynamicInputCounter = 0\n\n/*\n * WalletConfigForm is a dynamically generated sub-form for setting\n * asset-specific wallet configuration options.\n*/\nexport class WalletConfigForm {\n page: Record\n form: HTMLElement\n configElements: [ConfigOption, HTMLElement][]\n configOpts: ConfigOption[]\n sectionize: boolean\n allSettings: PageElement\n dynamicOpts: PageElement\n textInputTmpl: PageElement\n dateInputTmpl: PageElement\n checkboxTmpl: PageElement\n repeatableTmpl: PageElement\n fileSelector: PageElement\n fileInput: PageElement\n errMsg: PageElement\n showOther: PageElement\n showIcon: PageElement\n hideIcon: PageElement\n showHideMsg: PageElement\n otherSettings: PageElement\n loadedSettingsMsg: PageElement\n loadedSettings: PageElement\n defaultSettingsMsg: PageElement\n defaultSettings: PageElement\n assetHasActiveOrders: boolean\n assetID: number\n\n constructor (form: HTMLElement, sectionize: boolean) {\n this.page = Doc.idDescendants(form)\n this.form = form\n // A configElement is a div containing an input and its label.\n this.configElements = []\n // configOpts is the wallet options provided by core.\n this.configOpts = []\n this.sectionize = sectionize\n\n // Get template elements\n this.allSettings = Doc.tmplElement(form, 'allSettings')\n this.dynamicOpts = Doc.tmplElement(form, 'dynamicOpts')\n this.textInputTmpl = Doc.tmplElement(form, 'textInput')\n this.textInputTmpl.remove()\n this.dateInputTmpl = Doc.tmplElement(form, 'dateInput')\n this.dateInputTmpl.remove()\n this.checkboxTmpl = Doc.tmplElement(form, 'checkbox')\n this.checkboxTmpl.remove()\n this.repeatableTmpl = Doc.tmplElement(form, 'repeatableInput')\n this.repeatableTmpl.remove()\n this.fileSelector = Doc.tmplElement(form, 'fileSelector')\n this.fileInput = Doc.tmplElement(form, 'fileInput')\n this.errMsg = Doc.tmplElement(form, 'errMsg')\n this.showOther = Doc.tmplElement(form, 'showOther')\n this.showIcon = Doc.tmplElement(form, 'showIcon')\n this.hideIcon = Doc.tmplElement(form, 'hideIcon')\n this.showHideMsg = Doc.tmplElement(form, 'showHideMsg')\n this.otherSettings = Doc.tmplElement(form, 'otherSettings')\n this.loadedSettingsMsg = Doc.tmplElement(form, 'loadedSettingsMsg')\n this.loadedSettings = Doc.tmplElement(form, 'loadedSettings')\n this.defaultSettingsMsg = Doc.tmplElement(form, 'defaultSettingsMsg')\n this.defaultSettings = Doc.tmplElement(form, 'defaultSettings')\n\n if (!sectionize) Doc.hide(this.showOther)\n\n Doc.bind(this.fileSelector, 'click', () => this.fileInput.click())\n\n // config file upload\n Doc.bind(this.fileInput, 'change', async () => this.fileInputChanged())\n\n Doc.bind(this.showOther, 'click', () => {\n this.setOtherSettingsViz(this.hideIcon.classList.contains('d-hide'))\n })\n }\n\n /*\n * fileInputChanged will read the selected file and attempt to load the\n * configuration settings. All loaded settings will be made visible for\n * inspection by the user.\n */\n async fileInputChanged () {\n Doc.hide(this.errMsg)\n if (!this.fileInput.value) return\n const files = this.fileInput.files\n if (!files || files.length === 0) return\n const loaded = app().loading(this.form)\n const config = await files[0].text()\n if (!config) return\n const res = await postJSON('/api/parseconfig', {\n configtext: config\n })\n loaded()\n if (!app().checkResponse(res)) {\n this.errMsg.textContent = res.msg\n Doc.show(this.errMsg)\n return\n }\n if (Object.keys(res.map).length === 0) return\n this.dynamicOpts.append(...this.setConfig(res.map))\n this.reorder(this.dynamicOpts)\n const [loadedOpts, defaultOpts] = [this.loadedSettings.children.length, this.defaultSettings.children.length]\n if (loadedOpts === 0) Doc.hide(this.loadedSettings, this.loadedSettingsMsg)\n if (defaultOpts === 0) Doc.hide(this.defaultSettings, this.defaultSettingsMsg)\n if (loadedOpts + defaultOpts === 0) Doc.hide(this.showOther, this.otherSettings)\n }\n\n addOpt (box: HTMLElement, opt: ConfigOption, insertAfter?: PageElement, skipRepeatN?: boolean): PageElement {\n let el: HTMLElement\n if (opt.isboolean) el = this.checkboxTmpl.cloneNode(true) as HTMLElement\n else if (opt.isdate) el = this.dateInputTmpl.cloneNode(true) as HTMLElement\n else if (opt.repeatable) {\n el = this.repeatableTmpl.cloneNode(true) as HTMLElement\n el.classList.add('repeatable')\n Doc.bind(Doc.tmplElement(el, 'add'), 'click', () => {\n this.addOpt(box, opt, el, true)\n })\n if (!skipRepeatN) for (let i = 0; i < (opt.repeatN ? opt.repeatN - 1 : 0); i++) this.addOpt(box, opt, insertAfter, true)\n } else el = this.textInputTmpl.cloneNode(true) as HTMLElement\n const hiddenFields = app().extensionWallet(this.assetID)?.hiddenFields || []\n if (hiddenFields.indexOf(opt.key) !== -1) Doc.hide(el)\n this.configElements.push([opt, el])\n const input = el.querySelector('input') as ConfigOptionInput\n input.dataset.configKey = opt.key\n // We need to generate a unique ID only for the =>