@hashgraphonline/standards-sdk 0.1.107 → 0.1.109
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/cjs/hcs-11/client.d.ts +26 -26
- package/dist/cjs/hcs-12/validation/schemas.d.ts +10 -10
- package/dist/cjs/hcs-14/types.d.ts +2 -2
- package/dist/cjs/standards-sdk.cjs +1 -1
- package/dist/cjs/standards-sdk.cjs.map +1 -1
- package/dist/cjs/utils/logger.d.ts +7 -2
- package/dist/cjs/utils/logger.d.ts.map +1 -1
- package/dist/es/hcs-11/client.d.ts +26 -26
- package/dist/es/hcs-12/validation/schemas.d.ts +10 -10
- package/dist/es/hcs-14/types.d.ts +2 -2
- package/dist/es/standards-sdk.es112.js +1 -1
- package/dist/es/standards-sdk.es123.js +14 -201
- package/dist/es/standards-sdk.es123.js.map +1 -1
- package/dist/es/standards-sdk.es124.js +201 -14
- package/dist/es/standards-sdk.es124.js.map +1 -1
- package/dist/es/standards-sdk.es59.js +1 -1
- package/dist/es/standards-sdk.es60.js +1 -1
- package/dist/es/standards-sdk.es93.js +61 -39
- package/dist/es/standards-sdk.es93.js.map +1 -1
- package/dist/es/utils/logger.d.ts +7 -2
- package/dist/es/utils/logger.d.ts.map +1 -1
- package/package.json +8 -8
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var e,t;Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("pino"),n=require("zod"),o=require("@hashgraph/sdk"),r=require("axios"),a=require("@hashgraph/proto"),s=require("buffer"),c=require("ethers"),p=require("file-type"),l=require("mime-types"),u=require("date-fns"),d=require("crypto");function f(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const i in e)if("default"!==i){const n=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,n.get?n:{enumerable:!0,get:()=>e[i]})}return t.default=e,Object.freeze(t)}const m=f(l);let h=null;let g=((e=class{constructor(e={}){if(h)return h(e);const t="true"===process.env.DISABLE_LOGS,n=void 0!==process.env.JEST_WORKER_ID||"test"===process.env.NODE_ENV,o=e.silent||t,r=o?"silent":e.level||"info";this.moduleContext=e.module||"app";const a={level:r,enabled:!o,transport:!o&&!1!==e.prettyPrint&&!n?{target:"pino-pretty",options:{colorize:!0,translateTime:"SYS:standard",ignore:"pid,hostname"}}:void 0},s=n?i.destination({sync:!0}):void 0;this.logger=i(a,s)}static getInstance(t={}){const i=t.module||"default";if("true"===process.env.DISABLE_LOGS&&e.instances.has(i)){"silent"!==e.instances.get(i).getLevel()&&e.instances.delete(i)}if(!e.instances.has(i)){const n=h?h(t):new e(t);e.instances.set(i,n)}return e.instances.get(i)}setLogLevel(e){this.logger.level=e}getLevel(){return this.logger.level}setSilent(e){e&&(this.logger.level="silent")}setModule(e){this.moduleContext=e}formatArgs(e){if(0===e.length)return{msg:""};if(1===e.length)return"string"==typeof e[0]?{msg:e[0]}:{msg:"",data:e[0]};const t=[],i=[];e.forEach(e=>{"string"==typeof e||"number"==typeof e||"boolean"==typeof e?t.push(String(e)):i.push(e)});const n=t.join(" ");return i.length>0?{msg:n,data:i}:{msg:n}}debug(...e){const{msg:t,data:i}=this.formatArgs(e),n={module:this.moduleContext,...i&&{data:i}};this.logger.debug(n,t)}info(...e){const{msg:t,data:i}=this.formatArgs(e),n={module:this.moduleContext,...i&&{data:i}};this.logger.info(n,t)}warn(...e){const{msg:t,data:i}=this.formatArgs(e),n={module:this.moduleContext,...i&&{data:i}};this.logger.warn(n,t)}error(...e){const{msg:t,data:i}=this.formatArgs(e),n={module:this.moduleContext,...i&&{data:i}};this.logger.error(n,t)}trace(...e){const{msg:t,data:i}=this.formatArgs(e),n={module:this.moduleContext,...i&&{data:i}};this.logger.trace(n,t)}static clearInstances(){e.instances.clear()}}).instances=new Map,e);const y=e=>new Promise(t=>setTimeout(t,e));class v{constructor(){this.modelViewerLoaded=!1,this.modelViewerLoading=null,this.config={cdnUrl:"https://kiloscribe.com/api/inscription-cdn/",network:"mainnet",retryAttempts:3,retryBackoff:300,debug:!1,showLoadingIndicator:!1,loadingCallbackName:null},this.configMapping={hcsCdnUrl:"cdnUrl",hcsNetwork:"network",hcsRetryAttempts:"retryAttempts",hcsRetryBackoff:"retryBackoff",hcsDebug:"debug",hcsShowLoadingIndicator:"showLoadingIndicator",hcsLoadingCallbackName:"loadingCallbackName"},this.LoadedScripts={},this.LoadedWasm={},this.LoadedImages={},this.LoadedVideos={},this.LoadedAudios={},this.LoadedAudioUrls={},this.LoadedGLBs={},this.scriptLoadedEvent=new Event("HCSScriptLoaded"),this.loadQueue=[],this.isProcessingQueue=!1;try{this.logger=g.getInstance({module:"HCS-3",level:this.config.debug?"debug":"error"})}catch(e){this.logger=this.createFallbackLogger()}}createFallbackLogger(){return{debug:(...e)=>this.config.debug&&console.debug("[HCS-3]",...e),info:(...e)=>this.config.debug&&console.info("[HCS-3]",...e),warn:(...e)=>console.warn("[HCS-3]",...e),error:(...e)=>console.error("[HCS-3]",...e),setLogLevel:e=>{this.config.debug="debug"===e}}}log(...e){if(0===e.length)this.logger.debug("");else if(1===e.length)this.logger.debug(String(e[0]));else{const t=String(e[0]),i=e.slice(1);this.logger.debug(t,i)}}error(...e){if(0===e.length)this.logger.error("");else if(1===e.length)this.logger.error(String(e[0]));else{const t=String(e[0]),i=e.slice(1);this.logger.error(t,i)}}loadConfigFromHTML(){const e=document.querySelector("script[data-hcs-config]");e&&(Object.keys(this.configMapping).forEach(t=>{if(e.dataset[t]){const i=this.configMapping[t];let n=e.dataset[t];"true"===n&&(n=!0),"false"===n&&(n=!1),isNaN(Number(n))||""===n||(n=Number(n)),this.config[i]=n}}),this.logger.setLogLevel(this.config.debug?"debug":"error")),this.log("Loaded config:",this.config)}updateLoadingStatus(e,t){if("loaded"!==this.LoadedScripts[e]&&(this.config.showLoadingIndicator&&console.log("[HCS Loading] "+e+" : "+t),this.LoadedScripts[e]=t,this.config.loadingCallbackName&&"function"==typeof window[this.config.loadingCallbackName])){const i=window[this.config.loadingCallbackName];"function"==typeof i&&i(e,t)}}async fetchWithRetry(e,t=this.config.retryAttempts,i=this.config.retryBackoff){try{const t=await fetch(e);if(!t.ok)throw new Error("HTTP error! status: "+t.status);return t}catch(n){if(t>0)return this.log("Retrying fetch for "+e+" Attempts left: "+(t-1)),await this.sleep(i),this.fetchWithRetry(e,t-1,2*i);throw n}}sleep(e){return y(e)}isDuplicate(e){return!!this.LoadedScripts[e]}async retrieveHCS1Data(e,t=this.config.cdnUrl,i=this.config.network){const n=i.replace(/['"]+/g,""),o=await this.fetchWithRetry(t+e+"?network="+n);return await o.blob()}async loadScript(e){const t=e.getAttribute("data-src"),i=e.getAttribute("data-script-id"),n=t?.split("/").pop(),o=e.getAttribute("type"),r=e.hasAttribute("data-required"),a="module"===e.getAttribute("type");if(!this.isDuplicate(n||"")){this.updateLoadingStatus(i,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,s=e.getAttribute("data-network")||this.config.network,c=await this.retrieveHCS1Data(n,t,s);if("wasm"===o){const t=await c.arrayBuffer(),n=await WebAssembly.compile(t);this.LoadedWasm[i]=await WebAssembly.instantiate(n,{env:{},...e.dataset}),this.updateLoadingStatus(i,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded wasm: "+i)}else{const e=await c.text(),t=document.createElement("script");if(t.textContent=e,t.className="hcs-inline-script",i&&t.setAttribute("data-loaded-script-id",i),a){t.type="module";const i=new Blob([e],{type:"application/javascript"});t.src=URL.createObjectURL(i)}document.body.appendChild(t),this.updateLoadingStatus(i,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded script: "+i),t.onerror=e=>{if(this.error("Failed to load "+o+": "+i,e),this.updateLoadingStatus(i,"failed"),r)throw e}}}catch(s){if(this.error("Failed to load "+o+": "+i,s),this.updateLoadingStatus(i,"failed"),r)throw s}}}async loadModuleExports(e){const t=document.querySelector('script[data-loaded-script-id="'+e+'"]');if(!t)throw new Error("Module script with id "+e+" not found");const i=t.getAttribute("src");if(!i)throw new Error("Module script "+e+" has no src attribute");try{const e=new Function("url","return import(url)");return await e(i)}catch(n){throw this.error("Failed to import module",n),n}}async loadStylesheet(e){const t=e.getAttribute("data-src"),i=e.getAttribute("data-script-id"),n=t?.split("/").pop(),o=e.hasAttribute("data-required");if(!this.isDuplicate(n||"")){this.updateLoadingStatus(i,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,o=e.getAttribute("data-network")||this.config.network,r=await this.retrieveHCS1Data(n,t,o),a=await r.text(),s=document.createElement("style");s.textContent=a,document.head.appendChild(s),this.updateLoadingStatus(i,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded and inlined stylesheet: "+i)}catch(r){if(this.error("Failed to load stylesheet: "+i,r),this.updateLoadingStatus(i,"failed"),o)throw r}}}async loadImage(e){const t=e.getAttribute("data-src"),i=t?.split("/").pop();this.log("Loading image: "+i),this.updateLoadingStatus("Image: "+i,"loaded");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,n=e.getAttribute("data-network")||this.config.network,o=await this.retrieveHCS1Data(i,t,n),r=URL.createObjectURL(o);e.src=r,this.LoadedImages[i]=r,this.updateLoadingStatus("Image: "+i,"loaded"),this.log("Loaded image: "+i)}catch(n){this.error("Failed to load image: "+i,n),this.updateLoadingStatus("Image: "+i,"failed")}}async loadMedia(e,t){const i=e.getAttribute("data-src"),n=i?.split("/").pop();this.log("Loading "+t+": "+n),this.updateLoadingStatus(t+": "+n,"loading");try{const i=e.getAttribute("data-cdn-url")||this.config.cdnUrl,o=e.getAttribute("data-network")||this.config.network,r=await this.retrieveHCS1Data(n,i,o),a=URL.createObjectURL(r);e.src=a,"video"===t?this.LoadedVideos[n]=a:this.LoadedAudioUrls[n]=a,this.updateLoadingStatus(t+": "+n,"loaded"),this.log("Loaded "+t+": "+n)}catch(o){this.error("Failed to load "+t+": "+n,o),this.updateLoadingStatus(t+": "+n,"failed")}}async loadModelViewer(){return this.modelViewerLoading?this.modelViewerLoading:this.modelViewerLoaded?Promise.resolve():(this.modelViewerLoading=new Promise(e=>{const t=document.createElement("script");t.setAttribute("data-src","hcs://1/0.0.7293044"),t.setAttribute("data-script-id","model-viewer"),t.setAttribute("type","module"),window.addEventListener("HCSScriptLoaded",()=>{this.modelViewerLoaded=!0,e()},{once:!0}),this.loadScript(t)}),this.modelViewerLoading)}async loadGLB(e){await this.loadModelViewer();const t=e.getAttribute("data-src"),i=t?.split("/").pop();this.log("Loading GLB: "+i),this.updateLoadingStatus("GLB: "+i,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,n=e.getAttribute("data-network")||this.config.network;let o;"model-viewer"!==e.tagName.toLowerCase()?(o=document.createElement("model-viewer"),Array.from(e.attributes).forEach(e=>{o.setAttribute(e.name,e.value)}),o.setAttribute("camera-controls",""),o.setAttribute("auto-rotate",""),o.setAttribute("ar",""),e.parentNode?.replaceChild(o,e)):o=e;const r=await this.retrieveHCS1Data(i,t,n),a=URL.createObjectURL(r);o.setAttribute("src",a),this.LoadedGLBs[i]=a,this.updateLoadingStatus("GLB: "+i,"loaded"),this.log("Loaded GLB: "+i)}catch(n){this.error("Failed to load GLB: "+i,n),this.updateLoadingStatus("GLB: "+i,"failed")}}async loadResource(e,t,i){return new Promise(n=>{this.loadQueue.push({element:e,type:t,order:i,resolve:n}),this.processQueue()})}async processQueue(){if(!this.isProcessingQueue){for(this.isProcessingQueue=!0;this.loadQueue.length>0;){const t=this.loadQueue.shift();try{"script"===t.type?await this.loadScript(t.element):"image"===t.type?await this.loadImage(t.element):"video"===t.type||"audio"===t.type?await this.loadMedia(t.element,t.type):"glb"===t.type?await this.loadGLB(t.element):"css"===t.type&&await this.loadStylesheet(t.element),t.resolve()}catch(e){if(this.error("Error processing queue item:",e),"script"===t.type&&t.element.hasAttribute("data-required"))break}}this.isProcessingQueue=!1}}async replaceHCSInStyle(e){let t=e,i=t.indexOf("hcs://");for(;-1!==i;){let e=i;for(;e<t.length&&!["'",'"'," ",")"].includes(t[e]);)e++;const o=t.substring(i,e),r=o.split("/").pop();try{const n=this.config.cdnUrl,a=this.config.network,s=await this.retrieveHCS1Data(r,n,a),c=URL.createObjectURL(s);t=t.substring(0,i)+c+t.substring(e),this.LoadedImages[r]=c,this.log("Replaced CSS HCS URL: "+o+" with "+c)}catch(n){this.error("Failed to load CSS image: "+r,n)}i=t.indexOf("hcs://",i+1)}return t}async processInlineStyles(){const e=document.querySelectorAll('[style*="hcs://"]');this.log("Found "+e.length+" elements with HCS style references");for(const i of Array.from(e)){const e=i.getAttribute("style");if(e){this.log("Processing style: "+e);const t=await this.replaceHCSInStyle(e);e!==t&&(i.setAttribute("style",t),this.log("Updated style to: "+t))}}const t=document.querySelectorAll("style");for(const i of Array.from(t))if(i.textContent?.includes("hcs://")){const e=await this.replaceHCSInStyle(i.textContent);i.textContent!==e&&(i.textContent=e)}}async init(){return this.loadConfigFromHTML(),new Promise(e=>{const t=async()=>{const t=document.querySelectorAll('script[data-src^="hcs://"]'),i=document.querySelectorAll('img[data-src^="hcs://"], img[src^="hcs://"]'),n=document.querySelectorAll('video[data-src^="hcs://"], video[src^="hcs://"]'),o=document.querySelectorAll('audio[data-src^="hcs://"], audio[src^="hcs://"]'),r=document.querySelectorAll('model-viewer[data-src^="hcs://"]'),a=document.querySelectorAll('link[data-src^="hcs://"]');document.querySelectorAll('[src^="hcs://"]').forEach(e=>{const t=e.getAttribute("src");t&&(e.setAttribute("data-src",t),e.removeAttribute("src"))}),await this.processInlineStyles();const s=[];[{elements:t,type:"script"},{elements:i,type:"image"},{elements:n,type:"video"},{elements:o,type:"audio"},{elements:r,type:"glb"},{elements:a,type:"css"}].forEach(({elements:e,type:t})=>{e.forEach(e=>{const i=parseInt(e.getAttribute("data-load-order")||"")||1/0;s.push(this.loadResource(e,t,i))})}),await Promise.all(s);const c=new MutationObserver(e=>{e.forEach(e=>{if(e.addedNodes.forEach(e=>{if(e.nodeType===Node.ELEMENT_NODE){const t=e;if(t.getAttribute("style")?.includes("hcs://")&&this.processInlineStyles(),"style"===t.tagName.toLowerCase()&&t.textContent?.includes("hcs://")&&this.processInlineStyles(),t.getAttribute("src")?.startsWith("hcs://")){const e=t.getAttribute("src");t.setAttribute("data-src",e),t.removeAttribute("src");switch(t.tagName.toLowerCase()){case"img":this.loadResource(t,"image",1/0);break;case"video":this.loadResource(t,"video",1/0);break;case"audio":this.loadResource(t,"audio",1/0);break;case"script":this.loadResource(t,"script",1/0)}}t.matches('script[data-src^="hcs://"]')?this.loadResource(t,"script",1/0):t.matches('img[data-src^="hcs://"]')?this.loadResource(t,"image",1/0):t.matches('video[data-src^="hcs://"]')?this.loadResource(t,"video",1/0):t.matches('audio[data-src^="hcs://"]')?this.loadResource(t,"audio",1/0):t.matches('model-viewer[data-src^="hcs://"]')?this.loadResource(t,"glb",1/0):t.matches('link[data-src^="hcs://"]')&&this.loadResource(t,"css",1/0);t.querySelectorAll('[data-src^="hcs://"], [src^="hcs://"]').forEach(e=>{const t=e,i=t.tagName.toLowerCase(),n=t.getAttribute("src");switch(n?.startsWith("hcs://")&&(t.setAttribute("data-src",n),t.removeAttribute("src")),i){case"script":this.loadResource(t,"script",1/0);break;case"img":this.loadResource(t,"image",1/0);break;case"video":this.loadResource(t,"video",1/0);break;case"audio":this.loadResource(t,"audio",1/0);break;case"model-viewer":this.loadResource(t,"glb",1/0);break;case"link":this.loadResource(t,"css",1/0)}})}}),"attributes"===e.type){const t=e.target;if("style"===e.attributeName&&t.getAttribute("style")?.includes("hcs://"))this.processInlineStyles();else if("src"===e.attributeName){const e=t.getAttribute("src");if(e?.startsWith("hcs://")){t.setAttribute("data-src",e),t.removeAttribute("src");const i=t.tagName.toLowerCase();["img","video","audio"].includes(i)&&this.loadResource(t,i,1/0)}}}})});document.body?c.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","src","data-src"]}):document.addEventListener("DOMContentLoaded",()=>{c.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","src","data-src"]})}),e()};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):t()})}async preloadImage(e){this.log("Loading image:"+e),this.updateLoadingStatus("image: "+e,"loading");const t=await this.retrieveHCS1Data(e),i=URL.createObjectURL(t);return this.LoadedImages[e]=i,this.updateLoadingStatus("image: "+e,"loaded"),i}async preloadAudio(e){const t=document.createElement("audio");t.setAttribute("data-topic-id",e),t.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(t),await this.loadMedia(t,"audio");const i=document.querySelector('audio[data-topic-id="'+e+'"]');return i?this.LoadedAudioUrls[e]=i.src:console.error("Failed to preload audio: "+e),this.LoadedAudioUrls[e]}async playAudio(e,t=1){const i=this.LoadedAudioUrls[e];if(i){const n=new Audio(i);n.volume=t,this.LoadedAudios[e]=n,n.play().catch(e=>{console.error("Failed to play audio:",e)}),n.addEventListener("ended",()=>{n.remove(),delete this.LoadedAudios[e]})}else console.error("Audio not preloaded: "+e)}async pauseAudio(e){const t=document.querySelector('audio[data-topic-id="'+e+'"]');t?(console.log("found element",t),t.pause(),this.LoadedAudios[e]?.pause()):this.LoadedAudios[e]?.pause()}async loadAndPlayAudio(e,t=!1,i=1){let n=document.querySelector('audio[data-topic-id="'+e+'"]');if(n)n.volume=i,await n.play();else{const o=document.createElement("audio");o.volume=i,t&&o.setAttribute("autoplay","autoplay"),o.setAttribute("data-topic-id",e),o.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(o),await this.loadMedia(o,"audio"),n=document.querySelector('audio[data-topic-id="'+e+'"]'),t||await n.play()}}}var b=(e=>(e.REGISTER="register",e))(b||{}),x=(e=>(e[e.NON_INDEXED=1]="NON_INDEXED",e))(x||{});function w(e){return`hcs://6/${e}`}const k=n.z.string().regex(/^\d+\.\d+\.\d+$/,{message:"Topic ID must be in Hedera format (e.g., '0.0.123456')"}),_=n.z.object({p:n.z.literal("hcs-6"),op:n.z.enum(["register"]),m:n.z.string().max(500,"Memo must not exceed 500 characters").optional()}),E=_.extend({op:n.z.literal("register"),t_id:k}),S=n.z.discriminatedUnion("op",[E]);function T(e){return e>=3600}function A(e){if(!T(e))throw new Error("TTL must be at least 3600 seconds (1 hour)");return`hcs-6:1:${e}`}let I=class{constructor(e,t,i){this.maxRetries=5,this.initialDelayMs=2e3,this.maxDelayMs=3e4,this.backoffFactor=2,this.network=e,this.apiKey=i?.apiKey,this.customHeaders=i?.headers||{},this.baseUrl=i?.customUrl||this.getMirrorNodeUrl(),this.logger=t||new g({level:"debug",module:"MirrorNode"}),this.isServerEnvironment="undefined"==typeof window,i?.customUrl&&this.logger.info(`Using custom mirror node URL: ${i.customUrl}`),i?.apiKey&&this.logger.info("Using API key for mirror node requests")}configureRetry(e){this.maxRetries=e.maxRetries??this.maxRetries,this.initialDelayMs=e.initialDelayMs??this.initialDelayMs,this.maxDelayMs=e.maxDelayMs??this.maxDelayMs,this.backoffFactor=e.backoffFactor??this.backoffFactor,this.logger.info(`Retry configuration updated: maxRetries=${this.maxRetries}, initialDelayMs=${this.initialDelayMs}, maxDelayMs=${this.maxDelayMs}, backoffFactor=${this.backoffFactor}`)}configureMirrorNode(e){e.customUrl&&(this.baseUrl=e.customUrl,this.logger.info(`Updated mirror node URL: ${e.customUrl}`)),e.apiKey&&(this.apiKey=e.apiKey,this.logger.info("Updated API key for mirror node requests")),e.headers&&(this.customHeaders={...this.customHeaders,...e.headers},this.logger.info("Updated custom headers for mirror node requests"))}constructUrl(e){if(this.baseUrl.includes("<API-KEY>")&&this.apiKey){const t=this.baseUrl.replace("<API-KEY>",this.apiKey);return e.startsWith("/")?`${t}${e}`:`${t}/${e}`}return e.startsWith("/")?`${this.baseUrl}${e}`:`${this.baseUrl}/${e}`}getMirrorNodeUrl(){return"mainnet"===this.network?"https://mainnet-public.mirrornode.hedera.com":"https://testnet.mirrornode.hedera.com"}getBaseUrl(){return this.baseUrl}async getPublicKey(e){this.logger.debug(`Getting public key for account ${e}`);const t=await this.requestAccount(e);try{if(!t||!t.key)throw new Error(`Failed to retrieve public key for account ID: ${e}`);return o.PublicKey.fromString(t.key.key)}catch(i){const e=`Error fetching public key from Mirror Node: ${i.message}`;throw this.logger.error(e),new Error(e)}}async getAccountMemo(e){this.logger.debug(`Getting account memo for account ID: ${e}`);try{const t=await this._requestWithRetry(`/api/v1/accounts/${e}`);return t?.memo?t.memo:(this.logger.warn(`No memo found for account ${e}`),null)}catch(t){const i=t;return this.logger.error(`Failed to get account memo for ${e} after retries: ${i.message}`),null}}async getTopicInfo(e){try{this.logger.debug(`Fetching topic info for ${e}`);return await this._requestWithRetry(`/api/v1/topics/${e}`)}catch(t){const i=`Error retrieving topic information for ${e} after retries: ${t.message}`;throw this.logger.error(i),new Error(i)}}async getTopicFees(e){try{return(await this.getTopicInfo(e)).custom_fees}catch(t){const e=`Error retrieving topic fees: ${t.message}`;return this.logger.error(e),null}}async getHBARPrice(e){try{const t=o.Timestamp.fromDate(e).toString();this.logger.debug(`Fetching HBAR price for timestamp ${t}`);const i=await this._requestWithRetry(`/api/v1/network/exchangerate?timestamp=${t}`);return Number(i?.current_rate?.cent_equivalent)/Number(i?.current_rate?.hbar_equivalent)/100}catch(t){const e=`Error retrieving HBAR price: ${t.message}`;return this.logger.error(e),null}}async getTokenInfo(e){this.logger.debug(`Fetching token info for ${e}`);try{const t=await this._requestWithRetry(`/api/v1/tokens/${e}`);return t?(this.logger.trace(`Token info found for ${e}:`,t),t):(this.logger.warn(`No token info found for ${e}`),null)}catch(t){const i=`Error fetching token info for ${e}: ${t.message}`;return this.logger.error(i),null}}async getTopicMessages(e,t){this.logger.trace(`Querying messages for topic ${e}${t?" with filters":""}`);let i=`/api/v1/topics/${e}/messages`;const n=new URLSearchParams;if(t){if(void 0!==t.sequenceNumber){const e="number"==typeof t.sequenceNumber?t.sequenceNumber.toString():t.sequenceNumber;e.match(/^(gt|gte|lt|lte|eq|ne):/)?n.append("sequencenumber",e):n.append("sequencenumber",`gt:${e}`)}t.limit&&n.append("limit",t.limit.toString()),t.order&&n.append("order",t.order)}const o=n.toString();o&&(i+=`?${o}`);const r=[];let a=i;for(;a;)try{const e=await this._requestWithRetry(a);if(e.messages&&e.messages.length>0)for(const t of e.messages)try{if(!t.message)continue;let e,i;try{e=this.isServerEnvironment?globalThis.Buffer.from(t.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(t.message),e=>e.charCodeAt(0)))}catch(s){const e=`Error decoding message: ${s}`;this.logger.error(e);continue}try{i=JSON.parse(e)}catch(s){const t=`Invalid JSON message content: ${e}`;this.logger.error(t);continue}i.sequence_number=t.sequence_number,r.push({...i,consensus_timestamp:t.consensus_timestamp,sequence_number:t.sequence_number,running_hash:t.running_hash,running_hash_version:t.running_hash_version,topic_id:t.topic_id,payer:t.payer_account_id,created:new Date(1e3*Number(t.consensus_timestamp))})}catch(s){const e=`Error processing message: ${s.message}`;this.logger.error(e)}a=e.links?.next||""}catch(c){const t=`Error querying topic messages for topic ${e} (endpoint: ${a}) after retries: ${c.message}`;throw this.logger.error(t),new Error(t)}return r}async requestAccount(e){try{this.logger.debug(`Requesting account info for ${e}`);const t=await this._requestWithRetry(`/api/v1/accounts/${e}`);if(!t)throw new Error(`No data received from mirror node for account: ${e}`);return t}catch(t){const i=`Failed to fetch account ${e} after retries: ${t.message}`;throw this.logger.error(i),new Error(i)}}async checkKeyListAccess(e,t){try{const i=a.proto.Key.decode(e);return this.evaluateKeyAccess(i,t)}catch(i){const e=`Error decoding protobuf key: ${i.message}`;throw this.logger.error(e),new Error(e)}}async evaluateKeyAccess(e,t){return e.ed25519?this.compareEd25519Key(e.ed25519,t):e.keyList?this.evaluateKeyList(e.keyList,t):!(!e.thresholdKey||!e.thresholdKey.keys)&&this.evaluateKeyList(e.thresholdKey.keys,t)}async evaluateKeyList(e,t){const i=e.keys||[];for(const o of i)if(o)if(o.ed25519){if(this.compareEd25519Key(o.ed25519,t))return!0}else if(o.keyList||o.thresholdKey)try{const e=a.proto.Key.encode({...o.keyList?{keyList:o.keyList}:{},...o.thresholdKey?{thresholdKey:o.thresholdKey}:{}}).finish();if(await this.checkKeyListAccess(globalThis.Buffer.from(e),t))return!0}catch(n){const e=`Error in nested key: ${n.message}`;this.logger.debug(e)}return!1}compareEd25519Key(e,t){try{return o.PublicKey.fromBytes(globalThis.Buffer.from(e)).toString()===t.toString()}catch(i){const e=`Error comparing Ed25519 key: ${i.message}`;return this.logger.debug(e),!1}}async getScheduleInfo(e){try{this.logger.info(`Getting information for scheduled transaction ${e}`);const t=await this._requestWithRetry(`/api/v1/schedules/${e}`);return t||(this.logger.warn(`No schedule info found for ${e} after retries.`),null)}catch(t){return this.logger.error(`Error fetching schedule info for ${e} after retries: ${t.message}`),null}}async getScheduledTransactionStatus(e){try{this.logger.info(`Checking status of scheduled transaction ${e}`);const t=await this.getScheduleInfo(e);if(!t)throw new Error(`Schedule ${e} not found`);return{executed:Boolean(t.executed_timestamp),executedDate:t.executed_timestamp?new Date(1e3*Number(t.executed_timestamp)):void 0,deleted:t.deleted||!1}}catch(t){throw this.logger.error(`Error checking scheduled transaction status: ${t}`),t}}async getTransaction(e){this.logger.info(`Getting transaction details for ID/hash: ${e}`);try{const t=await this._requestWithRetry(`/api/v1/transactions/${e}`);return t?.transactions?.length>0?(this.logger.trace(`Transaction details found for ${e}:`,t.transactions[0]),t.transactions[0]):(this.logger.warn(`No transaction details found for ${e} or unexpected response structure.`),null)}catch(t){const i=t;return this.logger.error(`Failed to get transaction details for ${e} after retries: ${i.message}`),null}}async _requestWithRetry(e,t){let i=0,n=this.initialDelayMs;const o=this.constructUrl(e),a={...t,headers:{...this.customHeaders,...t?.headers}};for(this.apiKey&&(a.headers={...a.headers,Authorization:`Bearer ${this.apiKey}`,"X-API-Key":this.apiKey});i<this.maxRetries;)try{return(await r.get(o,a)).data}catch(s){i++;const e=i>=this.maxRetries,t=s.response?.status;if(t&&t>404&&t<500&&429!==t)throw this.logger.error(`Client error for ${o} (status ${t}): ${s.message}. Not retrying.`),s;if(e)throw this.logger.error(`Max retries (${this.maxRetries}) reached for ${o}. Last error: ${s.message}`),s;this.logger.warn(`Attempt ${i}/${this.maxRetries} failed for ${o}: ${s.message}. Retrying in ${n}ms...`),await new Promise(e=>setTimeout(e,n)),n=Math.min(n*this.backoffFactor,this.maxDelayMs)}throw new Error(`Failed to fetch data from ${o} after ${this.maxRetries} attempts.`)}async _fetchWithRetry(e,t){let i=0,n=this.initialDelayMs;const o={...this.customHeaders};t?.headers&&(t.headers instanceof Headers?t.headers.forEach((e,t)=>{o[t]=e}):Array.isArray(t.headers)?t.headers.forEach(([e,t])=>{o[e]=t}):Object.assign(o,t.headers)),this.apiKey&&(o.Authorization=`Bearer ${this.apiKey}`,o["X-API-Key"]=this.apiKey);const r={...t,headers:o};for(;i<this.maxRetries;)try{const t=await fetch(e,r);if(!t.ok){if(t.status>=400&&t.status<500&&429!==t.status)throw this.logger.error(`Client error for ${e} (status ${t.status}): ${t.statusText}. Not retrying.`),new Error(`Fetch failed with status ${t.status}: ${t.statusText} for URL: ${e}`);throw new Error(`Fetch failed with status ${t.status}: ${t.statusText} for URL: ${e}`)}return await t.json()}catch(a){if(i++,i>=this.maxRetries)throw this.logger.error(`Max retries (${this.maxRetries}) reached for ${e}. Last error: ${a.message}`),a;this.logger.warn(`Attempt ${i}/${this.maxRetries} failed for ${e}: ${a.message}. Retrying in ${n}ms...`),await new Promise(e=>setTimeout(e,n)),n=Math.min(n*this.backoffFactor,this.maxDelayMs)}throw new Error(`Failed to fetch data from ${e} after ${this.maxRetries} attempts.`)}async getAccountBalance(e){this.logger.info(`Getting balance for account ${e}`);try{const t=await this.requestAccount(e);if(t&&t.balance){return t.balance.balance/1e8}return this.logger.warn(`Could not retrieve balance for account ${e} from account info.`),null}catch(t){return this.logger.error(`Error fetching numerical balance for account ${e}: ${t.message}`),null}}async getTopicMessagesByFilter(e,t){this.logger.trace(`Querying messages for topic ${e} with filters: ${JSON.stringify(t)}`);let i=`/api/v1/topics/${e}/messages`;const n=new URLSearchParams;t?.limit&&n.append("limit",t.limit.toString()),t?.sequenceNumber&&n.append("sequencenumber",t.sequenceNumber),t?.startTime&&n.append("timestamp",`gte:${t.startTime}`),t?.endTime&&n.append("timestamp",`lt:${t.endTime}`),t?.order&&n.append("order",t.order);const o=n.toString();o&&(i+=`?${o}`);const r=[];let a=0;try{for(;i&&a<10;){a++;const e=await this._requestWithRetry(i);if(e.messages&&e.messages.length>0)for(const t of e.messages)try{if(!t.message)continue;let e;e=this.isServerEnvironment?globalThis.Buffer.from(t.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(t.message),e=>e.charCodeAt(0)));let i={};try{i=JSON.parse(e)}catch(s){this.logger.debug(`Message content is not valid JSON, using raw: ${e}`),i={raw_content:e}}const n={...i,consensus_timestamp:t.consensus_timestamp,sequence_number:t.sequence_number,payer_account_id:t.payer_account_id,topic_id:t.topic_id,running_hash:t.running_hash,running_hash_version:t.running_hash_version,chunk_info:t.chunk_info,created:new Date(1e3*Number(t.consensus_timestamp.split(".")[0])+Number(t.consensus_timestamp.split(".")[1]||0)/1e6),payer:t.payer_account_id};r.push(n)}catch(c){this.logger.error(`Error processing individual message: ${c.message}`)}if(t?.limit&&r.length>=t.limit)break;i=e.links?.next?`${e.links.next}`:""}return r}catch(p){const t=p;return this.logger.error(`Error querying filtered topic messages for ${e}: ${t.message}`),null}}async getAccountTokens(e,t=100){this.logger.info(`Getting tokens for account ${e}`);let i=[],n=`/api/v1/accounts/${e}/tokens?limit=${t}`;try{for(let e=0;e<10&&n;e++){const e=await this._requestWithRetry(n);if(e&&e.tokens&&(i=i.concat(e.tokens)),n=e.links?.next||"",!n||t&&i.length>=t){t&&i.length>t&&(i=i.slice(0,t));break}}return i}catch(o){return this.logger.error(`Error fetching tokens for account ${e}: ${o.message}`),null}}async getTransactionByTimestamp(e){this.logger.info(`Getting transaction by timestamp: ${e}`);try{return(await this._requestWithRetry(`/api/v1/transactions?timestamp=${e}&limit=1`)).transactions}catch(t){return this.logger.error(`Error fetching transaction by timestamp ${e}: ${t}`),[]}}async getAccountNfts(e,t,i=100){this.logger.info(`Getting NFTs for account ${e}${t?` for token ${t}`:""}`);let n=[],o=`/api/v1/accounts/${e}/nfts?limit=${i}`;t&&(o+=`&token.id=${t}`);try{for(let e=0;e<10&&o;e++){const e=await this._requestWithRetry(o);if(e&&e.nfts){const t=e.nfts.map(e=>{let t;if(e.metadata)try{t=this.isServerEnvironment?globalThis.Buffer.from(e.metadata,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(e.metadata),e=>e.charCodeAt(0)))}catch(i){this.logger.warn(`Failed to decode metadata for NFT ${e.token_id} SN ${e.serial_number}: ${i.message}`)}return{...e,token_uri:t}});n=n.concat(t)}if(o=e.links?.next||"",!o)break}return n}catch(r){return this.logger.error(`Error fetching NFTs for account ${e}: ${r.message}`),null}}async validateNFTOwnership(e,t,i){this.logger.info(`Validating ownership of NFT ${t} SN ${i} for account ${e}`);try{const n=await this.getAccountNfts(e,t);if(n){return n.find(e=>e.token_id===t&&e.serial_number===i)||null}return null}catch(n){return this.logger.error(`Error validating NFT ownership: ${n.message}`),null}}async readSmartContractQuery(e,t,i,n){this.logger.info(`Reading smart contract ${e} with selector ${t}`);const r=e.startsWith("0x")?e:`0x${o.AccountId.fromString(e).toSolidityAddress()}`,a=i.startsWith("0x")?i:`0x${o.AccountId.fromString(i).toSolidityAddress()}`,s={block:n?.block||"latest",data:t,estimate:n?.estimate||!1,from:a,to:r,gas:n?.gas,gasPrice:n?.gasPrice,value:n?.value||0};Object.keys(s).forEach(e=>{const t=e;void 0===s[t]&&delete s[t]});try{const e=this.constructUrl("/api/v1/contracts/call");return await this._fetchWithRetry(e,{method:"POST",body:JSON.stringify(s),headers:{"Content-Type":"application/json"}})}catch(c){return this.logger.error(`Error reading smart contract ${e}: ${c.message}`),null}}async getOutstandingTokenAirdrops(e,t){this.logger.info(`Getting outstanding token airdrops sent by account ${e}`);let i=`/api/v1/accounts/${e}/airdrops/outstanding`;const n=new URLSearchParams;t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order),t?.receiverId&&n.append("receiver.id",t.receiverId),t?.serialNumber&&n.append("serialnumber",t.serialNumber),t?.tokenId&&n.append("token.id",t.tokenId);const o=n.toString();o&&(i+=`?${o}`);try{return(await this._requestWithRetry(i)).airdrops||[]}catch(r){return this.logger.error(`Error fetching outstanding token airdrops for account ${e}: ${r.message}`),null}}async getPendingTokenAirdrops(e,t){this.logger.info(`Getting pending token airdrops received by account ${e}`);let i=`/api/v1/accounts/${e}/airdrops/pending`;const n=new URLSearchParams;t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order),t?.senderId&&n.append("sender.id",t.senderId),t?.serialNumber&&n.append("serialnumber",t.serialNumber),t?.tokenId&&n.append("token.id",t.tokenId);const o=n.toString();o&&(i+=`?${o}`);try{return(await this._requestWithRetry(i)).airdrops||[]}catch(r){return this.logger.error(`Error fetching pending token airdrops for account ${e}: ${r.message}`),null}}async getBlocks(e){this.logger.info("Getting blocks from the network");let t="/api/v1/blocks";const i=new URLSearchParams;e?.limit&&i.append("limit",e.limit.toString()),e?.order&&i.append("order",e.order),e?.timestamp&&i.append("timestamp",e.timestamp),e?.blockNumber&&i.append("block.number",e.blockNumber);const n=i.toString();n&&(t+=`?${n}`);try{return(await this._requestWithRetry(t)).blocks||[]}catch(o){return this.logger.error(`Error fetching blocks: ${o.message}`),null}}async getBlock(e){this.logger.info(`Getting block ${e}`);try{return await this._requestWithRetry(`/api/v1/blocks/${e}`)}catch(t){return this.logger.error(`Error fetching block ${e}: ${t.message}`),null}}async getContracts(e){this.logger.info("Getting contracts from the network");let t="/api/v1/contracts";const i=new URLSearchParams;e?.contractId&&i.append("contract.id",e.contractId),e?.limit&&i.append("limit",e.limit.toString()),e?.order&&i.append("order",e.order);const n=i.toString();n&&(t+=`?${n}`);try{return(await this._requestWithRetry(t)).contracts||[]}catch(o){return this.logger.error(`Error fetching contracts: ${o.message}`),null}}async getContract(e,t){this.logger.info(`Getting contract ${e}`);let i=`/api/v1/contracts/${e}`;t&&(i+=`?timestamp=${t}`);try{return await this._requestWithRetry(i)}catch(n){return this.logger.error(`Error fetching contract ${e}: ${n.message}`),null}}async getContractResults(e){this.logger.info("Getting contract results from the network");let t="/api/v1/contracts/results";const i=new URLSearchParams;e?.from&&i.append("from",e.from),e?.blockHash&&i.append("block.hash",e.blockHash),e?.blockNumber&&i.append("block.number",e.blockNumber),void 0!==e?.internal&&i.append("internal",e.internal.toString()),e?.limit&&i.append("limit",e.limit.toString()),e?.order&&i.append("order",e.order),e?.timestamp&&i.append("timestamp",e.timestamp),e?.transactionIndex&&i.append("transaction.index",e.transactionIndex.toString());const n=i.toString();n&&(t+=`?${n}`);try{return(await this._requestWithRetry(t)).results||[]}catch(o){return this.logger.error(`Error fetching contract results: ${o.message}`),null}}async getContractResult(e,t){this.logger.info(`Getting contract result for ${e}`);let i=`/api/v1/contracts/results/${e}`;void 0!==t&&(i+=`?nonce=${t}`);try{return await this._requestWithRetry(i)}catch(n){return this.logger.error(`Error fetching contract result for ${e}: ${n.message}`),null}}async getContractResultsByContract(e,t){this.logger.info(`Getting contract results for contract ${e}`);let i=`/api/v1/contracts/${e}/results`;const n=new URLSearchParams;t?.blockHash&&n.append("block.hash",t.blockHash),t?.blockNumber&&n.append("block.number",t.blockNumber),t?.from&&n.append("from",t.from),void 0!==t?.internal&&n.append("internal",t.internal.toString()),t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order),t?.timestamp&&n.append("timestamp",t.timestamp),t?.transactionIndex&&n.append("transaction.index",t.transactionIndex.toString());const o=n.toString();o&&(i+=`?${o}`);try{return(await this._requestWithRetry(i)).results||[]}catch(r){return this.logger.error(`Error fetching contract results for ${e}: ${r.message}`),null}}async getContractState(e,t){this.logger.info(`Getting contract state for ${e}`);let i=`/api/v1/contracts/${e}/state`;const n=new URLSearchParams;t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order),t?.slot&&n.append("slot",t.slot),t?.timestamp&&n.append("timestamp",t.timestamp);const o=n.toString();o&&(i+=`?${o}`);try{return(await this._requestWithRetry(i)).state||[]}catch(r){return this.logger.error(`Error fetching contract state for ${e}: ${r.message}`),null}}async getContractActions(e,t){this.logger.info(`Getting contract actions for ${e}`);let i=`/api/v1/contracts/results/${e}/actions`;const n=new URLSearchParams;t?.index&&n.append("index",t.index),t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order);const o=n.toString();o&&(i+=`?${o}`);try{return(await this._requestWithRetry(i)).actions||[]}catch(r){return this.logger.error(`Error fetching contract actions for ${e}: ${r.message}`),null}}async getContractLogs(e){this.logger.info("Getting contract logs from the network");let t="/api/v1/contracts/results/logs";const i=new URLSearchParams;e?.index&&i.append("index",e.index),e?.limit&&i.append("limit",e.limit.toString()),e?.order&&i.append("order",e.order),e?.timestamp&&i.append("timestamp",e.timestamp),e?.topic0&&i.append("topic0",e.topic0),e?.topic1&&i.append("topic1",e.topic1),e?.topic2&&i.append("topic2",e.topic2),e?.topic3&&i.append("topic3",e.topic3),e?.transactionHash&&i.append("transaction.hash",e.transactionHash);const n=i.toString();n&&(t+=`?${n}`);try{return(await this._requestWithRetry(t)).logs||[]}catch(o){return this.logger.error(`Error fetching contract logs: ${o.message}`),null}}async getContractLogsByContract(e,t){this.logger.info(`Getting contract logs for contract ${e}`);let i=`/api/v1/contracts/${e}/results/logs`;const n=new URLSearchParams;t?.index&&n.append("index",t.index),t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order),t?.timestamp&&n.append("timestamp",t.timestamp),t?.topic0&&n.append("topic0",t.topic0),t?.topic1&&n.append("topic1",t.topic1),t?.topic2&&n.append("topic2",t.topic2),t?.topic3&&n.append("topic3",t.topic3);const o=n.toString();o&&(i+=`?${o}`);try{return(await this._requestWithRetry(i)).logs||[]}catch(r){return this.logger.error(`Error fetching contract logs for ${e}: ${r.message}`),null}}async getNftInfo(e,t){this.logger.info(`Getting NFT info for ${e}/${t}`);const i=`/api/v1/tokens/${e}/nfts/${t}`;try{return await this._requestWithRetry(i)}catch(n){return this.logger.error(`Error fetching NFT info for ${e}/${t}: ${n.message}`),null}}async getNftsByToken(e,t){this.logger.info(`Getting NFTs for token ${e}`);let i=`/api/v1/tokens/${e}/nfts`;const n=new URLSearchParams;t?.accountId&&n.append("account.id",t.accountId),t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order),t?.serialNumber&&n.append("serialnumber",t.serialNumber);const o=n.toString();o&&(i+=`?${o}`);try{return(await this._requestWithRetry(i)).nfts||[]}catch(r){return this.logger.error(`Error fetching NFTs for token ${e}: ${r.message}`),null}}async getNetworkInfo(){this.logger.info("Getting network information");try{return await this._requestWithRetry("/api/v1/network/nodes")}catch(e){return this.logger.error(`Error fetching network info: ${e.message}`),null}}async getNetworkFees(e){this.logger.info("Getting network fees");let t="/api/v1/network/fees";e&&(t+=`?timestamp=${e}`);try{return await this._requestWithRetry(t)}catch(i){return this.logger.error(`Error fetching network fees: ${i.message}`),null}}async getNetworkSupply(e){this.logger.info("Getting network supply");let t="/api/v1/network/supply";e&&(t+=`?timestamp=${e}`);try{return await this._requestWithRetry(t)}catch(i){return this.logger.error(`Error fetching network supply: ${i.message}`),null}}async getNetworkStake(e){this.logger.info("Getting network stake");let t="/api/v1/network/stake";e&&(t+=`?timestamp=${e}`);try{return await this._requestWithRetry(t)}catch(i){return this.logger.error(`Error fetching network stake: ${i.message}`),null}}async getOpcodeTraces(e,t){this.logger.info(`Getting opcode traces for ${e}`);let i=`/api/v1/contracts/results/${e}/opcodes`;const n=new URLSearchParams;void 0!==t?.stack&&n.append("stack",t.stack.toString()),void 0!==t?.memory&&n.append("memory",t.memory.toString()),void 0!==t?.storage&&n.append("storage",t.storage.toString());const o=n.toString();o&&(i+=`?${o}`);try{return await this._requestWithRetry(i)}catch(r){return this.logger.error(`Error fetching opcode traces for ${e}: ${r.message}`),null}}};class R{constructor(e){this.network=e.network,this.logger=e.logger||g.getInstance({level:e.logLevel||"info",module:"HCS6Client",silent:e.silent}),this.mirrorNode=new I(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0)}parseRegistryTypeFromMemo(e){try{const t=/hcs-6:(\d):(\d+)/,i=e.match(t);if(i&&3===i.length){const e=parseInt(i[1]),t=parseInt(i[2]);if(e===x.NON_INDEXED&&T(t))return{registryType:e,ttl:t}}return}catch(t){return void this.logger.error(`Error parsing HCS-6 registry type from memo: ${t}`)}}generateRegistryMemo(e){return A(e)}validateMessage(e){try{return S.parse(e),{valid:!0,errors:[]}}catch(t){const e=[];return t instanceof n.ZodError?t.errors.forEach(t=>{const i=t.path.join(".");e.push(`${i?i+": ":""}${t.message}`)}):e.push(`Unexpected error: ${t}`),this.logger.debug(`HCS-6 message validation failed: ${e.join(", ")}`),{valid:!1,errors:e}}}createRegisterMessage(e,t){return{p:"hcs-6",op:b.REGISTER,t_id:e,m:t}}parseRegistryEntries(e,t,i,n){const o=[];let r;this.logger.debug(`Parsing ${t.length} messages for HCS-6 topic ${e}`);for(const s of t)try{if(!s.message){this.logger.debug(`Message is missing 'message' property: ${JSON.stringify(s)}`);continue}const t=globalThis.Buffer.from(s.message,"base64").toString("utf-8"),n=JSON.parse(t);this.logger.debug(`Successfully parsed HCS-6 message: ${JSON.stringify(n)}`);const{valid:a,errors:c}=this.validateMessage(n);if(!a){this.logger.warn(`Invalid HCS-6 message: ${c.join(", ")}`);continue}const p={topicId:e,sequence:s.sequence_number,timestamp:s.consensus_timestamp,payer:s.payer_account_id,message:n,consensus_timestamp:s.consensus_timestamp,registry_type:i};o.push(p),(!r||p.timestamp>r.timestamp)&&(r=p)}catch(a){this.logger.warn(`Error parsing HCS-6 message: ${a}`)}return this.logger.debug(`Parsed ${o.length} valid entries for HCS-6 topic ${e}`),{topicId:e,registryType:i,ttl:n,entries:r?[r]:[],latestEntry:r}}async validateHCS6Topic(e){try{const t=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(t.memo);return i?i.registryType===x.NON_INDEXED||(this.logger.warn(`Topic ${e} is not a valid HCS-6 registry (must be non-indexed)`),!1):(this.logger.warn(`Topic ${e} is not a valid HCS-6 registry (invalid memo format)`),!1)}catch(t){return this.logger.error(`Error validating HCS-6 topic ${e}: ${t}`),!1}}}function O(e){const{memo:t,adminKey:i,submitKey:n,operatorPublicKey:r}=e,a=(new o.TopicCreateTransaction).setTopicMemo(t),s=e=>{if(e){if(e instanceof o.PublicKey||e instanceof o.KeyList)return e;if("boolean"==typeof e)return e?r:void 0;if("string"==typeof e)try{return o.PublicKey.fromString(e)}catch{return}}},c=s(i);c&&a.setAdminKey(c);const p=s(n);return p&&a.setSubmitKey(p),a}function C(e){const t=(new o.TopicMessageSubmitTransaction).setTopicId(o.TopicId.fromString(e.topicId)).setMessage(e.message);return e.transactionMemo&&t.setTransactionMemo(e.transactionMemo),t}function j(e){return O({memo:e.memoOverride??`hcs-6:1:${e.ttl}`,submitKey:e.submitKey,adminKey:e.adminKey,operatorPublicKey:e.operatorPublicKey})}var N=(e=>(e.ED25519="ed25519",e.ECDSA="ecdsa",e.UNKNOWN="unknown",e))(N||{});let B=(t=class{static detect(e){try{let t,i="raw";if("string"==typeof e){let n=e.trim();if(n.includes("-----BEGIN"))return this.detectFromPem(n);if(n.toLowerCase().startsWith("0x")&&(n=n.substring(2)),this.isValidHex(n))t=this.hexToBytes(n),i="hex";else{if(!this.isBase64(n))return{type:"unknown",format:"raw",isPrivateKey:!1,confidence:"certain"};t=globalThis.Buffer.from(n,"base64"),i="der"}}else t=e instanceof globalThis.Buffer?new Uint8Array(e):e;return this.detectFromBytes(t,i)}catch(t){return{type:"unknown",format:"raw",isPrivateKey:!1,confidence:"certain"}}}static detectFromBytes(e,t){if(this.hasPrefix(e,this.ED25519_PUBLIC_KEY_PREFIX)){const t=this.ED25519_PUBLIC_KEY_PREFIX.length;return{type:"ed25519",format:"der",isPrivateKey:!1,rawBytes:e.slice(t),confidence:"certain"}}if(this.hasPrefix(e,this.ED25519_PRIVATE_KEY_PREFIX)){const t=this.ED25519_PRIVATE_KEY_PREFIX.length;if(e.length>=t+32)return{type:"ed25519",format:"der",isPrivateKey:!0,rawBytes:e.slice(t,t+32),confidence:"certain"}}if(this.hasPrefix(e,this.ECDSA_SECP256K1_PUBLIC_KEY_PREFIX)){const t=this.ECDSA_SECP256K1_PUBLIC_KEY_PREFIX.length;return{type:"ecdsa",format:"der",isPrivateKey:!1,rawBytes:e.slice(t),confidence:"certain"}}if(this.hasPrefix(e,this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_SHORT)){const t=this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_SHORT.length;return{type:"ecdsa",format:"der",isPrivateKey:!0,rawBytes:e.slice(t),confidence:"certain"}}if(this.hasPrefix(e,this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX)){const t=this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX.length;return{type:"ecdsa",format:"der",isPrivateKey:!0,rawBytes:e.slice(t,t+32),confidence:"certain"}}if(this.hasPrefix(e,this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_LONG)){const t=this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_LONG.length;return{type:"ecdsa",format:"der",isPrivateKey:!0,rawBytes:e.slice(t,t+32),confidence:"certain"}}if(e.length>36&&this.containsECDSAPrivateKeyPattern(e))return{type:"ecdsa",format:"der",isPrivateKey:!0,rawBytes:this.extractECDSAPrivateKey(e),confidence:"certain"};switch(e.length){case this.ED25519_PUBLIC_KEY_LENGTH:if("hex"===t){const t=Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join(""),i=this.tryCreateKey(t);if("unknown"!==i.type)return i}return{type:"unknown",format:t,isPrivateKey:!1,rawBytes:e,confidence:"certain"};case this.ED25519_EXPANDED_PRIVATE_KEY_LENGTH:return{type:"ed25519",format:t,isPrivateKey:!0,rawBytes:e,confidence:"certain"}}return{type:"unknown",format:t,isPrivateKey:!1,rawBytes:e,confidence:"certain"}}static detectFromPem(e){const t=e.trim(),i=t.includes("PRIVATE KEY"),n={EC_PRIVATE:/-----BEGIN EC PRIVATE KEY-----/,EC_PUBLIC:/-----BEGIN EC PUBLIC KEY-----/,PRIVATE:/-----BEGIN PRIVATE KEY-----/,PUBLIC:/-----BEGIN PUBLIC KEY-----/};let o=!1;for(const[s,c]of Object.entries(n))if(c.test(t)&&s.includes("EC")){o=!0;break}const r=t.match(/-----BEGIN[\s\S]+?-----[\r\n]+([\s\S]+?)[\r\n]+-----END/);if(!r)return{type:"unknown",format:"pem",isPrivateKey:i,confidence:"certain"};const a=r[1].replace(/\s/g,"");try{const e=globalThis.Buffer.from(a,"base64"),t=this.detectFromBytes(new Uint8Array(e),"der");return"unknown"===t.type&&o?{type:"ecdsa",format:"pem",isPrivateKey:i,rawBytes:e,confidence:"certain"}:{...t,format:"pem"}}catch{return{type:"unknown",format:"pem",isPrivateKey:i,confidence:"certain"}}}static tryCreateKey(e){try{if("string"==typeof e){let t=e.trim();if(t.toLowerCase().startsWith("0x")&&(t=t.substring(2)),this.isValidHex(t)&&64===t.length){const e=this.hexToBytes(t),i=this.detectBySignature(t);return"unknown"!==i.type?{type:i.type,format:"hex",isPrivateKey:!0,rawBytes:e,confidence:i.confidence,warning:i.warning}:{type:"unknown",format:"hex",isPrivateKey:!1,rawBytes:e,confidence:"certain"}}}}catch{}return{type:"unknown",format:"hex",isPrivateKey:!1,rawBytes:new Uint8Array,confidence:"certain"}}static detectBySignature(e){const t=BigInt("0x"+e),i=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141");if(0n===t)return{type:"ed25519",confidence:"certain"};if(t>=i)return{type:"ed25519",confidence:"certain"};let n=!1,r=!1;try{const t=o.PrivateKey.fromStringED25519(e),i=new Uint8Array([1,2,3,4,5]),r=t.sign(i);t.publicKey.verify(i,r)&&(n=!0)}catch{}try{const t=o.PrivateKey.fromStringECDSA(e),i=new Uint8Array([1,2,3,4,5]),n=t.sign(i);t.publicKey.verify(i,n)&&(r=!0)}catch{}if(n&&r){const t=this.hexToBytes(e);if(168===t[0]&&1===t[1])return{type:"ed25519",confidence:"uncertain",warning:"Detection based on byte pattern heuristic. Both ED25519 and ECDSA accept this key."};let i=0;for(const e of t)e>=128&&i++;const n=i/t.length;return n>=.4&&n<=.6?{type:"ecdsa",confidence:"uncertain",warning:"Detection based on entropy heuristic. Both ED25519 and ECDSA accept this key."}:{type:"ecdsa",confidence:"uncertain",warning:"Detection based on entropy heuristic. Both ED25519 and ECDSA accept this key. Defaulting to ECDSA."}}return n&&!r?{type:"ed25519",confidence:"certain"}:r&&!n?{type:"ecdsa",confidence:"certain"}:{type:"unknown",confidence:"certain"}}static isValidHex(e){return/^[0-9a-fA-F]+$/.test(e)&&e.length%2==0}static isBase64(e){try{return globalThis.Buffer.from(e,"base64").toString("base64")===e}catch{return!1}}static hexToBytes(e){const t=new Uint8Array(e.length/2);for(let i=0;i<e.length;i+=2)t[i/2]=parseInt(e.substr(i,2),16);return t}static hasPrefix(e,t){if(e.length<t.length)return!1;for(let i=0;i<t.length;i++)if(e[i]!==t[i])return!1;return!0}static containsECDSAPrivateKeyPattern(e){for(let t=0;t<e.length-7;t++)if(48===e[t]&&116===e[t+1]&&2===e[t+2]&&1===e[t+3]&&1===e[t+4]&&4===e[t+5]&&32===e[t+6])return!0;return!1}static extractECDSAPrivateKey(e){for(let t=0;t<e.length-32;t++)if(4===e[t]&&32===e[t+1])return e.slice(t+2,t+34);return e}},t.ED25519_PUBLIC_KEY_LENGTH=32,t.ED25519_EXPANDED_PRIVATE_KEY_LENGTH=64,t.ED25519_PUBLIC_KEY_PREFIX=globalThis.Buffer.from([48,42,48,5,6,3,43,101,112,3,33,0]),t.ED25519_PRIVATE_KEY_PREFIX=globalThis.Buffer.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),t.ECDSA_SECP256K1_PUBLIC_KEY_PREFIX=globalThis.Buffer.from([48,86,48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,10,3,66,0]),t.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX=globalThis.Buffer.from([48,116,2,1,1,4,32]),t.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_SHORT=globalThis.Buffer.from([48,48,2,1,0,48,7,6,5,43,129,4,0,10,4,34,4,32]),t.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_LONG=globalThis.Buffer.from([48,119,2,1,1,4,32]),t);function P(e){const t=B.detect(e);if("unknown"!==t.type)try{const i="ecdsa"===t.type?o.PrivateKey.fromStringECDSA(e):o.PrivateKey.fromStringED25519(e),n={detectedType:t.type,privateKey:i};return"uncertain"===t.confidence&&(n.warning="Key type detection is uncertain. If you have the associated account ID, consider using the Hedera mirror node to confirm the key type."),n}catch(i){}try{return{detectedType:"ecdsa",privateKey:o.PrivateKey.fromStringECDSA(e),warning:"Using ECDSA as default. If you have the associated account ID, consider using the Hedera mirror node to confirm the key type."}}catch(n){try{return{detectedType:"ed25519",privateKey:o.PrivateKey.fromStringED25519(e),warning:"Using ED25519 as fallback. If you have the associated account ID, consider using the Hedera mirror node to confirm the key type."}}catch(r){throw new Error(`Failed to parse private key as either ECDSA or ED25519: ${n}`)}}}class L{constructor(e){this.mirror=e.mirrorNode,this.logger=e.logger}bestGuessOperatorKey(e,t){if("string"!=typeof e)return{keyType:t||"ecdsa",privateKey:e};if(t){return{keyType:t,privateKey:"ed25519"===t?o.PrivateKey.fromStringED25519(e):o.PrivateKey.fromStringECDSA(e)}}try{const t=P(e);return{keyType:t.detectedType,privateKey:t.privateKey}}catch{return{keyType:"ecdsa",privateKey:o.PrivateKey.fromStringECDSA(e)}}}async resolveOperatorKey(e,t,i){if("string"!=typeof t)return{keyType:i||"ecdsa",privateKey:t};if(i){return{keyType:i,privateKey:"ed25519"===i?o.PrivateKey.fromStringED25519(t):o.PrivateKey.fromStringECDSA(t)}}const n="string"==typeof e?e:e.toString();try{const e=await this.mirror.requestAccount(n),i=(e?.key?._type||"").includes("ED25519")?"ed25519":"ecdsa";return{keyType:i,privateKey:"ed25519"===i?o.PrivateKey.fromStringED25519(t):o.PrivateKey.fromStringECDSA(t)}}catch{return this.logger.warn("Mirror node key detection failed; using local detection or default ECDSA"),this.bestGuessOperatorKey(t)}}async resolveSupplyKey(e,t,i,n){try{const r=await this.mirror.getTokenInfo(e),a=r?.supply_key?._type||"";return"string"!=typeof t?t:n?"ed25519"===n?o.PrivateKey.fromStringED25519(t):o.PrivateKey.fromStringECDSA(t):a.includes("ED25519")?o.PrivateKey.fromStringED25519(t):a.includes("ECDSA")?o.PrivateKey.fromStringECDSA(t):"ed25519"===i?o.PrivateKey.fromStringED25519(t):o.PrivateKey.fromStringECDSA(t)}catch{return"string"!=typeof t?t:n?"ed25519"===n?o.PrivateKey.fromStringED25519(t):o.PrivateKey.fromStringECDSA(t):"ed25519"===i?o.PrivateKey.fromStringED25519(t):o.PrivateKey.fromStringECDSA(t)}}}function U(e){const t="string"==typeof e.operatorId?o.AccountId.fromString(e.operatorId):e.operatorId,i=e.client?e.client:"mainnet"===e.network?o.Client.forMainnet():o.Client.forTestnet(),n=new L({mirrorNode:e.mirrorNode,logger:e.logger});let r,a;const s=n.bestGuessOperatorKey(e.operatorKey,e.keyType);r=s.keyType,a=s.privateKey,i.setOperator(t,a);const c=(async()=>{try{const o=await n.resolveOperatorKey(t,e.operatorKey,e.keyType);r=o.keyType,a=o.privateKey,i.setOperator(t,a)}catch{}})();return{client:i,operatorId:t,get operatorKey(){return a},get keyType(){return r},ensureInitialized:async()=>{await c}}}for(var M,F=Object.defineProperty,D=((e,t,i)=>((e,t,i)=>t in e?F(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i)),z={},$={byteLength:function(e){var t=G(e),i=t[0],n=t[1];return 3*(i+n)/4-n},toByteArray:function(e){var t,i,n=G(e),o=n[0],r=n[1],a=new W(function(e,t,i){return 3*(t+i)/4-i}(0,o,r)),s=0,c=r>0?o-4:o;for(i=0;i<c;i+=4)t=K[e.charCodeAt(i)]<<18|K[e.charCodeAt(i+1)]<<12|K[e.charCodeAt(i+2)]<<6|K[e.charCodeAt(i+3)],a[s++]=t>>16&255,a[s++]=t>>8&255,a[s++]=255&t;2===r&&(t=K[e.charCodeAt(i)]<<2|K[e.charCodeAt(i+1)]>>4,a[s++]=255&t);1===r&&(t=K[e.charCodeAt(i)]<<10|K[e.charCodeAt(i+1)]<<4|K[e.charCodeAt(i+2)]>>2,a[s++]=t>>8&255,a[s++]=255&t);return a},fromByteArray:function(e){for(var t,i=e.length,n=i%3,o=[],r=16383,a=0,s=i-n;a<s;a+=r)o.push(J(e,a,a+r>s?s:a+r));1===n?(t=e[i-1],o.push(q[t>>2]+q[t<<4&63]+"==")):2===n&&(t=(e[i-2]<<8)+e[i-1],o.push(q[t>>10]+q[t>>4&63]+q[t<<2&63]+"="));return o.join("")}},q=[],K=[],W="undefined"!=typeof Uint8Array?Uint8Array:Array,H="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",V=0;V<64;++V)q[V]=H[V],K[H.charCodeAt(V)]=V;function G(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var i=e.indexOf("=");return-1===i&&(i=t),[i,i===t?0:4-i%4]}function Z(e){return q[e>>18&63]+q[e>>12&63]+q[e>>6&63]+q[63&e]}function J(e,t,i){for(var n,o=[],r=t;r<i;r+=3)n=(e[r]<<16&16711680)+(e[r+1]<<8&65280)+(255&e[r+2]),o.push(Z(n));return o.join("")}K["-".charCodeAt(0)]=62,K["_".charCodeAt(0)]=63;var Y={
|
|
1
|
+
"use strict";var e,t;Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("util"),n=require("zod"),o=require("@hashgraph/sdk"),r=require("axios"),a=require("@hashgraph/proto"),s=require("buffer"),c=require("ethers"),p=require("file-type"),l=require("mime-types"),u=require("date-fns"),d=require("crypto");function f(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const i in e)if("default"!==i){const n=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,n.get?n:{enumerable:!0,get:()=>e[i]})}return t.default=e,Object.freeze(t)}const m=f(l);let h=null;let g=((e=class{constructor(e={}){if(h)return h(e);const t="undefined"!=typeof process&&"true"===process.env?.DISABLE_LOGS;this.silent=e.silent||t,this.level=this.silent?"silent":e.level||"info",this.moduleContext=e.module||"app",this.prettyPrint=!this.silent&&!1!==e.prettyPrint}static getInstance(t={}){const i=t.module||"default";if("undefined"!=typeof process&&"true"===process.env?.DISABLE_LOGS&&e.instances.has(i)){"silent"!==e.instances.get(i).getLevel()&&e.instances.delete(i)}if(!e.instances.has(i)){const n=h?h(t):new e(t);e.instances.set(i,n)}return e.instances.get(i)}setLogLevel(e){this.level=e}getLevel(){return this.level}setSilent(e){this.silent=e,e&&(this.level="silent")}setModule(e){this.moduleContext=e}formatArgs(e){if(0===e.length)return{msg:""};if(1===e.length)return"string"==typeof e[0]?{msg:e[0]}:{msg:"",data:e[0]};const t=[],i=[];e.forEach(e=>{"string"==typeof e||"number"==typeof e||"boolean"==typeof e?t.push(String(e)):i.push(e)});const n=t.join(" ");return i.length>0?{msg:n,data:i}:{msg:n}}shouldLog(e){if(this.silent||"silent"===this.level)return!1;const t=["trace","debug","info","warn","error","silent"],i=t.indexOf(this.level);return t.indexOf(e)>=i}getConsoleMethod(e){return"error"===e?console.error:"warn"===e?console.warn:"debug"===e?console.debug:console.log}writeLog(e,...t){if(!this.shouldLog(e))return;const{msg:n,data:o}=this.formatArgs(t),r=(new Date).toISOString(),a=this.getConsoleMethod(e);if(this.prettyPrint){let t=`${r} ${e.toUpperCase().padEnd(5)} [${this.moduleContext}] ${n}`;o&&(t+="\n"+i.inspect(o,{colors:!0,depth:3})),a(t)}else{const t={timestamp:r,level:e,module:this.moduleContext,message:n,...o&&{data:o}};a(JSON.stringify(t))}}debug(...e){this.writeLog("debug",...e)}info(...e){this.writeLog("info",...e)}warn(...e){this.writeLog("warn",...e)}error(...e){this.writeLog("error",...e)}trace(...e){this.writeLog("trace",...e)}static clearInstances(){e.instances.clear()}}).instances=new Map,e);const y=e=>new Promise(t=>setTimeout(t,e));class v{constructor(){this.modelViewerLoaded=!1,this.modelViewerLoading=null,this.config={cdnUrl:"https://kiloscribe.com/api/inscription-cdn/",network:"mainnet",retryAttempts:3,retryBackoff:300,debug:!1,showLoadingIndicator:!1,loadingCallbackName:null},this.configMapping={hcsCdnUrl:"cdnUrl",hcsNetwork:"network",hcsRetryAttempts:"retryAttempts",hcsRetryBackoff:"retryBackoff",hcsDebug:"debug",hcsShowLoadingIndicator:"showLoadingIndicator",hcsLoadingCallbackName:"loadingCallbackName"},this.LoadedScripts={},this.LoadedWasm={},this.LoadedImages={},this.LoadedVideos={},this.LoadedAudios={},this.LoadedAudioUrls={},this.LoadedGLBs={},this.scriptLoadedEvent=new Event("HCSScriptLoaded"),this.loadQueue=[],this.isProcessingQueue=!1;try{this.logger=g.getInstance({module:"HCS-3",level:this.config.debug?"debug":"error"})}catch(e){this.logger=this.createFallbackLogger()}}createFallbackLogger(){return{debug:(...e)=>this.config.debug&&console.debug("[HCS-3]",...e),info:(...e)=>this.config.debug&&console.info("[HCS-3]",...e),warn:(...e)=>console.warn("[HCS-3]",...e),error:(...e)=>console.error("[HCS-3]",...e),setLogLevel:e=>{this.config.debug="debug"===e}}}log(...e){if(0===e.length)this.logger.debug("");else if(1===e.length)this.logger.debug(String(e[0]));else{const t=String(e[0]),i=e.slice(1);this.logger.debug(t,i)}}error(...e){if(0===e.length)this.logger.error("");else if(1===e.length)this.logger.error(String(e[0]));else{const t=String(e[0]),i=e.slice(1);this.logger.error(t,i)}}loadConfigFromHTML(){const e=document.querySelector("script[data-hcs-config]");e&&(Object.keys(this.configMapping).forEach(t=>{if(e.dataset[t]){const i=this.configMapping[t];let n=e.dataset[t];"true"===n&&(n=!0),"false"===n&&(n=!1),isNaN(Number(n))||""===n||(n=Number(n)),this.config[i]=n}}),this.logger.setLogLevel(this.config.debug?"debug":"error")),this.log("Loaded config:",this.config)}updateLoadingStatus(e,t){if("loaded"!==this.LoadedScripts[e]&&(this.config.showLoadingIndicator&&console.log("[HCS Loading] "+e+" : "+t),this.LoadedScripts[e]=t,this.config.loadingCallbackName&&"function"==typeof window[this.config.loadingCallbackName])){const i=window[this.config.loadingCallbackName];"function"==typeof i&&i(e,t)}}async fetchWithRetry(e,t=this.config.retryAttempts,i=this.config.retryBackoff){try{const t=await fetch(e);if(!t.ok)throw new Error("HTTP error! status: "+t.status);return t}catch(n){if(t>0)return this.log("Retrying fetch for "+e+" Attempts left: "+(t-1)),await this.sleep(i),this.fetchWithRetry(e,t-1,2*i);throw n}}sleep(e){return y(e)}isDuplicate(e){return!!this.LoadedScripts[e]}async retrieveHCS1Data(e,t=this.config.cdnUrl,i=this.config.network){const n=i.replace(/['"]+/g,""),o=await this.fetchWithRetry(t+e+"?network="+n);return await o.blob()}async loadScript(e){const t=e.getAttribute("data-src"),i=e.getAttribute("data-script-id"),n=t?.split("/").pop(),o=e.getAttribute("type"),r=e.hasAttribute("data-required"),a="module"===e.getAttribute("type");if(!this.isDuplicate(n||"")){this.updateLoadingStatus(i,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,s=e.getAttribute("data-network")||this.config.network,c=await this.retrieveHCS1Data(n,t,s);if("wasm"===o){const t=await c.arrayBuffer(),n=await WebAssembly.compile(t);this.LoadedWasm[i]=await WebAssembly.instantiate(n,{env:{},...e.dataset}),this.updateLoadingStatus(i,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded wasm: "+i)}else{const e=await c.text(),t=document.createElement("script");if(t.textContent=e,t.className="hcs-inline-script",i&&t.setAttribute("data-loaded-script-id",i),a){t.type="module";const i=new Blob([e],{type:"application/javascript"});t.src=URL.createObjectURL(i)}document.body.appendChild(t),this.updateLoadingStatus(i,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded script: "+i),t.onerror=e=>{if(this.error("Failed to load "+o+": "+i,e),this.updateLoadingStatus(i,"failed"),r)throw e}}}catch(s){if(this.error("Failed to load "+o+": "+i,s),this.updateLoadingStatus(i,"failed"),r)throw s}}}async loadModuleExports(e){const t=document.querySelector('script[data-loaded-script-id="'+e+'"]');if(!t)throw new Error("Module script with id "+e+" not found");const i=t.getAttribute("src");if(!i)throw new Error("Module script "+e+" has no src attribute");try{const e=new Function("url","return import(url)");return await e(i)}catch(n){throw this.error("Failed to import module",n),n}}async loadStylesheet(e){const t=e.getAttribute("data-src"),i=e.getAttribute("data-script-id"),n=t?.split("/").pop(),o=e.hasAttribute("data-required");if(!this.isDuplicate(n||"")){this.updateLoadingStatus(i,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,o=e.getAttribute("data-network")||this.config.network,r=await this.retrieveHCS1Data(n,t,o),a=await r.text(),s=document.createElement("style");s.textContent=a,document.head.appendChild(s),this.updateLoadingStatus(i,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded and inlined stylesheet: "+i)}catch(r){if(this.error("Failed to load stylesheet: "+i,r),this.updateLoadingStatus(i,"failed"),o)throw r}}}async loadImage(e){const t=e.getAttribute("data-src"),i=t?.split("/").pop();this.log("Loading image: "+i),this.updateLoadingStatus("Image: "+i,"loaded");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,n=e.getAttribute("data-network")||this.config.network,o=await this.retrieveHCS1Data(i,t,n),r=URL.createObjectURL(o);e.src=r,this.LoadedImages[i]=r,this.updateLoadingStatus("Image: "+i,"loaded"),this.log("Loaded image: "+i)}catch(n){this.error("Failed to load image: "+i,n),this.updateLoadingStatus("Image: "+i,"failed")}}async loadMedia(e,t){const i=e.getAttribute("data-src"),n=i?.split("/").pop();this.log("Loading "+t+": "+n),this.updateLoadingStatus(t+": "+n,"loading");try{const i=e.getAttribute("data-cdn-url")||this.config.cdnUrl,o=e.getAttribute("data-network")||this.config.network,r=await this.retrieveHCS1Data(n,i,o),a=URL.createObjectURL(r);e.src=a,"video"===t?this.LoadedVideos[n]=a:this.LoadedAudioUrls[n]=a,this.updateLoadingStatus(t+": "+n,"loaded"),this.log("Loaded "+t+": "+n)}catch(o){this.error("Failed to load "+t+": "+n,o),this.updateLoadingStatus(t+": "+n,"failed")}}async loadModelViewer(){return this.modelViewerLoading?this.modelViewerLoading:this.modelViewerLoaded?Promise.resolve():(this.modelViewerLoading=new Promise(e=>{const t=document.createElement("script");t.setAttribute("data-src","hcs://1/0.0.7293044"),t.setAttribute("data-script-id","model-viewer"),t.setAttribute("type","module"),window.addEventListener("HCSScriptLoaded",()=>{this.modelViewerLoaded=!0,e()},{once:!0}),this.loadScript(t)}),this.modelViewerLoading)}async loadGLB(e){await this.loadModelViewer();const t=e.getAttribute("data-src"),i=t?.split("/").pop();this.log("Loading GLB: "+i),this.updateLoadingStatus("GLB: "+i,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,n=e.getAttribute("data-network")||this.config.network;let o;"model-viewer"!==e.tagName.toLowerCase()?(o=document.createElement("model-viewer"),Array.from(e.attributes).forEach(e=>{o.setAttribute(e.name,e.value)}),o.setAttribute("camera-controls",""),o.setAttribute("auto-rotate",""),o.setAttribute("ar",""),e.parentNode?.replaceChild(o,e)):o=e;const r=await this.retrieveHCS1Data(i,t,n),a=URL.createObjectURL(r);o.setAttribute("src",a),this.LoadedGLBs[i]=a,this.updateLoadingStatus("GLB: "+i,"loaded"),this.log("Loaded GLB: "+i)}catch(n){this.error("Failed to load GLB: "+i,n),this.updateLoadingStatus("GLB: "+i,"failed")}}async loadResource(e,t,i){return new Promise(n=>{this.loadQueue.push({element:e,type:t,order:i,resolve:n}),this.processQueue()})}async processQueue(){if(!this.isProcessingQueue){for(this.isProcessingQueue=!0;this.loadQueue.length>0;){const t=this.loadQueue.shift();try{"script"===t.type?await this.loadScript(t.element):"image"===t.type?await this.loadImage(t.element):"video"===t.type||"audio"===t.type?await this.loadMedia(t.element,t.type):"glb"===t.type?await this.loadGLB(t.element):"css"===t.type&&await this.loadStylesheet(t.element),t.resolve()}catch(e){if(this.error("Error processing queue item:",e),"script"===t.type&&t.element.hasAttribute("data-required"))break}}this.isProcessingQueue=!1}}async replaceHCSInStyle(e){let t=e,i=t.indexOf("hcs://");for(;-1!==i;){let e=i;for(;e<t.length&&!["'",'"'," ",")"].includes(t[e]);)e++;const o=t.substring(i,e),r=o.split("/").pop();try{const n=this.config.cdnUrl,a=this.config.network,s=await this.retrieveHCS1Data(r,n,a),c=URL.createObjectURL(s);t=t.substring(0,i)+c+t.substring(e),this.LoadedImages[r]=c,this.log("Replaced CSS HCS URL: "+o+" with "+c)}catch(n){this.error("Failed to load CSS image: "+r,n)}i=t.indexOf("hcs://",i+1)}return t}async processInlineStyles(){const e=document.querySelectorAll('[style*="hcs://"]');this.log("Found "+e.length+" elements with HCS style references");for(const i of Array.from(e)){const e=i.getAttribute("style");if(e){this.log("Processing style: "+e);const t=await this.replaceHCSInStyle(e);e!==t&&(i.setAttribute("style",t),this.log("Updated style to: "+t))}}const t=document.querySelectorAll("style");for(const i of Array.from(t))if(i.textContent?.includes("hcs://")){const e=await this.replaceHCSInStyle(i.textContent);i.textContent!==e&&(i.textContent=e)}}async init(){return this.loadConfigFromHTML(),new Promise(e=>{const t=async()=>{const t=document.querySelectorAll('script[data-src^="hcs://"]'),i=document.querySelectorAll('img[data-src^="hcs://"], img[src^="hcs://"]'),n=document.querySelectorAll('video[data-src^="hcs://"], video[src^="hcs://"]'),o=document.querySelectorAll('audio[data-src^="hcs://"], audio[src^="hcs://"]'),r=document.querySelectorAll('model-viewer[data-src^="hcs://"]'),a=document.querySelectorAll('link[data-src^="hcs://"]');document.querySelectorAll('[src^="hcs://"]').forEach(e=>{const t=e.getAttribute("src");t&&(e.setAttribute("data-src",t),e.removeAttribute("src"))}),await this.processInlineStyles();const s=[];[{elements:t,type:"script"},{elements:i,type:"image"},{elements:n,type:"video"},{elements:o,type:"audio"},{elements:r,type:"glb"},{elements:a,type:"css"}].forEach(({elements:e,type:t})=>{e.forEach(e=>{const i=parseInt(e.getAttribute("data-load-order")||"")||1/0;s.push(this.loadResource(e,t,i))})}),await Promise.all(s);const c=new MutationObserver(e=>{e.forEach(e=>{if(e.addedNodes.forEach(e=>{if(e.nodeType===Node.ELEMENT_NODE){const t=e;if(t.getAttribute("style")?.includes("hcs://")&&this.processInlineStyles(),"style"===t.tagName.toLowerCase()&&t.textContent?.includes("hcs://")&&this.processInlineStyles(),t.getAttribute("src")?.startsWith("hcs://")){const e=t.getAttribute("src");t.setAttribute("data-src",e),t.removeAttribute("src");switch(t.tagName.toLowerCase()){case"img":this.loadResource(t,"image",1/0);break;case"video":this.loadResource(t,"video",1/0);break;case"audio":this.loadResource(t,"audio",1/0);break;case"script":this.loadResource(t,"script",1/0)}}t.matches('script[data-src^="hcs://"]')?this.loadResource(t,"script",1/0):t.matches('img[data-src^="hcs://"]')?this.loadResource(t,"image",1/0):t.matches('video[data-src^="hcs://"]')?this.loadResource(t,"video",1/0):t.matches('audio[data-src^="hcs://"]')?this.loadResource(t,"audio",1/0):t.matches('model-viewer[data-src^="hcs://"]')?this.loadResource(t,"glb",1/0):t.matches('link[data-src^="hcs://"]')&&this.loadResource(t,"css",1/0);t.querySelectorAll('[data-src^="hcs://"], [src^="hcs://"]').forEach(e=>{const t=e,i=t.tagName.toLowerCase(),n=t.getAttribute("src");switch(n?.startsWith("hcs://")&&(t.setAttribute("data-src",n),t.removeAttribute("src")),i){case"script":this.loadResource(t,"script",1/0);break;case"img":this.loadResource(t,"image",1/0);break;case"video":this.loadResource(t,"video",1/0);break;case"audio":this.loadResource(t,"audio",1/0);break;case"model-viewer":this.loadResource(t,"glb",1/0);break;case"link":this.loadResource(t,"css",1/0)}})}}),"attributes"===e.type){const t=e.target;if("style"===e.attributeName&&t.getAttribute("style")?.includes("hcs://"))this.processInlineStyles();else if("src"===e.attributeName){const e=t.getAttribute("src");if(e?.startsWith("hcs://")){t.setAttribute("data-src",e),t.removeAttribute("src");const i=t.tagName.toLowerCase();["img","video","audio"].includes(i)&&this.loadResource(t,i,1/0)}}}})});document.body?c.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","src","data-src"]}):document.addEventListener("DOMContentLoaded",()=>{c.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","src","data-src"]})}),e()};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):t()})}async preloadImage(e){this.log("Loading image:"+e),this.updateLoadingStatus("image: "+e,"loading");const t=await this.retrieveHCS1Data(e),i=URL.createObjectURL(t);return this.LoadedImages[e]=i,this.updateLoadingStatus("image: "+e,"loaded"),i}async preloadAudio(e){const t=document.createElement("audio");t.setAttribute("data-topic-id",e),t.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(t),await this.loadMedia(t,"audio");const i=document.querySelector('audio[data-topic-id="'+e+'"]');return i?this.LoadedAudioUrls[e]=i.src:console.error("Failed to preload audio: "+e),this.LoadedAudioUrls[e]}async playAudio(e,t=1){const i=this.LoadedAudioUrls[e];if(i){const n=new Audio(i);n.volume=t,this.LoadedAudios[e]=n,n.play().catch(e=>{console.error("Failed to play audio:",e)}),n.addEventListener("ended",()=>{n.remove(),delete this.LoadedAudios[e]})}else console.error("Audio not preloaded: "+e)}async pauseAudio(e){const t=document.querySelector('audio[data-topic-id="'+e+'"]');t?(console.log("found element",t),t.pause(),this.LoadedAudios[e]?.pause()):this.LoadedAudios[e]?.pause()}async loadAndPlayAudio(e,t=!1,i=1){let n=document.querySelector('audio[data-topic-id="'+e+'"]');if(n)n.volume=i,await n.play();else{const o=document.createElement("audio");o.volume=i,t&&o.setAttribute("autoplay","autoplay"),o.setAttribute("data-topic-id",e),o.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(o),await this.loadMedia(o,"audio"),n=document.querySelector('audio[data-topic-id="'+e+'"]'),t||await n.play()}}}var b=(e=>(e.REGISTER="register",e))(b||{}),x=(e=>(e[e.NON_INDEXED=1]="NON_INDEXED",e))(x||{});function w(e){return`hcs://6/${e}`}const k=n.z.string().regex(/^\d+\.\d+\.\d+$/,{message:"Topic ID must be in Hedera format (e.g., '0.0.123456')"}),_=n.z.object({p:n.z.literal("hcs-6"),op:n.z.enum(["register"]),m:n.z.string().max(500,"Memo must not exceed 500 characters").optional()}),E=_.extend({op:n.z.literal("register"),t_id:k}),S=n.z.discriminatedUnion("op",[E]);function T(e){return e>=3600}function A(e){if(!T(e))throw new Error("TTL must be at least 3600 seconds (1 hour)");return`hcs-6:1:${e}`}let I=class{constructor(e,t,i){this.maxRetries=5,this.initialDelayMs=2e3,this.maxDelayMs=3e4,this.backoffFactor=2,this.network=e,this.apiKey=i?.apiKey,this.customHeaders=i?.headers||{},this.baseUrl=i?.customUrl||this.getMirrorNodeUrl(),this.logger=t||new g({level:"debug",module:"MirrorNode"}),this.isServerEnvironment="undefined"==typeof window,i?.customUrl&&this.logger.info(`Using custom mirror node URL: ${i.customUrl}`),i?.apiKey&&this.logger.info("Using API key for mirror node requests")}configureRetry(e){this.maxRetries=e.maxRetries??this.maxRetries,this.initialDelayMs=e.initialDelayMs??this.initialDelayMs,this.maxDelayMs=e.maxDelayMs??this.maxDelayMs,this.backoffFactor=e.backoffFactor??this.backoffFactor,this.logger.info(`Retry configuration updated: maxRetries=${this.maxRetries}, initialDelayMs=${this.initialDelayMs}, maxDelayMs=${this.maxDelayMs}, backoffFactor=${this.backoffFactor}`)}configureMirrorNode(e){e.customUrl&&(this.baseUrl=e.customUrl,this.logger.info(`Updated mirror node URL: ${e.customUrl}`)),e.apiKey&&(this.apiKey=e.apiKey,this.logger.info("Updated API key for mirror node requests")),e.headers&&(this.customHeaders={...this.customHeaders,...e.headers},this.logger.info("Updated custom headers for mirror node requests"))}constructUrl(e){if(this.baseUrl.includes("<API-KEY>")&&this.apiKey){const t=this.baseUrl.replace("<API-KEY>",this.apiKey);return e.startsWith("/")?`${t}${e}`:`${t}/${e}`}return e.startsWith("/")?`${this.baseUrl}${e}`:`${this.baseUrl}/${e}`}getMirrorNodeUrl(){return"mainnet"===this.network?"https://mainnet-public.mirrornode.hedera.com":"https://testnet.mirrornode.hedera.com"}getBaseUrl(){return this.baseUrl}async getPublicKey(e){this.logger.debug(`Getting public key for account ${e}`);const t=await this.requestAccount(e);try{if(!t||!t.key)throw new Error(`Failed to retrieve public key for account ID: ${e}`);return o.PublicKey.fromString(t.key.key)}catch(i){const e=`Error fetching public key from Mirror Node: ${i.message}`;throw this.logger.error(e),new Error(e)}}async getAccountMemo(e){this.logger.debug(`Getting account memo for account ID: ${e}`);try{const t=await this._requestWithRetry(`/api/v1/accounts/${e}`);return t?.memo?t.memo:(this.logger.warn(`No memo found for account ${e}`),null)}catch(t){const i=t;return this.logger.error(`Failed to get account memo for ${e} after retries: ${i.message}`),null}}async getTopicInfo(e){try{this.logger.debug(`Fetching topic info for ${e}`);return await this._requestWithRetry(`/api/v1/topics/${e}`)}catch(t){const i=`Error retrieving topic information for ${e} after retries: ${t.message}`;throw this.logger.error(i),new Error(i)}}async getTopicFees(e){try{return(await this.getTopicInfo(e)).custom_fees}catch(t){const e=`Error retrieving topic fees: ${t.message}`;return this.logger.error(e),null}}async getHBARPrice(e){try{const t=o.Timestamp.fromDate(e).toString();this.logger.debug(`Fetching HBAR price for timestamp ${t}`);const i=await this._requestWithRetry(`/api/v1/network/exchangerate?timestamp=${t}`);return Number(i?.current_rate?.cent_equivalent)/Number(i?.current_rate?.hbar_equivalent)/100}catch(t){const e=`Error retrieving HBAR price: ${t.message}`;return this.logger.error(e),null}}async getTokenInfo(e){this.logger.debug(`Fetching token info for ${e}`);try{const t=await this._requestWithRetry(`/api/v1/tokens/${e}`);return t?(this.logger.trace(`Token info found for ${e}:`,t),t):(this.logger.warn(`No token info found for ${e}`),null)}catch(t){const i=`Error fetching token info for ${e}: ${t.message}`;return this.logger.error(i),null}}async getTopicMessages(e,t){this.logger.trace(`Querying messages for topic ${e}${t?" with filters":""}`);let i=`/api/v1/topics/${e}/messages`;const n=new URLSearchParams;if(t){if(void 0!==t.sequenceNumber){const e="number"==typeof t.sequenceNumber?t.sequenceNumber.toString():t.sequenceNumber;e.match(/^(gt|gte|lt|lte|eq|ne):/)?n.append("sequencenumber",e):n.append("sequencenumber",`gt:${e}`)}t.limit&&n.append("limit",t.limit.toString()),t.order&&n.append("order",t.order)}const o=n.toString();o&&(i+=`?${o}`);const r=[];let a=i;for(;a;)try{const e=await this._requestWithRetry(a);if(e.messages&&e.messages.length>0)for(const t of e.messages)try{if(!t.message)continue;let e,i;try{e=this.isServerEnvironment?globalThis.Buffer.from(t.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(t.message),e=>e.charCodeAt(0)))}catch(s){const e=`Error decoding message: ${s}`;this.logger.error(e);continue}try{i=JSON.parse(e)}catch(s){const t=`Invalid JSON message content: ${e}`;this.logger.error(t);continue}i.sequence_number=t.sequence_number,r.push({...i,consensus_timestamp:t.consensus_timestamp,sequence_number:t.sequence_number,running_hash:t.running_hash,running_hash_version:t.running_hash_version,topic_id:t.topic_id,payer:t.payer_account_id,created:new Date(1e3*Number(t.consensus_timestamp))})}catch(s){const e=`Error processing message: ${s.message}`;this.logger.error(e)}a=e.links?.next||""}catch(c){const t=`Error querying topic messages for topic ${e} (endpoint: ${a}) after retries: ${c.message}`;throw this.logger.error(t),new Error(t)}return r}async requestAccount(e){try{this.logger.debug(`Requesting account info for ${e}`);const t=await this._requestWithRetry(`/api/v1/accounts/${e}`);if(!t)throw new Error(`No data received from mirror node for account: ${e}`);return t}catch(t){const i=`Failed to fetch account ${e} after retries: ${t.message}`;throw this.logger.error(i),new Error(i)}}async checkKeyListAccess(e,t){try{const i=a.proto.Key.decode(e);return this.evaluateKeyAccess(i,t)}catch(i){const e=`Error decoding protobuf key: ${i.message}`;throw this.logger.error(e),new Error(e)}}async evaluateKeyAccess(e,t){return e.ed25519?this.compareEd25519Key(e.ed25519,t):e.keyList?this.evaluateKeyList(e.keyList,t):!(!e.thresholdKey||!e.thresholdKey.keys)&&this.evaluateKeyList(e.thresholdKey.keys,t)}async evaluateKeyList(e,t){const i=e.keys||[];for(const o of i)if(o)if(o.ed25519){if(this.compareEd25519Key(o.ed25519,t))return!0}else if(o.keyList||o.thresholdKey)try{const e=a.proto.Key.encode({...o.keyList?{keyList:o.keyList}:{},...o.thresholdKey?{thresholdKey:o.thresholdKey}:{}}).finish();if(await this.checkKeyListAccess(globalThis.Buffer.from(e),t))return!0}catch(n){const e=`Error in nested key: ${n.message}`;this.logger.debug(e)}return!1}compareEd25519Key(e,t){try{return o.PublicKey.fromBytes(globalThis.Buffer.from(e)).toString()===t.toString()}catch(i){const e=`Error comparing Ed25519 key: ${i.message}`;return this.logger.debug(e),!1}}async getScheduleInfo(e){try{this.logger.info(`Getting information for scheduled transaction ${e}`);const t=await this._requestWithRetry(`/api/v1/schedules/${e}`);return t||(this.logger.warn(`No schedule info found for ${e} after retries.`),null)}catch(t){return this.logger.error(`Error fetching schedule info for ${e} after retries: ${t.message}`),null}}async getScheduledTransactionStatus(e){try{this.logger.info(`Checking status of scheduled transaction ${e}`);const t=await this.getScheduleInfo(e);if(!t)throw new Error(`Schedule ${e} not found`);return{executed:Boolean(t.executed_timestamp),executedDate:t.executed_timestamp?new Date(1e3*Number(t.executed_timestamp)):void 0,deleted:t.deleted||!1}}catch(t){throw this.logger.error(`Error checking scheduled transaction status: ${t}`),t}}async getTransaction(e){this.logger.info(`Getting transaction details for ID/hash: ${e}`);try{const t=await this._requestWithRetry(`/api/v1/transactions/${e}`);return t?.transactions?.length>0?(this.logger.trace(`Transaction details found for ${e}:`,t.transactions[0]),t.transactions[0]):(this.logger.warn(`No transaction details found for ${e} or unexpected response structure.`),null)}catch(t){const i=t;return this.logger.error(`Failed to get transaction details for ${e} after retries: ${i.message}`),null}}async _requestWithRetry(e,t){let i=0,n=this.initialDelayMs;const o=this.constructUrl(e),a={...t,headers:{...this.customHeaders,...t?.headers}};for(this.apiKey&&(a.headers={...a.headers,Authorization:`Bearer ${this.apiKey}`,"X-API-Key":this.apiKey});i<this.maxRetries;)try{return(await r.get(o,a)).data}catch(s){i++;const e=i>=this.maxRetries,t=s.response?.status;if(t&&t>404&&t<500&&429!==t)throw this.logger.error(`Client error for ${o} (status ${t}): ${s.message}. Not retrying.`),s;if(e)throw this.logger.error(`Max retries (${this.maxRetries}) reached for ${o}. Last error: ${s.message}`),s;this.logger.warn(`Attempt ${i}/${this.maxRetries} failed for ${o}: ${s.message}. Retrying in ${n}ms...`),await new Promise(e=>setTimeout(e,n)),n=Math.min(n*this.backoffFactor,this.maxDelayMs)}throw new Error(`Failed to fetch data from ${o} after ${this.maxRetries} attempts.`)}async _fetchWithRetry(e,t){let i=0,n=this.initialDelayMs;const o={...this.customHeaders};t?.headers&&(t.headers instanceof Headers?t.headers.forEach((e,t)=>{o[t]=e}):Array.isArray(t.headers)?t.headers.forEach(([e,t])=>{o[e]=t}):Object.assign(o,t.headers)),this.apiKey&&(o.Authorization=`Bearer ${this.apiKey}`,o["X-API-Key"]=this.apiKey);const r={...t,headers:o};for(;i<this.maxRetries;)try{const t=await fetch(e,r);if(!t.ok){if(t.status>=400&&t.status<500&&429!==t.status)throw this.logger.error(`Client error for ${e} (status ${t.status}): ${t.statusText}. Not retrying.`),new Error(`Fetch failed with status ${t.status}: ${t.statusText} for URL: ${e}`);throw new Error(`Fetch failed with status ${t.status}: ${t.statusText} for URL: ${e}`)}return await t.json()}catch(a){if(i++,i>=this.maxRetries)throw this.logger.error(`Max retries (${this.maxRetries}) reached for ${e}. Last error: ${a.message}`),a;this.logger.warn(`Attempt ${i}/${this.maxRetries} failed for ${e}: ${a.message}. Retrying in ${n}ms...`),await new Promise(e=>setTimeout(e,n)),n=Math.min(n*this.backoffFactor,this.maxDelayMs)}throw new Error(`Failed to fetch data from ${e} after ${this.maxRetries} attempts.`)}async getAccountBalance(e){this.logger.info(`Getting balance for account ${e}`);try{const t=await this.requestAccount(e);if(t&&t.balance){return t.balance.balance/1e8}return this.logger.warn(`Could not retrieve balance for account ${e} from account info.`),null}catch(t){return this.logger.error(`Error fetching numerical balance for account ${e}: ${t.message}`),null}}async getTopicMessagesByFilter(e,t){this.logger.trace(`Querying messages for topic ${e} with filters: ${JSON.stringify(t)}`);let i=`/api/v1/topics/${e}/messages`;const n=new URLSearchParams;t?.limit&&n.append("limit",t.limit.toString()),t?.sequenceNumber&&n.append("sequencenumber",t.sequenceNumber),t?.startTime&&n.append("timestamp",`gte:${t.startTime}`),t?.endTime&&n.append("timestamp",`lt:${t.endTime}`),t?.order&&n.append("order",t.order);const o=n.toString();o&&(i+=`?${o}`);const r=[];let a=0;try{for(;i&&a<10;){a++;const e=await this._requestWithRetry(i);if(e.messages&&e.messages.length>0)for(const t of e.messages)try{if(!t.message)continue;let e;e=this.isServerEnvironment?globalThis.Buffer.from(t.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(t.message),e=>e.charCodeAt(0)));let i={};try{i=JSON.parse(e)}catch(s){this.logger.debug(`Message content is not valid JSON, using raw: ${e}`),i={raw_content:e}}const n={...i,consensus_timestamp:t.consensus_timestamp,sequence_number:t.sequence_number,payer_account_id:t.payer_account_id,topic_id:t.topic_id,running_hash:t.running_hash,running_hash_version:t.running_hash_version,chunk_info:t.chunk_info,created:new Date(1e3*Number(t.consensus_timestamp.split(".")[0])+Number(t.consensus_timestamp.split(".")[1]||0)/1e6),payer:t.payer_account_id};r.push(n)}catch(c){this.logger.error(`Error processing individual message: ${c.message}`)}if(t?.limit&&r.length>=t.limit)break;i=e.links?.next?`${e.links.next}`:""}return r}catch(p){const t=p;return this.logger.error(`Error querying filtered topic messages for ${e}: ${t.message}`),null}}async getAccountTokens(e,t=100){this.logger.info(`Getting tokens for account ${e}`);let i=[],n=`/api/v1/accounts/${e}/tokens?limit=${t}`;try{for(let e=0;e<10&&n;e++){const e=await this._requestWithRetry(n);if(e&&e.tokens&&(i=i.concat(e.tokens)),n=e.links?.next||"",!n||t&&i.length>=t){t&&i.length>t&&(i=i.slice(0,t));break}}return i}catch(o){return this.logger.error(`Error fetching tokens for account ${e}: ${o.message}`),null}}async getTransactionByTimestamp(e){this.logger.info(`Getting transaction by timestamp: ${e}`);try{return(await this._requestWithRetry(`/api/v1/transactions?timestamp=${e}&limit=1`)).transactions}catch(t){return this.logger.error(`Error fetching transaction by timestamp ${e}: ${t}`),[]}}async getAccountNfts(e,t,i=100){this.logger.info(`Getting NFTs for account ${e}${t?` for token ${t}`:""}`);let n=[],o=`/api/v1/accounts/${e}/nfts?limit=${i}`;t&&(o+=`&token.id=${t}`);try{for(let e=0;e<10&&o;e++){const e=await this._requestWithRetry(o);if(e&&e.nfts){const t=e.nfts.map(e=>{let t;if(e.metadata)try{t=this.isServerEnvironment?globalThis.Buffer.from(e.metadata,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(e.metadata),e=>e.charCodeAt(0)))}catch(i){this.logger.warn(`Failed to decode metadata for NFT ${e.token_id} SN ${e.serial_number}: ${i.message}`)}return{...e,token_uri:t}});n=n.concat(t)}if(o=e.links?.next||"",!o)break}return n}catch(r){return this.logger.error(`Error fetching NFTs for account ${e}: ${r.message}`),null}}async validateNFTOwnership(e,t,i){this.logger.info(`Validating ownership of NFT ${t} SN ${i} for account ${e}`);try{const n=await this.getAccountNfts(e,t);if(n){return n.find(e=>e.token_id===t&&e.serial_number===i)||null}return null}catch(n){return this.logger.error(`Error validating NFT ownership: ${n.message}`),null}}async readSmartContractQuery(e,t,i,n){this.logger.info(`Reading smart contract ${e} with selector ${t}`);const r=e.startsWith("0x")?e:`0x${o.AccountId.fromString(e).toSolidityAddress()}`,a=i.startsWith("0x")?i:`0x${o.AccountId.fromString(i).toSolidityAddress()}`,s={block:n?.block||"latest",data:t,estimate:n?.estimate||!1,from:a,to:r,gas:n?.gas,gasPrice:n?.gasPrice,value:n?.value||0};Object.keys(s).forEach(e=>{const t=e;void 0===s[t]&&delete s[t]});try{const e=this.constructUrl("/api/v1/contracts/call");return await this._fetchWithRetry(e,{method:"POST",body:JSON.stringify(s),headers:{"Content-Type":"application/json"}})}catch(c){return this.logger.error(`Error reading smart contract ${e}: ${c.message}`),null}}async getOutstandingTokenAirdrops(e,t){this.logger.info(`Getting outstanding token airdrops sent by account ${e}`);let i=`/api/v1/accounts/${e}/airdrops/outstanding`;const n=new URLSearchParams;t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order),t?.receiverId&&n.append("receiver.id",t.receiverId),t?.serialNumber&&n.append("serialnumber",t.serialNumber),t?.tokenId&&n.append("token.id",t.tokenId);const o=n.toString();o&&(i+=`?${o}`);try{return(await this._requestWithRetry(i)).airdrops||[]}catch(r){return this.logger.error(`Error fetching outstanding token airdrops for account ${e}: ${r.message}`),null}}async getPendingTokenAirdrops(e,t){this.logger.info(`Getting pending token airdrops received by account ${e}`);let i=`/api/v1/accounts/${e}/airdrops/pending`;const n=new URLSearchParams;t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order),t?.senderId&&n.append("sender.id",t.senderId),t?.serialNumber&&n.append("serialnumber",t.serialNumber),t?.tokenId&&n.append("token.id",t.tokenId);const o=n.toString();o&&(i+=`?${o}`);try{return(await this._requestWithRetry(i)).airdrops||[]}catch(r){return this.logger.error(`Error fetching pending token airdrops for account ${e}: ${r.message}`),null}}async getBlocks(e){this.logger.info("Getting blocks from the network");let t="/api/v1/blocks";const i=new URLSearchParams;e?.limit&&i.append("limit",e.limit.toString()),e?.order&&i.append("order",e.order),e?.timestamp&&i.append("timestamp",e.timestamp),e?.blockNumber&&i.append("block.number",e.blockNumber);const n=i.toString();n&&(t+=`?${n}`);try{return(await this._requestWithRetry(t)).blocks||[]}catch(o){return this.logger.error(`Error fetching blocks: ${o.message}`),null}}async getBlock(e){this.logger.info(`Getting block ${e}`);try{return await this._requestWithRetry(`/api/v1/blocks/${e}`)}catch(t){return this.logger.error(`Error fetching block ${e}: ${t.message}`),null}}async getContracts(e){this.logger.info("Getting contracts from the network");let t="/api/v1/contracts";const i=new URLSearchParams;e?.contractId&&i.append("contract.id",e.contractId),e?.limit&&i.append("limit",e.limit.toString()),e?.order&&i.append("order",e.order);const n=i.toString();n&&(t+=`?${n}`);try{return(await this._requestWithRetry(t)).contracts||[]}catch(o){return this.logger.error(`Error fetching contracts: ${o.message}`),null}}async getContract(e,t){this.logger.info(`Getting contract ${e}`);let i=`/api/v1/contracts/${e}`;t&&(i+=`?timestamp=${t}`);try{return await this._requestWithRetry(i)}catch(n){return this.logger.error(`Error fetching contract ${e}: ${n.message}`),null}}async getContractResults(e){this.logger.info("Getting contract results from the network");let t="/api/v1/contracts/results";const i=new URLSearchParams;e?.from&&i.append("from",e.from),e?.blockHash&&i.append("block.hash",e.blockHash),e?.blockNumber&&i.append("block.number",e.blockNumber),void 0!==e?.internal&&i.append("internal",e.internal.toString()),e?.limit&&i.append("limit",e.limit.toString()),e?.order&&i.append("order",e.order),e?.timestamp&&i.append("timestamp",e.timestamp),e?.transactionIndex&&i.append("transaction.index",e.transactionIndex.toString());const n=i.toString();n&&(t+=`?${n}`);try{return(await this._requestWithRetry(t)).results||[]}catch(o){return this.logger.error(`Error fetching contract results: ${o.message}`),null}}async getContractResult(e,t){this.logger.info(`Getting contract result for ${e}`);let i=`/api/v1/contracts/results/${e}`;void 0!==t&&(i+=`?nonce=${t}`);try{return await this._requestWithRetry(i)}catch(n){return this.logger.error(`Error fetching contract result for ${e}: ${n.message}`),null}}async getContractResultsByContract(e,t){this.logger.info(`Getting contract results for contract ${e}`);let i=`/api/v1/contracts/${e}/results`;const n=new URLSearchParams;t?.blockHash&&n.append("block.hash",t.blockHash),t?.blockNumber&&n.append("block.number",t.blockNumber),t?.from&&n.append("from",t.from),void 0!==t?.internal&&n.append("internal",t.internal.toString()),t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order),t?.timestamp&&n.append("timestamp",t.timestamp),t?.transactionIndex&&n.append("transaction.index",t.transactionIndex.toString());const o=n.toString();o&&(i+=`?${o}`);try{return(await this._requestWithRetry(i)).results||[]}catch(r){return this.logger.error(`Error fetching contract results for ${e}: ${r.message}`),null}}async getContractState(e,t){this.logger.info(`Getting contract state for ${e}`);let i=`/api/v1/contracts/${e}/state`;const n=new URLSearchParams;t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order),t?.slot&&n.append("slot",t.slot),t?.timestamp&&n.append("timestamp",t.timestamp);const o=n.toString();o&&(i+=`?${o}`);try{return(await this._requestWithRetry(i)).state||[]}catch(r){return this.logger.error(`Error fetching contract state for ${e}: ${r.message}`),null}}async getContractActions(e,t){this.logger.info(`Getting contract actions for ${e}`);let i=`/api/v1/contracts/results/${e}/actions`;const n=new URLSearchParams;t?.index&&n.append("index",t.index),t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order);const o=n.toString();o&&(i+=`?${o}`);try{return(await this._requestWithRetry(i)).actions||[]}catch(r){return this.logger.error(`Error fetching contract actions for ${e}: ${r.message}`),null}}async getContractLogs(e){this.logger.info("Getting contract logs from the network");let t="/api/v1/contracts/results/logs";const i=new URLSearchParams;e?.index&&i.append("index",e.index),e?.limit&&i.append("limit",e.limit.toString()),e?.order&&i.append("order",e.order),e?.timestamp&&i.append("timestamp",e.timestamp),e?.topic0&&i.append("topic0",e.topic0),e?.topic1&&i.append("topic1",e.topic1),e?.topic2&&i.append("topic2",e.topic2),e?.topic3&&i.append("topic3",e.topic3),e?.transactionHash&&i.append("transaction.hash",e.transactionHash);const n=i.toString();n&&(t+=`?${n}`);try{return(await this._requestWithRetry(t)).logs||[]}catch(o){return this.logger.error(`Error fetching contract logs: ${o.message}`),null}}async getContractLogsByContract(e,t){this.logger.info(`Getting contract logs for contract ${e}`);let i=`/api/v1/contracts/${e}/results/logs`;const n=new URLSearchParams;t?.index&&n.append("index",t.index),t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order),t?.timestamp&&n.append("timestamp",t.timestamp),t?.topic0&&n.append("topic0",t.topic0),t?.topic1&&n.append("topic1",t.topic1),t?.topic2&&n.append("topic2",t.topic2),t?.topic3&&n.append("topic3",t.topic3);const o=n.toString();o&&(i+=`?${o}`);try{return(await this._requestWithRetry(i)).logs||[]}catch(r){return this.logger.error(`Error fetching contract logs for ${e}: ${r.message}`),null}}async getNftInfo(e,t){this.logger.info(`Getting NFT info for ${e}/${t}`);const i=`/api/v1/tokens/${e}/nfts/${t}`;try{return await this._requestWithRetry(i)}catch(n){return this.logger.error(`Error fetching NFT info for ${e}/${t}: ${n.message}`),null}}async getNftsByToken(e,t){this.logger.info(`Getting NFTs for token ${e}`);let i=`/api/v1/tokens/${e}/nfts`;const n=new URLSearchParams;t?.accountId&&n.append("account.id",t.accountId),t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order),t?.serialNumber&&n.append("serialnumber",t.serialNumber);const o=n.toString();o&&(i+=`?${o}`);try{return(await this._requestWithRetry(i)).nfts||[]}catch(r){return this.logger.error(`Error fetching NFTs for token ${e}: ${r.message}`),null}}async getNetworkInfo(){this.logger.info("Getting network information");try{return await this._requestWithRetry("/api/v1/network/nodes")}catch(e){return this.logger.error(`Error fetching network info: ${e.message}`),null}}async getNetworkFees(e){this.logger.info("Getting network fees");let t="/api/v1/network/fees";e&&(t+=`?timestamp=${e}`);try{return await this._requestWithRetry(t)}catch(i){return this.logger.error(`Error fetching network fees: ${i.message}`),null}}async getNetworkSupply(e){this.logger.info("Getting network supply");let t="/api/v1/network/supply";e&&(t+=`?timestamp=${e}`);try{return await this._requestWithRetry(t)}catch(i){return this.logger.error(`Error fetching network supply: ${i.message}`),null}}async getNetworkStake(e){this.logger.info("Getting network stake");let t="/api/v1/network/stake";e&&(t+=`?timestamp=${e}`);try{return await this._requestWithRetry(t)}catch(i){return this.logger.error(`Error fetching network stake: ${i.message}`),null}}async getOpcodeTraces(e,t){this.logger.info(`Getting opcode traces for ${e}`);let i=`/api/v1/contracts/results/${e}/opcodes`;const n=new URLSearchParams;void 0!==t?.stack&&n.append("stack",t.stack.toString()),void 0!==t?.memory&&n.append("memory",t.memory.toString()),void 0!==t?.storage&&n.append("storage",t.storage.toString());const o=n.toString();o&&(i+=`?${o}`);try{return await this._requestWithRetry(i)}catch(r){return this.logger.error(`Error fetching opcode traces for ${e}: ${r.message}`),null}}};class R{constructor(e){this.network=e.network,this.logger=e.logger||g.getInstance({level:e.logLevel||"info",module:"HCS6Client",silent:e.silent}),this.mirrorNode=new I(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0)}parseRegistryTypeFromMemo(e){try{const t=/hcs-6:(\d):(\d+)/,i=e.match(t);if(i&&3===i.length){const e=parseInt(i[1]),t=parseInt(i[2]);if(e===x.NON_INDEXED&&T(t))return{registryType:e,ttl:t}}return}catch(t){return void this.logger.error(`Error parsing HCS-6 registry type from memo: ${t}`)}}generateRegistryMemo(e){return A(e)}validateMessage(e){try{return S.parse(e),{valid:!0,errors:[]}}catch(t){const e=[];return t instanceof n.ZodError?t.errors.forEach(t=>{const i=t.path.join(".");e.push(`${i?i+": ":""}${t.message}`)}):e.push(`Unexpected error: ${t}`),this.logger.debug(`HCS-6 message validation failed: ${e.join(", ")}`),{valid:!1,errors:e}}}createRegisterMessage(e,t){return{p:"hcs-6",op:b.REGISTER,t_id:e,m:t}}parseRegistryEntries(e,t,i,n){const o=[];let r;this.logger.debug(`Parsing ${t.length} messages for HCS-6 topic ${e}`);for(const s of t)try{if(!s.message){this.logger.debug(`Message is missing 'message' property: ${JSON.stringify(s)}`);continue}const t=globalThis.Buffer.from(s.message,"base64").toString("utf-8"),n=JSON.parse(t);this.logger.debug(`Successfully parsed HCS-6 message: ${JSON.stringify(n)}`);const{valid:a,errors:c}=this.validateMessage(n);if(!a){this.logger.warn(`Invalid HCS-6 message: ${c.join(", ")}`);continue}const p={topicId:e,sequence:s.sequence_number,timestamp:s.consensus_timestamp,payer:s.payer_account_id,message:n,consensus_timestamp:s.consensus_timestamp,registry_type:i};o.push(p),(!r||p.timestamp>r.timestamp)&&(r=p)}catch(a){this.logger.warn(`Error parsing HCS-6 message: ${a}`)}return this.logger.debug(`Parsed ${o.length} valid entries for HCS-6 topic ${e}`),{topicId:e,registryType:i,ttl:n,entries:r?[r]:[],latestEntry:r}}async validateHCS6Topic(e){try{const t=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(t.memo);return i?i.registryType===x.NON_INDEXED||(this.logger.warn(`Topic ${e} is not a valid HCS-6 registry (must be non-indexed)`),!1):(this.logger.warn(`Topic ${e} is not a valid HCS-6 registry (invalid memo format)`),!1)}catch(t){return this.logger.error(`Error validating HCS-6 topic ${e}: ${t}`),!1}}}function O(e){const{memo:t,adminKey:i,submitKey:n,operatorPublicKey:r}=e,a=(new o.TopicCreateTransaction).setTopicMemo(t),s=e=>{if(e){if(e instanceof o.PublicKey||e instanceof o.KeyList)return e;if("boolean"==typeof e)return e?r:void 0;if("string"==typeof e)try{return o.PublicKey.fromString(e)}catch{return}}},c=s(i);c&&a.setAdminKey(c);const p=s(n);return p&&a.setSubmitKey(p),a}function C(e){const t=(new o.TopicMessageSubmitTransaction).setTopicId(o.TopicId.fromString(e.topicId)).setMessage(e.message);return e.transactionMemo&&t.setTransactionMemo(e.transactionMemo),t}function j(e){return O({memo:e.memoOverride??`hcs-6:1:${e.ttl}`,submitKey:e.submitKey,adminKey:e.adminKey,operatorPublicKey:e.operatorPublicKey})}var N=(e=>(e.ED25519="ed25519",e.ECDSA="ecdsa",e.UNKNOWN="unknown",e))(N||{});let B=(t=class{static detect(e){try{let t,i="raw";if("string"==typeof e){let n=e.trim();if(n.includes("-----BEGIN"))return this.detectFromPem(n);if(n.toLowerCase().startsWith("0x")&&(n=n.substring(2)),this.isValidHex(n))t=this.hexToBytes(n),i="hex";else{if(!this.isBase64(n))return{type:"unknown",format:"raw",isPrivateKey:!1,confidence:"certain"};t=globalThis.Buffer.from(n,"base64"),i="der"}}else t=e instanceof globalThis.Buffer?new Uint8Array(e):e;return this.detectFromBytes(t,i)}catch(t){return{type:"unknown",format:"raw",isPrivateKey:!1,confidence:"certain"}}}static detectFromBytes(e,t){if(this.hasPrefix(e,this.ED25519_PUBLIC_KEY_PREFIX)){const t=this.ED25519_PUBLIC_KEY_PREFIX.length;return{type:"ed25519",format:"der",isPrivateKey:!1,rawBytes:e.slice(t),confidence:"certain"}}if(this.hasPrefix(e,this.ED25519_PRIVATE_KEY_PREFIX)){const t=this.ED25519_PRIVATE_KEY_PREFIX.length;if(e.length>=t+32)return{type:"ed25519",format:"der",isPrivateKey:!0,rawBytes:e.slice(t,t+32),confidence:"certain"}}if(this.hasPrefix(e,this.ECDSA_SECP256K1_PUBLIC_KEY_PREFIX)){const t=this.ECDSA_SECP256K1_PUBLIC_KEY_PREFIX.length;return{type:"ecdsa",format:"der",isPrivateKey:!1,rawBytes:e.slice(t),confidence:"certain"}}if(this.hasPrefix(e,this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_SHORT)){const t=this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_SHORT.length;return{type:"ecdsa",format:"der",isPrivateKey:!0,rawBytes:e.slice(t),confidence:"certain"}}if(this.hasPrefix(e,this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX)){const t=this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX.length;return{type:"ecdsa",format:"der",isPrivateKey:!0,rawBytes:e.slice(t,t+32),confidence:"certain"}}if(this.hasPrefix(e,this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_LONG)){const t=this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_LONG.length;return{type:"ecdsa",format:"der",isPrivateKey:!0,rawBytes:e.slice(t,t+32),confidence:"certain"}}if(e.length>36&&this.containsECDSAPrivateKeyPattern(e))return{type:"ecdsa",format:"der",isPrivateKey:!0,rawBytes:this.extractECDSAPrivateKey(e),confidence:"certain"};switch(e.length){case this.ED25519_PUBLIC_KEY_LENGTH:if("hex"===t){const t=Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join(""),i=this.tryCreateKey(t);if("unknown"!==i.type)return i}return{type:"unknown",format:t,isPrivateKey:!1,rawBytes:e,confidence:"certain"};case this.ED25519_EXPANDED_PRIVATE_KEY_LENGTH:return{type:"ed25519",format:t,isPrivateKey:!0,rawBytes:e,confidence:"certain"}}return{type:"unknown",format:t,isPrivateKey:!1,rawBytes:e,confidence:"certain"}}static detectFromPem(e){const t=e.trim(),i=t.includes("PRIVATE KEY"),n={EC_PRIVATE:/-----BEGIN EC PRIVATE KEY-----/,EC_PUBLIC:/-----BEGIN EC PUBLIC KEY-----/,PRIVATE:/-----BEGIN PRIVATE KEY-----/,PUBLIC:/-----BEGIN PUBLIC KEY-----/};let o=!1;for(const[s,c]of Object.entries(n))if(c.test(t)&&s.includes("EC")){o=!0;break}const r=t.match(/-----BEGIN[\s\S]+?-----[\r\n]+([\s\S]+?)[\r\n]+-----END/);if(!r)return{type:"unknown",format:"pem",isPrivateKey:i,confidence:"certain"};const a=r[1].replace(/\s/g,"");try{const e=globalThis.Buffer.from(a,"base64"),t=this.detectFromBytes(new Uint8Array(e),"der");return"unknown"===t.type&&o?{type:"ecdsa",format:"pem",isPrivateKey:i,rawBytes:e,confidence:"certain"}:{...t,format:"pem"}}catch{return{type:"unknown",format:"pem",isPrivateKey:i,confidence:"certain"}}}static tryCreateKey(e){try{if("string"==typeof e){let t=e.trim();if(t.toLowerCase().startsWith("0x")&&(t=t.substring(2)),this.isValidHex(t)&&64===t.length){const e=this.hexToBytes(t),i=this.detectBySignature(t);return"unknown"!==i.type?{type:i.type,format:"hex",isPrivateKey:!0,rawBytes:e,confidence:i.confidence,warning:i.warning}:{type:"unknown",format:"hex",isPrivateKey:!1,rawBytes:e,confidence:"certain"}}}}catch{}return{type:"unknown",format:"hex",isPrivateKey:!1,rawBytes:new Uint8Array,confidence:"certain"}}static detectBySignature(e){const t=BigInt("0x"+e),i=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141");if(0n===t)return{type:"ed25519",confidence:"certain"};if(t>=i)return{type:"ed25519",confidence:"certain"};let n=!1,r=!1;try{const t=o.PrivateKey.fromStringED25519(e),i=new Uint8Array([1,2,3,4,5]),r=t.sign(i);t.publicKey.verify(i,r)&&(n=!0)}catch{}try{const t=o.PrivateKey.fromStringECDSA(e),i=new Uint8Array([1,2,3,4,5]),n=t.sign(i);t.publicKey.verify(i,n)&&(r=!0)}catch{}if(n&&r){const t=this.hexToBytes(e);if(168===t[0]&&1===t[1])return{type:"ed25519",confidence:"uncertain",warning:"Detection based on byte pattern heuristic. Both ED25519 and ECDSA accept this key."};let i=0;for(const e of t)e>=128&&i++;const n=i/t.length;return n>=.4&&n<=.6?{type:"ecdsa",confidence:"uncertain",warning:"Detection based on entropy heuristic. Both ED25519 and ECDSA accept this key."}:{type:"ecdsa",confidence:"uncertain",warning:"Detection based on entropy heuristic. Both ED25519 and ECDSA accept this key. Defaulting to ECDSA."}}return n&&!r?{type:"ed25519",confidence:"certain"}:r&&!n?{type:"ecdsa",confidence:"certain"}:{type:"unknown",confidence:"certain"}}static isValidHex(e){return/^[0-9a-fA-F]+$/.test(e)&&e.length%2==0}static isBase64(e){try{return globalThis.Buffer.from(e,"base64").toString("base64")===e}catch{return!1}}static hexToBytes(e){const t=new Uint8Array(e.length/2);for(let i=0;i<e.length;i+=2)t[i/2]=parseInt(e.substr(i,2),16);return t}static hasPrefix(e,t){if(e.length<t.length)return!1;for(let i=0;i<t.length;i++)if(e[i]!==t[i])return!1;return!0}static containsECDSAPrivateKeyPattern(e){for(let t=0;t<e.length-7;t++)if(48===e[t]&&116===e[t+1]&&2===e[t+2]&&1===e[t+3]&&1===e[t+4]&&4===e[t+5]&&32===e[t+6])return!0;return!1}static extractECDSAPrivateKey(e){for(let t=0;t<e.length-32;t++)if(4===e[t]&&32===e[t+1])return e.slice(t+2,t+34);return e}},t.ED25519_PUBLIC_KEY_LENGTH=32,t.ED25519_EXPANDED_PRIVATE_KEY_LENGTH=64,t.ED25519_PUBLIC_KEY_PREFIX=globalThis.Buffer.from([48,42,48,5,6,3,43,101,112,3,33,0]),t.ED25519_PRIVATE_KEY_PREFIX=globalThis.Buffer.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),t.ECDSA_SECP256K1_PUBLIC_KEY_PREFIX=globalThis.Buffer.from([48,86,48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,10,3,66,0]),t.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX=globalThis.Buffer.from([48,116,2,1,1,4,32]),t.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_SHORT=globalThis.Buffer.from([48,48,2,1,0,48,7,6,5,43,129,4,0,10,4,34,4,32]),t.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_LONG=globalThis.Buffer.from([48,119,2,1,1,4,32]),t);function P(e){const t=B.detect(e);if("unknown"!==t.type)try{const i="ecdsa"===t.type?o.PrivateKey.fromStringECDSA(e):o.PrivateKey.fromStringED25519(e),n={detectedType:t.type,privateKey:i};return"uncertain"===t.confidence&&(n.warning="Key type detection is uncertain. If you have the associated account ID, consider using the Hedera mirror node to confirm the key type."),n}catch(i){}try{return{detectedType:"ecdsa",privateKey:o.PrivateKey.fromStringECDSA(e),warning:"Using ECDSA as default. If you have the associated account ID, consider using the Hedera mirror node to confirm the key type."}}catch(n){try{return{detectedType:"ed25519",privateKey:o.PrivateKey.fromStringED25519(e),warning:"Using ED25519 as fallback. If you have the associated account ID, consider using the Hedera mirror node to confirm the key type."}}catch(r){throw new Error(`Failed to parse private key as either ECDSA or ED25519: ${n}`)}}}class L{constructor(e){this.mirror=e.mirrorNode,this.logger=e.logger}bestGuessOperatorKey(e,t){if("string"!=typeof e)return{keyType:t||"ecdsa",privateKey:e};if(t){return{keyType:t,privateKey:"ed25519"===t?o.PrivateKey.fromStringED25519(e):o.PrivateKey.fromStringECDSA(e)}}try{const t=P(e);return{keyType:t.detectedType,privateKey:t.privateKey}}catch{return{keyType:"ecdsa",privateKey:o.PrivateKey.fromStringECDSA(e)}}}async resolveOperatorKey(e,t,i){if("string"!=typeof t)return{keyType:i||"ecdsa",privateKey:t};if(i){return{keyType:i,privateKey:"ed25519"===i?o.PrivateKey.fromStringED25519(t):o.PrivateKey.fromStringECDSA(t)}}const n="string"==typeof e?e:e.toString();try{const e=await this.mirror.requestAccount(n),i=(e?.key?._type||"").includes("ED25519")?"ed25519":"ecdsa";return{keyType:i,privateKey:"ed25519"===i?o.PrivateKey.fromStringED25519(t):o.PrivateKey.fromStringECDSA(t)}}catch{return this.logger.warn("Mirror node key detection failed; using local detection or default ECDSA"),this.bestGuessOperatorKey(t)}}async resolveSupplyKey(e,t,i,n){try{const r=await this.mirror.getTokenInfo(e),a=r?.supply_key?._type||"";return"string"!=typeof t?t:n?"ed25519"===n?o.PrivateKey.fromStringED25519(t):o.PrivateKey.fromStringECDSA(t):a.includes("ED25519")?o.PrivateKey.fromStringED25519(t):a.includes("ECDSA")?o.PrivateKey.fromStringECDSA(t):"ed25519"===i?o.PrivateKey.fromStringED25519(t):o.PrivateKey.fromStringECDSA(t)}catch{return"string"!=typeof t?t:n?"ed25519"===n?o.PrivateKey.fromStringED25519(t):o.PrivateKey.fromStringECDSA(t):"ed25519"===i?o.PrivateKey.fromStringED25519(t):o.PrivateKey.fromStringECDSA(t)}}}function U(e){const t="string"==typeof e.operatorId?o.AccountId.fromString(e.operatorId):e.operatorId,i=e.client?e.client:"mainnet"===e.network?o.Client.forMainnet():o.Client.forTestnet(),n=new L({mirrorNode:e.mirrorNode,logger:e.logger});let r,a;const s=n.bestGuessOperatorKey(e.operatorKey,e.keyType);r=s.keyType,a=s.privateKey,i.setOperator(t,a);const c=(async()=>{try{const o=await n.resolveOperatorKey(t,e.operatorKey,e.keyType);r=o.keyType,a=o.privateKey,i.setOperator(t,a)}catch{}})();return{client:i,operatorId:t,get operatorKey(){return a},get keyType(){return r},ensureInitialized:async()=>{await c}}}for(var M,F=Object.defineProperty,D=((e,t,i)=>((e,t,i)=>t in e?F(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i)),z={},$={byteLength:function(e){var t=G(e),i=t[0],n=t[1];return 3*(i+n)/4-n},toByteArray:function(e){var t,i,n=G(e),o=n[0],r=n[1],a=new W(function(e,t,i){return 3*(t+i)/4-i}(0,o,r)),s=0,c=r>0?o-4:o;for(i=0;i<c;i+=4)t=K[e.charCodeAt(i)]<<18|K[e.charCodeAt(i+1)]<<12|K[e.charCodeAt(i+2)]<<6|K[e.charCodeAt(i+3)],a[s++]=t>>16&255,a[s++]=t>>8&255,a[s++]=255&t;2===r&&(t=K[e.charCodeAt(i)]<<2|K[e.charCodeAt(i+1)]>>4,a[s++]=255&t);1===r&&(t=K[e.charCodeAt(i)]<<10|K[e.charCodeAt(i+1)]<<4|K[e.charCodeAt(i+2)]>>2,a[s++]=t>>8&255,a[s++]=255&t);return a},fromByteArray:function(e){for(var t,i=e.length,n=i%3,o=[],r=16383,a=0,s=i-n;a<s;a+=r)o.push(J(e,a,a+r>s?s:a+r));1===n?(t=e[i-1],o.push(q[t>>2]+q[t<<4&63]+"==")):2===n&&(t=(e[i-2]<<8)+e[i-1],o.push(q[t>>10]+q[t>>4&63]+q[t<<2&63]+"="));return o.join("")}},q=[],K=[],W="undefined"!=typeof Uint8Array?Uint8Array:Array,H="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",V=0;V<64;++V)q[V]=H[V],K[H.charCodeAt(V)]=V;function G(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var i=e.indexOf("=");return-1===i&&(i=t),[i,i===t?0:4-i%4]}function Z(e){return q[e>>18&63]+q[e>>12&63]+q[e>>6&63]+q[63&e]}function J(e,t,i){for(var n,o=[],r=t;r<i;r+=3)n=(e[r]<<16&16711680)+(e[r+1]<<8&65280)+(255&e[r+2]),o.push(Z(n));return o.join("")}K["-".charCodeAt(0)]=62,K["_".charCodeAt(0)]=63;var Y={
|
|
2
2
|
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
|
|
3
3
|
read:function(e,t,i,n,o){var r,a,s=8*o-n-1,c=(1<<s)-1,p=c>>1,l=-7,u=i?o-1:0,d=i?-1:1,f=e[t+u];for(u+=d,r=f&(1<<-l)-1,f>>=-l,l+=s;l>0;r=256*r+e[t+u],u+=d,l-=8);for(a=r&(1<<-l)-1,r>>=-l,l+=n;l>0;a=256*a+e[t+u],u+=d,l-=8);if(0===r)r=1-p;else{if(r===c)return a?NaN:1/0*(f?-1:1);a+=Math.pow(2,n),r-=p}return(f?-1:1)*a*Math.pow(2,r-n)},write:function(e,t,i,n,o,r){var a,s,c,p=8*r-o-1,l=(1<<p)-1,u=l>>1,d=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:r-1,m=n?1:-1,h=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-a))<1&&(a--,c*=2),(t+=a+u>=1?d/c:d*Math.pow(2,1-u))*c>=2&&(a++,c/=2),a+u>=l?(s=0,a=l):a+u>=1?(s=(t*c-1)*Math.pow(2,o),a+=u):(s=t*Math.pow(2,u-1)*Math.pow(2,o),a=0));o>=8;e[i+f]=255&s,f+=m,s/=256,o-=8);for(a=a<<o|s,p+=o;p>0;e[i+f]=255&a,f+=m,a/=256,p-=8);e[i+f-m]|=128*h}};
|
|
4
4
|
/*!
|