@wishknish/knishio-client-js 0.4.39 → 0.4.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("js-sha3"),require("big-integer"),require("@stablelib/base64"),require("get-random-values"),require("big-integer/BigInteger"),require("buffer"),require("base-x"),require("tweetnacl"),require("tweetnacl-sealedbox-js"),require("@stablelib/utf8"),require("@apollo/client/core"),require("isomorphic-fetch"),require("@apollo/client/cache"),require("@apollo/client/link/error"),require("laravel-echo"),require("socket.io-client"),require("graphql")):"function"==typeof define&&define.amd?define(["exports","js-sha3","big-integer","@stablelib/base64","get-random-values","big-integer/BigInteger","buffer","base-x","tweetnacl","tweetnacl-sealedbox-js","@stablelib/utf8","@apollo/client/core","isomorphic-fetch","@apollo/client/cache","@apollo/client/link/error","laravel-echo","socket.io-client","graphql"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).KnishIO={},e.jsSha3,e.bigInt,e.base64,e.getRandomValues,e.bigIntB,e.buffer,e.baseX,e.tweetnacl,e.tweetnaclSealedboxJs,e.utf8,e.core,e.fetch,e.cache,e.error,e.Echo,e.io,e.graphql)}(this,(function(e,t,s,n,a,i,r,l,o,u,c,h,d,p,m,y,g,b){"use strict";function k(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var f=k(s),_=k(a),w=k(i),$=k(l),I=k(d),S=k(y),A=k(g);class x{static toHex(e,t){const s=(e,t)=>{const s=t?["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]:["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];return s[Math.floor(e/16)]+s[e%16]},n=Object.assign({grouping:0,rowlength:0,uppercase:!1},t||{});let a="",i=0,r=0;for(let t=0;t<e.length&&(a+=s(e[t],n.uppercase),t!==e.length-1);++t)n.grouping>0&&++i===n.grouping&&(i=0,n.rowlength>0&&++r===n.rowlength?(r=0,a+="\n"):a+=" ");return a}static toUint8Array(e){let t=e.toLowerCase().replace(/\s/g,"");t.length%2==1&&(t=`0${t}`);let s=new Uint8Array(Math.floor(t.length/2)),n=-1;for(let e=0;e<t.length;++e){let a=t[e],i=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"].indexOf(a);if(-1===i)throw Error("unexpected character");-1===n?n=16*i:(s[Math.floor(e/2)]=n+i,n=-1)}return s}}function T(e,t){const s=Math.ceil(e.length/t),n=[];for(let a=0,i=0;a<s;++a,i+=t)n[a]=e.substr(i,t);return n}function q(e=256,t="abcdef0123456789"){let s=new Uint8Array(e);return s=_.default(s),s=s.map((e=>t.charCodeAt(e%t.length))),String.fromCharCode.apply(null,s)}function v(e,t,s,n,a){if(n=n||"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~`!@#$%^&*()-_=+[{]}\\|;:'\",<.>/?¿¡",a=a||n,t>n.length||s>a.length)return console.warn("Strings::charsetBaseConvert() - Can't convert",e,"to base",s,"greater than symbol table length. src-table:",n.length,"dest-table:",a.length),!1;let i=f.default(0);for(let s=0;s<e.length;s++)i=i.multiply(t).add(n.indexOf(e.charAt(s)));if(i.lesser(0))return 0;let r=i.mod(s),l=a.charAt(r),o=i.divide(s);for(;!o.equals(0);)r=o.mod(s),o=o.divide(s),l=a.charAt(r)+l;return l}function M(e){return n.encode(x.toUint8Array(e))}function C(e){return x.toHex(n.decode(e),{})}function W(e){return/^[A-F0-9]+$/i.test(e)}function H(e,t){let s,n,a,i=[Array,Date,Number,String,Boolean],r=Object.prototype.toString;for(t=t||[],s=0;s<t.length;s+=2)e===t[s]&&(n=t[s+1]);if(!n&&e&&"object"==typeof e){for(n={},s=0;s<i.length;s++)r.call(e)===r.call(a=new i[s](e))&&(n=s?a:[]);for(s in t.push(e,n),e)t.hasOwnProperty.call(e,s)&&(n[s]=H(e[s],t))}return n||e}function B(...e){return[].concat(...e.map(((t,s)=>{const n=e.slice(0);n.splice(s,1);const a=[...new Set([].concat(...n))];return t.filter((e=>!a.includes(e)))})))}String.prototype.trim||(String.prototype.trim=function(){return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}),String.prototype.toCamelCase||(String.prototype.toCamelCase=function(){return this.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g,((e,t)=>t.toUpperCase()))}),String.prototype.toSnakeCase||(String.prototype.toSnakeCase=function(){return this.replace(/[A-Z]/g,(e=>`_${e.toLowerCase()}`))});class U{constructor({meta:e}){this.meta=e,this.createdAt=+new Date}static normalizeMeta(e){const t=[];for(const s in e)e.hasOwnProperty(s)&&null!==e[s]&&t.push({key:s,value:e[s].toString()});return t}static aggregateMeta(e){let t={};if(Array.isArray(e))for(let s of e)t[s.key]=s.value;else t=e;return t}static policy(e,t){const s={conditions:"policy",rule:e.rule||[],callback:e.callback||{}};if(t)for(const[e,n]of Object.entries(t||{}))if(null!==n&&["read","write"].includes(e)){s.callback[e]={};for(const[t,a]of Object.entries(n))s.callback[e][t]=a}s.callback=U.__defaultPolicy(s.callback,e);for(const e of["conditions","rule","callback"])s[e]=Array.isArray(s[e])||"[object Object]"===Object.prototype.toString.call(s[e])?JSON.stringify(s[e]):s[e],"conditions"===e&&"[object String]"===Object.prototype.toString.call(s[e])&&(s[e]=JSON.stringify(s[e]));return s}static __defaultPolicy(e,t){const s=H(e),n=Array.from(s).filter((e=>"read"===e.action)),a=Array.from(s).filter((e=>"write"===e.action)),i=Object.keys(t||{});for(const[e,t]of Object.entries({read:n,write:a})){const n=t.map((e=>e.key));s[e]||(s[e]={});for(const t of B(i,n))s[e][t]||(s[e][t]="write"!==e||["characters","pubkey"].includes(t)?["all"]:["self"])}return s}}class j{constructor({position:e=null,walletAddress:t=null,isotope:s=null,token:n=null,value:a=null,batchId:i=null,metaType:r=null,metaId:l=null,meta:o=null,otsFragment:u=null,index:c=null}){this.position=e,this.walletAddress=t,this.isotope=s,this.token=n,this.value=null!==a?String(a):null,this.batchId=i,this.metaType=r,this.metaId=l,this.meta=o?U.normalizeMeta(o):[],this.index=c,this.otsFragment=u,this.createdAt=String(+new Date)}static get create(){return{C({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="C",new j(arguments[0])},I({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="I",new j(arguments[0])},M({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="M",new j(arguments[0])},T({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="T",new j(arguments[0])},U({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="U",new j(arguments[0])},V({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="V",new j(arguments[0])},R({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="R",new j(arguments[0])}}}static get hashSchema(){return new Map([["position",null],["walletAddress",null],["isotope",null],["token",null],["value",null],["batchId",null],["metaType",null],["metaId",null],["meta",null],["createdAt",null]])}aggregatedMeta(){return U.aggregateMeta(this.meta)}static jsonToObject(e){const t=Object.assign(new j({}),JSON.parse(e)),s=Object.keys(new j({}));for(const e in t)t.hasOwnProperty(e)&&!s.includes(e)&&delete t[e];return t}static molecularHashSchema(e){const t=j.hashSchema;for(const s in e)e.hasOwnProperty(s)&&t.has(s)&&t.set(s,e[s]);return t}static hashAtoms({atoms:e,output:s="base17"}){const n=t.shake256.create(256),a=e.length,i=j.sortAtoms(e);for(const e of i){const t=j.molecularHashSchema(e);n.update(String(a));for(const e of t.keys()){const s=t.get(e);if(null!==s||["position","walletAddress"].includes(e))if("meta"!==e)n.update(null===s?"":String(s));else for(const e of s)void 0!==e.value&&null!==e.value&&(n.update(String(e.key)),n.update(String(e.value)))}}switch(s){case"hex":return n.hex();case"array":return n.array();default:return v(n.hex(),16,17,"0123456789abcdef","0123456789abcdefg").padStart(64,"0")}}static sortAtoms(e){const t=[...e];return t.sort(((e,t)=>e.index===t.index?0:e.index<t.index?-1:1)),t}}class O{static encode(e){return n.encode(e)}static decode(e){return r.Buffer.from(n.decode(e))}encode(e){return O.encode(e)}decode(e){return O.decode(e)}}class R{constructor(e={}){this.$options=Object.assign({characters:"GMP"},e),this.$encoder=$.default(this[this.$options.characters]||this.GMP)}encode(e){return this.$encoder.encode(r.Buffer.from(e))}decode(e){return this.$encoder.decode(e)}get GMP(){return"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv"}get BITCOIN(){return"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}get FLICKR(){return"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}get RIPPLE(){return"rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"}get IPFS(){return"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}}class E{constructor(e={}){this.$options=Object.assign({characters:"BASE64"},e),this.$encoder=new R,["BASE64"].includes(this.$options.characters)?this.$encoder=new O:["BASE2","BASE8","BASE11","BASE36","BASE62","BASE67"].includes(this.$options.characters)?this.$encoder=$.default(this[this.$options.characters]):["BITCOIN","FLICKR","RIPPLE","IPFS"].includes(this.$options.characters)&&(this.$encoder=new R(this.$options))}encode(e){return this.$encoder.encode(r.Buffer.from(e))}decode(e){return this.$encoder.decode(e)}get BASE2(){return"01"}get BASE8(){return"01234567"}get BASE11(){return"0123456789a"}get BASE36(){return"0123456789abcdefghijklmnopqrstuvwxyz"}get BASE62(){return"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"}get BASE67(){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~"}}class K{constructor(e=null){this.base=new E({characters:e||"BASE64"})}encrypt(e,t){return this.encode(u.seal(c.encode(JSON.stringify(e)),this.decode(t)))}decrypt(e,t,s){try{return JSON.parse(c.decode(u.open(this.decode(e),this.decode(s),this.decode(t))))}catch(e){return null}}generatePrivateKey(e){const s=t.shake256.create(8*o.box.secretKeyLength);return s.update(e),this.base.encode(r.Buffer.from(s.digest()))}generatePublicKey(e){const t=o.box.keyPair.fromSecretKey(this.decode(e));return this.encode(t.publicKey)}shortHash(e){const s=t.shake256.create(64);return s.update(e),this.base.encode(r.Buffer.from(s.digest()))}decode(e){return this.base.decode(e)}encode(e){return this.base.encode(e)}}function Q(e=null,s=2048){if(console.info(`Crypto::generateSecret() - Computing new secret${e?" from existing seed":""}...`),e){const n=t.shake256.create(2*s);return n.update(e),n.hex()}return q(s)}function P(e){console.info("Crypto::generateBundleHash() - Computing wallet bundle from secret...");const s=t.shake256.create(256);return s.update(e),s.hex()}function N({molecularHash:e=null,index:t=null}){return null!==e&&null!==t?P(String(e)+String(t)):q(64)}function F(e=64){return q(e,"abcdef0123456789")}function V(e,t,s=null){return new K(s).encrypt(e,t)}function D(e,t,s,n=null){return new K(n).decrypt(e,t,s)}function J(e,t=null){return new K(t).generatePrivateKey(e)}function L(e,t=null){return new K(t).generatePublicKey(e)}function z(e,t=null){return new K(t).shortHash(e)}class G{constructor({secret:e=null,token:t="USER",position:s=null,batchId:n=null,characters:a=null}){this.token=t,this.balance=0,this.molecules={},this.key=null,this.address=null,this.privkey=null,this.pubkey=null,this.tokenUnits=[],this.bundle=e?P(e):null,this.batchId=n,this.position=s,this.characters=a||"BASE64",e&&(this.position=this.position||F(),this.prepareKeys(e))}static create({secretOrBundle:e,token:t,batchId:s=null,characters:n=null}){let a=G.isBundleHash(e)?null:e,i=a?P(a):e,r=a?F():null,l=new G({secret:a,token:t,position:r,batchId:s,characters:n});return l.bundle=i,l}static isBundleHash(e){return"string"==typeof e&&(64===e.length&&W(e))}static getTokenUnits(e){let t=[];return e.forEach((e=>{t.push({id:e.shift(),name:e.shift(),metas:e})})),t}hasTokenUnits(){return!!this.tokenUnits&&this.tokenUnits.length>0}tokenUnitsJson(){if(this.hasTokenUnits()){const e=[];return this.tokenUnits.forEach((t=>{e.push([t.id,t.name].concat(t.metas))})),JSON.stringify(e)}return null}splitUnits(e,t,s=null){if(0===e.length)return;let n=[],a=[];this.tokenUnits.forEach((t=>{e.includes(t.id)?n.push(t):a.push(t)})),this.tokenUnits=n,null!==s&&(s.tokenUnits=n),t.tokenUnits=a}isShadow(){return!(void 0!==this.position&&null!==this.position||void 0!==this.address&&null!==this.address)}initBatchId({sourceWallet:e,isRemainder:t=!1}){e.batchId&&(this.batchId=t?e.batchId:N({}))}prepareKeys(e){null===this.key&&null===this.address&&(this.key=G.generatePrivateKey({secret:e,token:this.token,position:this.position}),this.address=G.generatePublicKey(this.key),this.getMyEncPrivateKey(),this.getMyEncPublicKey())}getMyEncPrivateKey(){return null===this.privkey&&null!==this.key&&(this.privkey=J(this.key,this.characters)),this.privkey}getMyEncPublicKey(){const e=this.getMyEncPrivateKey();return!this.pubkey&&e&&(this.pubkey=L(e,this.characters)),this.pubkey}encryptMyMessage(e){const t={};for(let s=1,n=arguments.length;s<n;s++)t[z(arguments[s],this.characters)]=V(e,arguments[s],this.characters);return t}decryptMyMessage(e){const t=this.getMyEncPublicKey();let s=e;return null!==e&&"object"==typeof e&&"[object Object]"===Object.prototype.toString.call(e)&&(s=e[z(t,this.characters)]||""),D(s,this.getMyEncPrivateKey(),t,this.characters)}decryptBinary(e){const t=this.decryptMyMessage(e);return new E({characters:"BASE64"}).decode(t)}encryptBinary(e){const t=Array.from(arguments).slice(1),s=new E({characters:"BASE64"}).encode(e);return this.encryptMyMessage(s,...t)}encryptString({data:e,publicKeys:t}){if(e){const s=this.getMyEncPublicKey();"string"==typeof t&&(t=[t]);const n=this.encryptMyMessage(e,s,...t);return btoa(JSON.stringify(n))}}decryptString({data:e,fallbackValue:t=null}){if(e)try{const s=JSON.parse(atob(e));return this.decryptMyMessage(s)||t}catch(s){return console.error(s),t||e}}static generatePrivateKey({secret:e,token:s,position:n}){const a=w.default(e,16).add(w.default(n,16)),i=t.shake256.create(8192);return i.update(a.toString(16)),s&&i.update(s),t.shake256.create(8192).update(i.hex()).hex()}static generatePublicKey(e){const s=T(e,128),n=t.shake256.create(8192);for(const e in s){let a=s[e];for(let e=1;e<=16;e++)a=t.shake256.create(512).update(a).hex();n.update(a)}return t.shake256.create(256).update(n.hex()).hex()}}class Z extends TypeError{constructor(e=null,t=null,s=null){if(super(e,t,s),null===e)throw new this(`Unknown ${this.constructor.name}`);this.name="BaseException"}toString(){return`${this.name}: ${this.message}.\nStack:\n${this.stack}`}}class X extends Z{constructor(e="There is an atom without an index",t=null,s=null){super(e,t,s),this.name="AtomIndexException"}}class Y extends Z{constructor(e="The molecule does not contain atoms",t=null,s=null){super(e,t,s),this.name="AtomsMissingException"}}class ee extends Z{constructor(e="The molecular hash does not match",t=null,s=null){super(e,t,s),this.name="MolecularHashMismatchException"}}class te extends Z{constructor(e="The molecular hash is missing",t=null,s=null){super(e,t,s),this.name="MolecularHashMissingException"}}class se extends Z{constructor(e="OTS malformed",t=null,s=null){super(e,t,s),this.name="SignatureMalformedException"}}class ne extends Z{constructor(e="One-time signature (OTS) does not match!",t=null,s=null){super(e,t,s),this.name="SignatureMismatchException"}}class ae extends Z{constructor(e="Insufficient balance to make transfer",t=null,s=null){super(e,t,s),this.name="TransferBalanceException"}}class ie extends Z{constructor(e="Token transfer atoms are malformed",t=null,s=null){super(e,t,s),this.name="TransferMalformedException"}}class re extends Z{constructor(e="Token slugs for wallets in transfer do not match!",t=null,s=null){super(e,t,s),this.name="TransferMismatchedException"}}class le extends Z{constructor(e="Invalid remainder provided",t=null,s=null){super(e,t,s),this.name="TransferRemainderException"}}class oe extends Z{constructor(e="Sender and recipient(s) cannot be the same",t=null,s=null){super(e,t,s),this.name="TransferToSelfException"}}class ue extends Z{constructor(e="Token transfer atoms are unbalanced",t=null,s=null){super(e,t,s),this.name="TransferUnbalancedException"}}class ce extends Z{constructor(e="Empty meta data.",t=null,s=null){super(e,t,s),this.name="MetaMissingException"}}class he extends Z{constructor(e="Wrong type of token for this isotope",t=null,s=null){super(e,t,s),this.name="WrongTokenTypeException"}}class de extends Z{constructor(e="Incorrect BatchId",t=null,s=null){super(e,t,s),this.name="BatchIdException"}}class pe extends Z{constructor(e="",t=null,s=null){super(e,t,s),this.name="KnishIOInvalidPolicyException"}}class me{static continuId(e){me.missing(e);if("USER"===e.atoms[0].token&&me.isotopeFilter("I",e.atoms).length<1)throw new Y("Check::continuId() - Molecule is missing required ContinuID Atom!");return!0}static batchId(e){if(e.atoms.length>0){const t=e.atoms[0];if("V"===t.isotope&&null!==t.batchId){const s=me.isotopeFilter("V",e.atoms),n=s[s.length-1];if(t.batchId!==n.batchId)throw new de;for(const e of s)if(null===e.batchId)throw new de}return!0}throw new de}static isotopeI(e){me.missing(e);for(let t of me.isotopeFilter("I",e.atoms)){if("USER"!==t.token)throw new he(`Check::isotopeI() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);if(0===t.index)throw new X(`Check::isotopeI() - Isotope "${t.isotope}" Atoms must have a non-zero index!`)}return!0}static isotopeU(e){me.missing(e);for(let t of me.isotopeFilter("U",e.atoms)){if("AUTH"!==t.token)throw new he(`Check::isotopeU() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);if(0!==t.index)throw new X(`Check::isotopeU() - Isotope "${t.isotope}" Atoms must have an index equal to 0!`)}return!0}static isotopeM(e){me.missing(e);const t=["readPolicy","writePolicy"];for(let s of me.isotopeFilter("M",e.atoms)){if(s.meta.length<1)throw new ce;if("USER"!==s.token)throw new he(`Check::isotopeM() - "${s.token}" is not a valid Token slug for "${s.isotope}" isotope Atoms!`);const e=U.aggregateMeta(s.meta);for(const s of t){let n=e[s];if(n){n=JSON.parse(n);for(const[s,a]of Object.entries(n))if(!t.includes(s)){if(!Object.keys(e).includes(s))throw new pe(`${s} is missing from the meta.`);for(const e of a)if(!G.isBundleHash(e)&&!["all","self"].includes(e))throw new pe(`${e} does not correspond to the format of the policy.`)}}}}return!0}static isotopeC(e){me.missing(e);for(let t of me.isotopeFilter("C",e.atoms)){if("USER"!==t.token)throw new he(`Check::isotopeC() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);if(0!==t.index)throw new X(`Check::isotopeC() - Isotope "${t.isotope}" Atoms must have an index equal to 0!`)}return!0}static isotopeT(e){me.missing(e);for(let t of me.isotopeFilter("T",e.atoms)){const e=t.aggregatedMeta();if("wallet"===String(t.metaType).toLowerCase())for(let t of["position","bundle"])if(!e.hasOwnProperty(t)||!Boolean(e[t]))throw new ce(`Check::isotopeT() - Required meta field "${t}" is missing!`);for(let t of["token"])if(!e.hasOwnProperty(t)||!Boolean(e[t]))throw new ce(`Check::isotopeT() - Required meta field "${t}" is missing!`);if("USER"!==t.token)throw new he(`Check::isotopeT() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);if(0!==t.index)throw new X(`Check::isotopeT() - Isotope "${t.isotope}" Atoms must have an index equal to 0!`)}return!0}static isotopeR(e){me.missing(e);for(let t of me.isotopeFilter("R",e.atoms)){const e=t.aggregatedMeta();for(let t of["callback","conditions","rule"])if(!e.hasOwnProperty(t))throw new ce(`Check::isotopeR() - Required meta field "${t}" is missing!`);try{JSON.parse(e.conditions),JSON.parse(e.callback)}catch(e){throw new ce("Check::isotopeR() - Condition is formatted incorrectly!")}if("policy"===conditions&&callback.length&&!callback.every((e=>["read","write"].includes(e.action))))throw new ce("Check::isotopeR() - Mixing rules with politics!");if(Array.isArray(conditions)&&conditions.length)for(let e of conditions){const t=Object.keys(e),s=t.filter((e=>-1!==["key","value","comparison"].indexOf(e))),n=t.filter((e=>-1!==["managedBy"].indexOf(e)));if(s.length<3&&n.length)throw new ce("Check::isotopeR() - Required condition field is missing!")}}return!0}static isotopeV(e,t=null){me.missing(e);const s=me.isotopeFilter("V",e.atoms);if(0===s.length)return!0;const n=e.atoms[0];if("V"===n.isotope&&2===s.length){const e=s[s.length-1];if(n.token!==e.token)throw new re;if(e.value<0)throw new ie;return!0}let a=0,i=0;for(let t in e.atoms)if(e.atoms.hasOwnProperty(t)){const s=e.atoms[t];if("V"!==s.isotope)continue;if(i=1*s.value,Number.isNaN(i))throw new TypeError('Invalid isotope "V" values');if(s.token!==n.token)throw new re;if(t>0){if(i<0)throw new ie;if(s.walletAddress===n.walletAddress)throw new oe}a+=i}if(a!==i)throw new ue;if(t){if(i=1*n.value,Number.isNaN(i))throw new TypeError('Invalid isotope "V" values');const e=1*t.balance+1*i;if(e<0)throw new ae;if(e!==a)throw new le}else if(0!==i)throw new le;return!0}static molecularHash(e){if(me.missing(e),e.molecularHash!==j.hashAtoms({atoms:e.atoms}))throw new ee;return!0}static ots(e){me.missing(e);const s=e.atoms[0].walletAddress,n=me.normalizedHash(e.molecularHash);let a=e.atoms.map((e=>e.otsFragment)).reduce(((e,t)=>e+t));if(2048!==a.length&&(a=C(a),2048!==a.length))throw new se;const i=T(a,128);let r="";for(const e in i){let s=i[e];for(let a=0,i=8+n[e];a<i;a++)s=t.shake256.create(512).update(s).hex();r+=s}const l=t.shake256.create(8192).update(r).hex();if(t.shake256.create(256).update(l).hex()!==s)throw new ne;return!0}static index(e){me.missing(e);for(let t of e.atoms)if(null===t.index)throw new X;return!0}static isotopeFilter(e,t){return(t=t||[]).filter((t=>e===t.isotope))}static normalizedHash(e){return me.normalize(me.enumerate(e))}static enumerate(e){const t={0:-8,1:-7,2:-6,3:-5,4:-4,5:-3,6:-2,7:-1,8:0,9:1,a:2,b:3,c:4,d:5,e:6,f:7,g:8},s=[],n=e.toLowerCase().split("");for(let e=0,a=n.length;e<a;++e){const a=n[e];void 0!==t[a]&&(s[e]=t[a])}return s}static normalize(e){let t=e.reduce(((e,t)=>e+t));const s=t<0;for(;t<0||t>0;)for(const n of Object.keys(e)){if((s?e[n]<8:e[n]>-8)&&(s?(++e[n],++t):(--e[n],--t),0===t))break}return e}static missing(e){if(null===e.molecularHash)throw new te;if(1>e.atoms.length)throw new Y}}class ye extends Z{constructor(e="Insufficient balance for requested transfer",t=null,s=null){super(e,t,s),this.name="BalanceInsufficientException"}}class ge extends Z{constructor(e="Amount cannot be negative!",t=null,s=null){super(e,t,s),this.name="NegativeAmountException"}}class be{constructor({secret:e=null,sourceWallet:t=null,remainderWallet:s=null,cellSlug:n=null}){this.cellSlugOrigin=this.cellSlug=n,this.secret=e,this.sourceWallet=t,this.atoms=[],(s||t)&&(this.remainderWallet=s||G.create({secretOrBundle:e,token:t.token,batchId:t.batchId,characters:t.characters})),this.clear()}static generateNextAtomIndex(e){const t=e.length-1;return t>-1?e[t].index+1:0}continuIdMetaType(){return"walletBundle"}fill(e){for(let t in Object.keys(e))this[t]=e[t]}addAtom(e){return this.molecularHash=null,this.atoms.push(e),this.atoms=j.sortAtoms(this.atoms),this}finalMetas(e=null,t=null){return e=e||{},(t=t||this.sourceWallet).hasTokenUnits()&&(e.tokenUnits=t.tokenUnitsJson()),e.pubkey=t.pubkey,e.characters=t.characters,e}contextMetas(e=null,t=null){return e=e||{}}replenishTokens({amount:e,token:t,metas:s}){s.action="add";for(let e of["address","position","batchId"])if(void 0===s[e])throw new ce(`Molecule::replenishTokens() - Missing ${e} in meta!`);return this.molecularHash=null,this.atoms.push(j.create.C({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,amount:e,batchId:this.sourceWallet.batchId,metaType:"token",metaId:t,meta:this.finalMetas(s),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}addUserRemainderAtom(e){return this.molecularHash=null,this.atoms.push(j.create.I({position:e.position,walletAddress:e.address,token:e.token,metaType:"walletBundle",metaId:e.bundle,meta:this.finalMetas({},e),index:this.generateIndex()})),this.atoms=j.sortAtoms(this.atoms),this}addPolicyAtom({metaType:e,metaId:t,meta:s={},policy:n={}}){return this.molecularHash=null,this.addAtom(j.create.R({token:"USER",metaType:e,metaId:t,meta:U.policy(this.finalMetas(s),n),index:this.generateIndex()})),this.atoms=j.sortAtoms(this.atoms),this}burnToken({amount:e,walletBundle:t=null}){if(e<0)throw new ge("Molecule::burnToken() - Amount to burn must be positive!");if(this.sourceWallet.balance-e<0)throw new ye;return this.molecularHash=null,this.atoms.push(j.create.V({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,value:-e,batchId:this.sourceWallet.batchId,meta:this.finalMetas({}),index:this.generateIndex()})),this.atoms.push(j.create.V({position:this.remainderWallet.position,walletAddress:this.remainderWallet.address,token:this.sourceWallet.token,value:this.sourceWallet.balance-e,batchId:this.remainderWallet.batchId,metaType:t?"walletBundle":null,metaId:t,meta:this.finalMetas({},this.remainderWallet),index:this.generateIndex()})),this.atoms=j.sortAtoms(this.atoms),this}initValue({recipientWallet:e,amount:t}){if(this.sourceWallet.balance-t<0)throw new ye;return this.molecularHash=null,this.atoms.push(j.create.V({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,value:-t,batchId:this.sourceWallet.batchId,meta:this.finalMetas({}),index:this.generateIndex()})),this.atoms.push(j.create.V({position:e.position,walletAddress:e.address,token:this.sourceWallet.token,value:t,batchId:e.batchId,metaType:"walletBundle",metaId:e.bundle,meta:this.finalMetas({},e),index:this.generateIndex()})),this.atoms.push(j.create.V({position:this.remainderWallet.position,walletAddress:this.remainderWallet.address,token:this.sourceWallet.token,value:this.sourceWallet.balance-t,batchId:this.remainderWallet.batchId,metaType:"walletBundle",metaId:this.sourceWallet.bundle,meta:this.finalMetas({},this.remainderWallet),index:this.generateIndex()})),this.atoms=j.sortAtoms(this.atoms),this}initWalletCreation(e){this.molecularHash=null;const t={address:e.address,token:e.token,bundle:e.bundle,position:e.position,amount:0,batchId:e.batchId,pubkey:e.pubkey,characters:e.characters};return this.atoms.push(j.create.C({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,batchId:this.sourceWallet.batchId,metaType:"wallet",metaId:e.address,meta:this.finalMetas(this.contextMetas(t),e),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}initTokenCreation({recipientWallet:e,amount:t,meta:s}){this.molecularHash=null;for(const t of["walletAddress","walletPosition","walletPubkey","walletCharacters"])s[t]||(s[t]=e[t.toLowerCase().substr(6)]);return this.atoms.push(j.create.C({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,value:t,batchId:e.batchId,metaType:"token",metaId:e.token,meta:this.finalMetas(this.contextMetas(s),this.sourceWallet),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}createRule({metaType:e,metaId:t,meta:s}){for(let e of["conditions","callback","rule"]){if(void 0===s[e])throw new ce(`Molecule::createRule() - Value for required meta key ${e} in missing!`);for(let t of["[object Object]","[object Array]"])Object.prototype.toString.call(s[e])===t&&(s[e]=JSON.stringify(s[e]))}return this.addAtom(j.create.R({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,metaType:e,metaId:t,meta:this.finalMetas(s,this.sourceWallet),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}initShadowWalletClaim({token:e,wallet:t}){this.molecularHash=null;let s={tokenSlug:e,walletAddress:t.address,walletPosition:t.position,batchId:t.batchId};return this.atoms.push(j.create.C({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,metaType:"wallet",metaId:t.address,meta:this.finalMetas(this.contextMetas(s)),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}initIdentifierCreation({type:e,contact:t,code:s}){this.molecularHash=null;const n={code:s,hash:P(t.trim())};return this.atoms.push(j.create.C({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,metaType:"identifier",metaId:e,meta:this.finalMetas(n,this.sourceWallet),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}initMeta({meta:e,metaType:t,metaId:s,policy:n}){return this.molecularHash=null,this.atoms.push(j.create.M({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,batchId:this.sourceWallet.batchId,metaType:t,metaId:s,meta:this.finalMetas(e,this.sourceWallet),index:this.generateIndex()})),this.addPolicyAtom({metaType:t,metaId:s,meta:e,policy:n}),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}initTokenRequest({token:e,amount:t,metaType:s,metaId:n,meta:a={},batchId:i=null}){return this.molecularHash=null,a.token=e,this.atoms.push(j.create.T({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,value:t,batchId:i,metaType:s,metaId:n,meta:this.finalMetas(a),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}initAuthorization({meta:e}){return this.molecularHash=null,this.atoms.push(j.create.U({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,batchId:this.sourceWallet.batchId,meta:this.finalMetas(e),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}clear(){return this.molecularHash=null,this.bundle=null,this.status=null,this.createdAt=String(+new Date),this.atoms=[],this}sign({anonymous:e=!1,compressed:s=!0}){if(0===this.atoms.length||0!==this.atoms.filter((e=>!(e instanceof j))).length)throw new Y;e||(this.bundle=P(this.secret)),this.molecularHash=j.hashAtoms({atoms:this.atoms});const n=this.atoms[0],a=T(G.generatePrivateKey({secret:this.secret,token:n.token,position:n.position}),128),i=me.normalizedHash(this.molecularHash);let r="";for(const e in a){let s=a[e];for(let n=0,a=8-i[e];n<a;n++)s=t.shake256.create(512).update(s).hex();r+=s}s&&(r=M(r));const l=T(r,Math.ceil(r.length/this.atoms.length));let o=null;for(let e=0,t=l.length;e<t;e++)this.atoms[e].otsFragment=l[e],o=this.atoms[e].position;return o}generateIndex(){return be.generateNextAtomIndex(this.atoms)}static jsonToObject(e){const t=Object.assign(new be({}),JSON.parse(e)),s=Object.keys(new be({}));if(!Array.isArray(t.atoms))throw new Y;for(const e in Object.keys(t.atoms)){t.atoms[e]=j.jsonToObject(JSON.stringify(t.atoms[e]));for(const s of["position","walletAddress","isotope"])if(void 0===t.atoms[e][s]||null===t.atoms[e][s])throw new Y("MolecularStructure::jsonToObject() - Required Atom properties are missing!")}for(const e in t)t.hasOwnProperty(e)&&!s.includes(e)&&delete t[e];return t.atoms=j.sortAtoms(t.atoms),t}get cellSlugDelimiter(){return"."}cellSlugBase(){return(this.cellSlug||"").split(this.cellSlugDelimiter)[0]}toJSON(){let e=H(this);for(let t of["remainderWallet","secret","sourceWallet","cellSlugOrigin"])e.hasOwnProperty(t)&&delete e[t];return e}check(e=null){return be.verify({molecule:this,sourceWallet:e})}static verify({molecule:e,sourceWallet:t=null}){return me.molecularHash(e)&&me.ots(e)&&me.index(e)&&me.batchId(e)&&me.continuId(e)&&me.isotopeM(e)&&me.isotopeT(e)&&me.isotopeC(e)&&me.isotopeU(e)&&me.isotopeI(e)&&me.isotopeR(e)&&me.isotopeV(e,t)}}class ke{static __init(e,t){this.arr=[],this.key=null,this.arr=String(t).split("."),this.key=this.arr.shift();const s=Number(this.key);Number.isInteger(s)&&(this.key=s),this.__nextKey=this.arr.length,this.__next=this.__tic(e)}static __tic(e){return!!(Array.isArray(e)||e instanceof Object)&&void 0!==e[this.key]}static has(e,t){return this.__init(e,t),!!this.__next&&(0===this.__nextKey||this.has(e[this.key],this.arr.join(".")))}static get(e,t,s=null){return this.__init(e,t),this.__next?0===this.__nextKey?e[this.key]:this.get(e[this.key],this.arr.join("."),s):s}}const fe=10**18;class _e{static val(e){return Math.abs(e*fe)<1?0:e}static cmp(e,t,s=!1){const n=_e.val(e)*fe,a=_e.val(t)*fe;return Math.abs(n-a)<1?0:n>a?1:-1}static equal(e,t){return 0===_e.cmp(e,t)}}class we{static create(e,t){let s=new we(e);return s.setWallet(t),s}static restore(e,t){let s=new G({secret:t,token:"AUTH",position:e.wallet.position,characters:e.wallet.characters});return we.create({token:e.token,expiresAt:e.expiresAt,pubkey:e.pubkey,encrypt:e.encrypt},s)}constructor({token:e,expiresAt:t,encrypt:s,pubkey:n}){this.$__token=e,this.$__expiresAt=t,this.$__pubkey=n,this.$__encrypt=s}setWallet(e){this.$__wallet=e}getWallet(){return this.$__wallet}getSnapshot(){return{token:this.$__token,expiresAt:this.$__expiresAt,pubkey:this.$__pubkey,encrypt:this.$__encrypt,wallet:{position:this.$__wallet.position,characters:this.$__wallet.characters}}}getToken(){return this.$__token}getPubkey(){return this.$__pubkey}getExpireInterval(){return 1e3*this.$__expiresAt-Date.now()}isExpired(){return!this.$__expiresAt||this.getExpireInterval()<0}getAuthData(){return{token:this.getToken(),pubkey:this.getPubkey(),wallet:this.getWallet()}}}class $e extends Z{constructor(e="Code exception",t=null,s=null){super(e,t,s),this.name="CodeException"}}class Ie extends Z{constructor(e="GraphQL did not provide a valid response.",t=null,s=null){super(e,t,s),this.name="InvalidResponseException"}}class Se extends Z{constructor(e="Authorization token missing or invalid.",t=null,s=null){super(e,t,s),this.name="UnauthenticatedException"}}class Ae{constructor({query:e,json:t,dataKey:s=null}){if(this.dataKey=s,this.errorKey="exception",this.$__payload=null,this.$__query=e,this.$__originResponse=t,this.$__response=t,void 0===this.$__response||null===this.$__response)throw new Ie;if(ke.has(this.$__response,this.errorKey)){const e=ke.get(this.$__response,this.errorKey);if(String(e).includes("Unauthenticated"))throw new Se;throw new Ie}this.init()}init(){}data(){if(!this.dataKey)return this.response();if(!ke.has(this.response(),this.dataKey))throw new Ie;return ke.get(this.response(),this.dataKey)}response(){return this.$__response}payload(){return null}query(){return this.$__query}status(){return null}}class xe{constructor(e){this.client=e,this.$__variables=null,this.$__query=null}response(){return this.$__response}async createResponseRaw(e){return this.createResponse(e)}createResponse(e){return new Ae({query:this,json:e})}createQuery({variables:e=null}){if(this.$__variables=this.compiledVariables(e),!this.uri())throw new $e("Query::createQuery() - Node URI was not initialized for this client instance!");if(null===this.$__query)throw new $e("Query::createQuery() - GraphQL subscription was not initialized!");return{query:this.$__query,variables:this.variables()}}async execute({variables:e=null}){this.$__request=this.createQuery({variables:e});let t=await this.client.query(this.$__request);return this.$__response=await this.createResponseRaw(t),this.$__response}compiledVariables(e=null){return e||{}}uri(){return this.client.getUri()}variables(){return this.$__variables}}class Te extends Ae{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.ContinuId"})}payload(){let e=null;const t=this.data();return t&&(e=new G({secret:null,token:t.tokenSlug}),e.address=t.address,e.position=t.position,e.bundle=t.bundleHash,e.batchId=t.batchId,e.characters=t.characters,e.pubkey=t.pubkey,e.balance=1*t.amount),e}}class qe extends xe{constructor(e){super(e),this.$__query=h.gql`query ($bundle: String!) {
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("js-sha3"),require("big-integer"),require("@stablelib/base64"),require("get-random-values"),require("big-integer/BigInteger"),require("buffer"),require("base-x"),require("tweetnacl"),require("tweetnacl-sealedbox-js"),require("@stablelib/utf8"),require("@apollo/client/core"),require("isomorphic-fetch"),require("@apollo/client/cache"),require("@apollo/client/link/error"),require("laravel-echo"),require("socket.io-client"),require("graphql")):"function"==typeof define&&define.amd?define(["exports","js-sha3","big-integer","@stablelib/base64","get-random-values","big-integer/BigInteger","buffer","base-x","tweetnacl","tweetnacl-sealedbox-js","@stablelib/utf8","@apollo/client/core","isomorphic-fetch","@apollo/client/cache","@apollo/client/link/error","laravel-echo","socket.io-client","graphql"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).KnishIO={},e.shake256,e.bigInt,e.base64,e.getRandomValues,e.bigIntB,e.buffer,e.baseX,e.tweetnacl,e.tweetnaclSealedboxJs,e.utf8,e.apolloClientCore,e.fetch,e.apolloClientCache,e.apolloClientLinkError,e.Echo,e.io,e.graphql)}(this,(function(e,t,s,n,a,i,r,l,o,u,c,h,d,p,m,y,g,k){"use strict";function b(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var _=b(s),f=b(a),w=b(i),$=b(l),I=b(d),S=b(y),A=b(g);class T{static toHex(e,t){const s=(e,t)=>{const s=t?["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]:["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];return s[Math.floor(e/16)]+s[e%16]},n=Object.assign({grouping:0,rowlength:0,uppercase:!1},t||{});let a="",i=0,r=0;for(let t=0;t<e.length&&(a+=s(e[t],n.uppercase),t!==e.length-1);++t)n.grouping>0&&++i===n.grouping&&(i=0,n.rowlength>0&&++r===n.rowlength?(r=0,a+="\n"):a+=" ");return a}static toUint8Array(e){let t=e.toLowerCase().replace(/\s/g,"");t.length%2==1&&(t=`0${t}`);let s=new Uint8Array(Math.floor(t.length/2)),n=-1;for(let e=0;e<t.length;++e){let a=t[e],i=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"].indexOf(a);if(-1===i)throw Error("unexpected character");-1===n?n=16*i:(s[Math.floor(e/2)]=n+i,n=-1)}return s}}function x(e,t){const s=Math.ceil(e.length/t),n=[];for(let a=0,i=0;a<s;++a,i+=t)n[a]=e.substr(i,t);return n}function v(e=256,t="abcdef0123456789"){let s=new Uint8Array(e);return s=f.default(s),s=s.map((e=>t.charCodeAt(e%t.length))),String.fromCharCode.apply(null,s)}function q(e,t,s,n,a){if(n=n||"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~`!@#$%^&*()-_=+[{]}\\|;:'\",<.>/?¿¡",a=a||n,t>n.length||s>a.length)return console.warn("Strings::charsetBaseConvert() - Can't convert",e,"to base",s,"greater than symbol table length. src-table:",n.length,"dest-table:",a.length),!1;let i=_.default(0);for(let s=0;s<e.length;s++)i=i.multiply(t).add(n.indexOf(e.charAt(s)));if(i.lesser(0))return 0;let r=i.mod(s),l=a.charAt(r),o=i.divide(s);for(;!o.equals(0);)r=o.mod(s),o=o.divide(s),l=a.charAt(r)+l;return l}function M(e){return n.encode(T.toUint8Array(e))}function W(e){return T.toHex(n.decode(e),{})}function C(e){return/^[A-F0-9]+$/i.test(e)}function U(e,t){let s,n,a,i=[Array,Date,Number,String,Boolean],r=Object.prototype.toString;for(t=t||[],s=0;s<t.length;s+=2)e===t[s]&&(n=t[s+1]);if(!n&&e&&"object"==typeof e){for(n={},s=0;s<i.length;s++)r.call(e)===r.call(a=new i[s](e))&&(n=s?a:[]);for(s in t.push(e,n),e)t.hasOwnProperty.call(e,s)&&(n[s]=U(e[s],t))}return n||e}function H(...e){return[].concat(...e.map(((t,s)=>{const n=e.slice(0);n.splice(s,1);const a=[...new Set([].concat(...n))];return t.filter((e=>!a.includes(e)))})))}String.prototype.trim||(String.prototype.trim=function(){return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}),String.prototype.toCamelCase||(String.prototype.toCamelCase=function(){return this.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g,((e,t)=>t.toUpperCase()))}),String.prototype.toSnakeCase||(String.prototype.toSnakeCase=function(){return this.replace(/[A-Z]/g,(e=>`_${e.toLowerCase()}`))});class B{constructor({meta:e}){this.meta=e,this.createdAt=+new Date}static normalizeMeta(e){const t=[];for(const s in e)e.hasOwnProperty(s)&&null!==e[s]&&t.push({key:s,value:e[s].toString()});return t}static aggregateMeta(e){let t={};if(Array.isArray(e))for(let s of e)t[s.key]=s.value;else t=e;return t}static policy(e,t){const s={policy:{}};if(t)for(const[e,n]of Object.entries(t||{}))if(null!==n&&["read","write"].includes(e)){s.policy[e]={};for(const[t,a]of Object.entries(n))s.policy[e][t]=a}return s.policy=JSON.stringify(B.__defaultPolicy(s.policy,e)),s}static __defaultPolicy(e,t){const s=U(e),n=Array.from(s).filter((e=>"read"===e.action)),a=Array.from(s).filter((e=>"write"===e.action)),i=Object.keys(t||{});for(const[e,t]of Object.entries({read:n,write:a})){const n=t.map((e=>e.key));s[e]||(s[e]={});for(const t of H(i,n))s[e][t]||(s[e][t]="write"!==e||["characters","pubkey"].includes(t)?["all"]:["self"])}return s}}class R{constructor({position:e=null,walletAddress:t=null,isotope:s=null,token:n=null,value:a=null,batchId:i=null,metaType:r=null,metaId:l=null,meta:o=null,otsFragment:u=null,index:c=null}){this.position=e,this.walletAddress=t,this.isotope=s,this.token=n,this.value=null!==a?String(a):null,this.batchId=i,this.metaType=r,this.metaId=l,this.meta=o?B.normalizeMeta(o):[],this.index=c,this.otsFragment=u,this.createdAt=String(+new Date)}static get create(){return{C({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="C",new R(arguments[0])},I({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="I",new R(arguments[0])},M({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="M",new R(arguments[0])},T({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="T",new R(arguments[0])},U({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="U",new R(arguments[0])},V({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="V",new R(arguments[0])},R({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="R",new R(arguments[0])}}}static get hashSchema(){return new Map([["position",null],["walletAddress",null],["isotope",null],["token",null],["value",null],["batchId",null],["metaType",null],["metaId",null],["meta",null],["createdAt",null]])}aggregatedMeta(){return B.aggregateMeta(this.meta)}static jsonToObject(e){const t=Object.assign(new R({}),JSON.parse(e)),s=Object.keys(new R({}));for(const e in t)t.hasOwnProperty(e)&&!s.includes(e)&&delete t[e];return t}static molecularHashSchema(e){const t=R.hashSchema;for(const s in e)e.hasOwnProperty(s)&&t.has(s)&&t.set(s,e[s]);return t}static hashAtoms({atoms:e,output:s="base17"}){const n=t.shake256.create(256),a=e.length,i=R.sortAtoms(e);for(const e of i){const t=R.molecularHashSchema(e);n.update(String(a));for(const e of t.keys()){const s=t.get(e);if((null!==s||["position","walletAddress"].includes(e))&&!["otsFragment","index"].includes(e))if("meta"!==e)n.update(null===s?"":String(s));else for(const e of s)void 0!==e.value&&null!==e.value&&(n.update(String(e.key)),n.update(String(e.value)))}}switch(s){case"hex":return n.hex();case"array":return n.array();default:return q(n.hex(),16,17,"0123456789abcdef","0123456789abcdefg").padStart(64,"0")}}static sortAtoms(e){const t=[...e];return t.sort(((e,t)=>e.index===t.index?0:e.index<t.index?-1:1)),t}}class j{static encode(e){return n.encode(e)}static decode(e){return r.Buffer.from(n.decode(e))}encode(e){return j.encode(e)}decode(e){return j.decode(e)}}class O{constructor(e={}){this.$options=Object.assign({characters:"GMP"},e),this.$encoder=$.default(this[this.$options.characters]||this.GMP)}encode(e){return this.$encoder.encode(r.Buffer.from(e))}decode(e){return this.$encoder.decode(e)}get GMP(){return"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv"}get BITCOIN(){return"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}get FLICKR(){return"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}get RIPPLE(){return"rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"}get IPFS(){return"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}}class E{constructor(e={}){this.$options=Object.assign({characters:"BASE64"},e),this.$encoder=new O,["BASE64"].includes(this.$options.characters)?this.$encoder=new j:["BASE2","BASE8","BASE11","BASE36","BASE62","BASE67"].includes(this.$options.characters)?this.$encoder=$.default(this[this.$options.characters]):["BITCOIN","FLICKR","RIPPLE","IPFS"].includes(this.$options.characters)&&(this.$encoder=new O(this.$options))}encode(e){return this.$encoder.encode(r.Buffer.from(e))}decode(e){return this.$encoder.decode(e)}get BASE2(){return"01"}get BASE8(){return"01234567"}get BASE11(){return"0123456789a"}get BASE36(){return"0123456789abcdefghijklmnopqrstuvwxyz"}get BASE62(){return"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"}get BASE67(){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~"}}class K{constructor(e=null){this.base=new E({characters:e||"BASE64"})}encrypt(e,t){return this.encode(u.seal(c.encode(JSON.stringify(e)),this.decode(t)))}decrypt(e,t,s){try{return JSON.parse(c.decode(u.open(this.decode(e),this.decode(s),this.decode(t))))}catch(e){return null}}generatePrivateKey(e){const s=t.shake256.create(8*o.box.secretKeyLength);return s.update(e),this.base.encode(r.Buffer.from(s.digest()))}generatePublicKey(e){const t=o.box.keyPair.fromSecretKey(this.decode(e));return this.encode(t.publicKey)}shortHash(e){const s=t.shake256.create(64);return s.update(e),this.base.encode(r.Buffer.from(s.digest()))}decode(e){return this.base.decode(e)}encode(e){return this.base.encode(e)}}function Q(e=null,s=2048){if(console.info(`Crypto::generateSecret() - Computing new secret${e?" from existing seed":""}...`),e){const n=t.shake256.create(2*s);return n.update(e),n.hex()}return v(s)}function P(e){console.info("Crypto::generateBundleHash() - Computing wallet bundle from secret...");const s=t.shake256.create(256);return s.update(e),s.hex()}function N({molecularHash:e=null,index:t=null}){return null!==e&&null!==t?P(String(e)+String(t)):v(64)}function F(e=64){return v(e,"abcdef0123456789")}function V(e,t,s=null){return new K(s).encrypt(e,t)}function J(e,t,s,n=null){return new K(n).decrypt(e,t,s)}function D(e,t=null){return new K(t).generatePrivateKey(e)}function L(e,t=null){return new K(t).generatePublicKey(e)}function z(e,t=null){return new K(t).shortHash(e)}class G{constructor({secret:e=null,token:t="USER",position:s=null,batchId:n=null,characters:a=null}){this.token=t,this.balance=0,this.molecules={},this.key=null,this.address=null,this.privkey=null,this.pubkey=null,this.tokenUnits=[],this.bundle=e?P(e):null,this.batchId=n,this.position=s,this.characters=a||"BASE64",e&&(this.position=this.position||F(),this.prepareKeys(e))}static create({secretOrBundle:e,token:t,batchId:s=null,characters:n=null}){let a=G.isBundleHash(e)?null:e,i=a?P(a):e,r=a?F():null,l=new G({secret:a,token:t,position:r,batchId:s,characters:n});return l.bundle=i,l}static isBundleHash(e){return"string"==typeof e&&(64===e.length&&C(e))}static getTokenUnits(e){let t=[];return e.forEach((e=>{t.push({id:e.shift(),name:e.shift(),metas:e})})),t}hasTokenUnits(){return!!this.tokenUnits&&this.tokenUnits.length>0}tokenUnitsJson(){if(this.hasTokenUnits()){const e=[];return this.tokenUnits.forEach((t=>{e.push([t.id,t.name].concat(t.metas))})),JSON.stringify(e)}return null}splitUnits(e,t,s=null){if(0===e.length)return;let n=[],a=[];this.tokenUnits.forEach((t=>{e.includes(t.id)?n.push(t):a.push(t)})),this.tokenUnits=n,null!==s&&(s.tokenUnits=n),t.tokenUnits=a}isShadow(){return!(void 0!==this.position&&null!==this.position||void 0!==this.address&&null!==this.address)}initBatchId({sourceWallet:e,isRemainder:t=!1}){e.batchId&&(this.batchId=t?e.batchId:N({}))}prepareKeys(e){null===this.key&&null===this.address&&(this.key=G.generatePrivateKey({secret:e,token:this.token,position:this.position}),this.address=G.generatePublicKey(this.key),this.getMyEncPrivateKey(),this.getMyEncPublicKey())}getMyEncPrivateKey(){return null===this.privkey&&null!==this.key&&(this.privkey=D(this.key,this.characters)),this.privkey}getMyEncPublicKey(){const e=this.getMyEncPrivateKey();return!this.pubkey&&e&&(this.pubkey=L(e,this.characters)),this.pubkey}encryptMyMessage(e){const t={};for(let s=1,n=arguments.length;s<n;s++)t[z(arguments[s],this.characters)]=V(e,arguments[s],this.characters);return t}decryptMyMessage(e){const t=this.getMyEncPublicKey();let s=e;return null!==e&&"object"==typeof e&&"[object Object]"===Object.prototype.toString.call(e)&&(s=e[z(t,this.characters)]||""),J(s,this.getMyEncPrivateKey(),t,this.characters)}decryptBinary(e){const t=this.decryptMyMessage(e);return new E({characters:"BASE64"}).decode(t)}encryptBinary(e){const t=Array.from(arguments).slice(1),s=new E({characters:"BASE64"}).encode(e);return this.encryptMyMessage(s,...t)}encryptString({data:e,publicKeys:t}){if(e){const s=this.getMyEncPublicKey();"string"==typeof t&&(t=[t]);const n=this.encryptMyMessage(e,s,...t);return btoa(JSON.stringify(n))}}decryptString({data:e,fallbackValue:t=null}){if(e)try{const s=JSON.parse(atob(e));return this.decryptMyMessage(s)||t}catch(s){return console.error(s),t||e}}static generatePrivateKey({secret:e,token:s,position:n}){const a=w.default(e,16).add(w.default(n,16)),i=t.shake256.create(8192);return i.update(a.toString(16)),s&&i.update(s),t.shake256.create(8192).update(i.hex()).hex()}static generatePublicKey(e){const s=x(e,128),n=t.shake256.create(8192);for(const e in s){let a=s[e];for(let e=1;e<=16;e++)a=t.shake256.create(512).update(a).hex();n.update(a)}return t.shake256.create(256).update(n.hex()).hex()}}class Z extends TypeError{constructor(e=null,t=null,s=null){if(super(e,t,s),null===e)throw new this(`Unknown ${this.constructor.name}`);this.name="BaseException"}toString(){return`${this.name}: ${this.message}.\nStack:\n${this.stack}`}}class X extends Z{constructor(e="There is an atom without an index",t=null,s=null){super(e,t,s),this.name="AtomIndexException"}}class Y extends Z{constructor(e="The molecule does not contain atoms",t=null,s=null){super(e,t,s),this.name="AtomsMissingException"}}class ee extends Z{constructor(e="The molecular hash does not match",t=null,s=null){super(e,t,s),this.name="MolecularHashMismatchException"}}class te extends Z{constructor(e="The molecular hash is missing",t=null,s=null){super(e,t,s),this.name="MolecularHashMissingException"}}class se extends Z{constructor(e="OTS malformed",t=null,s=null){super(e,t,s),this.name="SignatureMalformedException"}}class ne extends Z{constructor(e="One-time signature (OTS) does not match!",t=null,s=null){super(e,t,s),this.name="SignatureMismatchException"}}class ae extends Z{constructor(e="Insufficient balance to make transfer",t=null,s=null){super(e,t,s),this.name="TransferBalanceException"}}class ie extends Z{constructor(e="Token transfer atoms are malformed",t=null,s=null){super(e,t,s),this.name="TransferMalformedException"}}class re extends Z{constructor(e="Token slugs for wallets in transfer do not match!",t=null,s=null){super(e,t,s),this.name="TransferMismatchedException"}}class le extends Z{constructor(e="Invalid remainder provided",t=null,s=null){super(e,t,s),this.name="TransferRemainderException"}}class oe extends Z{constructor(e="Sender and recipient(s) cannot be the same",t=null,s=null){super(e,t,s),this.name="TransferToSelfException"}}class ue extends Z{constructor(e="Token transfer atoms are unbalanced",t=null,s=null){super(e,t,s),this.name="TransferUnbalancedException"}}class ce extends Z{constructor(e="Empty meta data.",t=null,s=null){super(e,t,s),this.name="MetaMissingException"}}class he extends Z{constructor(e="Wrong type of token for this isotope",t=null,s=null){super(e,t,s),this.name="WrongTokenTypeException"}}class de extends Z{constructor(e="Incorrect BatchId",t=null,s=null){super(e,t,s),this.name="BatchIdException"}}class pe extends Z{constructor(e="",t=null,s=null){super(e,t,s),this.name="KnishIOInvalidPolicyException"}}class me{static continuId(e){me.missing(e);if("USER"===e.atoms[0].token&&me.isotopeFilter("I",e.atoms).length<1)throw new Y("Check::continuId() - Molecule is missing required ContinuID Atom!");return!0}static batchId(e){if(e.atoms.length>0){const t=e.atoms[0];if("V"===t.isotope&&null!==t.batchId){const s=me.isotopeFilter("V",e.atoms),n=s[s.length-1];if(t.batchId!==n.batchId)throw new de;for(const e of s)if(null===e.batchId)throw new de}return!0}throw new de}static isotopeI(e){me.missing(e);for(let t of me.isotopeFilter("I",e.atoms)){if("USER"!==t.token)throw new he(`Check::isotopeI() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);if(0===t.index)throw new X(`Check::isotopeI() - Isotope "${t.isotope}" Atoms must have a non-zero index!`)}return!0}static isotopeU(e){me.missing(e);for(let t of me.isotopeFilter("U",e.atoms)){if("AUTH"!==t.token)throw new he(`Check::isotopeU() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);if(0!==t.index)throw new X(`Check::isotopeU() - Isotope "${t.isotope}" Atoms must have an index equal to 0!`)}return!0}static isotopeM(e){me.missing(e);const t=["readPolicy","writePolicy"];for(let s of me.isotopeFilter("M",e.atoms)){if(s.meta.length<1)throw new ce;if("USER"!==s.token)throw new he(`Check::isotopeM() - "${s.token}" is not a valid Token slug for "${s.isotope}" isotope Atoms!`);const e=B.aggregateMeta(s.meta);for(const s of t){let n=e[s];if(n){n=JSON.parse(n);for(const[s,a]of Object.entries(n))if(!t.includes(s)){if(!Object.keys(e).includes(s))throw new pe(`${s} is missing from the meta.`);for(const e of a)if(!G.isBundleHash(e)&&!["all","self"].includes(e))throw new pe(`${e} does not correspond to the format of the policy.`)}}}}return!0}static isotopeC(e){me.missing(e);for(let t of me.isotopeFilter("C",e.atoms)){if("USER"!==t.token)throw new he(`Check::isotopeC() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);if(0!==t.index)throw new X(`Check::isotopeC() - Isotope "${t.isotope}" Atoms must have an index equal to 0!`)}return!0}static isotopeT(e){me.missing(e);for(let t of me.isotopeFilter("T",e.atoms)){const e=t.aggregatedMeta();if("wallet"===String(t.metaType).toLowerCase())for(let t of["position","bundle"])if(!e.hasOwnProperty(t)||!Boolean(e[t]))throw new ce(`Check::isotopeT() - Required meta field "${t}" is missing!`);for(let t of["token"])if(!e.hasOwnProperty(t)||!Boolean(e[t]))throw new ce(`Check::isotopeT() - Required meta field "${t}" is missing!`);if("USER"!==t.token)throw new he(`Check::isotopeT() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);if(0!==t.index)throw new X(`Check::isotopeT() - Isotope "${t.isotope}" Atoms must have an index equal to 0!`)}return!0}static isotopeR(e){me.missing(e);for(let t of me.isotopeFilter("R",e.atoms)){const e=t.aggregatedMeta();if(e.policy){const t=JSON.parse(e.policy);if(!Object.keys(t).every((e=>["read","write"].includes(e))))throw new ce("Check::isotopeR() - Mixing rules with politics!")}if(e.rule){const t=JSON.parse(e.rule);if(!Array.isArray(t))throw new ce("Check::isotopeR() - Incorrect rule format!");if(t.length<1)throw new ce("Check::isotopeR() - No rules!");for(const e of t){if(Object.keys(e).filter((e=>["key","value","callback"].includes(e))).length<3)throw new ce("Check::isotopeR() - Necessary rule fields are missing!")}}}return!0}static isotopeV(e,t=null){me.missing(e);const s=me.isotopeFilter("V",e.atoms);if(0===s.length)return!0;const n=e.atoms[0];if("V"===n.isotope&&2===s.length){const e=s[s.length-1];if(n.token!==e.token)throw new re;if(e.value<0)throw new ie;return!0}let a=0,i=0;for(let t in e.atoms)if(e.atoms.hasOwnProperty(t)){const s=e.atoms[t];if("V"!==s.isotope)continue;if(i=1*s.value,Number.isNaN(i))throw new TypeError('Invalid isotope "V" values');if(s.token!==n.token)throw new re;if(t>0){if(i<0)throw new ie;if(s.walletAddress===n.walletAddress)throw new oe}a+=i}if(a!==i)throw new ue;if(t){if(i=1*n.value,Number.isNaN(i))throw new TypeError('Invalid isotope "V" values');const e=1*t.balance+1*i;if(e<0)throw new ae;if(e!==a)throw new le}else if(0!==i)throw new le;return!0}static molecularHash(e){if(me.missing(e),e.molecularHash!==R.hashAtoms({atoms:e.atoms}))throw new ee;return!0}static ots(e){me.missing(e);const s=e.atoms[0].walletAddress,n=me.normalizedHash(e.molecularHash);let a=e.atoms.map((e=>e.otsFragment)).reduce(((e,t)=>e+t));if(2048!==a.length&&(a=W(a),2048!==a.length))throw new se;const i=x(a,128);let r="";for(const e in i){let s=i[e];for(let a=0,i=8+n[e];a<i;a++)s=t.shake256.create(512).update(s).hex();r+=s}const l=t.shake256.create(8192).update(r).hex();if(t.shake256.create(256).update(l).hex()!==s)throw new ne;return!0}static index(e){me.missing(e);for(let t of e.atoms)if(null===t.index)throw new X;return!0}static isotopeFilter(e,t){return(t=t||[]).filter((t=>e===t.isotope))}static normalizedHash(e){return me.normalize(me.enumerate(e))}static enumerate(e){const t={0:-8,1:-7,2:-6,3:-5,4:-4,5:-3,6:-2,7:-1,8:0,9:1,a:2,b:3,c:4,d:5,e:6,f:7,g:8},s=[],n=e.toLowerCase().split("");for(let e=0,a=n.length;e<a;++e){const a=n[e];void 0!==t[a]&&(s[e]=t[a])}return s}static normalize(e){let t=e.reduce(((e,t)=>e+t));const s=t<0;for(;t<0||t>0;)for(const n of Object.keys(e)){if((s?e[n]<8:e[n]>-8)&&(s?(++e[n],++t):(--e[n],--t),0===t))break}return e}static missing(e){if(null===e.molecularHash)throw new te;if(1>e.atoms.length)throw new Y}}class ye extends Z{constructor(e="Insufficient balance for requested transfer",t=null,s=null){super(e,t,s),this.name="BalanceInsufficientException"}}class ge extends Z{constructor(e="Amount cannot be negative!",t=null,s=null){super(e,t,s),this.name="NegativeAmountException"}}class ke{#e;#t;#s;#n;#a;constructor({metaType:e,metaId:t,isotope:s,token:n,amount:a}){this.#e=e,this.#t=t,this.#s=s,this.#n=n,this.#a=a}toJSON(){return{metaType:this.#e,metaId:this.#t,isotope:this.#s,token:this.#n,amount:this.#a}}}class be extends Z{constructor(e="An incorrect argument!",t=null,s=null){super(e,t,s),this.name="RuleArgumentException"}}class _e{#i;#r=null;constructor({action:e,meta:t}){if(t&&(this.meta=t),!e)throw new be('Callback structure violated, missing mandatory "action" parameter.');this.#i=e}set meta(e){if(!(e instanceof ke))throw new be("Incorrect meta argument. The meta argument can only be an instance of the Meta class.");this.#r=e}toJSON(){const e={action:this.#i};return this.#r&&(e.meta=this.#r),e}static toObject(e){const t=new _e({action:e.action,meta:null});return e.meta&&(t.meta=new ke({metaType:e.meta.metaType,metaId:e.meta.metaId,isotope:e.meta.isotope,token:e.meta.token,amount:e.meta.amount})),t}}class fe{#l;#o;#u;#c;constructor({key:e,value:t,comparison:s="===",callback:n=[]}){if(!e)throw new be('Rule structure violated, missing mandatory "key" parameter!');if(!t)throw new be('Rule structure violated, missing mandatory "value" parameter');for(const e of n)if(!(e instanceof _e))throw new be;this.#l=e,this.#o=t,this.#u=s,this.#c=n}set comparison(e){this.#u=e}set callback(e){this.#c.push(e)}toJSON(){return{key:this.#l,value:this.#o,comparison:this.#u,callback:this.#c}}static toObject(e){const t=new fe({key:e.key,value:e.value});if(e.comparison&&(t.comparison=e.comparison),e.callback)for(const s of e.callback)t.callback=s instanceof _e?s:_e.toObject(s);return t}}class we{constructor({secret:e=null,sourceWallet:t=null,remainderWallet:s=null,cellSlug:n=null}){this.cellSlugOrigin=this.cellSlug=n,this.secret=e,this.sourceWallet=t,this.atoms=[],(s||t)&&(this.remainderWallet=s||G.create({secretOrBundle:e,token:t.token,batchId:t.batchId,characters:t.characters})),this.clear()}static generateNextAtomIndex(e){const t=e.length-1;return t>-1?e[t].index+1:0}continuIdMetaType(){return"walletBundle"}fill(e){for(let t in Object.keys(e))this[t]=e[t]}addAtom(e){return this.molecularHash=null,this.atoms.push(e),this.atoms=R.sortAtoms(this.atoms),this}finalMetas(e=null,t=null){return e=e||{},t=t||this.sourceWallet,e.pubkey=t.pubkey,e.characters=t.characters,e}tokenUnitMetas(e,t=[]){return e.hasTokenUnits()&&(t.tokenUnits=e.tokenUnitsJson()),t}contextMetas(e=null,t=null){return e=e||{}}addUserRemainderAtom(e){return this.molecularHash=null,this.atoms.push(R.create.I({position:e.position,walletAddress:e.address,token:e.token,metaType:"walletBundle",metaId:e.bundle,meta:this.finalMetas({},e),index:this.generateIndex()})),this.atoms=R.sortAtoms(this.atoms),this}addPolicyAtom({metaType:e,metaId:t,meta:s={},policy:n={}}){return this.molecularHash=null,this.addAtom(R.create.R({token:"USER",metaType:e,metaId:t,meta:B.policy(this.finalMetas(s),n),index:this.generateIndex()})),this.atoms=R.sortAtoms(this.atoms),this}burnToken({amount:e,walletBundle:t=null}){if(e<0)throw new ge("Molecule::burnToken() - Amount to burn must be positive!");if(this.sourceWallet.balance-e<0)throw new ye;return this.molecularHash=null,this.atoms.push(R.create.V({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,value:-e,batchId:this.sourceWallet.batchId,meta:this.finalMetas(this.tokenUnitMetas(this.sourceWallet)),index:this.generateIndex()})),this.atoms.push(R.create.V({position:this.remainderWallet.position,walletAddress:this.remainderWallet.address,token:this.sourceWallet.token,value:this.sourceWallet.balance-e,batchId:this.remainderWallet.batchId,metaType:t?"walletBundle":null,metaId:t,meta:this.finalMetas(this.tokenUnitMetas(this.remainderWallet),this.remainderWallet),index:this.generateIndex()})),this.atoms=R.sortAtoms(this.atoms),this}replenishToken({amount:e,units:t=[]}){if(e<0)throw new ge("Molecule::replenishToken() - Amount to replenish must be positive!");if(t.length){t=G.getTokenUnits(t),this.remainderWallet.tokenUnits=this.sourceWallet.tokenUnits;for(const e of t)this.remainderWallet.tokenUnits.push(e);this.remainderWallet.balance=this.remainderWallet.tokenUnits.length,this.sourceWallet.tokenUnits=t,this.sourceWallet.balance=this.sourceWallet.tokenUnits.length}else this.remainderWallet.balance=this.sourceWallet.balance+e,this.sourceWallet.balance=e;this.molecularHash=null,this.atoms.push(R.create.V({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,value:this.sourceWallet.balance,batchId:this.sourceWallet.batchId,meta:this.finalMetas(this.tokenUnitMetas(this.sourceWallet)),index:this.generateIndex()}));const s=this.remainderWallet.bundle;return this.atoms.push(R.create.V({position:this.remainderWallet.position,walletAddress:this.remainderWallet.address,token:this.sourceWallet.token,value:this.remainderWallet.balance,batchId:this.remainderWallet.batchId,metaType:s?"walletBundle":null,metaId:s,meta:this.finalMetas(this.tokenUnitMetas(this.remainderWallet),this.remainderWallet),index:this.generateIndex()})),this.atoms=R.sortAtoms(this.atoms),this}initValue({recipientWallet:e,amount:t}){if(this.sourceWallet.balance-t<0)throw new ye;return this.molecularHash=null,this.atoms.push(R.create.V({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,value:-t,batchId:this.sourceWallet.batchId,meta:this.finalMetas(this.tokenUnitMetas(this.sourceWallet)),index:this.generateIndex()})),this.atoms.push(R.create.V({position:e.position,walletAddress:e.address,token:this.sourceWallet.token,value:t,batchId:e.batchId,metaType:"walletBundle",metaId:e.bundle,meta:this.finalMetas(this.tokenUnitMetas(e),e),index:this.generateIndex()})),this.atoms.push(R.create.V({position:this.remainderWallet.position,walletAddress:this.remainderWallet.address,token:this.sourceWallet.token,value:this.sourceWallet.balance-t,batchId:this.remainderWallet.batchId,metaType:"walletBundle",metaId:this.sourceWallet.bundle,meta:this.finalMetas(this.tokenUnitMetas(this.remainderWallet),this.remainderWallet),index:this.generateIndex()})),this.atoms=R.sortAtoms(this.atoms),this}initWalletCreation(e){this.molecularHash=null;const t={address:e.address,token:e.token,bundle:e.bundle,position:e.position,amount:0,batchId:e.batchId,pubkey:e.pubkey,characters:e.characters};return this.atoms.push(R.create.C({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,batchId:this.sourceWallet.batchId,metaType:"wallet",metaId:e.address,meta:this.finalMetas(this.contextMetas(t),e),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=R.sortAtoms(this.atoms),this}initTokenCreation({recipientWallet:e,amount:t,meta:s}){this.molecularHash=null;for(const t of["walletAddress","walletPosition","walletPubkey","walletCharacters"])s[t]||(s[t]=e[t.toLowerCase().substring(6)]);return this.atoms.push(R.create.C({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,value:t,batchId:e.batchId,metaType:"token",metaId:e.token,meta:this.finalMetas(this.contextMetas(s),this.sourceWallet),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=R.sortAtoms(this.atoms),this}createRule({metaType:e,metaId:t,rule:s,policy:n={}}){const a=[];for(const e of s)a.push(e instanceof fe?e:fe.toObject(e));const i={rule:JSON.stringify(a)},r=B.policy(i,n);return this.addAtom(R.create.R({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,metaType:e,metaId:t,meta:{...i,...r},index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=R.sortAtoms(this.atoms),this}initShadowWalletClaim({token:e,wallet:t}){this.molecularHash=null;let s={tokenSlug:e,walletAddress:t.address,walletPosition:t.position,batchId:t.batchId};return this.atoms.push(R.create.C({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,metaType:"wallet",metaId:t.address,meta:this.finalMetas(this.contextMetas(s)),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=R.sortAtoms(this.atoms),this}initIdentifierCreation({type:e,contact:t,code:s}){this.molecularHash=null;const n={code:s,hash:P(t.trim())};return this.atoms.push(R.create.C({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,metaType:"identifier",metaId:e,meta:this.finalMetas(n,this.sourceWallet),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=R.sortAtoms(this.atoms),this}initMeta({meta:e,metaType:t,metaId:s,policy:n}){return this.molecularHash=null,this.atoms.push(R.create.M({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,batchId:this.sourceWallet.batchId,metaType:t,metaId:s,meta:this.finalMetas(e,this.sourceWallet),index:this.generateIndex()})),this.addPolicyAtom({metaType:t,metaId:s,meta:e,policy:n}),this.addUserRemainderAtom(this.remainderWallet),this.atoms=R.sortAtoms(this.atoms),this}initTokenRequest({token:e,amount:t,metaType:s,metaId:n,meta:a={},batchId:i=null}){return this.molecularHash=null,a.token=e,this.atoms.push(R.create.T({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,value:t,batchId:i,metaType:s,metaId:n,meta:this.finalMetas(a),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=R.sortAtoms(this.atoms),this}initAuthorization({meta:e}){return this.molecularHash=null,this.atoms.push(R.create.U({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,batchId:this.sourceWallet.batchId,meta:this.finalMetas(e),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=R.sortAtoms(this.atoms),this}clear(){return this.molecularHash=null,this.bundle=null,this.status=null,this.createdAt=String(+new Date),this.atoms=[],this}sign({anonymous:e=!1,compressed:s=!0}){if(0===this.atoms.length||0!==this.atoms.filter((e=>!(e instanceof R))).length)throw new Y;e||(this.bundle=P(this.secret)),this.molecularHash=R.hashAtoms({atoms:this.atoms});const n=this.atoms[0],a=x(G.generatePrivateKey({secret:this.secret,token:n.token,position:n.position}),128),i=me.normalizedHash(this.molecularHash);let r="";for(const e in a){let s=a[e];for(let n=0,a=8-i[e];n<a;n++)s=t.shake256.create(512).update(s).hex();r+=s}s&&(r=M(r));const l=x(r,Math.ceil(r.length/this.atoms.length));let o=null;for(let e=0,t=l.length;e<t;e++)this.atoms[e].otsFragment=l[e],o=this.atoms[e].position;return o}generateIndex(){return we.generateNextAtomIndex(this.atoms)}static jsonToObject(e){const t=Object.assign(new we({}),JSON.parse(e)),s=Object.keys(new we({}));if(!Array.isArray(t.atoms))throw new Y;for(const e in Object.keys(t.atoms)){t.atoms[e]=R.jsonToObject(JSON.stringify(t.atoms[e]));for(const s of["position","walletAddress","isotope"])if(void 0===t.atoms[e][s]||null===t.atoms[e][s])throw new Y("MolecularStructure::jsonToObject() - Required Atom properties are missing!")}for(const e in t)t.hasOwnProperty(e)&&!s.includes(e)&&delete t[e];return t.atoms=R.sortAtoms(t.atoms),t}get cellSlugDelimiter(){return"."}cellSlugBase(){return(this.cellSlug||"").split(this.cellSlugDelimiter)[0]}toJSON(){let e=U(this);for(let t of["remainderWallet","secret","sourceWallet","cellSlugOrigin"])e.hasOwnProperty(t)&&delete e[t];return e}check(e=null){return we.verify({molecule:this,sourceWallet:e})}static verify({molecule:e,sourceWallet:t=null}){return me.molecularHash(e)&&me.ots(e)&&me.index(e)&&me.batchId(e)&&me.continuId(e)&&me.isotopeM(e)&&me.isotopeT(e)&&me.isotopeC(e)&&me.isotopeU(e)&&me.isotopeI(e)&&me.isotopeR(e)&&me.isotopeV(e,t)}}class $e{static __init(e,t){this.arr=[],this.key=null,this.arr=String(t).split("."),this.key=this.arr.shift();const s=Number(this.key);Number.isInteger(s)&&(this.key=s),this.__nextKey=this.arr.length,this.__next=this.__tic(e)}static __tic(e){return!!(Array.isArray(e)||e instanceof Object)&&void 0!==e[this.key]}static has(e,t){return this.__init(e,t),!!this.__next&&(0===this.__nextKey||this.has(e[this.key],this.arr.join(".")))}static get(e,t,s=null){return this.__init(e,t),this.__next?0===this.__nextKey?e[this.key]:this.get(e[this.key],this.arr.join("."),s):s}}const Ie=10**18;class Se{static val(e){return Math.abs(e*Ie)<1?0:e}static cmp(e,t,s=!1){const n=Se.val(e)*Ie,a=Se.val(t)*Ie;return Math.abs(n-a)<1?0:n>a?1:-1}static equal(e,t){return 0===Se.cmp(e,t)}}class Ae{static create(e,t){let s=new Ae(e);return s.setWallet(t),s}static restore(e,t){let s=new G({secret:t,token:"AUTH",position:e.wallet.position,characters:e.wallet.characters});return Ae.create({token:e.token,expiresAt:e.expiresAt,pubkey:e.pubkey,encrypt:e.encrypt},s)}constructor({token:e,expiresAt:t,encrypt:s,pubkey:n}){this.$__token=e,this.$__expiresAt=t,this.$__pubkey=n,this.$__encrypt=s}setWallet(e){this.$__wallet=e}getWallet(){return this.$__wallet}getSnapshot(){return{token:this.$__token,expiresAt:this.$__expiresAt,pubkey:this.$__pubkey,encrypt:this.$__encrypt,wallet:{position:this.$__wallet.position,characters:this.$__wallet.characters}}}getToken(){return this.$__token}getPubkey(){return this.$__pubkey}getExpireInterval(){return 1e3*this.$__expiresAt-Date.now()}isExpired(){return!this.$__expiresAt||this.getExpireInterval()<0}getAuthData(){return{token:this.getToken(),pubkey:this.getPubkey(),wallet:this.getWallet()}}}class Te extends Z{constructor(e="Code exception",t=null,s=null){super(e,t,s),this.name="CodeException"}}class xe extends Z{constructor(e="GraphQL did not provide a valid response.",t=null,s=null){super(e,t,s),this.name="InvalidResponseException"}}class ve extends Z{constructor(e="Authorization token missing or invalid.",t=null,s=null){super(e,t,s),this.name="UnauthenticatedException"}}class qe{constructor({query:e,json:t,dataKey:s=null}){if(this.dataKey=s,this.errorKey="exception",this.$__payload=null,this.$__query=e,this.$__originResponse=t,this.$__response=t,void 0===this.$__response||null===this.$__response)throw new xe;if($e.has(this.$__response,this.errorKey)){const e=$e.get(this.$__response,this.errorKey);if(String(e).includes("Unauthenticated"))throw new ve;throw new xe}this.init()}init(){}data(){if(!this.dataKey)return this.response();if(!$e.has(this.response(),this.dataKey))throw new xe;return $e.get(this.response(),this.dataKey)}response(){return this.$__response}payload(){return null}query(){return this.$__query}status(){return null}}class Me{constructor(e){this.client=e,this.$__variables=null,this.$__query=null}response(){return this.$__response}async createResponseRaw(e){return this.createResponse(e)}createResponse(e){return new qe({query:this,json:e})}createQuery({variables:e=null}){if(this.$__variables=this.compiledVariables(e),!this.uri())throw new Te("Query::createQuery() - Node URI was not initialized for this client instance!");if(null===this.$__query)throw new Te("Query::createQuery() - GraphQL subscription was not initialized!");return{query:this.$__query,variables:this.variables()}}async execute({variables:e=null}){this.$__request=this.createQuery({variables:e});let t=await this.client.query(this.$__request);return this.$__response=await this.createResponseRaw(t),this.$__response}compiledVariables(e=null){return e||{}}uri(){return this.client.getUri()}variables(){return this.$__variables}}class We extends qe{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.ContinuId"})}payload(){let e=null;const t=this.data();return t&&(e=new G({secret:null,token:t.tokenSlug}),e.address=t.address,e.position=t.position,e.bundle=t.bundleHash,e.batchId=t.batchId,e.characters=t.characters,e.pubkey=t.pubkey,e.balance=1*t.amount),e}}class Ce extends Me{constructor(e){super(e),this.$__query=h.gql`query ($bundle: String!) {
2
2
  ContinuId(bundle: $bundle) {
3
3
  address,
4
4
  bundleHash,
@@ -10,7 +10,7 @@
10
10
  amount,
11
11
  createdAt
12
12
  }
13
- }`}createResponse(e){return new Te({query:this,json:e})}}class ve extends Ae{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.WalletBundle"})}payload(){const e=this.data();if(!e||0===e.length)return null;const t={};return e.forEach((e=>{e.metas=U.aggregateMeta(e.metas),t[e.bundleHash]=e})),t}}class Me extends xe{constructor(e){super(e),this.$__query=h.gql`query( $bundleHash: String, $bundleHashes: [ String! ], $key: String, $keys: [ String! ], $value: String, $values: [ String! ], $keys_values: [ MetaInput ], $latest: Boolean, $limit: Int, $order: String ) {
13
+ }`}createResponse(e){return new We({query:this,json:e})}}class Ue extends qe{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.WalletBundle"})}payload(){const e=this.data();if(!e||0===e.length)return null;const t={};return e.forEach((e=>{e.metas=B.aggregateMeta(e.metas),t[e.bundleHash]=e})),t}}class He extends Me{constructor(e){super(e),this.$__query=h.gql`query( $bundleHash: String, $bundleHashes: [ String! ], $key: String, $keys: [ String! ], $value: String, $values: [ String! ], $keys_values: [ MetaInput ], $latest: Boolean, $limit: Int, $order: String ) {
14
14
  WalletBundle( bundleHash: $bundleHash, bundleHashes: $bundleHashes, key: $key, keys: $keys, value: $value, values: $values, keys_values: $keys_values, latest: $latest, limit: $limit, order: $order ) {
15
15
  bundleHash,
16
16
  metas {
@@ -22,7 +22,7 @@
22
22
  },
23
23
  createdAt
24
24
  }
25
- }`}createResponse(e){return new ve({query:this,json:e})}static createVariables({bundleHash:e=null,key:t=null,value:s=null,latest:n=!0}){const a={latest:n};return e&&(a["string"==typeof e?"bundleHash":"bundleHashes"]=e),t&&(a["string"==typeof t?"key":"keys"]=t),s&&(a["string"==typeof s?"value":"values"]=s),a}}class Ce extends Ae{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.Wallet"})}static toClientWallet({data:e,secret:t=null}){let s;return null===e.position||void 0===e.position?s=G.create({secretOrBundle:e.bundleHash,token:e.tokenSlug,batchId:e.batchId,characters:e.characters}):(s=new G({secret:t,token:e.tokenSlug,position:e.position,batchId:e.batchId,characters:e.characters}),s.address=e.address,s.bundle=e.bundleHash),e.token&&(s.tokenName=e.token.name,s.tokenAmount=e.token.amount,s.tokenSupply=e.token.supply,s.tokenFungibility=e.token.fungibility),s.tokenUnits=e.tokenUnits,s.molecules=e.molecules,s.balance=Number(e.amount),s.pubkey=e.pubkey,s.createdAt=e.createdAt,s}getWallets(e=null){const t=this.data();if(!t)return null;const s=[];for(let n of t)s.push(Ce.toClientWallet({data:n,secret:e}));return s}payload(){return this.getWallets()}}class We extends xe{constructor(e){super(e),this.$__query=h.gql`query( $address: String, $bundleHash: String, $token: String, $position: String, $unspent: Boolean ) {
25
+ }`}createResponse(e){return new Ue({query:this,json:e})}static createVariables({bundleHash:e=null,key:t=null,value:s=null,latest:n=!0}){const a={latest:n};return e&&(a["string"==typeof e?"bundleHash":"bundleHashes"]=e),t&&(a["string"==typeof t?"key":"keys"]=t),s&&(a["string"==typeof s?"value":"values"]=s),a}}class Be extends qe{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.Wallet"})}static toClientWallet({data:e,secret:t=null}){let s;return null===e.position||void 0===e.position?s=G.create({secretOrBundle:e.bundleHash,token:e.tokenSlug,batchId:e.batchId,characters:e.characters}):(s=new G({secret:t,token:e.tokenSlug,position:e.position,batchId:e.batchId,characters:e.characters}),s.address=e.address,s.bundle=e.bundleHash),e.token&&(s.tokenName=e.token.name,s.tokenAmount=e.token.amount,s.tokenSupply=e.token.supply,s.tokenFungibility=e.token.fungibility),s.tokenUnits=e.tokenUnits,s.molecules=e.molecules,s.balance=Number(e.amount),s.pubkey=e.pubkey,s.createdAt=e.createdAt,s}getWallets(e=null){const t=this.data();if(!t)return null;const s=[];for(let n of t)s.push(Be.toClientWallet({data:n,secret:e}));return s}payload(){return this.getWallets()}}class Re extends Me{constructor(e){super(e),this.$__query=h.gql`query( $address: String, $bundleHash: String, $token: String, $position: String, $unspent: Boolean ) {
26
26
  Wallet( address: $address, bundleHash: $bundleHash, token: $token, position: $position, unspent: $unspent ) {
27
27
  address,
28
28
  bundleHash,
@@ -49,7 +49,7 @@
49
49
  metas
50
50
  }
51
51
  }
52
- }`}createResponse(e){return new Ce({query:this,json:e})}}class He extends Ae{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.Balance"})}payload(){const e=this.data();return e&&e.bundleHash&&e.tokenSlug?Ce.toClientWallet({data:e}):null}}class Be extends xe{constructor(e){super(e),this.$__query=h.gql`query( $address: String, $bundleHash: String, $token: String, $position: String ) {
52
+ }`}createResponse(e){return new Be({query:this,json:e})}}class je extends qe{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.Balance"})}payload(){const e=this.data();return e&&e.bundleHash&&e.tokenSlug?Be.toClientWallet({data:e}):null}}class Oe extends Me{constructor(e){super(e),this.$__query=h.gql`query( $address: String, $bundleHash: String, $token: String, $position: String ) {
53
53
  Balance( address: $address, bundleHash: $bundleHash, token: $token, position: $position ) {
54
54
  address,
55
55
  bundleHash,
@@ -66,7 +66,7 @@
66
66
  metas
67
67
  }
68
68
  }
69
- }`}createResponse(e){return new He({query:this,json:e})}}class Ue extends Ae{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.MetaType"})}payload(){const e=this.data();if(!e||0===e.length)return null;let t={instances:{},instanceCount:{},paginatorInfo:{}},s=e.pop();return s.instances&&(t.instances=s.instances),s.instanceCount&&(t.instanceCount=s.instanceCount),s.paginatorInfo&&(t.paginatorInfo=s.paginatorInfo),t}}class je extends xe{constructor(e){super(e),this.$__query=h.gql`query( $metaType: String, $metaTypes: [ String! ], $metaId: String, $metaIds: [ String! ], $key: String, $keys: [ String! ], $value: String, $values: [ String! ], $count: String, $latest: Boolean, $filter: [ MetaFilter! ], $latestMetas: Boolean, $queryArgs: QueryArgs, $countBy: String ) {
69
+ }`}createResponse(e){return new je({query:this,json:e})}}class Ee extends qe{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.MetaType"})}payload(){const e=this.data();if(!e||0===e.length)return null;let t={instances:{},instanceCount:{},paginatorInfo:{}},s=e.pop();return s.instances&&(t.instances=s.instances),s.instanceCount&&(t.instanceCount=s.instanceCount),s.paginatorInfo&&(t.paginatorInfo=s.paginatorInfo),t}}class Ke extends Me{constructor(e){super(e),this.$__query=h.gql`query( $metaType: String, $metaTypes: [ String! ], $metaId: String, $metaIds: [ String! ], $key: String, $keys: [ String! ], $value: String, $values: [ String! ], $count: String, $latest: Boolean, $filter: [ MetaFilter! ], $latestMetas: Boolean, $queryArgs: QueryArgs, $countBy: String ) {
70
70
  MetaType( metaType: $metaType, metaTypes: $metaTypes, metaId: $metaId, metaIds: $metaIds, key: $key, keys: $keys, value: $value, values: $values, count: $count, filter: $filter, latestMetas: $latestMetas, queryArgs: $queryArgs, countBy: $countBy ) {
71
71
  metaType,
72
72
  instanceCount {
@@ -90,18 +90,18 @@
90
90
  total
91
91
  }
92
92
  }
93
- }`}createResponse(e){return new Ue({query:this,json:e})}static createVariables({metaType:e=null,metaId:t=null,key:s=null,value:n=null,latest:a=null,latestMetas:i=!0,filter:r=null,queryArgs:l=null,count:o=null,countBy:u=null}){const c={};return e&&(c["string"==typeof e?"metaType":"metaTypes"]=e),t&&(c["string"==typeof t?"metaId":"metaIds"]=t),s&&(c["string"==typeof s?"key":"keys"]=s),n&&(c["string"==typeof n?"value":"values"]=n),a&&(c.latest=!!a),i&&(c.latestMetas=!!i),r&&(c.filter=r),l&&(void 0!==l.limit&&0!==l.limit||(l.limit="*"),c.queryArgs=l),o&&(c.count=o),u&&(c.countBy=u),c}}class Oe extends xe{constructor(e){super(e),this.$__query=h.gql`query( $batchId: String ) {
93
+ }`}createResponse(e){return new Ee({query:this,json:e})}static createVariables({metaType:e=null,metaId:t=null,key:s=null,value:n=null,latest:a=null,latestMetas:i=!0,filter:r=null,queryArgs:l=null,count:o=null,countBy:u=null}){const c={};return e&&(c["string"==typeof e?"metaType":"metaTypes"]=e),t&&(c["string"==typeof t?"metaId":"metaIds"]=t),s&&(c["string"==typeof s?"key":"keys"]=s),n&&(c["string"==typeof n?"value":"values"]=n),a&&(c.latest=!!a),i&&(c.latestMetas=!!i),r&&(c.filter=r),l&&(void 0!==l.limit&&0!==l.limit||(l.limit="*"),c.queryArgs=l),o&&(c.count=o),u&&(c.countBy=u),c}}class Qe extends Me{constructor(e){super(e),this.$__query=h.gql`query( $batchId: String ) {
94
94
  Batch( batchId: $batchId ) {
95
- ${Oe.getFields()},
95
+ ${Qe.getFields()},
96
96
  children {
97
- ${Oe.getFields()}
97
+ ${Qe.getFields()}
98
98
  }
99
99
  }
100
- }`}static getFields(){return"batchId,\n molecularHash,\n type,\n status,\n createdAt,\n wallet {\n address,\n bundleHash,\n amount,\n tokenSlug,\n token {\n name,\n amount\n },\n tokenUnits {\n id,\n name,\n metas\n }\n },\n fromWallet {\n address,\n bundleHash,\n amount,\n batchId\n },\n toWallet {\n address,\n bundleHash,\n amount,\n batchId\n },\n sourceTokenUnits {\n id,\n name,\n metas\n },\n transferTokenUnits {\n id,\n name,\n metas\n },\n metas {\n key,\n value,\n },\n throughMetas {\n key,\n value\n }"}createResponse(e){let t=new Ae({query:this,json:e});return t.dataKey="data.Batch",t}}class Re extends xe{constructor(e){super(e),this.$__query=h.gql`query( $batchId: String ) {
100
+ }`}static getFields(){return"batchId,\n molecularHash,\n type,\n status,\n createdAt,\n wallet {\n address,\n bundleHash,\n amount,\n tokenSlug,\n token {\n name,\n amount\n },\n tokenUnits {\n id,\n name,\n metas\n }\n },\n fromWallet {\n address,\n bundleHash,\n amount,\n batchId\n },\n toWallet {\n address,\n bundleHash,\n amount,\n batchId\n },\n sourceTokenUnits {\n id,\n name,\n metas\n },\n transferTokenUnits {\n id,\n name,\n metas\n },\n metas {\n key,\n value,\n },\n throughMetas {\n key,\n value\n }"}createResponse(e){let t=new qe({query:this,json:e});return t.dataKey="data.Batch",t}}class Pe extends Me{constructor(e){super(e),this.$__query=h.gql`query( $batchId: String ) {
101
101
  BatchHistory( batchId: $batchId ) {
102
- ${Oe.getFields()}
102
+ ${Qe.getFields()}
103
103
  }
104
- }`}createResponse(e){let t=new Ae({query:this,json:e});return t.dataKey="data.BatchHistory",t}}class Ee extends Ae{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.ProposeMolecule"}),this.$__clientMolecule=e.molecule()}init(){const e=ke.get(this.data(),"payload");try{this.$__payload="[object String]"===Object.prototype.toString.call(e)?JSON.parse(e):e}catch(e){this.$__payload=null}}clientMolecule(){return this.$__clientMolecule}molecule(){const e=this.data();if(!e)return null;const t=new be({});return t.molecularHash=ke.get(e,"molecularHash"),t.status=ke.get(e,"status"),t.createdAt=ke.get(e,"createdAt"),t}success(){return"accepted"===this.status()}status(){return ke.get(this.data(),"status","rejected")}reason(){return ke.get(this.data(),"reason","Invalid response from server")}payload(){return this.$__payload}}class Ke extends xe{constructor(e){super(e)}createQuery({variables:e=null}){const t=super.createQuery({variables:e});return t.mutation=t.query,delete t.query,t}async execute({variables:e=null}){this.$__request=this.createQuery({variables:e});let t=await this.client.mutate(this.$__request);return this.$__response=await this.createResponseRaw(t),this.$__response}}class Qe extends Ke{constructor(e,t=null){super(e),this.$__molecule=t,this.$__remainderWallet=null,this.$__query=h.gql`mutation( $molecule: MoleculeInput! ) {
104
+ }`}createResponse(e){let t=new qe({query:this,json:e});return t.dataKey="data.BatchHistory",t}}class Ne extends qe{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.ProposeMolecule"}),this.$__clientMolecule=e.molecule()}init(){const e=$e.get(this.data(),"payload");try{this.$__payload="[object String]"===Object.prototype.toString.call(e)?JSON.parse(e):e}catch(e){this.$__payload=null}}clientMolecule(){return this.$__clientMolecule}molecule(){const e=this.data();if(!e)return null;const t=new we({});return t.molecularHash=$e.get(e,"molecularHash"),t.status=$e.get(e,"status"),t.createdAt=$e.get(e,"createdAt"),t}success(){return"accepted"===this.status()}status(){return $e.get(this.data(),"status","rejected")}reason(){return $e.get(this.data(),"reason","Invalid response from server")}payload(){return this.$__payload}}class Fe extends Me{constructor(e){super(e)}createQuery({variables:e=null}){const t=super.createQuery({variables:e});return t.mutation=t.query,delete t.query,t}async execute({variables:e=null}){this.$__request=this.createQuery({variables:e});let t=await this.client.mutate(this.$__request);return this.$__response=await this.createResponseRaw(t),this.$__response}}class Ve extends Fe{constructor(e,t=null){super(e),this.$__molecule=t,this.$__remainderWallet=null,this.$__query=h.gql`mutation( $molecule: MoleculeInput! ) {
105
105
  ProposeMolecule( molecule: $molecule ) {
106
106
  molecularHash,
107
107
  height,
@@ -114,13 +114,13 @@
114
114
  processedAt,
115
115
  broadcastedAt,
116
116
  }
117
- }`}compiledVariables(e){return{...super.compiledVariables(e),molecule:this.molecule()}}createResponse(e){return new Ee({query:this,json:e})}async execute({variables:e=null}){return(e=e||{}).molecule=this.molecule(),super.execute({variables:e})}remainderWallet(){return this.$__remainderWallet}molecule(){return this.$__molecule}}class Pe extends Ee{payloadKey(e){if(!ke.has(this.payload(),e))throw new Ie(`ResponseRequestAuthorization::payloadKey() - '${e}' key was not found in the payload!`);return ke.get(this.payload(),e)}token(){return this.payloadKey("token")}time(){return this.payloadKey("time")}encrypt(){return this.payloadKey("encrypt")}pubKey(){return this.payloadKey("key")}}class Ne extends Qe{fillMolecule({meta:e}){this.$__molecule.initAuthorization({meta:e}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Pe({query:this,json:e})}}class Fe extends Ee{}class Ve extends Qe{fillMolecule({recipientWallet:e,amount:t,meta:s=null}){this.$__molecule.initTokenCreation({recipientWallet:e,amount:t,meta:s||{}}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Fe({query:this,json:e})}}class De extends Ee{}class Je extends Qe{fillMolecule({token:e,amount:t,metaType:s,metaId:n,meta:a=null,batchId:i=null}){this.$__molecule.initTokenRequest({token:e,amount:t,metaType:s,metaId:n,meta:a||{},batchId:i}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new De({query:this,json:e})}}class Le extends Ee{payload(){const e={reason:null,status:null},t=this.data();return e.reason=void 0===t.reason?"Invalid response from server":t.reason,e.status=void 0===t.status?"rejected":t.status,e}}class ze extends Qe{fillMolecule({recipientWallet:e,amount:t}){this.$__molecule.initValue({recipientWallet:e,amount:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}createResponse(e){return new Le({query:this,json:e})}}class Ge extends Ee{}class Ze extends Qe{fillMolecule({type:e,contact:t,code:s}){this.$__molecule.initIdentifierCreation({type:e,contact:t,code:s}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Ge({query:this,json:e})}}class Xe extends Ee{}class Ye extends Qe{fillMolecule({token:e,batchId:t=null}){let s=G.create({secretOrBundle:this.$__molecule.secret,token:e,batchId:t});this.$__molecule.initShadowWalletClaim({token:e,wallet:s}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Xe({query:this,json:e})}}class et extends Ee{}class tt extends Qe{fillMolecule({metaType:e,metaId:t,meta:s,policy:n}){this.$__molecule.initMeta({meta:s,metaType:e,metaId:t,policy:n}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new et({query:this,json:e})}}class st extends Ee{}class nt extends Qe{fillMolecule(e){this.$__molecule.initWalletCreation(e),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new st({query:this,json:e})}}class at extends Ae{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.AccessToken"})}reason(){return"Invalid response from server"}success(){return null!==this.payload()}payload(){return this.data()}payloadKey(e){if(!ke.has(this.payload(),e))throw new Ie(`ResponseAuthorizationGuest::payloadKey() - '${e}' key is not found in the payload!`);return ke.get(this.payload(),e)}token(){return this.payloadKey("token")}time(){return this.payloadKey("time")}pubKey(){return this.payloadKey("key")}encrypt(){return this.payloadKey("encrypt")}}class it extends Ke{constructor(e){super(e),this.$__query=h.gql`mutation( $cellSlug: String, $pubkey: String, $encrypt: Boolean ) {
117
+ }`}compiledVariables(e){return{...super.compiledVariables(e),molecule:this.molecule()}}createResponse(e){return new Ne({query:this,json:e})}async execute({variables:e=null}){return(e=e||{}).molecule=this.molecule(),super.execute({variables:e})}remainderWallet(){return this.$__remainderWallet}molecule(){return this.$__molecule}}class Je extends Ne{payloadKey(e){if(!$e.has(this.payload(),e))throw new xe(`ResponseRequestAuthorization::payloadKey() - '${e}' key was not found in the payload!`);return $e.get(this.payload(),e)}token(){return this.payloadKey("token")}time(){return this.payloadKey("time")}encrypt(){return this.payloadKey("encrypt")}pubKey(){return this.payloadKey("key")}}class De extends Ve{fillMolecule({meta:e}){this.$__molecule.initAuthorization({meta:e}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Je({query:this,json:e})}}class Le extends Ne{}class ze extends Ve{fillMolecule({recipientWallet:e,amount:t,meta:s=null}){this.$__molecule.initTokenCreation({recipientWallet:e,amount:t,meta:s||{}}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Le({query:this,json:e})}}class Ge extends Ne{}class Ze extends Ve{fillMolecule({token:e,amount:t,metaType:s,metaId:n,meta:a=null,batchId:i=null}){this.$__molecule.initTokenRequest({token:e,amount:t,metaType:s,metaId:n,meta:a||{},batchId:i}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Ge({query:this,json:e})}}class Xe extends Ne{payload(){const e={reason:null,status:null},t=this.data();return e.reason=void 0===t.reason?"Invalid response from server":t.reason,e.status=void 0===t.status?"rejected":t.status,e}}class Ye extends Ve{fillMolecule({recipientWallet:e,amount:t}){this.$__molecule.initValue({recipientWallet:e,amount:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}createResponse(e){return new Xe({query:this,json:e})}}class et extends Ne{}class tt extends Ve{fillMolecule({type:e,contact:t,code:s}){this.$__molecule.initIdentifierCreation({type:e,contact:t,code:s}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new et({query:this,json:e})}}class st extends Ne{}class nt extends Ve{fillMolecule({token:e,batchId:t=null}){let s=G.create({secretOrBundle:this.$__molecule.secret,token:e,batchId:t});this.$__molecule.initShadowWalletClaim({token:e,wallet:s}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new st({query:this,json:e})}}class at extends Ne{}class it extends Ve{fillMolecule({metaType:e,metaId:t,meta:s,policy:n}){this.$__molecule.initMeta({meta:s,metaType:e,metaId:t,policy:n}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new at({query:this,json:e})}}class rt extends Ne{}class lt extends Ve{fillMolecule(e){this.$__molecule.initWalletCreation(e),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new rt({query:this,json:e})}}class ot extends qe{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.AccessToken"})}reason(){return"Invalid response from server"}success(){return null!==this.payload()}payload(){return this.data()}payloadKey(e){if(!$e.has(this.payload(),e))throw new xe(`ResponseAuthorizationGuest::payloadKey() - '${e}' key is not found in the payload!`);return $e.get(this.payload(),e)}token(){return this.payloadKey("token")}time(){return this.payloadKey("time")}pubKey(){return this.payloadKey("key")}encrypt(){return this.payloadKey("encrypt")}}class ut extends Fe{constructor(e){super(e),this.$__query=h.gql`mutation( $cellSlug: String, $pubkey: String, $encrypt: Boolean ) {
118
118
  AccessToken( cellSlug: $cellSlug, pubkey: $pubkey, encrypt: $encrypt ) {
119
119
  token,
120
120
  pubkey,
121
121
  expiresAt
122
122
  }
123
- }`}createResponse(e){return new at({query:this,json:e})}}class rt extends Z{constructor(e="The shadow wallet does not exist",t=null,s=null){super(e,t,s),this.name="WalletShadowException"}}class lt extends Z{constructor(e="Stackable tokens with unit IDs cannot have decimal places!",t=null,s=null){super(e,t,s),this.name="StackableUnitDecimalsException"}}class ot extends Z{constructor(e="Stackable tokens with unit IDs cannot have decimal places!",t=null,s=null){super(e,t,s),this.name="StackableUnitAmountException"}}function ut(e){return e.query.definitions.find((e=>"OperationDefinition"===e.kind)).selectionSet.selections.find((e=>"Field"===e.kind)).name.value}function ct({graphQLErrors:e,networkError:t,operation:s,forward:n,response:a}){if(e&&e.map((({message:e,debugMessage:t,locations:s,path:n})=>console.error(`[GraphQL error]: ${e}\r\n`,` Message : ${t}\r\n`,` Path : ${n}\r\n`,` Location: ${s}\r\n`))),t){const{name:e,statusCode:s,result:n={}}=t;console.error(`[Network error]: ${e}, status code: ${s}`)}}function ht(e){return(t,s)=>{let n;return new h.Observable((a=>(s(t).subscribe(function(e,t,s,n){return a=>{const i=ut(t),r=function(e,t){if(e.extensions&&e.extensions.lighthouse_subscriptions&&e.extensions.lighthouse_subscriptions.version){const s=e.extensions.lighthouse_subscriptions.version;if(s<2&&e.extensions.lighthouse_subscriptions.channels)return e.extensions.lighthouse_subscriptions.channels[t];if(2===s)return e.extensions.lighthouse_subscriptions.channel}return null}(a,i);r?(n(r),function(e,t,s,n){e.private(t.replace(/^private-/,"")).listen(".lighthouse-subscription",(e=>{let t=e.data;t.data&&(t=t.data),t[n]&&(t=t[n]),s.next(t)}))}(e,r,s,i)):(s.next(a),s.complete())}}(e,t,a,(e=>n=e))),()=>function(e,t){const s=t();s&&e.leave(s)}(e,(()=>n)))))}}class dt extends h.HttpLink{constructor(e){super(e)}request(e,t){return t(e)}}class pt extends h.ApolloLink{constructor({socketUri:e}){super(),console.log("EchoLink::constructor()..."),this.echo=null,this.socketUri=null,this.auth="",this.setEcho(e)}getAuthToken(){return this.auth}setAuthToken(e){this.auth=e}getSocketUri(){return this.socketUri}setEcho(e){console.log(`Connecting to socket endpoint ${e}...`),this.socketUri=e,this.echo=new S.default({broadcaster:"socket.io",client:A.default,authEndpoint:"graphql/subscriptions/auth",host:this.getSocketUri(),transports:["websocket"],auth:{headers:{"X-Auth-Token":this.getAuthToken(),Accept:"application/json"}}})}request(e,t){return this.echo.options.auth.headers["X-Auth-Token"]=this.getAuthToken(),ht(this.echo)(e,t)}}class mt extends h.ApolloLink{constructor(){super(),this.auth=""}getAuthToken(){return this.auth}setAuthToken(e){this.auth=e}request(e,t){return e.setContext((({headers:e={}})=>({headers:{...e,"X-Auth-Token":this.getAuthToken()}}))),t(e)}}class yt extends h.ApolloLink{constructor(){super(),this.__wallet=null,this.__pubkey=null}setWallet(e){this.__wallet=e}getWallet(){return this.__wallet}setPubKey(e){this.__pubkey=e}getPubKey(){return this.__pubkey}request(e,t){const s=ut(e),n=function(e){return e.query.definitions.find((e=>"OperationDefinition"===e.kind)).operation}(e),a="mutation"===n&&"ProposeMolecule"===s,i=["query"===n&&["__schema","ContinuId"].includes(s),"mutation"===n&&"AccessToken"===s,a&&"U"===ke.get(e,"variables.molecule.atoms.0.isotope")],r={query:b.print(e.query),variables:JSON.stringify(e.variables)},l=this.getWallet(),o=this.getPubKey();for(const s in i)if(i[s])return t(e);if(!o)throw new $e("CipherLink::request() - Node public key missing!");if(!l)throw new $e("CipherLink::request() - Authorized wallet missing!");return e.operationName=null,e.query=h.gql`query ( $Hash: String! ) { CipherHash ( Hash: $Hash ) { hash } }`,e.variables={Hash:JSON.stringify(l.encryptMyMessage(r,o))},t(e).map((e=>{let t=e.data;if(t.data&&(t=t.data),t.CipherHash&&t.CipherHash.hash){const e=JSON.parse(t.CipherHash.hash),s=l.decryptMyMessage(e);if(null===s)throw new $e("CipherLink::request() - Unable to decrypt response!");return s}return e}))}}class gt extends h.ApolloClient{constructor({serverUri:e,socketUri:t,encrypt:s=!1}){const n=[],a=new dt({uri:e,fetch:I.default,transportBatching:!0}),i=new mt;let r=null,l=null;n.push(i),s&&(r=new yt,n.push(r)),t&&(l=new pt({socketUri:t}),n.push(l)),n.push(h.concat(m.onError(ct),a)),super({link:h.from(n),cache:new p.InMemoryCache,connectToDevTools:!0,defaultOptions:{watchQuery:{fetchPolicy:"no-cache",errorPolicy:"ignore"},query:{fetchPolicy:"no-cache",errorPolicy:"all"},mutate:{fetchPolicy:"no-cache",errorPolicy:"all"},subscribe:{fetchPolicy:"no-cache",errorPolicy:"all"}}}),this.__serverUri=e,this.__socketUri=t,this.__authLink=i,this.__echoLink=l,this.__cipherLink=r,this.__pubkey=null,this.__wallet=null}getAuthToken(){return this.__authLink.getAuthToken()}getPubKey(){return this.__pubkey}getWallet(){return this.__wallet}setAuthData({token:e,pubkey:t=null,wallet:s=null}){this.__wallet=s,this.__pubkey=t,this.__authLink.setAuthToken(e),this.__echoLink&&this.__echoLink.setAuthToken(e),this.__cipherLink&&(this.__cipherLink.setWallet(this.__wallet),this.__cipherLink.setPubKey(this.__pubkey))}getServerUri(){return this.__serverUri}getSocketUri(){return this.__socketUri}}class bt{constructor({serverUri:e,socketUri:t=null,encrypt:s=!1}){this.$__subscribers={},this.$__uri=e,this.$__socketUri=t,this.$__client=null,this.restartTransport(s)}restartTransport(e=!1){const t=new gt({serverUri:this.$__uri,socketUri:this.$__socketUri,encrypt:e});this.$__client&&(this.unsubscribeAll(),t.setAuthData({token:this.$__client.getAuthToken(),pubkey:this.$__client.getPubKey(),wallet:this.$__client.getWallet()})),this.$__client=t}enableEncryption(){this.restartTransport(!0)}disableEncryption(){this.restartTransport()}unsubscribe(e){this.$__subscribers[e]&&(this.$__subscribers[e].unsubscribe(),delete this.$__subscribers[e])}unsubscribeAll(){for(let e in this.$__subscribers)this.$__subscribers.hasOwnProperty(e)&&this.unsubscribe(e)}subscribe(e,t){const s=ut(e);return this.unsubscribe(s),this.$__subscribers[s]=this.$__client.subscribe(e).subscribe((e=>t(e))),s}async query(e){return await this.$__client.query(e)}async mutate(e){return await this.$__client.mutate(e)}setAuthData({token:e,pubkey:t,wallet:s}){this.$__client.setAuthData({token:e,pubkey:t,wallet:s})}getAuthToken(){let e=this.$__client.getAuthToken();return e?e.getToken():null}getUri(){return this.$__uri}setUri(e){this.$__uri=e}getSocketUri(){return this.$__socketUri}setSocketUri(e){this.$__socketUri=e}}class kt{constructor(e){this.client=e,this.$__variables=null,this.$__subscribe=null}createSubscribe({variables:e=null}){if(this.$__variables=this.compiledVariables(e),!this.uri())throw new $e("Subscribe::createSubscribe() - Node URI was not initialized for this client instance!");if(null===this.$__subscribe)throw new $e("Subscribe::createSubscribe() - GraphQL subscription was not initialized!");return{query:this.$__subscribe,variables:this.variables(),fetchPolicy:"no-cache"}}async execute({variables:e=null,closure:t}){if(!t)throw new $e(`${this.constructor.name}::execute() - closure parameter is required!`);return this.$__request=this.createSubscribe({variables:e}),this.client.subscribe(this.$__request,t)}compiledVariables(e=null){return e||{}}uri(){return this.client.getUri()}variables(){return this.$__variables}}class ft extends kt{constructor(e){super(e),this.$__subscribe=h.gql`
123
+ }`}createResponse(e){return new ot({query:this,json:e})}}class ct extends Z{constructor(e="The shadow wallet does not exist",t=null,s=null){super(e,t,s),this.name="WalletShadowException"}}class ht extends Z{constructor(e="Stackable tokens with unit IDs cannot have decimal places!",t=null,s=null){super(e,t,s),this.name="StackableUnitDecimalsException"}}class dt extends Z{constructor(e="Stackable tokens with unit IDs cannot have decimal places!",t=null,s=null){super(e,t,s),this.name="StackableUnitAmountException"}}function pt(e){return e.query.definitions.find((e=>"OperationDefinition"===e.kind)).selectionSet.selections.find((e=>"Field"===e.kind)).name.value}function mt({graphQLErrors:e,networkError:t,operation:s,forward:n,response:a}){if(e&&e.map((({message:e,debugMessage:t,locations:s,path:n})=>console.error(`[GraphQL error]: ${e}\r\n`,` Message : ${t}\r\n`,` Path : ${n}\r\n`,` Location: ${s}\r\n`))),t){const{name:e,statusCode:s,result:n={}}=t;console.error(`[Network error]: ${e}, status code: ${s}`)}}function yt(e){return(t,s)=>{let n;return new h.Observable((a=>(s(t).subscribe(function(e,t,s,n){return a=>{const i=pt(t),r=function(e,t){if(e.extensions&&e.extensions.lighthouse_subscriptions&&e.extensions.lighthouse_subscriptions.version){const s=e.extensions.lighthouse_subscriptions.version;if(s<2&&e.extensions.lighthouse_subscriptions.channels)return e.extensions.lighthouse_subscriptions.channels[t];if(2===s)return e.extensions.lighthouse_subscriptions.channel}return null}(a,i);r?(n(r),function(e,t,s,n){e.private(t.replace(/^private-/,"")).listen(".lighthouse-subscription",(e=>{let t=e.data;t.data&&(t=t.data),t[n]&&(t=t[n]),s.next(t)}))}(e,r,s,i)):(s.next(a),s.complete())}}(e,t,a,(e=>n=e))),()=>function(e,t){const s=t();s&&e.leave(s)}(e,(()=>n)))))}}class gt extends h.HttpLink{constructor(e){super(e)}request(e,t){return t(e)}}class kt extends h.ApolloLink{constructor({socketUri:e}){super(),console.log("EchoLink::constructor()..."),this.echo=null,this.socketUri=null,this.auth="",this.setEcho(e)}getAuthToken(){return this.auth}setAuthToken(e){this.auth=e}getSocketUri(){return this.socketUri}setEcho(e){console.log(`Connecting to socket endpoint ${e}...`),this.socketUri=e,this.echo=new S.default({broadcaster:"socket.io",client:A.default,authEndpoint:"graphql/subscriptions/auth",host:this.getSocketUri(),transports:["websocket"],auth:{headers:{"X-Auth-Token":this.getAuthToken(),Accept:"application/json"}}})}request(e,t){return this.echo.options.auth.headers["X-Auth-Token"]=this.getAuthToken(),yt(this.echo)(e,t)}}class bt extends h.ApolloLink{constructor(){super(),this.auth=""}getAuthToken(){return this.auth}setAuthToken(e){this.auth=e}request(e,t){return e.setContext((({headers:e={}})=>({headers:{...e,"X-Auth-Token":this.getAuthToken()}}))),t(e)}}class _t extends h.ApolloLink{constructor(){super(),this.__wallet=null,this.__pubkey=null}setWallet(e){this.__wallet=e}getWallet(){return this.__wallet}setPubKey(e){this.__pubkey=e}getPubKey(){return this.__pubkey}request(e,t){const s=pt(e),n=function(e){return e.query.definitions.find((e=>"OperationDefinition"===e.kind)).operation}(e),a="mutation"===n&&"ProposeMolecule"===s,i=["query"===n&&["__schema","ContinuId"].includes(s),"mutation"===n&&"AccessToken"===s,a&&"U"===$e.get(e,"variables.molecule.atoms.0.isotope")],r={query:k.print(e.query),variables:JSON.stringify(e.variables)},l=this.getWallet(),o=this.getPubKey();for(const s in i)if(i[s])return t(e);if(!o)throw new Te("CipherLink::request() - Node public key missing!");if(!l)throw new Te("CipherLink::request() - Authorized wallet missing!");return e.operationName=null,e.query=h.gql`query ( $Hash: String! ) { CipherHash ( Hash: $Hash ) { hash } }`,e.variables={Hash:JSON.stringify(l.encryptMyMessage(r,o))},t(e).map((e=>{let t=e.data;if(t.data&&(t=t.data),t.CipherHash&&t.CipherHash.hash){const e=JSON.parse(t.CipherHash.hash),s=l.decryptMyMessage(e);if(null===s)throw new Te("CipherLink::request() - Unable to decrypt response!");return s}return e}))}}class ft extends h.ApolloClient{constructor({serverUri:e,socketUri:t,encrypt:s=!1}){const n=[],a=new gt({uri:e,fetch:I.default,transportBatching:!0}),i=new bt;let r=null,l=null;n.push(i),s&&(r=new _t,n.push(r)),t&&(l=new kt({socketUri:t}),n.push(l)),n.push(h.concat(m.onError(mt),a)),super({link:h.from(n),cache:new p.InMemoryCache,connectToDevTools:!0,defaultOptions:{watchQuery:{fetchPolicy:"no-cache",errorPolicy:"ignore"},query:{fetchPolicy:"no-cache",errorPolicy:"all"},mutate:{fetchPolicy:"no-cache",errorPolicy:"all"},subscribe:{fetchPolicy:"no-cache",errorPolicy:"all"}}}),this.__serverUri=e,this.__socketUri=t,this.__authLink=i,this.__echoLink=l,this.__cipherLink=r,this.__pubkey=null,this.__wallet=null}getAuthToken(){return this.__authLink.getAuthToken()}getPubKey(){return this.__pubkey}getWallet(){return this.__wallet}setAuthData({token:e,pubkey:t=null,wallet:s=null}){this.__wallet=s,this.__pubkey=t,this.__authLink.setAuthToken(e),this.__echoLink&&this.__echoLink.setAuthToken(e),this.__cipherLink&&(this.__cipherLink.setWallet(this.__wallet),this.__cipherLink.setPubKey(this.__pubkey))}getServerUri(){return this.__serverUri}getSocketUri(){return this.__socketUri}}class wt{constructor({serverUri:e,socketUri:t=null,encrypt:s=!1}){this.$__subscribers={},this.$__uri=e,this.$__socketUri=t,this.$__client=null,this.restartTransport(s)}restartTransport(e=!1){const t=new ft({serverUri:this.$__uri,socketUri:this.$__socketUri,encrypt:e});this.$__client&&(this.unsubscribeAll(),t.setAuthData({token:this.$__client.getAuthToken(),pubkey:this.$__client.getPubKey(),wallet:this.$__client.getWallet()})),this.$__client=t}enableEncryption(){this.restartTransport(!0)}disableEncryption(){this.restartTransport()}unsubscribe(e){this.$__subscribers[e]&&(this.$__subscribers[e].unsubscribe(),delete this.$__subscribers[e])}unsubscribeAll(){for(let e in this.$__subscribers)this.$__subscribers.hasOwnProperty(e)&&this.unsubscribe(e)}subscribe(e,t){const s=pt(e);return this.unsubscribe(s),this.$__subscribers[s]=this.$__client.subscribe(e).subscribe((e=>t(e))),s}async query(e){return await this.$__client.query(e)}async mutate(e){return await this.$__client.mutate(e)}setAuthData({token:e,pubkey:t,wallet:s}){this.$__client.setAuthData({token:e,pubkey:t,wallet:s})}getAuthToken(){let e=this.$__client.getAuthToken();return e?e.getToken():null}getUri(){return this.$__uri}setUri(e){this.$__uri=e}getSocketUri(){return this.$__socketUri}setSocketUri(e){this.$__socketUri=e}}class $t{constructor(e){this.client=e,this.$__variables=null,this.$__subscribe=null}createSubscribe({variables:e=null}){if(this.$__variables=this.compiledVariables(e),!this.uri())throw new Te("Subscribe::createSubscribe() - Node URI was not initialized for this client instance!");if(null===this.$__subscribe)throw new Te("Subscribe::createSubscribe() - GraphQL subscription was not initialized!");return{query:this.$__subscribe,variables:this.variables(),fetchPolicy:"no-cache"}}async execute({variables:e=null,closure:t}){if(!t)throw new Te(`${this.constructor.name}::execute() - closure parameter is required!`);return this.$__request=this.createSubscribe({variables:e}),this.client.subscribe(this.$__request,t)}compiledVariables(e=null){return e||{}}uri(){return this.client.getUri()}variables(){return this.$__variables}}class It extends $t{constructor(e){super(e),this.$__subscribe=h.gql`
124
124
  subscription onCreateMolecule ( $bundle: String! ) {
125
125
  CreateMolecule( bundle: $bundle ) {
126
126
  molecularHash,
@@ -165,7 +165,7 @@
165
165
  }
166
166
  }
167
167
  }
168
- `}}class _t extends kt{constructor(e){super(e),this.$__subscribe=h.gql`
168
+ `}}class St extends $t{constructor(e){super(e),this.$__subscribe=h.gql`
169
169
  subscription onWalletStatus ( $bundle: String!, $token: String! ) {
170
170
  WalletStatus( bundle: $bundle, token: $token ) {
171
171
  bundle,
@@ -174,7 +174,7 @@
174
174
  balance,
175
175
  }
176
176
  }
177
- `}}class wt extends kt{constructor(e){super(e),this.$__subscribe=h.gql`
177
+ `}}class At extends $t{constructor(e){super(e),this.$__subscribe=h.gql`
178
178
  subscription onActiveWallet ( $bundle: String! ) {
179
179
  ActiveWallet( bundle: $bundle ) {
180
180
  address,
@@ -212,7 +212,7 @@
212
212
  }
213
213
  }
214
214
  }
215
- `}}class $t extends kt{constructor(e){super(e),this.$__subscribe=h.gql`
215
+ `}}class Tt extends $t{constructor(e){super(e),this.$__subscribe=h.gql`
216
216
  subscription onActiveUser ( $metaType: String!, $metaId: String! ) {
217
217
  ActiveUser( metaType: $metaType, metaId: $metaId ) {
218
218
  bundleHash,
@@ -222,7 +222,7 @@
222
222
  createdAt,
223
223
  updatedAt
224
224
  }
225
- }`}}class It extends Ae{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.ActiveSession"})}}class St extends Ke{constructor(e){super(e),this.$__query=h.gql`mutation(
225
+ }`}}class xt extends qe{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.ActiveSession"})}}class vt extends Fe{constructor(e){super(e),this.$__query=h.gql`mutation(
226
226
  $bundleHash: String!,
227
227
  $metaType: String!,
228
228
  $metaId: String!,
@@ -250,7 +250,7 @@
250
250
  createdAt,
251
251
  updatedAt
252
252
  }
253
- }`}createResponse(e){return new It({query:this,json:e})}}class At extends Ae{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.ActiveUser"})}payload(){const e=this.data();if(!e)return null;const t=[];for(let s of e){const e={...s};e.jsonData&&(e.jsonData=JSON.parse(e.jsonData)),e.createdAt&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt)),t.push(e)}return t}}class xt extends xe{constructor(e){super(e),this.$__query=h.gql`query ActiveUserQuery ($bundleHash:String, $metaType: String, $metaId: String) {
253
+ }`}createResponse(e){return new xt({query:this,json:e})}}class qt extends qe{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.ActiveUser"})}payload(){const e=this.data();if(!e)return null;const t=[];for(let s of e){const e={...s};e.jsonData&&(e.jsonData=JSON.parse(e.jsonData)),e.createdAt&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt)),t.push(e)}return t}}class Mt extends Me{constructor(e){super(e),this.$__query=h.gql`query ActiveUserQuery ($bundleHash:String, $metaType: String, $metaId: String) {
254
254
  ActiveUser (bundleHash: $bundleHash, metaType: $metaType, metaId: $metaId) {
255
255
  bundleHash,
256
256
  metaType,
@@ -259,7 +259,7 @@
259
259
  createdAt,
260
260
  updatedAt
261
261
  }
262
- }`}createResponse(e){return new At({query:this,json:e})}}class Tt extends Ae{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.UserActivity"})}payload(){const e=JSON.parse(JSON.stringify(this.data()));if(e.instances)for(const t of e.instances)t.jsonData=JSON.parse(t.jsonData);return e}}class qt extends xe{constructor(e){super(e),this.$__query=h.gql`query UserActivity (
262
+ }`}createResponse(e){return new qt({query:this,json:e})}}class Wt extends qe{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.UserActivity"})}payload(){const e=JSON.parse(JSON.stringify(this.data()));if(e.instances)for(const t of e.instances)t.jsonData=JSON.parse(t.jsonData);return e}}class Ct extends Me{constructor(e){super(e),this.$__query=h.gql`query UserActivity (
263
263
  $bundleHash:String,
264
264
  $metaType: String,
265
265
  $metaId: String,
@@ -332,7 +332,7 @@
332
332
  }
333
333
  }
334
334
  }
335
- }`}createResponse(e){return new Tt({query:this,json:e})}}class vt extends xe{constructor(e){super(e),this.$__query=h.gql`query( $slug: String, $slugs: [ String! ], $limit: Int, $order: String ) {
335
+ }`}createResponse(e){return new Wt({query:this,json:e})}}class Ut extends Me{constructor(e){super(e),this.$__query=h.gql`query( $slug: String, $slugs: [ String! ], $limit: Int, $order: String ) {
336
336
  Token( slug: $slug, slugs: $slugs, limit: $limit, order: $order ) {
337
337
  slug,
338
338
  name,
@@ -342,7 +342,7 @@
342
342
  amount,
343
343
  icon,
344
344
  }
345
- }`}createResponse(e){return new Ae({query:this,json:e,dataKey:"data.Token"})}}class Mt extends Z{constructor(e="Authorization attempt rejected by ledger.",t=null,s=null){super(e,t,s),this.name="AuthorizationRejectedException"}}class Ct extends Ae{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.Atom"})}payload(){const e=this.data();if(!e)return null;let t={instances:[],instanceCount:{},paginatorInfo:{}};if(e.instances){t.instances=e.instances;for(let e in t.instances){let s=t.instances[e];s.metasJson&&(t.instances[e].metas=JSON.parse(s.metasJson))}}return e.instanceCount&&(t.instanceCount=e.instanceCount),e.paginatorInfo&&(t.paginatorInfo=e.paginatorInfo),t}metas(){const e=this.payload(),t=[];if(e&&e.instances)for(const s of e.instances)s.metasJson&&t.push(JSON.parse(s.metasJson));return t}}class Wt extends xe{constructor(e){super(e),this.$__query=h.gql`query(
345
+ }`}createResponse(e){return new qe({query:this,json:e,dataKey:"data.Token"})}}class Ht extends Z{constructor(e="Authorization attempt rejected by ledger.",t=null,s=null){super(e,t,s),this.name="AuthorizationRejectedException"}}class Bt extends qe{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.Atom"})}payload(){const e=this.data();if(!e)return null;let t={instances:[],instanceCount:{},paginatorInfo:{}};if(e.instances){t.instances=e.instances;for(let e in t.instances){let s=t.instances[e];s.metasJson&&(t.instances[e].metas=JSON.parse(s.metasJson))}}return e.instanceCount&&(t.instanceCount=e.instanceCount),e.paginatorInfo&&(t.paginatorInfo=e.paginatorInfo),t}metas(){const e=this.payload(),t=[];if(e&&e.instances)for(const s of e.instances)s.metasJson&&t.push(JSON.parse(s.metasJson));return t}}class Rt extends Me{constructor(e){super(e),this.$__query=h.gql`query(
346
346
  $molecularHashes: [String!],
347
347
  $bundleHashes: [String!],
348
348
  $positions:[String!],
@@ -398,7 +398,7 @@
398
398
  total
399
399
  }
400
400
  }
401
- }`}createResponse(e){return new Ct({query:this,json:e})}static createVariables({molecularHashes:e,molecularHash:t,bundleHashes:s,bundleHash:n,positions:a,position:i,walletAddresses:r,walletAddress:l,isotopes:o,isotope:u,tokenSlugs:c,tokenSlug:h,cellSlugs:d,cellSlug:p,batchIds:m,batchId:y,values:g,value:b,metaTypes:k,metaType:f,metaIds:_,metaId:w,indexes:$,index:I,filter:S,latest:A,queryArgs:x}){return t&&(e=e||[]).push(t),n&&(s=s||[]).push(n),i&&(a=a||[]).push(i),l&&(r=r||[]).push(l),u&&(o=o||[]).push(u),h&&(c=c||[]).push(h),p&&(d=d||[]).push(p),y&&(m=m||[]).push(y),b&&(g=g||[]).push(b),f&&(k=k||[]).push(f),w&&(_=_||[]).push(w),I&&($=$||[]).push(I),{molecularHashes:e,bundleHashes:s,positions:a,walletAddresses:r,isotopes:o,tokenSlugs:c,cellSlugs:d,batchIds:m,values:g,metaTypes:k,metaIds:_,indexes:$,filter:S,latest:A,queryArgs:x}}}class Ht extends Ae{constructor({query:e,json:t}){super({query:e,json:t}),this.dataKey="data.Policy",this.init()}payload(){const e=this.data();return e&&e.callback?JSON.parse(e.callback):null}}class Bt extends xe{constructor(e){super(e),this.$__query=h.gql`query( $metaType: String, $metaId: String, ) {
401
+ }`}createResponse(e){return new Bt({query:this,json:e})}static createVariables({molecularHashes:e,molecularHash:t,bundleHashes:s,bundleHash:n,positions:a,position:i,walletAddresses:r,walletAddress:l,isotopes:o,isotope:u,tokenSlugs:c,tokenSlug:h,cellSlugs:d,cellSlug:p,batchIds:m,batchId:y,values:g,value:k,metaTypes:b,metaType:_,metaIds:f,metaId:w,indexes:$,index:I,filter:S,latest:A,queryArgs:T}){return t&&(e=e||[]).push(t),n&&(s=s||[]).push(n),i&&(a=a||[]).push(i),l&&(r=r||[]).push(l),u&&(o=o||[]).push(u),h&&(c=c||[]).push(h),p&&(d=d||[]).push(p),y&&(m=m||[]).push(y),k&&(g=g||[]).push(k),_&&(b=b||[]).push(_),w&&(f=f||[]).push(w),I&&($=$||[]).push(I),{molecularHashes:e,bundleHashes:s,positions:a,walletAddresses:r,isotopes:o,tokenSlugs:c,cellSlugs:d,batchIds:m,values:g,metaTypes:b,metaIds:f,indexes:$,filter:S,latest:A,queryArgs:T}}}class jt extends qe{constructor({query:e,json:t}){super({query:e,json:t}),this.dataKey="data.Policy",this.init()}payload(){const e=this.data();return e&&e.callback?JSON.parse(e.callback):null}}class Ot extends Me{constructor(e){super(e),this.$__query=h.gql`query( $metaType: String, $metaId: String, ) {
402
402
  Policy( metaType: $metaType, metaId: $metaId ) {
403
403
  molecularHash,
404
404
  position,
@@ -409,11 +409,11 @@
409
409
  rule,
410
410
  createdAt
411
411
  }
412
- }`}createResponse(e){return new Ht({query:this,json:e})}}class Ut extends Ee{}class jt extends Qe{fillMolecule({metaType:e,metaId:t,policy:s={}}){this.$__molecule.addPolicyAtom({metaType:e,metaId:t,meta:{},policy:s}),this.$__molecule.addUserRemainderAtom(this.$__molecule.remainderWallet),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Ut({query:this,json:e})}}class Ot extends Ae{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.MetaTypeViaAtom"})}payload(){const e=this.data();if(!e||0===e.length)return null;let t={instances:{},instanceCount:{},paginatorInfo:{}},s=e.pop();return s.instances&&(t.instances=s.instances),s.instanceCount&&(t.instanceCount=s.instanceCount),s.paginatorInfo&&(t.paginatorInfo=s.paginatorInfo),t}}class Rt extends xe{constructor(e){super(e),this.$__query=h.gql`query ($metaTypes: [String!], $metaIds: [String!], $values: [String!], $latest: Boolean, $filter: [MetaFilter!], $queryArgs: QueryArgs, $countBy: String) {
412
+ }`}createResponse(e){return new jt({query:this,json:e})}}class Et extends Ne{}class Kt extends Ve{fillMolecule({metaType:e,metaId:t,policy:s={}}){this.$__molecule.addPolicyAtom({metaType:e,metaId:t,meta:{},policy:s}),this.$__molecule.addUserRemainderAtom(this.$__molecule.remainderWallet),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Et({query:this,json:e})}}class Qt extends qe{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.MetaTypeViaAtom"})}payload(){const e=this.data();if(!e||0===e.length)return null;let t={instances:{},instanceCount:{},paginatorInfo:{}},s=e.pop();return s.instances&&(t.instances=s.instances),s.instanceCount&&(t.instanceCount=s.instanceCount),s.paginatorInfo&&(t.paginatorInfo=s.paginatorInfo),t}}class Pt extends Me{constructor(e){super(e),this.$__query=h.gql`query ($metaTypes: [String!], $metaIds: [String!], $values: [String!], $keys: [String!], $latest: Boolean, $filter: [MetaFilter!], $queryArgs: QueryArgs, $countBy: String, $atomValues: [String!] ) {
413
413
  MetaTypeViaAtom(
414
414
  metaTypes: $metaTypes
415
415
  metaIds: $metaIds
416
- values: $values
416
+ atomValues: $atomValues
417
417
  filter: $filter,
418
418
  latest: $latest,
419
419
  queryArgs: $queryArgs
@@ -428,7 +428,7 @@
428
428
  metaType,
429
429
  metaId,
430
430
  createdAt,
431
- metas {
431
+ metas( values: $values, keys: $keys ) {
432
432
  molecularHash,
433
433
  position,
434
434
  key,
@@ -441,4 +441,4 @@
441
441
  total
442
442
  }
443
443
  }
444
- }`}createResponse(e){return new Ot({query:this,json:e})}static createVariables({metaType:e=null,metaId:t=null,key:s=null,value:n=null,latest:a=null,latestMetas:i=!0,filter:r=null,queryArgs:l=null,countBy:o=null}){const u={};return e&&(u.metaTypes=[e]),t&&(u.metaIds=[t]),o&&(u.countBy=o),r&&(u.filter=r),s&&n&&(u.filter=u.filter||[],u.filter.push({key:s,value:n,comparison:"="})),a&&(u.latest=!!a,u.latest=!!i),l&&(void 0!==l.limit&&0!==l.limit||(l.limit="*"),u.queryArgs=l),u}}class Et{constructor({uri:e,cellSlug:t=null,client:s=null,socketUri:n=null,serverSdkVersion:a=3,logging:i=!1}){this.initialize({uri:e,cellSlug:t,socketUri:n,client:s,serverSdkVersion:a,logging:i})}initialize({uri:e,cellSlug:t=null,socketUri:s=null,client:n=null,serverSdkVersion:a=3,logging:i=!1}){this.$__logging=i,this.$__uris="object"==typeof e?e:[e],this.$__authTokenObjects={},this.$__authInProcess=!1,t&&this.setCellSlug(t);for(let e in this.$__uris){let t=this.$__uris[e];this.$__authTokenObjects[t]=null}this.$__logging&&console.info(`KnishIOClient::initialize() - Initializing new Knish.IO client session for SDK version ${a}...`),this.reset(),this.$__client=n||new bt({socketUri:s,serverUri:this.getRandomUri()}),this.$__serverSdkVersion=a}getRandomUri(){let e=Math.floor(Math.random()*this.$__uris.length);return this.$__uris[e]}switchEncryption(e){return this.hasEncryption()!==e&&(this.$__logging&&console.warn("KnishIOClient::switchEncryption() - Node not respecting requested encryption policy!"),e?(this.$__logging&&console.info("KnishIOClient::switchEncryption() - Forcing encryption on to match node..."),this.enableEncryption()):(this.$__logging&&console.info("KnishIOClient::switchEncryption() - Forcing encryption off to match node..."),this.disableEncryption()),!0)}enableEncryption(){this.$__logging&&console.info("KnishIOClient::enableEncryption() - Enabling end-to-end encryption mode..."),this.$__encrypt=!0,this.$__client.enableEncryption()}disableEncryption(){this.$__logging&&console.info("KnishIOClient::disableEncryption() - Disabling end-to-end encryption mode..."),this.$__encrypt=!1,this.$__client.disableEncryption()}hasEncryption(){return this.$__encrypt}deinitialize(){this.$__logging&&console.info("KnishIOClient::deinitialize() - Clearing the Knish.IO client session..."),this.reset()}subscribe(){if(!this.client().getSocketUri())throw new $e("KnishIOClient::subscribe() - Socket client not initialized!");return this.client()}getServerSdkVersion(){return this.$__serverSdkVersion}reset(){this.$__secret="",this.$__bundle="",this.remainderWallet=null}cellSlug(){return this.$__cellSlug||null}setCellSlug(e){this.$__cellSlug=e}uri(){return this.$__client.getUri()}client(){if(!this.$__authInProcess){let e=this.getRandomUri();this.$__client.setUri(e);let t=this.$__authTokenObjects[e];t?this.$__client.setAuthData(t.getAuthData()):this.requestAuthToken({secret:this.$__secret,cellSlug:this.$__cellSlug,encrypt:this.$__encrypt}).then((()=>{}))}return this.$__client}hasSecret(){return!!this.$__secret}setSecret(e){this.$__secret=e,this.$__bundle=P(e)}getSecret(){if(!this.hasSecret())throw new Se("KnishIOClient::getSecret() - Unable to find a stored secret! Have you set a secret?");return this.$__secret}hasBundle(){return!!this.$__bundle}getBundle(){if(!this.hasBundle())throw new Se("KnishIOClient::getBundle() - Unable to find a stored bundle! Have you set a secret?");return this.$__bundle}async getSourceWallet(){let e=(await this.queryContinuId({bundle:this.getBundle()})).payload();return e?e.key=G.generatePrivateKey({secret:this.getSecret(),token:e.token,position:e.position}):e=new G({secret:this.getSecret()}),e}getRemainderWallet(){return this.remainderWallet}async createMolecule({secret:e=null,sourceWallet:t=null,remainderWallet:s=null}){this.$__logging&&console.info("KnishIOClient::createMolecule() - Creating a new molecule...");const n=e||this.getSecret();let a=t;return!t&&this.lastMoleculeQuery&&"AUTH"!==this.getRemainderWallet().token&&this.lastMoleculeQuery&&this.lastMoleculeQuery.response()&&this.lastMoleculeQuery.response().success()&&(a=this.getRemainderWallet()),null===a&&(a=await this.getSourceWallet()),this.remainderWallet=s||G.create({secretOrBundle:n,token:"USER",batchId:a.batchId,characters:a.characters}),new be({secret:n,sourceWallet:a,remainderWallet:this.getRemainderWallet(),cellSlug:this.cellSlug()})}createQuery(e){return new e(this.client())}createSubscribe(e){return new e(this.subscribe())}async createMoleculeMutation({mutationClass:e,molecule:t=null}){this.$__logging&&console.info(`KnishIOClient::createMoleculeQuery() - Creating a new ${e.name} query...`);let s=t||await this.createMolecule({});const n=new e(this.client(),s);if(!(n instanceof Qe))throw new $e(`${this.constructor.name}::createMoleculeMutation() - This method only accepts MutationProposeMolecule!`);return this.lastMoleculeQuery=n,n}async executeQuery(e,t=null){return e.execute({variables:t})}async queryBalance({token:e,bundle:t=null}){const s=this.createQuery(Be);return this.executeQuery(s,{bundleHash:t||this.getBundle(),token:e})}subscribeCreateMolecule({bundle:e,closure:t}){return this.createSubscribe(ft).execute({variables:{bundle:e||this.getBundle()},closure:t})}subscribeWalletStatus({bundle:e,token:t,closure:s}){if(!t)throw new $e(`${this.constructor.name}::subscribeWalletStatus() - Token parameter is required!`);return this.createSubscribe(_t).execute({variables:{bundle:e||this.getBundle(),token:t},closure:s})}subscribeActiveWallet({bundle:e,closure:t}){return this.createSubscribe(wt).execute({variables:{bundle:e||this.getBundle()},closure:t})}subscribeActiveSession({metaType:e,metaId:t,closure:s}){return this.createSubscribe($t).execute({variables:{metaType:e,metaId:t},closure:s})}unsubscribe(e){this.subscribe().unsubscribe(e)}unsubscribeAll(){this.subscribe().unsubscribeAll()}async queryMetaViaAtom({metaType:e,metaId:t,filter:s=null,queryArgs:n={limit:15,offset:1}}){return await this.queryAtom({metaType:e,metaId:t,filter:s,isotopes:["C","M"],latest:!0,queryArgs:n})}queryMeta({metaType:e,metaId:t=null,key:s=null,value:n=null,latest:a=null,latestMetas:i=null,fields:r=null,filter:l=null,queryArgs:o=null,count:u=null,countBy:c=null,throughAtom:h=!1}){let d,p;return this.$__logging&&console.info(`KnishIOClient::queryMeta() - Querying metaType: ${e}, metaId: ${t}...`),h?(d=this.createQuery(Rt),p=Rt.createVariables({metaType:e,metaId:t,key:s,value:n,latest:a,latestMetas:i,filter:l,queryArgs:o,countBy:c})):(d=this.createQuery(je),p=je.createVariables({metaType:e,metaId:t,key:s,value:n,latest:a,latestMetas:i,filter:l,queryArgs:o,count:u,countBy:c})),this.executeQuery(d,p).then((e=>e.payload()))}queryMetaInstance({metaType:e,metaId:t=null,key:s=null,value:n=null,latest:a=null,filter:i=null,fields:r=null}){this.$__logging&&console.info(`KnishIOClient::queryMetaInstance() - Querying metaType: ${e}, metaId: ${t}...`);const l=this.createQuery(je),o={metaType:e,metaIds:[t],keys:[s],values:[n],latest:a,filter:i};return this.executeQuery(l,o).then((e=>e.data()))}async queryBatch({batchId:e}){this.$__logging&&console.info(`KnishIOClient::queryBatch() - Querying cascading meta instances for batchId: ${e}...`);const t=this.createQuery(Oe);return await this.executeQuery(t,{batchId:e})}async queryBatchHistory({batchId:e}){this.$__logging&&console.info(`KnishIOClient::queryBatchHistory() - Querying cascading meta instances for batchId: ${e}...`);const t=this.createQuery(Re);return await this.executeQuery(t,{batchId:e})}async queryAtom({molecularHashes:e,molecularHash:t,bundleHashes:s,bundleHash:n,positions:a,position:i,walletAddresses:r,walletAddress:l,isotopes:o,isotope:u,tokenSlugs:c,tokenSlug:h,cellSlugs:d,cellSlug:p,batchIds:m,batchId:y,values:g,value:b,metaTypes:k,metaType:f,metaIds:_,metaId:w,indexes:$,index:I,filter:S,latest:A,queryArgs:x={limit:15,offset:1}}){this.$__logging&&console.info("KnishIOClient::queryAtom() - Querying atom instances");const T=this.createQuery(Wt);return await this.executeQuery(T,Wt.createVariables({molecularHashes:e,molecularHash:t,bundleHashes:s,bundleHash:n,positions:a,position:i,walletAddresses:r,walletAddress:l,isotopes:o,isotope:u,tokenSlugs:c,tokenSlug:h,cellSlugs:d,cellSlug:p,batchIds:m,batchId:y,values:g,value:b,metaTypes:k,metaType:f,metaIds:_,metaId:w,indexes:$,index:I,filter:S,latest:A,queryArgs:x}))}async createWallet({token:e}){const t=new G({secret:this.getSecret(),token:e}),s=await this.createMoleculeMutation({mutationClass:nt});return s.fillMolecule(t),await this.executeQuery(s)}async queryActiveSession({bundleHash:e,metaType:t,metaId:s}){const n=this.createQuery(xt);return await this.executeQuery(n,{bundleHash:e,metaType:t,metaId:s})}async queryUserActivity({bundleHash:e,metaType:t,metaId:s,ipAddress:n,browser:a,osCpu:i,resolution:r,timeZone:l,countBy:o,interval:u}){const c=this.createQuery(qt);return await this.executeQuery(c,{bundleHash:e,metaType:t,metaId:s,ipAddress:n,browser:a,osCpu:i,resolution:r,timeZone:l,countBy:o,interval:u})}async activeSession({bundle:e,metaType:t,metaId:s,ipAddress:n,browser:a,osCpu:i,resolution:r,timeZone:l,json:o={}}){const u=this.createQuery(St);return await this.executeQuery(u,{bundleHash:e,metaType:t,metaId:s,ipAddress:n,browser:a,osCpu:i,resolution:r,timeZone:l,json:JSON.stringify(o)})}async createToken({token:e,amount:t=null,meta:s=null,batchId:n=null,units:a=[]}){if("stackable"===ke.get(s||{},"fungibility")&&(n||(n=N({})),s.batchId=n,a.length>0)){if(ke.get(s||{},"decimals")>0)throw new lt;if(t>0)throw new ot;t=a.length,s.splittable=1,s.tokenUnits=JSON.stringify(a)}const i=new G({secret:this.getSecret(),token:e,batchId:n}),r=await this.createMoleculeMutation({mutationClass:Ve});return r.fillMolecule({recipientWallet:i,amount:t,meta:s||{}}),await this.executeQuery(r)}async createMeta({metaType:e,metaId:t,meta:s=null,policy:n={}}){const a=await this.createMoleculeMutation({mutationClass:tt,molecule:await this.createMolecule({secret:this.getSecret(),sourceWallet:await this.getSourceWallet()})}),i=s||{};return a.fillMolecule({metaType:e,metaId:t,meta:i,policy:n}),await this.executeQuery(a)}async createIdentifier({type:e,contact:t,code:s}){const n=await this.createMoleculeMutation({mutationClass:Ze});return n.fillMolecule({type:e,contact:t,code:s}),await this.executeQuery(n)}async createPolicy({metaType:e,metaId:t,policy:s={}}){const n=await this.createMoleculeMutation({mutationClass:jt});return n.fillMolecule({metaType:e,metaId:t,policy:s}),await this.executeQuery(n)}async queryPolicy({metaType:e,metaId:t}){const s=this.createQuery(Bt);return await this.executeQuery(s,{metaType:e,metaId:t})}queryWallets({bundle:e=null,token:t=null,unspent:s=!0}){this.$__logging&&console.info(`KnishIOClient::queryWallets() - Querying wallets${e?` for ${e}`:""}...`);const n=this.createQuery(We);return this.executeQuery(n,{bundleHash:e||this.getBundle(),token:t,unspent:s}).then((e=>e.payload()))}queryShadowWallets({token:e="KNISH",bundle:t=null}){t=t||this.getBundle(),this.$__logging&&console.info(`KnishIOClient::queryShadowWallets() - Querying ${e} shadow wallets for ${t}...`);const s=this.createQuery(We);return this.executeQuery(s,{bundleHash:t,token:e}).then((e=>e.payload()))}queryBundle({bundle:e=null,key:t=null,value:s=null,latest:n=!0,fields:a=null,raw:i=!1}){this.$__logging&&console.info(`KnishIOClient::queryBundle() - Querying wallet bundle metadata${e?` for ${e}`:""}...`);const r=this.createQuery(Me),l=Me.createVariables({bundleHash:e||this.getBundle(),key:t,value:s,latest:n});return this.executeQuery(r,l).then((e=>i?e:e.payload()))}async queryContinuId({bundle:e}){const t=this.createQuery(qe);return this.executeQuery(t,{bundle:e})}async requestTokens({token:e,to:t,amount:s=null,units:n=[],meta:a=null,batchId:i=null}){let r,l;a=a||{};const o=this.createQuery(vt),u=await this.executeQuery(o,{slug:e}),c="stackable"===ke.get(u.data(),"0.fungibility");if(!c&&null!==i)throw new de("Expected Batch ID = null for non-stackable tokens.");if(c&&null===i&&(i=N({})),n.length>0){if(s>0)throw new ot;s=n.length,a.tokenUnits=JSON.stringify(n)}t?("[object String]"===Object.prototype.toString.call(t)&&(G.isBundleHash(t)?(r="walletBundle",l=t):t=G.create({secretOrBundle:t,token:e})),t instanceof G&&(r="wallet",a.position=t.position,a.bundle=t.bundle,l=t.address)):(r="walletBundle",l=this.getBundle());const h=await this.createMoleculeMutation({mutationClass:Je});return h.fillMolecule({token:e,amount:s,metaType:r,metaId:l,meta:a,batchId:i}),await this.executeQuery(h)}async claimShadowWallet({token:e,batchId:t=null,molecule:s=null}){const n=await this.createMoleculeMutation({mutationClass:Ye,molecule:s});return n.fillMolecule({token:e,batchId:t}),await this.executeQuery(n)}async claimShadowWallets({token:e}){const t=await this.queryShadowWallets({token:e});if(!t||!Array.isArray(t))throw new rt;t.forEach((e=>{if(!e.isShadow())throw new rt}));let s=[];for(const n of t)s.push(await this.claimShadowWallet({token:e,batchId:n.batchId}));return s}async transferToken({recipient:e,token:t,amount:s=null,units:n=[],batchId:a=null,sourceWallet:i=null}){if(null===i&&(i=(await this.queryBalance({token:t})).payload()),n.length>0){if(s>0)throw new ot;s=n.length}if(null===i||_e.cmp(i.balance,s)<0)throw new ae;let r=e instanceof G?e:(await this.queryBalance({token:t,bundle:e})).payload();null===r&&(r=G.create({secretOrBundle:e,token:t})),null!==a?r.batchId=a:r.initBatchId({sourceWallet:i}),this.remainderWallet=G.create({secretOrBundle:this.getSecret(),token:t,characters:i.characters}),this.remainderWallet.initBatchId({sourceWallet:i,isRemainder:!0}),i.splitUnits(n,this.remainderWallet,r);const l=await this.createMolecule({sourceWallet:i,remainderWallet:this.remainderWallet}),o=await this.createMoleculeMutation({mutationClass:ze,molecule:l});return o.fillMolecule({recipientWallet:r,amount:s}),await this.executeQuery(o)}async burnTokens({token:e,amount:t=null,units:s=[],sourceWallet:n=null}){null===n&&(n=(await this.queryBalance({token:e})).payload());let a=G.create({secretOrBundle:this.getSecret(),token:e,characters:n.characters});if(a.initBatchId({sourceWallet:n,isRemainder:!0}),s.length>0){if(t>0)throw new ot;t=s.length,n.splitUnits(s,a)}let i=await this.createMolecule({secret:null,sourceWallet:n,remainderWallet:a});i.burnToken({amount:t}),i.sign({}),i.check();const r=new Qe(this.client(),i);return this.executeQuery(r)}async requestGuestAuthToken({cellSlug:e,encrypt:t}){this.setCellSlug(e);const s=new G({secret:Q(),token:"AUTH"}),n=await this.createQuery(it),a=await this.executeQuery(n,{cellSlug:e,pubkey:s.pubkey,encrypt:t});if(!a.success())throw new Mt(`KnishIOClient::requestGuestAuthToken() - Authorization attempt rejected by ledger. Reason: ${a.reason()}`);{const e=we.create(a.payload(),s);this.setAuthToken(e)}return a}async requestProfileAuthToken({secret:e,encrypt:t}){this.setSecret(e);const s=new G({secret:e,token:"AUTH"}),n=await this.createMolecule({secret:e,sourceWallet:s}),a=await this.createMoleculeMutation({mutationClass:Ne,molecule:n});a.fillMolecule({meta:{encrypt:t?"true":"false"}});const i=await this.executeQuery(a);if(!i.success())throw new Mt(`KnishIOClient::requestProfileAuthToken() - Authorization attempt rejected by ledger. Reason: ${i.reason()}`);{const e=we.create(i.payload(),s);this.setAuthToken(e)}return i}async requestAuthToken({secret:e=null,seed:t=null,cellSlug:s=null,encrypt:n=!1}){if(this.$__serverSdkVersion<3)return this.$__logging&&console.warn("KnishIOClient::authorize() - Server SDK version does not require an authorization..."),null;let a;return null===e&&t&&(e=Q(t)),this.$__authInProcess=!0,a=e?await this.requestProfileAuthToken({secret:e,encrypt:n}):await this.requestGuestAuthToken({cellSlug:s,encrypt:n}),this.$__logging&&console.info(`KnishIOClient::authorize() - Successfully retrieved auth token ${this.$__authToken.token}...`),this.switchEncryption(n),this.$__authInProcess=!1,a}setAuthToken(e){e?(this.$__authTokenObjects[this.uri()]=e,this.client().setAuthData(e.getAuthData()),this.$__authToken=e):this.$__logging&&console.info("KnishIOClient::setAuthToken() - authToken object is empty.")}getAuthToken(){return this.$__authToken}}e.Atom=j,e.KnishIOClient=Et,e.Meta=U,e.Molecule=be,e.Test=class{constructor(e,t=!1){this.encrypt=t,this.secrets=[Q(),Q()],this.tokenSlugs=["TESTTOKEN","UTENVSTACKABLE","UTSTACKUNIT","UTENVSTACKUNIT"],this.graphqlUrl=e,console.log(`---------- GraphQL URI: ${this.graphqlUrl}`),this.clients={},this.tokenUnits=[["unit_id_1","unit_name_1","unit_meta_1"],["unit_id_2","unit_name_2","unit_meta_2"],["unit_id_3","unit_name_3","unit_meta_3"],["unit_id_4","unit_name_4","unit_meta_4"],["unit_id_5","unit_name_5","unit_meta_5"],["unit_id_6","unit_name_6","unit_meta_6"],["unit_id_7","unit_name_7","unit_meta_7"],["unit_id_8","unit_name_8","unit_meta_8"],["unit_id_9","unit_name_9","unit_meta_9"],["unit_id_10","unit_name_10","unit_meta_10"],["unit_id_11","unit_name_11","unit_meta_11"]],this.tokenUnits=[["unit_id_1"],["unit_id_2"],["unit_id_3"],["unit_id_4"],["unit_id_5"],["unit_id_6"],["unit_id_7"],["unit_id_8"],["unit_id_9"],["unit_id_10"],["unit_id_11"]]}async testAll(){await this.client(this.secrets[0])}async testCreateToken(){let e={},t=await this.client(this.secrets[0]);e[0]=await t.createToken({token:this.tokenSlugs[0],amount:1e3,meta:{name:this.tokenSlugs[0],fungibility:"stackable",supply:"limited",decimals:0,icon:"icon"},batchId:"batch_0"}),this.checkResponse(e[0],"testCreateToken.0");let s=await this.client(process.env.SECRET_TOKEN_KNISH);e[1]=await s.createToken({token:this.tokenSlugs[1],amount:1e3,meta:{name:this.tokenSlugs[1],fungibility:"stackable",supply:"limited",decimals:0,icon:"icon"},batchId:"server_batch_0"}),this.checkResponse(e[1],"testCreateToken.1"),e[2]=await t.createToken({token:this.tokenSlugs[2],units:this.tokenUnits,meta:{name:this.tokenSlugs[2],supply:"limited",fungibility:"stackable"},batchId:"unit_batch_0"}),this.checkResponse(e[2],"testCreateToken.2"),e[3]=await s.createToken({token:this.tokenSlugs[3],units:this.tokenUnits,meta:{name:this.tokenSlugs[3],supply:"limited",fungibility:"stackable"},batchId:"server_unit_batch_0"}),this.checkResponse(e[3],"testCreateToken.3")}async testCreateWallet(){let e=await this.client(this.secrets[0]),t=await e.createWallet({token:this.tokenSlugs[1]});this.checkResponse(t,"testCreateWallet")}async testCreateMeta(){let e=await this.client(this.secrets[0]),t=await e.createMeta({metaType:"metaType",metaId:"metaId",meta:{key1:"value1",key2:"value2"}});this.checkResponse(t,"testCreateMeta")}async testCreateIdentifier(){let e=await this.client(this.secrets[0]),t=await e.createIdentifier({type:"email",contact:"test@test.com",code:"1234"});this.checkResponse(t,"testCreateIdentifier")}async testRequestTokens(){let e=await this.client(this.secrets[0]),t=await e.requestTokens({token:this.tokenSlugs[1],amount:10,to:this.secrets[0],batchId:"batch_5"});this.checkResponse(t,"testRequestTokens.1"),t=await e.requestTokens({token:this.tokenSlugs[3],units:["unit_id_10","unit_id_11"],to:this.secrets[0],batchId:"batch_6"}),this.checkResponse(t,"testRequestTokens.2")}async testTransferToken(){let e,t=P(this.secrets[1]),s=await this.client(this.secrets[0]);e=await s.transferToken({recipient:t,token:this.tokenSlugs[0],amount:10,batchId:"batch_1"}),this.checkResponse(e,"testTransferToken"),e=await s.transferToken({recipient:t,token:this.tokenSlugs[2],units:["unit_id_1","unit_id_2"],batchId:"batch_2"}),this.checkResponse(e,"testTransferUnitToken")}async testBurnToken(){let e;P(this.secrets[1]);let t=await this.client(this.secrets[0]);e=await t.burnTokens({token:this.tokenSlugs[0],amount:10,batchId:"batch_3"}),this.checkResponse(e,"testBurnToken"),e=await t.burnTokens({token:this.tokenSlugs[2],units:["unit_id_3","unit_id_4"],batchId:"batch_4"}),this.checkResponse(e,"testBurnUnitToken")}async testClaimShadowWallet(){let e=await this.client(this.secrets[1]),t=await e.queryBalance({token:this.tokenSlugs[0]}),s=await e.claimShadowWallet({token:this.tokenSlugs[0],batchId:t.payload().batchId});this.checkResponse(s,"testClaimShadowWallet")}async testQueryMeta(){let e=await this.client(this.secrets[0]),t=await e.queryMeta({metaType:"metaType",metaId:"metaId"});this.checkResponse(t,"testQueryMeta")}async testQueryWallets(){let e=await this.client(this.secrets[0]),t=await e.queryWallets({});this.checkResponse(t,"testQueryWallets")}async testQueryShadowWallets(){let e=await this.client(this.secrets[1]),t=await e.queryShadowWallets({token:this.tokenSlugs[0]});this.checkResponse(t,"testQueryShadowWallets")}async testQueryBundle(){let e=await this.client(this.secrets[0]),t=await e.queryBundle({});this.checkResponse(t,"testQueryBundle")}async testQueryContinuId(){let e=P(this.secrets[0]),t=await this.client(this.secrets[0]),s=await t.queryContinuId({bundle:e});this.checkResponse(s,"testQueryContinuId")}async testQueryBalance(){let e=await this.client(this.secrets[0]),t=await e.queryBalance({token:this.tokenSlugs[0]});this.checkResponse(t,"testQueryBalance")}async client(e,t="unit_test"){return this.clients[e]||(this.clients[e]=new Et({uri:this.graphqlUrl,logging:!0}),await this.clients[e].requestAuthToken({secret:e,encrypt:this.encrypt,cellSlug:t}),this.clients[e].getAuthToken()||console.log("Error with authorize - get an empty response.")),this.clients[e]}checkResponse(e,t){console.log(` ############### ${t} ###############`),console.log(e),e instanceof Ee?(e.success()||this.debug(e),console.assert(e.success(),e)):this.debug(e)}debug(e){e.data&&ke.get(e.data()||{},"reason")?console.log(e.data().reason):console.log(e)}},e.Wallet=G,e.base64ToHex=C,e.bufferToHexString=function(e){return x.toHex(e,{})},e.charsetBaseConvert=v,e.chunkSubstr=T,e.decryptMessage=D,e.encryptMessage=V,e.generateBundleHash=P,e.generateEncPrivateKey=J,e.generateEncPublicKey=L,e.generateSecret=Q,e.hashShare=z,e.hexStringToBuffer=function(e){return x.toUint8Array(e)},e.hexToBase64=M,e.isHex=W,e.randomString=q,Object.defineProperty(e,"__esModule",{value:!0})}));
444
+ }`}createResponse(e){return new Qt({query:this,json:e})}static createVariables({metaType:e=null,metaId:t=null,key:s=null,value:n=null,keys:a=null,values:i=null,atomValues:r=null,latest:l=null,latestMetas:o=!0,filter:u=null,queryArgs:c=null,countBy:h=null}){const d={};return r&&(d.atomValues=r),a&&(d.keys=a),i&&(d.values=i),e&&(d.metaTypes="string"==typeof e?[e]:e),t&&(d.metaIds="string"==typeof t?[t]:t),h&&(d.countBy=h),u&&(d.filter=u),s&&n&&(d.filter=d.filter||[],d.filter.push({key:s,value:n,comparison:"="})),l&&(d.latest=!!l,d.latest=!!o),c&&(void 0!==c.limit&&0!==c.limit||(c.limit="*"),d.queryArgs=c),d}}class Nt extends Ne{}class Ft extends Ve{fillMolecule({metaType:e,metaId:t,rule:s,policy:n}){this.$__molecule.createRule({metaType:e,metaId:t,rule:s,policy:n}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Nt({query:this,json:e})}}class Vt{constructor({uri:e,cellSlug:t=null,client:s=null,socketUri:n=null,serverSdkVersion:a=3,logging:i=!1}){this.initialize({uri:e,cellSlug:t,socketUri:n,client:s,serverSdkVersion:a,logging:i})}initialize({uri:e,cellSlug:t=null,socketUri:s=null,client:n=null,serverSdkVersion:a=3,logging:i=!1}){this.$__logging=i,this.$__uris="object"==typeof e?e:[e],this.$__authTokenObjects={},this.$__authInProcess=!1,t&&this.setCellSlug(t);for(let e in this.$__uris){let t=this.$__uris[e];this.$__authTokenObjects[t]=null}this.$__logging&&console.info(`KnishIOClient::initialize() - Initializing new Knish.IO client session for SDK version ${a}...`),this.reset(),this.$__client=n||new wt({socketUri:s,serverUri:this.getRandomUri()}),this.$__serverSdkVersion=a}getRandomUri(){let e=Math.floor(Math.random()*this.$__uris.length);return this.$__uris[e]}switchEncryption(e){return this.hasEncryption()!==e&&(this.$__logging&&console.warn("KnishIOClient::switchEncryption() - Node not respecting requested encryption policy!"),e?(this.$__logging&&console.info("KnishIOClient::switchEncryption() - Forcing encryption on to match node..."),this.enableEncryption()):(this.$__logging&&console.info("KnishIOClient::switchEncryption() - Forcing encryption off to match node..."),this.disableEncryption()),!0)}enableEncryption(){this.$__logging&&console.info("KnishIOClient::enableEncryption() - Enabling end-to-end encryption mode..."),this.$__encrypt=!0,this.$__client.enableEncryption()}disableEncryption(){this.$__logging&&console.info("KnishIOClient::disableEncryption() - Disabling end-to-end encryption mode..."),this.$__encrypt=!1,this.$__client.disableEncryption()}hasEncryption(){return this.$__encrypt}deinitialize(){this.$__logging&&console.info("KnishIOClient::deinitialize() - Clearing the Knish.IO client session..."),this.reset()}subscribe(){if(!this.client().getSocketUri())throw new Te("KnishIOClient::subscribe() - Socket client not initialized!");return this.client()}getServerSdkVersion(){return this.$__serverSdkVersion}reset(){this.$__secret="",this.$__bundle="",this.remainderWallet=null}cellSlug(){return this.$__cellSlug||null}setCellSlug(e){this.$__cellSlug=e}uri(){return this.$__client.getUri()}client(){if(!this.$__authInProcess){let e=this.getRandomUri();this.$__client.setUri(e);let t=this.$__authTokenObjects[e];t?this.$__client.setAuthData(t.getAuthData()):this.requestAuthToken({secret:this.$__secret,cellSlug:this.$__cellSlug,encrypt:this.$__encrypt}).then((()=>{}))}return this.$__client}hasSecret(){return!!this.$__secret}setSecret(e){this.$__secret=e,this.$__bundle=P(e)}getSecret(){if(!this.hasSecret())throw new ve("KnishIOClient::getSecret() - Unable to find a stored secret! Have you set a secret?");return this.$__secret}hasBundle(){return!!this.$__bundle}getBundle(){if(!this.hasBundle())throw new ve("KnishIOClient::getBundle() - Unable to find a stored bundle! Have you set a secret?");return this.$__bundle}async getSourceWallet(){let e=(await this.queryContinuId({bundle:this.getBundle()})).payload();return e?e.key=G.generatePrivateKey({secret:this.getSecret(),token:e.token,position:e.position}):e=new G({secret:this.getSecret()}),e}getRemainderWallet(){return this.remainderWallet}async createMolecule({secret:e=null,sourceWallet:t=null,remainderWallet:s=null}){return this.$__logging&&console.info("KnishIOClient::createMolecule() - Creating a new molecule..."),e=e||this.getSecret(),!t&&this.lastMoleculeQuery&&"AUTH"!==this.getRemainderWallet().token&&this.lastMoleculeQuery.response()&&this.lastMoleculeQuery.response().success()&&(t=this.getRemainderWallet()),null===t&&(t=await this.getSourceWallet()),this.remainderWallet=s||G.create({secretOrBundle:e,token:"USER",batchId:t.batchId,characters:t.characters}),new we({secret:e,sourceWallet:t,remainderWallet:this.getRemainderWallet(),cellSlug:this.cellSlug()})}createQuery(e){return new e(this.client())}createSubscribe(e){return new e(this.subscribe())}async createMoleculeMutation({mutationClass:e,molecule:t=null}){this.$__logging&&console.info(`KnishIOClient::createMoleculeQuery() - Creating a new ${e.name} query...`);let s=t||await this.createMolecule({});const n=new e(this.client(),s);if(!(n instanceof Ve))throw new Te(`${this.constructor.name}::createMoleculeMutation() - This method only accepts MutationProposeMolecule!`);return this.lastMoleculeQuery=n,n}async executeQuery(e,t=null){return this.$__authToken&&this.$__authToken.isExpired()&&(console.info("KnishIOClient::executeQuery() - Access token is expired. Getting new one..."),await this.requestAuthToken({secret:this.$__secret,cellSlug:this.$__cellSlug,encrypt:this.$__encrypt})),e.execute({variables:t})}async queryBalance({token:e,bundle:t=null}){const s=this.createQuery(Oe);return this.executeQuery(s,{bundleHash:t||this.getBundle(),token:e})}subscribeCreateMolecule({bundle:e,closure:t}){return this.createSubscribe(It).execute({variables:{bundle:e||this.getBundle()},closure:t})}subscribeWalletStatus({bundle:e,token:t,closure:s}){if(!t)throw new Te(`${this.constructor.name}::subscribeWalletStatus() - Token parameter is required!`);return this.createSubscribe(St).execute({variables:{bundle:e||this.getBundle(),token:t},closure:s})}subscribeActiveWallet({bundle:e,closure:t}){return this.createSubscribe(At).execute({variables:{bundle:e||this.getBundle()},closure:t})}subscribeActiveSession({metaType:e,metaId:t,closure:s}){return this.createSubscribe(Tt).execute({variables:{metaType:e,metaId:t},closure:s})}unsubscribe(e){this.subscribe().unsubscribe(e)}unsubscribeAll(){this.subscribe().unsubscribeAll()}queryMeta({metaType:e,metaId:t=null,key:s=null,value:n=null,latest:a=null,latestMetas:i=null,fields:r=null,filter:l=null,queryArgs:o=null,count:u=null,countBy:c=null,throughAtom:h=!1,values:d=null,keys:p=null,atomValues:m=null}){let y,g;return this.$__logging&&console.info(`KnishIOClient::queryMeta() - Querying metaType: ${e}, metaId: ${t}...`),h?(y=this.createQuery(Pt),g=Pt.createVariables({metaType:e,metaId:t,key:s,value:n,latest:a,latestMetas:i,filter:l,queryArgs:o,countBy:c,values:d,keys:p,atomValues:m})):(y=this.createQuery(Ke),g=Ke.createVariables({metaType:e,metaId:t,key:s,value:n,latest:a,latestMetas:i,filter:l,queryArgs:o,count:u,countBy:c})),this.executeQuery(y,g).then((e=>e.payload()))}queryMetaInstance({metaType:e,metaId:t=null,key:s=null,value:n=null,latest:a=null,filter:i=null,fields:r=null}){this.$__logging&&console.info(`KnishIOClient::queryMetaInstance() - Querying metaType: ${e}, metaId: ${t}...`);const l=this.createQuery(Ke),o={metaType:e,metaIds:[t],keys:[s],values:[n],latest:a,filter:i};return this.executeQuery(l,o).then((e=>e.data()))}async queryBatch({batchId:e}){this.$__logging&&console.info(`KnishIOClient::queryBatch() - Querying cascading meta instances for batchId: ${e}...`);const t=this.createQuery(Qe);return await this.executeQuery(t,{batchId:e})}async queryBatchHistory({batchId:e}){this.$__logging&&console.info(`KnishIOClient::queryBatchHistory() - Querying cascading meta instances for batchId: ${e}...`);const t=this.createQuery(Pe);return await this.executeQuery(t,{batchId:e})}async queryAtom({molecularHashes:e,molecularHash:t,bundleHashes:s,bundleHash:n,positions:a,position:i,walletAddresses:r,walletAddress:l,isotopes:o,isotope:u,tokenSlugs:c,tokenSlug:h,cellSlugs:d,cellSlug:p,batchIds:m,batchId:y,values:g,value:k,metaTypes:b,metaType:_,metaIds:f,metaId:w,indexes:$,index:I,filter:S,latest:A,queryArgs:T={limit:15,offset:1}}){this.$__logging&&console.info("KnishIOClient::queryAtom() - Querying atom instances");const x=this.createQuery(Rt);return await this.executeQuery(x,Rt.createVariables({molecularHashes:e,molecularHash:t,bundleHashes:s,bundleHash:n,positions:a,position:i,walletAddresses:r,walletAddress:l,isotopes:o,isotope:u,tokenSlugs:c,tokenSlug:h,cellSlugs:d,cellSlug:p,batchIds:m,batchId:y,values:g,value:k,metaTypes:b,metaType:_,metaIds:f,metaId:w,indexes:$,index:I,filter:S,latest:A,queryArgs:T}))}async createWallet({token:e}){const t=new G({secret:this.getSecret(),token:e}),s=await this.createMoleculeMutation({mutationClass:lt});return s.fillMolecule(t),await this.executeQuery(s)}async queryActiveSession({bundleHash:e,metaType:t,metaId:s}){const n=this.createQuery(Mt);return await this.executeQuery(n,{bundleHash:e,metaType:t,metaId:s})}async queryUserActivity({bundleHash:e,metaType:t,metaId:s,ipAddress:n,browser:a,osCpu:i,resolution:r,timeZone:l,countBy:o,interval:u}){const c=this.createQuery(Ct);return await this.executeQuery(c,{bundleHash:e,metaType:t,metaId:s,ipAddress:n,browser:a,osCpu:i,resolution:r,timeZone:l,countBy:o,interval:u})}async activeSession({bundle:e,metaType:t,metaId:s,ipAddress:n,browser:a,osCpu:i,resolution:r,timeZone:l,json:o={}}){const u=this.createQuery(vt);return await this.executeQuery(u,{bundleHash:e,metaType:t,metaId:s,ipAddress:n,browser:a,osCpu:i,resolution:r,timeZone:l,json:JSON.stringify(o)})}async createToken({token:e,amount:t=null,meta:s=null,batchId:n=null,units:a=[]}){if("stackable"===$e.get(s||{},"fungibility")&&(n||(n=N({})),s.batchId=n,a.length>0)){if($e.get(s||{},"decimals")>0)throw new ht;if(t>0)throw new dt;t=a.length,s.splittable=1,s.tokenUnits=JSON.stringify(a)}const i=new G({secret:this.getSecret(),token:e,batchId:n}),r=await this.createMoleculeMutation({mutationClass:ze});return r.fillMolecule({recipientWallet:i,amount:t,meta:s||{}}),await this.executeQuery(r)}async createRule({metaType:e,metaId:t,rule:s,policy:n={}}){const a=await this.createMoleculeMutation({mutationClass:Ft,molecule:await this.createMolecule({secret:this.getSecret(),sourceWallet:await this.getSourceWallet()})});return a.fillMolecule({metaType:e,metaId:t,rule:s,policy:n}),await this.executeQuery(a)}async createMeta({metaType:e,metaId:t,meta:s=null,policy:n={}}){const a=await this.createMoleculeMutation({mutationClass:it,molecule:await this.createMolecule({secret:this.getSecret(),sourceWallet:await this.getSourceWallet()})}),i=s||{};return a.fillMolecule({metaType:e,metaId:t,meta:i,policy:n}),await this.executeQuery(a)}async createIdentifier({type:e,contact:t,code:s}){const n=await this.createMoleculeMutation({mutationClass:tt});return n.fillMolecule({type:e,contact:t,code:s}),await this.executeQuery(n)}async createPolicy({metaType:e,metaId:t,policy:s={}}){const n=await this.createMoleculeMutation({mutationClass:Kt});return n.fillMolecule({metaType:e,metaId:t,policy:s}),await this.executeQuery(n)}async queryPolicy({metaType:e,metaId:t}){const s=this.createQuery(Ot);return await this.executeQuery(s,{metaType:e,metaId:t})}queryWallets({bundle:e=null,token:t=null,unspent:s=!0}){this.$__logging&&console.info(`KnishIOClient::queryWallets() - Querying wallets${e?` for ${e}`:""}...`);const n=this.createQuery(Re);return this.executeQuery(n,{bundleHash:e||this.getBundle(),token:t,unspent:s}).then((e=>e.payload()))}queryShadowWallets({token:e="KNISH",bundle:t=null}){t=t||this.getBundle(),this.$__logging&&console.info(`KnishIOClient::queryShadowWallets() - Querying ${e} shadow wallets for ${t}...`);const s=this.createQuery(Re);return this.executeQuery(s,{bundleHash:t,token:e}).then((e=>e.payload()))}queryBundle({bundle:e=null,key:t=null,value:s=null,latest:n=!0,fields:a=null,raw:i=!1}){this.$__logging&&console.info(`KnishIOClient::queryBundle() - Querying wallet bundle metadata${e?` for ${e}`:""}...`);const r=this.createQuery(He),l=He.createVariables({bundleHash:e||this.getBundle(),key:t,value:s,latest:n});return this.executeQuery(r,l).then((e=>i?e:e.payload()))}async queryContinuId({bundle:e}){const t=this.createQuery(Ce);return this.executeQuery(t,{bundle:e})}async requestTokens({token:e,to:t,amount:s=null,units:n=[],meta:a=null,batchId:i=null}){let r,l;a=a||{};const o=this.createQuery(Ut),u=await this.executeQuery(o,{slug:e}),c="stackable"===$e.get(u.data(),"0.fungibility");if(!c&&null!==i)throw new de("Expected Batch ID = null for non-stackable tokens.");if(c&&null===i&&(i=N({})),n.length>0){if(s>0)throw new dt;s=n.length,a.tokenUnits=JSON.stringify(n)}t?("[object String]"===Object.prototype.toString.call(t)&&(G.isBundleHash(t)?(r="walletBundle",l=t):t=G.create({secretOrBundle:t,token:e})),t instanceof G&&(r="wallet",a.position=t.position,a.bundle=t.bundle,l=t.address)):(r="walletBundle",l=this.getBundle());const h=await this.createMoleculeMutation({mutationClass:Ze});return h.fillMolecule({token:e,amount:s,metaType:r,metaId:l,meta:a,batchId:i}),await this.executeQuery(h)}async claimShadowWallet({token:e,batchId:t=null,molecule:s=null}){const n=await this.createMoleculeMutation({mutationClass:nt,molecule:s});return n.fillMolecule({token:e,batchId:t}),await this.executeQuery(n)}async claimShadowWallets({token:e}){const t=await this.queryShadowWallets({token:e});if(!t||!Array.isArray(t))throw new ct;t.forEach((e=>{if(!e.isShadow())throw new ct}));let s=[];for(const n of t)s.push(await this.claimShadowWallet({token:e,batchId:n.batchId}));return s}async transferToken({recipient:e,token:t,amount:s=null,units:n=[],batchId:a=null,sourceWallet:i=null}){if(null===i&&(i=(await this.queryBalance({token:t})).payload()),n.length>0){if(s>0)throw new dt;s=n.length}if(null===i||Se.cmp(i.balance,s)<0)throw new ae;let r=e instanceof G?e:(await this.queryBalance({token:t,bundle:e})).payload();null===r&&(r=G.create({secretOrBundle:e,token:t})),null!==a?r.batchId=a:r.initBatchId({sourceWallet:i}),this.remainderWallet=G.create({secretOrBundle:this.getSecret(),token:t,characters:i.characters}),this.remainderWallet.initBatchId({sourceWallet:i,isRemainder:!0}),i.splitUnits(n,this.remainderWallet,r);const l=await this.createMolecule({sourceWallet:i,remainderWallet:this.remainderWallet}),o=await this.createMoleculeMutation({mutationClass:Ye,molecule:l});return o.fillMolecule({recipientWallet:r,amount:s}),await this.executeQuery(o)}async burnTokens({token:e,amount:t=null,units:s=[],sourceWallet:n=null}){null===n&&(n=(await this.queryBalance({token:e})).payload());let a=G.create({secretOrBundle:this.getSecret(),token:e,characters:n.characters});if(a.initBatchId({sourceWallet:n,isRemainder:!0}),s.length>0){if(t>0)throw new dt;t=s.length,n.splitUnits(s,a)}let i=await this.createMolecule({secret:null,sourceWallet:n,remainderWallet:a});i.burnToken({amount:t}),i.sign({}),i.check();const r=new Ve(this.client(),i);return this.executeQuery(r)}async replenishToken({token:e,amount:t=null,units:s=[],sourceWallet:n=null}){null===n&&(n=(await this.queryBalance({token:e})).payload());let a=G.create({secretOrBundle:this.getSecret(),token:e,characters:n.characters});a.initBatchId({sourceWallet:n,isRemainder:!0});let i=await this.createMolecule({secret:null,sourceWallet:n,remainderWallet:a});i.replenishToken({amount:t,units:s}),i.sign({}),i.check();const r=new Ve(this.client(),i);return this.executeQuery(r)}async requestGuestAuthToken({cellSlug:e,encrypt:t}){this.setCellSlug(e);const s=new G({secret:Q(),token:"AUTH"}),n=await this.createQuery(ut),a=await n.execute({cellSlug:e,pubkey:s.pubkey,encrypt:t});if(!a.success())throw new Ht(`KnishIOClient::requestGuestAuthToken() - Authorization attempt rejected by ledger. Reason: ${a.reason()}`);{const e=Ae.create(a.payload(),s);this.setAuthToken(e)}return a}async requestProfileAuthToken({secret:e,encrypt:t}){this.setSecret(e);const s=new G({secret:e,token:"AUTH"}),n=await this.createMolecule({secret:e,sourceWallet:s}),a=await this.createMoleculeMutation({mutationClass:De,molecule:n});a.fillMolecule({meta:{encrypt:t?"true":"false"}});const i=await a.execute({});if(!i.success())throw new Ht(`KnishIOClient::requestProfileAuthToken() - Authorization attempt rejected by ledger. Reason: ${i.reason()}`);{const e=Ae.create(i.payload(),s);this.setAuthToken(e)}return i}async requestAuthToken({secret:e=null,seed:t=null,cellSlug:s=null,encrypt:n=!1}){if(this.$__serverSdkVersion<3)return this.$__logging&&console.warn("KnishIOClient::authorize() - Server SDK version does not require an authorization..."),null;let a;return null===e&&t&&(e=Q(t)),this.$__authInProcess=!0,a=e?await this.requestProfileAuthToken({secret:e,encrypt:n}):await this.requestGuestAuthToken({cellSlug:s,encrypt:n}),this.$__logging&&console.info(`KnishIOClient::authorize() - Successfully retrieved auth token ${this.$__authToken.getToken()}...`),this.switchEncryption(n),this.$__authInProcess=!1,a}setAuthToken(e){e?(this.$__authTokenObjects[this.uri()]=e,this.client().setAuthData(e.getAuthData()),this.$__authToken=e):this.$__logging&&console.info("KnishIOClient::setAuthToken() - authToken object is empty.")}getAuthToken(){return this.$__authToken}}e.Atom=R,e.KnishIOClient=Vt,e.Meta=B,e.Molecule=we,e.Test=class{constructor(e,t=!1){this.encrypt=t,this.secrets=[Q(),Q()],this.tokenSlugs=["TESTTOKEN","UTENVSTACKABLE","UTSTACKUNIT","UTENVSTACKUNIT"],this.graphqlUrl=e,console.log(`---------- GraphQL URI: ${this.graphqlUrl}`),this.clients={},this.tokenUnits=[["unit_id_1","unit_name_1","unit_meta_1"],["unit_id_2","unit_name_2","unit_meta_2"],["unit_id_3","unit_name_3","unit_meta_3"],["unit_id_4","unit_name_4","unit_meta_4"],["unit_id_5","unit_name_5","unit_meta_5"],["unit_id_6","unit_name_6","unit_meta_6"],["unit_id_7","unit_name_7","unit_meta_7"],["unit_id_8","unit_name_8","unit_meta_8"],["unit_id_9","unit_name_9","unit_meta_9"],["unit_id_10","unit_name_10","unit_meta_10"],["unit_id_11","unit_name_11","unit_meta_11"]],this.tokenUnits=[["unit_id_1"],["unit_id_2"],["unit_id_3"],["unit_id_4"],["unit_id_5"],["unit_id_6"],["unit_id_7"],["unit_id_8"],["unit_id_9"],["unit_id_10"],["unit_id_11"]],this.replenishTokenUnits=[["unit_id_12"],["unit_id_13"],["unit_id_14"],["unit_id_15"]]}async testAll(){await this.client(this.secrets[0]),await this.client(this.secrets[1]),await this.testCreateToken(),await this.testCreateWallet(),await this.testCreateMeta(),await this.testCreateIdentifier(),await this.testRequestTokens(),await this.testTransferToken(),await this.testBurnToken(),await this.testReplenishToken(),await this.testClaimShadowWallet(),await this.testQueryMeta(),await this.testQueryWallets(),await this.testQueryShadowWallets(),await this.testQueryBundle(),await this.testQueryBalance()}async testTokenExpiration(){const e=await this.client(this.secrets[0]),t=t=>{setTimeout((e=>{console.warn(`setTimeout ${t}`),e.queryMeta({metaType:"metaType",metaId:"metaId"})}),t,e,t)};t(3e3),t(3e4),t(61e3),t(64e3)}async testCreateToken(){let e={},t=await this.client(this.secrets[0]);e[0]=await t.createToken({token:this.tokenSlugs[0],amount:1e3,meta:{name:this.tokenSlugs[0],fungibility:"stackable",supply:"limited",decimals:0,icon:"icon"},batchId:"batch_0"}),this.checkResponse(e[0],"testCreateToken.0");let s=await this.client(process.env.SECRET_TOKEN_KNISH);e[1]=await s.createToken({token:this.tokenSlugs[1],amount:1e3,meta:{name:this.tokenSlugs[1],fungibility:"stackable",supply:"limited",decimals:0,icon:"icon"},batchId:"server_batch_0"}),this.checkResponse(e[1],"testCreateToken.1"),e[2]=await t.createToken({token:this.tokenSlugs[2],units:this.tokenUnits,meta:{name:this.tokenSlugs[2],supply:"limited",fungibility:"stackable"},batchId:"unit_batch_0"}),this.checkResponse(e[2],"testCreateToken.2"),e[3]=await s.createToken({token:this.tokenSlugs[3],units:this.tokenUnits,meta:{name:this.tokenSlugs[3],supply:"limited",fungibility:"stackable"},batchId:"server_unit_batch_0"}),this.checkResponse(e[3],"testCreateToken.3")}async testCreateWallet(){let e=await this.client(this.secrets[0]),t=await e.createWallet({token:this.tokenSlugs[1]});this.checkResponse(t,"testCreateWallet")}async testCreateMeta(){let e=await this.client(this.secrets[0]),t=await e.createMeta({metaType:"metaType",metaId:"metaId",meta:{key1:"value1",key2:"value2"}});this.checkResponse(t,"testCreateMeta")}async testCreateIdentifier(){let e=await this.client(this.secrets[0]),t=await e.createIdentifier({type:"email",contact:"test@test.com",code:"1234"});this.checkResponse(t,"testCreateIdentifier")}async testRequestTokens(){let e=await this.client(this.secrets[0]),t=await e.requestTokens({token:this.tokenSlugs[1],amount:10,to:this.secrets[0],batchId:"batch_5"});this.checkResponse(t,"testRequestTokens.1"),t=await e.requestTokens({token:this.tokenSlugs[3],units:["unit_id_10","unit_id_11"],to:this.secrets[0],batchId:"batch_6"}),this.checkResponse(t,"testRequestTokens.2")}async testTransferToken(){let e,t=P(this.secrets[1]),s=await this.client(this.secrets[0]);e=await s.transferToken({recipient:t,token:this.tokenSlugs[0],amount:10,batchId:"batch_1"}),this.checkResponse(e,"testTransferToken"),e=await s.transferToken({recipient:t,token:this.tokenSlugs[2],units:["unit_id_1","unit_id_2"],batchId:"batch_2"}),this.checkResponse(e,"testTransferUnitToken")}async testBurnToken(){let e,t=await this.client(this.secrets[0]);e=await t.burnTokens({token:this.tokenSlugs[0],amount:10}),this.checkResponse(e,"testBurnToken"),e=await t.burnTokens({token:this.tokenSlugs[2],units:["unit_id_3","unit_id_4"]}),this.checkResponse(e,"testBurnUnitToken")}async testReplenishToken(){let e,t=await this.client(this.secrets[0]);e=await t.replenishToken({token:this.tokenSlugs[0],amount:25}),this.checkResponse(e,"testReplenishToken"),e=await t.replenishToken({token:this.tokenSlugs[2],amount:0,units:this.replenishTokenUnits}),this.checkResponse(e,"testReplenishUnitToken")}async testClaimShadowWallet(){let e=await this.client(this.secrets[1]),t=await e.queryBalance({token:this.tokenSlugs[0]}),s=await e.claimShadowWallet({token:this.tokenSlugs[0],batchId:t.payload().batchId});this.checkResponse(s,"testClaimShadowWallet")}async testQueryMeta(){let e=await this.client(this.secrets[0]),t=await e.queryMeta({metaType:"metaType",metaId:"metaId"});this.checkResponse(t,"testQueryMeta")}async testQueryWallets(){let e=await this.client(this.secrets[0]),t=await e.queryWallets({});this.checkResponse(t,"testQueryWallets")}async testQueryShadowWallets(){let e=await this.client(this.secrets[1]),t=await e.queryShadowWallets({token:this.tokenSlugs[0]});this.checkResponse(t,"testQueryShadowWallets")}async testQueryBundle(){let e=await this.client(this.secrets[0]),t=await e.queryBundle({});this.checkResponse(t,"testQueryBundle")}async testQueryContinuId(){let e=P(this.secrets[0]),t=await this.client(this.secrets[0]),s=await t.queryContinuId({bundle:e});this.checkResponse(s,"testQueryContinuId")}async testQueryBalance(){let e=await this.client(this.secrets[0]),t=await e.queryBalance({token:this.tokenSlugs[0]});this.checkResponse(t,"testQueryBalance")}async client(e,t="unit_test"){return this.clients[e]||(this.clients[e]=new Vt({uri:this.graphqlUrl,logging:!0}),await this.clients[e].requestAuthToken({secret:e,encrypt:this.encrypt,cellSlug:t}),this.clients[e].getAuthToken()||console.log("Error with authorize - get an empty response.")),this.clients[e]}checkResponse(e,t){console.log(` ############### ${t} ###############`),console.log(e),e instanceof Ne?(e.success()||this.debug(e),console.assert(e.success(),e)):this.debug(e)}debug(e){e.data&&$e.get(e.data()||{},"reason")?console.log(e.data().reason):console.log(e)}},e.Wallet=G,e.base64ToHex=W,e.bufferToHexString=function(e){return T.toHex(e,{})},e.charsetBaseConvert=q,e.chunkSubstr=x,e.decryptMessage=J,e.encryptMessage=V,e.generateBundleHash=P,e.generateEncPrivateKey=D,e.generateEncPublicKey=L,e.generateSecret=Q,e.hashShare=z,e.hexStringToBuffer=function(e){return T.toUint8Array(e)},e.hexToBase64=M,e.isHex=C,e.randomString=v,Object.defineProperty(e,"__esModule",{value:!0})}));