@wishknish/knishio-client-js 0.5.2 → 0.6.1
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.
- package/README.md +207 -274
- package/dist/client.iife.js +533 -0
- package/package.json +37 -79
- package/src/.babelrc +0 -22
- package/src/Atom.js +171 -132
- package/src/AtomMeta.js +76 -50
- package/src/AuthToken.js +38 -47
- package/src/KnishIOClient.js +934 -987
- package/src/Meta.js +15 -17
- package/src/Molecule.js +423 -494
- package/src/PolicyMeta.js +32 -41
- package/src/TokenUnit.js +30 -32
- package/src/Wallet.js +275 -265
- package/src/exception/AtomIndexException.js +4 -8
- package/src/exception/AtomsMissingException.js +4 -6
- package/src/exception/AuthorizationRejectedException.js +4 -5
- package/src/exception/BalanceInsufficientException.js +4 -8
- package/src/exception/BaseException.js +6 -8
- package/src/exception/BatchIdException.js +5 -7
- package/src/exception/CodeException.js +4 -8
- package/src/{libraries/ApolloLink/HttpLink.js → exception/DecryptionKeyException.js} +12 -15
- package/src/exception/InvalidResponseException.js +4 -5
- package/src/exception/MetaMissingException.js +4 -6
- package/src/exception/MolecularHashMismatchException.js +4 -6
- package/src/exception/MolecularHashMissingException.js +4 -5
- package/src/exception/NegativeAmountException.js +4 -5
- package/src/exception/PolicyInvalidException.js +4 -4
- package/src/exception/SignatureMalformedException.js +4 -5
- package/src/exception/SignatureMismatchException.js +4 -5
- package/src/exception/StackableUnitAmountException.js +4 -5
- package/src/exception/StackableUnitDecimalsException.js +4 -5
- package/src/exception/TransferBalanceException.js +4 -5
- package/src/exception/TransferMalformedException.js +4 -5
- package/src/exception/TransferMismatchedException.js +4 -5
- package/src/exception/TransferRemainderException.js +4 -5
- package/src/exception/TransferToSelfException.js +4 -5
- package/src/exception/TransferUnbalancedException.js +4 -5
- package/src/exception/UnauthenticatedException.js +4 -5
- package/src/{libraries/ApolloLink/AuthLink.js → exception/WalletCredentialException.js} +12 -40
- package/src/exception/WalletShadowException.js +4 -5
- package/src/exception/WrongTokenTypeException.js +4 -5
- package/src/exception/index.js +26 -26
- package/src/index.js +8 -10
- package/src/instance/Rules/Callback.js +91 -93
- package/src/instance/Rules/Condition.js +21 -23
- package/src/instance/Rules/Meta.js +13 -14
- package/src/instance/Rules/Rule.js +39 -43
- package/src/instance/Rules/exception/RuleArgumentException.js +4 -4
- package/src/libraries/CheckMolecule.js +253 -232
- package/src/libraries/Decimal.js +13 -17
- package/src/libraries/Dot.js +74 -48
- package/src/libraries/Hex.js +49 -54
- package/src/libraries/array.js +50 -41
- package/src/libraries/crypto.js +20 -27
- package/src/libraries/strings.js +58 -91
- package/src/libraries/urql/UrqlClientWrapper.js +166 -0
- package/src/mutation/Mutation.js +44 -25
- package/src/mutation/MutationActiveSession.js +12 -12
- package/src/mutation/MutationClaimShadowWallet.js +15 -17
- package/src/mutation/MutationCreateIdentifier.js +11 -12
- package/src/mutation/MutationCreateMeta.js +11 -12
- package/src/mutation/MutationCreateRule.js +11 -12
- package/src/mutation/MutationCreateToken.js +18 -13
- package/src/mutation/MutationCreateWallet.js +9 -11
- package/src/mutation/MutationDepositBufferToken.js +7 -9
- package/src/mutation/MutationLinkIdentifier.js +12 -14
- package/src/mutation/MutationProposeMolecule.js +24 -25
- package/src/mutation/MutationRequestAuthorization.js +9 -10
- package/src/mutation/MutationRequestAuthorizationGuest.js +12 -15
- package/src/mutation/MutationRequestTokens.js +11 -14
- package/src/mutation/MutationTransferTokens.js +11 -14
- package/src/mutation/MutationWithdrawBufferToken.js +7 -10
- package/src/query/Query.js +62 -36
- package/src/query/QueryActiveSession.js +11 -13
- package/src/query/QueryAtom.js +75 -76
- package/src/query/QueryBalance.js +11 -12
- package/src/query/QueryBatch.js +17 -14
- package/src/query/QueryBatchHistory.js +16 -13
- package/src/query/QueryContinuId.js +13 -10
- package/src/query/QueryMetaType.js +45 -57
- package/src/query/QueryMetaTypeViaAtom.js +49 -57
- package/src/query/QueryPolicy.js +11 -12
- package/src/query/QueryToken.js +11 -13
- package/src/query/QueryUserActivity.js +11 -13
- package/src/query/QueryWalletBundle.js +15 -47
- package/src/query/QueryWalletList.js +15 -16
- package/src/response/Response.js +29 -34
- package/src/response/ResponseActiveSession.js +6 -6
- package/src/response/ResponseAtom.js +29 -30
- package/src/response/ResponseAuthorizationGuest.js +17 -18
- package/src/response/ResponseBalance.js +12 -13
- package/src/response/ResponseClaimShadowWallet.js +1 -1
- package/src/response/ResponseContinuId.js +21 -22
- package/src/response/ResponseCreateIdentifier.js +1 -1
- package/src/response/ResponseCreateMeta.js +1 -1
- package/src/response/ResponseCreateRule.js +1 -1
- package/src/response/ResponseCreateToken.js +1 -1
- package/src/response/ResponseCreateWallet.js +1 -1
- package/src/response/ResponseLinkIdentifier.js +9 -10
- package/src/response/ResponseMetaBatch.js +6 -8
- package/src/response/ResponseMetaType.js +19 -20
- package/src/response/ResponseMetaTypeViaAtom.js +19 -19
- package/src/response/ResponsePolicy.js +14 -15
- package/src/response/ResponseProposeMolecule.js +27 -30
- package/src/response/ResponseQueryActiveSession.js +20 -23
- package/src/response/ResponseQueryUserActivity.js +11 -12
- package/src/response/ResponseRequestAuthorization.js +11 -16
- package/src/response/ResponseRequestAuthorizationGuest.js +18 -21
- package/src/response/ResponseRequestTokens.js +1 -1
- package/src/response/ResponseTransferTokens.js +8 -9
- package/src/response/ResponseWalletBundle.js +16 -17
- package/src/response/ResponseWalletList.js +44 -47
- package/src/subscribe/ActiveSessionSubscribe.js +5 -6
- package/src/subscribe/ActiveWalletSubscribe.js +5 -6
- package/src/subscribe/CreateMoleculeSubscribe.js +5 -5
- package/src/subscribe/Subscribe.js +26 -26
- package/src/subscribe/WalletStatusSubscribe.js +5 -6
- package/src/versions/HashAtom.js +78 -0
- package/src/versions/Version4.js +34 -0
- package/src/versions/index.js +5 -0
- package/dist/client.umd.js +0 -453
- package/src/httpClient/ApolloClient.js +0 -245
- package/src/libraries/ApolloLink/CipherLink.js +0 -117
- package/src/libraries/ApolloLink/Client.js +0 -231
- package/src/libraries/ApolloLink/PusherLink.js +0 -234
- package/src/libraries/ApolloLink/handler.js +0 -106
- package/src/libraries/Base58.js +0 -71
- package/src/libraries/Base64.js +0 -40
- package/src/libraries/BaseX.js +0 -91
- package/src/libraries/Soda.js +0 -93
- package/src/query/QueryMetaInstance.js +0 -99
- package/src/test/Test.js +0 -670
- package/src/test/TestTokenUnit.js +0 -340
package/dist/client.umd.js
DELETED
|
@@ -1,453 +0,0 @@
|
|
|
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("pusher-js"),require("uri-js"),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","pusher-js","uri-js","graphql"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).KnishIO={},e.shake256,e.bigInt,e.base64,e.getRandomValues,e.bigIntB,e.buffer,e.baseX,e.tweetnacl,e.tweetnaclSealedboxJs,e.utf8,e.apolloClientCore,e.fetch,e.apolloClientCache,e.apolloClientLinkError,e.pusherJs,e.uriJs,e.graphql)}(this,(function(e,t,s,n,a,i,r,l,o,u,c,h,d,p,m,y,g,k){"use strict";function b(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var _=b(s),f=b(a),w=b(i),$=b(l),S=b(d),I=b(y);class T{static toHex(e,t){const s=(e,t)=>{const s=t?["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]:["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];return s[Math.floor(e/16)]+s[e%16]},n=Object.assign({grouping:0,rowlength:0,uppercase:!1},t||{});let a="",i=0,r=0;for(let t=0;t<e.length&&(a+=s(e[t],n.uppercase),t!==e.length-1);++t)n.grouping>0&&++i===n.grouping&&(i=0,n.rowlength>0&&++r===n.rowlength?(r=0,a+="\n"):a+=" ");return a}static toUint8Array(e){let t=e.toLowerCase().replace(/\s/g,"");t.length%2==1&&(t=`0${t}`);let s=new Uint8Array(Math.floor(t.length/2)),n=-1;for(let e=0;e<t.length;++e){let a=t[e],i=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"].indexOf(a);if(-1===i)throw Error("unexpected character");-1===n?n=16*i:(s[Math.floor(e/2)]=n+i,n=-1)}return s}}function A(e,t){const s=Math.ceil(e.length/t),n=[];for(let a=0,i=0;a<s;++a,i+=t)n[a]=e.substr(i,t);return n}function x(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 v(e,t,s,n,a){if(n=n||"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~`!@#$%^&*()-_=+[{]}\\|;:'\",<.>/?¿¡",a=a||n,t>n.length||s>a.length)return console.warn("Strings::charsetBaseConvert() - Can't convert",e,"to base",s,"greater than symbol table length. src-table:",n.length,"dest-table:",a.length),!1;let i=_.default(0);for(let s=0;s<e.length;s++)i=i.multiply(t).add(n.indexOf(e.charAt(s)));if(i.lesser(0))return 0;let r=i.mod(s),l=a.charAt(r),o=i.divide(s);for(;!o.equals(0);)r=o.mod(s),o=o.divide(s),l=a.charAt(r)+l;return l}function q(e){return n.encode(T.toUint8Array(e))}function C(e){return T.toHex(n.decode(e),{})}function W(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{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}}function M(e,t){let s,n,a,i=[Array,Date,Number,String,Boolean],r=Object.prototype.toString;for(t=t||[],s=0;s<t.length;s+=2)e===t[s]&&(n=t[s+1]);if(!n&&e&&"object"==typeof e){for(n={},s=0;s<i.length;s++)r.call(e)===r.call(a=new i[s](e))&&(n=s?a:[]);for(s in t.push(e,n),e)t.hasOwnProperty.call(e,s)&&(n[s]=M(e[s],t))}return n||e}function U(...e){return[].concat(...e.map(((t,s)=>{const n=e.slice(0);n.splice(s,1);const a=[...new Set([].concat(...n))];return t.filter((e=>!a.includes(e)))})))}function O(...e){return e.reduce(((e,t)=>e.filter((e=>t.includes(e)))))}class H{static normalizePolicy(e={}){let t={};for(const[s,n]of Object.entries(e))if(null!==n&&["read","write"].includes(s)){t[s]={};for(const[e,a]of Object.entries(n))t[s][e]=a}return t}constructor(e={},t={}){this.policy=H.normalizePolicy(e),this.fillDefault(t)}fillDefault(e={}){const t=Array.from(this.policy).filter((e=>"read"===e.action)),s=Array.from(this.policy).filter((e=>"write"===e.action));for(const[n,a]of Object.entries({read:t,write:s})){const t=a.map((e=>e.key));this.policy[n]||(this.policy[n]={});for(const s of U(e,t))this.policy[n][s]||(this.policy[n][s]="write"!==n||["characters","pubkey"].includes(s)?["all"]:["self"])}}get(){return this.policy}toJson(){return JSON.stringify(this.get())}}class j{constructor(e={}){this.meta=e}merge(e){return this.meta=Object.assign(this.meta,e),this}addContext(e=null){return this}addWallet(e){let t={pubkey:e.pubkey,characters:e.characters};return e.tokenUnits&&e.tokenUnits.length&&(t.tokenUnits=JSON.stringify(e.getTokenUnitsData())),e.tradeRates&&e.tradeRates.length&&(t.tradeRates=JSON.stringify(e.tradeRates)),this.merge(t),this}addPolicy(e){let t=new H(e,Object.keys(this.meta));return this.merge({policy:t.toJson()}),this}addSigningWallet(e){return this.merge({signingWallet:JSON.stringify({address:e.address,position:e.position,pubkey:e.pubkey,characters:e.characters})}),this}get(){return this.meta}}class R{static getHashableProps(){return["position","walletAddress","isotope","token","value","batchId","metaType","metaId","meta","createdAt"]}constructor({position:e=null,walletAddress:t=null,isotope:s=null,token:n=null,value:a=null,batchId:i=null,metaType:r=null,metaId:l=null,meta:o=null,otsFragment:u=null,index:c=null}){this.position=e,this.walletAddress=t,this.isotope=s,this.token=n,this.value=null!==a?String(a):null,this.batchId=i,this.metaType=r,this.metaId=l,this.meta=o?B.normalizeMeta(o):[],this.index=c,this.otsFragment=u,this.createdAt=String(+new Date)}static create({isotope:e,wallet:t=null,value:s=null,metaType:n=null,metaId:a=null,meta:i=null,batchId:r=null}){return i||(i=new j),t&&(i.addWallet(t),r||(r=t.batchId)),new R({position:t?t.position:null,walletAddress:t?t.address:null,isotope:e,token:t?t.token:null,value:s,batchId:r,metaType:n,metaId:a,meta:i.get()})}aggregatedMeta(){return B.aggregateMeta(this.meta)}static jsonToObject(e){const t=Object.assign(new R({}),JSON.parse(e)),s=Object.keys(new R({}));for(const e in t)t.hasOwnProperty(e)&&!s.includes(e)&&delete t[e];return t}getHashableValues(){const e=[];for(let t of R.getHashableProps()){const s=this[t];if(null!==s||["position","walletAddress"].includes(t))if("meta"===t)for(const t of s)void 0!==t.value&&null!==t.value&&(e.push(String(t.key)),e.push(String(t.value)));else e.push(null===s?"":String(s))}return e}static hashAtoms({atoms:e,output:s="base17"}){const n=t.shake256.create(256),a=e.length,i=R.sortAtoms(e);let r=[];for(const e of i)r.push(String(a)),r=r.concat(e.getHashableValues());for(const e of r)n.update(e);switch(s){case"hex":return n.hex();case"array":return n.array();default:return v(n.hex(),16,17,"0123456789abcdef","0123456789abcdefg").padStart(64,"0")}}static sortAtoms(e){const t=[...e];return t.sort(((e,t)=>e.index<t.index?-1:1)),t}}function E(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 x(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 Q({molecularHash:e=null,index:t=null}){return null!==e&&null!==t?K(String(e)+String(t)):x(64)}class P{static encode(e){return n.encode(e)}static decode(e){return r.Buffer.from(n.decode(e))}encode(e){return P.encode(e)}decode(e){return P.decode(e)}}class N{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 F{constructor(e={}){this.$options=Object.assign({characters:"BASE64"},e),this.$encoder=new N,["BASE64"].includes(this.$options.characters)?this.$encoder=new P:["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 N(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 V{static createFromGraphQL(e){let t=e.metas||{};return t.length&&(t=JSON.parse(t),t||(t={})),new V(e.id,e.name,t)}static createFromDB(e){return new V(e[0],e[1],e.length>2?e[2]:{})}constructor(e,t,s){this.id=e,this.name=t,this.metas=s||{}}getFragmentZone(){return this.metas.fragmentZone||null}getFusedTokenUnits(){return this.metas.fusedTokenUnits||null}toData(){return[this.id,this.name,this.metas]}toGraphQLResponse(){return{id:this.id,name:this.name,metas:JSON.stringify(this.metas)}}}class J{constructor(e=null){this.base=new F({characters:e||"BASE64"})}encrypt(e,t){return this.encode(u.seal(c.encode(JSON.stringify(e)),this.decode(t)))}decrypt(e,t,s){try{return JSON.parse(c.decode(u.open(this.decode(e),this.decode(s),this.decode(t))))}catch(e){return null}}generatePrivateKey(e){const s=t.shake256.create(8*o.box.secretKeyLength);return s.update(e),this.base.encode(r.Buffer.from(s.digest()))}generatePublicKey(e){const t=o.box.keyPair.fromSecretKey(this.decode(e));return this.encode(t.publicKey)}shortHash(e){const s=t.shake256.create(64);return s.update(e),this.base.encode(r.Buffer.from(s.digest()))}decode(e){return this.base.decode(e)}encode(e){return this.base.encode(e)}}class D{constructor({secret:e=null,token:t="USER",position:s=null,batchId:n=null,characters:a=null}){this.token=t,this.balance=0,this.molecules={},this.key=null,this.address=null,this.privkey=null,this.pubkey=null,this.tokenUnits=[],this.tradeRates={},this.bundle=null,this.batchId=n,this.position=s,this.characters=a,e&&(this.bundle=K(e),this.position=this.position||D.generatePosition(),this.key=D.generateKey({secret:e,token:this.token,position:this.position}),this.address=D.generateAddress(this.key),this.soda=new J(a),this.privkey=this.soda.generatePrivateKey(this.key),this.pubkey=this.soda.generatePublicKey(this.privkey),this.characters=this.characters||"BASE64")}static create({secretOrBundle:e,token:t,batchId:s=null,characters:n=null}){let a=D.isBundleHash(e)?null:e,i=a?K(a):e,r=a?D.generatePosition():null,l=new D({secret:a,token:t,position:r,batchId:s,characters:n});return l.bundle=i,l}static isBundleHash(e){return"string"==typeof e&&(64===e.length&&W(e))}static getTokenUnits(e){let t=[];return e.forEach((e=>{t.push(V.createFromDB(e))})),t}getTokenUnitsData(){const e=[];return this.tokenUnits.forEach((t=>{e.push(t.toData())})),e}splitUnits(e,t,s=null){if(0===e.length)return;let n=[],a=[];this.tokenUnits.forEach((t=>{e.includes(t.id)?n.push(t):a.push(t)})),this.tokenUnits=n,null!==s&&(s.tokenUnits=n),t.tokenUnits=a}isShadow(){return!(void 0!==this.position&&null!==this.position||void 0!==this.address&&null!==this.address)}initBatchId({sourceWallet:e,isRemainder:t=!1}){e.batchId&&(this.batchId=t?e.batchId:Q({}))}encryptMessage(e){const t={};for(let s=1,n=arguments.length;s<n;s++)t[this.soda.shortHash(arguments[s])]=this.soda.encrypt(e,arguments[s]);return t}decryptMessage(e){const t=this.pubkey;let s=e;return null!==e&&"object"==typeof e&&"[object Object]"===Object.prototype.toString.call(e)&&(s=e[this.soda.shortHash(t)]||""),this.soda.decrypt(s,this.privkey,t)}decryptBinary(e){const t=this.decryptMessage(e);return new F({characters:"BASE64"}).decode(t)}encryptBinary(e){const t=Array.from(arguments).slice(1),s=new F({characters:"BASE64"}).encode(e);return this.encryptMessage(s,...t)}encryptString({data:e,publicKeys:t}){if(e){const s=this.pubkey;"string"==typeof t&&(t=[t]);const n=this.encryptMessage(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.decryptMessage(s)||t}catch(s){return console.error(s),t||e}}static generateKey({secret:e,token:s,position:n}){const a=w.default(e,16).add(w.default(n,16)),i=t.shake256.create(8192);return i.update(a.toString(16)),s&&i.update(s),t.shake256.create(8192).update(i.hex()).hex()}static generateAddress(e){const s=A(e,128),n=t.shake256.create(8192);for(const e in s){let a=s[e];for(let e=1;e<=16;e++)a=t.shake256.create(512).update(a).hex();n.update(a)}return t.shake256.create(256).update(n.hex()).hex()}static generatePosition(e=64){return x(e,"abcdef0123456789")}}class L 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 L{constructor(e="There is an atom without an index",t=null,s=null){super(e,t,s),this.name="AtomIndexException"}}class Z extends L{constructor(e="The molecule does not contain atoms",t=null,s=null){super(e,t,s),this.name="AtomsMissingException"}}class G extends L{constructor(e="The molecular hash does not match",t=null,s=null){super(e,t,s),this.name="MolecularHashMismatchException"}}class X extends L{constructor(e="The molecular hash is missing",t=null,s=null){super(e,t,s),this.name="MolecularHashMissingException"}}class Y extends L{constructor(e="",t=null,s=null){super(e,t,s),this.name="PolicyInvalidException"}}class ee extends L{constructor(e="OTS malformed",t=null,s=null){super(e,t,s),this.name="SignatureMalformedException"}}class te extends L{constructor(e="One-time signature (OTS) does not match!",t=null,s=null){super(e,t,s),this.name="SignatureMismatchException"}}class se extends L{constructor(e="Insufficient balance to make transfer",t=null,s=null){super(e,t,s),this.name="TransferBalanceException"}}class ne extends L{constructor(e="Token transfer atoms are malformed",t=null,s=null){super(e,t,s),this.name="TransferMalformedException"}}class ae extends L{constructor(e="Token slugs for wallets in transfer do not match!",t=null,s=null){super(e,t,s),this.name="TransferMismatchedException"}}class ie extends L{constructor(e="Invalid remainder provided",t=null,s=null){super(e,t,s),this.name="TransferRemainderException"}}class re extends L{constructor(e="Sender and recipient(s) cannot be the same",t=null,s=null){super(e,t,s),this.name="TransferToSelfException"}}class le extends L{constructor(e="Token transfer atoms are unbalanced",t=null,s=null){super(e,t,s),this.name="TransferUnbalancedException"}}class oe extends L{constructor(e="Empty meta data.",t=null,s=null){super(e,t,s),this.name="MetaMissingException"}}class ue extends L{constructor(e="Wrong type of token for this isotope",t=null,s=null){super(e,t,s),this.name="WrongTokenTypeException"}}class ce extends L{constructor(e="Incorrect BatchId",t=null,s=null){super(e,t,s),this.name="BatchIdException"}}class he{constructor({}){const e=arguments[0];for(const t in e)this[`__${t}`]=e[t]}toJSON(){const e={};for(const t of Object.keys(this))"__"===t.substring(0,2)&&(e[t.substring(2,t.length)]=this[t]);return e}static toObject(e){return new this(e)}}class de extends L{constructor(e="An incorrect argument!",t=null,s=null){super(e,t,s),this.name="RuleArgumentException"}}class pe extends L{constructor(e="Code exception",t=null,s=null){super(e,t,s),this.name="CodeException"}}class me{constructor({action:e,metaType:t=null,metaId:s=null,meta:n=null,address:a=null,token:i=null,amount:r=null,comparison:l=null}){if(n&&(this.meta=n),!e)throw new de('Callback structure violated, missing mandatory "action" parameter.');this.__metaId=s,this.__metaType=t,this.__action=e,this.__address=a,this.__token=i,this.__amount=r,this.__comparison=l}set comparison(e){this.__comparison=e}set amount(e){if("number"!=typeof(t=e)&&("string"!=typeof t||""===t.trim())||isNaN(t))throw new pe("Parameter amount should be a string containing numbers");var t;this.__amount=e}set token(e){this.__token=e}set address(e){this.__address=e}set meta(e){this.__meta=e instanceof he?e:he.toObject(e)}set metaType(e){this.__metaType=e}set metaId(e){this.__metaId=e}toJSON(){const e={action:this.__action};return this.__metaType&&(e.metaType=this.__metaType),this.__metaId&&(e.metaId=this.__metaId),this.__meta&&(e.meta=this.__meta),this.__address&&(e.address=this.__address),this.__token&&(e.token=this.__token),this.__amount&&(e.amount=this.__amount),this.__comparison&&(e.comparison=this.__comparison),e}static toObject(e){const t=new me({action:e.action});return e.metaType&&(t.metaType=e.metaType),e.metaId&&(t.metaId=e.metaId),e.meta&&(t.meta=e.meta),e.address&&(t.address=e.address),e.token&&(t.token=e.token),e.amount&&(t.amount=e.amount),e.comparison&&(t.comparison=e.comparison),t}isReject(){return this._is("reject")}isMeta(){return 4===O(Object.keys(this.toJSON()),["action","metaId","metaType","meta"]).length&&this._is("meta")}isCollect(){return 5===O(Object.keys(this.toJSON()),["action","address","token","amount","comparison"]).length&&this._is("collect")}isBuffer(){return 5===O(Object.keys(this.toJSON()),["action","address","token","amount","comparison"]).length&&this._is("buffer")}isRemit(){return 3===O(Object.keys(this.toJSON()),["action","token","amount"]).length&&this._is("remit")}isBurn(){return 4===O(Object.keys(this.toJSON()),["action","token","amount","comparison"]).length&&this._is("burn")}_is(e){return this.__action.toLowerCase()===e.toLowerCase()}}class ye{constructor({key:e,value:t,comparison:s}){if([e,t,s].some((e=>!e)))throw new de("Condition::constructor( { key, value, comparison } ) - not all class parameters are initialised!");this.__key=e,this.__value=t,this.__comparison=s}toJSON(){return{key:this.__key,value:this.__value,comparison:this.__comparison}}static toObject(e){return new this({key:e.key,value:e.value,comparison:e.comparison})}}class ge{constructor({condition:e=[],callback:t=[]}){for(const t of e)if(!(t instanceof ye))throw new de;for(const e of t)if(!(e instanceof me))throw new de;this.__condition=e,this.__callback=t}set comparison(e){this.__condition.push(e instanceof ye?e:ye.toObject(e))}set callback(e){this.__callback.push(e instanceof me?e:me.toObject(e))}toJSON(){return{condition:this.__condition,callback:this.__callback}}static toObject(e){if(!e.condition)throw new oe("Rule::toObject() - Incorrect rule format! There is no condition field.");if(!e.callback)throw new oe("Rule::toObject() - Incorrect rule format! There is no callback field.");const t=new ge({});for(const s of e.condition)t.comparison=s;for(const s of e.callback)console.log(s),t.callback=s;return t}}class ke{static __init(e,t){this.arr=[],this.key=null,this.arr=String(t).split("."),this.key=this.arr.shift();const s=Number(this.key);Number.isInteger(s)&&(this.key=s),this.__nextKey=this.arr.length,this.__next=this.__tic(e)}static __tic(e){return!!(Array.isArray(e)||e instanceof Object)&&void 0!==e[this.key]}static has(e,t){return this.__init(e,t),!!this.__next&&(0===this.__nextKey||this.has(e[this.key],this.arr.join(".")))}static get(e,t,s=null){return this.__init(e,t),this.__next?0===this.__nextKey?e[this.key]:this.get(e[this.key],this.arr.join("."),s):s}}class be{constructor(e){if(null===e.molecularHash)throw new X;if(!e.atoms.length)throw new Z;for(let t of e.atoms)if(null===t.index)throw new z;this.molecule=e}verify(e){return this.molecularHash()&&this.ots()&&this.batchId()&&this.continuId()&&this.isotopeM()&&this.isotopeT()&&this.isotopeC()&&this.isotopeU()&&this.isotopeI()&&this.isotopeR()&&this.isotopeV(e)}continuId(){if("USER"===this.molecule.atoms[0].token&&this.molecule.getIsotopes("I").length<1)throw new Z("Check::continuId() - Molecule is missing required ContinuID Atom!");return!0}batchId(){if(this.molecule.atoms.length>0){const e=this.molecule.atoms[0];if("V"===e.isotope&&null!==e.batchId){const t=this.molecule.getIsotopes("V"),s=t[t.length-1];if(e.batchId!==s.batchId)throw new ce;for(const e of t)if(null===e.batchId)throw new ce}return!0}throw new ce}isotopeI(){for(let e of this.molecule.getIsotopes("I")){if("USER"!==e.token)throw new ue(`Check::isotopeI() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(0===e.index)throw new z(`Check::isotopeI() - Isotope "${e.isotope}" Atoms must have a non-zero index!`)}return!0}isotopeU(){for(let e of this.molecule.getIsotopes("U")){if("AUTH"!==e.token)throw new ue(`Check::isotopeU() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(0!==e.index)throw new z(`Check::isotopeU() - Isotope "${e.isotope}" Atoms must have an index equal to 0!`)}return!0}isotopeM(){const e=["readPolicy","writePolicy"];for(let t of this.molecule.getIsotopes("M")){if(t.meta.length<1)throw new oe;if("USER"!==t.token)throw new ue(`Check::isotopeM() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);const s=B.aggregateMeta(t.meta);for(const t of e){let n=s[t];if(n){n=JSON.parse(n);for(const[t,a]of Object.entries(n))if(!e.includes(t)){if(!Object.keys(s).includes(t))throw new Y(`${t} is missing from the meta.`);for(const e of a)if(!D.isBundleHash(e)&&!["all","self"].includes(e))throw new Y(`${e} does not correspond to the format of the policy.`)}}}}return!0}isotopeC(){for(let e of this.molecule.getIsotopes("C")){if("USER"!==e.token)throw new ue(`Check::isotopeC() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(0!==e.index)throw new z(`Check::isotopeC() - Isotope "${e.isotope}" Atoms must have an index equal to 0!`)}return!0}isotopeT(){for(let e of this.molecule.getIsotopes("T")){const t=e.aggregatedMeta();if("wallet"===String(e.metaType).toLowerCase())for(let e of["position","bundle"])if(!t.hasOwnProperty(e)||!Boolean(t[e]))throw new oe(`Check::isotopeT() - Required meta field "${e}" is missing!`);for(let e of["token"])if(!t.hasOwnProperty(e)||!Boolean(t[e]))throw new oe(`Check::isotopeT() - Required meta field "${e}" is missing!`);if("USER"!==e.token)throw new ue(`Check::isotopeT() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(0!==e.index)throw new z(`Check::isotopeT() - Isotope "${e.isotope}" Atoms must have an index equal to 0!`)}return!0}isotopeR(){for(let e of this.molecule.getIsotopes("R")){const t=e.aggregatedMeta();if(t.policy){const e=JSON.parse(t.policy);if(!Object.keys(e).every((e=>["read","write"].includes(e))))throw new oe("Check::isotopeR() - Mixing rules with politics!")}if(t.rule){const e=JSON.parse(t.rule);if(!Array.isArray(e))throw new oe("Check::isotopeR() - Incorrect rule format!");for(const t of e)ge.toObject(t);if(e.length<1)throw new oe("Check::isotopeR() - No rules!")}}return!0}isotopeV(e=null){const t=this.molecule.getIsotopes("V");if(0===t.length)return!0;const s=this.molecule.atoms[0];if("V"===s.isotope&&2===t.length){const e=t[t.length-1];if(s.token!==e.token)throw new ae;if(e.value<0)throw new ne;return!0}let n=0,a=0;for(let e in this.molecule.atoms)if(this.molecule.atoms.hasOwnProperty(e)){const t=this.molecule.atoms[e];if("V"!==t.isotope)continue;if(a=1*t.value,Number.isNaN(a))throw new TypeError('Invalid isotope "V" values');if(t.token!==s.token)throw new ae;if(e>0){if(a<0)throw new ne;if(t.walletAddress===s.walletAddress)throw new re}n+=a}if(n!==a)throw new le;if(e){if(a=1*s.value,Number.isNaN(a))throw new TypeError('Invalid isotope "V" values');const t=1*e.balance+1*a;if(t<0)throw new se;if(t!==n)throw new ie}else if(0!==a)throw new ie;return!0}molecularHash(){if(this.molecule.molecularHash!==R.hashAtoms({atoms:this.molecule.atoms}))throw new G;return!0}ots(){const e=this.molecule.normalizedHash();let s=this.molecule.atoms.map((e=>e.otsFragment)).reduce(((e,t)=>e+t));if(2048!==s.length&&(s=C(s),2048!==s.length))throw new ee;const n=A(s,128);let a="";for(const s in n){let i=n[s];for(let n=0,a=8+e[s];n<a;n++)i=t.shake256.create(512).update(i).hex();a+=i}const i=t.shake256.create(8192).update(a).hex(),r=t.shake256.create(256).update(i).hex();let l=this.molecule.atoms[0],o=l.walletAddress,u=ke.get(l.aggregatedMeta(),"signingWallet");if(u&&(o=ke.get(JSON.parse(u),"address")),r!==o)throw new te;return!0}}class _e extends L{constructor(e="Insufficient balance for requested transfer",t=null,s=null){super(e,t,s),this.name="BalanceInsufficientException"}}class fe extends L{constructor(e="Amount cannot be negative!",t=null,s=null){super(e,t,s),this.name="NegativeAmountException"}}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||D.create({secretOrBundle:e,token:t.token,batchId:t.batchId,characters:t.characters})),this.clear()}static isotopeFilter(e,t){return Array.isArray(e)||(e=[e]),t.filter((t=>e.includes(t.isotope)))}getIsotopes(e){return we.isotopeFilter(e,this.atoms)}static generateNextAtomIndex(e){return e.length}generateIndex(){return we.generateNextAtomIndex(this.atoms)}fill(e){for(let t in Object.keys(e))this[t]=e[t]}addAtom(e){return this.molecularHash=null,e.index=this.generateIndex(),this.atoms.push(e),this.atoms=R.sortAtoms(this.atoms),this}addContinuIdAtom(){return this.addAtom(R.create({isotope:"I",wallet:this.remainderWallet,metaType:"walletBundle",metaId:this.remainderWallet.bundle})),this}addPolicyAtom({metaType:e,metaId:t,meta:s={},policy:n={}}){let a=new j(s);return a.addPolicy(n),this.addAtom(R.create({isotope:"R",metaType:e,metaId:t,meta:a})),this}fuseToken(e,t){let s=e.length;if(this.sourceWallet.balance-s<0)throw new _e;return this.addAtom(R.create({isotope:"V",wallet:this.sourceWallet,value:-s})),this.addAtom(R.create({isotope:"F",wallet:t,value:1,metaType:"walletBundle",metaId:t.bundle})),this.addAtom(R.create({isotope:"V",wallet:this.remainderWallet,value:this.sourceWallet.balance-s,metaType:"walletBundle",metaId:this.remainderWallet.bundle})),this}burnToken({amount:e,walletBundle:t=null}){if(e<0)throw new fe("Molecule::burnToken() - Amount to burn must be positive!");if(this.sourceWallet.balance-e<0)throw new _e;return this.molecularHash=null,this.addAtom(R.create({isotope:"V",wallet:this.sourceWallet,value:-e})),this.addAtom(R.create({isotope:"V",wallet:this.remainderWallet,value:this.sourceWallet.balance-e,metaType:"walletBundle",metaId:this.remainderWallet.bundle})),this}replenishToken({amount:e,units:t=[]}){if(e<0)throw new fe("Molecule::replenishToken() - Amount to replenish must be positive!");if(t.length){t=D.getTokenUnits(t),this.remainderWallet.tokenUnits=this.sourceWallet.tokenUnits;for(const e of t)this.remainderWallet.tokenUnits.push(e);this.remainderWallet.balance=this.remainderWallet.tokenUnits.length,this.sourceWallet.tokenUnits=t,this.sourceWallet.balance=this.sourceWallet.tokenUnits.length}else this.remainderWallet.balance=this.sourceWallet.balance+e,this.sourceWallet.balance=e;return this.molecularHash=null,this.addAtom(R.create({isotope:"V",wallet:this.sourceWallet,value:this.sourceWallet.balance})),this.addAtom(R.create({isotope:"V",wallet:this.remainderWallet,value:this.remainderWallet.balance,metaType:"walletBundle",metaId:this.remainderWallet.bundle})),this}initValue({recipientWallet:e,amount:t}){if(this.sourceWallet.balance-t<0)throw new _e;return this.molecularHash=null,this.addAtom(R.create({isotope:"V",wallet:this.sourceWallet,value:-t})),this.addAtom(R.create({isotope:"V",wallet:e,value:t,metaType:"walletBundle",metaId:e.bundle})),this.addAtom(R.create({isotope:"V",wallet:this.remainderWallet,value:this.sourceWallet.balance-t,metaType:"walletBundle",metaId:this.remainderWallet.bundle})),this}initDepositBuffer({amount:e,tradeRates:t}){if(this.sourceWallet.balance-e<0)throw new _e;let s=D.create({secretOrBundle:this.secret,token:this.sourceWallet.token,batchId:this.sourceWallet.batchId});return s.tradeRates=t,this.molecularHash=null,this.addAtom(R.create({isotope:"V",wallet:this.sourceWallet,value:-e})),this.addAtom(R.create({isotope:"B",wallet:s,value:e,metaType:"walletBundle",metaId:this.sourceWallet.bundle})),this.addAtom(R.create({isotope:"V",wallet:this.remainderWallet,value:this.sourceWallet.balance-e,metaType:"walletBundle",metaId:this.sourceWallet.bundle})),this}initWithdrawBuffer({recipients:e,signingWallet:t=null}){let s=0;for(const[t,n]of Object.entries(e||{}))s+=n;if(this.sourceWallet.balance-s<0)throw new _e;let n=new j;t&&n.addSigningWallet(t),this.addAtom(R.create({isotope:"B",wallet:this.sourceWallet,value:-s,meta:n,metaType:"walletBundle",metaId:this.sourceWallet.bundle}));for(const[t,s]of Object.entries(e||{}))this.addAtom(new R({isotope:"V",token:this.sourceWallet.token,value:s,batchId:this.sourceWallet.batchId?Q({}):null,metaType:"walletBundle",metaId:t}));return this.addAtom(R.create({isotope:"B",wallet:this.remainderWallet,value:this.sourceWallet.balance-s,metaType:"walletBundle",metaId:this.remainderWallet.bundle})),this}initWalletCreation(e){this.molecularHash=null;let t=new j({address:e.address,token:e.token,bundle:e.bundle,position:e.position,amount:0,batchId:e.batchId});return this.addAtom(R.create({isotope:"C",wallet:this.sourceWallet,metaType:"wallet",metaId:e.address,meta:t})),this.addContinuIdAtom(),this}initTokenCreation({recipientWallet:e,amount:t,meta:s}){this.molecularHash=null;for(const t of["walletAddress","walletPosition","walletPubkey","walletCharacters"])s[t]||(s[t]=e[t.toLowerCase().substring(6)]);return this.addAtom(R.create({isotope:"C",wallet:this.sourceWallet,value:t,metaType:"token",metaId:e.token,meta:new j(s),batchId:e.batchId})),this.addContinuIdAtom(),this}createRule({metaType:e,metaId:t,rule:s,policy:n={}}){const a=[];for(const e of s)a.push(e instanceof ge?e:ge.toObject(e));let i=new j({rule:JSON.stringify(a)});return i.addPolicy(n),this.addAtom(R.create({isotope:"R",wallet:this.sourceWallet,metaType:e,metaId:t,meta:i})),this.addContinuIdAtom(),this}initShadowWalletClaim({token:e,wallet:t}){let s={tokenSlug:e,walletAddress:t.address,walletPosition:t.position,pubkey:t.pubkey,characters:t.characters,batchId:t.batchId};return this.addAtom(R.create({isotope:"C",wallet:this.sourceWallet,metaType:"wallet",metaId:t.address,meta:new j(s)})),this.addContinuIdAtom(),this}initIdentifierCreation({type:e,contact:t,code:s}){const n={code:s,hash:K(t.trim())};return this.addAtom(R.create({isotope:"C",wallet:this.sourceWallet,metaType:"identifier",metaId:e,meta:new j(n)})),this.addContinuIdAtom(),this}initMeta({meta:e,metaType:t,metaId:s,policy:n}){return this.addAtom(R.create({isotope:"M",wallet:this.sourceWallet,metaType:t,metaId:s,meta:new j(e)})),this.addPolicyAtom({metaType:t,metaId:s,meta:e,policy:n}),this.addContinuIdAtom(),this}initTokenRequest({token:e,amount:t,metaType:s,metaId:n,meta:a={},batchId:i=null}){return a.token=e,this.addAtom(R.create({isotope:"T",wallet:this.sourceWallet,value:t,metaType:s,metaId:n,meta:new j(a),batchId:i})),this.addContinuIdAtom(),this}initAuthorization({meta:e}){return this.addAtom(R.create({isotope:"U",wallet:this.sourceWallet,meta:new j(e)})),this.addContinuIdAtom(),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 Z;e||(this.bundle=K(this.secret)),this.molecularHash=R.hashAtoms({atoms:this.atoms});const n=this.atoms[0];let a=n.position,i=ke.get(n.aggregatedMeta(),"signingWallet");if(i&&(a=ke.get(JSON.parse(i),"position")),!a)throw new ee("Signing wallet must have a position!");const r=A(D.generateKey({secret:this.secret,token:n.token,position:n.position}),128),l=this.normalizedHash();let o="";for(const e in r){let s=r[e];for(let n=0,a=8-l[e];n<a;n++)s=t.shake256.create(512).update(s).hex();o+=s}s&&(o=q(o));const u=A(o,Math.ceil(o.length/this.atoms.length));let c=null;for(let e=0,t=u.length;e<t;e++)this.atoms[e].otsFragment=u[e],c=this.atoms[e].position;return c}static jsonToObject(e){const t=Object.assign(new we({}),JSON.parse(e)),s=Object.keys(new we({}));if(!Array.isArray(t.atoms))throw new Z;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 Z("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=M(this);for(let t of["remainderWallet","secret","sourceWallet","cellSlugOrigin"])e.hasOwnProperty(t)&&delete e[t];return e}check(e=null){new be(this).verify(e)}normalizedHash(){return we.normalize(we.enumerate(this.molecularHash))}static enumerate(e){const t={0:-8,1:-7,2:-6,3:-5,4:-4,5:-3,6:-2,7:-1,8:0,9:1,a:2,b:3,c:4,d:5,e:6,f:7,g:8},s=[],n=e.toLowerCase().split("");for(let e=0,a=n.length;e<a;++e){const a=n[e];void 0!==t[a]&&(s[e]=t[a])}return s}static normalize(e){let t=e.reduce(((e,t)=>e+t));const s=t<0;for(;t<0||t>0;)for(const n of Object.keys(e)){if((s?e[n]<8:e[n]>-8)&&(s?(++e[n],++t):(--e[n],--t),0===t))break}return e}}const $e=10**18;class Se{static val(e){return Math.abs(e*$e)<1?0:e}static cmp(e,t,s=!1){const n=Se.val(e)*$e,a=Se.val(t)*$e;return Math.abs(n-a)<1?0:n>a?1:-1}static equal(e,t){return 0===Se.cmp(e,t)}}class Ie{static create(e,t){let s=new Ie(e);return s.setWallet(t),s}static restore(e,t){let s=new D({secret:t,token:"AUTH",position:e.wallet.position,characters:e.wallet.characters});return Ie.create({token:e.token,expiresAt:e.expiresAt,pubkey:e.pubkey,encrypt:e.encrypt},s)}constructor({token:e,expiresAt:t,encrypt:s,pubkey:n}){this.$__token=e,this.$__expiresAt=t,this.$__pubkey=n,this.$__encrypt=s}setWallet(e){this.$__wallet=e}getWallet(){return this.$__wallet}getSnapshot(){return{token:this.$__token,expiresAt:this.$__expiresAt,pubkey:this.$__pubkey,encrypt:this.$__encrypt,wallet:{position:this.$__wallet.position,characters:this.$__wallet.characters}}}getToken(){return this.$__token}getPubkey(){return this.$__pubkey}getExpireInterval(){return 1e3*this.$__expiresAt-Date.now()}isExpired(){return!this.$__expiresAt||this.getExpireInterval()<0}getAuthData(){return{token:this.getToken(),pubkey:this.getPubkey(),wallet:this.getWallet()}}}class Te extends L{constructor(e="GraphQL did not provide a valid response.",t=null,s=null){super(e,t,s),this.name="InvalidResponseException"}}class Ae extends L{constructor(e="Authorization token missing or invalid.",t=null,s=null){super(e,t,s),this.name="UnauthenticatedException"}}class xe{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(ke.has(this.$__response,this.errorKey)){const e=ke.get(this.$__response,this.errorKey);if(String(e).includes("Unauthenticated"))throw new Ae;throw new Te}this.init()}init(){}data(){if(!this.dataKey)return this.response();if(!ke.has(this.response(),this.dataKey))throw new Te;return ke.get(this.response(),this.dataKey)}response(){return this.$__response}payload(){return null}query(){return this.$__query}status(){return null}}class ve{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 xe({query:this,json:e})}createQuery({variables:e=null}){if(this.$__variables=this.compiledVariables(e),!this.uri())throw new pe("Query::createQuery() - Node URI was not initialized for this client instance!");if(null===this.$__query)throw new pe("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 qe extends xe{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 D({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 ve{constructor(e){super(e),this.$__query=h.gql`query ($bundle: String!) {
|
|
2
|
-
ContinuId(bundle: $bundle) {
|
|
3
|
-
address,
|
|
4
|
-
bundleHash,
|
|
5
|
-
tokenSlug,
|
|
6
|
-
position,
|
|
7
|
-
batchId,
|
|
8
|
-
characters,
|
|
9
|
-
pubkey,
|
|
10
|
-
amount,
|
|
11
|
-
createdAt
|
|
12
|
-
}
|
|
13
|
-
}`}createResponse(e){return new qe({query:this,json:e})}}class We extends xe{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 Be extends ve{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
|
-
WalletBundle( bundleHash: $bundleHash, bundleHashes: $bundleHashes, key: $key, keys: $keys, value: $value, values: $values, keys_values: $keys_values, latest: $latest, limit: $limit, order: $order ) {
|
|
15
|
-
bundleHash,
|
|
16
|
-
metas {
|
|
17
|
-
molecularHash,
|
|
18
|
-
position,
|
|
19
|
-
key,
|
|
20
|
-
value,
|
|
21
|
-
createdAt
|
|
22
|
-
},
|
|
23
|
-
createdAt
|
|
24
|
-
}
|
|
25
|
-
}`}createResponse(e){return new We({query:this,json:e})}static createVariables({bundleHash:e=null,key:t=null,value:s=null,latest:n=!0}){const a={latest:n};return e&&(a["string"==typeof e?"bundleHash":"bundleHashes"]=e),t&&(a["string"==typeof t?"key":"keys"]=t),s&&(a["string"==typeof s?"value":"values"]=s),a}}class Me extends xe{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.Wallet"})}static toClientWallet({data:e,secret:t=null}){let s;if(null===e.position||void 0===e.position?s=D.create({secretOrBundle:e.bundleHash,token:e.tokenSlug,batchId:e.batchId,characters:e.characters}):(s=new D({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),e.tokenUnits.length)for(let t of e.tokenUnits)s.tokenUnits.push(V.createFromGraphQL(t));if(e.tradeRates.length)for(let t of e.tradeRates)s.tradeRates[t.tokenSlug]=t.amount;return 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 Ue extends ve{constructor(e){super(e),this.$__query=h.gql`query( $address: String, $bundleHash: String, $token: String, $position: String, $unspent: Boolean ) {
|
|
26
|
-
Wallet( address: $address, bundleHash: $bundleHash, token: $token, position: $position, unspent: $unspent ) {
|
|
27
|
-
address,
|
|
28
|
-
bundleHash,
|
|
29
|
-
token {
|
|
30
|
-
name,
|
|
31
|
-
amount,
|
|
32
|
-
fungibility,
|
|
33
|
-
supply
|
|
34
|
-
},
|
|
35
|
-
molecules {
|
|
36
|
-
molecularHash,
|
|
37
|
-
createdAt
|
|
38
|
-
}
|
|
39
|
-
tokenSlug,
|
|
40
|
-
batchId,
|
|
41
|
-
position,
|
|
42
|
-
amount,
|
|
43
|
-
characters,
|
|
44
|
-
pubkey,
|
|
45
|
-
createdAt,
|
|
46
|
-
tokenUnits {
|
|
47
|
-
id,
|
|
48
|
-
name,
|
|
49
|
-
metas
|
|
50
|
-
},
|
|
51
|
-
tradeRates {
|
|
52
|
-
tokenSlug,
|
|
53
|
-
amount
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
}`}createResponse(e){return new Me({query:this,json:e})}}class Oe extends xe{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 He extends ve{constructor(e){super(e),this.$__query=h.gql`query( $address: String, $bundleHash: String, $type: String, $token: String, $position: String ) {
|
|
57
|
-
Balance( address: $address, bundleHash: $bundleHash, type: $type, token: $token, position: $position ) {
|
|
58
|
-
address,
|
|
59
|
-
bundleHash,
|
|
60
|
-
type,
|
|
61
|
-
tokenSlug,
|
|
62
|
-
batchId,
|
|
63
|
-
position,
|
|
64
|
-
amount,
|
|
65
|
-
characters,
|
|
66
|
-
pubkey,
|
|
67
|
-
createdAt,
|
|
68
|
-
tokenUnits {
|
|
69
|
-
id,
|
|
70
|
-
name,
|
|
71
|
-
metas
|
|
72
|
-
},
|
|
73
|
-
tradeRates {
|
|
74
|
-
tokenSlug,
|
|
75
|
-
amount
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
}`}createResponse(e){return new Oe({query:this,json:e})}}class je extends xe{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 Re extends ve{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 ) {
|
|
79
|
-
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 ) {
|
|
80
|
-
metaType,
|
|
81
|
-
instanceCount {
|
|
82
|
-
key,
|
|
83
|
-
value
|
|
84
|
-
},
|
|
85
|
-
instances {
|
|
86
|
-
metaType,
|
|
87
|
-
metaId,
|
|
88
|
-
createdAt,
|
|
89
|
-
metas(latest:$latest) {
|
|
90
|
-
molecularHash,
|
|
91
|
-
position,
|
|
92
|
-
key,
|
|
93
|
-
value,
|
|
94
|
-
createdAt
|
|
95
|
-
}
|
|
96
|
-
},
|
|
97
|
-
paginatorInfo {
|
|
98
|
-
currentPage,
|
|
99
|
-
total
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
}`}createResponse(e){return new je({query:this,json:e})}static createVariables({metaType:e=null,metaId:t=null,key:s=null,value:n=null,latest:a=null,latestMetas:i=!0,filter:r=null,queryArgs:l=null,count:o=null,countBy:u=null}){const c={};return e&&(c["string"==typeof e?"metaType":"metaTypes"]=e),t&&(c["string"==typeof t?"metaId":"metaIds"]=t),s&&(c["string"==typeof s?"key":"keys"]=s),n&&(c["string"==typeof n?"value":"values"]=n),a&&(c.latest=!!a),i&&(c.latestMetas=!!i),r&&(c.filter=r),l&&(void 0!==l.limit&&0!==l.limit||(l.limit="*"),c.queryArgs=l),o&&(c.count=o),u&&(c.countBy=u),c}}class Ee extends ve{constructor(e){super(e),this.$__query=h.gql`query( $batchId: String ) {
|
|
103
|
-
Batch( batchId: $batchId ) {
|
|
104
|
-
${Ee.getFields()},
|
|
105
|
-
children {
|
|
106
|
-
${Ee.getFields()}
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
}`}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 xe({query:this,json:e});return t.dataKey="data.Batch",t}}class Ke extends ve{constructor(e){super(e),this.$__query=h.gql`query( $batchId: String ) {
|
|
110
|
-
BatchHistory( batchId: $batchId ) {
|
|
111
|
-
${Ee.getFields()}
|
|
112
|
-
}
|
|
113
|
-
}`}createResponse(e){let t=new xe({query:this,json:e});return t.dataKey="data.BatchHistory",t}}class Qe extends xe{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.ProposeMolecule"}),this.$__clientMolecule=e.molecule()}init(){const e=ke.get(this.data(),"payload");try{this.$__payload="[object String]"===Object.prototype.toString.call(e)?JSON.parse(e):e}catch(e){this.$__payload=null}}clientMolecule(){return this.$__clientMolecule}molecule(){const e=this.data();if(!e)return null;const t=new we({});return t.molecularHash=ke.get(e,"molecularHash"),t.status=ke.get(e,"status"),t.createdAt=ke.get(e,"createdAt"),t}success(){return"accepted"===this.status()}status(){return ke.get(this.data(),"status","rejected")}reason(){return ke.get(this.data(),"reason","Invalid response from server")}payload(){return this.$__payload}}class Pe extends ve{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 Ne extends Pe{constructor(e,t=null){super(e),this.$__molecule=t,this.$__remainderWallet=null,this.$__query=h.gql`mutation( $molecule: MoleculeInput! ) {
|
|
114
|
-
ProposeMolecule( molecule: $molecule ) {
|
|
115
|
-
molecularHash,
|
|
116
|
-
height,
|
|
117
|
-
depth,
|
|
118
|
-
status,
|
|
119
|
-
reason,
|
|
120
|
-
payload,
|
|
121
|
-
createdAt,
|
|
122
|
-
receivedAt,
|
|
123
|
-
processedAt,
|
|
124
|
-
broadcastedAt,
|
|
125
|
-
}
|
|
126
|
-
}`}compiledVariables(e){return{...super.compiledVariables(e),molecule:this.molecule()}}createResponse(e){return new Qe({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 Fe extends Qe{payloadKey(e){if(!ke.has(this.payload(),e))throw new Te(`ResponseRequestAuthorization::payloadKey() - '${e}' key was not found in the payload!`);return ke.get(this.payload(),e)}token(){return this.payloadKey("token")}time(){return this.payloadKey("time")}encrypt(){return this.payloadKey("encrypt")}pubKey(){return this.payloadKey("key")}}class Ve extends Ne{fillMolecule({meta:e}){this.$__molecule.initAuthorization({meta:e}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Fe({query:this,json:e})}}class Je extends Qe{}class De extends Ne{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 Je({query:this,json:e})}}class Le extends Qe{}class ze extends Ne{fillMolecule({token:e,amount:t,metaType:s,metaId:n,meta:a=null,batchId:i=null}){this.$__molecule.initTokenRequest({token:e,amount:t,metaType:s,metaId:n,meta:a||{},batchId:i}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Le({query:this,json:e})}}class Ze extends Qe{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 Ge extends Ne{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 Ze({query:this,json:e})}}class Xe extends Qe{}class Ye extends Ne{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 Xe({query:this,json:e})}}class et extends Qe{}class tt extends Ne{fillMolecule({token:e,batchId:t=null}){let s=D.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 et({query:this,json:e})}}class st extends Qe{}class nt extends Ne{fillMolecule({metaType:e,metaId:t,meta:s,policy:n}){this.$__molecule.initMeta({meta:s,metaType:e,metaId:t,policy:n}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new st({query:this,json:e})}}class at extends Qe{}class it extends Ne{fillMolecule(e){this.$__molecule.initWalletCreation(e),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new at({query:this,json:e})}}class rt extends xe{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.AccessToken"})}reason(){return"Invalid response from server"}success(){return null!==this.payload()}payload(){return this.data()}payloadKey(e){if(!ke.has(this.payload(),e))throw new Te(`ResponseAuthorizationGuest::payloadKey() - '${e}' key is not found in the payload!`);return ke.get(this.payload(),e)}token(){return this.payloadKey("token")}time(){return this.payloadKey("time")}pubKey(){return this.payloadKey("key")}encrypt(){return this.payloadKey("encrypt")}}class lt extends Pe{constructor(e){super(e),this.$__query=h.gql`mutation( $cellSlug: String, $pubkey: String, $encrypt: Boolean ) {
|
|
127
|
-
AccessToken( cellSlug: $cellSlug, pubkey: $pubkey, encrypt: $encrypt ) {
|
|
128
|
-
token,
|
|
129
|
-
pubkey,
|
|
130
|
-
expiresAt
|
|
131
|
-
}
|
|
132
|
-
}`}createResponse(e){return new rt({query:this,json:e})}}class ot extends L{constructor(e="The shadow wallet does not exist",t=null,s=null){super(e,t,s),this.name="WalletShadowException"}}class ut extends L{constructor(e="Stackable tokens with unit IDs cannot have decimal places!",t=null,s=null){super(e,t,s),this.name="StackableUnitDecimalsException"}}class ct extends L{constructor(e="Stackable tokens with unit IDs cannot have decimal places!",t=null,s=null){super(e,t,s),this.name="StackableUnitAmountException"}}function ht(e){return e.query.definitions.find((e=>"OperationDefinition"===e.kind)).selectionSet.selections.find((e=>"Field"===e.kind)).name.value}function dt({graphQLErrors:e,networkError:t,operation:s,forward:n,response:a}){if(e&&e.map((({message:e,debugMessage:t,locations:s,path:n})=>console.error(`[GraphQL error]: ${e}\r\n`,` Message : ${t}\r\n`,` Path : ${n}\r\n`,` Location: ${s}\r\n`))),t){const{name:e,statusCode:s,result:n={}}=t;console.error(`[Network error]: ${e}, status code: ${s}`)}}class pt extends h.HttpLink{constructor(e){super(e)}request(e,t){return t(e)}}class mt extends h.ApolloLink{constructor({socketUri:e,authEndpoint:t,appKey:s="knishio"}){console.log("PusherLink::constructor()..."),super(),this.socketUri=e,this.authEndpoint=t,this.appKey=s,this.setAuthToken(""),this.setTransport(this.getSocketUri())}setTransport(e){console.log(`Connecting to socket endpoint ${e}...`);const t=g.parse(e);if(!["ws","wss"].includes(t.scheme))throw new pe("Incorrect scheme for the socket");this.transport=new I.default(this.appKey,{auth:{headers:{"X-Auth-Token":this.getAuthToken(),Accept:"application/json"}},wsHost:t.host,wsPort:t.port,forceTLS:"wss"===t.scheme,encrypted:!0,enabledTransports:[t.scheme],authEndpoint:this.authEndpoint})}disconnect(){this.transport.disconnect()}channel(e){return this.transport.channel(e)||null}getAuthToken(){return this.auth}setAuthToken(e){this.auth=e}getSocketUri(){return this.socketUri}request(e,t){this.transport.config.auth.headers["X-Auth-Token"]=this.getAuthToken();const s=new h.Observable((e=>{})),n=s.subscribe.bind(s);return s.subscribe=(s,a,i)=>{n(s,a,i);const r=function(e,t,s){return"function"==typeof e?{next:t=>e(t),error:e=>t&&t(e),complete:()=>s&&s()}:{next:t=>e.next&&e.next(t),error:t=>e.error&&e.error(t),complete:()=>e.complete&&e.complete()}}(s,a,i);let l;return t(e).subscribe({next:e=>{if(l=ke.get(e,"extensions.lighthouse_subscriptions.channel"),!l)return r.next(e),void r.complete();this.subscribeToChannel(l,r)}}),{closed:!1,unsubscribe:()=>{l&&this.unsubscribeFromChannel(l)}}},s}subscribeToChannel(e,t){this.transport.subscribe(e).bind("lighthouse-subscription",(s=>{s.more||(this.unsubscribeFromChannel(e),t.complete());const n=s.result;n&&t.next(n)}))}unsubscribeFromChannel(e){this.transport.unsubscribe(e)}}class yt 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 gt 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=ht(e),n=function(e){return e.query.definitions.find((e=>"OperationDefinition"===e.kind)).operation}(e),a="mutation"===n&&"ProposeMolecule"===s,i=["query"===n&&["__schema","ContinuId"].includes(s),"mutation"===n&&"AccessToken"===s,a&&"U"===ke.get(e,"variables.molecule.atoms.0.isotope")],r={query:k.print(e.query),variables:JSON.stringify(e.variables)},l=this.getWallet(),o=this.getPubKey();for(const s in i)if(i[s])return t(e);if(!o)throw new pe("CipherLink::request() - Node public key missing!");if(!l)throw new pe("CipherLink::request() - Authorized wallet missing!");return e.operationName=null,e.query=h.gql`query ( $Hash: String! ) { CipherHash ( Hash: $Hash ) { hash } }`,e.variables={Hash:JSON.stringify(l.encryptMessage(r,o))},t(e).map((e=>{let t=e.data;if(t.data&&(t=t.data),t.CipherHash&&t.CipherHash.hash){const e=JSON.parse(t.CipherHash.hash),s=l.decryptMessage(e);if(null===s)throw new pe("CipherLink::request() - Unable to decrypt response!");return s}return e}))}}class kt extends h.ApolloClient{constructor({serverUri:e,soketi:t=null,encrypt:s=!1}){const n={socketUri:null,appKey:"knishio",...t||{}},a=[],i=new pt({uri:e,fetch:S.default,transportBatching:!0}),r=new yt;let l=null,o=null;if(a.push(r),s&&(l=new gt,a.push(l)),n&&n.socketUri){const t=g.parse(e);o=new mt({socketUri:n.socketUri,authEndpoint:`${t.scheme}://${t.host}/graphql/subscriptions/auth`,appKey:n.appKey}),a.push(o)}a.push(h.concat(m.onError(dt),i)),super({link:h.from(a),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.__soketi=n,this.__authLink=r,this.__socket=o,this.__cipherLink=l,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.__socket&&this.__socket.setAuthToken(e),this.__cipherLink&&(this.__cipherLink.setWallet(this.__wallet),this.__cipherLink.setPubKey(this.__pubkey))}socketDisconnect(){this.__socket&&this.__socket.disconnect()}unsubscribeFromChannel(e){this.__socket&&this.__socket.unsubscribeFromChannel(e)}getServerUri(){return this.__serverUri}getSocketUri(){return this.__soketi.socketUri}}class bt{constructor({serverUri:e,socket:t=null,encrypt:s=!1}){this.$__subscribers={},this.$__uri=e,this.$__socket={socketUri:null,appKey:"knishio",...t||{}},this.$__client=null,this.restartTransport(s)}restartTransport(e=!1){const t=new kt({serverUri:this.$__uri,soketi:this.$__socket,encrypt:e});this.$__client&&(t.setAuthData({token:this.$__client.getAuthToken(),pubkey:this.$__client.getPubKey(),wallet:this.$__client.getWallet()}),this.socketDisconnect()),this.$__client=t}setEncryption(e=!1){this.restartTransport(e)}unsubscribe(e){this.$__subscribers.hasOwnProperty(e)&&(this.$__subscribers[e].unsubscribe(),this.$__client.unsubscribeFromChannel(e),delete this.$__subscribers[e])}unsubscribeAll(){for(let e in this.$__subscribers)this.unsubscribe(e)}socketDisconnect(){this.$__client.socketDisconnect(),this.$__subscribers={}}subscribe(e,t){const s=ht(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.$__socket?this.$__socket.socketUri:null}setSocketUri({socketUri:e,appKey:t}){this.$__socket=arguments.length?arguments[0]:this.$__socket}}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 pe("Subscribe::createSubscribe() - Node URI was not initialized for this client instance!");if(null===this.$__subscribe)throw new pe("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 pe(`${this.constructor.name}::execute() - closure parameter is required!`);return this.$__request=this.createSubscribe({variables:e}),this.client.subscribe(this.$__request,t)}compiledVariables(e=null){return e||{}}uri(){return this.client.getUri()}variables(){return this.$__variables}}class ft extends _t{constructor(e){super(e),this.$__subscribe=h.gql`
|
|
133
|
-
subscription onCreateMolecule ( $bundle: String! ) {
|
|
134
|
-
CreateMolecule( bundle: $bundle ) {
|
|
135
|
-
molecularHash,
|
|
136
|
-
cellSlug,
|
|
137
|
-
counterparty,
|
|
138
|
-
bundleHash,
|
|
139
|
-
status,
|
|
140
|
-
local,
|
|
141
|
-
height,
|
|
142
|
-
depth,
|
|
143
|
-
createdAt,
|
|
144
|
-
receivedAt,
|
|
145
|
-
processedAt,
|
|
146
|
-
broadcastedAt,
|
|
147
|
-
reason,
|
|
148
|
-
reasonPayload,
|
|
149
|
-
payload,
|
|
150
|
-
status,
|
|
151
|
-
atoms {
|
|
152
|
-
molecularHash,
|
|
153
|
-
position,
|
|
154
|
-
isotope,
|
|
155
|
-
walletAddress,
|
|
156
|
-
tokenSlug,
|
|
157
|
-
batchId,
|
|
158
|
-
value,
|
|
159
|
-
index,
|
|
160
|
-
metaType,
|
|
161
|
-
metaId,
|
|
162
|
-
metasJson,
|
|
163
|
-
otsFragment,
|
|
164
|
-
createdAt,
|
|
165
|
-
metas {
|
|
166
|
-
molecularHash,
|
|
167
|
-
position,
|
|
168
|
-
metaType,
|
|
169
|
-
metaId,
|
|
170
|
-
key,
|
|
171
|
-
value,
|
|
172
|
-
createdAt,
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
`}}class wt extends _t{constructor(e){super(e),this.$__subscribe=h.gql`
|
|
178
|
-
subscription onWalletStatus ( $bundle: String!, $token: String! ) {
|
|
179
|
-
WalletStatus( bundle: $bundle, token: $token ) {
|
|
180
|
-
bundle,
|
|
181
|
-
token,
|
|
182
|
-
admission,
|
|
183
|
-
balance,
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
`}}class $t extends _t{constructor(e){super(e),this.$__subscribe=h.gql`
|
|
187
|
-
subscription onActiveWallet ( $bundle: String! ) {
|
|
188
|
-
ActiveWallet( bundle: $bundle ) {
|
|
189
|
-
address,
|
|
190
|
-
bundleHash,
|
|
191
|
-
walletBundle {
|
|
192
|
-
bundleHash,
|
|
193
|
-
slug,
|
|
194
|
-
createdAt,
|
|
195
|
-
},
|
|
196
|
-
tokenSlug,
|
|
197
|
-
token {
|
|
198
|
-
slug,
|
|
199
|
-
name,
|
|
200
|
-
fungibility,
|
|
201
|
-
supply,
|
|
202
|
-
decimals,
|
|
203
|
-
amount,
|
|
204
|
-
icon,
|
|
205
|
-
createdAt
|
|
206
|
-
},
|
|
207
|
-
batchId,
|
|
208
|
-
position,
|
|
209
|
-
characters,
|
|
210
|
-
pubkey,
|
|
211
|
-
amount,
|
|
212
|
-
createdAt,
|
|
213
|
-
metas {
|
|
214
|
-
molecularHash,
|
|
215
|
-
position,
|
|
216
|
-
metaType,
|
|
217
|
-
metaId,
|
|
218
|
-
key,
|
|
219
|
-
value,
|
|
220
|
-
createdAt,
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
`}}class St extends _t{constructor(e){super(e),this.$__subscribe=h.gql`
|
|
225
|
-
subscription onActiveUser ( $metaType: String!, $metaId: String! ) {
|
|
226
|
-
ActiveUser( metaType: $metaType, metaId: $metaId ) {
|
|
227
|
-
bundleHash,
|
|
228
|
-
metaType,
|
|
229
|
-
metaId,
|
|
230
|
-
jsonData,
|
|
231
|
-
createdAt,
|
|
232
|
-
updatedAt
|
|
233
|
-
}
|
|
234
|
-
}`}}class It extends xe{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.ActiveSession"})}}class Tt extends Pe{constructor(e){super(e),this.$__query=h.gql`mutation(
|
|
235
|
-
$bundleHash: String!,
|
|
236
|
-
$metaType: String!,
|
|
237
|
-
$metaId: String!,
|
|
238
|
-
$ipAddress: String,
|
|
239
|
-
$browser: String,
|
|
240
|
-
$osCpu: String,
|
|
241
|
-
$resolution: String,
|
|
242
|
-
$timeZone: String,
|
|
243
|
-
$json: String ) {
|
|
244
|
-
ActiveSession(
|
|
245
|
-
bundleHash: $bundleHash,
|
|
246
|
-
metaType: $metaType,
|
|
247
|
-
metaId: $metaId,
|
|
248
|
-
ipAddress: $ipAddress,
|
|
249
|
-
browser: $browser,
|
|
250
|
-
osCpu: $osCpu,
|
|
251
|
-
resolution: $resolution,
|
|
252
|
-
timeZone: $timeZone,
|
|
253
|
-
json: $json
|
|
254
|
-
) {
|
|
255
|
-
bundleHash,
|
|
256
|
-
metaType,
|
|
257
|
-
metaId,
|
|
258
|
-
jsonData,
|
|
259
|
-
createdAt,
|
|
260
|
-
updatedAt
|
|
261
|
-
}
|
|
262
|
-
}`}createResponse(e){return new It({query:this,json:e})}}class At extends xe{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.ActiveUser"})}payload(){const e=this.data();if(!e)return null;const t=[];for(let s of e){const e={...s};e.jsonData&&(e.jsonData=JSON.parse(e.jsonData)),e.createdAt&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt)),t.push(e)}return t}}class xt extends ve{constructor(e){super(e),this.$__query=h.gql`query ActiveUserQuery ($bundleHash:String, $metaType: String, $metaId: String) {
|
|
263
|
-
ActiveUser (bundleHash: $bundleHash, metaType: $metaType, metaId: $metaId) {
|
|
264
|
-
bundleHash,
|
|
265
|
-
metaType,
|
|
266
|
-
metaId,
|
|
267
|
-
jsonData,
|
|
268
|
-
createdAt,
|
|
269
|
-
updatedAt
|
|
270
|
-
}
|
|
271
|
-
}`}createResponse(e){return new At({query:this,json:e})}}class vt extends xe{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.UserActivity"})}payload(){const e=JSON.parse(JSON.stringify(this.data()));if(e.instances)for(const t of e.instances)t.jsonData=JSON.parse(t.jsonData);return e}}class qt extends ve{constructor(e){super(e),this.$__query=h.gql`query UserActivity (
|
|
272
|
-
$bundleHash:String,
|
|
273
|
-
$metaType: String,
|
|
274
|
-
$metaId: String,
|
|
275
|
-
$ipAddress: String,
|
|
276
|
-
$browser: String,
|
|
277
|
-
$osCpu: String,
|
|
278
|
-
$resolution: String,
|
|
279
|
-
$timeZone: String,
|
|
280
|
-
$countBy: [CountByUserActivity],
|
|
281
|
-
$interval: span
|
|
282
|
-
) {
|
|
283
|
-
UserActivity (
|
|
284
|
-
bundleHash: $bundleHash,
|
|
285
|
-
metaType: $metaType,
|
|
286
|
-
metaId: $metaId,
|
|
287
|
-
ipAddress: $ipAddress,
|
|
288
|
-
browser: $browser,
|
|
289
|
-
osCpu: $osCpu,
|
|
290
|
-
resolution: $resolution,
|
|
291
|
-
timeZone: $timeZone,
|
|
292
|
-
countBy: $countBy,
|
|
293
|
-
interval: $interval
|
|
294
|
-
) {
|
|
295
|
-
createdAt,
|
|
296
|
-
bundleHash,
|
|
297
|
-
metaType,
|
|
298
|
-
metaId,
|
|
299
|
-
instances {
|
|
300
|
-
bundleHash,
|
|
301
|
-
metaType,
|
|
302
|
-
metaId,
|
|
303
|
-
jsonData,
|
|
304
|
-
createdAt,
|
|
305
|
-
updatedAt
|
|
306
|
-
},
|
|
307
|
-
instanceCount {
|
|
308
|
-
...SubFields,
|
|
309
|
-
...Recursive
|
|
310
|
-
}
|
|
311
|
-
}
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
fragment SubFields on InstanceCountType {
|
|
315
|
-
id,
|
|
316
|
-
count
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
fragment Recursive on InstanceCountType {
|
|
320
|
-
instances {
|
|
321
|
-
...SubFields
|
|
322
|
-
instances {
|
|
323
|
-
...SubFields,
|
|
324
|
-
instances {
|
|
325
|
-
...SubFields
|
|
326
|
-
instances {
|
|
327
|
-
...SubFields
|
|
328
|
-
instances {
|
|
329
|
-
...SubFields
|
|
330
|
-
instances {
|
|
331
|
-
...SubFields
|
|
332
|
-
instances {
|
|
333
|
-
...SubFields
|
|
334
|
-
instances {
|
|
335
|
-
...SubFields
|
|
336
|
-
}
|
|
337
|
-
}
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
}`}createResponse(e){return new vt({query:this,json:e})}}class Ct extends ve{constructor(e){super(e),this.$__query=h.gql`query( $slug: String, $slugs: [ String! ], $limit: Int, $order: String ) {
|
|
345
|
-
Token( slug: $slug, slugs: $slugs, limit: $limit, order: $order ) {
|
|
346
|
-
slug,
|
|
347
|
-
name,
|
|
348
|
-
fungibility,
|
|
349
|
-
supply,
|
|
350
|
-
decimals,
|
|
351
|
-
amount,
|
|
352
|
-
icon,
|
|
353
|
-
}
|
|
354
|
-
}`}createResponse(e){return new xe({query:this,json:e,dataKey:"data.Token"})}}class Wt extends L{constructor(e="Authorization attempt rejected by ledger.",t=null,s=null){super(e,t,s),this.name="AuthorizationRejectedException"}}class Bt extends xe{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.Atom"})}payload(){const e=this.data();if(!e)return null;let t={instances:[],instanceCount:{},paginatorInfo:{}};if(e.instances){t.instances=e.instances;for(let e in t.instances){let s=t.instances[e];s.metasJson&&(t.instances[e].metas=JSON.parse(s.metasJson))}}return e.instanceCount&&(t.instanceCount=e.instanceCount),e.paginatorInfo&&(t.paginatorInfo=e.paginatorInfo),t}metas(){const e=this.payload(),t=[];if(e&&e.instances)for(const s of e.instances)s.metasJson&&t.push(JSON.parse(s.metasJson));return t}}class Mt extends ve{constructor(e){super(e),this.$__query=h.gql`query(
|
|
355
|
-
$molecularHashes: [String!],
|
|
356
|
-
$bundleHashes: [String!],
|
|
357
|
-
$positions:[String!],
|
|
358
|
-
$walletAddresses: [String!],
|
|
359
|
-
$isotopes: [String!],
|
|
360
|
-
$tokenSlugs: [String!],
|
|
361
|
-
$cellSlugs: [String!],
|
|
362
|
-
$batchIds: [String!],
|
|
363
|
-
$values: [String!],
|
|
364
|
-
$metaTypes: [String!],
|
|
365
|
-
$metaIds: [String!],
|
|
366
|
-
$indexes: [String!],
|
|
367
|
-
$filter: [ MetaFilter! ],
|
|
368
|
-
$latest: Boolean,
|
|
369
|
-
$queryArgs: QueryArgs,
|
|
370
|
-
) {
|
|
371
|
-
Atom(
|
|
372
|
-
molecularHashes: $molecularHashes,
|
|
373
|
-
bundleHashes: $bundleHashes,
|
|
374
|
-
positions: $positions,
|
|
375
|
-
walletAddresses: $walletAddresses,
|
|
376
|
-
isotopes: $isotopes,
|
|
377
|
-
tokenSlugs: $tokenSlugs,
|
|
378
|
-
cellSlugs: $cellSlugs,
|
|
379
|
-
batchIds: $batchIds,
|
|
380
|
-
values: $values,
|
|
381
|
-
metaTypes: $metaTypes,
|
|
382
|
-
metaIds: $metaIds,
|
|
383
|
-
indexes: $indexes,
|
|
384
|
-
filter: $filter,
|
|
385
|
-
latest: $latest,
|
|
386
|
-
queryArgs: $queryArgs,
|
|
387
|
-
) {
|
|
388
|
-
instances {
|
|
389
|
-
position,
|
|
390
|
-
walletAddress,
|
|
391
|
-
tokenSlug,
|
|
392
|
-
isotope,
|
|
393
|
-
index,
|
|
394
|
-
molecularHash,
|
|
395
|
-
metaId,
|
|
396
|
-
metaType,
|
|
397
|
-
metasJson,
|
|
398
|
-
batchId,
|
|
399
|
-
value,
|
|
400
|
-
bundleHashes,
|
|
401
|
-
cellSlugs,
|
|
402
|
-
createdAt,
|
|
403
|
-
otsFragment
|
|
404
|
-
},
|
|
405
|
-
paginatorInfo {
|
|
406
|
-
currentPage,
|
|
407
|
-
total
|
|
408
|
-
}
|
|
409
|
-
}
|
|
410
|
-
}`}createResponse(e){return new Bt({query:this,json:e})}static createVariables({molecularHashes:e,molecularHash:t,bundleHashes:s,bundleHash:n,positions:a,position:i,walletAddresses:r,walletAddress:l,isotopes:o,isotope:u,tokenSlugs:c,tokenSlug:h,cellSlugs:d,cellSlug:p,batchIds:m,batchId:y,values:g,value:k,metaTypes:b,metaType:_,metaIds:f,metaId:w,indexes:$,index:S,filter:I,latest:T,queryArgs:A}){return t&&(e=e||[]).push(t),n&&(s=s||[]).push(n),i&&(a=a||[]).push(i),l&&(r=r||[]).push(l),u&&(o=o||[]).push(u),h&&(c=c||[]).push(h),p&&(d=d||[]).push(p),y&&(m=m||[]).push(y),k&&(g=g||[]).push(k),_&&(b=b||[]).push(_),w&&(f=f||[]).push(w),S&&($=$||[]).push(S),{molecularHashes:e,bundleHashes:s,positions:a,walletAddresses:r,isotopes:o,tokenSlugs:c,cellSlugs:d,batchIds:m,values:g,metaTypes:b,metaIds:f,indexes:$,filter:I,latest:T,queryArgs:A}}}class Ut extends xe{constructor({query:e,json:t}){super({query:e,json:t}),this.dataKey="data.Policy",this.init()}payload(){const e=this.data();return e&&e.callback?JSON.parse(e.callback):null}}class Ot extends ve{constructor(e){super(e),this.$__query=h.gql`query( $metaType: String, $metaId: String, ) {
|
|
411
|
-
Policy( metaType: $metaType, metaId: $metaId ) {
|
|
412
|
-
molecularHash,
|
|
413
|
-
position,
|
|
414
|
-
metaType,
|
|
415
|
-
metaId,
|
|
416
|
-
conditions,
|
|
417
|
-
callback,
|
|
418
|
-
rule,
|
|
419
|
-
createdAt
|
|
420
|
-
}
|
|
421
|
-
}`}createResponse(e){return new Ut({query:this,json:e})}}class Ht extends xe{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.MetaTypeViaAtom"})}payload(){const e=this.data();if(!e||0===e.length)return null;let t={instances:{},instanceCount:{},paginatorInfo:{}},s=e.pop();return s.instances&&(t.instances=s.instances),s.instanceCount&&(t.instanceCount=s.instanceCount),s.paginatorInfo&&(t.paginatorInfo=s.paginatorInfo),t}}class jt extends ve{constructor(e){super(e),this.$__query=h.gql`query ($metaTypes: [String!], $metaIds: [String!], $values: [String!], $keys: [String!], $latest: Boolean, $filter: [MetaFilter!], $queryArgs: QueryArgs, $countBy: String, $atomValues: [String!] ) {
|
|
422
|
-
MetaTypeViaAtom(
|
|
423
|
-
metaTypes: $metaTypes
|
|
424
|
-
metaIds: $metaIds
|
|
425
|
-
atomValues: $atomValues
|
|
426
|
-
filter: $filter,
|
|
427
|
-
latest: $latest,
|
|
428
|
-
queryArgs: $queryArgs
|
|
429
|
-
countBy: $countBy
|
|
430
|
-
) {
|
|
431
|
-
metaType,
|
|
432
|
-
instanceCount {
|
|
433
|
-
key,
|
|
434
|
-
value
|
|
435
|
-
},
|
|
436
|
-
instances {
|
|
437
|
-
metaType,
|
|
438
|
-
metaId,
|
|
439
|
-
createdAt,
|
|
440
|
-
metas( values: $values, keys: $keys ) {
|
|
441
|
-
molecularHash,
|
|
442
|
-
position,
|
|
443
|
-
key,
|
|
444
|
-
value,
|
|
445
|
-
createdAt
|
|
446
|
-
}
|
|
447
|
-
},
|
|
448
|
-
paginatorInfo {
|
|
449
|
-
currentPage,
|
|
450
|
-
total
|
|
451
|
-
}
|
|
452
|
-
}
|
|
453
|
-
}`}createResponse(e){return new Ht({query:this,json:e})}static createVariables({metaType:e=null,metaId:t=null,key:s=null,value:n=null,keys:a=null,values:i=null,atomValues:r=null,latest:l=null,latestMetas:o=!0,filter:u=null,queryArgs:c=null,countBy:h=null}){const d={};return r&&(d.atomValues=r),a&&(d.keys=a),i&&(d.values=i),e&&(d.metaTypes="string"==typeof e?[e]:e),t&&(d.metaIds="string"==typeof t?[t]:t),h&&(d.countBy=h),u&&(d.filter=u),s&&n&&(d.filter=d.filter||[],d.filter.push({key:s,value:n,comparison:"="})),l&&(d.latest=!!l,d.latest=!!o),c&&(void 0!==c.limit&&0!==c.limit||(c.limit="*"),d.queryArgs=c),d}}class Rt extends Qe{}class Et extends Ne{fillMolecule({metaType:e,metaId:t,rule:s,policy:n}){this.$__molecule.createRule({metaType:e,metaId:t,rule:s,policy:n}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Rt({query:this,json:e})}}class Kt extends Ne{fillMolecule({amount:e,tradeRates:t}){this.$__molecule.initDepositBuffer({amount:e,tradeRates:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}}class Qt extends Ne{fillMolecule({recipients:e,signingWallet:t}){this.$__molecule.initWithdrawBuffer({recipients:e,signingWallet:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}}class Pt{constructor({uri:e,cellSlug:t=null,client:s=null,socket:n=null,serverSdkVersion:a=3,logging:i=!1}){this.initialize({uri:e,cellSlug:t,socket:n,client:s,serverSdkVersion:a,logging:i})}initialize({uri:e,cellSlug:t=null,socket:s=null,client:n=null,serverSdkVersion:a=3,logging:i=!1}){this.$__logging=i,this.$__uris="object"==typeof e?e:[e],this.$__authTokenObjects={},this.$__authInProcess=!1,t&&this.setCellSlug(t);for(let e in this.$__uris){let t=this.$__uris[e];this.$__authTokenObjects[t]=null}this.$__logging&&console.info(`KnishIOClient::initialize() - Initializing new Knish.IO client session for SDK version ${a}...`),this.reset(),this.$__client=n||new bt({socket:{socketUri:null,appKey:"knishio",...s||{}},serverUri:this.getRandomUri()}),this.$__serverSdkVersion=a}getRandomUri(){let e=Math.floor(Math.random()*this.$__uris.length);return this.$__uris[e]}switchEncryption(e){return this.$__encrypt!==e&&(this.$__logging&&console.info(`KnishIOClient::switchEncryption() - Forcing encryption ${e?"on":"off"} to match node...`),this.$__encrypt=e,this.$__client.setEncryption(e),!0)}deinitialize(){this.$__logging&&console.info("KnishIOClient::deinitialize() - Clearing the Knish.IO client session..."),this.reset()}subscribe(){if(!this.client().getSocketUri())throw new pe("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 Ae("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 Ae("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=D.generateKey({secret:this.getSecret(),token:e.token,position:e.position}):e=new D({secret:this.getSecret()}),e}getRemainderWallet(){return this.remainderWallet}async createMolecule({secret:e=null,sourceWallet:t=null,remainderWallet:s=null}){return this.$__logging&&console.info("KnishIOClient::createMolecule() - Creating a new molecule..."),e=e||this.getSecret(),!t&&this.lastMoleculeQuery&&"USER"===this.getRemainderWallet().token&&this.lastMoleculeQuery.response()&&this.lastMoleculeQuery.response().success()&&(t=this.getRemainderWallet()),null===t&&(t=await this.getSourceWallet()),this.remainderWallet=s||D.create({secretOrBundle:e,token:"USER",batchId:t.batchId,characters:t.characters}),new we({secret:e,sourceWallet:t,remainderWallet:this.getRemainderWallet(),cellSlug:this.cellSlug()})}createQuery(e){return new e(this.client())}createSubscribe(e){return new e(this.subscribe())}async createMoleculeMutation({mutationClass:e,molecule:t=null}){this.$__logging&&console.info(`KnishIOClient::createMoleculeQuery() - Creating a new ${e.name} query...`);let s=t||await this.createMolecule({});const n=new e(this.client(),s);if(!(n instanceof Ne))throw new pe(`${this.constructor.name}::createMoleculeMutation() - This method only accepts MutationProposeMolecule!`);return this.lastMoleculeQuery=n,n}async executeQuery(e,t=null){return this.$__authToken&&this.$__authToken.isExpired()&&(console.info("KnishIOClient::executeQuery() - Access token is expired. Getting new one..."),await this.requestAuthToken({secret:this.$__secret,cellSlug:this.$__cellSlug,encrypt:this.$__encrypt})),e.execute({variables:t})}async queryBalance({token:e,bundle:t=null,type:s="regular"}){const n=this.createQuery(He);return this.executeQuery(n,{bundleHash:t||this.getBundle(),token:e,type:s})}async querySourceWallet({token:e,amount:t,type:s="regular"}){let n=(await this.queryBalance({token:e,type:s})).payload();if(null===n||Se.cmp(n.balance,t)<0)throw new se;if(!n.position||!n.address)throw new se("Source wallet can not be a shadow wallet.");return n}async subscribeCreateMolecule({bundle:e,closure:t}){const s=this.createSubscribe(ft);return await s.execute({variables:{bundle:e||this.getBundle()},closure:t})}subscribeWalletStatus({bundle:e,token:t,closure:s}){if(!t)throw new pe(`${this.constructor.name}::subscribeWalletStatus() - Token parameter is required!`);return this.createSubscribe(wt).execute({variables:{bundle:e||this.getBundle(),token:t},closure:s})}subscribeActiveWallet({bundle:e,closure:t}){return this.createSubscribe($t).execute({variables:{bundle:e||this.getBundle()},closure:t})}subscribeActiveSession({metaType:e,metaId:t,closure:s}){return this.createSubscribe(St).execute({variables:{metaType:e,metaId:t},closure:s})}unsubscribe(e){this.subscribe().unsubscribe(e)}unsubscribeAll(){this.subscribe().unsubscribeAll()}queryMeta({metaType:e,metaId:t=null,key:s=null,value:n=null,latest:a=null,latestMetas:i=null,fields:r=null,filter:l=null,queryArgs:o=null,count:u=null,countBy:c=null,throughAtom:h=!1,values:d=null,keys:p=null,atomValues:m=null}){let y,g;return this.$__logging&&console.info(`KnishIOClient::queryMeta() - Querying metaType: ${e}, metaId: ${t}...`),h?(y=this.createQuery(jt),g=jt.createVariables({metaType:e,metaId:t,key:s,value:n,latest:a,latestMetas:i,filter:l,queryArgs:o,countBy:c,values:d,keys:p,atomValues:m})):(y=this.createQuery(Re),g=Re.createVariables({metaType:e,metaId:t,key:s,value:n,latest:a,latestMetas:i,filter:l,queryArgs:o,count:u,countBy:c})),this.executeQuery(y,g).then((e=>e.payload()))}queryMetaInstance({metaType:e,metaId:t=null,key:s=null,value:n=null,latest:a=null,filter:i=null,fields:r=null}){this.$__logging&&console.info(`KnishIOClient::queryMetaInstance() - Querying metaType: ${e}, metaId: ${t}...`);const l=this.createQuery(Re),o={metaType:e,metaIds:[t],keys:[s],values:[n],latest:a,filter:i};return this.executeQuery(l,o).then((e=>e.data()))}async queryBatch({batchId:e}){this.$__logging&&console.info(`KnishIOClient::queryBatch() - Querying cascading meta instances for batchId: ${e}...`);const t=this.createQuery(Ee);return await this.executeQuery(t,{batchId:e})}async queryBatchHistory({batchId:e}){this.$__logging&&console.info(`KnishIOClient::queryBatchHistory() - Querying cascading meta instances for batchId: ${e}...`);const t=this.createQuery(Ke);return await this.executeQuery(t,{batchId:e})}async queryAtom({molecularHashes:e,molecularHash:t,bundleHashes:s,bundleHash:n,positions:a,position:i,walletAddresses:r,walletAddress:l,isotopes:o,isotope:u,tokenSlugs:c,tokenSlug:h,cellSlugs:d,cellSlug:p,batchIds:m,batchId:y,values:g,value:k,metaTypes:b,metaType:_,metaIds:f,metaId:w,indexes:$,index:S,filter:I,latest:T,queryArgs:A={limit:15,offset:1}}){this.$__logging&&console.info("KnishIOClient::queryAtom() - Querying atom instances");const x=this.createQuery(Mt);return await this.executeQuery(x,Mt.createVariables({molecularHashes:e,molecularHash:t,bundleHashes:s,bundleHash:n,positions:a,position:i,walletAddresses:r,walletAddress:l,isotopes:o,isotope:u,tokenSlugs:c,tokenSlug:h,cellSlugs:d,cellSlug:p,batchIds:m,batchId:y,values:g,value:k,metaTypes:b,metaType:_,metaIds:f,metaId:w,indexes:$,index:S,filter:I,latest:T,queryArgs:A}))}async createWallet({token:e}){const t=new D({secret:this.getSecret(),token:e}),s=await this.createMoleculeMutation({mutationClass:it});return s.fillMolecule(t),await this.executeQuery(s)}async queryActiveSession({bundleHash:e,metaType:t,metaId:s}){const n=this.createQuery(xt);return await this.executeQuery(n,{bundleHash:e,metaType:t,metaId:s})}async queryUserActivity({bundleHash:e,metaType:t,metaId:s,ipAddress:n,browser:a,osCpu:i,resolution:r,timeZone:l,countBy:o,interval:u}){const c=this.createQuery(qt);return await this.executeQuery(c,{bundleHash:e,metaType:t,metaId:s,ipAddress:n,browser:a,osCpu:i,resolution:r,timeZone:l,countBy:o,interval:u})}async activeSession({bundle:e,metaType:t,metaId:s,ipAddress:n,browser:a,osCpu:i,resolution:r,timeZone:l,json:o={}}){const u=this.createQuery(Tt);return await this.executeQuery(u,{bundleHash:e,metaType:t,metaId:s,ipAddress:n,browser:a,osCpu:i,resolution:r,timeZone:l,json:JSON.stringify(o)})}async createToken({token:e,amount:t=null,meta:s=null,batchId:n=null,units:a=[]}){const i=ke.get(s||{},"fungibility");if("stackable"===i&&(s.batchId=n||Q({})),["nonfungible","stackable"].includes(i)&&a.length>0){if(ke.get(s||{},"decimals")>0)throw new ut;if(t>0)throw new ct;t=a.length,s.splittable=1,s.decimals=0,s.tokenUnits=JSON.stringify(a)}const r=new D({secret:this.getSecret(),token:e,batchId:n}),l=await this.createMoleculeMutation({mutationClass:De});return l.fillMolecule({recipientWallet:r,amount:t,meta:s||{}}),await this.executeQuery(l)}async createRule({metaType:e,metaId:t,rule:s,policy:n={}}){const a=await this.createMoleculeMutation({mutationClass:Et,molecule:await this.createMolecule({secret:this.getSecret(),sourceWallet:await this.getSourceWallet()})});return a.fillMolecule({metaType:e,metaId:t,rule:s,policy:n}),await this.executeQuery(a)}async createMeta({metaType:e,metaId:t,meta:s=null,policy:n={}}){const a=await this.createMoleculeMutation({mutationClass:nt,molecule:await this.createMolecule({secret:this.getSecret(),sourceWallet:await this.getSourceWallet()})}),i=s||{};return a.fillMolecule({metaType:e,metaId:t,meta:i,policy:n}),await this.executeQuery(a)}async createIdentifier({type:e,contact:t,code:s}){const n=await this.createMoleculeMutation({mutationClass:Ye});return n.fillMolecule({type:e,contact:t,code:s}),await this.executeQuery(n)}async createPolicy({metaType:e,metaId:t,policy:s={}}){let n=await this.createMolecule({});n.addPolicyAtom({metaType:e,metaId:t,meta:{},policy:s}),n.addContinuIdAtom(),n.sign({}),n.check();const a=await this.createMoleculeMutation({mutationClass:Ne,molecule:n});return await this.executeQuery(a)}async queryPolicy({metaType:e,metaId:t}){const s=this.createQuery(Ot);return await this.executeQuery(s,{metaType:e,metaId:t})}queryWallets({bundle:e=null,token:t=null,unspent:s=!0}){this.$__logging&&console.info(`KnishIOClient::queryWallets() - Querying wallets${e?` for ${e}`:""}...`);const n=this.createQuery(Ue);return this.executeQuery(n,{bundleHash:e||this.getBundle(),token:t,unspent:s}).then((e=>e.payload()))}queryShadowWallets({token:e="KNISH",bundle:t=null}){t=t||this.getBundle(),this.$__logging&&console.info(`KnishIOClient::queryShadowWallets() - Querying ${e} shadow wallets for ${t}...`);const s=this.createQuery(Ue);return this.executeQuery(s,{bundleHash:t,token:e}).then((e=>e.payload()))}queryBundle({bundle:e=null,key:t=null,value:s=null,latest:n=!0,fields:a=null,raw:i=!1}){this.$__logging&&console.info(`KnishIOClient::queryBundle() - Querying wallet bundle metadata${e?` for ${e}`:""}...`);const r=this.createQuery(Be),l=Be.createVariables({bundleHash:e||this.getBundle(),key:t,value:s,latest:n});return this.executeQuery(r,l).then((e=>i?e:e.payload()))}async queryContinuId({bundle:e}){const t=this.createQuery(Ce);return this.executeQuery(t,{bundle:e})}async requestTokens({token:e,to:t,amount:s=null,units:n=[],meta:a=null,batchId:i=null}){let r,l;a=a||{};const o=this.createQuery(Ct),u=await this.executeQuery(o,{slug:e}),c="stackable"===ke.get(u.data(),"0.fungibility");if(!c&&null!==i)throw new ce("Expected Batch ID = null for non-stackable tokens.");if(c&&null===i&&(i=Q({})),n.length>0){if(s>0)throw new ct;s=n.length,a.tokenUnits=JSON.stringify(n)}t?("[object String]"===Object.prototype.toString.call(t)&&(D.isBundleHash(t)?(r="walletBundle",l=t):t=D.create({secretOrBundle:t,token:e})),t instanceof D&&(r="wallet",a.position=t.position,a.bundle=t.bundle,l=t.address)):(r="walletBundle",l=this.getBundle());const h=await this.createMoleculeMutation({mutationClass:ze});return h.fillMolecule({token:e,amount:s,metaType:r,metaId:l,meta:a,batchId:i}),await this.executeQuery(h)}async claimShadowWallet({token:e,batchId:t=null,molecule:s=null}){const n=await this.createMoleculeMutation({mutationClass:tt,molecule:s});return n.fillMolecule({token:e,batchId:t}),await this.executeQuery(n)}async claimShadowWallets({token:e}){const t=await this.queryShadowWallets({token:e});if(!t||!Array.isArray(t))throw new ot;t.forEach((e=>{if(!e.isShadow())throw new ot}));let s=[];for(const n of t)s.push(await this.claimShadowWallet({token:e,batchId:n.batchId}));return s}async transferToken({bundleHash:e,token:t,amount:s=null,units:n=[],batchId:a=null,sourceWallet:i=null}){if(n.length>0){if(s>0)throw new ct;s=n.length}if(null===i&&(i=await this.querySourceWallet({token:t,amount:s})),null===i||Se.cmp(i.balance,s)<0)throw new se;let r=D.create({secretOrBundle:e,token:t});null!==a?r.batchId=a:r.initBatchId({sourceWallet:i}),this.remainderWallet=D.create({secretOrBundle:this.getSecret(),token:t,characters:i.characters}),this.remainderWallet.initBatchId({sourceWallet:i,isRemainder:!0}),i.splitUnits(n,this.remainderWallet,r);const l=await this.createMolecule({sourceWallet:i,remainderWallet:this.remainderWallet}),o=await this.createMoleculeMutation({mutationClass:Ge,molecule:l});return o.fillMolecule({recipientWallet:r,amount:s}),await this.executeQuery(o)}async depositBufferToken({tokenSlug:e,amount:t,tradeRates:s,sourceWallet:n=null}){null===n&&(n=await this.querySourceWallet({token:e,amount:t})),this.remainderWallet=D.create({secretOrBundle:this.getSecret(),token:e,characters:n.characters}),this.remainderWallet.initBatchId({sourceWallet:n,isRemainder:!0});const a=await this.createMolecule({sourceWallet:n,remainderWallet:this.remainderWallet}),i=await this.createMoleculeMutation({mutationClass:Kt,molecule:a});return i.fillMolecule({amount:t,tradeRates:s}),await this.executeQuery(i)}async withdrawBufferToken({tokenSlug:e,amount:t,sourceWallet:s=null,signingWallet:n=null}){null===s&&(s=await this.querySourceWallet({token:e,amount:t,type:"buffer"})),this.remainderWallet=s;const a=await this.createMolecule({sourceWallet:s,remainderWallet:this.remainderWallet}),i=await this.createMoleculeMutation({mutationClass:Qt,molecule:a});let r={};return r[this.getBundle()]=t,i.fillMolecule({recipients:r,signingWallet:n}),await this.executeQuery(i)}async burnTokens({token:e,amount:t=null,units:s=[],sourceWallet:n=null}){null===n&&(n=await this.querySourceWallet({token:e,amount:t}));let a=D.create({secretOrBundle:this.getSecret(),token:e,characters:n.characters});if(a.initBatchId({sourceWallet:n,isRemainder:!0}),s.length>0){if(t>0)throw new ct;t=s.length,n.splitUnits(s,a)}let i=await this.createMolecule({sourceWallet:n,remainderWallet:a});i.burnToken({amount:t}),i.sign({}),i.check();const r=await this.createMoleculeMutation({mutationClass:Ne,molecule:i});return this.executeQuery(r)}async replenishToken({token:e,amount:t=null,units:s=[],sourceWallet:n=null}){if(null===n&&(n=(await this.queryBalance({token:e})).payload()),!n)throw new se("Source wallet is missing or invalid.");let a=D.create({secretOrBundle:this.getSecret(),token:e,characters:n.characters});a.initBatchId({sourceWallet:n,isRemainder:!0});let i=await this.createMolecule({sourceWallet:n,remainderWallet:a});i.replenishToken({amount:t,units:s}),i.sign({}),i.check();const r=await this.createMoleculeMutation({mutationClass:Ne,molecule:i});return this.executeQuery(r)}async fuseToken({bundleHash:e,tokenSlug:t,newTokenUnit:s,fusedTokenUnitIds:n,sourceWallet:a=null}){if(null===a&&(a=(await this.queryBalance({token:t})).payload()),null===a)throw new se("Source wallet is missing or invalid.");if(!a.tokenUnits||!a.tokenUnits.length)throw new se("Source wallet does not have token units.");if(!n.length)throw new se("Fused token unit list is empty.");let i=[];a.tokenUnits.forEach((e=>{i.push(e.id)})),n.forEach((e=>{if(!i.includes(e))throw new se(`Fused token unit ID = ${e} does not found in the source wallet.`)}));let r=D.create({secretOrBundle:e,token:t});r.initBatchId({sourceWallet:a});let l=D.create({secretOrBundle:this.getSecret(),token:t,batchId:a.batchId,characters:a.characters});l.initBatchId({sourceWallet:a,isRemainder:!0}),a.splitUnits(n,l),s.metas.fusedTokenUnits=a.getTokenUnitsData(),r.tokenUnits=[s];let o=await this.createMolecule({sourceWallet:a,remainderWallet:l});o.fuseToken(a.tokenUnits,r),o.sign({}),o.check();const u=await this.createMoleculeMutation({mutationClass:Ne,molecule:o});return this.executeQuery(u)}async requestGuestAuthToken({cellSlug:e,encrypt:t}){this.setCellSlug(e);const s=new D({secret:E(),token:"AUTH"}),n=await this.createQuery(lt),a={cellSlug:e,pubkey:s.pubkey,encrypt:t},i=await n.execute(a);if(!i.success())throw new Wt(`KnishIOClient::requestGuestAuthToken() - Authorization attempt rejected by ledger. Reason: ${i.reason()}`);{const e=Ie.create(i.payload(),s);this.setAuthToken(e)}return i}async requestProfileAuthToken({secret:e,encrypt:t}){this.setSecret(e);const s=new D({secret:e,token:"AUTH"}),n=await this.createMolecule({secret:e,sourceWallet:s}),a=await this.createMoleculeMutation({mutationClass:Ve,molecule:n});a.fillMolecule({meta:{encrypt:t?"true":"false"}});const i=await a.execute({});if(!i.success())throw new Wt(`KnishIOClient::requestProfileAuthToken() - Authorization attempt rejected by ledger. Reason: ${i.reason()}`);{const e=Ie.create(i.payload(),s);this.setAuthToken(e)}return i}async requestAuthToken({secret:e=null,seed:t=null,cellSlug:s=null,encrypt:n=!1}){if(this.$__serverSdkVersion<3)return this.$__logging&&console.warn("KnishIOClient::authorize() - Server SDK version does not require an authorization..."),null;let a;return null===e&&t&&(e=E(t)),this.$__authInProcess=!0,a=e?await this.requestProfileAuthToken({secret:e,encrypt:n}):await this.requestGuestAuthToken({cellSlug:s,encrypt:n}),this.$__logging&&console.info(`KnishIOClient::authorize() - Successfully retrieved auth token ${this.$__authToken.getToken()}...`),this.switchEncryption(n),this.$__authInProcess=!1,a}setAuthToken(e){e?(this.$__authTokenObjects[this.uri()]=e,this.client().setAuthData(e.getAuthData()),this.$__authToken=e):this.$__logging&&console.info("KnishIOClient::setAuthToken() - authToken object is empty.")}getAuthToken(){return this.$__authToken}}class Nt{static async run(e){for(let t in e){let s=new Nt(e[t]);await s.testAll()}}constructor(e,t=!1){this.encrypt=t,this.secrets=[E(),E()],this.tokenSlugs=["TESTTOKEN","UTENVSTACKABLE","UTSTACKUNIT","UTENVSTACKUNIT","UTSTACKUNITZONES","UTSLUG0","UTSLUG1"],this.graphqlUrl=e,console.log(`---------- GraphQL URI: ${this.graphqlUrl}`),this.clients={},this.tokenUnits=[["unit_id_1","unit_name_1"],["unit_id_2","unit_name_2"],["unit_id_3","unit_name_3"],["unit_id_4","unit_name_4"],["unit_id_5","unit_name_5"],["unit_id_6","unit_name_6"],["unit_id_7","unit_name_7"],["unit_id_8","unit_name_8"],["unit_id_9","unit_name_9"],["unit_id_10","unit_name_10"],["unit_id_11","unit_name_11"]],this.replenishTokenUnits=[["unit_id_12","unit_id_12"],["unit_id_13","unit_id_13"],["unit_id_14","unit_id_14"],["unit_id_15","unit_id_15"]];let s=(e,t=0)=>{let s=[];return e.forEach(((e,n)=>{let a=Array.from(e);a.push({fragmentZone:t+n}),s.push(a)})),s};this.tokenUnitsFZ=s(this.tokenUnits),this.replenishTokenUnitsFZ=s(Array.from(this.replenishTokenUnits),this.tokenUnits.length),this.fragmentZones=this.tokenUnitsFZ.length+this.replenishTokenUnitsFZ.length,this.fusedTokenUnitIds=[],this.tokenUnitsFZ.slice(0,5).forEach((e=>{this.fusedTokenUnitIds.push(e[0])}))}async testAll(){console.info(`Executing test for: ${this.graphqlUrl}...`),await this.client(this.secrets[0]),await this.client(this.secrets[1]),await this.testCreateToken(),await this.testFuseToken(),await this.testCreateWallet(),await this.testCreateMeta(),await this.testCreateIdentifier(),await this.testRequestTokens(),await this.testTransferToken(),await this.testBurnToken(),await this.testReplenishToken(),await this.testClaimShadowWallet(),await this.testWalletBufferTransactions(),await this.testQueryMeta(),await this.testQueryWallets(),await this.testQueryShadowWallets(),await this.testQueryBundle(),await this.testQueryBalance()}async testTokenExpiration(){const e=await this.client(this.secrets[0]),t=t=>{setTimeout((e=>{console.warn(`setTimeout ${t}`),e.queryMeta({metaType:"metaType",metaId:"metaId"})}),t,e,t)};t(3e3),t(3e4),t(61e3),t(64e3)}async testCreateToken(){let e={},t=await this.client(this.secrets[0]);e[0]=await t.createToken({token:this.tokenSlugs[0],amount:1e3,meta:{name:this.tokenSlugs[0],fungibility:"stackable",supply:"replenishable",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:"replenishable",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"),e[4]=await t.createToken({token:this.tokenSlugs[4],units:this.tokenUnitsFZ,meta:{name:this.tokenSlugs[4],supply:"replenishable",fungibility:"stackable",fragmentZones:this.fragmentZones},batchId:"unit_fz_batch_0"}),this.checkResponse(e[4],"testCreateToken.4"),t=await this.client(this.secrets[0]);for(const s of[this.tokenSlugs[5],this.tokenSlugs[6]])e[0]=await t.createToken({token:s,amount:1e3,meta:{name:s,fungibility:"fungible",supply:"limited",decimals:0,icon:"icon"}}),this.checkResponse(e[0],`testCreateToken.${s}`)}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"});console.log(" ############### testCreateIdentifier ###############"),"Outdated code"!==t.reason()&&console.error("Error with response."),this.debug(t)}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({bundleHash:t,token:this.tokenSlugs[0],amount:10,batchId:"batch_1"}),this.checkResponse(e,"testTransferToken"),e=await s.transferToken({bundleHash:t,token:this.tokenSlugs[2],units:["unit_id_1","unit_id_2"],batchId:"batch_2"}),this.checkResponse(e,"testTransferUnitToken")}async testBurnToken(){let e,t=await this.client(this.secrets[0]);e=await t.burnTokens({token:this.tokenSlugs[0],amount:10}),this.checkResponse(e,"testBurnToken"),e=await t.burnTokens({token:this.tokenSlugs[2],units:["unit_id_3","unit_id_4"]}),this.checkResponse(e,"testBurnUnitToken")}async testReplenishToken(){let e,t=await this.client(this.secrets[0]);e=await t.replenishToken({token:this.tokenSlugs[0],amount:25}),this.checkResponse(e,"testReplenishToken"),e=await t.replenishToken({token:this.tokenSlugs[2],amount:0,units:this.replenishTokenUnits}),this.checkResponse(e,"testReplenishUnitToken")}async testFuseToken(){let e=this.tokenSlugs[4],t=E(),s=await this.client(t),n=new V("fusedTokenUnitId"),a=await this.client(this.secrets[0]),i=await a.fuseToken({bundleHash:s.getBundle(),tokenSlug:e,newTokenUnit:n,fusedTokenUnitIds:this.fusedTokenUnitIds});this.checkResponse(i,"testFuseToken");let r=(await s.queryBalance({token:e})).payload(),l=(await a.queryBalance({token:e})).payload();console.assert(r.tokenUnits.length,1),console.assert(r.tokenUnits[0].id,"fusedTokenUnitId");let o=r.tokenUnits[0].getFusedTokenUnits();console.assert(o.length,this.fusedTokenUnitIds.length);let u=[];o.forEach((e=>{u.push(e[0])})),console.assert(l.tokenUnits.length,6);let c=[];l.tokenUnits.forEach((e=>{c.push(e.id)})),console.assert(c,["unit_id_6","unit_id_7","unit_id_8","unit_id_9","unit_id_10","unit_id_11"])}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 testWalletBufferTransactions(){let e=await this.client(this.secrets[0]),t={};t[this.tokenSlugs[1]]=2,t[this.tokenSlugs[3]]=1;let s=await e.depositBufferToken({tokenSlug:this.tokenSlugs[5],amount:200,tradeRates:t});this.checkResponse(s,"testWalletBufferTransactions: depositBufferToken"),await e.withdrawBufferToken({tokenSlug:this.tokenSlugs[5],amount:100}),this.checkResponse(s,"testWalletBufferTransactions: withdrawBufferToken")}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 Pt({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 Qe?(e.success()||this.debug(e),console.assert(e.success(),e)):this.debug(e)}debug(e){e.data&&ke.get(e.data()||{},"reason")?console.log(e.data().reason):console.log(e)}}e.Atom=R,e.KnishIOClient=Pt,e.Meta=B,e.Molecule=we,e.Test=Nt,e.Wallet=D,e.base64ToHex=C,e.bufferToHexString=function(e){return T.toHex(e,{})},e.charsetBaseConvert=v,e.chunkSubstr=A,e.generateBundleHash=K,e.generateSecret=E,e.hexStringToBuffer=function(e){return T.toUint8Array(e)},e.hexToBase64=q,e.isHex=W,e.randomString=x,Object.defineProperty(e,"__esModule",{value:!0})}));
|