@wishknish/knishio-client-js 0.4.28 → 0.4.32

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.
Files changed (46) hide show
  1. package/dist/client.umd.js +21 -21
  2. package/package.json +3 -8
  3. package/src/KnishIOClient.js +15 -6
  4. package/src/httpClient/ApolloClient.js +1 -1
  5. package/src/libraries/ApolloLink/AuthLink.js +1 -1
  6. package/src/libraries/ApolloLink/CipherLink.js +2 -2
  7. package/src/libraries/ApolloLink/Client.js +9 -8
  8. package/src/libraries/ApolloLink/EchoLink.js +1 -1
  9. package/src/libraries/ApolloLink/HttpLink.js +4 -3
  10. package/src/libraries/ApolloLink/handler.js +9 -4
  11. package/src/mutation/Mutation.js +1 -1
  12. package/src/mutation/MutationActiveSession.js +1 -1
  13. package/src/mutation/MutationLinkIdentifier.js +1 -1
  14. package/src/mutation/MutationProposeMolecule.js +1 -1
  15. package/src/mutation/MutationRequestAuthorizationGuest.js +1 -1
  16. package/src/query/Query.js +1 -1
  17. package/src/query/QueryActiveSession.js +1 -1
  18. package/src/query/QueryBalance.js +1 -1
  19. package/src/query/QueryBatch.js +1 -1
  20. package/src/query/QueryBatchHistory.js +1 -1
  21. package/src/query/QueryContinuId.js +1 -1
  22. package/src/query/QueryMetaInstance.js +1 -1
  23. package/src/query/QueryMetaType.js +1 -1
  24. package/src/query/QueryToken.js +4 -5
  25. package/src/query/QueryUserActivity.js +1 -1
  26. package/src/query/QueryWalletBundle.js +1 -1
  27. package/src/query/QueryWalletList.js +1 -1
  28. package/src/response/Response.js +5 -6
  29. package/src/response/ResponseActiveSession.js +2 -3
  30. package/src/response/ResponseAuthorizationGuest.js +2 -3
  31. package/src/response/ResponseBalance.js +2 -3
  32. package/src/response/ResponseContinuId.js +2 -3
  33. package/src/response/ResponseLinkIdentifier.js +2 -3
  34. package/src/response/ResponseMetaBatch.js +2 -3
  35. package/src/response/ResponseMetaType.js +2 -3
  36. package/src/response/ResponseProposeMolecule.js +2 -3
  37. package/src/response/ResponseQueryActiveSession.js +2 -3
  38. package/src/response/ResponseQueryUserActivity.js +2 -3
  39. package/src/response/ResponseRequestAuthorizationGuest.js +2 -3
  40. package/src/response/ResponseWalletBundle.js +2 -3
  41. package/src/response/ResponseWalletList.js +3 -4
  42. package/src/subscribe/ActiveSessionSubscribe.js +1 -1
  43. package/src/subscribe/ActiveWalletSubscribe.js +1 -1
  44. package/src/subscribe/CreateMoleculeSubscribe.js +1 -1
  45. package/src/subscribe/Subscribe.js +1 -1
  46. package/src/subscribe/WalletStatusSubscribe.js +1 -1
@@ -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-link"),require("graphql-tag"),require("apollo-client/util/Observable"),require("apollo-client"),require("isomorphic-fetch"),require("apollo-cache-inmemory"),require("apollo-link-http"),require("laravel-echo"),require("socket.io-client"),require("graphql"),require("apollo-link-error")):"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-link","graphql-tag","apollo-client/util/Observable","apollo-client","isomorphic-fetch","apollo-cache-inmemory","apollo-link-http","laravel-echo","socket.io-client","graphql","apollo-link-error"],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.apolloLink,e.gql,null,e.apolloClient,e.fetch,e.apolloCacheInmemory,e.apolloLinkHttp,e.Echo,e.io,e.graphql,e.apolloLinkError)}(this,(function(e,t,s,n,i,a,r,o,l,u,c,h,d,p,m,y,g,b,k,_,f,w){"use strict";function $(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var S=$(s),I=$(i),A=$(a),x=$(o),T=$(d),v=$(y),q=$(k),M=$(_);class W{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 i="",a=0,r=0;for(let t=0;t<e.length&&(i+=s(e[t],n.uppercase),t!==e.length-1);++t)n.grouping>0&&++a===n.grouping&&(a=0,n.rowlength>0&&++r===n.rowlength?(r=0,i+="\n"):i+=" ");return i}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 i=t[e],a=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"].indexOf(i);if(-1===a)throw Error("unexpected character");-1===n?n=16*a:(s[Math.floor(e/2)]=n+a,n=-1)}return s}}function C(e,t){const s=Math.ceil(e.length/t),n=[];for(let i=0,a=0;i<s;++i,a+=t)n[i]=e.substr(a,t);return n}function U(e=256,t="abcdef0123456789"){let s=new Uint8Array(e);return s=I.default(s),s=s.map((e=>t.charCodeAt(e%t.length))),String.fromCharCode.apply(null,s)}function B(e,t,s,n,i){if(n=n||"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~`!@#$%^&*()-_=+[{]}\\|;:'\",<.>/?¿¡",i=i||n,t>n.length||s>i.length)return console.warn("Strings::charsetBaseConvert() - Can't convert",e,"to base",s,"greater than symbol table length. src-table:",n.length,"dest-table:",i.length),!1;let a=S.default(0);for(let s=0;s<e.length;s++)a=a.multiply(t).add(n.indexOf(e.charAt(s)));if(a.lesser(0))return 0;let r=a.mod(s),o=i.charAt(r),l=a.divide(s);for(;!l.equals(0);)r=l.mod(s),l=l.divide(s),o=i.charAt(r)+o;return o}function H(e){return n.encode(W.toUint8Array(e))}function O(e){return W.toHex(n.decode(e),{})}function E(e){return/^[A-F0-9]+$/i.test(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 j{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}}class R{constructor({position:e=null,walletAddress:t=null,isotope:s=null,token:n=null,value:i=null,batchId:a=null,metaType:r=null,metaId:o=null,meta:l=null,otsFragment:u=null,index:c=null}){this.position=e,this.walletAddress=t,this.isotope=s,this.token=n,this.value=null!==i?String(i):null,this.batchId=a,this.metaType=r,this.metaId=o,this.meta=l?j.normalizeMeta(l):[],this.index=c,this.otsFragment=u,this.createdAt=String(+new Date)}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 j.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),i=e.length,a=R.sortAtoms(e);for(const e of a){const t=R.molecularHashSchema(e);n.update(String(i));for(const e of t.keys()){const s=t.get(e);if(!["batchId","pubkey","characters"].includes(e)||null!==s)if("meta"!==e)["position","walletAddress","isotope"].includes(e)?n.update(null===s?"":String(s)):null!==s&&n.update(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 B(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 K{static encode(e){return n.encode(e)}static decode(e){return r.Buffer.from(n.decode(e))}encode(e){return K.encode(e)}decode(e){return K.decode(e)}}class P{constructor(e={}){this.$options=Object.assign({characters:"GMP"},e),this.$encoder=x.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 Q{constructor(e={}){this.$options=Object.assign({characters:"BASE64"},e),this.$encoder=new P,["BASE64"].includes(this.$options.characters)?this.$encoder=new K:["BASE2","BASE8","BASE11","BASE36","BASE62","BASE67"].includes(this.$options.characters)?this.$encoder=x.default(this[this.$options.characters]):["BITCOIN","FLICKR","RIPPLE","IPFS"].includes(this.$options.characters)&&(this.$encoder=new P(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 N{constructor(e=null){this.base=new Q({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*l.box.secretKeyLength);return s.update(e),this.base.encode(r.Buffer.from(s.digest()))}generatePublicKey(e){const t=l.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 F(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 U(s)}function L(e){console.info("Crypto::generateBundleHash() - Computing wallet bundle from secret...");const s=t.shake256.create(256);return s.update(e),s.hex()}function D({molecularHash:e=null,index:t=null}){return null!==e&&null!==t?L(String(e)+String(t)):U(64)}function V(e=64){return U(e,"abcdef0123456789")}function z(e,t,s=null){return new N(s).encrypt(e,t)}function J(e,t,s,n=null){return new N(n).decrypt(e,t,s)}function Z(e,t=null){return new N(t).generatePrivateKey(e)}function G(e,t=null){return new N(t).generatePublicKey(e)}function X(e,t=null){return new N(t).shortHash(e)}class Y{constructor({secret:e=null,token:t="USER",position:s=null,batchId:n=null,characters:i=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?L(e):null,this.batchId=n,this.position=s,this.characters=i||"BASE64",e&&(this.position=this.position||V(),this.prepareKeys(e))}static create({secretOrBundle:e,token:t,batchId:s=null,characters:n=null}){let i=Y.isBundleHash(e)?null:e,a=i?L(i):e,r=i?V():null,o=new Y({secret:i,token:t,position:r,batchId:s,characters:n});return o.bundle=a,o}static isBundleHash(e){return"string"==typeof e&&(64===e.length&&E(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=[],i=[];this.tokenUnits.forEach((t=>{e.includes(t.id)?n.push(t):i.push(t)})),this.tokenUnits=n,null!==s&&(s.tokenUnits=n),t.tokenUnits=i}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:D({}))}prepareKeys(e){null===this.key&&null===this.address&&(this.key=Y.generatePrivateKey({secret:e,token:this.token,position:this.position}),this.address=Y.generatePublicKey(this.key),this.getMyEncPrivateKey(),this.getMyEncPublicKey())}getMyEncPrivateKey(){return null===this.privkey&&null!==this.key&&(this.privkey=Z(this.key,this.characters)),this.privkey}getMyEncPublicKey(){const e=this.getMyEncPrivateKey();return!this.pubkey&&e&&(this.pubkey=G(e,this.characters)),this.pubkey}encryptMyMessage(e){const t={};for(let s=1,n=arguments.length;s<n;s++)t[X(arguments[s],this.characters)]=z(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[X(t,this.characters)]||""),J(s,this.getMyEncPrivateKey(),t,this.characters)}decryptBinary(e){const t=this.decryptMyMessage(e);return new Q({characters:"BASE64"}).decode(t)}encryptBinary(e){const t=Array.from(arguments).slice(1),s=new Q({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 i=A.default(e,16).add(A.default(n,16)),a=t.shake256.create(8192);return a.update(i.toString(16)),s&&a.update(s),t.shake256.create(8192).update(a.hex()).hex()}static generatePublicKey(e){const s=C(e,128),n=t.shake256.create(8192);for(const e in s){let i=s[e];for(let e=1;e<=16;e++)i=t.shake256.create(512).update(i).hex();n.update(i)}return t.shake256.create(256).update(n.hex()).hex()}}class ee 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 te extends ee{constructor(e="There is an atom without an index",t=null,s=null){super(e,t,s),this.name="AtomIndexException"}}class se extends ee{constructor(e="The molecule does not contain atoms",t=null,s=null){super(e,t,s),this.name="AtomsMissingException"}}class ne extends ee{constructor(e="The molecular hash does not match",t=null,s=null){super(e,t,s),this.name="MolecularHashMismatchException"}}class ie extends ee{constructor(e="The molecular hash is missing",t=null,s=null){super(e,t,s),this.name="MolecularHashMissingException"}}class ae extends ee{constructor(e="OTS malformed",t=null,s=null){super(e,t,s),this.name="SignatureMalformedException"}}class re extends ee{constructor(e="One-time signature (OTS) does not match!",t=null,s=null){super(e,t,s),this.name="SignatureMismatchException"}}class oe extends ee{constructor(e="Insufficient balance to make transfer",t=null,s=null){super(e,t,s),this.name="TransferBalanceException"}}class le extends ee{constructor(e="Token transfer atoms are malformed",t=null,s=null){super(e,t,s),this.name="TransferMalformedException"}}class ue extends ee{constructor(e="Token slugs for wallets in transfer do not match!",t=null,s=null){super(e,t,s),this.name="TransferMismatchedException"}}class ce extends ee{constructor(e="Invalid remainder provided",t=null,s=null){super(e,t,s),this.name="TransferRemainderException"}}class he extends ee{constructor(e="Sender and recipient(s) cannot be the same",t=null,s=null){super(e,t,s),this.name="TransferToSelfException"}}class de extends ee{constructor(e="Token transfer atoms are unbalanced",t=null,s=null){super(e,t,s),this.name="TransferUnbalancedException"}}class pe extends ee{constructor(e="Empty meta data.",t=null,s=null){super(e,t,s),this.name="MetaMissingException"}}class me extends ee{constructor(e="Wrong type of token for this isotope",t=null,s=null){super(e,t,s),this.name="WrongTokenTypeException"}}class ye extends ee{constructor(e="Incorrect BatchId",t=null,s=null){super(e,t,s),this.name="BatchIdException"}}class ge extends ee{constructor(e="",t=null,s=null){super(e,t,s),this.name="KnishIOInvalidPolicyException"}}class be{static continuId(e){be.missing(e);if("USER"===e.atoms[0].token&&be.isotopeFilter("I",e.atoms).length<1)throw new se("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=be.isotopeFilter("V",e.atoms),n=s[s.length-1];if(t.batchId!==n.batchId)throw new ye;for(const e of s)if(null===e.batchId)throw new ye}return!0}throw new ye}static isotopeI(e){be.missing(e);for(let t of be.isotopeFilter("I",e.atoms)){if("USER"!==t.token)throw new me(`Check::isotopeI() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);if(0===t.index)throw new te(`Check::isotopeI() - Isotope "${t.isotope}" Atoms must have a non-zero index!`)}return!0}static isotopeU(e){be.missing(e);for(let t of be.isotopeFilter("U",e.atoms)){if("AUTH"!==t.token)throw new me(`Check::isotopeU() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);if(0!==t.index)throw new te(`Check::isotopeU() - Isotope "${t.isotope}" Atoms must have an index equal to 0!`)}return!0}static isotopeM(e){be.missing(e);const t=["readPolicy","writePolicy"];for(let s of be.isotopeFilter("M",e.atoms)){if(s.meta.length<1)throw new pe;if("USER"!==s.token)throw new me(`Check::isotopeM() - "${s.token}" is not a valid Token slug for "${s.isotope}" isotope Atoms!`);const e=j.aggregateMeta(s.meta);for(const s of t){let n=e[s];if(n){n=JSON.parse(n);for(const[s,i]of Object.entries(n))if(!t.includes(s)){if(!Object.keys(e).includes(s))throw new ge(`${s} is missing from the meta.`);for(const e of i)if(!Y.isBundleHash(e)&&!["all","self"].includes(e))throw new ge(`${e} does not correspond to the format of the policy.`)}}}}return!0}static isotopeC(e){be.missing(e);for(let t of be.isotopeFilter("C",e.atoms)){if("USER"!==t.token)throw new me(`Check::isotopeC() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);if(0!==t.index)throw new te(`Check::isotopeC() - Isotope "${t.isotope}" Atoms must have an index equal to 0!`)}return!0}static isotopeT(e){be.missing(e);for(let t of be.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 pe(`Check::isotopeT() - Required meta field "${t}" is missing!`);for(let t of["token"])if(!e.hasOwnProperty(t)||!Boolean(e[t]))throw new pe(`Check::isotopeT() - Required meta field "${t}" is missing!`);if("USER"!==t.token)throw new me(`Check::isotopeT() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);if(0!==t.index)throw new te(`Check::isotopeT() - Isotope "${t.isotope}" Atoms must have an index equal to 0!`)}return!0}static isotopeR(e){be.missing(e);for(let t of be.isotopeFilter("R",e.atoms)){const e=t.aggregatedMeta();for(let t of["callback","conditions","rule"])if(!e.hasOwnProperty(t))throw new pe(`Check::isotopeR() - Required meta field "${t}" is missing!`);try{const t=JSON.parse(e.conditions);for(let e of t){const t=Object.keys(e),s=t.filter((function(e){return-1!==["key","value","comparison"].indexOf(e)})),n=t.filter((function(e){return-1!==["managedBy"].indexOf(e)}));if(s.length<3&&n.length<1)throw new pe("Check::isotopeR() - Required condition field is missing!")}}catch(e){throw new pe("Check::isotopeR() - Condition is formatted incorrectly!")}}return!0}static isotopeV(e,t=null){be.missing(e);const s=be.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 ue;if(e.value<0)throw new le;return!0}let i=0,a=0;for(let t in e.atoms)if(e.atoms.hasOwnProperty(t)){const s=e.atoms[t];if("V"!==s.isotope)continue;if(a=1*s.value,Number.isNaN(a))throw new TypeError('Invalid isotope "V" values');if(s.token!==n.token)throw new ue;if(t>0){if(a<0)throw new le;if(s.walletAddress===n.walletAddress)throw new he}i+=a}if(i!==a)throw new de;if(t){if(a=1*n.value,Number.isNaN(a))throw new TypeError('Invalid isotope "V" values');const e=1*t.balance+1*a;if(e<0)throw new oe;if(e!==i)throw new ce}else if(0!==a)throw new ce;return!0}static molecularHash(e){if(be.missing(e),e.molecularHash!==R.hashAtoms({atoms:e.atoms}))throw new ne;return!0}static ots(e){be.missing(e);const s=e.atoms[0].walletAddress,n=be.normalizedHash(e.molecularHash);let i=e.atoms.map((e=>e.otsFragment)).reduce(((e,t)=>e+t));if(2048!==i.length&&(i=O(i),2048!==i.length))throw new ae;const a=C(i,128);let r="";for(const e in a){let s=a[e];for(let i=0,a=8+n[e];i<a;i++)s=t.shake256.create(512).update(s).hex();r+=s}const o=t.shake256.create(8192).update(r).hex();if(t.shake256.create(256).update(o).hex()!==s)throw new re;return!0}static index(e){be.missing(e);for(let t of e.atoms)if(null===t.index)throw new te;return!0}static isotopeFilter(e,t){return(t=t||[]).filter((t=>e===t.isotope))}static normalizedHash(e){return be.normalize(be.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,i=n.length;e<i;++e){const i=n[e];void 0!==t[i]&&(s[e]=t[i])}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 ie;if(1>e.atoms.length)throw new se}}class ke extends ee{constructor(e="Insufficient balance for requested transfer",t=null,s=null){super(e,t,s),this.name="BalanceInsufficientException"}}class _e extends ee{constructor(e="Amount cannot be negative!",t=null,s=null){super(e,t,s),this.name="NegativeAmountException"}}function fe(e,t){let s,n,i,a=[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<a.length;s++)r.call(e)===r.call(i=new a[s](e))&&(n=s?i:[]);for(s in t.push(e,n),e)t.hasOwnProperty.call(e,s)&&(n[s]=fe(e[s],t))}return n||e}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||Y.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).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 pe(`Molecule::replenishTokens() - Missing ${e} in meta!`);return this.molecularHash=null,this.atoms.push(new R({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,isotope:"C",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=R.sortAtoms(this.atoms),this}addUserRemainderAtom(e){return this.molecularHash=null,this.atoms.push(new R({position:e.position,walletAddress:e.address,isotope:"I",token:e.token,metaType:"walletBundle",metaId:e.bundle,meta:this.finalMetas({},e),index:this.generateIndex()})),this.atoms=R.sortAtoms(this.atoms),this}burnToken({amount:e,walletBundle:t=null}){if(e<0)throw new _e("Molecule::burnToken() - Amount to burn must be positive!");if(this.sourceWallet.balance-e<0)throw new ke;return this.molecularHash=null,this.atoms.push(new R({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,isotope:"V",token:this.sourceWallet.token,value:-e,batchId:this.sourceWallet.batchId,meta:this.finalMetas({}),index:this.generateIndex()})),this.atoms.push(new R({position:this.remainderWallet.position,walletAddress:this.remainderWallet.address,isotope:"V",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=R.sortAtoms(this.atoms),this}initValue({recipientWallet:e,amount:t}){if(this.sourceWallet.balance-t<0)throw new ke;return this.molecularHash=null,this.atoms.push(new R({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,isotope:"V",token:this.sourceWallet.token,value:-t,batchId:this.sourceWallet.batchId,meta:this.finalMetas({}),index:this.generateIndex()})),this.atoms.push(new R({position:e.position,walletAddress:e.address,isotope:"V",token:this.sourceWallet.token,value:t,batchId:e.batchId,metaType:"walletBundle",metaId:e.bundle,meta:this.finalMetas({},e),index:this.generateIndex()})),this.atoms.push(new R({position:this.remainderWallet.position,walletAddress:this.remainderWallet.address,isotope:"V",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=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(new R({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,isotope:"C",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().substr(6)]);return this.atoms.push(new R({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,isotope:"C",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,meta:s}){for(let e of["conditions","callback","rule"]){if(void 0===s[e])throw new pe(`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(new R({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,isotope:"R",token:this.sourceWallet.token,metaType:e,metaId:t,meta:this.finalMetas(s,this.sourceWallet),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(new R({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,isotope:"C",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:L(t.trim())};return this.atoms.push(new R({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,isotope:"C",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}){return this.molecularHash=null,this.atoms.push(new R({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,isotope:"M",token:this.sourceWallet.token,batchId:this.sourceWallet.batchId,metaType:t,metaId:s,meta:this.finalMetas(e,this.sourceWallet),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=R.sortAtoms(this.atoms),this}initTokenRequest({token:e,amount:t,metaType:s,metaId:n,meta:i={},batchId:a=null}){return this.molecularHash=null,i.token=e,this.atoms.push(new R({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,isotope:"T",token:this.sourceWallet.token,value:t,batchId:a,metaType:s,metaId:n,meta:this.finalMetas(i),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=R.sortAtoms(this.atoms),this}initAuthorization({meta:e}){return this.molecularHash=null,this.atoms.push(new R({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,isotope:"U",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 se;e||(this.bundle=L(this.secret)),this.molecularHash=R.hashAtoms({atoms:this.atoms});const n=this.atoms[0],i=C(Y.generatePrivateKey({secret:this.secret,token:n.token,position:n.position}),128),a=be.normalizedHash(this.molecularHash);let r="";for(const e in i){let s=i[e];for(let n=0,i=8-a[e];n<i;n++)s=t.shake256.create(512).update(s).hex();r+=s}s&&(r=H(r));const o=C(r,Math.ceil(r.length/this.atoms.length));let l=null;for(let e=0,t=o.length;e<t;e++)this.atoms[e].otsFragment=o[e],l=this.atoms[e].position;return l}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 se;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 se("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=fe(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 be.molecularHash(e)&&be.ots(e)&&be.index(e)&&be.batchId(e)&&be.continuId(e)&&be.isotopeM(e)&&be.isotopeT(e)&&be.isotopeC(e)&&be.isotopeU(e)&&be.isotopeI(e)&&be.isotopeR(e)&&be.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 Se=10**18;class Ie{static val(e){return Math.abs(e*Se)<1?0:e}static cmp(e,t,s=!1){const n=Ie.val(e)*Se,i=Ie.val(t)*Se;return Math.abs(n-i)<1?0:n>i?1:-1}static equal(e,t){return 0===Ie.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 Y({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 xe extends ee{constructor(e="Code exception",t=null,s=null){super(e,t,s),this.name="CodeException"}}class Te extends ee{constructor(e="GraphQL did not provide a valid response.",t=null,s=null){super(e,t,s),this.name="InvalidResponseException"}}class ve extends ee{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 Te;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 Te}this.init()}data(){if(!this.dataKey)return this.response();if(!$e.has(this.response(),this.dataKey))throw new Te;return $e.get(this.response(),this.dataKey)}response(){return this.$__response}payload(){return null}query(){return this.$__query}status(){return null}init(){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 xe("Query::createQuery() - Node URI was not initialized for this client instance!");if(null===this.$__query)throw new xe("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}),this.dataKey="data.ContinuId",this.init()}payload(){let e=null;const t=this.data();return t&&(e=new Y({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=T.default`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.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,i,a,r,o,l,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 _=k(s),f=k(i),w=k(a),$=k(o),S=k(d),I=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 i="",a=0,r=0;for(let t=0;t<e.length&&(i+=s(e[t],n.uppercase),t!==e.length-1);++t)n.grouping>0&&++a===n.grouping&&(a=0,n.rowlength>0&&++r===n.rowlength?(r=0,i+="\n"):i+=" ");return i}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 i=t[e],a=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"].indexOf(i);if(-1===a)throw Error("unexpected character");-1===n?n=16*a:(s[Math.floor(e/2)]=n+a,n=-1)}return s}}function T(e,t){const s=Math.ceil(e.length/t),n=[];for(let i=0,a=0;i<s;++i,a+=t)n[i]=e.substr(a,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,i){if(n=n||"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~`!@#$%^&*()-_=+[{]}\\|;:'\",<.>/?¿¡",i=i||n,t>n.length||s>i.length)return console.warn("Strings::charsetBaseConvert() - Can't convert",e,"to base",s,"greater than symbol table length. src-table:",n.length,"dest-table:",i.length),!1;let a=_.default(0);for(let s=0;s<e.length;s++)a=a.multiply(t).add(n.indexOf(e.charAt(s)));if(a.lesser(0))return 0;let r=a.mod(s),o=i.charAt(r),l=a.divide(s);for(;!l.equals(0);)r=l.mod(s),l=l.divide(s),o=i.charAt(r)+o;return o}function M(e){return n.encode(x.toUint8Array(e))}function W(e){return x.toHex(n.decode(e),{})}function C(e){return/^[A-F0-9]+$/i.test(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}}class U{constructor({position:e=null,walletAddress:t=null,isotope:s=null,token:n=null,value:i=null,batchId:a=null,metaType:r=null,metaId:o=null,meta:l=null,otsFragment:u=null,index:c=null}){this.position=e,this.walletAddress=t,this.isotope=s,this.token=n,this.value=null!==i?String(i):null,this.batchId=a,this.metaType=r,this.metaId=o,this.meta=l?B.normalizeMeta(l):[],this.index=c,this.otsFragment=u,this.createdAt=String(+new Date)}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 U({}),JSON.parse(e)),s=Object.keys(new U({}));for(const e in t)t.hasOwnProperty(e)&&!s.includes(e)&&delete t[e];return t}static molecularHashSchema(e){const t=U.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),i=e.length,a=U.sortAtoms(e);for(const e of a){const t=U.molecularHashSchema(e);n.update(String(i));for(const e of t.keys()){const s=t.get(e);if(!["batchId","pubkey","characters"].includes(e)||null!==s)if("meta"!==e)["position","walletAddress","isotope"].includes(e)?n.update(null===s?"":String(s)):null!==s&&n.update(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 H{static encode(e){return n.encode(e)}static decode(e){return r.Buffer.from(n.decode(e))}encode(e){return H.encode(e)}decode(e){return H.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 j{constructor(e={}){this.$options=Object.assign({characters:"BASE64"},e),this.$encoder=new O,["BASE64"].includes(this.$options.characters)?this.$encoder=new H:["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 E{constructor(e=null){this.base=new j({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*l.box.secretKeyLength);return s.update(e),this.base.encode(r.Buffer.from(s.digest()))}generatePublicKey(e){const t=l.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 R(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 K(e){console.info("Crypto::generateBundleHash() - Computing wallet bundle from secret...");const s=t.shake256.create(256);return s.update(e),s.hex()}function P({molecularHash:e=null,index:t=null}){return null!==e&&null!==t?K(String(e)+String(t)):v(64)}function Q(e=64){return v(e,"abcdef0123456789")}function N(e,t,s=null){return new E(s).encrypt(e,t)}function F(e,t,s,n=null){return new E(n).decrypt(e,t,s)}function D(e,t=null){return new E(t).generatePrivateKey(e)}function V(e,t=null){return new E(t).generatePublicKey(e)}function L(e,t=null){return new E(t).shortHash(e)}class z{constructor({secret:e=null,token:t="USER",position:s=null,batchId:n=null,characters:i=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?K(e):null,this.batchId=n,this.position=s,this.characters=i||"BASE64",e&&(this.position=this.position||Q(),this.prepareKeys(e))}static create({secretOrBundle:e,token:t,batchId:s=null,characters:n=null}){let i=z.isBundleHash(e)?null:e,a=i?K(i):e,r=i?Q():null,o=new z({secret:i,token:t,position:r,batchId:s,characters:n});return o.bundle=a,o}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=[],i=[];this.tokenUnits.forEach((t=>{e.includes(t.id)?n.push(t):i.push(t)})),this.tokenUnits=n,null!==s&&(s.tokenUnits=n),t.tokenUnits=i}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:P({}))}prepareKeys(e){null===this.key&&null===this.address&&(this.key=z.generatePrivateKey({secret:e,token:this.token,position:this.position}),this.address=z.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=V(e,this.characters)),this.pubkey}encryptMyMessage(e){const t={};for(let s=1,n=arguments.length;s<n;s++)t[L(arguments[s],this.characters)]=N(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[L(t,this.characters)]||""),F(s,this.getMyEncPrivateKey(),t,this.characters)}decryptBinary(e){const t=this.decryptMyMessage(e);return new j({characters:"BASE64"}).decode(t)}encryptBinary(e){const t=Array.from(arguments).slice(1),s=new j({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 i=w.default(e,16).add(w.default(n,16)),a=t.shake256.create(8192);return a.update(i.toString(16)),s&&a.update(s),t.shake256.create(8192).update(a.hex()).hex()}static generatePublicKey(e){const s=T(e,128),n=t.shake256.create(8192);for(const e in s){let i=s[e];for(let e=1;e<=16;e++)i=t.shake256.create(512).update(i).hex();n.update(i)}return t.shake256.create(256).update(n.hex()).hex()}}class J 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 Z extends J{constructor(e="There is an atom without an index",t=null,s=null){super(e,t,s),this.name="AtomIndexException"}}class G extends J{constructor(e="The molecule does not contain atoms",t=null,s=null){super(e,t,s),this.name="AtomsMissingException"}}class X extends J{constructor(e="The molecular hash does not match",t=null,s=null){super(e,t,s),this.name="MolecularHashMismatchException"}}class Y extends J{constructor(e="The molecular hash is missing",t=null,s=null){super(e,t,s),this.name="MolecularHashMissingException"}}class ee extends J{constructor(e="OTS malformed",t=null,s=null){super(e,t,s),this.name="SignatureMalformedException"}}class te extends J{constructor(e="One-time signature (OTS) does not match!",t=null,s=null){super(e,t,s),this.name="SignatureMismatchException"}}class se extends J{constructor(e="Insufficient balance to make transfer",t=null,s=null){super(e,t,s),this.name="TransferBalanceException"}}class ne extends J{constructor(e="Token transfer atoms are malformed",t=null,s=null){super(e,t,s),this.name="TransferMalformedException"}}class ie extends J{constructor(e="Token slugs for wallets in transfer do not match!",t=null,s=null){super(e,t,s),this.name="TransferMismatchedException"}}class ae extends J{constructor(e="Invalid remainder provided",t=null,s=null){super(e,t,s),this.name="TransferRemainderException"}}class re extends J{constructor(e="Sender and recipient(s) cannot be the same",t=null,s=null){super(e,t,s),this.name="TransferToSelfException"}}class oe extends J{constructor(e="Token transfer atoms are unbalanced",t=null,s=null){super(e,t,s),this.name="TransferUnbalancedException"}}class le extends J{constructor(e="Empty meta data.",t=null,s=null){super(e,t,s),this.name="MetaMissingException"}}class ue extends J{constructor(e="Wrong type of token for this isotope",t=null,s=null){super(e,t,s),this.name="WrongTokenTypeException"}}class ce extends J{constructor(e="Incorrect BatchId",t=null,s=null){super(e,t,s),this.name="BatchIdException"}}class he extends J{constructor(e="",t=null,s=null){super(e,t,s),this.name="KnishIOInvalidPolicyException"}}class de{static continuId(e){de.missing(e);if("USER"===e.atoms[0].token&&de.isotopeFilter("I",e.atoms).length<1)throw new G("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=de.isotopeFilter("V",e.atoms),n=s[s.length-1];if(t.batchId!==n.batchId)throw new ce;for(const e of s)if(null===e.batchId)throw new ce}return!0}throw new ce}static isotopeI(e){de.missing(e);for(let t of de.isotopeFilter("I",e.atoms)){if("USER"!==t.token)throw new ue(`Check::isotopeI() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);if(0===t.index)throw new Z(`Check::isotopeI() - Isotope "${t.isotope}" Atoms must have a non-zero index!`)}return!0}static isotopeU(e){de.missing(e);for(let t of de.isotopeFilter("U",e.atoms)){if("AUTH"!==t.token)throw new ue(`Check::isotopeU() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);if(0!==t.index)throw new Z(`Check::isotopeU() - Isotope "${t.isotope}" Atoms must have an index equal to 0!`)}return!0}static isotopeM(e){de.missing(e);const t=["readPolicy","writePolicy"];for(let s of de.isotopeFilter("M",e.atoms)){if(s.meta.length<1)throw new le;if("USER"!==s.token)throw new ue(`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,i]of Object.entries(n))if(!t.includes(s)){if(!Object.keys(e).includes(s))throw new he(`${s} is missing from the meta.`);for(const e of i)if(!z.isBundleHash(e)&&!["all","self"].includes(e))throw new he(`${e} does not correspond to the format of the policy.`)}}}}return!0}static isotopeC(e){de.missing(e);for(let t of de.isotopeFilter("C",e.atoms)){if("USER"!==t.token)throw new ue(`Check::isotopeC() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);if(0!==t.index)throw new Z(`Check::isotopeC() - Isotope "${t.isotope}" Atoms must have an index equal to 0!`)}return!0}static isotopeT(e){de.missing(e);for(let t of de.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 le(`Check::isotopeT() - Required meta field "${t}" is missing!`);for(let t of["token"])if(!e.hasOwnProperty(t)||!Boolean(e[t]))throw new le(`Check::isotopeT() - Required meta field "${t}" is missing!`);if("USER"!==t.token)throw new ue(`Check::isotopeT() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);if(0!==t.index)throw new Z(`Check::isotopeT() - Isotope "${t.isotope}" Atoms must have an index equal to 0!`)}return!0}static isotopeR(e){de.missing(e);for(let t of de.isotopeFilter("R",e.atoms)){const e=t.aggregatedMeta();for(let t of["callback","conditions","rule"])if(!e.hasOwnProperty(t))throw new le(`Check::isotopeR() - Required meta field "${t}" is missing!`);try{const t=JSON.parse(e.conditions);for(let e of t){const t=Object.keys(e),s=t.filter((function(e){return-1!==["key","value","comparison"].indexOf(e)})),n=t.filter((function(e){return-1!==["managedBy"].indexOf(e)}));if(s.length<3&&n.length<1)throw new le("Check::isotopeR() - Required condition field is missing!")}}catch(e){throw new le("Check::isotopeR() - Condition is formatted incorrectly!")}}return!0}static isotopeV(e,t=null){de.missing(e);const s=de.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 ie;if(e.value<0)throw new ne;return!0}let i=0,a=0;for(let t in e.atoms)if(e.atoms.hasOwnProperty(t)){const s=e.atoms[t];if("V"!==s.isotope)continue;if(a=1*s.value,Number.isNaN(a))throw new TypeError('Invalid isotope "V" values');if(s.token!==n.token)throw new ie;if(t>0){if(a<0)throw new ne;if(s.walletAddress===n.walletAddress)throw new re}i+=a}if(i!==a)throw new oe;if(t){if(a=1*n.value,Number.isNaN(a))throw new TypeError('Invalid isotope "V" values');const e=1*t.balance+1*a;if(e<0)throw new se;if(e!==i)throw new ae}else if(0!==a)throw new ae;return!0}static molecularHash(e){if(de.missing(e),e.molecularHash!==U.hashAtoms({atoms:e.atoms}))throw new X;return!0}static ots(e){de.missing(e);const s=e.atoms[0].walletAddress,n=de.normalizedHash(e.molecularHash);let i=e.atoms.map((e=>e.otsFragment)).reduce(((e,t)=>e+t));if(2048!==i.length&&(i=W(i),2048!==i.length))throw new ee;const a=T(i,128);let r="";for(const e in a){let s=a[e];for(let i=0,a=8+n[e];i<a;i++)s=t.shake256.create(512).update(s).hex();r+=s}const o=t.shake256.create(8192).update(r).hex();if(t.shake256.create(256).update(o).hex()!==s)throw new te;return!0}static index(e){de.missing(e);for(let t of e.atoms)if(null===t.index)throw new Z;return!0}static isotopeFilter(e,t){return(t=t||[]).filter((t=>e===t.isotope))}static normalizedHash(e){return de.normalize(de.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,i=n.length;e<i;++e){const i=n[e];void 0!==t[i]&&(s[e]=t[i])}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 Y;if(1>e.atoms.length)throw new G}}class pe extends J{constructor(e="Insufficient balance for requested transfer",t=null,s=null){super(e,t,s),this.name="BalanceInsufficientException"}}class me extends J{constructor(e="Amount cannot be negative!",t=null,s=null){super(e,t,s),this.name="NegativeAmountException"}}function ye(e,t){let s,n,i,a=[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<a.length;s++)r.call(e)===r.call(i=new a[s](e))&&(n=s?i:[]);for(s in t.push(e,n),e)t.hasOwnProperty.call(e,s)&&(n[s]=ye(e[s],t))}return n||e}class ge{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||z.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=U.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 le(`Molecule::replenishTokens() - Missing ${e} in meta!`);return this.molecularHash=null,this.atoms.push(new U({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,isotope:"C",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=U.sortAtoms(this.atoms),this}addUserRemainderAtom(e){return this.molecularHash=null,this.atoms.push(new U({position:e.position,walletAddress:e.address,isotope:"I",token:e.token,metaType:"walletBundle",metaId:e.bundle,meta:this.finalMetas({},e),index:this.generateIndex()})),this.atoms=U.sortAtoms(this.atoms),this}burnToken({amount:e,walletBundle:t=null}){if(e<0)throw new me("Molecule::burnToken() - Amount to burn must be positive!");if(this.sourceWallet.balance-e<0)throw new pe;return this.molecularHash=null,this.atoms.push(new U({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,isotope:"V",token:this.sourceWallet.token,value:-e,batchId:this.sourceWallet.batchId,meta:this.finalMetas({}),index:this.generateIndex()})),this.atoms.push(new U({position:this.remainderWallet.position,walletAddress:this.remainderWallet.address,isotope:"V",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=U.sortAtoms(this.atoms),this}initValue({recipientWallet:e,amount:t}){if(this.sourceWallet.balance-t<0)throw new pe;return this.molecularHash=null,this.atoms.push(new U({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,isotope:"V",token:this.sourceWallet.token,value:-t,batchId:this.sourceWallet.batchId,meta:this.finalMetas({}),index:this.generateIndex()})),this.atoms.push(new U({position:e.position,walletAddress:e.address,isotope:"V",token:this.sourceWallet.token,value:t,batchId:e.batchId,metaType:"walletBundle",metaId:e.bundle,meta:this.finalMetas({},e),index:this.generateIndex()})),this.atoms.push(new U({position:this.remainderWallet.position,walletAddress:this.remainderWallet.address,isotope:"V",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=U.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(new U({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,isotope:"C",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=U.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(new U({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,isotope:"C",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=U.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 le(`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(new U({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,isotope:"R",token:this.sourceWallet.token,metaType:e,metaId:t,meta:this.finalMetas(s,this.sourceWallet),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=U.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(new U({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,isotope:"C",token:this.sourceWallet.token,metaType:"wallet",metaId:t.address,meta:this.finalMetas(this.contextMetas(s)),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=U.sortAtoms(this.atoms),this}initIdentifierCreation({type:e,contact:t,code:s}){this.molecularHash=null;const n={code:s,hash:K(t.trim())};return this.atoms.push(new U({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,isotope:"C",token:this.sourceWallet.token,metaType:"identifier",metaId:e,meta:this.finalMetas(n,this.sourceWallet),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=U.sortAtoms(this.atoms),this}initMeta({meta:e,metaType:t,metaId:s}){return this.molecularHash=null,this.atoms.push(new U({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,isotope:"M",token:this.sourceWallet.token,batchId:this.sourceWallet.batchId,metaType:t,metaId:s,meta:this.finalMetas(e,this.sourceWallet),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=U.sortAtoms(this.atoms),this}initTokenRequest({token:e,amount:t,metaType:s,metaId:n,meta:i={},batchId:a=null}){return this.molecularHash=null,i.token=e,this.atoms.push(new U({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,isotope:"T",token:this.sourceWallet.token,value:t,batchId:a,metaType:s,metaId:n,meta:this.finalMetas(i),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=U.sortAtoms(this.atoms),this}initAuthorization({meta:e}){return this.molecularHash=null,this.atoms.push(new U({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,isotope:"U",token:this.sourceWallet.token,batchId:this.sourceWallet.batchId,meta:this.finalMetas(e),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=U.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 U))).length)throw new G;e||(this.bundle=K(this.secret)),this.molecularHash=U.hashAtoms({atoms:this.atoms});const n=this.atoms[0],i=T(z.generatePrivateKey({secret:this.secret,token:n.token,position:n.position}),128),a=de.normalizedHash(this.molecularHash);let r="";for(const e in i){let s=i[e];for(let n=0,i=8-a[e];n<i;n++)s=t.shake256.create(512).update(s).hex();r+=s}s&&(r=M(r));const o=T(r,Math.ceil(r.length/this.atoms.length));let l=null;for(let e=0,t=o.length;e<t;e++)this.atoms[e].otsFragment=o[e],l=this.atoms[e].position;return l}generateIndex(){return ge.generateNextAtomIndex(this.atoms)}static jsonToObject(e){const t=Object.assign(new ge({}),JSON.parse(e)),s=Object.keys(new ge({}));if(!Array.isArray(t.atoms))throw new G;for(const e in Object.keys(t.atoms)){t.atoms[e]=U.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 G("MolecularStructure::jsonToObject() - Required Atom properties are missing!")}for(const e in t)t.hasOwnProperty(e)&&!s.includes(e)&&delete t[e];return t.atoms=U.sortAtoms(t.atoms),t}get cellSlugDelimiter(){return"."}cellSlugBase(){return(this.cellSlug||"").split(this.cellSlugDelimiter)[0]}toJSON(){let e=ye(this);for(let t of["remainderWallet","secret","sourceWallet","cellSlugOrigin"])e.hasOwnProperty(t)&&delete e[t];return e}check(e=null){return ge.verify({molecule:this,sourceWallet:e})}static verify({molecule:e,sourceWallet:t=null}){return de.molecularHash(e)&&de.ots(e)&&de.index(e)&&de.batchId(e)&&de.continuId(e)&&de.isotopeM(e)&&de.isotopeT(e)&&de.isotopeC(e)&&de.isotopeU(e)&&de.isotopeI(e)&&de.isotopeR(e)&&de.isotopeV(e,t)}}class be{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 ke=10**18;class _e{static val(e){return Math.abs(e*ke)<1?0:e}static cmp(e,t,s=!1){const n=_e.val(e)*ke,i=_e.val(t)*ke;return Math.abs(n-i)<1?0:n>i?1:-1}static equal(e,t){return 0===_e.cmp(e,t)}}class fe{static create(e,t){let s=new fe(e);return s.setWallet(t),s}static restore(e,t){let s=new z({secret:t,token:"AUTH",position:e.wallet.position,characters:e.wallet.characters});return fe.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 we extends J{constructor(e="Code exception",t=null,s=null){super(e,t,s),this.name="CodeException"}}class $e extends J{constructor(e="GraphQL did not provide a valid response.",t=null,s=null){super(e,t,s),this.name="InvalidResponseException"}}class Se extends J{constructor(e="Authorization token missing or invalid.",t=null,s=null){super(e,t,s),this.name="UnauthenticatedException"}}class Ie{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 $e;if(be.has(this.$__response,this.errorKey)){const e=be.get(this.$__response,this.errorKey);if(String(e).includes("Unauthenticated"))throw new Se;throw new $e}this.init()}init(){}data(){if(!this.dataKey)return this.response();if(!be.has(this.response(),this.dataKey))throw new $e;return be.get(this.response(),this.dataKey)}response(){return this.$__response}payload(){return null}query(){return this.$__query}status(){return null}}class Ae{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 Ie({query:this,json:e})}createQuery({variables:e=null}){if(this.$__variables=this.compiledVariables(e),!this.uri())throw new we("Query::createQuery() - Node URI was not initialized for this client instance!");if(null===this.$__query)throw new we("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 xe extends Ie{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 z({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 Te extends Ae{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 We({query:this,json:e})}}class Ue extends qe{constructor({query:e,json:t}){super({query:e,json:t}),this.dataKey="data.WalletBundle",this.init()}payload(){const e=this.data();if(!e||0===e.length)return null;const t={};return e.forEach((e=>{e.metas=j.aggregateMeta(e.metas),t[e.bundleHash]=e})),t}}class Be extends Me{constructor(e){super(e),this.$__query=T.default`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 xe({query:this,json:e})}}class ve extends Ie{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 qe extends Ae{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 Ue({query:this,json:e})}static createVariables({bundleHash:e=null,key:t=null,value:s=null,latest:n=!0}){const i={latest:n};return e&&(i["string"==typeof e?"bundleHash":"bundleHashes"]=e),t&&(i["string"==typeof t?"key":"keys"]=t),s&&(i["string"==typeof s?"value":"values"]=s),i}}class He extends qe{constructor({query:e,json:t}){super({query:e,json:t}),this.dataKey="data.Wallet",this.init()}static toClientWallet({data:e,secret:t=null}){let s;return null===e.position||void 0===e.position?s=Y.create({secretOrBundle:e.bundleHash,token:e.tokenSlug,batchId:e.batchId,characters:e.characters}):(s=new Y({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(He.toClientWallet({data:n,secret:e}));return s}payload(){this.getWallets()}}class Oe extends Me{constructor(e){super(e),this.$__query=T.default`query( $address: String, $bundleHash: String, $token: String, $position: String, $unspent: Boolean ) {
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 i={latest:n};return e&&(i["string"==typeof e?"bundleHash":"bundleHashes"]=e),t&&(i["string"==typeof t?"key":"keys"]=t),s&&(i["string"==typeof s?"value":"values"]=s),i}}class Me extends Ie{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=z.create({secretOrBundle:e.bundleHash,token:e.tokenSlug,batchId:e.batchId,characters:e.characters}):(s=new z({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(Me.toClientWallet({data:n,secret:e}));return s}payload(){return this.getWallets()}}class We extends Ae{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 He({query:this,json:e})}}class Ee extends qe{constructor({query:e,json:t}){super({query:e,json:t}),this.dataKey="data.Balance",this.init()}payload(){const e=this.data();return e&&e.bundleHash&&e.tokenSlug?He.toClientWallet({data:e}):null}}class je extends Me{constructor(e){super(e),this.$__query=T.default`query( $address: String, $bundleHash: String, $token: String, $position: String ) {
52
+ }`}createResponse(e){return new Me({query:this,json:e})}}class Ce extends Ie{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.Balance"})}payload(){const e=this.data();return e&&e.bundleHash&&e.tokenSlug?Me.toClientWallet({data:e}):null}}class Be extends Ae{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 Ee({query:this,json:e})}}class Re extends qe{constructor({query:e,json:t}){super({query:e,json:t}),this.dataKey="data.MetaType",this.init()}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=T.default`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 Ce({query:this,json:e})}}class Ue extends Ie{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 He extends Ae{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 Re({query:this,json:e})}static createVariables({metaType:e=null,metaId:t=null,key:s=null,value:n=null,latest:i=null,latestMetas:a=!0,filter:r=null,queryArgs:o=null,count:l=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),i&&(c.latest=!!i),a&&(c.latestMetas=!!a),r&&(c.filter=r),o&&(void 0!==o.limit&&0!==o.limit||(o.limit="*"),c.queryArgs=o),l&&(c.count=l),u&&(c.countBy=u),c}}class Pe extends Me{constructor(e){super(e),this.$__query=T.default`query( $batchId: String ) {
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:i=null,latestMetas:a=!0,filter:r=null,queryArgs:o=null,count:l=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),i&&(c.latest=!!i),a&&(c.latestMetas=!!a),r&&(c.filter=r),o&&(void 0!==o.limit&&0!==o.limit||(o.limit="*"),c.queryArgs=o),l&&(c.count=l),u&&(c.countBy=u),c}}class Oe extends Ae{constructor(e){super(e),this.$__query=h.gql`query( $batchId: String ) {
94
94
  Batch( batchId: $batchId ) {
95
- ${Pe.getFields()},
95
+ ${Oe.getFields()},
96
96
  children {
97
- ${Pe.getFields()}
97
+ ${Oe.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 qe({query:this,json:e});return t.dataKey="data.Batch",t}}class Qe extends Me{constructor(e){super(e),this.$__query=T.default`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 Ie({query:this,json:e});return t.dataKey="data.Batch",t}}class je extends Ae{constructor(e){super(e),this.$__query=h.gql`query( $batchId: String ) {
101
101
  BatchHistory( batchId: $batchId ) {
102
- ${Pe.getFields()}
102
+ ${Oe.getFields()}
103
103
  }
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}),this.dataKey="data.ProposeMolecule",this.$__clientMolecule=e.molecule(),this.init()}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 Le extends Fe{constructor(e,t=null){super(e),this.$__molecule=t,this.$__remainderWallet=null,this.$__query=T.default`mutation( $molecule: MoleculeInput! ) {
104
+ }`}createResponse(e){let t=new Ie({query:this,json:e});return t.dataKey="data.BatchHistory",t}}class Ee extends Ie{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.ProposeMolecule"}),this.$__clientMolecule=e.molecule()}init(){const e=be.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 ge({});return t.molecularHash=be.get(e,"molecularHash"),t.status=be.get(e,"status"),t.createdAt=be.get(e,"createdAt"),t}success(){return"accepted"===this.status()}status(){return be.get(this.data(),"status","rejected")}reason(){return be.get(this.data(),"reason","Invalid response from server")}payload(){return this.$__payload}}class Re extends Ae{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 Ke extends Re{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 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 De extends Ne{payloadKey(e){if(!$e.has(this.payload(),e))throw new Te(`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 Ve extends Le{fillMolecule({meta:e}){this.$__molecule.initAuthorization({meta:e}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new De({query:this,json:e})}}class ze extends Ne{}class Je extends Le{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 ze({query:this,json:e})}}class Ze extends Ne{}class Ge extends Le{fillMolecule({token:e,amount:t,metaType:s,metaId:n,meta:i=null,batchId:a=null}){this.$__molecule.initTokenRequest({token:e,amount:t,metaType:s,metaId:n,meta:i||{},batchId:a}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Ze({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 Le{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 Le{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 Le{fillMolecule({token:e,batchId:t=null}){let s=Y.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 it extends Ne{}class at extends Le{fillMolecule({metaType:e,metaId:t,meta:s}){this.$__molecule.initMeta({meta:s,metaType:e,metaId:t}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new it({query:this,json:e})}}class rt extends Ne{}class ot extends Le{fillMolecule(e){this.$__molecule.initWalletCreation(e),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new rt({query:this,json:e})}}class lt extends qe{constructor({query:e,json:t}){super({query:e,json:t}),this.dataKey="data.AccessToken",this.init()}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 Te(`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=T.default`mutation( $cellSlug: String, $pubkey: String, $encrypt: Boolean ) {
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(!be.has(this.payload(),e))throw new $e(`ResponseRequestAuthorization::payloadKey() - '${e}' key was not found in the payload!`);return be.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 Qe extends Ke{fillMolecule({meta:e}){this.$__molecule.initAuthorization({meta:e}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Pe({query:this,json:e})}}class Ne extends Ee{}class Fe extends Ke{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 Ne({query:this,json:e})}}class De extends Ee{}class Ve extends Ke{fillMolecule({token:e,amount:t,metaType:s,metaId:n,meta:i=null,batchId:a=null}){this.$__molecule.initTokenRequest({token:e,amount:t,metaType:s,metaId:n,meta:i||{},batchId:a}),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 Ke{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 Je extends Ee{}class Ze extends Ke{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 Je({query:this,json:e})}}class Ge extends Ee{}class Xe extends Ke{fillMolecule({token:e,batchId:t=null}){let s=z.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 Ge({query:this,json:e})}}class Ye extends Ee{}class et extends Ke{fillMolecule({metaType:e,metaId:t,meta:s}){this.$__molecule.initMeta({meta:s,metaType:e,metaId:t}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Ye({query:this,json:e})}}class tt extends Ee{}class st extends Ke{fillMolecule(e){this.$__molecule.initWalletCreation(e),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new tt({query:this,json:e})}}class nt extends Ie{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(!be.has(this.payload(),e))throw new $e(`ResponseAuthorizationGuest::payloadKey() - '${e}' key is not found in the payload!`);return be.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 Re{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 lt({query:this,json:e})}}class ct extends ee{constructor(e="The shadow wallet does not exist",t=null,s=null){super(e,t,s),this.name="WalletShadowException"}}class ht extends ee{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 ee{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:i}){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&&console.error(`[Network error]: ${t}`)}function yt(e){return(t,s)=>{let n;return new h.Observable((i=>(s(t).subscribe(function(e,t,s,n){return i=>{const a=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}(i,a);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,a)):(s.next(i),s.complete())}}(e,t,i,(e=>n=e))),()=>function(e,t){const s=t();s&&e.leave(s)}(e,(()=>n)))))}}class gt extends b.HttpLink{constructor(e){super(e)}request(e,t){return t(e)}}class bt 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 q.default({broadcaster:"socket.io",client:M.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 kt 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),i="mutation"===n&&"ProposeMolecule"===s,a=["query"===n&&["__schema","ContinuId"].includes(s),"mutation"===n&&"AccessToken"===s,i&&"U"===$e.get(e,"variables.molecule.atoms.0.isotope")],r={query:f.print(e.query),variables:JSON.stringify(e.variables)},o=this.getWallet(),l=this.getPubKey();for(const s in a)if(a[s])return t(e);if(!l)throw new xe("CipherLink::request() - Node public key missing!");if(!o)throw new xe("CipherLink::request() - Authorized wallet missing!");return e.operationName=null,e.query=T.default`query ( $Hash: String! ) { CipherHash ( Hash: $Hash ) { hash } }`,e.variables={Hash:JSON.stringify(o.encryptMyMessage(r,l))},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=o.decryptMyMessage(e);if(null===s)throw new xe("CipherLink::request() - Unable to decrypt response!");return s}return e}))}}class ft extends m.ApolloClient{constructor({serverUri:e,socketUri:t,encrypt:s=!1}){const n=[],i=new gt({uri:e,fetch:v.default,transportBatching:!0}),a=w.onError(mt),r=new kt;let o=null,l=null;n.push(r),s&&(o=new _t,n.push(o)),t&&(l=new bt({socketUri:t}),n.push(l)),n.push(a.concat(i)),super({link:h.ApolloLink.from(n),cache:new g.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=r,this.__echoLink=l,this.__cipherLink=o,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 xe("Subscribe::createSubscribe() - Node URI was not initialized for this client instance!");if(null===this.$__subscribe)throw new xe("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 xe(`${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 St extends $t{constructor(e){super(e),this.$__subscribe=T.default`
123
+ }`}createResponse(e){return new nt({query:this,json:e})}}class at extends J{constructor(e="The shadow wallet does not exist",t=null,s=null){super(e,t,s),this.name="WalletShadowException"}}class rt extends J{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 J{constructor(e="Stackable tokens with unit IDs cannot have decimal places!",t=null,s=null){super(e,t,s),this.name="StackableUnitAmountException"}}function lt(e){return e.query.definitions.find((e=>"OperationDefinition"===e.kind)).selectionSet.selections.find((e=>"Field"===e.kind)).name.value}function ut({graphQLErrors:e,networkError:t,operation:s,forward:n,response:i}){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 ct(e){return(t,s)=>{let n;return new h.Observable((i=>(s(t).subscribe(function(e,t,s,n){return i=>{const a=lt(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}(i,a);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,a)):(s.next(i),s.complete())}}(e,t,i,(e=>n=e))),()=>function(e,t){const s=t();s&&e.leave(s)}(e,(()=>n)))))}}class ht extends h.HttpLink{constructor(e){super(e)}request(e,t){return t(e)}}class dt 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 I.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(),ct(this.echo)(e,t)}}class pt 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 mt 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=lt(e),n=function(e){return e.query.definitions.find((e=>"OperationDefinition"===e.kind)).operation}(e),i="mutation"===n&&"ProposeMolecule"===s,a=["query"===n&&["__schema","ContinuId"].includes(s),"mutation"===n&&"AccessToken"===s,i&&"U"===be.get(e,"variables.molecule.atoms.0.isotope")],r={query:b.print(e.query),variables:JSON.stringify(e.variables)},o=this.getWallet(),l=this.getPubKey();for(const s in a)if(a[s])return t(e);if(!l)throw new we("CipherLink::request() - Node public key missing!");if(!o)throw new we("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(o.encryptMyMessage(r,l))},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=o.decryptMyMessage(e);if(null===s)throw new we("CipherLink::request() - Unable to decrypt response!");return s}return e}))}}class yt extends h.ApolloClient{constructor({serverUri:e,socketUri:t,encrypt:s=!1}){const n=[],i=new ht({uri:e,fetch:S.default,transportBatching:!0}),a=new pt;let r=null,o=null;n.push(a),s&&(r=new mt,n.push(r)),t&&(o=new dt({socketUri:t}),n.push(o)),n.push(h.concat(m.onError(ut),i)),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=a,this.__echoLink=o,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 gt{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 yt({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=lt(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 bt{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 we("Subscribe::createSubscribe() - Node URI was not initialized for this client instance!");if(null===this.$__subscribe)throw new we("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 we(`${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 kt extends bt{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 It extends $t{constructor(e){super(e),this.$__subscribe=T.default`
168
+ `}}class _t extends bt{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 At extends $t{constructor(e){super(e),this.$__subscribe=T.default`
177
+ `}}class ft extends bt{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 xt extends $t{constructor(e){super(e),this.$__subscribe=T.default`
215
+ `}}class wt extends bt{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 Tt extends qe{constructor({query:e,json:t}){super({query:e,json:t}),this.dataKey="data.ActiveSession",this.init()}}class vt extends Fe{constructor(e){super(e),this.$__query=T.default`mutation(
225
+ }`}}class $t extends Ie{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.ActiveSession"})}}class St extends Re{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 Tt({query:this,json:e})}}class qt extends qe{constructor({query:e,json:t}){super({query:e,json:t}),this.dataKey="data.ActiveUser",this.init()}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=T.default`query ActiveUserQuery ($bundleHash:String, $metaType: String, $metaId: String) {
253
+ }`}createResponse(e){return new $t({query:this,json:e})}}class It extends Ie{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 At extends Ae{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 qt({query:this,json:e})}}class Wt extends qe{constructor({query:e,json:t}){super({query:e,json:t}),this.dataKey="data.UserActivity",this.init()}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=T.default`query UserActivity (
262
+ }`}createResponse(e){return new It({query:this,json:e})}}class xt extends Ie{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 Tt extends Ae{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 Wt({query:this,json:e})}}class Ut extends Me{constructor(e){super(e),this.$__query=T.default`query( $slug: String, $slugs: [ String! ], $limit: Int, $order: String ) {
335
+ }`}createResponse(e){return new xt({query:this,json:e})}}class vt extends Ae{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,4 +342,4 @@
342
342
  amount,
343
343
  icon,
344
344
  }
345
- }`}createResponse(e){let t=new qe({query:this,json:e});return t.dataKey="data.Token",t}}class Bt{constructor({uri:e,client:t=null,socketUri:s=null,serverSdkVersion:n=3,logging:i=!1}){this.initialize({uri:e,socketUri:s,client:t,serverSdkVersion:n,logging:i})}initialize({uri:e,socketUri:t=null,client:s=null,serverSdkVersion:n=3,logging:i=!1}){this.$__logging=i,this.$__uris="object"==typeof e?e:[e],this.$__authTokenObjects={},this.$__authInProcess=!1;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 ${n}...`),this.reset(),this.$__client=s||new wt({socketUri:t,serverUri:this.getRandomUri()}),this.$__serverSdkVersion=n}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 xe("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=L(e)}getSecret(){if(!this.$__secret)throw new ve("KnishIOClient::getSecret() - Unable to find a stored getSecret!");return this.$__secret}getBundle(){if(!this.$__bundle)throw new ve("KnishIOClient::getBundle() - Unable to find a stored getBundle!");return this.$__bundle}async getSourceWallet(){let e=(await this.queryContinuId({bundle:this.getBundle()})).payload();return e?e.key=Y.generatePrivateKey({secret:this.getSecret(),token:e.token,position:e.position}):e=new Y({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 i=t;return!t&&this.lastMoleculeQuery&&"AUTH"!==this.getRemainderWallet().token&&this.lastMoleculeQuery&&this.lastMoleculeQuery.response()&&this.lastMoleculeQuery.response().success()&&(i=this.getRemainderWallet()),null===i&&(i=await this.getSourceWallet()),this.remainderWallet=s||Y.create({secretOrBundle:n,token:"USER",batchId:i.batchId,characters:i.characters}),new we({secret:n,sourceWallet:i,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 Le))throw new xe(`${this.constructor.name}::createMoleculeMutation() - This method only accepts MutationProposeMolecule!`);return this.lastMoleculeQuery=n,n}async queryBalance({token:e,bundle:t=null}){return this.createQuery(je).execute({variables:{bundleHash:t||this.getBundle(),token:e}})}subscribeCreateMolecule({bundle:e,closure:t}){return this.createSubscribe(St).execute({variables:{bundle:e||this.getBundle()},closure:t})}subscribeWalletStatus({bundle:e,token:t,closure:s}){if(!t)throw new xe(`${this.constructor.name}::subscribeWalletStatus() - Token parameter is required!`);return this.createSubscribe(It).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(xt).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:i=null,latestMetas:a=null,fields:r=null,filter:o=null,queryArgs:l=null,count:u=null,countBy:c=null}){this.$__logging&&console.info(`KnishIOClient::queryMeta() - Querying metaType: ${e}, metaId: ${t}...`);const h=this.createQuery(Ke),d=Ke.createVariables({metaType:e,metaId:t,key:s,value:n,latest:i,latestMetas:a,filter:o,queryArgs:l,count:u,countBy:c});return h.execute({variables:d,fields:r}).then((e=>e.payload()))}queryMetaInstance({metaType:e,metaId:t=null,key:s=null,value:n=null,latest:i=null,filter:a=null,fields:r=null}){this.$__logging&&console.info(`KnishIOClient::queryMetaInstance() - Querying metaType: ${e}, metaId: ${t}...`);const o={metaType:e,metaIds:[t],keys:[s],values:[n],latest:i,filter:a};return this.createQuery(Ke).execute({variables:o,fields:r}).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(Pe);return await t.execute({variables:{batchId:e}})}async queryBatchHistory({batchId:e}){this.$__logging&&console.info(`KnishIOClient::queryBatchHistory() - Querying cascading meta instances for batchId: ${e}...`);const t=this.createQuery(Qe);return await t.execute({variables:{batchId:e}})}async createWallet({token:e}){const t=new Y({secret:this.getSecret(),token:e}),s=await this.createMoleculeMutation({mutationClass:ot});return s.fillMolecule(t),await s.execute({})}async queryActiveSession({bundleHash:e,metaType:t,metaId:s}){const n=this.createQuery(Mt);return await n.execute({variables:{bundleHash:e,metaType:t,metaId:s}})}async queryUserActivity({bundleHash:e,metaType:t,metaId:s,ipAddress:n,browser:i,osCpu:a,resolution:r,timeZone:o,countBy:l,interval:u}){const c=this.createQuery(Ct);return await c.execute({variables:{bundleHash:e,metaType:t,metaId:s,ipAddress:n,browser:i,osCpu:a,resolution:r,timeZone:o,countBy:l,interval:u}})}async activeSession({bundle:e,metaType:t,metaId:s,ipAddress:n,browser:i,osCpu:a,resolution:r,timeZone:o,json:l={}}){const u=this.createQuery(vt);return await u.execute({variables:{bundleHash:e,metaType:t,metaId:s,ipAddress:n,browser:i,osCpu:a,resolution:r,timeZone:o,json:JSON.stringify(l)}})}async createToken({token:e,amount:t=null,meta:s=null,batchId:n=null,units:i=[]}){if("stackable"===$e.get(s||{},"fungibility")&&(n||(n=D({})),s.batchId=n,i.length>0)){if($e.get(s||{},"decimals")>0)throw new ht;if(t>0)throw new dt;t=i.length,s.splittable=1,s.tokenUnits=JSON.stringify(i)}const a=new Y({secret:this.getSecret(),token:e,batchId:n}),r=await this.createMoleculeMutation({mutationClass:Je});return r.fillMolecule({recipientWallet:a,amount:t,meta:s||{}}),await r.execute({})}async createMeta({metaType:e,metaId:t,meta:s=null,policy:n=null}){const i=await this.createMoleculeMutation({mutationClass:at,molecule:await this.createMolecule({secret:this.getSecret(),sourceWallet:await this.getSourceWallet()})}),a=s||{};if(n)for(const[e,t]of Object.entries(n))null!==t&&["read","write"].includes(e)&&(a[`${e}Policy`]=JSON.stringify(t));return i.fillMolecule({metaType:e,metaId:t,meta:a}),await i.execute({})}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 n.execute({})}queryWallets({bundle:e=null,token:t=null,unspent:s=!0}){this.$__logging&&console.info(`KnishIOClient::queryWallets() - Querying wallets${e?` for ${e}`:""}...`);return this.createQuery(Oe).execute({variables:{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}...`);return this.createQuery(Oe).execute({variables:{bundleHash:t,token:e}}).then((e=>e.payload()))}queryBundle({bundle:e=null,key:t=null,value:s=null,latest:n=!0,fields:i=null,raw:a=!1}){this.$__logging&&console.info(`KnishIOClient::queryBundle() - Querying wallet bundle metadata${e?` for ${e}`:""}...`);const r=this.createQuery(Be),o=Be.createVariables({bundleHash:e||this.getBundle(),key:t,value:s,latest:n});return r.execute({variables:o,fields:i}).then((e=>a?e:e.payload()))}async queryContinuId({bundle:e}){return this.createQuery(Ce).execute({variables:{bundle:e}})}async requestTokens({token:e,to:t,amount:s=null,units:n=[],meta:i=null,batchId:a=null}){let r,o;i=i||{};const l=await this.createQuery(Ut).execute({slug:e}),u="stackable"===$e.get(l.data(),"0.fungibility");if(!u&&null!==a)throw new ye("Expected Batch ID = null for non-stackable tokens.");if(u&&null===a&&(a=D({})),n.length>0){if(s>0)throw new dt;s=n.length,i.tokenUnits=JSON.stringify(n)}t?("[object String]"===Object.prototype.toString.call(t)&&(Y.isBundleHash(t)?(r="walletBundle",o=t):t=Y.create({secretOrBundle:t,token:e})),t instanceof Y&&(r="wallet",i.position=t.position,i.bundle=t.bundle,o=t.address)):(r="walletBundle",o=this.getBundle());const c=await this.createMoleculeMutation({mutationClass:Ge});return c.fillMolecule({token:e,amount:s,metaType:r,metaId:o,meta:i,batchId:a}),await c.execute({})}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 n.execute({})}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:i=null,sourceWallet:a=null}){if(null===a&&(a=(await this.queryBalance({token:t})).payload()),n.length>0){if(s>0)throw new dt;s=n.length}if(null===a||Ie.cmp(a.balance,s)<0)throw new oe;let r=e instanceof Y?e:(await this.queryBalance({token:t,bundle:e})).payload();null===r&&(r=Y.create({secretOrBundle:e,token:t})),null!==i?r.batchId=i:r.initBatchId({sourceWallet:a}),this.remainderWallet=Y.create({secretOrBundle:this.getSecret(),token:t,characters:a.characters}),this.remainderWallet.initBatchId({sourceWallet:a,isRemainder:!0}),a.splitUnits(n,this.remainderWallet,r);const o=await this.createMolecule({sourceWallet:a,remainderWallet:this.remainderWallet}),l=await this.createMoleculeMutation({mutationClass:Ye,molecule:o});return l.fillMolecule({recipientWallet:r,amount:s}),await l.execute({})}async burnTokens({token:e,amount:t=null,units:s=[],sourceWallet:n=null}){null===n&&(n=(await this.queryBalance({token:e})).payload());let i=Y.create({secretOrBundle:this.getSecret(),token:e,characters:n.characters});if(i.initBatchId({sourceWallet:n,isRemainder:!0}),s.length>0){if(t>0)throw new dt;t=s.length,n.splitUnits(s,i)}let a=await this.createMolecule({secret:null,sourceWallet:n,remainderWallet:i});return a.burnToken({amount:t}),a.sign({}),a.check(),new Le(this.client(),a).execute({})}async requestGuestAuthToken({cellSlug:e,encrypt:t}){this.setCellSlug(e);const s=new Y({secret:F(),token:"AUTH"}),n=await this.createQuery(ut),i=await n.execute({variables:{cellSlug:e,pubkey:s.pubkey,encrypt:t}}),a=Ae.create(i.payload(),s);return this.setAuthToken(a),i}async requestProfileAuthToken({secret:e,encrypt:t}){this.setSecret(e);const s=new Y({secret:e,token:"AUTH"}),n=await this.createMolecule({secret:e,sourceWallet:s}),i=await this.createMoleculeMutation({mutationClass:Ve,molecule:n});i.fillMolecule({meta:{encrypt:t?"true":"false"}});const a=await i.execute({}),r=Ae.create(a.payload(),s);return this.setAuthToken(r),a}async requestAuthToken({secret:e,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 i;return null===e&&t&&(e=F(t)),this.$__authInProcess=!0,i=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,i}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=Bt,e.Meta=j,e.Molecule=we,e.Test=class{constructor(e,t=!1){this.encrypt=t,this.secrets=[F(),F()],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]),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.testClaimShadowWallet(),await this.testQueryMeta(),await this.testQueryWallets(),await this.testQueryShadowWallets(),await this.testQueryBundle(),await this.testQueryBalance()}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=L(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;L(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=L(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 Bt({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("accepted"===e.status(),e)):this.debug(e)}debug(e){e.data&&$e.get(e.data()||{},"reason")?console.log(e.data().reason):console.log(e)}},e.Wallet=Y,e.base64ToHex=O,e.bufferToHexString=function(e){return W.toHex(e,{})},e.charsetBaseConvert=B,e.chunkSubstr=C,e.decryptMessage=J,e.encryptMessage=z,e.generateBundleHash=L,e.generateEncPrivateKey=Z,e.generateEncPublicKey=G,e.generateSecret=F,e.hashShare=X,e.hexStringToBuffer=function(e){return W.toUint8Array(e)},e.hexToBase64=H,e.isHex=E,e.randomString=U,Object.defineProperty(e,"__esModule",{value:!0})}));
345
+ }`}createResponse(e){return new Ie({query:this,json:e,dataKey:"data.Token"})}}class qt{constructor({uri:e,client:t=null,socketUri:s=null,serverSdkVersion:n=3,logging:i=!1}){this.initialize({uri:e,socketUri:s,client:t,serverSdkVersion:n,logging:i})}initialize({uri:e,socketUri:t=null,client:s=null,serverSdkVersion:n=3,logging:i=!1}){this.$__logging=i,this.$__uris="object"==typeof e?e:[e],this.$__authTokenObjects={},this.$__authInProcess=!1;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 ${n}...`),this.reset(),this.$__client=s||new gt({socketUri:t,serverUri:this.getRandomUri()}),this.$__serverSdkVersion=n}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 we("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=K(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=z.generatePrivateKey({secret:this.getSecret(),token:e.token,position:e.position}):e=new z({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 i=t;return!t&&this.lastMoleculeQuery&&"AUTH"!==this.getRemainderWallet().token&&this.lastMoleculeQuery&&this.lastMoleculeQuery.response()&&this.lastMoleculeQuery.response().success()&&(i=this.getRemainderWallet()),null===i&&(i=await this.getSourceWallet()),this.remainderWallet=s||z.create({secretOrBundle:n,token:"USER",batchId:i.batchId,characters:i.characters}),new ge({secret:n,sourceWallet:i,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 Ke))throw new we(`${this.constructor.name}::createMoleculeMutation() - This method only accepts MutationProposeMolecule!`);return this.lastMoleculeQuery=n,n}async queryBalance({token:e,bundle:t=null}){return this.createQuery(Be).execute({variables:{bundleHash:t||this.getBundle(),token:e}})}subscribeCreateMolecule({bundle:e,closure:t}){return this.createSubscribe(kt).execute({variables:{bundle:e||this.getBundle()},closure:t})}subscribeWalletStatus({bundle:e,token:t,closure:s}){if(!t)throw new we(`${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(ft).execute({variables:{bundle:e||this.getBundle()},closure:t})}subscribeActiveSession({metaType:e,metaId:t,closure:s}){return this.createSubscribe(wt).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:i=null,latestMetas:a=null,fields:r=null,filter:o=null,queryArgs:l=null,count:u=null,countBy:c=null}){this.$__logging&&console.info(`KnishIOClient::queryMeta() - Querying metaType: ${e}, metaId: ${t}...`);const h=this.createQuery(He),d=He.createVariables({metaType:e,metaId:t,key:s,value:n,latest:i,latestMetas:a,filter:o,queryArgs:l,count:u,countBy:c});return h.execute({variables:d,fields:r}).then((e=>e.payload()))}queryMetaInstance({metaType:e,metaId:t=null,key:s=null,value:n=null,latest:i=null,filter:a=null,fields:r=null}){this.$__logging&&console.info(`KnishIOClient::queryMetaInstance() - Querying metaType: ${e}, metaId: ${t}...`);const o={metaType:e,metaIds:[t],keys:[s],values:[n],latest:i,filter:a};return this.createQuery(He).execute({variables:o,fields:r}).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 t.execute({variables:{batchId:e}})}async queryBatchHistory({batchId:e}){this.$__logging&&console.info(`KnishIOClient::queryBatchHistory() - Querying cascading meta instances for batchId: ${e}...`);const t=this.createQuery(je);return await t.execute({variables:{batchId:e}})}async createWallet({token:e}){const t=new z({secret:this.getSecret(),token:e}),s=await this.createMoleculeMutation({mutationClass:st});return s.fillMolecule(t),await s.execute({})}async queryActiveSession({bundleHash:e,metaType:t,metaId:s}){const n=this.createQuery(At);return await n.execute({variables:{bundleHash:e,metaType:t,metaId:s}})}async queryUserActivity({bundleHash:e,metaType:t,metaId:s,ipAddress:n,browser:i,osCpu:a,resolution:r,timeZone:o,countBy:l,interval:u}){const c=this.createQuery(Tt);return await c.execute({variables:{bundleHash:e,metaType:t,metaId:s,ipAddress:n,browser:i,osCpu:a,resolution:r,timeZone:o,countBy:l,interval:u}})}async activeSession({bundle:e,metaType:t,metaId:s,ipAddress:n,browser:i,osCpu:a,resolution:r,timeZone:o,json:l={}}){const u=this.createQuery(St);return await u.execute({variables:{bundleHash:e,metaType:t,metaId:s,ipAddress:n,browser:i,osCpu:a,resolution:r,timeZone:o,json:JSON.stringify(l)}})}async createToken({token:e,amount:t=null,meta:s=null,batchId:n=null,units:i=[]}){if("stackable"===be.get(s||{},"fungibility")&&(n||(n=P({})),s.batchId=n,i.length>0)){if(be.get(s||{},"decimals")>0)throw new rt;if(t>0)throw new ot;t=i.length,s.splittable=1,s.tokenUnits=JSON.stringify(i)}const a=new z({secret:this.getSecret(),token:e,batchId:n}),r=await this.createMoleculeMutation({mutationClass:Fe});return r.fillMolecule({recipientWallet:a,amount:t,meta:s||{}}),await r.execute({})}async createMeta({metaType:e,metaId:t,meta:s=null,policy:n=null}){const i=await this.createMoleculeMutation({mutationClass:et,molecule:await this.createMolecule({secret:this.getSecret(),sourceWallet:await this.getSourceWallet()})}),a=s||{};if(n)for(const[e,t]of Object.entries(n))null!==t&&["read","write"].includes(e)&&(a[`${e}Policy`]=JSON.stringify(t));return i.fillMolecule({metaType:e,metaId:t,meta:a}),await i.execute({})}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 n.execute({})}queryWallets({bundle:e=null,token:t=null,unspent:s=!0}){this.$__logging&&console.info(`KnishIOClient::queryWallets() - Querying wallets${e?` for ${e}`:""}...`);return this.createQuery(We).execute({variables:{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}...`);return this.createQuery(We).execute({variables:{bundleHash:t,token:e}}).then((e=>e.payload()))}queryBundle({bundle:e=null,key:t=null,value:s=null,latest:n=!0,fields:i=null,raw:a=!1}){this.$__logging&&console.info(`KnishIOClient::queryBundle() - Querying wallet bundle metadata${e?` for ${e}`:""}...`);const r=this.createQuery(qe),o=qe.createVariables({bundleHash:e||this.getBundle(),key:t,value:s,latest:n});return r.execute({variables:o,fields:i}).then((e=>a?e:e.payload()))}async queryContinuId({bundle:e}){return this.createQuery(Te).execute({variables:{bundle:e}})}async requestTokens({token:e,to:t,amount:s=null,units:n=[],meta:i=null,batchId:a=null}){let r,o;i=i||{};const l=await this.createQuery(vt).execute({slug:e}),u="stackable"===be.get(l.data(),"0.fungibility");if(!u&&null!==a)throw new ce("Expected Batch ID = null for non-stackable tokens.");if(u&&null===a&&(a=P({})),n.length>0){if(s>0)throw new ot;s=n.length,i.tokenUnits=JSON.stringify(n)}t?("[object String]"===Object.prototype.toString.call(t)&&(z.isBundleHash(t)?(r="walletBundle",o=t):t=z.create({secretOrBundle:t,token:e})),t instanceof z&&(r="wallet",i.position=t.position,i.bundle=t.bundle,o=t.address)):(r="walletBundle",o=this.getBundle());const c=await this.createMoleculeMutation({mutationClass:Ve});return c.fillMolecule({token:e,amount:s,metaType:r,metaId:o,meta:i,batchId:a}),await c.execute({})}async claimShadowWallet({token:e,batchId:t=null,molecule:s=null}){const n=await this.createMoleculeMutation({mutationClass:Xe,molecule:s});return n.fillMolecule({token:e,batchId:t}),await n.execute({})}async claimShadowWallets({token:e}){const t=await this.queryShadowWallets({token:e});if(!t||!Array.isArray(t))throw new at;t.forEach((e=>{if(!e.isShadow())throw new at}));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:i=null,sourceWallet:a=null}){if(null===a&&(a=(await this.queryBalance({token:t})).payload()),n.length>0){if(s>0)throw new ot;s=n.length}if(null===a||_e.cmp(a.balance,s)<0)throw new se;let r=e instanceof z?e:(await this.queryBalance({token:t,bundle:e})).payload();null===r&&(r=z.create({secretOrBundle:e,token:t})),null!==i?r.batchId=i:r.initBatchId({sourceWallet:a}),this.remainderWallet=z.create({secretOrBundle:this.getSecret(),token:t,characters:a.characters}),this.remainderWallet.initBatchId({sourceWallet:a,isRemainder:!0}),a.splitUnits(n,this.remainderWallet,r);const o=await this.createMolecule({sourceWallet:a,remainderWallet:this.remainderWallet}),l=await this.createMoleculeMutation({mutationClass:ze,molecule:o});return l.fillMolecule({recipientWallet:r,amount:s}),await l.execute({})}async burnTokens({token:e,amount:t=null,units:s=[],sourceWallet:n=null}){null===n&&(n=(await this.queryBalance({token:e})).payload());let i=z.create({secretOrBundle:this.getSecret(),token:e,characters:n.characters});if(i.initBatchId({sourceWallet:n,isRemainder:!0}),s.length>0){if(t>0)throw new ot;t=s.length,n.splitUnits(s,i)}let a=await this.createMolecule({secret:null,sourceWallet:n,remainderWallet:i});return a.burnToken({amount:t}),a.sign({}),a.check(),new Ke(this.client(),a).execute({})}async requestGuestAuthToken({cellSlug:e,encrypt:t}){this.setCellSlug(e);const s=new z({secret:R(),token:"AUTH"}),n=await this.createQuery(it),i=await n.execute({variables:{cellSlug:e,pubkey:s.pubkey,encrypt:t}}),a=fe.create(i.payload(),s);return this.setAuthToken(a),i}async requestProfileAuthToken({secret:e,encrypt:t}){this.setSecret(e);const s=new z({secret:e,token:"AUTH"}),n=await this.createMolecule({secret:e,sourceWallet:s}),i=await this.createMoleculeMutation({mutationClass:Qe,molecule:n});i.fillMolecule({meta:{encrypt:t?"true":"false"}});const a=await i.execute({}),r=fe.create(a.payload(),s);return this.setAuthToken(r),a}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 i;return null===e&&t&&(e=R(t)),this.$__authInProcess=!0,i=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,i}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=U,e.KnishIOClient=qt,e.Meta=B,e.Molecule=ge,e.Test=class{constructor(e,t=!1){this.encrypt=t,this.secrets=[R(),R()],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]),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.testClaimShadowWallet(),await this.testQueryMeta(),await this.testQueryWallets(),await this.testQueryShadowWallets(),await this.testQueryBundle(),await this.testQueryBalance()}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=K(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;K(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=K(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 qt({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("accepted"===e.status(),e)):this.debug(e)}debug(e){e.data&&be.get(e.data()||{},"reason")?console.log(e.data().reason):console.log(e)}},e.Wallet=z,e.base64ToHex=W,e.bufferToHexString=function(e){return x.toHex(e,{})},e.charsetBaseConvert=q,e.chunkSubstr=T,e.decryptMessage=F,e.encryptMessage=N,e.generateBundleHash=K,e.generateEncPrivateKey=D,e.generateEncPublicKey=V,e.generateSecret=R,e.hashShare=L,e.hexStringToBuffer=function(e){return x.toUint8Array(e)},e.hexToBase64=M,e.isHex=C,e.randomString=v,Object.defineProperty(e,"__esModule",{value:!0})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wishknish/knishio-client-js",
3
- "version": "0.4.28",
3
+ "version": "0.4.32",
4
4
  "productName": "Knish.IO Javascript SDK Client",
5
5
  "description": "JavaScript implementation of the Knish.IO SDK to consume Knish.IO GraphQL APIs.",
6
6
  "license": "GPL-3.0-or-later",
@@ -39,19 +39,14 @@
39
39
  "graphql"
40
40
  ],
41
41
  "dependencies": {
42
+ "@apollo/client": "^3.4.16",
42
43
  "@stablelib/base64": "^1.0.0",
43
44
  "@stablelib/utf8": "^1.0.0",
44
- "apollo-cache-inmemory": "^1.6.6",
45
- "apollo-client": "^2.6.10",
46
- "apollo-link": "^1.2.14",
47
- "apollo-link-error": "^1.1.13",
48
- "apollo-link-http": "^1.5.17",
49
45
  "base-x": "^3.0.8",
50
46
  "big-integer": "^1.6.48",
51
47
  "buffer": "^6.0.3",
52
48
  "get-random-values": "^1.2.2",
53
49
  "graphql": "^15.5.0",
54
- "graphql-tag": "^2.11.0",
55
50
  "isomorphic-fetch": "^3.0.0",
56
51
  "js-sha3": "^0.8.0",
57
52
  "laravel-echo": "^1.10.0",
@@ -123,7 +118,7 @@
123
118
  "build:umd": "rollup --config build/rollup.config.umd.js",
124
119
  "build:cjs": "rollup --config build/rollup.config.cjs.js",
125
120
  "dev": "nodemon --exec \"yarn build:es && yarn build:umd && yarn build:cjs\" --watch",
126
- "build:webpack:dev": "webpack --mode development --watch --stats-colors --profile",
121
+ "build:webpack:dev": "webpack --mode development --watch --stats-colors --profile --stats-error-details",
127
122
  "build:webpack:dev:sub": "webpack --mode development --watch --stats-colors --profile --config ./webpack.config.sub.js",
128
123
  "build:webpack": "webpack --mode production --progress --stats-colors --profile",
129
124
  "lint": "eslint --ext .js src"
@@ -364,20 +364,30 @@ export default class KnishIOClient {
364
364
  * @return {string}
365
365
  */
366
366
  getSecret () {
367
- if ( !this.$__secret ) {
368
- throw new UnauthenticatedException( 'KnishIOClient::getSecret() - Unable to find a stored getSecret!' );
367
+ if ( !this.hasSecret() ) {
368
+ throw new UnauthenticatedException( 'KnishIOClient::getSecret() - Unable to find a stored secret! Have you set a secret?' );
369
369
  }
370
370
  return this.$__secret;
371
371
  }
372
372
 
373
+ /**
374
+ * Returns whether or not a bundle hash is being stored for this session
375
+ *
376
+ * @return {boolean}
377
+ */
378
+ hasBundle () {
379
+ return !!this.$__bundle;
380
+ }
381
+
382
+
373
383
  /**
374
384
  * Returns the bundle hash for this session
375
385
  *
376
386
  * @return {string}
377
387
  */
378
388
  getBundle () {
379
- if ( !this.$__bundle ) {
380
- throw new UnauthenticatedException( 'KnishIOClient::getBundle() - Unable to find a stored getBundle!' );
389
+ if ( !this.hasBundle() ) {
390
+ throw new UnauthenticatedException( 'KnishIOClient::getBundle() - Unable to find a stored bundle! Have you set a secret?' );
381
391
  }
382
392
  return this.$__bundle;
383
393
  }
@@ -1659,7 +1669,7 @@ export default class KnishIOClient {
1659
1669
  * @returns {Promise<ResponseRequestAuthorizationGuest|ResponseRequestAuthorization|null>}
1660
1670
  */
1661
1671
  async requestAuthToken ( {
1662
- secret,
1672
+ secret = null,
1663
1673
  seed = null,
1664
1674
  cellSlug = null,
1665
1675
  encrypt = false
@@ -1681,7 +1691,6 @@ export default class KnishIOClient {
1681
1691
  // Auth in process...
1682
1692
  this.$__authInProcess = true;
1683
1693
 
1684
-
1685
1694
  // Auth token response
1686
1695
  let response;
1687
1696
 
@@ -45,7 +45,7 @@ Please visit https://github.com/WishKnish/KnishIO-Client-JS for information.
45
45
 
46
46
  License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
47
47
  */
48
- import { Operation } from 'apollo-link';
48
+ import { Operation } from '@apollo/client/core';
49
49
  import { operationName } from '../libraries/ApolloLink/handler';
50
50
  import Client from '../libraries/ApolloLink/Client';
51
51
 
@@ -49,7 +49,7 @@ import {
49
49
  ApolloLink,
50
50
  Operation,
51
51
  NextLink
52
- } from 'apollo-link';
52
+ } from '@apollo/client/core';
53
53
 
54
54
 
55
55
  class AuthLink extends ApolloLink {
@@ -2,9 +2,9 @@ import {
2
2
  ApolloLink,
3
3
  Operation,
4
4
  NextLink
5
- } from 'apollo-link';
5
+ } from '@apollo/client/core';
6
6
  import { print } from 'graphql';
7
- import gql from 'graphql-tag';
7
+ import { gql } from '@apollo/client/core';
8
8
  import {
9
9
  operationName,
10
10
  operationType
@@ -45,18 +45,20 @@ Please visit https://github.com/WishKnish/KnishIO-Client-JS for information.
45
45
 
46
46
  License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
47
47
  */
48
- import { ApolloClient } from 'apollo-client';
48
+ import {
49
+ ApolloClient,
50
+ from,
51
+ concat
52
+ } from '@apollo/client/core';
49
53
  import fetch from 'isomorphic-fetch';
50
- import { ApolloLink } from 'apollo-link';
51
- import { InMemoryCache } from 'apollo-cache-inmemory';
54
+ import { InMemoryCache } from '@apollo/client/cache';
55
+ import { onError } from '@apollo/client/link/error';
52
56
 
53
57
  import HttpLink from './HttpLink';
54
58
  import EchoLink from './EchoLink';
55
59
  import AuthLink from './AuthLink';
56
60
  import { errorHandler } from './handler';
57
61
  import CipherLink from './CipherLink';
58
- import { onError } from 'apollo-link-error';
59
-
60
62
 
61
63
  class Client extends ApolloClient {
62
64
 
@@ -77,7 +79,6 @@ class Client extends ApolloClient {
77
79
  fetch: fetch,
78
80
  transportBatching: true
79
81
  } );
80
- const error = onError( errorHandler );
81
82
  const auth = new AuthLink();
82
83
 
83
84
  let cipher = null;
@@ -95,10 +96,10 @@ class Client extends ApolloClient {
95
96
  links.push( echo );
96
97
  }
97
98
 
98
- links.push( error.concat( http ) );
99
+ links.push( concat( onError( errorHandler ), http ) );
99
100
 
100
101
  super( {
101
- link: ApolloLink.from( links ),
102
+ link: from( links ),
102
103
  cache: new InMemoryCache(),
103
104
  connectToDevTools: true,
104
105
  defaultOptions: {
@@ -49,7 +49,7 @@ import {
49
49
  ApolloLink,
50
50
  Operation,
51
51
  NextLink
52
- } from 'apollo-link';
52
+ } from '@apollo/client/core';
53
53
  import Echo from 'laravel-echo';
54
54
  import createRequestHandler from './handler';
55
55
  import io from 'socket.io-client';
@@ -47,9 +47,10 @@ License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
47
47
  */
48
48
  import {
49
49
  Operation,
50
- NextLink
51
- } from 'apollo-link';
52
- import { HttpLink as RootHttpLink } from 'apollo-link-http';
50
+ NextLink,
51
+ HttpLink as RootHttpLink
52
+ } from '@apollo/client/core';
53
+
53
54
 
54
55
  class HttpLink extends RootHttpLink {
55
56
 
@@ -48,9 +48,9 @@ License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
48
48
  import {
49
49
  Observable,
50
50
  Operation,
51
- FetchResult
52
- } from 'apollo-link';
53
- import { Observer } from 'apollo-client/util/Observable';
51
+ FetchResult,
52
+ Observer
53
+ } from '@apollo/client/core';
54
54
 
55
55
  /**
56
56
  * @param {Echo} echoClient
@@ -194,7 +194,12 @@ export function errorHandler ( {
194
194
  }
195
195
 
196
196
  if ( networkError ) {
197
- console.error( `[Network error]: ${ networkError }` );
197
+ const {
198
+ name,
199
+ statusCode,
200
+ result = {}
201
+ } = networkError;
202
+ console.error( `[Network error]: ${ name }, status code: ${ statusCode }` );
198
203
  // if you would also like to retry automatically on
199
204
  // network errors, we recommend that you use
200
205
  // apollo-link-retry
@@ -46,7 +46,7 @@ Please visit https://github.com/WishKnish/KnishIO-Client-JS for information.
46
46
  License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
47
47
  */
48
48
  import Query from '../query/Query';
49
- import { Operation } from 'apollo-link';
49
+ import { Operation } from '@apollo/client/core';
50
50
 
51
51
  /**
52
52
  * Base class used to construct various GraphQL mutations
@@ -47,7 +47,7 @@ License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
47
47
  */
48
48
  import Mutation from '../mutation/Mutation';
49
49
  import ResponseActiveSession from '../response/ResponseActiveSession';
50
- import gql from 'graphql-tag';
50
+ import { gql } from '@apollo/client/core';
51
51
 
52
52
  /**
53
53
  * Mutation for declaring an active User Session with a given MetaAsset
@@ -47,7 +47,7 @@ License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
47
47
  */
48
48
  import Mutation from '../mutation/Mutation';
49
49
  import ResponseLinkIdentifier from '../response/ResponseLinkIdentifier';
50
- import gql from 'graphql-tag';
50
+ import { gql } from '@apollo/client/core';
51
51
 
52
52
  /**
53
53
  * Query for linking an Identifier to a Wallet Bundle
@@ -47,7 +47,7 @@ License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
47
47
  */
48
48
  import ResponseProposeMolecule from '../response/ResponseProposeMolecule';
49
49
  import Mutation from './Mutation';
50
- import gql from 'graphql-tag';
50
+ import { gql } from '@apollo/client/core';
51
51
 
52
52
 
53
53
  export default class MutationProposeMolecule extends Mutation {
@@ -45,7 +45,7 @@ Please visit https://github.com/WishKnish/KnishIO-Client-JS for information.
45
45
 
46
46
  License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
47
47
  */
48
- import gql from 'graphql-tag';
48
+ import { gql } from '@apollo/client/core';
49
49
  import Mutation from '../mutation/Mutation';
50
50
  import ResponseRequestAuthorizationGuest from '../response/ResponseRequestAuthorizationGuest';
51
51
 
@@ -46,7 +46,7 @@ Please visit https://github.com/WishKnish/KnishIO-Client-JS for information.
46
46
  License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
47
47
  */
48
48
  import CodeException from '../exception/CodeException';
49
- import { Operation } from 'apollo-link';
49
+ import { Operation } from '@apollo/client/core';
50
50
  import Response from '../response/Response';
51
51
 
52
52
  export default class Query {
@@ -47,7 +47,7 @@ License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
47
47
  */
48
48
  import Query from './Query';
49
49
  import ResponseQueryActiveSession from '../response/ResponseQueryActiveSession';
50
- import gql from 'graphql-tag';
50
+ import { gql } from '@apollo/client/core';
51
51
 
52
52
  /**
53
53
  * Query for retrieving a list of active User Sessions
@@ -46,7 +46,7 @@ Please visit https://github.com/WishKnish/KnishIO-Client-JS for information.
46
46
  License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
47
47
  */
48
48
  import Query from './Query';
49
- import gql from 'graphql-tag';
49
+ import { gql } from '@apollo/client/core';
50
50
  import ResponseBalance from '../response/ResponseBalance';
51
51
 
52
52
  /**
@@ -47,7 +47,7 @@ License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
47
47
  */
48
48
  import Query from './Query';
49
49
  import Response from '../response/Response';
50
- import gql from 'graphql-tag';
50
+ import { gql } from '@apollo/client/core';
51
51
 
52
52
 
53
53
  /**
@@ -48,7 +48,7 @@ License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
48
48
  import Query from './Query';
49
49
  import QueryBatch from './QueryBatch';
50
50
  import Response from '../response/Response';
51
- import gql from 'graphql-tag';
51
+ import { gql } from '@apollo/client/core';
52
52
 
53
53
  /**
54
54
  * Query for retrieving Meta Asset information
@@ -47,7 +47,7 @@ License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
47
47
  */
48
48
  import Query from './Query';
49
49
  import ResponseContinuId from '../response/ResponseContinuId';
50
- import gql from 'graphql-tag';
50
+ import { gql } from '@apollo/client/core';
51
51
 
52
52
  /**
53
53
  * Queries the node for the next wallet to sign with for ContinuID
@@ -47,7 +47,7 @@ License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
47
47
  */
48
48
  import Query from './Query';
49
49
  import Response from '../response/Response';
50
- import gql from 'graphql-tag';
50
+ import { gql } from '@apollo/client/core';
51
51
 
52
52
  /**
53
53
  * Query for retrieving Meta Asset information
@@ -47,7 +47,7 @@ License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
47
47
  */
48
48
  import Query from './Query';
49
49
  import ResponseMetaType from '../response/ResponseMetaType';
50
- import gql from 'graphql-tag';
50
+ import { gql } from '@apollo/client/core';
51
51
 
52
52
  /**
53
53
  * Query for retrieving Meta Asset information
@@ -46,7 +46,7 @@ Please visit https://github.com/WishKnish/KnishIO-Client-JS for information.
46
46
  License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
47
47
  */
48
48
  import Query from './Query';
49
- import gql from 'graphql-tag';
49
+ import { gql } from '@apollo/client/core';
50
50
  import Response from '../response/Response';
51
51
 
52
52
 
@@ -81,11 +81,10 @@ export default class QueryToken extends Query {
81
81
  * @returns {Response}
82
82
  */
83
83
  createResponse ( json ) {
84
- let responseObject = new Response( {
84
+ return new Response( {
85
85
  query: this,
86
- json
86
+ json,
87
+ dataKey: 'data.Token'
87
88
  } );
88
- responseObject.dataKey = 'data.Token';
89
- return responseObject;
90
89
  }
91
90
  }
@@ -47,7 +47,7 @@ License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
47
47
  */
48
48
  import Query from './Query';
49
49
  import ResponseQueryUserActivity from '../response/ResponseQueryUserActivity';
50
- import gql from 'graphql-tag';
50
+ import { gql } from '@apollo/client/core';
51
51
 
52
52
  /**
53
53
  * Query for retrieving information about user activity
@@ -47,7 +47,7 @@ License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
47
47
  */
48
48
  import Query from './Query';
49
49
  import ResponseWalletBundle from '../response/ResponseWalletBundle';
50
- import gql from 'graphql-tag';
50
+ import { gql } from '@apollo/client/core';
51
51
 
52
52
  /**
53
53
  * Query for retrieving information about Wallet Bundles
@@ -47,7 +47,7 @@ License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
47
47
  */
48
48
  import Query from './Query';
49
49
  import ResponseWalletList from '../response/ResponseWalletList';
50
- import gql from 'graphql-tag';
50
+ import { gql } from '@apollo/client/core';
51
51
 
52
52
  /**
53
53
  * Query for getting a list of Wallets
@@ -92,6 +92,11 @@ export default class Response {
92
92
  this.init();
93
93
  }
94
94
 
95
+ /**
96
+ *
97
+ */
98
+ init () {}
99
+
95
100
  /**
96
101
  * @return {*}
97
102
  */
@@ -137,10 +142,4 @@ export default class Response {
137
142
  return null;
138
143
  }
139
144
 
140
- /**
141
- * @return {*}
142
- */
143
- init () {
144
- return null;
145
- }
146
145
  }
@@ -62,9 +62,8 @@ export default class ResponseActiveSession extends Response {
62
62
  } ) {
63
63
  super( {
64
64
  query,
65
- json
65
+ json,
66
+ dataKey: 'data.ActiveSession'
66
67
  } );
67
- this.dataKey = 'data.ActiveSession';
68
- this.init();
69
68
  }
70
69
  }
@@ -67,10 +67,9 @@ export default class ResponseAuthorizationGuest extends Response {
67
67
  } ) {
68
68
  super( {
69
69
  query,
70
- json
70
+ json,
71
+ dataKey: 'data.AccessToken'
71
72
  } );
72
- this.dataKey = 'data.AccessToken';
73
- this.init();
74
73
  }
75
74
 
76
75
  /**
@@ -66,10 +66,9 @@ export default class ResponseBalance extends Response {
66
66
  } ) {
67
67
  super( {
68
68
  query,
69
- json
69
+ json,
70
+ dataKey: 'data.Balance'
70
71
  } );
71
- this.dataKey = 'data.Balance';
72
- this.init();
73
72
  }
74
73
 
75
74
  /**
@@ -66,10 +66,9 @@ export default class ResponseContinuId extends Response {
66
66
  } ) {
67
67
  super( {
68
68
  query,
69
- json
69
+ json,
70
+ dataKey: 'data.ContinuId'
70
71
  } );
71
- this.dataKey = 'data.ContinuId';
72
- this.init();
73
72
  }
74
73
 
75
74
  /**
@@ -66,10 +66,9 @@ export default class ResponseLinkIdentifier extends Response {
66
66
  } ) {
67
67
  super( {
68
68
  query,
69
- json
69
+ json,
70
+ dataKey: 'data.LinkIdentifier'
70
71
  } );
71
- this.dataKey = 'data.LinkIdentifier';
72
- this.init();
73
72
  }
74
73
 
75
74
  /**
@@ -65,10 +65,9 @@ export default class ResponseMetaBatch extends Response {
65
65
  } ) {
66
66
  super( {
67
67
  query,
68
- json
68
+ json,
69
+ dataKey: 'data.MetaBatch'
69
70
  } );
70
- this.dataKey = 'data.MetaBatch';
71
- this.init();
72
71
  }
73
72
 
74
73
  }
@@ -66,10 +66,9 @@ export default class ResponseMetaType extends Response {
66
66
  } ) {
67
67
  super( {
68
68
  query,
69
- json
69
+ json,
70
+ dataKey: 'data.MetaType'
70
71
  } );
71
- this.dataKey = 'data.MetaType';
72
- this.init();
73
72
  }
74
73
 
75
74
  /**
@@ -66,11 +66,10 @@ export default class ResponseProposeMolecule extends Response {
66
66
  } ) {
67
67
  super( {
68
68
  query,
69
- json
69
+ json,
70
+ dataKey: 'data.ProposeMolecule'
70
71
  } );
71
- this.dataKey = 'data.ProposeMolecule';
72
72
  this.$__clientMolecule = query.molecule();
73
- this.init();
74
73
  }
75
74
 
76
75
  /**
@@ -66,10 +66,9 @@ export default class ResponseQueryActiveSession extends Response {
66
66
  } ) {
67
67
  super( {
68
68
  query,
69
- json
69
+ json,
70
+ dataKey: 'data.ActiveUser'
70
71
  } );
71
- this.dataKey = 'data.ActiveUser';
72
- this.init();
73
72
  }
74
73
 
75
74
  payload () {
@@ -61,10 +61,9 @@ export default class ResponseQueryUserActivity extends Response {
61
61
  } ) {
62
62
  super( {
63
63
  query,
64
- json
64
+ json,
65
+ dataKey: 'data.UserActivity'
65
66
  } );
66
- this.dataKey = 'data.UserActivity';
67
- this.init();
68
67
  }
69
68
 
70
69
  payload () {
@@ -66,10 +66,9 @@ export default class ResponseRequestAuthorizationGuest extends Response {
66
66
  } ) {
67
67
  super( {
68
68
  query,
69
- json
69
+ json,
70
+ dataKey: 'data.AccessToken'
70
71
  } );
71
- this.dataKey = 'data.AccessToken';
72
- this.init();
73
72
  }
74
73
 
75
74
  /**
@@ -66,10 +66,9 @@ export default class ResponseWalletBundle extends Response {
66
66
  } ) {
67
67
  super( {
68
68
  query,
69
- json
69
+ json,
70
+ dataKey: 'data.WalletBundle'
70
71
  } );
71
- this.dataKey = 'data.WalletBundle';
72
- this.init();
73
72
  }
74
73
 
75
74
  /**
@@ -66,10 +66,9 @@ export default class ResponseWalletList extends Response {
66
66
  } ) {
67
67
  super( {
68
68
  query,
69
- json
69
+ json,
70
+ dataKey: 'data.Wallet'
70
71
  } );
71
- this.dataKey = 'data.Wallet';
72
- this.init();
73
72
  }
74
73
 
75
74
  /**
@@ -152,6 +151,6 @@ export default class ResponseWalletList extends Response {
152
151
  * @return {null|[Wallet]}
153
152
  */
154
153
  payload () {
155
- this.getWallets();
154
+ return this.getWallets();
156
155
  }
157
156
  }
@@ -1,5 +1,5 @@
1
1
  import Subscribe from './Subscribe';
2
- import gql from 'graphql-tag';
2
+ import { gql } from '@apollo/client/core';
3
3
 
4
4
 
5
5
  export default class ActiveSessionSubscribe extends Subscribe {
@@ -1,5 +1,5 @@
1
1
  import Subscribe from './Subscribe';
2
- import gql from 'graphql-tag';
2
+ import { gql } from '@apollo/client/core';
3
3
 
4
4
 
5
5
  export default class ActiveWalletSubscribe extends Subscribe {
@@ -1,5 +1,5 @@
1
1
  import Subscribe from './Subscribe';
2
- import gql from 'graphql-tag';
2
+ import { gql } from '@apollo/client/core';
3
3
 
4
4
  export default class CreateMoleculeSubscribe extends Subscribe {
5
5
  constructor ( apolloClient ) {
@@ -1,5 +1,5 @@
1
1
  import CodeException from '../exception/CodeException';
2
- import { Operation } from 'apollo-link';
2
+ import { Operation } from '@apollo/client/core';
3
3
 
4
4
  export default class Subscribe {
5
5
  /**
@@ -1,5 +1,5 @@
1
1
  import Subscribe from './Subscribe';
2
- import gql from 'graphql-tag';
2
+ import { gql } from '@apollo/client/core';
3
3
 
4
4
 
5
5
  export default class WalletStatusSubscribe extends Subscribe {