@wishknish/knishio-client-js 0.9.2 → 0.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
- var KnishIOClient=(function(h,F,T,ls,Ze){"use strict";typeof self>"u"&&(global.self=global);class St{static toHex(e,t){const n=(c,u)=>{const l=u?["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 l[Math.floor(c/16)]+l[c%16]},s=Object.assign({grouping:0,rowlength:0,uppercase:!1},t||{});let r="",i=0,o=0;for(let c=0;c<e.length&&(r+=n(e[c],s.uppercase),c!==e.length-1);++c)s.grouping>0&&++i===s.grouping&&(i=0,s.rowlength>0&&++o===s.rowlength?(o=0,r+=`
2
- `):r+=" ");return r}static toUint8Array(e){let t=e.toLowerCase().replace(/\s/g,"");t.length%2===1&&(t=`0${t}`);const n=new Uint8Array(Math.floor(t.length/2));let s=-1;for(let r=0;r<t.length;++r){const i=t[r],o=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"].indexOf(i);if(o===-1)throw Error("unexpected character");s===-1?s=16*o:(n[Math.floor(r/2)]=s+o,s=-1)}return n}}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,(a,e)=>e.toUpperCase())}),String.prototype.toSnakeCase||(String.prototype.toSnakeCase=function(){return this.replace(/[A-Z]/g,a=>`_${a.toLowerCase()}`)});function Se(a,e){const t=Math.ceil(a.length/e),n=[];for(let s=0,r=0;s<t;++s,r+=e)n[s]=a.substr(r,e);return n}function Ue(a=256,e="abcdef0123456789"){let t=new Uint8Array(a);return t=crypto.getRandomValues(t),t=t.map(n=>e.charCodeAt(n%e.length)),String.fromCharCode.apply(null,t)}function $t(a,e,t,n,s){if(n=n||"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~`!@#$%^&*()-_=+[{]}\\|;:'\",<.>/?¿¡",s=s||n,e>n.length||t>s.length)return console.warn("Strings::charsetBaseConvert() - Can't convert",a,"to base",t,"greater than symbol table length. src-table:",n.length,"dest-table:",s.length),!1;let i=BigInt(0);for(let c=0;c<a.length;c++)i=i*BigInt(e)+BigInt(n.indexOf(a.charAt(c)));let o="";for(;i>0;){const c=i%BigInt(t);o=s.charAt(Number(c))+o,i/=BigInt(t)}return o||"0"}function At(a){return St.toHex(a,{})}function vt(a){return St.toUint8Array(a)}function It(a){const e=vt(a);return btoa(String.fromCharCode.apply(null,e))}function Mt(a){const e=new Uint8Array(atob(a).split("").map(t=>t.charCodeAt(0)));return At(e)}function Be(a){return/^[A-F0-9]+$/i.test(a)}function Tt(a){return(typeof a=="number"||typeof a=="string"&&a.trim()!=="")&&!isNaN(a)}let ie=class{static normalizeMeta(e){if(Array.isArray(e))return e.map(n=>({key:n.key,value:n.value==null?null:String(n.value)}));const t=[];for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)){const s=e[n];t.push({key:n,value:s==null?null:String(s)})}return t}static aggregateMeta(e){let t={};if(Array.isArray(e))for(const n of e)t[n.key]=n.value;else t=e;return t}};function Ct(a,e){return a.length?[a.slice(0,e)].concat(Ct(a.slice(e),e)):[]}function xt(a,e){let t,n,s;const r=[Array,Date,Number,String,Boolean],i=Object.prototype.toString;for(e=e||[],t=0;t<e.length;t+=2)a===e[t]&&(n=e[t+1]);if(!n&&a&&typeof a=="object"){for(n={},t=0;t<r.length;t++)i.call(a)===i.call(s=new r[t](a))&&(n=t?s:[]);e.push(a,n);for(t in a)e.hasOwnProperty.call(a,t)&&(n[t]=xt(a[t],e))}return n||a}function Et(...a){return[].concat(...a.map((e,t)=>{const n=a.slice(0);n.splice(t,1);const s=[...new Set([].concat(...n))];return e.filter(r=>!s.includes(r))}))}function fe(...a){return a.reduce((e,t)=>e.filter(n=>t.includes(n)))}class Pe{constructor(e={},t={}){this.policy=Pe.normalizePolicy(e),this.fillDefault(t)}static normalizePolicy(e={}){const t={};for(const[n,s]of Object.entries(e))if(s!==null&&["read","write"].includes(n)){t[n]={};for(const[r,i]of Object.entries(s))t[n][r]=i}return t}fillDefault(e={}){const t=Array.from(this.policy).filter(s=>s.action==="read"),n=Array.from(this.policy).filter(s=>s.action==="write");for(const[s,r]of Object.entries({read:t,write:n})){const i=r.map(o=>o.key);this.policy[s]||(this.policy[s]={});for(const o of Et(e,i))this.policy[s][o]||(this.policy[s][o]=s==="write"&&!["characters","pubkey"].includes(o)?["self"]:["all"])}}get(){return this.policy}toJson(){return JSON.stringify(this.get())}}class B{constructor(e=[]){this.meta=ie.normalizeMeta(e)}merge(e){return this.meta=Array.from(new Set([...this.meta,...ie.normalizeMeta(e)])),this}addContext(e=null){return this}setAtomWallet(e){const t={};return e.tokenUnits&&e.tokenUnits.length&&(t.tokenUnits=JSON.stringify(e.getTokenUnitsData())),e.tradeRates&&e.tradeRates.length&&(t.tradeRates=JSON.stringify(e.tradeRates)),Object.keys(t).length>0&&this.merge(t),this}setMetaWallet(e){return this.merge({walletTokenSlug:e.token,walletBundleHash:e.bundle,walletAddress:e.address,walletPosition:e.position,walletBatchId:e.batchId,walletPubkey:e.pubkey,walletCharacters:e.characters}),this}setShadowWalletClaim(e){return this.merge({shadowWalletClaim:e*1}),this}setSigningWallet(e){return this.merge({signingWallet:JSON.stringify({tokenSlug:e.token,bundleHash:e.bundle,address:e.address,position:e.position,pubkey:e.pubkey,characters:e.characters})}),this}addPolicy(e){const t=new Pe(e,Object.keys(this.meta));return this.merge({policy:t.toJson()}),this}get(){return this.meta}}class M extends TypeError{constructor(e=null,t=null,n=null){if(super(e,t,n),e===null)throw new this(`Unknown ${this.constructor.name}`);this.name="BaseException"}toString(){return`${this.name}: ${this.message}.
1
+ var KnishIOClient=(function(h,D,T,Ss,rt){"use strict";typeof self>"u"&&(global.self=global);class Et{static toHex(e,t){const n=(c,u)=>{const l=u?["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 l[Math.floor(c/16)]+l[c%16]},s=Object.assign({grouping:0,rowlength:0,uppercase:!1},t||{});let r="",i=0,o=0;for(let c=0;c<e.length&&(r+=n(e[c],s.uppercase),c!==e.length-1);++c)s.grouping>0&&++i===s.grouping&&(i=0,s.rowlength>0&&++o===s.rowlength?(o=0,r+=`
2
+ `):r+=" ");return r}static toUint8Array(e){let t=e.toLowerCase().replace(/\s/g,"");t.length%2===1&&(t=`0${t}`);const n=new Uint8Array(Math.floor(t.length/2));let s=-1;for(let r=0;r<t.length;++r){const i=t[r],o=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"].indexOf(i);if(o===-1)throw Error("unexpected character");s===-1?s=16*o:(n[Math.floor(r/2)]=s+o,s=-1)}return n}}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,(a,e)=>e.toUpperCase())}),String.prototype.toSnakeCase||(String.prototype.toSnakeCase=function(){return this.replace(/[A-Z]/g,a=>`_${a.toLowerCase()}`)});function Ie(a,e){const t=Math.ceil(a.length/e),n=[];for(let s=0,r=0;s<t;++s,r+=e)n[s]=a.substr(r,e);return n}function Ne(a=256,e="abcdef0123456789"){const t=new Uint8Array(a);crypto.getRandomValues(t);let n="";for(let s=0;s<a;s++)n+=e.charAt(t[s]%e.length);return n}function Rt(a,e,t,n,s){if(n=n||"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~`!@#$%^&*()-_=+[{]}\\|;:'\",<.>/?¿¡",s=s||n,e>n.length||t>s.length)return console.warn("Strings::charsetBaseConvert() - Can't convert",a,"to base",t,"greater than symbol table length. src-table:",n.length,"dest-table:",s.length),!1;let i=BigInt(0);for(let c=0;c<a.length;c++)i=i*BigInt(e)+BigInt(n.indexOf(a.charAt(c)));let o="";for(;i>0;){const c=i%BigInt(t);o=s.charAt(Number(c))+o,i/=BigInt(t)}return o||"0"}function it(a){return Et.toHex(a,{})}function qt(a){return Et.toUint8Array(a)}function Ot(a){const e=qt(a);if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";const n=32768;for(let s=0;s<e.length;s+=n)t+=String.fromCharCode(...e.subarray(s,s+n));return btoa(t)}function Bt(a){if(typeof Buffer<"u")return it(new Uint8Array(Buffer.from(a,"base64")));const e=atob(a),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return it(t)}function Fe(a){return/^[A-F0-9]+$/i.test(a)}function Wt(a){return(typeof a=="number"||typeof a=="string"&&a.trim()!=="")&&!isNaN(a)}let oe=class{static normalizeMeta(e){if(Array.isArray(e))return e.map(n=>({key:n.key,value:n.value==null?null:String(n.value)}));const t=[];for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)){const s=e[n];t.push({key:n,value:s==null?null:String(s)})}return t}static aggregateMeta(e){let t={};if(Array.isArray(e))for(const n of e)t[n.key]=n.value;else t=e;return t}};function _s(a,e){const t=[];for(let n=0;n<a.length;n+=e)t.push(a.slice(n,n+e));return t}function Ut(a,e){let t,n,s;const r=[Array,Date,Number,String,Boolean],i=Object.prototype.toString;for(e=e||[],t=0;t<e.length;t+=2)a===e[t]&&(n=e[t+1]);if(!n&&a&&typeof a=="object"){for(n={},t=0;t<r.length;t++)i.call(a)===i.call(s=new r[t](a))&&(n=t?s:[]);e.push(a,n);for(t in a)e.hasOwnProperty.call(a,t)&&(n[t]=Ut(a[t],e))}return n||a}function Pt(...a){return[].concat(...a.map((e,t)=>{const n=a.slice(0);n.splice(t,1);const s=[...new Set([].concat(...n))];return e.filter(r=>!s.includes(r))}))}function me(...a){return a.reduce((e,t)=>e.filter(n=>t.includes(n)))}class Le{constructor(e={},t={}){this.policy=Le.normalizePolicy(e),this.fillDefault(t)}static normalizePolicy(e={}){const t={};for(const[n,s]of Object.entries(e))if(s!==null&&["read","write"].includes(n)){t[n]={};for(const[r,i]of Object.entries(s))t[n][r]=i}return t}fillDefault(e={}){const t=Array.from(this.policy).filter(s=>s.action==="read"),n=Array.from(this.policy).filter(s=>s.action==="write");for(const[s,r]of Object.entries({read:t,write:n})){const i=r.map(o=>o.key);this.policy[s]||(this.policy[s]={});for(const o of Pt(e,i))this.policy[s][o]||(this.policy[s][o]=s==="write"&&!["characters","pubkey"].includes(o)?["self"]:["all"])}}get(){return this.policy}toJson(){return JSON.stringify(this.get())}}class P{constructor(e=[]){this.meta=oe.normalizeMeta(e)}merge(e){return this.meta=Array.from(new Set([...this.meta,...oe.normalizeMeta(e)])),this}addContext(e=null){return this}setAtomWallet(e){const t={};return e.tokenUnits&&e.tokenUnits.length&&(t.tokenUnits=JSON.stringify(e.getTokenUnitsData())),e.tradeRates&&e.tradeRates.length&&(t.tradeRates=JSON.stringify(e.tradeRates)),Object.keys(t).length>0&&this.merge(t),this}setMetaWallet(e){return this.merge({walletTokenSlug:e.token,walletBundleHash:e.bundle,walletAddress:e.address,walletPosition:e.position,walletBatchId:e.batchId,walletPubkey:e.pubkey,walletCharacters:e.characters}),this}setShadowWalletClaim(e){return this.merge({shadowWalletClaim:e*1}),this}setSigningWallet(e){return this.merge({signingWallet:JSON.stringify({tokenSlug:e.token,bundleHash:e.bundle,address:e.address,position:e.position,pubkey:e.pubkey,characters:e.characters})}),this}addPolicy(e){const t=new Le(e,Object.keys(this.meta));return this.merge({policy:t.toJson()}),this}get(){return this.meta}}class I extends TypeError{constructor(e=null,t=null,n=null){if(super(e,t,n),e===null)throw new this(`Unknown ${this.constructor.name}`);this.name="BaseException"}toString(){return`${this.name}: ${this.message}.
3
3
  Stack:
4
- ${this.stack}`}}class ne extends M{constructor(e="The molecule does not contain atoms",t=null,n=null){super(e,t,n),this.name="AtomsMissingException"}}class ae{static create(e){const t={};for(const n of Object.keys(e))Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return new this(t)}static structure(e){switch(Object.prototype.toString.call(e)){case"[object Array]":{const t=[];for(const n in e)t.push(ae.isStructure(e[n])?ae.structure(e[n]):e[n]);return t}case"[object Object]":{const t=[],n=Object.keys(e).sort((s,r)=>s===r?0:s<r?-1:1);for(const s of n)if(Object.prototype.hasOwnProperty.call(e,s)){const r={};r[s]=ae.isStructure(e[s])?ae.structure(e[s]):e[s],t.push(r)}if(t.length>0)return t;break}}return e}static isStructure(e){return["[object Object]","[object Array]"].includes(Object.prototype.toString.call(e))}view(){return ae.structure(this)}}class cs extends ae{constructor({position:e=null,walletAddress:t=null,isotope:n=null,token:s=null,value:r=null,batchId:i=null,metaType:o=null,metaId:c=null,meta:u=null,index:l=null,createdAt:d=null,version:f=null}){super(),this.position=e,this.walletAddress=t,this.isotope=n,this.token=s,this.value=r,this.batchId=i,this.metaType=o,this.metaId=c,this.meta=u,this.index=l,this.createdAt=d,this.version=f}}const He={4:cs};class b{constructor({position:e=null,walletAddress:t=null,isotope:n=null,token:s=null,value:r=null,batchId:i=null,metaType:o=null,metaId:c=null,meta:u=null,otsFragment:l=null,index:d=null,version:f=null}){this.position=e,this.walletAddress=t,this.isotope=n,this.token=s,this.value=r!==null?String(r):null,this.batchId=i,this.metaType=o,this.metaId=c,this.meta=u?ie.normalizeMeta(u):[],this.index=d,this.otsFragment=l,this.createdAt=String(+new Date),f!==null&&Object.prototype.hasOwnProperty.call(He,f)&&(this.version=String(f))}static getHashableProps(){return["position","walletAddress","isotope","token","value","batchId","metaType","metaId","meta","createdAt"]}static getUnclaimedProps(){return["otsFragment"]}static create({isotope:e,wallet:t=null,value:n=null,metaType:s=null,metaId:r=null,meta:i=null,batchId:o=null}){return i||(i=new B),i instanceof B||(i=new B(i)),t&&(i.setAtomWallet(t),o||(o=t.batchId)),new b({position:t?t.position:null,walletAddress:t?t.address:null,isotope:e,token:t?t.token:null,value:n,batchId:o,metaType:s,metaId:r,meta:i.get()})}static jsonToObject(e){const t=Object.assign(new b({}),JSON.parse(e)),n=Object.keys(new b({}));for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&!n.includes(s)&&delete t[s];return t}toJSON(e={}){const{includeOtsFragments:t=!0,validateFields:n=!1}=e;try{if(n){const r=["position","walletAddress","isotope","token"];for(const i of r)if(!this[i])throw new Error(`Required field '${i}' is missing or empty`)}const s={position:this.position??"",walletAddress:this.walletAddress??"",isotope:this.isotope,token:this.token??"",value:this.value,batchId:this.batchId,metaType:this.metaType,metaId:this.metaId,meta:this.meta||[],index:this.index,createdAt:this.createdAt,version:this.version};return t&&this.otsFragment&&(s.otsFragment=this.otsFragment),s}catch(s){throw new Error(`Atom serialization failed: ${s.message}`)}}static fromJSON(e,t={}){const{validateStructure:n=!0,strictMode:s=!1}=t;try{const r=typeof e=="string"?JSON.parse(e):e;if(s||n){const o=["position","walletAddress","isotope","token"];for(const c of o)if(!r[c])throw new Error(`Required field '${c}' is missing or empty`)}const i=new b({position:r.position,walletAddress:r.walletAddress,isotope:r.isotope,token:r.token,value:r.value,batchId:r.batchId,metaType:r.metaType,metaId:r.metaId,meta:r.meta,index:r.index,version:r.version});return r.otsFragment&&(i.otsFragment=r.otsFragment),r.createdAt&&(i.createdAt=r.createdAt),i}catch(r){throw new Error(`Atom deserialization failed: ${r.message}`)}}static hashAtoms({atoms:e,output:t="base17"}){const n=new F("SHAKE256","TEXT"),s=b.sortAtoms(e);if(s.length===0)throw new ne;if(s.map(r=>{if(!(r instanceof b))throw new ne;return r}),s.every(r=>r.version&&Object.prototype.hasOwnProperty.call(He,r.version)))n.update(JSON.stringify(s.map(r=>He[r.version].create(r).view())));else{const r=String(e.length);let i=[];for(const o of s)i.push(r),i=i.concat(o.getHashableValues());for(const o of i)n.update(o)}switch(t){case"hex":return n.getHash("HEX",{outputLen:256});case"array":return n.getHash("ARRAYBUFFER",{outputLen:256});default:return $t(n.getHash("HEX",{outputLen:256}),16,17,"0123456789abcdef","0123456789abcdefg").padStart(64,"0")}}static jsonSerialization(e,t){if(!b.getUnclaimedProps().includes(e))return t}static sortAtoms(e){const t=[...e];return t.sort((n,s)=>n.index<s.index?-1:1),t}aggregatedMeta(){return ie.aggregateMeta(this.meta)}getHashableValues(){const e=[];for(const t of b.getHashableProps()){const n=this[t];if(!(n===null&&!["position","walletAddress"].includes(t)))if(t==="meta")for(const s of n)typeof s.value<"u"&&s.value!==null&&(e.push(String(s.key)),e.push(String(s.value)));else e.push(n===null?"":String(n))}return e}}function Ke(a=null,e=2048){if(a){const t=new F("SHAKE256","TEXT");return t.update(a),t.getHash("HEX",{outputLen:e*4})}else return Ue(e)}function oe(a,e=null){const t=new F("SHAKE256","TEXT");return t.update(a),t.getHash("HEX",{outputLen:256})}function Ne(a,e){const t=new F("SHAKE256","TEXT");return t.update(a),t.getHash("HEX",{outputLen:e})}function $e({molecularHash:a=null,index:e=null}){return a!==null&&e!==null?oe(String(a)+String(e),"generateBatchId"):Ue(64)}class le{constructor(e,t,n){this.id=e,this.name=t,this.metas=n||{}}static createFromGraphQL(e){let t=e.metas||{};return t.length&&(t=JSON.parse(t),t||(t={})),new le(e.id,e.name,t)}static createFromDB(e){return new le(e[0],e[1],e.length>2?e[2]:{})}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 Ye extends M{constructor(e="Attempting to create a wallet with no credentials (secret or bundle hash)",t=null,n=null){super(e,t,n),this.name="WalletCredentialException"}}const Le=BigInt(2**32-1),Rt=BigInt(32);function us(a,e=!1){return e?{h:Number(a&Le),l:Number(a>>Rt&Le)}:{h:Number(a>>Rt&Le)|0,l:Number(a&Le)|0}}function hs(a,e=!1){const t=a.length;let n=new Uint32Array(t),s=new Uint32Array(t);for(let r=0;r<t;r++){const{h:i,l:o}=us(a[r],e);[n[r],s[r]]=[i,o]}return[n,s]}const ds=(a,e,t)=>a<<t|e>>>32-t,ps=(a,e,t)=>e<<t|a>>>32-t,fs=(a,e,t)=>e<<t-32|a>>>64-t,ms=(a,e,t)=>a<<t-32|e>>>64-t;function ys(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&a.constructor.name==="Uint8Array"}function qt(a,e=""){if(!Number.isSafeInteger(a)||a<0){const t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${a}`)}}function D(a,e,t=""){const n=ys(a),s=a?.length,r=e!==void 0;if(!n||r&&s!==e){const i=t&&`"${t}" `,o=r?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof a}`;throw new Error(i+"expected Uint8Array"+o+", got "+c)}return a}function Ot(a,e=!0){if(a.destroyed)throw new Error("Hash instance has been destroyed");if(e&&a.finished)throw new Error("Hash#digest() has already been called")}function gs(a,e){D(a,void 0,"digestInto() output");const t=e.outputLen;if(a.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function Wt(a){return new Uint32Array(a.buffer,a.byteOffset,Math.floor(a.byteLength/4))}function Ut(...a){for(let e=0;e<a.length;e++)a[e].fill(0)}const bs=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ws(a){return a<<24&4278190080|a<<8&16711680|a>>>8&65280|a>>>24&255}function ks(a){for(let e=0;e<a.length;e++)a[e]=ws(a[e]);return a}const Bt=bs?a=>a:ks;function Pt(a,e={}){const t=(s,r)=>a(r).update(s).digest(),n=a(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=s=>a(s),Object.assign(t,e),Object.freeze(t)}function _s(a=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(a))}const Qe=a=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,a])}),Ss=BigInt(0),Ae=BigInt(1),$s=BigInt(2),As=BigInt(7),vs=BigInt(256),Is=BigInt(113),Ht=[],Kt=[],Nt=[];for(let a=0,e=Ae,t=1,n=0;a<24;a++){[t,n]=[n,(2*t+3*n)%5],Ht.push(2*(5*n+t)),Kt.push((a+1)*(a+2)/2%64);let s=Ss;for(let r=0;r<7;r++)e=(e<<Ae^(e>>As)*Is)%vs,e&$s&&(s^=Ae<<(Ae<<BigInt(r))-Ae);Nt.push(s)}const Lt=hs(Nt,!0),Ms=Lt[0],Ts=Lt[1],Qt=(a,e,t)=>t>32?fs(a,e,t):ds(a,e,t),Ft=(a,e,t)=>t>32?ms(a,e,t):ps(a,e,t);function Cs(a,e=24){const t=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let i=0;i<10;i++)t[i]=a[i]^a[i+10]^a[i+20]^a[i+30]^a[i+40];for(let i=0;i<10;i+=2){const o=(i+8)%10,c=(i+2)%10,u=t[c],l=t[c+1],d=Qt(u,l,1)^t[o],f=Ft(u,l,1)^t[o+1];for(let p=0;p<50;p+=10)a[i+p]^=d,a[i+p+1]^=f}let s=a[2],r=a[3];for(let i=0;i<24;i++){const o=Kt[i],c=Qt(s,r,o),u=Ft(s,r,o),l=Ht[i];s=a[l],r=a[l+1],a[l]=c,a[l+1]=u}for(let i=0;i<50;i+=10){for(let o=0;o<10;o++)t[o]=a[i+o];for(let o=0;o<10;o++)a[i+o]^=~t[(o+2)%10]&t[(o+4)%10]}a[0]^=Ms[n],a[1]^=Ts[n]}Ut(t)}class Fe{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;enableXOF=!1;rounds;constructor(e,t,n,s=!1,r=24){if(this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=s,this.rounds=r,qt(n,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Wt(this.state)}clone(){return this._cloneInto()}keccak(){Bt(this.state32),Cs(this.state32,this.rounds),Bt(this.state32),this.posOut=0,this.pos=0}update(e){Ot(this),D(e);const{blockLen:t,state:n}=this,s=e.length;for(let r=0;r<s;){const i=Math.min(t-this.pos,s-r);for(let o=0;o<i;o++)n[this.pos++]^=e[r++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:s}=this;e[n]^=t,(t&128)!==0&&n===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){Ot(this,!1),D(e),this.finish();const t=this.state,{blockLen:n}=this;for(let s=0,r=e.length;s<r;){this.posOut>=n&&this.keccak();const i=Math.min(n-this.posOut,r-s);e.set(t.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return qt(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(gs(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Ut(this.state)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:s,rounds:r,enableXOF:i}=this;return e||=new Fe(t,n,s,i,r),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=r,e.suffix=n,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}}const jt=(a,e,t,n={})=>Pt(()=>new Fe(e,a,t),n),xs=jt(6,136,32,Qe(8)),Es=jt(6,72,64,Qe(10)),Dt=(a,e,t,n={})=>Pt((s={})=>new Fe(e,a,s.dkLen===void 0?t:s.dkLen,!0),n),Rs=Dt(31,168,16,Qe(11)),Vt=Dt(31,136,32,Qe(12));function et(a){if(!Number.isSafeInteger(a)||a<0||a>4294967295)throw new Error("wrong u32 integer:"+a);return a}function zt(a){return et(a),(a&a-1)===0&&a!==0}function Jt(a,e){et(a);let t=0;for(let n=0;n<e;n++,a>>>=1)t=t<<1|a&1;return t}function Gt(a){return et(a),31-Math.clz32(a)}function Xt(a){const e=a.length;if(e<2||!zt(e))throw new Error("n must be a power of 2 and greater than 1. Got "+e);const t=Gt(e);for(let n=0;n<e;n++){const s=Jt(n,t);if(n<s){const r=a[n];a[n]=a[s],a[s]=r}}return a}const Zt=(a,e)=>{const{N:t,roots:n,dit:s,invertButterflies:r=!1,skipStages:i=0,brp:o=!0}=e,c=Gt(t);if(!zt(t))throw new Error("FFT: Polynomial size should be power of two");const u=s!==r;return l=>{if(l.length!==t)throw new Error("FFT: wrong Polynomial length");s&&o&&Xt(l);for(let d=0,f=1;d<c-i;d++){const p=s?d+1+i:c-d,w=1<<p,v=w>>1,q=t>>p;for(let m=0;m<t;m+=w)for(let y=0,k=f++;y<v;y++){const R=r?s?t-k:k:y*q,S=m+y,A=m+y+v,I=n[R],x=l[A],$=l[S];if(u){const N=a.mul(x,I);l[S]=a.add($,N),l[A]=a.sub($,N)}else r?(l[S]=a.add(x,$),l[A]=a.mul(a.sub(x,$),I)):(l[S]=a.add($,x),l[A]=a.mul(a.sub($,x),I))}}return!s&&o&&Xt(l),l}};const Yt=_s;function tt(a,e){if(a.length!==e.length)return!1;let t=0;for(let n=0;n<a.length;n++)t|=a[n]^e[n];return t===0}function qs(a){return Uint8Array.from(a)}function je(a,...e){const t=s=>typeof s=="number"?s:s.bytesLen,n=e.reduce((s,r)=>s+t(r),0);return{bytesLen:n,encode:s=>{const r=new Uint8Array(n);for(let i=0,o=0;i<e.length;i++){const c=e[i],u=t(c),l=typeof c=="number"?s[i]:c.encode(s[i]);D(l,u,a),r.set(l,o),typeof c!="number"&&l.fill(0),o+=u}return r},decode:s=>{D(s,n,a);const r=[];for(const i of e){const o=t(i),c=s.subarray(0,o);r.push(typeof i=="number"?c:i.decode(c)),s=s.subarray(o)}return r}}}function nt(a,e){const t=e*a.bytesLen;return{bytesLen:t,encode:n=>{if(n.length!==e)throw new Error(`vecCoder.encode: wrong length=${n.length}. Expected: ${e}`);const s=new Uint8Array(t);for(let r=0,i=0;r<n.length;r++){const o=a.encode(n[r]);s.set(o,i),o.fill(0),i+=o.length}return s},decode:n=>{D(n,t);const s=[];for(let r=0;r<n.length;r+=a.bytesLen)s.push(a.decode(n.subarray(r,r+a.bytesLen)));return s}}}function X(...a){for(const e of a)if(Array.isArray(e))for(const t of e)t.fill(0);else e.fill(0)}function en(a){return(1<<a)-1}const Os=a=>{const{newPoly:e,N:t,Q:n,F:s,ROOT_OF_UNITY:r,brvBits:i}=a,o=(m,y=n)=>{const k=m%y|0;return(k>=0?k|0:y+k|0)|0},c=(m,y=n)=>{const k=o(m,y)|0;return(k>y>>1?k-y|0:k)|0};function u(){const m=e(t);for(let y=0;y<t;y++){const k=Jt(y,i),R=BigInt(r)**BigInt(k)%BigInt(n);m[y]=Number(R)|0}return m}const l=u(),d={add:(m,y)=>o((m|0)+(y|0))|0,sub:(m,y)=>o((m|0)-(y|0))|0,mul:(m,y)=>o((m|0)*(y|0))|0,inv:m=>{throw new Error("not implemented")}},f={N:t,roots:l,invertButterflies:!0,skipStages:1,brp:!1},p=Zt(d,{dit:!1,...f}),w=Zt(d,{dit:!0,...f});return{mod:o,smod:c,nttZetas:l,NTT:{encode:m=>p(m),decode:m=>{w(m);for(let y=0;y<m.length;y++)m[y]=o(s*m[y]);return m}},bitsCoder:(m,y)=>{const k=en(m),R=m*(t/8);return{bytesLen:R,encode:S=>{const A=new Uint8Array(R);for(let I=0,x=0,$=0,N=0;I<S.length;I++)for(x|=(y.encode(S[I])&k)<<$,$+=m;$>=8;$-=8,x>>=8)A[N++]=x&en($);return A},decode:S=>{const A=e(t);for(let I=0,x=0,$=0,N=0;I<S.length;I++)for(x|=S[I]<<$,$+=8;$>=m;$-=m,x>>=m)A[N++]=y.decode(x&k);return A}}}}},Ws=(a=>(e,t)=>{t||(t=a.blockLen);const n=new Uint8Array(e.length+2);n.set(e);const s=e.length,r=new Uint8Array(t);let i=a.create({}),o=0,c=0;return{stats:()=>({calls:o,xofs:c}),get:(u,l)=>(n[s+0]=u,n[s+1]=l,i.destroy(),i=a.create({}).update(n),o++,()=>(c++,i.xofInto(r))),clean:()=>{i.destroy(),X(r,n)}}})(Rs);const Q=256,ce=3329,Us=3303,Bs=17,{mod:ve,nttZetas:Ps,NTT:ue,bitsCoder:Hs}=Os({N:Q,Q:ce,F:Us,ROOT_OF_UNITY:Bs,newPoly:a=>new Uint16Array(a),brvBits:7}),Ks={768:{N:Q,Q:ce,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192}},Ns=a=>{if(a>=12)return{encode:t=>t,decode:t=>t};const e=2**(a-1);return{encode:t=>((t<<a)+ce/2)/ce,decode:t=>t*ce+e>>>a}},Ie=a=>Hs(a,Ns(a));function he(a,e){for(let t=0;t<Q;t++)a[t]=ve(a[t]+e[t])}function Ls(a,e){for(let t=0;t<Q;t++)a[t]=ve(a[t]-e[t])}function Qs(a,e,t,n,s){const r=ve(e*n*s+a*t),i=ve(a*n+e*t);return{c0:r,c1:i}}function De(a,e){for(let t=0;t<Q/2;t++){let n=Ps[64+(t>>1)];t&1&&(n=-n);const{c0:s,c1:r}=Qs(a[2*t+0],a[2*t+1],e[2*t+0],e[2*t+1],n);a[2*t+0]=s,a[2*t+1]=r}return a}function tn(a){const e=new Uint16Array(Q);for(let t=0;t<Q;){const n=a();if(n.length%3)throw new Error("SampleNTT: unaligned block");for(let s=0;t<Q&&s+3<=n.length;s+=3){const r=(n[s+0]>>0|n[s+1]<<8)&4095,i=(n[s+1]>>4|n[s+2]<<4)&4095;r<ce&&(e[t++]=r),t<Q&&i<ce&&(e[t++]=i)}}return e}function Me(a,e,t,n){const s=a(n*Q/4,e,t),r=new Uint16Array(Q),i=Wt(s);let o=0;for(let c=0,u=0,l=0,d=0;c<i.length;c++){let f=i[c];for(let p=0;p<32;p++)l+=f&1,f>>=1,o+=1,o===n?(d=l,l=0):o===2*n&&(r[u++]=ve(d-l),l=0,o=0)}if(o)throw new Error(`sampleCBD: leftover bits: ${o}`);return r}const Fs=a=>{const{K:e,PRF:t,XOF:n,HASH512:s,ETA1:r,ETA2:i,du:o,dv:c}=a,u=Ie(1),l=Ie(c),d=Ie(o),f=je("publicKey",nt(Ie(12),e),32),p=nt(Ie(12),e),w=je("ciphertext",nt(d,e),l),v=je("seed",32,32);return{secretCoder:p,lengths:{secretKey:p.bytesLen,publicKey:f.bytesLen,cipherText:w.bytesLen},keygen:q=>{D(q,32,"seed");const m=new Uint8Array(33);m.set(q),m[32]=e;const y=s(m),[k,R]=v.decode(y),S=[],A=[];for(let $=0;$<e;$++)S.push(ue.encode(Me(t,R,$,r)));const I=n(k);for(let $=0;$<e;$++){const N=ue.encode(Me(t,R,e+$,r));for(let U=0;U<e;U++){const _e=tn(I.get(U,$));he(N,De(_e,S[U]))}A.push(N)}I.clean();const x={publicKey:f.encode([A,k]),secretKey:p.encode(S)};return X(k,R,S,A,m,y),x},encrypt:(q,m,y)=>{const[k,R]=f.decode(q),S=[];for(let U=0;U<e;U++)S.push(ue.encode(Me(t,y,U,r)));const A=n(R),I=new Uint16Array(Q),x=[];for(let U=0;U<e;U++){const _e=Me(t,y,e+U,i),_t=new Uint16Array(Q);for(let Xe=0;Xe<e;Xe++){const kr=tn(A.get(U,Xe));he(_t,De(kr,S[Xe]))}he(_e,ue.decode(_t)),x.push(_e),he(I,De(k[U],S[U])),X(_t)}A.clean();const $=Me(t,y,2*e,i);he($,ue.decode(I));const N=u.decode(m);return he(N,$),X(k,S,I,$),w.encode([x,N])},decrypt:(q,m)=>{const[y,k]=w.decode(q),R=p.decode(m),S=new Uint16Array(Q);for(let A=0;A<e;A++)he(S,De(R[A],ue.encode(y[A])));return Ls(k,ue.decode(S)),X(S,R,y),u.encode(k)}}};function js(a){const e=Fs(a),{HASH256:t,HASH512:n,KDF:s}=a,{secretCoder:r,lengths:i}=e,o=je("secretKey",i.secretKey,i.publicKey,32,32),c=32,u=64;return{info:{type:"ml-kem"},lengths:{...i,seed:64,msg:c,msgRand:c,secretKey:o.bytesLen},keygen:(l=Yt(u))=>{D(l,u,"seed");const{publicKey:d,secretKey:f}=e.keygen(l.subarray(0,32)),p=t(d),w=o.encode([f,d,p,l.subarray(32)]);return X(f,p),{publicKey:d,secretKey:w}},getPublicKey:l=>{const[d,f]=o.decode(l);return Uint8Array.from(f)},encapsulate:(l,d=Yt(c))=>{D(l,i.publicKey,"publicKey"),D(d,c,"message");const f=l.subarray(0,384*a.K),p=r.encode(r.decode(qs(f)));if(!tt(p,f))throw X(p),new Error("ML-KEM.encapsulate: wrong publicKey modulus");X(p);const w=n.create().update(d).update(t(l)).digest(),v=e.encrypt(l,d,w.subarray(32,64));return X(w.subarray(32)),{cipherText:v,sharedSecret:w.subarray(0,32)}},decapsulate:(l,d)=>{D(d,o.bytesLen,"secretKey"),D(l,i.cipherText,"cipherText");const f=o.bytesLen-96,p=f+32,w=t(d.subarray(f/2,p));if(!tt(w,d.subarray(p,p+32)))throw new Error("invalid secretKey: hash check failed");const[v,q,m,y]=o.decode(d),k=e.decrypt(l,v),R=n.create().update(k).update(m).digest(),S=R.subarray(0,32),A=e.encrypt(q,k,R.subarray(32,64)),I=tt(l,A),x=s.create({dkLen:32}).update(y).update(l).digest();return X(k,A,I?x:S),I?S:x}}}function Ds(a,e,t){return Vt.create({dkLen:a}).update(e).update(new Uint8Array([t])).digest()}const st=js({...{HASH256:xs,HASH512:Es,KDF:Vt,XOF:Ws,PRF:Ds},...Ks[768]});class _{constructor({secret:e=null,bundle:t=null,token:n="USER",address:s=null,position:r=null,batchId:i=null,characters:o=null}){this.token=n,this.balance="0",this.molecules={},this.key=null,this.privkey=null,this.pubkey=null,this.tokenUnits=[],this.tradeRates={},this.address=s,this.position=r,this.bundle=t,this.batchId=i,this.characters=o,e&&(this.bundle=this.bundle||oe(e,"Wallet::constructor"),this.position=this.position||_.generatePosition(),this.key=_.generateKey({secret:e,token:this.token,position:this.position}),this.address=this.address||_.generateAddress(this.key),this.characters=this.characters||"BASE64",this.initializeMLKEM())}static create({secret:e=null,bundle:t=null,token:n,batchId:s=null,characters:r=null}){let i=null;if(!e&&!t)throw new Ye;return e&&!t&&(i=_.generatePosition(),t=oe(e,"Wallet::create")),new _({secret:e,bundle:t,token:n,position:i,batchId:s,characters:r})}static isBundleHash(e){return typeof e!="string"?!1:e.length===64&&Be(e)}static getTokenUnits(e){const t=[];return e.forEach(n=>{t.push(le.createFromDB(n))}),t}static generateKey({secret:e,token:t,position:n}){if(!e)throw new Ye("Wallet::generateKey() - Secret is required!");if(!n)throw new Ye("Wallet::generateKey() - Position is required!");const s=Be(e)?e:Ne(e,1024),r=Be(n)?n:Ne(n,256),o=BigInt(`0x${s}`)+BigInt(`0x${r}`),c=new F("SHAKE256","TEXT");c.update(o.toString(16)),t&&c.update(t);const u=new F("SHAKE256","TEXT");return u.update(c.getHash("HEX",{outputLen:8192})),u.getHash("HEX",{outputLen:8192})}static generateAddress(e){const t=Se(e,128),n=new F("SHAKE256","TEXT");for(const r in t){let i=t[r];for(let o=1;o<=16;o++){const c=new F("SHAKE256","TEXT");c.update(i),i=c.getHash("HEX",{outputLen:512})}n.update(i)}const s=new F("SHAKE256","TEXT");return s.update(n.getHash("HEX",{outputLen:8192})),s.getHash("HEX",{outputLen:256})}static generatePosition(e=64){return Ue(e,"abcdef0123456789")}initializeMLKEM(){const e=Ke(this.key,128),t=new Uint8Array(64);for(let r=0;r<64;r++)t[r]=parseInt(e.substr(r*2,2),16);const{publicKey:n,secretKey:s}=st.keygen(t);this.pubkey=this.serializeKey(n),this.privkey=s}serializeKey(e){return btoa(String.fromCharCode.apply(null,e))}deserializeKey(e){const t=atob(e);return new Uint8Array(t.length).map((n,s)=>t.charCodeAt(s))}balanceAsNumber(){return Number(this.balance)}balanceAsBigInt(){const e=String(this.balance),t=e.includes(".")?e.split(".")[0]:e;return BigInt(t||"0")}setBalanceBigInt(e){this.balance=e.toString()}setBalanceNumber(e){this.balance=String(e)}getTokenUnitsData(){const e=[];return this.tokenUnits.forEach(t=>{e.push(t.toData())}),e}splitUnits(e,t,n=null){if(e.length===0)return;const s=[],r=[];this.tokenUnits.forEach(i=>{e.includes(i.id)?s.push(i):r.push(i)}),this.tokenUnits=s,n!==null&&(n.tokenUnits=s),t.tokenUnits=r}splitUnitsMulti(e,t,n){const s=new Set;e.forEach(r=>{r.forEach(i=>s.add(i))}),s.size!==0&&(t.forEach((r,i)=>{const o=e[i];r.tokenUnits=this.tokenUnits.filter(c=>o.includes(c.id))}),n.tokenUnits=this.tokenUnits.filter(r=>!s.has(r.id)),this.tokenUnits=this.tokenUnits.filter(r=>s.has(r.id)))}createRemainder(e){const t=_.create({secret:e,token:this.token,characters:this.characters});return t.initBatchId({sourceWallet:this,isRemainder:!0}),t}isShadow(){return(typeof this.position>"u"||this.position===null)&&(typeof this.address>"u"||this.address===null)}initBatchId({sourceWallet:e,isRemainder:t=!1}){e.batchId&&(this.batchId=t?e.batchId:$e({}))}async encryptMessage(e,t){const n=JSON.stringify(e),s=new TextEncoder().encode(n),r=this.deserializeKey(t),i=1184;if(r.length!==i)throw new Error(`KnishIO: cannot ML-KEM-encrypt — recipient public key is ${r.length} bytes, expected ${i} (ML-KEM-768). The node likely did not advertise an ML-KEM public key (upgrade the validator to a PQ-transport build), or authenticate with { encrypt: false }.`);const{cipherText:o,sharedSecret:c}=st.encapsulate(r),u=await this.encryptWithSharedSecret(s,c);return{cipherText:this.serializeKey(o),encryptedMessage:this.serializeKey(u)}}async decryptMessage(e){const t=await this._mlkemDecryptToString(e);return t===null?null:JSON.parse(t)}async _mlkemDecryptToString(e){const{cipherText:t,encryptedMessage:n}=e;let s;try{s=st.decapsulate(this.deserializeKey(t),this.privkey)}catch(o){return console.error("Wallet::decryptMessage() - Decapsulation failed",o),console.info("Wallet::decryptMessage() - my public key",this.pubkey),null}let r;try{r=this.deserializeKey(n)}catch(o){return console.warn("Wallet::decryptMessage() - Deserialization failed",o),console.info("Wallet::decryptMessage() - my public key",this.pubkey),console.info("Wallet::decryptMessage() - our shared secret",s),null}let i;try{i=await this.decryptWithSharedSecret(r,s)}catch(o){return console.warn("Wallet::decryptMessage() - Decryption failed",o),console.info("Wallet::decryptMessage() - my public key",this.pubkey),console.info("Wallet::decryptMessage() - our shared secret",s),console.info("Wallet::decryptMessage() - deserialized encrypted message",r),null}try{return new TextDecoder().decode(i)}catch(o){return console.warn("Wallet::decryptMessage() - Decoding failed",o),console.info("Wallet::decryptMessage() - my public key",this.pubkey),console.info("Wallet::decryptMessage() - our shared secret",s),console.info("Wallet::decryptMessage() - deserialized encrypted message",r),console.info("Wallet::decryptMessage() - decrypted Uint8Array",i),null}}hashShare(e){const t=Ne(e,64),n=Uint8Array.from(t.match(/.{2}/g).map(s=>parseInt(s,16)));return this.serializeKey(n)}async encryptStringML768(e,t){const n=await this.encryptMessage(e,t);return JSON.stringify({[this.hashShare(t)]:n})}async decryptMyMessageML768(e){const t=e[this.hashShare(this.pubkey)];return t?this._mlkemDecryptToString(t):null}async encryptWithSharedSecret(e,t){const n=crypto.getRandomValues(new Uint8Array(12)),s={name:"AES-GCM",iv:n},r=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["encrypt"]),i=await crypto.subtle.encrypt(s,r,e),o=new Uint8Array(n.length+i.byteLength);return o.set(n),o.set(new Uint8Array(i),n.length),o}async decryptWithSharedSecret(e,t){const s={name:"AES-GCM",iv:e.slice(0,12)},r=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=await crypto.subtle.decrypt(s,r,e.slice(12));return new Uint8Array(i)}}class me extends M{constructor(e="There is an atom without an index",t=null,n=null){super(e,t,n),this.name="AtomIndexException"}}class nn extends M{constructor(e="The molecular hash does not match",t=null,n=null){super(e,t,n),this.name="MolecularHashMismatchException"}}class sn extends M{constructor(e="The molecular hash is missing",t=null,n=null){super(e,t,n),this.name="MolecularHashMissingException"}}class rt extends M{constructor(e="",t=null,n=null){super(e,t,n),this.name="PolicyInvalidException"}}class it extends M{constructor(e="OTS malformed",t=null,n=null){super(e,t,n),this.name="SignatureMalformedException"}}class rn extends M{constructor(e="One-time signature (OTS) does not match!",t=null,n=null){super(e,t,n),this.name="SignatureMismatchException"}}class J extends M{constructor(e="Insufficient balance to make transfer",t=null,n=null){super(e,t,n),this.name="TransferBalanceException"}}class ye extends M{constructor(e="Token transfer atoms are malformed",t=null,n=null){super(e,t,n),this.name="TransferMalformedException"}}class at extends M{constructor(e="Token slugs for wallets in transfer do not match!",t=null,n=null){super(e,t,n),this.name="TransferMismatchedException"}}class ot extends M{constructor(e="Invalid remainder provided",t=null,n=null){super(e,t,n),this.name="TransferRemainderException"}}class an extends M{constructor(e="Sender and recipient(s) cannot be the same",t=null,n=null){super(e,t,n),this.name="TransferToSelfException"}}class Te extends M{constructor(e="Token transfer atoms are unbalanced",t=null,n=null){super(e,t,n),this.name="TransferUnbalancedException"}}class P extends M{constructor(e="Empty meta data.",t=null,n=null){super(e,t,n),this.name="MetaMissingException"}}class se extends M{constructor(e="Wrong type of token for this isotope",t=null,n=null){super(e,t,n),this.name="WrongTokenTypeException"}}class Ce extends M{constructor(e="Incorrect BatchId",t=null,n=null){super(e,t,n),this.name="BatchIdException"}}class on{constructor(e={}){for(const t in e)this[`__${t}`]=e[t]}static toObject(e){return new this(e)}toJSON(){const e={};for(const t of Object.keys(this))t.substring(0,2)==="__"&&(e[t.substring(2,t.length)]=this[t]);return e}}class Ve extends M{constructor(e="An incorrect argument!",t=null,n=null){super(e,t,n),this.name="RuleArgumentException"}}class Z extends M{constructor(e="Code exception",t=null,n=null){super(e,t,n),this.name="CodeException"}}class xe{constructor({action:e,metaType:t=null,metaId:n=null,meta:s=null,address:r=null,token:i=null,amount:o=null,comparison:c=null}){if(s&&(this.meta=s),!e)throw new Ve('Callback structure violated, missing mandatory "action" parameter.');this.__metaId=n,this.__metaType=t,this.__action=e,this.__address=r,this.__token=i,this.__amount=o,this.__comparison=c}set comparison(e){this.__comparison=e}set amount(e){if(!Tt(e))throw new Z("Parameter amount should be a string containing numbers");this.__amount=e}set token(e){this.__token=e}set address(e){this.__address=e}set meta(e){this.__meta=e instanceof on?e:on.toObject(e)}set metaType(e){this.__metaType=e}set metaId(e){this.__metaId=e}static toObject(e){const t=new xe({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}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}isReject(){return this._is("reject")}isMeta(){return fe(Object.keys(this.toJSON()),["action","metaId","metaType","meta"]).length===4&&this._is("meta")}isCollect(){return fe(Object.keys(this.toJSON()),["action","address","token","amount","comparison"]).length===5&&this._is("collect")}isBuffer(){return fe(Object.keys(this.toJSON()),["action","address","token","amount","comparison"]).length===5&&this._is("buffer")}isRemit(){return fe(Object.keys(this.toJSON()),["action","token","amount"]).length===3&&this._is("remit")}isBurn(){return fe(Object.keys(this.toJSON()),["action","token","amount","comparison"]).length===4&&this._is("burn")}_is(e){return this.__action.toLowerCase()===e.toLowerCase()}}class lt{constructor({key:e,value:t,comparison:n}){if([e,t,n].some(s=>!s))throw new Ve("Condition::constructor( { key, value, comparison } ) - not all class parameters are initialised!");this.__key=e,this.__value=t,this.__comparison=n}static toObject(e){return new this({key:e.key,value:e.value,comparison:e.comparison})}toJSON(){return{key:this.__key,value:this.__value,comparison:this.__comparison}}}class Ee{constructor({condition:e=[],callback:t=[]}){for(const n of e)if(!(n instanceof lt))throw new Ve;for(const n of t)if(!(n instanceof xe))throw new Ve;this.__condition=e,this.__callback=t}set comparison(e){this.__condition.push(e instanceof lt?e:lt.toObject(e))}set callback(e){this.__callback.push(e instanceof xe?e:xe.toObject(e))}static toObject(e){if(!e.condition)throw new P("Rule::toObject() - Incorrect rule format! There is no condition field.");if(!e.callback)throw new P("Rule::toObject() - Incorrect rule format! There is no callback field.");const t=new Ee({});for(const n of e.condition)t.comparison=n;for(const n of e.callback)t.callback=n;return t}toJSON(){return{condition:this.__condition,callback:this.__callback}}}class C{static __init(e,t){this.arr=String(t).split("."),this.key=this.arr.shift();const n=Number(this.key);Number.isInteger(n)&&(this.key=n),this.__nextKey=this.arr.length,this.__next=this.__tic(e)}static __tic(e){return!Array.isArray(e)&&!(e instanceof Object)?!1:typeof e[this.key]<"u"}static has(e,t){return this.__init(e,t),this.__next?this.__nextKey===0?!0:this.has(e[this.key],this.arr.join(".")):!1}static get(e,t,n=null){return this.__init(e,t),this.__next?this.__nextKey===0?e[this.key]:this.get(e[this.key],this.arr.join("."),n):n}static set(e,t,n){const s=t.split(".");let r=e;const i=s.length-1;for(let u=0;u<i;u++){const l=s[u],d=Number(l),f=Number.isInteger(d);(f?d:l in r)||(r[f?d:l]=s[u+1].match(/^\d+$/)?[]:{}),r=r[f?d:l]}const o=s[i],c=Number(o);return r[Number.isInteger(c)?c:o]=n,e}}class ge{constructor(e){if(e.molecularHash===null)throw new sn;if(!e.atoms.length)throw new ne;for(const t of e.atoms)if(t.index===null)throw new me;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.isotopeP()&&this.isotopeA()&&this.isotopeB()&&this.isotopeF()&&this.isotopeV(e)}continuId(){if(this.molecule.atoms[0].token==="USER"&&this.molecule.getIsotopes("I").length<1)throw new ne("Check::continuId() - Molecule is missing required ContinuID Atom!");return!0}batchId(){if(this.molecule.atoms.length>0){const e=this.molecule.atoms[0];if(e.isotope==="V"&&e.batchId!==null){const t=this.molecule.getIsotopes("V"),n=t[t.length-1];if(e.batchId!==n.batchId)throw new Ce;for(const s of t)if(s.batchId===null)throw new Ce}return!0}throw new Ce}isotopeI(){for(const e of this.molecule.getIsotopes("I")){if(e.token!=="USER")throw new se(`Check::isotopeI() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index===0)throw new me(`Check::isotopeI() - Isotope "${e.isotope}" Atoms must have a non-zero index!`)}return!0}isotopeU(){for(const e of this.molecule.getIsotopes("U")){if(e.token!=="AUTH")throw new se(`Check::isotopeU() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index!==0)throw new me(`Check::isotopeU() - Isotope "${e.isotope}" Atoms must have an index equal to 0!`)}return!0}isotopeM(){const e=["readPolicy","writePolicy"];for(const t of this.molecule.getIsotopes("M")){if(t.meta.length<1)throw new P;if(t.token!=="USER")throw new se(`Check::isotopeM() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);const n=ie.aggregateMeta(t.meta);for(const s of e){let r=n[s];if(r){r=JSON.parse(r);for(const[i,o]of Object.entries(r))if(!e.includes(i)){if(!Object.keys(n).includes(i))throw new rt(`${i} is missing from the meta.`);for(const c of o)if(!_.isBundleHash(c)&&!["all","self"].includes(c))throw new rt(`${c} does not correspond to the format of the policy.`)}}}}return!0}isotopeC(){for(const e of this.molecule.getIsotopes("C")){if(e.token!=="USER")throw new se(`Check::isotopeC() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index!==0)throw new me(`Check::isotopeC() - Isotope "${e.isotope}" Atoms must have an index equal to 0!`)}return!0}isotopeT(){for(const e of this.molecule.getIsotopes("T")){const t=e.aggregatedMeta();if(String(e.metaType).toLowerCase()==="wallet"){for(const s of["position","bundle"])if(!Object.prototype.hasOwnProperty.call(t,s)||!t[s])throw new P(`Check::isotopeT() - Required meta field "${s}" is missing!`)}for(const s of["token"])if(!Object.prototype.hasOwnProperty.call(t,s)||!t[s])throw new P(`Check::isotopeT() - Required meta field "${s}" is missing!`);if(e.token!=="USER")throw new se(`Check::isotopeT() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index!==0)throw new me(`Check::isotopeT() - Isotope "${e.isotope}" Atoms must have an index equal to 0!`)}return!0}isotopeR(){for(const e of this.molecule.getIsotopes("R")){const t=e.aggregatedMeta();if(t.policy){const n=JSON.parse(t.policy);if(!Object.keys(n).every(s=>["read","write"].includes(s)))throw new P("Check::isotopeR() - Mixing rules with politics!")}if(t.rule){const n=JSON.parse(t.rule);if(!Array.isArray(n))throw new P("Check::isotopeR() - Incorrect rule format!");for(const s of n)Ee.toObject(s);if(n.length<1)throw new P("Check::isotopeR() - No rules!")}}return!0}isotopeP(){for(const e of this.molecule.getIsotopes("P")){if(e.token!=="USER")throw new se(`Check::isotopeP() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);const t=e.aggregatedMeta();if(!Object.prototype.hasOwnProperty.call(t,"peerHost")||!t.peerHost)throw new P('Check::isotopeP() - Required meta field "peerHost" is missing!')}return!0}isotopeA(){for(const e of this.molecule.getIsotopes("A")){if(e.token!=="USER")throw new se(`Check::isotopeA() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(!e.metaType)throw new P('Check::isotopeA() - Required field "metaType" is missing!');if(!e.metaId)throw new P('Check::isotopeA() - Required field "metaId" is missing!');const t=e.aggregatedMeta();if(!Object.prototype.hasOwnProperty.call(t,"action")||!t.action)throw new P('Check::isotopeA() - Required meta field "action" is missing!')}return!0}isotopeB(){const e=this.molecule.getIsotopes("B");if(e.length===0)return!0;for(const n of e){if(!n.metaType||n.metaType!=="walletBundle")throw new P('Check::isotopeB() - B-isotope atoms must have metaType "walletBundle"!');if(!n.metaId)throw new P("Check::isotopeB() - B-isotope atoms must have a metaId!");const s=Number(n.value);if(Number.isNaN(s))throw new ye("Check::isotopeB() - B-isotope atom value is not a valid number!")}const t=this.molecule.getIsotopes("V");if(t.length>0){let n=0;for(const s of[...t,...e]){const r=Number(s.value);Number.isNaN(r)||(n+=r)}if(n!==0)throw new Te("Check::isotopeB() - V+B atom values do not balance to zero!")}return!0}isotopeF(){const e=this.molecule.getIsotopes("F");if(e.length===0)return!0;for(const n of e){if(!n.metaType||n.metaType!=="walletBundle")throw new P('Check::isotopeF() - F-isotope atoms must have metaType "walletBundle"!');if(!n.metaId)throw new P("Check::isotopeF() - F-isotope atoms must have a metaId!");const s=Number(n.value);if(Number.isNaN(s))throw new ye("Check::isotopeF() - F-isotope atom value is not a valid number!");if(s<0)throw new ye("Check::isotopeF() - F-isotope atom value must not be negative!")}const t=this.molecule.getIsotopes("V");if(t.length>0){let n=0;for(const s of[...t,...e]){const r=Number(s.value);Number.isNaN(r)||(n+=r)}if(n!==0)throw new Te("Check::isotopeF() - V+F atom values do not balance to zero!")}return!0}isotopeV(e=null){const t=this.molecule.getIsotopes("V");if(t.length===0)return!0;const n=this.molecule.getIsotopes("B").length>0||this.molecule.getIsotopes("F").length>0,s=this.molecule.atoms[0];if(!n&&s.isotope==="V"&&t.length===2){const o=t[t.length-1];if(s.token!==o.token)throw new at;if(o.value<0)throw new ye;if(Number(s.value)+Number(o.value)!==0)throw new Te;return!0}let r=0,i=0;for(const o in this.molecule.atoms)if(Object.prototype.hasOwnProperty.call(this.molecule.atoms,o)){const c=this.molecule.atoms[o];if(c.isotope!=="V")continue;if(i=c.value*1,Number.isNaN(i))throw new TypeError('Invalid isotope "V" values');if(c.token!==s.token)throw new at;if(o>0){if(i<0)throw new ye;if(c.walletAddress===s.walletAddress)throw new an}r+=i}if(!n&&r!==0)throw new Te;if(e){if(i=s.value*1,Number.isNaN(i))throw new TypeError('Invalid isotope "V" values');const o=Number(e.balance)+i;if(o<0)throw new J;if(!n&&o!==r)throw new ot}else if(i!==0)throw new ot;return!0}molecularHash(){if(this.molecule.molecularHash!==b.hashAtoms({atoms:this.molecule.atoms}))throw new nn;return!0}ots(){const e=this.molecule.normalizedHash();let t=this.molecule.atoms.map(f=>f.otsFragment).reduce((f,p)=>f+p);if(t.length!==2048&&(t=Mt(t),t.length!==2048))throw new it;const n=Se(t,128);let s="";for(const f in n){let p=n[f];for(let w=0,v=8+e[f];w<v;w++)p=new F("SHAKE256","TEXT").update(p).getHash("HEX",{outputLen:512});s+=p}const r=new F("SHAKE256","TEXT");r.update(s);const i=r.getHash("HEX",{outputLen:8192}),o=new F("SHAKE256","TEXT");o.update(i);const c=o.getHash("HEX",{outputLen:256}),u=this.molecule.atoms[0];let l=u.walletAddress;const d=C.get(u.aggregatedMeta(),"signingWallet");if(d&&(l=C.get(JSON.parse(d),"address")),c!==l)throw new rn;return!0}static fromServerData({molecularHash:e,bundleHash:t,cellSlug:n=null,status:s=null,createdAt:r=null,atoms:i=[]}){const o=i.map(c=>{let u=[];if(c.metasJson)try{const l=JSON.parse(c.metasJson);Array.isArray(l)?u=l:l&&typeof l=="object"&&(u=Object.entries(l).map(([d,f])=>({key:d,value:f})))}catch{u=[]}return{position:c.position||null,walletAddress:c.walletAddress||null,isotope:c.isotope||null,token:c.tokenSlug||c.token||null,value:c.value!=null?String(c.value):null,batchId:c.batchId||null,metaType:c.metaType||null,metaId:c.metaId||null,meta:u,index:c.index!=null?c.index:null,otsFragment:c.otsFragment||null,createdAt:c.createdAt||null}});return V.fromJSON({molecularHash:e,bundle:t,cellSlug:n,status:s,createdAt:r,atoms:o})}static verifyFromServerData(e){try{const t=ge.fromServerData(e);return new ge(t).verify(),{molecularHash:e.molecularHash,verified:!0,error:null}}catch(t){return{molecularHash:e.molecularHash||null,verified:!1,error:t.message||String(t)}}}}class de extends M{constructor(e="Insufficient balance for requested transfer",t=null,n=null){super(e,t,n),this.name="BalanceInsufficientException"}}class ct extends M{constructor(e="Amount cannot be negative!",t=null,n=null){super(e,t,n),this.name="NegativeAmountException"}}class V{constructor({secret:e=null,bundle:t=null,sourceWallet:n=null,remainderWallet:s=null,cellSlug:r=null,version:i=null,continuIdPosition:o=null}){this.status=null,this.molecularHash=null,this.createdAt=String(+new Date),this.cellSlugOrigin=this.cellSlug=r,this.secret=e,this.bundle=t,this.sourceWallet=n,this.continuIdPosition=o,this.atoms=[],this.parentHashes=[],i!==null&&Object.prototype.hasOwnProperty.call(He,i)&&(this.version=String(i)),(s||n)&&(this.remainderWallet=s||_.create({secret:e,bundle:t,token:n.token,batchId:n.batchId,characters:n.characters}))}withParentHashes(e){return this.parentHashes=Array.isArray(e)?[...e]:[],this}get cellSlugDelimiter(){return"."}static isotopeFilter(e,t){return Array.isArray(e)||(e=[e]),t.filter(n=>e.includes(n.isotope))}static generateNextAtomIndex(e){return e.length}static jsonToObject(e){const t=Object.assign(new V({}),JSON.parse(e)),n=Object.keys(new V({}));if(!Array.isArray(t.atoms))throw new ne;for(const s in Object.keys(t.atoms)){t.atoms[s]=b.jsonToObject(JSON.stringify(t.atoms[s]));for(const r of["position","walletAddress","isotope"])if(t.atoms[s].isotope.toLowerCase()!=="r"&&(typeof t.atoms[s][r]>"u"||t.atoms[s][r]===null))throw new ne("MolecularStructure::jsonToObject() - Required Atom properties are missing!")}for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&!n.includes(s)&&delete t[s];return t.atoms=b.sortAtoms(t.atoms),t}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},n=[],s=e.toLowerCase().split("");for(let r=0,i=s.length;r<i;++r){const o=s[r];typeof t[o]<"u"&&(n[r]=t[o])}return n}static normalize(e){let t=e.reduce((s,r)=>s+r);const n=t<0;for(;t<0||t>0;)for(const s of Object.keys(e))if((n?e[s]<8:e[s]>-8)&&(n?(++e[s],++t):(--e[s],--t),t===0))break;return e}getIsotopes(e){return V.isotopeFilter(e,this.atoms)}generateIndex(){return V.generateNextAtomIndex(this.atoms)}fill(e){for(const t in Object.keys(e))this[t]=e[t]}addAtom(e){return this.molecularHash=null,e.index=this.generateIndex(),e.version=this.version,this.atoms.push(e),this.atoms=b.sortAtoms(this.atoms),this}addContinuIdAtom(){(!this.remainderWallet||this.remainderWallet.token!=="USER")&&(this.remainderWallet=_.create({secret:this.secret,bundle:this.bundle}));const e={};return this.continuIdPosition?e.previousPosition=this.continuIdPosition:this.sourceWallet&&this.sourceWallet.position&&(e.previousPosition=this.sourceWallet.position),this.remainderWallet.pubkey&&(e.pubkey=this.remainderWallet.pubkey),this.remainderWallet.characters&&(e.characters=this.remainderWallet.characters),this.addAtom(b.create({isotope:"I",wallet:this.remainderWallet,metaType:"walletBundle",metaId:this.remainderWallet.bundle,meta:new B(e)})),this}addPolicyAtom({metaType:e,metaId:t,meta:n={},policy:s={}}){const r=new B(n);return r.addPolicy(s),this.addAtom(b.create({wallet:this.sourceWallet,isotope:"R",metaType:e,metaId:t,meta:r})),this}fuseToken(e,t){const n=e.length;if(this.sourceWallet.balance-n<0)throw new de;return this.addAtom(b.create({isotope:"V",wallet:this.sourceWallet,value:-n})),this.addAtom(b.create({isotope:"F",wallet:t,value:1,metaType:"walletBundle",metaId:t.bundle})),this.addAtom(b.create({isotope:"V",wallet:this.remainderWallet,value:this.sourceWallet.balance-n,metaType:"walletBundle",metaId:this.remainderWallet.bundle})),this}burnToken({amount:e,walletBundle:t=null}){if(e<0)throw new ct("Molecule::burnToken() - Amount to burn must be positive!");if(this.sourceWallet.balance-e<0)throw new de;const n=new _({bundle:"0000000000000000000000000000000000000000000000000000000000000000",token:this.sourceWallet.token});return this.addAtom(b.create({isotope:"V",wallet:this.sourceWallet,value:-this.sourceWallet.balance})),this.addAtom(b.create({isotope:"V",wallet:n,value:e,metaType:"walletBundle",metaId:n.bundle})),this.addAtom(b.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 ct("Molecule::replenishToken() - Amount to replenish must be positive!");if(t.length){t=_.getTokenUnits(t),this.remainderWallet.tokenUnits=this.sourceWallet.tokenUnits;for(const n of t)this.remainderWallet.tokenUnits.push(n);this.remainderWallet.balance=String(this.remainderWallet.tokenUnits.length),this.sourceWallet.tokenUnits=t,this.sourceWallet.balance=String(this.sourceWallet.tokenUnits.length)}else this.remainderWallet.balance=String(Number(this.sourceWallet.balance)+e),this.sourceWallet.balance=String(e);return this.addAtom(b.create({isotope:"V",wallet:this.sourceWallet,value:Number(this.sourceWallet.balance)})),this.addAtom(b.create({isotope:"V",wallet:this.remainderWallet,value:Number(this.remainderWallet.balance),metaType:"walletBundle",metaId:this.remainderWallet.bundle})),this}initValue({recipientWallet:e,amount:t}){if(this.sourceWallet.balance-t<0)throw new de;return this.addAtom(b.create({isotope:"V",wallet:this.sourceWallet,value:-this.sourceWallet.balance})),this.addAtom(b.create({isotope:"V",wallet:e,value:t,metaType:"walletBundle",metaId:e.bundle})),this.addAtom(b.create({isotope:"V",wallet:this.remainderWallet,value:this.sourceWallet.balance-t,metaType:"walletBundle",metaId:this.remainderWallet.bundle})),this}initValues({recipientWallets:e,amounts:t}){const n=t.reduce((s,r)=>s+Number(r),0);if(this.sourceWallet.balance-n<0)throw new de;return this.addAtom(b.create({isotope:"V",wallet:this.sourceWallet,value:-this.sourceWallet.balance})),e.forEach((s,r)=>{this.addAtom(b.create({isotope:"V",wallet:s,value:t[r],metaType:"walletBundle",metaId:s.bundle}))}),this.addAtom(b.create({isotope:"V",wallet:this.remainderWallet,value:this.sourceWallet.balance-n,metaType:"walletBundle",metaId:this.remainderWallet.bundle})),this}initDepositBuffer({amount:e,tradeRates:t}){if(this.sourceWallet.balance-e<0)throw new de;const n=_.create({secret:this.secret,bundle:this.bundle,token:this.sourceWallet.token,batchId:this.sourceWallet.batchId});return n.tradeRates=t,this.addAtom(b.create({isotope:"V",wallet:this.sourceWallet,value:-this.sourceWallet.balance})),this.addAtom(b.create({isotope:"B",wallet:n,value:e,metaType:"walletBundle",metaId:this.sourceWallet.bundle})),this.addAtom(b.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 n=0;for(const r of Object.values(e||{}))n+=r;if(this.sourceWallet.balance-n<0)throw new de;const s=new B;t&&s.setSigningWallet(t),this.addAtom(b.create({isotope:"B",wallet:this.sourceWallet,value:-this.sourceWallet.balance,meta:s,metaType:"walletBundle",metaId:this.sourceWallet.bundle}));for(const[r,i]of Object.entries(e||{}))this.addAtom(new b({isotope:"V",token:this.sourceWallet.token,value:i,batchId:this.sourceWallet.batchId?$e({}):null,metaType:"walletBundle",metaId:r}));return this.addAtom(b.create({isotope:"B",wallet:this.remainderWallet,value:this.sourceWallet.balance-n,metaType:"walletBundle",metaId:this.remainderWallet.bundle})),this}initTokenCreation({recipientWallet:e,amount:t,meta:n}){const s=new B(n);return s.setMetaWallet(e),this.addAtom(b.create({isotope:"C",wallet:this.sourceWallet,value:t,metaType:"token",metaId:e.token,meta:s,batchId:e.batchId})),this.addContinuIdAtom(),this}createRule({metaType:e,metaId:t,rule:n,policy:s={}}){const r=[];for(const o of n)r.push(o instanceof Ee?o:Ee.toObject(o));const i=new B({rule:JSON.stringify(r)});return i.addPolicy(s),this.addAtom(b.create({isotope:"R",wallet:this.sourceWallet,metaType:e,metaId:t,meta:i})),this.addContinuIdAtom(),this}initWalletCreation(e,t=null){t||(t=new B),t.setMetaWallet(e);const n=b.create({isotope:"C",wallet:this.sourceWallet,metaType:"wallet",metaId:e.address,meta:t,batchId:e.batchId});return this.addAtom(n),this.addContinuIdAtom(),this}initShadowWalletClaim(e){const t=new B().setShadowWalletClaim(!0);return this.initWalletCreation(e,t)}initIdentifierCreation({type:e,contact:t,code:n}){const s={code:n,hash:oe(t.trim(),"Molecule::initIdentifierCreation")};return this.addAtom(b.create({isotope:"C",wallet:this.sourceWallet,metaType:"identifier",metaId:e,meta:new B(s)})),this.addContinuIdAtom(),this}initMeta({meta:e,metaType:t,metaId:n,policy:s}){return this.addAtom(b.create({isotope:"M",wallet:this.sourceWallet,metaType:t,metaId:n,meta:new B(e)})),s&&Object.keys(s).length>0&&this.addPolicyAtom({metaType:t,metaId:n,meta:e,policy:s}),this.addContinuIdAtom(),this}initPeering({host:e}){return this.addAtom(b.create({isotope:"P",wallet:this.sourceWallet,metaType:"walletBundle",metaId:this.bundle,meta:new B({peerHost:e})})),this.addContinuIdAtom(),this}initAppendRequest({metaType:e,metaId:t,action:n,meta:s={}}){return this.addAtom(b.create({isotope:"A",wallet:this.sourceWallet,metaType:e,metaId:t,meta:new B({action:n,...s})})),this.addContinuIdAtom(),this}initTokenRequest({token:e,amount:t,metaType:n,metaId:s,meta:r={},batchId:i=null}){return r.token=e,r.amount=String(t),this.addAtom(b.create({isotope:"T",wallet:this.sourceWallet,value:t,metaType:n,metaId:s,meta:new B(r),batchId:i})),this.addContinuIdAtom(),this}initAuthorization({meta:e}){return this.addAtom(b.create({isotope:"U",wallet:this.sourceWallet,meta:new B(e)})),this.addContinuIdAtom(),this}sign({bundle:e=null,anonymous:t=!1,compressed:n=!0}){if(this.atoms.length===0||this.atoms.filter(p=>!(p instanceof b)).length!==0)throw new ne;!t&&!this.bundle&&(this.bundle=e||oe(this.secret,"Molecule::sign")),this.molecularHash=b.hashAtoms({atoms:this.atoms});const s=this.atoms[0];let r=s.position;const i=C.get(s.aggregatedMeta(),"signingWallet");if(i&&(r=C.get(JSON.parse(i),"position")),!r)throw new it("Signing wallet must have a position!");const o=_.generateKey({secret:this.secret,token:s.token,position:s.position}),c=Se(o,128),u=this.normalizedHash();let l="";for(const p in c){let w=c[p];for(let v=0,q=8-u[p];v<q;v++)w=new F("SHAKE256","TEXT").update(w).getHash("HEX",{outputLen:512});l+=w}n&&(l=It(l));const d=Se(l,Math.ceil(l.length/this.atoms.length));let f=null;for(let p=0,w=d.length;p<w;p++)this.atoms[p].otsFragment=d[p],f=this.atoms[p].position;return f}signSync(e={}){return this.sign(e)}cellSlugBase(){return(this.cellSlug||"").split(this.cellSlugDelimiter)[0]}toJSON(e={}){const{includeValidationContext:t=!1,includeOtsFragments:n=!0}=e;try{const s={status:this.status,molecularHash:this.molecularHash,createdAt:this.createdAt,cellSlug:this.cellSlug,bundle:this.bundle,atoms:this.atoms.map(r=>r.toJSON({includeOtsFragments:n}))};return this.parentHashes&&this.parentHashes.length>0&&(s.parentHashes=this.parentHashes),t&&(s.cellSlugOrigin=this.cellSlugOrigin,s.version=this.version,this.sourceWallet&&(s.sourceWallet={address:this.sourceWallet.address,position:this.sourceWallet.position,token:this.sourceWallet.token,balance:this.sourceWallet.balance||"0",bundle:this.sourceWallet.bundle,batchId:this.sourceWallet.batchId||null,characters:this.sourceWallet.characters||"BASE64",pubkey:this.sourceWallet.pubkey||null,tokenUnits:this.sourceWallet.tokenUnits||[],tradeRates:this.sourceWallet.tradeRates||{},molecules:this.sourceWallet.molecules||{}}),this.remainderWallet&&(s.remainderWallet={address:this.remainderWallet.address,position:this.remainderWallet.position,token:this.remainderWallet.token,balance:this.remainderWallet.balance||"0",bundle:this.remainderWallet.bundle,batchId:this.remainderWallet.batchId||null,characters:this.remainderWallet.characters||"BASE64",pubkey:this.remainderWallet.pubkey||null,tokenUnits:this.remainderWallet.tokenUnits||[],tradeRates:this.remainderWallet.tradeRates||{},molecules:this.remainderWallet.molecules||{}})),s}catch(s){throw new Error(`Molecule serialization failed: ${s.message}`)}}static fromJSON(e,t={}){const{includeValidationContext:n=!1,validateStructure:s=!0}=t;try{const r=typeof e=="string"?JSON.parse(e):e;if(s&&(!r.molecularHash||!Array.isArray(r.atoms)))throw new Error("Invalid molecule data: missing molecularHash or atoms array");const i=new V({secret:null,bundle:r.bundle||null,cellSlug:r.cellSlug||null,version:r.version||null});return i.status=r.status,i.molecularHash=r.molecularHash,i.createdAt=r.createdAt||String(+new Date),i.cellSlugOrigin=r.cellSlugOrigin,i.parentHashes=Array.isArray(r.parentHashes)?[...r.parentHashes]:[],Array.isArray(r.atoms)&&(i.atoms=r.atoms.map((o,c)=>{try{return b.fromJSON(o)}catch(u){throw new Error(`Failed to reconstruct atom ${c}: ${u.message}`)}})),n&&(r.sourceWallet&&(i.sourceWallet=new _({secret:null,token:r.sourceWallet.token,position:r.sourceWallet.position,bundle:r.sourceWallet.bundle,batchId:r.sourceWallet.batchId,characters:r.sourceWallet.characters}),i.sourceWallet.balance=String(r.sourceWallet.balance!=null?r.sourceWallet.balance:0),i.sourceWallet.address=r.sourceWallet.address,r.sourceWallet.pubkey&&(i.sourceWallet.pubkey=r.sourceWallet.pubkey),i.sourceWallet.tokenUnits=r.sourceWallet.tokenUnits||[],i.sourceWallet.tradeRates=r.sourceWallet.tradeRates||{},i.sourceWallet.molecules=r.sourceWallet.molecules||{}),r.remainderWallet&&(i.remainderWallet=new _({secret:null,token:r.remainderWallet.token,position:r.remainderWallet.position,bundle:r.remainderWallet.bundle,batchId:r.remainderWallet.batchId,characters:r.remainderWallet.characters}),i.remainderWallet.balance=String(r.remainderWallet.balance!=null?r.remainderWallet.balance:0),i.remainderWallet.address=r.remainderWallet.address,r.remainderWallet.pubkey&&(i.remainderWallet.pubkey=r.remainderWallet.pubkey),i.remainderWallet.tokenUnits=r.remainderWallet.tokenUnits||[],i.remainderWallet.tradeRates=r.remainderWallet.tradeRates||{},i.remainderWallet.molecules=r.remainderWallet.molecules||{})),i}catch(r){throw new Error(`Molecule deserialization failed: ${r.message}`)}}check(e=null){return new ge(this).verify(e)}normalizedHash(){return V.normalize(V.enumerate(this.molecularHash))}}class be{constructor({token:e,expiresAt:t,encrypt:n,pubkey:s}){this.$__token=e,this.$__expiresAt=t,this.$__pubkey=s,this.$__encrypt=n}static create(e,t){const n=new be(e);return n.setWallet(t),n}static restore(e,t){const n=new _({secret:t,token:"AUTH",position:e.wallet.position,characters:e.wallet.characters});return be.create({token:e.token,expiresAt:e.expiresAt,pubkey:e.pubkey,encrypt:e.encrypt},n)}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 this.$__expiresAt*1e3-Date.now()}isExpired(){return!this.$__expiresAt||this.getExpireInterval()<0}getAuthData(){return{token:this.getToken(),pubkey:this.getPubkey(),wallet:this.getWallet()}}}const ut=10**18;class re{static val(e){return Math.abs(e*ut)<1?0:e}static cmp(e,t,n=!1){const s=re.val(e)*ut,r=re.val(t)*ut;return Math.abs(s-r)<1?0:s>r?1:-1}static equal(e,t){return re.cmp(e,t)===0}}class te extends M{constructor(e="GraphQL did not provide a valid response.",t=null,n=null){super(e,t,n),this.name="InvalidResponseException"}}class Re extends M{constructor(e="Authorization token missing or invalid.",t=null,n=null){super(e,t,n),this.name="UnauthenticatedException"}}let E=class{constructor({query:e,json:t,dataKey:n=null}){if(this.dataKey=n,this.errorKey="exception",this.$__payload=null,this.$__query=e,this.$__originResponse=t,this.$__response=t,typeof this.$__response>"u"||this.$__response===null)throw new te;if(C.has(this.$__response,this.errorKey)){const s=C.get(this.$__response,this.errorKey);throw String(s).includes("Unauthenticated")?new Re:new te}if(this.$__response.errors&&Array.isArray(this.$__response.errors)&&this.$__response.errors.length>0){const s=this.$__response.errors[0].message||"Unknown GraphQL error";throw s.includes("Unauthenticated")?new Re:new te(`GraphQL Error: ${s}`)}this.init()}init(){}data(){if(!this.dataKey)return this.response();if(!this.response().data)throw new te("Response has no data field");if(!C.has(this.response(),this.dataKey))throw new te(`Missing expected field: ${this.dataKey}`);return C.get(this.response(),this.dataKey)}response(){return this.$__response}payload(){return null}query(){return this.$__query}status(){return null}success(){return!this.$__response?.errors?.length}error(){return this.$__response?.errors?.length?this.$__response.errors[0].message||"Unknown error":null}reason(){return this.error()}toValidationResult(){return this.success()&&this.payload()!==null?{success:!0,data:this.payload(),warnings:[]}:{success:!1,error:{message:this.reason()||"Unknown error",context:this.constructor.name,details:this.$__response?.errors||[]}}}onSuccess(e){if(this.success()&&this.payload()!==null)try{e(this.payload())}catch(t){console.warn("Response.onSuccess callback failed:",t)}return this}onFailure(e){if(!this.success())try{e(this.reason()||"Unknown error")}catch(t){console.warn("Response.onFailure callback failed:",t)}return this}debug(e=null){const t=e?`[${e}]`:`[${this.constructor.name}]`;return this.success()?console.debug(`${t} Success:`,{payload:this.payload(),query:this.$__query?.constructor?.name,dataKey:this.dataKey}):console.debug(`${t} Failure:`,{error:this.reason(),errors:this.$__response?.errors,rawData:this.$__response}),this}toPromise(){return this.success()&&this.payload()!==null?Promise.resolve(this.payload()):Promise.reject(new Error(this.reason()||"Unknown error"))}map(e){if(this.success()&&this.payload()!==null)try{const t=e(this.payload()),n=Object.create(Object.getPrototypeOf(this));return Object.assign(n,this),n.$__payload=t,n}catch(t){const n=Object.create(Object.getPrototypeOf(this));return Object.assign(n,this),n.$__response={errors:[{message:`Mapping failed: ${t.message}`}]},n}else return this}};class H{constructor(e,t){this.client=e,this.knishIOClient=t,this.$__variables=null,this.$__query=null,this.$__response=null,this.$__request=null}response(){return this.$__response}async createResponseRaw(e){return this.createResponse(e)}createResponse(e){return new E({query:this,json:e})}createQuery({variables:e=null}){if(this.$__variables=this.compiledVariables(e),!this.uri())throw new Z("Query::createQuery() - Node URI was not initialized for this client instance!");if(this.$__query===null)throw new Z("Query::createQuery() - GraphQL subscription was not initialized!");return{query:this.$__query,variables:this.variables()}}async execute({variables:e=null,context:t={}}){this.$__request=this.createQuery({variables:e});const n={...t,...this.createQueryContext()};try{const s=await this.client.query({...this.$__request,context:n});return this.$__response=await this.createResponseRaw(s),this.$__response}catch(s){if(s.name==="AbortError")return this.knishIOClient.log("warn","Query was cancelled"),new E({query:this,json:{data:null,errors:[{message:"Query was cancelled"}]}});throw s}}compiledVariables(e=null){return e||{}}uri(){return this.client.getUri()}variables(){return this.$__variables}createQueryContext(){return{}}}class ln extends E{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 _({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=String(t.amount!=null?t.amount:0)),e}}class cn extends H{constructor(e,t){super(e,t),this.$__query=T.gql`query ($bundle: String!) {
4
+ ${this.stack}`}}class se extends I{constructor(e="The molecule does not contain atoms",t=null,n=null){super(e,t,n),this.name="AtomsMissingException"}}class le{static create(e){const t={};for(const n of Object.keys(e))Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return new this(t)}static structure(e){switch(Object.prototype.toString.call(e)){case"[object Array]":{const t=[];for(const n in e)t.push(le.isStructure(e[n])?le.structure(e[n]):e[n]);return t}case"[object Object]":{const t=[],n=Object.keys(e).sort((s,r)=>s===r?0:s<r?-1:1);for(const s of n)if(Object.prototype.hasOwnProperty.call(e,s)){const r={};r[s]=le.isStructure(e[s])?le.structure(e[s]):e[s],t.push(r)}if(t.length>0)return t;break}}return e}static isStructure(e){return["[object Object]","[object Array]"].includes(Object.prototype.toString.call(e))}view(){return le.structure(this)}}class $s extends le{constructor({position:e=null,walletAddress:t=null,isotope:n=null,token:s=null,value:r=null,batchId:i=null,metaType:o=null,metaId:c=null,meta:u=null,index:l=null,createdAt:d=null,version:f=null}){super(),this.position=e,this.walletAddress=t,this.isotope=n,this.token=s,this.value=r,this.batchId=i,this.metaType=o,this.metaId=c,this.meta=u,this.index=l,this.createdAt=d,this.version=f}}const Qe={4:$s};class b{constructor({position:e=null,walletAddress:t=null,isotope:n=null,token:s=null,value:r=null,batchId:i=null,metaType:o=null,metaId:c=null,meta:u=null,otsFragment:l=null,index:d=null,version:f=null}){this.position=e,this.walletAddress=t,this.isotope=n,this.token=s,this.value=r!==null?String(r):null,this.batchId=i,this.metaType=o,this.metaId=c,this.meta=u?oe.normalizeMeta(u):[],this.index=d,this.otsFragment=l,this.createdAt=String(+new Date),f!==null&&Object.prototype.hasOwnProperty.call(Qe,f)&&(this.version=String(f))}static getHashableProps(){return["position","walletAddress","isotope","token","value","batchId","metaType","metaId","meta","createdAt"]}static getUnclaimedProps(){return["otsFragment"]}static create({isotope:e,wallet:t=null,value:n=null,metaType:s=null,metaId:r=null,meta:i=null,batchId:o=null}){return i||(i=new P),i instanceof P||(i=new P(i)),t&&(i.setAtomWallet(t),o||(o=t.batchId)),new b({position:t?t.position:null,walletAddress:t?t.address:null,isotope:e,token:t?t.token:null,value:n,batchId:o,metaType:s,metaId:r,meta:i.get()})}static jsonToObject(e){const t=Object.assign(new b({}),JSON.parse(e)),n=Object.keys(new b({}));for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&!n.includes(s)&&delete t[s];return t}toJSON(e={}){const{includeOtsFragments:t=!0,validateFields:n=!1}=e;try{if(n){const r=["position","walletAddress","isotope","token"];for(const i of r)if(!this[i])throw new Error(`Required field '${i}' is missing or empty`)}const s={position:this.position??"",walletAddress:this.walletAddress??"",isotope:this.isotope,token:this.token??"",value:this.value,batchId:this.batchId,metaType:this.metaType,metaId:this.metaId,meta:this.meta||[],index:this.index,createdAt:this.createdAt,version:this.version};return t&&this.otsFragment&&(s.otsFragment=this.otsFragment),s}catch(s){throw new Error(`Atom serialization failed: ${s.message}`)}}static fromJSON(e,t={}){const{validateStructure:n=!0,strictMode:s=!1}=t;try{const r=typeof e=="string"?JSON.parse(e):e;if(s||n){const o=["position","walletAddress","isotope","token"];for(const c of o)if(!r[c])throw new Error(`Required field '${c}' is missing or empty`)}const i=new b({position:r.position,walletAddress:r.walletAddress,isotope:r.isotope,token:r.token,value:r.value,batchId:r.batchId,metaType:r.metaType,metaId:r.metaId,meta:r.meta,index:r.index,version:r.version});return r.otsFragment&&(i.otsFragment=r.otsFragment),r.createdAt&&(i.createdAt=r.createdAt),i}catch(r){throw new Error(`Atom deserialization failed: ${r.message}`)}}static hashAtoms({atoms:e,output:t="base17"}){const n=new D("SHAKE256","TEXT"),s=b.sortAtoms(e);if(s.length===0)throw new se;if(s.map(r=>{if(!(r instanceof b))throw new se;return r}),s.every(r=>r.version&&Object.prototype.hasOwnProperty.call(Qe,r.version)))n.update(JSON.stringify(s.map(r=>Qe[r.version].create(r).view())));else{const r=String(e.length);let i=[];for(const o of s)i.push(r),i=i.concat(o.getHashableValues());for(const o of i)n.update(o)}switch(t){case"hex":return n.getHash("HEX",{outputLen:256});case"array":return n.getHash("ARRAYBUFFER",{outputLen:256});default:return Rt(n.getHash("HEX",{outputLen:256}),16,17,"0123456789abcdef","0123456789abcdefg").padStart(64,"0")}}static jsonSerialization(e,t){if(!b.getUnclaimedProps().includes(e))return t}static sortAtoms(e){const t=[...e];return t.sort((n,s)=>n.index<s.index?-1:1),t}aggregatedMeta(){return oe.aggregateMeta(this.meta)}getHashableValues(){const e=[];for(const t of b.getHashableProps()){const n=this[t];if(!(n===null&&!["position","walletAddress"].includes(t)))if(t==="meta")for(const s of n)typeof s.value<"u"&&s.value!==null&&(e.push(String(s.key)),e.push(String(s.value)));else e.push(n===null?"":String(n))}return e}}function De(a=null,e=2048){if(a){const t=new D("SHAKE256","TEXT");return t.update(a),t.getHash("HEX",{outputLen:e*4})}else return Ne(e)}function ce(a,e=null){const t=new D("SHAKE256","TEXT");return t.update(a),t.getHash("HEX",{outputLen:256})}function je(a,e){const t=new D("SHAKE256","TEXT");return t.update(a),t.getHash("HEX",{outputLen:e})}function Me({molecularHash:a=null,index:e=null}){return a!==null&&e!==null?ce(String(a)+String(e),"generateBatchId"):Ne(64)}class ue{constructor(e,t,n){this.id=e,this.name=t,this.metas=n||{}}static createFromGraphQL(e){let t=e.metas||{};return t.length&&(t=JSON.parse(t),t||(t={})),new ue(e.id,e.name,t)}static createFromDB(e){return new ue(e[0],e[1],e.length>2?e[2]:{})}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 at extends I{constructor(e="Attempting to create a wallet with no credentials (secret or bundle hash)",t=null,n=null){super(e,t,n),this.name="WalletCredentialException"}}const Ve=BigInt(2**32-1),Ht=BigInt(32);function As(a,e=!1){return e?{h:Number(a&Ve),l:Number(a>>Ht&Ve)}:{h:Number(a>>Ht&Ve)|0,l:Number(a&Ve)|0}}function vs(a,e=!1){const t=a.length;let n=new Uint32Array(t),s=new Uint32Array(t);for(let r=0;r<t;r++){const{h:i,l:o}=As(a[r],e);[n[r],s[r]]=[i,o]}return[n,s]}const Is=(a,e,t)=>a<<t|e>>>32-t,Ms=(a,e,t)=>e<<t|a>>>32-t,Ts=(a,e,t)=>e<<t-32|a>>>64-t,Cs=(a,e,t)=>a<<t-32|e>>>64-t;function xs(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&a.constructor.name==="Uint8Array"}function Kt(a,e=""){if(!Number.isSafeInteger(a)||a<0){const t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${a}`)}}function V(a,e,t=""){const n=xs(a),s=a?.length,r=e!==void 0;if(!n||r&&s!==e){const i=t&&`"${t}" `,o=r?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof a}`;throw new Error(i+"expected Uint8Array"+o+", got "+c)}return a}function Nt(a,e=!0){if(a.destroyed)throw new Error("Hash instance has been destroyed");if(e&&a.finished)throw new Error("Hash#digest() has already been called")}function Es(a,e){V(a,void 0,"digestInto() output");const t=e.outputLen;if(a.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function Ft(a){return new Uint32Array(a.buffer,a.byteOffset,Math.floor(a.byteLength/4))}function Lt(...a){for(let e=0;e<a.length;e++)a[e].fill(0)}const Rs=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function qs(a){return a<<24&4278190080|a<<8&16711680|a>>>8&65280|a>>>24&255}function Os(a){for(let e=0;e<a.length;e++)a[e]=qs(a[e]);return a}const Qt=Rs?a=>a:Os;function Dt(a,e={}){const t=(s,r)=>a(r).update(s).digest(),n=a(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=s=>a(s),Object.assign(t,e),Object.freeze(t)}function Bs(a=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(a))}const ze=a=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,a])}),Ws=BigInt(0),Te=BigInt(1),Us=BigInt(2),Ps=BigInt(7),Hs=BigInt(256),Ks=BigInt(113),jt=[],Vt=[],zt=[];for(let a=0,e=Te,t=1,n=0;a<24;a++){[t,n]=[n,(2*t+3*n)%5],jt.push(2*(5*n+t)),Vt.push((a+1)*(a+2)/2%64);let s=Ws;for(let r=0;r<7;r++)e=(e<<Te^(e>>Ps)*Ks)%Hs,e&Us&&(s^=Te<<(Te<<BigInt(r))-Te);zt.push(s)}const Jt=vs(zt,!0),Ns=Jt[0],Fs=Jt[1],Gt=(a,e,t)=>t>32?Ts(a,e,t):Is(a,e,t),Xt=(a,e,t)=>t>32?Cs(a,e,t):Ms(a,e,t);function Ls(a,e=24){const t=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let i=0;i<10;i++)t[i]=a[i]^a[i+10]^a[i+20]^a[i+30]^a[i+40];for(let i=0;i<10;i+=2){const o=(i+8)%10,c=(i+2)%10,u=t[c],l=t[c+1],d=Gt(u,l,1)^t[o],f=Xt(u,l,1)^t[o+1];for(let p=0;p<50;p+=10)a[i+p]^=d,a[i+p+1]^=f}let s=a[2],r=a[3];for(let i=0;i<24;i++){const o=Vt[i],c=Gt(s,r,o),u=Xt(s,r,o),l=jt[i];s=a[l],r=a[l+1],a[l]=c,a[l+1]=u}for(let i=0;i<50;i+=10){for(let o=0;o<10;o++)t[o]=a[i+o];for(let o=0;o<10;o++)a[i+o]^=~t[(o+2)%10]&t[(o+4)%10]}a[0]^=Ns[n],a[1]^=Fs[n]}Lt(t)}class Je{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;enableXOF=!1;rounds;constructor(e,t,n,s=!1,r=24){if(this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=s,this.rounds=r,Kt(n,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Ft(this.state)}clone(){return this._cloneInto()}keccak(){Qt(this.state32),Ls(this.state32,this.rounds),Qt(this.state32),this.posOut=0,this.pos=0}update(e){Nt(this),V(e);const{blockLen:t,state:n}=this,s=e.length;for(let r=0;r<s;){const i=Math.min(t-this.pos,s-r);for(let o=0;o<i;o++)n[this.pos++]^=e[r++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:s}=this;e[n]^=t,(t&128)!==0&&n===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){Nt(this,!1),V(e),this.finish();const t=this.state,{blockLen:n}=this;for(let s=0,r=e.length;s<r;){this.posOut>=n&&this.keccak();const i=Math.min(n-this.posOut,r-s);e.set(t.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Kt(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Es(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Lt(this.state)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:s,rounds:r,enableXOF:i}=this;return e||=new Je(t,n,s,i,r),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=r,e.suffix=n,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}}const Zt=(a,e,t,n={})=>Dt(()=>new Je(e,a,t),n),Qs=Zt(6,136,32,ze(8)),Ds=Zt(6,72,64,ze(10)),Yt=(a,e,t,n={})=>Dt((s={})=>new Je(e,a,s.dkLen===void 0?t:s.dkLen,!0),n),js=Yt(31,168,16,ze(11)),en=Yt(31,136,32,ze(12));function ot(a){if(!Number.isSafeInteger(a)||a<0||a>4294967295)throw new Error("wrong u32 integer:"+a);return a}function tn(a){return ot(a),(a&a-1)===0&&a!==0}function nn(a,e){ot(a);let t=0;for(let n=0;n<e;n++,a>>>=1)t=t<<1|a&1;return t}function sn(a){return ot(a),31-Math.clz32(a)}function rn(a){const e=a.length;if(e<2||!tn(e))throw new Error("n must be a power of 2 and greater than 1. Got "+e);const t=sn(e);for(let n=0;n<e;n++){const s=nn(n,t);if(n<s){const r=a[n];a[n]=a[s],a[s]=r}}return a}const an=(a,e)=>{const{N:t,roots:n,dit:s,invertButterflies:r=!1,skipStages:i=0,brp:o=!0}=e,c=sn(t);if(!tn(t))throw new Error("FFT: Polynomial size should be power of two");const u=s!==r;return l=>{if(l.length!==t)throw new Error("FFT: wrong Polynomial length");s&&o&&rn(l);for(let d=0,f=1;d<c-i;d++){const p=s?d+1+i:c-d,w=1<<p,v=w>>1,O=t>>p;for(let y=0;y<t;y+=w)for(let m=0,k=f++;m<v;m++){const R=r?s?t-k:k:m*O,_=y+m,A=y+m+v,M=n[R],x=l[A],$=l[_];if(u){const F=a.mul(x,M);l[_]=a.add($,F),l[A]=a.sub($,F)}else r?(l[_]=a.add(x,$),l[A]=a.mul(a.sub(x,$),M)):(l[_]=a.add($,x),l[A]=a.mul(a.sub($,x),M))}}return!s&&o&&rn(l),l}};const on=Bs;function lt(a,e){if(a.length!==e.length)return!1;let t=0;for(let n=0;n<a.length;n++)t|=a[n]^e[n];return t===0}function Vs(a){return Uint8Array.from(a)}function Ge(a,...e){const t=s=>typeof s=="number"?s:s.bytesLen,n=e.reduce((s,r)=>s+t(r),0);return{bytesLen:n,encode:s=>{const r=new Uint8Array(n);for(let i=0,o=0;i<e.length;i++){const c=e[i],u=t(c),l=typeof c=="number"?s[i]:c.encode(s[i]);V(l,u,a),r.set(l,o),typeof c!="number"&&l.fill(0),o+=u}return r},decode:s=>{V(s,n,a);const r=[];for(const i of e){const o=t(i),c=s.subarray(0,o);r.push(typeof i=="number"?c:i.decode(c)),s=s.subarray(o)}return r}}}function ct(a,e){const t=e*a.bytesLen;return{bytesLen:t,encode:n=>{if(n.length!==e)throw new Error(`vecCoder.encode: wrong length=${n.length}. Expected: ${e}`);const s=new Uint8Array(t);for(let r=0,i=0;r<n.length;r++){const o=a.encode(n[r]);s.set(o,i),o.fill(0),i+=o.length}return s},decode:n=>{V(n,t);const s=[];for(let r=0;r<n.length;r+=a.bytesLen)s.push(a.decode(n.subarray(r,r+a.bytesLen)));return s}}}function Z(...a){for(const e of a)if(Array.isArray(e))for(const t of e)t.fill(0);else e.fill(0)}function ln(a){return(1<<a)-1}const zs=a=>{const{newPoly:e,N:t,Q:n,F:s,ROOT_OF_UNITY:r,brvBits:i}=a,o=(y,m=n)=>{const k=y%m|0;return(k>=0?k|0:m+k|0)|0},c=(y,m=n)=>{const k=o(y,m)|0;return(k>m>>1?k-m|0:k)|0};function u(){const y=e(t);for(let m=0;m<t;m++){const k=nn(m,i),R=BigInt(r)**BigInt(k)%BigInt(n);y[m]=Number(R)|0}return y}const l=u(),d={add:(y,m)=>o((y|0)+(m|0))|0,sub:(y,m)=>o((y|0)-(m|0))|0,mul:(y,m)=>o((y|0)*(m|0))|0,inv:y=>{throw new Error("not implemented")}},f={N:t,roots:l,invertButterflies:!0,skipStages:1,brp:!1},p=an(d,{dit:!1,...f}),w=an(d,{dit:!0,...f});return{mod:o,smod:c,nttZetas:l,NTT:{encode:y=>p(y),decode:y=>{w(y);for(let m=0;m<y.length;m++)y[m]=o(s*y[m]);return y}},bitsCoder:(y,m)=>{const k=ln(y),R=y*(t/8);return{bytesLen:R,encode:_=>{const A=new Uint8Array(R);for(let M=0,x=0,$=0,F=0;M<_.length;M++)for(x|=(m.encode(_[M])&k)<<$,$+=y;$>=8;$-=8,x>>=8)A[F++]=x&ln($);return A},decode:_=>{const A=e(t);for(let M=0,x=0,$=0,F=0;M<_.length;M++)for(x|=_[M]<<$,$+=8;$>=y;$-=y,x>>=y)A[F++]=m.decode(x&k);return A}}}}},Js=(a=>(e,t)=>{t||(t=a.blockLen);const n=new Uint8Array(e.length+2);n.set(e);const s=e.length,r=new Uint8Array(t);let i=a.create({}),o=0,c=0;return{stats:()=>({calls:o,xofs:c}),get:(u,l)=>(n[s+0]=u,n[s+1]=l,i.destroy(),i=a.create({}).update(n),o++,()=>(c++,i.xofInto(r))),clean:()=>{i.destroy(),Z(r,n)}}})(js);const Q=256,he=3329,Gs=3303,Xs=17,{mod:Ce,nttZetas:Zs,NTT:de,bitsCoder:Ys}=zs({N:Q,Q:he,F:Gs,ROOT_OF_UNITY:Xs,newPoly:a=>new Uint16Array(a),brvBits:7}),er={768:{N:Q,Q:he,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192}},tr=a=>{if(a>=12)return{encode:t=>t,decode:t=>t};const e=2**(a-1);return{encode:t=>((t<<a)+he/2)/he,decode:t=>t*he+e>>>a}},xe=a=>Ys(a,tr(a));function pe(a,e){for(let t=0;t<Q;t++)a[t]=Ce(a[t]+e[t])}function nr(a,e){for(let t=0;t<Q;t++)a[t]=Ce(a[t]-e[t])}function sr(a,e,t,n,s){const r=Ce(e*n*s+a*t),i=Ce(a*n+e*t);return{c0:r,c1:i}}function Xe(a,e){for(let t=0;t<Q/2;t++){let n=Zs[64+(t>>1)];t&1&&(n=-n);const{c0:s,c1:r}=sr(a[2*t+0],a[2*t+1],e[2*t+0],e[2*t+1],n);a[2*t+0]=s,a[2*t+1]=r}return a}function cn(a){const e=new Uint16Array(Q);for(let t=0;t<Q;){const n=a();if(n.length%3)throw new Error("SampleNTT: unaligned block");for(let s=0;t<Q&&s+3<=n.length;s+=3){const r=(n[s+0]>>0|n[s+1]<<8)&4095,i=(n[s+1]>>4|n[s+2]<<4)&4095;r<he&&(e[t++]=r),t<Q&&i<he&&(e[t++]=i)}}return e}function Ee(a,e,t,n){const s=a(n*Q/4,e,t),r=new Uint16Array(Q),i=Ft(s);let o=0;for(let c=0,u=0,l=0,d=0;c<i.length;c++){let f=i[c];for(let p=0;p<32;p++)l+=f&1,f>>=1,o+=1,o===n?(d=l,l=0):o===2*n&&(r[u++]=Ce(d-l),l=0,o=0)}if(o)throw new Error(`sampleCBD: leftover bits: ${o}`);return r}const rr=a=>{const{K:e,PRF:t,XOF:n,HASH512:s,ETA1:r,ETA2:i,du:o,dv:c}=a,u=xe(1),l=xe(c),d=xe(o),f=Ge("publicKey",ct(xe(12),e),32),p=ct(xe(12),e),w=Ge("ciphertext",ct(d,e),l),v=Ge("seed",32,32);return{secretCoder:p,lengths:{secretKey:p.bytesLen,publicKey:f.bytesLen,cipherText:w.bytesLen},keygen:O=>{V(O,32,"seed");const y=new Uint8Array(33);y.set(O),y[32]=e;const m=s(y),[k,R]=v.decode(m),_=[],A=[];for(let $=0;$<e;$++)_.push(de.encode(Ee(t,R,$,r)));const M=n(k);for(let $=0;$<e;$++){const F=de.encode(Ee(t,R,e+$,r));for(let U=0;U<e;U++){const ve=cn(M.get(U,$));pe(F,Xe(ve,_[U]))}A.push(F)}M.clean();const x={publicKey:f.encode([A,k]),secretKey:p.encode(_)};return Z(k,R,_,A,y,m),x},encrypt:(O,y,m)=>{const[k,R]=f.decode(O),_=[];for(let U=0;U<e;U++)_.push(de.encode(Ee(t,m,U,r)));const A=n(R),M=new Uint16Array(Q),x=[];for(let U=0;U<e;U++){const ve=Ee(t,m,e+U,i),xt=new Uint16Array(Q);for(let st=0;st<e;st++){const Wr=cn(A.get(U,st));pe(xt,Xe(Wr,_[st]))}pe(ve,de.decode(xt)),x.push(ve),pe(M,Xe(k[U],_[U])),Z(xt)}A.clean();const $=Ee(t,m,2*e,i);pe($,de.decode(M));const F=u.decode(y);return pe(F,$),Z(k,_,M,$),w.encode([x,F])},decrypt:(O,y)=>{const[m,k]=w.decode(O),R=p.decode(y),_=new Uint16Array(Q);for(let A=0;A<e;A++)pe(_,Xe(R[A],de.encode(m[A])));return nr(k,de.decode(_)),Z(_,R,m),u.encode(k)}}};function ir(a){const e=rr(a),{HASH256:t,HASH512:n,KDF:s}=a,{secretCoder:r,lengths:i}=e,o=Ge("secretKey",i.secretKey,i.publicKey,32,32),c=32,u=64;return{info:{type:"ml-kem"},lengths:{...i,seed:64,msg:c,msgRand:c,secretKey:o.bytesLen},keygen:(l=on(u))=>{V(l,u,"seed");const{publicKey:d,secretKey:f}=e.keygen(l.subarray(0,32)),p=t(d),w=o.encode([f,d,p,l.subarray(32)]);return Z(f,p),{publicKey:d,secretKey:w}},getPublicKey:l=>{const[d,f]=o.decode(l);return Uint8Array.from(f)},encapsulate:(l,d=on(c))=>{V(l,i.publicKey,"publicKey"),V(d,c,"message");const f=l.subarray(0,384*a.K),p=r.encode(r.decode(Vs(f)));if(!lt(p,f))throw Z(p),new Error("ML-KEM.encapsulate: wrong publicKey modulus");Z(p);const w=n.create().update(d).update(t(l)).digest(),v=e.encrypt(l,d,w.subarray(32,64));return Z(w.subarray(32)),{cipherText:v,sharedSecret:w.subarray(0,32)}},decapsulate:(l,d)=>{V(d,o.bytesLen,"secretKey"),V(l,i.cipherText,"cipherText");const f=o.bytesLen-96,p=f+32,w=t(d.subarray(f/2,p));if(!lt(w,d.subarray(p,p+32)))throw new Error("invalid secretKey: hash check failed");const[v,O,y,m]=o.decode(d),k=e.decrypt(l,v),R=n.create().update(k).update(y).digest(),_=R.subarray(0,32),A=e.encrypt(O,k,R.subarray(32,64)),M=lt(l,A),x=s.create({dkLen:32}).update(m).update(l).digest();return Z(k,A,M?x:_),M?_:x}}}function ar(a,e,t){return en.create({dkLen:a}).update(e).update(new Uint8Array([t])).digest()}const ut=ir({...{HASH256:Qs,HASH512:Ds,KDF:en,XOF:Js,PRF:ar},...er[768]});class S{constructor({secret:e=null,bundle:t=null,token:n="USER",address:s=null,position:r=null,batchId:i=null,characters:o=null}){this.token=n,this.balance="0",this.molecules={},this.key=null,this.privkey=null,this.pubkey=null,this.tokenUnits=[],this.tradeRates={},this.address=s,this.position=r,this.bundle=t,this.batchId=i,this.characters=o,e&&(this.bundle=this.bundle||ce(e,"Wallet::constructor"),this.position=this.position||S.generatePosition(),this.key=S.generateKey({secret:e,token:this.token,position:this.position}),this.address=this.address||S.generateAddress(this.key),this.characters=this.characters||"BASE64",this.initializeMLKEM())}static create({secret:e=null,bundle:t=null,token:n,batchId:s=null,characters:r=null}){let i=null;if(!e&&!t)throw new at;return e&&!t&&(i=S.generatePosition(),t=ce(e,"Wallet::create")),new S({secret:e,bundle:t,token:n,position:i,batchId:s,characters:r})}static isBundleHash(e){return typeof e!="string"?!1:e.length===64&&Fe(e)}static getTokenUnits(e){const t=[];return e.forEach(n=>{t.push(ue.createFromDB(n))}),t}static generateKey({secret:e,token:t,position:n}){if(!e)throw new at("Wallet::generateKey() - Secret is required!");if(!n)throw new at("Wallet::generateKey() - Position is required!");const s=Fe(e)?e:je(e,1024),r=Fe(n)?n:je(n,256),o=BigInt(`0x${s}`)+BigInt(`0x${r}`),c=new D("SHAKE256","TEXT");c.update(o.toString(16)),t&&c.update(t);const u=new D("SHAKE256","TEXT");return u.update(c.getHash("HEX",{outputLen:8192})),u.getHash("HEX",{outputLen:8192})}static generateAddress(e){const t=Ie(e,128),n=new D("SHAKE256","TEXT");for(const r in t){let i=t[r];for(let o=1;o<=16;o++){const c=new D("SHAKE256","TEXT");c.update(i),i=c.getHash("HEX",{outputLen:512})}n.update(i)}const s=new D("SHAKE256","TEXT");return s.update(n.getHash("HEX",{outputLen:8192})),s.getHash("HEX",{outputLen:256})}static generatePosition(e=64){return Ne(e,"abcdef0123456789")}initializeMLKEM(){const e=De(this.key,128),t=new Uint8Array(64);for(let r=0;r<64;r++)t[r]=parseInt(e.substr(r*2,2),16);const{publicKey:n,secretKey:s}=ut.keygen(t);this.pubkey=this.serializeKey(n),this.privkey=s}serializeKey(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";const n=32768;for(let s=0;s<e.length;s+=n)t+=String.fromCharCode(...e.subarray(s,s+n));return btoa(t)}deserializeKey(e){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));const t=atob(e);return new Uint8Array(t.length).map((n,s)=>t.charCodeAt(s))}balanceAsNumber(){return Number(this.balance)}balanceAsBigInt(){const e=String(this.balance),t=e.includes(".")?e.split(".")[0]:e;return BigInt(t||"0")}setBalanceBigInt(e){this.balance=e.toString()}setBalanceNumber(e){this.balance=String(e)}getTokenUnitsData(){const e=[];return this.tokenUnits.forEach(t=>{e.push(t.toData())}),e}splitUnits(e,t,n=null){if(e.length===0)return;const s=[],r=[];this.tokenUnits.forEach(i=>{e.includes(i.id)?s.push(i):r.push(i)}),this.tokenUnits=s,n!==null&&(n.tokenUnits=s),t.tokenUnits=r}splitUnitsMulti(e,t,n){const s=new Set;e.forEach(r=>{r.forEach(i=>s.add(i))}),s.size!==0&&(t.forEach((r,i)=>{const o=e[i];r.tokenUnits=this.tokenUnits.filter(c=>o.includes(c.id))}),n.tokenUnits=this.tokenUnits.filter(r=>!s.has(r.id)),this.tokenUnits=this.tokenUnits.filter(r=>s.has(r.id)))}createRemainder(e){const t=S.create({secret:e,token:this.token,characters:this.characters});return t.initBatchId({sourceWallet:this,isRemainder:!0}),t}isShadow(){return(typeof this.position>"u"||this.position===null)&&(typeof this.address>"u"||this.address===null)}initBatchId({sourceWallet:e,isRemainder:t=!1}){e.batchId&&(this.batchId=t?e.batchId:Me({}))}async encryptMessage(e,t){const n=JSON.stringify(e),s=new TextEncoder().encode(n),r=this.deserializeKey(t),i=1184;if(r.length!==i)throw new Error(`KnishIO: cannot ML-KEM-encrypt — recipient public key is ${r.length} bytes, expected ${i} (ML-KEM-768). The node likely did not advertise an ML-KEM public key (upgrade the validator to a PQ-transport build), or authenticate with { encrypt: false }.`);const{cipherText:o,sharedSecret:c}=ut.encapsulate(r),u=await this.encryptWithSharedSecret(s,c);return{cipherText:this.serializeKey(o),encryptedMessage:this.serializeKey(u)}}async decryptMessage(e){const t=await this._mlkemDecryptToString(e);return t===null?null:JSON.parse(t)}async _mlkemDecryptToString(e){const{cipherText:t,encryptedMessage:n}=e;let s;try{s=ut.decapsulate(this.deserializeKey(t),this.privkey)}catch(o){return console.error("Wallet::decryptMessage() - Decapsulation failed",o),console.info("Wallet::decryptMessage() - my public key",this.pubkey),null}let r;try{r=this.deserializeKey(n)}catch(o){return console.warn("Wallet::decryptMessage() - Deserialization failed",o),console.info("Wallet::decryptMessage() - my public key",this.pubkey),console.info("Wallet::decryptMessage() - our shared secret",s),null}let i;try{i=await this.decryptWithSharedSecret(r,s)}catch(o){return console.warn("Wallet::decryptMessage() - Decryption failed",o),console.info("Wallet::decryptMessage() - my public key",this.pubkey),console.info("Wallet::decryptMessage() - our shared secret",s),console.info("Wallet::decryptMessage() - deserialized encrypted message",r),null}try{return new TextDecoder().decode(i)}catch(o){return console.warn("Wallet::decryptMessage() - Decoding failed",o),console.info("Wallet::decryptMessage() - my public key",this.pubkey),console.info("Wallet::decryptMessage() - our shared secret",s),console.info("Wallet::decryptMessage() - deserialized encrypted message",r),console.info("Wallet::decryptMessage() - decrypted Uint8Array",i),null}}hashShare(e){const t=je(e,64),n=Uint8Array.from(t.match(/.{2}/g).map(s=>parseInt(s,16)));return this.serializeKey(n)}async encryptStringML768(e,t){const n=await this.encryptMessage(e,t);return JSON.stringify({[this.hashShare(t)]:n})}async decryptMyMessageML768(e){const t=e[this.hashShare(this.pubkey)];return t?this._mlkemDecryptToString(t):null}async encryptWithSharedSecret(e,t){const n=crypto.getRandomValues(new Uint8Array(12)),s={name:"AES-GCM",iv:n},r=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["encrypt"]),i=await crypto.subtle.encrypt(s,r,e),o=new Uint8Array(n.length+i.byteLength);return o.set(n),o.set(new Uint8Array(i),n.length),o}async decryptWithSharedSecret(e,t){const s={name:"AES-GCM",iv:e.slice(0,12)},r=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=await crypto.subtle.decrypt(s,r,e.slice(12));return new Uint8Array(i)}}class ge extends I{constructor(e="There is an atom without an index",t=null,n=null){super(e,t,n),this.name="AtomIndexException"}}class un extends I{constructor(e="The molecular hash does not match",t=null,n=null){super(e,t,n),this.name="MolecularHashMismatchException"}}class hn extends I{constructor(e="The molecular hash is missing",t=null,n=null){super(e,t,n),this.name="MolecularHashMissingException"}}class ht extends I{constructor(e="",t=null,n=null){super(e,t,n),this.name="PolicyInvalidException"}}class dt extends I{constructor(e="OTS malformed",t=null,n=null){super(e,t,n),this.name="SignatureMalformedException"}}class dn extends I{constructor(e="One-time signature (OTS) does not match!",t=null,n=null){super(e,t,n),this.name="SignatureMismatchException"}}class G extends I{constructor(e="Insufficient balance to make transfer",t=null,n=null){super(e,t,n),this.name="TransferBalanceException"}}class be extends I{constructor(e="Token transfer atoms are malformed",t=null,n=null){super(e,t,n),this.name="TransferMalformedException"}}class pt extends I{constructor(e="Token slugs for wallets in transfer do not match!",t=null,n=null){super(e,t,n),this.name="TransferMismatchedException"}}class ft extends I{constructor(e="Invalid remainder provided",t=null,n=null){super(e,t,n),this.name="TransferRemainderException"}}class pn extends I{constructor(e="Sender and recipient(s) cannot be the same",t=null,n=null){super(e,t,n),this.name="TransferToSelfException"}}class Re extends I{constructor(e="Token transfer atoms are unbalanced",t=null,n=null){super(e,t,n),this.name="TransferUnbalancedException"}}class H extends I{constructor(e="Empty meta data.",t=null,n=null){super(e,t,n),this.name="MetaMissingException"}}class re extends I{constructor(e="Wrong type of token for this isotope",t=null,n=null){super(e,t,n),this.name="WrongTokenTypeException"}}class qe extends I{constructor(e="Incorrect BatchId",t=null,n=null){super(e,t,n),this.name="BatchIdException"}}class fn{constructor(e={}){for(const t in e)this[`__${t}`]=e[t]}static toObject(e){return new this(e)}toJSON(){const e={};for(const t of Object.keys(this))t.substring(0,2)==="__"&&(e[t.substring(2,t.length)]=this[t]);return e}}class Ze extends I{constructor(e="An incorrect argument!",t=null,n=null){super(e,t,n),this.name="RuleArgumentException"}}class Y extends I{constructor(e="Code exception",t=null,n=null){super(e,t,n),this.name="CodeException"}}class Oe{constructor({action:e,metaType:t=null,metaId:n=null,meta:s=null,address:r=null,token:i=null,amount:o=null,comparison:c=null}){if(s&&(this.meta=s),!e)throw new Ze('Callback structure violated, missing mandatory "action" parameter.');this.__metaId=n,this.__metaType=t,this.__action=e,this.__address=r,this.__token=i,this.__amount=o,this.__comparison=c}set comparison(e){this.__comparison=e}set amount(e){if(!Wt(e))throw new Y("Parameter amount should be a string containing numbers");this.__amount=e}set token(e){this.__token=e}set address(e){this.__address=e}set meta(e){this.__meta=e instanceof fn?e:fn.toObject(e)}set metaType(e){this.__metaType=e}set metaId(e){this.__metaId=e}static toObject(e){const t=new Oe({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}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}isReject(){return this._is("reject")}isMeta(){return me(Object.keys(this.toJSON()),["action","metaId","metaType","meta"]).length===4&&this._is("meta")}isCollect(){return me(Object.keys(this.toJSON()),["action","address","token","amount","comparison"]).length===5&&this._is("collect")}isBuffer(){return me(Object.keys(this.toJSON()),["action","address","token","amount","comparison"]).length===5&&this._is("buffer")}isRemit(){return me(Object.keys(this.toJSON()),["action","token","amount"]).length===3&&this._is("remit")}isBurn(){return me(Object.keys(this.toJSON()),["action","token","amount","comparison"]).length===4&&this._is("burn")}_is(e){return this.__action.toLowerCase()===e.toLowerCase()}}class yt{constructor({key:e,value:t,comparison:n}){if([e,t,n].some(s=>!s))throw new Ze("Condition::constructor( { key, value, comparison } ) - not all class parameters are initialised!");this.__key=e,this.__value=t,this.__comparison=n}static toObject(e){return new this({key:e.key,value:e.value,comparison:e.comparison})}toJSON(){return{key:this.__key,value:this.__value,comparison:this.__comparison}}}class Be{constructor({condition:e=[],callback:t=[]}){for(const n of e)if(!(n instanceof yt))throw new Ze;for(const n of t)if(!(n instanceof Oe))throw new Ze;this.__condition=e,this.__callback=t}set comparison(e){this.__condition.push(e instanceof yt?e:yt.toObject(e))}set callback(e){this.__callback.push(e instanceof Oe?e:Oe.toObject(e))}static toObject(e){if(!e.condition)throw new H("Rule::toObject() - Incorrect rule format! There is no condition field.");if(!e.callback)throw new H("Rule::toObject() - Incorrect rule format! There is no callback field.");const t=new Be({});for(const n of e.condition)t.comparison=n;for(const n of e.callback)t.callback=n;return t}toJSON(){return{condition:this.__condition,callback:this.__callback}}}class C{static __init(e,t){this.arr=String(t).split("."),this.key=this.arr.shift();const n=Number(this.key);Number.isInteger(n)&&(this.key=n),this.__nextKey=this.arr.length,this.__next=this.__tic(e)}static __tic(e){return!Array.isArray(e)&&!(e instanceof Object)?!1:typeof e[this.key]<"u"}static has(e,t){return this.__init(e,t),this.__next?this.__nextKey===0?!0:this.has(e[this.key],this.arr.join(".")):!1}static get(e,t,n=null){return this.__init(e,t),this.__next?this.__nextKey===0?e[this.key]:this.get(e[this.key],this.arr.join("."),n):n}static set(e,t,n){const s=t.split(".");let r=e;const i=s.length-1;for(let u=0;u<i;u++){const l=s[u],d=Number(l),f=Number.isInteger(d);(f?d:l in r)||(r[f?d:l]=s[u+1].match(/^\d+$/)?[]:{}),r=r[f?d:l]}const o=s[i],c=Number(o);return r[Number.isInteger(c)?c:o]=n,e}}class we{constructor(e){if(e.molecularHash===null)throw new hn;if(!e.atoms.length)throw new se;for(const t of e.atoms)if(t.index===null)throw new ge;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.isotopeP()&&this.isotopeA()&&this.isotopeB()&&this.isotopeF()&&this.isotopeV(e)}continuId(){if(this.molecule.atoms[0].token==="USER"&&this.molecule.getIsotopes("I").length<1)throw new se("Check::continuId() - Molecule is missing required ContinuID Atom!");return!0}batchId(){if(this.molecule.atoms.length>0){const e=this.molecule.atoms[0];if(e.isotope==="V"&&e.batchId!==null){const t=this.molecule.getIsotopes("V"),n=t[t.length-1];if(e.batchId!==n.batchId)throw new qe;for(const s of t)if(s.batchId===null)throw new qe}return!0}throw new qe}isotopeI(){for(const e of this.molecule.getIsotopes("I")){if(e.token!=="USER")throw new re(`Check::isotopeI() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index===0)throw new ge(`Check::isotopeI() - Isotope "${e.isotope}" Atoms must have a non-zero index!`)}return!0}isotopeU(){for(const e of this.molecule.getIsotopes("U")){if(e.token!=="AUTH")throw new re(`Check::isotopeU() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index!==0)throw new ge(`Check::isotopeU() - Isotope "${e.isotope}" Atoms must have an index equal to 0!`)}return!0}isotopeM(){const e=["readPolicy","writePolicy"];for(const t of this.molecule.getIsotopes("M")){if(t.meta.length<1)throw new H;if(t.token!=="USER")throw new re(`Check::isotopeM() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);const n=oe.aggregateMeta(t.meta);for(const s of e){let r=n[s];if(r){r=JSON.parse(r);for(const[i,o]of Object.entries(r))if(!e.includes(i)){if(!Object.keys(n).includes(i))throw new ht(`${i} is missing from the meta.`);for(const c of o)if(!S.isBundleHash(c)&&!["all","self"].includes(c))throw new ht(`${c} does not correspond to the format of the policy.`)}}}}return!0}isotopeC(){for(const e of this.molecule.getIsotopes("C")){if(e.token!=="USER")throw new re(`Check::isotopeC() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index!==0)throw new ge(`Check::isotopeC() - Isotope "${e.isotope}" Atoms must have an index equal to 0!`)}return!0}isotopeT(){for(const e of this.molecule.getIsotopes("T")){const t=e.aggregatedMeta();if(String(e.metaType).toLowerCase()==="wallet"){for(const s of["position","bundle"])if(!Object.prototype.hasOwnProperty.call(t,s)||!t[s])throw new H(`Check::isotopeT() - Required meta field "${s}" is missing!`)}for(const s of["token"])if(!Object.prototype.hasOwnProperty.call(t,s)||!t[s])throw new H(`Check::isotopeT() - Required meta field "${s}" is missing!`);if(e.token!=="USER")throw new re(`Check::isotopeT() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index!==0)throw new ge(`Check::isotopeT() - Isotope "${e.isotope}" Atoms must have an index equal to 0!`)}return!0}isotopeR(){for(const e of this.molecule.getIsotopes("R")){const t=e.aggregatedMeta();if(t.policy){const n=JSON.parse(t.policy);if(!Object.keys(n).every(s=>["read","write"].includes(s)))throw new H("Check::isotopeR() - Mixing rules with politics!")}if(t.rule){const n=JSON.parse(t.rule);if(!Array.isArray(n))throw new H("Check::isotopeR() - Incorrect rule format!");for(const s of n)Be.toObject(s);if(n.length<1)throw new H("Check::isotopeR() - No rules!")}}return!0}isotopeP(){for(const e of this.molecule.getIsotopes("P")){if(e.token!=="USER")throw new re(`Check::isotopeP() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);const t=e.aggregatedMeta();if(!Object.prototype.hasOwnProperty.call(t,"peerHost")||!t.peerHost)throw new H('Check::isotopeP() - Required meta field "peerHost" is missing!')}return!0}isotopeA(){for(const e of this.molecule.getIsotopes("A")){if(e.token!=="USER")throw new re(`Check::isotopeA() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(!e.metaType)throw new H('Check::isotopeA() - Required field "metaType" is missing!');if(!e.metaId)throw new H('Check::isotopeA() - Required field "metaId" is missing!');const t=e.aggregatedMeta();if(!Object.prototype.hasOwnProperty.call(t,"action")||!t.action)throw new H('Check::isotopeA() - Required meta field "action" is missing!')}return!0}isotopeB(){const e=this.molecule.getIsotopes("B");if(e.length===0)return!0;for(const n of e){if(!n.metaType||n.metaType!=="walletBundle")throw new H('Check::isotopeB() - B-isotope atoms must have metaType "walletBundle"!');if(!n.metaId)throw new H("Check::isotopeB() - B-isotope atoms must have a metaId!");const s=Number(n.value);if(Number.isNaN(s))throw new be("Check::isotopeB() - B-isotope atom value is not a valid number!")}const t=this.molecule.getIsotopes("V");if(t.length>0){let n=0;for(const s of[...t,...e]){const r=Number(s.value);Number.isNaN(r)||(n+=r)}if(n!==0)throw new Re("Check::isotopeB() - V+B atom values do not balance to zero!")}return!0}isotopeF(){const e=this.molecule.getIsotopes("F");if(e.length===0)return!0;for(const n of e){if(!n.metaType||n.metaType!=="walletBundle")throw new H('Check::isotopeF() - F-isotope atoms must have metaType "walletBundle"!');if(!n.metaId)throw new H("Check::isotopeF() - F-isotope atoms must have a metaId!");const s=Number(n.value);if(Number.isNaN(s))throw new be("Check::isotopeF() - F-isotope atom value is not a valid number!");if(s<0)throw new be("Check::isotopeF() - F-isotope atom value must not be negative!")}const t=this.molecule.getIsotopes("V");if(t.length>0){let n=0;for(const s of[...t,...e]){const r=Number(s.value);Number.isNaN(r)||(n+=r)}if(n!==0)throw new Re("Check::isotopeF() - V+F atom values do not balance to zero!")}return!0}isotopeV(e=null){const t=this.molecule.getIsotopes("V");if(t.length===0)return!0;const n=this.molecule.getIsotopes("B").length>0||this.molecule.getIsotopes("F").length>0,s=this.molecule.atoms[0];if(!n&&s.isotope==="V"&&t.length===2){const o=t[t.length-1];if(s.token!==o.token)throw new pt;if(o.value<0)throw new be;if(Number(s.value)+Number(o.value)!==0)throw new Re;return!0}let r=0,i=0;for(const o in this.molecule.atoms)if(Object.prototype.hasOwnProperty.call(this.molecule.atoms,o)){const c=this.molecule.atoms[o];if(c.isotope!=="V")continue;if(i=c.value*1,Number.isNaN(i))throw new TypeError('Invalid isotope "V" values');if(c.token!==s.token)throw new pt;if(o>0){if(i<0)throw new be;if(c.walletAddress===s.walletAddress)throw new pn}r+=i}if(!n&&r!==0)throw new Re;if(e){if(i=s.value*1,Number.isNaN(i))throw new TypeError('Invalid isotope "V" values');const o=Number(e.balance)+i;if(o<0)throw new G;if(!n&&o!==r)throw new ft}else if(i!==0)throw new ft;return!0}molecularHash(){if(this.molecule.molecularHash!==b.hashAtoms({atoms:this.molecule.atoms}))throw new un;return!0}ots(){const e=this.molecule.normalizedHash();let t=this.molecule.atoms.map(f=>f.otsFragment).reduce((f,p)=>f+p);if(t.length!==2048&&(t=Bt(t),t.length!==2048))throw new dt;const n=Ie(t,128);let s="";for(const f in n){let p=n[f];for(let w=0,v=8+e[f];w<v;w++)p=new D("SHAKE256","TEXT").update(p).getHash("HEX",{outputLen:512});s+=p}const r=new D("SHAKE256","TEXT");r.update(s);const i=r.getHash("HEX",{outputLen:8192}),o=new D("SHAKE256","TEXT");o.update(i);const c=o.getHash("HEX",{outputLen:256}),u=this.molecule.atoms[0];let l=u.walletAddress;const d=C.get(u.aggregatedMeta(),"signingWallet");if(d&&(l=C.get(JSON.parse(d),"address")),c!==l)throw new dn;return!0}static fromServerData({molecularHash:e,bundleHash:t,cellSlug:n=null,status:s=null,createdAt:r=null,atoms:i=[]}){const o=i.map(c=>{let u=[];if(c.metasJson)try{const l=JSON.parse(c.metasJson);Array.isArray(l)?u=l:l&&typeof l=="object"&&(u=Object.entries(l).map(([d,f])=>({key:d,value:f})))}catch{u=[]}return{position:c.position||null,walletAddress:c.walletAddress||null,isotope:c.isotope||null,token:c.tokenSlug||c.token||null,value:c.value!=null?String(c.value):null,batchId:c.batchId||null,metaType:c.metaType||null,metaId:c.metaId||null,meta:u,index:c.index!=null?c.index:null,otsFragment:c.otsFragment||null,createdAt:c.createdAt||null}});return z.fromJSON({molecularHash:e,bundle:t,cellSlug:n,status:s,createdAt:r,atoms:o})}static verifyFromServerData(e){try{const t=we.fromServerData(e);return new we(t).verify(),{molecularHash:e.molecularHash,verified:!0,error:null}}catch(t){return{molecularHash:e.molecularHash||null,verified:!1,error:t.message||String(t)}}}}class fe extends I{constructor(e="Insufficient balance for requested transfer",t=null,n=null){super(e,t,n),this.name="BalanceInsufficientException"}}class mt extends I{constructor(e="Amount cannot be negative!",t=null,n=null){super(e,t,n),this.name="NegativeAmountException"}}class z{constructor({secret:e=null,bundle:t=null,sourceWallet:n=null,remainderWallet:s=null,cellSlug:r=null,version:i=null,continuIdPosition:o=null}){this.status=null,this.molecularHash=null,this.createdAt=String(+new Date),this.cellSlugOrigin=this.cellSlug=r,this.secret=e,this.bundle=t,this.sourceWallet=n,this.continuIdPosition=o,this.atoms=[],this.parentHashes=[],i!==null&&Object.prototype.hasOwnProperty.call(Qe,i)&&(this.version=String(i)),(s||n)&&(this.remainderWallet=s||S.create({secret:e,bundle:t,token:n.token,batchId:n.batchId,characters:n.characters}))}withParentHashes(e){return this.parentHashes=Array.isArray(e)?[...e]:[],this}get cellSlugDelimiter(){return"."}static isotopeFilter(e,t){return Array.isArray(e)||(e=[e]),t.filter(n=>e.includes(n.isotope))}static generateNextAtomIndex(e){return e.length}static jsonToObject(e){const t=Object.assign(new z({}),JSON.parse(e)),n=Object.keys(new z({}));if(!Array.isArray(t.atoms))throw new se;for(const s in Object.keys(t.atoms)){t.atoms[s]=b.jsonToObject(JSON.stringify(t.atoms[s]));for(const r of["position","walletAddress","isotope"])if(t.atoms[s].isotope.toLowerCase()!=="r"&&(typeof t.atoms[s][r]>"u"||t.atoms[s][r]===null))throw new se("MolecularStructure::jsonToObject() - Required Atom properties are missing!")}for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&!n.includes(s)&&delete t[s];return t.atoms=b.sortAtoms(t.atoms),t}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},n=[],s=e.toLowerCase().split("");for(let r=0,i=s.length;r<i;++r){const o=s[r];typeof t[o]<"u"&&(n[r]=t[o])}return n}static normalize(e){let t=e.reduce((s,r)=>s+r);const n=t<0;for(;t<0||t>0;)for(const s of Object.keys(e))if((n?e[s]<8:e[s]>-8)&&(n?(++e[s],++t):(--e[s],--t),t===0))break;return e}getIsotopes(e){return z.isotopeFilter(e,this.atoms)}generateIndex(){return z.generateNextAtomIndex(this.atoms)}fill(e){for(const t in Object.keys(e))this[t]=e[t]}addAtom(e){return this.molecularHash=null,e.index=this.generateIndex(),e.version=this.version,this.atoms.push(e),this.atoms=b.sortAtoms(this.atoms),this}addContinuIdAtom(){(!this.remainderWallet||this.remainderWallet.token!=="USER")&&(this.remainderWallet=S.create({secret:this.secret,bundle:this.bundle}));const e={};return this.continuIdPosition?e.previousPosition=this.continuIdPosition:this.sourceWallet&&this.sourceWallet.position&&(e.previousPosition=this.sourceWallet.position),this.remainderWallet.pubkey&&(e.pubkey=this.remainderWallet.pubkey),this.remainderWallet.characters&&(e.characters=this.remainderWallet.characters),this.addAtom(b.create({isotope:"I",wallet:this.remainderWallet,metaType:"walletBundle",metaId:this.remainderWallet.bundle,meta:new P(e)})),this}addPolicyAtom({metaType:e,metaId:t,meta:n={},policy:s={}}){const r=new P(n);return r.addPolicy(s),this.addAtom(b.create({wallet:this.sourceWallet,isotope:"R",metaType:e,metaId:t,meta:r})),this}fuseToken(e,t){const n=e.length;if(this.sourceWallet.balance-n<0)throw new fe;return this.addAtom(b.create({isotope:"V",wallet:this.sourceWallet,value:-n})),this.addAtom(b.create({isotope:"F",wallet:t,value:1,metaType:"walletBundle",metaId:t.bundle})),this.addAtom(b.create({isotope:"V",wallet:this.remainderWallet,value:this.sourceWallet.balance-n,metaType:"walletBundle",metaId:this.remainderWallet.bundle})),this}burnToken({amount:e,walletBundle:t=null}){if(e<0)throw new mt("Molecule::burnToken() - Amount to burn must be positive!");if(this.sourceWallet.balance-e<0)throw new fe;const n=new S({bundle:"0000000000000000000000000000000000000000000000000000000000000000",token:this.sourceWallet.token});return this.addAtom(b.create({isotope:"V",wallet:this.sourceWallet,value:-this.sourceWallet.balance})),this.addAtom(b.create({isotope:"V",wallet:n,value:e,metaType:"walletBundle",metaId:n.bundle})),this.addAtom(b.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 mt("Molecule::replenishToken() - Amount to replenish must be positive!");if(t.length){t=S.getTokenUnits(t),this.remainderWallet.tokenUnits=this.sourceWallet.tokenUnits;for(const n of t)this.remainderWallet.tokenUnits.push(n);this.remainderWallet.balance=String(this.remainderWallet.tokenUnits.length),this.sourceWallet.tokenUnits=t,this.sourceWallet.balance=String(this.sourceWallet.tokenUnits.length)}else this.remainderWallet.balance=String(Number(this.sourceWallet.balance)+e),this.sourceWallet.balance=String(e);return this.addAtom(b.create({isotope:"V",wallet:this.sourceWallet,value:Number(this.sourceWallet.balance)})),this.addAtom(b.create({isotope:"V",wallet:this.remainderWallet,value:Number(this.remainderWallet.balance),metaType:"walletBundle",metaId:this.remainderWallet.bundle})),this}initValue({recipientWallet:e,amount:t}){if(this.sourceWallet.balance-t<0)throw new fe;return this.addAtom(b.create({isotope:"V",wallet:this.sourceWallet,value:-this.sourceWallet.balance})),this.addAtom(b.create({isotope:"V",wallet:e,value:t,metaType:"walletBundle",metaId:e.bundle})),this.addAtom(b.create({isotope:"V",wallet:this.remainderWallet,value:this.sourceWallet.balance-t,metaType:"walletBundle",metaId:this.remainderWallet.bundle})),this}initValues({recipientWallets:e,amounts:t}){const n=t.reduce((s,r)=>s+Number(r),0);if(this.sourceWallet.balance-n<0)throw new fe;return this.addAtom(b.create({isotope:"V",wallet:this.sourceWallet,value:-this.sourceWallet.balance})),e.forEach((s,r)=>{this.addAtom(b.create({isotope:"V",wallet:s,value:t[r],metaType:"walletBundle",metaId:s.bundle}))}),this.addAtom(b.create({isotope:"V",wallet:this.remainderWallet,value:this.sourceWallet.balance-n,metaType:"walletBundle",metaId:this.remainderWallet.bundle})),this}initDepositBuffer({amount:e,tradeRates:t}){if(this.sourceWallet.balance-e<0)throw new fe;const n=S.create({secret:this.secret,bundle:this.bundle,token:this.sourceWallet.token,batchId:this.sourceWallet.batchId});return n.tradeRates=t,this.addAtom(b.create({isotope:"V",wallet:this.sourceWallet,value:-this.sourceWallet.balance})),this.addAtom(b.create({isotope:"B",wallet:n,value:e,metaType:"walletBundle",metaId:this.sourceWallet.bundle})),this.addAtom(b.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 n=0;for(const r of Object.values(e||{}))n+=r;if(this.sourceWallet.balance-n<0)throw new fe;const s=new P;t&&s.setSigningWallet(t),this.addAtom(b.create({isotope:"B",wallet:this.sourceWallet,value:-this.sourceWallet.balance,meta:s,metaType:"walletBundle",metaId:this.sourceWallet.bundle}));for(const[r,i]of Object.entries(e||{}))this.addAtom(new b({isotope:"V",token:this.sourceWallet.token,value:i,batchId:this.sourceWallet.batchId?Me({}):null,metaType:"walletBundle",metaId:r}));return this.addAtom(b.create({isotope:"B",wallet:this.remainderWallet,value:this.sourceWallet.balance-n,metaType:"walletBundle",metaId:this.remainderWallet.bundle})),this}initTokenCreation({recipientWallet:e,amount:t,meta:n}){const s=new P(n);return s.setMetaWallet(e),this.addAtom(b.create({isotope:"C",wallet:this.sourceWallet,value:t,metaType:"token",metaId:e.token,meta:s,batchId:e.batchId})),this.addContinuIdAtom(),this}createRule({metaType:e,metaId:t,rule:n,policy:s={}}){const r=[];for(const o of n)r.push(o instanceof Be?o:Be.toObject(o));const i=new P({rule:JSON.stringify(r)});return i.addPolicy(s),this.addAtom(b.create({isotope:"R",wallet:this.sourceWallet,metaType:e,metaId:t,meta:i})),this.addContinuIdAtom(),this}initWalletCreation(e,t=null){t||(t=new P),t.setMetaWallet(e);const n=b.create({isotope:"C",wallet:this.sourceWallet,metaType:"wallet",metaId:e.address,meta:t,batchId:e.batchId});return this.addAtom(n),this.addContinuIdAtom(),this}initShadowWalletClaim(e){const t=new P().setShadowWalletClaim(!0);return this.initWalletCreation(e,t)}initIdentifierCreation({type:e,contact:t,code:n}){const s={code:n,hash:ce(t.trim(),"Molecule::initIdentifierCreation")};return this.addAtom(b.create({isotope:"C",wallet:this.sourceWallet,metaType:"identifier",metaId:e,meta:new P(s)})),this.addContinuIdAtom(),this}initMeta({meta:e,metaType:t,metaId:n,policy:s}){return this.addAtom(b.create({isotope:"M",wallet:this.sourceWallet,metaType:t,metaId:n,meta:new P(e)})),s&&Object.keys(s).length>0&&this.addPolicyAtom({metaType:t,metaId:n,meta:e,policy:s}),this.addContinuIdAtom(),this}initPeering({host:e}){return this.addAtom(b.create({isotope:"P",wallet:this.sourceWallet,metaType:"walletBundle",metaId:this.bundle,meta:new P({peerHost:e})})),this.addContinuIdAtom(),this}initAppendRequest({metaType:e,metaId:t,action:n,meta:s={}}){return this.addAtom(b.create({isotope:"A",wallet:this.sourceWallet,metaType:e,metaId:t,meta:new P({action:n,...s})})),this.addContinuIdAtom(),this}initTokenRequest({token:e,amount:t,metaType:n,metaId:s,meta:r={},batchId:i=null}){return r.token=e,r.amount=String(t),this.addAtom(b.create({isotope:"T",wallet:this.sourceWallet,value:t,metaType:n,metaId:s,meta:new P(r),batchId:i})),this.addContinuIdAtom(),this}initAuthorization({meta:e}){return this.addAtom(b.create({isotope:"U",wallet:this.sourceWallet,meta:new P(e)})),this.addContinuIdAtom(),this}sign({bundle:e=null,anonymous:t=!1,compressed:n=!0}={}){if(this.atoms.length===0||this.atoms.filter(p=>!(p instanceof b)).length!==0)throw new se;!t&&!this.bundle&&(this.bundle=e||ce(this.secret,"Molecule::sign")),this.molecularHash=b.hashAtoms({atoms:this.atoms});const s=this.atoms[0];let r=s.position;const i=C.get(s.aggregatedMeta(),"signingWallet");if(i&&(r=C.get(JSON.parse(i),"position")),!r)throw new dt("Signing wallet must have a position!");const o=S.generateKey({secret:this.secret,token:s.token,position:s.position}),c=Ie(o,128),u=this.normalizedHash();let l="";for(const p in c){let w=c[p];for(let v=0,O=8-u[p];v<O;v++)w=new D("SHAKE256","TEXT").update(w).getHash("HEX",{outputLen:512});l+=w}n&&(l=Ot(l));const d=Ie(l,Math.ceil(l.length/this.atoms.length));let f=null;for(let p=0,w=d.length;p<w;p++)this.atoms[p].otsFragment=d[p],f=this.atoms[p].position;return f}signSync(e={}){return this.sign(e)}cellSlugBase(){return(this.cellSlug||"").split(this.cellSlugDelimiter)[0]}toJSON(e={}){const{includeValidationContext:t=!1,includeOtsFragments:n=!0}=e;try{const s={status:this.status,molecularHash:this.molecularHash,createdAt:this.createdAt,cellSlug:this.cellSlug,bundle:this.bundle,atoms:this.atoms.map(r=>r.toJSON({includeOtsFragments:n}))};return this.parentHashes&&this.parentHashes.length>0&&(s.parentHashes=this.parentHashes),t&&(s.cellSlugOrigin=this.cellSlugOrigin,s.version=this.version,this.sourceWallet&&(s.sourceWallet={address:this.sourceWallet.address,position:this.sourceWallet.position,token:this.sourceWallet.token,balance:this.sourceWallet.balance||"0",bundle:this.sourceWallet.bundle,batchId:this.sourceWallet.batchId||null,characters:this.sourceWallet.characters||"BASE64",pubkey:this.sourceWallet.pubkey||null,tokenUnits:this.sourceWallet.tokenUnits||[],tradeRates:this.sourceWallet.tradeRates||{},molecules:this.sourceWallet.molecules||{}}),this.remainderWallet&&(s.remainderWallet={address:this.remainderWallet.address,position:this.remainderWallet.position,token:this.remainderWallet.token,balance:this.remainderWallet.balance||"0",bundle:this.remainderWallet.bundle,batchId:this.remainderWallet.batchId||null,characters:this.remainderWallet.characters||"BASE64",pubkey:this.remainderWallet.pubkey||null,tokenUnits:this.remainderWallet.tokenUnits||[],tradeRates:this.remainderWallet.tradeRates||{},molecules:this.remainderWallet.molecules||{}})),s}catch(s){throw new Error(`Molecule serialization failed: ${s.message}`)}}static fromJSON(e,t={}){const{includeValidationContext:n=!1,validateStructure:s=!0}=t;try{const r=typeof e=="string"?JSON.parse(e):e;if(s&&(!r.molecularHash||!Array.isArray(r.atoms)))throw new Error("Invalid molecule data: missing molecularHash or atoms array");const i=new z({secret:null,bundle:r.bundle||null,cellSlug:r.cellSlug||null,version:r.version||null});return i.status=r.status,i.molecularHash=r.molecularHash,i.createdAt=r.createdAt||String(+new Date),i.cellSlugOrigin=r.cellSlugOrigin,i.parentHashes=Array.isArray(r.parentHashes)?[...r.parentHashes]:[],Array.isArray(r.atoms)&&(i.atoms=r.atoms.map((o,c)=>{try{return b.fromJSON(o)}catch(u){throw new Error(`Failed to reconstruct atom ${c}: ${u.message}`)}})),n&&(r.sourceWallet&&(i.sourceWallet=new S({secret:null,token:r.sourceWallet.token,position:r.sourceWallet.position,bundle:r.sourceWallet.bundle,batchId:r.sourceWallet.batchId,characters:r.sourceWallet.characters}),i.sourceWallet.balance=String(r.sourceWallet.balance!=null?r.sourceWallet.balance:0),i.sourceWallet.address=r.sourceWallet.address,r.sourceWallet.pubkey&&(i.sourceWallet.pubkey=r.sourceWallet.pubkey),i.sourceWallet.tokenUnits=r.sourceWallet.tokenUnits||[],i.sourceWallet.tradeRates=r.sourceWallet.tradeRates||{},i.sourceWallet.molecules=r.sourceWallet.molecules||{}),r.remainderWallet&&(i.remainderWallet=new S({secret:null,token:r.remainderWallet.token,position:r.remainderWallet.position,bundle:r.remainderWallet.bundle,batchId:r.remainderWallet.batchId,characters:r.remainderWallet.characters}),i.remainderWallet.balance=String(r.remainderWallet.balance!=null?r.remainderWallet.balance:0),i.remainderWallet.address=r.remainderWallet.address,r.remainderWallet.pubkey&&(i.remainderWallet.pubkey=r.remainderWallet.pubkey),i.remainderWallet.tokenUnits=r.remainderWallet.tokenUnits||[],i.remainderWallet.tradeRates=r.remainderWallet.tradeRates||{},i.remainderWallet.molecules=r.remainderWallet.molecules||{})),i}catch(r){throw new Error(`Molecule deserialization failed: ${r.message}`)}}check(e=null){return new we(this).verify(e)}normalizedHash(){return z.normalize(z.enumerate(this.molecularHash))}}class ke{constructor({token:e,expiresAt:t,encrypt:n,pubkey:s}){this.$__token=e,this.$__expiresAt=t,this.$__pubkey=s,this.$__encrypt=n}static create(e,t){const n=new ke(e);return n.setWallet(t),n}static restore(e,t){const n=new S({secret:t,token:"AUTH",position:e.wallet.position,characters:e.wallet.characters});return ke.create({token:e.token,expiresAt:e.expiresAt,pubkey:e.pubkey,encrypt:e.encrypt},n)}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 this.$__expiresAt*1e3-Date.now()}isExpired(){return!this.$__expiresAt||this.getExpireInterval()<0}getAuthData(){return{token:this.getToken(),pubkey:this.getPubkey(),wallet:this.getWallet()}}}class q extends I{constructor(e="Secret storage operation failed",t=null,n=null){super(e,t,n),this.name="SecretStorageException"}static notFound(e){return new q(`Secret not found for bundle: ${e}`)}static decryptionFailed(e="Invalid passphrase or corrupted ciphertext"){return new q(`Failed to decrypt master secret: ${e}`)}static unavailable(e,t="Hardware or API not accessible"){return new q(`Secret storage provider '${e}' is unavailable: ${t}`)}}const gt=new TextEncoder;function ie(a){if(a instanceof Uint8Array)a.fill(0);else if(Array.isArray(a))for(let e=0;e<a.length;e++)a[e]=0}async function yn(a,e){try{return await e(a)}finally{ie(a)}}async function mn(a,e){const t=gt.encode(a);try{return await e(a)}finally{ie(t)}}function or(a,e){const t=typeof a=="string"?gt.encode(a):a,n=typeof e=="string"?gt.encode(e):e;let s=t.length===n.length?0:1;const r=Math.min(t.length,n.length);for(let i=0;i<r;i++)s|=(t[i]??0)^(n[i]??0);return typeof a=="string"&&ie(t),typeof e=="string"&&ie(n),s===0}class Ye{constructor(){this.providerType="memory",this.secrets=new Map}isHardwareBacked(){return!1}async isAvailable(){return!0}async storeSecret(e,t,n={}){if(!e)throw new q("Bundle hash cannot be empty");if(!t)throw new q("Secret cannot be empty");const s={bundleHash:e,label:n.label,createdAt:Date.now(),hardwareBacked:!1,providerType:this.providerType};this.secrets.set(e,{secret:t,metadata:s})}async retrieveSecret(e){const t=this.secrets.get(e);return t?t.secret:null}async deleteSecret(e){return this.secrets.delete(e)}async hasSecret(e){return this.secrets.has(e)}async listSecrets(){return Array.from(this.secrets.values()).map(e=>({...e.metadata}))}async withSecret(e,t){const n=this.secrets.get(e);if(!n)throw q.notFound(e);return mn(n.secret,t)}clear(){this.secrets.clear()}}const bt=10**18;class ae{static val(e){return Math.abs(e*bt)<1?0:e}static cmp(e,t,n=!1){const s=ae.val(e)*bt,r=ae.val(t)*bt;return Math.abs(s-r)<1?0:s>r?1:-1}static equal(e,t){return ae.cmp(e,t)===0}}class ne extends I{constructor(e="GraphQL did not provide a valid response.",t=null,n=null){super(e,t,n),this.name="InvalidResponseException"}}class We extends I{constructor(e="Authorization token missing or invalid.",t=null,n=null){super(e,t,n),this.name="UnauthenticatedException"}}let E=class{constructor({query:e,json:t,dataKey:n=null}){if(this.dataKey=n,this.errorKey="exception",this.$__payload=null,this.$__query=e,this.$__originResponse=t,this.$__response=t,typeof this.$__response>"u"||this.$__response===null)throw new ne;if(C.has(this.$__response,this.errorKey)){const s=C.get(this.$__response,this.errorKey);throw String(s).includes("Unauthenticated")?new We:new ne}if(this.$__response.errors&&Array.isArray(this.$__response.errors)&&this.$__response.errors.length>0){const s=this.$__response.errors[0].message||"Unknown GraphQL error";throw s.includes("Unauthenticated")?new We:new ne(`GraphQL Error: ${s}`)}this.init()}init(){}data(){if(!this.dataKey)return this.response();if(!this.response().data)throw new ne("Response has no data field");if(!C.has(this.response(),this.dataKey))throw new ne(`Missing expected field: ${this.dataKey}`);return C.get(this.response(),this.dataKey)}response(){return this.$__response}payload(){return null}query(){return this.$__query}status(){return null}success(){return!this.$__response?.errors?.length}error(){return this.$__response?.errors?.length?this.$__response.errors[0].message||"Unknown error":null}reason(){return this.error()}toValidationResult(){return this.success()&&this.payload()!==null?{success:!0,data:this.payload(),warnings:[]}:{success:!1,error:{message:this.reason()||"Unknown error",context:this.constructor.name,details:this.$__response?.errors||[]}}}onSuccess(e){if(this.success()&&this.payload()!==null)try{e(this.payload())}catch(t){console.warn("Response.onSuccess callback failed:",t)}return this}onFailure(e){if(!this.success())try{e(this.reason()||"Unknown error")}catch(t){console.warn("Response.onFailure callback failed:",t)}return this}debug(e=null){const t=e?`[${e}]`:`[${this.constructor.name}]`;return this.success()?console.debug(`${t} Success:`,{payload:this.payload(),query:this.$__query?.constructor?.name,dataKey:this.dataKey}):console.debug(`${t} Failure:`,{error:this.reason(),errors:this.$__response?.errors,rawData:this.$__response}),this}toPromise(){return this.success()&&this.payload()!==null?Promise.resolve(this.payload()):Promise.reject(new Error(this.reason()||"Unknown error"))}map(e){if(this.success()&&this.payload()!==null)try{const t=e(this.payload()),n=Object.create(Object.getPrototypeOf(this));return Object.assign(n,this),n.$__payload=t,n}catch(t){const n=Object.create(Object.getPrototypeOf(this));return Object.assign(n,this),n.$__response={errors:[{message:`Mapping failed: ${t.message}`}]},n}else return this}};class K{constructor(e,t){this.client=e,this.knishIOClient=t,this.$__variables=null,this.$__query=null,this.$__response=null,this.$__request=null}response(){return this.$__response}async createResponseRaw(e){return this.createResponse(e)}createResponse(e){return new E({query:this,json:e})}createQuery({variables:e=null}){if(this.$__variables=this.compiledVariables(e),!this.uri())throw new Y("Query::createQuery() - Node URI was not initialized for this client instance!");if(this.$__query===null)throw new Y("Query::createQuery() - GraphQL subscription was not initialized!");return{query:this.$__query,variables:this.variables()}}async execute({variables:e=null,context:t={}}){this.$__request=this.createQuery({variables:e});const n={...t,...this.createQueryContext()};try{const s=await this.client.query({...this.$__request,context:n});return this.$__response=await this.createResponseRaw(s),this.$__response}catch(s){if(s.name==="AbortError")return this.knishIOClient.log("warn","Query was cancelled"),new E({query:this,json:{data:null,errors:[{message:"Query was cancelled"}]}});throw s}}compiledVariables(e=null){return e||{}}uri(){return this.client.getUri()}variables(){return this.$__variables}createQueryContext(){return{}}}class gn extends E{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 S({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=String(t.amount!=null?t.amount:0)),e}}class bn extends K{constructor(e,t){super(e,t),this.$__query=T.gql`query ($bundle: String!) {
5
5
  ContinuId(bundle: $bundle) {
6
6
  address,
7
7
  bundleHash,
@@ -13,7 +13,7 @@ ${this.stack}`}}class ne extends M{constructor(e="The molecule does not contain
13
13
  amount,
14
14
  createdAt
15
15
  }
16
- }`}createQueryContext(){return{requestPolicy:"network-only"}}createResponse(e){return new ln({query:this,json:e})}}class un extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.WalletBundle"})}payload(){const e=this.data();if(!e||e.length===0)return null;const t={};return e.forEach(n=>{n.metas=ie.aggregateMeta(n.metas),t[n.bundleHash]=n}),t}}class hn extends H{constructor(e,t){super(e,t),this.$__query=T.gql`query( $bundleHashes: [ String! ] ) {
16
+ }`}createQueryContext(){return{requestPolicy:"network-only"}}createResponse(e){return new gn({query:this,json:e})}}class wn extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.WalletBundle"})}payload(){const e=this.data();if(!e||e.length===0)return null;const t={};return e.forEach(n=>{n.metas=oe.aggregateMeta(n.metas),t[n.bundleHash]=n}),t}}class kn extends K{constructor(e,t){super(e,t),this.$__query=T.gql`query( $bundleHashes: [ String! ] ) {
17
17
  WalletBundle( bundleHashes: $bundleHashes ) {
18
18
  bundleHash,
19
19
  metas {
@@ -25,7 +25,7 @@ ${this.stack}`}}class ne extends M{constructor(e="The molecule does not contain
25
25
  },
26
26
  createdAt
27
27
  }
28
- }`}createResponse(e){return new un({query:this,json:e})}}class qe extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.Wallet"})}static toClientWallet({data:e,secret:t=null}){let n;if(e.position===null||typeof e.position>"u"?n=_.create({bundle:e.bundleHash,token:e.tokenSlug,batchId:e.batchId,characters:e.characters}):(n=new _({secret:t,token:e.tokenSlug,position:e.position,batchId:e.batchId,characters:e.characters}),n.address=e.address,n.bundle=e.bundleHash),e.token&&(n.tokenName=e.token.name,n.tokenAmount=e.token.amount,n.tokenSupply=e.token.supply,n.tokenFungibility=e.token.fungibility),e.tokenUnits.length)for(const s of e.tokenUnits)n.tokenUnits.push(le.createFromGraphQL(s));if(e.tradeRates.length)for(const s of e.tradeRates)n.tradeRates[s.tokenSlug]=s.amount;return n.balance=String(e.amount!=null?e.amount:0),n.pubkey=e.pubkey,n.createdAt=e.createdAt,n}getWallets(e=null){const t=this.data();if(!t)return null;const n=[];for(const s of t)n.push(qe.toClientWallet({data:s,secret:e}));return n}payload(){return this.getWallets()}}class dn extends H{constructor(e,t){super(e,t),this.$__query=T.gql`query( $bundleHash: String, $token: String ) {
28
+ }`}createResponse(e){return new wn({query:this,json:e})}}class Ue extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.Wallet"})}static toClientWallet({data:e,secret:t=null}){let n;if(e.position===null||typeof e.position>"u"?n=S.create({bundle:e.bundleHash,token:e.tokenSlug,batchId:e.batchId,characters:e.characters}):(n=new S({secret:t,token:e.tokenSlug,position:e.position,batchId:e.batchId,characters:e.characters}),n.address=e.address,n.bundle=e.bundleHash),e.token&&(n.tokenName=e.token.name,n.tokenAmount=e.token.amount,n.tokenSupply=e.token.supply,n.tokenFungibility=e.token.fungibility),e.tokenUnits.length)for(const s of e.tokenUnits)n.tokenUnits.push(ue.createFromGraphQL(s));if(e.tradeRates.length)for(const s of e.tradeRates)n.tradeRates[s.tokenSlug]=s.amount;return n.balance=String(e.amount!=null?e.amount:0),n.pubkey=e.pubkey,n.createdAt=e.createdAt,n}getWallets(e=null){const t=this.data();if(!t)return null;const n=[];for(const s of t)n.push(Ue.toClientWallet({data:s,secret:e}));return n}payload(){return this.getWallets()}}class Sn extends K{constructor(e,t){super(e,t),this.$__query=T.gql`query( $bundleHash: String, $token: String ) {
29
29
  Wallet( bundleHash: $bundleHash, token: $token ) {
30
30
  address,
31
31
  bundleHash,
@@ -52,7 +52,7 @@ ${this.stack}`}}class ne extends M{constructor(e="The molecule does not contain
52
52
  amount
53
53
  }
54
54
  }
55
- }`}createResponse(e){return new qe({query:this,json:e})}}class pn extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.Balance"})}payload(){let e=this.data();return Array.isArray(e)&&(e=e.length>0?e[0]:null),!e||!e.bundleHash||!e.tokenSlug?null:qe.toClientWallet({data:e})}}class fn extends H{constructor(e,t){super(e,t),this.$__query=T.gql`query( $address: String, $bundleHash: String, $type: String, $token: String, $position: String ) {
55
+ }`}createResponse(e){return new Ue({query:this,json:e})}}class _n extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.Balance"})}payload(){let e=this.data();return Array.isArray(e)&&(e=e.length>0?e[0]:null),!e||!e.bundleHash||!e.tokenSlug?null:Ue.toClientWallet({data:e})}}class $n extends K{constructor(e,t){super(e,t),this.$__query=T.gql`query( $address: String, $bundleHash: String, $type: String, $token: String, $position: String ) {
56
56
  Balance( address: $address, bundleHash: $bundleHash, type: $type, token: $token, position: $position ) {
57
57
  address,
58
58
  bundleHash,
@@ -74,7 +74,7 @@ ${this.stack}`}}class ne extends M{constructor(e="The molecule does not contain
74
74
  amount
75
75
  }
76
76
  }
77
- }`}createResponse(e){return new pn({query:this,json:e})}}class mn extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.MetaType"})}payload(){const e=this.data();if(!e||e.length===0)return null;const t={instances:{},instanceCount:{},paginatorInfo:{}},n=e.pop();return n.instances&&(t.instances=n.instances),n.instanceCount&&(t.instanceCount=n.instanceCount),n.paginatorInfo&&(t.paginatorInfo=n.paginatorInfo),t}}class ht extends H{constructor(e,t){super(e,t),this.$__query=T.gql`query( $metaType: String, $metaTypes: [ String! ], $metaId: String, $metaIds: [ String! ], $key: String, $keys: [ String! ], $value: String, $values: [ String! ], $count: String, $latest: Boolean, $filter: [ MetaFilter! ], $queryArgs: QueryArgs, $countBy: String, $cellSlug: String ) {
77
+ }`}createResponse(e){return new _n({query:this,json:e})}}class An extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.MetaType"})}payload(){const e=this.data();if(!e||e.length===0)return null;const t={instances:{},instanceCount:{},paginatorInfo:{}},n=e.pop();return n.instances&&(t.instances=n.instances),n.instanceCount&&(t.instanceCount=n.instanceCount),n.paginatorInfo&&(t.paginatorInfo=n.paginatorInfo),t}}class wt extends K{constructor(e,t){super(e,t),this.$__query=T.gql`query( $metaType: String, $metaTypes: [ String! ], $metaId: String, $metaIds: [ String! ], $key: String, $keys: [ String! ], $value: String, $values: [ String! ], $count: String, $latest: Boolean, $filter: [ MetaFilter! ], $queryArgs: QueryArgs, $countBy: String, $cellSlug: String ) {
78
78
  MetaType( metaType: $metaType, metaTypes: $metaTypes, metaId: $metaId, metaIds: $metaIds, key: $key, keys: $keys, value: $value, values: $values, count: $count, filter: $filter, queryArgs: $queryArgs, countBy: $countBy, cellSlug: $cellSlug ) {
79
79
  metaType,
80
80
  instanceCount {
@@ -98,11 +98,11 @@ ${this.stack}`}}class ne extends M{constructor(e="The molecule does not contain
98
98
  total
99
99
  }
100
100
  }
101
- }`}static createVariables({metaType:e=null,metaId:t=null,key:n=null,value:s=null,latest:r=null,filter:i=null,queryArgs:o=null,count:c=null,countBy:u=null,cellSlug:l=null}){const d={};return e&&(d[typeof e=="string"?"metaType":"metaTypes"]=e),t&&(d[typeof t=="string"?"metaId":"metaIds"]=t),n&&(d[typeof n=="string"?"key":"keys"]=n),s&&(d[typeof s=="string"?"value":"values"]=s),d.latest=r===!0,i&&(d.filter=i),o&&((typeof o.limit>"u"||o.limit===0)&&(o.limit="*"),d.queryArgs=o),c&&(d.count=c),u&&(d.countBy=u),l&&(d.cellSlug=l),d}createResponse(e){return new mn({query:this,json:e})}}class we extends H{constructor(e,t){super(e,t),this.$__query=T.gql`query( $batchId: String ) {
101
+ }`}static createVariables({metaType:e=null,metaId:t=null,key:n=null,value:s=null,latest:r=null,filter:i=null,queryArgs:o=null,count:c=null,countBy:u=null,cellSlug:l=null}){const d={};return e&&(d[typeof e=="string"?"metaType":"metaTypes"]=e),t&&(d[typeof t=="string"?"metaId":"metaIds"]=t),n&&(d[typeof n=="string"?"key":"keys"]=n),s&&(d[typeof s=="string"?"value":"values"]=s),d.latest=r===!0,i&&(d.filter=i),o&&((typeof o.limit>"u"||o.limit===0)&&(o.limit="*"),d.queryArgs=o),c&&(d.count=c),u&&(d.countBy=u),l&&(d.cellSlug=l),d}createResponse(e){return new An({query:this,json:e})}}class Se extends K{constructor(e,t){super(e,t),this.$__query=T.gql`query( $batchId: String ) {
102
102
  Batch( batchId: $batchId ) {
103
- ${we.getFields()},
103
+ ${Se.getFields()},
104
104
  children {
105
- ${we.getFields()}
105
+ ${Se.getFields()}
106
106
  }
107
107
  }
108
108
  }`}static getFields(){return`batchId,
@@ -154,11 +154,11 @@ ${this.stack}`}}class ne extends M{constructor(e="The molecule does not contain
154
154
  throughMetas {
155
155
  key,
156
156
  value
157
- }`}createResponse(e){const t=new E({query:this,json:e});return t.dataKey="data.Batch",t}}class yn extends H{constructor(e,t){super(e,t),this.$__query=T.gql`query( $batchId: String ) {
157
+ }`}createResponse(e){const t=new E({query:this,json:e});return t.dataKey="data.Batch",t}}class vn extends K{constructor(e,t){super(e,t),this.$__query=T.gql`query( $batchId: String ) {
158
158
  BatchHistory( batchId: $batchId ) {
159
- ${we.getFields()}
159
+ ${Se.getFields()}
160
160
  }
161
- }`}createResponse(e){const t=new E({query:this,json:e});return t.dataKey="data.BatchHistory",t}}class j extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.ProposeMolecule"}),this.$__clientMolecule=e.molecule()}init(){const e=C.get(this.data(),"payload");try{this.$__payload=Object.prototype.toString.call(e)==="[object String]"?JSON.parse(e):e}catch{this.$__payload=null}}clientMolecule(){return this.$__clientMolecule}molecule(){const e=this.data();if(!e)return null;const t=new V({});return t.molecularHash=C.get(e,"molecularHash"),t.status=C.get(e,"status"),t.createdAt=C.get(e,"createdAt"),t}success(){return this.status()==="accepted"}status(){return C.get(this.data(),"status","rejected")}reason(){return C.get(this.data(),"reason","Invalid response from server")}payload(){return this.$__payload}}class Oe extends H{createQuery({variables:e=null}){const t=super.createQuery({variables:e});return t.mutation=t.query,delete t.query,t}async execute({variables:e={},context:t={}}){this.$__request=this.createQuery({variables:e});const n={...t,...this.createQueryContext()};try{const s={...this.$__request,context:n},r=await this.client.mutate(s);return this.$__response=await this.createResponseRaw(r),this.$__response}catch(s){if(s.name==="AbortError")return this.knishIOClient.log("warn","Mutation was cancelled"),new E({query:this,json:{data:null,errors:[{message:"Mutation was cancelled"}]}});throw s}}createQueryContext(){return{}}}class O extends Oe{constructor(e,t,n){super(e,t),this.$__molecule=n,this.$__remainderWallet=null,this.$__query=T.gql`mutation( $molecule: MoleculeInput! ) {
161
+ }`}createResponse(e){const t=new E({query:this,json:e});return t.dataKey="data.BatchHistory",t}}class j extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.ProposeMolecule"}),this.$__clientMolecule=e.molecule()}init(){const e=C.get(this.data(),"payload");try{this.$__payload=Object.prototype.toString.call(e)==="[object String]"?JSON.parse(e):e}catch{this.$__payload=null}}clientMolecule(){return this.$__clientMolecule}molecule(){const e=this.data();if(!e)return null;const t=new z({});return t.molecularHash=C.get(e,"molecularHash"),t.status=C.get(e,"status"),t.createdAt=C.get(e,"createdAt"),t}success(){return this.status()==="accepted"}status(){return C.get(this.data(),"status","rejected")}reason(){return C.get(this.data(),"reason","Invalid response from server")}payload(){return this.$__payload}}class Pe extends K{createQuery({variables:e=null}){const t=super.createQuery({variables:e});return t.mutation=t.query,delete t.query,t}async execute({variables:e={},context:t={}}){this.$__request=this.createQuery({variables:e});const n={...t,...this.createQueryContext()};try{const s={...this.$__request,context:n},r=await this.client.mutate(s);return this.$__response=await this.createResponseRaw(r),this.$__response}catch(s){if(s.name==="AbortError")return this.knishIOClient.log("warn","Mutation was cancelled"),new E({query:this,json:{data:null,errors:[{message:"Mutation was cancelled"}]}});throw s}}createQueryContext(){return{}}}class B extends Pe{constructor(e,t,n){super(e,t),this.$__molecule=n,this.$__remainderWallet=null,this.$__query=T.gql`mutation( $molecule: MoleculeInput! ) {
162
162
  ProposeMolecule( molecule: $molecule ) {
163
163
  molecularHash,
164
164
  height,
@@ -171,7 +171,7 @@ ${this.stack}`}}class ne extends M{constructor(e="The molecule does not contain
171
171
  processedAt,
172
172
  broadcastedAt,
173
173
  }
174
- }`}compiledVariables(e){return{...super.compiledVariables(e),molecule:this.molecule()}}createResponse(e){return new j({query:this,json:e})}async execute({variables:e=null}){return e=e||{},e.molecule=this.molecule(),super.execute({variables:e})}remainderWallet(){return this.$__remainderWallet}molecule(){return this.$__molecule}}class gn extends j{payloadKey(e){if(!C.has(this.payload(),e))throw new te(`ResponseRequestAuthorization::payloadKey() - '${e}' key was not found in the payload!`);return C.get(this.payload(),e)}token(){return this.payloadKey("token")}time(){return this.payloadKey("time")}expiresAt(){try{const t=this.payloadKey("expiresAt");if(t)return Number(t)}catch{}const e=Number(this.time());return e>=1577836800?e:Math.floor(Date.now()/1e3)+Math.floor(e/1e3)}encrypt(){return this.payloadKey("encrypt")}pubKey(){return this.payloadKey("key")}}class bn extends O{fillMolecule({meta:e}){this.$__molecule.initAuthorization({meta:e}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new gn({query:this,json:e})}}class wn extends j{}class kn extends O{fillMolecule({recipientWallet:e,amount:t,meta:n=null}){this.$__molecule.initTokenCreation({recipientWallet:e,amount:t,meta:n||{}}),this.$__molecule.sign({bundle:e.bundle}),this.$__molecule.check()}createResponse(e){return new wn({query:this,json:e})}}class _n extends j{}class Sn extends O{fillMolecule({token:e,amount:t,metaType:n,metaId:s,meta:r=null,batchId:i=null}){this.$__molecule.initTokenRequest({token:e,amount:t,metaType:n,metaId:s,meta:r||{},batchId:i}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new _n({query:this,json:e})}}class $n extends j{payload(){const e={reason:null,status:null},t=this.data();return e.reason=typeof t.reason>"u"?"Invalid response from server":t.reason,e.status=typeof t.status>"u"?"rejected":t.status,e}}class dt extends O{fillMolecule({recipientWallet:e,amount:t}){this.$__molecule.initValue({recipientWallet:e,amount:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}fillMoleculeMulti({recipientWallets:e,amounts:t}){this.$__molecule.initValues({recipientWallets:e,amounts:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}createResponse(e){return new $n({query:this,json:e})}}class An extends j{}class vn extends O{fillMolecule({type:e,contact:t,code:n}){this.$__molecule.initIdentifierCreation({type:e,contact:t,code:n}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new An({query:this,json:e})}}class In extends j{}class Mn extends O{fillMolecule({token:e,batchId:t=null}){const n=_.create({secret:this.$__molecule.secret,bundle:this.$__molecule.bundle,token:e,batchId:t});this.$__molecule.initShadowWalletClaim(n),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new In({query:this,json:e})}}class Tn extends j{}class Cn extends O{fillMolecule({metaType:e,metaId:t,meta:n,policy:s}){this.$__molecule.initMeta({meta:n,metaType:e,metaId:t,policy:s}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Tn({query:this,json:e})}}class xn extends j{}class En extends O{fillMolecule({host:e}){this.$__molecule.initPeering({host:e}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new xn({query:this,json:e})}}class Rn extends j{}class qn extends O{fillMolecule({metaType:e,metaId:t,action:n,meta:s={}}){this.$__molecule.initAppendRequest({metaType:e,metaId:t,action:n,meta:s}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Rn({query:this,json:e})}}class On extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.LinkIdentifier"})}success(){return C.get(this.data(),"set")}message(){return C.get(this.data(),"message")}}class Wn extends Oe{constructor(e,t){super(e,t),this.$__query=T.gql`mutation( $bundle: String!, $type: String!, $content: String! ) {
174
+ }`}compiledVariables(e){return{...super.compiledVariables(e),molecule:this.molecule()}}createResponse(e){return new j({query:this,json:e})}async execute({variables:e=null}){return e=e||{},e.molecule=this.molecule(),super.execute({variables:e})}remainderWallet(){return this.$__remainderWallet}molecule(){return this.$__molecule}}class In extends j{payloadKey(e){if(!C.has(this.payload(),e))throw new ne(`ResponseRequestAuthorization::payloadKey() - '${e}' key was not found in the payload!`);return C.get(this.payload(),e)}token(){return this.payloadKey("token")}time(){return this.payloadKey("time")}expiresAt(){try{const t=this.payloadKey("expiresAt");if(t)return Number(t)}catch{}const e=Number(this.time());return e>=1577836800?e:Math.floor(Date.now()/1e3)+Math.floor(e/1e3)}encrypt(){return this.payloadKey("encrypt")}pubKey(){return this.payloadKey("key")}}class Mn extends B{fillMolecule({meta:e}){this.$__molecule.initAuthorization({meta:e}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new In({query:this,json:e})}}class Tn extends j{}class Cn extends B{fillMolecule({recipientWallet:e,amount:t,meta:n=null}){this.$__molecule.initTokenCreation({recipientWallet:e,amount:t,meta:n||{}}),this.$__molecule.sign({bundle:e.bundle}),this.$__molecule.check()}createResponse(e){return new Tn({query:this,json:e})}}class xn extends j{}class En extends B{fillMolecule({token:e,amount:t,metaType:n,metaId:s,meta:r=null,batchId:i=null}){this.$__molecule.initTokenRequest({token:e,amount:t,metaType:n,metaId:s,meta:r||{},batchId:i}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new xn({query:this,json:e})}}class Rn extends j{payload(){const e={reason:null,status:null},t=this.data();return e.reason=typeof t.reason>"u"?"Invalid response from server":t.reason,e.status=typeof t.status>"u"?"rejected":t.status,e}}class kt extends B{fillMolecule({recipientWallet:e,amount:t}){this.$__molecule.initValue({recipientWallet:e,amount:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}fillMoleculeMulti({recipientWallets:e,amounts:t}){this.$__molecule.initValues({recipientWallets:e,amounts:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}createResponse(e){return new Rn({query:this,json:e})}}class qn extends j{}class On extends B{fillMolecule({type:e,contact:t,code:n}){this.$__molecule.initIdentifierCreation({type:e,contact:t,code:n}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new qn({query:this,json:e})}}class Bn extends j{}class Wn extends B{fillMolecule({token:e,batchId:t=null}){const n=S.create({secret:this.$__molecule.secret,bundle:this.$__molecule.bundle,token:e,batchId:t});this.$__molecule.initShadowWalletClaim(n),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Bn({query:this,json:e})}}class Un extends j{}class Pn extends B{fillMolecule({metaType:e,metaId:t,meta:n,policy:s}){this.$__molecule.initMeta({meta:n,metaType:e,metaId:t,policy:s}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Un({query:this,json:e})}}class Hn extends j{}class Kn extends B{fillMolecule({host:e}){this.$__molecule.initPeering({host:e}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Hn({query:this,json:e})}}class Nn extends j{}class Fn extends B{fillMolecule({metaType:e,metaId:t,action:n,meta:s={}}){this.$__molecule.initAppendRequest({metaType:e,metaId:t,action:n,meta:s}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Nn({query:this,json:e})}}class Ln extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.LinkIdentifier"})}success(){return C.get(this.data(),"set")}message(){return C.get(this.data(),"message")}}class Qn extends Pe{constructor(e,t){super(e,t),this.$__query=T.gql`mutation( $bundle: String!, $type: String!, $content: String! ) {
175
175
  LinkIdentifier( bundle: $bundle, type: $type, content: $content ) {
176
176
  type,
177
177
  bundle,
@@ -179,13 +179,13 @@ ${this.stack}`}}class ne extends M{constructor(e="The molecule does not contain
179
179
  set,
180
180
  message
181
181
  }
182
- }`}createResponse(e){return new On({query:this,json:e})}}class Un extends j{}class Bn extends O{fillMolecule(e){this.$__molecule.initWalletCreation(e),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Un({query:this,json:e})}}class Pn extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.AccessToken"})}reason(){return"Invalid response from server"}success(){return this.payload()!==null}payload(){return this.data()}payloadKey(e){if(!C.has(this.payload(),e))throw new te(`ResponseAuthorizationGuest::payloadKey() - '${e}' key is not found in the payload!`);return C.get(this.payload(),e)}token(){return this.payloadKey("token")}time(){return this.payloadKey("time")}expiresAt(){try{const t=this.payloadKey("expiresAt");if(t)return Number(t)}catch{}const e=Number(this.time());return e>=1577836800?e:Math.floor(Date.now()/1e3)+Math.floor(e/1e3)}pubKey(){return this.payloadKey("key")}encrypt(){return this.payloadKey("encrypt")}}class Hn extends Oe{constructor(e,t){super(e,t),this.$__query=T.gql`mutation( $cellSlug: String, $pubkey: String, $encrypt: Boolean ) {
182
+ }`}createResponse(e){return new Ln({query:this,json:e})}}class Dn extends j{}class jn extends B{fillMolecule(e){this.$__molecule.initWalletCreation(e),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Dn({query:this,json:e})}}class Vn extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.AccessToken"})}reason(){return"Invalid response from server"}success(){return this.payload()!==null}payload(){return this.data()}payloadKey(e){if(!C.has(this.payload(),e))throw new ne(`ResponseAuthorizationGuest::payloadKey() - '${e}' key is not found in the payload!`);return C.get(this.payload(),e)}token(){return this.payloadKey("token")}time(){return this.payloadKey("time")}expiresAt(){try{const t=this.payloadKey("expiresAt");if(t)return Number(t)}catch{}const e=Number(this.time());return e>=1577836800?e:Math.floor(Date.now()/1e3)+Math.floor(e/1e3)}pubKey(){return this.payloadKey("key")}encrypt(){return this.payloadKey("encrypt")}}class zn extends Pe{constructor(e,t){super(e,t),this.$__query=T.gql`mutation( $cellSlug: String, $pubkey: String, $encrypt: Boolean ) {
183
183
  AccessToken( cellSlug: $cellSlug, pubkey: $pubkey, encrypt: $encrypt ) {
184
184
  token,
185
185
  pubkey,
186
186
  expiresAt
187
187
  }
188
- }`}createResponse(e){return new Pn({query:this,json:e})}}class pt extends M{constructor(e="The shadow wallet does not exist",t=null,n=null){super(e,t,n),this.name="WalletShadowException"}}class Kn extends M{constructor(e="Stackable tokens with unit IDs cannot have decimal places!",t=null,n=null){super(e,t,n),this.name="StackableUnitDecimalsException"}}class ke extends M{constructor(e="Stackable tokens with unit IDs cannot have an amount!",t=null,n=null){super(e,t,n),this.name="StackableUnitAmountException"}}class ze{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 Z("Subscribe::createSubscribe() - Node URI was not initialized for this client instance!");if(this.$__subscribe===null)throw new Z("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 Z(`${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 Vs extends ze{constructor(e){super(e),this.$__subscribe=T.gql`
188
+ }`}createResponse(e){return new Vn({query:this,json:e})}}class St extends I{constructor(e="The shadow wallet does not exist",t=null,n=null){super(e,t,n),this.name="WalletShadowException"}}class Jn extends I{constructor(e="Stackable tokens with unit IDs cannot have decimal places!",t=null,n=null){super(e,t,n),this.name="StackableUnitDecimalsException"}}class _e extends I{constructor(e="Stackable tokens with unit IDs cannot have an amount!",t=null,n=null){super(e,t,n),this.name="StackableUnitAmountException"}}class et{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 Y("Subscribe::createSubscribe() - Node URI was not initialized for this client instance!");if(this.$__subscribe===null)throw new Y("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 Y(`${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 lr extends et{constructor(e){super(e),this.$__subscribe=T.gql`
189
189
  subscription onCreateMolecule ( $bundle: String! ) {
190
190
  CreateMolecule( bundle: $bundle ) {
191
191
  molecularHash,
@@ -230,7 +230,7 @@ ${this.stack}`}}class ne extends M{constructor(e="The molecule does not contain
230
230
  }
231
231
  }
232
232
  }
233
- `}}class zs extends ze{constructor(e){super(e),this.$__subscribe=T.gql`
233
+ `}}class cr extends et{constructor(e){super(e),this.$__subscribe=T.gql`
234
234
  subscription onWalletStatus ( $bundle: String!, $token: String! ) {
235
235
  WalletStatus( bundle: $bundle, token: $token ) {
236
236
  bundle,
@@ -239,7 +239,7 @@ ${this.stack}`}}class ne extends M{constructor(e="The molecule does not contain
239
239
  balance,
240
240
  }
241
241
  }
242
- `}}class Js extends ze{constructor(e){super(e),this.$__subscribe=T.gql`
242
+ `}}class ur extends et{constructor(e){super(e),this.$__subscribe=T.gql`
243
243
  subscription onActiveWallet ( $bundle: String! ) {
244
244
  ActiveWallet( bundle: $bundle ) {
245
245
  address,
@@ -277,7 +277,7 @@ ${this.stack}`}}class ne extends M{constructor(e="The molecule does not contain
277
277
  }
278
278
  }
279
279
  }
280
- `}}class Gs extends ze{constructor(e){super(e),this.$__subscribe=T.gql`
280
+ `}}class hr extends et{constructor(e){super(e),this.$__subscribe=T.gql`
281
281
  subscription onActiveUser ( $metaType: String!, $metaId: String! ) {
282
282
  ActiveUser( metaType: $metaType, metaId: $metaId ) {
283
283
  bundleHash,
@@ -287,7 +287,7 @@ ${this.stack}`}}class ne extends M{constructor(e="The molecule does not contain
287
287
  createdAt,
288
288
  updatedAt
289
289
  }
290
- }`}}class Nn extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.ActiveSession"})}}class Ln extends Oe{constructor(e,t){super(e,t),this.$__query=T.gql`mutation(
290
+ }`}}class Gn extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.ActiveSession"})}}class Xn extends Pe{constructor(e,t){super(e,t),this.$__query=T.gql`mutation(
291
291
  $bundleHash: String!,
292
292
  $metaType: String!,
293
293
  $metaId: String!,
@@ -315,7 +315,7 @@ ${this.stack}`}}class ne extends M{constructor(e="The molecule does not contain
315
315
  createdAt,
316
316
  updatedAt
317
317
  }
318
- }`}createResponse(e){return new Nn({query:this,json:e})}}class Qn extends E{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(const n of e){const s={...n};s.jsonData&&(s.jsonData=JSON.parse(s.jsonData)),s.createdAt&&(s.createdAt=new Date(s.createdAt)),s.updatedAt&&(s.updatedAt=new Date(s.updatedAt)),t.push(s)}return t}}class Fn extends H{constructor(e,t){super(e,t),this.$__query=T.gql`query ActiveUserQuery ($bundleHash:String, $metaType: String, $metaId: String) {
318
+ }`}createResponse(e){return new Gn({query:this,json:e})}}class Zn extends E{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(const n of e){const s={...n};s.jsonData&&(s.jsonData=JSON.parse(s.jsonData)),s.createdAt&&(s.createdAt=new Date(s.createdAt)),s.updatedAt&&(s.updatedAt=new Date(s.updatedAt)),t.push(s)}return t}}class Yn extends K{constructor(e,t){super(e,t),this.$__query=T.gql`query ActiveUserQuery ($bundleHash:String, $metaType: String, $metaId: String) {
319
319
  ActiveUser (bundleHash: $bundleHash, metaType: $metaType, metaId: $metaId) {
320
320
  bundleHash,
321
321
  metaType,
@@ -324,7 +324,7 @@ ${this.stack}`}}class ne extends M{constructor(e="The molecule does not contain
324
324
  createdAt,
325
325
  updatedAt
326
326
  }
327
- }`}createResponse(e){return new Qn({query:this,json:e})}}class jn extends H{constructor(e,t){super(e,t),this.$__query=T.gql`query( $slug: String, $slugs: [ String! ], $limit: Int, $order: String ) {
327
+ }`}createResponse(e){return new Zn({query:this,json:e})}}class es extends K{constructor(e,t){super(e,t),this.$__query=T.gql`query( $slug: String, $slugs: [ String! ], $limit: Int, $order: String ) {
328
328
  Token( slug: $slug, slugs: $slugs, limit: $limit, order: $order ) {
329
329
  slug,
330
330
  name,
@@ -334,7 +334,7 @@ ${this.stack}`}}class ne extends M{constructor(e="The molecule does not contain
334
334
  amount,
335
335
  icon,
336
336
  }
337
- }`}createResponse(e){return new E({query:this,json:e,dataKey:"data.Token"})}}class ft extends M{constructor(e="Authorization attempt rejected by ledger.",t=null,n=null){super(e,t,n),this.name="AuthorizationRejectedException"}}class Dn extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.Atom"})}payload(){const e=this.data();if(!e)return null;const t={instances:[],instanceCount:{},paginatorInfo:{}};if(e.instances){t.instances=e.instances;for(const n in t.instances){const s=t.instances[n];s.metasJson&&(t.instances[n].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 n of e.instances)n.metasJson&&t.push(JSON.parse(n.metasJson));return t}}class mt extends H{constructor(e,t){super(e,t),this.$__query=T.gql`query(
337
+ }`}createResponse(e){return new E({query:this,json:e,dataKey:"data.Token"})}}class _t extends I{constructor(e="Authorization attempt rejected by ledger.",t=null,n=null){super(e,t,n),this.name="AuthorizationRejectedException"}}class ts extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.Atom"})}payload(){const e=this.data();if(!e)return null;const t={instances:[],instanceCount:{},paginatorInfo:{}};if(e.instances){t.instances=e.instances;for(const n in t.instances){const s=t.instances[n];s.metasJson&&(t.instances[n].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 n of e.instances)n.metasJson&&t.push(JSON.parse(n.metasJson));return t}}class $t extends K{constructor(e,t){super(e,t),this.$__query=T.gql`query(
338
338
  $molecularHashes: [String!],
339
339
  $bundleHashes: [String!],
340
340
  $positions:[String!],
@@ -390,7 +390,7 @@ ${this.stack}`}}class ne extends M{constructor(e="The molecule does not contain
390
390
  total
391
391
  }
392
392
  }
393
- }`}static createVariables({molecularHashes:e,molecularHash:t,bundleHashes:n,bundleHash:s,positions:r,position:i,walletAddresses:o,walletAddress:c,isotopes:u,isotope:l,tokenSlugs:d,tokenSlug:f,cellSlugs:p,cellSlug:w,batchIds:v,batchId:q,values:m,value:y,metaTypes:k,metaType:R,metaIds:S,metaId:A,indexes:I,index:x,filter:$,latest:N,queryArgs:U}){return t&&(e=e||[],e.push(t)),s&&(n=n||[],n.push(s)),i&&(r=r||[],r.push(i)),c&&(o=o||[],o.push(c)),l&&(u=u||[],u.push(l)),f&&(d=d||[],d.push(f)),w&&(p=p||[],p.push(w)),q&&(v=v||[],v.push(q)),y&&(m=m||[],m.push(y)),R&&(k=k||[],k.push(R)),A&&(S=S||[],S.push(A)),x&&(I=I||[],I.push(x)),{molecularHashes:e,bundleHashes:n,positions:r,walletAddresses:o,isotopes:u,tokenSlugs:d,cellSlugs:p,batchIds:v,values:m,metaTypes:k,metaIds:S,indexes:I,filter:$,latest:N,queryArgs:U}}createResponse(e){return new Dn({query:this,json:e})}}class Vn extends E{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 zn extends H{constructor(e,t){super(e,t),this.$__query=T.gql`query( $metaType: String, $metaId: String, ) {
393
+ }`}static createVariables({molecularHashes:e,molecularHash:t,bundleHashes:n,bundleHash:s,positions:r,position:i,walletAddresses:o,walletAddress:c,isotopes:u,isotope:l,tokenSlugs:d,tokenSlug:f,cellSlugs:p,cellSlug:w,batchIds:v,batchId:O,values:y,value:m,metaTypes:k,metaType:R,metaIds:_,metaId:A,indexes:M,index:x,filter:$,latest:F,queryArgs:U}){return t&&(e=e||[],e.push(t)),s&&(n=n||[],n.push(s)),i&&(r=r||[],r.push(i)),c&&(o=o||[],o.push(c)),l&&(u=u||[],u.push(l)),f&&(d=d||[],d.push(f)),w&&(p=p||[],p.push(w)),O&&(v=v||[],v.push(O)),m&&(y=y||[],y.push(m)),R&&(k=k||[],k.push(R)),A&&(_=_||[],_.push(A)),x&&(M=M||[],M.push(x)),{molecularHashes:e,bundleHashes:n,positions:r,walletAddresses:o,isotopes:u,tokenSlugs:d,cellSlugs:p,batchIds:v,values:y,metaTypes:k,metaIds:_,indexes:M,filter:$,latest:F,queryArgs:U}}createResponse(e){return new ts({query:this,json:e})}}class ns extends E{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 ss extends K{constructor(e,t){super(e,t),this.$__query=T.gql`query( $metaType: String, $metaId: String, ) {
394
394
  Policy( metaType: $metaType, metaId: $metaId ) {
395
395
  molecularHash,
396
396
  position,
@@ -401,7 +401,7 @@ ${this.stack}`}}class ne extends M{constructor(e="The molecule does not contain
401
401
  rule,
402
402
  createdAt
403
403
  }
404
- }`}createResponse(e){return new Vn({query:this,json:e})}}class Jn extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.MetaTypeViaAtom"})}payload(){const e=this.data();if(!e||e.length===0)return null;const t={instances:{},instanceCount:{},paginatorInfo:{}},n=e.pop();return n.instances&&(t.instances=n.instances),n.instanceCount&&(t.instanceCount=n.instanceCount),n.paginatorInfo&&(t.paginatorInfo=n.paginatorInfo),t}}class yt extends H{constructor(e,t){super(e,t),this.$__query=T.gql`query ($metaTypes: [String!], $metaIds: [String!], $values: [String!], $keys: [String!], $latest: Boolean, $filter: [MetaFilter!], $queryArgs: QueryArgs, $countBy: String, $atomValues: [String!], $cellSlugs: [String!] ) {
404
+ }`}createResponse(e){return new ns({query:this,json:e})}}class rs extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.MetaTypeViaAtom"})}payload(){const e=this.data();if(!e||e.length===0)return null;const t={instances:{},instanceCount:{},paginatorInfo:{}},n=e.pop();return n.instances&&(t.instances=n.instances),n.instanceCount&&(t.instanceCount=n.instanceCount),n.paginatorInfo&&(t.paginatorInfo=n.paginatorInfo),t}}class At extends K{constructor(e,t){super(e,t),this.$__query=T.gql`query ($metaTypes: [String!], $metaIds: [String!], $values: [String!], $keys: [String!], $latest: Boolean, $filter: [MetaFilter!], $queryArgs: QueryArgs, $countBy: String, $atomValues: [String!], $cellSlugs: [String!] ) {
405
405
  MetaTypeViaAtom(
406
406
  metaTypes: $metaTypes
407
407
  metaIds: $metaIds
@@ -434,7 +434,7 @@ ${this.stack}`}}class ne extends M{constructor(e="The molecule does not contain
434
434
  total
435
435
  }
436
436
  }
437
- }`}static createVariables({metaType:e=null,metaId:t=null,key:n=null,value:s=null,keys:r=null,values:i=null,atomValues:o=null,latest:c=null,filter:u=null,queryArgs:l=null,countBy:d=null,cellSlug:f=null}){const p={};return o&&(p.atomValues=o),r&&(p.keys=r),i&&(p.values=i),e&&(p.metaTypes=typeof e=="string"?[e]:e),t&&(p.metaIds=typeof t=="string"?[t]:t),f&&(p.cellSlugs=typeof f=="string"?[f]:f),d&&(p.countBy=d),u&&(p.filter=u),n&&s&&(p.filter=p.filter||[],p.filter.push({key:n,value:s,comparison:"="})),p.latest=c===!0,l&&((typeof l.limit>"u"||l.limit===0)&&(l.limit="*"),p.queryArgs=l),p}createResponse(e){return new Jn({query:this,json:e})}}class Je extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.MetaTypeViaAtom"})}static extractMetasFromMolecule(e,t,n){if(!e||!e.atoms)return[];const s=[];for(const r of e.atoms){if(r.metaType!==t||r.metaId!==n||!r.metasJson)continue;let i;try{if(i=JSON.parse(r.metasJson),!Array.isArray(i))continue}catch{continue}for(const o of i)s.push({molecularHash:e.molecularHash,position:r.position,key:o.key,value:o.value,createdAt:r.createdAt})}return s}payload(){const e=this.data();if(!e||e.length===0)return null;const t={instances:{},instanceCount:{},paginatorInfo:{}},n=e.pop();return n.instances&&(t.instances=n.instances.map(s=>{let r=s.metas;return(!r||r.length===0)&&(r=Je.extractMetasFromMolecule(s.molecule,s.metaType,s.metaId)),{...s,metas:r}})),n.instanceCount&&(t.instanceCount=n.instanceCount),n.paginatorInfo&&(t.paginatorInfo=n.paginatorInfo),t}verifyIntegrity(){const e=[],t=this.data();if(!t||t.length===0)return{verified:!0,molecules:e};const n=t[t.length-1]?.instances||[];for(const s of n)s.molecule&&e.push(ge.verifyFromServerData(s.molecule));return{verified:e.length===0||e.every(s=>s.verified),molecules:e}}}class gt extends H{constructor(e,t){super(e,t),this.$__query=T.gql`query ($metaTypes: [String!], $metaIds: [String!], $values: [String!], $keys: [String!], $latest: Boolean, $filter: [MetaFilter!], $queryArgs: QueryArgs, $countBy: String, $atomValues: [String!], $cellSlugs: [String!] ) {
437
+ }`}static createVariables({metaType:e=null,metaId:t=null,key:n=null,value:s=null,keys:r=null,values:i=null,atomValues:o=null,latest:c=null,filter:u=null,queryArgs:l=null,countBy:d=null,cellSlug:f=null}){const p={};return o&&(p.atomValues=o),r&&(p.keys=r),i&&(p.values=i),e&&(p.metaTypes=typeof e=="string"?[e]:e),t&&(p.metaIds=typeof t=="string"?[t]:t),f&&(p.cellSlugs=typeof f=="string"?[f]:f),d&&(p.countBy=d),u&&(p.filter=u),n&&s&&(p.filter=p.filter||[],p.filter.push({key:n,value:s,comparison:"="})),p.latest=c===!0,l&&((typeof l.limit>"u"||l.limit===0)&&(l.limit="*"),p.queryArgs=l),p}createResponse(e){return new rs({query:this,json:e})}}class tt extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.MetaTypeViaAtom"})}static extractMetasFromMolecule(e,t,n){if(!e||!e.atoms)return[];const s=[];for(const r of e.atoms){if(r.metaType!==t||r.metaId!==n||!r.metasJson)continue;let i;try{if(i=JSON.parse(r.metasJson),!Array.isArray(i))continue}catch{continue}for(const o of i)s.push({molecularHash:e.molecularHash,position:r.position,key:o.key,value:o.value,createdAt:r.createdAt})}return s}payload(){const e=this.data();if(!e||e.length===0)return null;const t={instances:{},instanceCount:{},paginatorInfo:{}},n=e.pop();return n.instances&&(t.instances=n.instances.map(s=>{let r=s.metas;return(!r||r.length===0)&&(r=tt.extractMetasFromMolecule(s.molecule,s.metaType,s.metaId)),{...s,metas:r}})),n.instanceCount&&(t.instanceCount=n.instanceCount),n.paginatorInfo&&(t.paginatorInfo=n.paginatorInfo),t}verifyIntegrity(){const e=[],t=this.data();if(!t||t.length===0)return{verified:!0,molecules:e};const n=t[t.length-1]?.instances||[];for(const s of n)s.molecule&&e.push(we.verifyFromServerData(s.molecule));return{verified:e.length===0||e.every(s=>s.verified),molecules:e}}}class vt extends K{constructor(e,t){super(e,t),this.$__query=T.gql`query ($metaTypes: [String!], $metaIds: [String!], $values: [String!], $keys: [String!], $latest: Boolean, $filter: [MetaFilter!], $queryArgs: QueryArgs, $countBy: String, $atomValues: [String!], $cellSlugs: [String!] ) {
438
438
  MetaTypeViaAtom(
439
439
  metaTypes: $metaTypes
440
440
  metaIds: $metaIds
@@ -488,7 +488,7 @@ ${this.stack}`}}class ne extends M{constructor(e="The molecule does not contain
488
488
  total
489
489
  }
490
490
  }
491
- }`}static createVariables({metaType:e=null,metaId:t=null,key:n=null,value:s=null,keys:r=null,values:i=null,atomValues:o=null,latest:c=null,filter:u=null,queryArgs:l=null,countBy:d=null,cellSlug:f=null}){const p={};return o&&(p.atomValues=o),r&&(p.keys=r),i&&(p.values=i),e&&(p.metaTypes=typeof e=="string"?[e]:e),t&&(p.metaIds=typeof t=="string"?[t]:t),f&&(p.cellSlugs=typeof f=="string"?[f]:f),d&&(p.countBy=d),u&&(p.filter=u),n&&s&&(p.filter=p.filter||[],p.filter.push({key:n,value:s,comparison:"="})),p.latest=c===!0,l&&((typeof l.limit>"u"||l.limit===0)&&(l.limit="*"),p.queryArgs=l),p}createResponse(e){return new Je({query:this,json:e})}}class Gn extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.embeddingStatus"})}payload(){const e=this.data();return!e||!Array.isArray(e)||e.length===0?null:e}}class bt extends H{constructor(e,t){super(e,t),this.$__query=T.gql`query( $metaType: String, $metaId: String, $instances: [EmbeddingStatusInput!] ) {
491
+ }`}static createVariables({metaType:e=null,metaId:t=null,key:n=null,value:s=null,keys:r=null,values:i=null,atomValues:o=null,latest:c=null,filter:u=null,queryArgs:l=null,countBy:d=null,cellSlug:f=null}){const p={};return o&&(p.atomValues=o),r&&(p.keys=r),i&&(p.values=i),e&&(p.metaTypes=typeof e=="string"?[e]:e),t&&(p.metaIds=typeof t=="string"?[t]:t),f&&(p.cellSlugs=typeof f=="string"?[f]:f),d&&(p.countBy=d),u&&(p.filter=u),n&&s&&(p.filter=p.filter||[],p.filter.push({key:n,value:s,comparison:"="})),p.latest=c===!0,l&&((typeof l.limit>"u"||l.limit===0)&&(l.limit="*"),p.queryArgs=l),p}createResponse(e){return new tt({query:this,json:e})}}class is extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.embeddingStatus"})}payload(){const e=this.data();return!e||!Array.isArray(e)||e.length===0?null:e}}class It extends K{constructor(e,t){super(e,t),this.$__query=T.gql`query( $metaType: String, $metaId: String, $instances: [EmbeddingStatusInput!] ) {
492
492
  embeddingStatus( metaType: $metaType, metaId: $metaId, instances: $instances ) {
493
493
  metaType,
494
494
  metaId,
@@ -498,7 +498,7 @@ ${this.stack}`}}class ne extends M{constructor(e="The molecule does not contain
498
498
  embeddedAt,
499
499
  model
500
500
  }
501
- }`}static createVariables({metaType:e=null,metaId:t=null,instances:n=null}){const s={};return n&&n.length>0&&(s.instances=n),e&&(s.metaType=e),t&&(s.metaId=t),s}createResponse(e){return new Gn({query:this,json:e})}}class Xn extends j{}class Zn extends O{fillMolecule({metaType:e,metaId:t,rule:n,policy:s}){this.$__molecule.createRule({metaType:e,metaId:t,rule:n,policy:s}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Xn({query:this,json:e})}}class Yn extends O{fillMolecule({amount:e,tradeRates:t}){this.$__molecule.initDepositBuffer({amount:e,tradeRates:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}}class es extends O{fillMolecule({recipients:e,signingWallet:t}){this.$__molecule.initWithdrawBuffer({recipients:e,signingWallet:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}}function Y(a,e,t,n){return new(t||(t=Promise))((function(s,r){function i(u){try{c(n.next(u))}catch(l){r(l)}}function o(u){try{c(n.throw(u))}catch(l){r(l)}}function c(u){var l;u.done?s(u.value):(l=u.value,l instanceof t?l:new t((function(d){d(l)}))).then(i,o)}c((n=n.apply(a,[])).next())}))}function ee(a,e){var t,n,s,r,i={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return r={next:o(0),throw:o(1),return:o(2)},typeof Symbol=="function"&&(r[Symbol.iterator]=function(){return this}),r;function o(c){return function(u){return(function(l){if(t)throw new TypeError("Generator is already executing.");for(;r&&(r=0,l[0]&&(i=0)),i;)try{if(t=1,n&&(s=2&l[0]?n.return:l[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,l[1])).done)return s;switch(n=0,s&&(l=[2&l[0],s.value]),l[0]){case 0:case 1:s=l;break;case 4:return i.label++,{value:l[1],done:!1};case 5:i.label++,n=l[1],l=[0];continue;case 7:l=i.ops.pop(),i.trys.pop();continue;default:if(s=i.trys,!((s=s.length>0&&s[s.length-1])||l[0]!==6&&l[0]!==2)){i=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){i.label=l[1];break}if(l[0]===6&&i.label<s[1]){i.label=s[1],s=l;break}if(s&&i.label<s[2]){i.label=s[2],i.ops.push(l);break}s[2]&&i.ops.pop(),i.trys.pop();continue}l=e.call(a,i)}catch(d){l=[6,d],n=0}finally{t=s=0}if(5&l[0])throw l[1];return{value:l[0]?l[1]:void 0,done:!0}})([c,u])}}}typeof SuppressedError=="function"&&SuppressedError;var W={exclude:[],include:[],logging:!0},ts={},Xs={timeout:"true"},G=function(a,e){typeof window<"u"&&(ts[a]=e)},Zs=function(){return Object.fromEntries(Object.entries(ts).filter((function(a){var e,t=a[0];return!(!((e=W?.exclude)===null||e===void 0)&&e.includes(t))})).filter((function(a){var e,t,n,s,r=a[0];return!((e=W?.include)===null||e===void 0)&&e.some((function(i){return i.includes(".")}))?(t=W?.include)===null||t===void 0?void 0:t.some((function(i){return i.startsWith(r)})):((n=W?.include)===null||n===void 0?void 0:n.length)===0||((s=W?.include)===null||s===void 0?void 0:s.includes(r))})).map((function(a){return[a[0],(0,a[1])()]})))};function Ge(a){return a^=a>>>16,a=Math.imul(a,2246822507),a^=a>>>13,a=Math.imul(a,3266489909),(a^=a>>>16)>>>0}var K=new Uint32Array([597399067,2869860233,951274213,2716044179]);function z(a,e){return a<<e|a>>>32-e}function wt(a,e){var t;if(e===void 0&&(e=0),e=e?0|e:0,typeof a=="string"&&(t=a,a=new TextEncoder().encode(t).buffer),!(a instanceof ArrayBuffer))throw new TypeError("Expected key to be ArrayBuffer or string");var n=new Uint32Array([e,e,e,e]);(function(r,i){for(var o=r.byteLength/16|0,c=new Uint32Array(r,0,4*o),u=0;u<o;u++){var l=c.subarray(4*u,4*(u+1));l[0]=Math.imul(l[0],K[0]),l[0]=z(l[0],15),l[0]=Math.imul(l[0],K[1]),i[0]=i[0]^l[0],i[0]=z(i[0],19),i[0]=i[0]+i[1],i[0]=Math.imul(i[0],5)+1444728091,l[1]=Math.imul(l[1],K[1]),l[1]=z(l[1],16),l[1]=Math.imul(l[1],K[2]),i[1]=i[1]^l[1],i[1]=z(i[1],17),i[1]=i[1]+i[2],i[1]=Math.imul(i[1],5)+197830471,l[2]=Math.imul(l[2],K[2]),l[2]=z(l[2],17),l[2]=Math.imul(l[2],K[3]),i[2]=i[2]^l[2],i[2]=z(i[2],15),i[2]=i[2]+i[3],i[2]=Math.imul(i[2],5)+2530024501,l[3]=Math.imul(l[3],K[3]),l[3]=z(l[3],18),l[3]=Math.imul(l[3],K[0]),i[3]=i[3]^l[3],i[3]=z(i[3],13),i[3]=i[3]+i[0],i[3]=Math.imul(i[3],5)+850148119}})(a,n),(function(r,i){var o=r.byteLength/16|0,c=r.byteLength%16,u=new Uint32Array(4),l=new Uint8Array(r,16*o,c);switch(c){case 15:u[3]=u[3]^l[14]<<16;case 14:u[3]=u[3]^l[13]<<8;case 13:u[3]=u[3]^l[12]<<0,u[3]=Math.imul(u[3],K[3]),u[3]=z(u[3],18),u[3]=Math.imul(u[3],K[0]),i[3]=i[3]^u[3];case 12:u[2]=u[2]^l[11]<<24;case 11:u[2]=u[2]^l[10]<<16;case 10:u[2]=u[2]^l[9]<<8;case 9:u[2]=u[2]^l[8]<<0,u[2]=Math.imul(u[2],K[2]),u[2]=z(u[2],17),u[2]=Math.imul(u[2],K[3]),i[2]=i[2]^u[2];case 8:u[1]=u[1]^l[7]<<24;case 7:u[1]=u[1]^l[6]<<16;case 6:u[1]=u[1]^l[5]<<8;case 5:u[1]=u[1]^l[4]<<0,u[1]=Math.imul(u[1],K[1]),u[1]=z(u[1],16),u[1]=Math.imul(u[1],K[2]),i[1]=i[1]^u[1];case 4:u[0]=u[0]^l[3]<<24;case 3:u[0]=u[0]^l[2]<<16;case 2:u[0]=u[0]^l[1]<<8;case 1:u[0]=u[0]^l[0]<<0,u[0]=Math.imul(u[0],K[0]),u[0]=z(u[0],15),u[0]=Math.imul(u[0],K[1]),i[0]=i[0]^u[0]}})(a,n),(function(r,i){i[0]=i[0]^r.byteLength,i[1]=i[1]^r.byteLength,i[2]=i[2]^r.byteLength,i[3]=i[3]^r.byteLength,i[0]=i[0]+i[1]|0,i[0]=i[0]+i[2]|0,i[0]=i[0]+i[3]|0,i[1]=i[1]+i[0]|0,i[2]=i[2]+i[0]|0,i[3]=i[3]+i[0]|0,i[0]=Ge(i[0]),i[1]=Ge(i[1]),i[2]=Ge(i[2]),i[3]=Ge(i[3]),i[0]=i[0]+i[1]|0,i[0]=i[0]+i[2]|0,i[0]=i[0]+i[3]|0,i[1]=i[1]+i[0]|0,i[2]=i[2]+i[0]|0,i[3]=i[3]+i[0]|0})(a,n);var s=new Uint8Array(n.buffer);return Array.from(s).map((function(r){return r.toString(16).padStart(2,"0")})).join("")}function Ys(a,e){return new Promise((function(t){setTimeout((function(){return t(e)}),a)}))}function er(a,e,t){return Promise.all(a.map((function(n){return Promise.race([n,Ys(e,t)])})))}var tr="0.19.1";function nr(){return tr}function ns(){return Y(this,void 0,void 0,(function(){var a,e,t,n,s;return ee(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),a=Zs(),e=Object.keys(a),[4,er(Object.values(a),W?.timeout||1e3,Xs)];case 1:return t=r.sent(),n=t.filter((function(i){return i!==void 0})),s={},n.forEach((function(i,o){s[e[o]]=i})),[2,ss(s,W.exclude||[],W.include||[],"")];case 2:throw r.sent();case 3:return[2]}}))}))}function ss(a,e,t,n){n===void 0&&(n="");for(var s={},r=function(u,l){var d=n+u+".";if(typeof l!="object"||Array.isArray(l)){var f=e.some((function(v){return d.startsWith(v)})),p=t.some((function(v){return d.startsWith(v)}));f&&!p||(s[u]=l)}else{var w=ss(l,e,t,d);Object.keys(w).length>0&&(s[u]=w)}},i=0,o=Object.entries(a);i<o.length;i++){var c=o[i];r(c[0],c[1])}return s}function sr(a){return Y(this,void 0,void 0,(function(){var e,t;return ee(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,ns()];case 1:return e=n.sent(),t=wt(JSON.stringify(e)),Math.random()<.001&&W.logging&&(function(s,r){Y(this,void 0,void 0,(function(){var i,o;return ee(this,(function(c){switch(c.label){case 0:if(i="https://logging.thumbmarkjs.com/v1/log",o={thumbmark:s,components:r,version:nr()},sessionStorage.getItem("_tmjs_l"))return[3,4];sessionStorage.setItem("_tmjs_l","1"),c.label=1;case 1:return c.trys.push([1,3,,4]),[4,fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})];case 2:case 3:return c.sent(),[3,4];case 4:return[2]}}))}))})(t,e),[2,t.toString()];case 2:throw n.sent();case 3:return[2]}}))}))}function rr(a){for(var e=0,t=0;t<a.length;++t)e+=Math.abs(a[t]);return e}function rs(a,e,t){for(var n=[],s=0;s<a[0].data.length;s++){for(var r=[],i=0;i<a.length;i++)r.push(a[i].data[s]);n.push(ir(r))}var o=new Uint8ClampedArray(n);return new ImageData(o,e,t)}function ir(a){if(a.length===0)return 0;for(var e={},t=0,n=a;t<n.length;t++)e[r=n[t]]=(e[r]||0)+1;var s=a[0];for(var r in e)e[r]>e[s]&&(s=parseInt(r,10));return s}function We(){if(typeof navigator>"u")return{name:"unknown",version:"unknown"};for(var a=navigator.userAgent,e={Edg:"Edge",OPR:"Opera"},t=0,n=[/(?<name>Edge|Edg)\/(?<version>\d+(?:\.\d+)?)/,/(?<name>(?:Chrome|Chromium|OPR|Opera|Vivaldi|Brave))\/(?<version>\d+(?:\.\d+)?)/,/(?<name>(?:Firefox|Waterfox|Iceweasel|IceCat))\/(?<version>\d+(?:\.\d+)?)/,/(?<name>Safari)\/(?<version>\d+(?:\.\d+)?)/,/(?<name>MSIE|Trident|IEMobile).+?(?<version>\d+(?:\.\d+)?)/,/(?<name>[A-Za-z]+)\/(?<version>\d+(?:\.\d+)?)/,/(?<name>SamsungBrowser)\/(?<version>\d+(?:\.\d+)?)/];t<n.length;t++){var s=n[t],r=a.match(s);if(r&&r.groups)return{name:e[r.groups.name]||r.groups.name,version:r.groups.version}}return{name:"unknown",version:"unknown"}}G("audio",(function(){return Y(this,void 0,void 0,(function(){return ee(this,(function(a){return[2,new Promise((function(e,t){try{var n=new(window.OfflineAudioContext||window.webkitOfflineAudioContext)(1,5e3,44100),s=n.createBufferSource(),r=n.createOscillator();r.frequency.value=1e3;var i,o=n.createDynamicsCompressor();o.threshold.value=-50,o.knee.value=40,o.ratio.value=12,o.attack.value=0,o.release.value=.2,r.connect(o),o.connect(n.destination),r.start(),n.oncomplete=function(c){i=c.renderedBuffer.getChannelData(0),e({sampleHash:rr(i),oscillator:r.type,maxChannels:n.destination.maxChannelCount,channelCountMode:s.channelCountMode})},n.startRendering()}catch(c){console.error("Error creating audio fingerprint:",c),t(c)}}))]}))}))}));var ar=We().name!=="SamsungBrowser"?1:3,is=280,as=20;We().name!="Firefox"&&G("canvas",(function(){return document.createElement("canvas").getContext("2d"),new Promise((function(a){var e=Array.from({length:ar},(function(){return(function(){var t=document.createElement("canvas"),n=t.getContext("2d");if(!n)return new ImageData(1,1);t.width=is,t.height=as;var s=n.createLinearGradient(0,0,t.width,t.height);s.addColorStop(0,"red"),s.addColorStop(.16666666666666666,"orange"),s.addColorStop(.3333333333333333,"yellow"),s.addColorStop(.5,"green"),s.addColorStop(.6666666666666666,"blue"),s.addColorStop(.8333333333333334,"indigo"),s.addColorStop(1,"violet"),n.fillStyle=s,n.fillRect(0,0,t.width,t.height);var r="Random Text WMwmil10Oo";n.font="23.123px Arial",n.fillStyle="black",n.fillText(r,-5,15),n.fillStyle="rgba(0, 0, 255, 0.5)",n.fillText(r,-3.3,17.7),n.beginPath(),n.moveTo(0,0),n.lineTo(2*t.width/7,t.height),n.strokeStyle="white",n.lineWidth=2,n.stroke();var i=n.getImageData(0,0,t.width,t.height);return i})()}));a({commonImageDataHash:wt(rs(e,is,as).data.toString()).toString()})}))}));var kt,or=["Arial","Arial Black","Arial Narrow","Arial Rounded MT","Arimo","Archivo","Barlow","Bebas Neue","Bitter","Bookman","Calibri","Cabin","Candara","Century","Century Gothic","Comic Sans MS","Constantia","Courier","Courier New","Crimson Text","DM Mono","DM Sans","DM Serif Display","DM Serif Text","Dosis","Droid Sans","Exo","Fira Code","Fira Sans","Franklin Gothic Medium","Garamond","Geneva","Georgia","Gill Sans","Helvetica","Impact","Inconsolata","Indie Flower","Inter","Josefin Sans","Karla","Lato","Lexend","Lucida Bright","Lucida Console","Lucida Sans Unicode","Manrope","Merriweather","Merriweather Sans","Montserrat","Myriad","Noto Sans","Nunito","Nunito Sans","Open Sans","Optima","Orbitron","Oswald","Pacifico","Palatino","Perpetua","PT Sans","PT Serif","Poppins","Prompt","Public Sans","Quicksand","Rajdhani","Recursive","Roboto","Roboto Condensed","Rockwell","Rubik","Segoe Print","Segoe Script","Segoe UI","Sora","Source Sans Pro","Space Mono","Tahoma","Taviraj","Times","Times New Roman","Titillium Web","Trebuchet MS","Ubuntu","Varela Round","Verdana","Work Sans"],lr=["monospace","sans-serif","serif"];function os(a,e){if(!a)throw new Error("Canvas context not supported");return a.font,a.font="72px ".concat(e),a.measureText("WwMmLli0Oo").width}function cr(){var a,e=document.createElement("canvas"),t=(a=e.getContext("webgl"))!==null&&a!==void 0?a:e.getContext("experimental-webgl");if(t&&"getParameter"in t)try{var n=(t.getParameter(t.VENDOR)||"").toString(),s=(t.getParameter(t.RENDERER)||"").toString(),r={vendor:n,renderer:s,version:(t.getParameter(t.VERSION)||"").toString(),shadingLanguageVersion:(t.getParameter(t.SHADING_LANGUAGE_VERSION)||"").toString()};if(!s.length||!n.length){var i=t.getExtension("WEBGL_debug_renderer_info");if(i){var o=(t.getParameter(i.UNMASKED_VENDOR_WEBGL)||"").toString(),c=(t.getParameter(i.UNMASKED_RENDERER_WEBGL)||"").toString();o&&(r.vendorUnmasked=o),c&&(r.rendererUnmasked=c)}}return r}catch{}return"undefined"}function ur(){var a=new Float32Array(1),e=new Uint8Array(a.buffer);return a[0]=1/0,a[0]=a[0]-a[0],e[3]}function hr(a,e){var t={};return e.forEach((function(n){var s=(function(r){if(r.length===0)return null;var i={};r.forEach((function(u){var l=String(u);i[l]=(i[l]||0)+1}));var o=r[0],c=1;return Object.keys(i).forEach((function(u){i[u]>c&&(o=u,c=i[u])})),o})(a.map((function(r){return n in r?r[n]:void 0})).filter((function(r){return r!==void 0})));s&&(t[n]=s)})),t}function dr(){var a=[],e={"prefers-contrast":["high","more","low","less","forced","no-preference"],"any-hover":["hover","none"],"any-pointer":["none","coarse","fine"],pointer:["none","coarse","fine"],hover:["hover","none"],update:["fast","slow"],"inverted-colors":["inverted","none"],"prefers-reduced-motion":["reduce","no-preference"],"prefers-reduced-transparency":["reduce","no-preference"],scripting:["none","initial-only","enabled"],"forced-colors":["active","none"]};return Object.keys(e).forEach((function(t){e[t].forEach((function(n){matchMedia("(".concat(t,": ").concat(n,")")).matches&&a.push("".concat(t,": ").concat(n))}))})),a}function pr(){if(window.location.protocol==="https:"&&typeof window.ApplePaySession=="function")try{for(var a=window.ApplePaySession.supportsVersion,e=15;e>0;e--)if(a(e))return e}catch{return 0}return 0}We().name!="Firefox"&&G("fonts",(function(){var a=this;return new Promise((function(e,t){try{(function(n){var s;Y(this,void 0,void 0,(function(){var r,i,o;return ee(this,(function(c){switch(c.label){case 0:return document.body?[3,2]:[4,(u=50,new Promise((function(d){return setTimeout(d,u,l)})))];case 1:return c.sent(),[3,0];case 2:if((r=document.createElement("iframe")).setAttribute("frameBorder","0"),(i=r.style).setProperty("position","fixed"),i.setProperty("display","block","important"),i.setProperty("visibility","visible"),i.setProperty("border","0"),i.setProperty("opacity","0"),r.src="about:blank",document.body.appendChild(r),!(o=r.contentDocument||((s=r.contentWindow)===null||s===void 0?void 0:s.document)))throw new Error("Iframe document is not accessible");return n({iframe:o}),setTimeout((function(){document.body.removeChild(r)}),0),[2]}var u,l}))}))})((function(n){var s=n.iframe;return Y(a,void 0,void 0,(function(){var r,i,o,c;return ee(this,(function(u){return r=s.createElement("canvas"),i=r.getContext("2d"),o=lr.map((function(l){return os(i,l)})),c={},or.forEach((function(l){var d=os(i,l);o.includes(d)||(c[l]=d)})),e(c),[2]}))}))}))}catch{t({error:"unsupported"})}}))})),G("hardware",(function(){return new Promise((function(a,e){var t=navigator.deviceMemory!==void 0?navigator.deviceMemory:0,n=window.performance&&window.performance.memory?window.performance.memory:0;a({videocard:cr(),architecture:ur(),deviceMemory:t.toString()||"undefined",jsHeapSizeLimit:n.jsHeapSizeLimit||0})}))})),G("locales",(function(){return new Promise((function(a){a({languages:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone})}))})),G("permissions",(function(){return Y(this,void 0,void 0,(function(){var a;return ee(this,(function(e){return kt=W?.permissions_to_check||["accelerometer","accessibility","accessibility-events","ambient-light-sensor","background-fetch","background-sync","bluetooth","camera","clipboard-read","clipboard-write","device-info","display-capture","gyroscope","geolocation","local-fonts","magnetometer","microphone","midi","nfc","notifications","payment-handler","persistent-storage","push","speaker","storage-access","top-level-storage-access","window-management","query"],a=Array.from({length:W?.retries||3},(function(){return(function(){return Y(this,void 0,void 0,(function(){var t,n,s,r,i;return ee(this,(function(o){switch(o.label){case 0:t={},n=0,s=kt,o.label=1;case 1:if(!(n<s.length))return[3,6];r=s[n],o.label=2;case 2:return o.trys.push([2,4,,5]),[4,navigator.permissions.query({name:r})];case 3:return i=o.sent(),t[r]=i.state.toString(),[3,5];case 4:return o.sent(),[3,5];case 5:return n++,[3,1];case 6:return[2,t]}}))}))})()})),[2,Promise.all(a).then((function(t){return hr(t,kt)}))]}))}))})),G("plugins",(function(){var a=[];if(navigator.plugins)for(var e=0;e<navigator.plugins.length;e++){var t=navigator.plugins[e];a.push([t.name,t.filename,t.description].join("|"))}return new Promise((function(n){n({plugins:a})}))})),G("screen",(function(){return new Promise((function(a){a({is_touchscreen:navigator.maxTouchPoints>0,maxTouchPoints:navigator.maxTouchPoints,colorDepth:screen.colorDepth,mediaMatches:dr()})}))})),G("system",(function(){return new Promise((function(a){var e=We();a({platform:window.navigator.platform,cookieEnabled:window.navigator.cookieEnabled,productSub:navigator.productSub,product:navigator.product,useragent:navigator.userAgent,hardwareConcurrency:navigator.hardwareConcurrency,browser:{name:e.name,version:e.version},applePayVersion:pr()})}))}));var L,fr=We().name!=="SamsungBrowser"?1:3,g=null;G("webgl",(function(){return Y(this,void 0,void 0,(function(){var a;return ee(this,(function(e){typeof document<"u"&&((L=document.createElement("canvas")).width=200,L.height=100,g=L.getContext("webgl"));try{if(!g)throw new Error("WebGL not supported");return a=Array.from({length:fr},(function(){return(function(){try{if(!g)throw new Error("WebGL not supported");var t=`
501
+ }`}static createVariables({metaType:e=null,metaId:t=null,instances:n=null}){const s={};return n&&n.length>0&&(s.instances=n),e&&(s.metaType=e),t&&(s.metaId=t),s}createResponse(e){return new is({query:this,json:e})}}class as extends j{}class os extends B{fillMolecule({metaType:e,metaId:t,rule:n,policy:s}){this.$__molecule.createRule({metaType:e,metaId:t,rule:n,policy:s}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new as({query:this,json:e})}}class ls extends B{fillMolecule({amount:e,tradeRates:t}){this.$__molecule.initDepositBuffer({amount:e,tradeRates:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}}class cs extends B{fillMolecule({recipients:e,signingWallet:t}){this.$__molecule.initWithdrawBuffer({recipients:e,signingWallet:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}}function ee(a,e,t,n){return new(t||(t=Promise))((function(s,r){function i(u){try{c(n.next(u))}catch(l){r(l)}}function o(u){try{c(n.throw(u))}catch(l){r(l)}}function c(u){var l;u.done?s(u.value):(l=u.value,l instanceof t?l:new t((function(d){d(l)}))).then(i,o)}c((n=n.apply(a,[])).next())}))}function te(a,e){var t,n,s,r,i={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return r={next:o(0),throw:o(1),return:o(2)},typeof Symbol=="function"&&(r[Symbol.iterator]=function(){return this}),r;function o(c){return function(u){return(function(l){if(t)throw new TypeError("Generator is already executing.");for(;r&&(r=0,l[0]&&(i=0)),i;)try{if(t=1,n&&(s=2&l[0]?n.return:l[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,l[1])).done)return s;switch(n=0,s&&(l=[2&l[0],s.value]),l[0]){case 0:case 1:s=l;break;case 4:return i.label++,{value:l[1],done:!1};case 5:i.label++,n=l[1],l=[0];continue;case 7:l=i.ops.pop(),i.trys.pop();continue;default:if(s=i.trys,!((s=s.length>0&&s[s.length-1])||l[0]!==6&&l[0]!==2)){i=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){i.label=l[1];break}if(l[0]===6&&i.label<s[1]){i.label=s[1],s=l;break}if(s&&i.label<s[2]){i.label=s[2],i.ops.push(l);break}s[2]&&i.ops.pop(),i.trys.pop();continue}l=e.call(a,i)}catch(d){l=[6,d],n=0}finally{t=s=0}if(5&l[0])throw l[1];return{value:l[0]?l[1]:void 0,done:!0}})([c,u])}}}typeof SuppressedError=="function"&&SuppressedError;var W={exclude:[],include:[],logging:!0},us={},dr={timeout:"true"},X=function(a,e){typeof window<"u"&&(us[a]=e)},pr=function(){return Object.fromEntries(Object.entries(us).filter((function(a){var e,t=a[0];return!(!((e=W?.exclude)===null||e===void 0)&&e.includes(t))})).filter((function(a){var e,t,n,s,r=a[0];return!((e=W?.include)===null||e===void 0)&&e.some((function(i){return i.includes(".")}))?(t=W?.include)===null||t===void 0?void 0:t.some((function(i){return i.startsWith(r)})):((n=W?.include)===null||n===void 0?void 0:n.length)===0||((s=W?.include)===null||s===void 0?void 0:s.includes(r))})).map((function(a){return[a[0],(0,a[1])()]})))};function nt(a){return a^=a>>>16,a=Math.imul(a,2246822507),a^=a>>>13,a=Math.imul(a,3266489909),(a^=a>>>16)>>>0}var N=new Uint32Array([597399067,2869860233,951274213,2716044179]);function J(a,e){return a<<e|a>>>32-e}function Mt(a,e){var t;if(e===void 0&&(e=0),e=e?0|e:0,typeof a=="string"&&(t=a,a=new TextEncoder().encode(t).buffer),!(a instanceof ArrayBuffer))throw new TypeError("Expected key to be ArrayBuffer or string");var n=new Uint32Array([e,e,e,e]);(function(r,i){for(var o=r.byteLength/16|0,c=new Uint32Array(r,0,4*o),u=0;u<o;u++){var l=c.subarray(4*u,4*(u+1));l[0]=Math.imul(l[0],N[0]),l[0]=J(l[0],15),l[0]=Math.imul(l[0],N[1]),i[0]=i[0]^l[0],i[0]=J(i[0],19),i[0]=i[0]+i[1],i[0]=Math.imul(i[0],5)+1444728091,l[1]=Math.imul(l[1],N[1]),l[1]=J(l[1],16),l[1]=Math.imul(l[1],N[2]),i[1]=i[1]^l[1],i[1]=J(i[1],17),i[1]=i[1]+i[2],i[1]=Math.imul(i[1],5)+197830471,l[2]=Math.imul(l[2],N[2]),l[2]=J(l[2],17),l[2]=Math.imul(l[2],N[3]),i[2]=i[2]^l[2],i[2]=J(i[2],15),i[2]=i[2]+i[3],i[2]=Math.imul(i[2],5)+2530024501,l[3]=Math.imul(l[3],N[3]),l[3]=J(l[3],18),l[3]=Math.imul(l[3],N[0]),i[3]=i[3]^l[3],i[3]=J(i[3],13),i[3]=i[3]+i[0],i[3]=Math.imul(i[3],5)+850148119}})(a,n),(function(r,i){var o=r.byteLength/16|0,c=r.byteLength%16,u=new Uint32Array(4),l=new Uint8Array(r,16*o,c);switch(c){case 15:u[3]=u[3]^l[14]<<16;case 14:u[3]=u[3]^l[13]<<8;case 13:u[3]=u[3]^l[12]<<0,u[3]=Math.imul(u[3],N[3]),u[3]=J(u[3],18),u[3]=Math.imul(u[3],N[0]),i[3]=i[3]^u[3];case 12:u[2]=u[2]^l[11]<<24;case 11:u[2]=u[2]^l[10]<<16;case 10:u[2]=u[2]^l[9]<<8;case 9:u[2]=u[2]^l[8]<<0,u[2]=Math.imul(u[2],N[2]),u[2]=J(u[2],17),u[2]=Math.imul(u[2],N[3]),i[2]=i[2]^u[2];case 8:u[1]=u[1]^l[7]<<24;case 7:u[1]=u[1]^l[6]<<16;case 6:u[1]=u[1]^l[5]<<8;case 5:u[1]=u[1]^l[4]<<0,u[1]=Math.imul(u[1],N[1]),u[1]=J(u[1],16),u[1]=Math.imul(u[1],N[2]),i[1]=i[1]^u[1];case 4:u[0]=u[0]^l[3]<<24;case 3:u[0]=u[0]^l[2]<<16;case 2:u[0]=u[0]^l[1]<<8;case 1:u[0]=u[0]^l[0]<<0,u[0]=Math.imul(u[0],N[0]),u[0]=J(u[0],15),u[0]=Math.imul(u[0],N[1]),i[0]=i[0]^u[0]}})(a,n),(function(r,i){i[0]=i[0]^r.byteLength,i[1]=i[1]^r.byteLength,i[2]=i[2]^r.byteLength,i[3]=i[3]^r.byteLength,i[0]=i[0]+i[1]|0,i[0]=i[0]+i[2]|0,i[0]=i[0]+i[3]|0,i[1]=i[1]+i[0]|0,i[2]=i[2]+i[0]|0,i[3]=i[3]+i[0]|0,i[0]=nt(i[0]),i[1]=nt(i[1]),i[2]=nt(i[2]),i[3]=nt(i[3]),i[0]=i[0]+i[1]|0,i[0]=i[0]+i[2]|0,i[0]=i[0]+i[3]|0,i[1]=i[1]+i[0]|0,i[2]=i[2]+i[0]|0,i[3]=i[3]+i[0]|0})(a,n);var s=new Uint8Array(n.buffer);return Array.from(s).map((function(r){return r.toString(16).padStart(2,"0")})).join("")}function fr(a,e){return new Promise((function(t){setTimeout((function(){return t(e)}),a)}))}function yr(a,e,t){return Promise.all(a.map((function(n){return Promise.race([n,fr(e,t)])})))}var mr="0.19.1";function gr(){return mr}function hs(){return ee(this,void 0,void 0,(function(){var a,e,t,n,s;return te(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),a=pr(),e=Object.keys(a),[4,yr(Object.values(a),W?.timeout||1e3,dr)];case 1:return t=r.sent(),n=t.filter((function(i){return i!==void 0})),s={},n.forEach((function(i,o){s[e[o]]=i})),[2,ds(s,W.exclude||[],W.include||[],"")];case 2:throw r.sent();case 3:return[2]}}))}))}function ds(a,e,t,n){n===void 0&&(n="");for(var s={},r=function(u,l){var d=n+u+".";if(typeof l!="object"||Array.isArray(l)){var f=e.some((function(v){return d.startsWith(v)})),p=t.some((function(v){return d.startsWith(v)}));f&&!p||(s[u]=l)}else{var w=ds(l,e,t,d);Object.keys(w).length>0&&(s[u]=w)}},i=0,o=Object.entries(a);i<o.length;i++){var c=o[i];r(c[0],c[1])}return s}function br(a){return ee(this,void 0,void 0,(function(){var e,t;return te(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,hs()];case 1:return e=n.sent(),t=Mt(JSON.stringify(e)),Math.random()<.001&&W.logging&&(function(s,r){ee(this,void 0,void 0,(function(){var i,o;return te(this,(function(c){switch(c.label){case 0:if(i="https://logging.thumbmarkjs.com/v1/log",o={thumbmark:s,components:r,version:gr()},sessionStorage.getItem("_tmjs_l"))return[3,4];sessionStorage.setItem("_tmjs_l","1"),c.label=1;case 1:return c.trys.push([1,3,,4]),[4,fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})];case 2:case 3:return c.sent(),[3,4];case 4:return[2]}}))}))})(t,e),[2,t.toString()];case 2:throw n.sent();case 3:return[2]}}))}))}function wr(a){for(var e=0,t=0;t<a.length;++t)e+=Math.abs(a[t]);return e}function ps(a,e,t){for(var n=[],s=0;s<a[0].data.length;s++){for(var r=[],i=0;i<a.length;i++)r.push(a[i].data[s]);n.push(kr(r))}var o=new Uint8ClampedArray(n);return new ImageData(o,e,t)}function kr(a){if(a.length===0)return 0;for(var e={},t=0,n=a;t<n.length;t++)e[r=n[t]]=(e[r]||0)+1;var s=a[0];for(var r in e)e[r]>e[s]&&(s=parseInt(r,10));return s}function He(){if(typeof navigator>"u")return{name:"unknown",version:"unknown"};for(var a=navigator.userAgent,e={Edg:"Edge",OPR:"Opera"},t=0,n=[/(?<name>Edge|Edg)\/(?<version>\d+(?:\.\d+)?)/,/(?<name>(?:Chrome|Chromium|OPR|Opera|Vivaldi|Brave))\/(?<version>\d+(?:\.\d+)?)/,/(?<name>(?:Firefox|Waterfox|Iceweasel|IceCat))\/(?<version>\d+(?:\.\d+)?)/,/(?<name>Safari)\/(?<version>\d+(?:\.\d+)?)/,/(?<name>MSIE|Trident|IEMobile).+?(?<version>\d+(?:\.\d+)?)/,/(?<name>[A-Za-z]+)\/(?<version>\d+(?:\.\d+)?)/,/(?<name>SamsungBrowser)\/(?<version>\d+(?:\.\d+)?)/];t<n.length;t++){var s=n[t],r=a.match(s);if(r&&r.groups)return{name:e[r.groups.name]||r.groups.name,version:r.groups.version}}return{name:"unknown",version:"unknown"}}X("audio",(function(){return ee(this,void 0,void 0,(function(){return te(this,(function(a){return[2,new Promise((function(e,t){try{var n=new(window.OfflineAudioContext||window.webkitOfflineAudioContext)(1,5e3,44100),s=n.createBufferSource(),r=n.createOscillator();r.frequency.value=1e3;var i,o=n.createDynamicsCompressor();o.threshold.value=-50,o.knee.value=40,o.ratio.value=12,o.attack.value=0,o.release.value=.2,r.connect(o),o.connect(n.destination),r.start(),n.oncomplete=function(c){i=c.renderedBuffer.getChannelData(0),e({sampleHash:wr(i),oscillator:r.type,maxChannels:n.destination.maxChannelCount,channelCountMode:s.channelCountMode})},n.startRendering()}catch(c){console.error("Error creating audio fingerprint:",c),t(c)}}))]}))}))}));var Sr=He().name!=="SamsungBrowser"?1:3,fs=280,ys=20;He().name!="Firefox"&&X("canvas",(function(){return document.createElement("canvas").getContext("2d"),new Promise((function(a){var e=Array.from({length:Sr},(function(){return(function(){var t=document.createElement("canvas"),n=t.getContext("2d");if(!n)return new ImageData(1,1);t.width=fs,t.height=ys;var s=n.createLinearGradient(0,0,t.width,t.height);s.addColorStop(0,"red"),s.addColorStop(.16666666666666666,"orange"),s.addColorStop(.3333333333333333,"yellow"),s.addColorStop(.5,"green"),s.addColorStop(.6666666666666666,"blue"),s.addColorStop(.8333333333333334,"indigo"),s.addColorStop(1,"violet"),n.fillStyle=s,n.fillRect(0,0,t.width,t.height);var r="Random Text WMwmil10Oo";n.font="23.123px Arial",n.fillStyle="black",n.fillText(r,-5,15),n.fillStyle="rgba(0, 0, 255, 0.5)",n.fillText(r,-3.3,17.7),n.beginPath(),n.moveTo(0,0),n.lineTo(2*t.width/7,t.height),n.strokeStyle="white",n.lineWidth=2,n.stroke();var i=n.getImageData(0,0,t.width,t.height);return i})()}));a({commonImageDataHash:Mt(ps(e,fs,ys).data.toString()).toString()})}))}));var Tt,_r=["Arial","Arial Black","Arial Narrow","Arial Rounded MT","Arimo","Archivo","Barlow","Bebas Neue","Bitter","Bookman","Calibri","Cabin","Candara","Century","Century Gothic","Comic Sans MS","Constantia","Courier","Courier New","Crimson Text","DM Mono","DM Sans","DM Serif Display","DM Serif Text","Dosis","Droid Sans","Exo","Fira Code","Fira Sans","Franklin Gothic Medium","Garamond","Geneva","Georgia","Gill Sans","Helvetica","Impact","Inconsolata","Indie Flower","Inter","Josefin Sans","Karla","Lato","Lexend","Lucida Bright","Lucida Console","Lucida Sans Unicode","Manrope","Merriweather","Merriweather Sans","Montserrat","Myriad","Noto Sans","Nunito","Nunito Sans","Open Sans","Optima","Orbitron","Oswald","Pacifico","Palatino","Perpetua","PT Sans","PT Serif","Poppins","Prompt","Public Sans","Quicksand","Rajdhani","Recursive","Roboto","Roboto Condensed","Rockwell","Rubik","Segoe Print","Segoe Script","Segoe UI","Sora","Source Sans Pro","Space Mono","Tahoma","Taviraj","Times","Times New Roman","Titillium Web","Trebuchet MS","Ubuntu","Varela Round","Verdana","Work Sans"],$r=["monospace","sans-serif","serif"];function ms(a,e){if(!a)throw new Error("Canvas context not supported");return a.font,a.font="72px ".concat(e),a.measureText("WwMmLli0Oo").width}function Ar(){var a,e=document.createElement("canvas"),t=(a=e.getContext("webgl"))!==null&&a!==void 0?a:e.getContext("experimental-webgl");if(t&&"getParameter"in t)try{var n=(t.getParameter(t.VENDOR)||"").toString(),s=(t.getParameter(t.RENDERER)||"").toString(),r={vendor:n,renderer:s,version:(t.getParameter(t.VERSION)||"").toString(),shadingLanguageVersion:(t.getParameter(t.SHADING_LANGUAGE_VERSION)||"").toString()};if(!s.length||!n.length){var i=t.getExtension("WEBGL_debug_renderer_info");if(i){var o=(t.getParameter(i.UNMASKED_VENDOR_WEBGL)||"").toString(),c=(t.getParameter(i.UNMASKED_RENDERER_WEBGL)||"").toString();o&&(r.vendorUnmasked=o),c&&(r.rendererUnmasked=c)}}return r}catch{}return"undefined"}function vr(){var a=new Float32Array(1),e=new Uint8Array(a.buffer);return a[0]=1/0,a[0]=a[0]-a[0],e[3]}function Ir(a,e){var t={};return e.forEach((function(n){var s=(function(r){if(r.length===0)return null;var i={};r.forEach((function(u){var l=String(u);i[l]=(i[l]||0)+1}));var o=r[0],c=1;return Object.keys(i).forEach((function(u){i[u]>c&&(o=u,c=i[u])})),o})(a.map((function(r){return n in r?r[n]:void 0})).filter((function(r){return r!==void 0})));s&&(t[n]=s)})),t}function Mr(){var a=[],e={"prefers-contrast":["high","more","low","less","forced","no-preference"],"any-hover":["hover","none"],"any-pointer":["none","coarse","fine"],pointer:["none","coarse","fine"],hover:["hover","none"],update:["fast","slow"],"inverted-colors":["inverted","none"],"prefers-reduced-motion":["reduce","no-preference"],"prefers-reduced-transparency":["reduce","no-preference"],scripting:["none","initial-only","enabled"],"forced-colors":["active","none"]};return Object.keys(e).forEach((function(t){e[t].forEach((function(n){matchMedia("(".concat(t,": ").concat(n,")")).matches&&a.push("".concat(t,": ").concat(n))}))})),a}function Tr(){if(window.location.protocol==="https:"&&typeof window.ApplePaySession=="function")try{for(var a=window.ApplePaySession.supportsVersion,e=15;e>0;e--)if(a(e))return e}catch{return 0}return 0}He().name!="Firefox"&&X("fonts",(function(){var a=this;return new Promise((function(e,t){try{(function(n){var s;ee(this,void 0,void 0,(function(){var r,i,o;return te(this,(function(c){switch(c.label){case 0:return document.body?[3,2]:[4,(u=50,new Promise((function(d){return setTimeout(d,u,l)})))];case 1:return c.sent(),[3,0];case 2:if((r=document.createElement("iframe")).setAttribute("frameBorder","0"),(i=r.style).setProperty("position","fixed"),i.setProperty("display","block","important"),i.setProperty("visibility","visible"),i.setProperty("border","0"),i.setProperty("opacity","0"),r.src="about:blank",document.body.appendChild(r),!(o=r.contentDocument||((s=r.contentWindow)===null||s===void 0?void 0:s.document)))throw new Error("Iframe document is not accessible");return n({iframe:o}),setTimeout((function(){document.body.removeChild(r)}),0),[2]}var u,l}))}))})((function(n){var s=n.iframe;return ee(a,void 0,void 0,(function(){var r,i,o,c;return te(this,(function(u){return r=s.createElement("canvas"),i=r.getContext("2d"),o=$r.map((function(l){return ms(i,l)})),c={},_r.forEach((function(l){var d=ms(i,l);o.includes(d)||(c[l]=d)})),e(c),[2]}))}))}))}catch{t({error:"unsupported"})}}))})),X("hardware",(function(){return new Promise((function(a,e){var t=navigator.deviceMemory!==void 0?navigator.deviceMemory:0,n=window.performance&&window.performance.memory?window.performance.memory:0;a({videocard:Ar(),architecture:vr(),deviceMemory:t.toString()||"undefined",jsHeapSizeLimit:n.jsHeapSizeLimit||0})}))})),X("locales",(function(){return new Promise((function(a){a({languages:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone})}))})),X("permissions",(function(){return ee(this,void 0,void 0,(function(){var a;return te(this,(function(e){return Tt=W?.permissions_to_check||["accelerometer","accessibility","accessibility-events","ambient-light-sensor","background-fetch","background-sync","bluetooth","camera","clipboard-read","clipboard-write","device-info","display-capture","gyroscope","geolocation","local-fonts","magnetometer","microphone","midi","nfc","notifications","payment-handler","persistent-storage","push","speaker","storage-access","top-level-storage-access","window-management","query"],a=Array.from({length:W?.retries||3},(function(){return(function(){return ee(this,void 0,void 0,(function(){var t,n,s,r,i;return te(this,(function(o){switch(o.label){case 0:t={},n=0,s=Tt,o.label=1;case 1:if(!(n<s.length))return[3,6];r=s[n],o.label=2;case 2:return o.trys.push([2,4,,5]),[4,navigator.permissions.query({name:r})];case 3:return i=o.sent(),t[r]=i.state.toString(),[3,5];case 4:return o.sent(),[3,5];case 5:return n++,[3,1];case 6:return[2,t]}}))}))})()})),[2,Promise.all(a).then((function(t){return Ir(t,Tt)}))]}))}))})),X("plugins",(function(){var a=[];if(navigator.plugins)for(var e=0;e<navigator.plugins.length;e++){var t=navigator.plugins[e];a.push([t.name,t.filename,t.description].join("|"))}return new Promise((function(n){n({plugins:a})}))})),X("screen",(function(){return new Promise((function(a){a({is_touchscreen:navigator.maxTouchPoints>0,maxTouchPoints:navigator.maxTouchPoints,colorDepth:screen.colorDepth,mediaMatches:Mr()})}))})),X("system",(function(){return new Promise((function(a){var e=He();a({platform:window.navigator.platform,cookieEnabled:window.navigator.cookieEnabled,productSub:navigator.productSub,product:navigator.product,useragent:navigator.userAgent,hardwareConcurrency:navigator.hardwareConcurrency,browser:{name:e.name,version:e.version},applePayVersion:Tr()})}))}));var L,Cr=He().name!=="SamsungBrowser"?1:3,g=null;X("webgl",(function(){return ee(this,void 0,void 0,(function(){var a;return te(this,(function(e){typeof document<"u"&&((L=document.createElement("canvas")).width=200,L.height=100,g=L.getContext("webgl"));try{if(!g)throw new Error("WebGL not supported");return a=Array.from({length:Cr},(function(){return(function(){try{if(!g)throw new Error("WebGL not supported");var t=`
502
502
  attribute vec2 position;
503
503
  void main() {
504
504
  gl_Position = vec4(position, 0.0, 1.0);
@@ -508,5 +508,5 @@ ${this.stack}`}}class ne extends M{constructor(e="The molecule does not contain
508
508
  void main() {
509
509
  gl_FragColor = vec4(0.812, 0.195, 0.553, 0.921); // Set line color
510
510
  }
511
- `,s=g.createShader(g.VERTEX_SHADER),r=g.createShader(g.FRAGMENT_SHADER);if(!s||!r)throw new Error("Failed to create shaders");if(g.shaderSource(s,t),g.shaderSource(r,n),g.compileShader(s),!g.getShaderParameter(s,g.COMPILE_STATUS))throw new Error("Vertex shader compilation failed: "+g.getShaderInfoLog(s));if(g.compileShader(r),!g.getShaderParameter(r,g.COMPILE_STATUS))throw new Error("Fragment shader compilation failed: "+g.getShaderInfoLog(r));var i=g.createProgram();if(!i)throw new Error("Failed to create shader program");if(g.attachShader(i,s),g.attachShader(i,r),g.linkProgram(i),!g.getProgramParameter(i,g.LINK_STATUS))throw new Error("Shader program linking failed: "+g.getProgramInfoLog(i));g.useProgram(i);for(var o=137,c=new Float32Array(4*o),u=2*Math.PI/o,l=0;l<o;l++){var d=l*u;c[4*l]=0,c[4*l+1]=0,c[4*l+2]=Math.cos(d)*(L.width/2),c[4*l+3]=Math.sin(d)*(L.height/2)}var f=g.createBuffer();g.bindBuffer(g.ARRAY_BUFFER,f),g.bufferData(g.ARRAY_BUFFER,c,g.STATIC_DRAW);var p=g.getAttribLocation(i,"position");g.enableVertexAttribArray(p),g.vertexAttribPointer(p,2,g.FLOAT,!1,0,0),g.viewport(0,0,L.width,L.height),g.clearColor(0,0,0,1),g.clear(g.COLOR_BUFFER_BIT),g.drawArrays(g.LINES,0,2*o);var w=new Uint8ClampedArray(L.width*L.height*4);return g.readPixels(0,0,L.width,L.height,g.RGBA,g.UNSIGNED_BYTE,w),new ImageData(w,L.width,L.height)}catch{return new ImageData(1,1)}finally{g&&(g.bindBuffer(g.ARRAY_BUFFER,null),g.useProgram(null),g.viewport(0,0,g.drawingBufferWidth,g.drawingBufferHeight),g.clearColor(0,0,0,0))}})()})),[2,{commonImageHash:wt(rs(a,L.width,L.height).data.toString()).toString()}]}catch{return[2,{webgl:"unsupported"}]}return[2]}))}))}));var pe=function(a,e,t,n){for(var s=(t-e)/n,r=0,i=0;i<n;i++)r+=a(e+(i+.5)*s);return r*s};G("math",(function(){return Y(void 0,void 0,void 0,(function(){return ee(this,(function(a){return[2,{acos:Math.acos(.5),asin:pe(Math.asin,-1,1,97),atan:pe(Math.atan,-1,1,97),cos:pe(Math.cos,0,Math.PI,97),cosh:Math.cosh(1.2857142857142858),e:Math.E,largeCos:Math.cos(1e20),largeSin:Math.sin(1e20),largeTan:Math.tan(1e20),log:Math.log(1e3),pi:Math.PI,sin:pe(Math.sin,-Math.PI,Math.PI,97),sinh:pe(Math.sinh,-1.2857142857142858,.7777777777777778,97),sqrt:Math.sqrt(2),tan:pe(Math.tan,0,2*Math.PI,97),tanh:pe(Math.tanh,-1.2857142857142858,.7777777777777778,97)}]}))}))}));const mr="query ( $Hash: String! ) { CipherHash ( Hash: $Hash ) { hash } }";function yr(a){const e=(a||"").match(/\b(query|mutation|subscription)\b/i),t=e?e[1].toLowerCase():"query",n=(a||"").indexOf("{"),s=n>=0?a.slice(n+1).match(/[A-Za-z_][A-Za-z0-9_]*/):null;return{type:t,name:s?s[0]:""}}class gr{constructor({serverUri:e,socket:t=null,encrypt:n=!1}){this.$__client=this.createUrqlClient({serverUri:e,socket:t,encrypt:n}),this.$__authToken="",this.$__pubkey=null,this.$__wallet=null,this.serverUri=e,this.soketi=t,this.cipherLink=!!n,this.$__subscriptionManager=new Map}createUrqlClient({serverUri:e,socket:t,encrypt:n}){const s=[T.cacheExchange,T.fetchExchange];if(t&&t.socketUri){const r=ls.createClient({url:t.socketUri,connectionParams:()=>({authToken:this.$__authToken})});s.push(T.subscriptionExchange({forwardSubscription:i=>({subscribe:o=>({unsubscribe:r.subscribe(i,o)})})}))}return T.createClient({url:e,exchanges:s,...n?{fetch:(r,i)=>this.cipherFetch(r,i)}:{},fetchOptions:()=>({headers:{"X-Auth-Token":this.$__authToken},signal:AbortSignal.timeout(6e4)})})}shouldEncrypt(e){let t;try{t=JSON.parse(e)}catch{return!1}const{type:n,name:s}=yr(t.query);return!(n==="query"&&(s==="__schema"||s==="ContinuId")||n==="mutation"&&s==="AccessToken"||n==="mutation"&&s==="ProposeMolecule"&&(t.variables&&t.variables.molecule&&t.variables.molecule.atoms&&t.variables.molecule.atoms[0]&&t.variables.molecule.atoms[0].isotope)==="U")}async cipherFetch(e,t){const n=this.getWallet(),s=this.getPubKey();let r=!1,i=t;if(n&&s&&t&&typeof t.body=="string"&&this.shouldEncrypt(t.body)){const p=await n.encryptStringML768(t.body,s);i={...t,body:JSON.stringify({query:mr,variables:{Hash:p}})},r=!0}const o=await fetch(e,i);if(!r)return o;const c=await o.text(),u={status:o.status,statusText:o.statusText,headers:o.headers};let l;try{l=JSON.parse(c)}catch{return new Response(c,u)}const d=l&&l.data&&l.data.CipherHash&&l.data.CipherHash.hash;if(typeof d!="string")return new Response(c,u);const f=await n.decryptMyMessageML768(JSON.parse(d));return new Response(f??c,u)}setAuthData({token:e,pubkey:t,wallet:n}){this.$__authToken=e,this.$__pubkey=t,this.$__wallet=n,this.$__client=this.createUrqlClient({serverUri:this.serverUri,socket:this.soketi,encrypt:!!this.cipherLink})}buildRequestOptions(e){if(!e)return;const t={};e.requestPolicy&&(t.requestPolicy=e.requestPolicy);const n=e.fetchOptions&&e.fetchOptions.signal;if(n){const s=typeof AbortSignal<"u"&&typeof AbortSignal.any=="function"?AbortSignal.any([n,AbortSignal.timeout(6e4)]):n;t.fetchOptions={headers:{"X-Auth-Token":this.$__authToken},signal:s}}return Object.keys(t).length?t:void 0}async query(e){const{query:t,variables:n,context:s}=e,r=this.buildRequestOptions(s),i=await this.$__client.query(t,n||{},r).toPromise();return this.formatResponse(i)}async mutate(e){const{mutation:t,variables:n,context:s}=e,r=this.buildRequestOptions(s),i=await this.$__client.mutation(t,n||{},r).toPromise();return this.formatResponse(i)}subscribe(e,t){const{query:n,variables:s,operationName:r}=e,i=Ze.pipe(this.$__client.subscription(n,s),Ze.map(o=>{t(this.formatResponse(o))}),Ze.subscribe(()=>{}));return this.$__subscriptionManager.set(r,i),{unsubscribe:()=>this.unsubscribe(r)}}formatResponse(e){return{data:e.data,errors:e.error?[e.error]:void 0}}socketDisconnect(){this.soketi&&this.unsubscribeAll()}unsubscribe(e){const t=this.$__subscriptionManager.get(e);t&&(t.unsubscribe(),this.$__subscriptionManager.delete(e))}unsubscribeAll(){this.$__subscriptionManager.forEach((e,t)=>{this.unsubscribe(t)})}unsubscribeFromChannel(e){this.unsubscribe(e)}setEncryption(e=!1){this.cipherLink=e,this.$__client=this.createUrqlClient({serverUri:this.serverUri,socket:this.soketi,encrypt:e})}getAuthToken(){return this.$__authToken}getPubKey(){return this.$__pubkey}getWallet(){return this.$__wallet}getServerUri(){return this.serverUri}getSocketUri(){return this.soketi?this.soketi.socketUri:null}getUri(){return this.serverUri}setUri(e){this.serverUri=e,this.$__client=this.createUrqlClient({serverUri:e,socket:this.soketi,encrypt:!!this.cipherLink})}setSocketUri({socketUri:e,appKey:t}){this.soketi={socketUri:e,appKey:t},this.$__client=this.createUrqlClient({serverUri:this.serverUri,socket:this.soketi,encrypt:!!this.cipherLink})}}class br{constructor({uri:e,cellSlug:t=null,client:n=null,socket:s=null,serverSdkVersion:r=3,logging:i=!1,defaultRequestPolicy:o=null}){this.initialize({uri:e,cellSlug:t,socket:s,client:n,serverSdkVersion:r,logging:i,defaultRequestPolicy:o})}initialize({uri:e,cellSlug:t=null,socket:n=null,client:s=null,serverSdkVersion:r=3,logging:i=!1,defaultRequestPolicy:o=null}){this.reset(),this.$__logging=i,this.$__defaultRequestPolicy=o,this.$__authTokenObjects={},this.$__authInProcess=!1,this.abortControllers=new Map,this.setUri(e),t&&this.setCellSlug(t);for(const c in this.$__uris){const u=this.$__uris[c];this.$__authTokenObjects[u]=null}this.log("info",`KnishIOClient::initialize() - Initializing new Knish.IO client session for SDK version ${r}...`),this.$__client=s||new gr({socket:{socketUri:null,appKey:"knishio",...n||{}},serverUri:this.getRandomUri()}),this.$__serverSdkVersion=r}getRandomUri(){const e=Math.floor(Math.random()*this.$__uris.length);return this.$__uris[e]}switchEncryption(e){return this.$__encrypt===e?!1:(this.log("info",`KnishIOClient::switchEncryption() - Forcing encryption ${e?"on":"off"} to match node...`),this.$__encrypt=e,this.$__client.setEncryption(e),!0)}deinitialize(){this.log("info","KnishIOClient::deinitialize() - Clearing the Knish.IO client session..."),this.reset()}subscribe(){if(!this.client().getSocketUri())throw new Z("KnishIOClient::subscribe() - Socket client not initialized!");return this.client()}getServerSdkVersion(){return this.$__serverSdkVersion}getDefaultRequestPolicy(){return this.$__defaultRequestPolicy||null}setDefaultRequestPolicy(e){this.$__defaultRequestPolicy=e}reset(){this.$__secret="",this.$__bundle="",this.remainderWallet=null,this.$__capabilityCache={},this.$__defaultRequestPolicy=null}getCellSlug(){return this.$__cellSlug||null}setCellSlug(e){this.$__cellSlug=e}setUri(e){if(this.$__uris=typeof e=="object"?e:[e],this.$__client){const t=this.getRandomUri();this.$__client.setUri(t)}}setSocketUri(e){this.$__client&&typeof this.$__client.setSocketUri=="function"&&this.$__client.setSocketUri({socketUri:e,appKey:"knishio"})}getUri(){return this.$__client.getUri()}client(){if(!this.$__authInProcess){const e=this.getRandomUri();this.$__client.setUri(e);const t=this.$__authTokenObjects[e];t?this.$__client.setAuthData(t.getAuthData()):this.requestAuthToken({secret:this.$__secret,cellSlug:this.$__cellSlug,encrypt:this.$__encrypt}).catch(n=>{this.log("warn",`KnishIOClient::client() - Background authorization failed: ${n.message}`)})}return this.$__client}hasSecret(){return!!this.$__secret}setSecret(e){this.$__secret=e,this.$__bundle=this.hashSecret(e,"setSecret")}hashSecret(e,t=null){return this.log("info",`KnishIOClient::hashSecret(${t?`source: ${t}`:""}) - Computing wallet bundle from secret...`),oe(e)}getSecret(){if(!this.hasSecret())throw new Re("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 Re("KnishIOClient::getBundle() - Unable to find a stored bundle! Have you set a secret?");return this.$__bundle}getFingerprint(){return sr()}getFingerprintData(){return ns()}async getSourceWallet(){let e=(await this.queryContinuId({bundle:this.getBundle()})).payload();return e?e.key=_.generateKey({secret:this.getSecret(),token:e.token,position:e.position}):e=new _({secret:this.getSecret()}),e}getRemainderWallet(){return this.remainderWallet}async createMolecule({secret:e=null,bundle:t=null,sourceWallet:n=null,remainderWallet:s=null}){this.log("info","KnishIOClient::createMolecule() - Creating a new molecule..."),e=e||this.getSecret(),t=t||this.getBundle();let r=null;if(n&&n.token!=="USER")if(this.lastMoleculeQuery&&this.getRemainderWallet()&&this.getRemainderWallet().token==="USER"&&this.lastMoleculeQuery.response()&&this.lastMoleculeQuery.response().success())r=this.getRemainderWallet().position;else{const i=await this.getSourceWallet();r=i?i.position:null}return!n&&this.lastMoleculeQuery&&this.getRemainderWallet().token==="USER"&&this.lastMoleculeQuery.response()&&this.lastMoleculeQuery.response().success()&&(n=this.getRemainderWallet()),n===null&&(n=await this.getSourceWallet()),this.remainderWallet=s||_.create({secret:e,bundle:t,token:"USER",batchId:n.batchId,characters:n.characters}),new V({secret:e,sourceWallet:n,remainderWallet:this.getRemainderWallet(),cellSlug:this.getCellSlug(),version:this.getServerSdkVersion(),continuIdPosition:r})}createQuery(e){return new e(this.client(),this)}createSubscribe(e){return new e(this.subscribe())}async createMoleculeMutation({mutationClass:e,molecule:t=null}){this.log("info",`KnishIOClient::createMoleculeQuery() - Creating a new ${e.name} query...`);const n=t||await this.createMolecule({}),s=new e(this.client(),this,n);if(!(s instanceof O))throw new Z(`${this.constructor.name}::createMoleculeMutation() - This method only accepts MutationProposeMolecule!`);return this.lastMoleculeQuery=s,s}async executeQuery(e,t=null,n={}){this.$__authToken&&this.$__authToken.isExpired()&&!this.$__authInProcess&&(this.log("info","KnishIOClient::executeQuery() - Access token is expired. Getting new one..."),await this.requestAuthToken({secret:this.$__secret,cellSlug:this.$__cellSlug,encrypt:this.$__encrypt}));const s=new AbortController,r=JSON.stringify({query:e.$__query,variables:t});this.abortControllers.set(r,s);try{const i={...n};this.$__defaultRequestPolicy&&!i.requestPolicy&&(i.requestPolicy=this.$__defaultRequestPolicy);const o=await e.execute({variables:t,context:{fetchOptions:{signal:s.signal},...i}});return this.abortControllers.delete(r),o}catch(i){if(i.name==="AbortError")this.log("warn","Query was cancelled");else throw i}}cancelQuery(e,t=null){const n=JSON.stringify({query:e.$__query,variables:t}),s=this.abortControllers.get(n);s&&(s.abort(),this.abortControllers.delete(n))}cancelAllQueries(){for(const e of this.abortControllers.values())e.abort();this.abortControllers.clear()}async queryBalance({token:e,bundle:t=null,type:n="regular"}){const s=this.createQuery(fn);return this.executeQuery(s,{bundleHash:t||this.getBundle(),token:e,type:n})}async querySourceWallet({token:e,amount:t,type:n="regular"}){const s=(await this.queryBalance({token:e,type:n})).payload();if(s===null||re.cmp(s.balance,t)<0)throw new J;if(!s.position||!s.address)throw new J("Source wallet can not be a shadow wallet.");return s}async subscribeCreateMolecule({bundle:e,closure:t}){return await this.createSubscribe(Vs).execute({variables:{bundle:e||this.getBundle()},closure:t})}subscribeWalletStatus({bundle:e,token:t,closure:n}){if(!t)throw new Z(`${this.constructor.name}::subscribeWalletStatus() - Token parameter is required!`);return this.createSubscribe(zs).execute({variables:{bundle:e||this.getBundle(),token:t},closure:n})}subscribeActiveWallet({bundle:e,closure:t}){return this.createSubscribe(Js).execute({variables:{bundle:e||this.getBundle()},closure:t})}subscribeActiveSession({metaType:e,metaId:t,closure:n}){return this.createSubscribe(Gs).execute({variables:{metaType:e,metaId:t},closure:n})}unsubscribe(e){this.subscribe().unsubscribe(e)}unsubscribeAll(){this.subscribe().unsubscribeAll()}queryMeta({metaType:e,metaId:t=null,key:n=null,value:s=null,latest:r=!0,fields:i=null,filter:o=null,queryArgs:c=null,count:u=null,countBy:l=null,throughAtom:d=!0,throughMolecule:f=!1,values:p=null,keys:w=null,atomValues:v=null,requestPolicy:q=null}){this.log("info",`KnishIOClient::queryMeta() - Querying metaType: ${e}, metaId: ${t}...`);let m,y;return f?(m=this.createQuery(gt),y=gt.createVariables({metaType:e,metaId:t,key:n,value:s,latest:r,filter:o,queryArgs:c,countBy:l,values:p,keys:w,atomValues:v,cellSlug:this.getCellSlug()})):d?(m=this.createQuery(yt),y=yt.createVariables({metaType:e,metaId:t,key:n,value:s,latest:r,filter:o,queryArgs:c,countBy:l,values:p,keys:w,atomValues:v,cellSlug:this.getCellSlug()})):(m=this.createQuery(ht),y=ht.createVariables({metaType:e,metaId:t,key:n,value:s,latest:r,filter:o,queryArgs:c,count:u,countBy:l,cellSlug:this.getCellSlug()})),this.executeQuery(m,y,q?{requestPolicy:q}:{})}async queryMetaVerified(e){const t=await this.queryMeta(e),n=t.payload();return n&&(n.integrity=t.verifyIntegrity()),t}async hasQueryField(e){const n=`${this.getUri()}::${e}`;if(typeof this.$__capabilityCache[n]=="boolean")return this.$__capabilityCache[n];try{const i=((await this.$__client.query({query:"{ __schema { queryType { fields { name } } } }",variables:{}}))?.data?.__schema?.queryType?.fields||[]).some(o=>o.name===e);return this.$__capabilityCache[n]=i,i}catch(s){return this.log("warn",`KnishIOClient::hasQueryField() - Capability probe for '${e}' failed: ${s.message}`),this.$__capabilityCache[n]=!1,!1}}async queryEmbeddingStatus({metaType:e=null,metaId:t=null,instances:n=null}){if(this.log("info",`KnishIOClient::queryEmbeddingStatus() - Checking embedding status for metaType: ${e||"(bulk)"}...`),!await this.hasQueryField("embeddingStatus"))return this.log("warn","KnishIOClient::queryEmbeddingStatus() - Server does not support embeddingStatus query. Returning null."),null;const r=this.createQuery(bt),i=bt.createVariables({metaType:e,metaId:t,instances:n});return this.executeQuery(r,i)}async queryBatch({batchId:e}){this.log("info",`KnishIOClient::queryBatch() - Querying cascading meta instances for batchId: ${e}...`);const t=this.createQuery(we);return await this.executeQuery(t,{batchId:e})}async queryBatchHistory({batchId:e}){this.log("info",`KnishIOClient::queryBatchHistory() - Querying cascading meta instances for batchId: ${e}...`);const t=this.createQuery(yn);return await this.executeQuery(t,{batchId:e})}async queryAtom({molecularHashes:e,molecularHash:t,bundleHashes:n,bundleHash:s,positions:r,position:i,walletAddresses:o,walletAddress:c,isotopes:u,isotope:l,tokenSlugs:d,tokenSlug:f,cellSlugs:p,cellSlug:w,batchIds:v,batchId:q,values:m,value:y,metaTypes:k,metaType:R,metaIds:S,metaId:A,indexes:I,index:x,filter:$,latest:N,queryArgs:U={limit:15,offset:1}}){this.log("info","KnishIOClient::queryAtom() - Querying atom instances");const _e=this.createQuery(mt);return await this.executeQuery(_e,mt.createVariables({molecularHashes:e,molecularHash:t,bundleHashes:n,bundleHash:s,positions:r,position:i,walletAddresses:o,walletAddress:c,isotopes:u,isotope:l,tokenSlugs:d,tokenSlug:f,cellSlugs:p,cellSlug:w,batchIds:v,batchId:q,values:m,value:y,metaTypes:k,metaType:R,metaIds:S,metaId:A,indexes:I,index:x,filter:$,latest:N,queryArgs:U}))}async createWallet({token:e}){const t=new _({secret:this.getSecret(),token:e}),n=await this.createMoleculeMutation({mutationClass:Bn});return n.fillMolecule(t),await this.executeQuery(n)}async queryActiveSession({bundleHash:e,metaType:t,metaId:n}){const s=this.createQuery(Fn);return await this.executeQuery(s,{bundleHash:e,metaType:t,metaId:n})}async activeSession({bundle:e,metaType:t,metaId:n,ipAddress:s,browser:r,osCpu:i,resolution:o,timeZone:c,json:u={}}){const l=this.createQuery(Ln);return await this.executeQuery(l,{bundleHash:e,metaType:t,metaId:n,ipAddress:s,browser:r,osCpu:i,resolution:o,timeZone:c,json:JSON.stringify(u)})}async createToken({token:e,amount:t=null,meta:n=null,batchId:s=null,units:r=[]}){const i=C.get(n||{},"fungibility");if(i==="stackable"&&(n.batchId=s||$e({})),["nonfungible","stackable"].includes(i)&&r.length>0){if(C.get(n||{},"decimals")>0)throw new Kn;if(t>0)throw new ke;t=r.length,n.splittable=1,n.decimals=0,n.tokenUnits=JSON.stringify(r)}const o=new _({secret:this.getSecret(),bundle:this.getBundle(),token:e,batchId:s}),c=await this.createMoleculeMutation({mutationClass:kn});return c.fillMolecule({recipientWallet:o,amount:t,meta:n||{}}),await this.executeQuery(c)}async createRule({metaType:e,metaId:t,rule:n,policy:s={}}){const r=await this.createMoleculeMutation({mutationClass:Zn,molecule:await this.createMolecule({secret:this.getSecret()})});return r.fillMolecule({metaType:e,metaId:t,rule:n,policy:s}),await this.executeQuery(r)}async createMeta({metaType:e,metaId:t,meta:n=null,policy:s={}}){const r=await this.createMoleculeMutation({mutationClass:Cn,molecule:await this.createMolecule({secret:this.getSecret()})}),i=n||{};return r.fillMolecule({metaType:e,metaId:t,meta:i,policy:s}),await this.executeQuery(r)}async registerPeer({host:e}){const t=await this.createMoleculeMutation({mutationClass:En,molecule:await this.createMolecule({secret:this.getSecret()})});return t.fillMolecule({host:e}),await this.executeQuery(t)}async appendRequest({metaType:e,metaId:t,action:n,meta:s={}}){const r=await this.createMoleculeMutation({mutationClass:qn,molecule:await this.createMolecule({secret:this.getSecret()})});return r.fillMolecule({metaType:e,metaId:t,action:n,meta:s}),await this.executeQuery(r)}async createIdentifier({type:e,contact:t,code:n}){const s=await this.createMoleculeMutation({mutationClass:vn});return s.fillMolecule({type:e,contact:t,code:n}),await this.executeQuery(s)}async linkIdentifier({type:e,contact:t}){const n=this.createQuery(Wn);return await this.executeQuery(n,{bundle:this.getBundle(),type:e,content:t})}async createPolicy({metaType:e,metaId:t,policy:n={}}){const s=await this.createMolecule({});s.addPolicyAtom({metaType:e,metaId:t,meta:{},policy:n}),s.addContinuIdAtom(),s.sign({bundle:this.getBundle()}),s.check();const r=await this.createMoleculeMutation({mutationClass:O,molecule:s});return await this.executeQuery(r)}async queryPolicy({metaType:e,metaId:t}){const n=this.createQuery(zn);return await this.executeQuery(n,{metaType:e,metaId:t})}queryWallets({bundle:e=null,token:t=null,unspent:n=!0}){this.log("info",`KnishIOClient::queryWallets() - Querying wallets${e?` for ${e}`:""}...`);const s=this.createQuery(dn);return this.executeQuery(s,{bundleHash:e||this.getBundle(),token:t,unspent:n}).then(r=>r.payload())}queryBundle({bundle:e=null,fields:t=null,raw:n=!1}){this.log("info",`KnishIOClient::queryBundle() - Querying wallet bundle metadata${e?` for ${e}`:""}...`),e||(e=this.getBundle()),typeof e=="string"&&(e=[e]);const s=this.createQuery(hn);return this.executeQuery(s,{bundleHashes:e}).then(r=>n?r:r.payload())}async queryContinuId({bundle:e}){const t=this.createQuery(cn);return this.executeQuery(t,{bundle:e})}async requestTokens({token:e,to:t,amount:n=null,units:s=[],meta:r=null,batchId:i=null}){let o,c;r=r||{};const u=this.createQuery(jn),l=await this.executeQuery(u,{slug:e}),d=C.get(l.data(),"0.fungibility")==="stackable";if(!d&&i!==null)throw new Ce("Expected Batch ID = null for non-stackable tokens.");if(d&&i===null&&(i=$e({})),s.length>0){if(n>0)throw new ke;n=s.length,r.tokenUnits=JSON.stringify(s)}t?(Object.prototype.toString.call(t)==="[object String]"&&(_.isBundleHash(t)?(o="walletBundle",c=t):t=_.create({secret:t,token:e})),t instanceof _&&(o="wallet",r.position=t.position,r.bundle=t.bundle,c=t.address)):(o="walletBundle",c=this.getBundle());const f=await this.createMoleculeMutation({mutationClass:Sn});return f.fillMolecule({token:e,amount:n,metaType:o,metaId:c,meta:r,batchId:i}),await this.executeQuery(f)}async claimShadowWallet({token:e,batchId:t=null,molecule:n=null}){const s=await this.createMoleculeMutation({mutationClass:Mn,molecule:n});return s.fillMolecule({token:e,batchId:t}),await this.executeQuery(s)}async claimShadowWallets({token:e}){const t=await this.queryWallets({token:e});if(!t||!Array.isArray(t))throw new pt;t.forEach(s=>{if(!s.isShadow())throw new pt});const n=[];for(const s of t)n.push(await this.claimShadowWallet({token:e,batchId:s.batchId}));return n}async transferToken({bundleHash:e,token:t,amount:n=null,units:s=[],batchId:r=null,sourceWallet:i=null}){if(s.length>0){if(n>0)throw new ke;n=s.length}if(i===null&&(i=await this.querySourceWallet({token:t,amount:n})),i===null||re.cmp(i.balance,n)<0)throw new J;const o=_.create({bundle:e,token:t});r!==null?o.batchId=r:o.initBatchId({sourceWallet:i});const c=i.createRemainder(this.getSecret());i.splitUnits(s,c,o);const u=await this.createMolecule({sourceWallet:i,remainderWallet:c}),l=await this.createMoleculeMutation({mutationClass:dt,molecule:u});return l.fillMolecule({recipientWallet:o,amount:n}),await this.executeQuery(l)}async transferTokens({token:e,recipients:t,sourceWallet:n=null}){const s=t.map(l=>{const d=l.units||[];if(d.length>0){if(l.amount>0)throw new ke;return d.length}return l.amount||0}),r=s.reduce((l,d)=>l+d,0);if(n===null&&(n=await this.querySourceWallet({token:e,amount:r})),n===null||re.cmp(n.balance,r)<0)throw new J;const i=t.map(l=>{const d=_.create({bundle:l.bundleHash,token:e});return l.batchId!==void 0&&l.batchId!==null?d.batchId=l.batchId:d.initBatchId({sourceWallet:n}),d}),o=n.createRemainder(this.getSecret());n.splitUnitsMulti(t.map(l=>l.units||[]),i,o);const c=await this.createMolecule({sourceWallet:n,remainderWallet:o}),u=await this.createMoleculeMutation({mutationClass:dt,molecule:c});return u.fillMoleculeMulti({recipientWallets:i,amounts:s}),await this.executeQuery(u)}async depositBufferToken({tokenSlug:e,amount:t,tradeRates:n,sourceWallet:s=null}){s===null&&(s=await this.querySourceWallet({token:e,amount:t}));const r=s.createRemainder(this.getSecret()),i=await this.createMolecule({sourceWallet:s,remainderWallet:r}),o=await this.createMoleculeMutation({mutationClass:Yn,molecule:i});return o.fillMolecule({amount:t,tradeRates:n}),await this.executeQuery(o)}async withdrawBufferToken({tokenSlug:e,amount:t,sourceWallet:n=null,signingWallet:s=null}){n===null&&(n=await this.querySourceWallet({token:e,amount:t,type:"buffer"}));const r=n,i=await this.createMolecule({sourceWallet:n,remainderWallet:r}),o=await this.createMoleculeMutation({mutationClass:es,molecule:i}),c={};return c[this.getBundle()]=t,o.fillMolecule({recipients:c,signingWallet:s}),await this.executeQuery(o)}async burnTokens({token:e,amount:t=null,units:n=[],sourceWallet:s=null}){s===null&&(s=await this.querySourceWallet({token:e,amount:t}));const r=s.createRemainder(this.getSecret());if(n.length>0){if(t>0)throw new ke;t=n.length,s.splitUnits(n,r)}const i=await this.createMolecule({sourceWallet:s,remainderWallet:r});i.burnToken({amount:t}),i.sign({bundle:this.getBundle()}),i.check(s);const o=await this.createMoleculeMutation({mutationClass:O,molecule:i});return this.executeQuery(o)}async replenishToken({token:e,amount:t=null,units:n=[],sourceWallet:s=null}){if(s===null&&(s=(await this.queryBalance({token:e})).payload()),!s)throw new J("Source wallet is missing or invalid.");const r=s.createRemainder(this.getSecret()),i=await this.createMolecule({sourceWallet:s,remainderWallet:r});i.replenishToken({amount:t,units:n}),i.sign({bundle:this.getBundle()}),i.check();const o=await this.createMoleculeMutation({mutationClass:O,molecule:i});return this.executeQuery(o)}async fuseToken({bundleHash:e,tokenSlug:t,newTokenUnit:n,fusedTokenUnitIds:s,sourceWallet:r=null}){if(r===null&&(r=(await this.queryBalance({token:t})).payload()),r===null)throw new J("Source wallet is missing or invalid.");if(!r.tokenUnits||!r.tokenUnits.length)throw new J("Source wallet does not have token units.");if(!s.length)throw new J("Fused token unit list is empty.");const i=[];r.tokenUnits.forEach(d=>{i.push(d.id)}),s.forEach(d=>{if(!i.includes(d))throw new J(`Fused token unit ID = ${d} does not found in the source wallet.`)});const o=_.create({bundle:e,token:t});o.initBatchId({sourceWallet:r});const c=r.createRemainder(this.getSecret());r.splitUnits(s,c),typeof n=="string"&&(n=new le(n,n,{})),n.metas.fusedTokenUnits=r.getTokenUnitsData(),o.tokenUnits=[n];const u=await this.createMolecule({sourceWallet:r,remainderWallet:c});u.fuseToken(r.tokenUnits,o),u.sign({bundle:this.getBundle()}),u.check();const l=await this.createMoleculeMutation({mutationClass:O,molecule:u});return this.executeQuery(l)}async requestGuestAuthToken({cellSlug:e,encrypt:t}){this.setCellSlug(e);const n=new _({secret:Ke(await this.getFingerprint()),token:"AUTH"}),s=await this.createQuery(Hn),r={cellSlug:e,pubkey:n.pubkey,encrypt:t},i=await s.execute({variables:r});if(i.success()){const o=be.create({token:i.token(),expiresAt:i.expiresAt(),pubkey:i.pubKey(),encrypt:i.encrypt()},n);this.setAuthToken(o)}else throw new ft(`KnishIOClient::requestGuestAuthToken() - Authorization attempt rejected by ledger. Reason: ${i.reason()}`);return i}async requestProfileAuthToken({secret:e,encrypt:t}){this.setSecret(e);const n=new _({secret:e,token:"AUTH"}),s=await this.createMolecule({secret:e,sourceWallet:n}),r=await this.createMoleculeMutation({mutationClass:bn,molecule:s}),i={encrypt:t?"true":"false"};n.pubkey&&(i.walletPubkey=n.pubkey),r.fillMolecule({meta:i});const o=await r.execute({});if(o.success()){const c=be.create({token:o.token(),expiresAt:o.expiresAt(),pubkey:o.pubKey(),encrypt:o.encrypt()},n);this.setAuthToken(c)}else throw new ft(`KnishIOClient::requestProfileAuthToken() - Authorization attempt rejected by ledger. Reason: ${o.reason()}`);return o}async requestAuthToken({secret:e=null,seed:t=null,cellSlug:n=null,encrypt:s=!1}){if(this.$__serverSdkVersion<3)return this.log("warn","KnishIOClient::authorize() - Server SDK version does not require an authorization..."),null;e===null&&t&&(e=Ke(t)),n&&this.setCellSlug(n),this.$__authInProcess=!0;let r;return e?r=await this.requestProfileAuthToken({secret:e,encrypt:s}):r=await this.requestGuestAuthToken({cellSlug:n,encrypt:s}),this.log("info",`KnishIOClient::authorize() - Successfully retrieved auth token ${this.$__authToken.getToken()}...`),this.switchEncryption(s),this.$__authInProcess=!1,r}setAuthToken(e){if(!e){this.log("info","KnishIOClient::setAuthToken() - authToken object is empty.");return}this.$__authTokenObjects[this.getUri()]=e,this.client().setAuthData(e.getAuthData()),this.$__authToken=e}getAuthToken(){return this.$__authToken}log(e,t){if(this.$__logging)switch(e){case"info":console.info(t);break;case"warn":console.warn(t);break;case"error":console.error(t);break;default:console.log(t)}}}class wr extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.AccessToken"})}reason(){return"Invalid response from server"}success(){return this.payload()!==null}payload(){return this.data()}payloadKey(e){if(!C.has(this.payload(),e))throw new te(`ResponseAuthorizationGuest::payloadKey() - '${e}' key is not found in the payload!`);return C.get(this.payload(),e)}token(){return this.payloadKey("token")}time(){return this.payloadKey("time")}}return h.Atom=b,h.AtomIndexException=me,h.AtomMeta=B,h.AtomsMissingException=ne,h.AuthToken=be,h.AuthorizationRejectedException=ft,h.BalanceInsufficientException=de,h.BatchIdException=Ce,h.CheckMolecule=ge,h.CodeException=Z,h.Decimal=re,h.Dot=C,h.InvalidResponseException=te,h.KnishIOClient=br,h.Meta=ie,h.MetaMissingException=P,h.MolecularHashMismatchException=nn,h.MolecularHashMissingException=sn,h.Molecule=V,h.Mutation=Oe,h.MutationActiveSession=Ln,h.MutationAppendRequest=qn,h.MutationClaimShadowWallet=Mn,h.MutationCreateIdentifier=vn,h.MutationCreateMeta=Cn,h.MutationCreateRule=Zn,h.MutationCreateToken=kn,h.MutationCreateWallet=Bn,h.MutationDepositBufferToken=Yn,h.MutationLinkIdentifier=Wn,h.MutationPeering=En,h.MutationProposeMolecule=O,h.MutationRequestAuthorization=bn,h.MutationRequestAuthorizationGuest=Hn,h.MutationRequestTokens=Sn,h.MutationTransferTokens=dt,h.MutationWithdrawBufferToken=es,h.NegativeAmountException=ct,h.PolicyInvalidException=rt,h.PolicyMeta=Pe,h.Query=H,h.QueryActiveSession=Fn,h.QueryAtom=mt,h.QueryBalance=fn,h.QueryBatch=we,h.QueryBatchHistory=yn,h.QueryContinuId=cn,h.QueryEmbeddingStatus=bt,h.QueryMetaType=ht,h.QueryMetaTypeViaAtom=yt,h.QueryMetaTypeViaMolecule=gt,h.QueryPolicy=zn,h.QueryToken=jn,h.QueryWalletBundle=hn,h.QueryWalletList=dn,h.Response=E,h.ResponseActiveSession=Nn,h.ResponseAppendRequest=Rn,h.ResponseAtom=Dn,h.ResponseAuthorizationGuest=wr,h.ResponseBalance=pn,h.ResponseClaimShadowWallet=In,h.ResponseContinuId=ln,h.ResponseCreateIdentifier=An,h.ResponseCreateMeta=Tn,h.ResponseCreateRule=Xn,h.ResponseCreateToken=wn,h.ResponseCreateWallet=Un,h.ResponseEmbeddingStatus=Gn,h.ResponseLinkIdentifier=On,h.ResponseMetaType=mn,h.ResponseMetaTypeViaAtom=Jn,h.ResponseMetaTypeViaMolecule=Je,h.ResponsePeering=xn,h.ResponsePolicy=Vn,h.ResponseProposeMolecule=j,h.ResponseQueryActiveSession=Qn,h.ResponseRequestAuthorization=gn,h.ResponseRequestAuthorizationGuest=Pn,h.ResponseRequestTokens=_n,h.ResponseTransferTokens=$n,h.ResponseWalletBundle=un,h.ResponseWalletList=qe,h.SignatureMalformedException=it,h.SignatureMismatchException=rn,h.StackableUnitAmountException=ke,h.StackableUnitDecimalsException=Kn,h.TokenUnit=le,h.TransferBalanceException=J,h.TransferMalformedException=ye,h.TransferMismatchedException=at,h.TransferRemainderException=ot,h.TransferToSelfException=an,h.TransferUnbalancedException=Te,h.UnauthenticatedException=Re,h.Wallet=_,h.WalletShadowException=pt,h.WrongTokenTypeException=se,h.base64ToHex=Mt,h.bufferToHexString=At,h.charsetBaseConvert=$t,h.chunkArray=Ct,h.chunkSubstr=Se,h.deepCloning=xt,h.diff=Et,h.generateBatchId=$e,h.generateBundleHash=oe,h.generateSecret=Ke,h.hexStringToBuffer=vt,h.hexToBase64=It,h.intersect=fe,h.isHex=Be,h.isNumeric=Tt,h.randomString=Ue,h.shake256=Ne,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"}),h})({},jsSHA,UrqlCore,GraphQLWS,wonka);
511
+ `,s=g.createShader(g.VERTEX_SHADER),r=g.createShader(g.FRAGMENT_SHADER);if(!s||!r)throw new Error("Failed to create shaders");if(g.shaderSource(s,t),g.shaderSource(r,n),g.compileShader(s),!g.getShaderParameter(s,g.COMPILE_STATUS))throw new Error("Vertex shader compilation failed: "+g.getShaderInfoLog(s));if(g.compileShader(r),!g.getShaderParameter(r,g.COMPILE_STATUS))throw new Error("Fragment shader compilation failed: "+g.getShaderInfoLog(r));var i=g.createProgram();if(!i)throw new Error("Failed to create shader program");if(g.attachShader(i,s),g.attachShader(i,r),g.linkProgram(i),!g.getProgramParameter(i,g.LINK_STATUS))throw new Error("Shader program linking failed: "+g.getProgramInfoLog(i));g.useProgram(i);for(var o=137,c=new Float32Array(4*o),u=2*Math.PI/o,l=0;l<o;l++){var d=l*u;c[4*l]=0,c[4*l+1]=0,c[4*l+2]=Math.cos(d)*(L.width/2),c[4*l+3]=Math.sin(d)*(L.height/2)}var f=g.createBuffer();g.bindBuffer(g.ARRAY_BUFFER,f),g.bufferData(g.ARRAY_BUFFER,c,g.STATIC_DRAW);var p=g.getAttribLocation(i,"position");g.enableVertexAttribArray(p),g.vertexAttribPointer(p,2,g.FLOAT,!1,0,0),g.viewport(0,0,L.width,L.height),g.clearColor(0,0,0,1),g.clear(g.COLOR_BUFFER_BIT),g.drawArrays(g.LINES,0,2*o);var w=new Uint8ClampedArray(L.width*L.height*4);return g.readPixels(0,0,L.width,L.height,g.RGBA,g.UNSIGNED_BYTE,w),new ImageData(w,L.width,L.height)}catch{return new ImageData(1,1)}finally{g&&(g.bindBuffer(g.ARRAY_BUFFER,null),g.useProgram(null),g.viewport(0,0,g.drawingBufferWidth,g.drawingBufferHeight),g.clearColor(0,0,0,0))}})()})),[2,{commonImageHash:Mt(ps(a,L.width,L.height).data.toString()).toString()}]}catch{return[2,{webgl:"unsupported"}]}return[2]}))}))}));var ye=function(a,e,t,n){for(var s=(t-e)/n,r=0,i=0;i<n;i++)r+=a(e+(i+.5)*s);return r*s};X("math",(function(){return ee(void 0,void 0,void 0,(function(){return te(this,(function(a){return[2,{acos:Math.acos(.5),asin:ye(Math.asin,-1,1,97),atan:ye(Math.atan,-1,1,97),cos:ye(Math.cos,0,Math.PI,97),cosh:Math.cosh(1.2857142857142858),e:Math.E,largeCos:Math.cos(1e20),largeSin:Math.sin(1e20),largeTan:Math.tan(1e20),log:Math.log(1e3),pi:Math.PI,sin:ye(Math.sin,-Math.PI,Math.PI,97),sinh:ye(Math.sinh,-1.2857142857142858,.7777777777777778,97),sqrt:Math.sqrt(2),tan:ye(Math.tan,0,2*Math.PI,97),tanh:ye(Math.tanh,-1.2857142857142858,.7777777777777778,97)}]}))}))}));const xr="query ( $Hash: String! ) { CipherHash ( Hash: $Hash ) { hash } }";function Er(a){const e=(a||"").match(/\b(query|mutation|subscription)\b/i),t=e?e[1].toLowerCase():"query",n=(a||"").indexOf("{"),s=n>=0?a.slice(n+1).match(/[A-Za-z_][A-Za-z0-9_]*/):null;return{type:t,name:s?s[0]:""}}class Rr{constructor({serverUri:e,socket:t=null,encrypt:n=!1}){this.$__client=this.createUrqlClient({serverUri:e,socket:t,encrypt:n}),this.$__authToken="",this.$__pubkey=null,this.$__wallet=null,this.serverUri=e,this.soketi=t,this.cipherLink=!!n,this.$__subscriptionManager=new Map}createUrqlClient({serverUri:e,socket:t,encrypt:n}){const s=[T.cacheExchange,T.fetchExchange];if(t&&t.socketUri){const r=Ss.createClient({url:t.socketUri,connectionParams:()=>({authToken:this.$__authToken})});s.push(T.subscriptionExchange({forwardSubscription:i=>({subscribe:o=>({unsubscribe:r.subscribe(i,o)})})}))}return T.createClient({url:e,exchanges:s,...n?{fetch:(r,i)=>this.cipherFetch(r,i)}:{},fetchOptions:()=>({headers:{"X-Auth-Token":this.$__authToken},signal:AbortSignal.timeout(6e4)})})}shouldEncrypt(e){let t;try{t=JSON.parse(e)}catch{return!1}const{type:n,name:s}=Er(t.query);return!(n==="query"&&(s==="__schema"||s==="ContinuId")||n==="mutation"&&s==="AccessToken"||n==="mutation"&&s==="ProposeMolecule"&&(t.variables&&t.variables.molecule&&t.variables.molecule.atoms&&t.variables.molecule.atoms[0]&&t.variables.molecule.atoms[0].isotope)==="U")}async cipherFetch(e,t){const n=this.getWallet(),s=this.getPubKey();let r=!1,i=t;if(n&&s&&t&&typeof t.body=="string"&&this.shouldEncrypt(t.body)){const p=await n.encryptStringML768(t.body,s);i={...t,body:JSON.stringify({query:xr,variables:{Hash:p}})},r=!0}const o=await fetch(e,i);if(!r)return o;const c=await o.text(),u={status:o.status,statusText:o.statusText,headers:o.headers};let l;try{l=JSON.parse(c)}catch{return new Response(c,u)}const d=l&&l.data&&l.data.CipherHash&&l.data.CipherHash.hash;if(typeof d!="string")return new Response(c,u);const f=await n.decryptMyMessageML768(JSON.parse(d));return new Response(f??c,u)}setAuthData({token:e,pubkey:t,wallet:n}){this.$__authToken=e,this.$__pubkey=t,this.$__wallet=n,this.$__client=this.createUrqlClient({serverUri:this.serverUri,socket:this.soketi,encrypt:!!this.cipherLink})}buildRequestOptions(e){if(!e)return;const t={};e.requestPolicy&&(t.requestPolicy=e.requestPolicy);const n=e.fetchOptions&&e.fetchOptions.signal;if(n){const s=typeof AbortSignal<"u"&&typeof AbortSignal.any=="function"?AbortSignal.any([n,AbortSignal.timeout(6e4)]):n;t.fetchOptions={headers:{"X-Auth-Token":this.$__authToken},signal:s}}return Object.keys(t).length?t:void 0}async query(e){const{query:t,variables:n,context:s}=e,r=this.buildRequestOptions(s),i=await this.$__client.query(t,n||{},r).toPromise();return this.formatResponse(i)}async mutate(e){const{mutation:t,variables:n,context:s}=e,r=this.buildRequestOptions(s),i=await this.$__client.mutation(t,n||{},r).toPromise();return this.formatResponse(i)}subscribe(e,t){const{query:n,variables:s,operationName:r}=e,i=rt.pipe(this.$__client.subscription(n,s),rt.map(o=>{t(this.formatResponse(o))}),rt.subscribe(()=>{}));return this.$__subscriptionManager.set(r,i),{unsubscribe:()=>this.unsubscribe(r)}}formatResponse(e){return{data:e.data,errors:e.error?[e.error]:void 0}}socketDisconnect(){this.soketi&&this.unsubscribeAll()}unsubscribe(e){const t=this.$__subscriptionManager.get(e);t&&(t.unsubscribe(),this.$__subscriptionManager.delete(e))}unsubscribeAll(){this.$__subscriptionManager.forEach((e,t)=>{this.unsubscribe(t)})}unsubscribeFromChannel(e){this.unsubscribe(e)}setEncryption(e=!1){this.cipherLink=e,this.$__client=this.createUrqlClient({serverUri:this.serverUri,socket:this.soketi,encrypt:e})}getAuthToken(){return this.$__authToken}getPubKey(){return this.$__pubkey}getWallet(){return this.$__wallet}getServerUri(){return this.serverUri}getSocketUri(){return this.soketi?this.soketi.socketUri:null}getUri(){return this.serverUri}setUri(e){this.serverUri=e,this.$__client=this.createUrqlClient({serverUri:e,socket:this.soketi,encrypt:!!this.cipherLink})}setSocketUri({socketUri:e,appKey:t}){this.soketi={socketUri:e,appKey:t},this.$__client=this.createUrqlClient({serverUri:this.serverUri,socket:this.soketi,encrypt:!!this.cipherLink})}}class qr{constructor({uri:e,cellSlug:t=null,client:n=null,socket:s=null,serverSdkVersion:r=3,logging:i=!1,defaultRequestPolicy:o=null,secretStorage:c=null}){this.initialize({uri:e,cellSlug:t,socket:s,client:n,serverSdkVersion:r,logging:i,defaultRequestPolicy:o,secretStorage:c})}initialize({uri:e,cellSlug:t=null,socket:n=null,client:s=null,serverSdkVersion:r=3,logging:i=!1,defaultRequestPolicy:o=null,secretStorage:c=null}){this.reset(),this.$__secretStorage=c,this.$__logging=i,this.$__defaultRequestPolicy=o,this.$__authTokenObjects={},this.$__authInProcess=!1,this.abortControllers=new Map,this.setUri(e),t&&this.setCellSlug(t);for(const u in this.$__uris){const l=this.$__uris[u];this.$__authTokenObjects[l]=null}this.log("info",`KnishIOClient::initialize() - Initializing new Knish.IO client session for SDK version ${r}...`),this.$__client=s||new Rr({socket:{socketUri:null,appKey:"knishio",...n||{}},serverUri:this.getRandomUri()}),this.$__serverSdkVersion=r}getRandomUri(){const e=Math.floor(Math.random()*this.$__uris.length);return this.$__uris[e]}switchEncryption(e){return this.$__encrypt===e?!1:(this.log("info",`KnishIOClient::switchEncryption() - Forcing encryption ${e?"on":"off"} to match node...`),this.$__encrypt=e,this.$__client.setEncryption(e),!0)}deinitialize(){this.log("info","KnishIOClient::deinitialize() - Clearing the Knish.IO client session..."),this.reset()}subscribe(){if(!this.client().getSocketUri())throw new Y("KnishIOClient::subscribe() - Socket client not initialized!");return this.client()}getServerSdkVersion(){return this.$__serverSdkVersion}getDefaultRequestPolicy(){return this.$__defaultRequestPolicy||null}setDefaultRequestPolicy(e){this.$__defaultRequestPolicy=e}reset(){this.$__secret="",this.$__bundle="",this.$__secretStorage=null,this.remainderWallet=null,this.$__capabilityCache={},this.$__defaultRequestPolicy=null}getCellSlug(){return this.$__cellSlug||null}setCellSlug(e){this.$__cellSlug=e}setUri(e){if(this.$__uris=typeof e=="object"?e:[e],this.$__client){const t=this.getRandomUri();this.$__client.setUri(t)}}setSocketUri(e){this.$__client&&typeof this.$__client.setSocketUri=="function"&&this.$__client.setSocketUri({socketUri:e,appKey:"knishio"})}getUri(){return this.$__client.getUri()}client(){if(!this.$__authInProcess){const e=this.getRandomUri();this.$__client.setUri(e);const t=this.$__authTokenObjects[e];t?this.$__client.setAuthData(t.getAuthData()):this.requestAuthToken({secret:this.$__secret,cellSlug:this.$__cellSlug,encrypt:this.$__encrypt}).catch(n=>{this.log("warn",`KnishIOClient::client() - Background authorization failed: ${n.message}`)})}return this.$__client}hasSecret(){return!!this.$__secret&&this.$__secret.length>0||!!this.$__secretStorage&&!!this.$__bundle&&this.$__bundle.length>0}setSecret(e){if(this.$__secret=e,this.$__bundle=this.hashSecret(e,"setSecret"),this.$__secretStorage)this.$__secretStorage.storeSecret(this.$__bundle,e);else{const t=new Ye;t.storeSecret(this.$__bundle,e),this.$__secretStorage=t}}hashSecret(e,t=null){return this.log("info",`KnishIOClient::hashSecret(${t?`source: ${t}`:""}) - Computing wallet bundle from secret...`),ce(e)}getSecret(){if(!this.hasSecret())throw new We("KnishIOClient::getSecret() - Unable to find a stored secret! Have you set a secret?");return this.$__secret}setSecretStorage(e,t=null){this.$__secretStorage=e,t&&(this.$__bundle=t)}getSecretStorage(){return this.$__secretStorage}async retrieveSecret(e={}){return this.$__secret&&this.$__secret.length>0?this.$__secret:this.$__secretStorage&&this.$__bundle&&this.$__bundle.length>0?await this.$__secretStorage.retrieveSecret(this.$__bundle,e):null}hasBundle(){return!!this.$__bundle}getBundle(){if(!this.hasBundle())throw new We("KnishIOClient::getBundle() - Unable to find a stored bundle! Have you set a secret?");return this.$__bundle}getFingerprint(){return br()}getFingerprintData(){return hs()}async getSourceWallet(){let e=(await this.queryContinuId({bundle:this.getBundle()})).payload();return e?e.key=S.generateKey({secret:this.getSecret(),token:e.token,position:e.position}):e=new S({secret:this.getSecret()}),e}getRemainderWallet(){return this.remainderWallet}async createMolecule({secret:e=null,bundle:t=null,sourceWallet:n=null,remainderWallet:s=null}){this.log("info","KnishIOClient::createMolecule() - Creating a new molecule..."),e||(this.$__secret&&this.$__secret.length>0?e=this.getSecret():this.$__secretStorage&&this.$__bundle&&this.$__bundle.length>0&&(e=await this.$__secretStorage.retrieveSecret(this.$__bundle))),e=e||this.getSecret(),t=t||this.getBundle();let r=null;if(n&&n.token!=="USER")if(this.lastMoleculeQuery&&this.getRemainderWallet()&&this.getRemainderWallet().token==="USER"&&this.lastMoleculeQuery.response()&&this.lastMoleculeQuery.response().success())r=this.getRemainderWallet().position;else{const i=await this.getSourceWallet();r=i?i.position:null}return!n&&this.lastMoleculeQuery&&this.getRemainderWallet().token==="USER"&&this.lastMoleculeQuery.response()&&this.lastMoleculeQuery.response().success()&&(n=this.getRemainderWallet()),n===null&&(n=await this.getSourceWallet()),this.remainderWallet=s||S.create({secret:e,bundle:t,token:"USER",batchId:n.batchId,characters:n.characters}),new z({secret:e,bundle:t,sourceWallet:n,remainderWallet:this.getRemainderWallet(),cellSlug:this.getCellSlug(),version:this.getServerSdkVersion(),continuIdPosition:r})}createQuery(e){return new e(this.client(),this)}createSubscribe(e){return new e(this.subscribe())}async createMoleculeMutation({mutationClass:e,molecule:t=null}){this.log("info",`KnishIOClient::createMoleculeQuery() - Creating a new ${e.name} query...`);const n=t||await this.createMolecule({}),s=new e(this.client(),this,n);if(!(s instanceof B))throw new Y(`${this.constructor.name}::createMoleculeMutation() - This method only accepts MutationProposeMolecule!`);return this.lastMoleculeQuery=s,s}async executeQuery(e,t=null,n={}){if(this.$__authToken&&this.$__authToken.isExpired()&&!this.$__authInProcess){this.log("info","KnishIOClient::executeQuery() - Access token is expired. Getting new one...");const i=this.$__secret||await this.retrieveSecret()||"";await this.requestAuthToken({secret:i,cellSlug:this.$__cellSlug,encrypt:this.$__encrypt})}const s=new AbortController,r=JSON.stringify({query:e.$__query,variables:t});this.abortControllers.set(r,s);try{const i={...n};this.$__defaultRequestPolicy&&!i.requestPolicy&&(i.requestPolicy=this.$__defaultRequestPolicy);const o=await e.execute({variables:t,context:{fetchOptions:{signal:s.signal},...i}});return this.abortControllers.delete(r),o}catch(i){if(i.name==="AbortError")this.log("warn","Query was cancelled");else throw i}}cancelQuery(e,t=null){const n=JSON.stringify({query:e.$__query,variables:t}),s=this.abortControllers.get(n);s&&(s.abort(),this.abortControllers.delete(n))}cancelAllQueries(){for(const e of this.abortControllers.values())e.abort();this.abortControllers.clear()}async queryBalance({token:e,bundle:t=null,type:n="regular"}){const s=this.createQuery($n);return this.executeQuery(s,{bundleHash:t||this.getBundle(),token:e,type:n})}async querySourceWallet({token:e,amount:t,type:n="regular"}){const s=(await this.queryBalance({token:e,type:n})).payload();if(s===null||ae.cmp(s.balance,t)<0)throw new G;if(!s.position||!s.address)throw new G("Source wallet can not be a shadow wallet.");return s}async subscribeCreateMolecule({bundle:e,closure:t}){return await this.createSubscribe(lr).execute({variables:{bundle:e||this.getBundle()},closure:t})}subscribeWalletStatus({bundle:e,token:t,closure:n}){if(!t)throw new Y(`${this.constructor.name}::subscribeWalletStatus() - Token parameter is required!`);return this.createSubscribe(cr).execute({variables:{bundle:e||this.getBundle(),token:t},closure:n})}subscribeActiveWallet({bundle:e,closure:t}){return this.createSubscribe(ur).execute({variables:{bundle:e||this.getBundle()},closure:t})}subscribeActiveSession({metaType:e,metaId:t,closure:n}){return this.createSubscribe(hr).execute({variables:{metaType:e,metaId:t},closure:n})}unsubscribe(e){this.subscribe().unsubscribe(e)}unsubscribeAll(){this.subscribe().unsubscribeAll()}queryMeta({metaType:e,metaId:t=null,key:n=null,value:s=null,latest:r=!0,fields:i=null,filter:o=null,queryArgs:c=null,count:u=null,countBy:l=null,throughAtom:d=!0,throughMolecule:f=!1,values:p=null,keys:w=null,atomValues:v=null,requestPolicy:O=null}){this.log("info",`KnishIOClient::queryMeta() - Querying metaType: ${e}, metaId: ${t}...`);let y,m;return f?(y=this.createQuery(vt),m=vt.createVariables({metaType:e,metaId:t,key:n,value:s,latest:r,filter:o,queryArgs:c,countBy:l,values:p,keys:w,atomValues:v,cellSlug:this.getCellSlug()})):d?(y=this.createQuery(At),m=At.createVariables({metaType:e,metaId:t,key:n,value:s,latest:r,filter:o,queryArgs:c,countBy:l,values:p,keys:w,atomValues:v,cellSlug:this.getCellSlug()})):(y=this.createQuery(wt),m=wt.createVariables({metaType:e,metaId:t,key:n,value:s,latest:r,filter:o,queryArgs:c,count:u,countBy:l,cellSlug:this.getCellSlug()})),this.executeQuery(y,m,O?{requestPolicy:O}:{})}async queryMetaVerified(e){const t=await this.queryMeta(e),n=t.payload();return n&&(n.integrity=t.verifyIntegrity()),t}async hasQueryField(e){const n=`${this.getUri()}::${e}`;if(typeof this.$__capabilityCache[n]=="boolean")return this.$__capabilityCache[n];try{const i=((await this.$__client.query({query:"{ __schema { queryType { fields { name } } } }",variables:{}}))?.data?.__schema?.queryType?.fields||[]).some(o=>o.name===e);return this.$__capabilityCache[n]=i,i}catch(s){return this.log("warn",`KnishIOClient::hasQueryField() - Capability probe for '${e}' failed: ${s.message}`),this.$__capabilityCache[n]=!1,!1}}async queryEmbeddingStatus({metaType:e=null,metaId:t=null,instances:n=null}){if(this.log("info",`KnishIOClient::queryEmbeddingStatus() - Checking embedding status for metaType: ${e||"(bulk)"}...`),!await this.hasQueryField("embeddingStatus"))return this.log("warn","KnishIOClient::queryEmbeddingStatus() - Server does not support embeddingStatus query. Returning null."),null;const r=this.createQuery(It),i=It.createVariables({metaType:e,metaId:t,instances:n});return this.executeQuery(r,i)}async queryBatch({batchId:e}){this.log("info",`KnishIOClient::queryBatch() - Querying cascading meta instances for batchId: ${e}...`);const t=this.createQuery(Se);return await this.executeQuery(t,{batchId:e})}async queryBatchHistory({batchId:e}){this.log("info",`KnishIOClient::queryBatchHistory() - Querying cascading meta instances for batchId: ${e}...`);const t=this.createQuery(vn);return await this.executeQuery(t,{batchId:e})}async queryAtom({molecularHashes:e,molecularHash:t,bundleHashes:n,bundleHash:s,positions:r,position:i,walletAddresses:o,walletAddress:c,isotopes:u,isotope:l,tokenSlugs:d,tokenSlug:f,cellSlugs:p,cellSlug:w,batchIds:v,batchId:O,values:y,value:m,metaTypes:k,metaType:R,metaIds:_,metaId:A,indexes:M,index:x,filter:$,latest:F,queryArgs:U={limit:15,offset:1}}){this.log("info","KnishIOClient::queryAtom() - Querying atom instances");const ve=this.createQuery($t);return await this.executeQuery(ve,$t.createVariables({molecularHashes:e,molecularHash:t,bundleHashes:n,bundleHash:s,positions:r,position:i,walletAddresses:o,walletAddress:c,isotopes:u,isotope:l,tokenSlugs:d,tokenSlug:f,cellSlugs:p,cellSlug:w,batchIds:v,batchId:O,values:y,value:m,metaTypes:k,metaType:R,metaIds:_,metaId:A,indexes:M,index:x,filter:$,latest:F,queryArgs:U}))}async createWallet({token:e}){const t=new S({secret:this.getSecret(),token:e}),n=await this.createMoleculeMutation({mutationClass:jn});return n.fillMolecule(t),await this.executeQuery(n)}async queryActiveSession({bundleHash:e,metaType:t,metaId:n}){const s=this.createQuery(Yn);return await this.executeQuery(s,{bundleHash:e,metaType:t,metaId:n})}async activeSession({bundle:e,metaType:t,metaId:n,ipAddress:s,browser:r,osCpu:i,resolution:o,timeZone:c,json:u={}}){const l=this.createQuery(Xn);return await this.executeQuery(l,{bundleHash:e,metaType:t,metaId:n,ipAddress:s,browser:r,osCpu:i,resolution:o,timeZone:c,json:JSON.stringify(u)})}async createToken({token:e,amount:t=null,meta:n=null,batchId:s=null,units:r=[]}){const i=C.get(n||{},"fungibility");if(i==="stackable"&&(n.batchId=s||Me({})),["nonfungible","stackable"].includes(i)&&r.length>0){if(C.get(n||{},"decimals")>0)throw new Jn;if(t>0)throw new _e;t=r.length,n.splittable=1,n.decimals=0,n.tokenUnits=JSON.stringify(r)}const o=new S({secret:this.getSecret(),bundle:this.getBundle(),token:e,batchId:s}),c=await this.createMoleculeMutation({mutationClass:Cn});return c.fillMolecule({recipientWallet:o,amount:t,meta:n||{}}),await this.executeQuery(c)}async createRule({metaType:e,metaId:t,rule:n,policy:s={}}){const r=await this.createMoleculeMutation({mutationClass:os,molecule:await this.createMolecule({secret:this.getSecret()})});return r.fillMolecule({metaType:e,metaId:t,rule:n,policy:s}),await this.executeQuery(r)}async createMeta({metaType:e,metaId:t,meta:n=null,policy:s={}}){const r=await this.createMoleculeMutation({mutationClass:Pn,molecule:await this.createMolecule({secret:this.getSecret()})}),i=n||{};return r.fillMolecule({metaType:e,metaId:t,meta:i,policy:s}),await this.executeQuery(r)}async registerPeer({host:e}){const t=await this.createMoleculeMutation({mutationClass:Kn,molecule:await this.createMolecule({secret:this.getSecret()})});return t.fillMolecule({host:e}),await this.executeQuery(t)}async appendRequest({metaType:e,metaId:t,action:n,meta:s={}}){const r=await this.createMoleculeMutation({mutationClass:Fn,molecule:await this.createMolecule({secret:this.getSecret()})});return r.fillMolecule({metaType:e,metaId:t,action:n,meta:s}),await this.executeQuery(r)}async createIdentifier({type:e,contact:t,code:n}){const s=await this.createMoleculeMutation({mutationClass:On});return s.fillMolecule({type:e,contact:t,code:n}),await this.executeQuery(s)}async linkIdentifier({type:e,contact:t}){const n=this.createQuery(Qn);return await this.executeQuery(n,{bundle:this.getBundle(),type:e,content:t})}async createPolicy({metaType:e,metaId:t,policy:n={}}){const s=await this.createMolecule({});s.addPolicyAtom({metaType:e,metaId:t,meta:{},policy:n}),s.addContinuIdAtom(),s.sign({bundle:this.getBundle()}),s.check();const r=await this.createMoleculeMutation({mutationClass:B,molecule:s});return await this.executeQuery(r)}async queryPolicy({metaType:e,metaId:t}){const n=this.createQuery(ss);return await this.executeQuery(n,{metaType:e,metaId:t})}queryWallets({bundle:e=null,token:t=null,unspent:n=!0}){this.log("info",`KnishIOClient::queryWallets() - Querying wallets${e?` for ${e}`:""}...`);const s=this.createQuery(Sn);return this.executeQuery(s,{bundleHash:e||this.getBundle(),token:t,unspent:n}).then(r=>r.payload())}queryBundle({bundle:e=null,fields:t=null,raw:n=!1}){this.log("info",`KnishIOClient::queryBundle() - Querying wallet bundle metadata${e?` for ${e}`:""}...`),e||(e=this.getBundle()),typeof e=="string"&&(e=[e]);const s=this.createQuery(kn);return this.executeQuery(s,{bundleHashes:e}).then(r=>n?r:r.payload())}async queryContinuId({bundle:e}){const t=this.createQuery(bn);return this.executeQuery(t,{bundle:e})}async requestTokens({token:e,to:t,amount:n=null,units:s=[],meta:r=null,batchId:i=null}){let o,c;r=r||{};const u=this.createQuery(es),l=await this.executeQuery(u,{slug:e}),d=C.get(l.data(),"0.fungibility")==="stackable";if(!d&&i!==null)throw new qe("Expected Batch ID = null for non-stackable tokens.");if(d&&i===null&&(i=Me({})),s.length>0){if(n>0)throw new _e;n=s.length,r.tokenUnits=JSON.stringify(s)}t?(Object.prototype.toString.call(t)==="[object String]"&&(S.isBundleHash(t)?(o="walletBundle",c=t):t=S.create({secret:t,token:e})),t instanceof S&&(o="wallet",r.position=t.position,r.bundle=t.bundle,c=t.address)):(o="walletBundle",c=this.getBundle());const f=await this.createMoleculeMutation({mutationClass:En});return f.fillMolecule({token:e,amount:n,metaType:o,metaId:c,meta:r,batchId:i}),await this.executeQuery(f)}async claimShadowWallet({token:e,batchId:t=null,molecule:n=null}){const s=await this.createMoleculeMutation({mutationClass:Wn,molecule:n});return s.fillMolecule({token:e,batchId:t}),await this.executeQuery(s)}async claimShadowWallets({token:e}){const t=await this.queryWallets({token:e});if(!t||!Array.isArray(t))throw new St;t.forEach(s=>{if(!s.isShadow())throw new St});const n=[];for(const s of t)n.push(await this.claimShadowWallet({token:e,batchId:s.batchId}));return n}async transferToken({bundleHash:e,token:t,amount:n=null,units:s=[],batchId:r=null,sourceWallet:i=null}){if(s.length>0){if(n>0)throw new _e;n=s.length}if(i===null&&(i=await this.querySourceWallet({token:t,amount:n})),i===null||ae.cmp(i.balance,n)<0)throw new G;const o=S.create({bundle:e,token:t});r!==null?o.batchId=r:o.initBatchId({sourceWallet:i});const c=i.createRemainder(this.getSecret());i.splitUnits(s,c,o);const u=await this.createMolecule({sourceWallet:i,remainderWallet:c}),l=await this.createMoleculeMutation({mutationClass:kt,molecule:u});return l.fillMolecule({recipientWallet:o,amount:n}),await this.executeQuery(l)}async transferTokens({token:e,recipients:t,sourceWallet:n=null}){const s=t.map(l=>{const d=l.units||[];if(d.length>0){if(l.amount>0)throw new _e;return d.length}return l.amount||0}),r=s.reduce((l,d)=>l+d,0);if(n===null&&(n=await this.querySourceWallet({token:e,amount:r})),n===null||ae.cmp(n.balance,r)<0)throw new G;const i=t.map(l=>{const d=S.create({bundle:l.bundleHash,token:e});return l.batchId!==void 0&&l.batchId!==null?d.batchId=l.batchId:d.initBatchId({sourceWallet:n}),d}),o=n.createRemainder(this.getSecret());n.splitUnitsMulti(t.map(l=>l.units||[]),i,o);const c=await this.createMolecule({sourceWallet:n,remainderWallet:o}),u=await this.createMoleculeMutation({mutationClass:kt,molecule:c});return u.fillMoleculeMulti({recipientWallets:i,amounts:s}),await this.executeQuery(u)}async depositBufferToken({tokenSlug:e,amount:t,tradeRates:n,sourceWallet:s=null}){s===null&&(s=await this.querySourceWallet({token:e,amount:t}));const r=s.createRemainder(this.getSecret()),i=await this.createMolecule({sourceWallet:s,remainderWallet:r}),o=await this.createMoleculeMutation({mutationClass:ls,molecule:i});return o.fillMolecule({amount:t,tradeRates:n}),await this.executeQuery(o)}async withdrawBufferToken({tokenSlug:e,amount:t,sourceWallet:n=null,signingWallet:s=null}){n===null&&(n=await this.querySourceWallet({token:e,amount:t,type:"buffer"}));const r=n,i=await this.createMolecule({sourceWallet:n,remainderWallet:r}),o=await this.createMoleculeMutation({mutationClass:cs,molecule:i}),c={};return c[this.getBundle()]=t,o.fillMolecule({recipients:c,signingWallet:s}),await this.executeQuery(o)}async burnTokens({token:e,amount:t=null,units:n=[],sourceWallet:s=null}){s===null&&(s=await this.querySourceWallet({token:e,amount:t}));const r=s.createRemainder(this.getSecret());if(n.length>0){if(t>0)throw new _e;t=n.length,s.splitUnits(n,r)}const i=await this.createMolecule({sourceWallet:s,remainderWallet:r});i.burnToken({amount:t}),i.sign({bundle:this.getBundle()}),i.check(s);const o=await this.createMoleculeMutation({mutationClass:B,molecule:i});return this.executeQuery(o)}async replenishToken({token:e,amount:t=null,units:n=[],sourceWallet:s=null}){if(s===null&&(s=(await this.queryBalance({token:e})).payload()),!s)throw new G("Source wallet is missing or invalid.");const r=s.createRemainder(this.getSecret()),i=await this.createMolecule({sourceWallet:s,remainderWallet:r});i.replenishToken({amount:t,units:n}),i.sign({bundle:this.getBundle()}),i.check();const o=await this.createMoleculeMutation({mutationClass:B,molecule:i});return this.executeQuery(o)}async fuseToken({bundleHash:e,tokenSlug:t,newTokenUnit:n,fusedTokenUnitIds:s,sourceWallet:r=null}){if(r===null&&(r=(await this.queryBalance({token:t})).payload()),r===null)throw new G("Source wallet is missing or invalid.");if(!r.tokenUnits||!r.tokenUnits.length)throw new G("Source wallet does not have token units.");if(!s.length)throw new G("Fused token unit list is empty.");const i=[];r.tokenUnits.forEach(d=>{i.push(d.id)}),s.forEach(d=>{if(!i.includes(d))throw new G(`Fused token unit ID = ${d} does not found in the source wallet.`)});const o=S.create({bundle:e,token:t});o.initBatchId({sourceWallet:r});const c=r.createRemainder(this.getSecret());r.splitUnits(s,c),typeof n=="string"&&(n=new ue(n,n,{})),n.metas.fusedTokenUnits=r.getTokenUnitsData(),o.tokenUnits=[n];const u=await this.createMolecule({sourceWallet:r,remainderWallet:c});u.fuseToken(r.tokenUnits,o),u.sign({bundle:this.getBundle()}),u.check();const l=await this.createMoleculeMutation({mutationClass:B,molecule:u});return this.executeQuery(l)}async requestGuestAuthToken({cellSlug:e,encrypt:t}){this.setCellSlug(e);const n=new S({secret:De(await this.getFingerprint()),token:"AUTH"}),s=await this.createQuery(zn),r={cellSlug:e,pubkey:n.pubkey,encrypt:t},i=await s.execute({variables:r});if(i.success()){const o=ke.create({token:i.token(),expiresAt:i.expiresAt(),pubkey:i.pubKey(),encrypt:i.encrypt()},n);this.setAuthToken(o)}else throw new _t(`KnishIOClient::requestGuestAuthToken() - Authorization attempt rejected by ledger. Reason: ${i.reason()}`);return i}async requestProfileAuthToken({secret:e,encrypt:t}){this.setSecret(e);const n=new S({secret:e,token:"AUTH"}),s=await this.createMolecule({secret:e,sourceWallet:n}),r=await this.createMoleculeMutation({mutationClass:Mn,molecule:s}),i={encrypt:t?"true":"false"};n.pubkey&&(i.walletPubkey=n.pubkey),r.fillMolecule({meta:i});const o=await r.execute({});if(o.success()){const c=ke.create({token:o.token(),expiresAt:o.expiresAt(),pubkey:o.pubKey(),encrypt:o.encrypt()},n);this.setAuthToken(c)}else throw new _t(`KnishIOClient::requestProfileAuthToken() - Authorization attempt rejected by ledger. Reason: ${o.reason()}`);return o}async requestAuthToken({secret:e=null,seed:t=null,cellSlug:n=null,encrypt:s=!1}){if(this.$__serverSdkVersion<3)return this.log("warn","KnishIOClient::authorize() - Server SDK version does not require an authorization..."),null;e===null&&t&&(e=De(t)),n&&this.setCellSlug(n),e===null&&this.$__secretStorage&&this.$__bundle&&(e=await this.$__secretStorage.retrieveSecret(this.$__bundle)),this.$__authInProcess=!0;let r;return e?r=await this.requestProfileAuthToken({secret:e,encrypt:s}):r=await this.requestGuestAuthToken({cellSlug:n,encrypt:s}),this.log("info",`KnishIOClient::authorize() - Successfully retrieved auth token ${this.$__authToken.getToken()}...`),this.switchEncryption(s),this.$__authInProcess=!1,r}setAuthToken(e){if(!e){this.log("info","KnishIOClient::setAuthToken() - authToken object is empty.");return}this.$__authTokenObjects[this.getUri()]=e,this.client().setAuthData(e.getAuthData()),this.$__authToken=e}getAuthToken(){return this.$__authToken}log(e,t){if(this.$__logging)switch(e){case"info":console.info(t);break;case"warn":console.warn(t);break;case"error":console.error(t);break;default:console.log(t)}}}class Or extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.AccessToken"})}reason(){return"Invalid response from server"}success(){return this.payload()!==null}payload(){return this.data()}payloadKey(e){if(!C.has(this.payload(),e))throw new ne(`ResponseAuthorizationGuest::payloadKey() - '${e}' key is not found in the payload!`);return C.get(this.payload(),e)}token(){return this.payloadKey("token")}time(){return this.payloadKey("time")}}class gs{constructor(){this.store=new Map}getItem(e){return this.store.get(e)??null}setItem(e,t){this.store.set(e,t)}removeItem(e){return this.store.delete(e)}keys(){return Array.from(this.store.keys())}}function Ct(a){let e="";const t=a.byteLength;for(let n=0;n<t;n++){const s=a[n];s!==void 0&&(e+=String.fromCharCode(s))}return btoa(e)}function $e(a){const e=atob(a),t=e.length,n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=e.charCodeAt(s);return n}const bs=new TextEncoder,ws=new TextDecoder,Ae="knishio:secret:",Ke=1e5;class ks{constructor(e={}){this.providerType="webcrypto-aes-gcm",this.backend=e.backend||new gs,this.defaultPassphrase=e.defaultPassphrase,this.hardwareBacked=e.hardwareBacked||!1}isHardwareBacked(){return this.hardwareBacked}async isAvailable(){return typeof globalThis.crypto<"u"&&typeof globalThis.crypto.subtle<"u"}async deriveKey(e,t,n=Ke){if(!await this.isAvailable())throw q.unavailable(this.providerType,"WebCrypto API is not available");const s=bs.encode(e);try{const r=await globalThis.crypto.subtle.importKey("raw",s,"PBKDF2",!1,["deriveKey"]);return await globalThis.crypto.subtle.deriveKey({name:"PBKDF2",salt:t,iterations:n,hash:"SHA-256"},r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}finally{ie(s)}}async storeSecret(e,t,n={}){if(!e)throw new q("Bundle hash cannot be empty");if(!t)throw new q("Secret cannot be empty");const s=n.passphrase||this.defaultPassphrase;if(!s)throw new q("Passphrase required for envelope encryption");const r=new Uint8Array(16),i=new Uint8Array(12);globalThis.crypto.getRandomValues(r),globalThis.crypto.getRandomValues(i);const o=await this.deriveKey(s,r,Ke),c=bs.encode(t);try{const u=await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:i},o,c),l=Ct(new Uint8Array(u)),d={bundleHash:e,label:n.label,createdAt:Date.now(),hardwareBacked:this.hardwareBacked,providerType:this.providerType},f={version:1,ciphertext:l,iv:Ct(i),salt:Ct(r),algorithm:"AES-GCM",iterations:Ke,metadata:d};await this.backend.setItem(`${Ae}${e}`,JSON.stringify(f))}catch(u){const l=u instanceof Error?u.message:String(u);throw new q(`Encryption failed: ${l}`)}finally{ie(c)}}async retrieveSecret(e,t={}){const n=await this.backend.getItem(`${Ae}${e}`);if(!n)return null;let s;try{s=JSON.parse(n)}catch{throw q.decryptionFailed("Corrupted payload format")}const r=t.passphrase||this.defaultPassphrase;if(!r)throw new q("Passphrase required for secret decryption");const i=$e(s.salt),o=$e(s.iv),c=$e(s.ciphertext);try{const u=await this.deriveKey(r,i,s.iterations||Ke),l=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:o},u,c),d=new Uint8Array(l);try{return ws.decode(d)}finally{ie(d)}}catch(u){const l=u instanceof Error?u.message:String(u);throw q.decryptionFailed(l)}}async deleteSecret(e){const t=`${Ae}${e}`;return await this.backend.removeItem(t)!==!1}async hasSecret(e){return await this.backend.getItem(`${Ae}${e}`)!==null}async listSecrets(){const t=(await this.backend.keys()).filter(s=>s.startsWith(Ae)),n=[];for(const s of t){const r=await this.backend.getItem(s);if(r)try{const i=JSON.parse(r);i.metadata&&n.push(i.metadata)}catch{}}return n}async withSecret(e,t,n={}){const s=await this.backend.getItem(`${Ae}${e}`);if(!s)throw q.notFound(e);let r;try{r=JSON.parse(s)}catch{throw q.decryptionFailed("Corrupted payload format")}const i=n.passphrase||this.defaultPassphrase;if(!i)throw new q("Passphrase required for secret decryption");const o=$e(r.salt),c=$e(r.iv),u=$e(r.ciphertext);try{const l=await this.deriveKey(i,o,r.iterations||Ke),d=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:c},l,u),f=new Uint8Array(d);return await yn(f,async p=>{const w=ws.decode(p);return await t(w)})}catch(l){if(l instanceof q)throw l;const d=l instanceof Error?l.message:String(l);throw q.decryptionFailed(d)}}}function Br(a={}){return a.type==="memory"?new Ye:typeof globalThis.crypto<"u"&&typeof globalThis.crypto.subtle<"u"?new ks({backend:a.backend,defaultPassphrase:a.defaultPassphrase,hardwareBacked:a.hardwareBacked}):new Ye}return h.Atom=b,h.AtomIndexException=ge,h.AtomMeta=P,h.AtomsMissingException=se,h.AuthToken=ke,h.AuthorizationRejectedException=_t,h.BalanceInsufficientException=fe,h.BatchIdException=qe,h.CheckMolecule=we,h.CodeException=Y,h.Decimal=ae,h.Dot=C,h.InvalidResponseException=ne,h.KnishIOClient=qr,h.MemorySecretStorageProvider=Ye,h.MemoryStorageBackend=gs,h.Meta=oe,h.MetaMissingException=H,h.MolecularHashMismatchException=un,h.MolecularHashMissingException=hn,h.Molecule=z,h.Mutation=Pe,h.MutationActiveSession=Xn,h.MutationAppendRequest=Fn,h.MutationClaimShadowWallet=Wn,h.MutationCreateIdentifier=On,h.MutationCreateMeta=Pn,h.MutationCreateRule=os,h.MutationCreateToken=Cn,h.MutationCreateWallet=jn,h.MutationDepositBufferToken=ls,h.MutationLinkIdentifier=Qn,h.MutationPeering=Kn,h.MutationProposeMolecule=B,h.MutationRequestAuthorization=Mn,h.MutationRequestAuthorizationGuest=zn,h.MutationRequestTokens=En,h.MutationTransferTokens=kt,h.MutationWithdrawBufferToken=cs,h.NegativeAmountException=mt,h.PolicyInvalidException=ht,h.PolicyMeta=Le,h.Query=K,h.QueryActiveSession=Yn,h.QueryAtom=$t,h.QueryBalance=$n,h.QueryBatch=Se,h.QueryBatchHistory=vn,h.QueryContinuId=bn,h.QueryEmbeddingStatus=It,h.QueryMetaType=wt,h.QueryMetaTypeViaAtom=At,h.QueryMetaTypeViaMolecule=vt,h.QueryPolicy=ss,h.QueryToken=es,h.QueryWalletBundle=kn,h.QueryWalletList=Sn,h.Response=E,h.ResponseActiveSession=Gn,h.ResponseAppendRequest=Nn,h.ResponseAtom=ts,h.ResponseAuthorizationGuest=Or,h.ResponseBalance=_n,h.ResponseClaimShadowWallet=Bn,h.ResponseContinuId=gn,h.ResponseCreateIdentifier=qn,h.ResponseCreateMeta=Un,h.ResponseCreateRule=as,h.ResponseCreateToken=Tn,h.ResponseCreateWallet=Dn,h.ResponseEmbeddingStatus=is,h.ResponseLinkIdentifier=Ln,h.ResponseMetaType=An,h.ResponseMetaTypeViaAtom=rs,h.ResponseMetaTypeViaMolecule=tt,h.ResponsePeering=Hn,h.ResponsePolicy=ns,h.ResponseProposeMolecule=j,h.ResponseQueryActiveSession=Zn,h.ResponseRequestAuthorization=In,h.ResponseRequestAuthorizationGuest=Vn,h.ResponseRequestTokens=xn,h.ResponseTransferTokens=Rn,h.ResponseWalletBundle=wn,h.ResponseWalletList=Ue,h.SecretStorageException=q,h.SignatureMalformedException=dt,h.SignatureMismatchException=dn,h.StackableUnitAmountException=_e,h.StackableUnitDecimalsException=Jn,h.TokenUnit=ue,h.TransferBalanceException=G,h.TransferMalformedException=be,h.TransferMismatchedException=pt,h.TransferRemainderException=ft,h.TransferToSelfException=pn,h.TransferUnbalancedException=Re,h.UnauthenticatedException=We,h.Wallet=S,h.WalletShadowException=St,h.WebCryptoSecretStorageProvider=ks,h.WrongTokenTypeException=re,h.base64ToHex=Bt,h.bufferToHexString=it,h.charsetBaseConvert=Rt,h.chunkArray=_s,h.chunkSubstr=Ie,h.constantTimeCompare=or,h.createDefaultSecretStorage=Br,h.deepCloning=Ut,h.diff=Pt,h.generateBatchId=Me,h.generateBundleHash=ce,h.generateSecret=De,h.hexStringToBuffer=qt,h.hexToBase64=Ot,h.intersect=me,h.isHex=Fe,h.isNumeric=Wt,h.randomString=Ne,h.shake256=je,h.withSecureBytes=yn,h.withSecureString=mn,h.zeroizeBytes=ie,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"}),h})({},jsSHA,UrqlCore,GraphQLWS,wonka);
512
512
  //# sourceMappingURL=client.iife.js.map