UNPKG

starknetkit

Version:

<!-- logo --> <p align="center"> <img width='300' src="https://starknetkit-website-git-blo-1541-argentlabs.vercel.app/starknetKit-logo.svg"> </p>

1 lines 96.8 kB
"use strict";var Tt=Object.defineProperty;var St=(e,t,r)=>t in e?Tt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var d=(e,t,r)=>(St(e,typeof t!="symbol"?t+"":t,r),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const k=require("starknet"),C=require("./connector-e4ffe813.cjs"),tt="0.10.0",Ct={version:tt};var B=(e=>(e.SUCCESS="SUCCESS",e.NOT_CONNECTED="NOT_CONNECTED",e.ERROR="ERROR",e.CANCELED="CANCELED",e.USER_INTERACTION_REQUIRED="USER_INTERACTION_REQUIRED",e))(B||{});function xt(e){return Array.isArray(e)?e:[e]}function $t(e){const t=e.pathname.split("/");if(e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="0.0.0.0"){if(typeof XMLHttpRequest>"u")return console.warn(`Cannot make synchronous HTTP call in Node.js environment for ${e.toString()}`),k.shortString.encodeShortString("LOCALHOST");const r=new XMLHttpRequest;r.open("POST",e.toString(),!1),r.setRequestHeader("Content-Type","application/json");const n=JSON.stringify({jsonrpc:"2.0",method:"starknet_chainId",params:[],id:1});try{if(r.send(n),r.status===200){const o=JSON.parse(r.responseText);if(o.result)return o.result}throw new Error(`Failed to get chain ID from ${e.toString()}: ${r.status} ${r.statusText}`)}catch(o){throw new Error(`Failed to connect to ${e.toString()}: ${o}`)}}if(t.includes("starknet")){if(t.includes("mainnet"))return k.constants.StarknetChainId.SN_MAIN;if(t.includes("sepolia"))return k.constants.StarknetChainId.SN_SEPOLIA}else if(t.length>=3){const r=t[2];if(t.includes("katana"))return k.shortString.encodeShortString(`WP_${r.toUpperCase().replace(/-/g,"_")}`);if(t.includes("mainnet"))return k.shortString.encodeShortString(`GG_${r.toUpperCase().replace(/-/g,"_")}`)}throw new Error(`Chain ${e.toString()} not supported`)}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cz0idXNlclNwYWNlT25Vc2UiIGNvbG9yLWludGVycG9sYXRpb24tZmlsdGVycz0ic1JHQiI+CjxmZUZsb29kIGZsb29kLW9wYWNpdHk9IjAiIHJlc3VsdD0iQmFja2dyb3VuZEltYWdlRml4Ii8+CjxmZUNvbG9yTWF0cml4IGluPSJTb3VyY2VBbHBoYSIgdHlwZT0ibWF0cml4IiB2YWx1ZXM9IjAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDEyNyAwIiByZXN1bHQ9ImhhcmRBbHBoYSIvPgo8ZmVPZmZzZXQgZHk9IjQiLz4KPGZlR2F1c3NpYW5CbHVyIHN0ZERldmlhdGlvbj0iMiIvPgo8ZmVDb21wb3NpdGUgaW4yPSJoYXJkQWxwaGEiIG9wZXJhdG9yPSJvdXQiLz4KPGZlQ29sb3JNYXRyaXggdHlwZT0ibWF0cml4IiB2YWx1ZXM9IjAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAuMjUgMCIvPgo8ZmVCbGVuZCBtb2RlPSJub3JtYWwiIGluMj0iQmFja2dyb3VuZEltYWdlRml4IiByZXN1bHQ9ImVmZmVjdDFfZHJvcFNoYWRvd181MTEyXzc4MiIvPgo8ZmVCbGVuZCBtb2RlPSJub3JtYWwiIGluPSJTb3VyY2VHcmFwaGljIiBpbjI9ImVmZmVjdDFfZHJvcFNoYWRvd181MTEyXzc4MiIgcmVzdWx0PSJzaGFwZSIvPgo8L2ZpbHRlcj4KPC9kZWZzPgo8L3N2Zz4K";function Yt(){}class Qt{constructor(){d(this,"m_lastPromise",Promise.resolve())}async obtain(t=!1){let r=Yt;if(t)return r;const n=this.m_lastPromise;return this.m_lastPromise=new Promise(o=>r=o),await n,r}}const Pt=new Qt;let Bt=class{constructor(){d(this,"id","controller");d(this,"name","Controller");d(this,"version",Ct.version);d(this,"icon",Ut);d(this,"account");d(this,"subscriptions",[]);d(this,"_probePromise",null);d(this,"request",async t=>{switch(t.type){case"wallet_getPermissions":return await this.safeProbe(),this.account?[Lt.ACCOUNTS]:[];case"wallet_requestAccounts":{if(this.account)return[this.account.address];const n=t.params&&t.params.silent_mode;return this.account=await this.safeProbe(),!this.account&&!n&&(this.account=await this.connect()),this.account?[this.account.address]:[]}case"wallet_watchAsset":throw{code:63,message:"An unexpected error occurred",data:"wallet_watchAsset not implemented"};case"wallet_addStarknetChain":{let n=t.params;return this.addStarknetChain(n)}case"wallet_switchStarknetChain":{let n=t.params;return this.switchStarknetChain(n.chainId)}case"wallet_requestChainId":if(!this.account)throw{code:63,message:"An unexpected error occurred",data:"Account not initialized"};return await this.account.getChainId();case"wallet_deploymentData":throw{code:63,message:"An unexpected error occurred",data:"wallet_deploymentData not implemented"};case"wallet_addInvokeTransaction":if(!this.account)throw{code:63,message:"An unexpected error occurred",data:"Account not initialized"};let r=t.params;return await this.account.execute(r.calls.map(n=>({contractAddress:n.contract_address,entrypoint:n.entry_point,calldata:n.calldata})));case"wallet_addDeclareTransaction":throw{code:63,message:"An unexpected error occurred",data:"wallet_addDeclareTransaction not implemented"};case"wallet_signTypedData":{if(!this.account)throw{code:63,message:"An unexpected error occurred",data:"Account not initialized"};return await this.account.signMessage(t.params)}case"wallet_supportedSpecs":return[];case"wallet_supportedWalletApi":return[];default:throw{code:63,message:"An unexpected error occurred",data:`Unknown RPC call type: ${t.type}`}}});d(this,"on",(t,r)=>{if(t!=="accountsChanged"&&t!=="networkChanged")throw new Error(`Unknown event: ${t}`);this.subscriptions.push({type:t,handler:r})});d(this,"off",(t,r)=>{if(t!=="accountsChanged"&&t!=="networkChanged")throw new Error(`Unknown event: ${t}`);const n=this.subscriptions.findIndex(o=>o.type===t&&o.handler===r);n>=0&&this.subscriptions.splice(n,1)})}async safeProbe(){if(this.account)return this.account;if(this._probePromise)return this._probePromise;const t=await Pt.obtain();return await new Promise(async r=>{try{this._probePromise=this.probe();const n=await this._probePromise;r(n)}finally{this._probePromise=null}}).finally(()=>{t()})}emitNetworkChanged(t){this.subscriptions.filter(r=>r.type==="networkChanged").forEach(r=>{r.handler(t)})}emitAccountsChanged(t){this.subscriptions.filter(r=>r.type==="accountsChanged").forEach(r=>{r.handler(t)})}};class Ue extends k.WalletAccount{constructor(r,n,o,i,s,a){super({provider:{nodeUrl:n},walletProvider:r,address:o});d(this,"keychain");d(this,"modal");d(this,"options");this.keychain=i,this.options=s,this.modal=a}async execute(r){return r=xt(r),new Promise(async(n,o)=>{const i=await this.keychain.execute(r,void 0,void 0,!1,this.options?.feeSource);if(i.code===B.SUCCESS){n(i);return}if(this.options?.propagateSessionErrors&&i.code!==B.USER_INTERACTION_REQUIRED){o(i.error);return}this.modal.open();const s=await this.keychain.execute(r,void 0,void 0,!0,i.error);if(s.code===B.SUCCESS){n(s),this.modal.close();return}o(s.error)})}async signMessage(r){return new Promise(async(n,o)=>{const i=await this.keychain.signMessage(r,"",!0);if(!("code"in i)){n(i);return}this.modal.open();const s=await this.keychain.signMessage(r,"",!1);"code"in s?o(s.error):n(s),this.modal.close()})}}var $;(function(e){e.Call="call",e.Reply="reply",e.Syn="syn",e.SynAck="synAck",e.Ack="ack"})($||($={}));var Q;(function(e){e.Fulfilled="fulfilled",e.Rejected="rejected"})(Q||(Q={}));var X;(function(e){e.ConnectionDestroyed="ConnectionDestroyed",e.ConnectionTimeout="ConnectionTimeout",e.NoIframeSrc="NoIframeSrc"})(X||(X={}));var Ne;(function(e){e.DataCloneError="DataCloneError"})(Ne||(Ne={}));var U;(function(e){e.Message="message"})(U||(U={}));const Rt=(e,t)=>{const r=[];let n=!1;return{destroy(o){n||(n=!0,t(`${e}: Destroying connection`),r.forEach(i=>{i(o)}))},onDestroy(o){n?o():r.push(o)}}},_t=e=>(...t)=>{e&&console.log("[Penpal]",...t)},Zt={"http:":"80","https:":"443"},Wt=/^(https?:)?\/\/([^/:]+)?(:(\d+))?/,Vt=["file:","data:"],Ft=e=>{if(e&&Vt.find(a=>e.startsWith(a)))return"null";const t=document.location,r=Wt.exec(e);let n,o,i;r?(n=r[1]?r[1]:t.protocol,o=r[2],i=r[4]):(n=t.protocol,o=t.hostname,i=t.port);const s=i&&i!==Zt[n]?`:${i}`:"";return`${n}//${o}${s}`},Ye=({name:e,message:t,stack:r})=>({name:e,message:t,stack:r}),Gt=e=>{const t=new Error;return Object.keys(e).forEach(r=>t[r]=e[r]),t},Ht=(e,t,r)=>{const{localName:n,local:o,remote:i,originForSending:s,originForReceiving:a}=e;let h=!1;const c=l=>{if(l.source!==i||l.data.penpal!==$.Call)return;if(a!=="*"&&l.origin!==a){r(`${n} received message from origin ${l.origin} which did not match expected origin ${a}`);return}const u=l.data,{methodName:w,args:g,id:f}=u;r(`${n}: Received ${w}() call`);const A=N=>z=>{if(r(`${n}: Sending ${w}() reply`),h){r(`${n}: Unable to send ${w}() reply due to destroyed connection`);return}const p={penpal:$.Reply,id:f,resolution:N,returnValue:z};N===Q.Rejected&&z instanceof Error&&(p.returnValue=Ye(z),p.returnValueIsError=!0);try{i.postMessage(p,s)}catch(M){if(M.name===Ne.DataCloneError){const T={penpal:$.Reply,id:f,resolution:Q.Rejected,returnValue:Ye(M),returnValueIsError:!0};i.postMessage(T,s)}throw M}};new Promise(N=>N(t[w].call(t,l.origin).apply(t,g))).then(A(Q.Fulfilled),A(Q.Rejected))};return o.addEventListener(U.Message,c),()=>{h=!0,o.removeEventListener(U.Message,c)}};let Jt=0;const Xt=()=>++Jt,nt=".",ot=e=>e?e.split(nt):[],qt=e=>e.join(nt),Kt=(e,t)=>{const r=ot(t||"");return r.push(e),qt(r)},er=(e,t,r)=>{const n=ot(t);return n.reduce((o,i,s)=>(typeof o[i]>"u"&&(o[i]={}),s===n.length-1&&(o[i]=r),o[i]),e),e},it=(e,t)=>{const r={};return Object.keys(e).forEach(n=>{const o=e[n],i=Kt(n,t);typeof o=="object"&&Object.assign(r,it(o,i)),typeof o=="function"&&(r[i]=o)}),r},tr=e=>{const t={};for(const r in e)er(t,r,e[r]);return t},rr=(e,t,r,n,o)=>{const{localName:i,local:s,remote:a,originForSending:h,originForReceiving:c}=t;let l=!1;o(`${i}: Connecting call sender`);const u=g=>(...f)=>{o(`${i}: Sending ${g}() call`);let A;try{a.closed&&(A=!0)}catch{A=!0}if(A&&n(),l){const N=new Error(`Unable to send ${g}() call due to destroyed connection`);throw N.code=X.ConnectionDestroyed,N}return new Promise((N,z)=>{const p=Xt(),M=S=>{if(S.source!==a||S.data.penpal!==$.Reply||S.data.id!==p)return;if(c!=="*"&&S.origin!==c){o(`${i} received message from origin ${S.origin} which did not match expected origin ${c}`);return}const le=S.data;o(`${i}: Received ${g}() reply`),s.removeEventListener(U.Message,M);let ue=le.returnValue;le.returnValueIsError&&(ue=Gt(ue)),(le.resolution===Q.Fulfilled?N:z)(ue)};s.addEventListener(U.Message,M);const T={penpal:$.Call,id:p,methodName:g,args:f};a.postMessage(T,h)})},w=r.reduce((g,f)=>(g[f]=u(f),g),{});return Object.assign(e,tr(w)),()=>{l=!0}},nr=(e,t,r,n,o)=>{const{destroy:i,onDestroy:s}=n;let a,h;const c={};return l=>{if(t!=="*"&&l.origin!==t){o(`Parent: Handshake - Received ACK message from origin ${l.origin} which did not match expected origin ${t}`);return}o("Parent: Handshake - Received ACK");const u={localName:"Parent",local:window,remote:l.source,originForSending:r,originForReceiving:t};a&&a(),a=Ht(u,e,o),s(a),h&&h.forEach(g=>{delete c[g]}),h=l.data.methodNames;const w=rr(c,u,h,i,o);return s(w),c}},or=(e,t,r,n)=>o=>{if(!o.source)return;if(r!=="*"&&o.origin!==r){e(`Parent: Handshake - Received SYN message from origin ${o.origin} which did not match expected origin ${r}`);return}e("Parent: Handshake - Received SYN, responding with SYN-ACK");const i={penpal:$.SynAck,methodNames:Object.keys(t)};o.source.postMessage(i,n)},ir=6e4,sr=(e,t)=>{const{destroy:r,onDestroy:n}=t,o=setInterval(()=>{e.isConnected||(clearInterval(o),r())},ir);n(()=>{clearInterval(o)})},ar=(e,t)=>{let r;return e!==void 0&&(r=window.setTimeout(()=>{const n=new Error(`Connection timed out after ${e}ms`);n.code=X.ConnectionTimeout,t(n)},e)),()=>{clearTimeout(r)}},cr=e=>{if(!e.src&&!e.srcdoc){const t=new Error("Iframe must have src or srcdoc property defined.");throw t.code=X.NoIframeSrc,t}},hr=e=>{let{iframe:t,methods:r={},childOrigin:n,timeout:o,debug:i=!1}=e;const s=_t(i),a=Rt("Parent",s),{onDestroy:h,destroy:c}=a;n||(cr(t),n=Ft(t.src));const l=n==="null"?"*":n,u=it(r),w=or(s,u,n,l),g=nr(u,n,l,a,s);return{promise:new Promise((f,A)=>{const N=ar(o,c),z=p=>{if(!(p.source!==t.contentWindow||!p.data)){if(p.data.penpal===$.Syn){w(p);return}if(p.data.penpal===$.Ack){const M=g(p);M&&(N(),f(M));return}}};window.addEventListener(U.Message,z),s("Parent: Awaiting handshake"),sr(t,a),h(p=>{window.removeEventListener(U.Message,z),p&&A(p)})}),destroy(){c()}}};class lr{constructor({id:t,url:r,preset:n,onClose:o,onConnect:i,methods:s={}}){d(this,"url");d(this,"iframe");d(this,"container");d(this,"onClose");d(this,"child");d(this,"closeTimeout");if(typeof document>"u"||typeof window>"u")return;n&&r.searchParams.set("preset",n),this.url=r;const a=document.createElement("iframe");a.src=r.toString(),a.id=t,a.style.border="none",a.sandbox.add("allow-forms"),a.sandbox.add("allow-popups"),a.sandbox.add("allow-popups-to-escape-sandbox"),a.sandbox.add("allow-scripts"),a.sandbox.add("allow-same-origin"),a.allow="publickey-credentials-create *; publickey-credentials-get *; clipboard-write",document.hasStorageAccess&&a.sandbox.add("allow-storage-access-by-user-activation");const h=document.createElement("div");h.id="controller",h.style.position="fixed",h.style.height="100%",h.style.width="100%",h.style.top="0",h.style.left="0",h.style.zIndex="10000",h.style.backgroundColor="rgba(0,0,0,0.6)",h.style.display="none",h.style.alignItems="center",h.style.justifyContent="center",h.style.transition="opacity 0.2s ease",h.style.opacity="0",h.style.pointerEvents="auto",h.appendChild(a),h.addEventListener("click",u=>{u.target===h&&(t==="controller-keychain"&&this.child&&this.child.reset?.().catch(w=>console.error("Error resetting context:",w)),this.close())}),this.iframe=a,this.container=h,hr({iframe:this.iframe,methods:{close:u=>()=>this.close(),reload:u=>()=>window.location.reload(),...s}}).promise.then(u=>{this.child=u,i(u)}),this.resize(),window.addEventListener("resize",()=>this.resize());const c=new MutationObserver(()=>{if(typeof document>"u")return;const u=document.getElementById("controller");document.body&&t==="controller-keychain"&&!u&&(document.body.appendChild(h),c.disconnect())});c.observe(document.documentElement,{childList:!0,subtree:!0});const l=document.getElementById("controller");document.body&&t==="controller-keychain"&&!l&&document.body.appendChild(h),this.onClose=o}open(){!this.container||typeof document>"u"||!document.body||(this.closeTimeout&&(clearTimeout(this.closeTimeout),this.closeTimeout=void 0),document.body.style.overflow="hidden",this.container.style.display="flex",requestAnimationFrame(()=>{this.container&&(this.container.style.opacity="1")}))}close(){!this.container||typeof document>"u"||!document.body||(this.onClose?.(),document.body.style.overflow="auto",this.container.style.opacity="0",this.closeTimeout=setTimeout(()=>{this.container&&(this.container.style.display="none"),this.closeTimeout=void 0},200))}sendBackward(){this.container&&(this.container.style.zIndex="9999")}sendForward(){this.container&&(this.container.style.zIndex="10000")}resize(){if(!(!this.iframe||typeof window>"u")){if(this.iframe.style.userSelect="none",window.innerWidth<768){this.iframe.style.height="100%",this.iframe.style.width="100%",this.iframe.style.borderRadius="0";return}this.iframe.style.height="600px",this.iframe.style.width="432px",this.iframe.style.borderRadius="8px"}}isOpen(){return this.container?.style.display!=="none"}}const ur="6.13.7";function Qe(e,t,r){for(let n in t){let o=t[n];Object.defineProperty(e,n,{enumerable:!0,value:o,writable:!1})}}function Z(e){if(e==null)return"null";if(Array.isArray(e))return"[ "+e.map(Z).join(", ")+" ]";if(e instanceof Uint8Array){const t="0123456789abcdef";let r="0x";for(let n=0;n<e.length;n++)r+=t[e[n]>>4],r+=t[e[n]&15];return r}if(typeof e=="object"&&typeof e.toJSON=="function")return Z(e.toJSON());switch(typeof e){case"boolean":case"symbol":return e.toString();case"bigint":return BigInt(e).toString();case"number":return e.toString();case"string":return JSON.stringify(e);case"object":{const t=Object.keys(e);return t.sort(),"{ "+t.map(r=>`${Z(r)}: ${Z(e[r])}`).join(", ")+" }"}}return"[ COULD NOT SERIALIZE ]"}function dr(e,t,r){let n=e;{const i=[];if(r){if("message"in r||"code"in r||"name"in r)throw new Error(`value will overwrite populated values: ${Z(r)}`);for(const s in r){if(s==="shortMessage")continue;const a=r[s];i.push(s+"="+Z(a))}}i.push(`code=${t}`),i.push(`version=${ur}`),i.length&&(e+=" ("+i.join(", ")+")")}let o;switch(t){case"INVALID_ARGUMENT":o=new TypeError(e);break;case"NUMERIC_FAULT":case"BUFFER_OVERRUN":o=new RangeError(e);break;default:o=new Error(e)}return Qe(o,{code:t}),r&&Object.assign(o,r),o.shortMessage==null&&Qe(o,{shortMessage:n}),o}function wr(e,t,r,n){if(!e)throw dr(t,r,n)}function F(e,t,r,n){wr(e,t,"INVALID_ARGUMENT",{argument:r,value:n})}["NFD","NFC","NFKD","NFKC"].reduce((e,t)=>{try{if("test".normalize(t)!=="test")throw new Error("bad");if(t==="NFD"&&"é".normalize("NFD")!=="é")throw new Error("broken");e.push(t)}catch{}return e},[]);function gr(e,t,r){if(e instanceof Uint8Array)return e;if(typeof e=="string"&&e.match(/^0x(?:[0-9a-f][0-9a-f])*$/i)){const n=new Uint8Array((e.length-2)/2);let o=2;for(let i=0;i<n.length;i++)n[i]=parseInt(e.substring(o,o+2),16),o+=2;return n}F(!1,"invalid BytesLike value",t||"value",e)}function be(e,t){return gr(e,t)}const Pe="0123456789abcdef";function yr(e){const t=be(e);let r="0x";for(let n=0;n<t.length;n++){const o=t[n];r+=Pe[(o&240)>>4]+Pe[o&15]}return r}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function fr(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Be(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function ne(e,...t){if(!fr(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Re(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function pr(e,t){ne(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function mr(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function st(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const Nr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Mr(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function Ir(e){for(let t=0;t<e.length;t++)e[t]=Mr(e[t]);return e}const _e=Nr?e=>e:Ir;function Ar(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function at(e){return typeof e=="string"&&(e=Ar(e)),ne(e),e}class jr{}function Dr(e){const t=n=>e().update(at(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}const ee=BigInt(2**32-1),Ze=BigInt(32);function br(e,t=!1){return t?{h:Number(e&ee),l:Number(e>>Ze&ee)}:{h:Number(e>>Ze&ee)|0,l:Number(e&ee)|0}}function Er(e,t=!1){const r=e.length;let n=new Uint32Array(r),o=new Uint32Array(r);for(let i=0;i<r;i++){const{h:s,l:a}=br(e[i],t);[n[i],o[i]]=[s,a]}return[n,o]}const kr=(e,t,r)=>e<<r|t>>>32-r,zr=(e,t,r)=>t<<r|e>>>32-r,vr=(e,t,r)=>t<<r-32|e>>>64-r,Tr=(e,t,r)=>e<<r-32|t>>>64-r,Sr=BigInt(0),V=BigInt(1),Cr=BigInt(2),xr=BigInt(7),$r=BigInt(256),Or=BigInt(113),ct=[],ht=[],lt=[];for(let e=0,t=V,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],ct.push(2*(5*n+r)),ht.push((e+1)*(e+2)/2%64);let o=Sr;for(let i=0;i<7;i++)t=(t<<V^(t>>xr)*Or)%$r,t&Cr&&(o^=V<<(V<<BigInt(i))-V);lt.push(o)}const ut=Er(lt,!0),Lr=ut[0],Ur=ut[1],We=(e,t,r)=>r>32?vr(e,t,r):kr(e,t,r),Ve=(e,t,r)=>r>32?Tr(e,t,r):zr(e,t,r);function Yr(e,t=24){const r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let s=0;s<10;s++)r[s]=e[s]^e[s+10]^e[s+20]^e[s+30]^e[s+40];for(let s=0;s<10;s+=2){const a=(s+8)%10,h=(s+2)%10,c=r[h],l=r[h+1],u=We(c,l,1)^r[a],w=Ve(c,l,1)^r[a+1];for(let g=0;g<50;g+=10)e[s+g]^=u,e[s+g+1]^=w}let o=e[2],i=e[3];for(let s=0;s<24;s++){const a=ht[s],h=We(o,i,a),c=Ve(o,i,a),l=ct[s];o=e[l],i=e[l+1],e[l]=h,e[l+1]=c}for(let s=0;s<50;s+=10){for(let a=0;a<10;a++)r[a]=e[s+a];for(let a=0;a<10;a++)e[s+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=Lr[n],e[1]^=Ur[n]}st(r)}class Ee extends jr{constructor(t,r,n,o=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=o,this.rounds=i,Be(n),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=mr(this.state)}clone(){return this._cloneInto()}keccak(){_e(this.state32),Yr(this.state32,this.rounds),_e(this.state32),this.posOut=0,this.pos=0}update(t){Re(this),t=at(t),ne(t);const{blockLen:r,state:n}=this,o=t.length;for(let i=0;i<o;){const s=Math.min(r-this.pos,o-i);for(let a=0;a<s;a++)n[this.pos++]^=t[i++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:r,pos:n,blockLen:o}=this;t[n]^=r,r&128&&n===o-1&&this.keccak(),t[o-1]^=128,this.keccak()}writeInto(t){Re(this,!1),ne(t),this.finish();const r=this.state,{blockLen:n}=this;for(let o=0,i=t.length;o<i;){this.posOut>=n&&this.keccak();const s=Math.min(n-this.posOut,i-o);t.set(r.subarray(this.posOut,this.posOut+s),o),this.posOut+=s,o+=s}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return Be(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(pr(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,st(this.state)}_cloneInto(t){const{blockLen:r,suffix:n,outputLen:o,rounds:i,enableXOF:s}=this;return t||(t=new Ee(r,n,o,s,i)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=i,t.suffix=n,t.outputLen=o,t.enableXOF=s,t.destroyed=this.destroyed,t}}const Qr=(e,t,r)=>Dr(()=>new Ee(t,e,r)),Pr=Qr(1,136,256/8);let dt=!1;const wt=function(e){return Pr(e)};let gt=wt;function q(e){const t=be(e,"data");return yr(gt(t))}q._=wt;q.lock=function(){dt=!0};q.register=function(e){if(dt)throw new TypeError("keccak256 is locked");gt=e};Object.freeze(q);const Br=BigInt(0),Rr=BigInt(36);function Fe(e){e=e.toLowerCase();const t=e.substring(2).split(""),r=new Uint8Array(40);for(let o=0;o<40;o++)r[o]=t[o].charCodeAt(0);const n=be(q(r));for(let o=0;o<40;o+=2)n[o>>1]>>4>=8&&(t[o]=t[o].toUpperCase()),(n[o>>1]&15)>=8&&(t[o+1]=t[o+1].toUpperCase());return"0x"+t.join("")}const ke={};for(let e=0;e<10;e++)ke[String(e)]=String(e);for(let e=0;e<26;e++)ke[String.fromCharCode(65+e)]=String(10+e);const Ge=15;function _r(e){e=e.toUpperCase(),e=e.substring(4)+e.substring(0,2)+"00";let t=e.split("").map(n=>ke[n]).join("");for(;t.length>=Ge;){let n=t.substring(0,Ge);t=parseInt(n,10)%97+t.substring(n.length)}let r=String(98-parseInt(t,10)%97);for(;r.length<2;)r="0"+r;return r}const Zr=function(){const e={};for(let t=0;t<36;t++){const r="0123456789abcdefghijklmnopqrstuvwxyz"[t];e[r]=BigInt(t)}return e}();function Wr(e){e=e.toLowerCase();let t=Br;for(let r=0;r<e.length;r++)t=t*Rr+Zr[e[r]];return t}function O(e){if(F(typeof e=="string","invalid address","address",e),e.match(/^(0x)?[0-9a-fA-F]{40}$/)){e.startsWith("0x")||(e="0x"+e);const t=Fe(e);return F(!e.match(/([A-F].*[a-f])|([a-f].*[A-F])/)||t===e,"bad address checksum","address",e),t}if(e.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){F(e.substring(2,4)===_r(e),"bad icap checksum","address",e);let t=Wr(e.substring(4)).toString(16);for(;t.length<40;)t="0"+t;return Fe("0x"+t)}F(!1,"invalid address","address",e)}class Vr{constructor(){d(this,"type","argent");d(this,"platform","starknet");d(this,"wallet");d(this,"account");d(this,"connectedAccounts",[])}isAvailable(){return typeof window<"u"&&!!window.starknet_argentX}getInfo(){const t=this.isAvailable();return{type:this.type,available:t,version:t?window.starknet_argentX?.version||"Unknown":void 0,chainId:t?window.starknet_argentX?.chainId:void 0,name:"Argent",platform:this.platform}}async connect(){if(this.account)return{success:!0,wallet:this.type,account:this.account};try{if(!this.isAvailable())throw new Error("Argent is not available");const t=window.starknet_argentX;if(!t)throw new Error("No wallet found");const r=await t.request({type:"wallet_requestAccounts",params:{silent_mode:!1}});if(!r||r.length===0)throw new Error("No accounts found");return this.wallet=t,this.account=r[0],this.connectedAccounts=r,{success:!0,wallet:this.type,account:this.account}}catch(t){return console.error("Error connecting to Argent:",t),{success:!1,wallet:this.type,error:t.message||"Unknown error"}}}getConnectedAccounts(){return this.connectedAccounts}async signTypedData(t){try{if(!this.isAvailable()||!this.wallet)throw new Error("Argent is not connected");const r=await this.wallet.request({type:"wallet_signTypedData",params:t});return{success:!0,wallet:this.type,result:r}}catch(r){return console.error("Error signing typed data with Argent:",r),{success:!1,wallet:this.type,error:r.message||"Unknown error"}}}async sendTransaction(t){if(!this.wallet)throw new Error("No wallet found");try{const r=await this.wallet.request({type:"wallet_addInvokeTransaction",params:{calls:t}});return{success:!0,wallet:this.type,result:r}}catch(r){return console.error("Error sending transaction with Argent:",r),{success:!1,wallet:this.type,error:r.message||"Unknown error"}}}async switchChain(t){if(!this.wallet)throw new Error("No wallet found");return await this.wallet.request({type:"wallet_switchStarknetChain",params:{chainId:t}})}async getBalance(t){try{if(!this.isAvailable()||!this.wallet)throw new Error("Argent is not connected");return{success:!0,wallet:this.type,result:"Implement based on Argent API"}}catch(r){return console.error("Error getting balance from Argent:",r),{success:!1,wallet:this.type,error:r.message||"Unknown error"}}}async waitForTransaction(t,r){return{success:!1,wallet:this.type,error:"waitForTransaction not supported for Argent wallet"}}}function Fr(e){if(typeof window>"u")return;const t=r=>e(r.detail);return window.addEventListener("eip6963:announceProvider",t),window.dispatchEvent(new CustomEvent("eip6963:requestProvider")),()=>window.removeEventListener("eip6963:announceProvider",t)}function Gr(){const e=new Set;let t=[];const r=()=>Fr(o=>{t.some(({info:i})=>i.uuid===o.info.uuid)||(t=[...t,o],e.forEach(i=>i(t,{added:[o]})))});let n=r();return{_listeners(){return e},clear(){e.forEach(o=>o([],{removed:[...t]})),t=[]},destroy(){this.clear(),e.clear(),n?.()},findProvider({rdns:o}){return t.find(i=>i.info.rdns===o)},getProviders(){return t},reset(){this.clear(),n?.(),n=r()},subscribe(o,{emitImmediately:i}={}){return e.add(o),i&&o(t,{added:t}),()=>e.delete(o)}}}const Hr={"0x1":"ethereum","0xaa36a7":"ethereum","0x14a34":"base","0x2105":"base","0x66eee":"arbitrum","0xa4b1":"arbitrum","0xa":"optimism","0xaa37dc":"optimism",[k.constants.StarknetChainId.SN_MAIN]:"starknet",[k.constants.StarknetChainId.SN_SEPOLIA]:"starknet"},de=e=>{const t=k.num.toHex(e),r=Hr[t];return r||console.warn(`Unknown chain ID: ${t}`),r};class ze{constructor(){d(this,"platform");d(this,"account");d(this,"store",Gr());d(this,"provider");d(this,"connectedAccounts",[]);d(this,"initialized",!1);this.initializeIfAvailable()}getProvider(){return this.provider||(this.provider=this.store.getProviders().find(t=>t.info.rdns===this.rdns)),this.provider}getEthereumProvider(){const t=this.getProvider();return t?t.provider:this.rdns==="io.metamask"&&typeof window<"u"&&window.ethereum?.isMetaMask?window.ethereum:null}initializeIfAvailable(){this.getProvider()&&!this.initialized&&(this.initialized=!0,this.initializeProvider())}initializeProvider(){const t=this.getProvider();t&&(t.provider.request({method:"eth_accounts"}).then(r=>{this.connectedAccounts=r.map(O),r.length>0&&(this.account=O(r[0]))}).catch(console.error),t.provider.request({method:"eth_chainId"}).then(r=>{this.platform=de(r)}).catch(console.error),t.provider?.on("chainChanged",r=>{this.platform=de(r)}),t.provider?.on("accountsChanged",r=>{r&&(this.connectedAccounts=r.map(n=>O(n)),this.account=r.length>0?O(r[0]):void 0)}))}isAvailable(){const t=this.getProvider();return!t&&this.rdns==="io.metamask"&&typeof window<"u"?!!window.ethereum?.isMetaMask:(t&&!this.initialized&&this.initializeIfAvailable(),typeof window<"u"&&!!t)}getInfo(){const t=this.isAvailable();return{type:this.type,available:t,version:t?window.ethereum?.version||"Unknown":void 0,chainId:t?window.ethereum?.chainId:void 0,name:this.displayName,platform:this.platform,connectedAccounts:this.connectedAccounts}}getConnectedAccounts(){return this.connectedAccounts}async connect(t){if(t&&this.connectedAccounts.includes(O(t))&&(this.account=O(t)),this.account)return{success:!0,wallet:this.type,account:this.account};try{if(!this.isAvailable())throw new Error(`${this.displayName} is not available`);let r;const n=this.getProvider();if(n?r=n.provider:this.rdns==="io.metamask"&&window.ethereum?.isMetaMask&&(r=window.ethereum),!r)throw new Error(`${this.displayName} provider not found`);const o=await r.request({method:"eth_requestAccounts"});if(o&&o.length>0)return this.account=O(o[0]),this.connectedAccounts=o.map(O),!n&&this.rdns==="io.metamask"&&(this.provider={info:{uuid:"metamask-fallback",name:"MetaMask",icon:"data:image/svg+xml;base64,",rdns:"io.metamask"},provider:r},this.initializeIfAvailable()),{success:!0,wallet:this.type,account:this.account};throw new Error("No accounts found")}catch(r){return console.error(`Error connecting to ${this.displayName}:`,r),{success:!1,wallet:this.type,error:r.message||"Unknown error"}}}async signTransaction(t){try{if(!this.isAvailable()||!this.account)throw new Error(`${this.displayName} is not connected`);const r=this.getEthereumProvider();if(!r)throw new Error(`${this.displayName} is not connected`);const n=await r.request({method:"eth_sendTransaction",params:[t]});return{success:!0,wallet:this.type,result:n}}catch(r){return console.error(`Error signing transaction with ${this.displayName}:`,r),{success:!1,wallet:this.type,error:r.message||"Unknown error"}}}async signMessage(t,r){try{if(!this.isAvailable()||!this.account)throw new Error(`${this.displayName} is not connected`);const n=this.getEthereumProvider();if(!n)throw new Error(`${this.displayName} provider not found`);const o=await n.request({method:"personal_sign",params:[t,r||this.account]});return{success:!0,wallet:this.type,result:o}}catch(n){return console.error(`Error signing message with ${this.displayName}:`,n),{success:!1,wallet:this.type,error:n.message||"Unknown error"}}}async signTypedData(t){try{if(!this.isAvailable()||!this.account)throw new Error(`${this.displayName} is not connected`);const r=this.getEthereumProvider();if(!r)throw new Error(`${this.displayName} is not connected`);const n=await r.request({method:"eth_signTypedData_v4",params:[this.account,JSON.stringify(t)]});return{success:!0,wallet:this.type,result:n}}catch(r){return console.error(`Error signing typed data with ${this.displayName}:`,r),{success:!1,wallet:this.type,error:r.message||"Unknown error"}}}async sendTransaction(t){try{if(!this.isAvailable()||!this.account)throw new Error(`${this.displayName} is not connected`);const r=this.getEthereumProvider();if(!r)throw new Error(`${this.displayName} is not connected`);const n=await r.request({method:"eth_sendTransaction",params:[t]});return{success:!0,wallet:this.type,result:n}}catch(r){return console.error(`Error sending transaction with ${this.displayName}:`,r),{success:!1,wallet:this.type,error:r.message||"Unknown error"}}}async switchChain(t){try{if(!this.isAvailable())throw new Error(`${this.displayName} is not available`);const r=this.getEthereumProvider();if(!r)throw new Error(`${this.displayName} is not connected`);try{return await r.request({method:"wallet_switchEthereumChain",params:[{chainId:t}]}),this.platform=de(t),!0}catch(n){throw n.code===4902&&console.warn(`Chain not added to ${this.displayName}`),n}}catch(r){return console.error(`Error switching chain for ${this.displayName}:`,r),!1}}async getBalance(t){try{if(!this.isAvailable()||!this.account)throw new Error(`${this.displayName} is not connected`);if(t)return{success:!1,wallet:this.type,error:"Not implemented for ERC20"};{const r=this.getEthereumProvider();if(!r)throw new Error(`${this.displayName} is not connected`);const n=await r.request({method:"eth_getBalance",params:[this.account,"latest"]});return{success:!0,wallet:this.type,result:n}}}catch(r){return console.error(`Error getting balance from ${this.displayName}:`,r),{success:!1,wallet:this.type,error:r.message||"Unknown error"}}}async waitForTransaction(t,r=6e4){try{if(!this.isAvailable())throw new Error(`${this.displayName} is not connected`);const n=this.getEthereumProvider();if(!n)throw new Error(`${this.displayName} is not connected`);const o=Date.now(),i=1e3;for(;Date.now()-o<r;){const s=await n.request({method:"eth_getTransactionReceipt",params:[t]});if(s)return{success:!0,wallet:this.type,result:s};await new Promise(a=>setTimeout(a,i))}throw new Error("Transaction confirmation timed out")}catch(n){return console.error(`Error waiting for transaction with ${this.displayName}:`,n),{success:!1,wallet:this.type,error:n.message||"Unknown error"}}}}class Jr extends ze{constructor(){super(...arguments);d(this,"type","base");d(this,"rdns","com.coinbase.wallet");d(this,"displayName","Base Wallet")}}class Xr extends ze{constructor(){super(...arguments);d(this,"type","metamask");d(this,"rdns","io.metamask");d(this,"displayName","MetaMask")}}/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ve(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function yt(e,...t){if(!ve(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function ft(e,t){return Array.isArray(t)?t.length===0?!0:e?t.every(r=>typeof r=="string"):t.every(r=>Number.isSafeInteger(r)):!1}function qr(e){if(typeof e!="function")throw new Error("function expected");return!0}function W(e,t){if(typeof t!="string")throw new Error(`${e}: string expected`);return!0}function K(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function oe(e){if(!Array.isArray(e))throw new Error("array expected")}function ie(e,t){if(!ft(!0,t))throw new Error(`${e}: array of strings expected`)}function pt(e,t){if(!ft(!1,t))throw new Error(`${e}: array of numbers expected`)}function Te(...e){const t=i=>i,r=(i,s)=>a=>i(s(a)),n=e.map(i=>i.encode).reduceRight(r,t),o=e.map(i=>i.decode).reduce(r,t);return{encode:n,decode:o}}function Se(e){const t=typeof e=="string"?e.split(""):e,r=t.length;ie("alphabet",t);const n=new Map(t.map((o,i)=>[o,i]));return{encode:o=>(oe(o),o.map(i=>{if(!Number.isSafeInteger(i)||i<0||i>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${e}`);return t[i]})),decode:o=>(oe(o),o.map(i=>{W("alphabet.decode",i);const s=n.get(i);if(s===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${e}`);return s}))}}function Ce(e=""){return W("join",e),{encode:t=>(ie("join.decode",t),t.join(e)),decode:t=>(W("join.decode",t),t.split(e))}}function Kr(e,t="="){return K(e),W("padding",t),{encode(r){for(ie("padding.encode",r);r.length*e%8;)r.push(t);return r},decode(r){ie("padding.decode",r);let n=r.length;if(n*e%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;n>0&&r[n-1]===t;n--)if((n-1)*e%8===0)throw new Error("padding: invalid, string has too much padding");return r.slice(0,n)}}}function en(e){return qr(e),{encode:t=>t,decode:t=>e(t)}}function He(e,t,r){if(t<2)throw new Error(`convertRadix: invalid from=${t}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: invalid to=${r}, base cannot be less than 2`);if(oe(e),!e.length)return[];let n=0;const o=[],i=Array.from(e,a=>{if(K(a),a<0||a>=t)throw new Error(`invalid integer: ${a}`);return a}),s=i.length;for(;;){let a=0,h=!0;for(let c=n;c<s;c++){const l=i[c],u=t*a,w=u+l;if(!Number.isSafeInteger(w)||u/t!==a||w-l!==u)throw new Error("convertRadix: carry overflow");const g=w/r;a=w%r;const f=Math.floor(g);if(i[c]=f,!Number.isSafeInteger(f)||f*r+a!==w)throw new Error("convertRadix: carry overflow");if(h)f?h=!1:n=c;else continue}if(o.push(a),h)break}for(let a=0;a<e.length-1&&e[a]===0;a++)o.push(0);return o.reverse()}const mt=(e,t)=>t===0?e:mt(t,e%t),se=(e,t)=>e+(t-mt(e,t)),we=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function Je(e,t,r,n){if(oe(e),t<=0||t>32)throw new Error(`convertRadix2: wrong from=${t}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(se(t,r)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${r} carryBits=${se(t,r)}`);let o=0,i=0;const s=we[t],a=we[r]-1,h=[];for(const c of e){if(K(c),c>=s)throw new Error(`convertRadix2: invalid data word=${c} from=${t}`);if(o=o<<t|c,i+t>32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${t}`);for(i+=t;i>=r;i-=r)h.push((o>>i-r&a)>>>0);const l=we[i];if(l===void 0)throw new Error("invalid carry");o&=l-1}if(o=o<<r-i&a,!n&&i>=t)throw new Error("Excess padding");if(!n&&o>0)throw new Error(`Non-zero padding: ${o}`);return n&&i>0&&h.push(o>>>0),h}function tn(e){K(e);const t=2**8;return{encode:r=>{if(!ve(r))throw new Error("radix.encode input should be Uint8Array");return He(Array.from(r),t,e)},decode:r=>(pt("radix.decode",r),Uint8Array.from(He(r,e,t)))}}function Nt(e,t=!1){if(K(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(se(8,e)>32||se(e,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!ve(r))throw new Error("radix2.encode input should be Uint8Array");return Je(Array.from(r),8,e,!t)},decode:r=>(pt("radix2.decode",r),Uint8Array.from(Je(r,e,8,t)))}}const rn=typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function",nn=rn?{encode(e){return yt(e),e.toBase64()},decode(e){return W("base64",e),Uint8Array.fromBase64(e,{lastChunkHandling:"strict"})}}:Te(Nt(6),Se("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Kr(6),Ce("")),on=e=>Te(tn(58),Se(e),Ce("")),Me=on("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),sn={encode:e=>new TextDecoder().decode(e),decode:e=>new TextEncoder().encode(e)},an=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",cn={encode(e){return yt(e),e.toHex()},decode(e){return W("hex",e),Uint8Array.fromHex(e)}},ge=an?cn:Te(Nt(4),Se("0123456789abcdef"),Ce(""),en(e=>{if(typeof e!="string"||e.length%2!==0)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()}));function Ie(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function L(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}const Mt=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);function _(e){return Object.prototype.toString.call(e)==="[object Object]"}function x(e){return Number.isSafeInteger(e)}const It=e=>{if(e!==null&&typeof e!="string"&&!v(e)&&!L(e)&&!x(e))throw new Error(`lengthCoder: expected null | number | Uint8Array | CoderType, got ${e} (${typeof e})`);return{encodeStream(t,r){if(e===null)return;if(v(e))return e.encodeStream(t,r);let n;if(typeof e=="number"?n=e:typeof e=="string"&&(n=R.resolve(t.stack,e)),typeof n=="bigint"&&(n=Number(n)),n===void 0||n!==r)throw t.err(`Wrong length: ${n} len=${e} exp=${r} (${typeof r})`)},decodeStream(t){let r;if(v(e)?r=Number(e.decodeStream(t)):typeof e=="number"?r=e:typeof e=="string"&&(r=R.resolve(t.stack,e)),typeof r=="bigint"&&(r=Number(r)),typeof r!="number")throw t.err(`Wrong length: ${r}`);return r}}},j={BITS:32,FULL_MASK:-1>>>0,len:e=>Math.ceil(e/32),create:e=>new Uint32Array(j.len(e)),clean:e=>e.fill(0),debug:e=>Array.from(e).map(t=>(t>>>0).toString(2).padStart(32,"0")),checkLen:(e,t)=>{if(j.len(t)!==e.length)throw new Error(`wrong length=${e.length}. Expected: ${j.len(t)}`)},chunkLen:(e,t,r)=>{if(t<0)throw new Error(`wrong pos=${t}`);if(t+r>e)throw new Error(`wrong range=${t}/${r} of ${e}`)},set:(e,t,r,n=!0)=>!n&&e[t]&r?!1:(e[t]|=r,!0),pos:(e,t)=>({chunk:Math.floor((e+t)/32),mask:1<<32-(e+t)%32-1}),indices:(e,t,r=!1)=>{j.checkLen(e,t);const{FULL_MASK:n,BITS:o}=j,i=o-t%o,s=i?n>>>i<<i:n,a=[];for(let h=0;h<e.length;h++){let c=e[h];if(r&&(c=~c),h===e.length-1&&(c&=s),c!==0)for(let l=0;l<o;l++){const u=1<<o-l-1;c&u&&a.push(h*o+l)}}return a},range:e=>{const t=[];let r;for(const n of e)r===void 0||n!==r.pos+r.length?t.push(r={pos:n,length:1}):r.length+=1;return t},rangeDebug:(e,t,r=!1)=>`[${j.range(j.indices(e,t,r)).map(n=>`(${n.pos}/${n.length})`).join(", ")}]`,setRange:(e,t,r,n,o=!0)=>{j.chunkLen(t,r,n);const{FULL_MASK:i,BITS:s}=j,a=r%s?Math.floor(r/s):void 0,h=r+n,c=h%s?Math.floor(h/s):void 0;if(a!==void 0&&a===c)return j.set(e,a,i>>>s-n<<s-n-r,o);if(a!==void 0&&!j.set(e,a,i>>>r%s,o))return!1;const l=a!==void 0?a+1:r/s,u=c!==void 0?c:h/s;for(let w=l;w<u;w++)if(!j.set(e,w,i,o))return!1;return!(c!==void 0&&a!==c&&!j.set(e,c,i<<s-h%s,o))}},R={pushObj:(e,t,r)=>{const n={obj:t};e.push(n),r((o,i)=>{n.field=o,i(),n.field=void 0}),e.pop()},path:e=>{const t=[];for(const r of e)r.field!==void 0&&t.push(r.field);return t.join("/")},err:(e,t,r)=>{const n=new Error(`${e}(${R.path(t)}): ${typeof r=="string"?r:r.message}`);return r instanceof Error&&r.stack&&(n.stack=r.stack),n},resolve:(e,t)=>{const r=t.split("/"),n=e.map(s=>s.obj);let o=0;for(;o<r.length&&r[o]==="..";o++)n.pop();let i=n.pop();for(;o<r.length;o++){if(!i||i[r[o]]===void 0)return;i=i[r[o]]}return i}};class xe{constructor(t,r={},n=[],o=void 0,i=0){this.pos=0,this.bitBuf=0,this.bitPos=0,this.data=t,this.opts=r,this.stack=n,this.parent=o,this.parentOffset=i,this.view=Mt(t)}_enablePointers(){if(this.parent)return this.parent._enablePointers();this.bs||(this.bs=j.create(this.data.length),j.setRange(this.bs,this.data.length,0,this.pos,this.opts.allowMultipleReads))}markBytesBS(t,r){return this.parent?this.parent.markBytesBS(this.parentOffset+t,r):!r||!this.bs?!0:j.setRange(this.bs,this.data.length,t,r,!1)}markBytes(t){const r=this.pos;this.pos+=t;const n=this.markBytesBS(r,t);if(!this.opts.allowMultipleReads&&!n)throw this.err(`multiple read pos=${this.pos} len=${t}`);return n}pushObj(t,r){return R.pushObj(this.stack,t,r)}readView(t,r){if(!Number.isFinite(t))throw this.err(`readView: wrong length=${t}`);if(this.pos+t>this.data.length)throw this.err("readView: Unexpected end of buffer");const n=r(this.view,this.pos);return this.markBytes(t),n}absBytes(t){if(t>this.data.length)throw new Error("Unexpected end of buffer");return this.data.subarray(t)}finish(){if(!this.opts.allowUnreadBytes){if(this.bitPos)throw this.err(`${this.bitPos} bits left after unpack: ${ge.encode(this.data.slice(this.pos))}`);if(this.bs&&!this.parent){const t=j.indices(this.bs,this.data.length,!0);if(t.length){const r=j.range(t).map(({pos:n,length:o})=>`(${n}/${o})[${ge.encode(this.data.subarray(n,n+o))}]`).join(", ");throw this.err(`unread byte ranges: ${r} (total=${this.data.length})`)}else return}if(!this.isEnd())throw this.err(`${this.leftBytes} bytes ${this.bitPos} bits left after unpack: ${ge.encode(this.data.slice(this.pos))}`)}}err(t){return R.err("Reader",this.stack,t)}offsetReader(t){if(t>this.data.length)throw this.err("offsetReader: Unexpected end of buffer");return new xe(this.absBytes(t),this.opts,this.stack,this,t)}bytes(t,r=!1){if(this.bitPos)throw this.err("readBytes: bitPos not empty");if(!Number.isFinite(t))throw this.err(`readBytes: wrong length=${t}`);if(this.pos+t>this.data.length)throw this.err("readBytes: Unexpected end of buffer");const n=this.data.subarray(this.pos,this.pos+t);return r||this.markBytes(t),n}byte(t=!1){if(this.bitPos)throw this.err("readByte: bitPos not empty");if(this.pos+1>this.data.length)throw this.err("readBytes: Unexpected end of buffer");const r=this.data[this.pos];return t||this.markBytes(1),r}get leftBytes(){return this.data.length-this.pos}get totalBytes(){return this.data.length}isEnd(){return this.pos>=this.data.length&&!this.bitPos}bits(t){if(t>32)throw this.err("BitReader: cannot read more than 32 bits in single call");let r=0;for(;t;){this.bitPos||(this.bitBuf=this.byte(),this.bitPos=8);const n=Math.min(t,this.bitPos);this.bitPos-=n,r=r<<n|this.bitBuf>>this.bitPos&2**n-1,this.bitBuf&=2**this.bitPos-1,t-=n}return r>>>0}find(t,r=this.pos){if(!L(t))throw this.err(`find: needle is not bytes! ${t}`);if(this.bitPos)throw this.err("findByte: bitPos not empty");if(!t.length)throw this.err("find: needle is empty");for(let n=r;(n=this.data.indexOf(t[0],n))!==-1;n++){if(n===-1||this.data.length-n<t.length)return;if(Ie(t,this.data.subarray(n,n+t.length)))return n}}}class hn{constructor(t=[]){this.pos=0,this.buffers=[],this.ptrs=[],this.bitBuf=0,this.bitPos=0,this.viewBuf=new Uint8Array(8),this.finished=!1,this.stack=t,this.view=Mt(this.viewBuf)}pushObj(t,r){return R.pushObj(this.stack,t,r)}writeView(t,r){if(this.finished)throw this.err("buffer: finished");if(!x(t)||t>8)throw new Error(`wrong writeView length=${t}`);r(this.view),this.bytes(this.viewBuf.slice(0,t)),this.viewBuf.fill(0)}err(t){if(this.finished)throw this.err("buffer: finished");return R.err("Reader",this.stack,t)}bytes(t){if(this.finished)throw this.err("buffer: finished");if(this.bitPos)throw this.err("writeBytes: ends with non-empty bit buffer");this.buffers.push(t),this.pos+=t.length}byte(t){if(this.finished)throw this.err("buffer: finished");if(this.bitPos)throw this.err("writeByte: ends with non-empty bit buffer");this.buffers.push(new Uint8Array([t])),this.pos++}finish(t=!0){if(this.finished)throw this.err("buffer: finished");if(this.bitPos)throw this.err("buffer: ends with non-empty bit buffer");const r=this.buffers.concat(this.ptrs.map(i=>i.buffer)),n=r.map(i=>i.length).reduce((i,s)=>i+s,0),o=new Uint8Array(n);for(let i=0,s=0;i<r.length;i++){const a=r[i];o.set(a,s),s+=a.length}for(let i=this.pos,s=0;s<this.ptrs.length;s++){con