@wishknish/knishio-client-js 0.7.4 → 0.7.5

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(x,O,v,rn,rt){"use strict";var pr=Object.defineProperty;var fr=(x,O,v)=>O in x?pr(x,O,{enumerable:!0,configurable:!0,writable:!0,value:v}):x[O]=v;var z=(x,O,v)=>fr(x,typeof O!="symbol"?O+"":O,v);typeof self>"u"&&(global.self=global);class it{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,a=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&&++a===s.rowlength?(a=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],a=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"].indexOf(i);if(a===-1)throw Error("unexpected character");s===-1?s=16*a:(n[Math.floor(r/2)]=s+a,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,(o,e)=>e.toUpperCase())}),String.prototype.toSnakeCase||(String.prototype.toSnakeCase=function(){return this.replace(/[A-Z]/g,o=>`_${o.toLowerCase()}`)});function fe(o,e){const t=Math.ceil(o.length/e),n=[];for(let s=0,r=0;s<t;++s,r+=e)n[s]=o.substr(r,e);return n}function Me(o=256,e="abcdef0123456789"){let t=new Uint8Array(o);return t=crypto.getRandomValues(t),t=t.map(n=>e.charCodeAt(n%e.length)),String.fromCharCode.apply(null,t)}function ot(o,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",o,"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<o.length;c++)i=i*BigInt(e)+BigInt(n.indexOf(o.charAt(c)));let a="";for(;i>0;){const c=i%BigInt(t);a=s.charAt(Number(c))+a,i/=BigInt(t)}return a||"0"}function at(o){return it.toHex(o,{})}function lt(o){return it.toUint8Array(o)}function ct(o){const e=lt(o);return btoa(String.fromCharCode.apply(null,e))}function ut(o){const e=new Uint8Array(atob(o).split("").map(t=>t.charCodeAt(0)));return at(e)}function Te(o){return/^[A-F0-9]+$/i.test(o)}function on(o){return(typeof o=="number"||typeof o=="string"&&o.trim()!=="")&&!isNaN(o)}let ne=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 an(...o){return[].concat(...o.map((e,t)=>{const n=o.slice(0);n.splice(t,1);const s=[...new Set([].concat(...n))];return e.filter(r=>!s.includes(r))}))}function me(...o){return o.reduce((e,t)=>e.filter(n=>t.includes(n)))}class De{constructor(e={},t={}){this.policy=De.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(a=>a.key);this.policy[s]||(this.policy[s]={});for(const a of an(e,i))this.policy[s][a]||(this.policy[s][a]=s==="write"&&!["characters","pubkey"].includes(a)?["self"]:["all"])}}get(){return this.policy}toJson(){return JSON.stringify(this.get())}}class P{constructor(e=[]){this.meta=ne.normalizeMeta(e)}merge(e){return this.meta=Array.from(new Set([...this.meta,...ne.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 De(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($,O,A,un,ht){"use strict";var mr=Object.defineProperty;var yr=($,O,A)=>O in $?mr($,O,{enumerable:!0,configurable:!0,writable:!0,value:A}):$[O]=A;var J=($,O,A)=>yr($,typeof O!="symbol"?O+"":O,A);typeof self>"u"&&(global.self=global);class dt{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,a=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&&++a===s.rowlength?(a=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],a=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"].indexOf(i);if(a===-1)throw Error("unexpected character");s===-1?s=16*a:(n[Math.floor(r/2)]=s+a,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,(o,e)=>e.toUpperCase())}),String.prototype.toSnakeCase||(String.prototype.toSnakeCase=function(){return this.replace(/[A-Z]/g,o=>`_${o.toLowerCase()}`)});function ge(o,e){const t=Math.ceil(o.length/e),n=[];for(let s=0,r=0;s<t;++s,r+=e)n[s]=o.substr(r,e);return n}function Ee(o=256,e="abcdef0123456789"){let t=new Uint8Array(o);return t=crypto.getRandomValues(t),t=t.map(n=>e.charCodeAt(n%e.length)),String.fromCharCode.apply(null,t)}function pt(o,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",o,"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<o.length;c++)i=i*BigInt(e)+BigInt(n.indexOf(o.charAt(c)));let a="";for(;i>0;){const c=i%BigInt(t);a=s.charAt(Number(c))+a,i/=BigInt(t)}return a||"0"}function ft(o){return dt.toHex(o,{})}function mt(o){return dt.toUint8Array(o)}function yt(o){const e=mt(o);return btoa(String.fromCharCode.apply(null,e))}function gt(o){const e=new Uint8Array(atob(o).split("").map(t=>t.charCodeAt(0)));return ft(e)}function Oe(o){return/^[A-F0-9]+$/i.test(o)}function hn(o){return(typeof o=="number"||typeof o=="string"&&o.trim()!=="")&&!isNaN(o)}let ne=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 dn(...o){return[].concat(...o.map((e,t)=>{const n=o.slice(0);n.splice(t,1);const s=[...new Set([].concat(...n))];return e.filter(r=>!s.includes(r))}))}function be(...o){return o.reduce((e,t)=>e.filter(n=>t.includes(n)))}class Ge{constructor(e={},t={}){this.policy=Ge.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(a=>a.key);this.policy[s]||(this.policy[s]={});for(const a of dn(e,i))this.policy[s][a]||(this.policy[s][a]=s==="write"&&!["characters","pubkey"].includes(a)?["self"]:["all"])}}get(){return this.policy}toJson(){return JSON.stringify(this.get())}}class H{constructor(e=[]){this.meta=ne.normalizeMeta(e)}merge(e){return this.meta=Array.from(new Set([...this.meta,...ne.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 Ge(e,Object.keys(this.meta));return this.merge({policy:t.toJson()}),this}get(){return this.meta}}class T 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 se extends M{constructor(e="The molecule does not contain atoms",t=null,n=null){super(e,t,n),this.name="AtomsMissingException"}}class re{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(re.isStructure(e[n])?re.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]=re.isStructure(e[s])?re.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 re.structure(this)}}class ln extends re{constructor({position:e=null,walletAddress:t=null,isotope:n=null,token:s=null,value:r=null,batchId:i=null,metaType:a=null,metaId:c=null,meta:u=null,index:l=null,createdAt:h=null,version:p=null}){super(),this.position=e,this.walletAddress=t,this.isotope=n,this.token=s,this.value=r,this.batchId=i,this.metaType=a,this.metaId=c,this.meta=u,this.index=l,this.createdAt=h,this.version=p}}const Ce={4:ln};class g{constructor({position:e=null,walletAddress:t=null,isotope:n=null,token:s=null,value:r=null,batchId:i=null,metaType:a=null,metaId:c=null,meta:u=null,otsFragment:l=null,index:h=null,version:p=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=a,this.metaId=c,this.meta=u?ne.normalizeMeta(u):[],this.index=h,this.otsFragment=l,this.createdAt=String(+new Date),p!==null&&Object.prototype.hasOwnProperty.call(Ce,p)&&(this.version=String(p))}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:a=null}){return i||(i=new P),i instanceof P||(i=new P(i)),t&&(i.setAtomWallet(t),a||(a=t.batchId)),new g({position:t?t.position:null,walletAddress:t?t.address:null,isotope:e,token:t?t.token:null,value:n,batchId:a,metaType:s,metaId:r,meta:i.get()})}static jsonToObject(e){const t=Object.assign(new g({}),JSON.parse(e)),n=Object.keys(new g({}));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 a=["position","walletAddress","isotope","token"];for(const c of a)if(!r[c])throw new Error(`Required field '${c}' is missing or empty`)}const i=new g({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 O("SHAKE256","TEXT"),s=g.sortAtoms(e);if(s.length===0)throw new se;if(s.map(r=>{if(!(r instanceof g))throw new se;return r}),s.every(r=>r.version&&Object.prototype.hasOwnProperty.call(Ce,r.version)))n.update(JSON.stringify(s.map(r=>Ce[r.version].create(r).view())));else{const r=String(e.length);let i=[];for(const a of s)i.push(r),i=i.concat(a.getHashableValues());for(const a of i)n.update(a)}switch(t){case"hex":return n.getHash("HEX",{outputLen:256});case"array":return n.getHash("ARRAYBUFFER",{outputLen:256});default:return ot(n.getHash("HEX",{outputLen:256}),16,17,"0123456789abcdef","0123456789abcdefg").padStart(64,"0")}}static jsonSerialization(e,t){if(!g.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 ne.aggregateMeta(this.meta)}getHashableValues(){const e=[];for(const t of g.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 Ee(o=null,e=2048){if(o){const t=new O("SHAKE256","TEXT");return t.update(o),t.getHash("HEX",{outputLen:e*2})}else return Me(e)}function ie(o,e=null){const t=new O("SHAKE256","TEXT");return t.update(o),t.getHash("HEX",{outputLen:256})}function Ve(o,e){const t=new O("SHAKE256","TEXT");return t.update(o),t.getHash("HEX",{outputLen:e})}function Oe({molecularHash:o=null,index:e=null}){return o!==null&&e!==null?ie(String(o)+String(e),"generateBatchId"):Me(64)}class ye{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 ye(e.id,e.name,t)}static createFromDB(e){return new ye(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 cn 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 Re=BigInt(2**32-1),ht=BigInt(32);function un(o,e=!1){return e?{h:Number(o&Re),l:Number(o>>ht&Re)}:{h:Number(o>>ht&Re)|0,l:Number(o&Re)|0}}function hn(o,e=!1){const t=o.length;let n=new Uint32Array(t),s=new Uint32Array(t);for(let r=0;r<t;r++){const{h:i,l:a}=un(o[r],e);[n[r],s[r]]=[i,a]}return[n,s]}const dn=(o,e,t)=>o<<t|e>>>32-t,pn=(o,e,t)=>e<<t|o>>>32-t,fn=(o,e,t)=>e<<t-32|o>>>64-t,mn=(o,e,t)=>o<<t-32|e>>>64-t;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function yn(o){return o instanceof Uint8Array||ArrayBuffer.isView(o)&&o.constructor.name==="Uint8Array"}function dt(o,e=""){if(!Number.isSafeInteger(o)||o<0){const t=e&&`"${e}" `;throw new Error(`${t}expected integer >0, got ${o}`)}}function j(o,e,t=""){const n=yn(o),s=o==null?void 0:o.length,r=e!==void 0;if(!n||r&&s!==e){const i=t&&`"${t}" `,a=r?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof o}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return o}function pt(o,e=!0){if(o.destroyed)throw new Error("Hash instance has been destroyed");if(e&&o.finished)throw new Error("Hash#digest() has already been called")}function gn(o,e){j(o,void 0,"digestInto() output");const t=e.outputLen;if(o.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function ft(o){return new Uint32Array(o.buffer,o.byteOffset,Math.floor(o.byteLength/4))}function mt(...o){for(let e=0;e<o.length;e++)o[e].fill(0)}const wn=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function bn(o){return o<<24&4278190080|o<<8&16711680|o>>>8&65280|o>>>24&255}function kn(o){for(let e=0;e<o.length;e++)o[e]=bn(o[e]);return o}const yt=wn?o=>o:kn;function gt(o,e={}){const t=(s,r)=>o(r).update(s).digest(),n=o(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=s=>o(s),Object.assign(t,e),Object.freeze(t)}function _n(o=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(o))}const We=o=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,o])}),Sn=BigInt(0),ge=BigInt(1),$n=BigInt(2),An=BigInt(7),vn=BigInt(256),xn=BigInt(113),wt=[],bt=[],kt=[];for(let o=0,e=ge,t=1,n=0;o<24;o++){[t,n]=[n,(2*t+3*n)%5],wt.push(2*(5*n+t)),bt.push((o+1)*(o+2)/2%64);let s=Sn;for(let r=0;r<7;r++)e=(e<<ge^(e>>An)*xn)%vn,e&$n&&(s^=ge<<(ge<<BigInt(r))-ge);kt.push(s)}const _t=hn(kt,!0),In=_t[0],Mn=_t[1],St=(o,e,t)=>t>32?fn(o,e,t):dn(o,e,t),$t=(o,e,t)=>t>32?mn(o,e,t):pn(o,e,t);function Tn(o,e=24){const t=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let i=0;i<10;i++)t[i]=o[i]^o[i+10]^o[i+20]^o[i+30]^o[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,c=(i+2)%10,u=t[c],l=t[c+1],h=St(u,l,1)^t[a],p=$t(u,l,1)^t[a+1];for(let d=0;d<50;d+=10)o[i+d]^=h,o[i+d+1]^=p}let s=o[2],r=o[3];for(let i=0;i<24;i++){const a=bt[i],c=St(s,r,a),u=$t(s,r,a),l=wt[i];s=o[l],r=o[l+1],o[l]=c,o[l+1]=u}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)t[a]=o[i+a];for(let a=0;a<10;a++)o[i+a]^=~t[(a+2)%10]&t[(a+4)%10]}o[0]^=In[n],o[1]^=Mn[n]}mt(t)}class qe{constructor(e,t,n,s=!1,r=24){z(this,"state");z(this,"pos",0);z(this,"posOut",0);z(this,"finished",!1);z(this,"state32");z(this,"destroyed",!1);z(this,"blockLen");z(this,"suffix");z(this,"outputLen");z(this,"enableXOF",!1);z(this,"rounds");if(this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=s,this.rounds=r,dt(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(){yt(this.state32),Tn(this.state32,this.rounds),yt(this.state32),this.posOut=0,this.pos=0}update(e){pt(this),j(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 a=0;a<i;a++)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){pt(this,!1),j(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 dt(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(gn(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,mt(this.state)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:s,rounds:r,enableXOF:i}=this;return e||(e=new qe(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 At=(o,e,t,n={})=>gt(()=>new qe(e,o,t),n),Cn=At(6,136,32,We(8)),En=At(6,72,64,We(10)),vt=(o,e,t,n={})=>gt((s={})=>new qe(e,o,s.dkLen===void 0?t:s.dkLen,!0),n),On=vt(31,168,16,We(11)),xt=vt(31,136,32,We(12));function ze(o){if(!Number.isSafeInteger(o)||o<0||o>4294967295)throw new Error("wrong u32 integer:"+o);return o}function It(o){return ze(o),(o&o-1)===0&&o!==0}function Mt(o,e){ze(o);let t=0;for(let n=0;n<e;n++,o>>>=1)t=t<<1|o&1;return t}function Tt(o){return ze(o),31-Math.clz32(o)}function Ct(o){const e=o.length;if(e<2||!It(e))throw new Error("n must be a power of 2 and greater than 1. Got "+e);const t=Tt(e);for(let n=0;n<e;n++){const s=Mt(n,t);if(n<s){const r=o[n];o[n]=o[s],o[s]=r}}return o}const Et=(o,e)=>{const{N:t,roots:n,dit:s,invertButterflies:r=!1,skipStages:i=0,brp:a=!0}=e,c=Tt(t);if(!It(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&&a&&Ct(l);for(let h=0,p=1;h<c-i;h++){const d=s?h+1+i:c-h,w=1<<d,$=w>>1,E=t>>d;for(let m=0;m<t;m+=w)for(let y=0,b=p++;y<$;y++){const C=r?s?t-b:b:y*E,_=m+y,A=m+y+$,I=n[C],T=l[A],S=l[_];if(u){const K=o.mul(T,I);l[_]=o.add(S,K),l[A]=o.sub(S,K)}else r?(l[_]=o.add(T,S),l[A]=o.mul(o.sub(T,S),I)):(l[_]=o.add(S,T),l[A]=o.mul(o.sub(S,T),I))}}return!s&&a&&Ct(l),l}};/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */const Ot=_n;function Je(o,e){if(o.length!==e.length)return!1;let t=0;for(let n=0;n<o.length;n++)t|=o[n]^e[n];return t===0}function Rn(o){return Uint8Array.from(o)}function Ue(o,...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,a=0;i<e.length;i++){const c=e[i],u=t(c),l=typeof c=="number"?s[i]:c.encode(s[i]);j(l,u,o),r.set(l,a),typeof c!="number"&&l.fill(0),a+=u}return r},decode:s=>{j(s,n,o);const r=[];for(const i of e){const a=t(i),c=s.subarray(0,a);r.push(typeof i=="number"?c:i.decode(c)),s=s.subarray(a)}return r}}}function Ge(o,e){const t=e*o.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 a=o.encode(n[r]);s.set(a,i),a.fill(0),i+=a.length}return s},decode:n=>{j(n,t);const s=[];for(let r=0;r<n.length;r+=o.bytesLen)s.push(o.decode(n.subarray(r,r+o.bytesLen)));return s}}}function X(...o){for(const e of o)if(Array.isArray(e))for(const t of e)t.fill(0);else e.fill(0)}function Rt(o){return(1<<o)-1}/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */const Wn=o=>{const{newPoly:e,N:t,Q:n,F:s,ROOT_OF_UNITY:r,brvBits:i}=o,a=(m,y=n)=>{const b=m%y|0;return(b>=0?b|0:y+b|0)|0},c=(m,y=n)=>{const b=a(m,y)|0;return(b>y>>1?b-y|0:b)|0};function u(){const m=e(t);for(let y=0;y<t;y++){const b=Mt(y,i),C=BigInt(r)**BigInt(b)%BigInt(n);m[y]=Number(C)|0}return m}const l=u(),h={add:(m,y)=>a((m|0)+(y|0))|0,sub:(m,y)=>a((m|0)-(y|0))|0,mul:(m,y)=>a((m|0)*(y|0))|0,inv:m=>{throw new Error("not implemented")}},p={N:t,roots:l,invertButterflies:!0,skipStages:1,brp:!1},d=Et(h,{dit:!1,...p}),w=Et(h,{dit:!0,...p});return{mod:a,smod:c,nttZetas:l,NTT:{encode:m=>d(m),decode:m=>{w(m);for(let y=0;y<m.length;y++)m[y]=a(s*m[y]);return m}},bitsCoder:(m,y)=>{const b=Rt(m),C=m*(t/8);return{bytesLen:C,encode:_=>{const A=new Uint8Array(C);for(let I=0,T=0,S=0,K=0;I<_.length;I++)for(T|=(y.encode(_[I])&b)<<S,S+=m;S>=8;S-=8,T>>=8)A[K++]=T&Rt(S);return A},decode:_=>{const A=e(t);for(let I=0,T=0,S=0,K=0;I<_.length;I++)for(T|=_[I]<<S,S+=8;S>=m;S-=m,T>>=m)A[K++]=y.decode(T&b);return A}}}}},qn=(o=>(e,t)=>{t||(t=o.blockLen);const n=new Uint8Array(e.length+2);n.set(e);const s=e.length,r=new Uint8Array(t);let i=o.create({}),a=0,c=0;return{stats:()=>({calls:a,xofs:c}),get:(u,l)=>(n[s+0]=u,n[s+1]=l,i.destroy(),i=o.create({}).update(n),a++,()=>(c++,i.xofInto(r))),clean:()=>{i.destroy(),X(r,n)}}})(On);/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */const N=256,oe=3329,Un=3303,Bn=17,{mod:we,nttZetas:Pn,NTT:ae,bitsCoder:Hn}=Wn({N,Q:oe,F:Un,ROOT_OF_UNITY:Bn,newPoly:o=>new Uint16Array(o),brvBits:7}),Kn={768:{N,Q:oe,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192}},Ln=o=>{if(o>=12)return{encode:t=>t,decode:t=>t};const e=2**(o-1);return{encode:t=>((t<<o)+oe/2)/oe,decode:t=>t*oe+e>>>o}},be=o=>Hn(o,Ln(o));function le(o,e){for(let t=0;t<N;t++)o[t]=we(o[t]+e[t])}function Nn(o,e){for(let t=0;t<N;t++)o[t]=we(o[t]-e[t])}function Fn(o,e,t,n,s){const r=we(e*n*s+o*t),i=we(o*n+e*t);return{c0:r,c1:i}}function Be(o,e){for(let t=0;t<N/2;t++){let n=Pn[64+(t>>1)];t&1&&(n=-n);const{c0:s,c1:r}=Fn(o[2*t+0],o[2*t+1],e[2*t+0],e[2*t+1],n);o[2*t+0]=s,o[2*t+1]=r}return o}function Wt(o){const e=new Uint16Array(N);for(let t=0;t<N;){const n=o();if(n.length%3)throw new Error("SampleNTT: unaligned block");for(let s=0;t<N&&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<oe&&(e[t++]=r),t<N&&i<oe&&(e[t++]=i)}}return e}function ke(o,e,t,n){const s=o(n*N/4,e,t),r=new Uint16Array(N),i=ft(s);let a=0;for(let c=0,u=0,l=0,h=0;c<i.length;c++){let p=i[c];for(let d=0;d<32;d++)l+=p&1,p>>=1,a+=1,a===n?(h=l,l=0):a===2*n&&(r[u++]=we(h-l),l=0,a=0)}if(a)throw new Error(`sampleCBD: leftover bits: ${a}`);return r}const jn=o=>{const{K:e,PRF:t,XOF:n,HASH512:s,ETA1:r,ETA2:i,du:a,dv:c}=o,u=be(1),l=be(c),h=be(a),p=Ue("publicKey",Ge(be(12),e),32),d=Ge(be(12),e),w=Ue("ciphertext",Ge(h,e),l),$=Ue("seed",32,32);return{secretCoder:d,lengths:{secretKey:d.bytesLen,publicKey:p.bytesLen,cipherText:w.bytesLen},keygen:E=>{j(E,32,"seed");const m=new Uint8Array(33);m.set(E),m[32]=e;const y=s(m),[b,C]=$.decode(y),_=[],A=[];for(let S=0;S<e;S++)_.push(ae.encode(ke(t,C,S,r)));const I=n(b);for(let S=0;S<e;S++){const K=ae.encode(ke(t,C,e+S,r));for(let U=0;U<e;U++){const pe=Wt(I.get(U,S));le(K,Be(pe,_[U]))}A.push(K)}I.clean();const T={publicKey:p.encode([A,b]),secretKey:d.encode(_)};return X(b,C,_,A,m,y),T},encrypt:(E,m,y)=>{const[b,C]=p.decode(E),_=[];for(let U=0;U<e;U++)_.push(ae.encode(ke(t,y,U,r)));const A=n(C),I=new Uint16Array(N),T=[];for(let U=0;U<e;U++){const pe=ke(t,y,e+U,i),st=new Uint16Array(N);for(let Qe=0;Qe<e;Qe++){const dr=Wt(A.get(U,Qe));le(st,Be(dr,_[Qe]))}le(pe,ae.decode(st)),T.push(pe),le(I,Be(b[U],_[U])),X(st)}A.clean();const S=ke(t,y,2*e,i);le(S,ae.decode(I));const K=u.decode(m);return le(K,S),X(b,_,I,S),w.encode([T,K])},decrypt:(E,m)=>{const[y,b]=w.decode(E),C=d.decode(m),_=new Uint16Array(N);for(let A=0;A<e;A++)le(_,Be(C[A],ae.encode(y[A])));return Nn(b,ae.decode(_)),X(_,C,y),u.encode(b)}}};function Qn(o){const e=jn(o),{HASH256:t,HASH512:n,KDF:s}=o,{secretCoder:r,lengths:i}=e,a=Ue("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:a.bytesLen},keygen:(l=Ot(u))=>{j(l,u,"seed");const{publicKey:h,secretKey:p}=e.keygen(l.subarray(0,32)),d=t(h),w=a.encode([p,h,d,l.subarray(32)]);return X(p,d),{publicKey:h,secretKey:w}},getPublicKey:l=>{const[h,p]=a.decode(l);return Uint8Array.from(p)},encapsulate:(l,h=Ot(c))=>{j(l,i.publicKey,"publicKey"),j(h,c,"message");const p=l.subarray(0,384*o.K),d=r.encode(r.decode(Rn(p)));if(!Je(d,p))throw X(d),new Error("ML-KEM.encapsulate: wrong publicKey modulus");X(d);const w=n.create().update(h).update(t(l)).digest(),$=e.encrypt(l,h,w.subarray(32,64));return X(w.subarray(32)),{cipherText:$,sharedSecret:w.subarray(0,32)}},decapsulate:(l,h)=>{j(h,a.bytesLen,"secretKey"),j(l,i.cipherText,"cipherText");const p=a.bytesLen-96,d=p+32,w=t(h.subarray(p/2,d));if(!Je(w,h.subarray(d,d+32)))throw new Error("invalid secretKey: hash check failed");const[$,E,m,y]=a.decode(h),b=e.decrypt(l,$),C=n.create().update(b).update(m).digest(),_=C.subarray(0,32),A=e.encrypt(E,b,C.subarray(32,64)),I=Je(l,A),T=s.create({dkLen:32}).update(y).update(l).digest();return X(b,A,I?T:_),I?_:T}}}function Dn(o,e,t){return xt.create({dkLen:o}).update(e).update(new Uint8Array([t])).digest()}const Xe=Qn({...{HASH256:Cn,HASH512:En,KDF:xt,XOF:qn,PRF:Dn},...Kn[768]});class k{constructor({secret:e=null,bundle:t=null,token:n="USER",address:s=null,position:r=null,batchId:i=null,characters:a=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=a,e&&(this.bundle=this.bundle||ie(e,"Wallet::constructor"),this.position=this.position||k.generatePosition(),this.key=k.generateKey({secret:e,token:this.token,position:this.position}),this.address=this.address||k.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 cn;return e&&!t&&(i=k.generatePosition(),t=ie(e,"Wallet::create")),new k({secret:e,bundle:t,token:n,position:i,batchId:s,characters:r})}static isBundleHash(e){return typeof e!="string"?!1:e.length===64&&Te(e)}static getTokenUnits(e){const t=[];return e.forEach(n=>{t.push(ye.createFromDB(n))}),t}static generateKey({secret:e,token:t,position:n}){const s=Te(e)?e:Ve(e,1024),r=Te(n)?n:Ve(n,256),a=BigInt(`0x${s}`)+BigInt(`0x${r}`),c=new O("SHAKE256","TEXT");c.update(a.toString(16)),t&&c.update(t);const u=new O("SHAKE256","TEXT");return u.update(c.getHash("HEX",{outputLen:8192})),u.getHash("HEX",{outputLen:8192})}static generateAddress(e){const t=fe(e,128),n=new O("SHAKE256","TEXT");for(const r in t){let i=t[r];for(let a=1;a<=16;a++){const c=new O("SHAKE256","TEXT");c.update(i),i=c.getHash("HEX",{outputLen:512})}n.update(i)}const s=new O("SHAKE256","TEXT");return s.update(n.getHash("HEX",{outputLen:8192})),s.getHash("HEX",{outputLen:256})}static generatePosition(e=64){return Me(e,"abcdef0123456789")}initializeMLKEM(){const e=Ee(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}=Xe.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))}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}createRemainder(e){const t=k.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:Oe({}))}async encryptMessage(e,t){const n=JSON.stringify(e),s=new TextEncoder().encode(n),r=this.deserializeKey(t),{cipherText:i,sharedSecret:a}=Xe.encapsulate(r),c=await this.encryptWithSharedSecret(s,a);return{cipherText:this.serializeKey(i),encryptedMessage:this.serializeKey(c)}}async decryptMessage(e){const{cipherText:t,encryptedMessage:n}=e;let s;try{s=Xe.decapsulate(this.deserializeKey(t),this.privkey)}catch(c){return console.error("Wallet::decryptMessage() - Decapsulation failed",c),console.info("Wallet::decryptMessage() - my public key",this.pubkey),null}let r;try{r=this.deserializeKey(n)}catch(c){return console.warn("Wallet::decryptMessage() - Deserialization failed",c),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(c){return console.warn("Wallet::decryptMessage() - Decryption failed",c),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}let a;try{a=new TextDecoder().decode(i)}catch(c){return console.warn("Wallet::decryptMessage() - Decoding failed",c),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}return JSON.parse(a)}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),a=new Uint8Array(n.length+i.byteLength);return a.set(n),a.set(new Uint8Array(i),n.length),a}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 _e extends M{constructor(e="There is an atom without an index",t=null,n=null){super(e,t,n),this.name="AtomIndexException"}}class Vn extends M{constructor(e="The molecular hash does not match",t=null,n=null){super(e,t,n),this.name="MolecularHashMismatchException"}}class zn extends M{constructor(e="The molecular hash is missing",t=null,n=null){super(e,t,n),this.name="MolecularHashMissingException"}}class qt extends M{constructor(e="",t=null,n=null){super(e,t,n),this.name="PolicyInvalidException"}}class Ut extends M{constructor(e="OTS malformed",t=null,n=null){super(e,t,n),this.name="SignatureMalformedException"}}class Jn extends M{constructor(e="One-time signature (OTS) does not match!",t=null,n=null){super(e,t,n),this.name="SignatureMismatchException"}}class ee extends M{constructor(e="Insufficient balance to make transfer",t=null,n=null){super(e,t,n),this.name="TransferBalanceException"}}class Bt extends M{constructor(e="Token transfer atoms are malformed",t=null,n=null){super(e,t,n),this.name="TransferMalformedException"}}class Pt 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 Ht extends M{constructor(e="Invalid remainder provided",t=null,n=null){super(e,t,n),this.name="TransferRemainderException"}}class Gn extends M{constructor(e="Sender and recipient(s) cannot be the same",t=null,n=null){super(e,t,n),this.name="TransferToSelfException"}}class Xn extends M{constructor(e="Token transfer atoms are unbalanced",t=null,n=null){super(e,t,n),this.name="TransferUnbalancedException"}}class Q extends M{constructor(e="Empty meta data.",t=null,n=null){super(e,t,n),this.name="MetaMissingException"}}class ce extends M{constructor(e="Wrong type of token for this isotope",t=null,n=null){super(e,t,n),this.name="WrongTokenTypeException"}}class Pe extends M{constructor(e="Incorrect BatchId",t=null,n=null){super(e,t,n),this.name="BatchIdException"}}class Kt{constructor({}){const e=arguments[0];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 He extends M{constructor(e="An incorrect argument!",t=null,n=null){super(e,t,n),this.name="RuleArgumentException"}}class te extends M{constructor(e="Code exception",t=null,n=null){super(e,t,n),this.name="CodeException"}}class Se{constructor({action:e,metaType:t=null,metaId:n=null,meta:s=null,address:r=null,token:i=null,amount:a=null,comparison:c=null}){if(s&&(this.meta=s),!e)throw new He('Callback structure violated, missing mandatory "action" parameter.');this.__metaId=n,this.__metaType=t,this.__action=e,this.__address=r,this.__token=i,this.__amount=a,this.__comparison=c}set comparison(e){this.__comparison=e}set amount(e){if(!on(e))throw new te("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 Kt?e:Kt.toObject(e)}set metaType(e){this.__metaType=e}set metaId(e){this.__metaId=e}static toObject(e){const t=new Se({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 Ze{constructor({key:e,value:t,comparison:n}){if([e,t,n].some(s=>!s))throw new He("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 $e{constructor({condition:e=[],callback:t=[]}){for(const n of e)if(!(n instanceof Ze))throw new He;for(const n of t)if(!(n instanceof Se))throw new He;this.__condition=e,this.__callback=t}set comparison(e){this.__condition.push(e instanceof Ze?e:Ze.toObject(e))}set callback(e){this.__callback.push(e instanceof Se?e:Se.toObject(e))}static toObject(e){if(!e.condition)throw new Q("Rule::toObject() - Incorrect rule format! There is no condition field.");if(!e.callback)throw new Q("Rule::toObject() - Incorrect rule format! There is no callback field.");const t=new $e({});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 R{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],h=Number(l),p=Number.isInteger(h);(p?h:l in r)||(r[p?h:l]=s[u+1].match(/^\d+$/)?[]:{}),r=r[p?h:l]}const a=s[i],c=Number(a);return r[Number.isInteger(c)?c:a]=n,e}}class Zn{constructor(e){if(e.molecularHash===null)throw new zn;if(!e.atoms.length)throw new se;for(const t of e.atoms)if(t.index===null)throw new _e;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.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 Pe;for(const s of t)if(s.batchId===null)throw new Pe}return!0}throw new Pe}isotopeI(){for(const e of this.molecule.getIsotopes("I")){if(e.token!=="USER")throw new ce(`Check::isotopeI() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index===0)throw new _e(`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 ce(`Check::isotopeU() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index!==0)throw new _e(`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 Q;if(t.token!=="USER")throw new ce(`Check::isotopeM() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);const n=ne.aggregateMeta(t.meta);for(const s of e){let r=n[s];if(r){r=JSON.parse(r);for(const[i,a]of Object.entries(r))if(!e.includes(i)){if(!Object.keys(n).includes(i))throw new qt(`${i} is missing from the meta.`);for(const c of a)if(!k.isBundleHash(c)&&!["all","self"].includes(c))throw new qt(`${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 ce(`Check::isotopeC() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index!==0)throw new _e(`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 Q(`Check::isotopeT() - Required meta field "${s}" is missing!`)}for(const s of["token"])if(!Object.prototype.hasOwnProperty.call(t,s)||!t[s])throw new Q(`Check::isotopeT() - Required meta field "${s}" is missing!`);if(e.token!=="USER")throw new ce(`Check::isotopeT() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index!==0)throw new _e(`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 Q("Check::isotopeR() - Mixing rules with politics!")}if(t.rule){const n=JSON.parse(t.rule);if(!Array.isArray(n))throw new Q("Check::isotopeR() - Incorrect rule format!");for(const s of n)$e.toObject(s);if(n.length<1)throw new Q("Check::isotopeR() - No rules!")}}return!0}isotopeP(){for(const e of this.molecule.getIsotopes("P")){if(e.token!=="USER")throw new ce(`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 Q('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 ce(`Check::isotopeA() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(!e.metaType)throw new Q('Check::isotopeA() - Required field "metaType" is missing!');if(!e.metaId)throw new Q('Check::isotopeA() - Required field "metaId" is missing!');const t=e.aggregatedMeta();if(!Object.prototype.hasOwnProperty.call(t,"action")||!t.action)throw new Q('Check::isotopeA() - Required meta field "action" is missing!')}return!0}isotopeV(e=null){const t=this.molecule.getIsotopes("V");if(t.length===0)return!0;const n=this.molecule.atoms[0];if(n.isotope==="V"&&t.length===2){const i=t[t.length-1];if(n.token!==i.token)throw new Pt;if(i.value<0)throw new Bt;return!0}let s=0,r=0;for(const i in this.molecule.atoms)if(Object.prototype.hasOwnProperty.call(this.molecule.atoms,i)){const a=this.molecule.atoms[i];if(a.isotope!=="V")continue;if(r=a.value*1,Number.isNaN(r))throw new TypeError('Invalid isotope "V" values');if(a.token!==n.token)throw new Pt;if(i>0){if(r<0)throw new Bt;if(a.walletAddress===n.walletAddress)throw new Gn}s+=r}if(s!==0)throw new Xn;if(e){if(r=n.value*1,Number.isNaN(r))throw new TypeError('Invalid isotope "V" values');const i=e.balance+r;if(i<0)throw new ee;if(i!==s)throw new Ht}else if(r!==0)throw new Ht;return!0}molecularHash(){if(this.molecule.molecularHash!==g.hashAtoms({atoms:this.molecule.atoms}))throw new Vn;return!0}ots(){const e=this.molecule.normalizedHash();let t=this.molecule.atoms.map(p=>p.otsFragment).reduce((p,d)=>p+d);if(t.length!==2048&&(t=ut(t),t.length!==2048))throw new Ut;const n=fe(t,128);let s="";for(const p in n){let d=n[p];for(let w=0,$=8+e[p];w<$;w++)d=new O("SHAKE256","TEXT").update(d).getHash("HEX",{outputLen:512});s+=d}const r=new O("SHAKE256","TEXT");r.update(s);const i=r.getHash("HEX",{outputLen:8192}),a=new O("SHAKE256","TEXT");a.update(i);const c=a.getHash("HEX",{outputLen:256}),u=this.molecule.atoms[0];let l=u.walletAddress;const h=R.get(u.aggregatedMeta(),"signingWallet");if(h&&(l=R.get(JSON.parse(h),"address")),c!==l)throw new Jn;return!0}}class Ae extends M{constructor(e="Insufficient balance for requested transfer",t=null,n=null){super(e,t,n),this.name="BalanceInsufficientException"}}class Lt extends M{constructor(e="Amount cannot be negative!",t=null,n=null){super(e,t,n),this.name="NegativeAmountException"}}class J{constructor({secret:e=null,bundle:t=null,sourceWallet:n=null,remainderWallet:s=null,cellSlug:r=null,version:i=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.atoms=[],i!==null&&Object.prototype.hasOwnProperty.call(Ce,i)&&(this.version=String(i)),(s||n)&&(this.remainderWallet=s||k.create({secret:e,bundle:t,token:n.token,batchId:n.batchId,characters:n.characters}))}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 J({}),JSON.parse(e)),n=Object.keys(new J({}));if(!Array.isArray(t.atoms))throw new se;for(const s in Object.keys(t.atoms)){t.atoms[s]=g.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=g.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 a=s[r];typeof t[a]<"u"&&(n[r]=t[a])}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 J.isotopeFilter(e,this.atoms)}generateIndex(){return J.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=g.sortAtoms(this.atoms),this}addContinuIdAtom(){(!this.remainderWallet||this.remainderWallet.token!=="USER")&&(this.remainderWallet=k.create({secret:this.secret,bundle:this.bundle}));const e={};return 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(g.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);r.addPolicy(s);const i=k.create({secret:this.secret,bundle:this.sourceWallet.bundle,token:"USER"});return this.addAtom(g.create({wallet:i,isotope:"R",metaType:e,metaId:t,meta:r})),this}fuseToken(e,t){const n=e.length;if(this.sourceWallet.balance-n<0)throw new Ae;return this.addAtom(g.create({isotope:"V",wallet:this.sourceWallet,value:-n})),this.addAtom(g.create({isotope:"F",wallet:t,value:1,metaType:"walletBundle",metaId:t.bundle})),this.addAtom(g.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 Lt("Molecule::burnToken() - Amount to burn must be positive!");if(this.sourceWallet.balance-e<0)throw new Ae;return this.addAtom(g.create({isotope:"V",wallet:this.sourceWallet,value:-e})),this.addAtom(g.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 Lt("Molecule::replenishToken() - Amount to replenish must be positive!");if(t.length){t=k.getTokenUnits(t),this.remainderWallet.tokenUnits=this.sourceWallet.tokenUnits;for(const n of t)this.remainderWallet.tokenUnits.push(n);this.remainderWallet.balance=this.remainderWallet.tokenUnits.length,this.sourceWallet.tokenUnits=t,this.sourceWallet.balance=this.sourceWallet.tokenUnits.length}else this.remainderWallet.balance=this.sourceWallet.balance+e,this.sourceWallet.balance=e;return this.addAtom(g.create({isotope:"V",wallet:this.sourceWallet,value:this.sourceWallet.balance})),this.addAtom(g.create({isotope:"V",wallet:this.remainderWallet,value:this.remainderWallet.balance,metaType:"walletBundle",metaId:this.remainderWallet.bundle})),this}initValue({recipientWallet:e,amount:t}){if(this.sourceWallet.balance-t<0)throw new Ae;return this.addAtom(g.create({isotope:"V",wallet:this.sourceWallet,value:-this.sourceWallet.balance})),this.addAtom(g.create({isotope:"V",wallet:e,value:t,metaType:"walletBundle",metaId:e.bundle})),this.addAtom(g.create({isotope:"V",wallet:this.remainderWallet,value:this.sourceWallet.balance-t,metaType:"walletBundle",metaId:this.remainderWallet.bundle})),this}initDepositBuffer({amount:e,tradeRates:t}){if(this.sourceWallet.balance-e<0)throw new Ae;const n=k.create({secret:this.secret,bundle:this.bundle,token:this.sourceWallet.token,batchId:this.sourceWallet.batchId});return n.tradeRates=t,this.addAtom(g.create({isotope:"V",wallet:this.sourceWallet,value:-this.sourceWallet.balance})),this.addAtom(g.create({isotope:"B",wallet:n,value:e,metaType:"walletBundle",metaId:this.sourceWallet.bundle})),this.addAtom(g.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,i]of Object.entries(e||{}))n+=i;if(this.sourceWallet.balance-n<0)throw new Ae;const s=new P;t&&s.setSigningWallet(t),this.addAtom(g.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 g({isotope:"V",token:this.sourceWallet.token,value:i,batchId:this.sourceWallet.batchId?Oe({}):null,metaType:"walletBundle",metaId:r}));return this.addAtom(g.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(g.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 a of n)r.push(a instanceof $e?a:$e.toObject(a));const i=new P({rule:JSON.stringify(r)});return i.addPolicy(s),this.addAtom(g.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=g.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:ie(t.trim(),"Molecule::initIdentifierCreation")};return this.addAtom(g.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(g.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(g.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(g.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(g.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(g.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(d=>!(d instanceof g)).length!==0)throw new se;!t&&!this.bundle&&(this.bundle=e||ie(this.secret,"Molecule::sign")),this.molecularHash=g.hashAtoms({atoms:this.atoms});const s=this.atoms[0];let r=s.position;const i=R.get(s.aggregatedMeta(),"signingWallet");if(i&&(r=R.get(JSON.parse(i),"position")),!r)throw new Ut("Signing wallet must have a position!");const a=k.generateKey({secret:this.secret,token:s.token,position:s.position}),c=fe(a,128),u=this.normalizedHash();let l="";for(const d in c){let w=c[d];for(let $=0,E=8-u[d];$<E;$++)w=new O("SHAKE256","TEXT").update(w).getHash("HEX",{outputLen:512});l+=w}n&&(l=ct(l));const h=fe(l,Math.ceil(l.length/this.atoms.length));let p=null;for(let d=0,w=h.length;d<w;d++)this.atoms[d].otsFragment=h[d],p=this.atoms[d].position;return p}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 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 J({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,Array.isArray(r.atoms)&&(i.atoms=r.atoms.map((a,c)=>{try{return g.fromJSON(a)}catch(u){throw new Error(`Failed to reconstruct atom ${c}: ${u.message}`)}})),n&&(r.sourceWallet&&(i.sourceWallet=new k({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=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 k({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=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 Zn(this).verify(e)}normalizedHash(){return J.normalize(J.enumerate(this.molecularHash))}}const Ye=10**18;class de{static val(e){return Math.abs(e*Ye)<1?0:e}static cmp(e,t,n=!1){const s=de.val(e)*Ye,r=de.val(t)*Ye;return Math.abs(s-r)<1?0:s>r?1:-1}static equal(e,t){return de.cmp(e,t)===0}}class ve{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 ve(e);return n.setWallet(t),n}static restore(e,t){const n=new k({secret:t,token:"AUTH",position:e.wallet.position,characters:e.wallet.characters});return ve.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 ue extends M{constructor(e="GraphQL did not provide a valid response.",t=null,n=null){super(e,t,n),this.name="InvalidResponseException"}}class Ke extends M{constructor(e="Authorization token missing or invalid.",t=null,n=null){super(e,t,n),this.name="UnauthenticatedException"}}class W{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 ue;if(R.has(this.$__response,this.errorKey)){const s=R.get(this.$__response,this.errorKey);throw String(s).includes("Unauthenticated")?new Ke:new ue}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 Ke:new ue(`GraphQL Error: ${s}`)}this.init()}init(){}data(){if(!this.dataKey)return this.response();if(!this.response().data)throw new ue("Response has no data field");if(!R.has(this.response(),this.dataKey))throw new ue(`Missing expected field: ${this.dataKey}`);return R.get(this.response(),this.dataKey)}response(){return this.$__response}payload(){return null}query(){return this.$__query}status(){return null}success(){var e,t;return!((t=(e=this.$__response)==null?void 0:e.errors)!=null&&t.length)}error(){var e,t;return(t=(e=this.$__response)==null?void 0:e.errors)!=null&&t.length?this.$__response.errors[0].message||"Unknown error":null}reason(){return this.error()}toValidationResult(){var e;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:((e=this.$__response)==null?void 0:e.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){var n,s,r;const t=e?`[${e}]`:`[${this.constructor.name}]`;return this.success()?console.debug(`${t} Success:`,{payload:this.payload(),query:(s=(n=this.$__query)==null?void 0:n.constructor)==null?void 0:s.name,dataKey:this.dataKey}):console.debug(`${t} Failure:`,{error:this.reason(),errors:(r=this.$__response)==null?void 0:r.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 F{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 W({query:this,json:e})}createQuery({variables:e=null}){if(this.$__variables=this.compiledVariables(e),!this.uri())throw new te("Query::createQuery() - Node URI was not initialized for this client instance!");if(this.$__query===null)throw new te("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 W({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 Yn extends W{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 k({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=t.amount*1),e}}class es extends F{constructor(e,t){super(e,t),this.$__query=v.gql`query ($bundle: String!) {
4
+ ${this.stack}`}}class se extends T{constructor(e="The molecule does not contain atoms",t=null,n=null){super(e,t,n),this.name="AtomsMissingException"}}class re{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(re.isStructure(e[n])?re.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]=re.isStructure(e[s])?re.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 re.structure(this)}}class pn extends re{constructor({position:e=null,walletAddress:t=null,isotope:n=null,token:s=null,value:r=null,batchId:i=null,metaType:a=null,metaId:c=null,meta:u=null,index:l=null,createdAt:h=null,version:p=null}){super(),this.position=e,this.walletAddress=t,this.isotope=n,this.token=s,this.value=r,this.batchId=i,this.metaType=a,this.metaId=c,this.meta=u,this.index=l,this.createdAt=h,this.version=p}}const We={4:pn};class g{constructor({position:e=null,walletAddress:t=null,isotope:n=null,token:s=null,value:r=null,batchId:i=null,metaType:a=null,metaId:c=null,meta:u=null,otsFragment:l=null,index:h=null,version:p=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=a,this.metaId=c,this.meta=u?ne.normalizeMeta(u):[],this.index=h,this.otsFragment=l,this.createdAt=String(+new Date),p!==null&&Object.prototype.hasOwnProperty.call(We,p)&&(this.version=String(p))}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:a=null}){return i||(i=new H),i instanceof H||(i=new H(i)),t&&(i.setAtomWallet(t),a||(a=t.batchId)),new g({position:t?t.position:null,walletAddress:t?t.address:null,isotope:e,token:t?t.token:null,value:n,batchId:a,metaType:s,metaId:r,meta:i.get()})}static jsonToObject(e){const t=Object.assign(new g({}),JSON.parse(e)),n=Object.keys(new g({}));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 a=["position","walletAddress","isotope","token"];for(const c of a)if(!r[c])throw new Error(`Required field '${c}' is missing or empty`)}const i=new g({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 O("SHAKE256","TEXT"),s=g.sortAtoms(e);if(s.length===0)throw new se;if(s.map(r=>{if(!(r instanceof g))throw new se;return r}),s.every(r=>r.version&&Object.prototype.hasOwnProperty.call(We,r.version)))n.update(JSON.stringify(s.map(r=>We[r.version].create(r).view())));else{const r=String(e.length);let i=[];for(const a of s)i.push(r),i=i.concat(a.getHashableValues());for(const a of i)n.update(a)}switch(t){case"hex":return n.getHash("HEX",{outputLen:256});case"array":return n.getHash("ARRAYBUFFER",{outputLen:256});default:return pt(n.getHash("HEX",{outputLen:256}),16,17,"0123456789abcdef","0123456789abcdefg").padStart(64,"0")}}static jsonSerialization(e,t){if(!g.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 ne.aggregateMeta(this.meta)}getHashableValues(){const e=[];for(const t of g.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 Re(o=null,e=2048){if(o){const t=new O("SHAKE256","TEXT");return t.update(o),t.getHash("HEX",{outputLen:e*2})}else return Ee(e)}function ie(o,e=null){const t=new O("SHAKE256","TEXT");return t.update(o),t.getHash("HEX",{outputLen:256})}function Xe(o,e){const t=new O("SHAKE256","TEXT");return t.update(o),t.getHash("HEX",{outputLen:e})}function de({molecularHash:o=null,index:e=null}){return o!==null&&e!==null?ie(String(o)+String(e),"generateBatchId"):Ee(64)}class pe{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 pe(e.id,e.name,t)}static createFromDB(e){return new pe(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 Ze extends T{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 qe=BigInt(2**32-1),bt=BigInt(32);function fn(o,e=!1){return e?{h:Number(o&qe),l:Number(o>>bt&qe)}:{h:Number(o>>bt&qe)|0,l:Number(o&qe)|0}}function mn(o,e=!1){const t=o.length;let n=new Uint32Array(t),s=new Uint32Array(t);for(let r=0;r<t;r++){const{h:i,l:a}=fn(o[r],e);[n[r],s[r]]=[i,a]}return[n,s]}const yn=(o,e,t)=>o<<t|e>>>32-t,gn=(o,e,t)=>e<<t|o>>>32-t,bn=(o,e,t)=>e<<t-32|o>>>64-t,wn=(o,e,t)=>o<<t-32|e>>>64-t;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function kn(o){return o instanceof Uint8Array||ArrayBuffer.isView(o)&&o.constructor.name==="Uint8Array"}function wt(o,e=""){if(!Number.isSafeInteger(o)||o<0){const t=e&&`"${e}" `;throw new Error(`${t}expected integer >0, got ${o}`)}}function Q(o,e,t=""){const n=kn(o),s=o==null?void 0:o.length,r=e!==void 0;if(!n||r&&s!==e){const i=t&&`"${t}" `,a=r?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof o}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return o}function kt(o,e=!0){if(o.destroyed)throw new Error("Hash instance has been destroyed");if(e&&o.finished)throw new Error("Hash#digest() has already been called")}function Sn(o,e){Q(o,void 0,"digestInto() output");const t=e.outputLen;if(o.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function St(o){return new Uint32Array(o.buffer,o.byteOffset,Math.floor(o.byteLength/4))}function _t(...o){for(let e=0;e<o.length;e++)o[e].fill(0)}const _n=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function $n(o){return o<<24&4278190080|o<<8&16711680|o>>>8&65280|o>>>24&255}function An(o){for(let e=0;e<o.length;e++)o[e]=$n(o[e]);return o}const $t=_n?o=>o:An;function At(o,e={}){const t=(s,r)=>o(r).update(s).digest(),n=o(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=s=>o(s),Object.assign(t,e),Object.freeze(t)}function vn(o=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(o))}const Ue=o=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,o])}),In=BigInt(0),we=BigInt(1),xn=BigInt(2),Tn=BigInt(7),Mn=BigInt(256),Cn=BigInt(113),vt=[],It=[],xt=[];for(let o=0,e=we,t=1,n=0;o<24;o++){[t,n]=[n,(2*t+3*n)%5],vt.push(2*(5*n+t)),It.push((o+1)*(o+2)/2%64);let s=In;for(let r=0;r<7;r++)e=(e<<we^(e>>Tn)*Cn)%Mn,e&xn&&(s^=we<<(we<<BigInt(r))-we);xt.push(s)}const Tt=mn(xt,!0),En=Tt[0],On=Tt[1],Mt=(o,e,t)=>t>32?bn(o,e,t):yn(o,e,t),Ct=(o,e,t)=>t>32?wn(o,e,t):gn(o,e,t);function Wn(o,e=24){const t=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let i=0;i<10;i++)t[i]=o[i]^o[i+10]^o[i+20]^o[i+30]^o[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,c=(i+2)%10,u=t[c],l=t[c+1],h=Mt(u,l,1)^t[a],p=Ct(u,l,1)^t[a+1];for(let d=0;d<50;d+=10)o[i+d]^=h,o[i+d+1]^=p}let s=o[2],r=o[3];for(let i=0;i<24;i++){const a=It[i],c=Mt(s,r,a),u=Ct(s,r,a),l=vt[i];s=o[l],r=o[l+1],o[l]=c,o[l+1]=u}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)t[a]=o[i+a];for(let a=0;a<10;a++)o[i+a]^=~t[(a+2)%10]&t[(a+4)%10]}o[0]^=En[n],o[1]^=On[n]}_t(t)}class Be{constructor(e,t,n,s=!1,r=24){J(this,"state");J(this,"pos",0);J(this,"posOut",0);J(this,"finished",!1);J(this,"state32");J(this,"destroyed",!1);J(this,"blockLen");J(this,"suffix");J(this,"outputLen");J(this,"enableXOF",!1);J(this,"rounds");if(this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=s,this.rounds=r,wt(n,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=St(this.state)}clone(){return this._cloneInto()}keccak(){$t(this.state32),Wn(this.state32,this.rounds),$t(this.state32),this.posOut=0,this.pos=0}update(e){kt(this),Q(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 a=0;a<i;a++)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){kt(this,!1),Q(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 wt(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Sn(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,_t(this.state)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:s,rounds:r,enableXOF:i}=this;return e||(e=new Be(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 Et=(o,e,t,n={})=>At(()=>new Be(e,o,t),n),Rn=Et(6,136,32,Ue(8)),qn=Et(6,72,64,Ue(10)),Ot=(o,e,t,n={})=>At((s={})=>new Be(e,o,s.dkLen===void 0?t:s.dkLen,!0),n),Un=Ot(31,168,16,Ue(11)),Wt=Ot(31,136,32,Ue(12));function Ye(o){if(!Number.isSafeInteger(o)||o<0||o>4294967295)throw new Error("wrong u32 integer:"+o);return o}function Rt(o){return Ye(o),(o&o-1)===0&&o!==0}function qt(o,e){Ye(o);let t=0;for(let n=0;n<e;n++,o>>>=1)t=t<<1|o&1;return t}function Ut(o){return Ye(o),31-Math.clz32(o)}function Bt(o){const e=o.length;if(e<2||!Rt(e))throw new Error("n must be a power of 2 and greater than 1. Got "+e);const t=Ut(e);for(let n=0;n<e;n++){const s=qt(n,t);if(n<s){const r=o[n];o[n]=o[s],o[s]=r}}return o}const Ht=(o,e)=>{const{N:t,roots:n,dit:s,invertButterflies:r=!1,skipStages:i=0,brp:a=!0}=e,c=Ut(t);if(!Rt(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&&a&&Bt(l);for(let h=0,p=1;h<c-i;h++){const d=s?h+1+i:c-h,b=1<<d,I=b>>1,C=t>>d;for(let f=0;f<t;f+=b)for(let y=0,w=p++;y<I;y++){const E=r?s?t-w:w:y*C,S=f+y,v=f+y+I,x=n[E],M=l[v],_=l[S];if(u){const N=o.mul(M,x);l[S]=o.add(_,N),l[v]=o.sub(_,N)}else r?(l[S]=o.add(M,_),l[v]=o.mul(o.sub(M,_),x)):(l[S]=o.add(_,M),l[v]=o.mul(o.sub(_,M),x))}}return!s&&a&&Bt(l),l}};/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */const Pt=vn;function et(o,e){if(o.length!==e.length)return!1;let t=0;for(let n=0;n<o.length;n++)t|=o[n]^e[n];return t===0}function Bn(o){return Uint8Array.from(o)}function He(o,...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,a=0;i<e.length;i++){const c=e[i],u=t(c),l=typeof c=="number"?s[i]:c.encode(s[i]);Q(l,u,o),r.set(l,a),typeof c!="number"&&l.fill(0),a+=u}return r},decode:s=>{Q(s,n,o);const r=[];for(const i of e){const a=t(i),c=s.subarray(0,a);r.push(typeof i=="number"?c:i.decode(c)),s=s.subarray(a)}return r}}}function tt(o,e){const t=e*o.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 a=o.encode(n[r]);s.set(a,i),a.fill(0),i+=a.length}return s},decode:n=>{Q(n,t);const s=[];for(let r=0;r<n.length;r+=o.bytesLen)s.push(o.decode(n.subarray(r,r+o.bytesLen)));return s}}}function X(...o){for(const e of o)if(Array.isArray(e))for(const t of e)t.fill(0);else e.fill(0)}function Kt(o){return(1<<o)-1}/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */const Hn=o=>{const{newPoly:e,N:t,Q:n,F:s,ROOT_OF_UNITY:r,brvBits:i}=o,a=(f,y=n)=>{const w=f%y|0;return(w>=0?w|0:y+w|0)|0},c=(f,y=n)=>{const w=a(f,y)|0;return(w>y>>1?w-y|0:w)|0};function u(){const f=e(t);for(let y=0;y<t;y++){const w=qt(y,i),E=BigInt(r)**BigInt(w)%BigInt(n);f[y]=Number(E)|0}return f}const l=u(),h={add:(f,y)=>a((f|0)+(y|0))|0,sub:(f,y)=>a((f|0)-(y|0))|0,mul:(f,y)=>a((f|0)*(y|0))|0,inv:f=>{throw new Error("not implemented")}},p={N:t,roots:l,invertButterflies:!0,skipStages:1,brp:!1},d=Ht(h,{dit:!1,...p}),b=Ht(h,{dit:!0,...p});return{mod:a,smod:c,nttZetas:l,NTT:{encode:f=>d(f),decode:f=>{b(f);for(let y=0;y<f.length;y++)f[y]=a(s*f[y]);return f}},bitsCoder:(f,y)=>{const w=Kt(f),E=f*(t/8);return{bytesLen:E,encode:S=>{const v=new Uint8Array(E);for(let x=0,M=0,_=0,N=0;x<S.length;x++)for(M|=(y.encode(S[x])&w)<<_,_+=f;_>=8;_-=8,M>>=8)v[N++]=M&Kt(_);return v},decode:S=>{const v=e(t);for(let x=0,M=0,_=0,N=0;x<S.length;x++)for(M|=S[x]<<_,_+=8;_>=f;_-=f,M>>=f)v[N++]=y.decode(M&w);return v}}}}},Pn=(o=>(e,t)=>{t||(t=o.blockLen);const n=new Uint8Array(e.length+2);n.set(e);const s=e.length,r=new Uint8Array(t);let i=o.create({}),a=0,c=0;return{stats:()=>({calls:a,xofs:c}),get:(u,l)=>(n[s+0]=u,n[s+1]=l,i.destroy(),i=o.create({}).update(n),a++,()=>(c++,i.xofInto(r))),clean:()=>{i.destroy(),X(r,n)}}})(Un);/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */const j=256,oe=3329,Kn=3303,Nn=17,{mod:ke,nttZetas:Fn,NTT:ae,bitsCoder:Ln}=Hn({N:j,Q:oe,F:Kn,ROOT_OF_UNITY:Nn,newPoly:o=>new Uint16Array(o),brvBits:7}),jn={768:{N:j,Q:oe,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192}},Qn=o=>{if(o>=12)return{encode:t=>t,decode:t=>t};const e=2**(o-1);return{encode:t=>((t<<o)+oe/2)/oe,decode:t=>t*oe+e>>>o}},Se=o=>Ln(o,Qn(o));function le(o,e){for(let t=0;t<j;t++)o[t]=ke(o[t]+e[t])}function Dn(o,e){for(let t=0;t<j;t++)o[t]=ke(o[t]-e[t])}function Vn(o,e,t,n,s){const r=ke(e*n*s+o*t),i=ke(o*n+e*t);return{c0:r,c1:i}}function Pe(o,e){for(let t=0;t<j/2;t++){let n=Fn[64+(t>>1)];t&1&&(n=-n);const{c0:s,c1:r}=Vn(o[2*t+0],o[2*t+1],e[2*t+0],e[2*t+1],n);o[2*t+0]=s,o[2*t+1]=r}return o}function Nt(o){const e=new Uint16Array(j);for(let t=0;t<j;){const n=o();if(n.length%3)throw new Error("SampleNTT: unaligned block");for(let s=0;t<j&&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<oe&&(e[t++]=r),t<j&&i<oe&&(e[t++]=i)}}return e}function _e(o,e,t,n){const s=o(n*j/4,e,t),r=new Uint16Array(j),i=St(s);let a=0;for(let c=0,u=0,l=0,h=0;c<i.length;c++){let p=i[c];for(let d=0;d<32;d++)l+=p&1,p>>=1,a+=1,a===n?(h=l,l=0):a===2*n&&(r[u++]=ke(h-l),l=0,a=0)}if(a)throw new Error(`sampleCBD: leftover bits: ${a}`);return r}const zn=o=>{const{K:e,PRF:t,XOF:n,HASH512:s,ETA1:r,ETA2:i,du:a,dv:c}=o,u=Se(1),l=Se(c),h=Se(a),p=He("publicKey",tt(Se(12),e),32),d=tt(Se(12),e),b=He("ciphertext",tt(h,e),l),I=He("seed",32,32);return{secretCoder:d,lengths:{secretKey:d.bytesLen,publicKey:p.bytesLen,cipherText:b.bytesLen},keygen:C=>{Q(C,32,"seed");const f=new Uint8Array(33);f.set(C),f[32]=e;const y=s(f),[w,E]=I.decode(y),S=[],v=[];for(let _=0;_<e;_++)S.push(ae.encode(_e(t,E,_,r)));const x=n(w);for(let _=0;_<e;_++){const N=ae.encode(_e(t,E,e+_,r));for(let U=0;U<e;U++){const ye=Nt(x.get(U,_));le(N,Pe(ye,S[U]))}v.push(N)}x.clean();const M={publicKey:p.encode([v,w]),secretKey:d.encode(S)};return X(w,E,S,v,f,y),M},encrypt:(C,f,y)=>{const[w,E]=p.decode(C),S=[];for(let U=0;U<e;U++)S.push(ae.encode(_e(t,y,U,r)));const v=n(E),x=new Uint16Array(j),M=[];for(let U=0;U<e;U++){const ye=_e(t,y,e+U,i),ut=new Uint16Array(j);for(let Je=0;Je<e;Je++){const fr=Nt(v.get(U,Je));le(ut,Pe(fr,S[Je]))}le(ye,ae.decode(ut)),M.push(ye),le(x,Pe(w[U],S[U])),X(ut)}v.clean();const _=_e(t,y,2*e,i);le(_,ae.decode(x));const N=u.decode(f);return le(N,_),X(w,S,x,_),b.encode([M,N])},decrypt:(C,f)=>{const[y,w]=b.decode(C),E=d.decode(f),S=new Uint16Array(j);for(let v=0;v<e;v++)le(S,Pe(E[v],ae.encode(y[v])));return Dn(w,ae.decode(S)),X(S,E,y),u.encode(w)}}};function Jn(o){const e=zn(o),{HASH256:t,HASH512:n,KDF:s}=o,{secretCoder:r,lengths:i}=e,a=He("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:a.bytesLen},keygen:(l=Pt(u))=>{Q(l,u,"seed");const{publicKey:h,secretKey:p}=e.keygen(l.subarray(0,32)),d=t(h),b=a.encode([p,h,d,l.subarray(32)]);return X(p,d),{publicKey:h,secretKey:b}},getPublicKey:l=>{const[h,p]=a.decode(l);return Uint8Array.from(p)},encapsulate:(l,h=Pt(c))=>{Q(l,i.publicKey,"publicKey"),Q(h,c,"message");const p=l.subarray(0,384*o.K),d=r.encode(r.decode(Bn(p)));if(!et(d,p))throw X(d),new Error("ML-KEM.encapsulate: wrong publicKey modulus");X(d);const b=n.create().update(h).update(t(l)).digest(),I=e.encrypt(l,h,b.subarray(32,64));return X(b.subarray(32)),{cipherText:I,sharedSecret:b.subarray(0,32)}},decapsulate:(l,h)=>{Q(h,a.bytesLen,"secretKey"),Q(l,i.cipherText,"cipherText");const p=a.bytesLen-96,d=p+32,b=t(h.subarray(p/2,d));if(!et(b,h.subarray(d,d+32)))throw new Error("invalid secretKey: hash check failed");const[I,C,f,y]=a.decode(h),w=e.decrypt(l,I),E=n.create().update(w).update(f).digest(),S=E.subarray(0,32),v=e.encrypt(C,w,E.subarray(32,64)),x=et(l,v),M=s.create({dkLen:32}).update(y).update(l).digest();return X(w,v,x?M:S),x?S:M}}}function Gn(o,e,t){return Wt.create({dkLen:o}).update(e).update(new Uint8Array([t])).digest()}const nt=Jn({...{HASH256:Rn,HASH512:qn,KDF:Wt,XOF:Pn,PRF:Gn},...jn[768]});class k{constructor({secret:e=null,bundle:t=null,token:n="USER",address:s=null,position:r=null,batchId:i=null,characters:a=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=a,e&&(this.bundle=this.bundle||ie(e,"Wallet::constructor"),this.position=this.position||k.generatePosition(),this.key=k.generateKey({secret:e,token:this.token,position:this.position}),this.address=this.address||k.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 Ze;return e&&!t&&(i=k.generatePosition(),t=ie(e,"Wallet::create")),new k({secret:e,bundle:t,token:n,position:i,batchId:s,characters:r})}static isBundleHash(e){return typeof e!="string"?!1:e.length===64&&Oe(e)}static getTokenUnits(e){const t=[];return e.forEach(n=>{t.push(pe.createFromDB(n))}),t}static generateKey({secret:e,token:t,position:n}){if(!e)throw new Ze("Wallet::generateKey() - Secret is required!");if(!n)throw new Ze("Wallet::generateKey() - Position is required!");const s=Oe(e)?e:Xe(e,1024),r=Oe(n)?n:Xe(n,256),a=BigInt(`0x${s}`)+BigInt(`0x${r}`),c=new O("SHAKE256","TEXT");c.update(a.toString(16)),t&&c.update(t);const u=new O("SHAKE256","TEXT");return u.update(c.getHash("HEX",{outputLen:8192})),u.getHash("HEX",{outputLen:8192})}static generateAddress(e){const t=ge(e,128),n=new O("SHAKE256","TEXT");for(const r in t){let i=t[r];for(let a=1;a<=16;a++){const c=new O("SHAKE256","TEXT");c.update(i),i=c.getHash("HEX",{outputLen:512})}n.update(i)}const s=new O("SHAKE256","TEXT");return s.update(n.getHash("HEX",{outputLen:8192})),s.getHash("HEX",{outputLen:256})}static generatePosition(e=64){return Ee(e,"abcdef0123456789")}initializeMLKEM(){const e=Re(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}=nt.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}createRemainder(e){const t=k.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:de({}))}async encryptMessage(e,t){const n=JSON.stringify(e),s=new TextEncoder().encode(n),r=this.deserializeKey(t),{cipherText:i,sharedSecret:a}=nt.encapsulate(r),c=await this.encryptWithSharedSecret(s,a);return{cipherText:this.serializeKey(i),encryptedMessage:this.serializeKey(c)}}async decryptMessage(e){const{cipherText:t,encryptedMessage:n}=e;let s;try{s=nt.decapsulate(this.deserializeKey(t),this.privkey)}catch(c){return console.error("Wallet::decryptMessage() - Decapsulation failed",c),console.info("Wallet::decryptMessage() - my public key",this.pubkey),null}let r;try{r=this.deserializeKey(n)}catch(c){return console.warn("Wallet::decryptMessage() - Deserialization failed",c),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(c){return console.warn("Wallet::decryptMessage() - Decryption failed",c),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}let a;try{a=new TextDecoder().decode(i)}catch(c){return console.warn("Wallet::decryptMessage() - Decoding failed",c),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}return JSON.parse(a)}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),a=new Uint8Array(n.length+i.byteLength);return a.set(n),a.set(new Uint8Array(i),n.length),a}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 $e extends T{constructor(e="There is an atom without an index",t=null,n=null){super(e,t,n),this.name="AtomIndexException"}}class Xn extends T{constructor(e="The molecular hash does not match",t=null,n=null){super(e,t,n),this.name="MolecularHashMismatchException"}}class Zn extends T{constructor(e="The molecular hash is missing",t=null,n=null){super(e,t,n),this.name="MolecularHashMissingException"}}class Ft extends T{constructor(e="",t=null,n=null){super(e,t,n),this.name="PolicyInvalidException"}}class Lt extends T{constructor(e="OTS malformed",t=null,n=null){super(e,t,n),this.name="SignatureMalformedException"}}class Yn extends T{constructor(e="One-time signature (OTS) does not match!",t=null,n=null){super(e,t,n),this.name="SignatureMismatchException"}}class ee extends T{constructor(e="Insufficient balance to make transfer",t=null,n=null){super(e,t,n),this.name="TransferBalanceException"}}class Ae extends T{constructor(e="Token transfer atoms are malformed",t=null,n=null){super(e,t,n),this.name="TransferMalformedException"}}class jt extends T{constructor(e="Token slugs for wallets in transfer do not match!",t=null,n=null){super(e,t,n),this.name="TransferMismatchedException"}}class Qt extends T{constructor(e="Invalid remainder provided",t=null,n=null){super(e,t,n),this.name="TransferRemainderException"}}class es extends T{constructor(e="Sender and recipient(s) cannot be the same",t=null,n=null){super(e,t,n),this.name="TransferToSelfException"}}class Ke extends T{constructor(e="Token transfer atoms are unbalanced",t=null,n=null){super(e,t,n),this.name="TransferUnbalancedException"}}class P extends T{constructor(e="Empty meta data.",t=null,n=null){super(e,t,n),this.name="MetaMissingException"}}class ce extends T{constructor(e="Wrong type of token for this isotope",t=null,n=null){super(e,t,n),this.name="WrongTokenTypeException"}}class Ne extends T{constructor(e="Incorrect BatchId",t=null,n=null){super(e,t,n),this.name="BatchIdException"}}class Dt{constructor({}){const e=arguments[0];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 Fe extends T{constructor(e="An incorrect argument!",t=null,n=null){super(e,t,n),this.name="RuleArgumentException"}}class te extends T{constructor(e="Code exception",t=null,n=null){super(e,t,n),this.name="CodeException"}}class ve{constructor({action:e,metaType:t=null,metaId:n=null,meta:s=null,address:r=null,token:i=null,amount:a=null,comparison:c=null}){if(s&&(this.meta=s),!e)throw new Fe('Callback structure violated, missing mandatory "action" parameter.');this.__metaId=n,this.__metaType=t,this.__action=e,this.__address=r,this.__token=i,this.__amount=a,this.__comparison=c}set comparison(e){this.__comparison=e}set amount(e){if(!hn(e))throw new te("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 Dt?e:Dt.toObject(e)}set metaType(e){this.__metaType=e}set metaId(e){this.__metaId=e}static toObject(e){const t=new ve({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 be(Object.keys(this.toJSON()),["action","metaId","metaType","meta"]).length===4&&this._is("meta")}isCollect(){return be(Object.keys(this.toJSON()),["action","address","token","amount","comparison"]).length===5&&this._is("collect")}isBuffer(){return be(Object.keys(this.toJSON()),["action","address","token","amount","comparison"]).length===5&&this._is("buffer")}isRemit(){return be(Object.keys(this.toJSON()),["action","token","amount"]).length===3&&this._is("remit")}isBurn(){return be(Object.keys(this.toJSON()),["action","token","amount","comparison"]).length===4&&this._is("burn")}_is(e){return this.__action.toLowerCase()===e.toLowerCase()}}class st{constructor({key:e,value:t,comparison:n}){if([e,t,n].some(s=>!s))throw new Fe("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 Ie{constructor({condition:e=[],callback:t=[]}){for(const n of e)if(!(n instanceof st))throw new Fe;for(const n of t)if(!(n instanceof ve))throw new Fe;this.__condition=e,this.__callback=t}set comparison(e){this.__condition.push(e instanceof st?e:st.toObject(e))}set callback(e){this.__callback.push(e instanceof ve?e:ve.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 Ie({});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 W{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],h=Number(l),p=Number.isInteger(h);(p?h:l in r)||(r[p?h:l]=s[u+1].match(/^\d+$/)?[]:{}),r=r[p?h:l]}const a=s[i],c=Number(a);return r[Number.isInteger(c)?c:a]=n,e}}class xe{constructor(e){if(e.molecularHash===null)throw new Zn;if(!e.atoms.length)throw new se;for(const t of e.atoms)if(t.index===null)throw new $e;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 Ne;for(const s of t)if(s.batchId===null)throw new Ne}return!0}throw new Ne}isotopeI(){for(const e of this.molecule.getIsotopes("I")){if(e.token!=="USER")throw new ce(`Check::isotopeI() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index===0)throw new $e(`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 ce(`Check::isotopeU() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index!==0)throw new $e(`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 ce(`Check::isotopeM() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);const n=ne.aggregateMeta(t.meta);for(const s of e){let r=n[s];if(r){r=JSON.parse(r);for(const[i,a]of Object.entries(r))if(!e.includes(i)){if(!Object.keys(n).includes(i))throw new Ft(`${i} is missing from the meta.`);for(const c of a)if(!k.isBundleHash(c)&&!["all","self"].includes(c))throw new Ft(`${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 ce(`Check::isotopeC() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index!==0)throw new $e(`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 ce(`Check::isotopeT() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index!==0)throw new $e(`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)Ie.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 ce(`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 ce(`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 Ae("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 Ke("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 Ae("Check::isotopeF() - F-isotope atom value is not a valid number!");if(s<0)throw new Ae("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 Ke("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 a=t[t.length-1];if(s.token!==a.token)throw new jt;if(a.value<0)throw new Ae;if(Number(s.value)+Number(a.value)!==0)throw new Ke;return!0}let r=0,i=0;for(const a in this.molecule.atoms)if(Object.prototype.hasOwnProperty.call(this.molecule.atoms,a)){const c=this.molecule.atoms[a];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 jt;if(a>0){if(i<0)throw new Ae;if(c.walletAddress===s.walletAddress)throw new es}r+=i}if(!n&&r!==0)throw new Ke;if(e){if(i=s.value*1,Number.isNaN(i))throw new TypeError('Invalid isotope "V" values');const a=Number(e.balance)+i;if(a<0)throw new ee;if(!n&&a!==r)throw new Qt}else if(i!==0)throw new Qt;return!0}molecularHash(){if(this.molecule.molecularHash!==g.hashAtoms({atoms:this.molecule.atoms}))throw new Xn;return!0}ots(){const e=this.molecule.normalizedHash();let t=this.molecule.atoms.map(p=>p.otsFragment).reduce((p,d)=>p+d);if(t.length!==2048&&(t=gt(t),t.length!==2048))throw new Lt;const n=ge(t,128);let s="";for(const p in n){let d=n[p];for(let b=0,I=8+e[p];b<I;b++)d=new O("SHAKE256","TEXT").update(d).getHash("HEX",{outputLen:512});s+=d}const r=new O("SHAKE256","TEXT");r.update(s);const i=r.getHash("HEX",{outputLen:8192}),a=new O("SHAKE256","TEXT");a.update(i);const c=a.getHash("HEX",{outputLen:256}),u=this.molecule.atoms[0];let l=u.walletAddress;const h=W.get(u.aggregatedMeta(),"signingWallet");if(h&&(l=W.get(JSON.parse(h),"address")),c!==l)throw new Yn;return!0}static fromServerData({molecularHash:e,bundleHash:t,cellSlug:n=null,status:s=null,createdAt:r=null,atoms:i=[]}){const a=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(([h,p])=>({key:h,value:p})))}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 D.fromJSON({molecularHash:e,bundle:t,cellSlug:n,status:s,createdAt:r,atoms:a})}static verifyFromServerData(e){try{const t=xe.fromServerData(e);return new xe(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 T{constructor(e="Insufficient balance for requested transfer",t=null,n=null){super(e,t,n),this.name="BalanceInsufficientException"}}class rt extends T{constructor(e="Amount cannot be negative!",t=null,n=null){super(e,t,n),this.name="NegativeAmountException"}}class D{constructor({secret:e=null,bundle:t=null,sourceWallet:n=null,remainderWallet:s=null,cellSlug:r=null,version:i=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.atoms=[],this.parentHashes=[],i!==null&&Object.prototype.hasOwnProperty.call(We,i)&&(this.version=String(i)),(s||n)&&(this.remainderWallet=s||k.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 D({}),JSON.parse(e)),n=Object.keys(new D({}));if(!Array.isArray(t.atoms))throw new se;for(const s in Object.keys(t.atoms)){t.atoms[s]=g.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=g.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 a=s[r];typeof t[a]<"u"&&(n[r]=t[a])}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 D.isotopeFilter(e,this.atoms)}generateIndex(){return D.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=g.sortAtoms(this.atoms),this}addContinuIdAtom(){(!this.remainderWallet||this.remainderWallet.token!=="USER")&&(this.remainderWallet=k.create({secret:this.secret,bundle:this.bundle}));const e={};return 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(g.create({isotope:"I",wallet:this.remainderWallet,metaType:"walletBundle",metaId:this.remainderWallet.bundle,meta:new H(e)})),this}addPolicyAtom({metaType:e,metaId:t,meta:n={},policy:s={}}){const r=new H(n);r.addPolicy(s);const i=k.create({secret:this.secret,bundle:this.sourceWallet.bundle,token:"USER"});return this.addAtom(g.create({wallet:i,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(g.create({isotope:"V",wallet:this.sourceWallet,value:-n})),this.addAtom(g.create({isotope:"F",wallet:t,value:1,metaType:"walletBundle",metaId:t.bundle})),this.addAtom(g.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 rt("Molecule::burnToken() - Amount to burn must be positive!");if(this.sourceWallet.balance-e<0)throw new fe;return this.addAtom(g.create({isotope:"V",wallet:this.sourceWallet,value:-e})),this.addAtom(g.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 rt("Molecule::replenishToken() - Amount to replenish must be positive!");if(t.length){t=k.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(g.create({isotope:"V",wallet:this.sourceWallet,value:Number(this.sourceWallet.balance)})),this.addAtom(g.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(g.create({isotope:"V",wallet:this.sourceWallet,value:-this.sourceWallet.balance})),this.addAtom(g.create({isotope:"V",wallet:e,value:t,metaType:"walletBundle",metaId:e.bundle})),this.addAtom(g.create({isotope:"V",wallet:this.remainderWallet,value:this.sourceWallet.balance-t,metaType:"walletBundle",metaId:this.remainderWallet.bundle})),this}addStackableTransfer({recipientWallet:e,amount:t}){if(t<=0)throw new rt("Molecule::addStackableTransfer() - Amount must be positive!");if(this.sourceWallet.balance-t<0)throw new fe;const n=this.sourceWallet.batchId||de({});return this.addAtom(g.create({isotope:"V",wallet:this.sourceWallet,value:-t,batchId:n})),this.addAtom(g.create({isotope:"V",wallet:e,value:t,metaType:"walletBundle",metaId:e.bundle,batchId:de({})})),this.addAtom(g.create({isotope:"V",wallet:this.remainderWallet,value:this.sourceWallet.balance-t,metaType:"walletBundle",metaId:this.remainderWallet.bundle,batchId:n})),this}initDepositBuffer({amount:e,tradeRates:t}){if(this.sourceWallet.balance-e<0)throw new fe;const n=k.create({secret:this.secret,bundle:this.bundle,token:this.sourceWallet.token,batchId:this.sourceWallet.batchId});return n.tradeRates=t,this.addAtom(g.create({isotope:"V",wallet:this.sourceWallet,value:-this.sourceWallet.balance})),this.addAtom(g.create({isotope:"B",wallet:n,value:e,metaType:"walletBundle",metaId:this.sourceWallet.bundle})),this.addAtom(g.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,i]of Object.entries(e||{}))n+=i;if(this.sourceWallet.balance-n<0)throw new fe;const s=new H;t&&s.setSigningWallet(t),this.addAtom(g.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 g({isotope:"V",token:this.sourceWallet.token,value:i,batchId:this.sourceWallet.batchId?de({}):null,metaType:"walletBundle",metaId:r}));return this.addAtom(g.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 H(n);return s.setMetaWallet(e),this.addAtom(g.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 a of n)r.push(a instanceof Ie?a:Ie.toObject(a));const i=new H({rule:JSON.stringify(r)});return i.addPolicy(s),this.addAtom(g.create({isotope:"R",wallet:this.sourceWallet,metaType:e,metaId:t,meta:i})),this.addContinuIdAtom(),this}initWalletCreation(e,t=null){t||(t=new H),t.setMetaWallet(e);const n=g.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 H().setShadowWalletClaim(!0);return this.initWalletCreation(e,t)}initIdentifierCreation({type:e,contact:t,code:n}){const s={code:n,hash:ie(t.trim(),"Molecule::initIdentifierCreation")};return this.addAtom(g.create({isotope:"C",wallet:this.sourceWallet,metaType:"identifier",metaId:e,meta:new H(s)})),this.addContinuIdAtom(),this}initMeta({meta:e,metaType:t,metaId:n,policy:s}){return this.addAtom(g.create({isotope:"M",wallet:this.sourceWallet,metaType:t,metaId:n,meta:new H(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(g.create({isotope:"P",wallet:this.sourceWallet,metaType:"walletBundle",metaId:this.bundle,meta:new H({peerHost:e})})),this.addContinuIdAtom(),this}initAppendRequest({metaType:e,metaId:t,action:n,meta:s={}}){return this.addAtom(g.create({isotope:"A",wallet:this.sourceWallet,metaType:e,metaId:t,meta:new H({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(g.create({isotope:"T",wallet:this.sourceWallet,value:t,metaType:n,metaId:s,meta:new H(r),batchId:i})),this.addContinuIdAtom(),this}initAuthorization({meta:e}){return this.addAtom(g.create({isotope:"U",wallet:this.sourceWallet,meta:new H(e)})),this.addContinuIdAtom(),this}sign({bundle:e=null,anonymous:t=!1,compressed:n=!0}){if(this.atoms.length===0||this.atoms.filter(d=>!(d instanceof g)).length!==0)throw new se;!t&&!this.bundle&&(this.bundle=e||ie(this.secret,"Molecule::sign")),this.molecularHash=g.hashAtoms({atoms:this.atoms});const s=this.atoms[0];let r=s.position;const i=W.get(s.aggregatedMeta(),"signingWallet");if(i&&(r=W.get(JSON.parse(i),"position")),!r)throw new Lt("Signing wallet must have a position!");const a=k.generateKey({secret:this.secret,token:s.token,position:s.position}),c=ge(a,128),u=this.normalizedHash();let l="";for(const d in c){let b=c[d];for(let I=0,C=8-u[d];I<C;I++)b=new O("SHAKE256","TEXT").update(b).getHash("HEX",{outputLen:512});l+=b}n&&(l=yt(l));const h=ge(l,Math.ceil(l.length/this.atoms.length));let p=null;for(let d=0,b=h.length;d<b;d++)this.atoms[d].otsFragment=h[d],p=this.atoms[d].position;return p}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 D({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((a,c)=>{try{return g.fromJSON(a)}catch(u){throw new Error(`Failed to reconstruct atom ${c}: ${u.message}`)}})),n&&(r.sourceWallet&&(i.sourceWallet=new k({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 k({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 xe(this).verify(e)}normalizedHash(){return D.normalize(D.enumerate(this.molecularHash))}}const it=10**18;class me{static val(e){return Math.abs(e*it)<1?0:e}static cmp(e,t,n=!1){const s=me.val(e)*it,r=me.val(t)*it;return Math.abs(s-r)<1?0:s>r?1:-1}static equal(e,t){return me.cmp(e,t)===0}}class Te{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 Te(e);return n.setWallet(t),n}static restore(e,t){const n=new k({secret:t,token:"AUTH",position:e.wallet.position,characters:e.wallet.characters});return Te.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 ue extends T{constructor(e="GraphQL did not provide a valid response.",t=null,n=null){super(e,t,n),this.name="InvalidResponseException"}}class Le extends T{constructor(e="Authorization token missing or invalid.",t=null,n=null){super(e,t,n),this.name="UnauthenticatedException"}}class R{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 ue;if(W.has(this.$__response,this.errorKey)){const s=W.get(this.$__response,this.errorKey);throw String(s).includes("Unauthenticated")?new Le:new ue}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 Le:new ue(`GraphQL Error: ${s}`)}this.init()}init(){}data(){if(!this.dataKey)return this.response();if(!this.response().data)throw new ue("Response has no data field");if(!W.has(this.response(),this.dataKey))throw new ue(`Missing expected field: ${this.dataKey}`);return W.get(this.response(),this.dataKey)}response(){return this.$__response}payload(){return null}query(){return this.$__query}status(){return null}success(){var e,t;return!((t=(e=this.$__response)==null?void 0:e.errors)!=null&&t.length)}error(){var e,t;return(t=(e=this.$__response)==null?void 0:e.errors)!=null&&t.length?this.$__response.errors[0].message||"Unknown error":null}reason(){return this.error()}toValidationResult(){var e;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:((e=this.$__response)==null?void 0:e.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){var n,s,r;const t=e?`[${e}]`:`[${this.constructor.name}]`;return this.success()?console.debug(`${t} Success:`,{payload:this.payload(),query:(s=(n=this.$__query)==null?void 0:n.constructor)==null?void 0:s.name,dataKey:this.dataKey}):console.debug(`${t} Failure:`,{error:this.reason(),errors:(r=this.$__response)==null?void 0:r.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 F{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 R({query:this,json:e})}createQuery({variables:e=null}){if(this.$__variables=this.compiledVariables(e),!this.uri())throw new te("Query::createQuery() - Node URI was not initialized for this client instance!");if(this.$__query===null)throw new te("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 R({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 ts extends R{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 k({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 ns extends F{constructor(e,t){super(e,t),this.$__query=A.gql`query ($bundle: String!) {
5
5
  ContinuId(bundle: $bundle) {
6
6
  address,
7
7
  bundleHash,
@@ -13,7 +13,7 @@ ${this.stack}`}}class se extends M{constructor(e="The molecule does not contain
13
13
  amount,
14
14
  createdAt
15
15
  }
16
- }`}createResponse(e){return new Yn({query:this,json:e})}}class ts extends W{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=ne.aggregateMeta(n.metas),t[n.bundleHash]=n}),t}}class ns extends F{constructor(e,t){super(e,t),this.$__query=v.gql`query( $bundleHashes: [ String! ] ) {
16
+ }`}createResponse(e){return new ts({query:this,json:e})}}class ss extends R{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=ne.aggregateMeta(n.metas),t[n.bundleHash]=n}),t}}class rs extends F{constructor(e,t){super(e,t),this.$__query=A.gql`query( $bundleHashes: [ String! ] ) {
17
17
  WalletBundle( bundleHashes: $bundleHashes ) {
18
18
  bundleHash,
19
19
  metas {
@@ -25,7 +25,7 @@ ${this.stack}`}}class se extends M{constructor(e="The molecule does not contain
25
25
  },
26
26
  createdAt
27
27
  }
28
- }`}createResponse(e){return new ts({query:this,json:e})}}class Le extends W{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=k.create({bundle:e.bundleHash,token:e.tokenSlug,batchId:e.batchId,characters:e.characters}):(n=new k({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(ye.createFromGraphQL(s));if(e.tradeRates.length)for(const s of e.tradeRates)n.tradeRates[s.tokenSlug]=s.amount;return n.balance=Number(e.amount),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(Le.toClientWallet({data:s,secret:e}));return n}payload(){return this.getWallets()}}class ss extends F{constructor(e,t){super(e,t),this.$__query=v.gql`query( $bundleHash: String, $tokenSlug: String ) {
28
+ }`}createResponse(e){return new ss({query:this,json:e})}}class je extends R{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=k.create({bundle:e.bundleHash,token:e.tokenSlug,batchId:e.batchId,characters:e.characters}):(n=new k({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(pe.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(je.toClientWallet({data:s,secret:e}));return n}payload(){return this.getWallets()}}class is extends F{constructor(e,t){super(e,t),this.$__query=A.gql`query( $bundleHash: String, $tokenSlug: String ) {
29
29
  Wallet( bundleHash: $bundleHash, tokenSlug: $tokenSlug ) {
30
30
  address,
31
31
  bundleHash,
@@ -52,7 +52,7 @@ ${this.stack}`}}class se extends M{constructor(e="The molecule does not contain
52
52
  amount
53
53
  }
54
54
  }
55
- }`}createResponse(e){return new Le({query:this,json:e})}}class rs extends W{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:Le.toClientWallet({data:e})}}class is extends F{constructor(e,t){super(e,t),this.$__query=v.gql`query( $address: String, $bundleHash: String, $type: String, $token: String, $position: String ) {
55
+ }`}createResponse(e){return new je({query:this,json:e})}}class os extends R{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:je.toClientWallet({data:e})}}class as extends F{constructor(e,t){super(e,t),this.$__query=A.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 se extends M{constructor(e="The molecule does not contain
74
74
  amount
75
75
  }
76
76
  }
77
- }`}createResponse(e){return new rs({query:this,json:e})}}class os extends W{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 Nt extends F{constructor(e,t){super(e,t),this.$__query=v.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 os({query:this,json:e})}}class ls extends R{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 Vt extends F{constructor(e,t){super(e,t),this.$__query=A.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 se 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:a=null,count:c=null,countBy:u=null,cellSlug:l=null}){const h={};return e&&(h[typeof e=="string"?"metaType":"metaTypes"]=e),t&&(h[typeof t=="string"?"metaId":"metaIds"]=t),n&&(h[typeof n=="string"?"key":"keys"]=n),s&&(h[typeof s=="string"?"value":"values"]=s),h.latest=r===!0,i&&(h.filter=i),a&&((typeof a.limit>"u"||a.limit===0)&&(a.limit="*"),h.queryArgs=a),c&&(h.count=c),u&&(h.countBy=u),l&&(h.cellSlug=l),h}createResponse(e){return new os({query:this,json:e})}}class xe extends F{constructor(e,t){super(e,t),this.$__query=v.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:a=null,count:c=null,countBy:u=null,cellSlug:l=null}){const h={};return e&&(h[typeof e=="string"?"metaType":"metaTypes"]=e),t&&(h[typeof t=="string"?"metaId":"metaIds"]=t),n&&(h[typeof n=="string"?"key":"keys"]=n),s&&(h[typeof s=="string"?"value":"values"]=s),h.latest=r===!0,i&&(h.filter=i),a&&((typeof a.limit>"u"||a.limit===0)&&(a.limit="*"),h.queryArgs=a),c&&(h.count=c),u&&(h.countBy=u),l&&(h.cellSlug=l),h}createResponse(e){return new ls({query:this,json:e})}}class Me extends F{constructor(e,t){super(e,t),this.$__query=A.gql`query( $batchId: String ) {
102
102
  Batch( batchId: $batchId ) {
103
- ${xe.getFields()},
103
+ ${Me.getFields()},
104
104
  children {
105
- ${xe.getFields()}
105
+ ${Me.getFields()}
106
106
  }
107
107
  }
108
108
  }`}static getFields(){return`batchId,
@@ -154,11 +154,11 @@ ${this.stack}`}}class se extends M{constructor(e="The molecule does not contain
154
154
  throughMetas {
155
155
  key,
156
156
  value
157
- }`}createResponse(e){const t=new W({query:this,json:e});return t.dataKey="data.Batch",t}}class as extends F{constructor(e,t){super(e,t),this.$__query=v.gql`query( $batchId: String ) {
157
+ }`}createResponse(e){const t=new R({query:this,json:e});return t.dataKey="data.Batch",t}}class cs extends F{constructor(e,t){super(e,t),this.$__query=A.gql`query( $batchId: String ) {
158
158
  BatchHistory( batchId: $batchId ) {
159
- ${xe.getFields()}
159
+ ${Me.getFields()}
160
160
  }
161
- }`}createResponse(e){const t=new W({query:this,json:e});return t.dataKey="data.BatchHistory",t}}class D extends W{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.ProposeMolecule"}),this.$__clientMolecule=e.molecule()}init(){const e=R.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 J({});return t.molecularHash=R.get(e,"molecularHash"),t.status=R.get(e,"status"),t.createdAt=R.get(e,"createdAt"),t}success(){return this.status()==="accepted"}status(){return R.get(this.data(),"status","rejected")}reason(){return R.get(this.data(),"reason","Invalid response from server")}payload(){return this.$__payload}}class et extends F{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 W({query:this,json:{data:null,errors:[{message:"Mutation was cancelled"}]}});throw s}}createQueryContext(){return{}}}class B extends et{constructor(e,t,n){super(e,t),this.$__molecule=n,this.$__remainderWallet=null,this.$__query=v.gql`mutation( $molecule: MoleculeInput! ) {
161
+ }`}createResponse(e){const t=new R({query:this,json:e});return t.dataKey="data.BatchHistory",t}}class V extends R{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.ProposeMolecule"}),this.$__clientMolecule=e.molecule()}init(){const e=W.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 D({});return t.molecularHash=W.get(e,"molecularHash"),t.status=W.get(e,"status"),t.createdAt=W.get(e,"createdAt"),t}success(){return this.status()==="accepted"}status(){return W.get(this.data(),"status","rejected")}reason(){return W.get(this.data(),"reason","Invalid response from server")}payload(){return this.$__payload}}class ot extends F{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 R({query:this,json:{data:null,errors:[{message:"Mutation was cancelled"}]}});throw s}}createQueryContext(){return{}}}class B extends ot{constructor(e,t,n){super(e,t),this.$__molecule=n,this.$__remainderWallet=null,this.$__query=A.gql`mutation( $molecule: MoleculeInput! ) {
162
162
  ProposeMolecule( molecule: $molecule ) {
163
163
  molecularHash,
164
164
  height,
@@ -171,13 +171,13 @@ ${this.stack}`}}class se 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 D({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 ls extends D{payloadKey(e){if(!R.has(this.payload(),e))throw new ue(`ResponseRequestAuthorization::payloadKey() - '${e}' key was not found in the payload!`);return R.get(this.payload(),e)}token(){return this.payloadKey("token")}time(){return this.payloadKey("time")}encrypt(){return this.payloadKey("encrypt")}pubKey(){return this.payloadKey("key")}}class cs extends B{fillMolecule({meta:e}){this.$__molecule.initAuthorization({meta:e}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new ls({query:this,json:e})}}class us extends D{}class hs 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 us({query:this,json:e})}}class ds extends D{}class ps 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 ds({query:this,json:e})}}class fs extends D{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 ms extends B{fillMolecule({recipientWallet:e,amount:t}){this.$__molecule.initValue({recipientWallet:e,amount:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}createResponse(e){return new fs({query:this,json:e})}}class ys extends D{}class gs 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 ys({query:this,json:e})}}class ws extends D{}class bs extends B{fillMolecule({token:e,batchId:t=null}){const n=k.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 ws({query:this,json:e})}}class ks extends D{}class _s 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 ks({query:this,json:e})}}class Ft extends D{}class jt extends B{fillMolecule({host:e}){this.$__molecule.initPeering({host:e}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Ft({query:this,json:e})}}class Qt extends D{}class Dt 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 Qt({query:this,json:e})}}class Ss extends D{}class $s extends B{fillMolecule(e){this.$__molecule.initWalletCreation(e),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Ss({query:this,json:e})}}class As extends W{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(!R.has(this.payload(),e))throw new ue(`ResponseAuthorizationGuest::payloadKey() - '${e}' key is not found in the payload!`);return R.get(this.payload(),e)}token(){return this.payloadKey("token")}time(){return this.payloadKey("time")}pubKey(){return this.payloadKey("key")}encrypt(){return this.payloadKey("encrypt")}}class vs extends et{constructor(e,t){super(e,t),this.$__query=v.gql`mutation( $cellSlug: String, $pubkey: String, $encrypt: Boolean ) {
174
+ }`}compiledVariables(e){return{...super.compiledVariables(e),molecule:this.molecule()}}createResponse(e){return new V({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 us extends V{payloadKey(e){if(!W.has(this.payload(),e))throw new ue(`ResponseRequestAuthorization::payloadKey() - '${e}' key was not found in the payload!`);return W.get(this.payload(),e)}token(){return this.payloadKey("token")}time(){return this.payloadKey("time")}encrypt(){return this.payloadKey("encrypt")}pubKey(){return this.payloadKey("key")}}class hs extends B{fillMolecule({meta:e}){this.$__molecule.initAuthorization({meta:e}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new us({query:this,json:e})}}class ds extends V{}class ps 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 ds({query:this,json:e})}}class fs extends V{}class ms 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 fs({query:this,json:e})}}class ys extends V{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 gs extends B{fillMolecule({recipientWallet:e,amount:t}){this.$__molecule.initValue({recipientWallet:e,amount:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}createResponse(e){return new ys({query:this,json:e})}}class bs extends V{}class ws 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 bs({query:this,json:e})}}class ks extends V{}class Ss extends B{fillMolecule({token:e,batchId:t=null}){const n=k.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 ks({query:this,json:e})}}class _s extends V{}class $s 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 _s({query:this,json:e})}}class zt extends V{}class Jt extends B{fillMolecule({host:e}){this.$__molecule.initPeering({host:e}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new zt({query:this,json:e})}}class Gt extends V{}class Xt 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 Gt({query:this,json:e})}}class As extends V{}class vs extends B{fillMolecule(e){this.$__molecule.initWalletCreation(e),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new As({query:this,json:e})}}class Is extends R{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(!W.has(this.payload(),e))throw new ue(`ResponseAuthorizationGuest::payloadKey() - '${e}' key is not found in the payload!`);return W.get(this.payload(),e)}token(){return this.payloadKey("token")}time(){return this.payloadKey("time")}pubKey(){return this.payloadKey("key")}encrypt(){return this.payloadKey("encrypt")}}class xs extends ot{constructor(e,t){super(e,t),this.$__query=A.gql`mutation( $cellSlug: String, $pubkey: String, $encrypt: Boolean ) {
175
175
  AccessToken( cellSlug: $cellSlug, pubkey: $pubkey, encrypt: $encrypt ) {
176
176
  token,
177
177
  pubkey,
178
178
  expiresAt
179
179
  }
180
- }`}createResponse(e){return new As({query:this,json:e})}}class Vt extends M{constructor(e="The shadow wallet does not exist",t=null,n=null){super(e,t,n),this.name="WalletShadowException"}}class xs 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 Ne 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 Fe{constructor(e){this.client=e,this.$__variables=null,this.$__subscribe=null}createSubscribe({variables:e=null}){if(this.$__variables=this.compiledVariables(e),!this.uri())throw new te("Subscribe::createSubscribe() - Node URI was not initialized for this client instance!");if(this.$__subscribe===null)throw new te("Subscribe::createSubscribe() - GraphQL subscription was not initialized!");return{query:this.$__subscribe,variables:this.variables(),fetchPolicy:"no-cache"}}async execute({variables:e=null,closure:t}){if(!t)throw new te(`${this.constructor.name}::execute() - closure parameter is required!`);return this.$__request=this.createSubscribe({variables:e}),this.client.subscribe(this.$__request,t)}compiledVariables(e=null){return e||{}}uri(){return this.client.getUri()}variables(){return this.$__variables}}class Is extends Fe{constructor(e){super(e),this.$__subscribe=v.gql`
180
+ }`}createResponse(e){return new Is({query:this,json:e})}}class Zt extends T{constructor(e="The shadow wallet does not exist",t=null,n=null){super(e,t,n),this.name="WalletShadowException"}}class Ts extends T{constructor(e="Stackable tokens with unit IDs cannot have decimal places!",t=null,n=null){super(e,t,n),this.name="StackableUnitDecimalsException"}}class Qe extends T{constructor(e="Stackable tokens with unit IDs cannot have an amount!",t=null,n=null){super(e,t,n),this.name="StackableUnitAmountException"}}class De{constructor(e){this.client=e,this.$__variables=null,this.$__subscribe=null}createSubscribe({variables:e=null}){if(this.$__variables=this.compiledVariables(e),!this.uri())throw new te("Subscribe::createSubscribe() - Node URI was not initialized for this client instance!");if(this.$__subscribe===null)throw new te("Subscribe::createSubscribe() - GraphQL subscription was not initialized!");return{query:this.$__subscribe,variables:this.variables(),fetchPolicy:"no-cache"}}async execute({variables:e=null,closure:t}){if(!t)throw new te(`${this.constructor.name}::execute() - closure parameter is required!`);return this.$__request=this.createSubscribe({variables:e}),this.client.subscribe(this.$__request,t)}compiledVariables(e=null){return e||{}}uri(){return this.client.getUri()}variables(){return this.$__variables}}class Ms extends De{constructor(e){super(e),this.$__subscribe=A.gql`
181
181
  subscription onCreateMolecule ( $bundle: String! ) {
182
182
  CreateMolecule( bundle: $bundle ) {
183
183
  molecularHash,
@@ -222,7 +222,7 @@ ${this.stack}`}}class se extends M{constructor(e="The molecule does not contain
222
222
  }
223
223
  }
224
224
  }
225
- `}}class Ms extends Fe{constructor(e){super(e),this.$__subscribe=v.gql`
225
+ `}}class Cs extends De{constructor(e){super(e),this.$__subscribe=A.gql`
226
226
  subscription onWalletStatus ( $bundle: String!, $token: String! ) {
227
227
  WalletStatus( bundle: $bundle, token: $token ) {
228
228
  bundle,
@@ -231,7 +231,7 @@ ${this.stack}`}}class se extends M{constructor(e="The molecule does not contain
231
231
  balance,
232
232
  }
233
233
  }
234
- `}}class Ts extends Fe{constructor(e){super(e),this.$__subscribe=v.gql`
234
+ `}}class Es extends De{constructor(e){super(e),this.$__subscribe=A.gql`
235
235
  subscription onActiveWallet ( $bundle: String! ) {
236
236
  ActiveWallet( bundle: $bundle ) {
237
237
  address,
@@ -269,7 +269,7 @@ ${this.stack}`}}class se extends M{constructor(e="The molecule does not contain
269
269
  }
270
270
  }
271
271
  }
272
- `}}class Cs extends Fe{constructor(e){super(e),this.$__subscribe=v.gql`
272
+ `}}class Os extends De{constructor(e){super(e),this.$__subscribe=A.gql`
273
273
  subscription onActiveUser ( $metaType: String!, $metaId: String! ) {
274
274
  ActiveUser( metaType: $metaType, metaId: $metaId ) {
275
275
  bundleHash,
@@ -279,7 +279,7 @@ ${this.stack}`}}class se extends M{constructor(e="The molecule does not contain
279
279
  createdAt,
280
280
  updatedAt
281
281
  }
282
- }`}}class Es extends W{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.ActiveSession"})}}class Os extends et{constructor(e,t){super(e,t),this.$__query=v.gql`mutation(
282
+ }`}}class Ws extends R{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.ActiveSession"})}}class Rs extends ot{constructor(e,t){super(e,t),this.$__query=A.gql`mutation(
283
283
  $bundleHash: String!,
284
284
  $metaType: String!,
285
285
  $metaId: String!,
@@ -307,7 +307,7 @@ ${this.stack}`}}class se extends M{constructor(e="The molecule does not contain
307
307
  createdAt,
308
308
  updatedAt
309
309
  }
310
- }`}createResponse(e){return new Es({query:this,json:e})}}class Rs extends W{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 Ws extends F{constructor(e,t){super(e,t),this.$__query=v.gql`query ActiveUserQuery ($bundleHash:String, $metaType: String, $metaId: String) {
310
+ }`}createResponse(e){return new Ws({query:this,json:e})}}class qs extends R{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 Us extends F{constructor(e,t){super(e,t),this.$__query=A.gql`query ActiveUserQuery ($bundleHash:String, $metaType: String, $metaId: String) {
311
311
  ActiveUser (bundleHash: $bundleHash, metaType: $metaType, metaId: $metaId) {
312
312
  bundleHash,
313
313
  metaType,
@@ -316,7 +316,7 @@ ${this.stack}`}}class se extends M{constructor(e="The molecule does not contain
316
316
  createdAt,
317
317
  updatedAt
318
318
  }
319
- }`}createResponse(e){return new Rs({query:this,json:e})}}class qs extends W{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.UserActivity"})}payload(){const e=JSON.parse(JSON.stringify(this.data()));if(e.instances)for(const t of e.instances)t.jsonData=JSON.parse(t.jsonData);return e}}class Us extends F{constructor(e,t){super(e,t),this.$__query=v.gql`query UserActivity (
319
+ }`}createResponse(e){return new qs({query:this,json:e})}}class Bs extends R{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.UserActivity"})}payload(){const e=JSON.parse(JSON.stringify(this.data()));if(e.instances)for(const t of e.instances)t.jsonData=JSON.parse(t.jsonData);return e}}class Hs extends F{constructor(e,t){super(e,t),this.$__query=A.gql`query UserActivity (
320
320
  $bundleHash:String,
321
321
  $metaType: String,
322
322
  $metaId: String,
@@ -389,7 +389,7 @@ ${this.stack}`}}class se extends M{constructor(e="The molecule does not contain
389
389
  }
390
390
  }
391
391
  }
392
- }`}createResponse(e){return new qs({query:this,json:e})}}class Bs extends F{constructor(e,t){super(e,t),this.$__query=v.gql`query( $slug: String, $slugs: [ String! ], $limit: Int, $order: String ) {
392
+ }`}createResponse(e){return new Bs({query:this,json:e})}}class Ps extends F{constructor(e,t){super(e,t),this.$__query=A.gql`query( $slug: String, $slugs: [ String! ], $limit: Int, $order: String ) {
393
393
  Token( slug: $slug, slugs: $slugs, limit: $limit, order: $order ) {
394
394
  slug,
395
395
  name,
@@ -399,7 +399,7 @@ ${this.stack}`}}class se extends M{constructor(e="The molecule does not contain
399
399
  amount,
400
400
  icon,
401
401
  }
402
- }`}createResponse(e){return new W({query:this,json:e,dataKey:"data.Token"})}}class zt extends M{constructor(e="Authorization attempt rejected by ledger.",t=null,n=null){super(e,t,n),this.name="AuthorizationRejectedException"}}class Ps extends W{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 Jt extends F{constructor(e,t){super(e,t),this.$__query=v.gql`query(
402
+ }`}createResponse(e){return new R({query:this,json:e,dataKey:"data.Token"})}}class Yt extends T{constructor(e="Authorization attempt rejected by ledger.",t=null,n=null){super(e,t,n),this.name="AuthorizationRejectedException"}}class Ks extends R{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 en extends F{constructor(e,t){super(e,t),this.$__query=A.gql`query(
403
403
  $molecularHashes: [String!],
404
404
  $bundleHashes: [String!],
405
405
  $positions:[String!],
@@ -455,7 +455,7 @@ ${this.stack}`}}class se extends M{constructor(e="The molecule does not contain
455
455
  total
456
456
  }
457
457
  }
458
- }`}static createVariables({molecularHashes:e,molecularHash:t,bundleHashes:n,bundleHash:s,positions:r,position:i,walletAddresses:a,walletAddress:c,isotopes:u,isotope:l,tokenSlugs:h,tokenSlug:p,cellSlugs:d,cellSlug:w,batchIds:$,batchId:E,values:m,value:y,metaTypes:b,metaType:C,metaIds:_,metaId:A,indexes:I,index:T,filter:S,latest:K,queryArgs:U}){return t&&(e=e||[],e.push(t)),s&&(n=n||[],n.push(s)),i&&(r=r||[],r.push(i)),c&&(a=a||[],a.push(c)),l&&(u=u||[],u.push(l)),p&&(h=h||[],h.push(p)),w&&(d=d||[],d.push(w)),E&&($=$||[],$.push(E)),y&&(m=m||[],m.push(y)),C&&(b=b||[],b.push(C)),A&&(_=_||[],_.push(A)),T&&(I=I||[],I.push(T)),{molecularHashes:e,bundleHashes:n,positions:r,walletAddresses:a,isotopes:u,tokenSlugs:h,cellSlugs:d,batchIds:$,values:m,metaTypes:b,metaIds:_,indexes:I,filter:S,latest:K,queryArgs:U}}createResponse(e){return new Ps({query:this,json:e})}}class Hs extends W{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 Ks extends F{constructor(e,t){super(e,t),this.$__query=v.gql`query( $metaType: String, $metaId: String, ) {
458
+ }`}static createVariables({molecularHashes:e,molecularHash:t,bundleHashes:n,bundleHash:s,positions:r,position:i,walletAddresses:a,walletAddress:c,isotopes:u,isotope:l,tokenSlugs:h,tokenSlug:p,cellSlugs:d,cellSlug:b,batchIds:I,batchId:C,values:f,value:y,metaTypes:w,metaType:E,metaIds:S,metaId:v,indexes:x,index:M,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&&(a=a||[],a.push(c)),l&&(u=u||[],u.push(l)),p&&(h=h||[],h.push(p)),b&&(d=d||[],d.push(b)),C&&(I=I||[],I.push(C)),y&&(f=f||[],f.push(y)),E&&(w=w||[],w.push(E)),v&&(S=S||[],S.push(v)),M&&(x=x||[],x.push(M)),{molecularHashes:e,bundleHashes:n,positions:r,walletAddresses:a,isotopes:u,tokenSlugs:h,cellSlugs:d,batchIds:I,values:f,metaTypes:w,metaIds:S,indexes:x,filter:_,latest:N,queryArgs:U}}createResponse(e){return new Ks({query:this,json:e})}}class Ns extends R{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 Fs extends F{constructor(e,t){super(e,t),this.$__query=A.gql`query( $metaType: String, $metaId: String, ) {
459
459
  Policy( metaType: $metaType, metaId: $metaId ) {
460
460
  molecularHash,
461
461
  position,
@@ -466,7 +466,7 @@ ${this.stack}`}}class se extends M{constructor(e="The molecule does not contain
466
466
  rule,
467
467
  createdAt
468
468
  }
469
- }`}createResponse(e){return new Hs({query:this,json:e})}}class Ls extends W{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 Gt extends F{constructor(e,t){super(e,t),this.$__query=v.gql`query ($metaTypes: [String!], $metaIds: [String!], $values: [String!], $keys: [String!], $latest: Boolean, $filter: [MetaFilter!], $queryArgs: QueryArgs, $countBy: String, $atomValues: [String!], $cellSlugs: [String!] ) {
469
+ }`}createResponse(e){return new Ns({query:this,json:e})}}class Ls extends R{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 tn extends F{constructor(e,t){super(e,t),this.$__query=A.gql`query ($metaTypes: [String!], $metaIds: [String!], $values: [String!], $keys: [String!], $latest: Boolean, $filter: [MetaFilter!], $queryArgs: QueryArgs, $countBy: String, $atomValues: [String!], $cellSlugs: [String!] ) {
470
470
  MetaTypeViaAtom(
471
471
  metaTypes: $metaTypes
472
472
  metaIds: $metaIds
@@ -499,7 +499,61 @@ ${this.stack}`}}class se extends M{constructor(e="The molecule does not contain
499
499
  total
500
500
  }
501
501
  }
502
- }`}static createVariables({metaType:e=null,metaId:t=null,key:n=null,value:s=null,keys:r=null,values:i=null,atomValues:a=null,latest:c=null,filter:u=null,queryArgs:l=null,countBy:h=null,cellSlug:p=null}){const d={};return a&&(d.atomValues=a),r&&(d.keys=r),i&&(d.values=i),e&&(d.metaTypes=typeof e=="string"?[e]:e),t&&(d.metaIds=typeof t=="string"?[t]:t),p&&(d.cellSlugs=typeof p=="string"?[p]:p),h&&(d.countBy=h),u&&(d.filter=u),n&&s&&(d.filter=d.filter||[],d.filter.push({key:n,value:s,comparison:"="})),d.latest=c===!0,l&&((typeof l.limit>"u"||l.limit===0)&&(l.limit="*"),d.queryArgs=l),d}createResponse(e){return new Ls({query:this,json:e})}}class Ns extends D{}class Fs 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 Ns({query:this,json:e})}}class js extends B{fillMolecule({amount:e,tradeRates:t}){this.$__molecule.initDepositBuffer({amount:e,tradeRates:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}}class Qs extends B{fillMolecule({recipients:e,signingWallet:t}){this.$__molecule.initWithdrawBuffer({recipients:e,signingWallet:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}}function Z(o,e,t,n){return new(t||(t=Promise))((function(s,r){function i(u){try{c(n.next(u))}catch(l){r(l)}}function a(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(h){h(l)}))).then(i,a)}c((n=n.apply(o,[])).next())}))}function Y(o,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:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(r[Symbol.iterator]=function(){return this}),r;function a(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(o,i)}catch(h){l=[6,h],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 q={exclude:[],include:[],logging:!0},Xt={},Ds={timeout:"true"},G=function(o,e){typeof window<"u"&&(Xt[o]=e)},Vs=function(){return Object.fromEntries(Object.entries(Xt).filter((function(o){var e,t=o[0];return!(!((e=q==null?void 0:q.exclude)===null||e===void 0)&&e.includes(t))})).filter((function(o){var e,t,n,s,r=o[0];return!((e=q==null?void 0:q.include)===null||e===void 0)&&e.some((function(i){return i.includes(".")}))?(t=q==null?void 0:q.include)===null||t===void 0?void 0:t.some((function(i){return i.startsWith(r)})):((n=q==null?void 0:q.include)===null||n===void 0?void 0:n.length)===0||((s=q==null?void 0:q.include)===null||s===void 0?void 0:s.includes(r))})).map((function(o){return[o[0],(0,o[1])()]})))};function je(o){return o^=o>>>16,o=Math.imul(o,2246822507),o^=o>>>13,o=Math.imul(o,3266489909),(o^=o>>>16)>>>0}var H=new Uint32Array([597399067,2869860233,951274213,2716044179]);function V(o,e){return o<<e|o>>>32-e}function tt(o,e){var t;if(e===void 0&&(e=0),e=e?0|e:0,typeof o=="string"&&(t=o,o=new TextEncoder().encode(t).buffer),!(o 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 a=r.byteLength/16|0,c=new Uint32Array(r,0,4*a),u=0;u<a;u++){var l=c.subarray(4*u,4*(u+1));l[0]=Math.imul(l[0],H[0]),l[0]=V(l[0],15),l[0]=Math.imul(l[0],H[1]),i[0]=i[0]^l[0],i[0]=V(i[0],19),i[0]=i[0]+i[1],i[0]=Math.imul(i[0],5)+1444728091,l[1]=Math.imul(l[1],H[1]),l[1]=V(l[1],16),l[1]=Math.imul(l[1],H[2]),i[1]=i[1]^l[1],i[1]=V(i[1],17),i[1]=i[1]+i[2],i[1]=Math.imul(i[1],5)+197830471,l[2]=Math.imul(l[2],H[2]),l[2]=V(l[2],17),l[2]=Math.imul(l[2],H[3]),i[2]=i[2]^l[2],i[2]=V(i[2],15),i[2]=i[2]+i[3],i[2]=Math.imul(i[2],5)+2530024501,l[3]=Math.imul(l[3],H[3]),l[3]=V(l[3],18),l[3]=Math.imul(l[3],H[0]),i[3]=i[3]^l[3],i[3]=V(i[3],13),i[3]=i[3]+i[0],i[3]=Math.imul(i[3],5)+850148119}})(o,n),(function(r,i){var a=r.byteLength/16|0,c=r.byteLength%16,u=new Uint32Array(4),l=new Uint8Array(r,16*a,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],H[3]),u[3]=V(u[3],18),u[3]=Math.imul(u[3],H[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],H[2]),u[2]=V(u[2],17),u[2]=Math.imul(u[2],H[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],H[1]),u[1]=V(u[1],16),u[1]=Math.imul(u[1],H[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],H[0]),u[0]=V(u[0],15),u[0]=Math.imul(u[0],H[1]),i[0]=i[0]^u[0]}})(o,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]=je(i[0]),i[1]=je(i[1]),i[2]=je(i[2]),i[3]=je(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})(o,n);var s=new Uint8Array(n.buffer);return Array.from(s).map((function(r){return r.toString(16).padStart(2,"0")})).join("")}function zs(o,e){return new Promise((function(t){setTimeout((function(){return t(e)}),o)}))}function Js(o,e,t){return Promise.all(o.map((function(n){return Promise.race([n,zs(e,t)])})))}var Gs="0.19.1";function Xs(){return Gs}function Zt(){return Z(this,void 0,void 0,(function(){var o,e,t,n,s;return Y(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),o=Vs(),e=Object.keys(o),[4,Js(Object.values(o),(q==null?void 0:q.timeout)||1e3,Ds)];case 1:return t=r.sent(),n=t.filter((function(i){return i!==void 0})),s={},n.forEach((function(i,a){s[e[a]]=i})),[2,Yt(s,q.exclude||[],q.include||[],"")];case 2:throw r.sent();case 3:return[2]}}))}))}function Yt(o,e,t,n){n===void 0&&(n="");for(var s={},r=function(u,l){var h=n+u+".";if(typeof l!="object"||Array.isArray(l)){var p=e.some((function($){return h.startsWith($)})),d=t.some((function($){return h.startsWith($)}));p&&!d||(s[u]=l)}else{var w=Yt(l,e,t,h);Object.keys(w).length>0&&(s[u]=w)}},i=0,a=Object.entries(o);i<a.length;i++){var c=a[i];r(c[0],c[1])}return s}function Zs(o){return Z(this,void 0,void 0,(function(){var e,t;return Y(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,Zt()];case 1:return e=n.sent(),t=tt(JSON.stringify(e)),Math.random()<.001&&q.logging&&(function(s,r){Z(this,void 0,void 0,(function(){var i,a;return Y(this,(function(c){switch(c.label){case 0:if(i="https://logging.thumbmarkjs.com/v1/log",a={thumbmark:s,components:r,version:Xs()},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(a)})];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 Ys(o){for(var e=0,t=0;t<o.length;++t)e+=Math.abs(o[t]);return e}function en(o,e,t){for(var n=[],s=0;s<o[0].data.length;s++){for(var r=[],i=0;i<o.length;i++)r.push(o[i].data[s]);n.push(er(r))}var a=new Uint8ClampedArray(n);return new ImageData(a,e,t)}function er(o){if(o.length===0)return 0;for(var e={},t=0,n=o;t<n.length;t++)e[r=n[t]]=(e[r]||0)+1;var s=o[0];for(var r in e)e[r]>e[s]&&(s=parseInt(r,10));return s}function Ie(){if(typeof navigator>"u")return{name:"unknown",version:"unknown"};for(var o=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=o.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 Z(this,void 0,void 0,(function(){return Y(this,(function(o){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,a=n.createDynamicsCompressor();a.threshold.value=-50,a.knee.value=40,a.ratio.value=12,a.attack.value=0,a.release.value=.2,r.connect(a),a.connect(n.destination),r.start(),n.oncomplete=function(c){i=c.renderedBuffer.getChannelData(0),e({sampleHash:Ys(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 tr=Ie().name!=="SamsungBrowser"?1:3,tn=280,nn=20;Ie().name!="Firefox"&&G("canvas",(function(){return document.createElement("canvas").getContext("2d"),new Promise((function(o){var e=Array.from({length:tr},(function(){return(function(){var t=document.createElement("canvas"),n=t.getContext("2d");if(!n)return new ImageData(1,1);t.width=tn,t.height=nn;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})()}));o({commonImageDataHash:tt(en(e,tn,nn).data.toString()).toString()})}))}));var nt,nr=["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"],sr=["monospace","sans-serif","serif"];function sn(o,e){if(!o)throw new Error("Canvas context not supported");return o.font,o.font="72px ".concat(e),o.measureText("WwMmLli0Oo").width}function rr(){var o,e=document.createElement("canvas"),t=(o=e.getContext("webgl"))!==null&&o!==void 0?o: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 a=(t.getParameter(i.UNMASKED_VENDOR_WEBGL)||"").toString(),c=(t.getParameter(i.UNMASKED_RENDERER_WEBGL)||"").toString();a&&(r.vendorUnmasked=a),c&&(r.rendererUnmasked=c)}}return r}catch{}return"undefined"}function ir(){var o=new Float32Array(1),e=new Uint8Array(o.buffer);return o[0]=1/0,o[0]=o[0]-o[0],e[3]}function or(o,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 a=r[0],c=1;return Object.keys(i).forEach((function(u){i[u]>c&&(a=u,c=i[u])})),a})(o.map((function(r){return n in r?r[n]:void 0})).filter((function(r){return r!==void 0})));s&&(t[n]=s)})),t}function ar(){var o=[],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&&o.push("".concat(t,": ").concat(n))}))})),o}function lr(){if(window.location.protocol==="https:"&&typeof window.ApplePaySession=="function")try{for(var o=window.ApplePaySession.supportsVersion,e=15;e>0;e--)if(o(e))return e}catch{return 0}return 0}Ie().name!="Firefox"&&G("fonts",(function(){var o=this;return new Promise((function(e,t){try{(function(n){var s;Z(this,void 0,void 0,(function(){var r,i,a;return Y(this,(function(c){switch(c.label){case 0:return document.body?[3,2]:[4,(u=50,new Promise((function(h){return setTimeout(h,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),!(a=r.contentDocument||((s=r.contentWindow)===null||s===void 0?void 0:s.document)))throw new Error("Iframe document is not accessible");return n({iframe:a}),setTimeout((function(){document.body.removeChild(r)}),0),[2]}var u,l}))}))})((function(n){var s=n.iframe;return Z(o,void 0,void 0,(function(){var r,i,a,c;return Y(this,(function(u){return r=s.createElement("canvas"),i=r.getContext("2d"),a=sr.map((function(l){return sn(i,l)})),c={},nr.forEach((function(l){var h=sn(i,l);a.includes(h)||(c[l]=h)})),e(c),[2]}))}))}))}catch{t({error:"unsupported"})}}))})),G("hardware",(function(){return new Promise((function(o,e){var t=navigator.deviceMemory!==void 0?navigator.deviceMemory:0,n=window.performance&&window.performance.memory?window.performance.memory:0;o({videocard:rr(),architecture:ir(),deviceMemory:t.toString()||"undefined",jsHeapSizeLimit:n.jsHeapSizeLimit||0})}))})),G("locales",(function(){return new Promise((function(o){o({languages:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone})}))})),G("permissions",(function(){return Z(this,void 0,void 0,(function(){var o;return Y(this,(function(e){return nt=(q==null?void 0:q.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"],o=Array.from({length:(q==null?void 0:q.retries)||3},(function(){return(function(){return Z(this,void 0,void 0,(function(){var t,n,s,r,i;return Y(this,(function(a){switch(a.label){case 0:t={},n=0,s=nt,a.label=1;case 1:if(!(n<s.length))return[3,6];r=s[n],a.label=2;case 2:return a.trys.push([2,4,,5]),[4,navigator.permissions.query({name:r})];case 3:return i=a.sent(),t[r]=i.state.toString(),[3,5];case 4:return a.sent(),[3,5];case 5:return n++,[3,1];case 6:return[2,t]}}))}))})()})),[2,Promise.all(o).then((function(t){return or(t,nt)}))]}))}))})),G("plugins",(function(){var o=[];if(navigator.plugins)for(var e=0;e<navigator.plugins.length;e++){var t=navigator.plugins[e];o.push([t.name,t.filename,t.description].join("|"))}return new Promise((function(n){n({plugins:o})}))})),G("screen",(function(){return new Promise((function(o){o({is_touchscreen:navigator.maxTouchPoints>0,maxTouchPoints:navigator.maxTouchPoints,colorDepth:screen.colorDepth,mediaMatches:ar()})}))})),G("system",(function(){return new Promise((function(o){var e=Ie();o({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:lr()})}))}));var L,cr=Ie().name!=="SamsungBrowser"?1:3,f=null;G("webgl",(function(){return Z(this,void 0,void 0,(function(){var o;return Y(this,(function(e){typeof document<"u"&&((L=document.createElement("canvas")).width=200,L.height=100,f=L.getContext("webgl"));try{if(!f)throw new Error("WebGL not supported");return o=Array.from({length:cr},(function(){return(function(){try{if(!f)throw new Error("WebGL not supported");var t=`
502
+ }`}static createVariables({metaType:e=null,metaId:t=null,key:n=null,value:s=null,keys:r=null,values:i=null,atomValues:a=null,latest:c=null,filter:u=null,queryArgs:l=null,countBy:h=null,cellSlug:p=null}){const d={};return a&&(d.atomValues=a),r&&(d.keys=r),i&&(d.values=i),e&&(d.metaTypes=typeof e=="string"?[e]:e),t&&(d.metaIds=typeof t=="string"?[t]:t),p&&(d.cellSlugs=typeof p=="string"?[p]:p),h&&(d.countBy=h),u&&(d.filter=u),n&&s&&(d.filter=d.filter||[],d.filter.push({key:n,value:s,comparison:"="})),d.latest=c===!0,l&&((typeof l.limit>"u"||l.limit===0)&&(l.limit="*"),d.queryArgs=l),d}createResponse(e){return new Ls({query:this,json:e})}}class Ve extends R{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 a of i)s.push({molecularHash:e.molecularHash,position:r.position,key:a.key,value:a.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=Ve.extractMetasFromMolecule(s.molecule,s.metaType,s.metaId)),{...s,metas:r}})),n.instanceCount&&(t.instanceCount=n.instanceCount),n.paginatorInfo&&(t.paginatorInfo=n.paginatorInfo),t}verifyIntegrity(){var s;const e=[],t=this.data();if(!t||t.length===0)return{verified:!0,molecules:e};const n=((s=t[t.length-1])==null?void 0:s.instances)||[];for(const r of n)r.molecule&&e.push(xe.verifyFromServerData(r.molecule));return{verified:e.length===0||e.every(r=>r.verified),molecules:e}}}class at extends F{constructor(e,t){super(e,t),this.$__query=A.gql`query ($metaTypes: [String!], $metaIds: [String!], $values: [String!], $keys: [String!], $latest: Boolean, $filter: [MetaFilter!], $queryArgs: QueryArgs, $countBy: String, $atomValues: [String!], $cellSlugs: [String!] ) {
503
+ MetaTypeViaAtom(
504
+ metaTypes: $metaTypes
505
+ metaIds: $metaIds
506
+ atomValues: $atomValues
507
+ cellSlugs: $cellSlugs
508
+ filter: $filter,
509
+ latest: $latest,
510
+ queryArgs: $queryArgs
511
+ countBy: $countBy
512
+ ) {
513
+ metaType,
514
+ instanceCount {
515
+ key,
516
+ value
517
+ },
518
+ instances {
519
+ metaType,
520
+ metaId,
521
+ createdAt,
522
+ metas( values: $values, keys: $keys ) {
523
+ molecularHash,
524
+ position,
525
+ key,
526
+ value,
527
+ createdAt
528
+ },
529
+ molecule {
530
+ molecularHash,
531
+ bundleHash,
532
+ cellSlug,
533
+ status,
534
+ createdAt,
535
+ atoms {
536
+ position,
537
+ walletAddress,
538
+ isotope,
539
+ tokenSlug,
540
+ value,
541
+ batchId,
542
+ metaType,
543
+ metaId,
544
+ index,
545
+ createdAt,
546
+ otsFragment,
547
+ metasJson
548
+ }
549
+ }
550
+ },
551
+ paginatorInfo {
552
+ currentPage,
553
+ total
554
+ }
555
+ }
556
+ }`}static createVariables({metaType:e=null,metaId:t=null,key:n=null,value:s=null,keys:r=null,values:i=null,atomValues:a=null,latest:c=null,filter:u=null,queryArgs:l=null,countBy:h=null,cellSlug:p=null}){const d={};return a&&(d.atomValues=a),r&&(d.keys=r),i&&(d.values=i),e&&(d.metaTypes=typeof e=="string"?[e]:e),t&&(d.metaIds=typeof t=="string"?[t]:t),p&&(d.cellSlugs=typeof p=="string"?[p]:p),h&&(d.countBy=h),u&&(d.filter=u),n&&s&&(d.filter=d.filter||[],d.filter.push({key:n,value:s,comparison:"="})),d.latest=c===!0,l&&((typeof l.limit>"u"||l.limit===0)&&(l.limit="*"),d.queryArgs=l),d}createResponse(e){return new Ve({query:this,json:e})}}class js extends V{}class Qs 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 js({query:this,json:e})}}class Ds extends B{fillMolecule({amount:e,tradeRates:t}){this.$__molecule.initDepositBuffer({amount:e,tradeRates:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}}class Vs extends B{fillMolecule({recipients:e,signingWallet:t}){this.$__molecule.initWithdrawBuffer({recipients:e,signingWallet:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}}function Z(o,e,t,n){return new(t||(t=Promise))((function(s,r){function i(u){try{c(n.next(u))}catch(l){r(l)}}function a(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(h){h(l)}))).then(i,a)}c((n=n.apply(o,[])).next())}))}function Y(o,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:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(r[Symbol.iterator]=function(){return this}),r;function a(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(o,i)}catch(h){l=[6,h],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 q={exclude:[],include:[],logging:!0},nn={},zs={timeout:"true"},G=function(o,e){typeof window<"u"&&(nn[o]=e)},Js=function(){return Object.fromEntries(Object.entries(nn).filter((function(o){var e,t=o[0];return!(!((e=q==null?void 0:q.exclude)===null||e===void 0)&&e.includes(t))})).filter((function(o){var e,t,n,s,r=o[0];return!((e=q==null?void 0:q.include)===null||e===void 0)&&e.some((function(i){return i.includes(".")}))?(t=q==null?void 0:q.include)===null||t===void 0?void 0:t.some((function(i){return i.startsWith(r)})):((n=q==null?void 0:q.include)===null||n===void 0?void 0:n.length)===0||((s=q==null?void 0:q.include)===null||s===void 0?void 0:s.includes(r))})).map((function(o){return[o[0],(0,o[1])()]})))};function ze(o){return o^=o>>>16,o=Math.imul(o,2246822507),o^=o>>>13,o=Math.imul(o,3266489909),(o^=o>>>16)>>>0}var K=new Uint32Array([597399067,2869860233,951274213,2716044179]);function z(o,e){return o<<e|o>>>32-e}function lt(o,e){var t;if(e===void 0&&(e=0),e=e?0|e:0,typeof o=="string"&&(t=o,o=new TextEncoder().encode(t).buffer),!(o 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 a=r.byteLength/16|0,c=new Uint32Array(r,0,4*a),u=0;u<a;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}})(o,n),(function(r,i){var a=r.byteLength/16|0,c=r.byteLength%16,u=new Uint32Array(4),l=new Uint8Array(r,16*a,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]}})(o,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]=ze(i[0]),i[1]=ze(i[1]),i[2]=ze(i[2]),i[3]=ze(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})(o,n);var s=new Uint8Array(n.buffer);return Array.from(s).map((function(r){return r.toString(16).padStart(2,"0")})).join("")}function Gs(o,e){return new Promise((function(t){setTimeout((function(){return t(e)}),o)}))}function Xs(o,e,t){return Promise.all(o.map((function(n){return Promise.race([n,Gs(e,t)])})))}var Zs="0.19.1";function Ys(){return Zs}function sn(){return Z(this,void 0,void 0,(function(){var o,e,t,n,s;return Y(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),o=Js(),e=Object.keys(o),[4,Xs(Object.values(o),(q==null?void 0:q.timeout)||1e3,zs)];case 1:return t=r.sent(),n=t.filter((function(i){return i!==void 0})),s={},n.forEach((function(i,a){s[e[a]]=i})),[2,rn(s,q.exclude||[],q.include||[],"")];case 2:throw r.sent();case 3:return[2]}}))}))}function rn(o,e,t,n){n===void 0&&(n="");for(var s={},r=function(u,l){var h=n+u+".";if(typeof l!="object"||Array.isArray(l)){var p=e.some((function(I){return h.startsWith(I)})),d=t.some((function(I){return h.startsWith(I)}));p&&!d||(s[u]=l)}else{var b=rn(l,e,t,h);Object.keys(b).length>0&&(s[u]=b)}},i=0,a=Object.entries(o);i<a.length;i++){var c=a[i];r(c[0],c[1])}return s}function er(o){return Z(this,void 0,void 0,(function(){var e,t;return Y(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,sn()];case 1:return e=n.sent(),t=lt(JSON.stringify(e)),Math.random()<.001&&q.logging&&(function(s,r){Z(this,void 0,void 0,(function(){var i,a;return Y(this,(function(c){switch(c.label){case 0:if(i="https://logging.thumbmarkjs.com/v1/log",a={thumbmark:s,components:r,version:Ys()},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(a)})];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 tr(o){for(var e=0,t=0;t<o.length;++t)e+=Math.abs(o[t]);return e}function on(o,e,t){for(var n=[],s=0;s<o[0].data.length;s++){for(var r=[],i=0;i<o.length;i++)r.push(o[i].data[s]);n.push(nr(r))}var a=new Uint8ClampedArray(n);return new ImageData(a,e,t)}function nr(o){if(o.length===0)return 0;for(var e={},t=0,n=o;t<n.length;t++)e[r=n[t]]=(e[r]||0)+1;var s=o[0];for(var r in e)e[r]>e[s]&&(s=parseInt(r,10));return s}function Ce(){if(typeof navigator>"u")return{name:"unknown",version:"unknown"};for(var o=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=o.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 Z(this,void 0,void 0,(function(){return Y(this,(function(o){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,a=n.createDynamicsCompressor();a.threshold.value=-50,a.knee.value=40,a.ratio.value=12,a.attack.value=0,a.release.value=.2,r.connect(a),a.connect(n.destination),r.start(),n.oncomplete=function(c){i=c.renderedBuffer.getChannelData(0),e({sampleHash:tr(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=Ce().name!=="SamsungBrowser"?1:3,an=280,ln=20;Ce().name!="Firefox"&&G("canvas",(function(){return document.createElement("canvas").getContext("2d"),new Promise((function(o){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=an,t.height=ln;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})()}));o({commonImageDataHash:lt(on(e,an,ln).data.toString()).toString()})}))}));var ct,rr=["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"],ir=["monospace","sans-serif","serif"];function cn(o,e){if(!o)throw new Error("Canvas context not supported");return o.font,o.font="72px ".concat(e),o.measureText("WwMmLli0Oo").width}function or(){var o,e=document.createElement("canvas"),t=(o=e.getContext("webgl"))!==null&&o!==void 0?o: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 a=(t.getParameter(i.UNMASKED_VENDOR_WEBGL)||"").toString(),c=(t.getParameter(i.UNMASKED_RENDERER_WEBGL)||"").toString();a&&(r.vendorUnmasked=a),c&&(r.rendererUnmasked=c)}}return r}catch{}return"undefined"}function ar(){var o=new Float32Array(1),e=new Uint8Array(o.buffer);return o[0]=1/0,o[0]=o[0]-o[0],e[3]}function lr(o,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 a=r[0],c=1;return Object.keys(i).forEach((function(u){i[u]>c&&(a=u,c=i[u])})),a})(o.map((function(r){return n in r?r[n]:void 0})).filter((function(r){return r!==void 0})));s&&(t[n]=s)})),t}function cr(){var o=[],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&&o.push("".concat(t,": ").concat(n))}))})),o}function ur(){if(window.location.protocol==="https:"&&typeof window.ApplePaySession=="function")try{for(var o=window.ApplePaySession.supportsVersion,e=15;e>0;e--)if(o(e))return e}catch{return 0}return 0}Ce().name!="Firefox"&&G("fonts",(function(){var o=this;return new Promise((function(e,t){try{(function(n){var s;Z(this,void 0,void 0,(function(){var r,i,a;return Y(this,(function(c){switch(c.label){case 0:return document.body?[3,2]:[4,(u=50,new Promise((function(h){return setTimeout(h,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),!(a=r.contentDocument||((s=r.contentWindow)===null||s===void 0?void 0:s.document)))throw new Error("Iframe document is not accessible");return n({iframe:a}),setTimeout((function(){document.body.removeChild(r)}),0),[2]}var u,l}))}))})((function(n){var s=n.iframe;return Z(o,void 0,void 0,(function(){var r,i,a,c;return Y(this,(function(u){return r=s.createElement("canvas"),i=r.getContext("2d"),a=ir.map((function(l){return cn(i,l)})),c={},rr.forEach((function(l){var h=cn(i,l);a.includes(h)||(c[l]=h)})),e(c),[2]}))}))}))}catch{t({error:"unsupported"})}}))})),G("hardware",(function(){return new Promise((function(o,e){var t=navigator.deviceMemory!==void 0?navigator.deviceMemory:0,n=window.performance&&window.performance.memory?window.performance.memory:0;o({videocard:or(),architecture:ar(),deviceMemory:t.toString()||"undefined",jsHeapSizeLimit:n.jsHeapSizeLimit||0})}))})),G("locales",(function(){return new Promise((function(o){o({languages:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone})}))})),G("permissions",(function(){return Z(this,void 0,void 0,(function(){var o;return Y(this,(function(e){return ct=(q==null?void 0:q.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"],o=Array.from({length:(q==null?void 0:q.retries)||3},(function(){return(function(){return Z(this,void 0,void 0,(function(){var t,n,s,r,i;return Y(this,(function(a){switch(a.label){case 0:t={},n=0,s=ct,a.label=1;case 1:if(!(n<s.length))return[3,6];r=s[n],a.label=2;case 2:return a.trys.push([2,4,,5]),[4,navigator.permissions.query({name:r})];case 3:return i=a.sent(),t[r]=i.state.toString(),[3,5];case 4:return a.sent(),[3,5];case 5:return n++,[3,1];case 6:return[2,t]}}))}))})()})),[2,Promise.all(o).then((function(t){return lr(t,ct)}))]}))}))})),G("plugins",(function(){var o=[];if(navigator.plugins)for(var e=0;e<navigator.plugins.length;e++){var t=navigator.plugins[e];o.push([t.name,t.filename,t.description].join("|"))}return new Promise((function(n){n({plugins:o})}))})),G("screen",(function(){return new Promise((function(o){o({is_touchscreen:navigator.maxTouchPoints>0,maxTouchPoints:navigator.maxTouchPoints,colorDepth:screen.colorDepth,mediaMatches:cr()})}))})),G("system",(function(){return new Promise((function(o){var e=Ce();o({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:ur()})}))}));var L,hr=Ce().name!=="SamsungBrowser"?1:3,m=null;G("webgl",(function(){return Z(this,void 0,void 0,(function(){var o;return Y(this,(function(e){typeof document<"u"&&((L=document.createElement("canvas")).width=200,L.height=100,m=L.getContext("webgl"));try{if(!m)throw new Error("WebGL not supported");return o=Array.from({length:hr},(function(){return(function(){try{if(!m)throw new Error("WebGL not supported");var t=`
503
557
  attribute vec2 position;
504
558
  void main() {
505
559
  gl_Position = vec4(position, 0.0, 1.0);
@@ -509,5 +563,5 @@ ${this.stack}`}}class se extends M{constructor(e="The molecule does not contain
509
563
  void main() {
510
564
  gl_FragColor = vec4(0.812, 0.195, 0.553, 0.921); // Set line color
511
565
  }
512
- `,s=f.createShader(f.VERTEX_SHADER),r=f.createShader(f.FRAGMENT_SHADER);if(!s||!r)throw new Error("Failed to create shaders");if(f.shaderSource(s,t),f.shaderSource(r,n),f.compileShader(s),!f.getShaderParameter(s,f.COMPILE_STATUS))throw new Error("Vertex shader compilation failed: "+f.getShaderInfoLog(s));if(f.compileShader(r),!f.getShaderParameter(r,f.COMPILE_STATUS))throw new Error("Fragment shader compilation failed: "+f.getShaderInfoLog(r));var i=f.createProgram();if(!i)throw new Error("Failed to create shader program");if(f.attachShader(i,s),f.attachShader(i,r),f.linkProgram(i),!f.getProgramParameter(i,f.LINK_STATUS))throw new Error("Shader program linking failed: "+f.getProgramInfoLog(i));f.useProgram(i);for(var a=137,c=new Float32Array(4*a),u=2*Math.PI/a,l=0;l<a;l++){var h=l*u;c[4*l]=0,c[4*l+1]=0,c[4*l+2]=Math.cos(h)*(L.width/2),c[4*l+3]=Math.sin(h)*(L.height/2)}var p=f.createBuffer();f.bindBuffer(f.ARRAY_BUFFER,p),f.bufferData(f.ARRAY_BUFFER,c,f.STATIC_DRAW);var d=f.getAttribLocation(i,"position");f.enableVertexAttribArray(d),f.vertexAttribPointer(d,2,f.FLOAT,!1,0,0),f.viewport(0,0,L.width,L.height),f.clearColor(0,0,0,1),f.clear(f.COLOR_BUFFER_BIT),f.drawArrays(f.LINES,0,2*a);var w=new Uint8ClampedArray(L.width*L.height*4);return f.readPixels(0,0,L.width,L.height,f.RGBA,f.UNSIGNED_BYTE,w),new ImageData(w,L.width,L.height)}catch{return new ImageData(1,1)}finally{f&&(f.bindBuffer(f.ARRAY_BUFFER,null),f.useProgram(null),f.viewport(0,0,f.drawingBufferWidth,f.drawingBufferHeight),f.clearColor(0,0,0,0))}})()})),[2,{commonImageHash:tt(en(o,L.width,L.height).data.toString()).toString()}]}catch{return[2,{webgl:"unsupported"}]}return[2]}))}))}));var he=function(o,e,t,n){for(var s=(t-e)/n,r=0,i=0;i<n;i++)r+=o(e+(i+.5)*s);return r*s};G("math",(function(){return Z(void 0,void 0,void 0,(function(){return Y(this,(function(o){return[2,{acos:Math.acos(.5),asin:he(Math.asin,-1,1,97),atan:he(Math.atan,-1,1,97),cos:he(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:he(Math.sin,-Math.PI,Math.PI,97),sinh:he(Math.sinh,-1.2857142857142858,.7777777777777778,97),sqrt:Math.sqrt(2),tan:he(Math.tan,0,2*Math.PI,97),tanh:he(Math.tanh,-1.2857142857142858,.7777777777777778,97)}]}))}))}));class ur{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=[v.cacheExchange,v.fetchExchange];if(t&&t.socketUri){const r=rn.createClient({url:t.socketUri,connectionParams:()=>({authToken:this.$__authToken})});s.push(v.subscriptionExchange({forwardSubscription:i=>({subscribe:a=>({unsubscribe:r.subscribe(i,a)})})}))}return v.createClient({url:e,exchanges:s,fetchOptions:()=>({headers:{"X-Auth-Token":this.$__authToken},signal:AbortSignal.timeout(6e4)})})}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})}async query(e){const{query:t,variables:n}=e,s=await this.$__client.query(t,n).toPromise();return this.formatResponse(s)}async mutate(e){const{mutation:t,variables:n}=e,s=await this.$__client.mutation(t,n).toPromise();return this.formatResponse(s)}subscribe(e,t){const{query:n,variables:s,operationName:r}=e,{unsubscribe:i}=rt.pipe(this.$__client.subscription(n,s),rt.map(a=>{t(this.formatResponse(a))})).subscribe(()=>{});return this.$__subscriptionManager.set(r,{unsubscribe: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 hr{constructor({uri:e,cellSlug:t=null,client:n=null,socket:s=null,serverSdkVersion:r=3,logging:i=!1}){this.initialize({uri:e,cellSlug:t,socket:s,client:n,serverSdkVersion:r,logging:i})}initialize({uri:e,cellSlug:t=null,socket:n=null,client:s=null,serverSdkVersion:r=3,logging:i=!1}){this.reset(),this.$__logging=i,this.$__authTokenObjects={},this.$__authInProcess=!1,this.abortControllers=new Map,this.setUri(e),t&&this.setCellSlug(t);for(const a in this.$__uris){const c=this.$__uris[a];this.$__authTokenObjects[c]=null}this.log("info",`KnishIOClient::initialize() - Initializing new Knish.IO client session for SDK version ${r}...`),this.$__client=s||new ur({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 te("KnishIOClient::subscribe() - Socket client not initialized!");return this.client()}getServerSdkVersion(){return this.$__serverSdkVersion}reset(){this.$__secret="",this.$__bundle="",this.remainderWallet=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)}}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...`),ie(e)}getSecret(){if(!this.hasSecret())throw new Ke("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 Ke("KnishIOClient::getBundle() - Unable to find a stored bundle! Have you set a secret?");return this.$__bundle}getFingerprint(){return Zs()}getFingerprintData(){return Zt()}async getSourceWallet(){let e=(await this.queryContinuId({bundle:this.getBundle()})).payload();return e?e.key=k.generateKey({secret:this.getSecret(),token:e.token,position:e.position}):e=new k({secret:this.getSecret()}),e}getRemainderWallet(){return this.remainderWallet}async createMolecule({secret:e=null,bundle:t=null,sourceWallet:n=null,remainderWallet:s=null}){return this.log("info","KnishIOClient::createMolecule() - Creating a new molecule..."),e=e||this.getSecret(),t=t||this.getBundle(),!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||k.create({secret:e,bundle:t,token:"USER",batchId:n.batchId,characters:n.characters}),new J({secret:e,sourceWallet:n,remainderWallet:this.getRemainderWallet(),cellSlug:this.getCellSlug(),version:this.getServerSdkVersion()})}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 te(`${this.constructor.name}::createMoleculeMutation() - This method only accepts MutationProposeMolecule!`);return this.lastMoleculeQuery=s,s}async executeQuery(e,t=null){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 n=new AbortController,s=JSON.stringify({query:e.$__query,variables:t});this.abortControllers.set(s,n);try{const r=await e.execute({variables:t,context:{fetchOptions:{signal:n.signal}}});return this.abortControllers.delete(s),r}catch(r){if(r.name==="AbortError")this.log("warn","Query was cancelled");else throw r}}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(is);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||de.cmp(s.balance,t)<0)throw new ee;if(!s.position||!s.address)throw new ee("Source wallet can not be a shadow wallet.");return s}async subscribeCreateMolecule({bundle:e,closure:t}){return await this.createSubscribe(Is).execute({variables:{bundle:e||this.getBundle()},closure:t})}subscribeWalletStatus({bundle:e,token:t,closure:n}){if(!t)throw new te(`${this.constructor.name}::subscribeWalletStatus() - Token parameter is required!`);return this.createSubscribe(Ms).execute({variables:{bundle:e||this.getBundle(),token:t},closure:n})}subscribeActiveWallet({bundle:e,closure:t}){return this.createSubscribe(Ts).execute({variables:{bundle:e||this.getBundle()},closure:t})}subscribeActiveSession({metaType:e,metaId:t,closure:n}){return this.createSubscribe(Cs).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:a=null,queryArgs:c=null,count:u=null,countBy:l=null,throughAtom:h=!0,values:p=null,keys:d=null,atomValues:w=null}){this.log("info",`KnishIOClient::queryMeta() - Querying metaType: ${e}, metaId: ${t}...`);let $,E;return h?($=this.createQuery(Gt),E=Gt.createVariables({metaType:e,metaId:t,key:n,value:s,latest:r,filter:a,queryArgs:c,countBy:l,values:p,keys:d,atomValues:w,cellSlug:this.getCellSlug()})):($=this.createQuery(Nt),E=Nt.createVariables({metaType:e,metaId:t,key:n,value:s,latest:r,filter:a,queryArgs:c,count:u,countBy:l,cellSlug:this.getCellSlug()})),this.executeQuery($,E)}async queryBatch({batchId:e}){this.log("info",`KnishIOClient::queryBatch() - Querying cascading meta instances for batchId: ${e}...`);const t=this.createQuery(xe);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(as);return await this.executeQuery(t,{batchId:e})}async queryAtom({molecularHashes:e,molecularHash:t,bundleHashes:n,bundleHash:s,positions:r,position:i,walletAddresses:a,walletAddress:c,isotopes:u,isotope:l,tokenSlugs:h,tokenSlug:p,cellSlugs:d,cellSlug:w,batchIds:$,batchId:E,values:m,value:y,metaTypes:b,metaType:C,metaIds:_,metaId:A,indexes:I,index:T,filter:S,latest:K,queryArgs:U={limit:15,offset:1}}){this.log("info","KnishIOClient::queryAtom() - Querying atom instances");const pe=this.createQuery(Jt);return await this.executeQuery(pe,Jt.createVariables({molecularHashes:e,molecularHash:t,bundleHashes:n,bundleHash:s,positions:r,position:i,walletAddresses:a,walletAddress:c,isotopes:u,isotope:l,tokenSlugs:h,tokenSlug:p,cellSlugs:d,cellSlug:w,batchIds:$,batchId:E,values:m,value:y,metaTypes:b,metaType:C,metaIds:_,metaId:A,indexes:I,index:T,filter:S,latest:K,queryArgs:U}))}async createWallet({token:e}){const t=new k({secret:this.getSecret(),token:e}),n=await this.createMoleculeMutation({mutationClass:$s});return n.fillMolecule(t),await this.executeQuery(n)}async queryActiveSession({bundleHash:e,metaType:t,metaId:n}){const s=this.createQuery(Ws);return await this.executeQuery(s,{bundleHash:e,metaType:t,metaId:n})}async queryUserActivity({bundleHash:e,metaType:t,metaId:n,ipAddress:s,browser:r,osCpu:i,resolution:a,timeZone:c,countBy:u,interval:l}){const h=this.createQuery(Us);return await this.executeQuery(h,{bundleHash:e,metaType:t,metaId:n,ipAddress:s,browser:r,osCpu:i,resolution:a,timeZone:c,countBy:u,interval:l})}async activeSession({bundle:e,metaType:t,metaId:n,ipAddress:s,browser:r,osCpu:i,resolution:a,timeZone:c,json:u={}}){const l=this.createQuery(Os);return await this.executeQuery(l,{bundleHash:e,metaType:t,metaId:n,ipAddress:s,browser:r,osCpu:i,resolution:a,timeZone:c,json:JSON.stringify(u)})}async createToken({token:e,amount:t=null,meta:n=null,batchId:s=null,units:r=[]}){const i=R.get(n||{},"fungibility");if(i==="stackable"&&(n.batchId=s||Oe({})),["nonfungible","stackable"].includes(i)&&r.length>0){if(R.get(n||{},"decimals")>0)throw new xs;if(t>0)throw new Ne;t=r.length,n.splittable=1,n.decimals=0,n.tokenUnits=JSON.stringify(r)}const a=new k({secret:this.getSecret(),bundle:this.getBundle(),token:e,batchId:s}),c=await this.createMoleculeMutation({mutationClass:hs});return c.fillMolecule({recipientWallet:a,amount:t,meta:n||{}}),await this.executeQuery(c)}async createRule({metaType:e,metaId:t,rule:n,policy:s={}}){const r=await this.createMoleculeMutation({mutationClass:Fs,molecule:await this.createMolecule({secret:this.getSecret(),sourceWallet:await this.getSourceWallet()})});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:_s,molecule:await this.createMolecule({secret:this.getSecret(),sourceWallet:await this.getSourceWallet()})}),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:jt,molecule:await this.createMolecule({secret:this.getSecret(),sourceWallet:await this.getSourceWallet()})});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:Dt,molecule:await this.createMolecule({secret:this.getSecret(),sourceWallet:await this.getSourceWallet()})});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:gs});return s.fillMolecule({type:e,contact:t,code:n}),await this.executeQuery(s)}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(Ks);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(ss);return this.executeQuery(s,{bundleHash:e||this.getBundle(),tokenSlug: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(ns);return this.executeQuery(s,{bundleHashes:e}).then(r=>n?r:r.payload())}async queryContinuId({bundle:e}){const t=this.createQuery(es);return this.executeQuery(t,{bundle:e})}async requestTokens({token:e,to:t,amount:n=null,units:s=[],meta:r=null,batchId:i=null}){let a,c;r=r||{};const u=this.createQuery(Bs),l=await this.executeQuery(u,{slug:e}),h=R.get(l.data(),"0.fungibility")==="stackable";if(!h&&i!==null)throw new Pe("Expected Batch ID = null for non-stackable tokens.");if(h&&i===null&&(i=Oe({})),s.length>0){if(n>0)throw new Ne;n=s.length,r.tokenUnits=JSON.stringify(s)}t?(Object.prototype.toString.call(t)==="[object String]"&&(k.isBundleHash(t)?(a="walletBundle",c=t):t=k.create({secret:t,token:e})),t instanceof k&&(a="wallet",r.position=t.position,r.bundle=t.bundle,c=t.address)):(a="walletBundle",c=this.getBundle());const p=await this.createMoleculeMutation({mutationClass:ps});return p.fillMolecule({token:e,amount:n,metaType:a,metaId:c,meta:r,batchId:i}),await this.executeQuery(p)}async claimShadowWallet({token:e,batchId:t=null,molecule:n=null}){const s=await this.createMoleculeMutation({mutationClass:bs,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 Vt;t.forEach(s=>{if(!s.isShadow())throw new Vt});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 Ne;n=s.length}if(i===null&&(i=await this.querySourceWallet({token:t,amount:n})),i===null||de.cmp(i.balance,n)<0)throw new ee;const a=k.create({bundle:e,token:t});r!==null?a.batchId=r:a.initBatchId({sourceWallet:i});const c=i.createRemainder(this.getSecret());i.splitUnits(s,c,a);const u=await this.createMolecule({sourceWallet:i,remainderWallet:c}),l=await this.createMoleculeMutation({mutationClass:ms,molecule:u});return l.fillMolecule({recipientWallet:a,amount:n}),await this.executeQuery(l)}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}),a=await this.createMoleculeMutation({mutationClass:js,molecule:i});return a.fillMolecule({amount:t,tradeRates:n}),await this.executeQuery(a)}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}),a=await this.createMoleculeMutation({mutationClass:Qs,molecule:i}),c={};return c[this.getBundle()]=t,a.fillMolecule({recipients:c,signingWallet:s}),await this.executeQuery(a)}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 Ne;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();const a=await this.createMoleculeMutation({mutationClass:B,molecule:i});return this.executeQuery(a)}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 ee("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 a=await this.createMoleculeMutation({mutationClass:B,molecule:i});return this.executeQuery(a)}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 ee("Source wallet is missing or invalid.");if(!r.tokenUnits||!r.tokenUnits.length)throw new ee("Source wallet does not have token units.");if(!s.length)throw new ee("Fused token unit list is empty.");const i=[];r.tokenUnits.forEach(h=>{i.push(h.id)}),s.forEach(h=>{if(!i.includes(h))throw new ee(`Fused token unit ID = ${h} does not found in the source wallet.`)});const a=k.create({bundle:e,token:t});a.initBatchId({sourceWallet:r});const c=r.createRemainder(this.getSecret());r.splitUnits(s,c),n.metas.fusedTokenUnits=r.getTokenUnitsData(),a.tokenUnits=[n];const u=await this.createMolecule({sourceWallet:r,remainderWallet:c});u.fuseToken(r.tokenUnits,a),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 k({secret:Ee(await this.getFingerprint()),token:"AUTH"}),s=await this.createQuery(vs),r={cellSlug:e,pubkey:n.pubkey,encrypt:t},i=await s.execute({variables:r});if(i.success()){const a=ve.create({token:i.token(),expiresAt:i.time(),pubkey:i.pubKey(),encrypt:i.encrypt()},n);this.setAuthToken(a)}else throw new zt(`KnishIOClient::requestGuestAuthToken() - Authorization attempt rejected by ledger. Reason: ${i.reason()}`);return i}async requestProfileAuthToken({secret:e,encrypt:t}){this.setSecret(e);const n=new k({secret:e,token:"AUTH"}),s=await this.createMolecule({secret:e,sourceWallet:n}),r=await this.createMoleculeMutation({mutationClass:cs,molecule:s});r.fillMolecule({meta:{encrypt:t?"true":"false"}});const i=await r.execute({});if(i.success()){const a=ve.create({token:i.token(),expiresAt:i.time(),pubkey:i.pubKey(),encrypt:i.encrypt()},n);this.setAuthToken(a)}else throw new zt(`KnishIOClient::requestProfileAuthToken() - Authorization attempt rejected by ledger. Reason: ${i.reason()}`);return i}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=Ee(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)}}}return x.Atom=g,x.KnishIOClient=hr,x.Meta=ne,x.Molecule=J,x.MutationAppendRequest=Dt,x.MutationPeering=jt,x.ResponseAppendRequest=Qt,x.ResponsePeering=Ft,x.Wallet=k,x.base64ToHex=ut,x.bufferToHexString=at,x.charsetBaseConvert=ot,x.chunkSubstr=fe,x.generateBundleHash=ie,x.generateSecret=Ee,x.hexStringToBuffer=lt,x.hexToBase64=ct,x.isHex=Te,x.randomString=Me,x.shake256=Ve,Object.defineProperty(x,Symbol.toStringTag,{value:"Module"}),x})({},jsSHA,UrqlCore,GraphQLWS,wonka);
566
+ `,s=m.createShader(m.VERTEX_SHADER),r=m.createShader(m.FRAGMENT_SHADER);if(!s||!r)throw new Error("Failed to create shaders");if(m.shaderSource(s,t),m.shaderSource(r,n),m.compileShader(s),!m.getShaderParameter(s,m.COMPILE_STATUS))throw new Error("Vertex shader compilation failed: "+m.getShaderInfoLog(s));if(m.compileShader(r),!m.getShaderParameter(r,m.COMPILE_STATUS))throw new Error("Fragment shader compilation failed: "+m.getShaderInfoLog(r));var i=m.createProgram();if(!i)throw new Error("Failed to create shader program");if(m.attachShader(i,s),m.attachShader(i,r),m.linkProgram(i),!m.getProgramParameter(i,m.LINK_STATUS))throw new Error("Shader program linking failed: "+m.getProgramInfoLog(i));m.useProgram(i);for(var a=137,c=new Float32Array(4*a),u=2*Math.PI/a,l=0;l<a;l++){var h=l*u;c[4*l]=0,c[4*l+1]=0,c[4*l+2]=Math.cos(h)*(L.width/2),c[4*l+3]=Math.sin(h)*(L.height/2)}var p=m.createBuffer();m.bindBuffer(m.ARRAY_BUFFER,p),m.bufferData(m.ARRAY_BUFFER,c,m.STATIC_DRAW);var d=m.getAttribLocation(i,"position");m.enableVertexAttribArray(d),m.vertexAttribPointer(d,2,m.FLOAT,!1,0,0),m.viewport(0,0,L.width,L.height),m.clearColor(0,0,0,1),m.clear(m.COLOR_BUFFER_BIT),m.drawArrays(m.LINES,0,2*a);var b=new Uint8ClampedArray(L.width*L.height*4);return m.readPixels(0,0,L.width,L.height,m.RGBA,m.UNSIGNED_BYTE,b),new ImageData(b,L.width,L.height)}catch{return new ImageData(1,1)}finally{m&&(m.bindBuffer(m.ARRAY_BUFFER,null),m.useProgram(null),m.viewport(0,0,m.drawingBufferWidth,m.drawingBufferHeight),m.clearColor(0,0,0,0))}})()})),[2,{commonImageHash:lt(on(o,L.width,L.height).data.toString()).toString()}]}catch{return[2,{webgl:"unsupported"}]}return[2]}))}))}));var he=function(o,e,t,n){for(var s=(t-e)/n,r=0,i=0;i<n;i++)r+=o(e+(i+.5)*s);return r*s};G("math",(function(){return Z(void 0,void 0,void 0,(function(){return Y(this,(function(o){return[2,{acos:Math.acos(.5),asin:he(Math.asin,-1,1,97),atan:he(Math.atan,-1,1,97),cos:he(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:he(Math.sin,-Math.PI,Math.PI,97),sinh:he(Math.sinh,-1.2857142857142858,.7777777777777778,97),sqrt:Math.sqrt(2),tan:he(Math.tan,0,2*Math.PI,97),tanh:he(Math.tanh,-1.2857142857142858,.7777777777777778,97)}]}))}))}));class dr{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=[A.cacheExchange,A.fetchExchange];if(t&&t.socketUri){const r=un.createClient({url:t.socketUri,connectionParams:()=>({authToken:this.$__authToken})});s.push(A.subscriptionExchange({forwardSubscription:i=>({subscribe:a=>({unsubscribe:r.subscribe(i,a)})})}))}return A.createClient({url:e,exchanges:s,fetchOptions:()=>({headers:{"X-Auth-Token":this.$__authToken},signal:AbortSignal.timeout(6e4)})})}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})}async query(e){const{query:t,variables:n}=e,s=await this.$__client.query(t,n).toPromise();return this.formatResponse(s)}async mutate(e){const{mutation:t,variables:n}=e,s=await this.$__client.mutation(t,n).toPromise();return this.formatResponse(s)}subscribe(e,t){const{query:n,variables:s,operationName:r}=e,{unsubscribe:i}=ht.pipe(this.$__client.subscription(n,s),ht.map(a=>{t(this.formatResponse(a))})).subscribe(()=>{});return this.$__subscriptionManager.set(r,{unsubscribe: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 pr{constructor({uri:e,cellSlug:t=null,client:n=null,socket:s=null,serverSdkVersion:r=3,logging:i=!1}){this.initialize({uri:e,cellSlug:t,socket:s,client:n,serverSdkVersion:r,logging:i})}initialize({uri:e,cellSlug:t=null,socket:n=null,client:s=null,serverSdkVersion:r=3,logging:i=!1}){this.reset(),this.$__logging=i,this.$__authTokenObjects={},this.$__authInProcess=!1,this.abortControllers=new Map,this.setUri(e),t&&this.setCellSlug(t);for(const a in this.$__uris){const c=this.$__uris[a];this.$__authTokenObjects[c]=null}this.log("info",`KnishIOClient::initialize() - Initializing new Knish.IO client session for SDK version ${r}...`),this.$__client=s||new dr({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 te("KnishIOClient::subscribe() - Socket client not initialized!");return this.client()}getServerSdkVersion(){return this.$__serverSdkVersion}reset(){this.$__secret="",this.$__bundle="",this.remainderWallet=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)}}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...`),ie(e)}getSecret(){if(!this.hasSecret())throw new Le("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 Le("KnishIOClient::getBundle() - Unable to find a stored bundle! Have you set a secret?");return this.$__bundle}getFingerprint(){return er()}getFingerprintData(){return sn()}async getSourceWallet(){let e=(await this.queryContinuId({bundle:this.getBundle()})).payload();return e?e.key=k.generateKey({secret:this.getSecret(),token:e.token,position:e.position}):e=new k({secret:this.getSecret()}),e}getRemainderWallet(){return this.remainderWallet}async createMolecule({secret:e=null,bundle:t=null,sourceWallet:n=null,remainderWallet:s=null}){return this.log("info","KnishIOClient::createMolecule() - Creating a new molecule..."),e=e||this.getSecret(),t=t||this.getBundle(),!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||k.create({secret:e,bundle:t,token:"USER",batchId:n.batchId,characters:n.characters}),new D({secret:e,sourceWallet:n,remainderWallet:this.getRemainderWallet(),cellSlug:this.getCellSlug(),version:this.getServerSdkVersion()})}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 te(`${this.constructor.name}::createMoleculeMutation() - This method only accepts MutationProposeMolecule!`);return this.lastMoleculeQuery=s,s}async executeQuery(e,t=null){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 n=new AbortController,s=JSON.stringify({query:e.$__query,variables:t});this.abortControllers.set(s,n);try{const r=await e.execute({variables:t,context:{fetchOptions:{signal:n.signal}}});return this.abortControllers.delete(s),r}catch(r){if(r.name==="AbortError")this.log("warn","Query was cancelled");else throw r}}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(as);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||me.cmp(s.balance,t)<0)throw new ee;if(!s.position||!s.address)throw new ee("Source wallet can not be a shadow wallet.");return s}async subscribeCreateMolecule({bundle:e,closure:t}){return await this.createSubscribe(Ms).execute({variables:{bundle:e||this.getBundle()},closure:t})}subscribeWalletStatus({bundle:e,token:t,closure:n}){if(!t)throw new te(`${this.constructor.name}::subscribeWalletStatus() - Token parameter is required!`);return this.createSubscribe(Cs).execute({variables:{bundle:e||this.getBundle(),token:t},closure:n})}subscribeActiveWallet({bundle:e,closure:t}){return this.createSubscribe(Es).execute({variables:{bundle:e||this.getBundle()},closure:t})}subscribeActiveSession({metaType:e,metaId:t,closure:n}){return this.createSubscribe(Os).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:a=null,queryArgs:c=null,count:u=null,countBy:l=null,throughAtom:h=!0,throughMolecule:p=!1,values:d=null,keys:b=null,atomValues:I=null}){this.log("info",`KnishIOClient::queryMeta() - Querying metaType: ${e}, metaId: ${t}...`);let C,f;return p?(C=this.createQuery(at),f=at.createVariables({metaType:e,metaId:t,key:n,value:s,latest:r,filter:a,queryArgs:c,countBy:l,values:d,keys:b,atomValues:I,cellSlug:this.getCellSlug()})):h?(C=this.createQuery(tn),f=tn.createVariables({metaType:e,metaId:t,key:n,value:s,latest:r,filter:a,queryArgs:c,countBy:l,values:d,keys:b,atomValues:I,cellSlug:this.getCellSlug()})):(C=this.createQuery(Vt),f=Vt.createVariables({metaType:e,metaId:t,key:n,value:s,latest:r,filter:a,queryArgs:c,count:u,countBy:l,cellSlug:this.getCellSlug()})),this.executeQuery(C,f)}async queryMetaVerified(e){const t=await this.queryMeta(e),n=t.payload();return n&&(n.integrity=t.verifyIntegrity()),t}async queryBatch({batchId:e}){this.log("info",`KnishIOClient::queryBatch() - Querying cascading meta instances for batchId: ${e}...`);const t=this.createQuery(Me);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(cs);return await this.executeQuery(t,{batchId:e})}async queryAtom({molecularHashes:e,molecularHash:t,bundleHashes:n,bundleHash:s,positions:r,position:i,walletAddresses:a,walletAddress:c,isotopes:u,isotope:l,tokenSlugs:h,tokenSlug:p,cellSlugs:d,cellSlug:b,batchIds:I,batchId:C,values:f,value:y,metaTypes:w,metaType:E,metaIds:S,metaId:v,indexes:x,index:M,filter:_,latest:N,queryArgs:U={limit:15,offset:1}}){this.log("info","KnishIOClient::queryAtom() - Querying atom instances");const ye=this.createQuery(en);return await this.executeQuery(ye,en.createVariables({molecularHashes:e,molecularHash:t,bundleHashes:n,bundleHash:s,positions:r,position:i,walletAddresses:a,walletAddress:c,isotopes:u,isotope:l,tokenSlugs:h,tokenSlug:p,cellSlugs:d,cellSlug:b,batchIds:I,batchId:C,values:f,value:y,metaTypes:w,metaType:E,metaIds:S,metaId:v,indexes:x,index:M,filter:_,latest:N,queryArgs:U}))}async createWallet({token:e}){const t=new k({secret:this.getSecret(),token:e}),n=await this.createMoleculeMutation({mutationClass:vs});return n.fillMolecule(t),await this.executeQuery(n)}async queryActiveSession({bundleHash:e,metaType:t,metaId:n}){const s=this.createQuery(Us);return await this.executeQuery(s,{bundleHash:e,metaType:t,metaId:n})}async queryUserActivity({bundleHash:e,metaType:t,metaId:n,ipAddress:s,browser:r,osCpu:i,resolution:a,timeZone:c,countBy:u,interval:l}){const h=this.createQuery(Hs);return await this.executeQuery(h,{bundleHash:e,metaType:t,metaId:n,ipAddress:s,browser:r,osCpu:i,resolution:a,timeZone:c,countBy:u,interval:l})}async activeSession({bundle:e,metaType:t,metaId:n,ipAddress:s,browser:r,osCpu:i,resolution:a,timeZone:c,json:u={}}){const l=this.createQuery(Rs);return await this.executeQuery(l,{bundleHash:e,metaType:t,metaId:n,ipAddress:s,browser:r,osCpu:i,resolution:a,timeZone:c,json:JSON.stringify(u)})}async createToken({token:e,amount:t=null,meta:n=null,batchId:s=null,units:r=[]}){const i=W.get(n||{},"fungibility");if(i==="stackable"&&(n.batchId=s||de({})),["nonfungible","stackable"].includes(i)&&r.length>0){if(W.get(n||{},"decimals")>0)throw new Ts;if(t>0)throw new Qe;t=r.length,n.splittable=1,n.decimals=0,n.tokenUnits=JSON.stringify(r)}const a=new k({secret:this.getSecret(),bundle:this.getBundle(),token:e,batchId:s}),c=await this.createMoleculeMutation({mutationClass:ps});return c.fillMolecule({recipientWallet:a,amount:t,meta:n||{}}),await this.executeQuery(c)}async createRule({metaType:e,metaId:t,rule:n,policy:s={}}){const r=await this.createMoleculeMutation({mutationClass:Qs,molecule:await this.createMolecule({secret:this.getSecret(),sourceWallet:await this.getSourceWallet()})});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:$s,molecule:await this.createMolecule({secret:this.getSecret(),sourceWallet:await this.getSourceWallet()})}),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:Jt,molecule:await this.createMolecule({secret:this.getSecret(),sourceWallet:await this.getSourceWallet()})});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:Xt,molecule:await this.createMolecule({secret:this.getSecret(),sourceWallet:await this.getSourceWallet()})});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:ws});return s.fillMolecule({type:e,contact:t,code:n}),await this.executeQuery(s)}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(Fs);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(is);return this.executeQuery(s,{bundleHash:e||this.getBundle(),tokenSlug: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(rs);return this.executeQuery(s,{bundleHashes:e}).then(r=>n?r:r.payload())}async queryContinuId({bundle:e}){const t=this.createQuery(ns);return this.executeQuery(t,{bundle:e})}async requestTokens({token:e,to:t,amount:n=null,units:s=[],meta:r=null,batchId:i=null}){let a,c;r=r||{};const u=this.createQuery(Ps),l=await this.executeQuery(u,{slug:e}),h=W.get(l.data(),"0.fungibility")==="stackable";if(!h&&i!==null)throw new Ne("Expected Batch ID = null for non-stackable tokens.");if(h&&i===null&&(i=de({})),s.length>0){if(n>0)throw new Qe;n=s.length,r.tokenUnits=JSON.stringify(s)}t?(Object.prototype.toString.call(t)==="[object String]"&&(k.isBundleHash(t)?(a="walletBundle",c=t):t=k.create({secret:t,token:e})),t instanceof k&&(a="wallet",r.position=t.position,r.bundle=t.bundle,c=t.address)):(a="walletBundle",c=this.getBundle());const p=await this.createMoleculeMutation({mutationClass:ms});return p.fillMolecule({token:e,amount:n,metaType:a,metaId:c,meta:r,batchId:i}),await this.executeQuery(p)}async claimShadowWallet({token:e,batchId:t=null,molecule:n=null}){const s=await this.createMoleculeMutation({mutationClass:Ss,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 Zt;t.forEach(s=>{if(!s.isShadow())throw new Zt});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 Qe;n=s.length}if(i===null&&(i=await this.querySourceWallet({token:t,amount:n})),i===null||me.cmp(i.balance,n)<0)throw new ee;const a=k.create({bundle:e,token:t});r!==null?a.batchId=r:a.initBatchId({sourceWallet:i});const c=i.createRemainder(this.getSecret());i.splitUnits(s,c,a);const u=await this.createMolecule({sourceWallet:i,remainderWallet:c}),l=await this.createMoleculeMutation({mutationClass:gs,molecule:u});return l.fillMolecule({recipientWallet:a,amount:n}),await this.executeQuery(l)}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}),a=await this.createMoleculeMutation({mutationClass:Ds,molecule:i});return a.fillMolecule({amount:t,tradeRates:n}),await this.executeQuery(a)}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}),a=await this.createMoleculeMutation({mutationClass:Vs,molecule:i}),c={};return c[this.getBundle()]=t,a.fillMolecule({recipients:c,signingWallet:s}),await this.executeQuery(a)}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 Qe;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();const a=await this.createMoleculeMutation({mutationClass:B,molecule:i});return this.executeQuery(a)}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 ee("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 a=await this.createMoleculeMutation({mutationClass:B,molecule:i});return this.executeQuery(a)}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 ee("Source wallet is missing or invalid.");if(!r.tokenUnits||!r.tokenUnits.length)throw new ee("Source wallet does not have token units.");if(!s.length)throw new ee("Fused token unit list is empty.");const i=[];r.tokenUnits.forEach(h=>{i.push(h.id)}),s.forEach(h=>{if(!i.includes(h))throw new ee(`Fused token unit ID = ${h} does not found in the source wallet.`)});const a=k.create({bundle:e,token:t});a.initBatchId({sourceWallet:r});const c=r.createRemainder(this.getSecret());r.splitUnits(s,c),typeof n=="string"&&(n=new pe(n,n,{})),n.metas.fusedTokenUnits=r.getTokenUnitsData(),a.tokenUnits=[n];const u=await this.createMolecule({sourceWallet:r,remainderWallet:c});u.fuseToken(r.tokenUnits,a),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 k({secret:Re(await this.getFingerprint()),token:"AUTH"}),s=await this.createQuery(xs),r={cellSlug:e,pubkey:n.pubkey,encrypt:t},i=await s.execute({variables:r});if(i.success()){const a=Te.create({token:i.token(),expiresAt:i.time(),pubkey:i.pubKey(),encrypt:i.encrypt()},n);this.setAuthToken(a)}else throw new Yt(`KnishIOClient::requestGuestAuthToken() - Authorization attempt rejected by ledger. Reason: ${i.reason()}`);return i}async requestProfileAuthToken({secret:e,encrypt:t}){this.setSecret(e);const n=new k({secret:e,token:"AUTH"}),s=await this.createMolecule({secret:e,sourceWallet:n}),r=await this.createMoleculeMutation({mutationClass:hs,molecule:s});r.fillMolecule({meta:{encrypt:t?"true":"false"}});const i=await r.execute({});if(i.success()){const a=Te.create({token:i.token(),expiresAt:i.time(),pubkey:i.pubKey(),encrypt:i.encrypt()},n);this.setAuthToken(a)}else throw new Yt(`KnishIOClient::requestProfileAuthToken() - Authorization attempt rejected by ledger. Reason: ${i.reason()}`);return i}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=Re(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)}}}return $.Atom=g,$.KnishIOClient=pr,$.Meta=ne,$.Molecule=D,$.MutationAppendRequest=Xt,$.MutationPeering=Jt,$.QueryMetaTypeViaMolecule=at,$.ResponseAppendRequest=Gt,$.ResponseMetaTypeViaMolecule=Ve,$.ResponsePeering=zt,$.Wallet=k,$.base64ToHex=gt,$.bufferToHexString=ft,$.charsetBaseConvert=pt,$.chunkSubstr=ge,$.generateBundleHash=ie,$.generateSecret=Re,$.hexStringToBuffer=mt,$.hexToBase64=yt,$.isHex=Oe,$.randomString=Ee,$.shake256=Xe,Object.defineProperty($,Symbol.toStringTag,{value:"Module"}),$})({},jsSHA,UrqlCore,GraphQLWS,wonka);
513
567
  //# sourceMappingURL=client.iife.js.map