@nimiq/hub-api
Advanced tools
Comparing version 1.3.0-beta.3 to 1.3.0-beta.4
@@ -23,2 +23,10 @@ import { PostMessageRpcClient, RedirectRpcClient } from '@nimiq/rpc'; | ||
var nl = { | ||
"popup-overlay": "Er is een pop-up geopend,\nklik op het scherm om het weer naar voren te brengen." | ||
}; | ||
var ru = { | ||
"popup-overlay": "Открыто всплывающее окно.\nНажмите где-нибудь, чтобы вернуть его на передний план." | ||
}; | ||
var zh = { | ||
@@ -29,3 +37,3 @@ "popup-overlay": "弹出窗口已打开,\n单击任意位置即可回到前页。" | ||
// Import the languages you want to support. Note that the language files are not lazy loaded on purpose, as they are | ||
const translations = { de, en, es, fil, fr, zh }; | ||
const translations = { de, en, es, fil, fr, nl, ru, zh }; | ||
function translate(id, language) { | ||
@@ -32,0 +40,0 @@ if (!language) { |
@@ -27,2 +27,10 @@ (function (global, factory) { | ||
var nl = { | ||
"popup-overlay": "Er is een pop-up geopend,\nklik op het scherm om het weer naar voren te brengen." | ||
}; | ||
var ru = { | ||
"popup-overlay": "Открыто всплывающее окно.\nНажмите где-нибудь, чтобы вернуть его на передний план." | ||
}; | ||
var zh = { | ||
@@ -33,3 +41,3 @@ "popup-overlay": "弹出窗口已打开,\n单击任意位置即可回到前页。" | ||
// Import the languages you want to support. Note that the language files are not lazy loaded on purpose, as they are | ||
const translations = { de, en, es, fil, fr, zh }; | ||
const translations = { de, en, es, fil, fr, nl, ru, zh }; | ||
function translate(id, language) { | ||
@@ -36,0 +44,0 @@ if (!language) { |
export declare enum SwapAsset { | ||
NIM = "NIM", | ||
BTC = "BTC" | ||
BTC = "BTC", | ||
EUR = "EUR" | ||
} | ||
@@ -49,2 +50,5 @@ export declare type Asset = { | ||
}; | ||
export declare type ContractWithEstimate<T extends SwapAsset> = Estimate & { | ||
contract: Contract<T>; | ||
}; | ||
export declare type PreSwap = Estimate & { | ||
@@ -78,4 +82,4 @@ id: string; | ||
export declare function cancelSwap(swap: PreSwap): Promise<PreSwap>; | ||
export declare function getContract<T extends SwapAsset>(asset: T, address: string): Promise<Contract<T>>; | ||
export declare function getContract<T extends SwapAsset>(asset: T, address: string): Promise<ContractWithEstimate<T>>; | ||
export declare function getLimits<T extends SwapAsset>(asset: T, address: string): Promise<Limits<T>>; | ||
export declare function getAssets(): Promise<AssetList>; |
@@ -1,1 +0,1 @@ | ||
class e{static byteLength(t){const[s,r]=e._getLengths(t);return e._byteLength(s,r)}static decode(t){e._initRevLookup();const[s,r]=e._getLengths(t),n=new Uint8Array(e._byteLength(s,r));let i=0;const o=r>0?s-4:s;let a=0;for(;a<o;a+=4){const s=e._revLookup[t.charCodeAt(a)]<<18|e._revLookup[t.charCodeAt(a+1)]<<12|e._revLookup[t.charCodeAt(a+2)]<<6|e._revLookup[t.charCodeAt(a+3)];n[i++]=s>>16&255,n[i++]=s>>8&255,n[i++]=255&s}if(2===r){const s=e._revLookup[t.charCodeAt(a)]<<2|e._revLookup[t.charCodeAt(a+1)]>>4;n[i++]=255&s}if(1===r){const s=e._revLookup[t.charCodeAt(a)]<<10|e._revLookup[t.charCodeAt(a+1)]<<4|e._revLookup[t.charCodeAt(a+2)]>>2;n[i++]=s>>8&255,n[i]=255&s}return n}static encode(t){const s=t.length,r=s%3,n=[];for(let i=0,o=s-r;i<o;i+=16383)n.push(e._encodeChunk(t,i,i+16383>o?o:i+16383));if(1===r){const r=t[s-1];n.push(e._lookup[r>>2]+e._lookup[r<<4&63]+"==")}else if(2===r){const r=(t[s-2]<<8)+t[s-1];n.push(e._lookup[r>>10]+e._lookup[r>>4&63]+e._lookup[r<<2&63]+"=")}return n.join("")}static encodeUrl(t){return e.encode(t).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,".")}static decodeUrl(t){return e.decode(t.replace(/_/g,"/").replace(/-/g,"+").replace(/\./g,"="))}static _initRevLookup(){if(0===e._revLookup.length){e._revLookup=[];for(let t=0,s=e._lookup.length;t<s;t++)e._revLookup[e._lookup.charCodeAt(t)]=t;e._revLookup["-".charCodeAt(0)]=62,e._revLookup["_".charCodeAt(0)]=63}}static _getLengths(e){const t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");let s=e.indexOf("=");return-1===s&&(s=t),[s,s===t?0:4-s%4]}static _byteLength(e,t){return 3*(e+t)/4-t}static _tripletToBase64(t){return e._lookup[t>>18&63]+e._lookup[t>>12&63]+e._lookup[t>>6&63]+e._lookup[63&t]}static _encodeChunk(t,s,r){const n=[];for(let i=s;i<r;i+=3){const s=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(255&t[i+2]);n.push(e._tripletToBase64(s))}return n.join("")}}var t,s,r;e._lookup="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e._revLookup=[],function(e){e[e.UINT8_ARRAY=0]="UINT8_ARRAY"}(t||(t={}));class n{static stringify(e){return JSON.stringify(e,n._jsonifyType)}static parse(e){return JSON.parse(e,n._parseType)}static _parseType(s,r){if(r&&r.hasOwnProperty&&r.hasOwnProperty(n.TYPE_SYMBOL)&&r.hasOwnProperty(n.VALUE_SYMBOL))switch(r[n.TYPE_SYMBOL]){case t.UINT8_ARRAY:return e.decode(r[n.VALUE_SYMBOL])}return r}static _jsonifyType(s,r){return r instanceof Uint8Array?n._typedObject(t.UINT8_ARRAY,e.encode(r)):r}static _typedObject(e,t){const s={};return s[n.TYPE_SYMBOL]=e,s[n.VALUE_SYMBOL]=t,s}}n.TYPE_SYMBOL="__",n.VALUE_SYMBOL="v";class i{static generateRandomId(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}}!function(e){e.HTTP_POST="http-post",e.HTTP_GET="http-get",e.POST_MESSAGE="post-message"}(s||(s={})),function(e){e.OK="ok",e.ERROR="error"}(r||(r={}));class o{constructor(e=!0){this._store=e?window.sessionStorage:null,this._validIds=new Map,e&&this._restoreIds()}static _decodeIds(e){const t=n.parse(e),s=new Map;for(const e of Object.keys(t)){const r=parseInt(e,10);s.set(isNaN(r)?e:r,t[e])}return s}has(e){return this._validIds.has(e)}getCommand(e){const t=this._validIds.get(e);return t?t[0]:null}getState(e){const t=this._validIds.get(e);return t?t[1]:null}add(e,t,s=null){this._validIds.set(e,[t,s]),this._storeIds()}remove(e){this._validIds.delete(e),this._storeIds()}clear(){this._validIds.clear(),this._store&&this._store.removeItem(o.KEY)}_encodeIds(){const e=Object.create(null);for(const[t,s]of this._validIds)e[t]=s;return n.stringify(e)}_restoreIds(){const e=this._store.getItem(o.KEY);e&&(this._validIds=o._decodeIds(e))}_storeIds(){this._store&&this._store.setItem(o.KEY,this._encodeIds())}}o.KEY="rpcRequests";class a{static receiveRedirectCommand(e){const t=new URL(e.href);if(!document.referrer)return null;const r=new URL(document.referrer),i=new URLSearchParams(t.search),o=new URLSearchParams(t.hash.substring(1));if(!o.has("id"))return null;const c=parseInt(o.get("id"),10);if(o.delete("id"),i.set(a.URL_SEARCHPARAM_NAME,c.toString()),!o.has("command"))return null;const l=o.get("command");if(o.delete("command"),!o.has("returnURL"))return null;const h=o.get("returnURL");o.delete("returnURL");let d=s.HTTP_GET;if(o.has("responseMethod")&&(d=o.get("responseMethod"),o.delete("responseMethod"),!Object.values(s).includes(d)))throw new Error("Invalid ResponseMethod");if(!(d===s.POST_MESSAGE&&(window.opener||window.parent))&&new URL(h).origin!==r.origin)return null;let u=[];if(o.has("args"))try{u=n.parse(o.get("args"))}catch(e){}return u=Array.isArray(u)?u:[],o.delete("args"),t.search=i.toString(),this._setUrlFragment(t,o),history.replaceState(history.state,"",t.href),{origin:r.origin,data:{id:c,command:l,args:u},returnURL:h,responseMethod:d,source:d===s.POST_MESSAGE?window.opener||window.parent:null}}static receiveRedirectResponse(e){const t=new URL(e.href);if(!document.referrer)return null;const s=new URL(document.referrer),i=new URLSearchParams(t.search),o=new URLSearchParams(t.hash.substring(1));if(!o.has("id"))return null;const c=parseInt(o.get("id"),10);if(o.delete("id"),i.set(a.URL_SEARCHPARAM_NAME,c.toString()),!o.has("status"))return null;const l=o.get("status")===r.OK?r.OK:r.ERROR;if(o.delete("status"),!o.has("result"))return null;const h=n.parse(o.get("result"));return o.delete("result"),t.search=i.toString(),this._setUrlFragment(t,o),history.replaceState(history.state,"",t.href),{origin:s.origin,data:{id:c,status:l,result:h}}}static prepareRedirectReply(e,t,s){const r=new URL(e.returnURL),i=new URLSearchParams(r.hash.substring(1));return i.set("id",e.id.toString()),i.set("status",t),i.set("result",n.stringify(s)),r.hash=i.toString(),r.href}static prepareRedirectInvocation(e,t,s,r,i,o){const a=new URL(e),c=new URLSearchParams(a.hash.substring(1));return c.set("id",t.toString()),c.set("returnURL",s),c.set("command",r),c.set("responseMethod",o),Array.isArray(i)&&c.set("args",n.stringify(i)),a.hash=c.toString(),a.href}static _setUrlFragment(e,t){t.toString().endsWith("=")?e.hash=t.toString().slice(0,-1):e.hash=t.toString()}}a.URL_SEARCHPARAM_NAME="rpcId";class c{constructor(e,t=!1){this._allowedOrigin=e,this._waitingRequests=new o(t),this._responseHandlers=new Map,this._preserveRequests=!1}onResponse(e,t,s){this._responseHandlers.set(e,{resolve:t,reject:s})}_receive(e){if(!e.data||!e.data.status||!e.data.id||"*"!==this._allowedOrigin&&e.origin!==this._allowedOrigin)return!1;const t=e.data,s=this._getCallback(t.id),n=this._waitingRequests.getState(t.id);if(s){if(this._preserveRequests||(this._waitingRequests.remove(t.id),this._responseHandlers.delete(t.id)),console.debug("RpcClient RECEIVE",t),t.status===r.OK)s.resolve(t.result,t.id,n);else if(t.status===r.ERROR){const e=new Error(t.result.message);t.result.stack&&(e.stack=t.result.stack),t.result.name&&(e.name=t.result.name),s.reject(e,t.id,n)}return!0}return console.warn("Unknown RPC response:",t),!1}_getCallback(e){if(this._responseHandlers.has(e))return this._responseHandlers.get(e);{const t=this._waitingRequests.getCommand(e);if(t)return this._responseHandlers.get(t)}}}class l extends c{constructor(e,t){super(t),this._serverCloseCheckInterval=-1,this._target=e,this._connectionState=0,this._receiveListener=this._receive.bind(this)}async init(){2!==this._connectionState&&(await this._connect(),window.addEventListener("message",this._receiveListener),-1===this._serverCloseCheckInterval&&(this._serverCloseCheckInterval=window.setInterval(()=>this._checkIfServerClosed(),300)))}async call(e,...t){return this._call({command:e,args:t,id:i.generateRandomId()})}close(){this._connectionState=0,window.removeEventListener("message",this._receiveListener),window.clearInterval(this._serverCloseCheckInterval),this._serverCloseCheckInterval=-1;for(const[e,{reject:t}]of this._responseHandlers){const s=this._waitingRequests.getState(e);t("Connection was closed","number"==typeof e?e:void 0,s)}this._waitingRequests.clear(),this._responseHandlers.clear(),this._target&&this._target.closed&&(this._target=null)}_receive(e){return e.source===this._target&&super._receive(e)}async _call(e){if(!this._target||this._target.closed)throw new Error("Connection was closed.");if(2!==this._connectionState)throw new Error("Client is not connected, call init first");return new Promise((t,s)=>{this._responseHandlers.set(e.id,{resolve:t,reject:s}),this._waitingRequests.add(e.id,e.command),console.debug("RpcClient REQUEST",e.command,e.args),this._target.postMessage(e,this._allowedOrigin)})}_connect(){if(2!==this._connectionState)return this._connectionState=1,new Promise((e,t)=>{const s=t=>{const{source:n,origin:i,data:o}=t;if(n===this._target&&o.status===r.OK&&"pong"===o.result&&1===o.id&&("*"===this._allowedOrigin||i===this._allowedOrigin)){if(o.result.stack){const e=new Error(o.result.message);e.stack=o.result.stack,o.result.name&&(e.name=o.result.name),console.error(e)}window.removeEventListener("message",s),this._connectionState=2,console.log("RpcClient: Connection established"),e(!0)}};window.addEventListener("message",s);const n=()=>{if(2!==this._connectionState){if(0===this._connectionState||this._checkIfServerClosed())return window.removeEventListener("message",s),void t(new Error("Connection was closed"));try{this._target.postMessage({command:"ping",id:1},this._allowedOrigin)}catch(e){console.error(`postMessage failed: ${e}`)}window.setTimeout(n,100)}};window.setTimeout(n,100)})}_checkIfServerClosed(){return!(this._target&&!this._target.closed)&&(this.close(),!0)}}class h extends c{constructor(e,t,s=!0){super(t,!0),this._target=e,this._preserveRequests=s}async init(){const e=a.receiveRedirectResponse(window.location);if(e)return void this._receive(e);if(this._rejectOnBack())return;const t=new URLSearchParams(window.location.search);if(t.has(a.URL_SEARCHPARAM_NAME)){const e=window.sessionStorage.getItem(`response-${t.get(a.URL_SEARCHPARAM_NAME)}`);if(e)return void this._receive(n.parse(e),!1)}}close(){}call(e,t,r,...n){if(r&&"boolean"!=typeof r){if("object"==typeof r){if(r.responseMethod===s.POST_MESSAGE){if(!window.opener&&!window.parent)throw new Error("Window has no opener or parent, responseMethod: ResponseMethod.POST_MESSAGE would fail.");console.warn("Response will skip at least one rpc call, which will result in an unknown response.")}this._call(e,t,r,...n)}}else"boolean"==typeof r&&console.warn("RedirectRpcClient.call(string, string, boolean, any[]) is deprecated. Use RedirectRpcClient.call(string, string, CallOptions, any[]) with an appropriate CallOptions object instead."),this._call(e,t,{responseMethod:s.HTTP_GET,handleHistoryBack:!!r},...n)}callAndSaveLocalState(e,t,r,n=!1,...i){console.warn("RedirectRpcClient.callAndSaveLocalState() is deprecated. Use RedirectRpcClient.call() with an apropriate CallOptions object instead."),this._call(e,r,{responseMethod:s.HTTP_GET,state:t||void 0,handleHistoryBack:n},...i)}_receive(e,t=!0){const s=super._receive(e);return s&&t&&window.sessionStorage.setItem(`response-${e.data.id}`,n.stringify(e)),s}_call(e,t,r,...n){const o=i.generateRandomId(),c=r.responseMethod||s.HTTP_GET,l=a.prepareRedirectInvocation(this._target,o,e,t,n,c);this._waitingRequests.add(o,t,r.state||null),r.handleHistoryBack&&history.replaceState(Object.assign({},history.state,{rpcBackRejectionId:o}),""),console.debug("RpcClient REQUEST",t,n),window.location.href=l}_rejectOnBack(){if(!history.state||!history.state.rpcBackRejectionId)return!1;const e=history.state.rpcBackRejectionId;history.replaceState(Object.assign({},history.state,{rpcBackRejectionId:null}),"");const t=this._getCallback(e),s=this._waitingRequests.getState(e);if(t){this._preserveRequests||(this._waitingRequests.remove(e),this._responseHandlers.delete(e)),console.debug("RpcClient BACK");const r=new Error("Request aborted");return t.reject(r,e,s),!0}return!1}}var d={"popup-overlay":"A popup has been opened,\nclick anywhere to bring it back to the front."};const u={de:{"popup-overlay":"Ein Popup hat sich geöffnet,\nklicke hier, um zurück zum Popup zu kommen."},en:d,es:{"popup-overlay":"Se ha abierto una ventana emergente.\nHaga click en cualquier lugar para traer la ventana al primer plano."},fil:{"popup-overlay":"Nag-bukas ang isang pop-up.\nMaaring i-click kahit saan para ibalik ito sa harap."},fr:{"popup-overlay":"Une popup a été ouverte,\ncliquez n'importe où pour la ramener au premier plan."},zh:{"popup-overlay":"弹出窗口已打开,\n单击任意位置即可回到前页。"}};class _{constructor(e){this._type=e}static getAllowedOrigin(e){return new URL(e).origin}async request(e,t,s){throw new Error("Not implemented")}}var p,g,w,m,R,A,S;!function(e){e[e.REDIRECT=0]="REDIRECT",e[e.POPUP=1]="POPUP",e[e.IFRAME=2]="IFRAME"}(p||(p={}));class f extends _{constructor(e,t){super(p.REDIRECT);const s=window.location;if(this._returnUrl=e||`${s.origin}${s.pathname}`,this._localState=t||{},void 0!==this._localState.__command)throw new Error("Invalid localState: Property '__command' is reserved")}static withLocalState(e){return new f(void 0,e)}async request(e,t,s){const r=_.getAllowedOrigin(e),n=new h(e,r);await n.init();const i=Object.assign({},this._localState,{__command:t});n.callAndSaveLocalState(this._returnUrl,i,t,!0,...await Promise.all(s))}}class v extends _{constructor(e=v.DEFAULT_FEATURES,t){super(p.POPUP),this._popupFeatures=e,this._options={...v.DEFAULT_OPTIONS,...t}}async request(e,t,s){const r=_.getAllowedOrigin(e),n=this.createPopup(e),i=this.appendOverlay(n),o=new l(n,r);try{return await o.init(),await o.call(t,...await Promise.all(s))}catch(e){throw e}finally{this.removeOverlay(i),o.close(),n.close()}}createPopup(e){const t=window.open(e,"NimiqAccounts",this._popupFeatures);if(!t)throw new Error("Failed to open popup");return t}appendOverlay(e){if(!this._options.overlay)return null;const t=document.createElement.bind(document),s=(e,t)=>e.appendChild(t),r=t("div");r.id="nimiq-hub-overlay";const n=r.style;n.position="fixed",n.top="0",n.right="0",n.bottom="0",n.left="0",n.background="rgba(31, 35, 72, 0.8)",n.display="flex",n.flexDirection="column",n.alignItems="center",n.justifyContent="space-between",n.cursor="pointer",n.color="white",n.textAlign="center",n.opacity="0",n.transition="opacity 0.6s ease",n.zIndex="99999",r.addEventListener("click",()=>e.focus()),s(r,t("div"));const i=t("div");i.textContent=function(e,t){if(!t){const e=document.cookie.match(/(^| )lang=([^;]+)/);t=e&&e[2]||navigator.language.split("-")[0]}return(u[t]||d)[e]||d[e]}("popup-overlay");const o=i.style;o.padding="20px",o.fontFamily='Muli, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif',o.fontSize="24px",o.fontWeight="600",o.lineHeight="40px",o.whiteSpace="pre-line",s(r,i);const a=t("img");a.src='data:image/svg+xml,<svg width="135" height="32" viewBox="0 0 135 32" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M35.6 14.5l-7.5-13A3 3 0 0025.5 0h-15a3 3 0 00-2.6 1.5l-7.5 13a3 3 0 000 3l7.5 13a3 3 0 002.6 1.5h15a3 3 0 002.6-1.5l7.5-13a3 3 0 000-3z" fill="url(%23hub-overlay-nimiq-logo)"/><path d="M62.25 6.5h3.26v19H63L52.75 12.25V25.5H49.5v-19H52l10.25 13.25V6.5zM72 25.5v-19h3.5v19H72zM97.75 6.5h2.75v19h-3V13.75L92.37 25.5h-2.25L85 13.75V25.5h-3v-19h2.75l6.5 14.88 6.5-14.88zM107 25.5v-19h3.5v19H107zM133.88 21.17a7.91 7.91 0 01-4.01 3.8c.16.38.94 1.44 1.52 2.05.59.6 1.2 1.23 1.98 1.86L131 30.75a15.91 15.91 0 01-4.45-5.02l-.8.02c-1.94 0-3.55-.4-4.95-1.18a7.79 7.79 0 01-3.2-3.4 11.68 11.68 0 01-1.1-5.17c0-2.03.37-3.69 1.12-5.17a7.9 7.9 0 013.2-3.4 9.8 9.8 0 014.93-1.18c1.9 0 3.55.4 4.94 1.18a7.79 7.79 0 013.2 3.4 11.23 11.23 0 011.1 5.17c0 2.03-.44 3.83-1.11 5.17zm-12.37.01a5.21 5.21 0 004.24 1.82 5.2 5.2 0 004.23-1.82c1.01-1.21 1.52-2.92 1.52-5.18 0-2.24-.5-4-1.52-5.2a5.23 5.23 0 00-4.23-1.8c-1.82 0-3.23.6-4.24 1.79-1 1.2-1.51 2.95-1.51 5.21s.5 3.97 1.51 5.18z" fill="white"/><defs><radialGradient id="hub-overlay-nimiq-logo" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-35.9969 0 0 -32 36 32)"><stop stop-color="%23EC991C"/><stop offset="1" stop-color="%23E9B213"/></radialGradient></defs></svg>',a.style.marginBottom="56px",s(r,a);const c=t("div"),l=c.style;return c.innerHTML="×",l.position="absolute",l.top="8px",l.right="8px",l.fontSize="24px",l.lineHeight="32px",l.fontWeight="600",l.width="32px",l.height="32px",l.opacity="0.8",c.addEventListener("click",()=>e.close()),s(r,c),setTimeout(()=>r.style.opacity="1",100),s(document.body,r)}removeOverlay(e){e&&(e.style.opacity="0",setTimeout(()=>document.body.removeChild(e),400))}}v.DEFAULT_FEATURES="",v.DEFAULT_OPTIONS={overlay:!0};class E extends _{constructor(){super(p.IFRAME),this._iframe=null,this._client=null}async request(e,t,s){if(this._iframe&&this._iframe.src!==`${e}${E.IFRAME_PATH_SUFFIX}`)throw new Error("Hub iframe is already opened with another endpoint");const r=_.getAllowedOrigin(e);if(this._iframe||(this._iframe=await this.createIFrame(e)),!this._iframe.contentWindow)throw new Error(`IFrame contentWindow is ${typeof this._iframe.contentWindow}`);return this._client||(this._client=new l(this._iframe.contentWindow,r),await this._client.init()),await this._client.call(t,...await Promise.all(s))}async createIFrame(e){return new Promise((t,s)=>{const r=document.createElement("iframe");r.name="NimiqAccountsIFrame",r.style.display="none",document.body.appendChild(r),r.src=`${e}${E.IFRAME_PATH_SUFFIX}`,r.onload=(()=>t(r)),r.onerror=s})}}E.IFRAME_PATH_SUFFIX="/iframe.html",function(e){e.LIST="list",e.LIST_CASHLINKS="list-cashlinks",e.MIGRATE="migrate",e.CHECKOUT="checkout",e.SIGN_MESSAGE="sign-message",e.SIGN_TRANSACTION="sign-transaction",e.ONBOARD="onboard",e.SIGNUP="signup",e.LOGIN="login",e.EXPORT="export",e.CHANGE_PASSWORD="change-password",e.LOGOUT="logout",e.ADD_ADDRESS="add-address",e.RENAME="rename",e.CHOOSE_ADDRESS="choose-address",e.CREATE_CASHLINK="create-cashlink",e.MANAGE_CASHLINK="manage-cashlink",e.SIGN_BTC_TRANSACTION="sign-btc-transaction",e.ADD_BTC_ADDRESSES="add-btc-addresses",e.ACTIVATE_BITCOIN="activate-bitcoin",e.SETUP_SWAP="setup-swap",e.REFUND_SWAP="refund-swap"}(g||(g={})),function(e){e[e.DIRECT=0]="DIRECT",e[e.OASIS=1]="OASIS"}(w||(w={})),function(e){e.NIM="nim",e.BTC="btc",e.ETH="eth"}(m||(m={})),function(e){e.NOT_FOUND="NOT_FOUND",e.PAID="PAID",e.UNDERPAID="UNDERPAID",e.OVERPAID="OVERPAID"}(R||(R={})),function(e){e[e.UNKNOWN=-1]="UNKNOWN",e[e.UNCHARGED=0]="UNCHARGED",e[e.CHARGING=1]="CHARGING",e[e.UNCLAIMED=2]="UNCLAIMED",e[e.CLAIMING=3]="CLAIMING",e[e.CLAIMED=4]="CLAIMED"}(A||(A={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.STANDARD=1]="STANDARD",e[e.CHRISTMAS=2]="CHRISTMAS",e[e.LUNAR_NEW_YEAR=3]="LUNAR_NEW_YEAR",e[e.EASTER=4]="EASTER",e[e.GENERIC=5]="GENERIC",e[e.BIRTHDAY=6]="BIRTHDAY"}(S||(S={}));class I{constructor(e=I.DEFAULT_ENDPOINT,t){this._endpoint=e,this._defaultBehavior=t||new v(`left=${window.innerWidth/2-400},top=75,width=800,height=850,location=yes,dependent=yes`),this._checkoutDefaultBehavior=t||new v(`left=${window.innerWidth/2-400},top=50,width=800,height=895,location=yes,dependent=yes`),this._iframeBehavior=new E,this._redirectClient=new h("",_.getAllowedOrigin(this._endpoint))}static get PaymentMethod(){return console.warn("PaymentMethod has been renamed to PaymentType. Access via HubApi.PaymentMethod will soon get disabled. Use HubApi.PaymentType instead."),w}static get DEFAULT_ENDPOINT(){const e=location.origin.split(".");switch(e.shift(),e.join(".")){case"nimiq.com":return"https://hub.nimiq.com";case"nimiq-testnet.com":return"https://hub.nimiq-testnet.com";default:return"http://localhost:8080"}}checkRedirectResponse(){return this._redirectClient.init()}on(e,t,s){this._redirectClient.onResponse(e,(e,s,r)=>t(e,r),(e,t,r)=>{s&&s(e,r)})}createCashlink(e,t=this._defaultBehavior){return this._request(t,g.CREATE_CASHLINK,[e])}manageCashlink(e,t=this._defaultBehavior){return this._request(t,g.MANAGE_CASHLINK,[e])}checkout(e,t=this._checkoutDefaultBehavior){return this._request(t,g.CHECKOUT,[e])}chooseAddress(e,t=this._defaultBehavior){return this._request(t,g.CHOOSE_ADDRESS,[e])}signTransaction(e,t=this._defaultBehavior){return this._request(t,g.SIGN_TRANSACTION,[e])}signMessage(e,t=this._defaultBehavior){return this._request(t,g.SIGN_MESSAGE,[e])}signBtcTransaction(e,t=this._defaultBehavior){return this._request(t,g.SIGN_BTC_TRANSACTION,[e])}setupSwap(e,t=this._defaultBehavior){return this._request(t,g.SETUP_SWAP,[e])}refundSwap(e,t=this._defaultBehavior){return this._request(t,g.REFUND_SWAP,[e])}onboard(e,t=this._defaultBehavior){return this._request(t,g.ONBOARD,[e])}signup(e,t=this._defaultBehavior){return this._request(t,g.SIGNUP,[e])}login(e,t=this._defaultBehavior){return this._request(t,g.LOGIN,[e])}logout(e,t=this._defaultBehavior){return this._request(t,g.LOGOUT,[e])}export(e,t=this._defaultBehavior){return this._request(t,g.EXPORT,[e])}changePassword(e,t=this._defaultBehavior){return this._request(t,g.CHANGE_PASSWORD,[e])}addAddress(e,t=this._defaultBehavior){return this._request(t,g.ADD_ADDRESS,[e])}rename(e,t=this._defaultBehavior){return this._request(t,g.RENAME,[e])}migrate(e=this._defaultBehavior){return this._request(e,g.MIGRATE,[{appName:"Account list"}])}activateBitcoin(e,t=this._defaultBehavior){return this._request(t,g.ACTIVATE_BITCOIN,[e])}list(e=this._iframeBehavior){return this._request(e,g.LIST,[])}cashlinks(e=this._iframeBehavior){return this._request(e,g.LIST_CASHLINKS,[])}addBtcAddresses(e,t=this._iframeBehavior){return this._request(t,g.ADD_BTC_ADDRESSES,[e])}_request(e,t,s){return e.request(this._endpoint,t,s)}}I.RequestType=g,I.RedirectRequestBehavior=f,I.PopupRequestBehavior=v,I.CashlinkState=A,I.CashlinkTheme=S,I.Currency=m,I.PaymentType=w,I.PaymentState=R,I.MSG_PREFIX="Nimiq Signed Message:\n";export default I; | ||
class e{static byteLength(t){const[s,r]=e._getLengths(t);return e._byteLength(s,r)}static decode(t){e._initRevLookup();const[s,r]=e._getLengths(t),n=new Uint8Array(e._byteLength(s,r));let i=0;const o=r>0?s-4:s;let a=0;for(;a<o;a+=4){const s=e._revLookup[t.charCodeAt(a)]<<18|e._revLookup[t.charCodeAt(a+1)]<<12|e._revLookup[t.charCodeAt(a+2)]<<6|e._revLookup[t.charCodeAt(a+3)];n[i++]=s>>16&255,n[i++]=s>>8&255,n[i++]=255&s}if(2===r){const s=e._revLookup[t.charCodeAt(a)]<<2|e._revLookup[t.charCodeAt(a+1)]>>4;n[i++]=255&s}if(1===r){const s=e._revLookup[t.charCodeAt(a)]<<10|e._revLookup[t.charCodeAt(a+1)]<<4|e._revLookup[t.charCodeAt(a+2)]>>2;n[i++]=s>>8&255,n[i]=255&s}return n}static encode(t){const s=t.length,r=s%3,n=[];for(let i=0,o=s-r;i<o;i+=16383)n.push(e._encodeChunk(t,i,i+16383>o?o:i+16383));if(1===r){const r=t[s-1];n.push(e._lookup[r>>2]+e._lookup[r<<4&63]+"==")}else if(2===r){const r=(t[s-2]<<8)+t[s-1];n.push(e._lookup[r>>10]+e._lookup[r>>4&63]+e._lookup[r<<2&63]+"=")}return n.join("")}static encodeUrl(t){return e.encode(t).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,".")}static decodeUrl(t){return e.decode(t.replace(/_/g,"/").replace(/-/g,"+").replace(/\./g,"="))}static _initRevLookup(){if(0===e._revLookup.length){e._revLookup=[];for(let t=0,s=e._lookup.length;t<s;t++)e._revLookup[e._lookup.charCodeAt(t)]=t;e._revLookup["-".charCodeAt(0)]=62,e._revLookup["_".charCodeAt(0)]=63}}static _getLengths(e){const t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");let s=e.indexOf("=");return-1===s&&(s=t),[s,s===t?0:4-s%4]}static _byteLength(e,t){return 3*(e+t)/4-t}static _tripletToBase64(t){return e._lookup[t>>18&63]+e._lookup[t>>12&63]+e._lookup[t>>6&63]+e._lookup[63&t]}static _encodeChunk(t,s,r){const n=[];for(let i=s;i<r;i+=3){const s=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(255&t[i+2]);n.push(e._tripletToBase64(s))}return n.join("")}}var t,s,r;e._lookup="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e._revLookup=[],function(e){e[e.UINT8_ARRAY=0]="UINT8_ARRAY"}(t||(t={}));class n{static stringify(e){return JSON.stringify(e,n._jsonifyType)}static parse(e){return JSON.parse(e,n._parseType)}static _parseType(s,r){if(r&&r.hasOwnProperty&&r.hasOwnProperty(n.TYPE_SYMBOL)&&r.hasOwnProperty(n.VALUE_SYMBOL))switch(r[n.TYPE_SYMBOL]){case t.UINT8_ARRAY:return e.decode(r[n.VALUE_SYMBOL])}return r}static _jsonifyType(s,r){return r instanceof Uint8Array?n._typedObject(t.UINT8_ARRAY,e.encode(r)):r}static _typedObject(e,t){const s={};return s[n.TYPE_SYMBOL]=e,s[n.VALUE_SYMBOL]=t,s}}n.TYPE_SYMBOL="__",n.VALUE_SYMBOL="v";class i{static generateRandomId(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}}!function(e){e.HTTP_POST="http-post",e.HTTP_GET="http-get",e.POST_MESSAGE="post-message"}(s||(s={})),function(e){e.OK="ok",e.ERROR="error"}(r||(r={}));class o{constructor(e=!0){this._store=e?window.sessionStorage:null,this._validIds=new Map,e&&this._restoreIds()}static _decodeIds(e){const t=n.parse(e),s=new Map;for(const e of Object.keys(t)){const r=parseInt(e,10);s.set(isNaN(r)?e:r,t[e])}return s}has(e){return this._validIds.has(e)}getCommand(e){const t=this._validIds.get(e);return t?t[0]:null}getState(e){const t=this._validIds.get(e);return t?t[1]:null}add(e,t,s=null){this._validIds.set(e,[t,s]),this._storeIds()}remove(e){this._validIds.delete(e),this._storeIds()}clear(){this._validIds.clear(),this._store&&this._store.removeItem(o.KEY)}_encodeIds(){const e=Object.create(null);for(const[t,s]of this._validIds)e[t]=s;return n.stringify(e)}_restoreIds(){const e=this._store.getItem(o.KEY);e&&(this._validIds=o._decodeIds(e))}_storeIds(){this._store&&this._store.setItem(o.KEY,this._encodeIds())}}o.KEY="rpcRequests";class a{static receiveRedirectCommand(e){const t=new URL(e.href);if(!document.referrer)return null;const r=new URL(document.referrer),i=new URLSearchParams(t.search),o=new URLSearchParams(t.hash.substring(1));if(!o.has("id"))return null;const c=parseInt(o.get("id"),10);if(o.delete("id"),i.set(a.URL_SEARCHPARAM_NAME,c.toString()),!o.has("command"))return null;const l=o.get("command");if(o.delete("command"),!o.has("returnURL"))return null;const h=o.get("returnURL");o.delete("returnURL");let d=s.HTTP_GET;if(o.has("responseMethod")&&(d=o.get("responseMethod"),o.delete("responseMethod"),!Object.values(s).includes(d)))throw new Error("Invalid ResponseMethod");if(!(d===s.POST_MESSAGE&&(window.opener||window.parent))&&new URL(h).origin!==r.origin)return null;let u=[];if(o.has("args"))try{u=n.parse(o.get("args"))}catch(e){}return u=Array.isArray(u)?u:[],o.delete("args"),t.search=i.toString(),this._setUrlFragment(t,o),history.replaceState(history.state,"",t.href),{origin:r.origin,data:{id:c,command:l,args:u},returnURL:h,responseMethod:d,source:d===s.POST_MESSAGE?window.opener||window.parent:null}}static receiveRedirectResponse(e){const t=new URL(e.href);if(!document.referrer)return null;const s=new URL(document.referrer),i=new URLSearchParams(t.search),o=new URLSearchParams(t.hash.substring(1));if(!o.has("id"))return null;const c=parseInt(o.get("id"),10);if(o.delete("id"),i.set(a.URL_SEARCHPARAM_NAME,c.toString()),!o.has("status"))return null;const l=o.get("status")===r.OK?r.OK:r.ERROR;if(o.delete("status"),!o.has("result"))return null;const h=n.parse(o.get("result"));return o.delete("result"),t.search=i.toString(),this._setUrlFragment(t,o),history.replaceState(history.state,"",t.href),{origin:s.origin,data:{id:c,status:l,result:h}}}static prepareRedirectReply(e,t,s){const r=new URL(e.returnURL),i=new URLSearchParams(r.hash.substring(1));return i.set("id",e.id.toString()),i.set("status",t),i.set("result",n.stringify(s)),r.hash=i.toString(),r.href}static prepareRedirectInvocation(e,t,s,r,i,o){const a=new URL(e),c=new URLSearchParams(a.hash.substring(1));return c.set("id",t.toString()),c.set("returnURL",s),c.set("command",r),c.set("responseMethod",o),Array.isArray(i)&&c.set("args",n.stringify(i)),a.hash=c.toString(),a.href}static _setUrlFragment(e,t){t.toString().endsWith("=")?e.hash=t.toString().slice(0,-1):e.hash=t.toString()}}a.URL_SEARCHPARAM_NAME="rpcId";class c{constructor(e,t=!1){this._allowedOrigin=e,this._waitingRequests=new o(t),this._responseHandlers=new Map,this._preserveRequests=!1}onResponse(e,t,s){this._responseHandlers.set(e,{resolve:t,reject:s})}_receive(e){if(!e.data||!e.data.status||!e.data.id||"*"!==this._allowedOrigin&&e.origin!==this._allowedOrigin)return!1;const t=e.data,s=this._getCallback(t.id),n=this._waitingRequests.getState(t.id);if(s){if(this._preserveRequests||(this._waitingRequests.remove(t.id),this._responseHandlers.delete(t.id)),console.debug("RpcClient RECEIVE",t),t.status===r.OK)s.resolve(t.result,t.id,n);else if(t.status===r.ERROR){const e=new Error(t.result.message);t.result.stack&&(e.stack=t.result.stack),t.result.name&&(e.name=t.result.name),s.reject(e,t.id,n)}return!0}return console.warn("Unknown RPC response:",t),!1}_getCallback(e){if(this._responseHandlers.has(e))return this._responseHandlers.get(e);{const t=this._waitingRequests.getCommand(e);if(t)return this._responseHandlers.get(t)}}}class l extends c{constructor(e,t){super(t),this._serverCloseCheckInterval=-1,this._target=e,this._connectionState=0,this._receiveListener=this._receive.bind(this)}async init(){2!==this._connectionState&&(await this._connect(),window.addEventListener("message",this._receiveListener),-1===this._serverCloseCheckInterval&&(this._serverCloseCheckInterval=window.setInterval(()=>this._checkIfServerClosed(),300)))}async call(e,...t){return this._call({command:e,args:t,id:i.generateRandomId()})}close(){this._connectionState=0,window.removeEventListener("message",this._receiveListener),window.clearInterval(this._serverCloseCheckInterval),this._serverCloseCheckInterval=-1;for(const[e,{reject:t}]of this._responseHandlers){const s=this._waitingRequests.getState(e);t("Connection was closed","number"==typeof e?e:void 0,s)}this._waitingRequests.clear(),this._responseHandlers.clear(),this._target&&this._target.closed&&(this._target=null)}_receive(e){return e.source===this._target&&super._receive(e)}async _call(e){if(!this._target||this._target.closed)throw new Error("Connection was closed.");if(2!==this._connectionState)throw new Error("Client is not connected, call init first");return new Promise((t,s)=>{this._responseHandlers.set(e.id,{resolve:t,reject:s}),this._waitingRequests.add(e.id,e.command),console.debug("RpcClient REQUEST",e.command,e.args),this._target.postMessage(e,this._allowedOrigin)})}_connect(){if(2!==this._connectionState)return this._connectionState=1,new Promise((e,t)=>{const s=t=>{const{source:n,origin:i,data:o}=t;if(n===this._target&&o.status===r.OK&&"pong"===o.result&&1===o.id&&("*"===this._allowedOrigin||i===this._allowedOrigin)){if(o.result.stack){const e=new Error(o.result.message);e.stack=o.result.stack,o.result.name&&(e.name=o.result.name),console.error(e)}window.removeEventListener("message",s),this._connectionState=2,console.log("RpcClient: Connection established"),e(!0)}};window.addEventListener("message",s);const n=()=>{if(2!==this._connectionState){if(0===this._connectionState||this._checkIfServerClosed())return window.removeEventListener("message",s),void t(new Error("Connection was closed"));try{this._target.postMessage({command:"ping",id:1},this._allowedOrigin)}catch(e){console.error(`postMessage failed: ${e}`)}window.setTimeout(n,100)}};window.setTimeout(n,100)})}_checkIfServerClosed(){return!(this._target&&!this._target.closed)&&(this.close(),!0)}}class h extends c{constructor(e,t,s=!0){super(t,!0),this._target=e,this._preserveRequests=s}async init(){const e=a.receiveRedirectResponse(window.location);if(e)return void this._receive(e);if(this._rejectOnBack())return;const t=new URLSearchParams(window.location.search);if(t.has(a.URL_SEARCHPARAM_NAME)){const e=window.sessionStorage.getItem(`response-${t.get(a.URL_SEARCHPARAM_NAME)}`);if(e)return void this._receive(n.parse(e),!1)}}close(){}call(e,t,r,...n){if(r&&"boolean"!=typeof r){if("object"==typeof r){if(r.responseMethod===s.POST_MESSAGE){if(!window.opener&&!window.parent)throw new Error("Window has no opener or parent, responseMethod: ResponseMethod.POST_MESSAGE would fail.");console.warn("Response will skip at least one rpc call, which will result in an unknown response.")}this._call(e,t,r,...n)}}else"boolean"==typeof r&&console.warn("RedirectRpcClient.call(string, string, boolean, any[]) is deprecated. Use RedirectRpcClient.call(string, string, CallOptions, any[]) with an appropriate CallOptions object instead."),this._call(e,t,{responseMethod:s.HTTP_GET,handleHistoryBack:!!r},...n)}callAndSaveLocalState(e,t,r,n=!1,...i){console.warn("RedirectRpcClient.callAndSaveLocalState() is deprecated. Use RedirectRpcClient.call() with an apropriate CallOptions object instead."),this._call(e,r,{responseMethod:s.HTTP_GET,state:t||void 0,handleHistoryBack:n},...i)}_receive(e,t=!0){const s=super._receive(e);return s&&t&&window.sessionStorage.setItem(`response-${e.data.id}`,n.stringify(e)),s}_call(e,t,r,...n){const o=i.generateRandomId(),c=r.responseMethod||s.HTTP_GET,l=a.prepareRedirectInvocation(this._target,o,e,t,n,c);this._waitingRequests.add(o,t,r.state||null),r.handleHistoryBack&&history.replaceState(Object.assign({},history.state,{rpcBackRejectionId:o}),""),console.debug("RpcClient REQUEST",t,n),window.location.href=l}_rejectOnBack(){if(!history.state||!history.state.rpcBackRejectionId)return!1;const e=history.state.rpcBackRejectionId;history.replaceState(Object.assign({},history.state,{rpcBackRejectionId:null}),"");const t=this._getCallback(e),s=this._waitingRequests.getState(e);if(t){this._preserveRequests||(this._waitingRequests.remove(e),this._responseHandlers.delete(e)),console.debug("RpcClient BACK");const r=new Error("Request aborted");return t.reject(r,e,s),!0}return!1}}var d={"popup-overlay":"A popup has been opened,\nclick anywhere to bring it back to the front."};const u={de:{"popup-overlay":"Ein Popup hat sich geöffnet,\nklicke hier, um zurück zum Popup zu kommen."},en:d,es:{"popup-overlay":"Se ha abierto una ventana emergente.\nHaga click en cualquier lugar para traer la ventana al primer plano."},fil:{"popup-overlay":"Nag-bukas ang isang pop-up.\nMaaring i-click kahit saan para ibalik ito sa harap."},fr:{"popup-overlay":"Une popup a été ouverte,\ncliquez n'importe où pour la ramener au premier plan."},nl:{"popup-overlay":"Er is een pop-up geopend,\nklik op het scherm om het weer naar voren te brengen."},ru:{"popup-overlay":"Открыто всплывающее окно.\nНажмите где-нибудь, чтобы вернуть его на передний план."},zh:{"popup-overlay":"弹出窗口已打开,\n单击任意位置即可回到前页。"}};class _{constructor(e){this._type=e}static getAllowedOrigin(e){return new URL(e).origin}async request(e,t,s){throw new Error("Not implemented")}}var p,g,w,m,R,A,S;!function(e){e[e.REDIRECT=0]="REDIRECT",e[e.POPUP=1]="POPUP",e[e.IFRAME=2]="IFRAME"}(p||(p={}));class v extends _{constructor(e,t){super(p.REDIRECT);const s=window.location;if(this._returnUrl=e||`${s.origin}${s.pathname}`,this._localState=t||{},void 0!==this._localState.__command)throw new Error("Invalid localState: Property '__command' is reserved")}static withLocalState(e){return new v(void 0,e)}async request(e,t,s){const r=_.getAllowedOrigin(e),n=new h(e,r);await n.init();const i=Object.assign({},this._localState,{__command:t});n.callAndSaveLocalState(this._returnUrl,i,t,!0,...await Promise.all(s))}}class f extends _{constructor(e=f.DEFAULT_FEATURES,t){super(p.POPUP),this._popupFeatures=e,this._options={...f.DEFAULT_OPTIONS,...t}}async request(e,t,s){const r=_.getAllowedOrigin(e),n=this.createPopup(e),i=this.appendOverlay(n),o=new l(n,r);try{return await o.init(),await o.call(t,...await Promise.all(s))}catch(e){throw e}finally{this.removeOverlay(i),o.close(),n.close()}}createPopup(e){const t=window.open(e,"NimiqAccounts",this._popupFeatures);if(!t)throw new Error("Failed to open popup");return t}appendOverlay(e){if(!this._options.overlay)return null;const t=document.createElement.bind(document),s=(e,t)=>e.appendChild(t),r=t("div");r.id="nimiq-hub-overlay";const n=r.style;n.position="fixed",n.top="0",n.right="0",n.bottom="0",n.left="0",n.background="rgba(31, 35, 72, 0.8)",n.display="flex",n.flexDirection="column",n.alignItems="center",n.justifyContent="space-between",n.cursor="pointer",n.color="white",n.textAlign="center",n.opacity="0",n.transition="opacity 0.6s ease",n.zIndex="99999",r.addEventListener("click",()=>e.focus()),s(r,t("div"));const i=t("div");i.textContent=function(e,t){if(!t){const e=document.cookie.match(/(^| )lang=([^;]+)/);t=e&&e[2]||navigator.language.split("-")[0]}return(u[t]||d)[e]||d[e]}("popup-overlay");const o=i.style;o.padding="20px",o.fontFamily='Muli, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif',o.fontSize="24px",o.fontWeight="600",o.lineHeight="40px",o.whiteSpace="pre-line",s(r,i);const a=t("img");a.src='data:image/svg+xml,<svg width="135" height="32" viewBox="0 0 135 32" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M35.6 14.5l-7.5-13A3 3 0 0025.5 0h-15a3 3 0 00-2.6 1.5l-7.5 13a3 3 0 000 3l7.5 13a3 3 0 002.6 1.5h15a3 3 0 002.6-1.5l7.5-13a3 3 0 000-3z" fill="url(%23hub-overlay-nimiq-logo)"/><path d="M62.25 6.5h3.26v19H63L52.75 12.25V25.5H49.5v-19H52l10.25 13.25V6.5zM72 25.5v-19h3.5v19H72zM97.75 6.5h2.75v19h-3V13.75L92.37 25.5h-2.25L85 13.75V25.5h-3v-19h2.75l6.5 14.88 6.5-14.88zM107 25.5v-19h3.5v19H107zM133.88 21.17a7.91 7.91 0 01-4.01 3.8c.16.38.94 1.44 1.52 2.05.59.6 1.2 1.23 1.98 1.86L131 30.75a15.91 15.91 0 01-4.45-5.02l-.8.02c-1.94 0-3.55-.4-4.95-1.18a7.79 7.79 0 01-3.2-3.4 11.68 11.68 0 01-1.1-5.17c0-2.03.37-3.69 1.12-5.17a7.9 7.9 0 013.2-3.4 9.8 9.8 0 014.93-1.18c1.9 0 3.55.4 4.94 1.18a7.79 7.79 0 013.2 3.4 11.23 11.23 0 011.1 5.17c0 2.03-.44 3.83-1.11 5.17zm-12.37.01a5.21 5.21 0 004.24 1.82 5.2 5.2 0 004.23-1.82c1.01-1.21 1.52-2.92 1.52-5.18 0-2.24-.5-4-1.52-5.2a5.23 5.23 0 00-4.23-1.8c-1.82 0-3.23.6-4.24 1.79-1 1.2-1.51 2.95-1.51 5.21s.5 3.97 1.51 5.18z" fill="white"/><defs><radialGradient id="hub-overlay-nimiq-logo" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-35.9969 0 0 -32 36 32)"><stop stop-color="%23EC991C"/><stop offset="1" stop-color="%23E9B213"/></radialGradient></defs></svg>',a.style.marginBottom="56px",s(r,a);const c=t("div"),l=c.style;return c.innerHTML="×",l.position="absolute",l.top="8px",l.right="8px",l.fontSize="24px",l.lineHeight="32px",l.fontWeight="600",l.width="32px",l.height="32px",l.opacity="0.8",c.addEventListener("click",()=>e.close()),s(r,c),setTimeout(()=>r.style.opacity="1",100),s(document.body,r)}removeOverlay(e){e&&(e.style.opacity="0",setTimeout(()=>document.body.removeChild(e),400))}}f.DEFAULT_FEATURES="",f.DEFAULT_OPTIONS={overlay:!0};class E extends _{constructor(){super(p.IFRAME),this._iframe=null,this._client=null}async request(e,t,s){if(this._iframe&&this._iframe.src!==`${e}${E.IFRAME_PATH_SUFFIX}`)throw new Error("Hub iframe is already opened with another endpoint");const r=_.getAllowedOrigin(e);if(this._iframe||(this._iframe=await this.createIFrame(e)),!this._iframe.contentWindow)throw new Error(`IFrame contentWindow is ${typeof this._iframe.contentWindow}`);return this._client||(this._client=new l(this._iframe.contentWindow,r),await this._client.init()),await this._client.call(t,...await Promise.all(s))}async createIFrame(e){return new Promise((t,s)=>{const r=document.createElement("iframe");r.name="NimiqAccountsIFrame",r.style.display="none",document.body.appendChild(r),r.src=`${e}${E.IFRAME_PATH_SUFFIX}`,r.onload=(()=>t(r)),r.onerror=s})}}E.IFRAME_PATH_SUFFIX="/iframe.html",function(e){e.LIST="list",e.LIST_CASHLINKS="list-cashlinks",e.MIGRATE="migrate",e.CHECKOUT="checkout",e.SIGN_MESSAGE="sign-message",e.SIGN_TRANSACTION="sign-transaction",e.ONBOARD="onboard",e.SIGNUP="signup",e.LOGIN="login",e.EXPORT="export",e.CHANGE_PASSWORD="change-password",e.LOGOUT="logout",e.ADD_ADDRESS="add-address",e.RENAME="rename",e.CHOOSE_ADDRESS="choose-address",e.CREATE_CASHLINK="create-cashlink",e.MANAGE_CASHLINK="manage-cashlink",e.SIGN_BTC_TRANSACTION="sign-btc-transaction",e.ADD_BTC_ADDRESSES="add-btc-addresses",e.ACTIVATE_BITCOIN="activate-bitcoin",e.SETUP_SWAP="setup-swap",e.REFUND_SWAP="refund-swap"}(g||(g={})),function(e){e[e.DIRECT=0]="DIRECT",e[e.OASIS=1]="OASIS"}(w||(w={})),function(e){e.NIM="nim",e.BTC="btc",e.ETH="eth"}(m||(m={})),function(e){e.NOT_FOUND="NOT_FOUND",e.PAID="PAID",e.UNDERPAID="UNDERPAID",e.OVERPAID="OVERPAID"}(R||(R={})),function(e){e[e.UNKNOWN=-1]="UNKNOWN",e[e.UNCHARGED=0]="UNCHARGED",e[e.CHARGING=1]="CHARGING",e[e.UNCLAIMED=2]="UNCLAIMED",e[e.CLAIMING=3]="CLAIMING",e[e.CLAIMED=4]="CLAIMED"}(A||(A={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.STANDARD=1]="STANDARD",e[e.CHRISTMAS=2]="CHRISTMAS",e[e.LUNAR_NEW_YEAR=3]="LUNAR_NEW_YEAR",e[e.EASTER=4]="EASTER",e[e.GENERIC=5]="GENERIC",e[e.BIRTHDAY=6]="BIRTHDAY"}(S||(S={}));class I{constructor(e=I.DEFAULT_ENDPOINT,t){this._endpoint=e,this._defaultBehavior=t||new f(`left=${window.innerWidth/2-400},top=75,width=800,height=850,location=yes,dependent=yes`),this._checkoutDefaultBehavior=t||new f(`left=${window.innerWidth/2-400},top=50,width=800,height=895,location=yes,dependent=yes`),this._iframeBehavior=new E,this._redirectClient=new h("",_.getAllowedOrigin(this._endpoint))}static get PaymentMethod(){return console.warn("PaymentMethod has been renamed to PaymentType. Access via HubApi.PaymentMethod will soon get disabled. Use HubApi.PaymentType instead."),w}static get DEFAULT_ENDPOINT(){const e=location.origin.split(".");switch(e.shift(),e.join(".")){case"nimiq.com":return"https://hub.nimiq.com";case"nimiq-testnet.com":return"https://hub.nimiq-testnet.com";default:return"http://localhost:8080"}}checkRedirectResponse(){return this._redirectClient.init()}on(e,t,s){this._redirectClient.onResponse(e,(e,s,r)=>t(e,r),(e,t,r)=>{s&&s(e,r)})}createCashlink(e,t=this._defaultBehavior){return this._request(t,g.CREATE_CASHLINK,[e])}manageCashlink(e,t=this._defaultBehavior){return this._request(t,g.MANAGE_CASHLINK,[e])}checkout(e,t=this._checkoutDefaultBehavior){return this._request(t,g.CHECKOUT,[e])}chooseAddress(e,t=this._defaultBehavior){return this._request(t,g.CHOOSE_ADDRESS,[e])}signTransaction(e,t=this._defaultBehavior){return this._request(t,g.SIGN_TRANSACTION,[e])}signMessage(e,t=this._defaultBehavior){return this._request(t,g.SIGN_MESSAGE,[e])}signBtcTransaction(e,t=this._defaultBehavior){return this._request(t,g.SIGN_BTC_TRANSACTION,[e])}setupSwap(e,t=this._defaultBehavior){return this._request(t,g.SETUP_SWAP,[e])}refundSwap(e,t=this._defaultBehavior){return this._request(t,g.REFUND_SWAP,[e])}onboard(e,t=this._defaultBehavior){return this._request(t,g.ONBOARD,[e])}signup(e,t=this._defaultBehavior){return this._request(t,g.SIGNUP,[e])}login(e,t=this._defaultBehavior){return this._request(t,g.LOGIN,[e])}logout(e,t=this._defaultBehavior){return this._request(t,g.LOGOUT,[e])}export(e,t=this._defaultBehavior){return this._request(t,g.EXPORT,[e])}changePassword(e,t=this._defaultBehavior){return this._request(t,g.CHANGE_PASSWORD,[e])}addAddress(e,t=this._defaultBehavior){return this._request(t,g.ADD_ADDRESS,[e])}rename(e,t=this._defaultBehavior){return this._request(t,g.RENAME,[e])}migrate(e=this._defaultBehavior){return this._request(e,g.MIGRATE,[{appName:"Account list"}])}activateBitcoin(e,t=this._defaultBehavior){return this._request(t,g.ACTIVATE_BITCOIN,[e])}list(e=this._iframeBehavior){return this._request(e,g.LIST,[])}cashlinks(e=this._iframeBehavior){return this._request(e,g.LIST_CASHLINKS,[])}addBtcAddresses(e,t=this._iframeBehavior){return this._request(t,g.ADD_BTC_ADDRESSES,[e])}_request(e,t,s){return e.request(this._endpoint,t,s)}}I.RequestType=g,I.RedirectRequestBehavior=v,I.PopupRequestBehavior=f,I.CashlinkState=A,I.CashlinkTheme=S,I.Currency=m,I.PaymentType=w,I.PaymentState=R,I.MSG_PREFIX="Nimiq Signed Message:\n";export default I; |
@@ -1,1 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).HubApi=t()}(this,function(){"use strict";class e{static byteLength(t){const[s,r]=e._getLengths(t);return e._byteLength(s,r)}static decode(t){e._initRevLookup();const[s,r]=e._getLengths(t),n=new Uint8Array(e._byteLength(s,r));let i=0;const o=r>0?s-4:s;let a=0;for(;a<o;a+=4){const s=e._revLookup[t.charCodeAt(a)]<<18|e._revLookup[t.charCodeAt(a+1)]<<12|e._revLookup[t.charCodeAt(a+2)]<<6|e._revLookup[t.charCodeAt(a+3)];n[i++]=s>>16&255,n[i++]=s>>8&255,n[i++]=255&s}if(2===r){const s=e._revLookup[t.charCodeAt(a)]<<2|e._revLookup[t.charCodeAt(a+1)]>>4;n[i++]=255&s}if(1===r){const s=e._revLookup[t.charCodeAt(a)]<<10|e._revLookup[t.charCodeAt(a+1)]<<4|e._revLookup[t.charCodeAt(a+2)]>>2;n[i++]=s>>8&255,n[i]=255&s}return n}static encode(t){const s=t.length,r=s%3,n=[];for(let i=0,o=s-r;i<o;i+=16383)n.push(e._encodeChunk(t,i,i+16383>o?o:i+16383));if(1===r){const r=t[s-1];n.push(e._lookup[r>>2]+e._lookup[r<<4&63]+"==")}else if(2===r){const r=(t[s-2]<<8)+t[s-1];n.push(e._lookup[r>>10]+e._lookup[r>>4&63]+e._lookup[r<<2&63]+"=")}return n.join("")}static encodeUrl(t){return e.encode(t).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,".")}static decodeUrl(t){return e.decode(t.replace(/_/g,"/").replace(/-/g,"+").replace(/\./g,"="))}static _initRevLookup(){if(0===e._revLookup.length){e._revLookup=[];for(let t=0,s=e._lookup.length;t<s;t++)e._revLookup[e._lookup.charCodeAt(t)]=t;e._revLookup["-".charCodeAt(0)]=62,e._revLookup["_".charCodeAt(0)]=63}}static _getLengths(e){const t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");let s=e.indexOf("=");return-1===s&&(s=t),[s,s===t?0:4-s%4]}static _byteLength(e,t){return 3*(e+t)/4-t}static _tripletToBase64(t){return e._lookup[t>>18&63]+e._lookup[t>>12&63]+e._lookup[t>>6&63]+e._lookup[63&t]}static _encodeChunk(t,s,r){const n=[];for(let i=s;i<r;i+=3){const s=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(255&t[i+2]);n.push(e._tripletToBase64(s))}return n.join("")}}var t,s,r;e._lookup="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e._revLookup=[],function(e){e[e.UINT8_ARRAY=0]="UINT8_ARRAY"}(t||(t={}));class n{static stringify(e){return JSON.stringify(e,n._jsonifyType)}static parse(e){return JSON.parse(e,n._parseType)}static _parseType(s,r){if(r&&r.hasOwnProperty&&r.hasOwnProperty(n.TYPE_SYMBOL)&&r.hasOwnProperty(n.VALUE_SYMBOL))switch(r[n.TYPE_SYMBOL]){case t.UINT8_ARRAY:return e.decode(r[n.VALUE_SYMBOL])}return r}static _jsonifyType(s,r){return r instanceof Uint8Array?n._typedObject(t.UINT8_ARRAY,e.encode(r)):r}static _typedObject(e,t){const s={};return s[n.TYPE_SYMBOL]=e,s[n.VALUE_SYMBOL]=t,s}}n.TYPE_SYMBOL="__",n.VALUE_SYMBOL="v";class i{static generateRandomId(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}}!function(e){e.HTTP_POST="http-post",e.HTTP_GET="http-get",e.POST_MESSAGE="post-message"}(s||(s={})),function(e){e.OK="ok",e.ERROR="error"}(r||(r={}));class o{constructor(e=!0){this._store=e?window.sessionStorage:null,this._validIds=new Map,e&&this._restoreIds()}static _decodeIds(e){const t=n.parse(e),s=new Map;for(const e of Object.keys(t)){const r=parseInt(e,10);s.set(isNaN(r)?e:r,t[e])}return s}has(e){return this._validIds.has(e)}getCommand(e){const t=this._validIds.get(e);return t?t[0]:null}getState(e){const t=this._validIds.get(e);return t?t[1]:null}add(e,t,s=null){this._validIds.set(e,[t,s]),this._storeIds()}remove(e){this._validIds.delete(e),this._storeIds()}clear(){this._validIds.clear(),this._store&&this._store.removeItem(o.KEY)}_encodeIds(){const e=Object.create(null);for(const[t,s]of this._validIds)e[t]=s;return n.stringify(e)}_restoreIds(){const e=this._store.getItem(o.KEY);e&&(this._validIds=o._decodeIds(e))}_storeIds(){this._store&&this._store.setItem(o.KEY,this._encodeIds())}}o.KEY="rpcRequests";class a{static receiveRedirectCommand(e){const t=new URL(e.href);if(!document.referrer)return null;const r=new URL(document.referrer),i=new URLSearchParams(t.search),o=new URLSearchParams(t.hash.substring(1));if(!o.has("id"))return null;const c=parseInt(o.get("id"),10);if(o.delete("id"),i.set(a.URL_SEARCHPARAM_NAME,c.toString()),!o.has("command"))return null;const l=o.get("command");if(o.delete("command"),!o.has("returnURL"))return null;const h=o.get("returnURL");o.delete("returnURL");let d=s.HTTP_GET;if(o.has("responseMethod")&&(d=o.get("responseMethod"),o.delete("responseMethod"),!Object.values(s).includes(d)))throw new Error("Invalid ResponseMethod");if(!(d===s.POST_MESSAGE&&(window.opener||window.parent))&&new URL(h).origin!==r.origin)return null;let u=[];if(o.has("args"))try{u=n.parse(o.get("args"))}catch(e){}return u=Array.isArray(u)?u:[],o.delete("args"),t.search=i.toString(),this._setUrlFragment(t,o),history.replaceState(history.state,"",t.href),{origin:r.origin,data:{id:c,command:l,args:u},returnURL:h,responseMethod:d,source:d===s.POST_MESSAGE?window.opener||window.parent:null}}static receiveRedirectResponse(e){const t=new URL(e.href);if(!document.referrer)return null;const s=new URL(document.referrer),i=new URLSearchParams(t.search),o=new URLSearchParams(t.hash.substring(1));if(!o.has("id"))return null;const c=parseInt(o.get("id"),10);if(o.delete("id"),i.set(a.URL_SEARCHPARAM_NAME,c.toString()),!o.has("status"))return null;const l=o.get("status")===r.OK?r.OK:r.ERROR;if(o.delete("status"),!o.has("result"))return null;const h=n.parse(o.get("result"));return o.delete("result"),t.search=i.toString(),this._setUrlFragment(t,o),history.replaceState(history.state,"",t.href),{origin:s.origin,data:{id:c,status:l,result:h}}}static prepareRedirectReply(e,t,s){const r=new URL(e.returnURL),i=new URLSearchParams(r.hash.substring(1));return i.set("id",e.id.toString()),i.set("status",t),i.set("result",n.stringify(s)),r.hash=i.toString(),r.href}static prepareRedirectInvocation(e,t,s,r,i,o){const a=new URL(e),c=new URLSearchParams(a.hash.substring(1));return c.set("id",t.toString()),c.set("returnURL",s),c.set("command",r),c.set("responseMethod",o),Array.isArray(i)&&c.set("args",n.stringify(i)),a.hash=c.toString(),a.href}static _setUrlFragment(e,t){t.toString().endsWith("=")?e.hash=t.toString().slice(0,-1):e.hash=t.toString()}}a.URL_SEARCHPARAM_NAME="rpcId";class c{constructor(e,t=!1){this._allowedOrigin=e,this._waitingRequests=new o(t),this._responseHandlers=new Map,this._preserveRequests=!1}onResponse(e,t,s){this._responseHandlers.set(e,{resolve:t,reject:s})}_receive(e){if(!e.data||!e.data.status||!e.data.id||"*"!==this._allowedOrigin&&e.origin!==this._allowedOrigin)return!1;const t=e.data,s=this._getCallback(t.id),n=this._waitingRequests.getState(t.id);if(s){if(this._preserveRequests||(this._waitingRequests.remove(t.id),this._responseHandlers.delete(t.id)),console.debug("RpcClient RECEIVE",t),t.status===r.OK)s.resolve(t.result,t.id,n);else if(t.status===r.ERROR){const e=new Error(t.result.message);t.result.stack&&(e.stack=t.result.stack),t.result.name&&(e.name=t.result.name),s.reject(e,t.id,n)}return!0}return console.warn("Unknown RPC response:",t),!1}_getCallback(e){if(this._responseHandlers.has(e))return this._responseHandlers.get(e);{const t=this._waitingRequests.getCommand(e);if(t)return this._responseHandlers.get(t)}}}class l extends c{constructor(e,t){super(t),this._serverCloseCheckInterval=-1,this._target=e,this._connectionState=0,this._receiveListener=this._receive.bind(this)}async init(){2!==this._connectionState&&(await this._connect(),window.addEventListener("message",this._receiveListener),-1===this._serverCloseCheckInterval&&(this._serverCloseCheckInterval=window.setInterval(()=>this._checkIfServerClosed(),300)))}async call(e,...t){return this._call({command:e,args:t,id:i.generateRandomId()})}close(){this._connectionState=0,window.removeEventListener("message",this._receiveListener),window.clearInterval(this._serverCloseCheckInterval),this._serverCloseCheckInterval=-1;for(const[e,{reject:t}]of this._responseHandlers){const s=this._waitingRequests.getState(e);t("Connection was closed","number"==typeof e?e:void 0,s)}this._waitingRequests.clear(),this._responseHandlers.clear(),this._target&&this._target.closed&&(this._target=null)}_receive(e){return e.source===this._target&&super._receive(e)}async _call(e){if(!this._target||this._target.closed)throw new Error("Connection was closed.");if(2!==this._connectionState)throw new Error("Client is not connected, call init first");return new Promise((t,s)=>{this._responseHandlers.set(e.id,{resolve:t,reject:s}),this._waitingRequests.add(e.id,e.command),console.debug("RpcClient REQUEST",e.command,e.args),this._target.postMessage(e,this._allowedOrigin)})}_connect(){if(2!==this._connectionState)return this._connectionState=1,new Promise((e,t)=>{const s=t=>{const{source:n,origin:i,data:o}=t;if(n===this._target&&o.status===r.OK&&"pong"===o.result&&1===o.id&&("*"===this._allowedOrigin||i===this._allowedOrigin)){if(o.result.stack){const e=new Error(o.result.message);e.stack=o.result.stack,o.result.name&&(e.name=o.result.name),console.error(e)}window.removeEventListener("message",s),this._connectionState=2,console.log("RpcClient: Connection established"),e(!0)}};window.addEventListener("message",s);const n=()=>{if(2!==this._connectionState){if(0===this._connectionState||this._checkIfServerClosed())return window.removeEventListener("message",s),void t(new Error("Connection was closed"));try{this._target.postMessage({command:"ping",id:1},this._allowedOrigin)}catch(e){console.error(`postMessage failed: ${e}`)}window.setTimeout(n,100)}};window.setTimeout(n,100)})}_checkIfServerClosed(){return!(this._target&&!this._target.closed)&&(this.close(),!0)}}class h extends c{constructor(e,t,s=!0){super(t,!0),this._target=e,this._preserveRequests=s}async init(){const e=a.receiveRedirectResponse(window.location);if(e)return void this._receive(e);if(this._rejectOnBack())return;const t=new URLSearchParams(window.location.search);if(t.has(a.URL_SEARCHPARAM_NAME)){const e=window.sessionStorage.getItem(`response-${t.get(a.URL_SEARCHPARAM_NAME)}`);if(e)return void this._receive(n.parse(e),!1)}}close(){}call(e,t,r,...n){if(r&&"boolean"!=typeof r){if("object"==typeof r){if(r.responseMethod===s.POST_MESSAGE){if(!window.opener&&!window.parent)throw new Error("Window has no opener or parent, responseMethod: ResponseMethod.POST_MESSAGE would fail.");console.warn("Response will skip at least one rpc call, which will result in an unknown response.")}this._call(e,t,r,...n)}}else"boolean"==typeof r&&console.warn("RedirectRpcClient.call(string, string, boolean, any[]) is deprecated. Use RedirectRpcClient.call(string, string, CallOptions, any[]) with an appropriate CallOptions object instead."),this._call(e,t,{responseMethod:s.HTTP_GET,handleHistoryBack:!!r},...n)}callAndSaveLocalState(e,t,r,n=!1,...i){console.warn("RedirectRpcClient.callAndSaveLocalState() is deprecated. Use RedirectRpcClient.call() with an apropriate CallOptions object instead."),this._call(e,r,{responseMethod:s.HTTP_GET,state:t||void 0,handleHistoryBack:n},...i)}_receive(e,t=!0){const s=super._receive(e);return s&&t&&window.sessionStorage.setItem(`response-${e.data.id}`,n.stringify(e)),s}_call(e,t,r,...n){const o=i.generateRandomId(),c=r.responseMethod||s.HTTP_GET,l=a.prepareRedirectInvocation(this._target,o,e,t,n,c);this._waitingRequests.add(o,t,r.state||null),r.handleHistoryBack&&history.replaceState(Object.assign({},history.state,{rpcBackRejectionId:o}),""),console.debug("RpcClient REQUEST",t,n),window.location.href=l}_rejectOnBack(){if(!history.state||!history.state.rpcBackRejectionId)return!1;const e=history.state.rpcBackRejectionId;history.replaceState(Object.assign({},history.state,{rpcBackRejectionId:null}),"");const t=this._getCallback(e),s=this._waitingRequests.getState(e);if(t){this._preserveRequests||(this._waitingRequests.remove(e),this._responseHandlers.delete(e)),console.debug("RpcClient BACK");const r=new Error("Request aborted");return t.reject(r,e,s),!0}return!1}}var d={"popup-overlay":"A popup has been opened,\nclick anywhere to bring it back to the front."};const u={de:{"popup-overlay":"Ein Popup hat sich geöffnet,\nklicke hier, um zurück zum Popup zu kommen."},en:d,es:{"popup-overlay":"Se ha abierto una ventana emergente.\nHaga click en cualquier lugar para traer la ventana al primer plano."},fil:{"popup-overlay":"Nag-bukas ang isang pop-up.\nMaaring i-click kahit saan para ibalik ito sa harap."},fr:{"popup-overlay":"Une popup a été ouverte,\ncliquez n'importe où pour la ramener au premier plan."},zh:{"popup-overlay":"弹出窗口已打开,\n单击任意位置即可回到前页。"}};class _{constructor(e){this._type=e}static getAllowedOrigin(e){return new URL(e).origin}async request(e,t,s){throw new Error("Not implemented")}}var p,g,w,m,f,R,A;!function(e){e[e.REDIRECT=0]="REDIRECT",e[e.POPUP=1]="POPUP",e[e.IFRAME=2]="IFRAME"}(p||(p={}));class S extends _{constructor(e,t){super(p.REDIRECT);const s=window.location;if(this._returnUrl=e||`${s.origin}${s.pathname}`,this._localState=t||{},void 0!==this._localState.__command)throw new Error("Invalid localState: Property '__command' is reserved")}static withLocalState(e){return new S(void 0,e)}async request(e,t,s){const r=_.getAllowedOrigin(e),n=new h(e,r);await n.init();const i=Object.assign({},this._localState,{__command:t});n.callAndSaveLocalState(this._returnUrl,i,t,!0,...await Promise.all(s))}}class v extends _{constructor(e=v.DEFAULT_FEATURES,t){super(p.POPUP),this._popupFeatures=e,this._options={...v.DEFAULT_OPTIONS,...t}}async request(e,t,s){const r=_.getAllowedOrigin(e),n=this.createPopup(e),i=this.appendOverlay(n),o=new l(n,r);try{return await o.init(),await o.call(t,...await Promise.all(s))}catch(e){throw e}finally{this.removeOverlay(i),o.close(),n.close()}}createPopup(e){const t=window.open(e,"NimiqAccounts",this._popupFeatures);if(!t)throw new Error("Failed to open popup");return t}appendOverlay(e){if(!this._options.overlay)return null;const t=document.createElement.bind(document),s=(e,t)=>e.appendChild(t),r=t("div");r.id="nimiq-hub-overlay";const n=r.style;n.position="fixed",n.top="0",n.right="0",n.bottom="0",n.left="0",n.background="rgba(31, 35, 72, 0.8)",n.display="flex",n.flexDirection="column",n.alignItems="center",n.justifyContent="space-between",n.cursor="pointer",n.color="white",n.textAlign="center",n.opacity="0",n.transition="opacity 0.6s ease",n.zIndex="99999",r.addEventListener("click",()=>e.focus()),s(r,t("div"));const i=t("div");i.textContent=function(e,t){if(!t){const e=document.cookie.match(/(^| )lang=([^;]+)/);t=e&&e[2]||navigator.language.split("-")[0]}return(u[t]||d)[e]||d[e]}("popup-overlay");const o=i.style;o.padding="20px",o.fontFamily='Muli, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif',o.fontSize="24px",o.fontWeight="600",o.lineHeight="40px",o.whiteSpace="pre-line",s(r,i);const a=t("img");a.src='data:image/svg+xml,<svg width="135" height="32" viewBox="0 0 135 32" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M35.6 14.5l-7.5-13A3 3 0 0025.5 0h-15a3 3 0 00-2.6 1.5l-7.5 13a3 3 0 000 3l7.5 13a3 3 0 002.6 1.5h15a3 3 0 002.6-1.5l7.5-13a3 3 0 000-3z" fill="url(%23hub-overlay-nimiq-logo)"/><path d="M62.25 6.5h3.26v19H63L52.75 12.25V25.5H49.5v-19H52l10.25 13.25V6.5zM72 25.5v-19h3.5v19H72zM97.75 6.5h2.75v19h-3V13.75L92.37 25.5h-2.25L85 13.75V25.5h-3v-19h2.75l6.5 14.88 6.5-14.88zM107 25.5v-19h3.5v19H107zM133.88 21.17a7.91 7.91 0 01-4.01 3.8c.16.38.94 1.44 1.52 2.05.59.6 1.2 1.23 1.98 1.86L131 30.75a15.91 15.91 0 01-4.45-5.02l-.8.02c-1.94 0-3.55-.4-4.95-1.18a7.79 7.79 0 01-3.2-3.4 11.68 11.68 0 01-1.1-5.17c0-2.03.37-3.69 1.12-5.17a7.9 7.9 0 013.2-3.4 9.8 9.8 0 014.93-1.18c1.9 0 3.55.4 4.94 1.18a7.79 7.79 0 013.2 3.4 11.23 11.23 0 011.1 5.17c0 2.03-.44 3.83-1.11 5.17zm-12.37.01a5.21 5.21 0 004.24 1.82 5.2 5.2 0 004.23-1.82c1.01-1.21 1.52-2.92 1.52-5.18 0-2.24-.5-4-1.52-5.2a5.23 5.23 0 00-4.23-1.8c-1.82 0-3.23.6-4.24 1.79-1 1.2-1.51 2.95-1.51 5.21s.5 3.97 1.51 5.18z" fill="white"/><defs><radialGradient id="hub-overlay-nimiq-logo" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-35.9969 0 0 -32 36 32)"><stop stop-color="%23EC991C"/><stop offset="1" stop-color="%23E9B213"/></radialGradient></defs></svg>',a.style.marginBottom="56px",s(r,a);const c=t("div"),l=c.style;return c.innerHTML="×",l.position="absolute",l.top="8px",l.right="8px",l.fontSize="24px",l.lineHeight="32px",l.fontWeight="600",l.width="32px",l.height="32px",l.opacity="0.8",c.addEventListener("click",()=>e.close()),s(r,c),setTimeout(()=>r.style.opacity="1",100),s(document.body,r)}removeOverlay(e){e&&(e.style.opacity="0",setTimeout(()=>document.body.removeChild(e),400))}}v.DEFAULT_FEATURES="",v.DEFAULT_OPTIONS={overlay:!0};class E extends _{constructor(){super(p.IFRAME),this._iframe=null,this._client=null}async request(e,t,s){if(this._iframe&&this._iframe.src!==`${e}${E.IFRAME_PATH_SUFFIX}`)throw new Error("Hub iframe is already opened with another endpoint");const r=_.getAllowedOrigin(e);if(this._iframe||(this._iframe=await this.createIFrame(e)),!this._iframe.contentWindow)throw new Error(`IFrame contentWindow is ${typeof this._iframe.contentWindow}`);return this._client||(this._client=new l(this._iframe.contentWindow,r),await this._client.init()),await this._client.call(t,...await Promise.all(s))}async createIFrame(e){return new Promise((t,s)=>{const r=document.createElement("iframe");r.name="NimiqAccountsIFrame",r.style.display="none",document.body.appendChild(r),r.src=`${e}${E.IFRAME_PATH_SUFFIX}`,r.onload=(()=>t(r)),r.onerror=s})}}E.IFRAME_PATH_SUFFIX="/iframe.html",function(e){e.LIST="list",e.LIST_CASHLINKS="list-cashlinks",e.MIGRATE="migrate",e.CHECKOUT="checkout",e.SIGN_MESSAGE="sign-message",e.SIGN_TRANSACTION="sign-transaction",e.ONBOARD="onboard",e.SIGNUP="signup",e.LOGIN="login",e.EXPORT="export",e.CHANGE_PASSWORD="change-password",e.LOGOUT="logout",e.ADD_ADDRESS="add-address",e.RENAME="rename",e.CHOOSE_ADDRESS="choose-address",e.CREATE_CASHLINK="create-cashlink",e.MANAGE_CASHLINK="manage-cashlink",e.SIGN_BTC_TRANSACTION="sign-btc-transaction",e.ADD_BTC_ADDRESSES="add-btc-addresses",e.ACTIVATE_BITCOIN="activate-bitcoin",e.SETUP_SWAP="setup-swap",e.REFUND_SWAP="refund-swap"}(g||(g={})),function(e){e[e.DIRECT=0]="DIRECT",e[e.OASIS=1]="OASIS"}(w||(w={})),function(e){e.NIM="nim",e.BTC="btc",e.ETH="eth"}(m||(m={})),function(e){e.NOT_FOUND="NOT_FOUND",e.PAID="PAID",e.UNDERPAID="UNDERPAID",e.OVERPAID="OVERPAID"}(f||(f={})),function(e){e[e.UNKNOWN=-1]="UNKNOWN",e[e.UNCHARGED=0]="UNCHARGED",e[e.CHARGING=1]="CHARGING",e[e.UNCLAIMED=2]="UNCLAIMED",e[e.CLAIMING=3]="CLAIMING",e[e.CLAIMED=4]="CLAIMED"}(R||(R={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.STANDARD=1]="STANDARD",e[e.CHRISTMAS=2]="CHRISTMAS",e[e.LUNAR_NEW_YEAR=3]="LUNAR_NEW_YEAR",e[e.EASTER=4]="EASTER",e[e.GENERIC=5]="GENERIC",e[e.BIRTHDAY=6]="BIRTHDAY"}(A||(A={}));class I{constructor(e=I.DEFAULT_ENDPOINT,t){this._endpoint=e,this._defaultBehavior=t||new v(`left=${window.innerWidth/2-400},top=75,width=800,height=850,location=yes,dependent=yes`),this._checkoutDefaultBehavior=t||new v(`left=${window.innerWidth/2-400},top=50,width=800,height=895,location=yes,dependent=yes`),this._iframeBehavior=new E,this._redirectClient=new h("",_.getAllowedOrigin(this._endpoint))}static get PaymentMethod(){return console.warn("PaymentMethod has been renamed to PaymentType. Access via HubApi.PaymentMethod will soon get disabled. Use HubApi.PaymentType instead."),w}static get DEFAULT_ENDPOINT(){const e=location.origin.split(".");switch(e.shift(),e.join(".")){case"nimiq.com":return"https://hub.nimiq.com";case"nimiq-testnet.com":return"https://hub.nimiq-testnet.com";default:return"http://localhost:8080"}}checkRedirectResponse(){return this._redirectClient.init()}on(e,t,s){this._redirectClient.onResponse(e,(e,s,r)=>t(e,r),(e,t,r)=>{s&&s(e,r)})}createCashlink(e,t=this._defaultBehavior){return this._request(t,g.CREATE_CASHLINK,[e])}manageCashlink(e,t=this._defaultBehavior){return this._request(t,g.MANAGE_CASHLINK,[e])}checkout(e,t=this._checkoutDefaultBehavior){return this._request(t,g.CHECKOUT,[e])}chooseAddress(e,t=this._defaultBehavior){return this._request(t,g.CHOOSE_ADDRESS,[e])}signTransaction(e,t=this._defaultBehavior){return this._request(t,g.SIGN_TRANSACTION,[e])}signMessage(e,t=this._defaultBehavior){return this._request(t,g.SIGN_MESSAGE,[e])}signBtcTransaction(e,t=this._defaultBehavior){return this._request(t,g.SIGN_BTC_TRANSACTION,[e])}setupSwap(e,t=this._defaultBehavior){return this._request(t,g.SETUP_SWAP,[e])}refundSwap(e,t=this._defaultBehavior){return this._request(t,g.REFUND_SWAP,[e])}onboard(e,t=this._defaultBehavior){return this._request(t,g.ONBOARD,[e])}signup(e,t=this._defaultBehavior){return this._request(t,g.SIGNUP,[e])}login(e,t=this._defaultBehavior){return this._request(t,g.LOGIN,[e])}logout(e,t=this._defaultBehavior){return this._request(t,g.LOGOUT,[e])}export(e,t=this._defaultBehavior){return this._request(t,g.EXPORT,[e])}changePassword(e,t=this._defaultBehavior){return this._request(t,g.CHANGE_PASSWORD,[e])}addAddress(e,t=this._defaultBehavior){return this._request(t,g.ADD_ADDRESS,[e])}rename(e,t=this._defaultBehavior){return this._request(t,g.RENAME,[e])}migrate(e=this._defaultBehavior){return this._request(e,g.MIGRATE,[{appName:"Account list"}])}activateBitcoin(e,t=this._defaultBehavior){return this._request(t,g.ACTIVATE_BITCOIN,[e])}list(e=this._iframeBehavior){return this._request(e,g.LIST,[])}cashlinks(e=this._iframeBehavior){return this._request(e,g.LIST_CASHLINKS,[])}addBtcAddresses(e,t=this._iframeBehavior){return this._request(t,g.ADD_BTC_ADDRESSES,[e])}_request(e,t,s){return e.request(this._endpoint,t,s)}}return I.RequestType=g,I.RedirectRequestBehavior=S,I.PopupRequestBehavior=v,I.CashlinkState=R,I.CashlinkTheme=A,I.Currency=m,I.PaymentType=w,I.PaymentState=f,I.MSG_PREFIX="Nimiq Signed Message:\n",I}); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).HubApi=t()}(this,function(){"use strict";class e{static byteLength(t){const[s,r]=e._getLengths(t);return e._byteLength(s,r)}static decode(t){e._initRevLookup();const[s,r]=e._getLengths(t),n=new Uint8Array(e._byteLength(s,r));let i=0;const o=r>0?s-4:s;let a=0;for(;a<o;a+=4){const s=e._revLookup[t.charCodeAt(a)]<<18|e._revLookup[t.charCodeAt(a+1)]<<12|e._revLookup[t.charCodeAt(a+2)]<<6|e._revLookup[t.charCodeAt(a+3)];n[i++]=s>>16&255,n[i++]=s>>8&255,n[i++]=255&s}if(2===r){const s=e._revLookup[t.charCodeAt(a)]<<2|e._revLookup[t.charCodeAt(a+1)]>>4;n[i++]=255&s}if(1===r){const s=e._revLookup[t.charCodeAt(a)]<<10|e._revLookup[t.charCodeAt(a+1)]<<4|e._revLookup[t.charCodeAt(a+2)]>>2;n[i++]=s>>8&255,n[i]=255&s}return n}static encode(t){const s=t.length,r=s%3,n=[];for(let i=0,o=s-r;i<o;i+=16383)n.push(e._encodeChunk(t,i,i+16383>o?o:i+16383));if(1===r){const r=t[s-1];n.push(e._lookup[r>>2]+e._lookup[r<<4&63]+"==")}else if(2===r){const r=(t[s-2]<<8)+t[s-1];n.push(e._lookup[r>>10]+e._lookup[r>>4&63]+e._lookup[r<<2&63]+"=")}return n.join("")}static encodeUrl(t){return e.encode(t).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,".")}static decodeUrl(t){return e.decode(t.replace(/_/g,"/").replace(/-/g,"+").replace(/\./g,"="))}static _initRevLookup(){if(0===e._revLookup.length){e._revLookup=[];for(let t=0,s=e._lookup.length;t<s;t++)e._revLookup[e._lookup.charCodeAt(t)]=t;e._revLookup["-".charCodeAt(0)]=62,e._revLookup["_".charCodeAt(0)]=63}}static _getLengths(e){const t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");let s=e.indexOf("=");return-1===s&&(s=t),[s,s===t?0:4-s%4]}static _byteLength(e,t){return 3*(e+t)/4-t}static _tripletToBase64(t){return e._lookup[t>>18&63]+e._lookup[t>>12&63]+e._lookup[t>>6&63]+e._lookup[63&t]}static _encodeChunk(t,s,r){const n=[];for(let i=s;i<r;i+=3){const s=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(255&t[i+2]);n.push(e._tripletToBase64(s))}return n.join("")}}var t,s,r;e._lookup="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e._revLookup=[],function(e){e[e.UINT8_ARRAY=0]="UINT8_ARRAY"}(t||(t={}));class n{static stringify(e){return JSON.stringify(e,n._jsonifyType)}static parse(e){return JSON.parse(e,n._parseType)}static _parseType(s,r){if(r&&r.hasOwnProperty&&r.hasOwnProperty(n.TYPE_SYMBOL)&&r.hasOwnProperty(n.VALUE_SYMBOL))switch(r[n.TYPE_SYMBOL]){case t.UINT8_ARRAY:return e.decode(r[n.VALUE_SYMBOL])}return r}static _jsonifyType(s,r){return r instanceof Uint8Array?n._typedObject(t.UINT8_ARRAY,e.encode(r)):r}static _typedObject(e,t){const s={};return s[n.TYPE_SYMBOL]=e,s[n.VALUE_SYMBOL]=t,s}}n.TYPE_SYMBOL="__",n.VALUE_SYMBOL="v";class i{static generateRandomId(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}}!function(e){e.HTTP_POST="http-post",e.HTTP_GET="http-get",e.POST_MESSAGE="post-message"}(s||(s={})),function(e){e.OK="ok",e.ERROR="error"}(r||(r={}));class o{constructor(e=!0){this._store=e?window.sessionStorage:null,this._validIds=new Map,e&&this._restoreIds()}static _decodeIds(e){const t=n.parse(e),s=new Map;for(const e of Object.keys(t)){const r=parseInt(e,10);s.set(isNaN(r)?e:r,t[e])}return s}has(e){return this._validIds.has(e)}getCommand(e){const t=this._validIds.get(e);return t?t[0]:null}getState(e){const t=this._validIds.get(e);return t?t[1]:null}add(e,t,s=null){this._validIds.set(e,[t,s]),this._storeIds()}remove(e){this._validIds.delete(e),this._storeIds()}clear(){this._validIds.clear(),this._store&&this._store.removeItem(o.KEY)}_encodeIds(){const e=Object.create(null);for(const[t,s]of this._validIds)e[t]=s;return n.stringify(e)}_restoreIds(){const e=this._store.getItem(o.KEY);e&&(this._validIds=o._decodeIds(e))}_storeIds(){this._store&&this._store.setItem(o.KEY,this._encodeIds())}}o.KEY="rpcRequests";class a{static receiveRedirectCommand(e){const t=new URL(e.href);if(!document.referrer)return null;const r=new URL(document.referrer),i=new URLSearchParams(t.search),o=new URLSearchParams(t.hash.substring(1));if(!o.has("id"))return null;const c=parseInt(o.get("id"),10);if(o.delete("id"),i.set(a.URL_SEARCHPARAM_NAME,c.toString()),!o.has("command"))return null;const l=o.get("command");if(o.delete("command"),!o.has("returnURL"))return null;const h=o.get("returnURL");o.delete("returnURL");let d=s.HTTP_GET;if(o.has("responseMethod")&&(d=o.get("responseMethod"),o.delete("responseMethod"),!Object.values(s).includes(d)))throw new Error("Invalid ResponseMethod");if(!(d===s.POST_MESSAGE&&(window.opener||window.parent))&&new URL(h).origin!==r.origin)return null;let u=[];if(o.has("args"))try{u=n.parse(o.get("args"))}catch(e){}return u=Array.isArray(u)?u:[],o.delete("args"),t.search=i.toString(),this._setUrlFragment(t,o),history.replaceState(history.state,"",t.href),{origin:r.origin,data:{id:c,command:l,args:u},returnURL:h,responseMethod:d,source:d===s.POST_MESSAGE?window.opener||window.parent:null}}static receiveRedirectResponse(e){const t=new URL(e.href);if(!document.referrer)return null;const s=new URL(document.referrer),i=new URLSearchParams(t.search),o=new URLSearchParams(t.hash.substring(1));if(!o.has("id"))return null;const c=parseInt(o.get("id"),10);if(o.delete("id"),i.set(a.URL_SEARCHPARAM_NAME,c.toString()),!o.has("status"))return null;const l=o.get("status")===r.OK?r.OK:r.ERROR;if(o.delete("status"),!o.has("result"))return null;const h=n.parse(o.get("result"));return o.delete("result"),t.search=i.toString(),this._setUrlFragment(t,o),history.replaceState(history.state,"",t.href),{origin:s.origin,data:{id:c,status:l,result:h}}}static prepareRedirectReply(e,t,s){const r=new URL(e.returnURL),i=new URLSearchParams(r.hash.substring(1));return i.set("id",e.id.toString()),i.set("status",t),i.set("result",n.stringify(s)),r.hash=i.toString(),r.href}static prepareRedirectInvocation(e,t,s,r,i,o){const a=new URL(e),c=new URLSearchParams(a.hash.substring(1));return c.set("id",t.toString()),c.set("returnURL",s),c.set("command",r),c.set("responseMethod",o),Array.isArray(i)&&c.set("args",n.stringify(i)),a.hash=c.toString(),a.href}static _setUrlFragment(e,t){t.toString().endsWith("=")?e.hash=t.toString().slice(0,-1):e.hash=t.toString()}}a.URL_SEARCHPARAM_NAME="rpcId";class c{constructor(e,t=!1){this._allowedOrigin=e,this._waitingRequests=new o(t),this._responseHandlers=new Map,this._preserveRequests=!1}onResponse(e,t,s){this._responseHandlers.set(e,{resolve:t,reject:s})}_receive(e){if(!e.data||!e.data.status||!e.data.id||"*"!==this._allowedOrigin&&e.origin!==this._allowedOrigin)return!1;const t=e.data,s=this._getCallback(t.id),n=this._waitingRequests.getState(t.id);if(s){if(this._preserveRequests||(this._waitingRequests.remove(t.id),this._responseHandlers.delete(t.id)),console.debug("RpcClient RECEIVE",t),t.status===r.OK)s.resolve(t.result,t.id,n);else if(t.status===r.ERROR){const e=new Error(t.result.message);t.result.stack&&(e.stack=t.result.stack),t.result.name&&(e.name=t.result.name),s.reject(e,t.id,n)}return!0}return console.warn("Unknown RPC response:",t),!1}_getCallback(e){if(this._responseHandlers.has(e))return this._responseHandlers.get(e);{const t=this._waitingRequests.getCommand(e);if(t)return this._responseHandlers.get(t)}}}class l extends c{constructor(e,t){super(t),this._serverCloseCheckInterval=-1,this._target=e,this._connectionState=0,this._receiveListener=this._receive.bind(this)}async init(){2!==this._connectionState&&(await this._connect(),window.addEventListener("message",this._receiveListener),-1===this._serverCloseCheckInterval&&(this._serverCloseCheckInterval=window.setInterval(()=>this._checkIfServerClosed(),300)))}async call(e,...t){return this._call({command:e,args:t,id:i.generateRandomId()})}close(){this._connectionState=0,window.removeEventListener("message",this._receiveListener),window.clearInterval(this._serverCloseCheckInterval),this._serverCloseCheckInterval=-1;for(const[e,{reject:t}]of this._responseHandlers){const s=this._waitingRequests.getState(e);t("Connection was closed","number"==typeof e?e:void 0,s)}this._waitingRequests.clear(),this._responseHandlers.clear(),this._target&&this._target.closed&&(this._target=null)}_receive(e){return e.source===this._target&&super._receive(e)}async _call(e){if(!this._target||this._target.closed)throw new Error("Connection was closed.");if(2!==this._connectionState)throw new Error("Client is not connected, call init first");return new Promise((t,s)=>{this._responseHandlers.set(e.id,{resolve:t,reject:s}),this._waitingRequests.add(e.id,e.command),console.debug("RpcClient REQUEST",e.command,e.args),this._target.postMessage(e,this._allowedOrigin)})}_connect(){if(2!==this._connectionState)return this._connectionState=1,new Promise((e,t)=>{const s=t=>{const{source:n,origin:i,data:o}=t;if(n===this._target&&o.status===r.OK&&"pong"===o.result&&1===o.id&&("*"===this._allowedOrigin||i===this._allowedOrigin)){if(o.result.stack){const e=new Error(o.result.message);e.stack=o.result.stack,o.result.name&&(e.name=o.result.name),console.error(e)}window.removeEventListener("message",s),this._connectionState=2,console.log("RpcClient: Connection established"),e(!0)}};window.addEventListener("message",s);const n=()=>{if(2!==this._connectionState){if(0===this._connectionState||this._checkIfServerClosed())return window.removeEventListener("message",s),void t(new Error("Connection was closed"));try{this._target.postMessage({command:"ping",id:1},this._allowedOrigin)}catch(e){console.error(`postMessage failed: ${e}`)}window.setTimeout(n,100)}};window.setTimeout(n,100)})}_checkIfServerClosed(){return!(this._target&&!this._target.closed)&&(this.close(),!0)}}class h extends c{constructor(e,t,s=!0){super(t,!0),this._target=e,this._preserveRequests=s}async init(){const e=a.receiveRedirectResponse(window.location);if(e)return void this._receive(e);if(this._rejectOnBack())return;const t=new URLSearchParams(window.location.search);if(t.has(a.URL_SEARCHPARAM_NAME)){const e=window.sessionStorage.getItem(`response-${t.get(a.URL_SEARCHPARAM_NAME)}`);if(e)return void this._receive(n.parse(e),!1)}}close(){}call(e,t,r,...n){if(r&&"boolean"!=typeof r){if("object"==typeof r){if(r.responseMethod===s.POST_MESSAGE){if(!window.opener&&!window.parent)throw new Error("Window has no opener or parent, responseMethod: ResponseMethod.POST_MESSAGE would fail.");console.warn("Response will skip at least one rpc call, which will result in an unknown response.")}this._call(e,t,r,...n)}}else"boolean"==typeof r&&console.warn("RedirectRpcClient.call(string, string, boolean, any[]) is deprecated. Use RedirectRpcClient.call(string, string, CallOptions, any[]) with an appropriate CallOptions object instead."),this._call(e,t,{responseMethod:s.HTTP_GET,handleHistoryBack:!!r},...n)}callAndSaveLocalState(e,t,r,n=!1,...i){console.warn("RedirectRpcClient.callAndSaveLocalState() is deprecated. Use RedirectRpcClient.call() with an apropriate CallOptions object instead."),this._call(e,r,{responseMethod:s.HTTP_GET,state:t||void 0,handleHistoryBack:n},...i)}_receive(e,t=!0){const s=super._receive(e);return s&&t&&window.sessionStorage.setItem(`response-${e.data.id}`,n.stringify(e)),s}_call(e,t,r,...n){const o=i.generateRandomId(),c=r.responseMethod||s.HTTP_GET,l=a.prepareRedirectInvocation(this._target,o,e,t,n,c);this._waitingRequests.add(o,t,r.state||null),r.handleHistoryBack&&history.replaceState(Object.assign({},history.state,{rpcBackRejectionId:o}),""),console.debug("RpcClient REQUEST",t,n),window.location.href=l}_rejectOnBack(){if(!history.state||!history.state.rpcBackRejectionId)return!1;const e=history.state.rpcBackRejectionId;history.replaceState(Object.assign({},history.state,{rpcBackRejectionId:null}),"");const t=this._getCallback(e),s=this._waitingRequests.getState(e);if(t){this._preserveRequests||(this._waitingRequests.remove(e),this._responseHandlers.delete(e)),console.debug("RpcClient BACK");const r=new Error("Request aborted");return t.reject(r,e,s),!0}return!1}}var d={"popup-overlay":"A popup has been opened,\nclick anywhere to bring it back to the front."};const u={de:{"popup-overlay":"Ein Popup hat sich geöffnet,\nklicke hier, um zurück zum Popup zu kommen."},en:d,es:{"popup-overlay":"Se ha abierto una ventana emergente.\nHaga click en cualquier lugar para traer la ventana al primer plano."},fil:{"popup-overlay":"Nag-bukas ang isang pop-up.\nMaaring i-click kahit saan para ibalik ito sa harap."},fr:{"popup-overlay":"Une popup a été ouverte,\ncliquez n'importe où pour la ramener au premier plan."},nl:{"popup-overlay":"Er is een pop-up geopend,\nklik op het scherm om het weer naar voren te brengen."},ru:{"popup-overlay":"Открыто всплывающее окно.\nНажмите где-нибудь, чтобы вернуть его на передний план."},zh:{"popup-overlay":"弹出窗口已打开,\n单击任意位置即可回到前页。"}};class p{constructor(e){this._type=e}static getAllowedOrigin(e){return new URL(e).origin}async request(e,t,s){throw new Error("Not implemented")}}var _,g,w,m,f,R,A;!function(e){e[e.REDIRECT=0]="REDIRECT",e[e.POPUP=1]="POPUP",e[e.IFRAME=2]="IFRAME"}(_||(_={}));class S extends p{constructor(e,t){super(_.REDIRECT);const s=window.location;if(this._returnUrl=e||`${s.origin}${s.pathname}`,this._localState=t||{},void 0!==this._localState.__command)throw new Error("Invalid localState: Property '__command' is reserved")}static withLocalState(e){return new S(void 0,e)}async request(e,t,s){const r=p.getAllowedOrigin(e),n=new h(e,r);await n.init();const i=Object.assign({},this._localState,{__command:t});n.callAndSaveLocalState(this._returnUrl,i,t,!0,...await Promise.all(s))}}class v extends p{constructor(e=v.DEFAULT_FEATURES,t){super(_.POPUP),this._popupFeatures=e,this._options={...v.DEFAULT_OPTIONS,...t}}async request(e,t,s){const r=p.getAllowedOrigin(e),n=this.createPopup(e),i=this.appendOverlay(n),o=new l(n,r);try{return await o.init(),await o.call(t,...await Promise.all(s))}catch(e){throw e}finally{this.removeOverlay(i),o.close(),n.close()}}createPopup(e){const t=window.open(e,"NimiqAccounts",this._popupFeatures);if(!t)throw new Error("Failed to open popup");return t}appendOverlay(e){if(!this._options.overlay)return null;const t=document.createElement.bind(document),s=(e,t)=>e.appendChild(t),r=t("div");r.id="nimiq-hub-overlay";const n=r.style;n.position="fixed",n.top="0",n.right="0",n.bottom="0",n.left="0",n.background="rgba(31, 35, 72, 0.8)",n.display="flex",n.flexDirection="column",n.alignItems="center",n.justifyContent="space-between",n.cursor="pointer",n.color="white",n.textAlign="center",n.opacity="0",n.transition="opacity 0.6s ease",n.zIndex="99999",r.addEventListener("click",()=>e.focus()),s(r,t("div"));const i=t("div");i.textContent=function(e,t){if(!t){const e=document.cookie.match(/(^| )lang=([^;]+)/);t=e&&e[2]||navigator.language.split("-")[0]}return(u[t]||d)[e]||d[e]}("popup-overlay");const o=i.style;o.padding="20px",o.fontFamily='Muli, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif',o.fontSize="24px",o.fontWeight="600",o.lineHeight="40px",o.whiteSpace="pre-line",s(r,i);const a=t("img");a.src='data:image/svg+xml,<svg width="135" height="32" viewBox="0 0 135 32" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M35.6 14.5l-7.5-13A3 3 0 0025.5 0h-15a3 3 0 00-2.6 1.5l-7.5 13a3 3 0 000 3l7.5 13a3 3 0 002.6 1.5h15a3 3 0 002.6-1.5l7.5-13a3 3 0 000-3z" fill="url(%23hub-overlay-nimiq-logo)"/><path d="M62.25 6.5h3.26v19H63L52.75 12.25V25.5H49.5v-19H52l10.25 13.25V6.5zM72 25.5v-19h3.5v19H72zM97.75 6.5h2.75v19h-3V13.75L92.37 25.5h-2.25L85 13.75V25.5h-3v-19h2.75l6.5 14.88 6.5-14.88zM107 25.5v-19h3.5v19H107zM133.88 21.17a7.91 7.91 0 01-4.01 3.8c.16.38.94 1.44 1.52 2.05.59.6 1.2 1.23 1.98 1.86L131 30.75a15.91 15.91 0 01-4.45-5.02l-.8.02c-1.94 0-3.55-.4-4.95-1.18a7.79 7.79 0 01-3.2-3.4 11.68 11.68 0 01-1.1-5.17c0-2.03.37-3.69 1.12-5.17a7.9 7.9 0 013.2-3.4 9.8 9.8 0 014.93-1.18c1.9 0 3.55.4 4.94 1.18a7.79 7.79 0 013.2 3.4 11.23 11.23 0 011.1 5.17c0 2.03-.44 3.83-1.11 5.17zm-12.37.01a5.21 5.21 0 004.24 1.82 5.2 5.2 0 004.23-1.82c1.01-1.21 1.52-2.92 1.52-5.18 0-2.24-.5-4-1.52-5.2a5.23 5.23 0 00-4.23-1.8c-1.82 0-3.23.6-4.24 1.79-1 1.2-1.51 2.95-1.51 5.21s.5 3.97 1.51 5.18z" fill="white"/><defs><radialGradient id="hub-overlay-nimiq-logo" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-35.9969 0 0 -32 36 32)"><stop stop-color="%23EC991C"/><stop offset="1" stop-color="%23E9B213"/></radialGradient></defs></svg>',a.style.marginBottom="56px",s(r,a);const c=t("div"),l=c.style;return c.innerHTML="×",l.position="absolute",l.top="8px",l.right="8px",l.fontSize="24px",l.lineHeight="32px",l.fontWeight="600",l.width="32px",l.height="32px",l.opacity="0.8",c.addEventListener("click",()=>e.close()),s(r,c),setTimeout(()=>r.style.opacity="1",100),s(document.body,r)}removeOverlay(e){e&&(e.style.opacity="0",setTimeout(()=>document.body.removeChild(e),400))}}v.DEFAULT_FEATURES="",v.DEFAULT_OPTIONS={overlay:!0};class E extends p{constructor(){super(_.IFRAME),this._iframe=null,this._client=null}async request(e,t,s){if(this._iframe&&this._iframe.src!==`${e}${E.IFRAME_PATH_SUFFIX}`)throw new Error("Hub iframe is already opened with another endpoint");const r=p.getAllowedOrigin(e);if(this._iframe||(this._iframe=await this.createIFrame(e)),!this._iframe.contentWindow)throw new Error(`IFrame contentWindow is ${typeof this._iframe.contentWindow}`);return this._client||(this._client=new l(this._iframe.contentWindow,r),await this._client.init()),await this._client.call(t,...await Promise.all(s))}async createIFrame(e){return new Promise((t,s)=>{const r=document.createElement("iframe");r.name="NimiqAccountsIFrame",r.style.display="none",document.body.appendChild(r),r.src=`${e}${E.IFRAME_PATH_SUFFIX}`,r.onload=(()=>t(r)),r.onerror=s})}}E.IFRAME_PATH_SUFFIX="/iframe.html",function(e){e.LIST="list",e.LIST_CASHLINKS="list-cashlinks",e.MIGRATE="migrate",e.CHECKOUT="checkout",e.SIGN_MESSAGE="sign-message",e.SIGN_TRANSACTION="sign-transaction",e.ONBOARD="onboard",e.SIGNUP="signup",e.LOGIN="login",e.EXPORT="export",e.CHANGE_PASSWORD="change-password",e.LOGOUT="logout",e.ADD_ADDRESS="add-address",e.RENAME="rename",e.CHOOSE_ADDRESS="choose-address",e.CREATE_CASHLINK="create-cashlink",e.MANAGE_CASHLINK="manage-cashlink",e.SIGN_BTC_TRANSACTION="sign-btc-transaction",e.ADD_BTC_ADDRESSES="add-btc-addresses",e.ACTIVATE_BITCOIN="activate-bitcoin",e.SETUP_SWAP="setup-swap",e.REFUND_SWAP="refund-swap"}(g||(g={})),function(e){e[e.DIRECT=0]="DIRECT",e[e.OASIS=1]="OASIS"}(w||(w={})),function(e){e.NIM="nim",e.BTC="btc",e.ETH="eth"}(m||(m={})),function(e){e.NOT_FOUND="NOT_FOUND",e.PAID="PAID",e.UNDERPAID="UNDERPAID",e.OVERPAID="OVERPAID"}(f||(f={})),function(e){e[e.UNKNOWN=-1]="UNKNOWN",e[e.UNCHARGED=0]="UNCHARGED",e[e.CHARGING=1]="CHARGING",e[e.UNCLAIMED=2]="UNCLAIMED",e[e.CLAIMING=3]="CLAIMING",e[e.CLAIMED=4]="CLAIMED"}(R||(R={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.STANDARD=1]="STANDARD",e[e.CHRISTMAS=2]="CHRISTMAS",e[e.LUNAR_NEW_YEAR=3]="LUNAR_NEW_YEAR",e[e.EASTER=4]="EASTER",e[e.GENERIC=5]="GENERIC",e[e.BIRTHDAY=6]="BIRTHDAY"}(A||(A={}));class I{constructor(e=I.DEFAULT_ENDPOINT,t){this._endpoint=e,this._defaultBehavior=t||new v(`left=${window.innerWidth/2-400},top=75,width=800,height=850,location=yes,dependent=yes`),this._checkoutDefaultBehavior=t||new v(`left=${window.innerWidth/2-400},top=50,width=800,height=895,location=yes,dependent=yes`),this._iframeBehavior=new E,this._redirectClient=new h("",p.getAllowedOrigin(this._endpoint))}static get PaymentMethod(){return console.warn("PaymentMethod has been renamed to PaymentType. Access via HubApi.PaymentMethod will soon get disabled. Use HubApi.PaymentType instead."),w}static get DEFAULT_ENDPOINT(){const e=location.origin.split(".");switch(e.shift(),e.join(".")){case"nimiq.com":return"https://hub.nimiq.com";case"nimiq-testnet.com":return"https://hub.nimiq-testnet.com";default:return"http://localhost:8080"}}checkRedirectResponse(){return this._redirectClient.init()}on(e,t,s){this._redirectClient.onResponse(e,(e,s,r)=>t(e,r),(e,t,r)=>{s&&s(e,r)})}createCashlink(e,t=this._defaultBehavior){return this._request(t,g.CREATE_CASHLINK,[e])}manageCashlink(e,t=this._defaultBehavior){return this._request(t,g.MANAGE_CASHLINK,[e])}checkout(e,t=this._checkoutDefaultBehavior){return this._request(t,g.CHECKOUT,[e])}chooseAddress(e,t=this._defaultBehavior){return this._request(t,g.CHOOSE_ADDRESS,[e])}signTransaction(e,t=this._defaultBehavior){return this._request(t,g.SIGN_TRANSACTION,[e])}signMessage(e,t=this._defaultBehavior){return this._request(t,g.SIGN_MESSAGE,[e])}signBtcTransaction(e,t=this._defaultBehavior){return this._request(t,g.SIGN_BTC_TRANSACTION,[e])}setupSwap(e,t=this._defaultBehavior){return this._request(t,g.SETUP_SWAP,[e])}refundSwap(e,t=this._defaultBehavior){return this._request(t,g.REFUND_SWAP,[e])}onboard(e,t=this._defaultBehavior){return this._request(t,g.ONBOARD,[e])}signup(e,t=this._defaultBehavior){return this._request(t,g.SIGNUP,[e])}login(e,t=this._defaultBehavior){return this._request(t,g.LOGIN,[e])}logout(e,t=this._defaultBehavior){return this._request(t,g.LOGOUT,[e])}export(e,t=this._defaultBehavior){return this._request(t,g.EXPORT,[e])}changePassword(e,t=this._defaultBehavior){return this._request(t,g.CHANGE_PASSWORD,[e])}addAddress(e,t=this._defaultBehavior){return this._request(t,g.ADD_ADDRESS,[e])}rename(e,t=this._defaultBehavior){return this._request(t,g.RENAME,[e])}migrate(e=this._defaultBehavior){return this._request(e,g.MIGRATE,[{appName:"Account list"}])}activateBitcoin(e,t=this._defaultBehavior){return this._request(t,g.ACTIVATE_BITCOIN,[e])}list(e=this._iframeBehavior){return this._request(e,g.LIST,[])}cashlinks(e=this._iframeBehavior){return this._request(e,g.LIST_CASHLINKS,[])}addBtcAddresses(e,t=this._iframeBehavior){return this._request(t,g.ADD_BTC_ADDRESSES,[e])}_request(e,t,s){return e.request(this._endpoint,t,s)}}return I.RequestType=g,I.RedirectRequestBehavior=S,I.PopupRequestBehavior=v,I.CashlinkState=R,I.CashlinkTheme=A,I.Currency=m,I.PaymentType=w,I.PaymentState=f,I.MSG_PREFIX="Nimiq Signed Message:\n",I}); |
{ | ||
"name": "@nimiq/hub-api", | ||
"version": "1.3.0-beta.3", | ||
"version": "1.3.0-beta.4", | ||
"main": "dist/HubApi.umd.js", | ||
@@ -5,0 +5,0 @@ "module": "dist/HubApi.es.js", |
124451
1944