@wishknish/knishio-client-js 0.7.8 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.iife.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
var KnishIOClient=(function(h,q,A,hs,Ye){"use strict";var _r=Object.defineProperty;var $r=(h,q,A)=>q in h?_r(h,q,{enumerable:!0,configurable:!0,writable:!0,value:A}):h[q]=A;var J=(h,q,A)=>$r(h,typeof q!="symbol"?q+"":q,A);typeof self>"u"&&(global.self=global);class _t{static toHex(e,t){const n=(c,u)=>{const l=u?["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]:["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];return l[Math.floor(c/16)]+l[c%16]},s=Object.assign({grouping:0,rowlength:0,uppercase:!1},t||{});let r="",i=0,o=0;for(let c=0;c<e.length&&(r+=n(e[c],s.uppercase),c!==e.length-1);++c)s.grouping>0&&++i===s.grouping&&(i=0,s.rowlength>0&&++o===s.rowlength?(o=0,r+=`
|
|
2
2
|
`):r+=" ");return r}static toUint8Array(e){let t=e.toLowerCase().replace(/\s/g,"");t.length%2===1&&(t=`0${t}`);const n=new Uint8Array(Math.floor(t.length/2));let s=-1;for(let r=0;r<t.length;++r){const i=t[r],o=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"].indexOf(i);if(o===-1)throw Error("unexpected character");s===-1?s=16*o:(n[Math.floor(r/2)]=s+o,s=-1)}return n}}String.prototype.trim||(String.prototype.trim=function(){return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}),String.prototype.toCamelCase||(String.prototype.toCamelCase=function(){return this.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g,(a,e)=>e.toUpperCase())}),String.prototype.toSnakeCase||(String.prototype.toSnakeCase=function(){return this.replace(/[A-Z]/g,a=>`_${a.toLowerCase()}`)});function $e(a,e){const t=Math.ceil(a.length/e),n=[];for(let s=0,r=0;s<t;++s,r+=e)n[s]=a.substr(r,e);return n}function Ue(a=256,e="abcdef0123456789"){let t=new Uint8Array(a);return t=crypto.getRandomValues(t),t=t.map(n=>e.charCodeAt(n%e.length)),String.fromCharCode.apply(null,t)}function $t(a,e,t,n,s){if(n=n||"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~`!@#$%^&*()-_=+[{]}\\|;:'\",<.>/?¿¡",s=s||n,e>n.length||t>s.length)return console.warn("Strings::charsetBaseConvert() - Can't convert",a,"to base",t,"greater than symbol table length. src-table:",n.length,"dest-table:",s.length),!1;let i=BigInt(0);for(let c=0;c<a.length;c++)i=i*BigInt(e)+BigInt(n.indexOf(a.charAt(c)));let o="";for(;i>0;){const c=i%BigInt(t);o=s.charAt(Number(c))+o,i/=BigInt(t)}return o||"0"}function At(a){return _t.toHex(a,{})}function vt(a){return _t.toUint8Array(a)}function It(a){const e=vt(a);return btoa(String.fromCharCode.apply(null,e))}function Mt(a){const e=new Uint8Array(atob(a).split("").map(t=>t.charCodeAt(0)));return At(e)}function He(a){return/^[A-F0-9]+$/i.test(a)}function Tt(a){return(typeof a=="number"||typeof a=="string"&&a.trim()!=="")&&!isNaN(a)}let ie=class{static normalizeMeta(e){if(Array.isArray(e))return e.map(n=>({key:n.key,value:n.value==null?null:String(n.value)}));const t=[];for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)){const s=e[n];t.push({key:n,value:s==null?null:String(s)})}return t}static aggregateMeta(e){let t={};if(Array.isArray(e))for(const n of e)t[n.key]=n.value;else t=e;return t}};function Ct(a,e){return a.length?[a.slice(0,e)].concat(Ct(a.slice(e),e)):[]}function xt(a,e){let t,n,s;const r=[Array,Date,Number,String,Boolean],i=Object.prototype.toString;for(e=e||[],t=0;t<e.length;t+=2)a===e[t]&&(n=e[t+1]);if(!n&&a&&typeof a=="object"){for(n={},t=0;t<r.length;t++)i.call(a)===i.call(s=new r[t](a))&&(n=t?s:[]);e.push(a,n);for(t in a)e.hasOwnProperty.call(a,t)&&(n[t]=xt(a[t],e))}return n||a}function Et(...a){return[].concat(...a.map((e,t)=>{const n=a.slice(0);n.splice(t,1);const s=[...new Set([].concat(...n))];return e.filter(r=>!s.includes(r))}))}function ye(...a){return a.reduce((e,t)=>e.filter(n=>t.includes(n)))}class Pe{constructor(e={},t={}){this.policy=Pe.normalizePolicy(e),this.fillDefault(t)}static normalizePolicy(e={}){const t={};for(const[n,s]of Object.entries(e))if(s!==null&&["read","write"].includes(n)){t[n]={};for(const[r,i]of Object.entries(s))t[n][r]=i}return t}fillDefault(e={}){const t=Array.from(this.policy).filter(s=>s.action==="read"),n=Array.from(this.policy).filter(s=>s.action==="write");for(const[s,r]of Object.entries({read:t,write:n})){const i=r.map(o=>o.key);this.policy[s]||(this.policy[s]={});for(const o of Et(e,i))this.policy[s][o]||(this.policy[s][o]=s==="write"&&!["characters","pubkey"].includes(o)?["self"]:["all"])}}get(){return this.policy}toJson(){return JSON.stringify(this.get())}}class H{constructor(e=[]){this.meta=ie.normalizeMeta(e)}merge(e){return this.meta=Array.from(new Set([...this.meta,...ie.normalizeMeta(e)])),this}addContext(e=null){return this}setAtomWallet(e){const t={};return e.tokenUnits&&e.tokenUnits.length&&(t.tokenUnits=JSON.stringify(e.getTokenUnitsData())),e.tradeRates&&e.tradeRates.length&&(t.tradeRates=JSON.stringify(e.tradeRates)),Object.keys(t).length>0&&this.merge(t),this}setMetaWallet(e){return this.merge({walletTokenSlug:e.token,walletBundleHash:e.bundle,walletAddress:e.address,walletPosition:e.position,walletBatchId:e.batchId,walletPubkey:e.pubkey,walletCharacters:e.characters}),this}setShadowWalletClaim(e){return this.merge({shadowWalletClaim:e*1}),this}setSigningWallet(e){return this.merge({signingWallet:JSON.stringify({tokenSlug:e.token,bundleHash:e.bundle,address:e.address,position:e.position,pubkey:e.pubkey,characters:e.characters})}),this}addPolicy(e){const t=new Pe(e,Object.keys(this.meta));return this.merge({policy:t.toJson()}),this}get(){return this.meta}}class 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 T{constructor(e="The molecule does not contain atoms",t=null,n=null){super(e,t,n),this.name="AtomsMissingException"}}class ae{static create(e){const t={};for(const n of Object.keys(e))Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return new this(t)}static structure(e){switch(Object.prototype.toString.call(e)){case"[object Array]":{const t=[];for(const n in e)t.push(ae.isStructure(e[n])?ae.structure(e[n]):e[n]);return t}case"[object Object]":{const t=[],n=Object.keys(e).sort((s,r)=>s===r?0:s<r?-1:1);for(const s of n)if(Object.prototype.hasOwnProperty.call(e,s)){const r={};r[s]=ae.isStructure(e[s])?ae.structure(e[s]):e[s],t.push(r)}if(t.length>0)return t;break}}return e}static isStructure(e){return["[object Object]","[object Array]"].includes(Object.prototype.toString.call(e))}view(){return ae.structure(this)}}class ds extends ae{constructor({position:e=null,walletAddress:t=null,isotope:n=null,token:s=null,value:r=null,batchId:i=null,metaType:o=null,metaId:c=null,meta:u=null,index:l=null,createdAt:d=null,version:f=null}){super(),this.position=e,this.walletAddress=t,this.isotope=n,this.token=s,this.value=r,this.batchId=i,this.metaType=o,this.metaId=c,this.meta=u,this.index=l,this.createdAt=d,this.version=f}}const Ke={4:ds};class g{constructor({position:e=null,walletAddress:t=null,isotope:n=null,token:s=null,value:r=null,batchId:i=null,metaType:o=null,metaId:c=null,meta:u=null,otsFragment:l=null,index:d=null,version:f=null}){this.position=e,this.walletAddress=t,this.isotope=n,this.token=s,this.value=r!==null?String(r):null,this.batchId=i,this.metaType=o,this.metaId=c,this.meta=u?ie.normalizeMeta(u):[],this.index=d,this.otsFragment=l,this.createdAt=String(+new Date),f!==null&&Object.prototype.hasOwnProperty.call(Ke,f)&&(this.version=String(f))}static getHashableProps(){return["position","walletAddress","isotope","token","value","batchId","metaType","metaId","meta","createdAt"]}static getUnclaimedProps(){return["otsFragment"]}static create({isotope:e,wallet:t=null,value:n=null,metaType:s=null,metaId:r=null,meta:i=null,batchId:o=null}){return i||(i=new H),i instanceof H||(i=new H(i)),t&&(i.setAtomWallet(t),o||(o=t.batchId)),new g({position:t?t.position:null,walletAddress:t?t.address:null,isotope:e,token:t?t.token:null,value:n,batchId:o,metaType:s,metaId:r,meta:i.get()})}static jsonToObject(e){const t=Object.assign(new 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 o=["position","walletAddress","isotope","token"];for(const c of o)if(!r[c])throw new Error(`Required field '${c}' is missing or empty`)}const i=new 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 q("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(Ke,r.version)))n.update(JSON.stringify(s.map(r=>Ke[r.version].create(r).view())));else{const r=String(e.length);let i=[];for(const o of s)i.push(r),i=i.concat(o.getHashableValues());for(const o of i)n.update(o)}switch(t){case"hex":return n.getHash("HEX",{outputLen:256});case"array":return n.getHash("ARRAYBUFFER",{outputLen:256});default:return $t(n.getHash("HEX",{outputLen:256}),16,17,"0123456789abcdef","0123456789abcdefg").padStart(64,"0")}}static jsonSerialization(e,t){if(!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 ie.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 Ne(a=null,e=2048){if(a){const t=new q("SHAKE256","TEXT");return t.update(a),t.getHash("HEX",{outputLen:e*2})}else return Ue(e)}function oe(a,e=null){const t=new q("SHAKE256","TEXT");return t.update(a),t.getHash("HEX",{outputLen:256})}function et(a,e){const t=new q("SHAKE256","TEXT");return t.update(a),t.getHash("HEX",{outputLen:e})}function le({molecularHash:a=null,index:e=null}){return a!==null&&e!==null?oe(String(a)+String(e),"generateBatchId"):Ue(64)}class ce{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 ce(e.id,e.name,t)}static createFromDB(e){return new ce(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 tt 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),Rt=BigInt(32);function ps(a,e=!1){return e?{h:Number(a&Qe),l:Number(a>>Rt&Qe)}:{h:Number(a>>Rt&Qe)|0,l:Number(a&Qe)|0}}function fs(a,e=!1){const t=a.length;let n=new Uint32Array(t),s=new Uint32Array(t);for(let r=0;r<t;r++){const{h:i,l:o}=ps(a[r],e);[n[r],s[r]]=[i,o]}return[n,s]}const ms=(a,e,t)=>a<<t|e>>>32-t,ys=(a,e,t)=>e<<t|a>>>32-t,gs=(a,e,t)=>e<<t-32|a>>>64-t,bs=(a,e,t)=>a<<t-32|e>>>64-t;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ws(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&a.constructor.name==="Uint8Array"}function Ot(a,e=""){if(!Number.isSafeInteger(a)||a<0){const t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${a}`)}}function D(a,e,t=""){const n=ws(a),s=a==null?void 0:a.length,r=e!==void 0;if(!n||r&&s!==e){const i=t&&`"${t}" `,o=r?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof a}`;throw new Error(i+"expected Uint8Array"+o+", got "+c)}return a}function qt(a,e=!0){if(a.destroyed)throw new Error("Hash instance has been destroyed");if(e&&a.finished)throw new Error("Hash#digest() has already been called")}function ks(a,e){D(a,void 0,"digestInto() output");const t=e.outputLen;if(a.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function Wt(a){return new Uint32Array(a.buffer,a.byteOffset,Math.floor(a.byteLength/4))}function Bt(...a){for(let e=0;e<a.length;e++)a[e].fill(0)}const Ss=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function _s(a){return a<<24&4278190080|a<<8&16711680|a>>>8&65280|a>>>24&255}function $s(a){for(let e=0;e<a.length;e++)a[e]=_s(a[e]);return a}const Ut=Ss?a=>a:$s;function Ht(a,e={}){const t=(s,r)=>a(r).update(s).digest(),n=a(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=s=>a(s),Object.assign(t,e),Object.freeze(t)}function As(a=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(a))}const Fe=a=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,a])}),vs=BigInt(0),Ae=BigInt(1),Is=BigInt(2),Ms=BigInt(7),Ts=BigInt(256),Cs=BigInt(113),Pt=[],Kt=[],Nt=[];for(let a=0,e=Ae,t=1,n=0;a<24;a++){[t,n]=[n,(2*t+3*n)%5],Pt.push(2*(5*n+t)),Kt.push((a+1)*(a+2)/2%64);let s=vs;for(let r=0;r<7;r++)e=(e<<Ae^(e>>Ms)*Cs)%Ts,e&Is&&(s^=Ae<<(Ae<<BigInt(r))-Ae);Nt.push(s)}const Qt=fs(Nt,!0),xs=Qt[0],Es=Qt[1],Ft=(a,e,t)=>t>32?gs(a,e,t):ms(a,e,t),Lt=(a,e,t)=>t>32?bs(a,e,t):ys(a,e,t);function Rs(a,e=24){const t=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let i=0;i<10;i++)t[i]=a[i]^a[i+10]^a[i+20]^a[i+30]^a[i+40];for(let i=0;i<10;i+=2){const o=(i+8)%10,c=(i+2)%10,u=t[c],l=t[c+1],d=Ft(u,l,1)^t[o],f=Lt(u,l,1)^t[o+1];for(let p=0;p<50;p+=10)a[i+p]^=d,a[i+p+1]^=f}let s=a[2],r=a[3];for(let i=0;i<24;i++){const o=Kt[i],c=Ft(s,r,o),u=Lt(s,r,o),l=Pt[i];s=a[l],r=a[l+1],a[l]=c,a[l+1]=u}for(let i=0;i<50;i+=10){for(let o=0;o<10;o++)t[o]=a[i+o];for(let o=0;o<10;o++)a[i+o]^=~t[(o+2)%10]&t[(o+4)%10]}a[0]^=xs[n],a[1]^=Es[n]}Bt(t)}class Le{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,Ot(n,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Wt(this.state)}clone(){return this._cloneInto()}keccak(){Ut(this.state32),Rs(this.state32,this.rounds),Ut(this.state32),this.posOut=0,this.pos=0}update(e){qt(this),D(e);const{blockLen:t,state:n}=this,s=e.length;for(let r=0;r<s;){const i=Math.min(t-this.pos,s-r);for(let o=0;o<i;o++)n[this.pos++]^=e[r++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:s}=this;e[n]^=t,(t&128)!==0&&n===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){qt(this,!1),D(e),this.finish();const t=this.state,{blockLen:n}=this;for(let s=0,r=e.length;s<r;){this.posOut>=n&&this.keccak();const i=Math.min(n-this.posOut,r-s);e.set(t.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Ot(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ks(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,Bt(this.state)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:s,rounds:r,enableXOF:i}=this;return e||(e=new Le(t,n,s,i,r)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=r,e.suffix=n,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}}const jt=(a,e,t,n={})=>Ht(()=>new Le(e,a,t),n),Os=jt(6,136,32,Fe(8)),qs=jt(6,72,64,Fe(10)),Dt=(a,e,t,n={})=>Ht((s={})=>new Le(e,a,s.dkLen===void 0?t:s.dkLen,!0),n),Ws=Dt(31,168,16,Fe(11)),Vt=Dt(31,136,32,Fe(12));function nt(a){if(!Number.isSafeInteger(a)||a<0||a>4294967295)throw new Error("wrong u32 integer:"+a);return a}function zt(a){return nt(a),(a&a-1)===0&&a!==0}function Jt(a,e){nt(a);let t=0;for(let n=0;n<e;n++,a>>>=1)t=t<<1|a&1;return t}function Gt(a){return nt(a),31-Math.clz32(a)}function Xt(a){const e=a.length;if(e<2||!zt(e))throw new Error("n must be a power of 2 and greater than 1. Got "+e);const t=Gt(e);for(let n=0;n<e;n++){const s=Jt(n,t);if(n<s){const r=a[n];a[n]=a[s],a[s]=r}}return a}const Zt=(a,e)=>{const{N:t,roots:n,dit:s,invertButterflies:r=!1,skipStages:i=0,brp:o=!0}=e,c=Gt(t);if(!zt(t))throw new Error("FFT: Polynomial size should be power of two");const u=s!==r;return l=>{if(l.length!==t)throw new Error("FFT: wrong Polynomial length");s&&o&&Xt(l);for(let d=0,f=1;d<c-i;d++){const p=s?d+1+i:c-d,w=1<<p,I=w>>1,R=t>>p;for(let m=0;m<t;m+=w)for(let b=0,k=f++;b<I;b++){const O=r?s?t-k:k:b*R,_=m+b,v=m+b+I,M=n[O],x=l[v],$=l[_];if(u){const Q=a.mul(x,M);l[_]=a.add($,Q),l[v]=a.sub($,Q)}else r?(l[_]=a.add(x,$),l[v]=a.mul(a.sub(x,$),M)):(l[_]=a.add($,x),l[v]=a.mul(a.sub($,x),M))}}return!s&&o&&Xt(l),l}};/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */const Yt=As;function st(a,e){if(a.length!==e.length)return!1;let t=0;for(let n=0;n<a.length;n++)t|=a[n]^e[n];return t===0}function Bs(a){return Uint8Array.from(a)}function je(a,...e){const t=s=>typeof s=="number"?s:s.bytesLen,n=e.reduce((s,r)=>s+t(r),0);return{bytesLen:n,encode:s=>{const r=new Uint8Array(n);for(let i=0,o=0;i<e.length;i++){const c=e[i],u=t(c),l=typeof c=="number"?s[i]:c.encode(s[i]);D(l,u,a),r.set(l,o),typeof c!="number"&&l.fill(0),o+=u}return r},decode:s=>{D(s,n,a);const r=[];for(const i of e){const o=t(i),c=s.subarray(0,o);r.push(typeof i=="number"?c:i.decode(c)),s=s.subarray(o)}return r}}}function rt(a,e){const t=e*a.bytesLen;return{bytesLen:t,encode:n=>{if(n.length!==e)throw new Error(`vecCoder.encode: wrong length=${n.length}. Expected: ${e}`);const s=new Uint8Array(t);for(let r=0,i=0;r<n.length;r++){const o=a.encode(n[r]);s.set(o,i),o.fill(0),i+=o.length}return s},decode:n=>{D(n,t);const s=[];for(let r=0;r<n.length;r+=a.bytesLen)s.push(a.decode(n.subarray(r,r+a.bytesLen)));return s}}}function X(...a){for(const e of a)if(Array.isArray(e))for(const t of e)t.fill(0);else e.fill(0)}function en(a){return(1<<a)-1}/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */const Us=a=>{const{newPoly:e,N:t,Q:n,F:s,ROOT_OF_UNITY:r,brvBits:i}=a,o=(m,b=n)=>{const k=m%b|0;return(k>=0?k|0:b+k|0)|0},c=(m,b=n)=>{const k=o(m,b)|0;return(k>b>>1?k-b|0:k)|0};function u(){const m=e(t);for(let b=0;b<t;b++){const k=Jt(b,i),O=BigInt(r)**BigInt(k)%BigInt(n);m[b]=Number(O)|0}return m}const l=u(),d={add:(m,b)=>o((m|0)+(b|0))|0,sub:(m,b)=>o((m|0)-(b|0))|0,mul:(m,b)=>o((m|0)*(b|0))|0,inv:m=>{throw new Error("not implemented")}},f={N:t,roots:l,invertButterflies:!0,skipStages:1,brp:!1},p=Zt(d,{dit:!1,...f}),w=Zt(d,{dit:!0,...f});return{mod:o,smod:c,nttZetas:l,NTT:{encode:m=>p(m),decode:m=>{w(m);for(let b=0;b<m.length;b++)m[b]=o(s*m[b]);return m}},bitsCoder:(m,b)=>{const k=en(m),O=m*(t/8);return{bytesLen:O,encode:_=>{const v=new Uint8Array(O);for(let M=0,x=0,$=0,Q=0;M<_.length;M++)for(x|=(b.encode(_[M])&k)<<$,$+=m;$>=8;$-=8,x>>=8)v[Q++]=x&en($);return v},decode:_=>{const v=e(t);for(let M=0,x=0,$=0,Q=0;M<_.length;M++)for(x|=_[M]<<$,$+=8;$>=m;$-=m,x>>=m)v[Q++]=b.decode(x&k);return v}}}}},Hs=(a=>(e,t)=>{t||(t=a.blockLen);const n=new Uint8Array(e.length+2);n.set(e);const s=e.length,r=new Uint8Array(t);let i=a.create({}),o=0,c=0;return{stats:()=>({calls:o,xofs:c}),get:(u,l)=>(n[s+0]=u,n[s+1]=l,i.destroy(),i=a.create({}).update(n),o++,()=>(c++,i.xofInto(r))),clean:()=>{i.destroy(),X(r,n)}}})(Ws);/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */const L=256,ue=3329,Ps=3303,Ks=17,{mod:ve,nttZetas:Ns,NTT:he,bitsCoder:Qs}=Us({N:L,Q:ue,F:Ps,ROOT_OF_UNITY:Ks,newPoly:a=>new Uint16Array(a),brvBits:7}),Fs={768:{N:L,Q:ue,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192}},Ls=a=>{if(a>=12)return{encode:t=>t,decode:t=>t};const e=2**(a-1);return{encode:t=>((t<<a)+ue/2)/ue,decode:t=>t*ue+e>>>a}},Ie=a=>Qs(a,Ls(a));function de(a,e){for(let t=0;t<L;t++)a[t]=ve(a[t]+e[t])}function js(a,e){for(let t=0;t<L;t++)a[t]=ve(a[t]-e[t])}function Ds(a,e,t,n,s){const r=ve(e*n*s+a*t),i=ve(a*n+e*t);return{c0:r,c1:i}}function De(a,e){for(let t=0;t<L/2;t++){let n=Ns[64+(t>>1)];t&1&&(n=-n);const{c0:s,c1:r}=Ds(a[2*t+0],a[2*t+1],e[2*t+0],e[2*t+1],n);a[2*t+0]=s,a[2*t+1]=r}return a}function tn(a){const e=new Uint16Array(L);for(let t=0;t<L;){const n=a();if(n.length%3)throw new Error("SampleNTT: unaligned block");for(let s=0;t<L&&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<ue&&(e[t++]=r),t<L&&i<ue&&(e[t++]=i)}}return e}function Me(a,e,t,n){const s=a(n*L/4,e,t),r=new Uint16Array(L),i=Wt(s);let o=0;for(let c=0,u=0,l=0,d=0;c<i.length;c++){let f=i[c];for(let p=0;p<32;p++)l+=f&1,f>>=1,o+=1,o===n?(d=l,l=0):o===2*n&&(r[u++]=ve(d-l),l=0,o=0)}if(o)throw new Error(`sampleCBD: leftover bits: ${o}`);return r}const Vs=a=>{const{K:e,PRF:t,XOF:n,HASH512:s,ETA1:r,ETA2:i,du:o,dv:c}=a,u=Ie(1),l=Ie(c),d=Ie(o),f=je("publicKey",rt(Ie(12),e),32),p=rt(Ie(12),e),w=je("ciphertext",rt(d,e),l),I=je("seed",32,32);return{secretCoder:p,lengths:{secretKey:p.bytesLen,publicKey:f.bytesLen,cipherText:w.bytesLen},keygen:R=>{D(R,32,"seed");const m=new Uint8Array(33);m.set(R),m[32]=e;const b=s(m),[k,O]=I.decode(b),_=[],v=[];for(let $=0;$<e;$++)_.push(he.encode(Me(t,O,$,r)));const M=n(k);for(let $=0;$<e;$++){const Q=he.encode(Me(t,O,e+$,r));for(let U=0;U<e;U++){const _e=tn(M.get(U,$));de(Q,De(_e,_[U]))}v.push(Q)}M.clean();const x={publicKey:f.encode([v,k]),secretKey:p.encode(_)};return X(k,O,_,v,m,b),x},encrypt:(R,m,b)=>{const[k,O]=f.decode(R),_=[];for(let U=0;U<e;U++)_.push(he.encode(Me(t,b,U,r)));const v=n(O),M=new Uint16Array(L),x=[];for(let U=0;U<e;U++){const _e=Me(t,b,e+U,i),St=new Uint16Array(L);for(let Ze=0;Ze<e;Ze++){const Sr=tn(v.get(U,Ze));de(St,De(Sr,_[Ze]))}de(_e,he.decode(St)),x.push(_e),de(M,De(k[U],_[U])),X(St)}v.clean();const $=Me(t,b,2*e,i);de($,he.decode(M));const Q=u.decode(m);return de(Q,$),X(k,_,M,$),w.encode([x,Q])},decrypt:(R,m)=>{const[b,k]=w.decode(R),O=p.decode(m),_=new Uint16Array(L);for(let v=0;v<e;v++)de(_,De(O[v],he.encode(b[v])));return js(k,he.decode(_)),X(_,O,b),u.encode(k)}}};function zs(a){const e=Vs(a),{HASH256:t,HASH512:n,KDF:s}=a,{secretCoder:r,lengths:i}=e,o=je("secretKey",i.secretKey,i.publicKey,32,32),c=32,u=64;return{info:{type:"ml-kem"},lengths:{...i,seed:64,msg:c,msgRand:c,secretKey:o.bytesLen},keygen:(l=Yt(u))=>{D(l,u,"seed");const{publicKey:d,secretKey:f}=e.keygen(l.subarray(0,32)),p=t(d),w=o.encode([f,d,p,l.subarray(32)]);return X(f,p),{publicKey:d,secretKey:w}},getPublicKey:l=>{const[d,f]=o.decode(l);return Uint8Array.from(f)},encapsulate:(l,d=Yt(c))=>{D(l,i.publicKey,"publicKey"),D(d,c,"message");const f=l.subarray(0,384*a.K),p=r.encode(r.decode(Bs(f)));if(!st(p,f))throw X(p),new Error("ML-KEM.encapsulate: wrong publicKey modulus");X(p);const w=n.create().update(d).update(t(l)).digest(),I=e.encrypt(l,d,w.subarray(32,64));return X(w.subarray(32)),{cipherText:I,sharedSecret:w.subarray(0,32)}},decapsulate:(l,d)=>{D(d,o.bytesLen,"secretKey"),D(l,i.cipherText,"cipherText");const f=o.bytesLen-96,p=f+32,w=t(d.subarray(f/2,p));if(!st(w,d.subarray(p,p+32)))throw new Error("invalid secretKey: hash check failed");const[I,R,m,b]=o.decode(d),k=e.decrypt(l,I),O=n.create().update(k).update(m).digest(),_=O.subarray(0,32),v=e.encrypt(R,k,O.subarray(32,64)),M=st(l,v),x=s.create({dkLen:32}).update(b).update(l).digest();return X(k,v,M?x:_),M?_:x}}}function Js(a,e,t){return Vt.create({dkLen:a}).update(e).update(new Uint8Array([t])).digest()}const it=zs({...{HASH256:Os,HASH512:qs,KDF:Vt,XOF:Hs,PRF:Js},...Fs[768]});class S{constructor({secret:e=null,bundle:t=null,token:n="USER",address:s=null,position:r=null,batchId:i=null,characters:o=null}){this.token=n,this.balance="0",this.molecules={},this.key=null,this.privkey=null,this.pubkey=null,this.tokenUnits=[],this.tradeRates={},this.address=s,this.position=r,this.bundle=t,this.batchId=i,this.characters=o,e&&(this.bundle=this.bundle||oe(e,"Wallet::constructor"),this.position=this.position||S.generatePosition(),this.key=S.generateKey({secret:e,token:this.token,position:this.position}),this.address=this.address||S.generateAddress(this.key),this.characters=this.characters||"BASE64",this.initializeMLKEM())}static create({secret:e=null,bundle:t=null,token:n,batchId:s=null,characters:r=null}){let i=null;if(!e&&!t)throw new tt;return e&&!t&&(i=S.generatePosition(),t=oe(e,"Wallet::create")),new S({secret:e,bundle:t,token:n,position:i,batchId:s,characters:r})}static isBundleHash(e){return typeof e!="string"?!1:e.length===64&&He(e)}static getTokenUnits(e){const t=[];return e.forEach(n=>{t.push(ce.createFromDB(n))}),t}static generateKey({secret:e,token:t,position:n}){if(!e)throw new tt("Wallet::generateKey() - Secret is required!");if(!n)throw new tt("Wallet::generateKey() - Position is required!");const s=He(e)?e:et(e,1024),r=He(n)?n:et(n,256),o=BigInt(`0x${s}`)+BigInt(`0x${r}`),c=new q("SHAKE256","TEXT");c.update(o.toString(16)),t&&c.update(t);const u=new q("SHAKE256","TEXT");return u.update(c.getHash("HEX",{outputLen:8192})),u.getHash("HEX",{outputLen:8192})}static generateAddress(e){const t=$e(e,128),n=new q("SHAKE256","TEXT");for(const r in t){let i=t[r];for(let o=1;o<=16;o++){const c=new q("SHAKE256","TEXT");c.update(i),i=c.getHash("HEX",{outputLen:512})}n.update(i)}const s=new q("SHAKE256","TEXT");return s.update(n.getHash("HEX",{outputLen:8192})),s.getHash("HEX",{outputLen:256})}static generatePosition(e=64){return Ue(e,"abcdef0123456789")}initializeMLKEM(){const e=Ne(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}=it.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=S.create({secret:e,token:this.token,characters:this.characters});return t.initBatchId({sourceWallet:this,isRemainder:!0}),t}isShadow(){return(typeof this.position>"u"||this.position===null)&&(typeof this.address>"u"||this.address===null)}initBatchId({sourceWallet:e,isRemainder:t=!1}){e.batchId&&(this.batchId=t?e.batchId:le({}))}async encryptMessage(e,t){const n=JSON.stringify(e),s=new TextEncoder().encode(n),r=this.deserializeKey(t),{cipherText:i,sharedSecret:o}=it.encapsulate(r),c=await this.encryptWithSharedSecret(s,o);return{cipherText:this.serializeKey(i),encryptedMessage:this.serializeKey(c)}}async decryptMessage(e){const{cipherText:t,encryptedMessage:n}=e;let s;try{s=it.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 o;try{o=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(o)}async encryptWithSharedSecret(e,t){const n=crypto.getRandomValues(new Uint8Array(12)),s={name:"AES-GCM",iv:n},r=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["encrypt"]),i=await crypto.subtle.encrypt(s,r,e),o=new Uint8Array(n.length+i.byteLength);return o.set(n),o.set(new Uint8Array(i),n.length),o}async decryptWithSharedSecret(e,t){const s={name:"AES-GCM",iv:e.slice(0,12)},r=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=await crypto.subtle.decrypt(s,r,e.slice(12));return new Uint8Array(i)}}class ge extends T{constructor(e="There is an atom without an index",t=null,n=null){super(e,t,n),this.name="AtomIndexException"}}class nn extends T{constructor(e="The molecular hash does not match",t=null,n=null){super(e,t,n),this.name="MolecularHashMismatchException"}}class sn extends T{constructor(e="The molecular hash is missing",t=null,n=null){super(e,t,n),this.name="MolecularHashMissingException"}}class at extends T{constructor(e="",t=null,n=null){super(e,t,n),this.name="PolicyInvalidException"}}class ot extends T{constructor(e="OTS malformed",t=null,n=null){super(e,t,n),this.name="SignatureMalformedException"}}class rn extends T{constructor(e="One-time signature (OTS) does not match!",t=null,n=null){super(e,t,n),this.name="SignatureMismatchException"}}class Z extends T{constructor(e="Insufficient balance to make transfer",t=null,n=null){super(e,t,n),this.name="TransferBalanceException"}}class be extends T{constructor(e="Token transfer atoms are malformed",t=null,n=null){super(e,t,n),this.name="TransferMalformedException"}}class lt 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 ct extends T{constructor(e="Invalid remainder provided",t=null,n=null){super(e,t,n),this.name="TransferRemainderException"}}class an extends T{constructor(e="Sender and recipient(s) cannot be the same",t=null,n=null){super(e,t,n),this.name="TransferToSelfException"}}class Te 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 re extends T{constructor(e="Wrong type of token for this isotope",t=null,n=null){super(e,t,n),this.name="WrongTokenTypeException"}}class Ce extends T{constructor(e="Incorrect BatchId",t=null,n=null){super(e,t,n),this.name="BatchIdException"}}class on{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 Ve extends T{constructor(e="An incorrect argument!",t=null,n=null){super(e,t,n),this.name="RuleArgumentException"}}class Y extends T{constructor(e="Code exception",t=null,n=null){super(e,t,n),this.name="CodeException"}}class xe{constructor({action:e,metaType:t=null,metaId:n=null,meta:s=null,address:r=null,token:i=null,amount:o=null,comparison:c=null}){if(s&&(this.meta=s),!e)throw new Ve('Callback structure violated, missing mandatory "action" parameter.');this.__metaId=n,this.__metaType=t,this.__action=e,this.__address=r,this.__token=i,this.__amount=o,this.__comparison=c}set comparison(e){this.__comparison=e}set amount(e){if(!Tt(e))throw new Y("Parameter amount should be a string containing numbers");this.__amount=e}set token(e){this.__token=e}set address(e){this.__address=e}set meta(e){this.__meta=e instanceof on?e:on.toObject(e)}set metaType(e){this.__metaType=e}set metaId(e){this.__metaId=e}static toObject(e){const t=new xe({action:e.action});return e.metaType&&(t.metaType=e.metaType),e.metaId&&(t.metaId=e.metaId),e.meta&&(t.meta=e.meta),e.address&&(t.address=e.address),e.token&&(t.token=e.token),e.amount&&(t.amount=e.amount),e.comparison&&(t.comparison=e.comparison),t}toJSON(){const e={action:this.__action};return this.__metaType&&(e.metaType=this.__metaType),this.__metaId&&(e.metaId=this.__metaId),this.__meta&&(e.meta=this.__meta),this.__address&&(e.address=this.__address),this.__token&&(e.token=this.__token),this.__amount&&(e.amount=this.__amount),this.__comparison&&(e.comparison=this.__comparison),e}isReject(){return this._is("reject")}isMeta(){return ye(Object.keys(this.toJSON()),["action","metaId","metaType","meta"]).length===4&&this._is("meta")}isCollect(){return ye(Object.keys(this.toJSON()),["action","address","token","amount","comparison"]).length===5&&this._is("collect")}isBuffer(){return ye(Object.keys(this.toJSON()),["action","address","token","amount","comparison"]).length===5&&this._is("buffer")}isRemit(){return ye(Object.keys(this.toJSON()),["action","token","amount"]).length===3&&this._is("remit")}isBurn(){return ye(Object.keys(this.toJSON()),["action","token","amount","comparison"]).length===4&&this._is("burn")}_is(e){return this.__action.toLowerCase()===e.toLowerCase()}}class ut{constructor({key:e,value:t,comparison:n}){if([e,t,n].some(s=>!s))throw new Ve("Condition::constructor( { key, value, comparison } ) - not all class parameters are initialised!");this.__key=e,this.__value=t,this.__comparison=n}static toObject(e){return new this({key:e.key,value:e.value,comparison:e.comparison})}toJSON(){return{key:this.__key,value:this.__value,comparison:this.__comparison}}}class Ee{constructor({condition:e=[],callback:t=[]}){for(const n of e)if(!(n instanceof ut))throw new Ve;for(const n of t)if(!(n instanceof xe))throw new Ve;this.__condition=e,this.__callback=t}set comparison(e){this.__condition.push(e instanceof ut?e:ut.toObject(e))}set callback(e){this.__callback.push(e instanceof xe?e:xe.toObject(e))}static toObject(e){if(!e.condition)throw new P("Rule::toObject() - Incorrect rule format! There is no condition field.");if(!e.callback)throw new P("Rule::toObject() - Incorrect rule format! There is no callback field.");const t=new Ee({});for(const n of e.condition)t.comparison=n;for(const n of e.callback)t.callback=n;return t}toJSON(){return{condition:this.__condition,callback:this.__callback}}}class C{static __init(e,t){this.arr=String(t).split("."),this.key=this.arr.shift();const n=Number(this.key);Number.isInteger(n)&&(this.key=n),this.__nextKey=this.arr.length,this.__next=this.__tic(e)}static __tic(e){return!Array.isArray(e)&&!(e instanceof Object)?!1:typeof e[this.key]<"u"}static has(e,t){return this.__init(e,t),this.__next?this.__nextKey===0?!0:this.has(e[this.key],this.arr.join(".")):!1}static get(e,t,n=null){return this.__init(e,t),this.__next?this.__nextKey===0?e[this.key]:this.get(e[this.key],this.arr.join("."),n):n}static set(e,t,n){const s=t.split(".");let r=e;const i=s.length-1;for(let u=0;u<i;u++){const l=s[u],d=Number(l),f=Number.isInteger(d);(f?d:l in r)||(r[f?d:l]=s[u+1].match(/^\d+$/)?[]:{}),r=r[f?d:l]}const o=s[i],c=Number(o);return r[Number.isInteger(c)?c:o]=n,e}}class we{constructor(e){if(e.molecularHash===null)throw new sn;if(!e.atoms.length)throw new se;for(const t of e.atoms)if(t.index===null)throw new ge;this.molecule=e}verify(e){return this.molecularHash()&&this.ots()&&this.batchId()&&this.continuId()&&this.isotopeM()&&this.isotopeT()&&this.isotopeC()&&this.isotopeU()&&this.isotopeI()&&this.isotopeR()&&this.isotopeP()&&this.isotopeA()&&this.isotopeB()&&this.isotopeF()&&this.isotopeV(e)}continuId(){if(this.molecule.atoms[0].token==="USER"&&this.molecule.getIsotopes("I").length<1)throw new se("Check::continuId() - Molecule is missing required ContinuID Atom!");return!0}batchId(){if(this.molecule.atoms.length>0){const e=this.molecule.atoms[0];if(e.isotope==="V"&&e.batchId!==null){const t=this.molecule.getIsotopes("V"),n=t[t.length-1];if(e.batchId!==n.batchId)throw new Ce;for(const s of t)if(s.batchId===null)throw new Ce}return!0}throw new Ce}isotopeI(){for(const e of this.molecule.getIsotopes("I")){if(e.token!=="USER")throw new re(`Check::isotopeI() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index===0)throw new ge(`Check::isotopeI() - Isotope "${e.isotope}" Atoms must have a non-zero index!`)}return!0}isotopeU(){for(const e of this.molecule.getIsotopes("U")){if(e.token!=="AUTH")throw new re(`Check::isotopeU() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index!==0)throw new ge(`Check::isotopeU() - Isotope "${e.isotope}" Atoms must have an index equal to 0!`)}return!0}isotopeM(){const e=["readPolicy","writePolicy"];for(const t of this.molecule.getIsotopes("M")){if(t.meta.length<1)throw new P;if(t.token!=="USER")throw new re(`Check::isotopeM() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);const n=ie.aggregateMeta(t.meta);for(const s of e){let r=n[s];if(r){r=JSON.parse(r);for(const[i,o]of Object.entries(r))if(!e.includes(i)){if(!Object.keys(n).includes(i))throw new at(`${i} is missing from the meta.`);for(const c of o)if(!S.isBundleHash(c)&&!["all","self"].includes(c))throw new at(`${c} does not correspond to the format of the policy.`)}}}}return!0}isotopeC(){for(const e of this.molecule.getIsotopes("C")){if(e.token!=="USER")throw new re(`Check::isotopeC() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index!==0)throw new ge(`Check::isotopeC() - Isotope "${e.isotope}" Atoms must have an index equal to 0!`)}return!0}isotopeT(){for(const e of this.molecule.getIsotopes("T")){const t=e.aggregatedMeta();if(String(e.metaType).toLowerCase()==="wallet"){for(const s of["position","bundle"])if(!Object.prototype.hasOwnProperty.call(t,s)||!t[s])throw new 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 re(`Check::isotopeT() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index!==0)throw new ge(`Check::isotopeT() - Isotope "${e.isotope}" Atoms must have an index equal to 0!`)}return!0}isotopeR(){for(const e of this.molecule.getIsotopes("R")){const t=e.aggregatedMeta();if(t.policy){const n=JSON.parse(t.policy);if(!Object.keys(n).every(s=>["read","write"].includes(s)))throw new P("Check::isotopeR() - Mixing rules with politics!")}if(t.rule){const n=JSON.parse(t.rule);if(!Array.isArray(n))throw new P("Check::isotopeR() - Incorrect rule format!");for(const s of n)Ee.toObject(s);if(n.length<1)throw new P("Check::isotopeR() - No rules!")}}return!0}isotopeP(){for(const e of this.molecule.getIsotopes("P")){if(e.token!=="USER")throw new re(`Check::isotopeP() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);const t=e.aggregatedMeta();if(!Object.prototype.hasOwnProperty.call(t,"peerHost")||!t.peerHost)throw new 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 re(`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 be("Check::isotopeB() - B-isotope atom value is not a valid number!")}const t=this.molecule.getIsotopes("V");if(t.length>0){let n=0;for(const s of[...t,...e]){const r=Number(s.value);Number.isNaN(r)||(n+=r)}if(n!==0)throw new Te("Check::isotopeB() - V+B atom values do not balance to zero!")}return!0}isotopeF(){const e=this.molecule.getIsotopes("F");if(e.length===0)return!0;for(const n of e){if(!n.metaType||n.metaType!=="walletBundle")throw new P('Check::isotopeF() - F-isotope atoms must have metaType "walletBundle"!');if(!n.metaId)throw new P("Check::isotopeF() - F-isotope atoms must have a metaId!");const s=Number(n.value);if(Number.isNaN(s))throw new be("Check::isotopeF() - F-isotope atom value is not a valid number!");if(s<0)throw new be("Check::isotopeF() - F-isotope atom value must not be negative!")}const t=this.molecule.getIsotopes("V");if(t.length>0){let n=0;for(const s of[...t,...e]){const r=Number(s.value);Number.isNaN(r)||(n+=r)}if(n!==0)throw new Te("Check::isotopeF() - V+F atom values do not balance to zero!")}return!0}isotopeV(e=null){const t=this.molecule.getIsotopes("V");if(t.length===0)return!0;const n=this.molecule.getIsotopes("B").length>0||this.molecule.getIsotopes("F").length>0,s=this.molecule.atoms[0];if(!n&&s.isotope==="V"&&t.length===2){const o=t[t.length-1];if(s.token!==o.token)throw new lt;if(o.value<0)throw new be;if(Number(s.value)+Number(o.value)!==0)throw new Te;return!0}let r=0,i=0;for(const o in this.molecule.atoms)if(Object.prototype.hasOwnProperty.call(this.molecule.atoms,o)){const c=this.molecule.atoms[o];if(c.isotope!=="V")continue;if(i=c.value*1,Number.isNaN(i))throw new TypeError('Invalid isotope "V" values');if(c.token!==s.token)throw new lt;if(o>0){if(i<0)throw new be;if(c.walletAddress===s.walletAddress)throw new an}r+=i}if(!n&&r!==0)throw new Te;if(e){if(i=s.value*1,Number.isNaN(i))throw new TypeError('Invalid isotope "V" values');const o=Number(e.balance)+i;if(o<0)throw new Z;if(!n&&o!==r)throw new ct}else if(i!==0)throw new ct;return!0}molecularHash(){if(this.molecule.molecularHash!==g.hashAtoms({atoms:this.molecule.atoms}))throw new nn;return!0}ots(){const e=this.molecule.normalizedHash();let t=this.molecule.atoms.map(f=>f.otsFragment).reduce((f,p)=>f+p);if(t.length!==2048&&(t=Mt(t),t.length!==2048))throw new ot;const n=$e(t,128);let s="";for(const f in n){let p=n[f];for(let w=0,I=8+e[f];w<I;w++)p=new q("SHAKE256","TEXT").update(p).getHash("HEX",{outputLen:512});s+=p}const r=new q("SHAKE256","TEXT");r.update(s);const i=r.getHash("HEX",{outputLen:8192}),o=new q("SHAKE256","TEXT");o.update(i);const c=o.getHash("HEX",{outputLen:256}),u=this.molecule.atoms[0];let l=u.walletAddress;const d=C.get(u.aggregatedMeta(),"signingWallet");if(d&&(l=C.get(JSON.parse(d),"address")),c!==l)throw new rn;return!0}static fromServerData({molecularHash:e,bundleHash:t,cellSlug:n=null,status:s=null,createdAt:r=null,atoms:i=[]}){const o=i.map(c=>{let u=[];if(c.metasJson)try{const l=JSON.parse(c.metasJson);Array.isArray(l)?u=l:l&&typeof l=="object"&&(u=Object.entries(l).map(([d,f])=>({key:d,value:f})))}catch{u=[]}return{position:c.position||null,walletAddress:c.walletAddress||null,isotope:c.isotope||null,token:c.tokenSlug||c.token||null,value:c.value!=null?String(c.value):null,batchId:c.batchId||null,metaType:c.metaType||null,metaId:c.metaId||null,meta:u,index:c.index!=null?c.index:null,otsFragment:c.otsFragment||null,createdAt:c.createdAt||null}});return V.fromJSON({molecularHash:e,bundle:t,cellSlug:n,status:s,createdAt:r,atoms:o})}static verifyFromServerData(e){try{const t=we.fromServerData(e);return new we(t).verify(),{molecularHash:e.molecularHash,verified:!0,error:null}}catch(t){return{molecularHash:e.molecularHash||null,verified:!1,error:t.message||String(t)}}}}class pe extends T{constructor(e="Insufficient balance for requested transfer",t=null,n=null){super(e,t,n),this.name="BalanceInsufficientException"}}class ze extends T{constructor(e="Amount cannot be negative!",t=null,n=null){super(e,t,n),this.name="NegativeAmountException"}}class V{constructor({secret:e=null,bundle:t=null,sourceWallet:n=null,remainderWallet:s=null,cellSlug:r=null,version:i=null,continuIdPosition:o=null}){this.status=null,this.molecularHash=null,this.createdAt=String(+new Date),this.cellSlugOrigin=this.cellSlug=r,this.secret=e,this.bundle=t,this.sourceWallet=n,this.continuIdPosition=o,this.atoms=[],this.parentHashes=[],i!==null&&Object.prototype.hasOwnProperty.call(Ke,i)&&(this.version=String(i)),(s||n)&&(this.remainderWallet=s||S.create({secret:e,bundle:t,token:n.token,batchId:n.batchId,characters:n.characters}))}withParentHashes(e){return this.parentHashes=Array.isArray(e)?[...e]:[],this}get cellSlugDelimiter(){return"."}static isotopeFilter(e,t){return Array.isArray(e)||(e=[e]),t.filter(n=>e.includes(n.isotope))}static generateNextAtomIndex(e){return e.length}static jsonToObject(e){const t=Object.assign(new V({}),JSON.parse(e)),n=Object.keys(new V({}));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 o=s[r];typeof t[o]<"u"&&(n[r]=t[o])}return n}static normalize(e){let t=e.reduce((s,r)=>s+r);const n=t<0;for(;t<0||t>0;)for(const s of Object.keys(e))if((n?e[s]<8:e[s]>-8)&&(n?(++e[s],++t):(--e[s],--t),t===0))break;return e}getIsotopes(e){return V.isotopeFilter(e,this.atoms)}generateIndex(){return V.generateNextAtomIndex(this.atoms)}fill(e){for(const t in Object.keys(e))this[t]=e[t]}addAtom(e){return this.molecularHash=null,e.index=this.generateIndex(),e.version=this.version,this.atoms.push(e),this.atoms=g.sortAtoms(this.atoms),this}addContinuIdAtom(){(!this.remainderWallet||this.remainderWallet.token!=="USER")&&(this.remainderWallet=S.create({secret:this.secret,bundle:this.bundle}));const e={};return this.continuIdPosition?e.previousPosition=this.continuIdPosition:this.sourceWallet&&this.sourceWallet.position&&(e.previousPosition=this.sourceWallet.position),this.remainderWallet.pubkey&&(e.pubkey=this.remainderWallet.pubkey),this.remainderWallet.characters&&(e.characters=this.remainderWallet.characters),this.addAtom(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);return r.addPolicy(s),this.addAtom(g.create({wallet:this.sourceWallet,isotope:"R",metaType:e,metaId:t,meta:r})),this}fuseToken(e,t){const n=e.length;if(this.sourceWallet.balance-n<0)throw new pe;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 ze("Molecule::burnToken() - Amount to burn must be positive!");if(this.sourceWallet.balance-e<0)throw new pe;const n=new S({bundle:"0000000000000000000000000000000000000000000000000000000000000000",token:this.sourceWallet.token});return this.addAtom(g.create({isotope:"V",wallet:this.sourceWallet,value:-this.sourceWallet.balance})),this.addAtom(g.create({isotope:"V",wallet:n,value:e,metaType:"walletBundle",metaId:n.bundle})),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 ze("Molecule::replenishToken() - Amount to replenish must be positive!");if(t.length){t=S.getTokenUnits(t),this.remainderWallet.tokenUnits=this.sourceWallet.tokenUnits;for(const n of t)this.remainderWallet.tokenUnits.push(n);this.remainderWallet.balance=String(this.remainderWallet.tokenUnits.length),this.sourceWallet.tokenUnits=t,this.sourceWallet.balance=String(this.sourceWallet.tokenUnits.length)}else this.remainderWallet.balance=String(Number(this.sourceWallet.balance)+e),this.sourceWallet.balance=String(e);return this.addAtom(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 pe;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 ze("Molecule::addStackableTransfer() - Amount must be positive!");if(this.sourceWallet.balance-t<0)throw new pe;const n=this.sourceWallet.batchId||le({});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:le({})})),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 pe;const n=S.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 pe;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?le({}):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 o of n)r.push(o instanceof Ee?o:Ee.toObject(o));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:oe(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(p=>!(p instanceof g)).length!==0)throw new se;!t&&!this.bundle&&(this.bundle=e||oe(this.secret,"Molecule::sign")),this.molecularHash=g.hashAtoms({atoms:this.atoms});const s=this.atoms[0];let r=s.position;const i=C.get(s.aggregatedMeta(),"signingWallet");if(i&&(r=C.get(JSON.parse(i),"position")),!r)throw new ot("Signing wallet must have a position!");const o=S.generateKey({secret:this.secret,token:s.token,position:s.position}),c=$e(o,128),u=this.normalizedHash();let l="";for(const p in c){let w=c[p];for(let I=0,R=8-u[p];I<R;I++)w=new q("SHAKE256","TEXT").update(w).getHash("HEX",{outputLen:512});l+=w}n&&(l=It(l));const d=$e(l,Math.ceil(l.length/this.atoms.length));let f=null;for(let p=0,w=d.length;p<w;p++)this.atoms[p].otsFragment=d[p],f=this.atoms[p].position;return f}signSync(e={}){return this.sign(e)}cellSlugBase(){return(this.cellSlug||"").split(this.cellSlugDelimiter)[0]}toJSON(e={}){const{includeValidationContext:t=!1,includeOtsFragments:n=!0}=e;try{const s={status:this.status,molecularHash:this.molecularHash,createdAt:this.createdAt,cellSlug:this.cellSlug,bundle:this.bundle,atoms:this.atoms.map(r=>r.toJSON({includeOtsFragments:n}))};return this.parentHashes&&this.parentHashes.length>0&&(s.parentHashes=this.parentHashes),t&&(s.cellSlugOrigin=this.cellSlugOrigin,s.version=this.version,this.sourceWallet&&(s.sourceWallet={address:this.sourceWallet.address,position:this.sourceWallet.position,token:this.sourceWallet.token,balance:this.sourceWallet.balance||"0",bundle:this.sourceWallet.bundle,batchId:this.sourceWallet.batchId||null,characters:this.sourceWallet.characters||"BASE64",pubkey:this.sourceWallet.pubkey||null,tokenUnits:this.sourceWallet.tokenUnits||[],tradeRates:this.sourceWallet.tradeRates||{},molecules:this.sourceWallet.molecules||{}}),this.remainderWallet&&(s.remainderWallet={address:this.remainderWallet.address,position:this.remainderWallet.position,token:this.remainderWallet.token,balance:this.remainderWallet.balance||"0",bundle:this.remainderWallet.bundle,batchId:this.remainderWallet.batchId||null,characters:this.remainderWallet.characters||"BASE64",pubkey:this.remainderWallet.pubkey||null,tokenUnits:this.remainderWallet.tokenUnits||[],tradeRates:this.remainderWallet.tradeRates||{},molecules:this.remainderWallet.molecules||{}})),s}catch(s){throw new Error(`Molecule serialization failed: ${s.message}`)}}static fromJSON(e,t={}){const{includeValidationContext:n=!1,validateStructure:s=!0}=t;try{const r=typeof e=="string"?JSON.parse(e):e;if(s&&(!r.molecularHash||!Array.isArray(r.atoms)))throw new Error("Invalid molecule data: missing molecularHash or atoms array");const i=new V({secret:null,bundle:r.bundle||null,cellSlug:r.cellSlug||null,version:r.version||null});return i.status=r.status,i.molecularHash=r.molecularHash,i.createdAt=r.createdAt||String(+new Date),i.cellSlugOrigin=r.cellSlugOrigin,i.parentHashes=Array.isArray(r.parentHashes)?[...r.parentHashes]:[],Array.isArray(r.atoms)&&(i.atoms=r.atoms.map((o,c)=>{try{return g.fromJSON(o)}catch(u){throw new Error(`Failed to reconstruct atom ${c}: ${u.message}`)}})),n&&(r.sourceWallet&&(i.sourceWallet=new S({secret:null,token:r.sourceWallet.token,position:r.sourceWallet.position,bundle:r.sourceWallet.bundle,batchId:r.sourceWallet.batchId,characters:r.sourceWallet.characters}),i.sourceWallet.balance=String(r.sourceWallet.balance!=null?r.sourceWallet.balance:0),i.sourceWallet.address=r.sourceWallet.address,r.sourceWallet.pubkey&&(i.sourceWallet.pubkey=r.sourceWallet.pubkey),i.sourceWallet.tokenUnits=r.sourceWallet.tokenUnits||[],i.sourceWallet.tradeRates=r.sourceWallet.tradeRates||{},i.sourceWallet.molecules=r.sourceWallet.molecules||{}),r.remainderWallet&&(i.remainderWallet=new S({secret:null,token:r.remainderWallet.token,position:r.remainderWallet.position,bundle:r.remainderWallet.bundle,batchId:r.remainderWallet.batchId,characters:r.remainderWallet.characters}),i.remainderWallet.balance=String(r.remainderWallet.balance!=null?r.remainderWallet.balance:0),i.remainderWallet.address=r.remainderWallet.address,r.remainderWallet.pubkey&&(i.remainderWallet.pubkey=r.remainderWallet.pubkey),i.remainderWallet.tokenUnits=r.remainderWallet.tokenUnits||[],i.remainderWallet.tradeRates=r.remainderWallet.tradeRates||{},i.remainderWallet.molecules=r.remainderWallet.molecules||{})),i}catch(r){throw new Error(`Molecule deserialization failed: ${r.message}`)}}check(e=null){return new we(this).verify(e)}normalizedHash(){return V.normalize(V.enumerate(this.molecularHash))}}class ke{constructor({token:e,expiresAt:t,encrypt:n,pubkey:s}){this.$__token=e,this.$__expiresAt=t,this.$__pubkey=s,this.$__encrypt=n}static create(e,t){const n=new ke(e);return n.setWallet(t),n}static restore(e,t){const n=new S({secret:t,token:"AUTH",position:e.wallet.position,characters:e.wallet.characters});return ke.create({token:e.token,expiresAt:e.expiresAt,pubkey:e.pubkey,encrypt:e.encrypt},n)}setWallet(e){this.$__wallet=e}getWallet(){return this.$__wallet}getSnapshot(){return{token:this.$__token,expiresAt:this.$__expiresAt,pubkey:this.$__pubkey,encrypt:this.$__encrypt,wallet:{position:this.$__wallet.position,characters:this.$__wallet.characters}}}getToken(){return this.$__token}getPubkey(){return this.$__pubkey}getExpireInterval(){return this.$__expiresAt*1e3-Date.now()}isExpired(){return!this.$__expiresAt||this.getExpireInterval()<0}getAuthData(){return{token:this.getToken(),pubkey:this.getPubkey(),wallet:this.getWallet()}}}const ht=10**18;class fe{static val(e){return Math.abs(e*ht)<1?0:e}static cmp(e,t,n=!1){const s=fe.val(e)*ht,r=fe.val(t)*ht;return Math.abs(s-r)<1?0:s>r?1:-1}static equal(e,t){return fe.cmp(e,t)===0}}class ne extends T{constructor(e="GraphQL did not provide a valid response.",t=null,n=null){super(e,t,n),this.name="InvalidResponseException"}}class Re extends T{constructor(e="Authorization token missing or invalid.",t=null,n=null){super(e,t,n),this.name="UnauthenticatedException"}}class E{constructor({query:e,json:t,dataKey:n=null}){if(this.dataKey=n,this.errorKey="exception",this.$__payload=null,this.$__query=e,this.$__originResponse=t,this.$__response=t,typeof this.$__response>"u"||this.$__response===null)throw new ne;if(C.has(this.$__response,this.errorKey)){const s=C.get(this.$__response,this.errorKey);throw String(s).includes("Unauthenticated")?new Re:new ne}if(this.$__response.errors&&Array.isArray(this.$__response.errors)&&this.$__response.errors.length>0){const s=this.$__response.errors[0].message||"Unknown GraphQL error";throw s.includes("Unauthenticated")?new Re:new ne(`GraphQL Error: ${s}`)}this.init()}init(){}data(){if(!this.dataKey)return this.response();if(!this.response().data)throw new ne("Response has no data field");if(!C.has(this.response(),this.dataKey))throw new ne(`Missing expected field: ${this.dataKey}`);return C.get(this.response(),this.dataKey)}response(){return this.$__response}payload(){return null}query(){return this.$__query}status(){return null}success(){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 K{constructor(e,t){this.client=e,this.knishIOClient=t,this.$__variables=null,this.$__query=null,this.$__response=null,this.$__request=null}response(){return this.$__response}async createResponseRaw(e){return this.createResponse(e)}createResponse(e){return new E({query:this,json:e})}createQuery({variables:e=null}){if(this.$__variables=this.compiledVariables(e),!this.uri())throw new Y("Query::createQuery() - Node URI was not initialized for this client instance!");if(this.$__query===null)throw new Y("Query::createQuery() - GraphQL subscription was not initialized!");return{query:this.$__query,variables:this.variables()}}async execute({variables:e=null,context:t={}}){this.$__request=this.createQuery({variables:e});const n={...t,...this.createQueryContext()};try{const s=await this.client.query({...this.$__request,context:n});return this.$__response=await this.createResponseRaw(s),this.$__response}catch(s){if(s.name==="AbortError")return this.knishIOClient.log("warn","Query was cancelled"),new E({query:this,json:{data:null,errors:[{message:"Query was cancelled"}]}});throw s}}compiledVariables(e=null){return e||{}}uri(){return this.client.getUri()}variables(){return this.$__variables}createQueryContext(){return{}}}class ln extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.ContinuId"})}payload(){let e=null;const t=this.data();return t&&(e=new S({secret:null,token:t.tokenSlug}),e.address=t.address,e.position=t.position,e.bundle=t.bundleHash,e.batchId=t.batchId,e.characters=t.characters,e.pubkey=t.pubkey,e.balance=String(t.amount!=null?t.amount:0)),e}}class cn extends K{constructor(e,t){super(e,t),this.$__query=A.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 ae{static create(e){const t={};for(const n of Object.keys(e))Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return new this(t)}static structure(e){switch(Object.prototype.toString.call(e)){case"[object Array]":{const t=[];for(const n in e)t.push(ae.isStructure(e[n])?ae.structure(e[n]):e[n]);return t}case"[object Object]":{const t=[],n=Object.keys(e).sort((s,r)=>s===r?0:s<r?-1:1);for(const s of n)if(Object.prototype.hasOwnProperty.call(e,s)){const r={};r[s]=ae.isStructure(e[s])?ae.structure(e[s]):e[s],t.push(r)}if(t.length>0)return t;break}}return e}static isStructure(e){return["[object Object]","[object Array]"].includes(Object.prototype.toString.call(e))}view(){return ae.structure(this)}}class ds extends ae{constructor({position:e=null,walletAddress:t=null,isotope:n=null,token:s=null,value:r=null,batchId:i=null,metaType:o=null,metaId:c=null,meta:u=null,index:l=null,createdAt:d=null,version:f=null}){super(),this.position=e,this.walletAddress=t,this.isotope=n,this.token=s,this.value=r,this.batchId=i,this.metaType=o,this.metaId=c,this.meta=u,this.index=l,this.createdAt=d,this.version=f}}const Ke={4:ds};class g{constructor({position:e=null,walletAddress:t=null,isotope:n=null,token:s=null,value:r=null,batchId:i=null,metaType:o=null,metaId:c=null,meta:u=null,otsFragment:l=null,index:d=null,version:f=null}){this.position=e,this.walletAddress=t,this.isotope=n,this.token=s,this.value=r!==null?String(r):null,this.batchId=i,this.metaType=o,this.metaId=c,this.meta=u?ie.normalizeMeta(u):[],this.index=d,this.otsFragment=l,this.createdAt=String(+new Date),f!==null&&Object.prototype.hasOwnProperty.call(Ke,f)&&(this.version=String(f))}static getHashableProps(){return["position","walletAddress","isotope","token","value","batchId","metaType","metaId","meta","createdAt"]}static getUnclaimedProps(){return["otsFragment"]}static create({isotope:e,wallet:t=null,value:n=null,metaType:s=null,metaId:r=null,meta:i=null,batchId:o=null}){return i||(i=new H),i instanceof H||(i=new H(i)),t&&(i.setAtomWallet(t),o||(o=t.batchId)),new g({position:t?t.position:null,walletAddress:t?t.address:null,isotope:e,token:t?t.token:null,value:n,batchId:o,metaType:s,metaId:r,meta:i.get()})}static jsonToObject(e){const t=Object.assign(new 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 o=["position","walletAddress","isotope","token"];for(const c of o)if(!r[c])throw new Error(`Required field '${c}' is missing or empty`)}const i=new 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 q("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(Ke,r.version)))n.update(JSON.stringify(s.map(r=>Ke[r.version].create(r).view())));else{const r=String(e.length);let i=[];for(const o of s)i.push(r),i=i.concat(o.getHashableValues());for(const o of i)n.update(o)}switch(t){case"hex":return n.getHash("HEX",{outputLen:256});case"array":return n.getHash("ARRAYBUFFER",{outputLen:256});default:return $t(n.getHash("HEX",{outputLen:256}),16,17,"0123456789abcdef","0123456789abcdefg").padStart(64,"0")}}static jsonSerialization(e,t){if(!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 ie.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 Ne(a=null,e=2048){if(a){const t=new q("SHAKE256","TEXT");return t.update(a),t.getHash("HEX",{outputLen:e*4})}else return Ue(e)}function oe(a,e=null){const t=new q("SHAKE256","TEXT");return t.update(a),t.getHash("HEX",{outputLen:256})}function et(a,e){const t=new q("SHAKE256","TEXT");return t.update(a),t.getHash("HEX",{outputLen:e})}function le({molecularHash:a=null,index:e=null}){return a!==null&&e!==null?oe(String(a)+String(e),"generateBatchId"):Ue(64)}class ce{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 ce(e.id,e.name,t)}static createFromDB(e){return new ce(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 tt 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),Rt=BigInt(32);function ps(a,e=!1){return e?{h:Number(a&Qe),l:Number(a>>Rt&Qe)}:{h:Number(a>>Rt&Qe)|0,l:Number(a&Qe)|0}}function fs(a,e=!1){const t=a.length;let n=new Uint32Array(t),s=new Uint32Array(t);for(let r=0;r<t;r++){const{h:i,l:o}=ps(a[r],e);[n[r],s[r]]=[i,o]}return[n,s]}const ms=(a,e,t)=>a<<t|e>>>32-t,ys=(a,e,t)=>e<<t|a>>>32-t,gs=(a,e,t)=>e<<t-32|a>>>64-t,bs=(a,e,t)=>a<<t-32|e>>>64-t;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ws(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&a.constructor.name==="Uint8Array"}function Ot(a,e=""){if(!Number.isSafeInteger(a)||a<0){const t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${a}`)}}function D(a,e,t=""){const n=ws(a),s=a==null?void 0:a.length,r=e!==void 0;if(!n||r&&s!==e){const i=t&&`"${t}" `,o=r?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof a}`;throw new Error(i+"expected Uint8Array"+o+", got "+c)}return a}function qt(a,e=!0){if(a.destroyed)throw new Error("Hash instance has been destroyed");if(e&&a.finished)throw new Error("Hash#digest() has already been called")}function ks(a,e){D(a,void 0,"digestInto() output");const t=e.outputLen;if(a.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function Wt(a){return new Uint32Array(a.buffer,a.byteOffset,Math.floor(a.byteLength/4))}function Bt(...a){for(let e=0;e<a.length;e++)a[e].fill(0)}const Ss=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function _s(a){return a<<24&4278190080|a<<8&16711680|a>>>8&65280|a>>>24&255}function $s(a){for(let e=0;e<a.length;e++)a[e]=_s(a[e]);return a}const Ut=Ss?a=>a:$s;function Ht(a,e={}){const t=(s,r)=>a(r).update(s).digest(),n=a(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=s=>a(s),Object.assign(t,e),Object.freeze(t)}function As(a=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(a))}const Fe=a=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,a])}),vs=BigInt(0),Ae=BigInt(1),Is=BigInt(2),Ms=BigInt(7),Ts=BigInt(256),Cs=BigInt(113),Pt=[],Kt=[],Nt=[];for(let a=0,e=Ae,t=1,n=0;a<24;a++){[t,n]=[n,(2*t+3*n)%5],Pt.push(2*(5*n+t)),Kt.push((a+1)*(a+2)/2%64);let s=vs;for(let r=0;r<7;r++)e=(e<<Ae^(e>>Ms)*Cs)%Ts,e&Is&&(s^=Ae<<(Ae<<BigInt(r))-Ae);Nt.push(s)}const Qt=fs(Nt,!0),xs=Qt[0],Es=Qt[1],Ft=(a,e,t)=>t>32?gs(a,e,t):ms(a,e,t),Lt=(a,e,t)=>t>32?bs(a,e,t):ys(a,e,t);function Rs(a,e=24){const t=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let i=0;i<10;i++)t[i]=a[i]^a[i+10]^a[i+20]^a[i+30]^a[i+40];for(let i=0;i<10;i+=2){const o=(i+8)%10,c=(i+2)%10,u=t[c],l=t[c+1],d=Ft(u,l,1)^t[o],f=Lt(u,l,1)^t[o+1];for(let p=0;p<50;p+=10)a[i+p]^=d,a[i+p+1]^=f}let s=a[2],r=a[3];for(let i=0;i<24;i++){const o=Kt[i],c=Ft(s,r,o),u=Lt(s,r,o),l=Pt[i];s=a[l],r=a[l+1],a[l]=c,a[l+1]=u}for(let i=0;i<50;i+=10){for(let o=0;o<10;o++)t[o]=a[i+o];for(let o=0;o<10;o++)a[i+o]^=~t[(o+2)%10]&t[(o+4)%10]}a[0]^=xs[n],a[1]^=Es[n]}Bt(t)}class Le{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,Ot(n,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Wt(this.state)}clone(){return this._cloneInto()}keccak(){Ut(this.state32),Rs(this.state32,this.rounds),Ut(this.state32),this.posOut=0,this.pos=0}update(e){qt(this),D(e);const{blockLen:t,state:n}=this,s=e.length;for(let r=0;r<s;){const i=Math.min(t-this.pos,s-r);for(let o=0;o<i;o++)n[this.pos++]^=e[r++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:s}=this;e[n]^=t,(t&128)!==0&&n===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){qt(this,!1),D(e),this.finish();const t=this.state,{blockLen:n}=this;for(let s=0,r=e.length;s<r;){this.posOut>=n&&this.keccak();const i=Math.min(n-this.posOut,r-s);e.set(t.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Ot(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ks(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,Bt(this.state)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:s,rounds:r,enableXOF:i}=this;return e||(e=new Le(t,n,s,i,r)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=r,e.suffix=n,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}}const jt=(a,e,t,n={})=>Ht(()=>new Le(e,a,t),n),Os=jt(6,136,32,Fe(8)),qs=jt(6,72,64,Fe(10)),Dt=(a,e,t,n={})=>Ht((s={})=>new Le(e,a,s.dkLen===void 0?t:s.dkLen,!0),n),Ws=Dt(31,168,16,Fe(11)),Vt=Dt(31,136,32,Fe(12));function nt(a){if(!Number.isSafeInteger(a)||a<0||a>4294967295)throw new Error("wrong u32 integer:"+a);return a}function zt(a){return nt(a),(a&a-1)===0&&a!==0}function Jt(a,e){nt(a);let t=0;for(let n=0;n<e;n++,a>>>=1)t=t<<1|a&1;return t}function Gt(a){return nt(a),31-Math.clz32(a)}function Xt(a){const e=a.length;if(e<2||!zt(e))throw new Error("n must be a power of 2 and greater than 1. Got "+e);const t=Gt(e);for(let n=0;n<e;n++){const s=Jt(n,t);if(n<s){const r=a[n];a[n]=a[s],a[s]=r}}return a}const Zt=(a,e)=>{const{N:t,roots:n,dit:s,invertButterflies:r=!1,skipStages:i=0,brp:o=!0}=e,c=Gt(t);if(!zt(t))throw new Error("FFT: Polynomial size should be power of two");const u=s!==r;return l=>{if(l.length!==t)throw new Error("FFT: wrong Polynomial length");s&&o&&Xt(l);for(let d=0,f=1;d<c-i;d++){const p=s?d+1+i:c-d,w=1<<p,I=w>>1,R=t>>p;for(let m=0;m<t;m+=w)for(let b=0,k=f++;b<I;b++){const O=r?s?t-k:k:b*R,_=m+b,v=m+b+I,M=n[O],x=l[v],$=l[_];if(u){const Q=a.mul(x,M);l[_]=a.add($,Q),l[v]=a.sub($,Q)}else r?(l[_]=a.add(x,$),l[v]=a.mul(a.sub(x,$),M)):(l[_]=a.add($,x),l[v]=a.mul(a.sub($,x),M))}}return!s&&o&&Xt(l),l}};/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */const Yt=As;function st(a,e){if(a.length!==e.length)return!1;let t=0;for(let n=0;n<a.length;n++)t|=a[n]^e[n];return t===0}function Bs(a){return Uint8Array.from(a)}function je(a,...e){const t=s=>typeof s=="number"?s:s.bytesLen,n=e.reduce((s,r)=>s+t(r),0);return{bytesLen:n,encode:s=>{const r=new Uint8Array(n);for(let i=0,o=0;i<e.length;i++){const c=e[i],u=t(c),l=typeof c=="number"?s[i]:c.encode(s[i]);D(l,u,a),r.set(l,o),typeof c!="number"&&l.fill(0),o+=u}return r},decode:s=>{D(s,n,a);const r=[];for(const i of e){const o=t(i),c=s.subarray(0,o);r.push(typeof i=="number"?c:i.decode(c)),s=s.subarray(o)}return r}}}function rt(a,e){const t=e*a.bytesLen;return{bytesLen:t,encode:n=>{if(n.length!==e)throw new Error(`vecCoder.encode: wrong length=${n.length}. Expected: ${e}`);const s=new Uint8Array(t);for(let r=0,i=0;r<n.length;r++){const o=a.encode(n[r]);s.set(o,i),o.fill(0),i+=o.length}return s},decode:n=>{D(n,t);const s=[];for(let r=0;r<n.length;r+=a.bytesLen)s.push(a.decode(n.subarray(r,r+a.bytesLen)));return s}}}function X(...a){for(const e of a)if(Array.isArray(e))for(const t of e)t.fill(0);else e.fill(0)}function en(a){return(1<<a)-1}/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */const Us=a=>{const{newPoly:e,N:t,Q:n,F:s,ROOT_OF_UNITY:r,brvBits:i}=a,o=(m,b=n)=>{const k=m%b|0;return(k>=0?k|0:b+k|0)|0},c=(m,b=n)=>{const k=o(m,b)|0;return(k>b>>1?k-b|0:k)|0};function u(){const m=e(t);for(let b=0;b<t;b++){const k=Jt(b,i),O=BigInt(r)**BigInt(k)%BigInt(n);m[b]=Number(O)|0}return m}const l=u(),d={add:(m,b)=>o((m|0)+(b|0))|0,sub:(m,b)=>o((m|0)-(b|0))|0,mul:(m,b)=>o((m|0)*(b|0))|0,inv:m=>{throw new Error("not implemented")}},f={N:t,roots:l,invertButterflies:!0,skipStages:1,brp:!1},p=Zt(d,{dit:!1,...f}),w=Zt(d,{dit:!0,...f});return{mod:o,smod:c,nttZetas:l,NTT:{encode:m=>p(m),decode:m=>{w(m);for(let b=0;b<m.length;b++)m[b]=o(s*m[b]);return m}},bitsCoder:(m,b)=>{const k=en(m),O=m*(t/8);return{bytesLen:O,encode:_=>{const v=new Uint8Array(O);for(let M=0,x=0,$=0,Q=0;M<_.length;M++)for(x|=(b.encode(_[M])&k)<<$,$+=m;$>=8;$-=8,x>>=8)v[Q++]=x&en($);return v},decode:_=>{const v=e(t);for(let M=0,x=0,$=0,Q=0;M<_.length;M++)for(x|=_[M]<<$,$+=8;$>=m;$-=m,x>>=m)v[Q++]=b.decode(x&k);return v}}}}},Hs=(a=>(e,t)=>{t||(t=a.blockLen);const n=new Uint8Array(e.length+2);n.set(e);const s=e.length,r=new Uint8Array(t);let i=a.create({}),o=0,c=0;return{stats:()=>({calls:o,xofs:c}),get:(u,l)=>(n[s+0]=u,n[s+1]=l,i.destroy(),i=a.create({}).update(n),o++,()=>(c++,i.xofInto(r))),clean:()=>{i.destroy(),X(r,n)}}})(Ws);/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */const L=256,ue=3329,Ps=3303,Ks=17,{mod:ve,nttZetas:Ns,NTT:he,bitsCoder:Qs}=Us({N:L,Q:ue,F:Ps,ROOT_OF_UNITY:Ks,newPoly:a=>new Uint16Array(a),brvBits:7}),Fs={768:{N:L,Q:ue,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192}},Ls=a=>{if(a>=12)return{encode:t=>t,decode:t=>t};const e=2**(a-1);return{encode:t=>((t<<a)+ue/2)/ue,decode:t=>t*ue+e>>>a}},Ie=a=>Qs(a,Ls(a));function de(a,e){for(let t=0;t<L;t++)a[t]=ve(a[t]+e[t])}function js(a,e){for(let t=0;t<L;t++)a[t]=ve(a[t]-e[t])}function Ds(a,e,t,n,s){const r=ve(e*n*s+a*t),i=ve(a*n+e*t);return{c0:r,c1:i}}function De(a,e){for(let t=0;t<L/2;t++){let n=Ns[64+(t>>1)];t&1&&(n=-n);const{c0:s,c1:r}=Ds(a[2*t+0],a[2*t+1],e[2*t+0],e[2*t+1],n);a[2*t+0]=s,a[2*t+1]=r}return a}function tn(a){const e=new Uint16Array(L);for(let t=0;t<L;){const n=a();if(n.length%3)throw new Error("SampleNTT: unaligned block");for(let s=0;t<L&&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<ue&&(e[t++]=r),t<L&&i<ue&&(e[t++]=i)}}return e}function Me(a,e,t,n){const s=a(n*L/4,e,t),r=new Uint16Array(L),i=Wt(s);let o=0;for(let c=0,u=0,l=0,d=0;c<i.length;c++){let f=i[c];for(let p=0;p<32;p++)l+=f&1,f>>=1,o+=1,o===n?(d=l,l=0):o===2*n&&(r[u++]=ve(d-l),l=0,o=0)}if(o)throw new Error(`sampleCBD: leftover bits: ${o}`);return r}const Vs=a=>{const{K:e,PRF:t,XOF:n,HASH512:s,ETA1:r,ETA2:i,du:o,dv:c}=a,u=Ie(1),l=Ie(c),d=Ie(o),f=je("publicKey",rt(Ie(12),e),32),p=rt(Ie(12),e),w=je("ciphertext",rt(d,e),l),I=je("seed",32,32);return{secretCoder:p,lengths:{secretKey:p.bytesLen,publicKey:f.bytesLen,cipherText:w.bytesLen},keygen:R=>{D(R,32,"seed");const m=new Uint8Array(33);m.set(R),m[32]=e;const b=s(m),[k,O]=I.decode(b),_=[],v=[];for(let $=0;$<e;$++)_.push(he.encode(Me(t,O,$,r)));const M=n(k);for(let $=0;$<e;$++){const Q=he.encode(Me(t,O,e+$,r));for(let U=0;U<e;U++){const _e=tn(M.get(U,$));de(Q,De(_e,_[U]))}v.push(Q)}M.clean();const x={publicKey:f.encode([v,k]),secretKey:p.encode(_)};return X(k,O,_,v,m,b),x},encrypt:(R,m,b)=>{const[k,O]=f.decode(R),_=[];for(let U=0;U<e;U++)_.push(he.encode(Me(t,b,U,r)));const v=n(O),M=new Uint16Array(L),x=[];for(let U=0;U<e;U++){const _e=Me(t,b,e+U,i),St=new Uint16Array(L);for(let Ze=0;Ze<e;Ze++){const Sr=tn(v.get(U,Ze));de(St,De(Sr,_[Ze]))}de(_e,he.decode(St)),x.push(_e),de(M,De(k[U],_[U])),X(St)}v.clean();const $=Me(t,b,2*e,i);de($,he.decode(M));const Q=u.decode(m);return de(Q,$),X(k,_,M,$),w.encode([x,Q])},decrypt:(R,m)=>{const[b,k]=w.decode(R),O=p.decode(m),_=new Uint16Array(L);for(let v=0;v<e;v++)de(_,De(O[v],he.encode(b[v])));return js(k,he.decode(_)),X(_,O,b),u.encode(k)}}};function zs(a){const e=Vs(a),{HASH256:t,HASH512:n,KDF:s}=a,{secretCoder:r,lengths:i}=e,o=je("secretKey",i.secretKey,i.publicKey,32,32),c=32,u=64;return{info:{type:"ml-kem"},lengths:{...i,seed:64,msg:c,msgRand:c,secretKey:o.bytesLen},keygen:(l=Yt(u))=>{D(l,u,"seed");const{publicKey:d,secretKey:f}=e.keygen(l.subarray(0,32)),p=t(d),w=o.encode([f,d,p,l.subarray(32)]);return X(f,p),{publicKey:d,secretKey:w}},getPublicKey:l=>{const[d,f]=o.decode(l);return Uint8Array.from(f)},encapsulate:(l,d=Yt(c))=>{D(l,i.publicKey,"publicKey"),D(d,c,"message");const f=l.subarray(0,384*a.K),p=r.encode(r.decode(Bs(f)));if(!st(p,f))throw X(p),new Error("ML-KEM.encapsulate: wrong publicKey modulus");X(p);const w=n.create().update(d).update(t(l)).digest(),I=e.encrypt(l,d,w.subarray(32,64));return X(w.subarray(32)),{cipherText:I,sharedSecret:w.subarray(0,32)}},decapsulate:(l,d)=>{D(d,o.bytesLen,"secretKey"),D(l,i.cipherText,"cipherText");const f=o.bytesLen-96,p=f+32,w=t(d.subarray(f/2,p));if(!st(w,d.subarray(p,p+32)))throw new Error("invalid secretKey: hash check failed");const[I,R,m,b]=o.decode(d),k=e.decrypt(l,I),O=n.create().update(k).update(m).digest(),_=O.subarray(0,32),v=e.encrypt(R,k,O.subarray(32,64)),M=st(l,v),x=s.create({dkLen:32}).update(b).update(l).digest();return X(k,v,M?x:_),M?_:x}}}function Js(a,e,t){return Vt.create({dkLen:a}).update(e).update(new Uint8Array([t])).digest()}const it=zs({...{HASH256:Os,HASH512:qs,KDF:Vt,XOF:Hs,PRF:Js},...Fs[768]});class S{constructor({secret:e=null,bundle:t=null,token:n="USER",address:s=null,position:r=null,batchId:i=null,characters:o=null}){this.token=n,this.balance="0",this.molecules={},this.key=null,this.privkey=null,this.pubkey=null,this.tokenUnits=[],this.tradeRates={},this.address=s,this.position=r,this.bundle=t,this.batchId=i,this.characters=o,e&&(this.bundle=this.bundle||oe(e,"Wallet::constructor"),this.position=this.position||S.generatePosition(),this.key=S.generateKey({secret:e,token:this.token,position:this.position}),this.address=this.address||S.generateAddress(this.key),this.characters=this.characters||"BASE64",this.initializeMLKEM())}static create({secret:e=null,bundle:t=null,token:n,batchId:s=null,characters:r=null}){let i=null;if(!e&&!t)throw new tt;return e&&!t&&(i=S.generatePosition(),t=oe(e,"Wallet::create")),new S({secret:e,bundle:t,token:n,position:i,batchId:s,characters:r})}static isBundleHash(e){return typeof e!="string"?!1:e.length===64&&He(e)}static getTokenUnits(e){const t=[];return e.forEach(n=>{t.push(ce.createFromDB(n))}),t}static generateKey({secret:e,token:t,position:n}){if(!e)throw new tt("Wallet::generateKey() - Secret is required!");if(!n)throw new tt("Wallet::generateKey() - Position is required!");const s=He(e)?e:et(e,1024),r=He(n)?n:et(n,256),o=BigInt(`0x${s}`)+BigInt(`0x${r}`),c=new q("SHAKE256","TEXT");c.update(o.toString(16)),t&&c.update(t);const u=new q("SHAKE256","TEXT");return u.update(c.getHash("HEX",{outputLen:8192})),u.getHash("HEX",{outputLen:8192})}static generateAddress(e){const t=$e(e,128),n=new q("SHAKE256","TEXT");for(const r in t){let i=t[r];for(let o=1;o<=16;o++){const c=new q("SHAKE256","TEXT");c.update(i),i=c.getHash("HEX",{outputLen:512})}n.update(i)}const s=new q("SHAKE256","TEXT");return s.update(n.getHash("HEX",{outputLen:8192})),s.getHash("HEX",{outputLen:256})}static generatePosition(e=64){return Ue(e,"abcdef0123456789")}initializeMLKEM(){const e=Ne(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}=it.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=S.create({secret:e,token:this.token,characters:this.characters});return t.initBatchId({sourceWallet:this,isRemainder:!0}),t}isShadow(){return(typeof this.position>"u"||this.position===null)&&(typeof this.address>"u"||this.address===null)}initBatchId({sourceWallet:e,isRemainder:t=!1}){e.batchId&&(this.batchId=t?e.batchId:le({}))}async encryptMessage(e,t){const n=JSON.stringify(e),s=new TextEncoder().encode(n),r=this.deserializeKey(t),{cipherText:i,sharedSecret:o}=it.encapsulate(r),c=await this.encryptWithSharedSecret(s,o);return{cipherText:this.serializeKey(i),encryptedMessage:this.serializeKey(c)}}async decryptMessage(e){const{cipherText:t,encryptedMessage:n}=e;let s;try{s=it.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 o;try{o=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(o)}async encryptWithSharedSecret(e,t){const n=crypto.getRandomValues(new Uint8Array(12)),s={name:"AES-GCM",iv:n},r=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["encrypt"]),i=await crypto.subtle.encrypt(s,r,e),o=new Uint8Array(n.length+i.byteLength);return o.set(n),o.set(new Uint8Array(i),n.length),o}async decryptWithSharedSecret(e,t){const s={name:"AES-GCM",iv:e.slice(0,12)},r=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=await crypto.subtle.decrypt(s,r,e.slice(12));return new Uint8Array(i)}}class ge extends T{constructor(e="There is an atom without an index",t=null,n=null){super(e,t,n),this.name="AtomIndexException"}}class nn extends T{constructor(e="The molecular hash does not match",t=null,n=null){super(e,t,n),this.name="MolecularHashMismatchException"}}class sn extends T{constructor(e="The molecular hash is missing",t=null,n=null){super(e,t,n),this.name="MolecularHashMissingException"}}class at extends T{constructor(e="",t=null,n=null){super(e,t,n),this.name="PolicyInvalidException"}}class ot extends T{constructor(e="OTS malformed",t=null,n=null){super(e,t,n),this.name="SignatureMalformedException"}}class rn extends T{constructor(e="One-time signature (OTS) does not match!",t=null,n=null){super(e,t,n),this.name="SignatureMismatchException"}}class Z extends T{constructor(e="Insufficient balance to make transfer",t=null,n=null){super(e,t,n),this.name="TransferBalanceException"}}class be extends T{constructor(e="Token transfer atoms are malformed",t=null,n=null){super(e,t,n),this.name="TransferMalformedException"}}class lt 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 ct extends T{constructor(e="Invalid remainder provided",t=null,n=null){super(e,t,n),this.name="TransferRemainderException"}}class an extends T{constructor(e="Sender and recipient(s) cannot be the same",t=null,n=null){super(e,t,n),this.name="TransferToSelfException"}}class Te 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 re extends T{constructor(e="Wrong type of token for this isotope",t=null,n=null){super(e,t,n),this.name="WrongTokenTypeException"}}class Ce extends T{constructor(e="Incorrect BatchId",t=null,n=null){super(e,t,n),this.name="BatchIdException"}}class on{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 Ve extends T{constructor(e="An incorrect argument!",t=null,n=null){super(e,t,n),this.name="RuleArgumentException"}}class Y extends T{constructor(e="Code exception",t=null,n=null){super(e,t,n),this.name="CodeException"}}class xe{constructor({action:e,metaType:t=null,metaId:n=null,meta:s=null,address:r=null,token:i=null,amount:o=null,comparison:c=null}){if(s&&(this.meta=s),!e)throw new Ve('Callback structure violated, missing mandatory "action" parameter.');this.__metaId=n,this.__metaType=t,this.__action=e,this.__address=r,this.__token=i,this.__amount=o,this.__comparison=c}set comparison(e){this.__comparison=e}set amount(e){if(!Tt(e))throw new Y("Parameter amount should be a string containing numbers");this.__amount=e}set token(e){this.__token=e}set address(e){this.__address=e}set meta(e){this.__meta=e instanceof on?e:on.toObject(e)}set metaType(e){this.__metaType=e}set metaId(e){this.__metaId=e}static toObject(e){const t=new xe({action:e.action});return e.metaType&&(t.metaType=e.metaType),e.metaId&&(t.metaId=e.metaId),e.meta&&(t.meta=e.meta),e.address&&(t.address=e.address),e.token&&(t.token=e.token),e.amount&&(t.amount=e.amount),e.comparison&&(t.comparison=e.comparison),t}toJSON(){const e={action:this.__action};return this.__metaType&&(e.metaType=this.__metaType),this.__metaId&&(e.metaId=this.__metaId),this.__meta&&(e.meta=this.__meta),this.__address&&(e.address=this.__address),this.__token&&(e.token=this.__token),this.__amount&&(e.amount=this.__amount),this.__comparison&&(e.comparison=this.__comparison),e}isReject(){return this._is("reject")}isMeta(){return ye(Object.keys(this.toJSON()),["action","metaId","metaType","meta"]).length===4&&this._is("meta")}isCollect(){return ye(Object.keys(this.toJSON()),["action","address","token","amount","comparison"]).length===5&&this._is("collect")}isBuffer(){return ye(Object.keys(this.toJSON()),["action","address","token","amount","comparison"]).length===5&&this._is("buffer")}isRemit(){return ye(Object.keys(this.toJSON()),["action","token","amount"]).length===3&&this._is("remit")}isBurn(){return ye(Object.keys(this.toJSON()),["action","token","amount","comparison"]).length===4&&this._is("burn")}_is(e){return this.__action.toLowerCase()===e.toLowerCase()}}class ut{constructor({key:e,value:t,comparison:n}){if([e,t,n].some(s=>!s))throw new Ve("Condition::constructor( { key, value, comparison } ) - not all class parameters are initialised!");this.__key=e,this.__value=t,this.__comparison=n}static toObject(e){return new this({key:e.key,value:e.value,comparison:e.comparison})}toJSON(){return{key:this.__key,value:this.__value,comparison:this.__comparison}}}class Ee{constructor({condition:e=[],callback:t=[]}){for(const n of e)if(!(n instanceof ut))throw new Ve;for(const n of t)if(!(n instanceof xe))throw new Ve;this.__condition=e,this.__callback=t}set comparison(e){this.__condition.push(e instanceof ut?e:ut.toObject(e))}set callback(e){this.__callback.push(e instanceof xe?e:xe.toObject(e))}static toObject(e){if(!e.condition)throw new P("Rule::toObject() - Incorrect rule format! There is no condition field.");if(!e.callback)throw new P("Rule::toObject() - Incorrect rule format! There is no callback field.");const t=new Ee({});for(const n of e.condition)t.comparison=n;for(const n of e.callback)t.callback=n;return t}toJSON(){return{condition:this.__condition,callback:this.__callback}}}class C{static __init(e,t){this.arr=String(t).split("."),this.key=this.arr.shift();const n=Number(this.key);Number.isInteger(n)&&(this.key=n),this.__nextKey=this.arr.length,this.__next=this.__tic(e)}static __tic(e){return!Array.isArray(e)&&!(e instanceof Object)?!1:typeof e[this.key]<"u"}static has(e,t){return this.__init(e,t),this.__next?this.__nextKey===0?!0:this.has(e[this.key],this.arr.join(".")):!1}static get(e,t,n=null){return this.__init(e,t),this.__next?this.__nextKey===0?e[this.key]:this.get(e[this.key],this.arr.join("."),n):n}static set(e,t,n){const s=t.split(".");let r=e;const i=s.length-1;for(let u=0;u<i;u++){const l=s[u],d=Number(l),f=Number.isInteger(d);(f?d:l in r)||(r[f?d:l]=s[u+1].match(/^\d+$/)?[]:{}),r=r[f?d:l]}const o=s[i],c=Number(o);return r[Number.isInteger(c)?c:o]=n,e}}class we{constructor(e){if(e.molecularHash===null)throw new sn;if(!e.atoms.length)throw new se;for(const t of e.atoms)if(t.index===null)throw new ge;this.molecule=e}verify(e){return this.molecularHash()&&this.ots()&&this.batchId()&&this.continuId()&&this.isotopeM()&&this.isotopeT()&&this.isotopeC()&&this.isotopeU()&&this.isotopeI()&&this.isotopeR()&&this.isotopeP()&&this.isotopeA()&&this.isotopeB()&&this.isotopeF()&&this.isotopeV(e)}continuId(){if(this.molecule.atoms[0].token==="USER"&&this.molecule.getIsotopes("I").length<1)throw new se("Check::continuId() - Molecule is missing required ContinuID Atom!");return!0}batchId(){if(this.molecule.atoms.length>0){const e=this.molecule.atoms[0];if(e.isotope==="V"&&e.batchId!==null){const t=this.molecule.getIsotopes("V"),n=t[t.length-1];if(e.batchId!==n.batchId)throw new Ce;for(const s of t)if(s.batchId===null)throw new Ce}return!0}throw new Ce}isotopeI(){for(const e of this.molecule.getIsotopes("I")){if(e.token!=="USER")throw new re(`Check::isotopeI() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index===0)throw new ge(`Check::isotopeI() - Isotope "${e.isotope}" Atoms must have a non-zero index!`)}return!0}isotopeU(){for(const e of this.molecule.getIsotopes("U")){if(e.token!=="AUTH")throw new re(`Check::isotopeU() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index!==0)throw new ge(`Check::isotopeU() - Isotope "${e.isotope}" Atoms must have an index equal to 0!`)}return!0}isotopeM(){const e=["readPolicy","writePolicy"];for(const t of this.molecule.getIsotopes("M")){if(t.meta.length<1)throw new P;if(t.token!=="USER")throw new re(`Check::isotopeM() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);const n=ie.aggregateMeta(t.meta);for(const s of e){let r=n[s];if(r){r=JSON.parse(r);for(const[i,o]of Object.entries(r))if(!e.includes(i)){if(!Object.keys(n).includes(i))throw new at(`${i} is missing from the meta.`);for(const c of o)if(!S.isBundleHash(c)&&!["all","self"].includes(c))throw new at(`${c} does not correspond to the format of the policy.`)}}}}return!0}isotopeC(){for(const e of this.molecule.getIsotopes("C")){if(e.token!=="USER")throw new re(`Check::isotopeC() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index!==0)throw new ge(`Check::isotopeC() - Isotope "${e.isotope}" Atoms must have an index equal to 0!`)}return!0}isotopeT(){for(const e of this.molecule.getIsotopes("T")){const t=e.aggregatedMeta();if(String(e.metaType).toLowerCase()==="wallet"){for(const s of["position","bundle"])if(!Object.prototype.hasOwnProperty.call(t,s)||!t[s])throw new 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 re(`Check::isotopeT() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index!==0)throw new ge(`Check::isotopeT() - Isotope "${e.isotope}" Atoms must have an index equal to 0!`)}return!0}isotopeR(){for(const e of this.molecule.getIsotopes("R")){const t=e.aggregatedMeta();if(t.policy){const n=JSON.parse(t.policy);if(!Object.keys(n).every(s=>["read","write"].includes(s)))throw new P("Check::isotopeR() - Mixing rules with politics!")}if(t.rule){const n=JSON.parse(t.rule);if(!Array.isArray(n))throw new P("Check::isotopeR() - Incorrect rule format!");for(const s of n)Ee.toObject(s);if(n.length<1)throw new P("Check::isotopeR() - No rules!")}}return!0}isotopeP(){for(const e of this.molecule.getIsotopes("P")){if(e.token!=="USER")throw new re(`Check::isotopeP() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);const t=e.aggregatedMeta();if(!Object.prototype.hasOwnProperty.call(t,"peerHost")||!t.peerHost)throw new 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 re(`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 be("Check::isotopeB() - B-isotope atom value is not a valid number!")}const t=this.molecule.getIsotopes("V");if(t.length>0){let n=0;for(const s of[...t,...e]){const r=Number(s.value);Number.isNaN(r)||(n+=r)}if(n!==0)throw new Te("Check::isotopeB() - V+B atom values do not balance to zero!")}return!0}isotopeF(){const e=this.molecule.getIsotopes("F");if(e.length===0)return!0;for(const n of e){if(!n.metaType||n.metaType!=="walletBundle")throw new P('Check::isotopeF() - F-isotope atoms must have metaType "walletBundle"!');if(!n.metaId)throw new P("Check::isotopeF() - F-isotope atoms must have a metaId!");const s=Number(n.value);if(Number.isNaN(s))throw new be("Check::isotopeF() - F-isotope atom value is not a valid number!");if(s<0)throw new be("Check::isotopeF() - F-isotope atom value must not be negative!")}const t=this.molecule.getIsotopes("V");if(t.length>0){let n=0;for(const s of[...t,...e]){const r=Number(s.value);Number.isNaN(r)||(n+=r)}if(n!==0)throw new Te("Check::isotopeF() - V+F atom values do not balance to zero!")}return!0}isotopeV(e=null){const t=this.molecule.getIsotopes("V");if(t.length===0)return!0;const n=this.molecule.getIsotopes("B").length>0||this.molecule.getIsotopes("F").length>0,s=this.molecule.atoms[0];if(!n&&s.isotope==="V"&&t.length===2){const o=t[t.length-1];if(s.token!==o.token)throw new lt;if(o.value<0)throw new be;if(Number(s.value)+Number(o.value)!==0)throw new Te;return!0}let r=0,i=0;for(const o in this.molecule.atoms)if(Object.prototype.hasOwnProperty.call(this.molecule.atoms,o)){const c=this.molecule.atoms[o];if(c.isotope!=="V")continue;if(i=c.value*1,Number.isNaN(i))throw new TypeError('Invalid isotope "V" values');if(c.token!==s.token)throw new lt;if(o>0){if(i<0)throw new be;if(c.walletAddress===s.walletAddress)throw new an}r+=i}if(!n&&r!==0)throw new Te;if(e){if(i=s.value*1,Number.isNaN(i))throw new TypeError('Invalid isotope "V" values');const o=Number(e.balance)+i;if(o<0)throw new Z;if(!n&&o!==r)throw new ct}else if(i!==0)throw new ct;return!0}molecularHash(){if(this.molecule.molecularHash!==g.hashAtoms({atoms:this.molecule.atoms}))throw new nn;return!0}ots(){const e=this.molecule.normalizedHash();let t=this.molecule.atoms.map(f=>f.otsFragment).reduce((f,p)=>f+p);if(t.length!==2048&&(t=Mt(t),t.length!==2048))throw new ot;const n=$e(t,128);let s="";for(const f in n){let p=n[f];for(let w=0,I=8+e[f];w<I;w++)p=new q("SHAKE256","TEXT").update(p).getHash("HEX",{outputLen:512});s+=p}const r=new q("SHAKE256","TEXT");r.update(s);const i=r.getHash("HEX",{outputLen:8192}),o=new q("SHAKE256","TEXT");o.update(i);const c=o.getHash("HEX",{outputLen:256}),u=this.molecule.atoms[0];let l=u.walletAddress;const d=C.get(u.aggregatedMeta(),"signingWallet");if(d&&(l=C.get(JSON.parse(d),"address")),c!==l)throw new rn;return!0}static fromServerData({molecularHash:e,bundleHash:t,cellSlug:n=null,status:s=null,createdAt:r=null,atoms:i=[]}){const o=i.map(c=>{let u=[];if(c.metasJson)try{const l=JSON.parse(c.metasJson);Array.isArray(l)?u=l:l&&typeof l=="object"&&(u=Object.entries(l).map(([d,f])=>({key:d,value:f})))}catch{u=[]}return{position:c.position||null,walletAddress:c.walletAddress||null,isotope:c.isotope||null,token:c.tokenSlug||c.token||null,value:c.value!=null?String(c.value):null,batchId:c.batchId||null,metaType:c.metaType||null,metaId:c.metaId||null,meta:u,index:c.index!=null?c.index:null,otsFragment:c.otsFragment||null,createdAt:c.createdAt||null}});return V.fromJSON({molecularHash:e,bundle:t,cellSlug:n,status:s,createdAt:r,atoms:o})}static verifyFromServerData(e){try{const t=we.fromServerData(e);return new we(t).verify(),{molecularHash:e.molecularHash,verified:!0,error:null}}catch(t){return{molecularHash:e.molecularHash||null,verified:!1,error:t.message||String(t)}}}}class pe extends T{constructor(e="Insufficient balance for requested transfer",t=null,n=null){super(e,t,n),this.name="BalanceInsufficientException"}}class ze extends T{constructor(e="Amount cannot be negative!",t=null,n=null){super(e,t,n),this.name="NegativeAmountException"}}class V{constructor({secret:e=null,bundle:t=null,sourceWallet:n=null,remainderWallet:s=null,cellSlug:r=null,version:i=null,continuIdPosition:o=null}){this.status=null,this.molecularHash=null,this.createdAt=String(+new Date),this.cellSlugOrigin=this.cellSlug=r,this.secret=e,this.bundle=t,this.sourceWallet=n,this.continuIdPosition=o,this.atoms=[],this.parentHashes=[],i!==null&&Object.prototype.hasOwnProperty.call(Ke,i)&&(this.version=String(i)),(s||n)&&(this.remainderWallet=s||S.create({secret:e,bundle:t,token:n.token,batchId:n.batchId,characters:n.characters}))}withParentHashes(e){return this.parentHashes=Array.isArray(e)?[...e]:[],this}get cellSlugDelimiter(){return"."}static isotopeFilter(e,t){return Array.isArray(e)||(e=[e]),t.filter(n=>e.includes(n.isotope))}static generateNextAtomIndex(e){return e.length}static jsonToObject(e){const t=Object.assign(new V({}),JSON.parse(e)),n=Object.keys(new V({}));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 o=s[r];typeof t[o]<"u"&&(n[r]=t[o])}return n}static normalize(e){let t=e.reduce((s,r)=>s+r);const n=t<0;for(;t<0||t>0;)for(const s of Object.keys(e))if((n?e[s]<8:e[s]>-8)&&(n?(++e[s],++t):(--e[s],--t),t===0))break;return e}getIsotopes(e){return V.isotopeFilter(e,this.atoms)}generateIndex(){return V.generateNextAtomIndex(this.atoms)}fill(e){for(const t in Object.keys(e))this[t]=e[t]}addAtom(e){return this.molecularHash=null,e.index=this.generateIndex(),e.version=this.version,this.atoms.push(e),this.atoms=g.sortAtoms(this.atoms),this}addContinuIdAtom(){(!this.remainderWallet||this.remainderWallet.token!=="USER")&&(this.remainderWallet=S.create({secret:this.secret,bundle:this.bundle}));const e={};return this.continuIdPosition?e.previousPosition=this.continuIdPosition:this.sourceWallet&&this.sourceWallet.position&&(e.previousPosition=this.sourceWallet.position),this.remainderWallet.pubkey&&(e.pubkey=this.remainderWallet.pubkey),this.remainderWallet.characters&&(e.characters=this.remainderWallet.characters),this.addAtom(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);return r.addPolicy(s),this.addAtom(g.create({wallet:this.sourceWallet,isotope:"R",metaType:e,metaId:t,meta:r})),this}fuseToken(e,t){const n=e.length;if(this.sourceWallet.balance-n<0)throw new pe;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 ze("Molecule::burnToken() - Amount to burn must be positive!");if(this.sourceWallet.balance-e<0)throw new pe;const n=new S({bundle:"0000000000000000000000000000000000000000000000000000000000000000",token:this.sourceWallet.token});return this.addAtom(g.create({isotope:"V",wallet:this.sourceWallet,value:-this.sourceWallet.balance})),this.addAtom(g.create({isotope:"V",wallet:n,value:e,metaType:"walletBundle",metaId:n.bundle})),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 ze("Molecule::replenishToken() - Amount to replenish must be positive!");if(t.length){t=S.getTokenUnits(t),this.remainderWallet.tokenUnits=this.sourceWallet.tokenUnits;for(const n of t)this.remainderWallet.tokenUnits.push(n);this.remainderWallet.balance=String(this.remainderWallet.tokenUnits.length),this.sourceWallet.tokenUnits=t,this.sourceWallet.balance=String(this.sourceWallet.tokenUnits.length)}else this.remainderWallet.balance=String(Number(this.sourceWallet.balance)+e),this.sourceWallet.balance=String(e);return this.addAtom(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 pe;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 ze("Molecule::addStackableTransfer() - Amount must be positive!");if(this.sourceWallet.balance-t<0)throw new pe;const n=this.sourceWallet.batchId||le({});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:le({})})),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 pe;const n=S.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 pe;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?le({}):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 o of n)r.push(o instanceof Ee?o:Ee.toObject(o));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:oe(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(p=>!(p instanceof g)).length!==0)throw new se;!t&&!this.bundle&&(this.bundle=e||oe(this.secret,"Molecule::sign")),this.molecularHash=g.hashAtoms({atoms:this.atoms});const s=this.atoms[0];let r=s.position;const i=C.get(s.aggregatedMeta(),"signingWallet");if(i&&(r=C.get(JSON.parse(i),"position")),!r)throw new ot("Signing wallet must have a position!");const o=S.generateKey({secret:this.secret,token:s.token,position:s.position}),c=$e(o,128),u=this.normalizedHash();let l="";for(const p in c){let w=c[p];for(let I=0,R=8-u[p];I<R;I++)w=new q("SHAKE256","TEXT").update(w).getHash("HEX",{outputLen:512});l+=w}n&&(l=It(l));const d=$e(l,Math.ceil(l.length/this.atoms.length));let f=null;for(let p=0,w=d.length;p<w;p++)this.atoms[p].otsFragment=d[p],f=this.atoms[p].position;return f}signSync(e={}){return this.sign(e)}cellSlugBase(){return(this.cellSlug||"").split(this.cellSlugDelimiter)[0]}toJSON(e={}){const{includeValidationContext:t=!1,includeOtsFragments:n=!0}=e;try{const s={status:this.status,molecularHash:this.molecularHash,createdAt:this.createdAt,cellSlug:this.cellSlug,bundle:this.bundle,atoms:this.atoms.map(r=>r.toJSON({includeOtsFragments:n}))};return this.parentHashes&&this.parentHashes.length>0&&(s.parentHashes=this.parentHashes),t&&(s.cellSlugOrigin=this.cellSlugOrigin,s.version=this.version,this.sourceWallet&&(s.sourceWallet={address:this.sourceWallet.address,position:this.sourceWallet.position,token:this.sourceWallet.token,balance:this.sourceWallet.balance||"0",bundle:this.sourceWallet.bundle,batchId:this.sourceWallet.batchId||null,characters:this.sourceWallet.characters||"BASE64",pubkey:this.sourceWallet.pubkey||null,tokenUnits:this.sourceWallet.tokenUnits||[],tradeRates:this.sourceWallet.tradeRates||{},molecules:this.sourceWallet.molecules||{}}),this.remainderWallet&&(s.remainderWallet={address:this.remainderWallet.address,position:this.remainderWallet.position,token:this.remainderWallet.token,balance:this.remainderWallet.balance||"0",bundle:this.remainderWallet.bundle,batchId:this.remainderWallet.batchId||null,characters:this.remainderWallet.characters||"BASE64",pubkey:this.remainderWallet.pubkey||null,tokenUnits:this.remainderWallet.tokenUnits||[],tradeRates:this.remainderWallet.tradeRates||{},molecules:this.remainderWallet.molecules||{}})),s}catch(s){throw new Error(`Molecule serialization failed: ${s.message}`)}}static fromJSON(e,t={}){const{includeValidationContext:n=!1,validateStructure:s=!0}=t;try{const r=typeof e=="string"?JSON.parse(e):e;if(s&&(!r.molecularHash||!Array.isArray(r.atoms)))throw new Error("Invalid molecule data: missing molecularHash or atoms array");const i=new V({secret:null,bundle:r.bundle||null,cellSlug:r.cellSlug||null,version:r.version||null});return i.status=r.status,i.molecularHash=r.molecularHash,i.createdAt=r.createdAt||String(+new Date),i.cellSlugOrigin=r.cellSlugOrigin,i.parentHashes=Array.isArray(r.parentHashes)?[...r.parentHashes]:[],Array.isArray(r.atoms)&&(i.atoms=r.atoms.map((o,c)=>{try{return g.fromJSON(o)}catch(u){throw new Error(`Failed to reconstruct atom ${c}: ${u.message}`)}})),n&&(r.sourceWallet&&(i.sourceWallet=new S({secret:null,token:r.sourceWallet.token,position:r.sourceWallet.position,bundle:r.sourceWallet.bundle,batchId:r.sourceWallet.batchId,characters:r.sourceWallet.characters}),i.sourceWallet.balance=String(r.sourceWallet.balance!=null?r.sourceWallet.balance:0),i.sourceWallet.address=r.sourceWallet.address,r.sourceWallet.pubkey&&(i.sourceWallet.pubkey=r.sourceWallet.pubkey),i.sourceWallet.tokenUnits=r.sourceWallet.tokenUnits||[],i.sourceWallet.tradeRates=r.sourceWallet.tradeRates||{},i.sourceWallet.molecules=r.sourceWallet.molecules||{}),r.remainderWallet&&(i.remainderWallet=new S({secret:null,token:r.remainderWallet.token,position:r.remainderWallet.position,bundle:r.remainderWallet.bundle,batchId:r.remainderWallet.batchId,characters:r.remainderWallet.characters}),i.remainderWallet.balance=String(r.remainderWallet.balance!=null?r.remainderWallet.balance:0),i.remainderWallet.address=r.remainderWallet.address,r.remainderWallet.pubkey&&(i.remainderWallet.pubkey=r.remainderWallet.pubkey),i.remainderWallet.tokenUnits=r.remainderWallet.tokenUnits||[],i.remainderWallet.tradeRates=r.remainderWallet.tradeRates||{},i.remainderWallet.molecules=r.remainderWallet.molecules||{})),i}catch(r){throw new Error(`Molecule deserialization failed: ${r.message}`)}}check(e=null){return new we(this).verify(e)}normalizedHash(){return V.normalize(V.enumerate(this.molecularHash))}}class ke{constructor({token:e,expiresAt:t,encrypt:n,pubkey:s}){this.$__token=e,this.$__expiresAt=t,this.$__pubkey=s,this.$__encrypt=n}static create(e,t){const n=new ke(e);return n.setWallet(t),n}static restore(e,t){const n=new S({secret:t,token:"AUTH",position:e.wallet.position,characters:e.wallet.characters});return ke.create({token:e.token,expiresAt:e.expiresAt,pubkey:e.pubkey,encrypt:e.encrypt},n)}setWallet(e){this.$__wallet=e}getWallet(){return this.$__wallet}getSnapshot(){return{token:this.$__token,expiresAt:this.$__expiresAt,pubkey:this.$__pubkey,encrypt:this.$__encrypt,wallet:{position:this.$__wallet.position,characters:this.$__wallet.characters}}}getToken(){return this.$__token}getPubkey(){return this.$__pubkey}getExpireInterval(){return this.$__expiresAt*1e3-Date.now()}isExpired(){return!this.$__expiresAt||this.getExpireInterval()<0}getAuthData(){return{token:this.getToken(),pubkey:this.getPubkey(),wallet:this.getWallet()}}}const ht=10**18;class fe{static val(e){return Math.abs(e*ht)<1?0:e}static cmp(e,t,n=!1){const s=fe.val(e)*ht,r=fe.val(t)*ht;return Math.abs(s-r)<1?0:s>r?1:-1}static equal(e,t){return fe.cmp(e,t)===0}}class ne extends T{constructor(e="GraphQL did not provide a valid response.",t=null,n=null){super(e,t,n),this.name="InvalidResponseException"}}class Re extends T{constructor(e="Authorization token missing or invalid.",t=null,n=null){super(e,t,n),this.name="UnauthenticatedException"}}class E{constructor({query:e,json:t,dataKey:n=null}){if(this.dataKey=n,this.errorKey="exception",this.$__payload=null,this.$__query=e,this.$__originResponse=t,this.$__response=t,typeof this.$__response>"u"||this.$__response===null)throw new ne;if(C.has(this.$__response,this.errorKey)){const s=C.get(this.$__response,this.errorKey);throw String(s).includes("Unauthenticated")?new Re:new ne}if(this.$__response.errors&&Array.isArray(this.$__response.errors)&&this.$__response.errors.length>0){const s=this.$__response.errors[0].message||"Unknown GraphQL error";throw s.includes("Unauthenticated")?new Re:new ne(`GraphQL Error: ${s}`)}this.init()}init(){}data(){if(!this.dataKey)return this.response();if(!this.response().data)throw new ne("Response has no data field");if(!C.has(this.response(),this.dataKey))throw new ne(`Missing expected field: ${this.dataKey}`);return C.get(this.response(),this.dataKey)}response(){return this.$__response}payload(){return null}query(){return this.$__query}status(){return null}success(){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 K{constructor(e,t){this.client=e,this.knishIOClient=t,this.$__variables=null,this.$__query=null,this.$__response=null,this.$__request=null}response(){return this.$__response}async createResponseRaw(e){return this.createResponse(e)}createResponse(e){return new E({query:this,json:e})}createQuery({variables:e=null}){if(this.$__variables=this.compiledVariables(e),!this.uri())throw new Y("Query::createQuery() - Node URI was not initialized for this client instance!");if(this.$__query===null)throw new Y("Query::createQuery() - GraphQL subscription was not initialized!");return{query:this.$__query,variables:this.variables()}}async execute({variables:e=null,context:t={}}){this.$__request=this.createQuery({variables:e});const n={...t,...this.createQueryContext()};try{const s=await this.client.query({...this.$__request,context:n});return this.$__response=await this.createResponseRaw(s),this.$__response}catch(s){if(s.name==="AbortError")return this.knishIOClient.log("warn","Query was cancelled"),new E({query:this,json:{data:null,errors:[{message:"Query was cancelled"}]}});throw s}}compiledVariables(e=null){return e||{}}uri(){return this.client.getUri()}variables(){return this.$__variables}createQueryContext(){return{}}}class ln extends E{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.ContinuId"})}payload(){let e=null;const t=this.data();return t&&(e=new S({secret:null,token:t.tokenSlug}),e.address=t.address,e.position=t.position,e.bundle=t.bundleHash,e.batchId=t.batchId,e.characters=t.characters,e.pubkey=t.pubkey,e.balance=String(t.amount!=null?t.amount:0)),e}}class cn extends K{constructor(e,t){super(e,t),this.$__query=A.gql`query ($bundle: String!) {
|
|
5
5
|
ContinuId(bundle: $bundle) {
|
|
6
6
|
address,
|
|
7
7
|
bundleHash,
|