buckyos 0.7.124 → 0.7.125

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,13 @@
1
- "use strict";var t,e,n,r,s,i,o,a,c,l,u,h,d,f,p,g,m,y,w,b,A,_,v,E,k,S,T,R,I,O,C,N,x,P,D,B,U,L,M,F,G,j,H,V,W,K,z,q,$,Q,J,Y,Z,X,tt,et,nt,rt,st,it,ot,at,ct,lt,ut,ht,dt,ft,pt,gt,mt,yt,wt,bt,At,_t,vt,Et,kt,St,Tt,Rt,It,Ot,Ct,Nt,xt,Pt,Dt,Bt,Ut,Lt,Mt,Ft,Gt,jt,Ht,Vt,Wt,Kt,zt,qt,$t,Qt,Jt,Yt,Zt,Xt,te,ee,ne,re,se,ie,oe,ae,ce,le,ue,he,de,fe,pe,ge,me,ye,we,be,Ae,_e,ve,Ee,ke,Se,Te,Re,Ie,Oe,Ce,Ne,xe,Pe,De,Be,Ue,Le,Me,Fe,Ge,je,He,Ve,We,Ke,ze,qe,$e,Qe,Je,Ye,Ze,Xe,tn,en,nn,rn,sn,on,an,cn,ln,un,hn,dn,fn,pn,gn,mn,yn,wn,bn,An,_n,vn,En,kn,Sn,Tn,Rn,In,On,Cn=Object.defineProperty,Nn=(t,e,n)=>(((t,e,n)=>{e in t?Cn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n})(t,"symbol"!=typeof e?e+"":e,n),n),xn=(t,e,n)=>{if(!e.has(t))throw TypeError("Cannot "+n)},Pn=(t,e,n)=>(xn(t,e,"read from private field"),n?n.call(t):e.get(t)),Dn=(t,e,n)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,n)},Bn=(t,e,n,r)=>(xn(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),Un=(t,e,n,r)=>({set _(r){Bn(t,e,r,n)},get _(){return Pn(t,e,r)}}),Ln=(t,e,n)=>(xn(t,e,"access private method"),n);const Mn=require("./ndn_types-44c69036.js");class Fn extends Error{constructor(t){super(t),this.name="RPCError"}}const Gn=async(t,e)=>{if("undefined"!=typeof window&&"function"==typeof window.fetch)return window.fetch(t,e);if("undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch)return globalThis.fetch(t,e);throw new Fn("fetch is not available in this runtime")};class jn{constructor(t,e=null,n=null,r={}){this.serverUrl=t,this.protocolType="HttpPostJson",this.seq=n??Date.now(),this.sessionToken=e||null,this.initToken=e||null,this.traceId=r.traceId||null,this.fetcher=r.fetcher??Gn,this.sessionTokenProvider=r.sessionTokenProvider??null,this.sessionTokenOverride=void 0}async call(t,e,n={}){return this._call(t,e,n)}async callWithSessionToken(t,e,n){return this._call(e,n,{sessionToken:t})}setSeq(t){this.seq=t}resetSessionToken(){this.sessionToken=this.initToken,this.sessionTokenOverride=void 0}setSessionToken(t){this.sessionToken=t||null,this.sessionTokenOverride=t||null}getSessionToken(){return this.sessionToken}setTraceId(t){this.traceId=t||null}getTraceId(){return this.traceId}buildRequest(t,e,n,r,s){let i;return i=s?[n,r,s]:r?[n,r]:[n],{method:t,params:e,sys:i}}parseResponseSys(t,e){if(null==t)return null;if(!Array.isArray(t))throw new Fn("sys is not array");if(t.length<1)throw new Fn("sys is empty");const n=t[0];if("number"!=typeof n)throw new Fn("sys[0] is not number");if(n!==e)throw new Fn(`seq not match: ${n}!=${e}`);if(t.length>=2){const e=t[1];if("string"!=typeof e)throw new Fn("sys[1] trace_id is not string");return e}return null}async prepareSessionToken(t){if(Object.prototype.hasOwnProperty.call(t,"sessionToken"))return t.sessionToken||null;if(void 0!==this.sessionTokenOverride)return this.sessionTokenOverride;if(this.sessionTokenProvider){const t=await this.sessionTokenProvider();void 0!==t&&(this.sessionToken=t||null)}return this.sessionToken}prepareTraceId(t){return Object.prototype.hasOwnProperty.call(t,"traceId")?t.traceId||null:this.traceId}async _call(t,e,n){const r=await this.prepareSessionToken(n),s=this.prepareTraceId(n),i=this.seq;this.seq+=1;const o=this.buildRequest(t,e,i,r,s);try{const t=await this.fetcher(this.serverUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!t.ok)throw new Fn(`RPC call error: ${t.status}`);const e=await t.json();if(this.parseResponseSys(e.sys,i),"error"in e&&e.error)throw new Fn(`RPC call error: ${e.error}`);if(!("result"in e)||void 0===e.result)throw new Fn("RPC response missing result");return e.result}catch(a){if(a instanceof Fn)throw a;const t=a instanceof Error?a.message:String(a);throw new Fn(`RPC call failed: ${t}`)}}}function Hn(){if("undefined"==typeof window||void 0===window.location)throw new Error("AuthClient can only be created in browser SSO environments")}class Vn{constructor(t,e={}){Hn(),this.zoneHostname=t,this.navigate=e.navigate??(t=>{window.location.assign(t)})}buildLoginURL(t=null){Hn();const e=t??window.location.href;return`${`${window.location.protocol}//sys.${this.zoneHostname}/login`}?redirect_url=${encodeURIComponent(e)}`}async login(t=null){const e=this.buildLoginURL(t);this.navigate(e)}}function Wn(t){if(!t||"object"!=typeof t)throw new Fn("verify-hub auth target is required");if("app"===t.kind&&"string"==typeof t.app_instance_id&&t.app_instance_id.length>0)return{kind:"app",app_instance_id:t.app_instance_id};if("system"===t.kind&&"string"==typeof t.service_id&&t.service_id.length>0)return{kind:"system",service_id:t.service_id};throw new Fn("invalid verify-hub auth target")}function Kn(t){const e=Wn(t);if("system"===e.kind)return e.service_id;const n=e.app_instance_id.lastIndexOf("@");if(n<=0||n===e.app_instance_id.length-1)throw new Fn("app auth target must use `<appId>@<ownerUserId>`");return e.app_instance_id.slice(0,n)}class zn{constructor(t){this.rpcClient=t}setSeq(t){this.rpcClient.setSeq(t)}async loginByJwt(t){return this.rpcClient.resetSessionToken(),this.rpcClient.call("login_by_jwt",{type:"jwt",jwt:t.jwt,target:Wn(t.target)})}async loginByPassword(t){this.rpcClient.resetSessionToken();const e={type:"password",username:t.username,password:t.password,target:Wn(t.target)};return void 0!==t.login_nonce&&(e.login_nonce=t.login_nonce),t.source_url&&(e.source_url=t.source_url),this.rpcClient.call("login_by_password",e)}async sudoByPassword(t){this.rpcClient.resetSessionToken();const e={username:t.username,password:t.password,target:Wn(t.target)};return void 0!==t.aud&&(e.aud=t.aud),void 0!==t.login_nonce&&(e.login_nonce=t.login_nonce),this.rpcClient.call("sudo_by_password",e)}async refreshToken(t){return this.rpcClient.call("refresh_token",{refresh_token:t.refresh_token})}async verifyToken(t){const e={session_token:t.session_token};return void 0!==t.expected_target&&(e.expected_target=Wn(t.expected_target)),this.rpcClient.call("verify_token",e)}static normalizeLoginResponse(t){if("user_info"in t)return{user_name:t.user_info.show_name,user_id:t.user_info.user_id,user_type:t.user_info.user_type,session_token:t.session_token,refresh_token:t.refresh_token};if(!t.session_token)throw new Fn("login_by_password response missing session_token");return t}}const qn="task_not_found",$n="permission_denied",Qn="revision_conflict",Jn="stale_runner_epoch",Yn="invalid_task_phase",Zn="control_not_available",Xn="control_already_pending",tr="task_already_completed",er="input_schema_mismatch",nr="result_schema_mismatch",rr="idempotency_conflict",sr="task_schema_not_found",ir=[qn,$n,Qn,Jn,Yn,Zn,Xn,tr,er,nr,rr,sr];function or(t){const e=t instanceof Error?t.message:String(t);for(const n of ir){const t=e.indexOf(n);if(t<0)continue;const r=0===t?"":e[t-1],s=e[t+n.length]??"";if((!r||/[\s:]/.test(r))&&(!s||/[\s:]/.test(s)))return n}return null}var ar=(t=>(t.Unbound="Unbound",t.App="App",t.HumanSet="HumanSet",t))(ar||{}),cr=(t=>(t.Promised="Promised",t.Accepted="Accepted",t.Running="Running",t.Waiting="Waiting",t.Paused="Paused",t.Terminal="Terminal",t))(cr||{});function lr(t){return"Terminal"===t}var ur=(t=>(t.Dispatch="Dispatch",t.Capacity="Capacity",t.Authorization="Authorization",t.HumanInput="HumanInput",t.ChildTask="ChildTask",t.Dependency="Dependency",t.External="External",t.Other="Other",t))(ur||{}),hr=(t=>(t.Succeeded="Succeeded",t.Failed="Failed",t.Canceled="Canceled",t))(hr||{}),dr=(t=>(t.Pause="Pause",t.Resume="Resume",t.Cancel="Cancel",t))(dr||{});var fr=(t=>(t.ReadMeta="ReadMeta",t.ReadInput="ReadInput",t.ReadResult="ReadResult",t.ReportProgress="ReportProgress",t.Control="Control",t.Commit="Commit",t.CreateChild="CreateChild",t.Reassign="Reassign",t.Grant="Grant",t.Archive="Archive",t))(fr||{}),pr=(t=>(t.SelfOnly="SelfOnly",t.Subtree="Subtree",t.WholeTree="WholeTree",t))(pr||{}),gr=(t=>(t.MetaOnly="MetaOnly",t.Payload="Payload",t.Full="Full",t))(gr||{}),mr=(t=>(t.User="User",t.System="System",t))(mr||{}),yr=(t=>(t.TaskCreated="TaskCreated",t.RunnerBound="RunnerBound",t.RunnerReleased="RunnerReleased",t.PhaseChanged="PhaseChanged",t.WaitReasonChanged="WaitReasonChanged",t.ProgressReported="ProgressReported",t.ControlProfileChanged="ControlProfileChanged",t.ControlRequested="ControlRequested",t.ControlSuperseded="ControlSuperseded",t.ControlApplied="ControlApplied",t.ControlRejected="ControlRejected",t.AssigneesChanged="AssigneesChanged",t.AccessGranted="AccessGranted",t.AccessRevoked="AccessRevoked",t.ResultCommitted="ResultCommitted",t.TaskFailed="TaskFailed",t.TaskCanceled="TaskCanceled",t.TaskArchived="TaskArchived",t.PayloadRedacted="PayloadRedacted",t))(yr||{});function wr(t,e,n){const r=function(t,e){if(!t||"object"!=typeof t||Array.isArray(t))throw new Fn(`Expected ${e} in TaskMgr response`);return t}(t,n);if(!(e in r))throw new Fn(`Expected ${e} in TaskMgr response`);return r[e]}function br(t){const e=wr(t,"task","task result");if(!e||"object"!=typeof e||"string"!=typeof e.task_id)throw new Fn("Expected a string task_id in TaskMgr response");return e}function Ar(){const t=globalThis.crypto;if(t&&"function"==typeof t.getRandomValues){const e=new Uint8Array(16);return t.getRandomValues(e),`ctl-${Array.from(e,(t=>t.toString(16).padStart(2,"0"))).join("")}`}return`ctl-${Date.now().toString(16)}${Math.random().toString(16).slice(2)}`}class _r{constructor(t){this.rpcClient=t}setSeq(t){this.rpcClient.setSeq(t)}async callTask(t,e){return br(await this.rpcClient.call(t,e))}async createTask(t){return this.callTask("create_task",t)}async getTask(t){return br(await this.rpcClient.call("get_task",{task_id:t}))}async listTasks(t={}){const e=await this.rpcClient.call("list_tasks",t),n=wr(e,"tasks","task summary page");if(!Array.isArray(n))throw new Fn("Expected tasks array in TaskMgr response");return e}async getTaskTree(t){const e=await this.rpcClient.call("get_task_tree",t),n=wr(e,"tasks","task tree page");if(!Array.isArray(n))throw new Fn("Expected tasks array in TaskMgr response");return e}async getSubtasks(t){const e=await this.rpcClient.call("get_subtasks",t),n=wr(e,"tasks","subtask page");if(!Array.isArray(n))throw new Fn("Expected tasks array in TaskMgr response");return e}async archiveTask(t){return this.callTask("archive_task",t)}async requestControl(t){const e=await this.rpcClient.call("request_control",t),n=wr(e,"kind","control result");if("Task"!==n&&"Batch"!==n)throw new Fn(`Invalid TaskMgr control result kind: ${n}`);return e}async updateAssignees(t){return this.callTask("update_assignees",t)}async grantTaskAccess(t){return this.callTask("grant_task_access",t)}async revokeTaskAccess(t){return this.callTask("revoke_task_access",t)}async listTaskAccess(t){const e=wr(await this.rpcClient.call("list_task_access",{task_id:t}),"grants","task access result");if(!Array.isArray(e))throw new Fn("Expected grants array in TaskMgr response");return e}async reportStarted(t){return this.callTask("report_started",t)}async reportProgress(t){return this.callTask("report_progress",t)}async reportWaiting(t){return this.callTask("report_waiting",t)}async reportRunning(t){return this.callTask("report_running",t)}async updateControlProfile(t){return this.callTask("update_control_profile",t)}async ackControl(t){return this.callTask("ack_control",t)}async commitResult(t){return this.callTask("commit_result",t)}async failTask(t){return this.callTask("fail_task",t)}async createPromisedTask(t){return this.callTask("create_promised_task",t)}async setPromiseWait(t){return this.callTask("set_promise_wait",t)}async bindAppExecutor(t){return this.callTask("bind_app_executor",t)}async releaseAppExecutor(t){return this.callTask("release_app_executor",t)}async finishPromiseFailure(t){return this.callTask("finish_promise_failure",t)}async cancelPromisedTask(t){return this.callTask("cancel_promised_task",t)}async registerTaskSchema(t){return this.rpcClient.call("register_task_schema",{definition:t})}async getTaskSchema(t,e){return this.rpcClient.call("get_task_schema",{schema_id:t,schema_version:e})}async listTaskSchemas(t={}){const e=wr(await this.rpcClient.call("list_task_schemas",t),"schemas","task schema list");if(!Array.isArray(e))throw new Fn("Expected schemas array in TaskMgr response");return e}async setTaskSchemaEnabled(t,e,n){return this.rpcClient.call("set_task_schema_enabled",{schema_id:t,schema_version:e,enabled:n})}async listTaskEvents(t){const e=await this.rpcClient.call("list_task_events",t),n=wr(e,"events","task event list");if(!Array.isArray(n))throw new Fn("Expected events array in TaskMgr response");return e}async addTaskNote(t){return wr(await this.rpcClient.call("add_task_note",t),"note","add task note result")}async listTaskNotes(t){const e=wr(await this.rpcClient.call("list_task_notes",{task_id:t}),"notes","task note list");if(!Array.isArray(e))throw new Fn("Expected notes array in TaskMgr response");return e}async cancelTask(t,e=!1){return this.requestControl({task_id:t,action:"Cancel",request_id:Ar(),recursive:e})}snapshotEnvelope(t){return{task_id:t.task_id,app_instance_id:"App"===t.executor.kind?t.executor.app_instance_id:void 0,runner_epoch:t.runner_epoch,expected_revision:t.revision}}async runnerStart(t){const e=await this.getTask(t);let n;if("Accepted"===e.phase)n=this.reportStarted(this.snapshotEnvelope(e));else{if("Waiting"!==e.phase)return e;n=this.reportRunning(this.snapshotEnvelope(e))}try{return await n}catch(r){const e=or(r);if(e===Qn||e===Yn)return this.getTask(t);throw r}}async runnerProgress(t,e,n){const r=await this.getTask(t);if(lr(r.phase))return r;try{return await this.reportProgress({...this.snapshotEnvelope(r),progress:e,message:n})}catch(s){if(or(s)!==Qn)throw s;const r=await this.getTask(t);return this.reportProgress({...this.snapshotEnvelope(r),progress:e,message:n})}}async runnerWait(t,e){const n=await this.runnerStart(t);return"Running"!==n.phase?n:this.reportWaiting({...this.snapshotEnvelope(n),reason:e})}async runnerComplete(t,e){const n=await this.getTask(t);if(lr(n.phase))return n;try{return await this.commitResult({task_id:n.task_id,result:e,app_instance_id:this.snapshotEnvelope(n).app_instance_id,runner_epoch:n.runner_epoch,expected_revision:n.revision})}catch(r){if(or(r)!==Qn)throw r;const n=await this.getTask(t);return lr(n.phase)?n:this.commitResult({task_id:n.task_id,result:e,app_instance_id:this.snapshotEnvelope(n).app_instance_id,runner_epoch:n.runner_epoch,expected_revision:n.revision})}}async runnerFail(t,e,n,r){const s=await this.getTask(t);return lr(s.phase)?s:this.failTask({...this.snapshotEnvelope(s),error:{code:e,message:n,detail:r}})}}var vr=(t=>(t.Autonomous="autonomous",t.HumanConfirm="human_confirm",t.HumanRequired="human_required",t))(vr||{}),Er=(t=>(t.Single="single",t.FiniteSeekable="finite_seekable",t.FiniteSequential="finite_sequential",t))(Er||{}),kr=(t=>(t.All="all",t.Any="any",t.NOfM="n_of_m",t))(kr||{}),Sr=(t=>(t.Human="human",t.Abort="abort",t))(Sr||{}),Tr=(t=>(t.Draft="draft",t.Active="active",t.Archived="archived",t))(Tr||{}),Rr=(t=>(t.Created="created",t.Running="running",t.WaitingHuman="waiting_human",t.Completed="completed",t.Failed="failed",t.Paused="paused",t.Aborted="aborted",t.BudgetExhausted="budget_exhausted",t))(Rr||{}),Ir=(t=>(t.Pending="pending",t.Ready="ready",t.Running="running",t.Completed="completed",t.Failed="failed",t.Retrying="retrying",t.WaitingHuman="waiting_human",t.Skipped="skipped",t.Aborted="aborted",t.Cancelled="cancelled",t))(Ir||{}),Or=(t=>(t.Approve="approve",t.Modify="modify",t.Reject="reject",t.Retry="retry",t.Skip="skip",t.Abort="abort",t.Rollback="rollback",t))(Or||{}),Cr=(t=>(t.Enabled="enabled",t.Paused="paused",t.Archived="archived",t.Error="error",t))(Cr||{}),Nr=(t=>(t.Skip="skip",t.RunOnce="run_once",t.CatchUp="catch_up",t.Manual="manual",t))(Nr||{}),xr=(t=>(t.Created="created",t.TaskCreated="task_created",t.Skipped="skipped",t.Failed="failed",t))(xr||{});function Pr(t,e){if(!(e in t))throw new Fn(`Expected ${e} in workflow response`);return t[e]}class Dr{constructor(t){this.rpcClient=t}setSeq(t){this.rpcClient.setSeq(t)}async callOk(t,e){const n=function(t){if(!t||"object"!=typeof t||Array.isArray(t))throw new Fn("Invalid workflow RPC response format");return t}(await this.rpcClient.call(t,e));if(!0===n.ok)return n;const r="string"==typeof n.message?n.message:"string"==typeof n.error?n.error:"workflow request failed";throw new Fn(r)}async submitDefinition(t){const e=await this.callOk("submit_definition",t);return{workflow_id:Pr(e,"workflow_id"),version:Pr(e,"version"),analysis:Pr(e,"analysis"),definition:Pr(e,"definition")}}async getDefinition(t){return Pr(await this.callOk("get_definition",{workflow_id:t}),"definition")}async listDefinitions(t={}){return Pr(await this.callOk("list_definitions",t),"definitions")}async archiveDefinition(t){return Pr(await this.callOk("archive_definition",{workflow_id:t}),"status")}async dryRun(t){const e=await this.callOk("dry_run",{definition:t});return{analysis:Pr(e,"analysis"),graph:Pr(e,"graph")}}async createRun(t){return await this.callOk("create_run",t)}async startRun(t){return await this.callOk("start_run",{run_id:t})}async tickRun(t){return await this.callOk("tick_run",{run_id:t})}async getRunGraph(t){return await this.callOk("get_run_graph",{run_id:t})}async listRuns(t={}){return Pr(await this.callOk("list_runs",t),"runs")}async submitStepOutput(t){return await this.callOk("submit_step_output",t)}async reportStepProgress(t){return await this.callOk("report_step_progress",t)}async requestHuman(t){return await this.callOk("request_human",t)}async submitAmendment(t){return Pr(await this.callOk("submit_amendment",t),"amendment")}async approveAmendment(t){const e=await this.callOk("approve_amendment",t);return{amendment:Pr(e,"amendment"),plan_version:Pr(e,"plan_version")}}async rejectAmendment(t){const e=await this.callOk("reject_amendment",t);return{amendment:Pr(e,"amendment"),plan_version:Pr(e,"plan_version")}}async getHistory(t){return await this.callOk("get_history",t)}async subscribeEvents(t){return await this.callOk("subscribe_events",t)}async createScheduledTask(t){return Pr(await this.callOk("create_scheduled_task",t),"schedule")}async updateScheduledTask(t){return Pr(await this.callOk("update_scheduled_task",t),"schedule")}async getScheduledTask(t){return Pr(await this.callOk("get_scheduled_task",{schedule_id:t}),"schedule")}async listScheduledTasks(t={}){return Pr(await this.callOk("list_scheduled_tasks",t),"schedules")}async pauseScheduledTask(t){return Pr(await this.callOk("pause_scheduled_task",{schedule_id:t}),"schedule")}async resumeScheduledTask(t){return Pr(await this.callOk("resume_scheduled_task",{schedule_id:t}),"schedule")}async archiveScheduledTask(t){return Pr(await this.callOk("archive_scheduled_task",{schedule_id:t}),"schedule")}async runScheduledTaskNow(t){return Pr(await this.callOk("run_scheduled_task_now",t),"fire")}async getScheduledTaskHistory(t){return Pr(await this.callOk("get_scheduled_task_history",t),"fires")}async validateScheduledTask(t){return await this.callOk("validate_scheduled_task",t)}}const Br=["services/","system/rbac/"];class Ur{constructor(t,e=null,n={}){this.configCache=new Map,this.rpcClient=new jn(t,e,null,n)}setSeq(t){this.rpcClient.setSeq(t)}async syncSessionToken(t){this.rpcClient.setSessionToken(t)}getSessionToken(){return this.rpcClient.getSessionToken()}needCache(t){return Br.some((e=>t.startsWith(e)))}getUnixTimestamp(){return Math.floor(Date.now()/1e3)}getConfigCache(t){const e=this.configCache.get(t);return e?e.cachedAt+10<this.getUnixTimestamp()?(this.configCache.delete(t),null):e:null}setConfigCache(t,e,n){if(!this.needCache(t))return!0;const r=this.configCache.get(t);return this.configCache.set(t,{value:e,version:n,cachedAt:this.getUnixTimestamp()}),!r||(r.value!==e||r.version!==n)}removeConfigCache(t){this.configCache.delete(t)}async get(t){const e=this.getConfigCache(t);if(null!=e)return{value:e.value,version:e.version,is_changed:!1};const n=await this.rpcClient.call("sys_config_get",{key:t});if(null==n)throw new Error(`system_config key not found: ${t}`);if("string"!=typeof n.value||"number"!=typeof n.version)throw new Error(`invalid sys_config_get response for key: ${t}`);const r=this.setConfigCache(t,n.value,n.version);return{value:n.value,version:n.version,is_changed:r}}async set(t,e){if(!t||!e)throw new Error("key or value is empty");if(t.includes(":"))throw new Error("key can not contain ':'");return await this.rpcClient.call("sys_config_set",{key:t,value:e}),this.removeConfigCache(t),0}async setByJsonPath(t,e,n){return await this.rpcClient.call("sys_config_set_by_json_path",{key:t,json_path:e,value:n}),this.removeConfigCache(t),0}async create(t,e){return await this.rpcClient.call("sys_config_create",{key:t,value:e}),this.removeConfigCache(t),0}async delete(t){return await this.rpcClient.call("sys_config_delete",{key:t}),this.removeConfigCache(t),0}async append(t,e){return await this.rpcClient.call("sys_config_append",{key:t,append_value:e}),this.removeConfigCache(t),0}async list(t){return this.rpcClient.call("sys_config_list",{key:t})}async execTx(t,e){const n={actions:t};e&&(n.main_key=`${e[0]}:${e[1]}`),await this.rpcClient.call("sys_config_exec_tx",n);for(const r of Object.keys(t))this.removeConfigCache(r);return 0}async dumpConfigsForScheduler(){return this.rpcClient.call("dump_configs_for_scheduler",{})}async refreshTrustKeys(){await this.rpcClient.call("sys_refresh_trust_keys",{})}}const Lr={CHAT_COMPLETIONS_CREATE:"chat.completions.create",IMAGES_GENERATE:"images.generate",EMBEDDING_TEXT:"embedding.text",EMBEDDING_MULTIMODAL:"embedding.multimodal",RERANK:"rerank",DECISION_EVALUATE:"decision.evaluate",IMAGE_IMG2IMG:"image.img2img",IMAGE_INPAINT:"image.inpaint",IMAGE_UPSCALE:"image.upscale",IMAGE_BG_REMOVE:"image.bg_remove",VISION_OCR:"vision.ocr",VISION_CAPTION:"vision.caption",VISION_DETECT:"vision.detect",VISION_SEGMENT:"vision.segment",AUDIO_TTS:"audio.tts",AUDIO_ASR:"audio.asr",AUDIO_MUSIC:"audio.music",AUDIO_ENHANCE:"audio.enhance",VIDEO_TXT2VIDEO:"video.txt2video",VIDEO_IMG2VIDEO:"video.img2video",VIDEO_VIDEO2VIDEO:"video.video2video",VIDEO_EXTEND:"video.extend",VIDEO_UPSCALE:"video.upscale",AGENT_COMPUTER_USE:"agent.computer_use"},Mr={ROUTE_RESOLVE:"route.resolve",HELPER_LLM_CHAT:"helper.llm_chat",HELPER_TEXT_TO_IMAGE:"helper.text_to_image",CANCEL:"cancel"},Fr={SERVICE_RELOAD_SETTINGS:"service.reload_settings",QUOTA_QUERY:"quota.query",USAGE_QUERY:"usage.query",TRACE_QUERY:"trace.query",ROUTING_GET:"routing.get",ROUTING_PREVIEW:"routing.preview",ROUTING_UPDATE:"routing.update",PROVIDER_CATALOG:"provider.catalog",PROTOCOL_ADAPTER_LIST:"protocol_adapter.list",PROVIDER_VALIDATE:"provider.validate",PROVIDER_ADD:"provider.add",PROVIDER_LIST:"provider.list",PROVIDER_HEALTH:"provider.health",PROVIDER_UPDATE:"provider.update",PROVIDER_DELETE:"provider.delete",PROVIDER_REFRESH_MODELS:"provider.refresh_models",MODELS_LIST:"models.list",DRIVER_METADATA_UPDATE_GET:"driver_metadata_update.get",DRIVER_METADATA_UPDATE_SET:"driver_metadata_update.set"},Gr={...Lr,...Mr,...Fr},jr={IMMEDIATE:"immediate",STREAM:"stream"},Hr=new Set(Object.values(Lr));function Vr(t){const e={system:["text"],developer:["text"],user:["text","image","document"],assistant:["text","image","document","tool_use","thinking","provider_state"],tool:["tool_result"]};if(!t||!Array.isArray(t.content)||!e[t.role])throw new Fn("invalid AiMessage");if("tool"===t.role&&(1!==t.content.length||"tool_result"!==t.content[0].type))throw new Fn("role Tool requires exactly one ToolResult block");for(const n of t.content){if(!e[t.role].includes(n.type))throw new Fn(`AiMessage role ${t.role} cannot contain ${n.type} content`);if(("tool_use"===n.type||"tool_result"===n.type)&&!n.call_id)throw new Fn(`${n.type} requires call_id`);if("tool_result"===n.type&&0===n.content.length)throw new Fn("tool_result requires non-empty content")}}function Wr(t){if(!t||2!==t.split("@").length||t.startsWith("@")||t.endsWith("@"))throw new Fn("exact_model must be `<provider_model_id>[:<variant>]@<provider_instance_name>`")}function Kr(t){if(!(null==t?void 0:t.trim())||t.includes("@"))throw new Fn("logical_model must be a non-empty logical path without `@`")}function zr(t,e){for(const s of Object.keys(t))if(!e.includes(s))throw new Fn(`unknown field \`${s}\``);const n=t.execution_mode;if(void 0!==n&&n!==jr.IMMEDIATE&&n!==jr.STREAM)throw new Fn("execution_mode must be `immediate` or `stream`");const r=t.session_id;if(void 0!==r&&("string"!=typeof r||!r.trim()||(new TextEncoder).encode(r).length>512))throw new Fn("session_id must contain 1..512 bytes")}const qr=["exact_model","trace_id","execution_mode","idempotency_key","task_options","session_id"],$r={[Lr.CHAT_COMPLETIONS_CREATE]:[...qr,"messages","tools","response_format","temperature","top_p","max_output_tokens","seed","stop","output"],[Lr.IMAGES_GENERATE]:[...qr,"prompt","negative_prompt","n","aspect_ratio","size","quality","style","seed","output"],[Lr.EMBEDDING_TEXT]:[...qr,"items","chunking","embedding_space_id","dimensions","normalize","prefer_artifact"],[Lr.EMBEDDING_MULTIMODAL]:[...qr,"items","dimensions","normalize"],[Lr.DECISION_EVALUATE]:[...qr,"state","questions"],[Lr.RERANK]:[...qr,"query","documents","n","return_documents"],[Lr.IMAGE_IMG2IMG]:[...qr,"images","prompt","strength","output"],[Lr.IMAGE_INPAINT]:[...qr,"image","mask","prompt","mask_semantics","output"],[Lr.IMAGE_UPSCALE]:[...qr,"image","scale","target_width","target_height","preserve_faces","output"],[Lr.IMAGE_BG_REMOVE]:[...qr,"image","mode","output"],[Lr.VISION_OCR]:[...qr,"document","level","language_hints","return_layout","return_artifacts"],[Lr.VISION_CAPTION]:[...qr,"image","style","language","n"],[Lr.VISION_DETECT]:[...qr,"image","classes","score_threshold","bbox_spec"],[Lr.VISION_SEGMENT]:[...qr,"image","prompt","mask_format","return_bitmap_mask"],[Lr.AUDIO_TTS]:[...qr,"text","voice","speed","output"],[Lr.AUDIO_ASR]:[...qr,"audio","language","timestamps","diarization","output_formats"],[Lr.AUDIO_MUSIC]:[...qr,"prompt","duration_seconds","instrumental","lyrics","seed","output"],[Lr.AUDIO_ENHANCE]:[...qr,"audio","task","strength","return_stems"],[Lr.VIDEO_TXT2VIDEO]:[...qr,"prompt","duration_seconds","aspect_ratio","resolution","generate_audio","seed","output"],[Lr.VIDEO_IMG2VIDEO]:[...qr,"image","prompt","duration_seconds","aspect_ratio","resolution"],[Lr.VIDEO_VIDEO2VIDEO]:[...qr,"video","prompt","preserve_motion","time_range"],[Lr.VIDEO_EXTEND]:[...qr,"video","prompt","continuation_handle","duration_seconds","resolution"],[Lr.VIDEO_UPSCALE]:[...qr,"video","target_resolution","denoise","sharpen","output"],[Lr.AGENT_COMPUTER_USE]:[...qr,"task","environment","allowed_actions"],[Mr.ROUTE_RESOLVE]:["trace_id","execution_mode","request_id","api_type","logical_model","requirements","disable","policy","estimated_input_tokens","estimated_output_tokens","session_overlay","session_id"],[Mr.HELPER_LLM_CHAT]:["logical_model","trace_id","execution_mode","requirements","disable","policy","messages","tools","response_format","temperature","top_p","max_output_tokens","seed","stop","output","idempotency_key","task_options","session_overlay","session_id"],[Mr.HELPER_TEXT_TO_IMAGE]:["logical_model","trace_id","execution_mode","requirements","disable","policy","prompt","negative_prompt","n","aspect_ratio","size","quality","style","seed","output","idempotency_key","task_options","session_overlay","session_id"],[Mr.CANCEL]:["task_id"],[Fr.SERVICE_RELOAD_SETTINGS]:[],[Fr.QUOTA_QUERY]:["capability","method"],[Fr.USAGE_QUERY]:["time_range","filters","group_by","time_bucket","output_mode","limit","cursor"],[Fr.TRACE_QUERY]:["limit","cursor","start_time_ms","end_time_ms","task_ids","request_ids","api_types","provider_instance_names","selected_exact_models","scheduler_profiles","query","outcome"],[Fr.ROUTING_GET]:[],[Fr.ROUTING_PREVIEW]:["paths","explain","requirements"],[Fr.ROUTING_UPDATE]:["settings_revision","provider_weights"],[Fr.PROVIDER_CATALOG]:[],[Fr.PROTOCOL_ADAPTER_LIST]:[],[Fr.PROVIDER_VALIDATE]:["provider_instance_name","provider_type","provider_profile_id","protocol_family_id","protocol_adapter_id","base_url","credentials","region","workspace","account","provider_rules_id","auth","discovery","instance_rules","timeout_ms","auto_sync_models"],[Fr.PROVIDER_ADD]:["provider_instance_name","provider_type","provider_profile_id","protocol_family_id","protocol_adapter_id","base_url","credentials","region","workspace","account","provider_rules_id","auth","discovery","instance_rules","timeout_ms","auto_sync_models"],[Fr.PROVIDER_LIST]:["method"],[Fr.PROVIDER_HEALTH]:["exact_model"],[Fr.PROVIDER_UPDATE]:["provider_instance_name","settings_revision","enabled","base_url","credential","provider_profile_id","protocol_adapter_id","discovery","instance_rules"],[Fr.PROVIDER_DELETE]:["provider_instance_name"],[Fr.PROVIDER_REFRESH_MODELS]:["provider_instance_name"],[Fr.MODELS_LIST]:[],[Fr.DRIVER_METADATA_UPDATE_GET]:[],[Fr.DRIVER_METADATA_UPDATE_SET]:["enabled","source_url","interval_secs"]};class Qr{constructor(t){this.rpcClient=t}setSeq(t){this.rpcClient.setSeq(t)}call(t,e){const n=$r[t],r=(null==n?void 0:n.includes("execution_mode"))&&void 0===e.execution_mode?{...e,execution_mode:jr.IMMEDIATE}:e;return n&&zr(r,n),this.rpcClient.call(t,r)}inference(t,e){return Wr(e.exact_model),this.call(t,e)}routeResolve(t){return Kr(t.logical_model),this.call(Mr.ROUTE_RESOLVE,t)}chatCompletionsCreate(t){return t.messages.forEach(Vr),this.inference(Lr.CHAT_COMPLETIONS_CREATE,t)}imagesGenerate(t){return this.inference(Lr.IMAGES_GENERATE,t)}helperLlmChat(t){return Kr(t.logical_model),t.messages.forEach(Vr),this.call(Mr.HELPER_LLM_CHAT,t)}helperTextToImage(t){return Kr(t.logical_model),this.call(Mr.HELPER_TEXT_TO_IMAGE,t)}embeddingText(t){return this.inference(Lr.EMBEDDING_TEXT,t)}embeddingMultimodal(t){return this.inference(Lr.EMBEDDING_MULTIMODAL,t)}async decisionEvaluate(t){es(t);const e=await this.inference(Lr.DECISION_EVALUATE,t);return"succeeded"===e.status&&ns(t,e.answers??[]),e}rerank(t){return this.inference(Lr.RERANK,t)}imageToImage(t){return this.inference(Lr.IMAGE_IMG2IMG,t)}imageInpaint(t){return this.inference(Lr.IMAGE_INPAINT,t)}imageUpscale(t){return this.inference(Lr.IMAGE_UPSCALE,t)}imageBackgroundRemove(t){return this.inference(Lr.IMAGE_BG_REMOVE,t)}visionOcr(t){return this.inference(Lr.VISION_OCR,t)}visionCaption(t){return this.inference(Lr.VISION_CAPTION,t)}visionDetect(t){return this.inference(Lr.VISION_DETECT,t)}visionSegment(t){return this.inference(Lr.VISION_SEGMENT,t)}audioTextToSpeech(t){return this.inference(Lr.AUDIO_TTS,t)}audioSpeechRecognition(t){return this.inference(Lr.AUDIO_ASR,t)}audioMusic(t){return this.inference(Lr.AUDIO_MUSIC,t)}audioEnhance(t){return this.inference(Lr.AUDIO_ENHANCE,t)}videoTextToVideo(t){return this.inference(Lr.VIDEO_TXT2VIDEO,t)}videoImageToVideo(t){return this.inference(Lr.VIDEO_IMG2VIDEO,t)}videoToVideo(t){return this.inference(Lr.VIDEO_VIDEO2VIDEO,t)}videoExtend(t){return this.inference(Lr.VIDEO_EXTEND,t)}videoUpscale(t){return this.inference(Lr.VIDEO_UPSCALE,t)}computerUse(t){return this.inference(Lr.AGENT_COMPUTER_USE,t)}cancel(t){if(!t)throw new Fn("cancel requires non-empty task_id");return this.call(Mr.CANCEL,{task_id:t})}reloadSettings(){return this.call(Fr.SERVICE_RELOAD_SETTINGS,{})}queryQuota(t={}){return this.call(Fr.QUOTA_QUERY,t)}queryUsage(t){return this.call(Fr.USAGE_QUERY,t)}queryTrace(t={}){return this.call(Fr.TRACE_QUERY,t)}previewRouting(t={}){return this.call(Fr.ROUTING_PREVIEW,t)}getRouting(){return this.call(Fr.ROUTING_GET,{})}updateRouting(t){return this.call(Fr.ROUTING_UPDATE,t)}providerCatalog(){return this.call(Fr.PROVIDER_CATALOG,{})}listProtocolAdapters(){return this.call(Fr.PROTOCOL_ADAPTER_LIST,{})}validateProvider(t){return this.call(Fr.PROVIDER_VALIDATE,t)}addProvider(t){return this.call(Fr.PROVIDER_ADD,t)}listProviders(t={}){return this.call(Fr.PROVIDER_LIST,t)}providerHealth(t){return Wr(t.exact_model),this.call(Fr.PROVIDER_HEALTH,t)}updateProvider(t){return this.call(Fr.PROVIDER_UPDATE,t)}deleteProvider(t){return this.call(Fr.PROVIDER_DELETE,t)}refreshProviderModels(t){return this.call(Fr.PROVIDER_REFRESH_MODELS,t)}listModels(){return this.call(Fr.MODELS_LIST,{})}getDriverMetadataUpdate(){return this.call(Fr.DRIVER_METADATA_UPDATE_GET,{})}setDriverMetadataUpdate(t){return this.call(Fr.DRIVER_METADATA_UPDATE_SET,t)}}function Jr(t,e=!0){return"string"==typeof t?!e||t.trim().length>0:null!==t&&"object"==typeof t&&(!e||Object.keys(t).length>0)}function Yr(t){return"string"==typeof t&&/^[A-Za-z0-9_.-]{1,128}$/.test(t)}function Zr(t){return null===t||"object"!=typeof t?JSON.stringify(t):Array.isArray(t)?`[${t.map(Zr).join(",")}]`:`{${Object.keys(t).sort().map((e=>`${JSON.stringify(e)}:${Zr(t[e])}`)).join(",")}}`}function Xr(t){return(new TextEncoder).encode(JSON.stringify(t)).length}function ts(t){const e=Xr(t.state),n={question_types:[],structured_state:"string"!=typeof t.state,structured_rules:!1,question_count:t.questions.length,max_options:0,max_levels:0,input_bytes:e+Xr(t.questions),max_state_question_bytes:0};for(const r of t.questions){n.question_types.includes(r.type)||n.question_types.push(r.type);const t=[r.instructions];"choice"===r.type?(n.max_options=Math.max(n.max_options,r.options.length),t.push(...r.options.map((t=>t.description)))):"score"===r.type?(n.max_levels=Math.max(n.max_levels,r.levels.length),t.push(...r.levels)):r.criteria&&t.push(...Object.values(r.criteria)),n.structured_rules||(n.structured_rules=t.some((t=>null!==t&&"object"==typeof t))),n.max_state_question_bytes=Math.max(n.max_state_question_bytes,e+Xr(r))}return{decision:n}}function es(t){if(Wr(t.exact_model),zr(t,$r[Lr.DECISION_EVALUATE]),!Jr(t.state,!1)||!Array.isArray(t.questions)||!t.questions.length||t.questions.length>1024)throw new Fn("decision requires a text/JSON state and 1..1024 questions");const e=new Set;for(const n of t.questions){if(!n||!Yr(n.id)||e.has(n.id)||!Jr(n.instructions))throw new Fn("invalid decision question");if(e.add(n.id),"choice"===n.type){if(zr(n,["type","id","instructions","options"]),!Array.isArray(n.options)||!n.options.length||n.options.length>1024)throw new Fn("invalid decision options");const t=new Set;for(const e of n.options){if(zr(e,["id","description"]),!Yr(e.id)||t.has(e.id)||null!==e.description&&!Jr(e.description))throw new Fn("invalid decision option");t.add(e.id)}}else if("score"===n.type){if(zr(n,["type","id","instructions","levels"]),!Array.isArray(n.levels)||n.levels.length<2||n.levels.length>1024||n.levels.some((t=>!Jr(t)))||new Set(n.levels.map(Zr)).size!==n.levels.length)throw new Fn("invalid decision levels")}else{if("boolean"!==n.type)throw new Fn("invalid decision question type");if(zr(n,["type","id","instructions","criteria"]),void 0!==n.criteria){if(null===n.criteria||"object"!=typeof n.criteria||Array.isArray(n.criteria))throw new Fn("invalid decision criteria");if(zr(n.criteria,["true","false"]),Object.values(n.criteria).some((t=>!Jr(t))))throw new Fn("invalid decision criteria")}}}if(ts(t).decision.input_bytes>1048576)throw new Fn("decision input exceeds 1 MiB")}function ns(t,e){const n=t=>"number"==typeof t&&Number.isFinite(t)&&t>=0&&t<=1,r=()=>{throw new Fn("invalid or incomplete decision answers")};Array.isArray(e)&&e.length===t.questions.length||r();const s=new Set;for(const i of e){i&&!s.has(i.id)||r(),s.add(i.id);const e=t.questions.find((t=>t.id===i.id));if(!e)throw new Fn("unknown decision question ID");if((e.type!==i.type||void 0!==i.confidence&&!n(i.confidence))&&r(),"boolean"===i.type){zr(i,["type","id","probability_true","confidence"]),n(i.probability_true)||r();continue}zr(i,"choice"===i.type?["type","id","selected","probabilities","confidence"]:["type","id","score","levels","probabilities","confidence"]);const o="choice"===e.type?e.options.map((t=>t.id)):"score"===e.type?e.levels.map(((t,e)=>String(e))):[];if((!i.probabilities||Array.isArray(i.probabilities)||Object.keys(i.probabilities).length!==o.length||o.some((t=>!Object.prototype.hasOwnProperty.call(i.probabilities,t)||!n(i.probabilities[t])))||Math.abs(Object.values(i.probabilities).reduce(((t,e)=>t+e),0)-1)>1e-4)&&r(),"choice"===i.type)o.includes(i.selected)&&!Object.values(i.probabilities).some((t=>t>i.probabilities[i.selected]+1e-4))||r();else if("score"===i.type&&"score"===e.type){const t=o.reduce(((t,e,n)=>t+n*i.probabilities[e]),0);(!Number.isFinite(i.score)||i.score<0||i.score>o.length-1||Math.abs(i.score-t)>1e-4*(o.length-1)||Zr(i.levels)!==Zr(e.levels))&&r()}else r()}}const rs={max_messages:null,retention_seconds:null,sync_write:!1,other_app_can_read:!0,other_app_can_write:!1,other_user_can_read:!1,other_user_can_write:!1};function ss(t,e){if("number"!=typeof t||!Number.isFinite(t))throw new Fn(`expected ${e} to be a number`);return t}function is(t,e){if("string"!=typeof t)throw new Fn(`expected ${e} to be a string`);return t}function os(t){if(!Array.isArray(t))throw new Fn("expected message list to be an array");return t.map(((t,e)=>{if(!t||"object"!=typeof t||Array.isArray(t))throw new Fn(`message[${e}] is not an object`);const n=t;return{index:ss(n.index,`message[${e}].index`),created_at:ss(n.created_at,`message[${e}].created_at`),payload:Array.isArray(n.payload)?n.payload:[],headers:n.headers&&"object"==typeof n.headers&&!Array.isArray(n.headers)?n.headers:{}}}))}class as{constructor(t){this.rpcClient=t}setSeq(t){this.rpcClient.setSeq(t)}async createQueue(t,e,n,r={...rs}){return is(await this.rpcClient.call("create_queue",{name:t,appid:e,app_owner:n,config:r}),"queue_urn")}async deleteQueue(t){await this.rpcClient.call("delete_queue",{queue_urn:t})}async getQueueStats(t){const e=await this.rpcClient.call("get_queue_stats",{queue_urn:t});if(!e||"object"!=typeof e)throw new Fn("invalid get_queue_stats response");const n=e;return{message_count:ss(n.message_count,"message_count"),first_index:ss(n.first_index,"first_index"),last_index:ss(n.last_index,"last_index"),size_bytes:ss(n.size_bytes,"size_bytes")}}async updateQueueConfig(t,e){await this.rpcClient.call("update_queue_config",{queue_urn:t,config:e})}async postMessage(t,e){return ss(await this.rpcClient.call("post_message",{queue_urn:t,message:e}),"msg_index")}async subscribe(t){return is(await this.rpcClient.call("subscribe",{queue_urn:t.queueUrn,userid:t.userId,appid:t.appId,sub_id:t.subId??null,position:t.position}),"subscription_id")}async unsubscribe(t){await this.rpcClient.call("unsubscribe",{sub_id:t})}async fetchMessages(t,e,n){return os(await this.rpcClient.call("fetch_messages",{sub_id:t,length:e,auto_commit:n}))}async readMessage(t,e,n){return os(await this.rpcClient.call("read_message",{queue_urn:t,cursor:e,length:n}))}async commitAck(t,e){await this.rpcClient.call("commit_ack",{sub_id:t,index:e})}async seek(t,e){await this.rpcClient.call("seek",{sub_id:t,index:e})}async deleteMessageBefore(t,e){return ss(await this.rpcClient.call("delete_message_before",{queue_urn:t,index:e}),"deleted_count")}}function cs(t){const e={};for(const[n,r]of Object.entries(t))void 0!==r&&(e[n]=r);return e}function ls(t,e){if(!t||"object"!=typeof t||Array.isArray(t))throw new Fn(`expected ${e} to be an object`);return t}function us(t,e){return null==t?null:ls(t,e)}function hs(t,e){if(!Array.isArray(t))throw new Fn(`expected ${e} to be an array`);return t}function ds(t,e){if("string"!=typeof t)throw new Fn(`${e} expected to return a DID string`);return t}class fs{constructor(t){this.rpcClient=t}setSeq(t){this.rpcClient.setSeq(t)}call(t,e){return this.rpcClient.call(t,e)}async dispatch(t,e,n){return ls(await this.call("msg.dispatch",cs({msg:t,ingress_ctx:e,idempotency_key:n})),"DispatchResult")}async postSend(t,e){return ls(await this.call("msg.post_send",cs({msg:t,idempotency_key:e})),"PostSendResult")}async getNext(t){return us(await this.call("msg.get_next",cs({...t})),"MailboxRecordWithObject")}async getNextDelivery(t){return us(await this.call("msg.get_next_delivery",cs({...t})),"DeliveryRecordWithObject")}async peekBox(t){return hs(await this.call("msg.peek_box",cs({...t})),"Vec<MailboxRecordWithObject>")}async listBoxByTime(t){const e=ls(await this.call("msg.list_box_by_time",cs({...t})),"MailboxRecordPage");return{...e,items:Array.isArray(e.items)?e.items:[]}}async listSessions(t){const e=ls(await this.call("msg.list_sessions",cs({...t})),"SessionSummaryPage");return{...e,items:Array.isArray(e.items)?e.items:[]}}async listSession(t){const e=ls(await this.call("msg.list_session",cs({...t})),"SessionMessagePage");return{...e,items:Array.isArray(e.items)?e.items:[]}}async updateRecordState(t,e){return ls(await this.call("msg.update_record_state",{record_id:t,new_state:e}),"MailboxRecord")}async updateRecordSession(t,e){return ls(await this.call("msg.update_record_session",{record_id:t,session_id:e}),"MailboxRecord")}async reportDelivery(t,e){return ls(await this.call("msg.report_delivery",{delivery_id:t,result:e}),"DeliveryRecord")}async setReadState(t){return ls(await this.call("msg.set_read_state",cs({...t})),"MsgReceiptObj")}async listReadReceipts(t){return hs(await this.call("msg.list_read_receipts",cs({...t})),"Vec<MsgReceiptObj>")}async getRecord(t,e){return us(await this.call("msg.get_record",cs({record_id:t,with_object:e})),"MailboxRecordWithObject")}async getMessage(t){return us(await this.call("msg.get_message",{msg_id:t}),"MsgObject")}async updateUiSessionState(t,e,n){return ls(await this.call("ui_session.update_state",{session_id:t,key:e,value:n}),"UiSessionStateEntry")}async getUiSessionState(t,e){return us(await this.call("ui_session.get_state",{session_id:t,key:e}),"UiSessionStateEntry")}async listUiSessionState(t){return hs(await this.call("ui_session.list_state",{session_id:t}),"Vec<UiSessionStateEntry>")}async resolveDid(t,e,n,r){return ds(await this.call("contact.resolve_did",cs({platform:t,account_id:e,profile_hint:n,contact_mgr_owner:r})),"contact.resolve_did")}async resolveEndpointDid(t,e,n,r,s){return ds(await this.call("contact.resolve_endpoint_did",cs({platform:t,account_id:e,account_type:n,tunnel_instance_id:r,contact_mgr_owner:s})),"contact.resolve_endpoint_did")}async resolveTarget(t,e,n){return ds(await this.call("contact.resolve_target",cs({contact_did:t,selector:e,contact_mgr_owner:n})),"contact.resolve_target")}async resolveContactForEndpoint(t,e){const n=await this.call("contact.resolve_contact_for_endpoint",cs({endpoint_did:t,contact_mgr_owner:e}));return s="contact.resolve_contact_for_endpoint",null==(r=n)?null:ds(r,s);var r,s}async resolveCanonicalDid(t,e){return ds(await this.call("contact.resolve_canonical_did",cs({did:t,contact_mgr_owner:e})),"contact.resolve_canonical_did")}async listAliasDids(t,e){return hs(await this.call("contact.list_alias_dids",cs({canonical_did:t,contact_mgr_owner:e})),"Vec<DID>")}async getPreferredBinding(t,e){return ls(await this.call("contact.get_preferred_binding",cs({did:t,contact_mgr_owner:e})),"AccountBinding")}async checkAccessPermission(t,e,n){return ls(await this.call("contact.check_access_permission",cs({did:t,context_id:e,contact_mgr_owner:n})),"AccessDecision")}async grantTemporaryAccess(t,e,n,r){const s=ls(await this.call("contact.grant_temporary_access",cs({dids:t,context_id:e,duration_secs:n,contact_mgr_owner:r})),"GrantTemporaryAccessResult");return{updated:Array.isArray(s.updated)?s.updated:[]}}async blockContact(t,e,n){await this.call("contact.block_contact",cs({did:t,reason:e,contact_mgr_owner:n}))}async importContacts(t,e,n){return ls(await this.call("contact.import_contacts",cs({contacts:t,upgrade_to_friend:e,contact_mgr_owner:n})),"ImportReport")}async mergeContacts(t,e,n){return ls(await this.call("contact.merge_contacts",cs({target_did:t,source_did:e,contact_mgr_owner:n})),"Contact")}async updateContact(t,e,n){return ls(await this.call("contact.update_contact",cs({did:t,patch:e,contact_mgr_owner:n})),"Contact")}async getContact(t,e){return us(await this.call("contact.get_contact",cs({did:t,contact_mgr_owner:e})),"Contact")}async listContacts(t,e){return hs(await this.call("contact.list_contacts",cs({query:t,contact_mgr_owner:e})),"Vec<Contact>")}async getGroupSubscribers(t,e,n,r){return hs(await this.call("contact.get_group_subscribers",cs({group_id:t,limit:e,offset:n,contact_mgr_owner:r})),"Vec<DID>")}async setGroupSubscribers(t,e,n){const r=ls(await this.call("contact.set_group_subscribers",cs({group_id:t,subscribers:e,contact_mgr_owner:n})),"SetGroupSubscribersResult");if("string"!=typeof r.group_id||"number"!=typeof r.subscriber_count)throw new Fn("Invalid SetGroupSubscribersResult");return{group_id:r.group_id,subscriber_count:r.subscriber_count}}async groupCreate(t){return ls(await this.call("group.create",t),"GroupDoc")}async groupGetDoc(t){return us(await this.call("group.get_doc",t),"GroupDoc")}async groupUpdateProfile(t){return ls(await this.call("group.update_profile",t),"GroupDoc")}async groupInviteMember(t){return ls(await this.call("group.invite_member",t),"GroupMemberRecord")}async groupSubmitMemberProof(t){return ls(await this.call("group.submit_member_proof",t),"GroupMemberRecord")}async groupRequestJoin(t){return ls(await this.call("group.request_join",t),"GroupMemberRecord")}async groupApproveMember(t){return ls(await this.call("group.approve_member",t),"GroupMemberRecord")}async groupRejectMember(t){return ls(await this.call("group.reject_member",t),"GroupMemberRecord")}async groupRemoveMember(t){return ls(await this.call("group.remove_member",t),"GroupMemberRecord")}async groupUpdateMemberRole(t){return ls(await this.call("group.update_member_role",t),"GroupMemberRecord")}async groupListMembers(t){return hs(await this.call("group.list_members",t),"Vec<GroupMemberRecord>")}async groupCreateSubgroup(t){return ls(await this.call("group.create_subgroup",t),"GroupSubgroup")}async groupUpdateSubgroup(t){return ls(await this.call("group.update_subgroup",t),"GroupSubgroup")}async groupListSubgroups(t){return hs(await this.call("group.list_subgroups",t),"Vec<GroupSubgroup>")}async groupUpdateCollectionPolicy(t){return ls(await this.call("group.update_collection_policy",t),"GroupDoc")}async groupUpdateAttributionPolicy(t){return ls(await this.call("group.update_attribution_policy",t),"GroupDoc")}async groupExpandMembers(t){return ls(await this.call("group.expand_members",t),"GroupExpansionSnapshot")}async groupListByMember(t){return hs(await this.call("group.list_by_member",t),"Vec<GroupSummary>")}async groupListParents(t){return hs(await this.call("group.list_parents",t),"Vec<GroupSummary>")}async groupCheckAccess(t){return ls(await this.call("group.check_access",t),"GroupAccessDecision")}}function ps(t){const e={};for(const[n,r]of Object.entries(t))void 0!==r&&(e[n]=r);return e}function gs(t,e){if("string"!=typeof t)throw new Fn(`expected ${e} to be a string`);return t}function ms(t,e){if("boolean"!=typeof t)throw new Fn(`expected ${e} to be a boolean`);return t}function ys(t,e){if("number"!=typeof t||!Number.isFinite(t))throw new Fn(`expected ${e} to be a number`);return t}function ws(t,e){if(!Array.isArray(t))throw new Fn(`expected ${e} to be an array`);return t}function bs(t,e){if(!t||"object"!=typeof t||Array.isArray(t))throw new Fn(`expected ${e} to be an object`);return t}class As{constructor(t){this.rpcClient=t}setSeq(t){this.rpcClient.setSeq(t)}async store(t){return gs(await this.rpcClient.call("store",{content_id:t}),"ObjId")}async collect(t,e){return gs(await this.rpcClient.call("collect",ps({content_meta:t,referral_proof:e})),"content_id")}async pin(t,e){return ms(await this.rpcClient.call("pin",{content_id:t,download_proof:e}),"pin response")}async unpin(t,e=!1){return ms(await this.rpcClient.call("unpin",{content_id:t,force:e}),"unpin response")}async uncollect(t,e=!1){return ms(await this.rpcClient.call("uncollect",{content_id:t,force:e}),"uncollect response")}async addProof(t){return gs(await this.rpcClient.call("add_proof",{proof:t}),"proof_id")}async getProofs(t,e){return ws(await this.rpcClient.call("get_proofs",ps({content_id:t,filter:e})),"Vec<RepoProof>").map(((t,e)=>{const n=bs(t,`RepoProof[${e}]`);if("Action"!==n.kind&&"Collection"!==n.kind)throw new Fn(`RepoProof[${e}] has unknown kind: ${String(n.kind)}`);return n}))}async resolve(t){return ws(await this.rpcClient.call("resolve",{content_name:t}),"Vec<ObjId>").map(((t,e)=>gs(t,`ObjId[${e}]`)))}async list(t){return ws(await this.rpcClient.call("list",ps({filter:t})),"Vec<RepoRecord>").map(((t,e)=>{const n=bs(t,`RepoRecord[${e}]`);return{content_id:gs(n.content_id,`RepoRecord[${e}].content_id`),content_name:"string"==typeof n.content_name?n.content_name:void 0,status:gs(n.status,`RepoRecord[${e}].status`),origin:gs(n.origin,`RepoRecord[${e}].origin`),meta:n.meta,owner_did:"string"==typeof n.owner_did?n.owner_did:void 0,author:"string"==typeof n.author?n.author:void 0,access_policy:gs(n.access_policy,`RepoRecord[${e}].access_policy`),price:"string"==typeof n.price?n.price:void 0,content_size:"number"==typeof n.content_size?n.content_size:void 0,collected_at:"number"==typeof n.collected_at?n.collected_at:void 0,pinned_at:"number"==typeof n.pinned_at?n.pinned_at:void 0,updated_at:"number"==typeof n.updated_at?n.updated_at:void 0}}))}async stat(){const t=bs(await this.rpcClient.call("stat",{}),"RepoStat");return{total_objects:ys(t.total_objects,"RepoStat.total_objects"),collected_objects:ys(t.collected_objects,"RepoStat.collected_objects"),pinned_objects:ys(t.pinned_objects,"RepoStat.pinned_objects"),local_objects:ys(t.local_objects,"RepoStat.local_objects"),remote_objects:ys(t.remote_objects,"RepoStat.remote_objects"),total_content_bytes:ys(t.total_content_bytes,"RepoStat.total_content_bytes"),total_proofs:ys(t.total_proofs,"RepoStat.total_proofs")}}async serve(t,e){const n=bs(await this.rpcClient.call("serve",{content_id:t,request_context:e}),"RepoServeResult");return{status:gs(n.status,"RepoServeResult.status"),content_ref:n.content_ref&&"object"==typeof n.content_ref?n.content_ref:void 0,download_proof:n.download_proof&&"object"==typeof n.download_proof?n.download_proof:void 0,reject_code:"string"==typeof n.reject_code?n.reject_code:void 0,reject_reason:"string"==typeof n.reject_reason?n.reject_reason:void 0}}async announce(t){return ms(await this.rpcClient.call("announce",{content_id:t}),"announce response")}}function _s(t){if(!t||t.length>253||t.includes("@"))throw new Error("hostname must be 1..=253 bytes and must not contain `@`");if(t!==t.toLowerCase()||!/^[\x00-\x7f]+$/.test(t))throw new Error("hostname must be canonical lowercase ASCII");for(const e of t.split("."))if(!e||e.length>63||e.startsWith("-")||e.endsWith("-")||!/^[a-z0-9-]+$/.test(e))throw new Error(`invalid DNS label \`${e}\``)}function vs(t){const e=/^did:([^:]+):(.+)$/.exec(t);if(!e)throw new Error("AppDID must be a canonical DID");const[,n,r]=e;if(!n||!r||n!==n.toLowerCase()||r!==r.toLowerCase()||r.includes(":")||r.includes("#")||r.includes("%"))throw new Error("AppDID must be a canonical lowercase hostname-form DID without path, port, encoding, or fragment");const s=new Mn.DID(n,r).toRawHostName();if(_s(s),"web"===n&&s.endsWith(".did"))throw new Error("AppDID did:web hostnames ending in `.did` are reserved");if(Mn.DID.fromStr(s).toString()!==t)throw new Error("AppDID raw hostname does not round-trip");return s}function Es(t){return vs(t.trim())}function ks(t){const e=t.trim();_s(e);const n=vs(Mn.DID.fromStr(e).toString());if(n!==e)throw new Error("AppId is not a canonical AppDID raw hostname");return n}function Ss(t){if(!t||t.length>64||!/^[a-z0-9._-]+$/.test(t))throw new Error("owner_user_id must be lowercase ASCII and contain only [a-z0-9._-]")}function Ts(t,e){const n=ks(t);return Ss(e),`${n}@${e}`}function Rs(t){const e=t.trim(),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)throw new Error("AppInstanceId must be `{app_id}@{owner_user_id}`");const r=ks(e.slice(0,n)),s=e.slice(n+1);return Ss(s),{appId:r,ownerUserId:s}}const Is="BUCKYOS_APP_DID",Os="BUCKYOS_APP_ID",Cs="BUCKYOS_APP_INSTANCE_ID",Ns="BUCKYOS_OWNER_USER_ID",xs="BUCKYOS_DATA_DIR",Ps="BUCKYOS_APP_TOKEN";var Ds=(t=>(t.Browser="Browser",t.NodeJS="NodeJS",t.AppRuntime="AppRuntime",t.AppClient="AppClient",t.AppService="AppService",t.Unknown="Unknown",t))(Ds||{});const Bs={zoneHost:"",appId:"",appDid:null,appInstanceId:null,dataDir:null,defaultProtocol:"http://",runtimeType:"Unknown",userid:null,ownerUserId:null,rootDir:"",sessionToken:null,refreshToken:null,privateKeySearchPaths:[],systemConfigServiceUrl:"",verifyHubServiceUrl:"",nodeGatewayPort:3180,autoRenew:!0,renewIntervalMs:5e3};function Us(){const t=globalThis.process;return(null==t?void 0:t.env)??{}}function Ls(){var t;const e=globalThis.process;return Boolean(null==(t=null==e?void 0:e.versions)?void 0:t.node)}function Ms(){return"undefined"!=typeof localStorage}function Fs(){return"function"==typeof fetch}function Gs(){const t=globalThis.Buffer;if(!t||"function"!=typeof t)throw new Error("Buffer is not available in this runtime");return t}function js(t){const e=Gs();return("string"==typeof t?e.from(t,"utf8").toString("base64"):e.from(t).toString("base64")).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Hs(t){if(!t)return null;const e=t.split(".");if(e.length<2)return null;try{return JSON.parse(function(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e+"=".repeat((4-e.length%4)%4);return"function"==typeof atob?atob(n):Gs().from(n,"base64").toString("utf8")}(e[1]))}catch{return null}}function Vs(t){if("string"!=typeof t)return null;const e=t.trim();return e.length>0?e:null}function Ws(t){const e=Vs(t);return e?e.startsWith("did:web:")?e.slice(8).replace(/:/g,"."):e.startsWith("did:bns:")?e.slice(8):null:null}async function Ks(t){if(Ls()&&"function"==typeof require)return require(t);return Function("name","return import(name)")(t)}class zs{async initialize(t){await t.resolveAppServiceIdentityFromEnv(),await t.resolveZoneHostFromLocalConfig()}async login(t){await t.initialize(),t.startAutoRenewIfNeeded()}supportsManagedSessionRenewal(){return!1}shouldSkipVerifyHubRenewal(t){return!1}async getVerifyHubLoginJwt(t,e){return e}}class qs extends zs{getRelativeZoneServiceURL(t){return`/kapi/${t}/`}getRelativeSystemConfigServiceURL(){return"/kapi/system_config"}getServiceSettingsPath(t){return`services/${t.getAppId()}/settings`}getZoneServiceURL(t,e){return this.getRelativeZoneServiceURL(e)}getSystemConfigServiceURL(t){return this.getRelativeSystemConfigServiceURL()}getMySettingsPath(t){return this.getServiceSettingsPath(t)}}class $s extends qs{}class Qs extends zs{async login(t){await t.initialize(),await t.renewTokenFromVerifyHub(),t.startAutoRenewIfNeeded()}supportsManagedSessionRenewal(){return!0}}class Js extends Qs{async initialize(t){await super.initialize(t),await t.ensureAppClientSessionToken()}getZoneGatewayServiceURL(t,e){const n=Vs(t.getZoneHostName());if(!n)throw new Error("zoneHost is required in AppClient mode");return`${t.getDefaultProtocol()}${n}/kapi/${e}`}getZoneSystemConfigURL(t){const e=Vs(t.getZoneHostName());if(!e)throw new Error("zoneHost is required in AppClient mode");return`${t.getDefaultProtocol()}${e}/kapi/system_config`}getZoneServiceURL(t,e){return this.getZoneGatewayServiceURL(t,e)}getSystemConfigServiceURL(t){return this.getZoneSystemConfigURL(t)}getMySettingsPath(){throw new Error("AppClient not support getMySettingsPath")}shouldSkipVerifyHubRenewal(t){return!Vs(t.getZoneHostName())&&!t.getConfiguredVerifyHubServiceUrl()}async getVerifyHubLoginJwt(t,e){return t.createAppClientSessionToken()}}class Ys extends Qs{async initialize(t){await super.initialize(t),t.ensureAppServiceSessionToken()}getNodeGatewayServiceURL(t,e){const n=t.getNodeGatewayPort();return`http://${t.resolveAppServiceGatewayHost()}:${n}/kapi/${e}`}getNodeGatewaySystemConfigURL(t){const e=t.getNodeGatewayPort();return`http://${t.resolveAppServiceGatewayHost()}:${e}/kapi/system_config`}getUserAppSettingsPath(t){const e=t.getOwnerUserId();if(!e)throw new Error("ownerUserId is required for AppService settings");return`users/${e}/apps/${t.getAppId()}/settings`}getZoneServiceURL(t,e){return this.getNodeGatewayServiceURL(t,e)}getSystemConfigServiceURL(t){return this.getNodeGatewaySystemConfigURL(t)}getMySettingsPath(t){return this.getUserAppSettingsPath(t)}}function Zs(t){switch(t){case"AppClient":return new Js;case"AppService":return new Ys;case"AppRuntime":return new $s;default:return new qs}}class Xs{constructor(t){const e=Vs(t.ownerUserId)??Vs(t.userid);this.config={...Bs,...t,appId:t.appId,appDid:Vs(t.appDid),appInstanceId:Vs(t.appInstanceId),dataDir:Vs(t.dataDir),userid:e,ownerUserId:e,zoneHost:t.zoneHost??"",defaultProtocol:t.defaultProtocol??Bs.defaultProtocol},this.sessionToken=Vs(t.sessionToken),this.refreshToken=Vs(t.refreshToken),this.renewTimer=null,this.browserRefreshPromise=null,this.authStateRevision=0,this.initialized=!1,this.profile=Zs(this.config.runtimeType)}async initialize(){this.initialized||(await this.profile.initialize(this),this.validateSessionToken(),this.initialized=!0)}async login(){await this.profile.login(this)}setConfig(t){const e=Vs(t.ownerUserId)??Vs(t.userid);this.config={...Bs,...t,appId:t.appId,appDid:Vs(t.appDid),appInstanceId:Vs(t.appInstanceId),dataDir:Vs(t.dataDir),userid:e,ownerUserId:e},this.profile=Zs(this.config.runtimeType)}getConfig(){return{...this.config}}getAppId(){return this.config.appId}getOwnerUserId(){return Vs(this.config.ownerUserId)}getAppDid(){return Vs(this.config.appDid)}getAppInstanceId(){return Vs(this.config.appInstanceId)}getDataDir(){return Vs(this.config.dataDir)}getAuthTarget(){if(this.config.authTarget){const t=Kn(this.config.authTarget);if(t!==this.config.appId)throw new Error(`auth target appid mismatch: ${t} != ${this.config.appId}`);return{...this.config.authTarget}}const t=this.getAppInstanceId();if(t){const e=Rs(t);if(e.appId!==this.config.appId)throw new Error(`auth target appid mismatch: ${e.appId} != ${this.config.appId}`);return{kind:"app",app_instance_id:t}}if("AppClient"===this.config.runtimeType||"AppService"===this.config.runtimeType){const t=this.getOwnerUserId();if(!t)throw new Error("ownerUserId is required to build an App auth target");return{kind:"app",app_instance_id:Ts(this.config.appId,t)}}throw new Error("authTarget or appInstanceId must be configured for this runtime")}getZoneHostName(){return this.config.zoneHost}getDefaultProtocol(){return this.config.defaultProtocol}getNodeGatewayPort(){return this.config.nodeGatewayPort??3180}getConfiguredVerifyHubServiceUrl(){return Vs(this.config.verifyHubServiceUrl)}getZoneServiceURL(t){const e=function(t){return"system-config"===t?"system_config":t}(t);return this.profile.getZoneServiceURL(this,e)}getSystemConfigServiceURL(){const t=this.getConfiguredSystemConfigServiceUrl();return t||this.profile.getSystemConfigServiceURL(this)}setSessionToken(t){const e=Vs(t);e!==this.sessionToken&&(this.authStateRevision+=1),this.sessionToken=e}setRefreshToken(t){this.refreshToken=Vs(t)}getSessionToken(){return this.sessionToken}getRefreshToken(){return this.refreshToken}clearAuthState(){this.authStateRevision+=1,this.sessionToken=null,this.refreshToken=null,this.stopAutoRenew()}stopAutoRenew(){this.renewTimer&&(clearInterval(this.renewTimer),this.renewTimer=null)}getServiceRpcClient(t){return new jn(this.getZoneServiceURL(t),this.sessionToken,null,{sessionTokenProvider:this.ensureSessionTokenReady.bind(this),onSessionTokenChanged:this.setSessionToken.bind(this)})}getSystemConfigClient(){return new Ur(this.getSystemConfigServiceURL(),this.sessionToken,{sessionTokenProvider:this.ensureSessionTokenReady.bind(this),onSessionTokenChanged:this.setSessionToken.bind(this)})}getVerifyHubClient(){const t=this.getConfiguredVerifyHubServiceUrl(),e=new jn(t??this.getZoneServiceURL("verify-hub"),this.sessionToken);return new zn(e)}getTaskManagerClient(){const t=this.getServiceRpcClient("task-manager");return new _r(t)}getWorkflowClient(){const t=this.getServiceRpcClient("workflow");return new Dr(t)}getAiccClient(){return new Qr(this.getServiceRpcClient("aicc"))}getMsgQueueClient(){return new as(this.getServiceRpcClient("kmsg"))}getMsgCenterClient(){return new fs(this.getServiceRpcClient("msg-center"))}getRepoClient(){return new As(this.getServiceRpcClient("repo-service"))}async getMySettings(){const t=this.getMySettingsPath(),e=await this.getSystemConfigClient().get(t);return JSON.parse(e.value)}async updateMySettings(t,e){const n=this.getMySettingsPath(),r=JSON.stringify(e);await this.getSystemConfigClient().setByJsonPath(n,t,r)}async updateAllMySettings(t){const e=this.getMySettingsPath(),n=JSON.stringify(t);await this.getSystemConfigClient().set(e,n)}async renewTokenFromVerifyHub(){if(!this.profile.supportsManagedSessionRenewal())return;const t=this.sessionToken;if(!t)return;const e=Hs(t);if(!e||!this.needsRenew(e))return;if(this.profile.shouldSkipVerifyHubRenewal(this))return;const n=this.getVerifyHubClient(),r="verify-hub"===e.iss?this.refreshToken?await n.refreshToken({refresh_token:this.refreshToken}):await n.loginByJwt({jwt:await this.profile.getVerifyHubLoginJwt(this,t),target:this.getAuthTarget()}):await n.loginByJwt({jwt:t,target:this.getAuthTarget()});this.sessionToken=Vs(r.session_token),this.refreshToken=Vs(r.refresh_token),this.validateSessionToken()}async ensureSessionTokenReady(){if(this.usesBrowserSessionRefresh()){const t=await this.ensureBrowserSessionToken();return t&&this.startAutoRenewIfNeeded(),t}return this.profile.supportsManagedSessionRenewal()&&await this.renewTokenFromVerifyHub(),this.sessionToken}ensureAppServiceSessionToken(){this.sessionToken||(this.sessionToken=this.loadAppServiceSessionTokenFromEnv())}async ensureAppClientSessionToken(){this.sessionToken||(this.sessionToken=this.loadAppClientSessionTokenFromEnv()),this.sessionToken||(this.sessionToken=await this.createAppClientSessionToken())}async resolveAppServiceIdentityFromEnv(){if(!Ls())return;if("AppService"!==this.config.runtimeType)return;const t=Us(),e=e=>{const n=Vs(t[e]);if(!n)throw new Error(`${e} is required for AppService runtime`);return n},n=e(Is),r=ks(e(Os)),s=e(Cs),i=e(Ns),o=e(xs),a=Rs(s);if(!(await Ks("node:path")).isAbsolute(o))throw new Error(`${xs} must be an absolute path`);if(Es(n)!==r||a.appId!==r||a.ownerUserId!==i||Ts(r,i)!==s)throw new Error("AppService identity environment variables are inconsistent");const c=Vs(this.config.appId),l=Vs(this.config.appDid),u=Vs(this.config.appInstanceId),h=this.getOwnerUserId(),d=Vs(this.config.dataDir);if(c&&c!==r)throw new Error(`runtime appId ${c} does not match ${Os} ${r}`);if(l&&l!==n)throw new Error(`runtime appDid ${l} does not match ${Is} ${n}`);if(u&&u!==s)throw new Error(`runtime appInstanceId ${u} does not match ${Cs} ${s}`);if(h&&h!==i)throw new Error(`runtime ownerUserId ${h} does not match ${Ns} ${i}`);if(d&&d!==o)throw new Error(`runtime dataDir ${d} does not match ${xs} ${o}`);this.config.appDid=n,this.config.appId=r,this.config.appInstanceId=s,this.config.ownerUserId=i,this.config.userid=i,this.config.dataDir=o}async resolveZoneHostFromLocalConfig(){if(!Ls())return;if(Vs(this.config.zoneHost))return;const t=await this.getPrivateKeySearchRoots(),e=await this.tryResolveZoneHostFromSearchRoots(t);e&&(this.config.zoneHost=e)}validateSessionToken(){if(!this.sessionToken)return;const t=Hs(this.sessionToken);if("AppService"===this.config.runtimeType&&!t)throw new Error("AppService session token must be a JWT with identity claims");const e="string"==typeof(null==t?void 0:t.appid)?t.appid:"string"==typeof(null==t?void 0:t.aud)?t.aud:null;if(e&&e!==this.config.appId)throw new Error(`session token appid mismatch: ${e} != ${this.config.appId}`);if("AppService"===this.config.runtimeType&&t){const e=this.getAppInstanceId();if(!e||t.app_instance_id!==e)throw new Error(`session token app_instance_id mismatch: ${String(t.app_instance_id)} != ${String(e)}`);const n=this.getOwnerUserId();if(!n||t.app_owner_user_id!==n)throw new Error(`session token app_owner_user_id mismatch: ${String(t.app_owner_user_id)} != ${String(n)}`)}}async ensureBrowserSessionToken(){const t=Hs(this.sessionToken);return this.sessionToken&&t&&!this.needsRenew(t)?this.sessionToken:this.refreshBrowserSessionToken()}normalizeBrowserUserInfo(t){if(!t||"object"!=typeof t||Array.isArray(t))return null;const e=t,n="string"==typeof e.user_id?e.user_id.trim():"",r="string"==typeof e.user_type?e.user_type.trim():"",s="string"==typeof e.user_name?e.user_name.trim():"string"==typeof e.show_name?e.show_name.trim():"";return n&&r?{user_name:s||n,user_id:n,user_type:r}:null}async refreshBrowserSession(){return await this.refreshBrowserSessionToken()&&Ms()?Mn.getBrowserUserInfo():null}async logoutBrowserSSO(){if(("Browser"===this.config.runtimeType||"AppRuntime"===this.config.runtimeType)&&Fs())try{const t=await fetch("/sso_logout",{method:"POST",credentials:"include",cache:"no-store",keepalive:!0});t.ok||console.warn("BuckyOS browser sso_logout failed:",t.status)}catch(t){console.warn("BuckyOS browser sso_logout failed:",t)}}async refreshBrowserSessionToken(){if(this.browserRefreshPromise)return this.browserRefreshPromise;const t=this.authStateRevision,e=this.requestBrowserSessionToken(t);this.browserRefreshPromise=e;try{return await e}finally{this.browserRefreshPromise===e&&(this.browserRefreshPromise=null)}}async requestBrowserSessionToken(t){if(!Fs())return this.sessionToken;const e=Ms()?Mn.getBrowserUserInfo():null;try{const n=await fetch("/sso_refresh",{method:"POST",credentials:"include",cache:"no-store"});if(!n.ok)return t===this.authStateRevision&&(this.sessionToken=null),null;const r=await n.json(),s=Vs("string"==typeof r.access_token?r.access_token:"string"==typeof r.session_token?r.session_token:null),i=this.normalizeBrowserUserInfo(r.user_info)??e;return s&&i?t!==this.authStateRevision?null:(this.sessionToken=s,this.refreshToken=null,Mn.saveBrowserUserInfo(i),this.validateSessionToken(),this.sessionToken):(t===this.authStateRevision&&(this.sessionToken=null),null)}catch(n){return console.warn("BuckyOS browser sso_refresh failed:",n),t===this.authStateRevision&&(this.sessionToken=null),null}}usesBrowserSessionRefresh(){return"Browser"===this.config.runtimeType||"AppRuntime"===this.config.runtimeType}needsRenew(t){if(t.iss&&"verify-hub"!==t.iss)return!0;if("number"!=typeof t.exp)return!1;return Math.floor(Date.now()/1e3)>=t.exp-30}startAutoRenewIfNeeded(){const t=this.usesBrowserSessionRefresh();if(!t&&!this.profile.supportsManagedSessionRenewal()||!1===this.config.autoRenew)return;if(this.renewTimer)return;const e=this.config.renewIntervalMs??5e3,n=async()=>{try{if(t){await this.ensureBrowserSessionToken()||this.stopAutoRenew()}else await this.renewTokenFromVerifyHub()}catch(e){console.warn("BuckyOS token renew failed:",e)}};this.renewTimer=setInterval((()=>{n()}),e),n()}loadAppServiceSessionTokenFromEnv(){const t=Vs(Us()[Ps]);if(t)return t;throw new Error(`${Ps} is required for AppService runtime`)}loadAppClientSessionTokenFromEnv(){return Vs(Us().BUCKYOS_APPCLIENT_SESSION_TOKEN)}async createAppClientSessionToken(){if(!Ls())throw new Error("AppClient mode requires Node.js");const t=await this.loadLocalSigningMaterial(),e=Math.floor(Date.now()/1e3),n={token_type:"Normal",appid:this.config.appId,jti:String(e),session:e,sub:t.subject,userid:t.subject,iss:t.issuer,exp:e+900,extra:{}};return this.signJwtWithEd25519({alg:"EdDSA",kid:t.issuer},n,t.keyPem)}async loadLocalSigningMaterial(){await Ks("node:fs/promises");const t=await Ks("node:path"),e=this.getOwnerUserId();if(!e){const e=await this.getBuckyOSEtcDir(),n=await this.readDeviceNameFromNodeIdentityPath(t.join(e,"node_identity.json"));if(!n)throw new Error(`failed to resolve userid from ${t.join(e,"node_identity.json")} device_mini_doc_jwt`);const r=await this.readPemFile(t.join(e,"node_private_key.pem"));if(!r)throw new Error(`failed to load node_private_key.pem from ${e}`);return this.config.userid=n,this.config.ownerUserId=n,{keyPem:r,issuer:n,subject:n,sourcePath:t.join(e,"node_private_key.pem")}}const n=await this.getPrivateKeySearchRoots(),r=await this.tryLoadDeviceSigningMaterial(e,n);if(r)return r;const s=await this.tryLoadUserSigningMaterial(e,n);if(s)return s;throw new Error(`failed to find AppClient private key for userid=${e} in search roots: ${n.join(", ")}`)}async getPrivateKeySearchRoots(){var t;const e=Us(),n=await Ks("node:path"),r=await Ks("node:os"),s=[];for(const c of this.config.privateKeySearchPaths??[]){const t=Vs(c);t&&s.push(t)}const i=Vs(e.BUCKYOS_APP_CLIENT_DIR);i&&s.push(i);const o=Vs(e.HOME)??Vs(e.USERPROFILE)??Vs(null==(t=r.homedir)?void 0:t.call(r));o&&(s.push(n.join(o,".buckyos")),s.push(n.join(o,".buckycli")));const a=Vs(this.config.rootDir)??Vs(e.BUCKYOS_ROOT)??"/opt/buckyos";return s.push(a),s.push(n.join(a,"etc")),Array.from(new Set(s))}async getBuckyOSRootDir(){const t=Us();return Vs(this.config.rootDir)??Vs(t.BUCKYOS_ROOT)??"/opt/buckyos"}async getBuckyOSEtcDir(){return(await Ks("node:path")).join(await this.getBuckyOSRootDir(),"etc")}async readPemFile(t){const e=await Ks("node:fs/promises");try{return(await e.readFile(t,"utf8")).trim()||null}catch{return null}}async readNodeIdentityMetadata(t){const e=await Ks("node:fs/promises");try{const n=await e.readFile(t,"utf8"),r=JSON.parse(n);return{deviceName:this.extractDeviceNameFromIdentityPayload(r),deviceDid:"string"==typeof r.device_did&&r.device_did.trim()||null,zoneDid:"string"==typeof r.zone_did&&r.zone_did.trim()||null,zoneName:"string"==typeof r.zone_name&&r.zone_name.trim()||null}}catch{return null}}extractDeviceNameFromIdentityPayload(t){const e="string"==typeof t.device_name?t.device_name.trim():"";if(e)return e;const n=Hs("string"==typeof t.device_mini_doc_jwt?t.device_mini_doc_jwt:null),r="string"==typeof(null==n?void 0:n.n)?n.n.trim():"";if(r)return r;const s=Hs("string"==typeof t.device_doc_jwt?t.device_doc_jwt:null);for(const i of["name","sub"]){const t=null==s?void 0:s[i],e="string"==typeof t?t.trim():"";if(e)return e}return null}async readDeviceNameFromNodeIdentityPath(t){const e=await this.readNodeIdentityMetadata(t);return(null==e?void 0:e.deviceName)??null}async tryLoadDeviceSigningMaterial(t,e){const n=await Ks("node:path"),r=[await this.getBuckyOSEtcDir(),...e.filter((t=>!t.endsWith(".pem")))];for(const s of Array.from(new Set(r))){const e=await this.readNodeIdentityMetadata(n.join(s,"node_identity.json")),r=(null==e?void 0:e.deviceName)??null;if(r&&r===t)for(const t of await this.deviceKeyPathCandidates(s,(null==e?void 0:e.deviceDid)??null)){const e=await this.readPemFile(t);if(e)return{keyPem:e,issuer:r,subject:r,sourcePath:t}}}return null}async deviceKeyPathCandidates(t,e){const n=await Ks("node:path"),r=[];if(e)try{const s=Mn.DID.fromStr(e).toFilename(),i="authentication.private.pem";r.push(n.join(t,"security",s,i));const o=Us(),a=Vs(o.BUCKYOS_SECURITY_ROOT)??n.join(Vs(o.BUCKYOS_ROOT)??"/opt/buckyos","security");r.push(n.join(a,s,i))}catch{}return r.push(n.join(t,"node_private_key.pem")),r}async tryLoadUserSigningMaterial(t,e){var n;const r=await Ks("node:fs/promises"),s=await Ks("node:path");for(const i of e){const e=i.endsWith(".pem")?i:s.join(i,"user_private_key.pem"),o=i.endsWith(".pem")?s.dirname(i):i,a=s.join(o,"user_config.json");try{const s=await r.readFile(a,"utf8"),i=Mn.parseBuckyOSOwnerDocument(JSON.parse(s)),o=null==(n=null==i?void 0:i.name)?void 0:n.trim();if(!o||o!==t)continue;const c=await this.readPemFile(e);if(!c)continue;return{keyPem:c,issuer:t,subject:t,sourcePath:e}}catch{}}return null}async tryResolveDeviceNameFromSearchRoots(t){const e=await Ks("node:path"),n=Us(),r=Vs(n.BUCKYOS_THIS_DEVICE_NAME);if(r)return r;for(const s of["BUCKYOS_THIS_DEVICE","BUCKYOS_THIS_DEVICE_INFO"]){const t=Vs(n[s]);if(t)try{const e=JSON.parse(t);if("string"==typeof e.name&&e.name.trim().length>0)return e.name.trim()}catch{}}for(const s of t){const t=e.join(s,"node_identity.json"),n=await this.readDeviceNameFromNodeIdentityPath(t);if(n)return n}return null}async tryResolveZoneHostFromSearchRoots(t){var e;const n=await Ks("node:fs/promises"),r=await Ks("node:path"),s=Vs(Us().BUCKYOS_ZONE_HOST);if(s)return s;for(const i of t){const t=r.join(i,"node_identity.json"),e=await this.readNodeIdentityMetadata(t);if(e){if(e.zoneName)return e.zoneName;if(e.zoneDid)return Ws(e.zoneDid)}}for(const i of t){const t=r.join(i,"user_config.json");try{const r=await n.readFile(t,"utf8"),s=Mn.parseBuckyOSOwnerDocument(JSON.parse(r)),i=Ws(null==(e=null==s?void 0:s.binded_zone_list)?void 0:e[0]);if(!i)continue;return i}catch{}}return null}getMySettingsPath(){return this.profile.getMySettingsPath(this)}getConfiguredSystemConfigServiceUrl(){return Vs(this.config.systemConfigServiceUrl)}resolveAppServiceGatewayHost(){return Vs(Us().BUCKYOS_HOST_GATEWAY)??"host.docker.internal"}async signJwtWithEd25519(t,e,n){const r=await Ks("node:crypto"),s=Gs(),i=`${js(JSON.stringify(t))}.${js(JSON.stringify(e))}`;return`${i}.${js(r.sign(null,s.from(i,"utf8"),r.createPrivateKey({key:n,format:"pem"})))}`}}const ti=1048576;class ei extends Error{constructor(t,e){super(e),this.name="KEventProtocolError",this.code=t}}const ni=async(t,e)=>{if("function"!=typeof fetch)throw new Error("fetch is not available in this runtime");return fetch(t,e)};function ri(){var t;const e=globalThis.process;return Boolean(null==(t=null==e?void 0:e.versions)?void 0:t.node)}function si(t){const e=(Array.isArray(t)?t:[t]).map((t=>"string"==typeof t?t.trim():"")).filter((t=>t.length>0));if(0===e.length)throw new Error("kevent patterns must not be empty");for(const n of e)if(!n.startsWith("/"))throw new Error(`kevent only supports global patterns: ${n}`);return e}function ii(t,e){return(null==e?void 0:e.aborted)?Promise.reject(new Error("Operation aborted")):new Promise(((n,r)=>{const s=setTimeout((()=>{o(),n()}),t),i=()=>{clearTimeout(s),o(),r(new Error("Operation aborted"))},o=()=>{e&&e.removeEventListener("abort",i)};e&&e.addEventListener("abort",i,{once:!0})}))}function oi(t){return t instanceof Error?t.message:String(t)}function ai(t){if("ok"===t.status)return t;throw new ei(t.code||"INTERNAL",t.message||"Unknown kevent error")}function ci(t){if(!t||"object"!=typeof t||Array.isArray(t))throw new Error("Invalid kevent event payload");const e=t;if("string"!=typeof e.eventid||"string"!=typeof e.source_node||"number"!=typeof e.source_pid||"number"!=typeof e.timestamp)throw new Error("Invalid kevent event payload");return{eventid:e.eventid,source_node:e.source_node,source_pid:e.source_pid,ingress_node:"string"==typeof e.ingress_node?e.ingress_node:null,timestamp:e.timestamp,data:"data"in e?e.data:null}}class li{constructor(){this.items=[],this.waiters=[],this.closed=!1}push(t){if(this.closed)return;const e=this.waiters.shift();if(e)return e.timeout&&clearTimeout(e.timeout),void e.resolve(t);this.items.push(t)}async shift(t){return this.items.length>0?this.items.shift()??null:this.closed||0===t?null:new Promise((e=>{const n={resolve:t=>{r(),e(t)},timeout:null},r=()=>{n.timeout&&(clearTimeout(n.timeout),n.timeout=null);const t=this.waiters.indexOf(n);t>=0&&this.waiters.splice(t,1)};"number"==typeof t&&t>0&&(n.timeout=setTimeout((()=>{r(),e(null)}),t)),this.waiters.push(n)}))}close(){if(!this.closed)for(this.closed=!0;this.waiters.length>0;){const t=this.waiters.shift();t&&(t.timeout&&clearTimeout(t.timeout),t.resolve(null))}}}class ui{constructor(){this.queue=new li,this.closed=!1,this.closePromise=null}async pullEvent(t){return this.queue.shift(t)}async pull_event(t){return this.pullEvent(t)}enqueue(t){this.queue.push(t)}isClosed(){return this.closed}markClosed(){this.closed=!0,this.queue.close()}async close(){return this.closePromise||(this.markClosed(),this.closePromise=this.closeTransport().catch((t=>{console.warn("kevent reader close failed:",t)})).then((()=>{}))),this.closePromise}}class hi extends ui{constructor(t,e,n,r,s,i){super(),this.streamUrl=t,this.patterns=e,this.keepaliveMs=n,this.fetcher=r,this.sessionTokenProvider=s,this.streamTask=null,this.controller=new AbortController,this.readyPromise=this.start(),i&&(i.aborted?this.controller.abort():i.addEventListener("abort",(()=>{this.controller.abort()}),{once:!0}))}async waitUntilReady(){await this.readyPromise}async start(){const t={"Content-Type":"application/json"};if(this.sessionTokenProvider){const e=await this.sessionTokenProvider();"string"==typeof e&&e.trim().length>0&&(t.Authorization=`Bearer ${e.trim()}`)}const e=await this.fetcher(this.streamUrl,{method:"POST",headers:t,body:JSON.stringify({patterns:this.patterns,keepalive_ms:this.keepaliveMs}),cache:"no-store",credentials:"include",signal:this.controller.signal});if(!e.ok){let t="";try{t=await e.text()}catch{t=""}throw new Error(`kevent stream request failed: ${e.status}${t?` ${t}`:""}`)}if(!e.body)throw new Error("kevent stream response missing body");let n=!1,r=null,s=null;const i=new Promise(((t,e)=>{r=t,s=e}));this.streamTask=this.consumeStream(e.body,(t=>{if("ack"===t.type)return n=!0,void(null==r||r());if("event"!==t.type){if("error"===t.type){const e=new Error(t.error||"kevent stream error");n?console.warn("kevent stream error:",e.message):null==s||s(e)}}else this.enqueue(ci(t.event))})).then((()=>{n||null==s||s(new Error("kevent stream closed before ack"))})).catch((t=>{n?this.controller.signal.aborted||console.warn("kevent browser stream stopped with error:",t):null==s||s(t instanceof Error?t:new Error(oi(t)))})).finally((()=>{this.markClosed()})),await i}async consumeStream(t,e){const n=t.getReader(),r=new TextDecoder;let s="";try{for(;!this.controller.signal.aborted;){const{value:t,done:i}=await n.read();if(i)break;s+=r.decode(t,{stream:!0}),s=this.processFrameBuffer(s,e)}s+=r.decode(),s=this.processFrameBuffer(s,e),s.trim().length>0&&this.handleFrameLine(s,e)}finally{try{await n.cancel()}catch{}}}processFrameBuffer(t,e){let n=t;for(;;){const t=n.indexOf("\n");if(t<0)return n;const r=n.slice(0,t);n=n.slice(t+1),this.handleFrameLine(r,e)}}handleFrameLine(t,e){const n=t.trim();if(!n)return;e(JSON.parse(n))}async closeTransport(){if(this.controller.abort(),this.streamTask)try{await this.streamTask}catch(t){this.controller.signal.aborted||console.warn("kevent browser stream stopped with error:",t)}}}class di{constructor(t,e,n,r){this.host=t,this.port=e,this.connectTimeoutMs=n,this.connector=r,this.socket=null,this.connectPromise=null,this.closed=!1,this.serial=Promise.resolve(),this.readBuffer=new Uint8Array(0),this.pending=[]}async call(t){const e=this.serial.then((()=>this.callInternal(t)));return this.serial=e.then((()=>{}),(()=>{})),e}async close(){if(this.closed=!0,this.rejectAllPending(new Error("kevent native connection closed")),this.socket){const t=this.socket;this.socket=null,t.end()}}async callInternal(t){if(this.closed)throw new Error("kevent native connection is closed");await this.ensureConnected();const e=this.socket;if(!e)throw new Error("kevent native socket is not connected");const n=(new TextEncoder).encode(JSON.stringify(t));if(0===n.length||n.length>ti)throw new Error(`invalid kevent native request payload size: ${n.length}`);const r=new Uint8Array(4+n.length);return new DataView(r.buffer).setUint32(0,n.length),r.set(n,4),new Promise(((t,n)=>{const s={resolve:t,reject:n};this.pending.push(s),e.write(r,(t=>{if(!t)return;const e=this.pending.indexOf(s);e>=0&&this.pending.splice(e,1),n(t instanceof Error?t:new Error(oi(t)))}))}))}async ensureConnected(){this.socket||(this.connectPromise||(this.connectPromise=this.connect().finally((()=>{this.connectPromise=null}))),await this.connectPromise)}async connect(){const t=await this.connector(this.host,this.port,this.connectTimeoutMs);this.socket=t,"function"==typeof t.setNoDelay&&t.setNoDelay(!0),t.on("data",(t=>{try{this.handleSocketData(function(t){if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);throw new Error("Unsupported socket data chunk")}(t))}catch(e){this.handleSocketFailure(e instanceof Error?e:new Error(oi(e)))}})),t.once("end",(()=>{this.handleSocketFailure(new Error("kevent native socket ended"))})),t.once("close",(()=>{this.handleSocketFailure(new Error("kevent native socket closed"))})),t.once("error",(t=>{this.handleSocketFailure(t)}))}handleSocketData(t){for(this.readBuffer=function(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}(this.readBuffer,t);this.readBuffer.length>=4;){const t=new DataView(this.readBuffer.buffer,this.readBuffer.byteOffset,this.readBuffer.byteLength).getUint32(0);if(0===t||t>ti)throw new Error(`invalid kevent native frame length: ${t}`);if(this.readBuffer.length<4+t)return;const e=this.readBuffer.slice(4,4+t);this.readBuffer=this.readBuffer.slice(4+t);const n=JSON.parse((new TextDecoder).decode(e)),r=this.pending.shift();r&&r.resolve(n)}}handleSocketFailure(t){if(this.socket){const e=this.socket;this.socket=null;try{e.destroy(t)}catch{}}this.closed||this.rejectAllPending(t)}rejectAllPending(t){for(;this.pending.length>0;){const e=this.pending.shift();null==e||e.reject(t)}}}class fi extends ui{constructor(t,e){super(),this.client=t,this.readerId=e}static async create(t,e){const n=new di(e.nativeHost,e.nativePort,e.nativeConnectTimeoutMs,e.nativeConnector),r=`ts_kevent_${Date.now()}_${Math.random().toString(36).slice(2,10)}`;try{return ai(await n.call({op:"register_reader",reader_id:r,patterns:t})),new fi(n,r)}catch(s){throw await n.close(),s}}async pullEvent(t){if(this.isClosed())return null;const e=ai(await this.client.call({op:"pull_event",reader_id:this.readerId,timeout_ms:"number"==typeof t?Math.max(0,Math.floor(t)):void 0}));return e.event?ci(e.event):null}async closeTransport(){try{ai(await this.client.call({op:"unregister_reader",reader_id:this.readerId}))}catch(t){t instanceof Error&&/closed/i.test(t.message)||console.warn("kevent unregister failed:",t)}finally{await this.client.close()}}}async function pi(t,e,n){if(!ri())throw new Error("native kevent requires Node.js");const r=await async function(t){return ri()&&"function"==typeof require?require(t):Function("name","return import(name)")(t)}("node:net");return new Promise(((s,i)=>{const o=r.createConnection({host:t,port:e});let a=!1;const c=setTimeout((()=>{if(!a){a=!0,h();try{o.destroy(new Error(`kevent native connect timeout after ${n}ms`))}catch{}i(new Error(`kevent native connect timeout after ${n}ms`))}}),n),l=()=>{a||(a=!0,h(),s(o))},u=t=>{if(!a){a=!0,h();try{o.destroy(t)}catch{}i(t)}},h=()=>{clearTimeout(c),"function"==typeof o.off?(o.off("connect",l),o.off("error",u)):"function"==typeof o.removeListener&&(o.removeListener("connect",l),o.removeListener("error",u))};o.once("connect",l),o.once("error",u)}))}class gi{constructor(t){this.mode=t.mode,this.streamUrl=`${(t.streamUrl??"/kapi/kevent").replace(/\/+$/,"")}/stream`,this.nativeHost=t.nativeHost??"127.0.0.1",this.nativePort=t.nativePort??3183,this.nativeConnectTimeoutMs=t.nativeConnectTimeoutMs??5e3,this.fetcher=t.fetcher??ni,this.sessionTokenProvider=t.sessionTokenProvider??null,this.nativeConnector=t.nativeConnector??pi}async createEventReader(t,e={}){const n=si(t);if("browser"===this.mode){const t=new hi(this.streamUrl,n,"number"!=typeof(r=e.keepaliveMs)||!Number.isFinite(r)||r<=0?15e3:Math.floor(r),this.fetcher,this.sessionTokenProvider,e.signal);try{return await t.waitUntilReady(),t}catch(s){throw await t.close(),s}}var r;return fi.create(n,{nativeHost:this.nativeHost,nativePort:this.nativePort,nativeConnectTimeoutMs:this.nativeConnectTimeoutMs,nativeConnector:this.nativeConnector})}async create_event_reader(t,e={}){return this.createEventReader(t,e)}async subscribe(t,e,n={}){const r=si(t),s=new AbortController,i="number"==typeof n.reconnectDelayMs&&n.reconnectDelayMs>=0?Math.floor(n.reconnectDelayMs):1e3;let o=null,a=!1;n.signal&&(n.signal.aborted?(s.abort(),a=!0):n.signal.addEventListener("abort",(()=>{s.abort()}),{once:!0}));const c=(async()=>{for(;!a&&!s.signal.aborted;){try{for(o=await this.createEventReader(r,{...n,signal:s.signal});!a&&!s.signal.aborted;){const n=await o.pullEvent();if(!n)break;try{await e(n)}catch(t){console.error("kevent callback failed:",t)}}}catch(t){a||s.signal.aborted||console.warn("kevent subscription disconnected, will retry:",t)}finally{const t=o;o=null,t&&await t.close()}if(a||s.signal.aborted)break;try{await ii(i,s.signal)}catch{break}}})();return{close:async()=>{if(a)return;a=!0,s.abort();const t=o;o=null,t&&await t.close(),await c.catch((()=>{}))}}}}const mi={runtime:null};function yi(){if("undefined"==typeof window)return null;const t=window.BuckyApi;return t&&"object"==typeof t?t:null}async function wi(){const t=yi(),e=null==t?void 0:t.getCurrentUser;if("function"!=typeof e)return null;const n=await e.call(t);return 0===(null==n?void 0:n.code)?n.data??null:(console.error("BuckyApi.getCurrentUser failed: ",null==n?void 0:n.message),null)}async function bi(t,e=null){const n=yi(),r=null==n?void 0:n.resolve_did;if("function"!=typeof r)return null;const s=await r.call(n,t,e);return 0===(null==s?void 0:s.code)&&function(t){if(!t||"object"!=typeof t)return!1;const e=t;return"json"===e.type&&Object.prototype.hasOwnProperty.call(e,"value")||"jwt"===e.type&&"string"==typeof e.jwt}(s.data)?s.data:(console.error("BuckyApi.resolve_did failed: ",null==s?void 0:s.message),null)}function Ai(){return"undefined"!=typeof window}function _i(){const t=globalThis.process;return(null==t?void 0:t.env)??{}}function vi(t){if("string"!=typeof t)return null;const e=t.trim();return e.length>0?e:null}function Ei(){return"undefined"!=typeof localStorage}function ki(t){return t?t.split(/[./]/).map((t=>t.trim())).filter((t=>t.length>0)):[]}function Si(){return vi(_i().BUCKYOS_APP_INSTANCE_ID)?Ds.AppService:Ds.AppClient}function Ti(){var t;return(null==(t=mi.runtime)?void 0:t.getConfig().runtimeType)??function(){var t;if("undefined"!=typeof window)return window.BuckyApi?Ds.AppRuntime:Ds.Browser;const e=globalThis.process;return(null==(t=null==e?void 0:e.versions)?void 0:t.node)?Ds.NodeJS:Ds.Unknown}()}function Ri(){var t;const e=mi.runtime;return e?function(t){try{const e="undefined"!=typeof window?window.location.origin:"http://localhost";return new URL(t,e).origin}catch{return null}}(e.getSystemConfigServiceURL()):"undefined"!=typeof window&&(null==(t=window.location)?void 0:t.origin)?window.location.origin:null}async function Ii(){const t=mi.runtime;return t?t.ensureSessionTokenReady():null}class Oi{constructor(t){this.currentRuntime=null,this.currentAccountInfo=null,this.currentKEventClient=null,this.target=t}async initBuckyOS(t="",e=null){var n;const r=this.buildRuntimeConfig(t,e);if("node"!==this.target&&Ai()&&!e){localStorage.removeItem("zone_host_name");let e=localStorage.getItem("zone_host_name_v2");e||(e=await this.tryGetZoneHostName(t,window.location.host,r.defaultProtocol),localStorage.setItem("zone_host_name_v2",e)),r.zoneHost=e}var s;null==(n=this.currentRuntime)||n.stopAutoRenew(),this.currentKEventClient=null,this.currentAccountInfo=null,this.currentRuntime=new Xs(r),await this.currentRuntime.initialize(),s=this.currentRuntime,mi.runtime=s,this.syncCurrentAccountInfoFromRuntime()}getBuckyOSConfig(){var t;return(null==(t=this.currentRuntime)?void 0:t.getConfig())??null}getRuntimeType(){return this.currentRuntime?this.currentRuntime.getConfig().runtimeType:this.detectEnvironmentRuntimeType()}getAppId(){return this.currentRuntime?this.currentRuntime.getAppId():(console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),null)}getAppDid(){var t;return(null==(t=this.currentRuntime)?void 0:t.getAppDid())??null}getAppInstanceId(){var t;return(null==(t=this.currentRuntime)?void 0:t.getAppInstanceId())??null}getAppDataDir(){var t;return(null==(t=this.currentRuntime)?void 0:t.getDataDir())??null}attachEvent(t,e){}removeEvent(t){}getKEventClient(){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");if(this.currentKEventClient)return this.currentKEventClient;const t=this.currentRuntime.getConfig().runtimeType,e=t===Ds.Browser||t===Ds.AppRuntime?"browser":"native";return this.currentKEventClient=new gi({mode:e,streamUrl:this.currentRuntime.getZoneServiceURL("kevent"),sessionTokenProvider:this.currentRuntime.ensureSessionTokenReady.bind(this.currentRuntime)}),this.currentKEventClient}async createEventReader(t,e={}){return this.getKEventClient().createEventReader(t,e)}async create_event_reader(t,e={}){return this.createEventReader(t,e)}async subscribeKEvent(t,e,n={}){return this.getKEventClient().subscribe(t,e,n)}async getAccountInfo(){if(null==this.currentRuntime)return console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),null;this.syncCurrentAccountInfoFromRuntime();const t=this.currentRuntime.getConfig().runtimeType;if(t!==Ds.Browser&&t!==Ds.AppRuntime)return this.currentAccountInfo;const e=await this.currentRuntime.ensureSessionTokenReady(),n=Ei()?Mn.getBrowserUserInfo():null;return e&&n?(this.currentAccountInfo={user_name:n.user_name,user_id:n.user_id,user_type:n.user_type,session_token:e,refresh_token:void 0},this.currentAccountInfo):(this.currentAccountInfo=null,null)}async loginByPassword(t,e,n){var r,s,i;const o=this.getAppId();if(null==o)return console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),null;const a=n??(null==(r=this.currentRuntime)?void 0:r.getAuthTarget());if(!a)throw new Error("loginByPassword requires an AuthTarget");const c=Kn(a);if(c!==o)throw new Error(`auth target appid mismatch: ${c} != ${o}`);const l=Date.now(),u=Mn.hashPassword(t,e,l);Ei()&&localStorage.removeItem(`buckyos.account_info.${o}`);try{const e=this.getVerifyHubClient();e.setSeq(l);const n=await e.loginByPassword({username:t,password:u,target:a,login_nonce:l,source_url:"undefined"!=typeof window?window.location.href:void 0}),r=zn.normalizeLoginResponse(n),c={user_name:r.user_name,user_id:r.user_id,user_type:r.user_type,session_token:r.session_token,refresh_token:r.refresh_token};return Ei()&&(Mn.saveLocalAccountInfo(o,c),Mn.saveBrowserUserInfo({user_name:c.user_name,user_id:c.user_id,user_type:r.user_type})),this.currentAccountInfo=c,null==(s=this.currentRuntime)||s.setSessionToken(c.session_token),null==(i=this.currentRuntime)||i.setRefreshToken(c.refresh_token??null),c}catch(h){throw console.error("login failed: ",h),h}}async loginByRuntimeSession(){const t=this.currentRuntime;return null==t?(console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),null):(await t.login(),this.syncCurrentAccountInfoFromRuntime(),this.currentAccountInfo)}async loginByBrowserSSO(){if(null==this.currentRuntime)return void console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first");const t=this.getAppId();if(null==t)return void console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first");Ei()&&Mn.cleanLocalAccountInfo(t);const e=this.getZoneHostName();if(null!=e)try{const t=new Vn(e);await t.login()}catch(n){throw console.error("login failed: ",n),n}else console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first")}async login(){return this.usesRuntimeManagedSession()?this.loginByRuntimeSession():(await this.loginByBrowserSSO(),this.currentAccountInfo)}logout(t=!0){if(null==this.currentRuntime)return void console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first");const e=this.getAppId();null!=e?(t&&this.currentRuntime.logoutBrowserSSO(),t&&Ei()&&Mn.cleanLocalAccountInfo(e),this.currentAccountInfo=null,this.currentKEventClient=null,this.currentRuntime.clearAuthState()):console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first")}async getAppSetting(t=null){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return function(t,e){const n=ki(e);if(0===n.length)return t;let r=t;for(const s of n){if(!r||"object"!=typeof r||Array.isArray(r)||!(s in r))return;r=r[s]}return r}(await this.currentRuntime.getMySettings(),t)}async setAppSetting(t=null,e){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");const n=await this.currentRuntime.getMySettings(),r=function(t,e,n){const r=ki(e);if(0===r.length){if(!n||"object"!=typeof n||Array.isArray(n))throw new Error("settingValue must be a JSON object when settingName is null");return n}const s=Array.isArray(t)?{}:{...t};let i=s;for(let o=0;o<r.length-1;o+=1){const t=r[o],e=i[t],n=e&&"object"==typeof e&&!Array.isArray(e)?{...e}:{};i[t]=n,i=n}return i[r[r.length-1]]=n,s}(n&&"object"==typeof n&&!Array.isArray(n)?{...n}:{},t,function(t){try{return JSON.parse(t)}catch{return t}}(e));await this.currentRuntime.updateAllMySettings(r)}getCurrentWalletUser(){if("undefined"==typeof window)throw new Error("BuckyApi is only available in browser runtime");return wi()}resolve_did(t,e=null){if("undefined"==typeof window)throw new Error("BuckyApi is only available in browser runtime");return bi(t,e)}walletSignWithActiveDid(t){if("undefined"==typeof window)throw new Error("BuckyApi is only available in browser runtime");return(async()=>{var e,n;const r=await window.BuckyApi.signJsonWithActiveDid(t);return 0===r.code?{signatures:Array.isArray(null==(e=r.data)?void 0:e.signatures)?r.data.signatures:[],pwd_hash:"string"==typeof(null==(n=r.data)?void 0:n.pwd_hash)?r.data.pwd_hash:null}:(console.error("BuckyApi.signWithActiveDid failed: ",r.message),null)})()}async openExternalUrl(t){if("undefined"==typeof window)throw new Error("openExternalUrl is only available in browser runtime");const e=window.BuckyApi;"function"!=typeof(null==e?void 0:e.openExternalUrl)?window.open(t,"_blank","noopener,noreferrer"):await e.openExternalUrl(t)}getZoneHostName(){return null==this.currentRuntime?(console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),null):this.currentRuntime.getZoneHostName()}getZoneServiceURL(t){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return this.currentRuntime.getZoneServiceURL(t)}getServiceRpcClient(t){if(null==this.currentRuntime)throw console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return this.syncCurrentAccountInfoFromRuntime(),this.currentRuntime.getServiceRpcClient(t)}getVerifyHubClient(){if(null==this.currentRuntime)throw console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return this.currentRuntime.getVerifyHubClient()}getSystemConfigClient(){if(null==this.currentRuntime)throw console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return this.currentRuntime.getSystemConfigClient()}getTaskManagerClient(){if(null==this.currentRuntime)throw console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return this.currentRuntime.getTaskManagerClient()}getWorkflowClient(){if(null==this.currentRuntime)throw console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return this.currentRuntime.getWorkflowClient()}getAiccClient(){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return this.currentRuntime.getAiccClient()}getMsgQueueClient(){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return this.currentRuntime.getMsgQueueClient()}getMsgCenterClient(){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return this.currentRuntime.getMsgCenterClient()}getRepoClient(){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return this.currentRuntime.getRepoClient()}buildRuntimeConfig(t,e){if(e){let n=e.runtimeType;return n===Ds.NodeJS&&"browser"!==this.target&&(n=Si()),{...Bs,...e,appId:e.appId||t,runtimeType:n}}return"browser"===this.target?{...Bs,appId:t,runtimeType:this.detectEnvironmentRuntimeType(),defaultProtocol:"undefined"!=typeof window?window.location.protocol+"//":"http://"}:"node"===this.target?{...Bs,appId:t,runtimeType:Si(),defaultProtocol:"https://",zoneHost:vi(_i().BUCKYOS_ZONE_HOST)??""}:Ai()?{...Bs,appId:t,runtimeType:this.detectEnvironmentRuntimeType(),defaultProtocol:window.location.protocol+"//"}:{...Bs,appId:t,runtimeType:Si(),defaultProtocol:"https://",zoneHost:vi(_i().BUCKYOS_ZONE_HOST)??""}}async tryGetZoneHostName(t,e,n){const r=await this.fetchZoneHostFromIdentifierDoc(n+e+"/1.0/identifiers/self");if(r)return r;const s=e.split(".").slice(1).join(".");if(!s)return e;const i=await this.fetchZoneHostFromIdentifierDoc(n+s+"/1.0/identifiers/self");return i||e}async fetchZoneHostFromIdentifierDoc(t){try{const e=await fetch(t);if(200!==e.status)return null;const n=await e.json(),r="string"==typeof n.hostname?n.hostname.trim():"";if(r.length>0)return r;if("string"==typeof n.id){const t=n.id.match(/^did:web:([^/?#]+)/);if(t&&t[1])return t[1]}return null}catch{return null}}syncCurrentAccountInfoFromRuntime(){if(null==this.currentRuntime)return;const t=this.currentRuntime.getSessionToken();if(!t)return;const e=Hs(t),n="string"==typeof(null==e?void 0:e.sub)?e.sub:"string"==typeof(null==e?void 0:e.userid)?e.userid:this.currentRuntime.getOwnerUserId()??"root",r="string"==typeof(null==e?void 0:e.user_type)?e.user_type:this.currentRuntime.getConfig().runtimeType===Ds.AppService?"service":void 0;this.currentAccountInfo={user_name:n,user_id:n,user_type:r,session_token:t,refresh_token:this.currentRuntime.getRefreshToken()??void 0}}usesRuntimeManagedSession(){if(null==this.currentRuntime)return!1;const t=this.currentRuntime.getConfig().runtimeType;return t===Ds.AppClient||t===Ds.AppService}detectEnvironmentRuntimeType(){var t,e;if("browser"===this.target)return"undefined"!=typeof window&&window.BuckyApi?Ds.AppRuntime:"undefined"!=typeof window?Ds.Browser:Ds.Unknown;if("node"===this.target){const e=globalThis.process;return(null==(t=null==e?void 0:e.versions)?void 0:t.node)?Si():Ds.Unknown}if("undefined"!=typeof window)return window.BuckyApi?Ds.AppRuntime:Ds.Browser;const n=globalThis.process;return(null==(e=null==n?void 0:n.versions)?void 0:e.node)?Ds.NodeJS:Ds.Unknown}}const Ci="/kapi/bns",Ni="/kapi/bns-indexer",xi="did:bns:",Pi="name.query_state",Di="name.resolve_owner",Bi="authority.get_set",Ui="authority.get_key",Li="document.resolve",Mi="document.get_version",Fi="name.query_by_addr",Gi="tx.query_state",ji="tx.submit_raw",Hi="events.list",Vi="checkpoint.latest",Wi={transport:"RPC_TRANSPORT_ERROR",serialization:"SERIALIZATION_ERROR",invalid_response:"INVALID_RESPONSE",timeout:"TX_WAIT_TIMEOUT"};class Ki extends Error{constructor(t,e,n=null){super(e),this.name="BnsClientError",this.kind=t,this.info=n}get code(){var t;return"registry"===this.kind?(null==(t=this.info)?void 0:t.code)??"UNKNOWN_BNS_ERROR":Wi[this.kind]}isRegistryCode(t){return"registry"===this.kind&&this.code===t}static registry(t){return new Ki("registry",`${t.code}: ${t.message}`,t)}static registryCode(t,e,n={}){return Ki.registry({code:t,message:e,name:null,doc_type:null,expected:null,actual:null,...n})}}class zi extends Error{constructor(t,e){super(`${t}: ${e}`),this.path=t,this.reason=e,this.name="BnsDecodeError"}}function qi(t,e){throw new zi(t,e)}const $i=(t,e)=>"string"==typeof t?t:qi(e,"expected string"),Qi=(t,e)=>"boolean"==typeof t?t:qi(e,"expected boolean"),Ji=(t,e)=>"number"==typeof t&&Number.isInteger(t)&&t>=0?t:qi(e,"expected u64"),Yi=(t,e)=>"number"==typeof t&&Number.isInteger(t)&&t>=0&&t<=4294967295?t:qi(e,"expected u32"),Zi=(t,e)=>{Array.isArray(t)||qi(e,"expected byte array");for(let n=0;n<t.length;n++){const r=t[n];("number"!=typeof r||!Number.isInteger(r)||r<0||r>255)&&qi(`${e}[${n}]`,"expected u8")}return t};function Xi(...t){return(e,n)=>"string"==typeof e&&t.includes(e)?e:qi(n,`expected one of ${t.join("|")}`)}function to(t){return(e,n)=>(Array.isArray(e)||qi(n,"expected array"),e.map(((e,r)=>t(e,`${n}[${r}]`))))}function eo(t,e){const n=(e,n)=>t(e,n);return n.onMissing=e,n}function no(t){return eo(((e,n)=>null===e?null:t(e,n)),(()=>null))}const ro=eo(Ji,(()=>0));function so(t,e){const n=Object.keys(e);return(r,s)=>{(null===r||"object"!=typeof r||Array.isArray(r))&&qi(s,`expected ${t} object`);const i=r,o={};for(const t of n){const n=e[t],r=`${s}.${t}`,a=i[t];if(void 0===a&&!(t in i)){if(n.onMissing){o[t]=n.onMissing();continue}qi(r,"missing field")}o[t]=n(a,r)}return o}}const io=Xi("available","active","expired","released","tombstoned"),oo=Xi("missing","active","revoked","expired","migrated","tombstoned"),ao=Xi("none","alias","migrated_to","canonical"),co=Xi("release_after_grace","tombstone_forever"),lo=Xi("unset","chain_account","bns_name"),uo=Xi("none","asset_owner_fallback","explicit_semantic_owner","parent_inherited"),ho=Xi("missing","active","revoked","expired"),fo=Xi("not_found","pending","succeeded","reverted"),po=so("Principal",{kind:lo,value:$i}),go=so("NameState",{name:$i,asset_owner:$i,semantic_owner:po,effective_owner:po,owner_source:uo,standard_transfer_enabled:Qi,status:io,registered_at:Ji,expire_at:Ji,grace_until:Ji,updated_at:Ji,name_seq:Ji,owner_document_version:Ji,min_document_iat:ro,owner_policy_seq:ro,lineage_epoch:Ji,renewable:Qi,transferable:Qi,allow_delegated_subnames:Qi,namespace_policy_hash:$i,payment_policy_hash:$i,alias_state_hash:$i}),mo=so("OwnerResolution",{effective_owner:po,source:uo,authority_root:$i,authority_seq:Ji}),yo=so("AuthoritySetState",{name:$i,authority_seq:Ji,authority_root:$i,active_key_count:Yi}),wo=so("AuthorityKey",{kid:$i,verification_method:$i,key_data:Zi,purposes:Yi,valid_from:Ji,valid_until:Ji,status:ho,metadata_hash:$i}),bo=so("DocumentRef",{storage_type:$i,uri:$i,inline_document:Zi,content_hash:$i,schema:$i,codec:$i,extra_hash:$i}),Ao=so("DocumentState",{name:$i,doc_type:$i,version:Ji,previous_version:Ji,status:oo,document:bo,controller:po,beneficiary:po,payment_target:$i,valid_from:Ji,expire_at:Ji,revoked_at:Ji,controller_policy_hash:$i,payment_policy_hash:$i,split_policy_hash:$i,price_policy_hash:$i,rights_policy_hash:$i,document_state_hash:$i}),_o=so("ResolveResult",{name_state:go,document_state:Ao,owner:mo,effective_controller:po,status:oo,alias_kind:ao,alias_target_did:$i,proof_root:$i}),vo=so("BnsNamePage",{names:to($i),next_cursor:no($i)}),Eo=so("BnsTxState",{tx_hash:$i,state:fo,block_number:no(Ji),confirmations:Ji}),ko=so("BnsSubmitRawTxResp",{tx_hash:$i}),So=so("LogCheckpoint",{log_root:$i,last_seq:Ji,issued_at:Ji,issuer:po,external_anchor:$i}),To={name_registered:so("name_registered",{name:$i,asset_owner:$i,expire_at:Ji,lineage_epoch:Ji,name_seq:Ji}),name_renewed:so("name_renewed",{name:$i,expire_at:Ji,name_seq:Ji}),name_asset_transferred:so("name_asset_transferred",{name:$i,old_asset_owner:$i,new_asset_owner:$i,standard_transfer:Qi,name_seq:Ji}),name_owner_updated:so("name_owner_updated",{name:$i,owner:po,owner_source:uo,standard_transfer_enabled:Qi,name_seq:Ji}),authority_keys_updated:so("authority_keys_updated",{name:$i,authority_seq:Ji,authority_root:$i}),name_released:so("name_released",{name:$i,mode:co,reason_hash:$i,name_seq:Ji}),document_published:so("document_published",{name:$i,doc_type:$i,version:Ji,content_hash:$i,document_state_hash:$i}),document_revoked:so("document_revoked",{name:$i,doc_type:$i,previous_version:Ji,new_version:Ji,reason_hash:$i}),owner_document_iat_floor_updated:so("owner_document_iat_floor_updated",{name:$i,previous_min_document_iat:Ji,new_min_document_iat:Ji,owner_policy_seq:Ji,name_seq:Ji,reason_hash:$i}),controller_policy_updated:so("controller_policy_updated",{name:$i,policy_hash:$i,name_seq:Ji}),namespace_policy_updated:so("namespace_policy_updated",{name:$i,allow_delegated_subnames:Qi,namespace_policy_hash:$i,name_seq:Ji}),did_alias_set:so("did_alias_set",{name:$i,target_did:$i,kind:ao,proof_hash:$i,name_seq:Ji}),payment_target_updated:so("payment_target_updated",{name:$i,doc_type:$i,payment_target:$i,payment_policy_hash:$i,version:Ji}),log_checkpoint_published:so("log_checkpoint_published",{log_root:$i,last_seq:Ji,issued_at:Ji,external_anchor:$i})},Ro=to(so("EventLogRecord",{seq:Ji,event_type:$i,observed_at:Ji,event_hash:$i,previous_log_root:$i,log_root:$i,event:(t,e)=>{(null===t||"object"!=typeof t||Array.isArray(t))&&qi(e,"expected RegistryEvent object");const n=t;"string"!=typeof n.type&&qi(`${e}.type`,"expected string event tag");const r=To[n.type];return r||qi(`${e}.type`,`unknown event type \`${n.type}\``),"data"in n&&void 0!==n.data||qi(`${e}.data`,"missing field"),{type:n.type,data:r(n.data,`${e}.data`)}}})),Io=so("BnsRpcErrorInfo",{code:$i,message:$i,name:no($i),doc_type:no($i),expected:no(Ji),actual:no(Ji)});function Oo(t){const e=t.split("://"),n=e.length>1?e.slice(1).join("://"):t,r=n.indexOf("/");return!(r<0)&&""!==n.slice(r+1).replace(/\/+$/,"")}function Co(t){const e=t.replace(/\/+$/,"");return Oo(e)?e:`${e}${Ci}`}function No(t){const e=t.replace(/\/+$/,"");return Oo(e)?e:`${e}${Ni}`}function xo(t){const e=e=>Ki.registryCode("INVALID_NAME",`invalid BNS name \`${t}\`: ${e}`,{name:t});if(!t)throw e("name is empty");if(t.trim()!==t)throw e("name must not contain leading or trailing whitespace");if(t.startsWith(xi))throw e("contract names must not include did:bns: prefix");if(t.length>253)throw e("name must be at most 253 bytes");for(const n of t.split(".")){if(!n)throw e("empty label");if(n.length>126)throw e("label must be at most 126 bytes");if(n.startsWith("-")||n.endsWith("-"))throw e("label must not start or end with '-'");if(!/^[a-z0-9-]+$/.test(n))throw e("only lower-case ASCII letters, digits, '-' and '.' are supported")}return t}function Po(t){const e=e=>Ki.registryCode("INVALID_DOC_TYPE",`invalid doc_type \`${t}\`: ${e}`,{doc_type:t});if(!t)throw e("doc_type is empty");if(t.length>32)throw e("doc_type must be at most 32 bytes");if(!/^[a-z0-9_-]+$/.test(t))throw e("only lower-case ASCII letters, digits, '-' and '_' are supported");return t}const Do="0123456789abcdef";function Bo(t){if(t instanceof Uint8Array){if(0===t.length)throw new Ki("serialization","raw_tx must not be empty");return`0x${function(t){let e="";for(let n=0;n<t.length;n++)e+=Do[t[n]>>4]+Do[15&t[n]];return e}(t)}`}const e=t.trim();if(!e)throw new Ki("serialization","raw_tx must not be empty");const n=e.startsWith("0x")?e.slice(2):e;if(!n||n.length%2!=0)throw new Ki("serialization",`raw_tx must be even-length hex, got \`${t}\``);if(!/^[0-9a-fA-F]+$/.test(n))throw new Ki("serialization",`invalid raw_tx hex \`${t}\``);return`0x${n}`}function Uo(t,e){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw new Ki("serialization",`waitTx ${t} must be a non-negative integer, got ${e}`);return Math.max(1,e)}class Lo{constructor(t,e=null,n={}){this.rpcClient=new jn(Co(t),e,null,n)}static forIndexer(t,e=null,n={}){return new Lo(No(t),e,n)}setSeq(t){this.rpcClient.setSeq(t)}async syncSessionToken(t){this.rpcClient.setSessionToken(t)}getSessionToken(){return this.rpcClient.getSessionToken()}setTraceId(t){this.rpcClient.setTraceId(t)}getTraceId(){return this.rpcClient.getTraceId()}async callEnvelope(t,e){let n;try{n=await this.rpcClient.call(t,e)}catch(s){const e=s instanceof Error?s.message:String(s);throw new Ki("transport",`${t} failed: ${e}`)}if(null===n||"object"!=typeof n||Array.isArray(n))throw new Ki("invalid_response",`invalid BNS RPC envelope for ${t}`);const r=n;if("boolean"!=typeof r.ok)throw new Ki("invalid_response",`invalid BNS RPC envelope for ${t}`);if(!r.ok){if(void 0!==r.result&&null!==r.result)throw new Ki("invalid_response",`unexpected result in failed BNS envelope for ${t}`);if(void 0===r.error||null===r.error)throw Ki.registryCode("UNKNOWN_BNS_ERROR","BNS RPC envelope missing error");let e;try{e=Io(r.error,"error")}catch(s){const e=s instanceof zi?s.message:String(s);throw new Ki("invalid_response",`invalid BNS error info for ${t}: ${e}`)}throw Ki.registry(e)}if(void 0!==r.error&&null!==r.error)throw new Ki("invalid_response",`unexpected error in successful BNS envelope for ${t}`);if(void 0===r.result)throw new Ki("invalid_response",`BNS RPC envelope missing result for ${t}`);return r.result}decodeResult(t,e,n){try{return e(n,"result")}catch(r){const e=r instanceof zi?r.message:String(r);throw new Ki("invalid_response",`invalid ${t} result: ${e}`)}}async call(t,e,n){const r=await this.callEnvelope(t,e);if(null===r)throw new Ki("invalid_response",`BNS RPC envelope missing result for ${t}`);return this.decodeResult(t,n,r)}async callNullable(t,e,n){const r=await this.callEnvelope(t,e);return null===r?null:this.decodeResult(t,n,r)}async queryNameState(t){return this.callNullable(Pi,{name:t},go)}async resolveOwner(t){return this.call(Di,{name:t},mo)}async getAuthoritySet(t){return this.call(Bi,{name:t},yo)}async getAuthorityKey(t,e){return this.callNullable(Ui,{name:t,kid:e},wo)}async resolveDocument(t,e){return this.call(Li,{name:t,doc_type:e},_o)}async getDocumentVersion(t,e,n){return this.callNullable(Mi,{name:t,doc_type:e,version:n},Ao)}async queryNamesByAddress(t,e=null,n=100){return this.call(Fi,{address:t,cursor:e,limit:n},vo)}async*iterNamesByAddress(t,e=100){let n=null;do{const r=await this.queryNamesByAddress(t,n,e);yield*r.names,n=r.next_cursor}while(null!==n)}async queryTxState(t){return this.call(Gi,{tx_hash:t},Eo)}async submitRawTx(t){return this.call(ji,{raw_tx:Bo(t)},ko)}async waitTx(t,e={}){const n=Uo("confirmations",e.confirmations??1),r=Uo("intervalMs",e.intervalMs??2e3),s=Uo("timeoutMs",e.timeoutMs??12e4),i=Date.now();for(;;){const e=await this.queryTxState(t);if("reverted"===e.state)return e;if("succeeded"===e.state&&e.confirmations>=n)return e;if(Date.now()-i>=s)throw new Ki("timeout",`timed out waiting for tx ${t} (last state: ${e.state})`);await new Promise((t=>setTimeout(t,r)))}}async listEvents(t,e=100){return this.call(Hi,{from_seq:t,limit:e},Ro)}async latestCheckpoint(){return this.callNullable(Vi,{},So)}}const Mo=Object.freeze(Object.defineProperty({__proto__:null,BNS_INDEXER_RPC_PATH:Ni,BNS_SERVER_RPC_PATH:Ci,BnsClient:Lo,BnsClientError:Ki,DID_BNS_PREFIX:xi,KEY_PURPOSE_AUTHENTICATION:1,KEY_PURPOSE_RECOVERY:2,KEY_PURPOSE_SIGN_DOCUMENT:4,MAX_BNS_LABEL_LEN:126,MAX_BNS_NAMES_PAGE_SIZE:1e3,MAX_BNS_NAME_LEN:253,METHOD_GET_AUTHORITY_KEY:Ui,METHOD_GET_AUTHORITY_SET:Bi,METHOD_GET_DOCUMENT_VERSION:Mi,METHOD_LATEST_CHECKPOINT:Vi,METHOD_LIST_EVENTS:Hi,METHOD_QUERY_NAMES_BY_ADDRESS:Fi,METHOD_QUERY_NAME_STATE:Pi,METHOD_QUERY_TX_STATE:Gi,METHOD_RESOLVE_DOCUMENT:Li,METHOD_RESOLVE_OWNER:Di,METHOD_SUBMIT_RAW_TX:ji,ZERO_HASH:"0x0000000000000000000000000000000000000000000000000000000000000000",canonicalBnsName:xo,canonicalDocType:Po,didBnsFromName:function(t){return`${xi}${xo(t)}`},nameFromDidBns:function(t){if(!t.startsWith(xi))throw Ki.registryCode("INVALID_NAME",`invalid BNS name \`${t}\`: DID must start with did:bns:`,{name:t});return xo(t.slice(8))},normalizeBnsIndexerUrl:No,normalizeBnsServerUrl:Co,normalizeRawTx:Bo},Symbol.toStringTag,{value:"Module"})),Fo="6.17.0";function Go(t,e,n){const r=e.split("|").map((t=>t.trim()));for(let i=0;i<r.length;i++)switch(e){case"any":return;case"bigint":case"boolean":case"number":case"string":if(typeof t===e)return}const s=new Error(`invalid value for type ${e}`);throw s.code="INVALID_ARGUMENT",s.argument=`value.${n}`,s.value=t,s}async function jo(t){const e=Object.keys(t);return(await Promise.all(e.map((e=>Promise.resolve(t[e]))))).reduce(((t,n,r)=>(t[e[r]]=n,t)),{})}function Ho(t,e,n){for(let r in e){let s=e[r];const i=n?n[r]:null;i&&Go(s,i,r),Object.defineProperty(t,r,{enumerable:!0,value:s,writable:!1})}}function Vo(t,e){if(null==t)return"null";if(null==e&&(e=new Set),"object"==typeof t){if(e.has(t))return"[Circular]";e.add(t)}if(Array.isArray(t))return"[ "+t.map((t=>Vo(t,e))).join(", ")+" ]";if(t instanceof Uint8Array){const e="0123456789abcdef";let n="0x";for(let r=0;r<t.length;r++)n+=e[t[r]>>4],n+=e[15&t[r]];return n}if("object"==typeof t&&"function"==typeof t.toJSON)return Vo(t.toJSON(),e);switch(typeof t){case"boolean":case"number":case"symbol":return t.toString();case"bigint":return BigInt(t).toString();case"string":return JSON.stringify(t);case"object":{const n=Object.keys(t);return n.sort(),"{ "+n.map((n=>`${Vo(n,e)}: ${Vo(t[n],e)}`)).join(", ")+" }"}}return"[ COULD NOT SERIALIZE ]"}function Wo(t,e){return t&&t.code===e}function Ko(t){return Wo(t,"CALL_EXCEPTION")}function zo(t,e,n){let r,s=t;{const r=[];if(n){if("message"in n||"code"in n||"name"in n)throw new Error(`value will overwrite populated values: ${Vo(n)}`);for(const t in n){if("shortMessage"===t)continue;const e=n[t];r.push(t+"="+Vo(e))}}r.push(`code=${e}`),r.push(`version=${Fo}`),r.length&&(t+=" ("+r.join(", ")+")")}switch(e){case"INVALID_ARGUMENT":r=new TypeError(t);break;case"NUMERIC_FAULT":case"BUFFER_OVERRUN":r=new RangeError(t);break;default:r=new Error(t)}return Ho(r,{code:e}),n&&Object.assign(r,n),null==r.shortMessage&&Ho(r,{shortMessage:s}),r}function qo(t,e,n,r){if(!t)throw zo(e,n,r)}function $o(t,e,n,r){qo(t,e,"INVALID_ARGUMENT",{argument:n,value:r})}function Qo(t,e,n){null==n&&(n=""),n&&(n=": "+n),qo(t>=e,"missing argument"+n,"MISSING_ARGUMENT",{count:t,expectedCount:e}),qo(t<=e,"too many arguments"+n,"UNEXPECTED_ARGUMENT",{count:t,expectedCount:e})}const Jo=["NFD","NFC","NFKD","NFKC"].reduce(((t,e)=>{try{if("test"!=="test".normalize(e))throw new Error("bad");if("NFD"===e){const t=String.fromCharCode(233).normalize("NFD");if(t!==String.fromCharCode(101,769))throw new Error("broken")}t.push(e)}catch(n){}return t}),[]);function Yo(t){qo(Jo.indexOf(t)>=0,"platform missing String.prototype.normalize","UNSUPPORTED_OPERATION",{operation:"String.prototype.normalize",info:{form:t}})}function Zo(t,e,n){if(null==n&&(n=""),t!==e){let t=n,e="new";n&&(t+=".",e+=" "+n),qo(!1,`private constructor; use ${t}from* methods`,"UNSUPPORTED_OPERATION",{operation:e})}}function Xo(t,e,n){if(t instanceof Uint8Array)return n?new Uint8Array(t):t;if("string"==typeof t&&t.length%2==0&&t.match(/^0x[0-9a-f]*$/i)){const e=new Uint8Array((t.length-2)/2);let n=2;for(let r=0;r<e.length;r++)e[r]=parseInt(t.substring(n,n+2),16),n+=2;return e}$o(!1,"invalid BytesLike value",e||"value",t)}function ta(t,e){return Xo(t,e,!1)}function ea(t,e){return Xo(t,e,!0)}function na(t,e){return!("string"!=typeof t||!t.match(/^0x[0-9A-Fa-f]*$/))&&(("number"!=typeof e||t.length===2+2*e)&&(!0!==e||t.length%2==0))}function ra(t){return na(t,!0)||t instanceof Uint8Array}const sa="0123456789abcdef";function ia(t){const e=ta(t);let n="0x";for(let r=0;r<e.length;r++){const t=e[r];n+=sa[(240&t)>>4]+sa[15&t]}return n}function oa(t){return"0x"+t.map((t=>ia(t).substring(2))).join("")}function aa(t){return na(t,!0)?(t.length-2)/2:ta(t).length}function ca(t,e,n){const r=ta(t);return null!=n&&n>r.length&&qo(!1,"cannot slice beyond data bounds","BUFFER_OVERRUN",{buffer:r,length:r.length,offset:n}),ia(r.slice(null==e?0:e,null==n?r.length:n))}function la(t,e,n){const r=ta(t);qo(e>=r.length,"padding exceeds data length","BUFFER_OVERRUN",{buffer:new Uint8Array(r),length:e,offset:e+1});const s=new Uint8Array(e);return s.fill(0),n?s.set(r,e-r.length):s.set(r,0),ia(s)}function ua(t,e){return la(t,e,!0)}function ha(t,e){return la(t,e,!1)}const da=BigInt(0),fa=BigInt(1),pa=9007199254740991;function ga(t,e){let n=ya(t,"value");const r=BigInt(_a(e,"width")),s=fa<<r-fa;if(n<da){n=-n,qo(n<=s,"too low","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:t});return(~n&(fa<<r)-fa)+fa}return qo(n<s,"too high","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:t}),n}function ma(t,e){const n=wa(t,"value"),r=BigInt(_a(e,"bits"));return n&(fa<<r)-fa}function ya(t,e){switch(typeof t){case"bigint":return t;case"number":return $o(Number.isInteger(t),"underflow",e||"value",t),$o(t>=-pa&&t<=pa,"overflow",e||"value",t),BigInt(t);case"string":try{if(""===t)throw new Error("empty string");return"-"===t[0]&&"-"!==t[1]?-BigInt(t.substring(1)):BigInt(t)}catch(n){$o(!1,`invalid BigNumberish string: ${n.message}`,e||"value",t)}}$o(!1,"invalid BigNumberish value",e||"value",t)}function wa(t,e){const n=ya(t,e);return qo(n>=da,"unsigned value cannot be negative","NUMERIC_FAULT",{fault:"overflow",operation:"getUint",value:t}),n}const ba="0123456789abcdef";function Aa(t){if(t instanceof Uint8Array){let e="0x0";for(const n of t)e+=ba[n>>4],e+=ba[15&n];return BigInt(e)}return ya(t)}function _a(t,e){switch(typeof t){case"bigint":return $o(t>=-pa&&t<=pa,"overflow",e||"value",t),Number(t);case"number":return $o(Number.isInteger(t),"underflow",e||"value",t),$o(t>=-pa&&t<=pa,"overflow",e||"value",t),t;case"string":try{if(""===t)throw new Error("empty string");return _a(BigInt(t),e)}catch(n){$o(!1,`invalid numeric string: ${n.message}`,e||"value",t)}}$o(!1,"invalid numeric value",e||"value",t)}function va(t,e){const n=wa(t,"value");let r=n.toString(16);if(null==e)r.length%2&&(r="0"+r);else{const s=_a(e,"width");if(0===s&&n===da)return"0x";for(qo(2*s>=r.length,`value exceeds width (${s} bytes)`,"NUMERIC_FAULT",{operation:"toBeHex",fault:"overflow",value:t});r.length<2*s;)r="0"+r}return"0x"+r}function Ea(t,e){const n=wa(t,"value");if(n===da){const t=null!=e?_a(e,"width"):0;return new Uint8Array(t)}let r=n.toString(16);if(r.length%2&&(r="0"+r),null!=e){const n=_a(e,"width");for(;r.length<2*n;)r="00"+r;qo(2*n===r.length,`value exceeds width (${n} bytes)`,"NUMERIC_FAULT",{operation:"toBeArray",fault:"overflow",value:t})}const s=new Uint8Array(r.length/2);for(let i=0;i<s.length;i++){const t=2*i;s[i]=parseInt(r.substring(t,t+2),16)}return s}function ka(t){let e=ia(ra(t)?t:Ea(t)).substring(2);for(;e.startsWith("0");)e=e.substring(1);return""===e&&(e="0"),"0x"+e}const Sa="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";let Ta=null;function Ra(t){if(null==Ta){Ta={};for(let t=0;t<58;t++)Ta[Sa[t]]=BigInt(t)}const e=Ta[t];return $o(null!=e,"invalid base58 value","letter",t),e}const Ia=BigInt(0),Oa=BigInt(58);function Ca(t){const e=ta(t);let n=Aa(e),r="";for(;n;)r=Sa[Number(n%Oa)]+r,n/=Oa;for(let s=0;s<e.length&&!e[s];s++)r=Sa[0]+r;return r}class Na{constructor(e,n,r){Nn(this,"filter"),Nn(this,"emitter"),Dn(this,t,void 0),Bn(this,t,n),Ho(this,{emitter:e,filter:r})}async removeListener(){null!=Pn(this,t)&&await this.emitter.off(this.filter,Pn(this,t))}}function xa(t,e,n,r,s){if("BAD_PREFIX"===t||"UNEXPECTED_CONTINUE"===t){let t=0;for(let r=e+1;r<n.length&&n[r]>>6==2;r++)t++;return t}return"OVERRUN"===t?n.length-e-1:0}t=new WeakMap;const Pa=Object.freeze({error:function(t,e,n,r,s){$o(!1,`invalid codepoint at offset ${e}; ${t}`,"bytes",n)},ignore:xa,replace:function(t,e,n,r,s){return"OVERLONG"===t?($o("number"==typeof s,"invalid bad code point for replacement","badCodepoint",s),r.push(s),0):(r.push(65533),xa(t,e,n))}});function Da(t,e){$o("string"==typeof t,"invalid string value","str",t),null!=e&&(Yo(e),t=t.normalize(e));let n=[];for(let r=0;r<t.length;r++){const e=t.charCodeAt(r);if(e<128)n.push(e);else if(e<2048)n.push(e>>6|192),n.push(63&e|128);else if(55296==(64512&e)){r++;const s=t.charCodeAt(r);$o(r<t.length&&56320==(64512&s),"invalid surrogate pair","str",t);const i=65536+((1023&e)<<10)+(1023&s);n.push(i>>18|240),n.push(i>>12&63|128),n.push(i>>6&63|128),n.push(63&i|128)}else n.push(e>>12|224),n.push(e>>6&63|128),n.push(63&e|128)}return new Uint8Array(n)}function Ba(t,e){return n=function(t,e){null==e&&(e=Pa.error);const n=ta(t,"bytes"),r=[];let s=0;for(;s<n.length;){const t=n[s++];if(!(t>>7)){r.push(t);continue}let i=null,o=null;if(192==(224&t))i=1,o=127;else if(224==(240&t))i=2,o=2047;else{if(240!=(248&t)){s+=e(128==(192&t)?"UNEXPECTED_CONTINUE":"BAD_PREFIX",s-1,n,r);continue}i=3,o=65535}if(s-1+i>=n.length){s+=e("OVERRUN",s-1,n,r);continue}let a=t&(1<<8-i-1)-1;for(let c=0;c<i;c++){let t=n[s];if(128!=(192&t)){s+=e("MISSING_CONTINUE",s,n,r),a=null;break}a=a<<6|63&t,s++}null!==a&&(a>1114111?s+=e("OUT_OF_RANGE",s-1-i,n,r,a):a>=55296&&a<=57343?s+=e("UTF16_SURROGATE",s-1-i,n,r,a):a<=o?s+=e("OVERLONG",s-1-i,n,r,a):r.push(a))}return r}(t,e),n.map((t=>t<=65535?String.fromCharCode(t):(t-=65536,String.fromCharCode(55296+(t>>10&1023),56320+(1023&t))))).join("");var n}function Ua(t){return async function(e,n){qo(null==n||!n.cancelled,"request cancelled before sending","CANCELLED");const r=e.url.split(":")[0].toLowerCase();qo("http"===r||"https"===r,`unsupported protocol ${r}`,"UNSUPPORTED_OPERATION",{info:{protocol:r},operation:"request"}),qo("https"===r||!e.credentials||e.allowInsecureAuthentication,"insecure authorized connections unsupported","UNSUPPORTED_OPERATION",{operation:"request"});let s=null;const i=new AbortController,o=setTimeout((()=>{s=zo("request timeout","TIMEOUT"),i.abort()}),e.timeout);n&&n.addListener((()=>{s=zo("request cancelled","CANCELLED"),i.abort()}));const a=Object.assign({},t,{method:e.method,headers:new Headers(Array.from(e)),body:e.body||void 0,signal:i.signal});let c;try{c=await fetch(e.url,a)}catch(d){if(clearTimeout(o),s)throw s;throw d}clearTimeout(o);const l={};c.headers.forEach(((t,e)=>{l[e.toLowerCase()]=t}));const u=await c.arrayBuffer(),h=null==u?null:new Uint8Array(u);return{statusCode:c.status,statusMessage:c.statusText,headers:l,body:h}}}let La=Ua();const Ma=new RegExp("^data:([^;:]*)?(;base64)?,(.*)$","i"),Fa=new RegExp("^ipfs://(ipfs/)?(.*)$","i");let Ga=!1;async function ja(t,e){try{const e=t.match(Ma);if(!e)throw new Error("invalid data");return new Ja(200,"OK",{"content-type":e[1]||"text/plain"},e[2]?function(t){t=atob(t);const e=new Uint8Array(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return ta(e)}(e[3]):Da(e[3].replace(/%([0-9a-f][0-9a-f])/gi,((t,e)=>String.fromCharCode(parseInt(e,16))))))}catch(n){return new Ja(599,"BAD REQUEST (invalid data: URI)",{},null,new $a(t))}}function Ha(t){return async function(e,n){try{const n=e.match(Fa);if(!n)throw new Error("invalid link");return new $a(`${t}${n[2]}`)}catch(r){return new Ja(599,"BAD REQUEST (invalid IPFS URI)",{},null,new $a(e))}}}const Va={data:ja,ipfs:Ha("https://gateway.ipfs.io/ipfs/")},Wa=new WeakMap;class Ka{constructor(t){Dn(this,e,void 0),Dn(this,n,void 0),Bn(this,e,[]),Bn(this,n,!1),Wa.set(t,(()=>{if(!Pn(this,n)){Bn(this,n,!0);for(const t of Pn(this,e))setTimeout((()=>{t()}),0);Bn(this,e,[])}}))}addListener(t){qo(!Pn(this,n),"singal already cancelled","UNSUPPORTED_OPERATION",{operation:"fetchCancelSignal.addCancelListener"}),Pn(this,e).push(t)}get cancelled(){return Pn(this,n)}checkSignal(){qo(!this.cancelled,"cancelled","CANCELLED",{})}}function za(t){if(null==t)throw new Error("missing signal; should not happen");return t.checkSignal(),t}e=new WeakMap,n=new WeakMap;const qa=class t{constructor(t){Dn(this,w),Dn(this,r,void 0),Dn(this,s,void 0),Dn(this,i,void 0),Dn(this,o,void 0),Dn(this,a,void 0),Dn(this,c,void 0),Dn(this,l,void 0),Dn(this,u,void 0),Dn(this,h,void 0),Dn(this,d,void 0),Dn(this,f,void 0),Dn(this,p,void 0),Dn(this,g,void 0),Dn(this,m,void 0),Dn(this,y,void 0),Bn(this,c,String(t)),Bn(this,r,!1),Bn(this,s,!0),Bn(this,i,{}),Bn(this,o,""),Bn(this,a,3e5),Bn(this,m,{slotInterval:250,maxAttempts:12}),Bn(this,y,null)}get url(){return Pn(this,c)}set url(t){Bn(this,c,String(t))}get body(){return null==Pn(this,l)?null:new Uint8Array(Pn(this,l))}set body(t){if(null==t)Bn(this,l,void 0),Bn(this,u,void 0);else if("string"==typeof t)Bn(this,l,Da(t)),Bn(this,u,"text/plain");else if(t instanceof Uint8Array)Bn(this,l,t),Bn(this,u,"application/octet-stream");else{if("object"!=typeof t)throw new Error("invalid body");Bn(this,l,Da(JSON.stringify(t))),Bn(this,u,"application/json")}}hasBody(){return null!=Pn(this,l)}get method(){return Pn(this,o)?Pn(this,o):this.hasBody()?"POST":"GET"}set method(t){null==t&&(t=""),Bn(this,o,String(t).toUpperCase())}get headers(){const t=Object.assign({},Pn(this,i));return Pn(this,h)&&(t.authorization=`Basic ${function(t){const e=ta(t);let n="";for(let r=0;r<e.length;r++)n+=String.fromCharCode(e[r]);return btoa(n)}(Da(Pn(this,h)))}`),this.allowGzip&&(t["accept-encoding"]="gzip"),null==t["content-type"]&&Pn(this,u)&&(t["content-type"]=Pn(this,u)),this.body&&(t["content-length"]=String(this.body.length)),t}getHeader(t){return this.headers[t.toLowerCase()]}setHeader(t,e){Pn(this,i)[String(t).toLowerCase()]=String(e)}clearHeaders(){Bn(this,i,{})}[Symbol.iterator](){const t=this.headers,e=Object.keys(t);let n=0;return{next:()=>{if(n<e.length){const r=e[n++];return{value:[r,t[r]],done:!1}}return{value:void 0,done:!0}}}}get credentials(){return Pn(this,h)||null}setCredentials(t,e){$o(!t.match(/:/),"invalid basic authentication username","username","[REDACTED]"),Bn(this,h,`${t}:${e}`)}get allowGzip(){return Pn(this,s)}set allowGzip(t){Bn(this,s,!!t)}get allowInsecureAuthentication(){return!!Pn(this,r)}set allowInsecureAuthentication(t){Bn(this,r,!!t)}get timeout(){return Pn(this,a)}set timeout(t){$o(t>=0,"timeout must be non-zero","timeout",t),Bn(this,a,t)}get preflightFunc(){return Pn(this,d)||null}set preflightFunc(t){Bn(this,d,t)}get processFunc(){return Pn(this,f)||null}set processFunc(t){Bn(this,f,t)}get retryFunc(){return Pn(this,p)||null}set retryFunc(t){Bn(this,p,t)}get getUrlFunc(){return Pn(this,y)||La}set getUrlFunc(t){Bn(this,y,t)}toString(){return`<FetchRequest method=${JSON.stringify(this.method)} url=${JSON.stringify(this.url)} headers=${JSON.stringify(this.headers)} body=${Pn(this,l)?ia(Pn(this,l)):"null"}>`}setThrottleParams(t){null!=t.slotInterval&&(Pn(this,m).slotInterval=t.slotInterval),null!=t.maxAttempts&&(Pn(this,m).maxAttempts=t.maxAttempts)}send(){return qo(null==Pn(this,g),"request already sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.send"}),Bn(this,g,new Ka(this)),Ln(this,w,b).call(this,0,Ya()+this.timeout,0,this,new Ja(0,"",{},null,this))}cancel(){qo(null!=Pn(this,g),"request has not been sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.cancel"});const t=Wa.get(this);if(!t)throw new Error("missing signal; should not happen");t()}redirect(e){const n=this.url.split(":")[0].toLowerCase(),r=e.split(":")[0].toLowerCase();qo(("https"!==n||"http"!==r)&&e.match(/^https?:/),"unsupported redirect","UNSUPPORTED_OPERATION",{operation:`redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(e)})`});const s=new t(e);return s.method=this.method,s.allowGzip=this.allowGzip,s.timeout=this.timeout,Bn(s,i,Object.assign({},Pn(this,i))),Pn(this,l)&&Bn(s,l,new Uint8Array(Pn(this,l))),Bn(s,u,Pn(this,u)),s}clone(){const e=new t(this.url);return Bn(e,o,Pn(this,o)),Pn(this,l)&&Bn(e,l,Pn(this,l)),Bn(e,u,Pn(this,u)),Bn(e,i,Object.assign({},Pn(this,i))),Bn(e,h,Pn(this,h)),this.allowGzip&&(e.allowGzip=!0),e.timeout=this.timeout,this.allowInsecureAuthentication&&(e.allowInsecureAuthentication=!0),Bn(e,d,Pn(this,d)),Bn(e,f,Pn(this,f)),Bn(e,p,Pn(this,p)),Bn(e,m,Object.assign({},Pn(this,m))),Bn(e,y,Pn(this,y)),e}static lockConfig(){Ga=!0}static getGateway(t){return Va[t.toLowerCase()]||null}static registerGateway(t,e){if("http"===(t=t.toLowerCase())||"https"===t)throw new Error(`cannot intercept ${t}; use registerGetUrl`);if(Ga)throw new Error("gateways locked");Va[t]=e}static registerGetUrl(t){if(Ga)throw new Error("gateways locked");La=t}static createGetUrlFunc(t){return Ua(t)}static createDataGateway(){return ja}static createIpfsGatewayFunc(t){return Ha(t)}};r=new WeakMap,s=new WeakMap,i=new WeakMap,o=new WeakMap,a=new WeakMap,c=new WeakMap,l=new WeakMap,u=new WeakMap,h=new WeakMap,d=new WeakMap,f=new WeakMap,p=new WeakMap,g=new WeakMap,m=new WeakMap,y=new WeakMap,w=new WeakSet,b=async function(t,e,n,r,s){var i,o,a;if(t>=Pn(this,m).maxAttempts)return s.makeServerError("exceeded maximum retry limit");qo(Ya()<=e,"timeout","TIMEOUT",{operation:"request.send",reason:"timeout",request:r}),n>0&&await function(t){return new Promise((e=>setTimeout(e,t)))}(n);let c=this.clone();const l=(c.url.split(":")[0]||"").toLowerCase();if(l in Va){const t=await Va[l](c.url,za(Pn(r,g)));if(t instanceof Ja){let e=t;if(this.processFunc){za(Pn(r,g));try{e=await this.processFunc(c,e)}catch(d){null!=d.throttle&&"number"==typeof d.stall||e.makeServerError("error in post-processing function",d).assertOk()}}return e}c=t}this.preflightFunc&&(c=await this.preflightFunc(c));const u=await this.getUrlFunc(c,za(Pn(r,g)));let h=new Ja(u.statusCode,u.statusMessage,u.headers,u.body,r);if([301,302,307,308].indexOf(h.statusCode)>=0){try{const n=h.headers.location||"";return Ln(i=c.redirect(n),w,b).call(i,t+1,e,0,r,h)}catch(d){}return h}if(429===h.statusCode&&(null==this.retryFunc||await this.retryFunc(c,h,t))){const n=h.headers["retry-after"];let s=Pn(this,m).slotInterval*Math.trunc(Math.random()*Math.pow(2,t));return"string"==typeof n&&n.match(/^[1-9][0-9]*$/)&&(s=parseInt(n)),Ln(o=c.clone(),w,b).call(o,t+1,e,s,r,h)}if(this.processFunc){za(Pn(r,g));try{h=await this.processFunc(c,h)}catch(d){null!=d.throttle&&"number"==typeof d.stall||h.makeServerError("error in post-processing function",d).assertOk();let n=Pn(this,m).slotInterval*Math.trunc(Math.random()*Math.pow(2,t));return d.stall>=0&&(n=d.stall),Ln(a=c.clone(),w,b).call(a,t+1,e,n,r,h)}}return h};let $a=qa;const Qa=class t{constructor(t,e,n,r,s){Dn(this,A,void 0),Dn(this,_,void 0),Dn(this,v,void 0),Dn(this,E,void 0),Dn(this,k,void 0),Dn(this,S,void 0),Bn(this,A,t),Bn(this,_,e),Bn(this,v,Object.keys(n).reduce(((t,e)=>(t[e.toLowerCase()]=String(n[e]),t)),{})),Bn(this,E,null==r?null:new Uint8Array(r)),Bn(this,k,s||null),Bn(this,S,{message:""})}toString(){return`<FetchResponse status=${this.statusCode} body=${Pn(this,E)?ia(Pn(this,E)):"null"}>`}get statusCode(){return Pn(this,A)}get statusMessage(){return Pn(this,_)}get headers(){return Object.assign({},Pn(this,v))}get body(){return null==Pn(this,E)?null:new Uint8Array(Pn(this,E))}get bodyText(){try{return null==Pn(this,E)?"":Ba(Pn(this,E))}catch(t){qo(!1,"response body is not valid UTF-8 data","UNSUPPORTED_OPERATION",{operation:"bodyText",info:{response:this}})}}get bodyJson(){try{return JSON.parse(this.bodyText)}catch(t){qo(!1,"response body is not valid JSON","UNSUPPORTED_OPERATION",{operation:"bodyJson",info:{response:this}})}}[Symbol.iterator](){const t=this.headers,e=Object.keys(t);let n=0;return{next:()=>{if(n<e.length){const r=e[n++];return{value:[r,t[r]],done:!1}}return{value:void 0,done:!0}}}}makeServerError(e,n){let r;r=e?`CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${e})`:`CLIENT ESCALATED SERVER ERROR (${e=`${this.statusCode} ${this.statusMessage}`})`;const s=new t(599,r,this.headers,this.body,Pn(this,k)||void 0);return Bn(s,S,{message:e,error:n}),s}throwThrottleError(t,e){null==e?e=-1:$o(Number.isInteger(e)&&e>=0,"invalid stall timeout","stall",e);const n=new Error(t||"throttling requests");throw Ho(n,{stall:e,throttle:!0}),n}getHeader(t){return this.headers[t.toLowerCase()]}hasBody(){return null!=Pn(this,E)}get request(){return Pn(this,k)}ok(){return""===Pn(this,S).message&&this.statusCode>=200&&this.statusCode<300}assertOk(){if(this.ok())return;let{message:t,error:e}=Pn(this,S);""===t&&(t=`server response ${this.statusCode} ${this.statusMessage}`);let n=null;this.request&&(n=this.request.url);let r=null;try{Pn(this,E)&&(r=Ba(Pn(this,E)))}catch(s){}qo(!1,t,"SERVER_ERROR",{request:this.request||"unknown request",response:this,error:e,info:{requestUrl:n,responseBody:r,responseStatus:`${this.statusCode} ${this.statusMessage}`}})}};A=new WeakMap,_=new WeakMap,v=new WeakMap,E=new WeakMap,k=new WeakMap,S=new WeakMap;let Ja=Qa;function Ya(){return(new Date).getTime()}function Za(t){let e=t.toString(16);for(;e.length<2;)e="0"+e;return"0x"+e}function Xa(t,e,n){let r=0;for(let s=0;s<n;s++)r=256*r+t[e+s];return r}function tc(t,e,n,r){const s=[];for(;n<e+1+r;){const i=ec(t,n);s.push(i.result),qo((n+=i.consumed)<=e+1+r,"child data too short","BUFFER_OVERRUN",{buffer:t,length:r,offset:e})}return{consumed:1+r,result:s}}function ec(t,e){qo(0!==t.length,"data too short","BUFFER_OVERRUN",{buffer:t,length:0,offset:1});const n=e=>{qo(e<=t.length,"data short segment too short","BUFFER_OVERRUN",{buffer:t,length:t.length,offset:e})};if(t[e]>=248){const r=t[e]-247;n(e+1+r);const s=Xa(t,e+1,r);return n(e+1+r+s),tc(t,e,e+1+r,r+s)}if(t[e]>=192){const r=t[e]-192;return n(e+1+r),tc(t,e,e+1,r)}if(t[e]>=184){const r=t[e]-183;n(e+1+r);const s=Xa(t,e+1,r);n(e+1+r+s);return{consumed:1+r+s,result:ia(t.slice(e+1+r,e+1+r+s))}}if(t[e]>=128){const r=t[e]-128;n(e+1+r);return{consumed:1+r,result:ia(t.slice(e+1,e+1+r))}}return{consumed:1,result:Za(t[e])}}function nc(t){const e=ta(t,"data"),n=ec(e,0);return $o(n.consumed===e.length,"unexpected junk after rlp payload","data",t),n.result}function rc(t){const e=[];for(;t;)e.unshift(255&t),t>>=8;return e}function sc(t){if(Array.isArray(t)){let e=[];if(t.forEach((function(t){e=e.concat(sc(t))})),e.length<=55)return e.unshift(192+e.length),e;const n=rc(e.length);return n.unshift(247+n.length),n.concat(e)}const e=Array.prototype.slice.call(ta(t,"object"));if(1===e.length&&e[0]<=127)return e;if(e.length<=55)return e.unshift(128+e.length),e;const n=rc(e.length);return n.unshift(183+n.length),n.concat(e)}const ic="0123456789abcdef";function oc(t){let e="0x";for(const n of sc(t))e+=ic[n>>4],e+=ic[15&n];return e}function ac(t){const e=ta(t,"randomBytes");e[6]=15&e[6]|64,e[8]=63&e[8]|128;const n=ia(e);return[n.substring(2,10),n.substring(10,14),n.substring(14,18),n.substring(18,22),n.substring(22,34)].join("-")}const cc=32,lc=new Uint8Array(cc),uc=["then"],hc={},dc=new WeakMap;function fc(t){return dc.get(t)}function pc(t,e){dc.set(t,e)}function gc(t,e){const n=new Error(`deferred error during ABI decoding triggered accessing ${t}`);throw n.error=e,n}function mc(t,e,n){return t.indexOf(null)>=0?e.map(((t,e)=>t instanceof yc?mc(fc(t),t,n):t)):t.reduce(((t,r,s)=>{let i=e.getValue(r);return r in t||(n&&i instanceof yc&&(i=mc(fc(i),i,n)),t[r]=i),t}),{})}T=new WeakMap;let yc=class t extends Array{constructor(...t){const e=t[0];let n=t[1],r=(t[2]||[]).slice(),s=!0;e!==hc&&(n=t,r=[],s=!1),super(n.length),Dn(this,T,void 0),n.forEach(((t,e)=>{this[e]=t}));const i=r.reduce(((t,e)=>("string"==typeof e&&t.set(e,(t.get(e)||0)+1),t)),new Map);if(pc(this,Object.freeze(n.map(((t,e)=>{const n=r[e];return null!=n&&1===i.get(n)?n:null})))),Bn(this,T,[]),null==Pn(this,T)&&Pn(this,T),!s)return;Object.freeze(this);const o=new Proxy(this,{get:(t,e,n)=>{if("string"==typeof e){if(e.match(/^[0-9]+$/)){const n=_a(e,"%index");if(n<0||n>=this.length)throw new RangeError("out of result range");const r=t[n];return r instanceof Error&&gc(`index ${n}`,r),r}if(uc.indexOf(e)>=0)return Reflect.get(t,e,n);const r=t[e];if(r instanceof Function)return function(...e){return r.apply(this===n?t:this,e)};if(!(e in t))return t.getValue.apply(this===n?t:this,[e])}return Reflect.get(t,e,n)}});return pc(o,fc(this)),o}toArray(e){const n=[];return this.forEach(((r,s)=>{r instanceof Error&&gc(`index ${s}`,r),e&&r instanceof t&&(r=r.toArray(e)),n.push(r)})),n}toObject(t){const e=fc(this);return e.reduce(((n,r,s)=>(qo(null!=r,`value at index ${s} unnamed`,"UNSUPPORTED_OPERATION",{operation:"toObject()"}),mc(e,this,t))),{})}slice(e,n){null==e&&(e=0),e<0&&(e+=this.length)<0&&(e=0),null==n&&(n=this.length),n<0&&(n+=this.length)<0&&(n=0),n>this.length&&(n=this.length);const r=fc(this),s=[],i=[];for(let t=e;t<n;t++)s.push(this[t]),i.push(r[t]);return new t(hc,s,i)}filter(e,n){const r=fc(this),s=[],i=[];for(let t=0;t<this.length;t++){const o=this[t];o instanceof Error&&gc(`index ${t}`,o),e.call(n,o,t,this)&&(s.push(o),i.push(r[t]))}return new t(hc,s,i)}map(t,e){const n=[];for(let r=0;r<this.length;r++){const s=this[r];s instanceof Error&&gc(`index ${r}`,s),n.push(t.call(e,s,r,this))}return n}getValue(t){const e=fc(this).indexOf(t);if(-1===e)return;const n=this[e];return n instanceof Error&&gc(`property ${JSON.stringify(t)}`,n.error),n}static fromItems(e,n){return new t(hc,e,n)}};function wc(t){let e=Ea(t);return qo(e.length<=cc,"value out-of-bounds","BUFFER_OVERRUN",{buffer:e,length:cc,offset:e.length}),e.length!==cc&&(e=ea(oa([lc.slice(e.length%cc),e]))),e}class bc{constructor(t,e,n,r){Nn(this,"name"),Nn(this,"type"),Nn(this,"localName"),Nn(this,"dynamic"),Ho(this,{name:t,type:e,localName:n,dynamic:r},{name:"string",type:"string",localName:"string",dynamic:"boolean"})}_throwError(t,e){$o(!1,t,this.localName,e)}}class Ac{constructor(){Dn(this,O),Dn(this,R,void 0),Dn(this,I,void 0),Bn(this,R,[]),Bn(this,I,0)}get data(){return oa(Pn(this,R))}get length(){return Pn(this,I)}appendWriter(t){return Ln(this,O,C).call(this,ea(t.data))}writeBytes(t){let e=ea(t);const n=e.length%cc;return n&&(e=ea(oa([e,lc.slice(n)]))),Ln(this,O,C).call(this,e)}writeValue(t){return Ln(this,O,C).call(this,wc(t))}writeUpdatableValue(){const t=Pn(this,R).length;return Pn(this,R).push(lc),Bn(this,I,Pn(this,I)+cc),e=>{Pn(this,R)[t]=wc(e)}}}R=new WeakMap,I=new WeakMap,O=new WeakSet,C=function(t){return Pn(this,R).push(t),Bn(this,I,Pn(this,I)+t.length),t.length};N=new WeakMap,x=new WeakMap,P=new WeakMap,D=new WeakMap,B=new WeakMap,U=new WeakSet,L=function(t){var e;if(Pn(this,D))return Ln(e=Pn(this,D),U,L).call(e,t);Bn(this,P,Pn(this,P)+t),qo(Pn(this,B)<1||Pn(this,P)<=Pn(this,B)*this.dataLength,`compressed ABI data exceeds inflation ratio of ${Pn(this,B)} ( see: https://github.com/ethers-io/ethers.js/issues/4537 )`,"BUFFER_OVERRUN",{buffer:ea(Pn(this,N)),offset:Pn(this,x),length:t,info:{bytesRead:Pn(this,P),dataLength:this.dataLength}})},M=new WeakSet,F=function(t,e,n){let r=Math.ceil(e/cc)*cc;return Pn(this,x)+r>Pn(this,N).length&&(this.allowLoose&&n&&Pn(this,x)+e<=Pn(this,N).length?r=e:qo(!1,"data out-of-bounds","BUFFER_OVERRUN",{buffer:ea(Pn(this,N)),length:Pn(this,N).length,offset:Pn(this,x)+r})),Pn(this,N).slice(Pn(this,x),Pn(this,x)+r)};let _c=class t{constructor(t,e,n){Dn(this,U),Dn(this,M),Nn(this,"allowLoose"),Dn(this,N,void 0),Dn(this,x,void 0),Dn(this,P,void 0),Dn(this,D,void 0),Dn(this,B,void 0),Ho(this,{allowLoose:!!e}),Bn(this,N,ea(t)),Bn(this,P,0),Bn(this,D,null),Bn(this,B,null!=n?n:1024),Bn(this,x,0)}get data(){return ia(Pn(this,N))}get dataLength(){return Pn(this,N).length}get consumed(){return Pn(this,x)}get bytes(){return new Uint8Array(Pn(this,N))}subReader(e){const n=new t(Pn(this,N).slice(Pn(this,x)+e),this.allowLoose,Pn(this,B));return Bn(n,D,this),n}readBytes(t,e){let n=Ln(this,M,F).call(this,0,t,!!e);return Ln(this,U,L).call(this,t),Bn(this,x,Pn(this,x)+n.length),n.slice(0,t)}readValue(){return Aa(this.readBytes(cc))}readIndex(){return _a(Aa(this.readBytes(cc)))}};function vc(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function Ec(t,...e){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}function kc(t){if("function"!=typeof t||"function"!=typeof t.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");vc(t.outputLen),vc(t.blockLen)}function Sc(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Tc(t,e){Ec(t);const n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}const Rc="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,Ic=t=>t instanceof Uint8Array,Oc=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4)),Cc=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),Nc=(t,e)=>t<<32-e|t>>>e;
2
- /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */if(!(68===new Uint8Array(new Uint32Array([287454020]).buffer)[0]))throw new Error("Non little-endian hardware is not supported");const xc=async()=>{};async function Pc(t,e,n){let r=Date.now();for(let s=0;s<t;s++){n(s);const t=Date.now()-r;t>=0&&t<e||(await xc(),r+=t)}}function Dc(t){if("string"==typeof t&&(t=function(t){if("string"!=typeof t)throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array((new TextEncoder).encode(t))}(t)),!Ic(t))throw new Error("expected Uint8Array, got "+typeof t);return t}class Bc{clone(){return this._cloneInto()}}const Uc={}.toString;function Lc(t,e){if(void 0!==e&&"[object Object]"!==Uc.call(e))throw new Error("Options should be object or undefined");return Object.assign(t,e)}function Mc(t){const e=e=>t().update(Dc(e)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Fc(t=32){if(Rc&&"function"==typeof Rc.getRandomValues)return Rc.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}class Gc extends Bc{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,kc(t);const n=Dc(e);if(this.iHash=t.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,s=new Uint8Array(r);s.set(n.length>r?t.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=t.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(t){return Sc(this),this.iHash.update(t),this}digestInto(t){Sc(this),Ec(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:e,iHash:n,finished:r,destroyed:s,blockLen:i,outputLen:o}=this;return t.finished=r,t.destroyed=s,t.blockLen=i,t.outputLen=o,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const jc=(t,e,n)=>new Gc(t,e).update(n).digest();function Hc(t,e,n,r){const{c:s,dkLen:i,DK:o,PRF:a,PRFSalt:c}=function(t,e,n,r){kc(t);const s=Lc({dkLen:32,asyncTick:10},r),{c:i,dkLen:o,asyncTick:a}=s;if(vc(i),vc(o),vc(a),i<1)throw new Error("PBKDF2: iterations (c) should be >= 1");const c=Dc(e),l=Dc(n),u=new Uint8Array(o),h=jc.create(t,c),d=h._cloneInto().update(l);return{c:i,dkLen:o,asyncTick:a,DK:u,PRF:h,PRFSalt:d}}(t,e,n,r);let l;const u=new Uint8Array(4),h=Cc(u),d=new Uint8Array(a.outputLen);for(let f=1,p=0;p<i;f++,p+=a.outputLen){const t=o.subarray(p,p+a.outputLen);h.setInt32(0,f,!1),(l=c._cloneInto(l)).update(u).digestInto(d),t.set(d.subarray(0,t.length));for(let e=1;e<s;e++){a._cloneInto(l).update(d).digestInto(d);for(let e=0;e<t.length;e++)t[e]^=d[e]}}return function(t,e,n,r,s){return t.destroy(),e.destroy(),r&&r.destroy(),s.fill(0),n}(a,c,o,l,d)}jc.create=(t,e)=>new Gc(t,e);class Vc extends Bc{constructor(t,e,n,r){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=Cc(this.buffer)}update(t){Sc(this);const{view:e,buffer:n,blockLen:r}=this,s=(t=Dc(t)).length;for(let i=0;i<s;){const o=Math.min(r-this.pos,s-i);if(o!==r)n.set(t.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===r&&(this.process(e,0),this.pos=0);else{const e=Cc(t);for(;r<=s-i;i+=r)this.process(e,i)}}return this.length+=t.length,this.roundClean(),this}digestInto(t){Sc(this),Tc(t,this),this.finished=!0;const{buffer:e,view:n,blockLen:r,isLE:s}=this;let{pos:i}=this;e[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>r-i&&(this.process(n,0),i=0);for(let u=i;u<r;u++)e[u]=0;!function(t,e,n,r){if("function"==typeof t.setBigUint64)return t.setBigUint64(e,n,r);const s=BigInt(32),i=BigInt(4294967295),o=Number(n>>s&i),a=Number(n&i),c=r?4:0,l=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+l,a,r)}(n,r-8,BigInt(8*this.length),s),this.process(n,0);const o=Cc(t),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<c;u++)o.setUint32(4*u,l[u],s)}digest(){const{buffer:t,outputLen:e}=this;this.digestInto(t);const n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:e,buffer:n,length:r,finished:s,destroyed:i,pos:o}=this;return t.length=r,t.pos=o,t.finished=s,t.destroyed=i,r%e&&t.buffer.set(n),t}}const Wc=(t,e,n)=>t&e^t&n^e&n,Kc=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),zc=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),qc=new Uint32Array(64);class $c extends Vc{constructor(){super(64,32,8,!1),this.A=0|zc[0],this.B=0|zc[1],this.C=0|zc[2],this.D=0|zc[3],this.E=0|zc[4],this.F=0|zc[5],this.G=0|zc[6],this.H=0|zc[7]}get(){const{A:t,B:e,C:n,D:r,E:s,F:i,G:o,H:a}=this;return[t,e,n,r,s,i,o,a]}set(t,e,n,r,s,i,o,a){this.A=0|t,this.B=0|e,this.C=0|n,this.D=0|r,this.E=0|s,this.F=0|i,this.G=0|o,this.H=0|a}process(t,e){for(let h=0;h<16;h++,e+=4)qc[h]=t.getUint32(e,!1);for(let h=16;h<64;h++){const t=qc[h-15],e=qc[h-2],n=Nc(t,7)^Nc(t,18)^t>>>3,r=Nc(e,17)^Nc(e,19)^e>>>10;qc[h]=r+qc[h-7]+n+qc[h-16]|0}let{A:n,B:r,C:s,D:i,E:o,F:a,G:c,H:l}=this;for(let h=0;h<64;h++){const t=l+(Nc(o,6)^Nc(o,11)^Nc(o,25))+((u=o)&a^~u&c)+Kc[h]+qc[h]|0,e=(Nc(n,2)^Nc(n,13)^Nc(n,22))+Wc(n,r,s)|0;l=c,c=a,a=o,o=i+t|0,i=s,s=r,r=n,n=t+e|0}var u;n=n+this.A|0,r=r+this.B|0,s=s+this.C|0,i=i+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,s,i,o,a,c,l)}roundClean(){qc.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const Qc=Mc((()=>new $c)),Jc=BigInt(2**32-1),Yc=BigInt(32);function Zc(t,e=!1){return e?{h:Number(t&Jc),l:Number(t>>Yc&Jc)}:{h:0|Number(t>>Yc&Jc),l:0|Number(t&Jc)}}function Xc(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){const{h:i,l:o}=Zc(t[s],e);[n[s],r[s]]=[i,o]}return[n,r]}const tl=(t,e,n)=>t<<n|e>>>32-n,el=(t,e,n)=>e<<n|t>>>32-n,nl=(t,e,n)=>e<<n-32|t>>>64-n,rl=(t,e,n)=>t<<n-32|e>>>64-n;const sl={fromBig:Zc,split:Xc,toBig:(t,e)=>BigInt(t>>>0)<<Yc|BigInt(e>>>0),shrSH:(t,e,n)=>t>>>n,shrSL:(t,e,n)=>t<<32-n|e>>>n,rotrSH:(t,e,n)=>t>>>n|e<<32-n,rotrSL:(t,e,n)=>t<<32-n|e>>>n,rotrBH:(t,e,n)=>t<<64-n|e>>>n-32,rotrBL:(t,e,n)=>t>>>n-32|e<<64-n,rotr32H:(t,e)=>e,rotr32L:(t,e)=>t,rotlSH:tl,rotlSL:el,rotlBH:nl,rotlBL:rl,add:function(t,e,n,r){const s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:0|s}},add3L:(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),add3H:(t,e,n,r)=>e+n+r+(t/2**32|0)|0,add4L:(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),add4H:(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0,add5H:(t,e,n,r,s,i)=>e+n+r+s+i+(t/2**32|0)|0,add5L:(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0)},[il,ol]=(()=>sl.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((t=>BigInt(t)))))(),al=new Uint32Array(80),cl=new Uint32Array(80);class ll extends Vc{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:t,Al:e,Bh:n,Bl:r,Ch:s,Cl:i,Dh:o,Dl:a,Eh:c,El:l,Fh:u,Fl:h,Gh:d,Gl:f,Hh:p,Hl:g}=this;return[t,e,n,r,s,i,o,a,c,l,u,h,d,f,p,g]}set(t,e,n,r,s,i,o,a,c,l,u,h,d,f,p,g){this.Ah=0|t,this.Al=0|e,this.Bh=0|n,this.Bl=0|r,this.Ch=0|s,this.Cl=0|i,this.Dh=0|o,this.Dl=0|a,this.Eh=0|c,this.El=0|l,this.Fh=0|u,this.Fl=0|h,this.Gh=0|d,this.Gl=0|f,this.Hh=0|p,this.Hl=0|g}process(t,e){for(let w=0;w<16;w++,e+=4)al[w]=t.getUint32(e),cl[w]=t.getUint32(e+=4);for(let w=16;w<80;w++){const t=0|al[w-15],e=0|cl[w-15],n=sl.rotrSH(t,e,1)^sl.rotrSH(t,e,8)^sl.shrSH(t,e,7),r=sl.rotrSL(t,e,1)^sl.rotrSL(t,e,8)^sl.shrSL(t,e,7),s=0|al[w-2],i=0|cl[w-2],o=sl.rotrSH(s,i,19)^sl.rotrBH(s,i,61)^sl.shrSH(s,i,6),a=sl.rotrSL(s,i,19)^sl.rotrBL(s,i,61)^sl.shrSL(s,i,6),c=sl.add4L(r,a,cl[w-7],cl[w-16]),l=sl.add4H(c,n,o,al[w-7],al[w-16]);al[w]=0|l,cl[w]=0|c}let{Ah:n,Al:r,Bh:s,Bl:i,Ch:o,Cl:a,Dh:c,Dl:l,Eh:u,El:h,Fh:d,Fl:f,Gh:p,Gl:g,Hh:m,Hl:y}=this;for(let w=0;w<80;w++){const t=sl.rotrSH(u,h,14)^sl.rotrSH(u,h,18)^sl.rotrBH(u,h,41),e=sl.rotrSL(u,h,14)^sl.rotrSL(u,h,18)^sl.rotrBL(u,h,41),b=u&d^~u&p,A=h&f^~h&g,_=sl.add5L(y,e,A,ol[w],cl[w]),v=sl.add5H(_,m,t,b,il[w],al[w]),E=0|_,k=sl.rotrSH(n,r,28)^sl.rotrBH(n,r,34)^sl.rotrBH(n,r,39),S=sl.rotrSL(n,r,28)^sl.rotrBL(n,r,34)^sl.rotrBL(n,r,39),T=n&s^n&o^s&o,R=r&i^r&a^i&a;m=0|p,y=0|g,p=0|d,g=0|f,d=0|u,f=0|h,({h:u,l:h}=sl.add(0|c,0|l,0|v,0|E)),c=0|o,l=0|a,o=0|s,a=0|i,s=0|n,i=0|r;const I=sl.add3L(E,S,R);n=sl.add3H(I,v,k,T),r=0|I}({h:n,l:r}=sl.add(0|this.Ah,0|this.Al,0|n,0|r)),({h:s,l:i}=sl.add(0|this.Bh,0|this.Bl,0|s,0|i)),({h:o,l:a}=sl.add(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l:l}=sl.add(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:h}=sl.add(0|this.Eh,0|this.El,0|u,0|h)),({h:d,l:f}=sl.add(0|this.Fh,0|this.Fl,0|d,0|f)),({h:p,l:g}=sl.add(0|this.Gh,0|this.Gl,0|p,0|g)),({h:m,l:y}=sl.add(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(n,r,s,i,o,a,c,l,u,h,d,f,p,g,m,y)}roundClean(){al.fill(0),cl.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const ul=Mc((()=>new ll));const hl=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("unable to locate global object")}(),dl=hl.crypto||hl.msCrypto;let fl=!1;const pl=function(t,e,n){return function(t,e){const n={sha256:Qc,sha512:ul}[t];return $o(null!=n,"invalid hmac algorithm","algorithm",t),jc.create(n,e)}(t,e).update(n).digest()};let gl=pl;function ml(t,e,n){const r=ta(e,"key"),s=ta(n,"data");return ia(gl(t,r,s))}ml._=pl,ml.lock=function(){fl=!0},ml.register=function(t){if(fl)throw new Error("computeHmac is locked");gl=t},Object.freeze(ml);const[yl,wl,bl]=[[],[],[]],Al=BigInt(0),_l=BigInt(1),vl=BigInt(2),El=BigInt(7),kl=BigInt(256),Sl=BigInt(113);for(let J_=0,Y_=_l,Z_=1,X_=0;J_<24;J_++){[Z_,X_]=[X_,(2*Z_+3*X_)%5],yl.push(2*(5*X_+Z_)),wl.push((J_+1)*(J_+2)/2%64);let t=Al;for(let e=0;e<7;e++)Y_=(Y_<<_l^(Y_>>El)*Sl)%kl,Y_&vl&&(t^=_l<<(_l<<BigInt(e))-_l);bl.push(t)}const[Tl,Rl]=Xc(bl,!0),Il=(t,e,n)=>n>32?nl(t,e,n):tl(t,e,n),Ol=(t,e,n)=>n>32?rl(t,e,n):el(t,e,n);class Cl extends Bc{constructor(t,e,n,r=!1,s=24){if(super(),this.blockLen=t,this.suffix=e,this.outputLen=n,this.enableXOF=r,this.rounds=s,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,vc(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Oc(this.state)}keccak(){!function(t,e=24){const n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let r=0;r<10;r++)n[r]=t[r]^t[r+10]^t[r+20]^t[r+30]^t[r+40];for(let r=0;r<10;r+=2){const e=(r+8)%10,s=(r+2)%10,i=n[s],o=n[s+1],a=Il(i,o,1)^n[e],c=Ol(i,o,1)^n[e+1];for(let n=0;n<50;n+=10)t[r+n]^=a,t[r+n+1]^=c}let e=t[2],s=t[3];for(let n=0;n<24;n++){const r=wl[n],i=Il(e,s,r),o=Ol(e,s,r),a=yl[n];e=t[a],s=t[a+1],t[a]=i,t[a+1]=o}for(let r=0;r<50;r+=10){for(let e=0;e<10;e++)n[e]=t[r+e];for(let e=0;e<10;e++)t[r+e]^=~n[(e+2)%10]&n[(e+4)%10]}t[0]^=Tl[r],t[1]^=Rl[r]}n.fill(0)}(this.state32,this.rounds),this.posOut=0,this.pos=0}update(t){Sc(this);const{blockLen:e,state:n}=this,r=(t=Dc(t)).length;for(let s=0;s<r;){const i=Math.min(e-this.pos,r-s);for(let e=0;e<i;e++)n[this.pos++]^=t[s++];this.pos===e&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:e,pos:n,blockLen:r}=this;t[n]^=e,128&e&&n===r-1&&this.keccak(),t[r-1]^=128,this.keccak()}writeInto(t){Sc(this,!1),Ec(t),this.finish();const e=this.state,{blockLen:n}=this;for(let r=0,s=t.length;r<s;){this.posOut>=n&&this.keccak();const i=Math.min(n-this.posOut,s-r);t.set(e.subarray(this.posOut,this.posOut+i),r),this.posOut+=i,r+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return vc(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(Tc(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(t){const{blockLen:e,suffix:n,outputLen:r,rounds:s,enableXOF:i}=this;return t||(t=new Cl(e,n,r,i,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=n,t.outputLen=r,t.enableXOF=i,t.destroyed=this.destroyed,t}}const Nl=((t,e,n)=>Mc((()=>new Cl(e,t,n))))(1,136,32);let xl=!1;const Pl=function(t){return Nl(t)};let Dl=Pl;function Bl(t){const e=ta(t,"data");return ia(Dl(e))}Bl._=Pl,Bl.lock=function(){xl=!0},Bl.register=function(t){if(xl)throw new TypeError("keccak256 is locked");Dl=t},Object.freeze(Bl);const Ul=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Ll=Uint8Array.from({length:16},((t,e)=>e));let Ml=[Ll],Fl=[Ll.map((t=>(9*t+5)%16))];for(let J_=0;J_<4;J_++)for(let t of[Ml,Fl])t.push(t[J_].map((t=>Ul[t])));const Gl=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map((t=>new Uint8Array(t))),jl=Ml.map(((t,e)=>t.map((t=>Gl[e][t])))),Hl=Fl.map(((t,e)=>t.map((t=>Gl[e][t])))),Vl=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),Wl=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]),Kl=(t,e)=>t<<e|t>>>32-e;function zl(t,e,n,r){return 0===t?e^n^r:1===t?e&n|~e&r:2===t?(e|~n)^r:3===t?e&r|n&~r:e^(n|~r)}const ql=new Uint32Array(16);class $l extends Vc{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:t,h1:e,h2:n,h3:r,h4:s}=this;return[t,e,n,r,s]}set(t,e,n,r,s){this.h0=0|t,this.h1=0|e,this.h2=0|n,this.h3=0|r,this.h4=0|s}process(t,e){for(let d=0;d<16;d++,e+=4)ql[d]=t.getUint32(e,!0);let n=0|this.h0,r=n,s=0|this.h1,i=s,o=0|this.h2,a=o,c=0|this.h3,l=c,u=0|this.h4,h=u;for(let d=0;d<5;d++){const t=4-d,e=Vl[d],f=Wl[d],p=Ml[d],g=Fl[d],m=jl[d],y=Hl[d];for(let r=0;r<16;r++){const t=Kl(n+zl(d,s,o,c)+ql[p[r]]+e,m[r])+u|0;n=u,u=c,c=0|Kl(o,10),o=s,s=t}for(let n=0;n<16;n++){const e=Kl(r+zl(t,i,a,l)+ql[g[n]]+f,y[n])+h|0;r=h,h=l,l=0|Kl(a,10),a=i,i=e}}this.set(this.h1+o+l|0,this.h2+c+h|0,this.h3+u+r|0,this.h4+n+i|0,this.h0+s+a|0)}roundClean(){ql.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}}const Ql=Mc((()=>new $l));let Jl=!1;const Yl=function(t){return Ql(t)};let Zl=Yl;function Xl(t){const e=ta(t,"data");return ia(Zl(e))}Xl._=Yl,Xl.lock=function(){Jl=!0},Xl.register=function(t){if(Jl)throw new TypeError("ripemd160 is locked");Zl=t},Object.freeze(Xl);let tu=!1;const eu=function(t,e,n,r,s){return function(t,e,n,r,s){const i={sha256:Qc,sha512:ul}[s];return $o(null!=i,"invalid pbkdf2 algorithm","algorithm",s),Hc(i,t,e,{c:n,dkLen:r})}(t,e,n,r,s)};let nu=eu;function ru(t,e,n,r,s){const i=ta(t,"password"),o=ta(e,"salt");return ia(nu(i,o,n,r,s))}ru._=eu,ru.lock=function(){tu=!0},ru.register=function(t){if(tu)throw new Error("pbkdf2 is locked");nu=t},Object.freeze(ru);let su=!1;const iu=function(t){return new Uint8Array(function(t){qo(null!=dl,"platform does not support secure random numbers","UNSUPPORTED_OPERATION",{operation:"randomBytes"}),$o(Number.isInteger(t)&&t>0&&t<=1024,"invalid length","length",t);const e=new Uint8Array(t);return dl.getRandomValues(e),e}(t))};let ou=iu;function au(t){return ou(t)}au._=iu,au.lock=function(){su=!0},au.register=function(t){if(su)throw new Error("randomBytes is locked");ou=t},Object.freeze(au);const cu=(t,e)=>t<<e|t>>>32-e;function lu(t,e,n,r,s,i){let o=t[e++]^n[r++],a=t[e++]^n[r++],c=t[e++]^n[r++],l=t[e++]^n[r++],u=t[e++]^n[r++],h=t[e++]^n[r++],d=t[e++]^n[r++],f=t[e++]^n[r++],p=t[e++]^n[r++],g=t[e++]^n[r++],m=t[e++]^n[r++],y=t[e++]^n[r++],w=t[e++]^n[r++],b=t[e++]^n[r++],A=t[e++]^n[r++],_=t[e++]^n[r++],v=o,E=a,k=c,S=l,T=u,R=h,I=d,O=f,C=p,N=g,x=m,P=y,D=w,B=b,U=A,L=_;for(let M=0;M<8;M+=2)T^=cu(v+D|0,7),C^=cu(T+v|0,9),D^=cu(C+T|0,13),v^=cu(D+C|0,18),N^=cu(R+E|0,7),B^=cu(N+R|0,9),E^=cu(B+N|0,13),R^=cu(E+B|0,18),U^=cu(x+I|0,7),k^=cu(U+x|0,9),I^=cu(k+U|0,13),x^=cu(I+k|0,18),S^=cu(L+P|0,7),O^=cu(S+L|0,9),P^=cu(O+S|0,13),L^=cu(P+O|0,18),E^=cu(v+S|0,7),k^=cu(E+v|0,9),S^=cu(k+E|0,13),v^=cu(S+k|0,18),I^=cu(R+T|0,7),O^=cu(I+R|0,9),T^=cu(O+I|0,13),R^=cu(T+O|0,18),P^=cu(x+N|0,7),C^=cu(P+x|0,9),N^=cu(C+P|0,13),x^=cu(N+C|0,18),D^=cu(L+U|0,7),B^=cu(D+L|0,9),U^=cu(B+D|0,13),L^=cu(U+B|0,18);s[i++]=o+v|0,s[i++]=a+E|0,s[i++]=c+k|0,s[i++]=l+S|0,s[i++]=u+T|0,s[i++]=h+R|0,s[i++]=d+I|0,s[i++]=f+O|0,s[i++]=p+C|0,s[i++]=g+N|0,s[i++]=m+x|0,s[i++]=y+P|0,s[i++]=w+D|0,s[i++]=b+B|0,s[i++]=A+U|0,s[i++]=_+L|0}function uu(t,e,n,r,s){let i=r+0,o=r+16*s;for(let a=0;a<16;a++)n[o+a]=t[e+16*(2*s-1)+a];for(let a=0;a<s;a++,i+=16,e+=16)lu(n,o,t,e,n,i),a>0&&(o+=16),lu(n,i,t,e+=16,n,o)}function hu(t,e,n){const r=Lc({dkLen:32,asyncTick:10,maxmem:1073742848},n),{N:s,r:i,p:o,dkLen:a,asyncTick:c,maxmem:l,onProgress:u}=r;if(vc(s),vc(i),vc(o),vc(a),vc(c),vc(l),void 0!==u&&"function"!=typeof u)throw new Error("progressCb should be function");const h=128*i,d=h/4;if(s<=1||s&s-1||s>=2**(h/8)||s>2**32)throw new Error("Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32");if(o<0||o>137438953440/h)throw new Error("Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)");if(a<0||a>137438953440)throw new Error("Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32");const f=h*(s+o);if(f>l)throw new Error(`Scrypt: parameters too large, ${f} (128 * r * (N + p)) > ${l} (maxmem)`);const p=Hc(Qc,t,e,{c:1,dkLen:h*o}),g=Oc(p),m=Oc(new Uint8Array(h*s)),y=Oc(new Uint8Array(h));let w=()=>{};if(u){const t=2*s*o,e=Math.max(Math.floor(t/1e4),1);let n=0;w=()=>{n++,!u||n%e&&n!==t||u(n/t)}}return{N:s,r:i,p:o,dkLen:a,blockSize32:d,V:m,B32:g,B:p,tmp:y,blockMixCb:w,asyncTick:c}}function du(t,e,n,r,s){const i=Hc(Qc,t,n,{c:1,dkLen:e});return n.fill(0),r.fill(0),s.fill(0),i}let fu=!1,pu=!1;const gu=async function(t,e,n,r,s,i,o){return await async function(t,e,n){const{N:r,r:s,p:i,dkLen:o,blockSize32:a,V:c,B32:l,B:u,tmp:h,blockMixCb:d,asyncTick:f}=hu(t,e,n);for(let p=0;p<i;p++){const t=a*p;for(let n=0;n<a;n++)c[n]=l[t+n];let e=0;await Pc(r-1,f,(()=>{uu(c,e,c,e+=a,s),d()})),uu(c,(r-1)*a,l,t,s),d(),await Pc(r,f,(()=>{const e=l[t+a-16]%r;for(let n=0;n<a;n++)h[n]=l[t+n]^c[e*a+n];uu(h,0,l,t,s),d()}))}return du(t,o,u,c,h)}(t,e,{N:n,r:r,p:s,dkLen:i,onProgress:o})},mu=function(t,e,n,r,s,i){return function(t,e,n){const{N:r,r:s,p:i,dkLen:o,blockSize32:a,V:c,B32:l,B:u,tmp:h,blockMixCb:d}=hu(t,e,n);for(let f=0;f<i;f++){const t=a*f;for(let e=0;e<a;e++)c[e]=l[t+e];for(let e=0,n=0;e<r-1;e++)uu(c,n,c,n+=a,s),d();uu(c,(r-1)*a,l,t,s),d();for(let e=0;e<r;e++){const e=l[t+a-16]%r;for(let n=0;n<a;n++)h[n]=l[t+n]^c[e*a+n];uu(h,0,l,t,s),d()}}return du(t,o,u,c,h)}(t,e,{N:n,r:r,p:s,dkLen:i})};let yu=gu,wu=mu;async function bu(t,e,n,r,s,i,o){const a=ta(t,"passwd"),c=ta(e,"salt");return ia(await yu(a,c,n,r,s,i,o))}function Au(t,e,n,r,s,i){const o=ta(t,"passwd"),a=ta(e,"salt");return ia(wu(o,a,n,r,s,i))}bu._=gu,bu.lock=function(){pu=!0},bu.register=function(t){if(pu)throw new Error("scrypt is locked");yu=t},Object.freeze(bu),Au._=mu,Au.lock=function(){fu=!0},Au.register=function(t){if(fu)throw new Error("scryptSync is locked");wu=t},Object.freeze(Au);const _u=function(t){return function(t){switch(t){case"sha256":return Qc.create();case"sha512":return ul.create()}$o(!1,"invalid hashing algorithm name","algorithm",t)}("sha256").update(t).digest()};let vu=_u,Eu=!1;function ku(t){const e=ta(t,"data");return ia(vu(e))}ku._=_u,ku.lock=function(){Eu=!0},ku.register=function(t){if(Eu)throw new Error("sha256 is locked");vu=t},Object.freeze(ku),Object.freeze(ku);
1
+ "use strict";var t,e,n,r,s,i,o,a,c,l,u,h,d,f,p,g,m,y,w,b,A,_,v,E,k,S,T,R,I,O,C,x,N,P,D,B,U,L,M,F,G,j,H,V,W,K,z,q,$,Q,J,Y,Z,X,tt,et,nt,rt,st,it,ot,at,ct,lt,ut,ht,dt,ft,pt,gt,mt,yt,wt,bt,At,_t,vt,Et,kt,St,Tt,Rt,It,Ot,Ct,xt,Nt,Pt,Dt,Bt,Ut,Lt,Mt,Ft,Gt,jt,Ht,Vt,Wt,Kt,zt,qt,$t,Qt,Jt,Yt,Zt,Xt,te,ee,ne,re,se,ie,oe,ae,ce,le,ue,he,de,fe,pe,ge,me,ye,we,be,Ae,_e,ve,Ee,ke,Se,Te,Re,Ie,Oe,Ce,xe,Ne,Pe,De,Be,Ue,Le,Me,Fe,Ge,je,He,Ve,We,Ke,ze,qe,$e,Qe,Je,Ye,Ze,Xe,tn,en,nn,rn,sn,on,an,cn,ln,un,hn,dn,fn,pn,gn,mn,yn,wn,bn,An,_n,vn,En,kn,Sn,Tn,Rn,In,On,Cn=Object.defineProperty,xn=(t,e,n)=>(((t,e,n)=>{e in t?Cn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n})(t,"symbol"!=typeof e?e+"":e,n),n),Nn=(t,e,n)=>{if(!e.has(t))throw TypeError("Cannot "+n)},Pn=(t,e,n)=>(Nn(t,e,"read from private field"),n?n.call(t):e.get(t)),Dn=(t,e,n)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,n)},Bn=(t,e,n,r)=>(Nn(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),Un=(t,e,n,r)=>({set _(r){Bn(t,e,r,n)},get _(){return Pn(t,e,r)}}),Ln=(t,e,n)=>(Nn(t,e,"access private method"),n);const Mn=require("./ndn_types-44c69036.js");class Fn extends Error{constructor(t){super(t),this.name="RPCError"}}const Gn=async(t,e)=>{if("undefined"!=typeof window&&"function"==typeof window.fetch)return window.fetch(t,e);if("undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch)return globalThis.fetch(t,e);throw new Fn("fetch is not available in this runtime")};class jn{constructor(t,e=null,n=null,r={}){this.serverUrl=t,this.protocolType="HttpPostJson",this.seq=n??Date.now(),this.sessionToken=e||null,this.initToken=e||null,this.traceId=r.traceId||null,this.fetcher=r.fetcher??Gn,this.sessionTokenProvider=r.sessionTokenProvider??null,this.sessionTokenOverride=void 0}async call(t,e,n={}){return this._call(t,e,n)}async callWithSessionToken(t,e,n){return this._call(e,n,{sessionToken:t})}setSeq(t){this.seq=t}resetSessionToken(){this.sessionToken=this.initToken,this.sessionTokenOverride=void 0}setSessionToken(t){this.sessionToken=t||null,this.sessionTokenOverride=t||null}getSessionToken(){return this.sessionToken}setTraceId(t){this.traceId=t||null}getTraceId(){return this.traceId}buildRequest(t,e,n,r,s){let i;return i=s?[n,r,s]:r?[n,r]:[n],{method:t,params:e,sys:i}}parseResponseSys(t,e){if(null==t)return null;if(!Array.isArray(t))throw new Fn("sys is not array");if(t.length<1)throw new Fn("sys is empty");const n=t[0];if("number"!=typeof n)throw new Fn("sys[0] is not number");if(n!==e)throw new Fn(`seq not match: ${n}!=${e}`);if(t.length>=2){const e=t[1];if("string"!=typeof e)throw new Fn("sys[1] trace_id is not string");return e}return null}async prepareSessionToken(t){if(Object.prototype.hasOwnProperty.call(t,"sessionToken"))return t.sessionToken||null;if(void 0!==this.sessionTokenOverride)return this.sessionTokenOverride;if(this.sessionTokenProvider){const t=await this.sessionTokenProvider();void 0!==t&&(this.sessionToken=t||null)}return this.sessionToken}prepareTraceId(t){return Object.prototype.hasOwnProperty.call(t,"traceId")?t.traceId||null:this.traceId}async _call(t,e,n){const r=await this.prepareSessionToken(n),s=this.prepareTraceId(n),i=this.seq;this.seq+=1;const o=this.buildRequest(t,e,i,r,s);try{const t=await this.fetcher(this.serverUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!t.ok)throw new Fn(`RPC call error: ${t.status}`);const e=await t.json();if(this.parseResponseSys(e.sys,i),"error"in e&&e.error)throw new Fn(`RPC call error: ${e.error}`);if(!("result"in e)||void 0===e.result)throw new Fn("RPC response missing result");return e.result}catch(a){if(a instanceof Fn)throw a;const t=a instanceof Error?a.message:String(a);throw new Fn(`RPC call failed: ${t}`)}}}function Hn(){if("undefined"==typeof window||void 0===window.location)throw new Error("AuthClient can only be created in browser SSO environments")}class Vn{constructor(t,e={}){Hn(),this.zoneHostname=t,this.navigate=e.navigate??(t=>{window.location.assign(t)})}buildLoginURL(t=null){Hn();const e=t??window.location.href;return`${`${window.location.protocol}//sys.${this.zoneHostname}/login`}?redirect_url=${encodeURIComponent(e)}`}async login(t=null){const e=this.buildLoginURL(t);this.navigate(e)}}function Wn(t){if(!t||"object"!=typeof t)throw new Fn("verify-hub auth target is required");if("app"===t.kind&&"string"==typeof t.app_instance_id&&t.app_instance_id.length>0)return{kind:"app",app_instance_id:t.app_instance_id};if("system"===t.kind&&"string"==typeof t.service_id&&t.service_id.length>0)return{kind:"system",service_id:t.service_id};throw new Fn("invalid verify-hub auth target")}function Kn(t){const e=Wn(t);if("system"===e.kind)return e.service_id;const n=e.app_instance_id.lastIndexOf("@");if(n<=0||n===e.app_instance_id.length-1)throw new Fn("app auth target must use `<appId>@<ownerUserId>`");return e.app_instance_id.slice(0,n)}class zn{constructor(t){this.rpcClient=t}setSeq(t){this.rpcClient.setSeq(t)}async loginByJwt(t){return this.rpcClient.resetSessionToken(),this.rpcClient.call("login_by_jwt",{type:"jwt",jwt:t.jwt,target:Wn(t.target)})}async loginByPassword(t){this.rpcClient.resetSessionToken();const e={type:"password",username:t.username,password:t.password,target:Wn(t.target)};return void 0!==t.login_nonce&&(e.login_nonce=t.login_nonce),t.source_url&&(e.source_url=t.source_url),this.rpcClient.call("login_by_password",e)}async sudoByPassword(t){this.rpcClient.resetSessionToken();const e={username:t.username,password:t.password,target:Wn(t.target)};return void 0!==t.aud&&(e.aud=t.aud),void 0!==t.login_nonce&&(e.login_nonce=t.login_nonce),this.rpcClient.call("sudo_by_password",e)}async refreshToken(t){return this.rpcClient.call("refresh_token",{refresh_token:t.refresh_token})}async verifyToken(t){const e={session_token:t.session_token};return void 0!==t.expected_target&&(e.expected_target=Wn(t.expected_target)),this.rpcClient.call("verify_token",e)}static normalizeLoginResponse(t){if("user_info"in t)return{user_name:t.user_info.show_name,user_id:t.user_info.user_id,user_type:t.user_info.user_type,session_token:t.session_token,refresh_token:t.refresh_token};if(!t.session_token)throw new Fn("login_by_password response missing session_token");return t}}const qn="task_not_found",$n="permission_denied",Qn="revision_conflict",Jn="stale_runner_epoch",Yn="invalid_task_phase",Zn="control_not_available",Xn="control_already_pending",tr="task_already_completed",er="input_schema_mismatch",nr="result_schema_mismatch",rr="idempotency_conflict",sr="task_schema_not_found",ir=[qn,$n,Qn,Jn,Yn,Zn,Xn,tr,er,nr,rr,sr];function or(t){const e=t instanceof Error?t.message:String(t);for(const n of ir){const t=e.indexOf(n);if(t<0)continue;const r=0===t?"":e[t-1],s=e[t+n.length]??"";if((!r||/[\s:]/.test(r))&&(!s||/[\s:]/.test(s)))return n}return null}var ar=(t=>(t.Unbound="Unbound",t.App="App",t.HumanSet="HumanSet",t))(ar||{}),cr=(t=>(t.Promised="Promised",t.Accepted="Accepted",t.Running="Running",t.Waiting="Waiting",t.Paused="Paused",t.Terminal="Terminal",t))(cr||{});function lr(t){return"Terminal"===t}var ur=(t=>(t.Dispatch="Dispatch",t.Capacity="Capacity",t.Authorization="Authorization",t.HumanInput="HumanInput",t.ChildTask="ChildTask",t.Dependency="Dependency",t.External="External",t.Other="Other",t))(ur||{}),hr=(t=>(t.Succeeded="Succeeded",t.Failed="Failed",t.Canceled="Canceled",t))(hr||{}),dr=(t=>(t.Pause="Pause",t.Resume="Resume",t.Cancel="Cancel",t))(dr||{});var fr=(t=>(t.ReadMeta="ReadMeta",t.ReadInput="ReadInput",t.ReadResult="ReadResult",t.ReportProgress="ReportProgress",t.Control="Control",t.Commit="Commit",t.CreateChild="CreateChild",t.Reassign="Reassign",t.Grant="Grant",t.Archive="Archive",t))(fr||{}),pr=(t=>(t.SelfOnly="SelfOnly",t.Subtree="Subtree",t.WholeTree="WholeTree",t))(pr||{}),gr=(t=>(t.MetaOnly="MetaOnly",t.Payload="Payload",t.Full="Full",t))(gr||{}),mr=(t=>(t.User="User",t.System="System",t))(mr||{}),yr=(t=>(t.TaskCreated="TaskCreated",t.RunnerBound="RunnerBound",t.RunnerReleased="RunnerReleased",t.PhaseChanged="PhaseChanged",t.WaitReasonChanged="WaitReasonChanged",t.ProgressReported="ProgressReported",t.ControlProfileChanged="ControlProfileChanged",t.ControlRequested="ControlRequested",t.ControlSuperseded="ControlSuperseded",t.ControlApplied="ControlApplied",t.ControlRejected="ControlRejected",t.AssigneesChanged="AssigneesChanged",t.AccessGranted="AccessGranted",t.AccessRevoked="AccessRevoked",t.ResultCommitted="ResultCommitted",t.TaskFailed="TaskFailed",t.TaskCanceled="TaskCanceled",t.TaskArchived="TaskArchived",t.PayloadRedacted="PayloadRedacted",t))(yr||{});function wr(t,e,n){const r=function(t,e){if(!t||"object"!=typeof t||Array.isArray(t))throw new Fn(`Expected ${e} in TaskMgr response`);return t}(t,n);if(!(e in r))throw new Fn(`Expected ${e} in TaskMgr response`);return r[e]}function br(t){const e=wr(t,"task","task result");if(!e||"object"!=typeof e||"string"!=typeof e.task_id)throw new Fn("Expected a string task_id in TaskMgr response");return e}function Ar(){const t=globalThis.crypto;if(t&&"function"==typeof t.getRandomValues){const e=new Uint8Array(16);return t.getRandomValues(e),`ctl-${Array.from(e,(t=>t.toString(16).padStart(2,"0"))).join("")}`}return`ctl-${Date.now().toString(16)}${Math.random().toString(16).slice(2)}`}class _r{constructor(t){this.rpcClient=t}setSeq(t){this.rpcClient.setSeq(t)}async callTask(t,e){return br(await this.rpcClient.call(t,e))}async createTask(t){return this.callTask("create_task",t)}async getTask(t){return br(await this.rpcClient.call("get_task",{task_id:t}))}async listTasks(t={}){const e=await this.rpcClient.call("list_tasks",t),n=wr(e,"tasks","task summary page");if(!Array.isArray(n))throw new Fn("Expected tasks array in TaskMgr response");return e}async getTaskTree(t){const e=await this.rpcClient.call("get_task_tree",t),n=wr(e,"tasks","task tree page");if(!Array.isArray(n))throw new Fn("Expected tasks array in TaskMgr response");return e}async getSubtasks(t){const e=await this.rpcClient.call("get_subtasks",t),n=wr(e,"tasks","subtask page");if(!Array.isArray(n))throw new Fn("Expected tasks array in TaskMgr response");return e}async archiveTask(t){return this.callTask("archive_task",t)}async requestControl(t){const e=await this.rpcClient.call("request_control",t),n=wr(e,"kind","control result");if("Task"!==n&&"Batch"!==n)throw new Fn(`Invalid TaskMgr control result kind: ${n}`);return e}async updateAssignees(t){return this.callTask("update_assignees",t)}async grantTaskAccess(t){return this.callTask("grant_task_access",t)}async revokeTaskAccess(t){return this.callTask("revoke_task_access",t)}async listTaskAccess(t){const e=wr(await this.rpcClient.call("list_task_access",{task_id:t}),"grants","task access result");if(!Array.isArray(e))throw new Fn("Expected grants array in TaskMgr response");return e}async reportStarted(t){return this.callTask("report_started",t)}async reportProgress(t){return this.callTask("report_progress",t)}async reportWaiting(t){return this.callTask("report_waiting",t)}async reportRunning(t){return this.callTask("report_running",t)}async updateControlProfile(t){return this.callTask("update_control_profile",t)}async ackControl(t){return this.callTask("ack_control",t)}async commitResult(t){return this.callTask("commit_result",t)}async failTask(t){return this.callTask("fail_task",t)}async createPromisedTask(t){return this.callTask("create_promised_task",t)}async setPromiseWait(t){return this.callTask("set_promise_wait",t)}async bindAppExecutor(t){return this.callTask("bind_app_executor",t)}async releaseAppExecutor(t){return this.callTask("release_app_executor",t)}async finishPromiseFailure(t){return this.callTask("finish_promise_failure",t)}async cancelPromisedTask(t){return this.callTask("cancel_promised_task",t)}async registerTaskSchema(t){return this.rpcClient.call("register_task_schema",{definition:t})}async getTaskSchema(t,e){return this.rpcClient.call("get_task_schema",{schema_id:t,schema_version:e})}async listTaskSchemas(t={}){const e=wr(await this.rpcClient.call("list_task_schemas",t),"schemas","task schema list");if(!Array.isArray(e))throw new Fn("Expected schemas array in TaskMgr response");return e}async setTaskSchemaEnabled(t,e,n){return this.rpcClient.call("set_task_schema_enabled",{schema_id:t,schema_version:e,enabled:n})}async listTaskEvents(t){const e=await this.rpcClient.call("list_task_events",t),n=wr(e,"events","task event list");if(!Array.isArray(n))throw new Fn("Expected events array in TaskMgr response");return e}async addTaskNote(t){return wr(await this.rpcClient.call("add_task_note",t),"note","add task note result")}async listTaskNotes(t){const e=wr(await this.rpcClient.call("list_task_notes",{task_id:t}),"notes","task note list");if(!Array.isArray(e))throw new Fn("Expected notes array in TaskMgr response");return e}async cancelTask(t,e=!1){return this.requestControl({task_id:t,action:"Cancel",request_id:Ar(),recursive:e})}snapshotEnvelope(t){return{task_id:t.task_id,app_instance_id:"App"===t.executor.kind?t.executor.app_instance_id:void 0,runner_epoch:t.runner_epoch,expected_revision:t.revision}}async runnerStart(t){const e=await this.getTask(t);let n;if("Accepted"===e.phase)n=this.reportStarted(this.snapshotEnvelope(e));else{if("Waiting"!==e.phase)return e;n=this.reportRunning(this.snapshotEnvelope(e))}try{return await n}catch(r){const e=or(r);if(e===Qn||e===Yn)return this.getTask(t);throw r}}async runnerProgress(t,e,n){const r=await this.getTask(t);if(lr(r.phase))return r;try{return await this.reportProgress({...this.snapshotEnvelope(r),progress:e,message:n})}catch(s){if(or(s)!==Qn)throw s;const r=await this.getTask(t);return this.reportProgress({...this.snapshotEnvelope(r),progress:e,message:n})}}async runnerWait(t,e){const n=await this.runnerStart(t);return"Running"!==n.phase?n:this.reportWaiting({...this.snapshotEnvelope(n),reason:e})}async runnerComplete(t,e){const n=await this.getTask(t);if(lr(n.phase))return n;try{return await this.commitResult({task_id:n.task_id,result:e,app_instance_id:this.snapshotEnvelope(n).app_instance_id,runner_epoch:n.runner_epoch,expected_revision:n.revision})}catch(r){if(or(r)!==Qn)throw r;const n=await this.getTask(t);return lr(n.phase)?n:this.commitResult({task_id:n.task_id,result:e,app_instance_id:this.snapshotEnvelope(n).app_instance_id,runner_epoch:n.runner_epoch,expected_revision:n.revision})}}async runnerFail(t,e,n,r){const s=await this.getTask(t);return lr(s.phase)?s:this.failTask({...this.snapshotEnvelope(s),error:{code:e,message:n,detail:r}})}}var vr=(t=>(t.Autonomous="autonomous",t.HumanConfirm="human_confirm",t.HumanRequired="human_required",t))(vr||{}),Er=(t=>(t.Single="single",t.FiniteSeekable="finite_seekable",t.FiniteSequential="finite_sequential",t))(Er||{}),kr=(t=>(t.All="all",t.Any="any",t.NOfM="n_of_m",t))(kr||{}),Sr=(t=>(t.Human="human",t.Abort="abort",t))(Sr||{}),Tr=(t=>(t.Draft="draft",t.Active="active",t.Archived="archived",t))(Tr||{}),Rr=(t=>(t.Created="created",t.Running="running",t.WaitingHuman="waiting_human",t.Completed="completed",t.Failed="failed",t.Paused="paused",t.Aborted="aborted",t.BudgetExhausted="budget_exhausted",t))(Rr||{}),Ir=(t=>(t.Pending="pending",t.Ready="ready",t.Running="running",t.Completed="completed",t.Failed="failed",t.Retrying="retrying",t.WaitingHuman="waiting_human",t.Skipped="skipped",t.Aborted="aborted",t.Cancelled="cancelled",t))(Ir||{}),Or=(t=>(t.Approve="approve",t.Modify="modify",t.Reject="reject",t.Retry="retry",t.Skip="skip",t.Abort="abort",t.Rollback="rollback",t))(Or||{}),Cr=(t=>(t.Enabled="enabled",t.Paused="paused",t.Archived="archived",t.Error="error",t))(Cr||{}),xr=(t=>(t.Skip="skip",t.RunOnce="run_once",t.CatchUp="catch_up",t.Manual="manual",t))(xr||{}),Nr=(t=>(t.Created="created",t.TaskCreated="task_created",t.Skipped="skipped",t.Failed="failed",t))(Nr||{});function Pr(t,e){if(!(e in t))throw new Fn(`Expected ${e} in workflow response`);return t[e]}class Dr{constructor(t){this.rpcClient=t}setSeq(t){this.rpcClient.setSeq(t)}async callOk(t,e){const n=function(t){if(!t||"object"!=typeof t||Array.isArray(t))throw new Fn("Invalid workflow RPC response format");return t}(await this.rpcClient.call(t,e));if(!0===n.ok)return n;const r="string"==typeof n.message?n.message:"string"==typeof n.error?n.error:"workflow request failed";throw new Fn(r)}async submitDefinition(t){const e=await this.callOk("submit_definition",t);return{workflow_id:Pr(e,"workflow_id"),version:Pr(e,"version"),analysis:Pr(e,"analysis"),definition:Pr(e,"definition")}}async getDefinition(t){return Pr(await this.callOk("get_definition",{workflow_id:t}),"definition")}async listDefinitions(t={}){return Pr(await this.callOk("list_definitions",t),"definitions")}async archiveDefinition(t){return Pr(await this.callOk("archive_definition",{workflow_id:t}),"status")}async dryRun(t){const e=await this.callOk("dry_run",{definition:t});return{analysis:Pr(e,"analysis"),graph:Pr(e,"graph")}}async createRun(t){return await this.callOk("create_run",t)}async startRun(t){return await this.callOk("start_run",{run_id:t})}async tickRun(t){return await this.callOk("tick_run",{run_id:t})}async getRunGraph(t){return await this.callOk("get_run_graph",{run_id:t})}async listRuns(t={}){return Pr(await this.callOk("list_runs",t),"runs")}async submitStepOutput(t){return await this.callOk("submit_step_output",t)}async reportStepProgress(t){return await this.callOk("report_step_progress",t)}async requestHuman(t){return await this.callOk("request_human",t)}async submitAmendment(t){return Pr(await this.callOk("submit_amendment",t),"amendment")}async approveAmendment(t){const e=await this.callOk("approve_amendment",t);return{amendment:Pr(e,"amendment"),plan_version:Pr(e,"plan_version")}}async rejectAmendment(t){const e=await this.callOk("reject_amendment",t);return{amendment:Pr(e,"amendment"),plan_version:Pr(e,"plan_version")}}async getHistory(t){return await this.callOk("get_history",t)}async subscribeEvents(t){return await this.callOk("subscribe_events",t)}async createScheduledTask(t){return Pr(await this.callOk("create_scheduled_task",t),"schedule")}async updateScheduledTask(t){return Pr(await this.callOk("update_scheduled_task",t),"schedule")}async getScheduledTask(t){return Pr(await this.callOk("get_scheduled_task",{schedule_id:t}),"schedule")}async listScheduledTasks(t={}){return Pr(await this.callOk("list_scheduled_tasks",t),"schedules")}async pauseScheduledTask(t){return Pr(await this.callOk("pause_scheduled_task",{schedule_id:t}),"schedule")}async resumeScheduledTask(t){return Pr(await this.callOk("resume_scheduled_task",{schedule_id:t}),"schedule")}async archiveScheduledTask(t){return Pr(await this.callOk("archive_scheduled_task",{schedule_id:t}),"schedule")}async runScheduledTaskNow(t){return Pr(await this.callOk("run_scheduled_task_now",t),"fire")}async getScheduledTaskHistory(t){return Pr(await this.callOk("get_scheduled_task_history",t),"fires")}async validateScheduledTask(t){return await this.callOk("validate_scheduled_task",t)}}const Br=["services/","system/rbac/"];class Ur{constructor(t,e=null,n={}){this.configCache=new Map,this.rpcClient=new jn(t,e,null,n)}setSeq(t){this.rpcClient.setSeq(t)}async syncSessionToken(t){this.rpcClient.setSessionToken(t)}getSessionToken(){return this.rpcClient.getSessionToken()}needCache(t){return Br.some((e=>t.startsWith(e)))}getUnixTimestamp(){return Math.floor(Date.now()/1e3)}getConfigCache(t){const e=this.configCache.get(t);return e?e.cachedAt+10<this.getUnixTimestamp()?(this.configCache.delete(t),null):e:null}setConfigCache(t,e,n){if(!this.needCache(t))return!0;const r=this.configCache.get(t);return this.configCache.set(t,{value:e,version:n,cachedAt:this.getUnixTimestamp()}),!r||(r.value!==e||r.version!==n)}removeConfigCache(t){this.configCache.delete(t)}async get(t){const e=this.getConfigCache(t);if(null!=e)return{value:e.value,version:e.version,is_changed:!1};const n=await this.rpcClient.call("sys_config_get",{key:t});if(null==n)throw new Error(`system_config key not found: ${t}`);if("string"!=typeof n.value||"number"!=typeof n.version)throw new Error(`invalid sys_config_get response for key: ${t}`);const r=this.setConfigCache(t,n.value,n.version);return{value:n.value,version:n.version,is_changed:r}}async set(t,e){if(!t||!e)throw new Error("key or value is empty");if(t.includes(":"))throw new Error("key can not contain ':'");return await this.rpcClient.call("sys_config_set",{key:t,value:e}),this.removeConfigCache(t),0}async setByJsonPath(t,e,n){return await this.rpcClient.call("sys_config_set_by_json_path",{key:t,json_path:e,value:n}),this.removeConfigCache(t),0}async create(t,e){return await this.rpcClient.call("sys_config_create",{key:t,value:e}),this.removeConfigCache(t),0}async delete(t){return await this.rpcClient.call("sys_config_delete",{key:t}),this.removeConfigCache(t),0}async append(t,e){return await this.rpcClient.call("sys_config_append",{key:t,append_value:e}),this.removeConfigCache(t),0}async list(t){return this.rpcClient.call("sys_config_list",{key:t})}async execTx(t,e){const n={actions:t};e&&(n.main_key=`${e[0]}:${e[1]}`),await this.rpcClient.call("sys_config_exec_tx",n);for(const r of Object.keys(t))this.removeConfigCache(r);return 0}async dumpConfigsForScheduler(){return this.rpcClient.call("dump_configs_for_scheduler",{})}async refreshTrustKeys(){await this.rpcClient.call("sys_refresh_trust_keys",{})}}const Lr={CHAT_COMPLETIONS_CREATE:"chat.completions.create",IMAGES_GENERATE:"images.generate",EMBEDDING_TEXT:"embedding.text",EMBEDDING_MULTIMODAL:"embedding.multimodal",RERANK:"rerank",DECISION_EVALUATE:"decision.evaluate",IMAGE_IMG2IMG:"image.img2img",IMAGE_INPAINT:"image.inpaint",IMAGE_UPSCALE:"image.upscale",IMAGE_BG_REMOVE:"image.bg_remove",VISION_OCR:"vision.ocr",VISION_CAPTION:"vision.caption",VISION_DETECT:"vision.detect",VISION_SEGMENT:"vision.segment",AUDIO_TTS:"audio.tts",AUDIO_ASR:"audio.asr",AUDIO_MUSIC:"audio.music",AUDIO_ENHANCE:"audio.enhance",VIDEO_TXT2VIDEO:"video.txt2video",VIDEO_IMG2VIDEO:"video.img2video",VIDEO_VIDEO2VIDEO:"video.video2video",VIDEO_EXTEND:"video.extend",VIDEO_UPSCALE:"video.upscale",AGENT_COMPUTER_USE:"agent.computer_use"},Mr={ROUTE_RESOLVE:"route.resolve",HELPER_LLM_CHAT:"helper.llm_chat",HELPER_TEXT_TO_IMAGE:"helper.text_to_image",CANCEL:"cancel"},Fr={SERVICE_RELOAD_SETTINGS:"service.reload_settings",QUOTA_QUERY:"quota.query",USAGE_QUERY:"usage.query",TRACE_QUERY:"trace.query",ROUTING_GET:"routing.get",ROUTING_PREVIEW:"routing.preview",ROUTING_UPDATE:"routing.update",PROVIDER_CATALOG:"provider.catalog",PROTOCOL_ADAPTER_LIST:"protocol_adapter.list",PROVIDER_VALIDATE:"provider.validate",PROVIDER_ADD:"provider.add",PROVIDER_LIST:"provider.list",PROVIDER_HEALTH:"provider.health",PROVIDER_UPDATE:"provider.update",PROVIDER_DELETE:"provider.delete",PROVIDER_REFRESH_MODELS:"provider.refresh_models",MODELS_LIST:"models.list",DRIVER_METADATA_UPDATE_GET:"driver_metadata_update.get",DRIVER_METADATA_UPDATE_SET:"driver_metadata_update.set"},Gr={...Lr,...Mr,...Fr},jr={IMMEDIATE:"immediate",STREAM:"stream"},Hr=new Set(Object.values(Lr));function Vr(t){const e={system:["text"],developer:["text"],user:["text","image","document"],assistant:["text","image","document","tool_use","thinking","provider_state"],tool:["tool_result"]};if(!t||!Array.isArray(t.content)||!e[t.role])throw new Fn("invalid AiMessage");if("tool"===t.role&&(1!==t.content.length||"tool_result"!==t.content[0].type))throw new Fn("role Tool requires exactly one ToolResult block");for(const n of t.content){if(!e[t.role].includes(n.type))throw new Fn(`AiMessage role ${t.role} cannot contain ${n.type} content`);if(("tool_use"===n.type||"tool_result"===n.type)&&!n.call_id)throw new Fn(`${n.type} requires call_id`);if("tool_result"===n.type&&0===n.content.length)throw new Fn("tool_result requires non-empty content")}}function Wr(t){if(!t||2!==t.split("@").length||t.startsWith("@")||t.endsWith("@"))throw new Fn("exact_model must be `<provider_model_id>[:<variant>]@<provider_instance_name>`")}function Kr(t){if(!(null==t?void 0:t.trim())||t.includes("@"))throw new Fn("logical_model must be a non-empty logical path without `@`")}function zr(t,e){for(const s of Object.keys(t))if(!e.includes(s))throw new Fn(`unknown field \`${s}\``);const n=t.execution_mode;if(void 0!==n&&n!==jr.IMMEDIATE&&n!==jr.STREAM)throw new Fn("execution_mode must be `immediate` or `stream`");const r=t.session_id;if(void 0!==r&&("string"!=typeof r||!r.trim()||(new TextEncoder).encode(r).length>512))throw new Fn("session_id must contain 1..512 bytes")}const qr=["exact_model","trace_id","execution_mode","idempotency_key","task_options","session_id"],$r={[Lr.CHAT_COMPLETIONS_CREATE]:[...qr,"messages","tools","response_format","temperature","top_p","max_output_tokens","seed","stop","output"],[Lr.IMAGES_GENERATE]:[...qr,"prompt","negative_prompt","n","aspect_ratio","size","quality","style","seed","output"],[Lr.EMBEDDING_TEXT]:[...qr,"items","chunking","embedding_space_id","dimensions","normalize","prefer_artifact"],[Lr.EMBEDDING_MULTIMODAL]:[...qr,"items","dimensions","normalize"],[Lr.DECISION_EVALUATE]:[...qr,"state","questions"],[Lr.RERANK]:[...qr,"query","documents","n","return_documents"],[Lr.IMAGE_IMG2IMG]:[...qr,"images","prompt","strength","output"],[Lr.IMAGE_INPAINT]:[...qr,"image","mask","prompt","mask_semantics","output"],[Lr.IMAGE_UPSCALE]:[...qr,"image","scale","target_width","target_height","preserve_faces","output"],[Lr.IMAGE_BG_REMOVE]:[...qr,"image","mode","output"],[Lr.VISION_OCR]:[...qr,"document","level","language_hints","return_layout","return_artifacts"],[Lr.VISION_CAPTION]:[...qr,"image","style","language","n"],[Lr.VISION_DETECT]:[...qr,"image","classes","score_threshold","bbox_spec"],[Lr.VISION_SEGMENT]:[...qr,"image","prompt","mask_format","return_bitmap_mask"],[Lr.AUDIO_TTS]:[...qr,"text","voice","speed","output"],[Lr.AUDIO_ASR]:[...qr,"audio","language","timestamps","diarization","output_formats"],[Lr.AUDIO_MUSIC]:[...qr,"prompt","duration_seconds","instrumental","lyrics","seed","output"],[Lr.AUDIO_ENHANCE]:[...qr,"audio","task","strength","return_stems"],[Lr.VIDEO_TXT2VIDEO]:[...qr,"prompt","duration_seconds","aspect_ratio","resolution","generate_audio","seed","output"],[Lr.VIDEO_IMG2VIDEO]:[...qr,"image","prompt","duration_seconds","aspect_ratio","resolution"],[Lr.VIDEO_VIDEO2VIDEO]:[...qr,"video","prompt","preserve_motion","time_range"],[Lr.VIDEO_EXTEND]:[...qr,"video","prompt","continuation_handle","duration_seconds","resolution"],[Lr.VIDEO_UPSCALE]:[...qr,"video","target_resolution","denoise","sharpen","output"],[Lr.AGENT_COMPUTER_USE]:[...qr,"task","environment","allowed_actions"],[Mr.ROUTE_RESOLVE]:["trace_id","execution_mode","request_id","api_type","logical_model","requirements","disable","policy","estimated_input_tokens","estimated_output_tokens","session_overlay","session_id"],[Mr.HELPER_LLM_CHAT]:["logical_model","trace_id","execution_mode","requirements","disable","policy","messages","tools","response_format","temperature","top_p","max_output_tokens","seed","stop","output","idempotency_key","task_options","session_overlay","session_id"],[Mr.HELPER_TEXT_TO_IMAGE]:["logical_model","trace_id","execution_mode","requirements","disable","policy","prompt","negative_prompt","n","aspect_ratio","size","quality","style","seed","output","idempotency_key","task_options","session_overlay","session_id"],[Mr.CANCEL]:["task_id"],[Fr.SERVICE_RELOAD_SETTINGS]:[],[Fr.QUOTA_QUERY]:["capability","method"],[Fr.USAGE_QUERY]:["time_range","filters","group_by","time_bucket","output_mode","limit","cursor"],[Fr.TRACE_QUERY]:["limit","cursor","start_time_ms","end_time_ms","task_ids","request_ids","api_types","provider_instance_names","selected_exact_models","scheduler_profiles","query","outcome"],[Fr.ROUTING_GET]:[],[Fr.ROUTING_PREVIEW]:["paths","explain","requirements"],[Fr.ROUTING_UPDATE]:["settings_revision","provider_weights"],[Fr.PROVIDER_CATALOG]:[],[Fr.PROTOCOL_ADAPTER_LIST]:[],[Fr.PROVIDER_VALIDATE]:["provider_instance_name","provider_type","provider_profile_id","protocol_family_id","protocol_adapter_id","base_url","credentials","region","workspace","account","provider_rules_id","auth","discovery","instance_rules","timeout_ms","auto_sync_models"],[Fr.PROVIDER_ADD]:["provider_instance_name","provider_type","provider_profile_id","protocol_family_id","protocol_adapter_id","base_url","credentials","region","workspace","account","provider_rules_id","auth","discovery","instance_rules","timeout_ms","auto_sync_models"],[Fr.PROVIDER_LIST]:["method"],[Fr.PROVIDER_HEALTH]:["exact_model"],[Fr.PROVIDER_UPDATE]:["provider_instance_name","settings_revision","enabled","base_url","credential","provider_profile_id","protocol_adapter_id","discovery","instance_rules"],[Fr.PROVIDER_DELETE]:["provider_instance_name"],[Fr.PROVIDER_REFRESH_MODELS]:["provider_instance_name"],[Fr.MODELS_LIST]:[],[Fr.DRIVER_METADATA_UPDATE_GET]:[],[Fr.DRIVER_METADATA_UPDATE_SET]:["enabled","source_url","interval_secs"]};class Qr{constructor(t){this.rpcClient=t}setSeq(t){this.rpcClient.setSeq(t)}call(t,e){const n=$r[t],r=(null==n?void 0:n.includes("execution_mode"))&&void 0===e.execution_mode?{...e,execution_mode:jr.IMMEDIATE}:e;return n&&zr(r,n),this.rpcClient.call(t,r)}inference(t,e){return Wr(e.exact_model),this.call(t,e)}routeResolve(t){return Kr(t.logical_model),this.call(Mr.ROUTE_RESOLVE,t)}chatCompletionsCreate(t){return t.messages.forEach(Vr),this.inference(Lr.CHAT_COMPLETIONS_CREATE,t)}imagesGenerate(t){return this.inference(Lr.IMAGES_GENERATE,t)}helperLlmChat(t){return Kr(t.logical_model),t.messages.forEach(Vr),this.call(Mr.HELPER_LLM_CHAT,t)}helperTextToImage(t){return Kr(t.logical_model),this.call(Mr.HELPER_TEXT_TO_IMAGE,t)}embeddingText(t){return this.inference(Lr.EMBEDDING_TEXT,t)}embeddingMultimodal(t){return this.inference(Lr.EMBEDDING_MULTIMODAL,t)}async decisionEvaluate(t){es(t);const e=await this.inference(Lr.DECISION_EVALUATE,t);return"succeeded"===e.status&&ns(t,e.answers??[]),e}rerank(t){return this.inference(Lr.RERANK,t)}imageToImage(t){return this.inference(Lr.IMAGE_IMG2IMG,t)}imageInpaint(t){return this.inference(Lr.IMAGE_INPAINT,t)}imageUpscale(t){return this.inference(Lr.IMAGE_UPSCALE,t)}imageBackgroundRemove(t){return this.inference(Lr.IMAGE_BG_REMOVE,t)}visionOcr(t){return this.inference(Lr.VISION_OCR,t)}visionCaption(t){return this.inference(Lr.VISION_CAPTION,t)}visionDetect(t){return this.inference(Lr.VISION_DETECT,t)}visionSegment(t){return this.inference(Lr.VISION_SEGMENT,t)}audioTextToSpeech(t){return this.inference(Lr.AUDIO_TTS,t)}audioSpeechRecognition(t){return this.inference(Lr.AUDIO_ASR,t)}audioMusic(t){return this.inference(Lr.AUDIO_MUSIC,t)}audioEnhance(t){return this.inference(Lr.AUDIO_ENHANCE,t)}videoTextToVideo(t){return this.inference(Lr.VIDEO_TXT2VIDEO,t)}videoImageToVideo(t){return this.inference(Lr.VIDEO_IMG2VIDEO,t)}videoToVideo(t){return this.inference(Lr.VIDEO_VIDEO2VIDEO,t)}videoExtend(t){return this.inference(Lr.VIDEO_EXTEND,t)}videoUpscale(t){return this.inference(Lr.VIDEO_UPSCALE,t)}computerUse(t){return this.inference(Lr.AGENT_COMPUTER_USE,t)}cancel(t){if(!t)throw new Fn("cancel requires non-empty task_id");return this.call(Mr.CANCEL,{task_id:t})}reloadSettings(){return this.call(Fr.SERVICE_RELOAD_SETTINGS,{})}queryQuota(t={}){return this.call(Fr.QUOTA_QUERY,t)}queryUsage(t){return this.call(Fr.USAGE_QUERY,t)}queryTrace(t={}){return this.call(Fr.TRACE_QUERY,t)}previewRouting(t={}){return this.call(Fr.ROUTING_PREVIEW,t)}getRouting(){return this.call(Fr.ROUTING_GET,{})}updateRouting(t){return this.call(Fr.ROUTING_UPDATE,t)}providerCatalog(){return this.call(Fr.PROVIDER_CATALOG,{})}listProtocolAdapters(){return this.call(Fr.PROTOCOL_ADAPTER_LIST,{})}validateProvider(t){return this.call(Fr.PROVIDER_VALIDATE,t)}addProvider(t){return this.call(Fr.PROVIDER_ADD,t)}listProviders(t={}){return this.call(Fr.PROVIDER_LIST,t)}providerHealth(t){return Wr(t.exact_model),this.call(Fr.PROVIDER_HEALTH,t)}updateProvider(t){return this.call(Fr.PROVIDER_UPDATE,t)}deleteProvider(t){return this.call(Fr.PROVIDER_DELETE,t)}refreshProviderModels(t){return this.call(Fr.PROVIDER_REFRESH_MODELS,t)}listModels(){return this.call(Fr.MODELS_LIST,{})}getDriverMetadataUpdate(){return this.call(Fr.DRIVER_METADATA_UPDATE_GET,{})}setDriverMetadataUpdate(t){return this.call(Fr.DRIVER_METADATA_UPDATE_SET,t)}}function Jr(t,e=!0){return"string"==typeof t?!e||t.trim().length>0:null!==t&&"object"==typeof t&&(!e||Object.keys(t).length>0)}function Yr(t){return"string"==typeof t&&/^[A-Za-z0-9_.-]{1,128}$/.test(t)}function Zr(t){return null===t||"object"!=typeof t?JSON.stringify(t):Array.isArray(t)?`[${t.map(Zr).join(",")}]`:`{${Object.keys(t).sort().map((e=>`${JSON.stringify(e)}:${Zr(t[e])}`)).join(",")}}`}function Xr(t){return(new TextEncoder).encode(JSON.stringify(t)).length}function ts(t){const e=Xr(t.state),n={question_types:[],structured_state:"string"!=typeof t.state,structured_rules:!1,question_count:t.questions.length,max_options:0,max_levels:0,input_bytes:e+Xr(t.questions),max_state_question_bytes:0};for(const r of t.questions){n.question_types.includes(r.type)||n.question_types.push(r.type);const t=[r.instructions];"choice"===r.type?(n.max_options=Math.max(n.max_options,r.options.length),t.push(...r.options.map((t=>t.description)))):"score"===r.type?(n.max_levels=Math.max(n.max_levels,r.levels.length),t.push(...r.levels)):r.criteria&&t.push(...Object.values(r.criteria)),n.structured_rules||(n.structured_rules=t.some((t=>null!==t&&"object"==typeof t))),n.max_state_question_bytes=Math.max(n.max_state_question_bytes,e+Xr(r))}return{decision:n}}function es(t){if(Wr(t.exact_model),zr(t,$r[Lr.DECISION_EVALUATE]),!Jr(t.state,!1)||!Array.isArray(t.questions)||!t.questions.length||t.questions.length>1024)throw new Fn("decision requires a text/JSON state and 1..1024 questions");const e=new Set;for(const n of t.questions){if(!n||!Yr(n.id)||e.has(n.id)||!Jr(n.instructions))throw new Fn("invalid decision question");if(e.add(n.id),"choice"===n.type){if(zr(n,["type","id","instructions","options"]),!Array.isArray(n.options)||!n.options.length||n.options.length>1024)throw new Fn("invalid decision options");const t=new Set;for(const e of n.options){if(zr(e,["id","description"]),!Yr(e.id)||t.has(e.id)||null!==e.description&&!Jr(e.description))throw new Fn("invalid decision option");t.add(e.id)}}else if("score"===n.type){if(zr(n,["type","id","instructions","levels"]),!Array.isArray(n.levels)||n.levels.length<2||n.levels.length>1024||n.levels.some((t=>!Jr(t)))||new Set(n.levels.map(Zr)).size!==n.levels.length)throw new Fn("invalid decision levels")}else{if("boolean"!==n.type)throw new Fn("invalid decision question type");if(zr(n,["type","id","instructions","criteria"]),void 0!==n.criteria){if(null===n.criteria||"object"!=typeof n.criteria||Array.isArray(n.criteria))throw new Fn("invalid decision criteria");if(zr(n.criteria,["true","false"]),Object.values(n.criteria).some((t=>!Jr(t))))throw new Fn("invalid decision criteria")}}}if(ts(t).decision.input_bytes>1048576)throw new Fn("decision input exceeds 1 MiB")}function ns(t,e){const n=t=>"number"==typeof t&&Number.isFinite(t)&&t>=0&&t<=1,r=()=>{throw new Fn("invalid or incomplete decision answers")};Array.isArray(e)&&e.length===t.questions.length||r();const s=new Set;for(const i of e){i&&!s.has(i.id)||r(),s.add(i.id);const e=t.questions.find((t=>t.id===i.id));if(!e)throw new Fn("unknown decision question ID");if((e.type!==i.type||void 0!==i.confidence&&!n(i.confidence))&&r(),"boolean"===i.type){zr(i,["type","id","probability_true","confidence"]),n(i.probability_true)||r();continue}zr(i,"choice"===i.type?["type","id","selected","probabilities","confidence"]:["type","id","score","levels","probabilities","confidence"]);const o="choice"===e.type?e.options.map((t=>t.id)):"score"===e.type?e.levels.map(((t,e)=>String(e))):[];if((!i.probabilities||Array.isArray(i.probabilities)||Object.keys(i.probabilities).length!==o.length||o.some((t=>!Object.prototype.hasOwnProperty.call(i.probabilities,t)||!n(i.probabilities[t])))||Math.abs(Object.values(i.probabilities).reduce(((t,e)=>t+e),0)-1)>1e-4)&&r(),"choice"===i.type)o.includes(i.selected)&&!Object.values(i.probabilities).some((t=>t>i.probabilities[i.selected]+1e-4))||r();else if("score"===i.type&&"score"===e.type){const t=o.reduce(((t,e,n)=>t+n*i.probabilities[e]),0);(!Number.isFinite(i.score)||i.score<0||i.score>o.length-1||Math.abs(i.score-t)>1e-4*(o.length-1)||Zr(i.levels)!==Zr(e.levels))&&r()}else r()}}const rs={max_messages:null,retention_seconds:null,sync_write:!1,other_app_can_read:!0,other_app_can_write:!1,other_user_can_read:!1,other_user_can_write:!1};function ss(t,e){if("number"!=typeof t||!Number.isFinite(t))throw new Fn(`expected ${e} to be a number`);return t}function is(t,e){if("string"!=typeof t)throw new Fn(`expected ${e} to be a string`);return t}function os(t){if(!Array.isArray(t))throw new Fn("expected message list to be an array");return t.map(((t,e)=>{if(!t||"object"!=typeof t||Array.isArray(t))throw new Fn(`message[${e}] is not an object`);const n=t;return{index:ss(n.index,`message[${e}].index`),created_at:ss(n.created_at,`message[${e}].created_at`),payload:Array.isArray(n.payload)?n.payload:[],headers:n.headers&&"object"==typeof n.headers&&!Array.isArray(n.headers)?n.headers:{}}}))}class as{constructor(t){this.rpcClient=t}setSeq(t){this.rpcClient.setSeq(t)}async createQueue(t,e,n,r={...rs}){return is(await this.rpcClient.call("create_queue",{name:t,appid:e,app_owner:n,config:r}),"queue_urn")}async deleteQueue(t){await this.rpcClient.call("delete_queue",{queue_urn:t})}async getQueueStats(t){const e=await this.rpcClient.call("get_queue_stats",{queue_urn:t});if(!e||"object"!=typeof e)throw new Fn("invalid get_queue_stats response");const n=e;return{message_count:ss(n.message_count,"message_count"),first_index:ss(n.first_index,"first_index"),last_index:ss(n.last_index,"last_index"),size_bytes:ss(n.size_bytes,"size_bytes")}}async updateQueueConfig(t,e){await this.rpcClient.call("update_queue_config",{queue_urn:t,config:e})}async postMessage(t,e){return ss(await this.rpcClient.call("post_message",{queue_urn:t,message:e}),"msg_index")}async subscribe(t){return is(await this.rpcClient.call("subscribe",{queue_urn:t.queueUrn,userid:t.userId,appid:t.appId,sub_id:t.subId??null,position:t.position}),"subscription_id")}async unsubscribe(t){await this.rpcClient.call("unsubscribe",{sub_id:t})}async fetchMessages(t,e,n){return os(await this.rpcClient.call("fetch_messages",{sub_id:t,length:e,auto_commit:n}))}async readMessage(t,e,n){return os(await this.rpcClient.call("read_message",{queue_urn:t,cursor:e,length:n}))}async commitAck(t,e){await this.rpcClient.call("commit_ack",{sub_id:t,index:e})}async seek(t,e){await this.rpcClient.call("seek",{sub_id:t,index:e})}async deleteMessageBefore(t,e){return ss(await this.rpcClient.call("delete_message_before",{queue_urn:t,index:e}),"deleted_count")}}function cs(t){const e={};for(const[n,r]of Object.entries(t))void 0!==r&&(e[n]=r);return e}function ls(t,e){if(!t||"object"!=typeof t||Array.isArray(t))throw new Fn(`expected ${e} to be an object`);return t}function us(t,e){return null==t?null:ls(t,e)}function hs(t,e){if(!Array.isArray(t))throw new Fn(`expected ${e} to be an array`);return t}function ds(t,e){if("string"!=typeof t)throw new Fn(`${e} expected to return a DID string`);return t}class fs{constructor(t){this.rpcClient=t}setSeq(t){this.rpcClient.setSeq(t)}call(t,e){return this.rpcClient.call(t,e)}async dispatch(t,e,n){return ls(await this.call("msg.dispatch",cs({msg:t,ingress_ctx:e,idempotency_key:n})),"DispatchResult")}async postSend(t,e){return ls(await this.call("msg.post_send",cs({msg:t,idempotency_key:e})),"PostSendResult")}async listMailboxes(t,e){return hs(await this.call("msg.list_mailboxes",{owner:t,box_kind:e}),"Vec<MailboxAddress>")}async moveRecord(t,e){return ls(await this.call("msg.move_record",{record_id:t,mailbox:e}),"MailboxRecord")}async getNext(t){return us(await this.call("msg.get_next",cs({...t})),"MailboxRecordWithObject")}async getNextDelivery(t){return us(await this.call("msg.get_next_delivery",cs({...t})),"DeliveryRecordWithObject")}async peekBox(t){return hs(await this.call("msg.peek_box",cs({...t})),"Vec<MailboxRecordWithObject>")}async listBoxByTime(t){const e=ls(await this.call("msg.list_box_by_time",cs({...t})),"MailboxRecordPage");return{...e,items:Array.isArray(e.items)?e.items:[]}}async listSessions(t){const e=ls(await this.call("msg.list_sessions",cs({...t})),"SessionSummaryPage");return{...e,items:Array.isArray(e.items)?e.items:[]}}async listSession(t){const e=ls(await this.call("msg.list_session",cs({...t})),"SessionMessagePage");return{...e,items:Array.isArray(e.items)?e.items:[]}}async updateRecordState(t,e){return ls(await this.call("msg.update_record_state",{record_id:t,new_state:e}),"MailboxRecord")}async updateRecordSession(t,e){return ls(await this.call("msg.update_record_session",{record_id:t,session_id:e}),"MailboxRecord")}async reportDelivery(t,e){return ls(await this.call("msg.report_delivery",{delivery_id:t,result:e}),"DeliveryRecord")}async setReadState(t){return ls(await this.call("msg.set_read_state",cs({...t})),"MsgReceiptObj")}async listReadReceipts(t){return hs(await this.call("msg.list_read_receipts",cs({...t})),"Vec<MsgReceiptObj>")}async getRecord(t,e){return us(await this.call("msg.get_record",cs({record_id:t,with_object:e})),"MailboxRecordWithObject")}async getMessage(t){return us(await this.call("msg.get_message",{msg_id:t}),"MsgObject")}async updateUiSessionState(t,e,n){return ls(await this.call("ui_session.update_state",{session_id:t,key:e,value:n}),"UiSessionStateEntry")}async getUiSessionState(t,e){return us(await this.call("ui_session.get_state",{session_id:t,key:e}),"UiSessionStateEntry")}async listUiSessionState(t){return hs(await this.call("ui_session.list_state",{session_id:t}),"Vec<UiSessionStateEntry>")}async resolveDid(t,e,n,r){return ds(await this.call("contact.resolve_did",cs({platform:t,account_id:e,profile_hint:n,contact_mgr_owner:r})),"contact.resolve_did")}async resolveEndpointDid(t,e,n,r,s){return ds(await this.call("contact.resolve_endpoint_did",cs({platform:t,account_id:e,account_type:n,tunnel_instance_id:r,contact_mgr_owner:s})),"contact.resolve_endpoint_did")}async resolveTarget(t,e,n){return ds(await this.call("contact.resolve_target",cs({contact_did:t,selector:e,contact_mgr_owner:n})),"contact.resolve_target")}async resolveContactForEndpoint(t,e){const n=await this.call("contact.resolve_contact_for_endpoint",cs({endpoint_did:t,contact_mgr_owner:e}));return s="contact.resolve_contact_for_endpoint",null==(r=n)?null:ds(r,s);var r,s}async resolveCanonicalDid(t,e){return ds(await this.call("contact.resolve_canonical_did",cs({did:t,contact_mgr_owner:e})),"contact.resolve_canonical_did")}async listAliasDids(t,e){return hs(await this.call("contact.list_alias_dids",cs({canonical_did:t,contact_mgr_owner:e})),"Vec<DID>")}async getPreferredBinding(t,e){return ls(await this.call("contact.get_preferred_binding",cs({did:t,contact_mgr_owner:e})),"AccountBinding")}async checkAccessPermission(t,e,n){return ls(await this.call("contact.check_access_permission",cs({did:t,context_id:e,contact_mgr_owner:n})),"AccessDecision")}async grantTemporaryAccess(t,e,n,r){const s=ls(await this.call("contact.grant_temporary_access",cs({dids:t,context_id:e,duration_secs:n,contact_mgr_owner:r})),"GrantTemporaryAccessResult");return{updated:Array.isArray(s.updated)?s.updated:[]}}async blockContact(t,e,n){await this.call("contact.block_contact",cs({did:t,reason:e,contact_mgr_owner:n}))}async importContacts(t,e,n){return ls(await this.call("contact.import_contacts",cs({contacts:t,upgrade_to_friend:e,contact_mgr_owner:n})),"ImportReport")}async mergeContacts(t,e,n){return ls(await this.call("contact.merge_contacts",cs({target_did:t,source_did:e,contact_mgr_owner:n})),"Contact")}async updateContact(t,e,n){return ls(await this.call("contact.update_contact",cs({did:t,patch:e,contact_mgr_owner:n})),"Contact")}async getContact(t,e){return us(await this.call("contact.get_contact",cs({did:t,contact_mgr_owner:e})),"Contact")}async listContacts(t,e){return hs(await this.call("contact.list_contacts",cs({query:t,contact_mgr_owner:e})),"Vec<Contact>")}async getGroupSubscribers(t,e,n,r){return hs(await this.call("contact.get_group_subscribers",cs({group_id:t,limit:e,offset:n,contact_mgr_owner:r})),"Vec<DID>")}async setGroupSubscribers(t,e,n){const r=ls(await this.call("contact.set_group_subscribers",cs({group_id:t,subscribers:e,contact_mgr_owner:n})),"SetGroupSubscribersResult");if("string"!=typeof r.group_id||"number"!=typeof r.subscriber_count)throw new Fn("Invalid SetGroupSubscribersResult");return{group_id:r.group_id,subscriber_count:r.subscriber_count}}async groupCreate(t){return ls(await this.call("group.create",t),"GroupDoc")}async groupGetDoc(t){return us(await this.call("group.get_doc",t),"GroupDoc")}async groupUpdateProfile(t){return ls(await this.call("group.update_profile",t),"GroupDoc")}async groupInviteMember(t){return ls(await this.call("group.invite_member",t),"GroupMemberRecord")}async groupSubmitMemberProof(t){return ls(await this.call("group.submit_member_proof",t),"GroupMemberRecord")}async groupRequestJoin(t){return ls(await this.call("group.request_join",t),"GroupMemberRecord")}async groupApproveMember(t){return ls(await this.call("group.approve_member",t),"GroupMemberRecord")}async groupRejectMember(t){return ls(await this.call("group.reject_member",t),"GroupMemberRecord")}async groupRemoveMember(t){return ls(await this.call("group.remove_member",t),"GroupMemberRecord")}async groupUpdateMemberRole(t){return ls(await this.call("group.update_member_role",t),"GroupMemberRecord")}async groupListMembers(t){return hs(await this.call("group.list_members",t),"Vec<GroupMemberRecord>")}async groupCreateSubgroup(t){return ls(await this.call("group.create_subgroup",t),"GroupSubgroup")}async groupUpdateSubgroup(t){return ls(await this.call("group.update_subgroup",t),"GroupSubgroup")}async groupListSubgroups(t){return hs(await this.call("group.list_subgroups",t),"Vec<GroupSubgroup>")}async groupUpdateCollectionPolicy(t){return ls(await this.call("group.update_collection_policy",t),"GroupDoc")}async groupUpdateAttributionPolicy(t){return ls(await this.call("group.update_attribution_policy",t),"GroupDoc")}async groupExpandMembers(t){return ls(await this.call("group.expand_members",t),"GroupExpansionSnapshot")}async groupListByMember(t){return hs(await this.call("group.list_by_member",t),"Vec<GroupSummary>")}async groupListParents(t){return hs(await this.call("group.list_parents",t),"Vec<GroupSummary>")}async groupCheckAccess(t){return ls(await this.call("group.check_access",t),"GroupAccessDecision")}}function ps(t){const e={};for(const[n,r]of Object.entries(t))void 0!==r&&(e[n]=r);return e}function gs(t,e){if("string"!=typeof t)throw new Fn(`expected ${e} to be a string`);return t}function ms(t,e){if("boolean"!=typeof t)throw new Fn(`expected ${e} to be a boolean`);return t}function ys(t,e){if("number"!=typeof t||!Number.isFinite(t))throw new Fn(`expected ${e} to be a number`);return t}function ws(t,e){if(!Array.isArray(t))throw new Fn(`expected ${e} to be an array`);return t}function bs(t,e){if(!t||"object"!=typeof t||Array.isArray(t))throw new Fn(`expected ${e} to be an object`);return t}class As{constructor(t){this.rpcClient=t}setSeq(t){this.rpcClient.setSeq(t)}async store(t){return gs(await this.rpcClient.call("store",{content_id:t}),"ObjId")}async collect(t,e){return gs(await this.rpcClient.call("collect",ps({content_meta:t,referral_proof:e})),"content_id")}async pin(t,e){return ms(await this.rpcClient.call("pin",{content_id:t,download_proof:e}),"pin response")}async unpin(t,e=!1){return ms(await this.rpcClient.call("unpin",{content_id:t,force:e}),"unpin response")}async uncollect(t,e=!1){return ms(await this.rpcClient.call("uncollect",{content_id:t,force:e}),"uncollect response")}async addProof(t){return gs(await this.rpcClient.call("add_proof",{proof:t}),"proof_id")}async getProofs(t,e){return ws(await this.rpcClient.call("get_proofs",ps({content_id:t,filter:e})),"Vec<RepoProof>").map(((t,e)=>{const n=bs(t,`RepoProof[${e}]`);if("Action"!==n.kind&&"Collection"!==n.kind)throw new Fn(`RepoProof[${e}] has unknown kind: ${String(n.kind)}`);return n}))}async resolve(t){return ws(await this.rpcClient.call("resolve",{content_name:t}),"Vec<ObjId>").map(((t,e)=>gs(t,`ObjId[${e}]`)))}async list(t){return ws(await this.rpcClient.call("list",ps({filter:t})),"Vec<RepoRecord>").map(((t,e)=>{const n=bs(t,`RepoRecord[${e}]`);return{content_id:gs(n.content_id,`RepoRecord[${e}].content_id`),content_name:"string"==typeof n.content_name?n.content_name:void 0,status:gs(n.status,`RepoRecord[${e}].status`),origin:gs(n.origin,`RepoRecord[${e}].origin`),meta:n.meta,owner_did:"string"==typeof n.owner_did?n.owner_did:void 0,author:"string"==typeof n.author?n.author:void 0,access_policy:gs(n.access_policy,`RepoRecord[${e}].access_policy`),price:"string"==typeof n.price?n.price:void 0,content_size:"number"==typeof n.content_size?n.content_size:void 0,collected_at:"number"==typeof n.collected_at?n.collected_at:void 0,pinned_at:"number"==typeof n.pinned_at?n.pinned_at:void 0,updated_at:"number"==typeof n.updated_at?n.updated_at:void 0}}))}async stat(){const t=bs(await this.rpcClient.call("stat",{}),"RepoStat");return{total_objects:ys(t.total_objects,"RepoStat.total_objects"),collected_objects:ys(t.collected_objects,"RepoStat.collected_objects"),pinned_objects:ys(t.pinned_objects,"RepoStat.pinned_objects"),local_objects:ys(t.local_objects,"RepoStat.local_objects"),remote_objects:ys(t.remote_objects,"RepoStat.remote_objects"),total_content_bytes:ys(t.total_content_bytes,"RepoStat.total_content_bytes"),total_proofs:ys(t.total_proofs,"RepoStat.total_proofs")}}async serve(t,e){const n=bs(await this.rpcClient.call("serve",{content_id:t,request_context:e}),"RepoServeResult");return{status:gs(n.status,"RepoServeResult.status"),content_ref:n.content_ref&&"object"==typeof n.content_ref?n.content_ref:void 0,download_proof:n.download_proof&&"object"==typeof n.download_proof?n.download_proof:void 0,reject_code:"string"==typeof n.reject_code?n.reject_code:void 0,reject_reason:"string"==typeof n.reject_reason?n.reject_reason:void 0}}async announce(t){return ms(await this.rpcClient.call("announce",{content_id:t}),"announce response")}}function _s(t){if(!t||t.length>253||t.includes("@"))throw new Error("hostname must be 1..=253 bytes and must not contain `@`");if(t!==t.toLowerCase()||!/^[\x00-\x7f]+$/.test(t))throw new Error("hostname must be canonical lowercase ASCII");for(const e of t.split("."))if(!e||e.length>63||e.startsWith("-")||e.endsWith("-")||!/^[a-z0-9-]+$/.test(e))throw new Error(`invalid DNS label \`${e}\``)}function vs(t){const e=/^did:([^:]+):(.+)$/.exec(t);if(!e)throw new Error("AppDID must be a canonical DID");const[,n,r]=e;if(!n||!r||n!==n.toLowerCase()||r!==r.toLowerCase()||r.includes(":")||r.includes("#")||r.includes("%"))throw new Error("AppDID must be a canonical lowercase hostname-form DID without path, port, encoding, or fragment");const s=new Mn.DID(n,r).toRawHostName();if(_s(s),"web"===n&&s.endsWith(".did"))throw new Error("AppDID did:web hostnames ending in `.did` are reserved");if(Mn.DID.fromStr(s).toString()!==t)throw new Error("AppDID raw hostname does not round-trip");return s}function Es(t){return vs(t.trim())}function ks(t){const e=t.trim();_s(e);const n=vs(Mn.DID.fromStr(e).toString());if(n!==e)throw new Error("AppId is not a canonical AppDID raw hostname");return n}function Ss(t){if(!t||t.length>64||!/^[a-z0-9._-]+$/.test(t))throw new Error("owner_user_id must be lowercase ASCII and contain only [a-z0-9._-]")}function Ts(t,e){const n=ks(t);return Ss(e),`${n}@${e}`}function Rs(t){const e=t.trim(),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)throw new Error("AppInstanceId must be `{app_id}@{owner_user_id}`");const r=ks(e.slice(0,n)),s=e.slice(n+1);return Ss(s),{appId:r,ownerUserId:s}}const Is="BUCKYOS_APP_DID",Os="BUCKYOS_APP_ID",Cs="BUCKYOS_APP_INSTANCE_ID",xs="BUCKYOS_OWNER_USER_ID",Ns="BUCKYOS_DATA_DIR",Ps="BUCKYOS_APP_TOKEN";var Ds=(t=>(t.Browser="Browser",t.NodeJS="NodeJS",t.AppRuntime="AppRuntime",t.AppClient="AppClient",t.AppService="AppService",t.Unknown="Unknown",t))(Ds||{});const Bs={zoneHost:"",appId:"",appDid:null,appInstanceId:null,dataDir:null,defaultProtocol:"http://",runtimeType:"Unknown",userid:null,ownerUserId:null,rootDir:"",sessionToken:null,refreshToken:null,privateKeySearchPaths:[],systemConfigServiceUrl:"",verifyHubServiceUrl:"",nodeGatewayPort:3180,autoRenew:!0,renewIntervalMs:5e3};function Us(){const t=globalThis.process;return(null==t?void 0:t.env)??{}}function Ls(){var t;const e=globalThis.process;return Boolean(null==(t=null==e?void 0:e.versions)?void 0:t.node)}function Ms(){return"undefined"!=typeof localStorage}function Fs(){return"function"==typeof fetch}function Gs(){const t=globalThis.Buffer;if(!t||"function"!=typeof t)throw new Error("Buffer is not available in this runtime");return t}function js(t){const e=Gs();return("string"==typeof t?e.from(t,"utf8").toString("base64"):e.from(t).toString("base64")).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Hs(t){if(!t)return null;const e=t.split(".");if(e.length<2)return null;try{return JSON.parse(function(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e+"=".repeat((4-e.length%4)%4);return"function"==typeof atob?atob(n):Gs().from(n,"base64").toString("utf8")}(e[1]))}catch{return null}}function Vs(t){if("string"!=typeof t)return null;const e=t.trim();return e.length>0?e:null}function Ws(t){const e=Vs(t);return e?e.startsWith("did:web:")?e.slice(8).replace(/:/g,"."):e.startsWith("did:bns:")?e.slice(8):null:null}async function Ks(t){if(Ls()&&"function"==typeof require)return require(t);return Function("name","return import(name)")(t)}class zs{async initialize(t){await t.resolveAppServiceIdentityFromEnv(),await t.resolveZoneHostFromLocalConfig()}async login(t){await t.initialize(),t.startAutoRenewIfNeeded()}supportsManagedSessionRenewal(){return!1}shouldSkipVerifyHubRenewal(t){return!1}async getVerifyHubLoginJwt(t,e){return e}}class qs extends zs{getRelativeZoneServiceURL(t){return`/kapi/${t}/`}getRelativeSystemConfigServiceURL(){return"/kapi/system_config"}getServiceSettingsPath(t){return`services/${t.getAppId()}/settings`}getZoneServiceURL(t,e){return this.getRelativeZoneServiceURL(e)}getSystemConfigServiceURL(t){return this.getRelativeSystemConfigServiceURL()}getMySettingsPath(t){return this.getServiceSettingsPath(t)}}class $s extends qs{}class Qs extends zs{async login(t){await t.initialize(),await t.renewTokenFromVerifyHub(),t.startAutoRenewIfNeeded()}supportsManagedSessionRenewal(){return!0}}class Js extends Qs{async initialize(t){await super.initialize(t),await t.ensureAppClientSessionToken()}getZoneGatewayServiceURL(t,e){const n=Vs(t.getZoneHostName());if(!n)throw new Error("zoneHost is required in AppClient mode");return`${t.getDefaultProtocol()}${n}/kapi/${e}`}getZoneSystemConfigURL(t){const e=Vs(t.getZoneHostName());if(!e)throw new Error("zoneHost is required in AppClient mode");return`${t.getDefaultProtocol()}${e}/kapi/system_config`}getZoneServiceURL(t,e){return this.getZoneGatewayServiceURL(t,e)}getSystemConfigServiceURL(t){return this.getZoneSystemConfigURL(t)}getMySettingsPath(){throw new Error("AppClient not support getMySettingsPath")}shouldSkipVerifyHubRenewal(t){return!Vs(t.getZoneHostName())&&!t.getConfiguredVerifyHubServiceUrl()}async getVerifyHubLoginJwt(t,e){return t.createAppClientSessionToken()}}class Ys extends Qs{async initialize(t){await super.initialize(t),t.ensureAppServiceSessionToken()}getNodeGatewayServiceURL(t,e){const n=t.getNodeGatewayPort();return`http://${t.resolveAppServiceGatewayHost()}:${n}/kapi/${e}`}getNodeGatewaySystemConfigURL(t){const e=t.getNodeGatewayPort();return`http://${t.resolveAppServiceGatewayHost()}:${e}/kapi/system_config`}getUserAppSettingsPath(t){const e=t.getOwnerUserId();if(!e)throw new Error("ownerUserId is required for AppService settings");return`users/${e}/apps/${t.getAppId()}/settings`}getZoneServiceURL(t,e){return this.getNodeGatewayServiceURL(t,e)}getSystemConfigServiceURL(t){return this.getNodeGatewaySystemConfigURL(t)}getMySettingsPath(t){return this.getUserAppSettingsPath(t)}}function Zs(t){switch(t){case"AppClient":return new Js;case"AppService":return new Ys;case"AppRuntime":return new $s;default:return new qs}}class Xs{constructor(t){const e=Vs(t.ownerUserId)??Vs(t.userid);this.config={...Bs,...t,appId:t.appId,appDid:Vs(t.appDid),appInstanceId:Vs(t.appInstanceId),dataDir:Vs(t.dataDir),userid:e,ownerUserId:e,zoneHost:t.zoneHost??"",defaultProtocol:t.defaultProtocol??Bs.defaultProtocol},this.sessionToken=Vs(t.sessionToken),this.refreshToken=Vs(t.refreshToken),this.renewTimer=null,this.browserRefreshPromise=null,this.authStateRevision=0,this.initialized=!1,this.profile=Zs(this.config.runtimeType)}async initialize(){this.initialized||(await this.profile.initialize(this),this.validateSessionToken(),this.initialized=!0)}async login(){await this.profile.login(this)}setConfig(t){const e=Vs(t.ownerUserId)??Vs(t.userid);this.config={...Bs,...t,appId:t.appId,appDid:Vs(t.appDid),appInstanceId:Vs(t.appInstanceId),dataDir:Vs(t.dataDir),userid:e,ownerUserId:e},this.profile=Zs(this.config.runtimeType)}getConfig(){return{...this.config}}getAppId(){return this.config.appId}getOwnerUserId(){return Vs(this.config.ownerUserId)}getAppDid(){return Vs(this.config.appDid)}getAppInstanceId(){return Vs(this.config.appInstanceId)}getDataDir(){return Vs(this.config.dataDir)}getAuthTarget(){if(this.config.authTarget){const t=Kn(this.config.authTarget);if(t!==this.config.appId)throw new Error(`auth target appid mismatch: ${t} != ${this.config.appId}`);return{...this.config.authTarget}}const t=this.getAppInstanceId();if(t){const e=Rs(t);if(e.appId!==this.config.appId)throw new Error(`auth target appid mismatch: ${e.appId} != ${this.config.appId}`);return{kind:"app",app_instance_id:t}}if("AppClient"===this.config.runtimeType||"AppService"===this.config.runtimeType){const t=this.getOwnerUserId();if(!t)throw new Error("ownerUserId is required to build an App auth target");return{kind:"app",app_instance_id:Ts(this.config.appId,t)}}throw new Error("authTarget or appInstanceId must be configured for this runtime")}getZoneHostName(){return this.config.zoneHost}getDefaultProtocol(){return this.config.defaultProtocol}getNodeGatewayPort(){return this.config.nodeGatewayPort??3180}getConfiguredVerifyHubServiceUrl(){return Vs(this.config.verifyHubServiceUrl)}getZoneServiceURL(t){const e=function(t){return"system-config"===t?"system_config":t}(t);return this.profile.getZoneServiceURL(this,e)}getSystemConfigServiceURL(){const t=this.getConfiguredSystemConfigServiceUrl();return t||this.profile.getSystemConfigServiceURL(this)}setSessionToken(t){const e=Vs(t);e!==this.sessionToken&&(this.authStateRevision+=1),this.sessionToken=e}setRefreshToken(t){this.refreshToken=Vs(t)}getSessionToken(){return this.sessionToken}getRefreshToken(){return this.refreshToken}clearAuthState(){this.authStateRevision+=1,this.sessionToken=null,this.refreshToken=null,this.stopAutoRenew()}stopAutoRenew(){this.renewTimer&&(clearInterval(this.renewTimer),this.renewTimer=null)}getServiceRpcClient(t){return new jn(this.getZoneServiceURL(t),this.sessionToken,null,{sessionTokenProvider:this.ensureSessionTokenReady.bind(this),onSessionTokenChanged:this.setSessionToken.bind(this)})}getSystemConfigClient(){return new Ur(this.getSystemConfigServiceURL(),this.sessionToken,{sessionTokenProvider:this.ensureSessionTokenReady.bind(this),onSessionTokenChanged:this.setSessionToken.bind(this)})}getVerifyHubClient(){const t=this.getConfiguredVerifyHubServiceUrl(),e=new jn(t??this.getZoneServiceURL("verify-hub"),this.sessionToken);return new zn(e)}getTaskManagerClient(){const t=this.getServiceRpcClient("task-manager");return new _r(t)}getWorkflowClient(){const t=this.getServiceRpcClient("workflow");return new Dr(t)}getAiccClient(){return new Qr(this.getServiceRpcClient("aicc"))}getMsgQueueClient(){return new as(this.getServiceRpcClient("kmsg"))}getMsgCenterClient(){return new fs(this.getServiceRpcClient("msg-center"))}getRepoClient(){return new As(this.getServiceRpcClient("repo-service"))}async getMySettings(){const t=this.getMySettingsPath(),e=await this.getSystemConfigClient().get(t);return JSON.parse(e.value)}async updateMySettings(t,e){const n=this.getMySettingsPath(),r=JSON.stringify(e);await this.getSystemConfigClient().setByJsonPath(n,t,r)}async updateAllMySettings(t){const e=this.getMySettingsPath(),n=JSON.stringify(t);await this.getSystemConfigClient().set(e,n)}async renewTokenFromVerifyHub(){if(!this.profile.supportsManagedSessionRenewal())return;const t=this.sessionToken;if(!t)return;const e=Hs(t);if(!e||!this.needsRenew(e))return;if(this.profile.shouldSkipVerifyHubRenewal(this))return;const n=this.getVerifyHubClient(),r="verify-hub"===e.iss?this.refreshToken?await n.refreshToken({refresh_token:this.refreshToken}):await n.loginByJwt({jwt:await this.profile.getVerifyHubLoginJwt(this,t),target:this.getAuthTarget()}):await n.loginByJwt({jwt:t,target:this.getAuthTarget()});this.sessionToken=Vs(r.session_token),this.refreshToken=Vs(r.refresh_token),this.validateSessionToken()}async ensureSessionTokenReady(){if(this.usesBrowserSessionRefresh()){const t=await this.ensureBrowserSessionToken();return t&&this.startAutoRenewIfNeeded(),t}return this.profile.supportsManagedSessionRenewal()&&await this.renewTokenFromVerifyHub(),this.sessionToken}ensureAppServiceSessionToken(){this.sessionToken||(this.sessionToken=this.loadAppServiceSessionTokenFromEnv())}async ensureAppClientSessionToken(){this.sessionToken||(this.sessionToken=this.loadAppClientSessionTokenFromEnv()),this.sessionToken||(this.sessionToken=await this.createAppClientSessionToken())}async resolveAppServiceIdentityFromEnv(){if(!Ls())return;if("AppService"!==this.config.runtimeType)return;const t=Us(),e=e=>{const n=Vs(t[e]);if(!n)throw new Error(`${e} is required for AppService runtime`);return n},n=e(Is),r=ks(e(Os)),s=e(Cs),i=e(xs),o=e(Ns),a=Rs(s);if(!(await Ks("node:path")).isAbsolute(o))throw new Error(`${Ns} must be an absolute path`);if(Es(n)!==r||a.appId!==r||a.ownerUserId!==i||Ts(r,i)!==s)throw new Error("AppService identity environment variables are inconsistent");const c=Vs(this.config.appId),l=Vs(this.config.appDid),u=Vs(this.config.appInstanceId),h=this.getOwnerUserId(),d=Vs(this.config.dataDir);if(c&&c!==r)throw new Error(`runtime appId ${c} does not match ${Os} ${r}`);if(l&&l!==n)throw new Error(`runtime appDid ${l} does not match ${Is} ${n}`);if(u&&u!==s)throw new Error(`runtime appInstanceId ${u} does not match ${Cs} ${s}`);if(h&&h!==i)throw new Error(`runtime ownerUserId ${h} does not match ${xs} ${i}`);if(d&&d!==o)throw new Error(`runtime dataDir ${d} does not match ${Ns} ${o}`);this.config.appDid=n,this.config.appId=r,this.config.appInstanceId=s,this.config.ownerUserId=i,this.config.userid=i,this.config.dataDir=o}async resolveZoneHostFromLocalConfig(){if(!Ls())return;if(Vs(this.config.zoneHost))return;const t=await this.getPrivateKeySearchRoots(),e=await this.tryResolveZoneHostFromSearchRoots(t);e&&(this.config.zoneHost=e)}validateSessionToken(){if(!this.sessionToken)return;const t=Hs(this.sessionToken);if("AppService"===this.config.runtimeType&&!t)throw new Error("AppService session token must be a JWT with identity claims");const e="string"==typeof(null==t?void 0:t.appid)?t.appid:"string"==typeof(null==t?void 0:t.aud)?t.aud:null;if(e&&e!==this.config.appId)throw new Error(`session token appid mismatch: ${e} != ${this.config.appId}`);if("AppService"===this.config.runtimeType&&t){const e=this.getAppInstanceId();if(!e||t.app_instance_id!==e)throw new Error(`session token app_instance_id mismatch: ${String(t.app_instance_id)} != ${String(e)}`);const n=this.getOwnerUserId();if(!n||t.app_owner_user_id!==n)throw new Error(`session token app_owner_user_id mismatch: ${String(t.app_owner_user_id)} != ${String(n)}`)}}async ensureBrowserSessionToken(){const t=Hs(this.sessionToken);return this.sessionToken&&t&&!this.needsRenew(t)?this.sessionToken:this.refreshBrowserSessionToken()}normalizeBrowserUserInfo(t){if(!t||"object"!=typeof t||Array.isArray(t))return null;const e=t,n="string"==typeof e.user_id?e.user_id.trim():"",r="string"==typeof e.user_type?e.user_type.trim():"",s="string"==typeof e.user_name?e.user_name.trim():"string"==typeof e.show_name?e.show_name.trim():"";return n&&r?{user_name:s||n,user_id:n,user_type:r}:null}async refreshBrowserSession(){return await this.refreshBrowserSessionToken()&&Ms()?Mn.getBrowserUserInfo():null}async logoutBrowserSSO(){if(("Browser"===this.config.runtimeType||"AppRuntime"===this.config.runtimeType)&&Fs())try{const t=await fetch("/sso_logout",{method:"POST",credentials:"include",cache:"no-store",keepalive:!0});t.ok||console.warn("BuckyOS browser sso_logout failed:",t.status)}catch(t){console.warn("BuckyOS browser sso_logout failed:",t)}}async refreshBrowserSessionToken(){if(this.browserRefreshPromise)return this.browserRefreshPromise;const t=this.authStateRevision,e=this.requestBrowserSessionToken(t);this.browserRefreshPromise=e;try{return await e}finally{this.browserRefreshPromise===e&&(this.browserRefreshPromise=null)}}async requestBrowserSessionToken(t){if(!Fs())return this.sessionToken;const e=Ms()?Mn.getBrowserUserInfo():null;try{const n=await fetch("/sso_refresh",{method:"POST",credentials:"include",cache:"no-store"});if(!n.ok)return t===this.authStateRevision&&(this.sessionToken=null),null;const r=await n.json(),s=Vs("string"==typeof r.access_token?r.access_token:"string"==typeof r.session_token?r.session_token:null),i=this.normalizeBrowserUserInfo(r.user_info)??e;return s&&i?t!==this.authStateRevision?null:(this.sessionToken=s,this.refreshToken=null,Mn.saveBrowserUserInfo(i),this.validateSessionToken(),this.sessionToken):(t===this.authStateRevision&&(this.sessionToken=null),null)}catch(n){return console.warn("BuckyOS browser sso_refresh failed:",n),t===this.authStateRevision&&(this.sessionToken=null),null}}usesBrowserSessionRefresh(){return"Browser"===this.config.runtimeType||"AppRuntime"===this.config.runtimeType}needsRenew(t){if(t.iss&&"verify-hub"!==t.iss)return!0;if("number"!=typeof t.exp)return!1;return Math.floor(Date.now()/1e3)>=t.exp-30}startAutoRenewIfNeeded(){const t=this.usesBrowserSessionRefresh();if(!t&&!this.profile.supportsManagedSessionRenewal()||!1===this.config.autoRenew)return;if(this.renewTimer)return;const e=this.config.renewIntervalMs??5e3,n=async()=>{try{if(t){await this.ensureBrowserSessionToken()||this.stopAutoRenew()}else await this.renewTokenFromVerifyHub()}catch(e){console.warn("BuckyOS token renew failed:",e)}};this.renewTimer=setInterval((()=>{n()}),e),n()}loadAppServiceSessionTokenFromEnv(){const t=Vs(Us()[Ps]);if(t)return t;throw new Error(`${Ps} is required for AppService runtime`)}loadAppClientSessionTokenFromEnv(){return Vs(Us().BUCKYOS_APPCLIENT_SESSION_TOKEN)}async createAppClientSessionToken(){if(!Ls())throw new Error("AppClient mode requires Node.js");const t=await this.loadLocalSigningMaterial(),e=Math.floor(Date.now()/1e3),n={token_type:"Normal",appid:this.config.appId,jti:String(e),session:e,sub:t.subject,userid:t.subject,iss:t.issuer,exp:e+900,extra:{}};return this.signJwtWithEd25519({alg:"EdDSA",kid:t.issuer},n,t.keyPem)}async loadLocalSigningMaterial(){await Ks("node:fs/promises");const t=await Ks("node:path"),e=this.getOwnerUserId();if(!e){const e=await this.getBuckyOSEtcDir(),n=await this.readDeviceNameFromNodeIdentityPath(t.join(e,"node_identity.json"));if(!n)throw new Error(`failed to resolve userid from ${t.join(e,"node_identity.json")} device_mini_doc_jwt`);const r=await this.readPemFile(t.join(e,"node_private_key.pem"));if(!r)throw new Error(`failed to load node_private_key.pem from ${e}`);return this.config.userid=n,this.config.ownerUserId=n,{keyPem:r,issuer:n,subject:n,sourcePath:t.join(e,"node_private_key.pem")}}const n=await this.getPrivateKeySearchRoots(),r=await this.tryLoadDeviceSigningMaterial(e,n);if(r)return r;const s=await this.tryLoadUserSigningMaterial(e,n);if(s)return s;throw new Error(`failed to find AppClient private key for userid=${e} in search roots: ${n.join(", ")}`)}async getPrivateKeySearchRoots(){var t;const e=Us(),n=await Ks("node:path"),r=await Ks("node:os"),s=[];for(const c of this.config.privateKeySearchPaths??[]){const t=Vs(c);t&&s.push(t)}const i=Vs(e.BUCKYOS_APP_CLIENT_DIR);i&&s.push(i);const o=Vs(e.HOME)??Vs(e.USERPROFILE)??Vs(null==(t=r.homedir)?void 0:t.call(r));o&&(s.push(n.join(o,".buckyos")),s.push(n.join(o,".buckycli")));const a=Vs(this.config.rootDir)??Vs(e.BUCKYOS_ROOT)??"/opt/buckyos";return s.push(a),s.push(n.join(a,"etc")),Array.from(new Set(s))}async getBuckyOSRootDir(){const t=Us();return Vs(this.config.rootDir)??Vs(t.BUCKYOS_ROOT)??"/opt/buckyos"}async getBuckyOSEtcDir(){return(await Ks("node:path")).join(await this.getBuckyOSRootDir(),"etc")}async readPemFile(t){const e=await Ks("node:fs/promises");try{return(await e.readFile(t,"utf8")).trim()||null}catch{return null}}async readNodeIdentityMetadata(t){const e=await Ks("node:fs/promises");try{const n=await e.readFile(t,"utf8"),r=JSON.parse(n);return{deviceName:this.extractDeviceNameFromIdentityPayload(r),deviceDid:"string"==typeof r.device_did&&r.device_did.trim()||null,zoneDid:"string"==typeof r.zone_did&&r.zone_did.trim()||null,zoneName:"string"==typeof r.zone_name&&r.zone_name.trim()||null}}catch{return null}}extractDeviceNameFromIdentityPayload(t){const e="string"==typeof t.device_name?t.device_name.trim():"";if(e)return e;const n=Hs("string"==typeof t.device_mini_doc_jwt?t.device_mini_doc_jwt:null),r="string"==typeof(null==n?void 0:n.n)?n.n.trim():"";if(r)return r;const s=Hs("string"==typeof t.device_doc_jwt?t.device_doc_jwt:null);for(const i of["name","sub"]){const t=null==s?void 0:s[i],e="string"==typeof t?t.trim():"";if(e)return e}return null}async readDeviceNameFromNodeIdentityPath(t){const e=await this.readNodeIdentityMetadata(t);return(null==e?void 0:e.deviceName)??null}async tryLoadDeviceSigningMaterial(t,e){const n=await Ks("node:path"),r=[await this.getBuckyOSEtcDir(),...e.filter((t=>!t.endsWith(".pem")))];for(const s of Array.from(new Set(r))){const e=await this.readNodeIdentityMetadata(n.join(s,"node_identity.json")),r=(null==e?void 0:e.deviceName)??null;if(r&&r===t)for(const t of await this.deviceKeyPathCandidates(s,(null==e?void 0:e.deviceDid)??null)){const e=await this.readPemFile(t);if(e)return{keyPem:e,issuer:r,subject:r,sourcePath:t}}}return null}async deviceKeyPathCandidates(t,e){const n=await Ks("node:path"),r=[];if(e)try{const s=Mn.DID.fromStr(e).toFilename(),i="authentication.private.pem";r.push(n.join(t,"security",s,i));const o=Us(),a=Vs(o.BUCKYOS_SECURITY_ROOT)??n.join(Vs(o.BUCKYOS_ROOT)??"/opt/buckyos","security");r.push(n.join(a,s,i))}catch{}return r.push(n.join(t,"node_private_key.pem")),r}async tryLoadUserSigningMaterial(t,e){var n;const r=await Ks("node:fs/promises"),s=await Ks("node:path");for(const i of e){const e=i.endsWith(".pem")?i:s.join(i,"user_private_key.pem"),o=i.endsWith(".pem")?s.dirname(i):i,a=s.join(o,"user_config.json");try{const s=await r.readFile(a,"utf8"),i=Mn.parseBuckyOSOwnerDocument(JSON.parse(s)),o=null==(n=null==i?void 0:i.name)?void 0:n.trim();if(!o||o!==t)continue;const c=await this.readPemFile(e);if(!c)continue;return{keyPem:c,issuer:t,subject:t,sourcePath:e}}catch{}}return null}async tryResolveDeviceNameFromSearchRoots(t){const e=await Ks("node:path"),n=Us(),r=Vs(n.BUCKYOS_THIS_DEVICE_NAME);if(r)return r;for(const s of["BUCKYOS_THIS_DEVICE","BUCKYOS_THIS_DEVICE_INFO"]){const t=Vs(n[s]);if(t)try{const e=JSON.parse(t);if("string"==typeof e.name&&e.name.trim().length>0)return e.name.trim()}catch{}}for(const s of t){const t=e.join(s,"node_identity.json"),n=await this.readDeviceNameFromNodeIdentityPath(t);if(n)return n}return null}async tryResolveZoneHostFromSearchRoots(t){var e;const n=await Ks("node:fs/promises"),r=await Ks("node:path"),s=Vs(Us().BUCKYOS_ZONE_HOST);if(s)return s;for(const i of t){const t=r.join(i,"node_identity.json"),e=await this.readNodeIdentityMetadata(t);if(e){if(e.zoneName)return e.zoneName;if(e.zoneDid)return Ws(e.zoneDid)}}for(const i of t){const t=r.join(i,"user_config.json");try{const r=await n.readFile(t,"utf8"),s=Mn.parseBuckyOSOwnerDocument(JSON.parse(r)),i=Ws(null==(e=null==s?void 0:s.binded_zone_list)?void 0:e[0]);if(!i)continue;return i}catch{}}return null}getMySettingsPath(){return this.profile.getMySettingsPath(this)}getConfiguredSystemConfigServiceUrl(){return Vs(this.config.systemConfigServiceUrl)}resolveAppServiceGatewayHost(){return Vs(Us().BUCKYOS_HOST_GATEWAY)??"host.docker.internal"}async signJwtWithEd25519(t,e,n){const r=await Ks("node:crypto"),s=Gs(),i=`${js(JSON.stringify(t))}.${js(JSON.stringify(e))}`;return`${i}.${js(r.sign(null,s.from(i,"utf8"),r.createPrivateKey({key:n,format:"pem"})))}`}}const ti=1048576;class ei extends Error{constructor(t,e){super(e),this.name="KEventProtocolError",this.code=t}}const ni=async(t,e)=>{if("function"!=typeof fetch)throw new Error("fetch is not available in this runtime");return fetch(t,e)};function ri(){var t;const e=globalThis.process;return Boolean(null==(t=null==e?void 0:e.versions)?void 0:t.node)}function si(t){const e=(Array.isArray(t)?t:[t]).map((t=>"string"==typeof t?t.trim():"")).filter((t=>t.length>0));if(0===e.length)throw new Error("kevent patterns must not be empty");for(const n of e)if(!n.startsWith("/"))throw new Error(`kevent only supports global patterns: ${n}`);return e}function ii(t,e){return(null==e?void 0:e.aborted)?Promise.reject(new Error("Operation aborted")):new Promise(((n,r)=>{const s=setTimeout((()=>{o(),n()}),t),i=()=>{clearTimeout(s),o(),r(new Error("Operation aborted"))},o=()=>{e&&e.removeEventListener("abort",i)};e&&e.addEventListener("abort",i,{once:!0})}))}function oi(t){return t instanceof Error?t.message:String(t)}function ai(t){if("ok"===t.status)return t;throw new ei(t.code||"INTERNAL",t.message||"Unknown kevent error")}function ci(t){if(!t||"object"!=typeof t||Array.isArray(t))throw new Error("Invalid kevent event payload");const e=t;if("string"!=typeof e.eventid||"string"!=typeof e.source_node||"number"!=typeof e.source_pid||"number"!=typeof e.timestamp)throw new Error("Invalid kevent event payload");return{eventid:e.eventid,source_node:e.source_node,source_pid:e.source_pid,ingress_node:"string"==typeof e.ingress_node?e.ingress_node:null,timestamp:e.timestamp,data:"data"in e?e.data:null}}class li{constructor(){this.items=[],this.waiters=[],this.closed=!1}push(t){if(this.closed)return;const e=this.waiters.shift();if(e)return e.timeout&&clearTimeout(e.timeout),void e.resolve(t);this.items.push(t)}async shift(t){return this.items.length>0?this.items.shift()??null:this.closed||0===t?null:new Promise((e=>{const n={resolve:t=>{r(),e(t)},timeout:null},r=()=>{n.timeout&&(clearTimeout(n.timeout),n.timeout=null);const t=this.waiters.indexOf(n);t>=0&&this.waiters.splice(t,1)};"number"==typeof t&&t>0&&(n.timeout=setTimeout((()=>{r(),e(null)}),t)),this.waiters.push(n)}))}close(){if(!this.closed)for(this.closed=!0;this.waiters.length>0;){const t=this.waiters.shift();t&&(t.timeout&&clearTimeout(t.timeout),t.resolve(null))}}}class ui{constructor(){this.queue=new li,this.closed=!1,this.closePromise=null}async pullEvent(t){return this.queue.shift(t)}async pull_event(t){return this.pullEvent(t)}enqueue(t){this.queue.push(t)}isClosed(){return this.closed}markClosed(){this.closed=!0,this.queue.close()}async close(){return this.closePromise||(this.markClosed(),this.closePromise=this.closeTransport().catch((t=>{console.warn("kevent reader close failed:",t)})).then((()=>{}))),this.closePromise}}class hi extends ui{constructor(t,e,n,r,s,i){super(),this.streamUrl=t,this.patterns=e,this.keepaliveMs=n,this.fetcher=r,this.sessionTokenProvider=s,this.streamTask=null,this.controller=new AbortController,this.readyPromise=this.start(),i&&(i.aborted?this.controller.abort():i.addEventListener("abort",(()=>{this.controller.abort()}),{once:!0}))}async waitUntilReady(){await this.readyPromise}async start(){const t={"Content-Type":"application/json"};if(this.sessionTokenProvider){const e=await this.sessionTokenProvider();"string"==typeof e&&e.trim().length>0&&(t.Authorization=`Bearer ${e.trim()}`)}const e=await this.fetcher(this.streamUrl,{method:"POST",headers:t,body:JSON.stringify({patterns:this.patterns,keepalive_ms:this.keepaliveMs}),cache:"no-store",credentials:"include",signal:this.controller.signal});if(!e.ok){let t="";try{t=await e.text()}catch{t=""}throw new Error(`kevent stream request failed: ${e.status}${t?` ${t}`:""}`)}if(!e.body)throw new Error("kevent stream response missing body");let n=!1,r=null,s=null;const i=new Promise(((t,e)=>{r=t,s=e}));this.streamTask=this.consumeStream(e.body,(t=>{if("ack"===t.type)return n=!0,void(null==r||r());if("event"!==t.type){if("error"===t.type){const e=new Error(t.error||"kevent stream error");n?console.warn("kevent stream error:",e.message):null==s||s(e)}}else this.enqueue(ci(t.event))})).then((()=>{n||null==s||s(new Error("kevent stream closed before ack"))})).catch((t=>{n?this.controller.signal.aborted||console.warn("kevent browser stream stopped with error:",t):null==s||s(t instanceof Error?t:new Error(oi(t)))})).finally((()=>{this.markClosed()})),await i}async consumeStream(t,e){const n=t.getReader(),r=new TextDecoder;let s="";try{for(;!this.controller.signal.aborted;){const{value:t,done:i}=await n.read();if(i)break;s+=r.decode(t,{stream:!0}),s=this.processFrameBuffer(s,e)}s+=r.decode(),s=this.processFrameBuffer(s,e),s.trim().length>0&&this.handleFrameLine(s,e)}finally{try{await n.cancel()}catch{}}}processFrameBuffer(t,e){let n=t;for(;;){const t=n.indexOf("\n");if(t<0)return n;const r=n.slice(0,t);n=n.slice(t+1),this.handleFrameLine(r,e)}}handleFrameLine(t,e){const n=t.trim();if(!n)return;e(JSON.parse(n))}async closeTransport(){if(this.controller.abort(),this.streamTask)try{await this.streamTask}catch(t){this.controller.signal.aborted||console.warn("kevent browser stream stopped with error:",t)}}}class di{constructor(t,e,n,r){this.host=t,this.port=e,this.connectTimeoutMs=n,this.connector=r,this.socket=null,this.connectPromise=null,this.closed=!1,this.serial=Promise.resolve(),this.readBuffer=new Uint8Array(0),this.pending=[]}async call(t){const e=this.serial.then((()=>this.callInternal(t)));return this.serial=e.then((()=>{}),(()=>{})),e}async close(){if(this.closed=!0,this.rejectAllPending(new Error("kevent native connection closed")),this.socket){const t=this.socket;this.socket=null,t.end()}}async callInternal(t){if(this.closed)throw new Error("kevent native connection is closed");await this.ensureConnected();const e=this.socket;if(!e)throw new Error("kevent native socket is not connected");const n=(new TextEncoder).encode(JSON.stringify(t));if(0===n.length||n.length>ti)throw new Error(`invalid kevent native request payload size: ${n.length}`);const r=new Uint8Array(4+n.length);return new DataView(r.buffer).setUint32(0,n.length),r.set(n,4),new Promise(((t,n)=>{const s={resolve:t,reject:n};this.pending.push(s),e.write(r,(t=>{if(!t)return;const e=this.pending.indexOf(s);e>=0&&this.pending.splice(e,1),n(t instanceof Error?t:new Error(oi(t)))}))}))}async ensureConnected(){this.socket||(this.connectPromise||(this.connectPromise=this.connect().finally((()=>{this.connectPromise=null}))),await this.connectPromise)}async connect(){const t=await this.connector(this.host,this.port,this.connectTimeoutMs);this.socket=t,"function"==typeof t.setNoDelay&&t.setNoDelay(!0),t.on("data",(t=>{try{this.handleSocketData(function(t){if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);throw new Error("Unsupported socket data chunk")}(t))}catch(e){this.handleSocketFailure(e instanceof Error?e:new Error(oi(e)))}})),t.once("end",(()=>{this.handleSocketFailure(new Error("kevent native socket ended"))})),t.once("close",(()=>{this.handleSocketFailure(new Error("kevent native socket closed"))})),t.once("error",(t=>{this.handleSocketFailure(t)}))}handleSocketData(t){for(this.readBuffer=function(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}(this.readBuffer,t);this.readBuffer.length>=4;){const t=new DataView(this.readBuffer.buffer,this.readBuffer.byteOffset,this.readBuffer.byteLength).getUint32(0);if(0===t||t>ti)throw new Error(`invalid kevent native frame length: ${t}`);if(this.readBuffer.length<4+t)return;const e=this.readBuffer.slice(4,4+t);this.readBuffer=this.readBuffer.slice(4+t);const n=JSON.parse((new TextDecoder).decode(e)),r=this.pending.shift();r&&r.resolve(n)}}handleSocketFailure(t){if(this.socket){const e=this.socket;this.socket=null;try{e.destroy(t)}catch{}}this.closed||this.rejectAllPending(t)}rejectAllPending(t){for(;this.pending.length>0;){const e=this.pending.shift();null==e||e.reject(t)}}}class fi extends ui{constructor(t,e){super(),this.client=t,this.readerId=e}static async create(t,e){const n=new di(e.nativeHost,e.nativePort,e.nativeConnectTimeoutMs,e.nativeConnector),r=`ts_kevent_${Date.now()}_${Math.random().toString(36).slice(2,10)}`;try{return ai(await n.call({op:"register_reader",reader_id:r,patterns:t})),new fi(n,r)}catch(s){throw await n.close(),s}}async pullEvent(t){if(this.isClosed())return null;const e=ai(await this.client.call({op:"pull_event",reader_id:this.readerId,timeout_ms:"number"==typeof t?Math.max(0,Math.floor(t)):void 0}));return e.event?ci(e.event):null}async closeTransport(){try{ai(await this.client.call({op:"unregister_reader",reader_id:this.readerId}))}catch(t){t instanceof Error&&/closed/i.test(t.message)||console.warn("kevent unregister failed:",t)}finally{await this.client.close()}}}async function pi(t,e,n){if(!ri())throw new Error("native kevent requires Node.js");const r=await async function(t){return ri()&&"function"==typeof require?require(t):Function("name","return import(name)")(t)}("node:net");return new Promise(((s,i)=>{const o=r.createConnection({host:t,port:e});let a=!1;const c=setTimeout((()=>{if(!a){a=!0,h();try{o.destroy(new Error(`kevent native connect timeout after ${n}ms`))}catch{}i(new Error(`kevent native connect timeout after ${n}ms`))}}),n),l=()=>{a||(a=!0,h(),s(o))},u=t=>{if(!a){a=!0,h();try{o.destroy(t)}catch{}i(t)}},h=()=>{clearTimeout(c),"function"==typeof o.off?(o.off("connect",l),o.off("error",u)):"function"==typeof o.removeListener&&(o.removeListener("connect",l),o.removeListener("error",u))};o.once("connect",l),o.once("error",u)}))}class gi{constructor(t){this.mode=t.mode,this.streamUrl=`${(t.streamUrl??"/kapi/kevent").replace(/\/+$/,"")}/stream`,this.nativeHost=t.nativeHost??"127.0.0.1",this.nativePort=t.nativePort??3183,this.nativeConnectTimeoutMs=t.nativeConnectTimeoutMs??5e3,this.fetcher=t.fetcher??ni,this.sessionTokenProvider=t.sessionTokenProvider??null,this.nativeConnector=t.nativeConnector??pi}async createEventReader(t,e={}){const n=si(t);if("browser"===this.mode){const t=new hi(this.streamUrl,n,"number"!=typeof(r=e.keepaliveMs)||!Number.isFinite(r)||r<=0?15e3:Math.floor(r),this.fetcher,this.sessionTokenProvider,e.signal);try{return await t.waitUntilReady(),t}catch(s){throw await t.close(),s}}var r;return fi.create(n,{nativeHost:this.nativeHost,nativePort:this.nativePort,nativeConnectTimeoutMs:this.nativeConnectTimeoutMs,nativeConnector:this.nativeConnector})}async create_event_reader(t,e={}){return this.createEventReader(t,e)}async subscribe(t,e,n={}){const r=si(t),s=new AbortController,i="number"==typeof n.reconnectDelayMs&&n.reconnectDelayMs>=0?Math.floor(n.reconnectDelayMs):1e3;let o=null,a=!1;n.signal&&(n.signal.aborted?(s.abort(),a=!0):n.signal.addEventListener("abort",(()=>{s.abort()}),{once:!0}));const c=(async()=>{for(;!a&&!s.signal.aborted;){try{for(o=await this.createEventReader(r,{...n,signal:s.signal});!a&&!s.signal.aborted;){const n=await o.pullEvent();if(!n)break;try{await e(n)}catch(t){console.error("kevent callback failed:",t)}}}catch(t){a||s.signal.aborted||console.warn("kevent subscription disconnected, will retry:",t)}finally{const t=o;o=null,t&&await t.close()}if(a||s.signal.aborted)break;try{await ii(i,s.signal)}catch{break}}})();return{close:async()=>{if(a)return;a=!0,s.abort();const t=o;o=null,t&&await t.close(),await c.catch((()=>{}))}}}}const mi={runtime:null};function yi(){if("undefined"==typeof window)return null;const t=window.BuckyApi;return t&&"object"==typeof t?t:null}async function wi(){const t=yi(),e=null==t?void 0:t.getCurrentUser;if("function"!=typeof e)return null;const n=await e.call(t);return 0===(null==n?void 0:n.code)?n.data??null:(console.error("BuckyApi.getCurrentUser failed: ",null==n?void 0:n.message),null)}async function bi(t,e=null){const n=yi(),r=null==n?void 0:n.resolve_did;if("function"!=typeof r)return null;const s=await r.call(n,t,e);return 0===(null==s?void 0:s.code)&&function(t){if(!t||"object"!=typeof t)return!1;const e=t;return"json"===e.type&&Object.prototype.hasOwnProperty.call(e,"value")||"jwt"===e.type&&"string"==typeof e.jwt}(s.data)?s.data:(console.error("BuckyApi.resolve_did failed: ",null==s?void 0:s.message),null)}function Ai(){return"undefined"!=typeof window}function _i(){const t=globalThis.process;return(null==t?void 0:t.env)??{}}function vi(t){if("string"!=typeof t)return null;const e=t.trim();return e.length>0?e:null}function Ei(){return"undefined"!=typeof localStorage}function ki(t){return t?t.split(/[./]/).map((t=>t.trim())).filter((t=>t.length>0)):[]}function Si(){return vi(_i().BUCKYOS_APP_INSTANCE_ID)?Ds.AppService:Ds.AppClient}function Ti(){var t;return(null==(t=mi.runtime)?void 0:t.getConfig().runtimeType)??function(){var t;if("undefined"!=typeof window)return window.BuckyApi?Ds.AppRuntime:Ds.Browser;const e=globalThis.process;return(null==(t=null==e?void 0:e.versions)?void 0:t.node)?Ds.NodeJS:Ds.Unknown}()}function Ri(){var t;const e=mi.runtime;return e?function(t){try{const e="undefined"!=typeof window?window.location.origin:"http://localhost";return new URL(t,e).origin}catch{return null}}(e.getSystemConfigServiceURL()):"undefined"!=typeof window&&(null==(t=window.location)?void 0:t.origin)?window.location.origin:null}async function Ii(){const t=mi.runtime;return t?t.ensureSessionTokenReady():null}class Oi{constructor(t){this.currentRuntime=null,this.currentAccountInfo=null,this.currentKEventClient=null,this.target=t}async initBuckyOS(t="",e=null){var n;const r=this.buildRuntimeConfig(t,e);if("node"!==this.target&&Ai()&&!e){localStorage.removeItem("zone_host_name");let e=localStorage.getItem("zone_host_name_v2");e||(e=await this.tryGetZoneHostName(t,window.location.host,r.defaultProtocol),localStorage.setItem("zone_host_name_v2",e)),r.zoneHost=e}var s;null==(n=this.currentRuntime)||n.stopAutoRenew(),this.currentKEventClient=null,this.currentAccountInfo=null,this.currentRuntime=new Xs(r),await this.currentRuntime.initialize(),s=this.currentRuntime,mi.runtime=s,this.syncCurrentAccountInfoFromRuntime()}getBuckyOSConfig(){var t;return(null==(t=this.currentRuntime)?void 0:t.getConfig())??null}getRuntimeType(){return this.currentRuntime?this.currentRuntime.getConfig().runtimeType:this.detectEnvironmentRuntimeType()}getAppId(){return this.currentRuntime?this.currentRuntime.getAppId():(console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),null)}getAppDid(){var t;return(null==(t=this.currentRuntime)?void 0:t.getAppDid())??null}getAppInstanceId(){var t;return(null==(t=this.currentRuntime)?void 0:t.getAppInstanceId())??null}getAppDataDir(){var t;return(null==(t=this.currentRuntime)?void 0:t.getDataDir())??null}attachEvent(t,e){}removeEvent(t){}getKEventClient(){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");if(this.currentKEventClient)return this.currentKEventClient;const t=this.currentRuntime.getConfig().runtimeType,e=t===Ds.Browser||t===Ds.AppRuntime?"browser":"native";return this.currentKEventClient=new gi({mode:e,streamUrl:this.currentRuntime.getZoneServiceURL("kevent"),sessionTokenProvider:this.currentRuntime.ensureSessionTokenReady.bind(this.currentRuntime)}),this.currentKEventClient}async createEventReader(t,e={}){return this.getKEventClient().createEventReader(t,e)}async create_event_reader(t,e={}){return this.createEventReader(t,e)}async subscribeKEvent(t,e,n={}){return this.getKEventClient().subscribe(t,e,n)}async getAccountInfo(){if(null==this.currentRuntime)return console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),null;this.syncCurrentAccountInfoFromRuntime();const t=this.currentRuntime.getConfig().runtimeType;if(t!==Ds.Browser&&t!==Ds.AppRuntime)return this.currentAccountInfo;const e=await this.currentRuntime.ensureSessionTokenReady(),n=Ei()?Mn.getBrowserUserInfo():null;return e&&n?(this.currentAccountInfo={user_name:n.user_name,user_id:n.user_id,user_type:n.user_type,session_token:e,refresh_token:void 0},this.currentAccountInfo):(this.currentAccountInfo=null,null)}async loginByPassword(t,e,n){var r,s,i;const o=this.getAppId();if(null==o)return console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),null;const a=n??(null==(r=this.currentRuntime)?void 0:r.getAuthTarget());if(!a)throw new Error("loginByPassword requires an AuthTarget");const c=Kn(a);if(c!==o)throw new Error(`auth target appid mismatch: ${c} != ${o}`);const l=Date.now(),u=Mn.hashPassword(t,e,l);Ei()&&localStorage.removeItem(`buckyos.account_info.${o}`);try{const e=this.getVerifyHubClient();e.setSeq(l);const n=await e.loginByPassword({username:t,password:u,target:a,login_nonce:l,source_url:"undefined"!=typeof window?window.location.href:void 0}),r=zn.normalizeLoginResponse(n),c={user_name:r.user_name,user_id:r.user_id,user_type:r.user_type,session_token:r.session_token,refresh_token:r.refresh_token};return Ei()&&(Mn.saveLocalAccountInfo(o,c),Mn.saveBrowserUserInfo({user_name:c.user_name,user_id:c.user_id,user_type:r.user_type})),this.currentAccountInfo=c,null==(s=this.currentRuntime)||s.setSessionToken(c.session_token),null==(i=this.currentRuntime)||i.setRefreshToken(c.refresh_token??null),c}catch(h){throw console.error("login failed: ",h),h}}async loginByRuntimeSession(){const t=this.currentRuntime;return null==t?(console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),null):(await t.login(),this.syncCurrentAccountInfoFromRuntime(),this.currentAccountInfo)}async loginByBrowserSSO(){if(null==this.currentRuntime)return void console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first");const t=this.getAppId();if(null==t)return void console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first");Ei()&&Mn.cleanLocalAccountInfo(t);const e=this.getZoneHostName();if(null!=e)try{const t=new Vn(e);await t.login()}catch(n){throw console.error("login failed: ",n),n}else console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first")}async login(){return this.usesRuntimeManagedSession()?this.loginByRuntimeSession():(await this.loginByBrowserSSO(),this.currentAccountInfo)}logout(t=!0){if(null==this.currentRuntime)return void console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first");const e=this.getAppId();null!=e?(t&&this.currentRuntime.logoutBrowserSSO(),t&&Ei()&&Mn.cleanLocalAccountInfo(e),this.currentAccountInfo=null,this.currentKEventClient=null,this.currentRuntime.clearAuthState()):console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first")}async getAppSetting(t=null){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return function(t,e){const n=ki(e);if(0===n.length)return t;let r=t;for(const s of n){if(!r||"object"!=typeof r||Array.isArray(r)||!(s in r))return;r=r[s]}return r}(await this.currentRuntime.getMySettings(),t)}async setAppSetting(t=null,e){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");const n=await this.currentRuntime.getMySettings(),r=function(t,e,n){const r=ki(e);if(0===r.length){if(!n||"object"!=typeof n||Array.isArray(n))throw new Error("settingValue must be a JSON object when settingName is null");return n}const s=Array.isArray(t)?{}:{...t};let i=s;for(let o=0;o<r.length-1;o+=1){const t=r[o],e=i[t],n=e&&"object"==typeof e&&!Array.isArray(e)?{...e}:{};i[t]=n,i=n}return i[r[r.length-1]]=n,s}(n&&"object"==typeof n&&!Array.isArray(n)?{...n}:{},t,function(t){try{return JSON.parse(t)}catch{return t}}(e));await this.currentRuntime.updateAllMySettings(r)}getCurrentWalletUser(){if("undefined"==typeof window)throw new Error("BuckyApi is only available in browser runtime");return wi()}resolve_did(t,e=null){if("undefined"==typeof window)throw new Error("BuckyApi is only available in browser runtime");return bi(t,e)}walletSignWithActiveDid(t){if("undefined"==typeof window)throw new Error("BuckyApi is only available in browser runtime");return(async()=>{var e,n;const r=await window.BuckyApi.signJsonWithActiveDid(t);return 0===r.code?{signatures:Array.isArray(null==(e=r.data)?void 0:e.signatures)?r.data.signatures:[],pwd_hash:"string"==typeof(null==(n=r.data)?void 0:n.pwd_hash)?r.data.pwd_hash:null}:(console.error("BuckyApi.signWithActiveDid failed: ",r.message),null)})()}async openExternalUrl(t){if("undefined"==typeof window)throw new Error("openExternalUrl is only available in browser runtime");const e=window.BuckyApi;"function"!=typeof(null==e?void 0:e.openExternalUrl)?window.open(t,"_blank","noopener,noreferrer"):await e.openExternalUrl(t)}getZoneHostName(){return null==this.currentRuntime?(console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),null):this.currentRuntime.getZoneHostName()}getZoneServiceURL(t){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return this.currentRuntime.getZoneServiceURL(t)}getServiceRpcClient(t){if(null==this.currentRuntime)throw console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return this.syncCurrentAccountInfoFromRuntime(),this.currentRuntime.getServiceRpcClient(t)}getVerifyHubClient(){if(null==this.currentRuntime)throw console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return this.currentRuntime.getVerifyHubClient()}getSystemConfigClient(){if(null==this.currentRuntime)throw console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return this.currentRuntime.getSystemConfigClient()}getTaskManagerClient(){if(null==this.currentRuntime)throw console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return this.currentRuntime.getTaskManagerClient()}getWorkflowClient(){if(null==this.currentRuntime)throw console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return this.currentRuntime.getWorkflowClient()}getAiccClient(){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return this.currentRuntime.getAiccClient()}getMsgQueueClient(){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return this.currentRuntime.getMsgQueueClient()}getMsgCenterClient(){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return this.currentRuntime.getMsgCenterClient()}getRepoClient(){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return this.currentRuntime.getRepoClient()}buildRuntimeConfig(t,e){if(e){let n=e.runtimeType;return n===Ds.NodeJS&&"browser"!==this.target&&(n=Si()),{...Bs,...e,appId:e.appId||t,runtimeType:n}}return"browser"===this.target?{...Bs,appId:t,runtimeType:this.detectEnvironmentRuntimeType(),defaultProtocol:"undefined"!=typeof window?window.location.protocol+"//":"http://"}:"node"===this.target?{...Bs,appId:t,runtimeType:Si(),defaultProtocol:"https://",zoneHost:vi(_i().BUCKYOS_ZONE_HOST)??""}:Ai()?{...Bs,appId:t,runtimeType:this.detectEnvironmentRuntimeType(),defaultProtocol:window.location.protocol+"//"}:{...Bs,appId:t,runtimeType:Si(),defaultProtocol:"https://",zoneHost:vi(_i().BUCKYOS_ZONE_HOST)??""}}async tryGetZoneHostName(t,e,n){const r=await this.fetchZoneHostFromIdentifierDoc(n+e+"/1.0/identifiers/self");if(r)return r;const s=e.split(".").slice(1).join(".");if(!s)return e;const i=await this.fetchZoneHostFromIdentifierDoc(n+s+"/1.0/identifiers/self");return i||e}async fetchZoneHostFromIdentifierDoc(t){try{const e=await fetch(t);if(200!==e.status)return null;const n=await e.json(),r="string"==typeof n.hostname?n.hostname.trim():"";if(r.length>0)return r;if("string"==typeof n.id){const t=n.id.match(/^did:web:([^/?#]+)/);if(t&&t[1])return t[1]}return null}catch{return null}}syncCurrentAccountInfoFromRuntime(){if(null==this.currentRuntime)return;const t=this.currentRuntime.getSessionToken();if(!t)return;const e=Hs(t),n="string"==typeof(null==e?void 0:e.sub)?e.sub:"string"==typeof(null==e?void 0:e.userid)?e.userid:this.currentRuntime.getOwnerUserId()??"root",r="string"==typeof(null==e?void 0:e.user_type)?e.user_type:this.currentRuntime.getConfig().runtimeType===Ds.AppService?"service":void 0;this.currentAccountInfo={user_name:n,user_id:n,user_type:r,session_token:t,refresh_token:this.currentRuntime.getRefreshToken()??void 0}}usesRuntimeManagedSession(){if(null==this.currentRuntime)return!1;const t=this.currentRuntime.getConfig().runtimeType;return t===Ds.AppClient||t===Ds.AppService}detectEnvironmentRuntimeType(){var t,e;if("browser"===this.target)return"undefined"!=typeof window&&window.BuckyApi?Ds.AppRuntime:"undefined"!=typeof window?Ds.Browser:Ds.Unknown;if("node"===this.target){const e=globalThis.process;return(null==(t=null==e?void 0:e.versions)?void 0:t.node)?Si():Ds.Unknown}if("undefined"!=typeof window)return window.BuckyApi?Ds.AppRuntime:Ds.Browser;const n=globalThis.process;return(null==(e=null==n?void 0:n.versions)?void 0:e.node)?Ds.NodeJS:Ds.Unknown}}const Ci="/kapi/bns",xi="/kapi/bns-indexer",Ni="did:bns:",Pi="name.query_state",Di="name.resolve_owner",Bi="authority.get_set",Ui="authority.get_key",Li="document.resolve",Mi="document.get_version",Fi="name.query_by_addr",Gi="tx.query_state",ji="tx.submit_raw",Hi="events.list",Vi="checkpoint.latest",Wi={transport:"RPC_TRANSPORT_ERROR",serialization:"SERIALIZATION_ERROR",invalid_response:"INVALID_RESPONSE",timeout:"TX_WAIT_TIMEOUT"};class Ki extends Error{constructor(t,e,n=null){super(e),this.name="BnsClientError",this.kind=t,this.info=n}get code(){var t;return"registry"===this.kind?(null==(t=this.info)?void 0:t.code)??"UNKNOWN_BNS_ERROR":Wi[this.kind]}isRegistryCode(t){return"registry"===this.kind&&this.code===t}static registry(t){return new Ki("registry",`${t.code}: ${t.message}`,t)}static registryCode(t,e,n={}){return Ki.registry({code:t,message:e,name:null,doc_type:null,expected:null,actual:null,...n})}}class zi extends Error{constructor(t,e){super(`${t}: ${e}`),this.path=t,this.reason=e,this.name="BnsDecodeError"}}function qi(t,e){throw new zi(t,e)}const $i=(t,e)=>"string"==typeof t?t:qi(e,"expected string"),Qi=(t,e)=>"boolean"==typeof t?t:qi(e,"expected boolean"),Ji=(t,e)=>"number"==typeof t&&Number.isInteger(t)&&t>=0?t:qi(e,"expected u64"),Yi=(t,e)=>"number"==typeof t&&Number.isInteger(t)&&t>=0&&t<=4294967295?t:qi(e,"expected u32"),Zi=(t,e)=>{Array.isArray(t)||qi(e,"expected byte array");for(let n=0;n<t.length;n++){const r=t[n];("number"!=typeof r||!Number.isInteger(r)||r<0||r>255)&&qi(`${e}[${n}]`,"expected u8")}return t};function Xi(...t){return(e,n)=>"string"==typeof e&&t.includes(e)?e:qi(n,`expected one of ${t.join("|")}`)}function to(t){return(e,n)=>(Array.isArray(e)||qi(n,"expected array"),e.map(((e,r)=>t(e,`${n}[${r}]`))))}function eo(t,e){const n=(e,n)=>t(e,n);return n.onMissing=e,n}function no(t){return eo(((e,n)=>null===e?null:t(e,n)),(()=>null))}const ro=eo(Ji,(()=>0));function so(t,e){const n=Object.keys(e);return(r,s)=>{(null===r||"object"!=typeof r||Array.isArray(r))&&qi(s,`expected ${t} object`);const i=r,o={};for(const t of n){const n=e[t],r=`${s}.${t}`,a=i[t];if(void 0===a&&!(t in i)){if(n.onMissing){o[t]=n.onMissing();continue}qi(r,"missing field")}o[t]=n(a,r)}return o}}const io=Xi("available","active","expired","released","tombstoned"),oo=Xi("missing","active","revoked","expired","migrated","tombstoned"),ao=Xi("none","alias","migrated_to","canonical"),co=Xi("release_after_grace","tombstone_forever"),lo=Xi("unset","chain_account","bns_name"),uo=Xi("none","asset_owner_fallback","explicit_semantic_owner","parent_inherited"),ho=Xi("missing","active","revoked","expired"),fo=Xi("not_found","pending","succeeded","reverted"),po=so("Principal",{kind:lo,value:$i}),go=so("NameState",{name:$i,asset_owner:$i,semantic_owner:po,effective_owner:po,owner_source:uo,standard_transfer_enabled:Qi,status:io,registered_at:Ji,expire_at:Ji,grace_until:Ji,updated_at:Ji,name_seq:Ji,owner_document_version:Ji,min_document_iat:ro,owner_policy_seq:ro,lineage_epoch:Ji,renewable:Qi,transferable:Qi,allow_delegated_subnames:Qi,namespace_policy_hash:$i,payment_policy_hash:$i,alias_state_hash:$i}),mo=so("OwnerResolution",{effective_owner:po,source:uo,authority_root:$i,authority_seq:Ji}),yo=so("AuthoritySetState",{name:$i,authority_seq:Ji,authority_root:$i,active_key_count:Yi}),wo=so("AuthorityKey",{kid:$i,verification_method:$i,key_data:Zi,purposes:Yi,valid_from:Ji,valid_until:Ji,status:ho,metadata_hash:$i}),bo=so("DocumentRef",{storage_type:$i,uri:$i,inline_document:Zi,content_hash:$i,schema:$i,codec:$i,extra_hash:$i}),Ao=so("DocumentState",{name:$i,doc_type:$i,version:Ji,previous_version:Ji,status:oo,document:bo,controller:po,beneficiary:po,payment_target:$i,valid_from:Ji,expire_at:Ji,revoked_at:Ji,controller_policy_hash:$i,payment_policy_hash:$i,split_policy_hash:$i,price_policy_hash:$i,rights_policy_hash:$i,document_state_hash:$i}),_o=so("ResolveResult",{name_state:go,document_state:Ao,owner:mo,effective_controller:po,status:oo,alias_kind:ao,alias_target_did:$i,proof_root:$i}),vo=so("BnsNamePage",{names:to($i),next_cursor:no($i)}),Eo=so("BnsTxState",{tx_hash:$i,state:fo,block_number:no(Ji),confirmations:Ji}),ko=so("BnsSubmitRawTxResp",{tx_hash:$i}),So=so("LogCheckpoint",{log_root:$i,last_seq:Ji,issued_at:Ji,issuer:po,external_anchor:$i}),To={name_registered:so("name_registered",{name:$i,asset_owner:$i,expire_at:Ji,lineage_epoch:Ji,name_seq:Ji}),name_renewed:so("name_renewed",{name:$i,expire_at:Ji,name_seq:Ji}),name_asset_transferred:so("name_asset_transferred",{name:$i,old_asset_owner:$i,new_asset_owner:$i,standard_transfer:Qi,name_seq:Ji}),name_owner_updated:so("name_owner_updated",{name:$i,owner:po,owner_source:uo,standard_transfer_enabled:Qi,name_seq:Ji}),authority_keys_updated:so("authority_keys_updated",{name:$i,authority_seq:Ji,authority_root:$i}),name_released:so("name_released",{name:$i,mode:co,reason_hash:$i,name_seq:Ji}),document_published:so("document_published",{name:$i,doc_type:$i,version:Ji,content_hash:$i,document_state_hash:$i}),document_revoked:so("document_revoked",{name:$i,doc_type:$i,previous_version:Ji,new_version:Ji,reason_hash:$i}),owner_document_iat_floor_updated:so("owner_document_iat_floor_updated",{name:$i,previous_min_document_iat:Ji,new_min_document_iat:Ji,owner_policy_seq:Ji,name_seq:Ji,reason_hash:$i}),controller_policy_updated:so("controller_policy_updated",{name:$i,policy_hash:$i,name_seq:Ji}),namespace_policy_updated:so("namespace_policy_updated",{name:$i,allow_delegated_subnames:Qi,namespace_policy_hash:$i,name_seq:Ji}),did_alias_set:so("did_alias_set",{name:$i,target_did:$i,kind:ao,proof_hash:$i,name_seq:Ji}),payment_target_updated:so("payment_target_updated",{name:$i,doc_type:$i,payment_target:$i,payment_policy_hash:$i,version:Ji}),log_checkpoint_published:so("log_checkpoint_published",{log_root:$i,last_seq:Ji,issued_at:Ji,external_anchor:$i})},Ro=to(so("EventLogRecord",{seq:Ji,event_type:$i,observed_at:Ji,event_hash:$i,previous_log_root:$i,log_root:$i,event:(t,e)=>{(null===t||"object"!=typeof t||Array.isArray(t))&&qi(e,"expected RegistryEvent object");const n=t;"string"!=typeof n.type&&qi(`${e}.type`,"expected string event tag");const r=To[n.type];return r||qi(`${e}.type`,`unknown event type \`${n.type}\``),"data"in n&&void 0!==n.data||qi(`${e}.data`,"missing field"),{type:n.type,data:r(n.data,`${e}.data`)}}})),Io=so("BnsRpcErrorInfo",{code:$i,message:$i,name:no($i),doc_type:no($i),expected:no(Ji),actual:no(Ji)});function Oo(t){const e=t.split("://"),n=e.length>1?e.slice(1).join("://"):t,r=n.indexOf("/");return!(r<0)&&""!==n.slice(r+1).replace(/\/+$/,"")}function Co(t){const e=t.replace(/\/+$/,"");return Oo(e)?e:`${e}${Ci}`}function xo(t){const e=t.replace(/\/+$/,"");return Oo(e)?e:`${e}${xi}`}function No(t){const e=e=>Ki.registryCode("INVALID_NAME",`invalid BNS name \`${t}\`: ${e}`,{name:t});if(!t)throw e("name is empty");if(t.trim()!==t)throw e("name must not contain leading or trailing whitespace");if(t.startsWith(Ni))throw e("contract names must not include did:bns: prefix");if(t.length>253)throw e("name must be at most 253 bytes");for(const n of t.split(".")){if(!n)throw e("empty label");if(n.length>126)throw e("label must be at most 126 bytes");if(n.startsWith("-")||n.endsWith("-"))throw e("label must not start or end with '-'");if(!/^[a-z0-9-]+$/.test(n))throw e("only lower-case ASCII letters, digits, '-' and '.' are supported")}return t}function Po(t){const e=e=>Ki.registryCode("INVALID_DOC_TYPE",`invalid doc_type \`${t}\`: ${e}`,{doc_type:t});if(!t)throw e("doc_type is empty");if(t.length>32)throw e("doc_type must be at most 32 bytes");if(!/^[a-z0-9_-]+$/.test(t))throw e("only lower-case ASCII letters, digits, '-' and '_' are supported");return t}const Do="0123456789abcdef";function Bo(t){if(t instanceof Uint8Array){if(0===t.length)throw new Ki("serialization","raw_tx must not be empty");return`0x${function(t){let e="";for(let n=0;n<t.length;n++)e+=Do[t[n]>>4]+Do[15&t[n]];return e}(t)}`}const e=t.trim();if(!e)throw new Ki("serialization","raw_tx must not be empty");const n=e.startsWith("0x")?e.slice(2):e;if(!n||n.length%2!=0)throw new Ki("serialization",`raw_tx must be even-length hex, got \`${t}\``);if(!/^[0-9a-fA-F]+$/.test(n))throw new Ki("serialization",`invalid raw_tx hex \`${t}\``);return`0x${n}`}function Uo(t,e){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw new Ki("serialization",`waitTx ${t} must be a non-negative integer, got ${e}`);return Math.max(1,e)}class Lo{constructor(t,e=null,n={}){this.rpcClient=new jn(Co(t),e,null,n)}static forIndexer(t,e=null,n={}){return new Lo(xo(t),e,n)}setSeq(t){this.rpcClient.setSeq(t)}async syncSessionToken(t){this.rpcClient.setSessionToken(t)}getSessionToken(){return this.rpcClient.getSessionToken()}setTraceId(t){this.rpcClient.setTraceId(t)}getTraceId(){return this.rpcClient.getTraceId()}async callEnvelope(t,e){let n;try{n=await this.rpcClient.call(t,e)}catch(s){const e=s instanceof Error?s.message:String(s);throw new Ki("transport",`${t} failed: ${e}`)}if(null===n||"object"!=typeof n||Array.isArray(n))throw new Ki("invalid_response",`invalid BNS RPC envelope for ${t}`);const r=n;if("boolean"!=typeof r.ok)throw new Ki("invalid_response",`invalid BNS RPC envelope for ${t}`);if(!r.ok){if(void 0!==r.result&&null!==r.result)throw new Ki("invalid_response",`unexpected result in failed BNS envelope for ${t}`);if(void 0===r.error||null===r.error)throw Ki.registryCode("UNKNOWN_BNS_ERROR","BNS RPC envelope missing error");let e;try{e=Io(r.error,"error")}catch(s){const e=s instanceof zi?s.message:String(s);throw new Ki("invalid_response",`invalid BNS error info for ${t}: ${e}`)}throw Ki.registry(e)}if(void 0!==r.error&&null!==r.error)throw new Ki("invalid_response",`unexpected error in successful BNS envelope for ${t}`);if(void 0===r.result)throw new Ki("invalid_response",`BNS RPC envelope missing result for ${t}`);return r.result}decodeResult(t,e,n){try{return e(n,"result")}catch(r){const e=r instanceof zi?r.message:String(r);throw new Ki("invalid_response",`invalid ${t} result: ${e}`)}}async call(t,e,n){const r=await this.callEnvelope(t,e);if(null===r)throw new Ki("invalid_response",`BNS RPC envelope missing result for ${t}`);return this.decodeResult(t,n,r)}async callNullable(t,e,n){const r=await this.callEnvelope(t,e);return null===r?null:this.decodeResult(t,n,r)}async queryNameState(t){return this.callNullable(Pi,{name:t},go)}async resolveOwner(t){return this.call(Di,{name:t},mo)}async getAuthoritySet(t){return this.call(Bi,{name:t},yo)}async getAuthorityKey(t,e){return this.callNullable(Ui,{name:t,kid:e},wo)}async resolveDocument(t,e){return this.call(Li,{name:t,doc_type:e},_o)}async getDocumentVersion(t,e,n){return this.callNullable(Mi,{name:t,doc_type:e,version:n},Ao)}async queryNamesByAddress(t,e=null,n=100){return this.call(Fi,{address:t,cursor:e,limit:n},vo)}async*iterNamesByAddress(t,e=100){let n=null;do{const r=await this.queryNamesByAddress(t,n,e);yield*r.names,n=r.next_cursor}while(null!==n)}async queryTxState(t){return this.call(Gi,{tx_hash:t},Eo)}async submitRawTx(t){return this.call(ji,{raw_tx:Bo(t)},ko)}async waitTx(t,e={}){const n=Uo("confirmations",e.confirmations??1),r=Uo("intervalMs",e.intervalMs??2e3),s=Uo("timeoutMs",e.timeoutMs??12e4),i=Date.now();for(;;){const e=await this.queryTxState(t);if("reverted"===e.state)return e;if("succeeded"===e.state&&e.confirmations>=n)return e;if(Date.now()-i>=s)throw new Ki("timeout",`timed out waiting for tx ${t} (last state: ${e.state})`);await new Promise((t=>setTimeout(t,r)))}}async listEvents(t,e=100){return this.call(Hi,{from_seq:t,limit:e},Ro)}async latestCheckpoint(){return this.callNullable(Vi,{},So)}}const Mo=Object.freeze(Object.defineProperty({__proto__:null,BNS_INDEXER_RPC_PATH:xi,BNS_SERVER_RPC_PATH:Ci,BnsClient:Lo,BnsClientError:Ki,DID_BNS_PREFIX:Ni,KEY_PURPOSE_AUTHENTICATION:1,KEY_PURPOSE_RECOVERY:2,KEY_PURPOSE_SIGN_DOCUMENT:4,MAX_BNS_LABEL_LEN:126,MAX_BNS_NAMES_PAGE_SIZE:1e3,MAX_BNS_NAME_LEN:253,METHOD_GET_AUTHORITY_KEY:Ui,METHOD_GET_AUTHORITY_SET:Bi,METHOD_GET_DOCUMENT_VERSION:Mi,METHOD_LATEST_CHECKPOINT:Vi,METHOD_LIST_EVENTS:Hi,METHOD_QUERY_NAMES_BY_ADDRESS:Fi,METHOD_QUERY_NAME_STATE:Pi,METHOD_QUERY_TX_STATE:Gi,METHOD_RESOLVE_DOCUMENT:Li,METHOD_RESOLVE_OWNER:Di,METHOD_SUBMIT_RAW_TX:ji,ZERO_HASH:"0x0000000000000000000000000000000000000000000000000000000000000000",canonicalBnsName:No,canonicalDocType:Po,didBnsFromName:function(t){return`${Ni}${No(t)}`},nameFromDidBns:function(t){if(!t.startsWith(Ni))throw Ki.registryCode("INVALID_NAME",`invalid BNS name \`${t}\`: DID must start with did:bns:`,{name:t});return No(t.slice(8))},normalizeBnsIndexerUrl:xo,normalizeBnsServerUrl:Co,normalizeRawTx:Bo},Symbol.toStringTag,{value:"Module"})),Fo="6.17.0";function Go(t,e,n){const r=e.split("|").map((t=>t.trim()));for(let i=0;i<r.length;i++)switch(e){case"any":return;case"bigint":case"boolean":case"number":case"string":if(typeof t===e)return}const s=new Error(`invalid value for type ${e}`);throw s.code="INVALID_ARGUMENT",s.argument=`value.${n}`,s.value=t,s}async function jo(t){const e=Object.keys(t);return(await Promise.all(e.map((e=>Promise.resolve(t[e]))))).reduce(((t,n,r)=>(t[e[r]]=n,t)),{})}function Ho(t,e,n){for(let r in e){let s=e[r];const i=n?n[r]:null;i&&Go(s,i,r),Object.defineProperty(t,r,{enumerable:!0,value:s,writable:!1})}}function Vo(t,e){if(null==t)return"null";if(null==e&&(e=new Set),"object"==typeof t){if(e.has(t))return"[Circular]";e.add(t)}if(Array.isArray(t))return"[ "+t.map((t=>Vo(t,e))).join(", ")+" ]";if(t instanceof Uint8Array){const e="0123456789abcdef";let n="0x";for(let r=0;r<t.length;r++)n+=e[t[r]>>4],n+=e[15&t[r]];return n}if("object"==typeof t&&"function"==typeof t.toJSON)return Vo(t.toJSON(),e);switch(typeof t){case"boolean":case"number":case"symbol":return t.toString();case"bigint":return BigInt(t).toString();case"string":return JSON.stringify(t);case"object":{const n=Object.keys(t);return n.sort(),"{ "+n.map((n=>`${Vo(n,e)}: ${Vo(t[n],e)}`)).join(", ")+" }"}}return"[ COULD NOT SERIALIZE ]"}function Wo(t,e){return t&&t.code===e}function Ko(t){return Wo(t,"CALL_EXCEPTION")}function zo(t,e,n){let r,s=t;{const r=[];if(n){if("message"in n||"code"in n||"name"in n)throw new Error(`value will overwrite populated values: ${Vo(n)}`);for(const t in n){if("shortMessage"===t)continue;const e=n[t];r.push(t+"="+Vo(e))}}r.push(`code=${e}`),r.push(`version=${Fo}`),r.length&&(t+=" ("+r.join(", ")+")")}switch(e){case"INVALID_ARGUMENT":r=new TypeError(t);break;case"NUMERIC_FAULT":case"BUFFER_OVERRUN":r=new RangeError(t);break;default:r=new Error(t)}return Ho(r,{code:e}),n&&Object.assign(r,n),null==r.shortMessage&&Ho(r,{shortMessage:s}),r}function qo(t,e,n,r){if(!t)throw zo(e,n,r)}function $o(t,e,n,r){qo(t,e,"INVALID_ARGUMENT",{argument:n,value:r})}function Qo(t,e,n){null==n&&(n=""),n&&(n=": "+n),qo(t>=e,"missing argument"+n,"MISSING_ARGUMENT",{count:t,expectedCount:e}),qo(t<=e,"too many arguments"+n,"UNEXPECTED_ARGUMENT",{count:t,expectedCount:e})}const Jo=["NFD","NFC","NFKD","NFKC"].reduce(((t,e)=>{try{if("test"!=="test".normalize(e))throw new Error("bad");if("NFD"===e){const t=String.fromCharCode(233).normalize("NFD");if(t!==String.fromCharCode(101,769))throw new Error("broken")}t.push(e)}catch(n){}return t}),[]);function Yo(t){qo(Jo.indexOf(t)>=0,"platform missing String.prototype.normalize","UNSUPPORTED_OPERATION",{operation:"String.prototype.normalize",info:{form:t}})}function Zo(t,e,n){if(null==n&&(n=""),t!==e){let t=n,e="new";n&&(t+=".",e+=" "+n),qo(!1,`private constructor; use ${t}from* methods`,"UNSUPPORTED_OPERATION",{operation:e})}}function Xo(t,e,n){if(t instanceof Uint8Array)return n?new Uint8Array(t):t;if("string"==typeof t&&t.length%2==0&&t.match(/^0x[0-9a-f]*$/i)){const e=new Uint8Array((t.length-2)/2);let n=2;for(let r=0;r<e.length;r++)e[r]=parseInt(t.substring(n,n+2),16),n+=2;return e}$o(!1,"invalid BytesLike value",e||"value",t)}function ta(t,e){return Xo(t,e,!1)}function ea(t,e){return Xo(t,e,!0)}function na(t,e){return!("string"!=typeof t||!t.match(/^0x[0-9A-Fa-f]*$/))&&(("number"!=typeof e||t.length===2+2*e)&&(!0!==e||t.length%2==0))}function ra(t){return na(t,!0)||t instanceof Uint8Array}const sa="0123456789abcdef";function ia(t){const e=ta(t);let n="0x";for(let r=0;r<e.length;r++){const t=e[r];n+=sa[(240&t)>>4]+sa[15&t]}return n}function oa(t){return"0x"+t.map((t=>ia(t).substring(2))).join("")}function aa(t){return na(t,!0)?(t.length-2)/2:ta(t).length}function ca(t,e,n){const r=ta(t);return null!=n&&n>r.length&&qo(!1,"cannot slice beyond data bounds","BUFFER_OVERRUN",{buffer:r,length:r.length,offset:n}),ia(r.slice(null==e?0:e,null==n?r.length:n))}function la(t,e,n){const r=ta(t);qo(e>=r.length,"padding exceeds data length","BUFFER_OVERRUN",{buffer:new Uint8Array(r),length:e,offset:e+1});const s=new Uint8Array(e);return s.fill(0),n?s.set(r,e-r.length):s.set(r,0),ia(s)}function ua(t,e){return la(t,e,!0)}function ha(t,e){return la(t,e,!1)}const da=BigInt(0),fa=BigInt(1),pa=9007199254740991;function ga(t,e){let n=ya(t,"value");const r=BigInt(_a(e,"width")),s=fa<<r-fa;if(n<da){n=-n,qo(n<=s,"too low","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:t});return(~n&(fa<<r)-fa)+fa}return qo(n<s,"too high","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:t}),n}function ma(t,e){const n=wa(t,"value"),r=BigInt(_a(e,"bits"));return n&(fa<<r)-fa}function ya(t,e){switch(typeof t){case"bigint":return t;case"number":return $o(Number.isInteger(t),"underflow",e||"value",t),$o(t>=-pa&&t<=pa,"overflow",e||"value",t),BigInt(t);case"string":try{if(""===t)throw new Error("empty string");return"-"===t[0]&&"-"!==t[1]?-BigInt(t.substring(1)):BigInt(t)}catch(n){$o(!1,`invalid BigNumberish string: ${n.message}`,e||"value",t)}}$o(!1,"invalid BigNumberish value",e||"value",t)}function wa(t,e){const n=ya(t,e);return qo(n>=da,"unsigned value cannot be negative","NUMERIC_FAULT",{fault:"overflow",operation:"getUint",value:t}),n}const ba="0123456789abcdef";function Aa(t){if(t instanceof Uint8Array){let e="0x0";for(const n of t)e+=ba[n>>4],e+=ba[15&n];return BigInt(e)}return ya(t)}function _a(t,e){switch(typeof t){case"bigint":return $o(t>=-pa&&t<=pa,"overflow",e||"value",t),Number(t);case"number":return $o(Number.isInteger(t),"underflow",e||"value",t),$o(t>=-pa&&t<=pa,"overflow",e||"value",t),t;case"string":try{if(""===t)throw new Error("empty string");return _a(BigInt(t),e)}catch(n){$o(!1,`invalid numeric string: ${n.message}`,e||"value",t)}}$o(!1,"invalid numeric value",e||"value",t)}function va(t,e){const n=wa(t,"value");let r=n.toString(16);if(null==e)r.length%2&&(r="0"+r);else{const s=_a(e,"width");if(0===s&&n===da)return"0x";for(qo(2*s>=r.length,`value exceeds width (${s} bytes)`,"NUMERIC_FAULT",{operation:"toBeHex",fault:"overflow",value:t});r.length<2*s;)r="0"+r}return"0x"+r}function Ea(t,e){const n=wa(t,"value");if(n===da){const t=null!=e?_a(e,"width"):0;return new Uint8Array(t)}let r=n.toString(16);if(r.length%2&&(r="0"+r),null!=e){const n=_a(e,"width");for(;r.length<2*n;)r="00"+r;qo(2*n===r.length,`value exceeds width (${n} bytes)`,"NUMERIC_FAULT",{operation:"toBeArray",fault:"overflow",value:t})}const s=new Uint8Array(r.length/2);for(let i=0;i<s.length;i++){const t=2*i;s[i]=parseInt(r.substring(t,t+2),16)}return s}function ka(t){let e=ia(ra(t)?t:Ea(t)).substring(2);for(;e.startsWith("0");)e=e.substring(1);return""===e&&(e="0"),"0x"+e}const Sa="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";let Ta=null;function Ra(t){if(null==Ta){Ta={};for(let t=0;t<58;t++)Ta[Sa[t]]=BigInt(t)}const e=Ta[t];return $o(null!=e,"invalid base58 value","letter",t),e}const Ia=BigInt(0),Oa=BigInt(58);function Ca(t){const e=ta(t);let n=Aa(e),r="";for(;n;)r=Sa[Number(n%Oa)]+r,n/=Oa;for(let s=0;s<e.length&&!e[s];s++)r=Sa[0]+r;return r}class xa{constructor(e,n,r){xn(this,"filter"),xn(this,"emitter"),Dn(this,t,void 0),Bn(this,t,n),Ho(this,{emitter:e,filter:r})}async removeListener(){null!=Pn(this,t)&&await this.emitter.off(this.filter,Pn(this,t))}}function Na(t,e,n,r,s){if("BAD_PREFIX"===t||"UNEXPECTED_CONTINUE"===t){let t=0;for(let r=e+1;r<n.length&&n[r]>>6==2;r++)t++;return t}return"OVERRUN"===t?n.length-e-1:0}t=new WeakMap;const Pa=Object.freeze({error:function(t,e,n,r,s){$o(!1,`invalid codepoint at offset ${e}; ${t}`,"bytes",n)},ignore:Na,replace:function(t,e,n,r,s){return"OVERLONG"===t?($o("number"==typeof s,"invalid bad code point for replacement","badCodepoint",s),r.push(s),0):(r.push(65533),Na(t,e,n))}});function Da(t,e){$o("string"==typeof t,"invalid string value","str",t),null!=e&&(Yo(e),t=t.normalize(e));let n=[];for(let r=0;r<t.length;r++){const e=t.charCodeAt(r);if(e<128)n.push(e);else if(e<2048)n.push(e>>6|192),n.push(63&e|128);else if(55296==(64512&e)){r++;const s=t.charCodeAt(r);$o(r<t.length&&56320==(64512&s),"invalid surrogate pair","str",t);const i=65536+((1023&e)<<10)+(1023&s);n.push(i>>18|240),n.push(i>>12&63|128),n.push(i>>6&63|128),n.push(63&i|128)}else n.push(e>>12|224),n.push(e>>6&63|128),n.push(63&e|128)}return new Uint8Array(n)}function Ba(t,e){return n=function(t,e){null==e&&(e=Pa.error);const n=ta(t,"bytes"),r=[];let s=0;for(;s<n.length;){const t=n[s++];if(!(t>>7)){r.push(t);continue}let i=null,o=null;if(192==(224&t))i=1,o=127;else if(224==(240&t))i=2,o=2047;else{if(240!=(248&t)){s+=e(128==(192&t)?"UNEXPECTED_CONTINUE":"BAD_PREFIX",s-1,n,r);continue}i=3,o=65535}if(s-1+i>=n.length){s+=e("OVERRUN",s-1,n,r);continue}let a=t&(1<<8-i-1)-1;for(let c=0;c<i;c++){let t=n[s];if(128!=(192&t)){s+=e("MISSING_CONTINUE",s,n,r),a=null;break}a=a<<6|63&t,s++}null!==a&&(a>1114111?s+=e("OUT_OF_RANGE",s-1-i,n,r,a):a>=55296&&a<=57343?s+=e("UTF16_SURROGATE",s-1-i,n,r,a):a<=o?s+=e("OVERLONG",s-1-i,n,r,a):r.push(a))}return r}(t,e),n.map((t=>t<=65535?String.fromCharCode(t):(t-=65536,String.fromCharCode(55296+(t>>10&1023),56320+(1023&t))))).join("");var n}function Ua(t){return async function(e,n){qo(null==n||!n.cancelled,"request cancelled before sending","CANCELLED");const r=e.url.split(":")[0].toLowerCase();qo("http"===r||"https"===r,`unsupported protocol ${r}`,"UNSUPPORTED_OPERATION",{info:{protocol:r},operation:"request"}),qo("https"===r||!e.credentials||e.allowInsecureAuthentication,"insecure authorized connections unsupported","UNSUPPORTED_OPERATION",{operation:"request"});let s=null;const i=new AbortController,o=setTimeout((()=>{s=zo("request timeout","TIMEOUT"),i.abort()}),e.timeout);n&&n.addListener((()=>{s=zo("request cancelled","CANCELLED"),i.abort()}));const a=Object.assign({},t,{method:e.method,headers:new Headers(Array.from(e)),body:e.body||void 0,signal:i.signal});let c;try{c=await fetch(e.url,a)}catch(d){if(clearTimeout(o),s)throw s;throw d}clearTimeout(o);const l={};c.headers.forEach(((t,e)=>{l[e.toLowerCase()]=t}));const u=await c.arrayBuffer(),h=null==u?null:new Uint8Array(u);return{statusCode:c.status,statusMessage:c.statusText,headers:l,body:h}}}let La=Ua();const Ma=new RegExp("^data:([^;:]*)?(;base64)?,(.*)$","i"),Fa=new RegExp("^ipfs://(ipfs/)?(.*)$","i");let Ga=!1;async function ja(t,e){try{const e=t.match(Ma);if(!e)throw new Error("invalid data");return new Ja(200,"OK",{"content-type":e[1]||"text/plain"},e[2]?function(t){t=atob(t);const e=new Uint8Array(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return ta(e)}(e[3]):Da(e[3].replace(/%([0-9a-f][0-9a-f])/gi,((t,e)=>String.fromCharCode(parseInt(e,16))))))}catch(n){return new Ja(599,"BAD REQUEST (invalid data: URI)",{},null,new $a(t))}}function Ha(t){return async function(e,n){try{const n=e.match(Fa);if(!n)throw new Error("invalid link");return new $a(`${t}${n[2]}`)}catch(r){return new Ja(599,"BAD REQUEST (invalid IPFS URI)",{},null,new $a(e))}}}const Va={data:ja,ipfs:Ha("https://gateway.ipfs.io/ipfs/")},Wa=new WeakMap;class Ka{constructor(t){Dn(this,e,void 0),Dn(this,n,void 0),Bn(this,e,[]),Bn(this,n,!1),Wa.set(t,(()=>{if(!Pn(this,n)){Bn(this,n,!0);for(const t of Pn(this,e))setTimeout((()=>{t()}),0);Bn(this,e,[])}}))}addListener(t){qo(!Pn(this,n),"singal already cancelled","UNSUPPORTED_OPERATION",{operation:"fetchCancelSignal.addCancelListener"}),Pn(this,e).push(t)}get cancelled(){return Pn(this,n)}checkSignal(){qo(!this.cancelled,"cancelled","CANCELLED",{})}}function za(t){if(null==t)throw new Error("missing signal; should not happen");return t.checkSignal(),t}e=new WeakMap,n=new WeakMap;const qa=class t{constructor(t){Dn(this,w),Dn(this,r,void 0),Dn(this,s,void 0),Dn(this,i,void 0),Dn(this,o,void 0),Dn(this,a,void 0),Dn(this,c,void 0),Dn(this,l,void 0),Dn(this,u,void 0),Dn(this,h,void 0),Dn(this,d,void 0),Dn(this,f,void 0),Dn(this,p,void 0),Dn(this,g,void 0),Dn(this,m,void 0),Dn(this,y,void 0),Bn(this,c,String(t)),Bn(this,r,!1),Bn(this,s,!0),Bn(this,i,{}),Bn(this,o,""),Bn(this,a,3e5),Bn(this,m,{slotInterval:250,maxAttempts:12}),Bn(this,y,null)}get url(){return Pn(this,c)}set url(t){Bn(this,c,String(t))}get body(){return null==Pn(this,l)?null:new Uint8Array(Pn(this,l))}set body(t){if(null==t)Bn(this,l,void 0),Bn(this,u,void 0);else if("string"==typeof t)Bn(this,l,Da(t)),Bn(this,u,"text/plain");else if(t instanceof Uint8Array)Bn(this,l,t),Bn(this,u,"application/octet-stream");else{if("object"!=typeof t)throw new Error("invalid body");Bn(this,l,Da(JSON.stringify(t))),Bn(this,u,"application/json")}}hasBody(){return null!=Pn(this,l)}get method(){return Pn(this,o)?Pn(this,o):this.hasBody()?"POST":"GET"}set method(t){null==t&&(t=""),Bn(this,o,String(t).toUpperCase())}get headers(){const t=Object.assign({},Pn(this,i));return Pn(this,h)&&(t.authorization=`Basic ${function(t){const e=ta(t);let n="";for(let r=0;r<e.length;r++)n+=String.fromCharCode(e[r]);return btoa(n)}(Da(Pn(this,h)))}`),this.allowGzip&&(t["accept-encoding"]="gzip"),null==t["content-type"]&&Pn(this,u)&&(t["content-type"]=Pn(this,u)),this.body&&(t["content-length"]=String(this.body.length)),t}getHeader(t){return this.headers[t.toLowerCase()]}setHeader(t,e){Pn(this,i)[String(t).toLowerCase()]=String(e)}clearHeaders(){Bn(this,i,{})}[Symbol.iterator](){const t=this.headers,e=Object.keys(t);let n=0;return{next:()=>{if(n<e.length){const r=e[n++];return{value:[r,t[r]],done:!1}}return{value:void 0,done:!0}}}}get credentials(){return Pn(this,h)||null}setCredentials(t,e){$o(!t.match(/:/),"invalid basic authentication username","username","[REDACTED]"),Bn(this,h,`${t}:${e}`)}get allowGzip(){return Pn(this,s)}set allowGzip(t){Bn(this,s,!!t)}get allowInsecureAuthentication(){return!!Pn(this,r)}set allowInsecureAuthentication(t){Bn(this,r,!!t)}get timeout(){return Pn(this,a)}set timeout(t){$o(t>=0,"timeout must be non-zero","timeout",t),Bn(this,a,t)}get preflightFunc(){return Pn(this,d)||null}set preflightFunc(t){Bn(this,d,t)}get processFunc(){return Pn(this,f)||null}set processFunc(t){Bn(this,f,t)}get retryFunc(){return Pn(this,p)||null}set retryFunc(t){Bn(this,p,t)}get getUrlFunc(){return Pn(this,y)||La}set getUrlFunc(t){Bn(this,y,t)}toString(){return`<FetchRequest method=${JSON.stringify(this.method)} url=${JSON.stringify(this.url)} headers=${JSON.stringify(this.headers)} body=${Pn(this,l)?ia(Pn(this,l)):"null"}>`}setThrottleParams(t){null!=t.slotInterval&&(Pn(this,m).slotInterval=t.slotInterval),null!=t.maxAttempts&&(Pn(this,m).maxAttempts=t.maxAttempts)}send(){return qo(null==Pn(this,g),"request already sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.send"}),Bn(this,g,new Ka(this)),Ln(this,w,b).call(this,0,Ya()+this.timeout,0,this,new Ja(0,"",{},null,this))}cancel(){qo(null!=Pn(this,g),"request has not been sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.cancel"});const t=Wa.get(this);if(!t)throw new Error("missing signal; should not happen");t()}redirect(e){const n=this.url.split(":")[0].toLowerCase(),r=e.split(":")[0].toLowerCase();qo(("https"!==n||"http"!==r)&&e.match(/^https?:/),"unsupported redirect","UNSUPPORTED_OPERATION",{operation:`redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(e)})`});const s=new t(e);return s.method=this.method,s.allowGzip=this.allowGzip,s.timeout=this.timeout,Bn(s,i,Object.assign({},Pn(this,i))),Pn(this,l)&&Bn(s,l,new Uint8Array(Pn(this,l))),Bn(s,u,Pn(this,u)),s}clone(){const e=new t(this.url);return Bn(e,o,Pn(this,o)),Pn(this,l)&&Bn(e,l,Pn(this,l)),Bn(e,u,Pn(this,u)),Bn(e,i,Object.assign({},Pn(this,i))),Bn(e,h,Pn(this,h)),this.allowGzip&&(e.allowGzip=!0),e.timeout=this.timeout,this.allowInsecureAuthentication&&(e.allowInsecureAuthentication=!0),Bn(e,d,Pn(this,d)),Bn(e,f,Pn(this,f)),Bn(e,p,Pn(this,p)),Bn(e,m,Object.assign({},Pn(this,m))),Bn(e,y,Pn(this,y)),e}static lockConfig(){Ga=!0}static getGateway(t){return Va[t.toLowerCase()]||null}static registerGateway(t,e){if("http"===(t=t.toLowerCase())||"https"===t)throw new Error(`cannot intercept ${t}; use registerGetUrl`);if(Ga)throw new Error("gateways locked");Va[t]=e}static registerGetUrl(t){if(Ga)throw new Error("gateways locked");La=t}static createGetUrlFunc(t){return Ua(t)}static createDataGateway(){return ja}static createIpfsGatewayFunc(t){return Ha(t)}};r=new WeakMap,s=new WeakMap,i=new WeakMap,o=new WeakMap,a=new WeakMap,c=new WeakMap,l=new WeakMap,u=new WeakMap,h=new WeakMap,d=new WeakMap,f=new WeakMap,p=new WeakMap,g=new WeakMap,m=new WeakMap,y=new WeakMap,w=new WeakSet,b=async function(t,e,n,r,s){var i,o,a;if(t>=Pn(this,m).maxAttempts)return s.makeServerError("exceeded maximum retry limit");qo(Ya()<=e,"timeout","TIMEOUT",{operation:"request.send",reason:"timeout",request:r}),n>0&&await function(t){return new Promise((e=>setTimeout(e,t)))}(n);let c=this.clone();const l=(c.url.split(":")[0]||"").toLowerCase();if(l in Va){const t=await Va[l](c.url,za(Pn(r,g)));if(t instanceof Ja){let e=t;if(this.processFunc){za(Pn(r,g));try{e=await this.processFunc(c,e)}catch(d){null!=d.throttle&&"number"==typeof d.stall||e.makeServerError("error in post-processing function",d).assertOk()}}return e}c=t}this.preflightFunc&&(c=await this.preflightFunc(c));const u=await this.getUrlFunc(c,za(Pn(r,g)));let h=new Ja(u.statusCode,u.statusMessage,u.headers,u.body,r);if([301,302,307,308].indexOf(h.statusCode)>=0){try{const n=h.headers.location||"";return Ln(i=c.redirect(n),w,b).call(i,t+1,e,0,r,h)}catch(d){}return h}if(429===h.statusCode&&(null==this.retryFunc||await this.retryFunc(c,h,t))){const n=h.headers["retry-after"];let s=Pn(this,m).slotInterval*Math.trunc(Math.random()*Math.pow(2,t));return"string"==typeof n&&n.match(/^[1-9][0-9]*$/)&&(s=parseInt(n)),Ln(o=c.clone(),w,b).call(o,t+1,e,s,r,h)}if(this.processFunc){za(Pn(r,g));try{h=await this.processFunc(c,h)}catch(d){null!=d.throttle&&"number"==typeof d.stall||h.makeServerError("error in post-processing function",d).assertOk();let n=Pn(this,m).slotInterval*Math.trunc(Math.random()*Math.pow(2,t));return d.stall>=0&&(n=d.stall),Ln(a=c.clone(),w,b).call(a,t+1,e,n,r,h)}}return h};let $a=qa;const Qa=class t{constructor(t,e,n,r,s){Dn(this,A,void 0),Dn(this,_,void 0),Dn(this,v,void 0),Dn(this,E,void 0),Dn(this,k,void 0),Dn(this,S,void 0),Bn(this,A,t),Bn(this,_,e),Bn(this,v,Object.keys(n).reduce(((t,e)=>(t[e.toLowerCase()]=String(n[e]),t)),{})),Bn(this,E,null==r?null:new Uint8Array(r)),Bn(this,k,s||null),Bn(this,S,{message:""})}toString(){return`<FetchResponse status=${this.statusCode} body=${Pn(this,E)?ia(Pn(this,E)):"null"}>`}get statusCode(){return Pn(this,A)}get statusMessage(){return Pn(this,_)}get headers(){return Object.assign({},Pn(this,v))}get body(){return null==Pn(this,E)?null:new Uint8Array(Pn(this,E))}get bodyText(){try{return null==Pn(this,E)?"":Ba(Pn(this,E))}catch(t){qo(!1,"response body is not valid UTF-8 data","UNSUPPORTED_OPERATION",{operation:"bodyText",info:{response:this}})}}get bodyJson(){try{return JSON.parse(this.bodyText)}catch(t){qo(!1,"response body is not valid JSON","UNSUPPORTED_OPERATION",{operation:"bodyJson",info:{response:this}})}}[Symbol.iterator](){const t=this.headers,e=Object.keys(t);let n=0;return{next:()=>{if(n<e.length){const r=e[n++];return{value:[r,t[r]],done:!1}}return{value:void 0,done:!0}}}}makeServerError(e,n){let r;r=e?`CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${e})`:`CLIENT ESCALATED SERVER ERROR (${e=`${this.statusCode} ${this.statusMessage}`})`;const s=new t(599,r,this.headers,this.body,Pn(this,k)||void 0);return Bn(s,S,{message:e,error:n}),s}throwThrottleError(t,e){null==e?e=-1:$o(Number.isInteger(e)&&e>=0,"invalid stall timeout","stall",e);const n=new Error(t||"throttling requests");throw Ho(n,{stall:e,throttle:!0}),n}getHeader(t){return this.headers[t.toLowerCase()]}hasBody(){return null!=Pn(this,E)}get request(){return Pn(this,k)}ok(){return""===Pn(this,S).message&&this.statusCode>=200&&this.statusCode<300}assertOk(){if(this.ok())return;let{message:t,error:e}=Pn(this,S);""===t&&(t=`server response ${this.statusCode} ${this.statusMessage}`);let n=null;this.request&&(n=this.request.url);let r=null;try{Pn(this,E)&&(r=Ba(Pn(this,E)))}catch(s){}qo(!1,t,"SERVER_ERROR",{request:this.request||"unknown request",response:this,error:e,info:{requestUrl:n,responseBody:r,responseStatus:`${this.statusCode} ${this.statusMessage}`}})}};A=new WeakMap,_=new WeakMap,v=new WeakMap,E=new WeakMap,k=new WeakMap,S=new WeakMap;let Ja=Qa;function Ya(){return(new Date).getTime()}function Za(t){let e=t.toString(16);for(;e.length<2;)e="0"+e;return"0x"+e}function Xa(t,e,n){let r=0;for(let s=0;s<n;s++)r=256*r+t[e+s];return r}function tc(t,e,n,r){const s=[];for(;n<e+1+r;){const i=ec(t,n);s.push(i.result),qo((n+=i.consumed)<=e+1+r,"child data too short","BUFFER_OVERRUN",{buffer:t,length:r,offset:e})}return{consumed:1+r,result:s}}function ec(t,e){qo(0!==t.length,"data too short","BUFFER_OVERRUN",{buffer:t,length:0,offset:1});const n=e=>{qo(e<=t.length,"data short segment too short","BUFFER_OVERRUN",{buffer:t,length:t.length,offset:e})};if(t[e]>=248){const r=t[e]-247;n(e+1+r);const s=Xa(t,e+1,r);return n(e+1+r+s),tc(t,e,e+1+r,r+s)}if(t[e]>=192){const r=t[e]-192;return n(e+1+r),tc(t,e,e+1,r)}if(t[e]>=184){const r=t[e]-183;n(e+1+r);const s=Xa(t,e+1,r);n(e+1+r+s);return{consumed:1+r+s,result:ia(t.slice(e+1+r,e+1+r+s))}}if(t[e]>=128){const r=t[e]-128;n(e+1+r);return{consumed:1+r,result:ia(t.slice(e+1,e+1+r))}}return{consumed:1,result:Za(t[e])}}function nc(t){const e=ta(t,"data"),n=ec(e,0);return $o(n.consumed===e.length,"unexpected junk after rlp payload","data",t),n.result}function rc(t){const e=[];for(;t;)e.unshift(255&t),t>>=8;return e}function sc(t){if(Array.isArray(t)){let e=[];if(t.forEach((function(t){e=e.concat(sc(t))})),e.length<=55)return e.unshift(192+e.length),e;const n=rc(e.length);return n.unshift(247+n.length),n.concat(e)}const e=Array.prototype.slice.call(ta(t,"object"));if(1===e.length&&e[0]<=127)return e;if(e.length<=55)return e.unshift(128+e.length),e;const n=rc(e.length);return n.unshift(183+n.length),n.concat(e)}const ic="0123456789abcdef";function oc(t){let e="0x";for(const n of sc(t))e+=ic[n>>4],e+=ic[15&n];return e}function ac(t){const e=ta(t,"randomBytes");e[6]=15&e[6]|64,e[8]=63&e[8]|128;const n=ia(e);return[n.substring(2,10),n.substring(10,14),n.substring(14,18),n.substring(18,22),n.substring(22,34)].join("-")}const cc=32,lc=new Uint8Array(cc),uc=["then"],hc={},dc=new WeakMap;function fc(t){return dc.get(t)}function pc(t,e){dc.set(t,e)}function gc(t,e){const n=new Error(`deferred error during ABI decoding triggered accessing ${t}`);throw n.error=e,n}function mc(t,e,n){return t.indexOf(null)>=0?e.map(((t,e)=>t instanceof yc?mc(fc(t),t,n):t)):t.reduce(((t,r,s)=>{let i=e.getValue(r);return r in t||(n&&i instanceof yc&&(i=mc(fc(i),i,n)),t[r]=i),t}),{})}T=new WeakMap;let yc=class t extends Array{constructor(...t){const e=t[0];let n=t[1],r=(t[2]||[]).slice(),s=!0;e!==hc&&(n=t,r=[],s=!1),super(n.length),Dn(this,T,void 0),n.forEach(((t,e)=>{this[e]=t}));const i=r.reduce(((t,e)=>("string"==typeof e&&t.set(e,(t.get(e)||0)+1),t)),new Map);if(pc(this,Object.freeze(n.map(((t,e)=>{const n=r[e];return null!=n&&1===i.get(n)?n:null})))),Bn(this,T,[]),null==Pn(this,T)&&Pn(this,T),!s)return;Object.freeze(this);const o=new Proxy(this,{get:(t,e,n)=>{if("string"==typeof e){if(e.match(/^[0-9]+$/)){const n=_a(e,"%index");if(n<0||n>=this.length)throw new RangeError("out of result range");const r=t[n];return r instanceof Error&&gc(`index ${n}`,r),r}if(uc.indexOf(e)>=0)return Reflect.get(t,e,n);const r=t[e];if(r instanceof Function)return function(...e){return r.apply(this===n?t:this,e)};if(!(e in t))return t.getValue.apply(this===n?t:this,[e])}return Reflect.get(t,e,n)}});return pc(o,fc(this)),o}toArray(e){const n=[];return this.forEach(((r,s)=>{r instanceof Error&&gc(`index ${s}`,r),e&&r instanceof t&&(r=r.toArray(e)),n.push(r)})),n}toObject(t){const e=fc(this);return e.reduce(((n,r,s)=>(qo(null!=r,`value at index ${s} unnamed`,"UNSUPPORTED_OPERATION",{operation:"toObject()"}),mc(e,this,t))),{})}slice(e,n){null==e&&(e=0),e<0&&(e+=this.length)<0&&(e=0),null==n&&(n=this.length),n<0&&(n+=this.length)<0&&(n=0),n>this.length&&(n=this.length);const r=fc(this),s=[],i=[];for(let t=e;t<n;t++)s.push(this[t]),i.push(r[t]);return new t(hc,s,i)}filter(e,n){const r=fc(this),s=[],i=[];for(let t=0;t<this.length;t++){const o=this[t];o instanceof Error&&gc(`index ${t}`,o),e.call(n,o,t,this)&&(s.push(o),i.push(r[t]))}return new t(hc,s,i)}map(t,e){const n=[];for(let r=0;r<this.length;r++){const s=this[r];s instanceof Error&&gc(`index ${r}`,s),n.push(t.call(e,s,r,this))}return n}getValue(t){const e=fc(this).indexOf(t);if(-1===e)return;const n=this[e];return n instanceof Error&&gc(`property ${JSON.stringify(t)}`,n.error),n}static fromItems(e,n){return new t(hc,e,n)}};function wc(t){let e=Ea(t);return qo(e.length<=cc,"value out-of-bounds","BUFFER_OVERRUN",{buffer:e,length:cc,offset:e.length}),e.length!==cc&&(e=ea(oa([lc.slice(e.length%cc),e]))),e}class bc{constructor(t,e,n,r){xn(this,"name"),xn(this,"type"),xn(this,"localName"),xn(this,"dynamic"),Ho(this,{name:t,type:e,localName:n,dynamic:r},{name:"string",type:"string",localName:"string",dynamic:"boolean"})}_throwError(t,e){$o(!1,t,this.localName,e)}}class Ac{constructor(){Dn(this,O),Dn(this,R,void 0),Dn(this,I,void 0),Bn(this,R,[]),Bn(this,I,0)}get data(){return oa(Pn(this,R))}get length(){return Pn(this,I)}appendWriter(t){return Ln(this,O,C).call(this,ea(t.data))}writeBytes(t){let e=ea(t);const n=e.length%cc;return n&&(e=ea(oa([e,lc.slice(n)]))),Ln(this,O,C).call(this,e)}writeValue(t){return Ln(this,O,C).call(this,wc(t))}writeUpdatableValue(){const t=Pn(this,R).length;return Pn(this,R).push(lc),Bn(this,I,Pn(this,I)+cc),e=>{Pn(this,R)[t]=wc(e)}}}R=new WeakMap,I=new WeakMap,O=new WeakSet,C=function(t){return Pn(this,R).push(t),Bn(this,I,Pn(this,I)+t.length),t.length};x=new WeakMap,N=new WeakMap,P=new WeakMap,D=new WeakMap,B=new WeakMap,U=new WeakSet,L=function(t){var e;if(Pn(this,D))return Ln(e=Pn(this,D),U,L).call(e,t);Bn(this,P,Pn(this,P)+t),qo(Pn(this,B)<1||Pn(this,P)<=Pn(this,B)*this.dataLength,`compressed ABI data exceeds inflation ratio of ${Pn(this,B)} ( see: https://github.com/ethers-io/ethers.js/issues/4537 )`,"BUFFER_OVERRUN",{buffer:ea(Pn(this,x)),offset:Pn(this,N),length:t,info:{bytesRead:Pn(this,P),dataLength:this.dataLength}})},M=new WeakSet,F=function(t,e,n){let r=Math.ceil(e/cc)*cc;return Pn(this,N)+r>Pn(this,x).length&&(this.allowLoose&&n&&Pn(this,N)+e<=Pn(this,x).length?r=e:qo(!1,"data out-of-bounds","BUFFER_OVERRUN",{buffer:ea(Pn(this,x)),length:Pn(this,x).length,offset:Pn(this,N)+r})),Pn(this,x).slice(Pn(this,N),Pn(this,N)+r)};let _c=class t{constructor(t,e,n){Dn(this,U),Dn(this,M),xn(this,"allowLoose"),Dn(this,x,void 0),Dn(this,N,void 0),Dn(this,P,void 0),Dn(this,D,void 0),Dn(this,B,void 0),Ho(this,{allowLoose:!!e}),Bn(this,x,ea(t)),Bn(this,P,0),Bn(this,D,null),Bn(this,B,null!=n?n:1024),Bn(this,N,0)}get data(){return ia(Pn(this,x))}get dataLength(){return Pn(this,x).length}get consumed(){return Pn(this,N)}get bytes(){return new Uint8Array(Pn(this,x))}subReader(e){const n=new t(Pn(this,x).slice(Pn(this,N)+e),this.allowLoose,Pn(this,B));return Bn(n,D,this),n}readBytes(t,e){let n=Ln(this,M,F).call(this,0,t,!!e);return Ln(this,U,L).call(this,t),Bn(this,N,Pn(this,N)+n.length),n.slice(0,t)}readValue(){return Aa(this.readBytes(cc))}readIndex(){return _a(Aa(this.readBytes(cc)))}};function vc(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function Ec(t,...e){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}function kc(t){if("function"!=typeof t||"function"!=typeof t.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");vc(t.outputLen),vc(t.blockLen)}function Sc(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Tc(t,e){Ec(t);const n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}const Rc="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,Ic=t=>t instanceof Uint8Array,Oc=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4)),Cc=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),xc=(t,e)=>t<<32-e|t>>>e;
2
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */if(!(68===new Uint8Array(new Uint32Array([287454020]).buffer)[0]))throw new Error("Non little-endian hardware is not supported");const Nc=async()=>{};async function Pc(t,e,n){let r=Date.now();for(let s=0;s<t;s++){n(s);const t=Date.now()-r;t>=0&&t<e||(await Nc(),r+=t)}}function Dc(t){if("string"==typeof t&&(t=function(t){if("string"!=typeof t)throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array((new TextEncoder).encode(t))}(t)),!Ic(t))throw new Error("expected Uint8Array, got "+typeof t);return t}class Bc{clone(){return this._cloneInto()}}const Uc={}.toString;function Lc(t,e){if(void 0!==e&&"[object Object]"!==Uc.call(e))throw new Error("Options should be object or undefined");return Object.assign(t,e)}function Mc(t){const e=e=>t().update(Dc(e)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Fc(t=32){if(Rc&&"function"==typeof Rc.getRandomValues)return Rc.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}class Gc extends Bc{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,kc(t);const n=Dc(e);if(this.iHash=t.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,s=new Uint8Array(r);s.set(n.length>r?t.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=t.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(t){return Sc(this),this.iHash.update(t),this}digestInto(t){Sc(this),Ec(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:e,iHash:n,finished:r,destroyed:s,blockLen:i,outputLen:o}=this;return t.finished=r,t.destroyed=s,t.blockLen=i,t.outputLen=o,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const jc=(t,e,n)=>new Gc(t,e).update(n).digest();function Hc(t,e,n,r){const{c:s,dkLen:i,DK:o,PRF:a,PRFSalt:c}=function(t,e,n,r){kc(t);const s=Lc({dkLen:32,asyncTick:10},r),{c:i,dkLen:o,asyncTick:a}=s;if(vc(i),vc(o),vc(a),i<1)throw new Error("PBKDF2: iterations (c) should be >= 1");const c=Dc(e),l=Dc(n),u=new Uint8Array(o),h=jc.create(t,c),d=h._cloneInto().update(l);return{c:i,dkLen:o,asyncTick:a,DK:u,PRF:h,PRFSalt:d}}(t,e,n,r);let l;const u=new Uint8Array(4),h=Cc(u),d=new Uint8Array(a.outputLen);for(let f=1,p=0;p<i;f++,p+=a.outputLen){const t=o.subarray(p,p+a.outputLen);h.setInt32(0,f,!1),(l=c._cloneInto(l)).update(u).digestInto(d),t.set(d.subarray(0,t.length));for(let e=1;e<s;e++){a._cloneInto(l).update(d).digestInto(d);for(let e=0;e<t.length;e++)t[e]^=d[e]}}return function(t,e,n,r,s){return t.destroy(),e.destroy(),r&&r.destroy(),s.fill(0),n}(a,c,o,l,d)}jc.create=(t,e)=>new Gc(t,e);class Vc extends Bc{constructor(t,e,n,r){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=Cc(this.buffer)}update(t){Sc(this);const{view:e,buffer:n,blockLen:r}=this,s=(t=Dc(t)).length;for(let i=0;i<s;){const o=Math.min(r-this.pos,s-i);if(o!==r)n.set(t.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===r&&(this.process(e,0),this.pos=0);else{const e=Cc(t);for(;r<=s-i;i+=r)this.process(e,i)}}return this.length+=t.length,this.roundClean(),this}digestInto(t){Sc(this),Tc(t,this),this.finished=!0;const{buffer:e,view:n,blockLen:r,isLE:s}=this;let{pos:i}=this;e[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>r-i&&(this.process(n,0),i=0);for(let u=i;u<r;u++)e[u]=0;!function(t,e,n,r){if("function"==typeof t.setBigUint64)return t.setBigUint64(e,n,r);const s=BigInt(32),i=BigInt(4294967295),o=Number(n>>s&i),a=Number(n&i),c=r?4:0,l=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+l,a,r)}(n,r-8,BigInt(8*this.length),s),this.process(n,0);const o=Cc(t),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<c;u++)o.setUint32(4*u,l[u],s)}digest(){const{buffer:t,outputLen:e}=this;this.digestInto(t);const n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:e,buffer:n,length:r,finished:s,destroyed:i,pos:o}=this;return t.length=r,t.pos=o,t.finished=s,t.destroyed=i,r%e&&t.buffer.set(n),t}}const Wc=(t,e,n)=>t&e^t&n^e&n,Kc=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),zc=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),qc=new Uint32Array(64);class $c extends Vc{constructor(){super(64,32,8,!1),this.A=0|zc[0],this.B=0|zc[1],this.C=0|zc[2],this.D=0|zc[3],this.E=0|zc[4],this.F=0|zc[5],this.G=0|zc[6],this.H=0|zc[7]}get(){const{A:t,B:e,C:n,D:r,E:s,F:i,G:o,H:a}=this;return[t,e,n,r,s,i,o,a]}set(t,e,n,r,s,i,o,a){this.A=0|t,this.B=0|e,this.C=0|n,this.D=0|r,this.E=0|s,this.F=0|i,this.G=0|o,this.H=0|a}process(t,e){for(let h=0;h<16;h++,e+=4)qc[h]=t.getUint32(e,!1);for(let h=16;h<64;h++){const t=qc[h-15],e=qc[h-2],n=xc(t,7)^xc(t,18)^t>>>3,r=xc(e,17)^xc(e,19)^e>>>10;qc[h]=r+qc[h-7]+n+qc[h-16]|0}let{A:n,B:r,C:s,D:i,E:o,F:a,G:c,H:l}=this;for(let h=0;h<64;h++){const t=l+(xc(o,6)^xc(o,11)^xc(o,25))+((u=o)&a^~u&c)+Kc[h]+qc[h]|0,e=(xc(n,2)^xc(n,13)^xc(n,22))+Wc(n,r,s)|0;l=c,c=a,a=o,o=i+t|0,i=s,s=r,r=n,n=t+e|0}var u;n=n+this.A|0,r=r+this.B|0,s=s+this.C|0,i=i+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,s,i,o,a,c,l)}roundClean(){qc.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const Qc=Mc((()=>new $c)),Jc=BigInt(2**32-1),Yc=BigInt(32);function Zc(t,e=!1){return e?{h:Number(t&Jc),l:Number(t>>Yc&Jc)}:{h:0|Number(t>>Yc&Jc),l:0|Number(t&Jc)}}function Xc(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){const{h:i,l:o}=Zc(t[s],e);[n[s],r[s]]=[i,o]}return[n,r]}const tl=(t,e,n)=>t<<n|e>>>32-n,el=(t,e,n)=>e<<n|t>>>32-n,nl=(t,e,n)=>e<<n-32|t>>>64-n,rl=(t,e,n)=>t<<n-32|e>>>64-n;const sl={fromBig:Zc,split:Xc,toBig:(t,e)=>BigInt(t>>>0)<<Yc|BigInt(e>>>0),shrSH:(t,e,n)=>t>>>n,shrSL:(t,e,n)=>t<<32-n|e>>>n,rotrSH:(t,e,n)=>t>>>n|e<<32-n,rotrSL:(t,e,n)=>t<<32-n|e>>>n,rotrBH:(t,e,n)=>t<<64-n|e>>>n-32,rotrBL:(t,e,n)=>t>>>n-32|e<<64-n,rotr32H:(t,e)=>e,rotr32L:(t,e)=>t,rotlSH:tl,rotlSL:el,rotlBH:nl,rotlBL:rl,add:function(t,e,n,r){const s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:0|s}},add3L:(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),add3H:(t,e,n,r)=>e+n+r+(t/2**32|0)|0,add4L:(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),add4H:(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0,add5H:(t,e,n,r,s,i)=>e+n+r+s+i+(t/2**32|0)|0,add5L:(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0)},[il,ol]=(()=>sl.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((t=>BigInt(t)))))(),al=new Uint32Array(80),cl=new Uint32Array(80);class ll extends Vc{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:t,Al:e,Bh:n,Bl:r,Ch:s,Cl:i,Dh:o,Dl:a,Eh:c,El:l,Fh:u,Fl:h,Gh:d,Gl:f,Hh:p,Hl:g}=this;return[t,e,n,r,s,i,o,a,c,l,u,h,d,f,p,g]}set(t,e,n,r,s,i,o,a,c,l,u,h,d,f,p,g){this.Ah=0|t,this.Al=0|e,this.Bh=0|n,this.Bl=0|r,this.Ch=0|s,this.Cl=0|i,this.Dh=0|o,this.Dl=0|a,this.Eh=0|c,this.El=0|l,this.Fh=0|u,this.Fl=0|h,this.Gh=0|d,this.Gl=0|f,this.Hh=0|p,this.Hl=0|g}process(t,e){for(let w=0;w<16;w++,e+=4)al[w]=t.getUint32(e),cl[w]=t.getUint32(e+=4);for(let w=16;w<80;w++){const t=0|al[w-15],e=0|cl[w-15],n=sl.rotrSH(t,e,1)^sl.rotrSH(t,e,8)^sl.shrSH(t,e,7),r=sl.rotrSL(t,e,1)^sl.rotrSL(t,e,8)^sl.shrSL(t,e,7),s=0|al[w-2],i=0|cl[w-2],o=sl.rotrSH(s,i,19)^sl.rotrBH(s,i,61)^sl.shrSH(s,i,6),a=sl.rotrSL(s,i,19)^sl.rotrBL(s,i,61)^sl.shrSL(s,i,6),c=sl.add4L(r,a,cl[w-7],cl[w-16]),l=sl.add4H(c,n,o,al[w-7],al[w-16]);al[w]=0|l,cl[w]=0|c}let{Ah:n,Al:r,Bh:s,Bl:i,Ch:o,Cl:a,Dh:c,Dl:l,Eh:u,El:h,Fh:d,Fl:f,Gh:p,Gl:g,Hh:m,Hl:y}=this;for(let w=0;w<80;w++){const t=sl.rotrSH(u,h,14)^sl.rotrSH(u,h,18)^sl.rotrBH(u,h,41),e=sl.rotrSL(u,h,14)^sl.rotrSL(u,h,18)^sl.rotrBL(u,h,41),b=u&d^~u&p,A=h&f^~h&g,_=sl.add5L(y,e,A,ol[w],cl[w]),v=sl.add5H(_,m,t,b,il[w],al[w]),E=0|_,k=sl.rotrSH(n,r,28)^sl.rotrBH(n,r,34)^sl.rotrBH(n,r,39),S=sl.rotrSL(n,r,28)^sl.rotrBL(n,r,34)^sl.rotrBL(n,r,39),T=n&s^n&o^s&o,R=r&i^r&a^i&a;m=0|p,y=0|g,p=0|d,g=0|f,d=0|u,f=0|h,({h:u,l:h}=sl.add(0|c,0|l,0|v,0|E)),c=0|o,l=0|a,o=0|s,a=0|i,s=0|n,i=0|r;const I=sl.add3L(E,S,R);n=sl.add3H(I,v,k,T),r=0|I}({h:n,l:r}=sl.add(0|this.Ah,0|this.Al,0|n,0|r)),({h:s,l:i}=sl.add(0|this.Bh,0|this.Bl,0|s,0|i)),({h:o,l:a}=sl.add(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l:l}=sl.add(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:h}=sl.add(0|this.Eh,0|this.El,0|u,0|h)),({h:d,l:f}=sl.add(0|this.Fh,0|this.Fl,0|d,0|f)),({h:p,l:g}=sl.add(0|this.Gh,0|this.Gl,0|p,0|g)),({h:m,l:y}=sl.add(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(n,r,s,i,o,a,c,l,u,h,d,f,p,g,m,y)}roundClean(){al.fill(0),cl.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const ul=Mc((()=>new ll));const hl=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("unable to locate global object")}(),dl=hl.crypto||hl.msCrypto;let fl=!1;const pl=function(t,e,n){return function(t,e){const n={sha256:Qc,sha512:ul}[t];return $o(null!=n,"invalid hmac algorithm","algorithm",t),jc.create(n,e)}(t,e).update(n).digest()};let gl=pl;function ml(t,e,n){const r=ta(e,"key"),s=ta(n,"data");return ia(gl(t,r,s))}ml._=pl,ml.lock=function(){fl=!0},ml.register=function(t){if(fl)throw new Error("computeHmac is locked");gl=t},Object.freeze(ml);const[yl,wl,bl]=[[],[],[]],Al=BigInt(0),_l=BigInt(1),vl=BigInt(2),El=BigInt(7),kl=BigInt(256),Sl=BigInt(113);for(let J_=0,Y_=_l,Z_=1,X_=0;J_<24;J_++){[Z_,X_]=[X_,(2*Z_+3*X_)%5],yl.push(2*(5*X_+Z_)),wl.push((J_+1)*(J_+2)/2%64);let t=Al;for(let e=0;e<7;e++)Y_=(Y_<<_l^(Y_>>El)*Sl)%kl,Y_&vl&&(t^=_l<<(_l<<BigInt(e))-_l);bl.push(t)}const[Tl,Rl]=Xc(bl,!0),Il=(t,e,n)=>n>32?nl(t,e,n):tl(t,e,n),Ol=(t,e,n)=>n>32?rl(t,e,n):el(t,e,n);class Cl extends Bc{constructor(t,e,n,r=!1,s=24){if(super(),this.blockLen=t,this.suffix=e,this.outputLen=n,this.enableXOF=r,this.rounds=s,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,vc(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Oc(this.state)}keccak(){!function(t,e=24){const n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let r=0;r<10;r++)n[r]=t[r]^t[r+10]^t[r+20]^t[r+30]^t[r+40];for(let r=0;r<10;r+=2){const e=(r+8)%10,s=(r+2)%10,i=n[s],o=n[s+1],a=Il(i,o,1)^n[e],c=Ol(i,o,1)^n[e+1];for(let n=0;n<50;n+=10)t[r+n]^=a,t[r+n+1]^=c}let e=t[2],s=t[3];for(let n=0;n<24;n++){const r=wl[n],i=Il(e,s,r),o=Ol(e,s,r),a=yl[n];e=t[a],s=t[a+1],t[a]=i,t[a+1]=o}for(let r=0;r<50;r+=10){for(let e=0;e<10;e++)n[e]=t[r+e];for(let e=0;e<10;e++)t[r+e]^=~n[(e+2)%10]&n[(e+4)%10]}t[0]^=Tl[r],t[1]^=Rl[r]}n.fill(0)}(this.state32,this.rounds),this.posOut=0,this.pos=0}update(t){Sc(this);const{blockLen:e,state:n}=this,r=(t=Dc(t)).length;for(let s=0;s<r;){const i=Math.min(e-this.pos,r-s);for(let e=0;e<i;e++)n[this.pos++]^=t[s++];this.pos===e&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:e,pos:n,blockLen:r}=this;t[n]^=e,128&e&&n===r-1&&this.keccak(),t[r-1]^=128,this.keccak()}writeInto(t){Sc(this,!1),Ec(t),this.finish();const e=this.state,{blockLen:n}=this;for(let r=0,s=t.length;r<s;){this.posOut>=n&&this.keccak();const i=Math.min(n-this.posOut,s-r);t.set(e.subarray(this.posOut,this.posOut+i),r),this.posOut+=i,r+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return vc(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(Tc(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(t){const{blockLen:e,suffix:n,outputLen:r,rounds:s,enableXOF:i}=this;return t||(t=new Cl(e,n,r,i,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=n,t.outputLen=r,t.enableXOF=i,t.destroyed=this.destroyed,t}}const xl=((t,e,n)=>Mc((()=>new Cl(e,t,n))))(1,136,32);let Nl=!1;const Pl=function(t){return xl(t)};let Dl=Pl;function Bl(t){const e=ta(t,"data");return ia(Dl(e))}Bl._=Pl,Bl.lock=function(){Nl=!0},Bl.register=function(t){if(Nl)throw new TypeError("keccak256 is locked");Dl=t},Object.freeze(Bl);const Ul=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Ll=Uint8Array.from({length:16},((t,e)=>e));let Ml=[Ll],Fl=[Ll.map((t=>(9*t+5)%16))];for(let J_=0;J_<4;J_++)for(let t of[Ml,Fl])t.push(t[J_].map((t=>Ul[t])));const Gl=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map((t=>new Uint8Array(t))),jl=Ml.map(((t,e)=>t.map((t=>Gl[e][t])))),Hl=Fl.map(((t,e)=>t.map((t=>Gl[e][t])))),Vl=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),Wl=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]),Kl=(t,e)=>t<<e|t>>>32-e;function zl(t,e,n,r){return 0===t?e^n^r:1===t?e&n|~e&r:2===t?(e|~n)^r:3===t?e&r|n&~r:e^(n|~r)}const ql=new Uint32Array(16);class $l extends Vc{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:t,h1:e,h2:n,h3:r,h4:s}=this;return[t,e,n,r,s]}set(t,e,n,r,s){this.h0=0|t,this.h1=0|e,this.h2=0|n,this.h3=0|r,this.h4=0|s}process(t,e){for(let d=0;d<16;d++,e+=4)ql[d]=t.getUint32(e,!0);let n=0|this.h0,r=n,s=0|this.h1,i=s,o=0|this.h2,a=o,c=0|this.h3,l=c,u=0|this.h4,h=u;for(let d=0;d<5;d++){const t=4-d,e=Vl[d],f=Wl[d],p=Ml[d],g=Fl[d],m=jl[d],y=Hl[d];for(let r=0;r<16;r++){const t=Kl(n+zl(d,s,o,c)+ql[p[r]]+e,m[r])+u|0;n=u,u=c,c=0|Kl(o,10),o=s,s=t}for(let n=0;n<16;n++){const e=Kl(r+zl(t,i,a,l)+ql[g[n]]+f,y[n])+h|0;r=h,h=l,l=0|Kl(a,10),a=i,i=e}}this.set(this.h1+o+l|0,this.h2+c+h|0,this.h3+u+r|0,this.h4+n+i|0,this.h0+s+a|0)}roundClean(){ql.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}}const Ql=Mc((()=>new $l));let Jl=!1;const Yl=function(t){return Ql(t)};let Zl=Yl;function Xl(t){const e=ta(t,"data");return ia(Zl(e))}Xl._=Yl,Xl.lock=function(){Jl=!0},Xl.register=function(t){if(Jl)throw new TypeError("ripemd160 is locked");Zl=t},Object.freeze(Xl);let tu=!1;const eu=function(t,e,n,r,s){return function(t,e,n,r,s){const i={sha256:Qc,sha512:ul}[s];return $o(null!=i,"invalid pbkdf2 algorithm","algorithm",s),Hc(i,t,e,{c:n,dkLen:r})}(t,e,n,r,s)};let nu=eu;function ru(t,e,n,r,s){const i=ta(t,"password"),o=ta(e,"salt");return ia(nu(i,o,n,r,s))}ru._=eu,ru.lock=function(){tu=!0},ru.register=function(t){if(tu)throw new Error("pbkdf2 is locked");nu=t},Object.freeze(ru);let su=!1;const iu=function(t){return new Uint8Array(function(t){qo(null!=dl,"platform does not support secure random numbers","UNSUPPORTED_OPERATION",{operation:"randomBytes"}),$o(Number.isInteger(t)&&t>0&&t<=1024,"invalid length","length",t);const e=new Uint8Array(t);return dl.getRandomValues(e),e}(t))};let ou=iu;function au(t){return ou(t)}au._=iu,au.lock=function(){su=!0},au.register=function(t){if(su)throw new Error("randomBytes is locked");ou=t},Object.freeze(au);const cu=(t,e)=>t<<e|t>>>32-e;function lu(t,e,n,r,s,i){let o=t[e++]^n[r++],a=t[e++]^n[r++],c=t[e++]^n[r++],l=t[e++]^n[r++],u=t[e++]^n[r++],h=t[e++]^n[r++],d=t[e++]^n[r++],f=t[e++]^n[r++],p=t[e++]^n[r++],g=t[e++]^n[r++],m=t[e++]^n[r++],y=t[e++]^n[r++],w=t[e++]^n[r++],b=t[e++]^n[r++],A=t[e++]^n[r++],_=t[e++]^n[r++],v=o,E=a,k=c,S=l,T=u,R=h,I=d,O=f,C=p,x=g,N=m,P=y,D=w,B=b,U=A,L=_;for(let M=0;M<8;M+=2)T^=cu(v+D|0,7),C^=cu(T+v|0,9),D^=cu(C+T|0,13),v^=cu(D+C|0,18),x^=cu(R+E|0,7),B^=cu(x+R|0,9),E^=cu(B+x|0,13),R^=cu(E+B|0,18),U^=cu(N+I|0,7),k^=cu(U+N|0,9),I^=cu(k+U|0,13),N^=cu(I+k|0,18),S^=cu(L+P|0,7),O^=cu(S+L|0,9),P^=cu(O+S|0,13),L^=cu(P+O|0,18),E^=cu(v+S|0,7),k^=cu(E+v|0,9),S^=cu(k+E|0,13),v^=cu(S+k|0,18),I^=cu(R+T|0,7),O^=cu(I+R|0,9),T^=cu(O+I|0,13),R^=cu(T+O|0,18),P^=cu(N+x|0,7),C^=cu(P+N|0,9),x^=cu(C+P|0,13),N^=cu(x+C|0,18),D^=cu(L+U|0,7),B^=cu(D+L|0,9),U^=cu(B+D|0,13),L^=cu(U+B|0,18);s[i++]=o+v|0,s[i++]=a+E|0,s[i++]=c+k|0,s[i++]=l+S|0,s[i++]=u+T|0,s[i++]=h+R|0,s[i++]=d+I|0,s[i++]=f+O|0,s[i++]=p+C|0,s[i++]=g+x|0,s[i++]=m+N|0,s[i++]=y+P|0,s[i++]=w+D|0,s[i++]=b+B|0,s[i++]=A+U|0,s[i++]=_+L|0}function uu(t,e,n,r,s){let i=r+0,o=r+16*s;for(let a=0;a<16;a++)n[o+a]=t[e+16*(2*s-1)+a];for(let a=0;a<s;a++,i+=16,e+=16)lu(n,o,t,e,n,i),a>0&&(o+=16),lu(n,i,t,e+=16,n,o)}function hu(t,e,n){const r=Lc({dkLen:32,asyncTick:10,maxmem:1073742848},n),{N:s,r:i,p:o,dkLen:a,asyncTick:c,maxmem:l,onProgress:u}=r;if(vc(s),vc(i),vc(o),vc(a),vc(c),vc(l),void 0!==u&&"function"!=typeof u)throw new Error("progressCb should be function");const h=128*i,d=h/4;if(s<=1||s&s-1||s>=2**(h/8)||s>2**32)throw new Error("Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32");if(o<0||o>137438953440/h)throw new Error("Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)");if(a<0||a>137438953440)throw new Error("Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32");const f=h*(s+o);if(f>l)throw new Error(`Scrypt: parameters too large, ${f} (128 * r * (N + p)) > ${l} (maxmem)`);const p=Hc(Qc,t,e,{c:1,dkLen:h*o}),g=Oc(p),m=Oc(new Uint8Array(h*s)),y=Oc(new Uint8Array(h));let w=()=>{};if(u){const t=2*s*o,e=Math.max(Math.floor(t/1e4),1);let n=0;w=()=>{n++,!u||n%e&&n!==t||u(n/t)}}return{N:s,r:i,p:o,dkLen:a,blockSize32:d,V:m,B32:g,B:p,tmp:y,blockMixCb:w,asyncTick:c}}function du(t,e,n,r,s){const i=Hc(Qc,t,n,{c:1,dkLen:e});return n.fill(0),r.fill(0),s.fill(0),i}let fu=!1,pu=!1;const gu=async function(t,e,n,r,s,i,o){return await async function(t,e,n){const{N:r,r:s,p:i,dkLen:o,blockSize32:a,V:c,B32:l,B:u,tmp:h,blockMixCb:d,asyncTick:f}=hu(t,e,n);for(let p=0;p<i;p++){const t=a*p;for(let n=0;n<a;n++)c[n]=l[t+n];let e=0;await Pc(r-1,f,(()=>{uu(c,e,c,e+=a,s),d()})),uu(c,(r-1)*a,l,t,s),d(),await Pc(r,f,(()=>{const e=l[t+a-16]%r;for(let n=0;n<a;n++)h[n]=l[t+n]^c[e*a+n];uu(h,0,l,t,s),d()}))}return du(t,o,u,c,h)}(t,e,{N:n,r:r,p:s,dkLen:i,onProgress:o})},mu=function(t,e,n,r,s,i){return function(t,e,n){const{N:r,r:s,p:i,dkLen:o,blockSize32:a,V:c,B32:l,B:u,tmp:h,blockMixCb:d}=hu(t,e,n);for(let f=0;f<i;f++){const t=a*f;for(let e=0;e<a;e++)c[e]=l[t+e];for(let e=0,n=0;e<r-1;e++)uu(c,n,c,n+=a,s),d();uu(c,(r-1)*a,l,t,s),d();for(let e=0;e<r;e++){const e=l[t+a-16]%r;for(let n=0;n<a;n++)h[n]=l[t+n]^c[e*a+n];uu(h,0,l,t,s),d()}}return du(t,o,u,c,h)}(t,e,{N:n,r:r,p:s,dkLen:i})};let yu=gu,wu=mu;async function bu(t,e,n,r,s,i,o){const a=ta(t,"passwd"),c=ta(e,"salt");return ia(await yu(a,c,n,r,s,i,o))}function Au(t,e,n,r,s,i){const o=ta(t,"passwd"),a=ta(e,"salt");return ia(wu(o,a,n,r,s,i))}bu._=gu,bu.lock=function(){pu=!0},bu.register=function(t){if(pu)throw new Error("scrypt is locked");yu=t},Object.freeze(bu),Au._=mu,Au.lock=function(){fu=!0},Au.register=function(t){if(fu)throw new Error("scryptSync is locked");wu=t},Object.freeze(Au);const _u=function(t){return function(t){switch(t){case"sha256":return Qc.create();case"sha512":return ul.create()}$o(!1,"invalid hashing algorithm name","algorithm",t)}("sha256").update(t).digest()};let vu=_u,Eu=!1;function ku(t){const e=ta(t,"data");return ia(vu(e))}ku._=_u,ku.lock=function(){Eu=!0},ku.register=function(t){if(Eu)throw new Error("sha256 is locked");vu=t},Object.freeze(ku),Object.freeze(ku);
3
3
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
4
- const Su=BigInt(0),Tu=BigInt(1),Ru=BigInt(2),Iu=t=>t instanceof Uint8Array,Ou=Array.from({length:256},((t,e)=>e.toString(16).padStart(2,"0")));function Cu(t){if(!Iu(t))throw new Error("Uint8Array expected");let e="";for(let n=0;n<t.length;n++)e+=Ou[t[n]];return e}function Nu(t){const e=t.toString(16);return 1&e.length?`0${e}`:e}function xu(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);return BigInt(""===t?"0":`0x${t}`)}function Pu(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);const e=t.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(e/2);for(let r=0;r<n.length;r++){const e=2*r,s=t.slice(e,e+2),i=Number.parseInt(s,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[r]=i}return n}function Du(t){return xu(Cu(t))}function Bu(t){if(!Iu(t))throw new Error("Uint8Array expected");return xu(Cu(Uint8Array.from(t).reverse()))}function Uu(t,e){return Pu(t.toString(16).padStart(2*e,"0"))}function Lu(t,e){return Uu(t,e).reverse()}function Mu(t,e,n){let r;if("string"==typeof e)try{r=Pu(e)}catch(i){throw new Error(`${t} must be valid hex string, got "${e}". Cause: ${i}`)}else{if(!Iu(e))throw new Error(`${t} must be hex string or Uint8Array`);r=Uint8Array.from(e)}const s=r.length;if("number"==typeof n&&s!==n)throw new Error(`${t} expected ${n} bytes, got ${s}`);return r}function Fu(...t){const e=new Uint8Array(t.reduce(((t,e)=>t+e.length),0));let n=0;return t.forEach((t=>{if(!Iu(t))throw new Error("Uint8Array expected");e.set(t,n),n+=t.length})),e}const Gu=t=>(Ru<<BigInt(t-1))-Tu,ju=t=>new Uint8Array(t),Hu=t=>Uint8Array.from(t);function Vu(t,e,n){if("number"!=typeof t||t<2)throw new Error("hashLen must be a number");if("number"!=typeof e||e<2)throw new Error("qByteLen must be a number");if("function"!=typeof n)throw new Error("hmacFn must be a function");let r=ju(t),s=ju(t),i=0;const o=()=>{r.fill(1),s.fill(0),i=0},a=(...t)=>n(s,r,...t),c=(t=ju())=>{s=a(Hu([0]),t),r=a(),0!==t.length&&(s=a(Hu([1]),t),r=a())},l=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let t=0;const n=[];for(;t<e;){r=a();const e=r.slice();n.push(e),t+=r.length}return Fu(...n)};return(t,e)=>{let n;for(o(),c(t);!(n=e(l()));)c();return o(),n}}const Wu={bigint:t=>"bigint"==typeof t,function:t=>"function"==typeof t,boolean:t=>"boolean"==typeof t,string:t=>"string"==typeof t,stringOrUint8Array:t=>"string"==typeof t||t instanceof Uint8Array,isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>"function"==typeof t&&Number.isSafeInteger(t.outputLen)};function Ku(t,e,n={}){const r=(e,n,r)=>{const s=Wu[n];if("function"!=typeof s)throw new Error(`Invalid validator "${n}", expected function`);const i=t[e];if(!(r&&void 0===i||s(i,t)))throw new Error(`Invalid param ${String(e)}=${i} (${typeof i}), expected ${n}`)};for(const[s,i]of Object.entries(e))r(s,i,!1);for(const[s,i]of Object.entries(n))r(s,i,!0);return t}const zu=Object.freeze(Object.defineProperty({__proto__:null,bitGet:function(t,e){return t>>BigInt(e)&Tu},bitLen:function(t){let e;for(e=0;t>Su;t>>=Tu,e+=1);return e},bitMask:Gu,bitSet:(t,e,n)=>t|(n?Tu:Su)<<BigInt(e),bytesToHex:Cu,bytesToNumberBE:Du,bytesToNumberLE:Bu,concatBytes:Fu,createHmacDrbg:Vu,ensureBytes:Mu,equalBytes:function(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0},hexToBytes:Pu,hexToNumber:xu,numberToBytesBE:Uu,numberToBytesLE:Lu,numberToHexUnpadded:Nu,numberToVarBytesBE:function(t){return Pu(Nu(t))},utf8ToBytes:function(t){if("string"!=typeof t)throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array((new TextEncoder).encode(t))},validateObject:Ku},Symbol.toStringTag,{value:"Module"})),qu=BigInt(0),$u=BigInt(1),Qu=BigInt(2),Ju=BigInt(3),Yu=BigInt(4),Zu=BigInt(5),Xu=BigInt(8);
4
+ const Su=BigInt(0),Tu=BigInt(1),Ru=BigInt(2),Iu=t=>t instanceof Uint8Array,Ou=Array.from({length:256},((t,e)=>e.toString(16).padStart(2,"0")));function Cu(t){if(!Iu(t))throw new Error("Uint8Array expected");let e="";for(let n=0;n<t.length;n++)e+=Ou[t[n]];return e}function xu(t){const e=t.toString(16);return 1&e.length?`0${e}`:e}function Nu(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);return BigInt(""===t?"0":`0x${t}`)}function Pu(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);const e=t.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(e/2);for(let r=0;r<n.length;r++){const e=2*r,s=t.slice(e,e+2),i=Number.parseInt(s,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[r]=i}return n}function Du(t){return Nu(Cu(t))}function Bu(t){if(!Iu(t))throw new Error("Uint8Array expected");return Nu(Cu(Uint8Array.from(t).reverse()))}function Uu(t,e){return Pu(t.toString(16).padStart(2*e,"0"))}function Lu(t,e){return Uu(t,e).reverse()}function Mu(t,e,n){let r;if("string"==typeof e)try{r=Pu(e)}catch(i){throw new Error(`${t} must be valid hex string, got "${e}". Cause: ${i}`)}else{if(!Iu(e))throw new Error(`${t} must be hex string or Uint8Array`);r=Uint8Array.from(e)}const s=r.length;if("number"==typeof n&&s!==n)throw new Error(`${t} expected ${n} bytes, got ${s}`);return r}function Fu(...t){const e=new Uint8Array(t.reduce(((t,e)=>t+e.length),0));let n=0;return t.forEach((t=>{if(!Iu(t))throw new Error("Uint8Array expected");e.set(t,n),n+=t.length})),e}const Gu=t=>(Ru<<BigInt(t-1))-Tu,ju=t=>new Uint8Array(t),Hu=t=>Uint8Array.from(t);function Vu(t,e,n){if("number"!=typeof t||t<2)throw new Error("hashLen must be a number");if("number"!=typeof e||e<2)throw new Error("qByteLen must be a number");if("function"!=typeof n)throw new Error("hmacFn must be a function");let r=ju(t),s=ju(t),i=0;const o=()=>{r.fill(1),s.fill(0),i=0},a=(...t)=>n(s,r,...t),c=(t=ju())=>{s=a(Hu([0]),t),r=a(),0!==t.length&&(s=a(Hu([1]),t),r=a())},l=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let t=0;const n=[];for(;t<e;){r=a();const e=r.slice();n.push(e),t+=r.length}return Fu(...n)};return(t,e)=>{let n;for(o(),c(t);!(n=e(l()));)c();return o(),n}}const Wu={bigint:t=>"bigint"==typeof t,function:t=>"function"==typeof t,boolean:t=>"boolean"==typeof t,string:t=>"string"==typeof t,stringOrUint8Array:t=>"string"==typeof t||t instanceof Uint8Array,isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>"function"==typeof t&&Number.isSafeInteger(t.outputLen)};function Ku(t,e,n={}){const r=(e,n,r)=>{const s=Wu[n];if("function"!=typeof s)throw new Error(`Invalid validator "${n}", expected function`);const i=t[e];if(!(r&&void 0===i||s(i,t)))throw new Error(`Invalid param ${String(e)}=${i} (${typeof i}), expected ${n}`)};for(const[s,i]of Object.entries(e))r(s,i,!1);for(const[s,i]of Object.entries(n))r(s,i,!0);return t}const zu=Object.freeze(Object.defineProperty({__proto__:null,bitGet:function(t,e){return t>>BigInt(e)&Tu},bitLen:function(t){let e;for(e=0;t>Su;t>>=Tu,e+=1);return e},bitMask:Gu,bitSet:(t,e,n)=>t|(n?Tu:Su)<<BigInt(e),bytesToHex:Cu,bytesToNumberBE:Du,bytesToNumberLE:Bu,concatBytes:Fu,createHmacDrbg:Vu,ensureBytes:Mu,equalBytes:function(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0},hexToBytes:Pu,hexToNumber:Nu,numberToBytesBE:Uu,numberToBytesLE:Lu,numberToHexUnpadded:xu,numberToVarBytesBE:function(t){return Pu(xu(t))},utf8ToBytes:function(t){if("string"!=typeof t)throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array((new TextEncoder).encode(t))},validateObject:Ku},Symbol.toStringTag,{value:"Module"})),qu=BigInt(0),$u=BigInt(1),Qu=BigInt(2),Ju=BigInt(3),Yu=BigInt(4),Zu=BigInt(5),Xu=BigInt(8);
5
5
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function th(t,e){const n=t%e;return n>=qu?n:e+n}function eh(t,e,n){if(n<=qu||e<qu)throw new Error("Expected power/modulo > 0");if(n===$u)return qu;let r=$u;for(;e>qu;)e&$u&&(r=r*t%n),t=t*t%n,e>>=$u;return r}function nh(t,e,n){let r=t;for(;e-- >qu;)r*=r,r%=n;return r}function rh(t,e){if(t===qu||e<=qu)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let n=th(t,e),r=e,s=qu,i=$u;for(;n!==qu;){const t=r%n,e=s-i*(r/n);r=n,n=t,s=i,i=e}if(r!==$u)throw new Error("invert: does not exist");return th(s,e)}function sh(t){if(t%Yu===Ju){const e=(t+$u)/Yu;return function(t,n){const r=t.pow(n,e);if(!t.eql(t.sqr(r),n))throw new Error("Cannot find square root");return r}}if(t%Xu===Zu){const e=(t-Zu)/Xu;return function(t,n){const r=t.mul(n,Qu),s=t.pow(r,e),i=t.mul(n,s),o=t.mul(t.mul(i,Qu),s),a=t.mul(i,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),n))throw new Error("Cannot find square root");return a}}return function(t){const e=(t-$u)/Qu;let n,r,s;for(n=t-$u,r=0;n%Qu===qu;n/=Qu,r++);for(s=Qu;s<t&&eh(s,e,t)!==t-$u;s++);if(1===r){const e=(t+$u)/Yu;return function(t,n){const r=t.pow(n,e);if(!t.eql(t.sqr(r),n))throw new Error("Cannot find square root");return r}}const i=(n+$u)/Qu;return function(t,o){if(t.pow(o,e)===t.neg(t.ONE))throw new Error("Cannot find square root");let a=r,c=t.pow(t.mul(t.ONE,s),n),l=t.pow(o,i),u=t.pow(o,n);for(;!t.eql(u,t.ONE);){if(t.eql(u,t.ZERO))return t.ZERO;let e=1;for(let r=t.sqr(u);e<a&&!t.eql(r,t.ONE);e++)r=t.sqr(r);const n=t.pow(c,$u<<BigInt(a-e-1));c=t.sqr(n),l=t.mul(l,n),u=t.mul(u,c),a=e}return l}}(t)}BigInt(9),BigInt(16);const ih=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function oh(t,e){const n=void 0!==e?e:t.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function ah(t){if("bigint"!=typeof t)throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function ch(t){const e=ah(t);return e+Math.ceil(e/2)}
6
6
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
7
7
  const lh=BigInt(0),uh=BigInt(1);function hh(t){return Ku(t.Fp,ih.reduce(((t,e)=>(t[e]="function",t)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"})),Ku(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...oh(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}
8
8
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const{bytesToNumberBE:dh,hexToBytes:fh}=zu,ph={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(t){const{Err:e}=ph;if(t.length<2||2!==t[0])throw new e("Invalid signature integer tag");const n=t[1],r=t.subarray(2,n+2);if(!n||r.length!==n)throw new e("Invalid signature integer: wrong length");if(128&r[0])throw new e("Invalid signature integer: negative");if(0===r[0]&&!(128&r[1]))throw new e("Invalid signature integer: unnecessary leading zero");return{d:dh(r),l:t.subarray(n+2)}},toSig(t){const{Err:e}=ph,n="string"==typeof t?fh(t):t;if(!(n instanceof Uint8Array))throw new Error("ui8a expected");let r=n.length;if(r<2||48!=n[0])throw new e("Invalid signature tag");if(n[1]!==r-2)throw new e("Invalid signature: incorrect length");const{d:s,l:i}=ph._parseInt(n.subarray(2)),{d:o,l:a}=ph._parseInt(i);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:s,s:o}},hexFromSig(t){const e=t=>8&Number.parseInt(t[0],16)?"00"+t:t,n=t=>{const e=t.toString(16);return 1&e.length?`0${e}`:e},r=e(n(t.s)),s=e(n(t.r)),i=r.length/2,o=s.length/2,a=n(i),c=n(o);return`30${n(o+i+4)}02${c}${s}02${a}${r}`}},gh=BigInt(0),mh=BigInt(1);BigInt(2);const yh=BigInt(3);function wh(t){const e=function(t){const e=hh(t);Ku(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:n,Fp:r,a:s}=e;if(n){if(!r.eql(s,r.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if("object"!=typeof n||"bigint"!=typeof n.beta||"function"!=typeof n.splitScalar)throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}(t),{Fp:n}=e,r=e.toBytes||((t,e,r)=>{const s=e.toAffine();return Fu(Uint8Array.from([4]),n.toBytes(s.x),n.toBytes(s.y))}),s=e.fromBytes||(t=>{const e=t.subarray(1);return{x:n.fromBytes(e.subarray(0,n.BYTES)),y:n.fromBytes(e.subarray(n.BYTES,2*n.BYTES))}});function i(t){const{a:r,b:s}=e,i=n.sqr(t),o=n.mul(i,t);return n.add(n.add(o,n.mul(t,r)),s)}if(!n.eql(n.sqr(e.Gy),i(e.Gx)))throw new Error("bad generator point: equation left != right");function o(t){return"bigint"==typeof t&&gh<t&&t<e.n}function a(t){if(!o(t))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(t){const{allowedPrivateKeyLengths:n,nByteLength:r,wrapPrivateKey:s,n:i}=e;if(n&&"bigint"!=typeof t){if(t instanceof Uint8Array&&(t=Cu(t)),"string"!=typeof t||!n.includes(t.length))throw new Error("Invalid key");t=t.padStart(2*r,"0")}let o;try{o="bigint"==typeof t?t:Du(Mu("private key",t,r))}catch(c){throw new Error(`private key must be ${r} bytes, hex or bigint, not ${typeof t}`)}return s&&(o=th(o,i)),a(o),o}const l=new Map;function u(t){if(!(t instanceof h))throw new Error("ProjectivePoint expected")}class h{constructor(t,e,r){if(this.px=t,this.py=e,this.pz=r,null==t||!n.isValid(t))throw new Error("x required");if(null==e||!n.isValid(e))throw new Error("y required");if(null==r||!n.isValid(r))throw new Error("z required")}static fromAffine(t){const{x:e,y:r}=t||{};if(!t||!n.isValid(e)||!n.isValid(r))throw new Error("invalid affine point");if(t instanceof h)throw new Error("projective point not allowed");const s=t=>n.eql(t,n.ZERO);return s(e)&&s(r)?h.ZERO:new h(e,r,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(t){const e=n.invertBatch(t.map((t=>t.pz)));return t.map(((t,n)=>t.toAffine(e[n]))).map(h.fromAffine)}static fromHex(t){const e=h.fromAffine(s(Mu("pointHex",t)));return e.assertValidity(),e}static fromPrivateKey(t){return h.BASE.multiply(c(t))}_setWindowSize(t){this._WINDOW_SIZE=t,l.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!n.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:t,y:r}=this.toAffine();if(!n.isValid(t)||!n.isValid(r))throw new Error("bad point: x or y not FE");const s=n.sqr(r),o=i(t);if(!n.eql(s,o))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:t}=this.toAffine();if(n.isOdd)return!n.isOdd(t);throw new Error("Field doesn't support isOdd")}equals(t){u(t);const{px:e,py:r,pz:s}=this,{px:i,py:o,pz:a}=t,c=n.eql(n.mul(e,a),n.mul(i,s)),l=n.eql(n.mul(r,a),n.mul(o,s));return c&&l}negate(){return new h(this.px,n.neg(this.py),this.pz)}double(){const{a:t,b:r}=e,s=n.mul(r,yh),{px:i,py:o,pz:a}=this;let c=n.ZERO,l=n.ZERO,u=n.ZERO,d=n.mul(i,i),f=n.mul(o,o),p=n.mul(a,a),g=n.mul(i,o);return g=n.add(g,g),u=n.mul(i,a),u=n.add(u,u),c=n.mul(t,u),l=n.mul(s,p),l=n.add(c,l),c=n.sub(f,l),l=n.add(f,l),l=n.mul(c,l),c=n.mul(g,c),u=n.mul(s,u),p=n.mul(t,p),g=n.sub(d,p),g=n.mul(t,g),g=n.add(g,u),u=n.add(d,d),d=n.add(u,d),d=n.add(d,p),d=n.mul(d,g),l=n.add(l,d),p=n.mul(o,a),p=n.add(p,p),d=n.mul(p,g),c=n.sub(c,d),u=n.mul(p,f),u=n.add(u,u),u=n.add(u,u),new h(c,l,u)}add(t){u(t);const{px:r,py:s,pz:i}=this,{px:o,py:a,pz:c}=t;let l=n.ZERO,d=n.ZERO,f=n.ZERO;const p=e.a,g=n.mul(e.b,yh);let m=n.mul(r,o),y=n.mul(s,a),w=n.mul(i,c),b=n.add(r,s),A=n.add(o,a);b=n.mul(b,A),A=n.add(m,y),b=n.sub(b,A),A=n.add(r,i);let _=n.add(o,c);return A=n.mul(A,_),_=n.add(m,w),A=n.sub(A,_),_=n.add(s,i),l=n.add(a,c),_=n.mul(_,l),l=n.add(y,w),_=n.sub(_,l),f=n.mul(p,A),l=n.mul(g,w),f=n.add(l,f),l=n.sub(y,f),f=n.add(y,f),d=n.mul(l,f),y=n.add(m,m),y=n.add(y,m),w=n.mul(p,w),A=n.mul(g,A),y=n.add(y,w),w=n.sub(m,w),w=n.mul(p,w),A=n.add(A,w),m=n.mul(y,A),d=n.add(d,m),m=n.mul(_,A),l=n.mul(b,l),l=n.sub(l,m),m=n.mul(b,y),f=n.mul(_,f),f=n.add(f,m),new h(l,d,f)}subtract(t){return this.add(t.negate())}is0(){return this.equals(h.ZERO)}wNAF(t){return f.wNAFCached(this,l,t,(t=>{const e=n.invertBatch(t.map((t=>t.pz)));return t.map(((t,n)=>t.toAffine(e[n]))).map(h.fromAffine)}))}multiplyUnsafe(t){const r=h.ZERO;if(t===gh)return r;if(a(t),t===mh)return this;const{endo:s}=e;if(!s)return f.unsafeLadder(this,t);let{k1neg:i,k1:o,k2neg:c,k2:l}=s.splitScalar(t),u=r,d=r,p=this;for(;o>gh||l>gh;)o&mh&&(u=u.add(p)),l&mh&&(d=d.add(p)),p=p.double(),o>>=mh,l>>=mh;return i&&(u=u.negate()),c&&(d=d.negate()),d=new h(n.mul(d.px,s.beta),d.py,d.pz),u.add(d)}multiply(t){a(t);let r,s,i=t;const{endo:o}=e;if(o){const{k1neg:t,k1:e,k2neg:a,k2:c}=o.splitScalar(i);let{p:l,f:u}=this.wNAF(e),{p:d,f:p}=this.wNAF(c);l=f.constTimeNegate(t,l),d=f.constTimeNegate(a,d),d=new h(n.mul(d.px,o.beta),d.py,d.pz),r=l.add(d),s=u.add(p)}else{const{p:t,f:e}=this.wNAF(i);r=t,s=e}return h.normalizeZ([r,s])[0]}multiplyAndAddUnsafe(t,e,n){const r=h.BASE,s=(t,e)=>e!==gh&&e!==mh&&t.equals(r)?t.multiply(e):t.multiplyUnsafe(e),i=s(this,e).add(s(t,n));return i.is0()?void 0:i}toAffine(t){const{px:e,py:r,pz:s}=this,i=this.is0();null==t&&(t=i?n.ONE:n.inv(s));const o=n.mul(e,t),a=n.mul(r,t),c=n.mul(s,t);if(i)return{x:n.ZERO,y:n.ZERO};if(!n.eql(c,n.ONE))throw new Error("invZ was invalid");return{x:o,y:a}}isTorsionFree(){const{h:t,isTorsionFree:n}=e;if(t===mh)return!0;if(n)return n(h,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:t,clearCofactor:n}=e;return t===mh?this:n?n(h,this):this.multiplyUnsafe(e.h)}toRawBytes(t=!0){return this.assertValidity(),r(h,this,t)}toHex(t=!0){return Cu(this.toRawBytes(t))}}h.BASE=new h(e.Gx,e.Gy,n.ONE),h.ZERO=new h(n.ZERO,n.ONE,n.ZERO);const d=e.nBitLength,f=function(t,e){const n=(t,e)=>{const n=e.negate();return t?n:e},r=t=>({windows:Math.ceil(e/t)+1,windowSize:2**(t-1)});return{constTimeNegate:n,unsafeLadder(e,n){let r=t.ZERO,s=e;for(;n>lh;)n&uh&&(r=r.add(s)),s=s.double(),n>>=uh;return r},precomputeWindow(t,e){const{windows:n,windowSize:s}=r(e),i=[];let o=t,a=o;for(let r=0;r<n;r++){a=o,i.push(a);for(let t=1;t<s;t++)a=a.add(o),i.push(a);o=a.double()}return i},wNAF(e,s,i){const{windows:o,windowSize:a}=r(e);let c=t.ZERO,l=t.BASE;const u=BigInt(2**e-1),h=2**e,d=BigInt(e);for(let t=0;t<o;t++){const e=t*a;let r=Number(i&u);i>>=d,r>a&&(r-=h,i+=uh);const o=e,f=e+Math.abs(r)-1,p=t%2!=0,g=r<0;0===r?l=l.add(n(p,s[o])):c=c.add(n(g,s[f]))}return{p:c,f:l}},wNAFCached(t,e,n,r){const s=t._WINDOW_SIZE||1;let i=e.get(t);return i||(i=this.precomputeWindow(t,s),1!==s&&e.set(t,r(i))),this.wNAF(s,i,n)}}}(h,e.endo?Math.ceil(d/2):d);return{CURVE:e,ProjectivePoint:h,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:o}}function bh(t){const e=function(t){const e=hh(t);return Ku(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}(t),{Fp:n,n:r}=e,s=n.BYTES+1,i=2*n.BYTES+1;function o(t){return th(t,r)}function a(t){return rh(t,r)}const{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:h}=wh({...e,toBytes(t,e,r){const s=e.toAffine(),i=n.toBytes(s.x),o=Fu;return r?o(Uint8Array.from([e.hasEvenY()?2:3]),i):o(Uint8Array.from([4]),i,n.toBytes(s.y))},fromBytes(t){const e=t.length,r=t[0],o=t.subarray(1);if(e!==s||2!==r&&3!==r){if(e===i&&4===r){return{x:n.fromBytes(o.subarray(0,n.BYTES)),y:n.fromBytes(o.subarray(n.BYTES,2*n.BYTES))}}throw new Error(`Point of length ${e} was invalid. Expected ${s} compressed bytes or ${i} uncompressed bytes`)}{const t=Du(o);if(!(gh<(a=t)&&a<n.ORDER))throw new Error("Point is not on curve");const e=u(t);let s=n.sqrt(e);return!(1&~r)!==((s&mh)===mh)&&(s=n.neg(s)),{x:t,y:s}}var a}}),d=t=>Cu(Uu(t,e.nByteLength));function f(t){return t>r>>mh}const p=(t,e,n)=>Du(t.slice(e,n));class g{constructor(t,e,n){this.r=t,this.s=e,this.recovery=n,this.assertValidity()}static fromCompact(t){const n=e.nByteLength;return t=Mu("compactSignature",t,2*n),new g(p(t,0,n),p(t,n,2*n))}static fromDER(t){const{r:e,s:n}=ph.toSig(Mu("DER",t));return new g(e,n)}assertValidity(){if(!h(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!h(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(t){return new g(this.r,this.s,t)}recoverPublicKey(t){const{r:r,s:s,recovery:i}=this,l=b(Mu("msgHash",t));if(null==i||![0,1,2,3].includes(i))throw new Error("recovery id invalid");const u=2===i||3===i?r+e.n:r;if(u>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");const h=1&i?"03":"02",f=c.fromHex(h+d(u)),p=a(u),g=o(-l*p),m=o(s*p),y=c.BASE.multiplyAndAddUnsafe(f,g,m);if(!y)throw new Error("point at infinify");return y.assertValidity(),y}hasHighS(){return f(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Pu(this.toDERHex())}toDERHex(){return ph.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Pu(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}const m={isValidPrivateKey(t){try{return l(t),!0}catch(e){return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const t=ch(e.n);return function(t,e,n=!1){const r=t.length,s=ah(e),i=ch(e);if(r<16||r<i||r>1024)throw new Error(`expected ${i}-1024 bytes of input, got ${r}`);const o=th(n?Du(t):Bu(t),e-$u)+$u;return n?Lu(o,s):Uu(o,s)}(e.randomBytes(t),e.n)},precompute:(t=8,e=c.BASE)=>(e._setWindowSize(t),e.multiply(BigInt(3)),e)};function y(t){const e=t instanceof Uint8Array,n="string"==typeof t,r=(e||n)&&t.length;return e?r===s||r===i:n?r===2*s||r===2*i:t instanceof c}const w=e.bits2int||function(t){const n=Du(t),r=8*t.length-e.nBitLength;return r>0?n>>BigInt(r):n},b=e.bits2int_modN||function(t){return o(w(t))},A=Gu(e.nBitLength);function _(t){if("bigint"!=typeof t)throw new Error("bigint expected");if(!(gh<=t&&t<A))throw new Error(`bigint expected < 2^${e.nBitLength}`);return Uu(t,e.nByteLength)}function v(t,r,s=E){if(["recovered","canonical"].some((t=>t in s)))throw new Error("sign() legacy options not supported");const{hash:i,randomBytes:u}=e;let{lowS:d,prehash:p,extraEntropy:m}=s;null==d&&(d=!0),t=Mu("msgHash",t),p&&(t=Mu("prehashed msgHash",i(t)));const y=b(t),A=l(r),v=[_(A),_(y)];if(null!=m){const t=!0===m?u(n.BYTES):m;v.push(Mu("extraEntropy",t))}const k=Fu(...v),S=y;return{seed:k,k2sig:function(t){const e=w(t);if(!h(e))return;const n=a(e),r=c.BASE.multiply(e).toAffine(),s=o(r.x);if(s===gh)return;const i=o(n*o(S+s*A));if(i===gh)return;let l=(r.x===s?0:2)|Number(r.y&mh),u=i;return d&&f(i)&&(u=function(t){return f(t)?o(-t):t}(i),l^=1),new g(s,u,l)}}}const E={lowS:e.lowS,prehash:!1},k={lowS:e.lowS,prehash:!1};return c.BASE._setWindowSize(8),{CURVE:e,getPublicKey:function(t,e=!0){return c.fromPrivateKey(t).toRawBytes(e)},getSharedSecret:function(t,e,n=!0){if(y(t))throw new Error("first arg must be private key");if(!y(e))throw new Error("second arg must be public key");return c.fromHex(e).multiply(l(t)).toRawBytes(n)},sign:function(t,n,r=E){const{seed:s,k2sig:i}=v(t,n,r),o=e;return Vu(o.hash.outputLen,o.nByteLength,o.hmac)(s,i)},verify:function(t,n,r,s=k){var i;const l=t;if(n=Mu("msgHash",n),r=Mu("publicKey",r),"strict"in s)throw new Error("options.strict was renamed to lowS");const{lowS:u,prehash:h}=s;let d,f;try{if("string"==typeof l||l instanceof Uint8Array)try{d=g.fromDER(l)}catch(E){if(!(E instanceof ph.Err))throw E;d=g.fromCompact(l)}else{if("object"!=typeof l||"bigint"!=typeof l.r||"bigint"!=typeof l.s)throw new Error("PARSE");{const{r:t,s:e}=l;d=new g(t,e)}}f=c.fromHex(r)}catch(S){if("PARSE"===S.message)throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(u&&d.hasHighS())return!1;h&&(n=e.hash(n));const{r:p,s:m}=d,y=b(n),w=a(m),A=o(y*w),_=o(p*w),v=null==(i=c.BASE.multiplyAndAddUnsafe(f,A,_))?void 0:i.toAffine();return!!v&&o(v.x)===p},ProjectivePoint:c,Signature:g,utils:m}}
9
9
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ah(t){return{hash:t,hmac:(e,...n)=>jc(t,e,function(...t){const e=new Uint8Array(t.reduce(((t,e)=>t+e.length),0));let n=0;return t.forEach((t=>{if(!Ic(t))throw new Error("Uint8Array expected");e.set(t,n),n+=t.length})),e}(...n)),randomBytes:Fc}}BigInt(4);
10
10
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
11
- const _h=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),vh=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Eh=BigInt(1),kh=BigInt(2),Sh=(t,e)=>(t+e/kh)/e;const Th=function(t,e,n=!1,r={}){if(t<=qu)throw new Error(`Expected Field ORDER > 0, got ${t}`);const{nBitLength:s,nByteLength:i}=oh(t,e);if(i>2048)throw new Error("Field lengths over 2048 bytes are not supported");const o=sh(t),a=Object.freeze({ORDER:t,BITS:s,BYTES:i,MASK:Gu(s),ZERO:qu,ONE:$u,create:e=>th(e,t),isValid:e=>{if("bigint"!=typeof e)throw new Error("Invalid field element: expected bigint, got "+typeof e);return qu<=e&&e<t},is0:t=>t===qu,isOdd:t=>(t&$u)===$u,neg:e=>th(-e,t),eql:(t,e)=>t===e,sqr:e=>th(e*e,t),add:(e,n)=>th(e+n,t),sub:(e,n)=>th(e-n,t),mul:(e,n)=>th(e*n,t),pow:(t,e)=>function(t,e,n){if(n<qu)throw new Error("Expected power > 0");if(n===qu)return t.ONE;if(n===$u)return e;let r=t.ONE,s=e;for(;n>qu;)n&$u&&(r=t.mul(r,s)),s=t.sqr(s),n>>=$u;return r}(a,t,e),div:(e,n)=>th(e*rh(n,t),t),sqrN:t=>t*t,addN:(t,e)=>t+e,subN:(t,e)=>t-e,mulN:(t,e)=>t*e,inv:e=>rh(e,t),sqrt:r.sqrt||(t=>o(a,t)),invertBatch:t=>function(t,e){const n=new Array(e.length),r=e.reduce(((e,r,s)=>t.is0(r)?e:(n[s]=e,t.mul(e,r))),t.ONE),s=t.inv(r);return e.reduceRight(((e,r,s)=>t.is0(r)?e:(n[s]=t.mul(e,n[s]),t.mul(e,r))),s),n}(a,t),cmov:(t,e,n)=>n?e:t,toBytes:t=>n?Lu(t,i):Uu(t,i),fromBytes:t=>{if(t.length!==i)throw new Error(`Fp.fromBytes: expected ${i}, got ${t.length}`);return n?Bu(t):Du(t)}});return Object.freeze(a)}(_h,void 0,void 0,{sqrt:function(t){const e=_h,n=BigInt(3),r=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,u=l*l*t%e,h=nh(u,n,e)*u%e,d=nh(h,n,e)*u%e,f=nh(d,kh,e)*l%e,p=nh(f,s,e)*f%e,g=nh(p,i,e)*p%e,m=nh(g,a,e)*g%e,y=nh(m,c,e)*m%e,w=nh(y,a,e)*g%e,b=nh(w,n,e)*u%e,A=nh(b,o,e)*p%e,_=nh(A,r,e)*l%e,v=nh(_,kh,e);if(!Th.eql(Th.sqr(v),t))throw new Error("Cannot find square root");return v}}),Rh=function(t,e){const n=e=>bh({...t,...Ah(e)});return Object.freeze({...n(e),create:n})}({a:BigInt(0),b:BigInt(7),Fp:Th,n:vh,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=vh,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-Eh*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=n,o=BigInt("0x100000000000000000000000000000000"),a=Sh(i*t,e),c=Sh(-r*t,e);let l=th(t-a*n-c*s,e),u=th(-a*r-c*i,e);const h=l>o,d=u>o;if(h&&(l=e-l),d&&(u=e-u),l>o||u>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:h,k1:l,k2neg:d,k2:u}}}},Qc);BigInt(0),Rh.ProjectivePoint;const Ih="0x0000000000000000000000000000000000000000",Oh="0x0000000000000000000000000000000000000000000000000000000000000000",Ch=BigInt(0),Nh=BigInt(1),xh=BigInt(2),Ph=BigInt(27),Dh=BigInt(28),Bh=BigInt(35),Uh=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Lh=Uh/xh,Mh=Symbol.for("nodejs.util.inspect.custom"),Fh={};function Gh(t){return ua(Ea(t),32)}G=new WeakMap,j=new WeakMap,H=new WeakMap,V=new WeakMap;let jh=class t{constructor(t,e,n,r){Dn(this,G,void 0),Dn(this,j,void 0),Dn(this,H,void 0),Dn(this,V,void 0),Zo(t,Fh,"Signature"),Bn(this,G,e),Bn(this,j,n),Bn(this,H,r),Bn(this,V,null)}get r(){return Pn(this,G)}set r(t){$o(32===aa(t),"invalid r","value",t),Bn(this,G,ia(t))}get s(){return $o(parseInt(Pn(this,j).substring(0,3))<8,"non-canonical s; use ._s","s",Pn(this,j)),Pn(this,j)}set s(t){$o(32===aa(t),"invalid s","value",t),Bn(this,j,ia(t))}get _s(){return Pn(this,j)}isValid(){return BigInt(Pn(this,j))<=Lh}get v(){return Pn(this,H)}set v(t){const e=_a(t,"value");$o(27===e||28===e,"invalid v","v",t),Bn(this,H,e)}get networkV(){return Pn(this,V)}get legacyChainId(){const e=this.networkV;return null==e?null:t.getChainId(e)}get yParity(){return 27===this.v?0:1}get yParityAndS(){const t=ta(this.s);return this.yParity&&(t[0]|=128),ia(t)}get compactSerialized(){return oa([this.r,this.yParityAndS])}get serialized(){return oa([this.r,this.s,this.yParity?"0x1c":"0x1b"])}getCanonical(){if(this.isValid())return this;const e=Uh-BigInt(this._s),n=55-this.v,r=new t(Fh,this.r,Gh(e),n);return this.networkV&&Bn(r,V,this.networkV),r}clone(){const e=new t(Fh,this.r,this._s,this.v);return this.networkV&&Bn(e,V,this.networkV),e}toJSON(){const t=this.networkV;return{_type:"signature",networkV:null!=t?t.toString():null,r:this.r,s:this._s,v:this.v}}[Mh](){return this.toString()}toString(){return this.isValid()?`Signature { r: ${this.r}, s: ${this._s}, v: ${this.v} }`:`Signature { r: ${this.r}, s: ${this._s}, v: ${this.v}, valid: false }`}static getChainId(t){const e=ya(t,"v");return e==Ph||e==Dh?Ch:($o(e>=Bh,"invalid EIP-155 v","v",t),(e-Bh)/xh)}static getChainIdV(t,e){return ya(t)*xh+BigInt(35+e-27)}static getNormalizedV(t){const e=ya(t);return e===Ch||e===Ph?27:e===Nh||e===Dh?28:($o(e>=Bh,"invalid v","v",t),e&Nh?27:28)}static from(e){function n(t,n){$o(t,n,"signature",e)}if(null==e)return new t(Fh,Oh,Oh,27);if("string"==typeof e){const r=ta(e,"signature");if(64===r.length){const e=ia(r.slice(0,32)),n=r.slice(32,64),s=128&n[0]?28:27;return n[0]&=127,new t(Fh,e,ia(n),s)}if(65===r.length){const e=ia(r.slice(0,32)),n=ia(r.slice(32,64)),s=t.getNormalizedV(r[64]);return new t(Fh,e,n,s)}n(!1,"invalid raw signature length")}if(e instanceof t)return e.clone();const r=e.r;n(null!=r,"missing r");const s=Gh(r),i=function(t,e){if(null!=t)return Gh(t);if(null!=e){n(na(e,32),"invalid yParityAndS");const t=ta(e);return t[0]&=127,ia(t)}n(!1,"missing s")}(e.s,e.yParityAndS),{networkV:o,v:a}=function(e,r,s){if(null!=e){const n=ya(e);return{networkV:n>=Bh?n:void 0,v:t.getNormalizedV(n)}}if(null!=r)return n(na(r,32),"invalid yParityAndS"),{v:128&ta(r)[0]?28:27};if(null!=s){switch(_a(s,"sig.yParity")){case 0:return{v:27};case 1:return{v:28}}n(!1,"invalid yParity")}n(!1,"missing v")}(e.v,e.yParityAndS,e.yParity),c=new t(Fh,s,i,a);return o&&Bn(c,V,o),n(null==e.yParity||_a(e.yParity,"sig.yParity")===c.yParity,"yParity mismatch"),n(null==e.yParityAndS||e.yParityAndS===c.yParityAndS,"yParityAndS mismatch"),c}};W=new WeakMap;let Hh=class t{constructor(t){Dn(this,W,void 0),$o(32===aa(t),"invalid private key","privateKey","[REDACTED]"),Bn(this,W,ia(t))}get privateKey(){return Pn(this,W)}get publicKey(){return t.computePublicKey(Pn(this,W))}get compressedPublicKey(){return t.computePublicKey(Pn(this,W),!0)}sign(t){$o(32===aa(t),"invalid digest length","digest",t);const e=Rh.sign(ea(t),ea(Pn(this,W)),{lowS:!0});return jh.from({r:va(e.r,32),s:va(e.s,32),v:e.recovery?28:27})}computeSharedSecret(e){const n=t.computePublicKey(e);return ia(Rh.getSharedSecret(ea(Pn(this,W)),ta(n),!1))}static computePublicKey(t,e){let n=ta(t,"key");if(32===n.length){return ia(Rh.getPublicKey(n,!!e))}if(64===n.length){const t=new Uint8Array(65);t[0]=4,t.set(n,1),n=t}return ia(Rh.ProjectivePoint.fromHex(n).toRawBytes(e))}static recoverPublicKey(t,e){$o(32===aa(t),"invalid digest length","digest",t);const n=jh.from(e);let r=Rh.Signature.fromCompact(ea(oa([n.r,n.s])));r=r.addRecoveryBit(n.yParity);const s=r.recoverPublicKey(ea(t));return $o(null!=s,"invalid signature for digest","signature",e),"0x"+s.toHex(!1)}static addPoints(e,n,r){const s=Rh.ProjectivePoint.fromHex(t.computePublicKey(e).substring(2)),i=Rh.ProjectivePoint.fromHex(t.computePublicKey(n).substring(2));return"0x"+s.add(i).toHex(!!r)}};const Vh=BigInt(0),Wh=BigInt(36);function Kh(t){const e=(t=t.toLowerCase()).substring(2).split(""),n=new Uint8Array(40);for(let s=0;s<40;s++)n[s]=e[s].charCodeAt(0);const r=ta(Bl(n));for(let s=0;s<40;s+=2)r[s>>1]>>4>=8&&(e[s]=e[s].toUpperCase()),(15&r[s>>1])>=8&&(e[s+1]=e[s+1].toUpperCase());return"0x"+e.join("")}const zh={};for(let J_=0;J_<10;J_++)zh[String(J_)]=String(J_);for(let J_=0;J_<26;J_++)zh[String.fromCharCode(65+J_)]=String(10+J_);const qh=function(){const t={};for(let e=0;e<36;e++){t["0123456789abcdefghijklmnopqrstuvwxyz"[e]]=BigInt(e)}return t}();function $h(t){if($o("string"==typeof t,"invalid address","address",t),t.match(/^(0x)?[0-9a-fA-F]{40}$/)){t.startsWith("0x")||(t="0x"+t);const e=Kh(t);return $o(!t.match(/([A-F].*[a-f])|([a-f].*[A-F])/)||e===t,"bad address checksum","address",t),e}if(t.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){$o(t.substring(2,4)===function(t){let e=(t=(t=t.toUpperCase()).substring(4)+t.substring(0,2)+"00").split("").map((t=>zh[t])).join("");for(;e.length>=15;){let t=e.substring(0,15);e=parseInt(t,10)%97+e.substring(t.length)}let n=String(98-parseInt(e,10)%97);for(;n.length<2;)n="0"+n;return n}(t),"bad icap checksum","address",t);let e=function(t){t=t.toLowerCase();let e=Vh;for(let n=0;n<t.length;n++)e=e*Wh+qh[t[n]];return e}(t.substring(4)).toString(16);for(;e.length<40;)e="0"+e;return Kh("0x"+e)}$o(!1,"invalid address","address",t)}function Qh(t){return t&&"function"==typeof t.getAddress}async function Jh(t,e){const n=await e;return null!=n&&"0x0000000000000000000000000000000000000000"!==n||(qo("string"!=typeof t,"unconfigured name","UNCONFIGURED_NAME",{value:t}),$o(!1,"invalid AddressLike value; did not resolve to a value address","target",t)),$h(n)}function Yh(t,e){return"string"==typeof t?t.match(/^0x[0-9a-f]{40}$/i)?$h(t):(qo(null!=e,"ENS resolution requires a provider","UNSUPPORTED_OPERATION",{operation:"resolveName"}),Jh(t,e.resolveName(t))):Qh(t)?Jh(t,t.getAddress()):t&&"function"==typeof t.then?Jh(t,t):void $o(!1,"unsupported addressable value","target",t)}const Zh={};function Xh(t,e){let n=!1;return e<0&&(n=!0,e*=-1),new nd(Zh,`${n?"":"u"}int${e}`,t,{signed:n,width:e})}function td(t,e){return new nd(Zh,`bytes${e||""}`,t,{size:e})}const ed=Symbol.for("_ethers_typed");K=new WeakMap;let nd=class t{constructor(t,e,n,r){Nn(this,"type"),Nn(this,"value"),Dn(this,K,void 0),Nn(this,"_typedSymbol"),null==r&&(r=null),Zo(Zh,t,"Typed"),Ho(this,{_typedSymbol:ed,type:e,value:n}),Bn(this,K,r),this.format()}format(){if("array"===this.type)throw new Error("");if("dynamicArray"===this.type)throw new Error("");return"tuple"===this.type?`tuple(${this.value.map((t=>t.format())).join(",")})`:this.type}defaultValue(){return 0}minValue(){return 0}maxValue(){return 0}isBigInt(){return!!this.type.match(/^u?int[0-9]+$/)}isData(){return this.type.startsWith("bytes")}isString(){return"string"===this.type}get tupleName(){if("tuple"!==this.type)throw TypeError("not a tuple");return Pn(this,K)}get arrayLength(){if("array"!==this.type)throw TypeError("not an array");return!0===Pn(this,K)?-1:!1===Pn(this,K)?this.value.length:null}static from(e,n){return new t(Zh,e,n)}static uint8(t){return Xh(t,8)}static uint16(t){return Xh(t,16)}static uint24(t){return Xh(t,24)}static uint32(t){return Xh(t,32)}static uint40(t){return Xh(t,40)}static uint48(t){return Xh(t,48)}static uint56(t){return Xh(t,56)}static uint64(t){return Xh(t,64)}static uint72(t){return Xh(t,72)}static uint80(t){return Xh(t,80)}static uint88(t){return Xh(t,88)}static uint96(t){return Xh(t,96)}static uint104(t){return Xh(t,104)}static uint112(t){return Xh(t,112)}static uint120(t){return Xh(t,120)}static uint128(t){return Xh(t,128)}static uint136(t){return Xh(t,136)}static uint144(t){return Xh(t,144)}static uint152(t){return Xh(t,152)}static uint160(t){return Xh(t,160)}static uint168(t){return Xh(t,168)}static uint176(t){return Xh(t,176)}static uint184(t){return Xh(t,184)}static uint192(t){return Xh(t,192)}static uint200(t){return Xh(t,200)}static uint208(t){return Xh(t,208)}static uint216(t){return Xh(t,216)}static uint224(t){return Xh(t,224)}static uint232(t){return Xh(t,232)}static uint240(t){return Xh(t,240)}static uint248(t){return Xh(t,248)}static uint256(t){return Xh(t,256)}static uint(t){return Xh(t,256)}static int8(t){return Xh(t,-8)}static int16(t){return Xh(t,-16)}static int24(t){return Xh(t,-24)}static int32(t){return Xh(t,-32)}static int40(t){return Xh(t,-40)}static int48(t){return Xh(t,-48)}static int56(t){return Xh(t,-56)}static int64(t){return Xh(t,-64)}static int72(t){return Xh(t,-72)}static int80(t){return Xh(t,-80)}static int88(t){return Xh(t,-88)}static int96(t){return Xh(t,-96)}static int104(t){return Xh(t,-104)}static int112(t){return Xh(t,-112)}static int120(t){return Xh(t,-120)}static int128(t){return Xh(t,-128)}static int136(t){return Xh(t,-136)}static int144(t){return Xh(t,-144)}static int152(t){return Xh(t,-152)}static int160(t){return Xh(t,-160)}static int168(t){return Xh(t,-168)}static int176(t){return Xh(t,-176)}static int184(t){return Xh(t,-184)}static int192(t){return Xh(t,-192)}static int200(t){return Xh(t,-200)}static int208(t){return Xh(t,-208)}static int216(t){return Xh(t,-216)}static int224(t){return Xh(t,-224)}static int232(t){return Xh(t,-232)}static int240(t){return Xh(t,-240)}static int248(t){return Xh(t,-248)}static int256(t){return Xh(t,-256)}static int(t){return Xh(t,-256)}static bytes1(t){return td(t,1)}static bytes2(t){return td(t,2)}static bytes3(t){return td(t,3)}static bytes4(t){return td(t,4)}static bytes5(t){return td(t,5)}static bytes6(t){return td(t,6)}static bytes7(t){return td(t,7)}static bytes8(t){return td(t,8)}static bytes9(t){return td(t,9)}static bytes10(t){return td(t,10)}static bytes11(t){return td(t,11)}static bytes12(t){return td(t,12)}static bytes13(t){return td(t,13)}static bytes14(t){return td(t,14)}static bytes15(t){return td(t,15)}static bytes16(t){return td(t,16)}static bytes17(t){return td(t,17)}static bytes18(t){return td(t,18)}static bytes19(t){return td(t,19)}static bytes20(t){return td(t,20)}static bytes21(t){return td(t,21)}static bytes22(t){return td(t,22)}static bytes23(t){return td(t,23)}static bytes24(t){return td(t,24)}static bytes25(t){return td(t,25)}static bytes26(t){return td(t,26)}static bytes27(t){return td(t,27)}static bytes28(t){return td(t,28)}static bytes29(t){return td(t,29)}static bytes30(t){return td(t,30)}static bytes31(t){return td(t,31)}static bytes32(t){return td(t,32)}static address(e){return new t(Zh,"address",e)}static bool(e){return new t(Zh,"bool",!!e)}static bytes(e){return new t(Zh,"bytes",e)}static string(e){return new t(Zh,"string",e)}static array(t,e){throw new Error("not implemented yet")}static tuple(t,e){throw new Error("not implemented yet")}static overrides(e){return new t(Zh,"overrides",Object.assign({},e))}static isTyped(t){return t&&"object"==typeof t&&"_typedSymbol"in t&&t._typedSymbol===ed}static dereference(e,n){if(t.isTyped(e)){if(e.type!==n)throw new Error(`invalid type: expecetd ${n}, got ${e.type}`);return e.value}return e}};class rd extends bc{constructor(t){super("address","address",t,!1)}defaultValue(){return"0x0000000000000000000000000000000000000000"}encode(t,e){let n=nd.dereference(e,"string");try{n=$h(n)}catch(r){return this._throwError(r.message,e)}return t.writeValue(n)}decode(t){return $h(va(t.readValue(),20))}}class sd extends bc{constructor(t){super(t.name,t.type,"_",t.dynamic),Nn(this,"coder"),this.coder=t}defaultValue(){return this.coder.defaultValue()}encode(t,e){return this.coder.encode(t,e)}decode(t){return this.coder.decode(t)}}function id(t,e,n){let r=[];if(Array.isArray(n))r=n;else if(n&&"object"==typeof n){let t={};r=e.map((e=>{const r=e.localName;return qo(r,"cannot encode object for signature with missing names","INVALID_ARGUMENT",{argument:"values",info:{coder:e},value:n}),qo(!t[r],"cannot encode object for signature with duplicate names","INVALID_ARGUMENT",{argument:"values",info:{coder:e},value:n}),t[r]=!0,n[r]}))}else $o(!1,"invalid tuple value","tuple",n);$o(e.length===r.length,"types/value length mismatch","tuple",n);let s=new Ac,i=new Ac,o=[];e.forEach(((t,e)=>{let n=r[e];if(t.dynamic){let e=i.length;t.encode(i,n);let r=s.writeUpdatableValue();o.push((t=>{r(t+e)}))}else t.encode(s,n)})),o.forEach((t=>{t(s.length)}));let a=t.appendWriter(s);return a+=t.appendWriter(i),a}function od(t,e){let n=[],r=[],s=t.subReader(0);return e.forEach((e=>{let i=null;if(e.dynamic){let n=t.readIndex(),r=s.subReader(n);try{i=e.decode(r)}catch(o){if(Wo(o,"BUFFER_OVERRUN"))throw o;i=o,i.baseType=e.name,i.name=e.localName,i.type=e.type}}else try{i=e.decode(t)}catch(o){if(Wo(o,"BUFFER_OVERRUN"))throw o;i=o,i.baseType=e.name,i.name=e.localName,i.type=e.type}if(null==i)throw new Error("investigate");n.push(i),r.push(e.localName||null)})),yc.fromItems(n,r)}class ad extends bc{constructor(t,e,n){super("array",t.type+"["+(e>=0?e:"")+"]",n,-1===e||t.dynamic),Nn(this,"coder"),Nn(this,"length"),Ho(this,{coder:t,length:e})}defaultValue(){const t=this.coder.defaultValue(),e=[];for(let n=0;n<this.length;n++)e.push(t);return e}encode(t,e){const n=nd.dereference(e,"array");Array.isArray(n)||this._throwError("expected array value",n);let r=this.length;-1===r&&(r=n.length,t.writeValue(n.length)),Qo(n.length,r,"coder array"+(this.localName?" "+this.localName:""));let s=[];for(let i=0;i<n.length;i++)s.push(this.coder);return id(t,s,n)}decode(t){let e=this.length;-1===e&&(e=t.readIndex(),qo(e*cc<=t.dataLength,"insufficient data length","BUFFER_OVERRUN",{buffer:t.bytes,offset:e*cc,length:t.dataLength}));let n=[];for(let r=0;r<e;r++)n.push(new sd(this.coder));return od(t,n)}}class cd extends bc{constructor(t){super("bool","bool",t,!1)}defaultValue(){return!1}encode(t,e){const n=nd.dereference(e,"bool");return t.writeValue(n?1:0)}decode(t){return!!t.readValue()}}class ld extends bc{constructor(t,e){super(t,t,e,!0)}defaultValue(){return"0x"}encode(t,e){e=ea(e);let n=t.writeValue(e.length);return n+=t.writeBytes(e),n}decode(t){return t.readBytes(t.readIndex(),!0)}}class ud extends ld{constructor(t){super("bytes",t)}decode(t){return ia(super.decode(t))}}class hd extends bc{constructor(t,e){let n="bytes"+String(t);super(n,n,e,!1),Nn(this,"size"),Ho(this,{size:t},{size:"number"})}defaultValue(){return"0x0000000000000000000000000000000000000000000000000000000000000000".substring(0,2+2*this.size)}encode(t,e){let n=ea(nd.dereference(e,this.type));return n.length!==this.size&&this._throwError("incorrect data length",e),t.writeBytes(n)}decode(t){return ia(t.readBytes(this.size))}}const dd=new Uint8Array([]);class fd extends bc{constructor(t){super("null","",t,!1)}defaultValue(){return null}encode(t,e){return null!=e&&this._throwError("not null",e),t.writeBytes(dd)}decode(t){return t.readBytes(0),null}}const pd=BigInt(0),gd=BigInt(1),md=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");class yd extends bc{constructor(t,e,n){const r=(e?"int":"uint")+8*t;super(r,r,n,!1),Nn(this,"size"),Nn(this,"signed"),Ho(this,{size:t,signed:e},{size:"number",signed:"boolean"})}defaultValue(){return 0}encode(t,e){let n=ya(nd.dereference(e,this.type)),r=ma(md,256);if(this.signed){let t=ma(r,8*this.size-1);(n>t||n<-(t+gd))&&this._throwError("value out-of-bounds",e),n=ga(n,256)}else(n<pd||n>ma(r,8*this.size))&&this._throwError("value out-of-bounds",e);return t.writeValue(n)}decode(t){let e=ma(t.readValue(),8*this.size);return this.signed&&(e=function(t,e){const n=wa(t,"value"),r=BigInt(_a(e,"width"));if(qo(n>>r===da,"overflow","NUMERIC_FAULT",{operation:"fromTwos",fault:"overflow",value:t}),n>>r-fa)return-((~n&(fa<<r)-fa)+fa);return n}(e,8*this.size)),e}}class wd extends ld{constructor(t){super("string",t)}defaultValue(){return""}encode(t,e){return super.encode(t,Da(nd.dereference(e,"string")))}decode(t){return Ba(super.decode(t))}}class bd extends bc{constructor(t,e){let n=!1;const r=[];t.forEach((t=>{t.dynamic&&(n=!0),r.push(t.type)}));super("tuple","tuple("+r.join(",")+")",e,n),Nn(this,"coders"),Ho(this,{coders:Object.freeze(t.slice())})}defaultValue(){const t=[];this.coders.forEach((e=>{t.push(e.defaultValue())}));const e=this.coders.reduce(((t,e)=>{const n=e.localName;return n&&(t[n]||(t[n]=0),t[n]++),t}),{});return this.coders.forEach(((n,r)=>{let s=n.localName;s&&1===e[s]&&("length"===s&&(s="_length"),null==t[s]&&(t[s]=t[r]))})),Object.freeze(t)}encode(t,e){const n=nd.dereference(e,"tuple");return id(t,this.coders,n)}decode(t){return od(t,this.coders)}}function Ad(t,e){return{address:$h(t),storageKeys:e.map(((t,e)=>($o(na(t,32),"invalid slot",`storageKeys[${e}]`,t),t.toLowerCase())))}}function _d(t){if(Array.isArray(t))return t.map(((e,n)=>Array.isArray(e)?($o(2===e.length,"invalid slot set",`value[${n}]`,e),Ad(e[0],e[1])):($o(null!=e&&"object"==typeof e,"invalid address-slot set","value",t),Ad(e.address,e.storageKeys))));$o(null!=t&&"object"==typeof t,"invalid access list","value",t);const e=Object.keys(t).map((e=>{const n=t[e].reduce(((t,e)=>(t[e]=!0,t)),{});return Ad(e,Object.keys(n).sort())}));return e.sort(((t,e)=>t.address.localeCompare(e.address))),e}function vd(t){return{address:$h(t.address),nonce:ya(null!=t.nonce?t.nonce:0),chainId:ya(null!=t.chainId?t.chainId:0),signature:jh.from(t.signature)}}function Ed(t){let e;return e="string"==typeof t?Hh.computePublicKey(t,!1):t.publicKey,$h(Bl("0x"+e.substring(4)).substring(26))}const kd=BigInt(0),Sd=BigInt(2),Td=BigInt(27),Rd=BigInt(28),Id=BigInt(35),Od=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Cd=Symbol.for("nodejs.util.inspect.custom"),Nd=131072,xd=128;function Pd(t,e){let n=t.toString(16);for(;n.length<2;)n="0"+n;return n+=ku(e).substring(4),"0x"+n}function Dd(t){return"0x"===t?null:$h(t)}function Bd(t,e){try{return _d(t)}catch(n){$o(!1,n.message,e,t)}}function Ud(t,e){try{if(!Array.isArray(t))throw new Error("authorizationList: invalid array");const e=[];for(let n=0;n<t.length;n++){const r=t[n];if(!Array.isArray(r))throw new Error(`authorization[${n}]: invalid array`);if(6!==r.length)throw new Error(`authorization[${n}]: wrong length`);if(!r[1])throw new Error(`authorization[${n}]: null address`);e.push({address:Dd(r[1]),nonce:Md(r[2],"nonce"),chainId:Md(r[0],"chainId"),signature:jh.from({yParity:Ld(r[3],"yParity"),r:ua(r[4],32),s:ua(r[5],32)})})}return e}catch(n){$o(!1,n.message,e,t)}}function Ld(t,e){return"0x"===t?0:_a(t,e)}function Md(t,e){if("0x"===t)return kd;const n=ya(t,e);return $o(n<=Od,"value exceeds uint size",e,n),n}function Fd(t,e){const n=ya(t,"value"),r=Ea(n);return $o(r.length<=32,"value too large",`tx.${e}`,n),r}function Gd(t){return _d(t).map((t=>[t.address,t.storageKeys]))}function jd(t,e){$o(Array.isArray(t),`invalid ${e}`,"value",t);for(let n=0;n<t.length;n++)$o(na(t[n],32),"invalid ${ param } hash",`value[${n}]`,t[n]);return t}function Hd(t,e){let n;try{if(n=Ld(e[0],"yParity"),0!==n&&1!==n)throw new Error("bad yParity")}catch(o){$o(!1,"invalid yParity","yParity",e[0])}const r=ua(e[1],32),s=ua(e[2],32),i=jh.from({r:r,s:s,yParity:n});t.signature=i}z=new WeakMap,q=new WeakMap,$=new WeakMap,Q=new WeakMap,J=new WeakMap,Y=new WeakMap,Z=new WeakMap,X=new WeakMap,tt=new WeakMap,et=new WeakMap,nt=new WeakMap,rt=new WeakMap,st=new WeakMap,it=new WeakMap,ot=new WeakMap,at=new WeakMap,ct=new WeakMap,lt=new WeakMap,ut=new WeakSet,ht=function(t,e){qo(!t||null!=this.signature,"cannot serialize unsigned transaction; maybe you meant .unsignedSerialized","UNSUPPORTED_OPERATION",{operation:".serialized"});const n=t?this.signature:null;switch(this.inferType()){case 0:return function(t,e){const n=[Fd(t.nonce,"nonce"),Fd(t.gasPrice||0,"gasPrice"),Fd(t.gasLimit,"gasLimit"),t.to||"0x",Fd(t.value,"value"),t.data];let r=kd;if(t.chainId!=kd)r=ya(t.chainId,"tx.chainId"),$o(!e||null==e.networkV||e.legacyChainId===r,"tx.chainId/sig.v mismatch","sig",e);else if(t.signature){const e=t.signature.legacyChainId;null!=e&&(r=e)}if(!e)return r!==kd&&(n.push(Ea(r)),n.push("0x"),n.push("0x")),oc(n);let s=BigInt(27+e.yParity);return r!==kd?s=jh.getChainIdV(r,e.v):BigInt(e.v)!==s&&$o(!1,"tx.chainId/sig.v mismatch","sig",e),n.push(Ea(s)),n.push(Ea(e.r)),n.push(Ea(e._s)),oc(n)}(this,n);case 1:return function(t,e){const n=[Fd(t.chainId,"chainId"),Fd(t.nonce,"nonce"),Fd(t.gasPrice||0,"gasPrice"),Fd(t.gasLimit,"gasLimit"),t.to||"0x",Fd(t.value,"value"),t.data,Gd(t.accessList||[])];return e&&(n.push(Fd(e.yParity,"recoveryParam")),n.push(Ea(e.r)),n.push(Ea(e.s))),oa(["0x01",oc(n)])}(this,n);case 2:return function(t,e){const n=[Fd(t.chainId,"chainId"),Fd(t.nonce,"nonce"),Fd(t.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),Fd(t.maxFeePerGas||0,"maxFeePerGas"),Fd(t.gasLimit,"gasLimit"),t.to||"0x",Fd(t.value,"value"),t.data,Gd(t.accessList||[])];return e&&(n.push(Fd(e.yParity,"yParity")),n.push(Ea(e.r)),n.push(Ea(e.s))),oa(["0x02",oc(n)])}(this,n);case 3:return function(t,e,n){const r=[Fd(t.chainId,"chainId"),Fd(t.nonce,"nonce"),Fd(t.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),Fd(t.maxFeePerGas||0,"maxFeePerGas"),Fd(t.gasLimit,"gasLimit"),t.to||Ih,Fd(t.value,"value"),t.data,Gd(t.accessList||[]),Fd(t.maxFeePerBlobGas||0,"maxFeePerBlobGas"),jd(t.blobVersionedHashes||[],"blobVersionedHashes")];if(e&&(r.push(Fd(e.yParity,"yParity")),r.push(Ea(e.r)),r.push(Ea(e.s)),n)){if(null!=t.blobWrapperVersion){const e=Ea(t.blobWrapperVersion),s=[];for(const{proof:t}of n){const e=ta(t),n=e.length/xd;for(let t=0;t<e.length;t+=n)s.push(e.subarray(t,t+n))}return oa(["0x03",oc([r,e,n.map((t=>t.data)),n.map((t=>t.commitment)),s])])}return oa(["0x03",oc([r,n.map((t=>t.data)),n.map((t=>t.commitment)),n.map((t=>t.proof))])])}return oa(["0x03",oc(r)])}(this,n,e?this.blobs:null);case 4:return function(t,e){const n=[Fd(t.chainId,"chainId"),Fd(t.nonce,"nonce"),Fd(t.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),Fd(t.maxFeePerGas||0,"maxFeePerGas"),Fd(t.gasLimit,"gasLimit"),t.to||"0x",Fd(t.value,"value"),t.data,Gd(t.accessList||[]),(r=t.authorizationList||[],r.map((t=>[Fd(t.chainId,"chainId"),t.address,Fd(t.nonce,"nonce"),Fd(t.signature.yParity,"yParity"),Ea(t.signature.r),Ea(t.signature._s)])))];var r;return e&&(n.push(Fd(e.yParity,"yParity")),n.push(Ea(e.r)),n.push(Ea(e.s))),oa(["0x04",oc(n)])}(this,n)}qo(!1,"unsupported transaction type","UNSUPPORTED_OPERATION",{operation:".serialized"})};let Vd=class t{constructor(){Dn(this,ut),Dn(this,z,void 0),Dn(this,q,void 0),Dn(this,$,void 0),Dn(this,Q,void 0),Dn(this,J,void 0),Dn(this,Y,void 0),Dn(this,Z,void 0),Dn(this,X,void 0),Dn(this,tt,void 0),Dn(this,et,void 0),Dn(this,nt,void 0),Dn(this,rt,void 0),Dn(this,st,void 0),Dn(this,it,void 0),Dn(this,ot,void 0),Dn(this,at,void 0),Dn(this,ct,void 0),Dn(this,lt,void 0),Bn(this,z,null),Bn(this,q,null),Bn(this,Q,0),Bn(this,J,kd),Bn(this,Y,null),Bn(this,Z,null),Bn(this,X,null),Bn(this,$,"0x"),Bn(this,tt,kd),Bn(this,et,kd),Bn(this,nt,null),Bn(this,rt,null),Bn(this,st,null),Bn(this,it,null),Bn(this,ot,null),Bn(this,at,null),Bn(this,ct,null),Bn(this,lt,null)}get type(){return Pn(this,z)}set type(t){switch(t){case null:Bn(this,z,null);break;case 0:case"legacy":Bn(this,z,0);break;case 1:case"berlin":case"eip-2930":Bn(this,z,1);break;case 2:case"london":case"eip-1559":Bn(this,z,2);break;case 3:case"cancun":case"eip-4844":Bn(this,z,3);break;case 4:case"pectra":case"eip-7702":Bn(this,z,4);break;default:$o(!1,"unsupported transaction type","type",t)}}get typeName(){switch(this.type){case 0:return"legacy";case 1:return"eip-2930";case 2:return"eip-1559";case 3:return"eip-4844";case 4:return"eip-7702"}return null}get to(){const t=Pn(this,q);return null==t&&3===this.type?Ih:t}set to(t){Bn(this,q,null==t?null:$h(t))}get nonce(){return Pn(this,Q)}set nonce(t){Bn(this,Q,_a(t,"value"))}get gasLimit(){return Pn(this,J)}set gasLimit(t){Bn(this,J,ya(t))}get gasPrice(){const t=Pn(this,Y);return null!=t||0!==this.type&&1!==this.type?t:kd}set gasPrice(t){Bn(this,Y,null==t?null:ya(t,"gasPrice"))}get maxPriorityFeePerGas(){const t=Pn(this,Z);return null==t?2===this.type||3===this.type?kd:null:t}set maxPriorityFeePerGas(t){Bn(this,Z,null==t?null:ya(t,"maxPriorityFeePerGas"))}get maxFeePerGas(){const t=Pn(this,X);return null==t?2===this.type||3===this.type?kd:null:t}set maxFeePerGas(t){Bn(this,X,null==t?null:ya(t,"maxFeePerGas"))}get data(){return Pn(this,$)}set data(t){Bn(this,$,ia(t))}get value(){return Pn(this,tt)}set value(t){Bn(this,tt,ya(t,"value"))}get chainId(){return Pn(this,et)}set chainId(t){Bn(this,et,ya(t))}get signature(){return Pn(this,nt)||null}set signature(t){Bn(this,nt,null==t?null:jh.from(t))}isValid(){const t=this.signature;if(t&&!t.isValid())return!1;const e=this.authorizationList;if(e)for(const n of e)if(!n.signature.isValid())return!1;return!0}get accessList(){const t=Pn(this,rt)||null;return null==t?1===this.type||2===this.type||3===this.type?[]:null:t}set accessList(t){Bn(this,rt,null==t?null:_d(t))}get authorizationList(){const t=Pn(this,ct)||null;return null==t&&4===this.type?[]:t}set authorizationList(t){Bn(this,ct,null==t?null:t.map((t=>vd(t))))}get maxFeePerBlobGas(){const t=Pn(this,st);return null==t&&3===this.type?kd:t}set maxFeePerBlobGas(t){Bn(this,st,null==t?null:ya(t,"maxFeePerBlobGas"))}get blobVersionedHashes(){let t=Pn(this,it);return null==t&&3===this.type?[]:t}set blobVersionedHashes(t){if(null!=t){$o(Array.isArray(t),"blobVersionedHashes must be an Array","value",t),t=t.slice();for(let e=0;e<t.length;e++)$o(na(t[e],32),"invalid blobVersionedHash",`value[${e}]`,t[e])}Bn(this,it,t)}get blobs(){return null==Pn(this,at)?null:Pn(this,at).map((t=>Object.assign({},t)))}set blobs(t){if(null==t)return void Bn(this,at,null);const e=[],n=[];for(let r=0;r<t.length;r++){const s=t[r];if(ra(s)){qo(Pn(this,ot),"adding a raw blob requires a KZG library","UNSUPPORTED_OPERATION",{operation:"set blobs()"});let t=ta(s);if($o(t.length<=Nd,"blob is too large",`blobs[${r}]`,s),t.length!==Nd){const e=new Uint8Array(Nd);e.set(t),t=e}const i=Pn(this,ot).blobToKzgCommitment(t),o=ia(Pn(this,ot).computeBlobKzgProof(t,i));e.push({data:ia(t),commitment:ia(i),proof:o}),n.push(Pd(1,i))}else{const t=ia(s.data),r=ia(s.commitment),i=ia(s.proof);e.push({data:t,commitment:r,proof:i}),n.push(Pd(1,r))}}Bn(this,at,e),Bn(this,it,n)}get kzg(){return Pn(this,ot)}set kzg(t){Bn(this,ot,null==t?null:function(t){return{blobToKzgCommitment:e=>{if("computeBlobProof"in t){if("blobToKzgCommitment"in t&&"function"==typeof t.blobToKzgCommitment)return ta(t.blobToKzgCommitment(ia(e)))}else if("blobToKzgCommitment"in t&&"function"==typeof t.blobToKzgCommitment)return ta(t.blobToKzgCommitment(e));if("blobToKZGCommitment"in t&&"function"==typeof t.blobToKZGCommitment)return ta(t.blobToKZGCommitment(ia(e)));$o(!1,"unsupported KZG library","kzg",t)},computeBlobKzgProof:(e,n)=>"computeBlobProof"in t&&"function"==typeof t.computeBlobProof?ta(t.computeBlobProof(ia(e),ia(n))):"computeBlobKzgProof"in t&&"function"==typeof t.computeBlobKzgProof?t.computeBlobKzgProof(e,n):"computeBlobKZGProof"in t&&"function"==typeof t.computeBlobKZGProof?ta(t.computeBlobKZGProof(ia(e),ia(n))):void $o(!1,"unsupported KZG library","kzg",t)}}(t))}get blobWrapperVersion(){return Pn(this,lt)}set blobWrapperVersion(t){Bn(this,lt,t)}get hash(){return null==this.signature?null:Bl(Ln(this,ut,ht).call(this,!0,!1))}get unsignedHash(){return Bl(this.unsignedSerialized)}get from(){return null==this.signature?null:(t=this.unsignedHash,e=this.signature.getCanonical(),Ed(Hh.recoverPublicKey(t,e)));var t,e}get fromPublicKey(){return null==this.signature?null:Hh.recoverPublicKey(this.unsignedHash,this.signature.getCanonical())}isSigned(){return null!=this.signature}get serialized(){return Ln(this,ut,ht).call(this,!0,!0)}get unsignedSerialized(){return Ln(this,ut,ht).call(this,!1,!1)}inferType(){const t=this.inferTypes();return t.indexOf(2)>=0?2:t.pop()}inferTypes(){const t=null!=this.gasPrice,e=null!=this.maxFeePerGas||null!=this.maxPriorityFeePerGas,n=null!=this.accessList,r=null!=Pn(this,st)||Pn(this,it);null!=this.maxFeePerGas&&null!=this.maxPriorityFeePerGas&&qo(this.maxFeePerGas>=this.maxPriorityFeePerGas,"priorityFee cannot be more than maxFee","BAD_DATA",{value:this}),qo(!e||0!==this.type&&1!==this.type,"transaction type cannot have maxFeePerGas or maxPriorityFeePerGas","BAD_DATA",{value:this}),qo(0!==this.type||!n,"legacy transaction cannot have accessList","BAD_DATA",{value:this});const s=[];return null!=this.type?s.push(this.type):this.authorizationList&&this.authorizationList.length?s.push(4):e?s.push(2):t?(s.push(1),n||s.push(0)):n?(s.push(1),s.push(2)):(r&&this.to||(s.push(0),s.push(1),s.push(2)),s.push(3)),s.sort(),s}isLegacy(){return 0===this.type}isBerlin(){return 1===this.type}isLondon(){return 2===this.type}isCancun(){return 3===this.type}clone(){return t.from(this)}toJSON(){const t=t=>null==t?null:t.toString();return{type:this.type,to:this.to,data:this.data,nonce:this.nonce,gasLimit:t(this.gasLimit),gasPrice:t(this.gasPrice),maxPriorityFeePerGas:t(this.maxPriorityFeePerGas),maxFeePerGas:t(this.maxFeePerGas),value:t(this.value),chainId:t(this.chainId),sig:this.signature?this.signature.toJSON():null,accessList:this.accessList}}[Cd](){return this.toString()}toString(){const t=[],e=e=>{let n=this[e];"string"==typeof n&&(n=JSON.stringify(n)),t.push(`${e}: ${n}`)};this.type&&e("type"),e("to"),e("data"),e("nonce"),e("gasLimit"),e("value"),null!=this.chainId&&e("chainId"),this.signature&&(e("from"),t.push(`signature: ${this.signature.toString()}`));const n=this.authorizationList;if(n){const e=[];for(const t of n){const n=[];n.push(`address: ${JSON.stringify(t.address)}`),null!=t.nonce&&n.push(`nonce: ${t.nonce}`),null!=t.chainId&&n.push(`chainId: ${t.chainId}`),t.signature&&n.push(`signature: ${t.signature.toString()}`),e.push(`Authorization { ${n.join(", ")} }`)}t.push(`authorizations: [ ${e.join(", ")} ]`)}return`Transaction { ${t.join(", ")} }`}static from(e){if(null==e)return new t;if("string"==typeof e){const n=ta(e);if(n[0]>=127)return t.from(function(t){const e=nc(t);$o(Array.isArray(e)&&(9===e.length||6===e.length),"invalid field count for legacy transaction","data",t);const n={type:0,nonce:Ld(e[0],"nonce"),gasPrice:Md(e[1],"gasPrice"),gasLimit:Md(e[2],"gasLimit"),to:Dd(e[3]),value:Md(e[4],"value"),data:ia(e[5]),chainId:kd};if(6===e.length)return n;const r=Md(e[6],"v"),s=Md(e[7],"r"),i=Md(e[8],"s");if(s===kd&&i===kd)n.chainId=r;else{let t=(r-Id)/Sd;t<kd&&(t=kd),n.chainId=t,$o(t!==kd||r===Td||r===Rd,"non-canonical legacy v","v",e[6]),n.signature=jh.from({r:ua(e[7],32),s:ua(e[8],32),v:r})}return n}(n));switch(n[0]){case 1:return t.from(function(t){const e=nc(ta(t).slice(1));$o(Array.isArray(e)&&(8===e.length||11===e.length),"invalid field count for transaction type: 1","data",ia(t));const n={type:1,chainId:Md(e[0],"chainId"),nonce:Ld(e[1],"nonce"),gasPrice:Md(e[2],"gasPrice"),gasLimit:Md(e[3],"gasLimit"),to:Dd(e[4]),value:Md(e[5],"value"),data:ia(e[6]),accessList:Bd(e[7],"accessList")};return 8===e.length||Hd(n,e.slice(8)),n}(n));case 2:return t.from(function(t){const e=nc(ta(t).slice(1));$o(Array.isArray(e)&&(9===e.length||12===e.length),"invalid field count for transaction type: 2","data",ia(t));const n={type:2,chainId:Md(e[0],"chainId"),nonce:Ld(e[1],"nonce"),maxPriorityFeePerGas:Md(e[2],"maxPriorityFeePerGas"),maxFeePerGas:Md(e[3],"maxFeePerGas"),gasPrice:null,gasLimit:Md(e[4],"gasLimit"),to:Dd(e[5]),value:Md(e[6],"value"),data:ia(e[7]),accessList:Bd(e[8],"accessList")};return 9===e.length||Hd(n,e.slice(9)),n}(n));case 3:return t.from(function(t){let e=nc(ta(t).slice(1)),n="3",r=null,s=null;if(4===e.length&&Array.isArray(e[0])){n="3 (network format)";const t=e[1],r=e[2],i=e[3];$o(Array.isArray(t),"invalid network format: blobs not an array","fields[1]",t),$o(Array.isArray(r),"invalid network format: commitments not an array","fields[2]",r),$o(Array.isArray(i),"invalid network format: proofs not an array","fields[3]",i),$o(t.length===r.length,"invalid network format: blobs/commitments length mismatch","fields",e),$o(t.length===i.length,"invalid network format: blobs/proofs length mismatch","fields",e),s=[];for(let n=0;n<e[1].length;n++)s.push({data:t[n],commitment:r[n],proof:i[n]});e=e[0]}else if(5===e.length&&Array.isArray(e[0])){n="3 (EIP-7594 network format)",r=_a(e[1]);const t=e[2],i=e[3],o=e[4];$o(1===r,`unsupported EIP-7594 network format version: ${r}`,"fields[1]",r),$o(Array.isArray(t),"invalid EIP-7594 network format: blobs not an array","fields[2]",t),$o(Array.isArray(i),"invalid EIP-7594 network format: commitments not an array","fields[3]",i),$o(Array.isArray(o),"invalid EIP-7594 network format: proofs not an array","fields[4]",o),$o(t.length===i.length,"invalid network format: blobs/commitments length mismatch","fields",e),$o(t.length*xd===o.length,"invalid network format: blobs/proofs length mismatch","fields",e),s=[];for(let e=0;e<t.length;e++){const n=[];for(let t=0;t<xd;t++)n.push(o[e*xd+t]);s.push({data:t[e],commitment:i[e],proof:oa(n)})}e=e[0]}$o(Array.isArray(e)&&(11===e.length||14===e.length),`invalid field count for transaction type: ${n}`,"data",ia(t));const i={type:3,chainId:Md(e[0],"chainId"),nonce:Ld(e[1],"nonce"),maxPriorityFeePerGas:Md(e[2],"maxPriorityFeePerGas"),maxFeePerGas:Md(e[3],"maxFeePerGas"),gasPrice:null,gasLimit:Md(e[4],"gasLimit"),to:Dd(e[5]),value:Md(e[6],"value"),data:ia(e[7]),accessList:Bd(e[8],"accessList"),maxFeePerBlobGas:Md(e[9],"maxFeePerBlobGas"),blobVersionedHashes:e[10],blobWrapperVersion:r};s&&(i.blobs=s),$o(null!=i.to,`invalid address for transaction type: ${n}`,"data",t),$o(Array.isArray(i.blobVersionedHashes),"invalid blobVersionedHashes: must be an array","data",t);for(let o=0;o<i.blobVersionedHashes.length;o++)$o(na(i.blobVersionedHashes[o],32),`invalid blobVersionedHash at index ${o}: must be length 32`,"data",t);return 11===e.length||Hd(i,e.slice(11)),i}(n));case 4:return t.from(function(t){const e=nc(ta(t).slice(1));$o(Array.isArray(e)&&(10===e.length||13===e.length),"invalid field count for transaction type: 4","data",ia(t));const n={type:4,chainId:Md(e[0],"chainId"),nonce:Ld(e[1],"nonce"),maxPriorityFeePerGas:Md(e[2],"maxPriorityFeePerGas"),maxFeePerGas:Md(e[3],"maxFeePerGas"),gasPrice:null,gasLimit:Md(e[4],"gasLimit"),to:Dd(e[5]),value:Md(e[6],"value"),data:ia(e[7]),accessList:Bd(e[8],"accessList"),authorizationList:Ud(e[9],"authorizationList")};return 10===e.length||Hd(n,e.slice(10)),n}(n))}qo(!1,"unsupported transaction type","UNSUPPORTED_OPERATION",{operation:"from"})}const n=new t;return null!=e.type&&(n.type=e.type),null!=e.to&&(n.to=e.to),null!=e.nonce&&(n.nonce=e.nonce),null!=e.gasLimit&&(n.gasLimit=e.gasLimit),null!=e.gasPrice&&(n.gasPrice=e.gasPrice),null!=e.maxPriorityFeePerGas&&(n.maxPriorityFeePerGas=e.maxPriorityFeePerGas),null!=e.maxFeePerGas&&(n.maxFeePerGas=e.maxFeePerGas),null!=e.maxFeePerBlobGas&&(n.maxFeePerBlobGas=e.maxFeePerBlobGas),null!=e.data&&(n.data=e.data),null!=e.value&&(n.value=e.value),null!=e.chainId&&(n.chainId=e.chainId),null!=e.signature&&(n.signature=jh.from(e.signature)),null!=e.accessList&&(n.accessList=e.accessList),null!=e.authorizationList&&(n.authorizationList=e.authorizationList),null!=e.blobVersionedHashes&&(n.blobVersionedHashes=e.blobVersionedHashes),null!=e.kzg&&(n.kzg=e.kzg),null!=e.blobWrapperVersion&&(n.blobWrapperVersion=e.blobWrapperVersion),null!=e.blobs&&(n.blobs=e.blobs),null!=e.hash&&($o(n.isSigned(),"unsigned transaction cannot define '.hash'","tx",e),$o(n.hash===e.hash,"hash mismatch","tx",e)),null!=e.from&&($o(n.isSigned(),"unsigned transaction cannot define '.from'","tx",e),$o(n.from.toLowerCase()===(e.from||"").toLowerCase(),"from mismatch","tx",e)),n}};function Wd(t){return Bl(Da(t))}const Kd=new Map([[8217,"apostrophe"],[8260,"fraction slash"],[12539,"middle dot"]]);function zd(t){return function(t){let e=0;return()=>t[e++]}(function(t){let e=0;function n(){return t[e++]<<8|t[e++]}let r=n(),s=1,i=[0,1];for(let A=1;A<r;A++)i.push(s+=n());let o=n(),a=e;e+=o;let c=0,l=0;function u(){return 0==c&&(l=l<<8|t[e++],c=8),l>>--c&1}const h=2**31,d=h>>>1,f=d>>1,p=h-1;let g=0;for(let A=0;A<31;A++)g=g<<1|u();let m=[],y=0,w=h;for(;;){let t=Math.floor(((g-y+1)*s-1)/w),e=0,n=r;for(;n-e>1;){let r=e+n>>>1;t<i[r]?n=r:e=r}if(0==e)break;m.push(e);let o=y+Math.floor(w*i[e]/s),a=y+Math.floor(w*i[e+1]/s)-1;for(;!((o^a)&d);)g=g<<1&p|u(),o=o<<1&p,a=a<<1&p|1;for(;o&~a&f;)g=g&d|g<<1&p>>>1|u(),o=o<<1^d,a=(a^d)<<1|d|1;y=o,w=1+a-o}let b=r-4;return m.map((e=>{switch(e-b){case 3:return b+65792+(t[a++]<<16|t[a++]<<8|t[a++]);case 2:return b+256+(t[a++]<<8|t[a++]);case 1:return b+t[a++];default:return e-1}}))}(function(t){let e=[];[..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"].forEach(((t,n)=>e[t.charCodeAt(0)]=n));let n=t.length,r=new Uint8Array(6*n>>3);for(let s=0,i=0,o=0,a=0;s<n;s++)a=a<<6|e[t.charCodeAt(s)],o+=6,o>=8&&(r[i++]=a>>(o-=8));return r}(t)))}function qd(t){return 1&t?~t>>1:t>>1}function $d(t,e){let n=Array(t);for(let r=0,s=0;r<t;r++)n[r]=s+=qd(e());return n}function Qd(t,e=0){let n=[];for(;;){let r=t(),s=t();if(!s)break;e+=r;for(let t=0;t<s;t++)n.push(e+t);e+=s+1}return n}function Jd(t){return Zd((()=>{let e=Qd(t);if(e.length)return e}))}function Yd(t){let e=[];for(;;){let n=t();if(0==n)break;e.push(tf(n,t))}for(;;){let n=t()-1;if(n<0)break;e.push(ef(n,t))}return e.flat()}function Zd(t){let e=[];for(;;){let n=t(e.length);if(!n)break;e.push(n)}return e}function Xd(t,e,n){let r=Array(t).fill().map((()=>[]));for(let s=0;s<e;s++)$d(t,n).forEach(((t,e)=>r[e].push(t)));return r}function tf(t,e){let n=1+e(),r=e(),s=Zd(e);return Xd(s.length,1+t,e).flatMap(((t,e)=>{let[i,...o]=t;return Array(s[e]).fill().map(((t,e)=>{let s=e*r;return[i+e*n,o.map((t=>t+s))]}))}))}function ef(t,e){return Xd(1+e(),1+t,e).map((t=>[t[0],t.slice(1)]))}function nf(t){return`{${function(t){return t.toString(16).toUpperCase().padStart(2,"0")}(t)}}`}function rf(t){let e=t.length;if(e<4096)return String.fromCodePoint(...t);let n=[];for(let r=0;r<e;)n.push(String.fromCodePoint(...t.slice(r,r+=4096)));return n.join("")}function sf(t,e){let n=t.length,r=n-e.length;for(let s=0;0==r&&s<n;s++)r=t[s]-e[s];return r}const of=44032,af=4352,cf=4449,lf=4519,uf=28,hf=588;function df(t){return t>>24&255}function ff(t){return 16777215&t}let pf,gf,mf,yf;function wf(t){return t>=of&&t<55204}function bf(t,e){if(t>=af&&t<4371&&e>=cf&&e<4470)return of+(t-af)*hf+(e-cf)*uf;if(wf(t)&&e>lf&&e<4547&&(t-of)%uf==0)return t+(e-lf);{let n=yf.get(t);return n&&(n=n.get(e),n)?n:-1}}function Af(t){pf||function(){let t=zd("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");pf=new Map(Jd(t).flatMap(((t,e)=>t.map((t=>[t,e+1<<24]))))),gf=new Set(Qd(t)),mf=new Map,yf=new Map;for(let[e,n]of Yd(t)){if(!gf.has(e)&&2==n.length){let[t,r]=n,s=yf.get(t);s||(s=new Map,yf.set(t,s)),s.set(r,e)}mf.set(e,n.reverse())}}();let e=[],n=[],r=!1;function s(t){let n=pf.get(t);n&&(r=!0,t|=n),e.push(t)}for(let i of t)for(;;){if(i<128)e.push(i);else if(wf(i)){let t=i-of,e=t%hf/uf|0,n=t%uf;s(af+(t/hf|0)),s(cf+e),n>0&&s(lf+n)}else{let t=mf.get(i);t?n.push(...t):s(i)}if(!n.length)break;i=n.pop()}if(r&&e.length>1){let t=df(e[0]);for(let n=1;n<e.length;n++){let r=df(e[n]);if(0==r||t<=r){t=r;continue}let s=n-1;for(;;){let n=e[s+1];if(e[s+1]=e[s],e[s]=n,!s)break;if(t=df(e[--s]),t<=r)break}t=df(e[n])}}return e}function _f(t){return Af(t).map(ff)}function vf(t){return function(t){let e=[],n=[],r=-1,s=0;for(let i of t){let t=df(i),o=ff(i);if(-1==r)0==t?r=o:e.push(o);else if(s>0&&s>=t)0==t?(e.push(r,...n),n.length=0,r=o):n.push(o),s=t;else{let i=bf(r,o);i>=0?r=i:0==s&&0==t?(e.push(r),r=o):(n.push(o),s=t)}}return r>=0&&e.push(r,...n),e}(Af(t))}const Ef=".",kf=t=>Array.from(t);function Sf(t,e){return t.P.has(e)||t.Q.has(e)}class Tf extends Array{get is_emoji(){return!0}}let Rf,If,Of,Cf,Nf,xf,Pf,Df,Bf,Uf,Lf;function Mf(){if(Rf)return;let t=zd("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");const e=()=>Qd(t),n=()=>new Set(e()),r=(t,e)=>e.forEach((e=>t.add(e)));Rf=new Map(Yd(t)),If=n(),Of=e(),Cf=new Set(e().map((t=>Of[t]))),Of=new Set(Of),Nf=n(),n();let s=Jd(t),i=t();const o=()=>{let t=new Set;return e().forEach((e=>r(t,s[e]))),r(t,e()),t};xf=Zd((e=>{let n=Zd(t).map((t=>t+96));if(n.length){let r=e>=i;return n[0]-=32,n=rf(n),r&&(n=`Restricted[${n}]`),{N:n,P:o(),Q:o(),M:!t(),R:r}}})),Pf=n(),Df=new Map;let a=e().concat(kf(Pf)).sort(((t,e)=>t-e));a.forEach(((e,n)=>{let r=t(),s=a[n]=r?a[n-r]:{V:[],M:new Map};s.V.push(e),Pf.has(e)||Df.set(e,s)}));for(let{V:u,M:h}of new Set(Df.values())){let t=[];for(let n of u){let e=xf.filter((t=>Sf(t,n))),s=t.find((({G:t})=>e.some((e=>t.has(e)))));s||(s={G:new Set,V:[]},t.push(s)),s.V.push(n),r(s.G,e)}let e=t.flatMap((t=>kf(t.G)));for(let{G:n,V:r}of t){let t=new Set(e.filter((t=>!n.has(t))));for(let e of r)h.set(e,t)}}Bf=new Set;let c=new Set;const l=t=>Bf.has(t)?c.add(t):Bf.add(t);for(let u of xf){for(let t of u.P)l(t);for(let t of u.Q)l(t)}for(let u of Bf)Df.has(u)||c.has(u)||Df.set(u,1);r(Bf,_f(Bf)),Uf=function(t){let e=[],n=Qd(t);return function t({S:n,B:r},s,i){if(!(4&n&&i===s[s.length-1])){2&n&&(i=s[s.length-1]),1&n&&e.push(s);for(let e of r)for(let n of e.Q)t(e,[...s,n],i)}}(function e(r){return{S:t(),B:Zd((()=>{let r=Qd(t).map((t=>n[t]));if(r.length)return e(r)})),Q:r}}([]),[]),e}(t).map((t=>Tf.from(t))).sort(sf),Lf=new Map;for(let u of Uf){let t=[Lf];for(let e of u){let n=t.map((t=>{let n=t.get(e);return n||(n=new Map,t.set(e,n)),n}));65039===e?t.push(...n):t=n}for(let e of t)e.V=u}}function Ff(t){return(Hf(t)?"":`${Gf(jf([t]))} `)+nf(t)}function Gf(t){return`"${t}"‎`}function jf(t,e=1/0,n=nf){let r=[];var s,i;s=t[0],Mf(),(i?Cf.has(s):Of.has(s))&&r.push("◌"),t.length>e&&(e>>=1,t=[...t.slice(0,e),8230,...t.slice(-e)]);let o=0,a=t.length;for(let c=0;c<a;c++){let e=t[c];Hf(e)&&(r.push(rf(t.slice(o,c))),r.push(n(e)),o=c+1)}return r.push(rf(t.slice(o,a))),r.join("")}function Hf(t){return Mf(),Nf.has(t)}function Vf(t){return e=function(t,e,n){if(!t)return[];Mf();let r=0;return t.split(Ef).map((t=>{let s=function(t){let e=[];for(let n=0,r=t.length;n<r;){let r=t.codePointAt(n);n+=r<65536?1:2,e.push(r)}return e}(t),i={input:s,offset:r};r+=s.length+1;try{let t,r=i.tokens=function(t,e,n){let r=[],s=[];for(t=t.slice().reverse();t.length;){let i=$f(t);if(i)s.length&&(r.push(e(s)),s=[]),r.push(n(i));else{let e=t.pop();if(Bf.has(e))s.push(e);else{let t=Rf.get(e);if(t)s.push(...t);else if(!If.has(e))throw Wf(e)}}}return s.length&&r.push(e(s)),r}(s,e,n),o=r.length;if(!o)throw new Error("empty label");let a=i.output=r.flat();if(function(t){for(let e=t.lastIndexOf(95);e>0;)if(95!==t[--e])throw new Error("underscore allowed only at start")}(a),!(i.emoji=o>1||r[0].is_emoji)&&a.every((t=>t<128)))!function(t){if(t.length>=4&&45==t[2]&&45==t[3])throw new Error(`invalid label extension: "${rf(t.slice(0,4))}"`)}(a),t="ASCII";else{let e=r.flatMap((t=>t.is_emoji?[]:t));if(e.length){if(Of.has(a[0]))throw zf("leading combining mark");for(let t=1;t<o;t++){let e=r[t];if(!e.is_emoji&&Of.has(e[0]))throw zf(`emoji + combining mark: "${rf(r[t-1])} + ${jf([e[0]])}"`)}!function(t){let e=t[0],n=Kd.get(e);if(n)throw zf(`leading ${n}`);let r=t.length,s=-1;for(let i=1;i<r;i++){e=t[i];let r=Kd.get(e);if(r){if(s==i)throw zf(`${n} + ${r}`);s=i+1,n=r}}if(s==r)throw zf(`trailing ${n}`)}(a);let n=kf(new Set(e)),[s]=function(t){let e=xf;for(let n of t){let t=e.filter((t=>Sf(t,n)));if(!t.length)throw xf.some((t=>Sf(t,n)))?Kf(e[0],n):Wf(n);if(e=t,1==t.length)break}return e}(n);!function(t,e){for(let n of e)if(!Sf(t,n))throw Kf(t,n);if(t.M){let t=_f(e);for(let e=1,n=t.length;e<n;e++)if(Cf.has(t[e])){let r=e+1;for(let s;r<n&&Cf.has(s=t[r]);r++)for(let n=e;n<r;n++)if(t[n]==s)throw new Error(`duplicate non-spacing marks: ${Ff(s)}`);if(r-e>4)throw new Error(`excessive non-spacing marks: ${Gf(jf(t.slice(e-1,r)))} (${r-e}/4)`);e=r}}}(s,e),function(t,e){let n,r=[];for(let s of e){let t=Df.get(s);if(1===t)return;if(t){let e=t.M.get(s);if(n=n?n.filter((t=>e.has(t))):kf(e),!n.length)return}else r.push(s)}if(n)for(let s of n)if(r.every((t=>Sf(s,t))))throw new Error(`whole-script confusable: ${t.N}/${s.N}`)}(s,n),t=s.N}else t="Emoji"}i.type=t}catch(o){i.error=o}return i}))}(t,vf,qf),e.map((({input:t,error:n,output:r})=>{if(n){let r=n.message;throw new Error(1==e.length?r:`Invalid label ${Gf(jf(t,63))}: ${r}`)}return rf(r)})).join(Ef);var e}function Wf(t){return new Error(`disallowed character: ${Ff(t)}`)}function Kf(t,e){let n=Ff(e),r=xf.find((t=>t.P.has(e)));return r&&(n=`${r.N} ${n}`),new Error(`illegal mixture: ${t.N} + ${n}`)}function zf(t){return new Error(`illegal placement: ${t}`)}function qf(t){return t.filter((t=>65039!=t))}function $f(t,e){let n,r=Lf,s=t.length;for(;s&&(r=r.get(t[--s]),r);){let{V:i}=r;i&&(n=i,e&&e.push(...t.slice(s).reverse()),t.length=s)}return n}const Qf=new Uint8Array(32);function Jf(t){return $o(0!==t.length,"invalid ENS name; empty component","comp",t),t}function Yf(t){const e=Da(Zf(t)),n=[];if(0===t.length)return n;let r=0;for(let s=0;s<e.length;s++){46===e[s]&&(n.push(Jf(e.slice(r,s))),r=s+1)}return $o(r<e.length,"invalid ENS name; empty component","name",t),n.push(Jf(e.slice(r))),n}function Zf(t){try{if(0===t.length)throw new Error("empty label");return Vf(t)}catch(e){$o(!1,`invalid ENS name (${e.message})`,"name",t)}}function Xf(t){try{return 0!==Yf(t).length}catch(e){}return!1}function tp(t){$o("string"==typeof t,"invalid ENS name; not a string","name",t),$o(t.length,"invalid ENS name (empty label)","name",t);let e=Qf;const n=Yf(t);for(;n.length;)e=Bl(oa([e,Bl(n.pop())]));return ia(e)}function ep(t,e){const n=null!=e?e:63;return $o(n<=255,"DNS encoded label cannot exceed 255","length",n),ia(oa(Yf(t).map((e=>{$o(e.length<=n,`label ${JSON.stringify(t)} exceeds ${n} bytes`,"name",t);const r=new Uint8Array(e.length+1);return r.set(e,1),r[0]=r.length-1,r}))))+"00"}Qf.fill(0);const np=new Uint8Array(32);np.fill(0);const rp=BigInt(-1),sp=BigInt(0),ip=BigInt(1),op=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");const ap=va(ip,32),cp=va(sp,32),lp={name:"string",version:"string",chainId:"uint256",verifyingContract:"address",salt:"bytes32"},up=["name","version","chainId","verifyingContract","salt"];function hp(t){return function(e){return $o("string"==typeof e,`invalid domain value for ${JSON.stringify(t)}`,`domain.${t}`,e),e}}const dp={name:hp("name"),version:hp("version"),chainId:function(t){const e=ya(t,"domain.chainId");return $o(e>=0,"invalid chain ID","domain.chainId",t),Number.isSafeInteger(e)?Number(e):ka(e)},verifyingContract:function(t){try{return $h(t).toLowerCase()}catch(e){}$o(!1,'invalid domain value "verifyingContract"',"domain.verifyingContract",t)},salt:function(t){const e=ta(t,"domain.salt");return $o(32===e.length,'invalid domain value "salt"',"domain.salt",t),ia(e)}};function fp(t){{const e=t.match(/^(u?)int(\d+)$/);if(e){const n=""===e[1],r=parseInt(e[2]);$o(r%8==0&&0!==r&&r<=256&&e[2]===String(r),"invalid numeric width","type",t);const s=ma(op,n?r-1:r),i=n?(s+ip)*rp:sp;return function(e){const r=ya(e,"value");return $o(r>=i&&r<=s,`value out-of-bounds for ${t}`,"value",r),va(n?ga(r,256):r,32)}}}{const e=t.match(/^bytes(\d+)$/);if(e){const n=parseInt(e[1]);return $o(0!==n&&n<=32&&e[1]===String(n),"invalid bytes width","type",t),function(e){return $o(ta(e).length===n,`invalid length for ${t}`,"value",e),function(t){const e=ta(t),n=e.length%32;return n?oa([e,np.slice(n)]):ia(e)}(e)}}}switch(t){case"address":return function(t){return ua($h(t),32)};case"bool":return function(t){return t?ap:cp};case"bytes":return function(t){return Bl(t)};case"string":return function(t){return Wd(t)}}return null}function pp(t,e){return`${t}(${e.map((({name:t,type:e})=>e+" "+t)).join(",")})`}function gp(t){const e=t.match(/^([^\x5b]*)((\x5b\d*\x5d)*)(\x5b(\d*)\x5d)$/);return e?{base:e[1],index:e[2]+e[4],array:{base:e[1],prefix:e[1]+e[2],count:e[5]?parseInt(e[5]):-1}}:{base:t}}dt=new WeakMap,ft=new WeakMap,pt=new WeakMap,gt=new WeakSet,mt=function(t){{const e=fp(t);if(e)return e}const e=gp(t).array;if(e){const t=e.prefix,n=this.getEncoder(t);return r=>{$o(-1===e.count||e.count===r.length,`array length mismatch; expected length ${e.count}`,"value",r);let s=r.map(n);return Pn(this,ft).has(t)&&(s=s.map(Bl)),Bl(oa(s))}}const n=this.types[t];if(n){const e=Wd(Pn(this,ft).get(t));return t=>{const r=n.map((({name:e,type:n})=>{const r=this.getEncoder(n)(t[e]);return Pn(this,ft).has(n)?Bl(r):r}));return r.unshift(e),oa(r)}}$o(!1,`unknown type: ${t}`,"type",t)};let mp=class t{constructor(t){Dn(this,gt),Nn(this,"primaryType"),Dn(this,dt,void 0),Dn(this,ft,void 0),Dn(this,pt,void 0),Bn(this,ft,new Map),Bn(this,pt,new Map);const e=new Map,n=new Map,r=new Map,s={};Object.keys(t).forEach((i=>{s[i]=t[i].map((({name:e,type:n})=>{let{base:r,index:s}=gp(n);return"int"!==r||t.int||(r="int256"),"uint"!==r||t.uint||(r="uint256"),{name:e,type:r+(s||"")}})),e.set(i,new Set),n.set(i,[]),r.set(i,new Set)})),Bn(this,dt,JSON.stringify(s));for(const o in s){const r=new Set;for(const i of s[o]){$o(!r.has(i.name),`duplicate variable name ${JSON.stringify(i.name)} in ${JSON.stringify(o)}`,"types",t),r.add(i.name);const s=gp(i.type).base;$o(s!==o,`circular type reference to ${JSON.stringify(s)}`,"types",t);fp(s)||($o(n.has(s),`unknown type ${JSON.stringify(s)}`,"types",t),n.get(s).push(o),e.get(o).add(s))}}const i=Array.from(n.keys()).filter((t=>0===n.get(t).length));$o(0!==i.length,"missing primary type","types",t),$o(1===i.length,`ambiguous primary types or unused types: ${i.map((t=>JSON.stringify(t))).join(", ")}`,"types",t),Ho(this,{primaryType:i[0]}),function s(i,o){$o(!o.has(i),`circular type reference to ${JSON.stringify(i)}`,"types",t),o.add(i);for(const t of e.get(i))if(n.has(t)){s(t,o);for(const e of o)r.get(e).add(t)}o.delete(i)}(this.primaryType,new Set);for(const[o,a]of r){const t=Array.from(a);t.sort(),Pn(this,ft).set(o,pp(o,s[o])+t.map((t=>pp(t,s[t]))).join(""))}}get types(){return JSON.parse(Pn(this,dt))}getEncoder(t){let e=Pn(this,pt).get(t);return e||(e=Ln(this,gt,mt).call(this,t),Pn(this,pt).set(t,e)),e}encodeType(t){const e=Pn(this,ft).get(t);return $o(e,`unknown type: ${JSON.stringify(t)}`,"name",t),e}encodeData(t,e){return this.getEncoder(t)(e)}hashStruct(t,e){return Bl(this.encodeData(t,e))}encode(t){return this.encodeData(this.primaryType,t)}hash(t){return this.hashStruct(this.primaryType,t)}_visit(t,e,n){if(fp(t))return n(t,e);const r=gp(t).array;if(r)return $o(-1===r.count||r.count===e.length,`array length mismatch; expected length ${r.count}`,"value",e),e.map((t=>this._visit(r.prefix,t,n)));const s=this.types[t];if(s)return s.reduce(((t,{name:r,type:s})=>(t[r]=this._visit(s,e[r],n),t)),{});$o(!1,`unknown type: ${t}`,"type",t)}visit(t,e){return this._visit(this.primaryType,t,e)}static from(e){return new t(e)}static getPrimaryType(e){return t.from(e).primaryType}static hashStruct(e,n,r){return t.from(n).hashStruct(e,r)}static hashDomain(e){const n=[];for(const t in e){if(null==e[t])continue;const r=lp[t];$o(r,`invalid typed-data domain key: ${JSON.stringify(t)}`,"domain",e),n.push({name:t,type:r})}return n.sort(((t,e)=>up.indexOf(t.name)-up.indexOf(e.name))),t.hashStruct("EIP712Domain",{EIP712Domain:n},e)}static encode(e,n,r){return oa(["0x1901",t.hashDomain(e),t.from(n).hash(r)])}static hash(e,n,r){return Bl(t.encode(e,n,r))}static async resolveNames(e,n,r,s){e=Object.assign({},e);for(const t in e)null==e[t]&&delete e[t];const i={};e.verifyingContract&&!na(e.verifyingContract,20)&&(i[e.verifyingContract]="0x");const o=t.from(n);o.visit(r,((t,e)=>("address"!==t||na(e,20)||(i[e]="0x"),e)));for(const t in i)i[t]=await s(t);return e.verifyingContract&&i[e.verifyingContract]&&(e.verifyingContract=i[e.verifyingContract]),{domain:e,value:r=o.visit(r,((t,e)=>"address"===t&&i[e]?i[e]:e))}}static getPayload(e,n,r){t.hashDomain(e);const s={},i=[];up.forEach((t=>{const n=e[t];null!=n&&(s[t]=dp[t](n),i.push({name:t,type:lp[t]}))}));const o=t.from(n);n=o.types;const a=Object.assign({},n);return $o(null==a.EIP712Domain,"types must not contain EIP712Domain type","types.EIP712Domain",n),a.EIP712Domain=i,o.encode(r),{types:a,domain:s,primaryType:o.primaryType,message:o.visit(r,((t,e)=>{if(t.match(/^bytes(\d*)/))return ia(ta(e));if(t.match(/^u?int/))return ya(e).toString();switch(t){case"address":return e.toLowerCase();case"bool":return!!e;case"string":return $o("string"==typeof e,"invalid string","value",e),e}$o(!1,"unsupported type","type",t)}))}}};function yp(t){const e=new Set;return t.forEach((t=>e.add(t))),Object.freeze(e)}const wp=yp("external public payable override".split(" ")),bp="constant external internal payable private public pure view override",Ap=yp(bp.split(" ")),_p="constructor error event fallback function receive struct",vp=yp(_p.split(" ")),Ep="calldata memory storage payable indexed",kp=yp(Ep.split(" ")),Sp=yp([_p,Ep,"tuple returns",bp].join(" ").split(" ")),Tp={"(":"OPEN_PAREN",")":"CLOSE_PAREN","[":"OPEN_BRACKET","]":"CLOSE_BRACKET",",":"COMMA","@":"AT"},Rp=new RegExp("^(\\s*)"),Ip=new RegExp("^([0-9]+)"),Op=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"),Cp=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$"),Np=new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$"),xp=class t{constructor(t){Dn(this,bt),Dn(this,yt,void 0),Dn(this,wt,void 0),Bn(this,yt,0),Bn(this,wt,t.slice())}get offset(){return Pn(this,yt)}get length(){return Pn(this,wt).length-Pn(this,yt)}clone(){return new t(Pn(this,wt))}reset(){Bn(this,yt,0)}popKeyword(t){const e=this.peek();if("KEYWORD"!==e.type||!t.has(e.text))throw new Error(`expected keyword ${e.text}`);return this.pop().text}popType(t){if(this.peek().type!==t){const e=this.peek();throw new Error(`expected ${t}; got ${e.type} ${JSON.stringify(e.text)}`)}return this.pop().text}popParen(){const t=this.peek();if("OPEN_PAREN"!==t.type)throw new Error("bad start");const e=Ln(this,bt,At).call(this,Pn(this,yt)+1,t.match+1);return Bn(this,yt,t.match+1),e}popParams(){const t=this.peek();if("OPEN_PAREN"!==t.type)throw new Error("bad start");const e=[];for(;Pn(this,yt)<t.match-1;){const t=this.peek().linkNext;e.push(Ln(this,bt,At).call(this,Pn(this,yt)+1,t)),Bn(this,yt,t)}return Bn(this,yt,t.match+1),e}peek(){if(Pn(this,yt)>=Pn(this,wt).length)throw new Error("out-of-bounds");return Pn(this,wt)[Pn(this,yt)]}peekKeyword(t){const e=this.peekType("KEYWORD");return null!=e&&t.has(e)?e:null}peekType(t){if(0===this.length)return null;const e=this.peek();return e.type===t?e.text:null}pop(){const t=this.peek();return Un(this,yt)._++,t}toString(){const t=[];for(let e=Pn(this,yt);e<Pn(this,wt).length;e++){const n=Pn(this,wt)[e];t.push(`${n.type}:${n.text}`)}return`<TokenString ${t.join(" ")}>`}};yt=new WeakMap,wt=new WeakMap,bt=new WeakSet,At=function(t=0,e=0){return new xp(Pn(this,wt).slice(t,e).map((e=>Object.freeze(Object.assign({},e,{match:e.match-t,linkBack:e.linkBack-t,linkNext:e.linkNext-t})))))};let Pp=xp;function Dp(t){const e=[],n=e=>{const n=i<t.length?JSON.stringify(t[i]):"$EOI";throw new Error(`invalid token ${n} at ${i}: ${e}`)};let r=[],s=[],i=0;for(;i<t.length;){let o=t.substring(i),a=o.match(Rp);a&&(i+=a[1].length,o=t.substring(i));const c={depth:r.length,linkBack:-1,linkNext:-1,match:-1,type:"",text:"",offset:i,value:-1};e.push(c);let l=Tp[o[0]]||"";if(l){if(c.type=l,c.text=o[0],i++,"OPEN_PAREN"===l)r.push(e.length-1),s.push(e.length-1);else if("CLOSE_PAREN"==l)0===r.length&&n("no matching open bracket"),c.match=r.pop(),e[c.match].match=e.length-1,c.depth--,c.linkBack=s.pop(),e[c.linkBack].linkNext=e.length-1;else if("COMMA"===l)c.linkBack=s.pop(),e[c.linkBack].linkNext=e.length-1,s.push(e.length-1);else if("OPEN_BRACKET"===l)c.type="BRACKET";else if("CLOSE_BRACKET"===l){let t=e.pop().text;if(e.length>0&&"NUMBER"===e[e.length-1].type){const n=e.pop().text;t=n+t,e[e.length-1].value=_a(n)}if(0===e.length||"BRACKET"!==e[e.length-1].type)throw new Error("missing opening bracket");e[e.length-1].text+=t}}else if(a=o.match(Op),a){if(c.text=a[1],i+=c.text.length,Sp.has(c.text)){c.type="KEYWORD";continue}if(c.text.match(Np)){c.type="TYPE";continue}c.type="ID"}else{if(a=o.match(Ip),!a)throw new Error(`unexpected token ${JSON.stringify(o[0])} at position ${i}`);c.text=a[1],c.type="NUMBER",i+=c.text.length}}return new Pp(e.map((t=>Object.freeze(t))))}function Bp(t,e){let n=[];for(const r in e.keys())t.has(r)&&n.push(r);if(n.length>1)throw new Error(`conflicting types: ${n.join(", ")}`)}function Up(t,e){if(e.peekKeyword(vp)){const n=e.pop().text;if(n!==t)throw new Error(`expected ${t}, got ${n}`)}return e.popType("ID")}function Lp(t,e){const n=new Set;for(;;){const r=t.peekType("KEYWORD");if(null==r||e&&!e.has(r))break;if(t.pop(),n.has(r))throw new Error(`duplicate keywords: ${JSON.stringify(r)}`);n.add(r)}return Object.freeze(n)}function Mp(t){let e=Lp(t,Ap);return Bp(e,yp("constant payable nonpayable".split(" "))),Bp(e,yp("pure view payable nonpayable".split(" "))),e.has("view")?"view":e.has("pure")?"pure":e.has("payable")?"payable":e.has("nonpayable")?"nonpayable":e.has("constant")?"view":"nonpayable"}function Fp(t,e){return t.popParams().map((t=>Xp.from(t,e)))}function Gp(t){if(t.peekType("AT")){if(t.pop(),t.peekType("NUMBER"))return ya(t.pop().text);throw new Error("invalid gas")}return null}function jp(t){if(t.length)throw new Error(`unexpected tokens at offset ${t.offset}: ${t.toString()}`)}const Hp=new RegExp(/^(.*)\[([0-9]*)\]$/);function Vp(t){const e=t.match(Np);if($o(e,"invalid type","type",t),"uint"===t)return"uint256";if("int"===t)return"int256";if(e[2]){const n=parseInt(e[2]);$o(0!==n&&n<=32,"invalid bytes length","type",t)}else if(e[3]){const n=parseInt(e[3]);$o(0!==n&&n<=256&&n%8==0,"invalid numeric width","type",t)}return t}const Wp={},Kp=Symbol.for("_ethers_internal"),zp="_ParamTypeInternal",qp="_ErrorInternal",$p="_EventInternal",Qp="_ConstructorInternal",Jp="_FallbackInternal",Yp="_FunctionInternal",Zp="_StructInternal";_t=new WeakSet,vt=function(t,e,n,r){if(this.isArray()){if(!Array.isArray(e))throw new Error("invalid array value");if(-1!==this.arrayLength&&e.length!==this.arrayLength)throw new Error("array is wrong length");const s=this.arrayChildren,i=e.slice();return i.forEach(((e,r)=>{var o;Ln(o=s,_t,vt).call(o,t,e,n,(t=>{i[r]=t}))})),void r(i)}if(this.isTuple()){const s=this.components;let i;if(Array.isArray(e))i=e.slice();else{if(null==e||"object"!=typeof e)throw new Error("invalid tuple value");i=s.map((t=>{if(!t.name)throw new Error("cannot use object value with unnamed components");if(!(t.name in e))throw new Error(`missing value for component ${t.name}`);return e[t.name]}))}if(i.length!==this.components.length)throw new Error("array is wrong length");return i.forEach(((e,r)=>{var o;Ln(o=s[r],_t,vt).call(o,t,e,n,(t=>{i[r]=t}))})),void r(i)}const s=n(this.type,e);s.then?t.push(async function(){r(await s)}()):r(s)};let Xp=class t{constructor(t,e,n,r,s,i,o,a){if(Dn(this,_t),Nn(this,"name"),Nn(this,"type"),Nn(this,"baseType"),Nn(this,"indexed"),Nn(this,"components"),Nn(this,"arrayLength"),Nn(this,"arrayChildren"),Zo(t,Wp,"ParamType"),Object.defineProperty(this,Kp,{value:zp}),i&&(i=Object.freeze(i.slice())),"array"===r){if(null==o||null==a)throw new Error("")}else if(null!=o||null!=a)throw new Error("");if("tuple"===r){if(null==i)throw new Error("")}else if(null!=i)throw new Error("");Ho(this,{name:e,type:n,baseType:r,indexed:s,components:i,arrayLength:o,arrayChildren:a})}format(t){if(null==t&&(t="sighash"),"json"===t){const e=this.name||"";if(this.isArray()){const t=JSON.parse(this.arrayChildren.format("json"));return t.name=e,t.type+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`,JSON.stringify(t)}const n={type:"tuple"===this.baseType?"tuple":this.type,name:e};return"boolean"==typeof this.indexed&&(n.indexed=this.indexed),this.isTuple()&&(n.components=this.components.map((e=>JSON.parse(e.format(t))))),JSON.stringify(n)}let e="";return this.isArray()?(e+=this.arrayChildren.format(t),e+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`):this.isTuple()?e+="("+this.components.map((e=>e.format(t))).join("full"===t?", ":",")+")":e+=this.type,"sighash"!==t&&(!0===this.indexed&&(e+=" indexed"),"full"===t&&this.name&&(e+=" "+this.name)),e}isArray(){return"array"===this.baseType}isTuple(){return"tuple"===this.baseType}isIndexable(){return null!=this.indexed}walk(t,e){if(this.isArray()){if(!Array.isArray(t))throw new Error("invalid array value");if(-1!==this.arrayLength&&t.length!==this.arrayLength)throw new Error("array is wrong length");const n=this;return t.map((t=>n.arrayChildren.walk(t,e)))}if(this.isTuple()){if(!Array.isArray(t))throw new Error("invalid tuple value");if(t.length!==this.components.length)throw new Error("array is wrong length");const n=this;return t.map(((t,r)=>n.components[r].walk(t,e)))}return e(this.type,t)}async walkAsync(t,e){const n=[],r=[t];return Ln(this,_t,vt).call(this,n,t,e,(t=>{r[0]=t})),n.length&&await Promise.all(n),r[0]}static from(e,n){if(t.isParamType(e))return e;if("string"==typeof e)try{return t.from(Dp(e),n)}catch(a){$o(!1,"invalid param type","obj",e)}else if(e instanceof Pp){let r="",s="",i=null;Lp(e,yp(["tuple"])).has("tuple")||e.peekType("OPEN_PAREN")?(s="tuple",i=e.popParams().map((e=>t.from(e))),r=`tuple(${i.map((t=>t.format())).join(",")})`):(r=Vp(e.popType("TYPE")),s=r);let o=null,a=null;for(;e.length&&e.peekType("BRACKET");){const n=e.pop();o=new t(Wp,"",r,s,null,i,a,o),a=n.value,r+=n.text,s="array",i=null}let c=null;if(Lp(e,kp).has("indexed")){if(!n)throw new Error("");c=!0}const l=e.peekType("ID")?e.pop().text:"";if(e.length)throw new Error("leftover tokens");return new t(Wp,l,r,s,c,i,a,o)}const r=e.name;$o(!r||"string"==typeof r&&r.match(Cp),"invalid name","obj.name",r);let s=e.indexed;null!=s&&($o(n,"parameter cannot be indexed","obj.indexed",e.indexed),s=!!s);let i=e.type,o=i.match(Hp);if(o){const n=parseInt(o[2]||"-1"),a=t.from({type:o[1],components:e.components});return new t(Wp,r||"",i,"array",s,null,n,a)}if("tuple"===i||i.startsWith("tuple(")||i.startsWith("(")){const n=null!=e.components?e.components.map((e=>t.from(e))):null;return new t(Wp,r||"",i,"tuple",s,n,null,null)}return i=Vp(e.type),new t(Wp,r||"",i,i,s,null,null,null)}static isParamType(t){return t&&t[Kp]===zp}};class tg{constructor(t,e,n){Nn(this,"type"),Nn(this,"inputs"),Zo(t,Wp,"Fragment"),Ho(this,{type:e,inputs:n=Object.freeze(n.slice())})}static from(t){if("string"==typeof t){try{tg.from(JSON.parse(t))}catch(e){}return tg.from(Dp(t))}if(t instanceof Pp){switch(t.peekKeyword(vp)){case"constructor":return ig.from(t);case"error":return rg.from(t);case"event":return sg.from(t);case"fallback":case"receive":return og.from(t);case"function":return ag.from(t);case"struct":return cg.from(t)}}else if("object"==typeof t){switch(t.type){case"constructor":return ig.from(t);case"error":return rg.from(t);case"event":return sg.from(t);case"fallback":case"receive":return og.from(t);case"function":return ag.from(t);case"struct":return cg.from(t)}qo(!1,`unsupported type: ${t.type}`,"UNSUPPORTED_OPERATION",{operation:"Fragment.from"})}$o(!1,"unsupported frgament object","obj",t)}static isConstructor(t){return ig.isFragment(t)}static isError(t){return rg.isFragment(t)}static isEvent(t){return sg.isFragment(t)}static isFunction(t){return ag.isFragment(t)}static isStruct(t){return cg.isFragment(t)}}class eg extends tg{constructor(t,e,n,r){super(t,e,r),Nn(this,"name"),$o("string"==typeof n&&n.match(Cp),"invalid identifier","name",n),r=Object.freeze(r.slice()),Ho(this,{name:n})}}function ng(t,e){return"("+e.map((e=>e.format(t))).join("full"===t?", ":",")+")"}class rg extends eg{constructor(t,e,n){super(t,"error",e,n),Object.defineProperty(this,Kp,{value:qp})}get selector(){return Wd(this.format("sighash")).substring(0,10)}format(t){if(null==t&&(t="sighash"),"json"===t)return JSON.stringify({type:"error",name:this.name,inputs:this.inputs.map((e=>JSON.parse(e.format(t))))});const e=[];return"sighash"!==t&&e.push("error"),e.push(this.name+ng(t,this.inputs)),e.join(" ")}static from(t){if(rg.isFragment(t))return t;if("string"==typeof t)return rg.from(Dp(t));if(t instanceof Pp){const e=Up("error",t),n=Fp(t);return jp(t),new rg(Wp,e,n)}return new rg(Wp,t.name,t.inputs?t.inputs.map(Xp.from):[])}static isFragment(t){return t&&t[Kp]===qp}}class sg extends eg{constructor(t,e,n,r){super(t,"event",e,n),Nn(this,"anonymous"),Object.defineProperty(this,Kp,{value:$p}),Ho(this,{anonymous:r})}get topicHash(){return Wd(this.format("sighash"))}format(t){if(null==t&&(t="sighash"),"json"===t)return JSON.stringify({type:"event",anonymous:this.anonymous,name:this.name,inputs:this.inputs.map((e=>JSON.parse(e.format(t))))});const e=[];return"sighash"!==t&&e.push("event"),e.push(this.name+ng(t,this.inputs)),"sighash"!==t&&this.anonymous&&e.push("anonymous"),e.join(" ")}static getTopicHash(t,e){e=(e||[]).map((t=>Xp.from(t)));return new sg(Wp,t,e,!1).topicHash}static from(t){if(sg.isFragment(t))return t;if("string"==typeof t)try{return sg.from(Dp(t))}catch(e){$o(!1,"invalid event fragment","obj",t)}else if(t instanceof Pp){const e=Up("event",t),n=Fp(t,!0),r=!!Lp(t,yp(["anonymous"])).has("anonymous");return jp(t),new sg(Wp,e,n,r)}return new sg(Wp,t.name,t.inputs?t.inputs.map((t=>Xp.from(t,!0))):[],!!t.anonymous)}static isFragment(t){return t&&t[Kp]===$p}}class ig extends tg{constructor(t,e,n,r,s){super(t,e,n),Nn(this,"payable"),Nn(this,"gas"),Object.defineProperty(this,Kp,{value:Qp}),Ho(this,{payable:r,gas:s})}format(t){if(qo(null!=t&&"sighash"!==t,"cannot format a constructor for sighash","UNSUPPORTED_OPERATION",{operation:"format(sighash)"}),"json"===t)return JSON.stringify({type:"constructor",stateMutability:this.payable?"payable":"undefined",payable:this.payable,gas:null!=this.gas?this.gas:void 0,inputs:this.inputs.map((e=>JSON.parse(e.format(t))))});const e=[`constructor${ng(t,this.inputs)}`];return this.payable&&e.push("payable"),null!=this.gas&&e.push(`@${this.gas.toString()}`),e.join(" ")}static from(t){if(ig.isFragment(t))return t;if("string"==typeof t)try{return ig.from(Dp(t))}catch(e){$o(!1,"invalid constuctor fragment","obj",t)}else if(t instanceof Pp){Lp(t,yp(["constructor"]));const e=Fp(t),n=!!Lp(t,wp).has("payable"),r=Gp(t);return jp(t),new ig(Wp,"constructor",e,n,r)}return new ig(Wp,"constructor",t.inputs?t.inputs.map(Xp.from):[],!!t.payable,null!=t.gas?t.gas:null)}static isFragment(t){return t&&t[Kp]===Qp}}class og extends tg{constructor(t,e,n){super(t,"fallback",e),Nn(this,"payable"),Object.defineProperty(this,Kp,{value:Jp}),Ho(this,{payable:n})}format(t){const e=0===this.inputs.length?"receive":"fallback";if("json"===t){const t=this.payable?"payable":"nonpayable";return JSON.stringify({type:e,stateMutability:t})}return`${e}()${this.payable?" payable":""}`}static from(t){if(og.isFragment(t))return t;if("string"==typeof t)try{return og.from(Dp(t))}catch(e){$o(!1,"invalid fallback fragment","obj",t)}else if(t instanceof Pp){const e=t.toString();$o(t.peekKeyword(yp(["fallback","receive"])),"type must be fallback or receive","obj",e);if("receive"===t.popKeyword(yp(["fallback","receive"]))){const e=Fp(t);return $o(0===e.length,"receive cannot have arguments","obj.inputs",e),Lp(t,yp(["payable"])),jp(t),new og(Wp,[],!0)}let n=Fp(t);n.length?$o(1===n.length&&"bytes"===n[0].type,"invalid fallback inputs","obj.inputs",n.map((t=>t.format("minimal"))).join(", ")):n=[Xp.from("bytes")];const r=Mp(t);if($o("nonpayable"===r||"payable"===r,"fallback cannot be constants","obj.stateMutability",r),Lp(t,yp(["returns"])).has("returns")){const e=Fp(t);$o(1===e.length&&"bytes"===e[0].type,"invalid fallback outputs","obj.outputs",e.map((t=>t.format("minimal"))).join(", "))}return jp(t),new og(Wp,n,"payable"===r)}if("receive"===t.type)return new og(Wp,[],!0);if("fallback"===t.type){const e=[Xp.from("bytes")],n="payable"===t.stateMutability;return new og(Wp,e,n)}$o(!1,"invalid fallback description","obj",t)}static isFragment(t){return t&&t[Kp]===Jp}}class ag extends eg{constructor(t,e,n,r,s,i){super(t,"function",e,r),Nn(this,"constant"),Nn(this,"outputs"),Nn(this,"stateMutability"),Nn(this,"payable"),Nn(this,"gas"),Object.defineProperty(this,Kp,{value:Yp});Ho(this,{constant:"view"===n||"pure"===n,gas:i,outputs:s=Object.freeze(s.slice()),payable:"payable"===n,stateMutability:n})}get selector(){return Wd(this.format("sighash")).substring(0,10)}format(t){if(null==t&&(t="sighash"),"json"===t)return JSON.stringify({type:"function",name:this.name,constant:this.constant,stateMutability:"nonpayable"!==this.stateMutability?this.stateMutability:void 0,payable:this.payable,gas:null!=this.gas?this.gas:void 0,inputs:this.inputs.map((e=>JSON.parse(e.format(t)))),outputs:this.outputs.map((e=>JSON.parse(e.format(t))))});const e=[];return"sighash"!==t&&e.push("function"),e.push(this.name+ng(t,this.inputs)),"sighash"!==t&&("nonpayable"!==this.stateMutability&&e.push(this.stateMutability),this.outputs&&this.outputs.length&&(e.push("returns"),e.push(ng(t,this.outputs))),null!=this.gas&&e.push(`@${this.gas.toString()}`)),e.join(" ")}static getSelector(t,e){e=(e||[]).map((t=>Xp.from(t)));return new ag(Wp,t,"view",e,[],null).selector}static from(t){if(ag.isFragment(t))return t;if("string"==typeof t)try{return ag.from(Dp(t))}catch(n){$o(!1,"invalid function fragment","obj",t)}else if(t instanceof Pp){const e=Up("function",t),n=Fp(t),r=Mp(t);let s=[];Lp(t,yp(["returns"])).has("returns")&&(s=Fp(t));const i=Gp(t);return jp(t),new ag(Wp,e,r,n,s,i)}let e=t.stateMutability;return null==e&&(e="payable","boolean"==typeof t.constant?(e="view",t.constant||(e="payable","boolean"!=typeof t.payable||t.payable||(e="nonpayable"))):"boolean"!=typeof t.payable||t.payable||(e="nonpayable")),new ag(Wp,t.name,e,t.inputs?t.inputs.map(Xp.from):[],t.outputs?t.outputs.map(Xp.from):[],null!=t.gas?t.gas:null)}static isFragment(t){return t&&t[Kp]===Yp}}class cg extends eg{constructor(t,e,n){super(t,"struct",e,n),Object.defineProperty(this,Kp,{value:Zp})}format(){throw new Error("@TODO")}static from(t){if("string"==typeof t)try{return cg.from(Dp(t))}catch(e){$o(!1,"invalid struct fragment","obj",t)}else if(t instanceof Pp){const e=Up("struct",t),n=Fp(t);return jp(t),new cg(Wp,e,n)}return new cg(Wp,t.name,t.inputs?t.inputs.map(Xp.from):[])}static isFragment(t){return t&&t[Kp]===Zp}}const lg=new Map;lg.set(0,"GENERIC_PANIC"),lg.set(1,"ASSERT_FALSE"),lg.set(17,"OVERFLOW"),lg.set(18,"DIVIDE_BY_ZERO"),lg.set(33,"ENUM_RANGE_ERROR"),lg.set(34,"BAD_STORAGE_DATA"),lg.set(49,"STACK_UNDERFLOW"),lg.set(50,"ARRAY_RANGE_ERROR"),lg.set(65,"OUT_OF_MEMORY"),lg.set(81,"UNINITIALIZED_FUNCTION_CALL");const ug=new RegExp(/^bytes([0-9]*)$/),hg=new RegExp(/^(u?int)([0-9]*)$/);let dg=null,fg=1024;Et=new WeakSet,kt=function(t){if(t.isArray())return new ad(Ln(this,Et,kt).call(this,t.arrayChildren),t.arrayLength,t.name);if(t.isTuple())return new bd(t.components.map((t=>Ln(this,Et,kt).call(this,t))),t.name);switch(t.baseType){case"address":return new rd(t.name);case"bool":return new cd(t.name);case"string":return new wd(t.name);case"bytes":return new ud(t.name);case"":return new fd(t.name)}let e=t.type.match(hg);if(e){let n=parseInt(e[2]||"256");return $o(0!==n&&n<=256&&n%8==0,"invalid "+e[1]+" bit length","param",t),new yd(n/8,"int"===e[1],t.name)}if(e=t.type.match(ug),e){let n=parseInt(e[1]);return $o(0!==n&&n<=32,"invalid bytes length","param",t),new hd(n,t.name)}$o(!1,"invalid type","type",t.type)};let pg=class t{constructor(){Dn(this,Et)}getDefaultValue(t){const e=t.map((t=>Ln(this,Et,kt).call(this,Xp.from(t))));return new bd(e,"_").defaultValue()}encode(t,e){Qo(e.length,t.length,"types/values length mismatch");const n=t.map((t=>Ln(this,Et,kt).call(this,Xp.from(t)))),r=new bd(n,"_"),s=new Ac;return r.encode(s,e),s.data}decode(t,e,n){const r=t.map((t=>Ln(this,Et,kt).call(this,Xp.from(t))));return new bd(r,"_").decode(new _c(e,n,fg))}static _setDefaultMaxInflation(t){$o("number"==typeof t&&Number.isInteger(t),"invalid defaultMaxInflation factor","value",t),fg=t}static defaultAbiCoder(){return null==dg&&(dg=new t),dg}static getBuiltinCallException(e,n,r){return function(t,e,n,r){let s="missing revert data",i=null,o=null;if(n){s="execution reverted";const t=ta(n);if(n=ia(n),0===t.length)s+=" (no data present; likely require(false) occurred",i="require(false)";else if(t.length%32!=4)s+=" (could not decode reason; invalid data length)";else if("0x08c379a0"===ia(t.slice(0,4)))try{i=r.decode(["string"],t.slice(4))[0],o={signature:"Error(string)",name:"Error",args:[i]},s+=`: ${JSON.stringify(i)}`}catch(c){s+=" (could not decode reason; invalid string data)"}else if("0x4e487b71"===ia(t.slice(0,4)))try{const e=Number(r.decode(["uint256"],t.slice(4))[0]);o={signature:"Panic(uint256)",name:"Panic",args:[e]},i=`Panic due to ${lg.get(e)||"UNKNOWN"}(${e})`,s+=`: ${i}`}catch(c){s+=" (could not decode panic code)"}else s+=" (unknown custom error)"}const a={to:e.to?$h(e.to):null,data:e.data||"0x"};return e.from&&(a.from=$h(e.from)),zo(s,"CALL_EXCEPTION",{action:t,data:n,reason:i,transaction:a,invocation:null,revert:o})}(e,n,r,t.defaultAbiCoder())}};class gg{constructor(t,e,n){Nn(this,"fragment"),Nn(this,"name"),Nn(this,"signature"),Nn(this,"topic"),Nn(this,"args");const r=t.name,s=t.format();Ho(this,{fragment:t,name:r,signature:s,topic:e,args:n})}}class mg{constructor(t,e,n,r){Nn(this,"fragment"),Nn(this,"name"),Nn(this,"args"),Nn(this,"signature"),Nn(this,"selector"),Nn(this,"value");const s=t.name,i=t.format();Ho(this,{fragment:t,name:s,args:n,signature:i,selector:e,value:r})}}class yg{constructor(t,e,n){Nn(this,"fragment"),Nn(this,"name"),Nn(this,"args"),Nn(this,"signature"),Nn(this,"selector");const r=t.name,s=t.format();Ho(this,{fragment:t,name:r,args:n,signature:s,selector:e})}}class wg{constructor(t){Nn(this,"hash"),Nn(this,"_isIndexed"),Ho(this,{hash:t,_isIndexed:!0})}static isIndexed(t){return!(!t||!t._isIndexed)}}const bg={0:"generic panic",1:"assert(false)",17:"arithmetic overflow",18:"division or modulo by zero",33:"enum overflow",34:"invalid encoded storage byte array accessed",49:"out-of-bounds array access; popping on an empty array",50:"out-of-bounds access of an array or bytesN",65:"out of memory",81:"uninitialized function"},Ag={"0x08c379a0":{signature:"Error(string)",name:"Error",inputs:["string"],reason:t=>`reverted with reason string ${JSON.stringify(t)}`},"0x4e487b71":{signature:"Panic(uint256)",name:"Panic",inputs:["uint256"],reason:t=>{let e="unknown panic code";return t>=0&&t<=255&&bg[t.toString()]&&(e=bg[t.toString()]),`reverted with panic code 0x${t.toString(16)} (${e})`}}};St=new WeakMap,Tt=new WeakMap,Rt=new WeakMap,It=new WeakMap,Ot=new WeakSet,Ct=function(t,e,n){if(na(t)){const e=t.toLowerCase();for(const t of Pn(this,Rt).values())if(e===t.selector)return t;return null}if(-1===t.indexOf("(")){const r=[];for(const[e,n]of Pn(this,Rt))e.split("(")[0]===t&&r.push(n);if(e){const t=e.length>0?e[e.length-1]:null;let n=e.length,s=!0;nd.isTyped(t)&&"overrides"===t.type&&(s=!1,n--);for(let e=r.length-1;e>=0;e--){const t=r[e].inputs.length;t===n||s&&t===n-1||r.splice(e,1)}for(let i=r.length-1;i>=0;i--){const t=r[i].inputs;for(let n=0;n<e.length;n++)if(nd.isTyped(e[n])){if(n>=t.length){if("overrides"===e[n].type)continue;r.splice(i,1);break}if(e[n].type!==t[n].baseType){r.splice(i,1);break}}}}if(1===r.length&&e&&e.length!==r[0].inputs.length){const t=e[e.length-1];(null==t||Array.isArray(t)||"object"!=typeof t)&&r.splice(0,1)}if(0===r.length)return null;if(r.length>1&&n){$o(!1,`ambiguous function description (i.e. matches ${r.map((t=>JSON.stringify(t.format()))).join(", ")})`,"key",t)}return r[0]}const r=Pn(this,Rt).get(ag.from(t).format());return r||null},Nt=new WeakSet,xt=function(t,e,n){if(na(t)){const e=t.toLowerCase();for(const t of Pn(this,Tt).values())if(e===t.topicHash)return t;return null}if(-1===t.indexOf("(")){const r=[];for(const[e,n]of Pn(this,Tt))e.split("(")[0]===t&&r.push(n);if(e){for(let t=r.length-1;t>=0;t--)r[t].inputs.length<e.length&&r.splice(t,1);for(let t=r.length-1;t>=0;t--){const n=r[t].inputs;for(let s=0;s<e.length;s++)if(nd.isTyped(e[s])&&e[s].type!==n[s].baseType){r.splice(t,1);break}}}if(0===r.length)return null;if(r.length>1&&n){$o(!1,`ambiguous event description (i.e. matches ${r.map((t=>JSON.stringify(t.format()))).join(", ")})`,"key",t)}return r[0]}const r=Pn(this,Tt).get(sg.from(t).format());return r||null};let _g=class t{constructor(t){Dn(this,Ot),Dn(this,Nt),Nn(this,"fragments"),Nn(this,"deploy"),Nn(this,"fallback"),Nn(this,"receive"),Dn(this,St,void 0),Dn(this,Tt,void 0),Dn(this,Rt,void 0),Dn(this,It,void 0);let e=[];e="string"==typeof t?JSON.parse(t):t,Bn(this,Rt,new Map),Bn(this,St,new Map),Bn(this,Tt,new Map);const n=[];for(const o of e)try{n.push(tg.from(o))}catch(i){console.log(`[Warning] Invalid Fragment ${JSON.stringify(o)}:`,i.message)}Ho(this,{fragments:Object.freeze(n)});let r=null,s=!1;Bn(this,It,this.getAbiCoder()),this.fragments.forEach(((t,e)=>{let n;switch(t.type){case"constructor":return this.deploy?void console.log("duplicate definition - constructor"):void Ho(this,{deploy:t});case"fallback":return void(0===t.inputs.length?s=!0:($o(!r||t.payable!==r.payable,"conflicting fallback fragments",`fragments[${e}]`,t),r=t,s=r.payable));case"function":n=Pn(this,Rt);break;case"event":n=Pn(this,Tt);break;case"error":n=Pn(this,St);break;default:return}const i=t.format();n.has(i)||n.set(i,t)})),this.deploy||Ho(this,{deploy:ig.from("constructor()")}),Ho(this,{fallback:r,receive:s})}format(t){const e=t?"minimal":"full";return this.fragments.map((t=>t.format(e)))}formatJson(){const t=this.fragments.map((t=>t.format("json")));return JSON.stringify(t.map((t=>JSON.parse(t))))}getAbiCoder(){return pg.defaultAbiCoder()}getFunctionName(t){const e=Ln(this,Ot,Ct).call(this,t,null,!1);return $o(e,"no matching function","key",t),e.name}hasFunction(t){return!!Ln(this,Ot,Ct).call(this,t,null,!1)}getFunction(t,e){return Ln(this,Ot,Ct).call(this,t,e||null,!0)}forEachFunction(t){const e=Array.from(Pn(this,Rt).keys());e.sort(((t,e)=>t.localeCompare(e)));for(let n=0;n<e.length;n++){const r=e[n];t(Pn(this,Rt).get(r),n)}}getEventName(t){const e=Ln(this,Nt,xt).call(this,t,null,!1);return $o(e,"no matching event","key",t),e.name}hasEvent(t){return!!Ln(this,Nt,xt).call(this,t,null,!1)}getEvent(t,e){return Ln(this,Nt,xt).call(this,t,e||null,!0)}forEachEvent(t){const e=Array.from(Pn(this,Tt).keys());e.sort(((t,e)=>t.localeCompare(e)));for(let n=0;n<e.length;n++){const r=e[n];t(Pn(this,Tt).get(r),n)}}getError(t,e){if(na(t)){const e=t.toLowerCase();if(Ag[e])return rg.from(Ag[e].signature);for(const t of Pn(this,St).values())if(e===t.selector)return t;return null}if(-1===t.indexOf("(")){const e=[];for(const[n,r]of Pn(this,St))n.split("(")[0]===t&&e.push(r);if(0===e.length)return"Error"===t?rg.from("error Error(string)"):"Panic"===t?rg.from("error Panic(uint256)"):null;if(e.length>1){$o(!1,`ambiguous error description (i.e. ${e.map((t=>JSON.stringify(t.format()))).join(", ")})`,"name",t)}return e[0]}if("Error(string)"===(t=rg.from(t).format()))return rg.from("error Error(string)");if("Panic(uint256)"===t)return rg.from("error Panic(uint256)");const n=Pn(this,St).get(t);return n||null}forEachError(t){const e=Array.from(Pn(this,St).keys());e.sort(((t,e)=>t.localeCompare(e)));for(let n=0;n<e.length;n++){const r=e[n];t(Pn(this,St).get(r),n)}}_decodeParams(t,e){return Pn(this,It).decode(t,e)}_encodeParams(t,e){return Pn(this,It).encode(t,e)}encodeDeploy(t){return this._encodeParams(this.deploy.inputs,t||[])}decodeErrorResult(t,e){if("string"==typeof t){const e=this.getError(t);$o(e,"unknown error","fragment",t),t=e}return $o(ca(e,0,4)===t.selector,`data signature does not match error ${t.name}.`,"data",e),this._decodeParams(t.inputs,ca(e,4))}encodeErrorResult(t,e){if("string"==typeof t){const e=this.getError(t);$o(e,"unknown error","fragment",t),t=e}return oa([t.selector,this._encodeParams(t.inputs,e||[])])}decodeFunctionData(t,e){if("string"==typeof t){const e=this.getFunction(t);$o(e,"unknown function","fragment",t),t=e}return $o(ca(e,0,4)===t.selector,`data signature does not match function ${t.name}.`,"data",e),this._decodeParams(t.inputs,ca(e,4))}encodeFunctionData(t,e){if("string"==typeof t){const e=this.getFunction(t);$o(e,"unknown function","fragment",t),t=e}return oa([t.selector,this._encodeParams(t.inputs,e||[])])}decodeFunctionResult(t,e){if("string"==typeof t){const e=this.getFunction(t);$o(e,"unknown function","fragment",t),t=e}let n="invalid length for result data";const r=ea(e);if(r.length%32==0)try{return Pn(this,It).decode(t.outputs,r)}catch(s){n="could not decode result data"}qo(!1,n,"BAD_DATA",{value:ia(r),info:{method:t.name,signature:t.format()}})}makeError(t,e){const n=ta(t,"data"),r=pg.getBuiltinCallException("call",e,n);if(r.message.startsWith("execution reverted (unknown custom error)")){const t=ia(n.slice(0,4)),e=this.getError(t);if(e)try{const t=Pn(this,It).decode(e.inputs,n.slice(4));r.revert={name:e.name,signature:e.format(),args:t},r.reason=r.revert.signature,r.message=`execution reverted: ${r.reason}`}catch(i){r.message="execution reverted (coult not decode custom error)"}}const s=this.parseTransaction(e);return s&&(r.invocation={method:s.name,signature:s.signature,args:s.args}),r}encodeFunctionResult(t,e){if("string"==typeof t){const e=this.getFunction(t);$o(e,"unknown function","fragment",t),t=e}return ia(Pn(this,It).encode(t.outputs,e||[]))}encodeFilterTopics(t,e){if("string"==typeof t){const e=this.getEvent(t);$o(e,"unknown event","eventFragment",t),t=e}qo(e.length<=t.inputs.length,`too many arguments for ${t.format()}`,"UNEXPECTED_ARGUMENT",{count:e.length,expectedCount:t.inputs.length});const n=[];t.anonymous||n.push(t.topicHash);const r=(t,e)=>"string"===t.type?Wd(e):"bytes"===t.type?Bl(ia(e)):("bool"===t.type&&"boolean"==typeof e?e=e?"0x01":"0x00":t.type.match(/^u?int/)?e=va(e):t.type.match(/^bytes/)?e=ha(e,32):"address"===t.type&&Pn(this,It).encode(["address"],[e]),ua(ia(e),32));for(e.forEach(((e,s)=>{const i=t.inputs[s];i.indexed?null==e?n.push(null):"array"===i.baseType||"tuple"===i.baseType?$o(!1,"filtering with tuples or arrays not supported","contract."+i.name,e):Array.isArray(e)?n.push(e.map((t=>r(i,t)))):n.push(r(i,e)):$o(null==e,"cannot filter non-indexed parameters; must be null","contract."+i.name,e)}));n.length&&null===n[n.length-1];)n.pop();return n}encodeEventLog(t,e){if("string"==typeof t){const e=this.getEvent(t);$o(e,"unknown event","eventFragment",t),t=e}const n=[],r=[],s=[];return t.anonymous||n.push(t.topicHash),$o(e.length===t.inputs.length,"event arguments/values mismatch","values",e),t.inputs.forEach(((t,i)=>{const o=e[i];if(t.indexed)if("string"===t.type)n.push(Wd(o));else if("bytes"===t.type)n.push(Bl(o));else{if("tuple"===t.baseType||"array"===t.baseType)throw new Error("not implemented");n.push(Pn(this,It).encode([t.type],[o]))}else r.push(t),s.push(o)})),{data:Pn(this,It).encode(r,s),topics:n}}decodeEventLog(t,e,n){if("string"==typeof t){const e=this.getEvent(t);$o(e,"unknown event","eventFragment",t),t=e}if(null!=n&&!t.anonymous){const e=t.topicHash;$o(na(n[0],32)&&n[0].toLowerCase()===e,"fragment/topic mismatch","topics[0]",n[0]),n=n.slice(1)}const r=[],s=[],i=[];t.inputs.forEach(((t,e)=>{t.indexed?"string"===t.type||"bytes"===t.type||"tuple"===t.baseType||"array"===t.baseType?(r.push(Xp.from({type:"bytes32",name:t.name})),i.push(!0)):(r.push(t),i.push(!1)):(s.push(t),i.push(!1))}));const o=null!=n?Pn(this,It).decode(r,oa(n)):null,a=Pn(this,It).decode(s,e,!0),c=[],l=[];let u=0,h=0;return t.inputs.forEach(((t,e)=>{let n=null;if(t.indexed)if(null==o)n=new wg(null);else if(i[e])n=new wg(o[h++]);else try{n=o[h++]}catch(r){n=r}else try{n=a[u++]}catch(r){n=r}c.push(n),l.push(t.name||null)})),yc.fromItems(c,l)}parseTransaction(t){const e=ta(t.data,"tx.data"),n=ya(null!=t.value?t.value:0,"tx.value"),r=this.getFunction(ia(e.slice(0,4)));if(!r)return null;const s=Pn(this,It).decode(r.inputs,e.slice(4));return new mg(r,r.selector,s,n)}parseCallResult(t){throw new Error("@TODO")}parseLog(t){const e=this.getEvent(t.topics[0]);return!e||e.anonymous?null:new gg(e,e.topicHash,this.decodeEventLog(e,t.data,t.topics))}parseError(t){const e=ia(t),n=this.getError(ca(e,0,4));if(!n)return null;const r=Pn(this,It).decode(n.inputs,ca(e,4));return new yg(n,n.selector,r)}static from(e){return e instanceof t?e:"string"==typeof e?new t(JSON.parse(e)):"function"==typeof e.formatJson?new t(e.formatJson()):"function"==typeof e.format?new t(e.format("json")):new t(e)}};const vg=BigInt(0);function Eg(t){return null==t?null:t}function kg(t){return null==t?null:t.toString()}class Sg{constructor(t,e,n){Nn(this,"gasPrice"),Nn(this,"maxFeePerGas"),Nn(this,"maxPriorityFeePerGas"),Ho(this,{gasPrice:Eg(t),maxFeePerGas:Eg(e),maxPriorityFeePerGas:Eg(n)})}toJSON(){const{gasPrice:t,maxFeePerGas:e,maxPriorityFeePerGas:n}=this;return{_type:"FeeData",gasPrice:kg(t),maxFeePerGas:kg(e),maxPriorityFeePerGas:kg(n)}}}function Tg(t){const e={};t.to&&(e.to=t.to),t.from&&(e.from=t.from),t.data&&(e.data=ia(t.data));const n="chainId,gasLimit,gasPrice,maxFeePerBlobGas,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/);for(const s of n)s in t&&null!=t[s]&&(e[s]=ya(t[s],`request.${s}`));const r="type,nonce".split(/,/);for(const s of r)s in t&&null!=t[s]&&(e[s]=_a(t[s],`request.${s}`));return t.accessList&&(e.accessList=_d(t.accessList)),t.authorizationList&&(e.authorizationList=t.authorizationList.slice()),"blockTag"in t&&(e.blockTag=t.blockTag),"enableCcipRead"in t&&(e.enableCcipRead=!!t.enableCcipRead),"customData"in t&&(e.customData=t.customData),"blobVersionedHashes"in t&&t.blobVersionedHashes&&(e.blobVersionedHashes=t.blobVersionedHashes.slice()),"kzg"in t&&(e.kzg=t.kzg),"blobWrapperVersion"in t&&(e.blobWrapperVersion=t.blobWrapperVersion),"blobs"in t&&t.blobs&&(e.blobs=t.blobs.map((t=>ra(t)?ia(t):Object.assign({},t)))),e}class Rg{constructor(t,e){Nn(this,"provider"),Nn(this,"number"),Nn(this,"hash"),Nn(this,"timestamp"),Nn(this,"parentHash"),Nn(this,"parentBeaconBlockRoot"),Nn(this,"nonce"),Nn(this,"difficulty"),Nn(this,"gasLimit"),Nn(this,"gasUsed"),Nn(this,"stateRoot"),Nn(this,"receiptsRoot"),Nn(this,"transactionsRoot"),Nn(this,"blobGasUsed"),Nn(this,"excessBlobGas"),Nn(this,"miner"),Nn(this,"prevRandao"),Nn(this,"extraData"),Nn(this,"baseFeePerGas"),Dn(this,Pt,void 0),Bn(this,Pt,t.transactions.map((t=>"string"!=typeof t?new Cg(t,e):t))),Ho(this,{provider:e,hash:Eg(t.hash),number:t.number,timestamp:t.timestamp,parentHash:t.parentHash,parentBeaconBlockRoot:t.parentBeaconBlockRoot,nonce:t.nonce,difficulty:t.difficulty,gasLimit:t.gasLimit,gasUsed:t.gasUsed,blobGasUsed:t.blobGasUsed,excessBlobGas:t.excessBlobGas,miner:t.miner,prevRandao:Eg(t.prevRandao),extraData:t.extraData,baseFeePerGas:Eg(t.baseFeePerGas),stateRoot:t.stateRoot,receiptsRoot:t.receiptsRoot,transactionsRoot:t.transactionsRoot})}get transactions(){return Pn(this,Pt).map((t=>"string"==typeof t?t:t.hash))}get prefetchedTransactions(){const t=Pn(this,Pt).slice();return 0===t.length?[]:(qo("object"==typeof t[0],"transactions were not prefetched with block request","UNSUPPORTED_OPERATION",{operation:"transactionResponses()"}),t)}toJSON(){const{baseFeePerGas:t,difficulty:e,extraData:n,gasLimit:r,gasUsed:s,hash:i,miner:o,prevRandao:a,nonce:c,number:l,parentHash:u,parentBeaconBlockRoot:h,stateRoot:d,receiptsRoot:f,transactionsRoot:p,timestamp:g,transactions:m}=this;return{_type:"Block",baseFeePerGas:kg(t),difficulty:kg(e),extraData:n,gasLimit:kg(r),gasUsed:kg(s),blobGasUsed:kg(this.blobGasUsed),excessBlobGas:kg(this.excessBlobGas),hash:i,miner:o,prevRandao:a,nonce:c,number:l,parentHash:u,timestamp:g,parentBeaconBlockRoot:h,stateRoot:d,receiptsRoot:f,transactionsRoot:p,transactions:m}}[Symbol.iterator](){let t=0;const e=this.transactions;return{next:()=>t<this.length?{value:e[t++],done:!1}:{value:void 0,done:!0}}}get length(){return Pn(this,Pt).length}get date(){return null==this.timestamp?null:new Date(1e3*this.timestamp)}async getTransaction(t){let e;if("number"==typeof t)e=Pn(this,Pt)[t];else{const n=t.toLowerCase();for(const t of Pn(this,Pt)){if("string"==typeof t){if(t!==n)continue;e=t;break}if(t.hash===n){e=t;break}}}if(null==e)throw new Error("no such tx");return"string"==typeof e?await this.provider.getTransaction(e):e}getPrefetchedTransaction(t){const e=this.prefetchedTransactions;if("number"==typeof t)return e[t];t=t.toLowerCase();for(const n of e)if(n.hash===t)return n;$o(!1,"no matching transaction","indexOrHash",t)}isMined(){return!!this.hash}isLondon(){return!!this.baseFeePerGas}orphanedEvent(){if(!this.isMined())throw new Error("");return{orphan:"drop-block",hash:(t=this).hash,number:t.number};var t}}Pt=new WeakMap;class Ig{constructor(t,e){Nn(this,"provider"),Nn(this,"transactionHash"),Nn(this,"blockHash"),Nn(this,"blockNumber"),Nn(this,"removed"),Nn(this,"address"),Nn(this,"data"),Nn(this,"topics"),Nn(this,"index"),Nn(this,"transactionIndex"),this.provider=e;const n=Object.freeze(t.topics.slice());Ho(this,{transactionHash:t.transactionHash,blockHash:t.blockHash,blockNumber:t.blockNumber,removed:t.removed,address:t.address,data:t.data,topics:n,index:t.index,transactionIndex:t.transactionIndex})}toJSON(){const{address:t,blockHash:e,blockNumber:n,data:r,index:s,removed:i,topics:o,transactionHash:a,transactionIndex:c}=this;return{_type:"log",address:t,blockHash:e,blockNumber:n,data:r,index:s,removed:i,topics:o,transactionHash:a,transactionIndex:c}}async getBlock(){const t=await this.provider.getBlock(this.blockHash);return qo(!!t,"failed to find transaction","UNKNOWN_ERROR",{}),t}async getTransaction(){const t=await this.provider.getTransaction(this.transactionHash);return qo(!!t,"failed to find transaction","UNKNOWN_ERROR",{}),t}async getTransactionReceipt(){const t=await this.provider.getTransactionReceipt(this.transactionHash);return qo(!!t,"failed to find transaction receipt","UNKNOWN_ERROR",{}),t}removedEvent(){return{orphan:"drop-log",log:{transactionHash:(t=this).transactionHash,blockHash:t.blockHash,blockNumber:t.blockNumber,address:t.address,data:t.data,topics:Object.freeze(t.topics.slice()),index:t.index}};var t}}class Og{constructor(t,e){Nn(this,"provider"),Nn(this,"to"),Nn(this,"from"),Nn(this,"contractAddress"),Nn(this,"hash"),Nn(this,"index"),Nn(this,"blockHash"),Nn(this,"blockNumber"),Nn(this,"logsBloom"),Nn(this,"gasUsed"),Nn(this,"blobGasUsed"),Nn(this,"cumulativeGasUsed"),Nn(this,"gasPrice"),Nn(this,"blobGasPrice"),Nn(this,"type"),Nn(this,"status"),Nn(this,"root"),Dn(this,Dt,void 0),Bn(this,Dt,Object.freeze(t.logs.map((t=>new Ig(t,e)))));let n=vg;null!=t.effectiveGasPrice?n=t.effectiveGasPrice:null!=t.gasPrice&&(n=t.gasPrice),Ho(this,{provider:e,to:t.to,from:t.from,contractAddress:t.contractAddress,hash:t.hash,index:t.index,blockHash:t.blockHash,blockNumber:t.blockNumber,logsBloom:t.logsBloom,gasUsed:t.gasUsed,cumulativeGasUsed:t.cumulativeGasUsed,blobGasUsed:t.blobGasUsed,gasPrice:n,blobGasPrice:t.blobGasPrice,type:t.type,status:t.status,root:t.root})}get logs(){return Pn(this,Dt)}toJSON(){const{to:t,from:e,contractAddress:n,hash:r,index:s,blockHash:i,blockNumber:o,logsBloom:a,logs:c,status:l,root:u}=this;return{_type:"TransactionReceipt",blockHash:i,blockNumber:o,contractAddress:n,cumulativeGasUsed:kg(this.cumulativeGasUsed),from:e,gasPrice:kg(this.gasPrice),blobGasUsed:kg(this.blobGasUsed),blobGasPrice:kg(this.blobGasPrice),gasUsed:kg(this.gasUsed),hash:r,index:s,logs:c,logsBloom:a,root:u,status:l,to:t}}get length(){return this.logs.length}[Symbol.iterator](){let t=0;return{next:()=>t<this.length?{value:this.logs[t++],done:!1}:{value:void 0,done:!0}}}get fee(){return this.gasUsed*this.gasPrice}async getBlock(){const t=await this.provider.getBlock(this.blockHash);if(null==t)throw new Error("TODO");return t}async getTransaction(){const t=await this.provider.getTransaction(this.hash);if(null==t)throw new Error("TODO");return t}async getResult(){return await this.provider.getTransactionResult(this.hash)}async confirmations(){return await this.provider.getBlockNumber()-this.blockNumber+1}removedEvent(){return xg(this)}reorderedEvent(t){return qo(!t||t.isMined(),"unmined 'other' transction cannot be orphaned","UNSUPPORTED_OPERATION",{operation:"reorderedEvent(other)"}),Ng(this,t)}}Dt=new WeakMap;Bt=new WeakMap;let Cg=class t{constructor(t,e){Nn(this,"provider"),Nn(this,"blockNumber"),Nn(this,"blockHash"),Nn(this,"index"),Nn(this,"hash"),Nn(this,"type"),Nn(this,"to"),Nn(this,"from"),Nn(this,"nonce"),Nn(this,"gasLimit"),Nn(this,"gasPrice"),Nn(this,"maxPriorityFeePerGas"),Nn(this,"maxFeePerGas"),Nn(this,"maxFeePerBlobGas"),Nn(this,"data"),Nn(this,"value"),Nn(this,"chainId"),Nn(this,"signature"),Nn(this,"accessList"),Nn(this,"blobVersionedHashes"),Nn(this,"authorizationList"),Dn(this,Bt,void 0),this.provider=e,this.blockNumber=null!=t.blockNumber?t.blockNumber:null,this.blockHash=null!=t.blockHash?t.blockHash:null,this.hash=t.hash,this.index=t.index,this.type=t.type,this.from=t.from,this.to=t.to||null,this.gasLimit=t.gasLimit,this.nonce=t.nonce,this.data=t.data,this.value=t.value,this.gasPrice=t.gasPrice,this.maxPriorityFeePerGas=null!=t.maxPriorityFeePerGas?t.maxPriorityFeePerGas:null,this.maxFeePerGas=null!=t.maxFeePerGas?t.maxFeePerGas:null,this.maxFeePerBlobGas=null!=t.maxFeePerBlobGas?t.maxFeePerBlobGas:null,this.chainId=t.chainId,this.signature=t.signature,this.accessList=null!=t.accessList?t.accessList:null,this.blobVersionedHashes=null!=t.blobVersionedHashes?t.blobVersionedHashes:null,this.authorizationList=null!=t.authorizationList?t.authorizationList:null,Bn(this,Bt,-1)}toJSON(){const{blockNumber:t,blockHash:e,index:n,hash:r,type:s,to:i,from:o,nonce:a,data:c,signature:l,accessList:u,blobVersionedHashes:h}=this;return{_type:"TransactionResponse",accessList:u,blockNumber:t,blockHash:e,blobVersionedHashes:h,chainId:kg(this.chainId),data:c,from:o,gasLimit:kg(this.gasLimit),gasPrice:kg(this.gasPrice),hash:r,maxFeePerGas:kg(this.maxFeePerGas),maxPriorityFeePerGas:kg(this.maxPriorityFeePerGas),maxFeePerBlobGas:kg(this.maxFeePerBlobGas),nonce:a,signature:l,to:i,index:n,type:s,value:kg(this.value)}}async getBlock(){let t=this.blockNumber;if(null==t){const e=await this.getTransaction();e&&(t=e.blockNumber)}if(null==t)return null;const e=this.provider.getBlock(t);if(null==e)throw new Error("TODO");return e}async getTransaction(){return this.provider.getTransaction(this.hash)}async confirmations(){if(null==this.blockNumber){const{tx:t,blockNumber:e}=await jo({tx:this.getTransaction(),blockNumber:this.provider.getBlockNumber()});return null==t||null==t.blockNumber?0:e-t.blockNumber+1}return await this.provider.getBlockNumber()-this.blockNumber+1}async wait(t,e){const n=null==t?1:t,r=null==e?0:e;let s=Pn(this,Bt),i=-1,o=-1===s;const a=async()=>{if(o)return null;const{blockNumber:t,nonce:e}=await jo({blockNumber:this.provider.getBlockNumber(),nonce:this.provider.getTransactionCount(this.from)});if(e<this.nonce)return void(s=t);if(o)return null;const r=await this.getTransaction();if(!r||null==r.blockNumber)for(-1===i&&(i=s-3,i<Pn(this,Bt)&&(i=Pn(this,Bt)));i<=t;){if(o)return null;const e=await this.provider.getBlock(i,!0);if(null==e)return;for(const t of e)if(t===this.hash)return;for(let r=0;r<e.length;r++){const i=await e.getTransaction(r);if(i.from===this.from&&i.nonce===this.nonce){if(o)return null;const e=await this.provider.getTransactionReceipt(i.hash);if(null==e)return;if(t-e.blockNumber+1<n)return;let r="replaced";i.data===this.data&&i.to===this.to&&i.value===this.value?r="repriced":"0x"===i.data&&i.from===i.to&&i.value===vg&&(r="cancelled"),qo(!1,"transaction was replaced","TRANSACTION_REPLACED",{cancelled:"replaced"===r||"cancelled"===r,reason:r,replacement:i.replaceableTransaction(s),hash:i.hash,receipt:e})}}i++}},c=t=>{if(null==t||0!==t.status)return t;qo(!1,"transaction execution reverted","CALL_EXCEPTION",{action:"sendTransaction",data:null,reason:null,invocation:null,revert:null,transaction:{to:t.to,from:t.from,data:""},receipt:t})},l=await this.provider.getTransactionReceipt(this.hash);if(0===n)return c(l);if(l){if(1===n||await l.confirmations()>=n)return c(l)}else if(await a(),0===n)return null;const u=new Promise(((t,e)=>{const i=[],l=()=>{i.forEach((t=>t()))};if(i.push((()=>{o=!0})),r>0){const t=setTimeout((()=>{l(),e(zo("wait for transaction timeout","TIMEOUT"))}),r);i.push((()=>{clearTimeout(t)}))}const u=async r=>{if(await r.confirmations()>=n){l();try{t(c(r))}catch(s){e(s)}}};if(i.push((()=>{this.provider.off(this.hash,u)})),this.provider.on(this.hash,u),s>=0){const t=async()=>{try{await a()}catch(n){if(Wo(n,"TRANSACTION_REPLACED"))return l(),void e(n)}o||this.provider.once("block",t)};i.push((()=>{this.provider.off("block",t)})),this.provider.once("block",t)}}));return await u}isMined(){return null!=this.blockHash}isLegacy(){return 0===this.type}isBerlin(){return 1===this.type}isLondon(){return 2===this.type}isCancun(){return 3===this.type}removedEvent(){return qo(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),xg(this)}reorderedEvent(t){return qo(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),qo(!t||t.isMined(),"unmined 'other' transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),Ng(this,t)}replaceableTransaction(e){$o(Number.isInteger(e)&&e>=0,"invalid startBlock","startBlock",e);const n=new t(this,this.provider);return Bn(n,Bt,e),n}};function Ng(t,e){return{orphan:"reorder-transaction",tx:t,other:e}}function xg(t){return{orphan:"drop-transaction",tx:t}}class Pg extends Ig{constructor(t,e,n){super(t,t.provider),Nn(this,"interface"),Nn(this,"fragment"),Nn(this,"args");Ho(this,{args:e.decodeEventLog(n,t.data,t.topics),fragment:n,interface:e})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}class Dg extends Ig{constructor(t,e){super(t,t.provider),Nn(this,"error"),Ho(this,{error:e})}}class Bg extends Og{constructor(t,e,n){super(n,e),Dn(this,Ut,void 0),Bn(this,Ut,t)}get logs(){return super.logs.map((t=>{const e=t.topics.length?Pn(this,Ut).getEvent(t.topics[0]):null;if(e)try{return new Pg(t,Pn(this,Ut),e)}catch(n){return new Dg(t,n)}return t}))}}Ut=new WeakMap;class Ug extends Cg{constructor(t,e,n){super(n,e),Dn(this,Lt,void 0),Bn(this,Lt,t)}async wait(t,e){const n=await super.wait(t,e);return null==n?null:new Bg(Pn(this,Lt),this.provider,n)}}Lt=new WeakMap;class Lg extends Na{constructor(t,e,n,r){super(t,e,n),Nn(this,"log"),Ho(this,{log:r})}async getBlock(){return await this.log.getBlock()}async getTransaction(){return await this.log.getTransaction()}async getTransactionReceipt(){return await this.log.getTransactionReceipt()}}class Mg extends Lg{constructor(t,e,n,r,s){super(t,e,n,new Pg(s,t.interface,r));Ho(this,{args:t.interface.decodeEventLog(r,this.log.data,this.log.topics),fragment:r})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}const Fg=BigInt(0);function Gg(t){return t&&"function"==typeof t.call}function jg(t){return t&&"function"==typeof t.estimateGas}function Hg(t){return t&&"function"==typeof t.resolveName}function Vg(t){return t&&"function"==typeof t.sendTransaction}function Wg(t){if(null!=t){if(Hg(t))return t;if(t.provider)return t.provider}}class Kg{constructor(t,e,n){if(Dn(this,Mt,void 0),Nn(this,"fragment"),Ho(this,{fragment:e}),e.inputs.length<n.length)throw new Error("too many arguments");const r=zg(t.runner,"resolveName"),s=Hg(r)?r:null;Bn(this,Mt,async function(){const r=await Promise.all(e.inputs.map(((t,e)=>null==n[e]?null:t.walkAsync(n[e],((t,e)=>"address"===t?Array.isArray(e)?Promise.all(e.map((t=>Yh(t,s)))):Yh(e,s):e)))));return t.interface.encodeFilterTopics(e,r)}())}getTopicFilter(){return Pn(this,Mt)}}function zg(t,e){return null==t?null:"function"==typeof t[e]?t:t.provider&&"function"==typeof t.provider[e]?t.provider:null}function qg(t){return null==t?null:t.provider||null}async function $g(t,e){const n=nd.dereference(t,"overrides");$o("object"==typeof n,"invalid overrides parameter","overrides",t);const r=Tg(n);return $o(null==r.to||(e||[]).indexOf("to")>=0,"cannot override to","overrides.to",r.to),$o(null==r.data||(e||[]).indexOf("data")>=0,"cannot override data","overrides.data",r.data),r.from&&(r.from=r.from),r}function Qg(t){const e=async function(e){const n=await $g(e,["data"]);n.to=await t.getAddress(),n.from&&(n.from=await Yh(n.from,Wg(t.runner)));const r=t.interface,s=ya(n.value||Fg,"overrides.value")===Fg,i="0x"===(n.data||"0x");!r.fallback||r.fallback.payable||!r.receive||i||s||$o(!1,"cannot send data to receive or send value to non-payable fallback","overrides",e),$o(r.fallback||i,"cannot send data to receive-only contract","overrides.data",n.data);return $o(r.receive||r.fallback&&r.fallback.payable||s,"cannot send value to non-payable fallback","overrides.value",n.value),$o(r.fallback||i,"cannot send data to receive-only contract","overrides.data",n.data),n},n=async function(n){const r=t.runner;qo(Vg(r),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const s=await r.sendTransaction(await e(n)),i=qg(t.runner);return new Ug(t.interface,i,s)},r=async t=>await n(t);return Ho(r,{_contract:t,estimateGas:async function(n){const r=zg(t.runner,"estimateGas");return qo(jg(r),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await r.estimateGas(await e(n))},populateTransaction:e,send:n,staticCall:async function(n){const r=zg(t.runner,"call");qo(Gg(r),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const s=await e(n);try{return await r.call(s)}catch(i){if(Ko(i)&&i.data)throw t.interface.makeError(i.data,s);throw i}}}),r}function Jg(t,e){const n=function(...n){const r=t.interface.getFunction(e,n);return qo(r,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:e,args:n}}),r},r=async function(...e){const r=n(...e);let s={};if(r.inputs.length+1===e.length&&(s=await $g(e.pop()),s.from&&(s.from=await Yh(s.from,Wg(t.runner)))),r.inputs.length!==e.length)throw new Error("internal error: fragment inputs doesn't match arguments; should not happen");const i=await async function(t,e,n){const r=zg(t,"resolveName"),s=Hg(r)?r:null;return await Promise.all(e.map(((t,e)=>t.walkAsync(n[e],((t,e)=>(e=nd.dereference(e,t),"address"===t?Yh(e,s):e))))))}(t.runner,r.inputs,e);return Object.assign({},s,await jo({to:t.getAddress(),data:t.interface.encodeFunctionData(r,i)}))},s=async function(...t){const e=await o(...t);return 1===e.length?e[0]:e},i=async function(...e){const n=t.runner;qo(Vg(n),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const s=await n.sendTransaction(await r(...e)),i=qg(t.runner);return new Ug(t.interface,i,s)},o=async function(...e){const s=zg(t.runner,"call");qo(Gg(s),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const i=await r(...e);let o="0x";try{o=await s.call(i)}catch(c){if(Ko(c)&&c.data)throw t.interface.makeError(c.data,i);throw c}const a=n(...e);return t.interface.decodeFunctionResult(a,o)},a=async(...t)=>n(...t).constant?await s(...t):await i(...t);return Ho(a,{name:t.interface.getFunctionName(e),_contract:t,_key:e,getFragment:n,estimateGas:async function(...e){const n=zg(t.runner,"estimateGas");return qo(jg(n),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await n.estimateGas(await r(...e))},populateTransaction:r,send:i,staticCall:s,staticCallResult:o}),Object.defineProperty(a,"fragment",{configurable:!1,enumerable:!0,get:()=>{const n=t.interface.getFunction(e);return qo(n,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:e}}),n}}),a}Mt=new WeakMap;const Yg=Symbol.for("_ethersInternal_contract"),Zg=new WeakMap;function Xg(t){return Zg.get(t[Yg])}async function tm(t,e){let n,r=null;if(Array.isArray(e)){const r=function(e){if(na(e,32))return e;const n=t.interface.getEvent(e);return $o(n,"unknown fragment","name",e),n.topicHash};n=e.map((t=>null==t?null:Array.isArray(t)?t.map(r):r(t)))}else"*"===e?n=[null]:"string"==typeof e?na(e,32)?n=[e]:(r=t.interface.getEvent(e),$o(r,"unknown fragment","event",e),n=[r.topicHash]):(s=e)&&"object"==typeof s&&"getTopicFilter"in s&&"function"==typeof s.getTopicFilter&&s.fragment?n=await e.getTopicFilter():"fragment"in e?(r=e.fragment,n=[r.topicHash]):$o(!1,"unknown event name","event",e);var s;n=n.map((t=>{if(null==t)return null;if(Array.isArray(t)){const e=Array.from(new Set(t.map((t=>t.toLowerCase()))).values());return 1===e.length?e[0]:(e.sort(),e)}return t.toLowerCase()}));return{fragment:r,tag:n.map((t=>null==t?"null":Array.isArray(t)?t.join("|"):t)).join("&"),topics:n}}async function em(t,e){const{subs:n}=Xg(t);return n.get((await tm(t,e)).tag)||null}async function nm(t,e,n){const r=qg(t.runner);qo(r,"contract runner does not support subscribing","UNSUPPORTED_OPERATION",{operation:e});const{fragment:s,tag:i,topics:o}=await tm(t,n),{addr:a,subs:c}=Xg(t);let l=c.get(i);if(!l){const e={address:a||t,topics:o},u=e=>{let r=s;if(null==r)try{r=t.interface.getEvent(e.topics[0])}catch(i){}if(r){const i=r,o=s?t.interface.decodeEventLog(s,e.data,e.topics):[];sm(t,n,o,(r=>new Mg(t,r,n,i,e)))}else sm(t,n,[],(r=>new Lg(t,r,n,e)))};let h=[];l={tag:i,listeners:[],start:()=>{h.length||h.push(r.on(e,u))},stop:async()=>{if(0==h.length)return;let t=h;h=[],await Promise.all(t),r.off(e,u)}},c.set(i,l)}return l}let rm=Promise.resolve();async function sm(t,e,n,r){try{await rm}catch(i){}const s=async function(t,e,n,r){await rm;const s=await em(t,e);if(!s)return!1;const o=s.listeners.length;return s.listeners=s.listeners.filter((({listener:e,once:s})=>{const o=Array.from(n);r&&o.push(r(s?null:e));try{e.call(t,...o)}catch(i){}return!s})),0===s.listeners.length&&(s.stop(),Xg(t).subs.delete(s.tag)),o>0}(t,e,n,r);return rm=s,await s}const im=["then"];Ft=Yg;let om=class t{constructor(t,e,n,r){Nn(this,"target"),Nn(this,"interface"),Nn(this,"runner"),Nn(this,"filters"),Nn(this,Ft),Nn(this,"fallback"),$o("string"==typeof t||Qh(t),"invalid value for Contract target","target",t),null==n&&(n=null);const s=_g.from(e);let i;Ho(this,{target:t,runner:n,interface:s}),Object.defineProperty(this,Yg,{value:{}});let o=null,a=null;if(r){const t=qg(n);a=new Ug(this.interface,t,r)}let c=new Map;if("string"==typeof t)if(na(t))o=t,i=Promise.resolve(t);else{const e=zg(n,"resolveName");if(!Hg(e))throw zo("contract runner does not support name resolution","UNSUPPORTED_OPERATION",{operation:"resolveName"});i=e.resolveName(t).then((e=>{if(null==e)throw zo("an ENS name used for a contract target must be correctly configured","UNCONFIGURED_NAME",{value:t});return Xg(this).addr=e,e}))}else i=t.getAddress().then((t=>{if(null==t)throw new Error("TODO");return Xg(this).addr=t,t}));var l,u;l=this,u={addrPromise:i,addr:o,deployTx:a,subs:c},Zg.set(l[Yg],u);return Ho(this,{filters:new Proxy({},{get:(t,e,n)=>{if("symbol"==typeof e||im.indexOf(e)>=0)return Reflect.get(t,e,n);try{return this.getEvent(e)}catch(r){if(!Wo(r,"INVALID_ARGUMENT")||"key"!==r.argument)throw r}},has:(t,e)=>im.indexOf(e)>=0?Reflect.has(t,e):Reflect.has(t,e)||this.interface.hasEvent(String(e))})}),Ho(this,{fallback:s.receive||s.fallback?Qg(this):null}),new Proxy(this,{get:(t,e,n)=>{if("symbol"==typeof e||e in t||im.indexOf(e)>=0)return Reflect.get(t,e,n);try{return t.getFunction(e)}catch(r){if(!Wo(r,"INVALID_ARGUMENT")||"key"!==r.argument)throw r}},has:(t,e)=>"symbol"==typeof e||e in t||im.indexOf(e)>=0?Reflect.has(t,e):t.interface.hasFunction(e)})}connect(e){return new t(this.target,this.interface,e)}attach(e){return new t(e,this.interface,this.runner)}async getAddress(){return await Xg(this).addrPromise}async getDeployedCode(){const t=qg(this.runner);qo(t,"runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"getDeployedCode"});const e=await t.getCode(await this.getAddress());return"0x"===e?null:e}async waitForDeployment(){const t=this.deploymentTransaction();if(t)return await t.wait(),this;if(null!=await this.getDeployedCode())return this;const e=qg(this.runner);return qo(null!=e,"contract runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"waitForDeployment"}),new Promise(((t,n)=>{const r=async()=>{try{if(null!=await this.getDeployedCode())return t(this);e.once("block",r)}catch(s){n(s)}};r()}))}deploymentTransaction(){return Xg(this).deployTx}getFunction(t){"string"!=typeof t&&(t=t.format());return Jg(this,t)}getEvent(t){return"string"!=typeof t&&(t=t.format()),function(t,e){const n=function(...n){const r=t.interface.getEvent(e,n);return qo(r,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:e,args:n}}),r},r=function(...e){return new Kg(t,n(...e),e)};return Ho(r,{name:t.interface.getEventName(e),_contract:t,_key:e,getFragment:n}),Object.defineProperty(r,"fragment",{configurable:!1,enumerable:!0,get:()=>{const n=t.interface.getEvent(e);return qo(n,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:e}}),n}}),r}(this,t)}async queryTransaction(t){throw new Error("@TODO")}async queryFilter(t,e,n){null==e&&(e=0),null==n&&(n="latest");const{addr:r,addrPromise:s}=Xg(this),i=r||await s,{fragment:o,topics:a}=await tm(this,t),c={address:i,topics:a,fromBlock:e,toBlock:n},l=qg(this.runner);return qo(l,"contract runner does not have a provider","UNSUPPORTED_OPERATION",{operation:"queryFilter"}),(await l.getLogs(c)).map((t=>{let e=o;if(null==e)try{e=this.interface.getEvent(t.topics[0])}catch(n){}if(e)try{return new Pg(t,this.interface,e)}catch(n){return new Dg(t,n)}return new Ig(t,l)}))}async on(t,e){const n=await nm(this,"on",t);return n.listeners.push({listener:e,once:!1}),n.start(),this}async once(t,e){const n=await nm(this,"once",t);return n.listeners.push({listener:e,once:!0}),n.start(),this}async emit(t,...e){return await sm(this,t,e,null)}async listenerCount(t){if(t){const e=await em(this,t);return e?e.listeners.length:0}const{subs:e}=Xg(this);let n=0;for(const{listeners:r}of e.values())n+=r.length;return n}async listeners(t){if(t){const e=await em(this,t);return e?e.listeners.map((({listener:t})=>t)):[]}const{subs:e}=Xg(this);let n=[];for(const{listeners:r}of e.values())n=n.concat(r.map((({listener:t})=>t)));return n}async off(t,e){const n=await em(this,t);if(!n)return this;if(e){const t=n.listeners.map((({listener:t})=>t)).indexOf(e);t>=0&&n.listeners.splice(t,1)}return null!=e&&0!==n.listeners.length||(n.stop(),Xg(this).subs.delete(n.tag)),this}async removeAllListeners(t){if(t){const e=await em(this,t);if(!e)return this;e.stop(),Xg(this).subs.delete(e.tag)}else{const{subs:t}=Xg(this);for(const{tag:e,stop:n}of t.values())n(),t.delete(e)}return this}async addListener(t,e){return await this.on(t,e)}async removeListener(t,e){return await this.off(t,e)}static buildClass(e){return class extends t{constructor(t,n=null){super(t,e,n)}}}static from(t,e,n){null==n&&(n=null);return new this(t,e,n)}};class am extends(function(){return om}()){}const cm=BigInt(60);function lm(t){return t.match(/^ipfs:\/\/ipfs\//i)?t=t.substring(12):t.match(/^ipfs:\/\//i)?t=t.substring(7):$o(!1,"unsupported IPFS format","link",t),`https://gateway.ipfs.io/ipfs/${t}`}class um{constructor(t){Nn(this,"name"),Ho(this,{name:t})}connect(t){return this}supportsCoinType(t){return!1}async encodeAddress(t,e){throw new Error("unsupported coin")}async decodeAddress(t,e){throw new Error("unsupported coin")}}const hm=new RegExp("^(ipfs)://(.*)$","i"),dm=[new RegExp("^(https)://(.*)$","i"),new RegExp("^(data):(.*)$","i"),hm,new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$","i")];function fm(t){return t===cm||t>=2147483648&&t<=4294967295}const pm=class t{constructor(t,e,n,r){Dn(this,Ht),Nn(this,"provider"),Nn(this,"address"),Nn(this,"name"),Dn(this,Gt,void 0),Dn(this,jt,void 0),Ho(this,{provider:t,address:e,name:n}),Bn(this,Gt,null!=r?Promise.resolve(r):null),Bn(this,jt,new am(e,["function supportsInterface(bytes4) view returns (bool)","function resolve(bytes, bytes) view returns (bytes)","function addr(bytes32) view returns (address)","function addr(bytes32, uint) view returns (bytes)","function text(bytes32, string) view returns (string)","function contenthash(bytes32) view returns (bytes)","function name(bytes32) view returns (string)"],t))}async supportsWildcard(){return null==Pn(this,Gt)&&Bn(this,Gt,(async()=>{try{return await Pn(this,jt).supportsInterface("0x9061b923")}catch(t){if(Wo(t,"CALL_EXCEPTION"))return!1;throw Bn(this,Gt,null),t}})()),await Pn(this,Gt)}async getAddress(t){const e=null==t?cm:ya(t);if(e===cm)try{const t=await Ln(this,Ht,Vt).call(this,"addr(bytes32)");return null==t||t===Ih?null:t}catch(s){if(Wo(s,"CALL_EXCEPTION"))return null;throw s}if(fm(e)){const t=await Ln(this,Ht,Vt).call(this,"addr(bytes32,uint)",[e]);return na(t,20)?$h(t):null}if(e>=0&&e<2147483648){let t=e+BigInt(2147483648);const n=await Ln(this,Ht,Vt).call(this,"addr(bytes32,uint)",[t]);if(na(n,20))return $h(n)}let n=null;for(const i of this.provider.plugins)if(i instanceof um&&e<=2147483648&&i.supportsCoinType(Number(e))){n=i;break}if(null==n)return null;const r=await Ln(this,Ht,Vt).call(this,"addr(bytes32,uint)",[e]);if(null==r||"0x"===r)return null;if(e<2147483648){const t=await n.decodeAddress(Number(e),r);if(null!=t)return t}qo(!1,"invalid coin data","UNSUPPORTED_OPERATION",{operation:`getAddress(${e})`,info:{coinType:e,data:r}})}async getText(t){const e=await Ln(this,Ht,Vt).call(this,"text(bytes32,string)",[t]);return null==e||"0x"===e?null:e}async getContentHash(){const t=await Ln(this,Ht,Vt).call(this,"contenthash(bytes32)");if(null==t||"0x"===t)return null;const e=t.match(/^0x(e3010170|e5010172)(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);if(e){const t="e3010170"===e[1]?"ipfs":"ipns",n=parseInt(e[4],16);if(e[5].length===2*n)return`${t}://${Ca("0x"+e[2])}`}const n=t.match(/^0xe40101fa011b20([0-9a-f]*)$/);if(n&&64===n[1].length)return`bzz://${n[1]}`;qo(!1,"invalid or unsupported content hash data","UNSUPPORTED_OPERATION",{operation:"getContentHash()",info:{data:t}})}async getName(){return await Ln(this,Ht,Vt).call(this,"name(bytes32)")}async getAvatar(){return(await this._getAvatar()).url}async _getAvatar(){const t=[{type:"name",value:this.name}];try{const r=await this.getText("avatar");if(null==r)return t.push({type:"!avatar",value:""}),{url:null,linkage:t};t.push({type:"avatar",value:r});for(let s=0;s<dm.length;s++){const i=r.match(dm[s]);if(null==i)continue;const o=i[1].toLowerCase();switch(o){case"https":case"data":return t.push({type:"url",value:r}),{linkage:t,url:r};case"ipfs":{const e=lm(r);return t.push({type:"ipfs",value:r}),t.push({type:"url",value:e}),{linkage:t,url:e}}case"erc721":case"erc1155":{const s="erc721"===o?"tokenURI(uint256)":"uri(uint256)";t.push({type:o,value:r});const a=await this.getAddress();if(null==a)return t.push({type:"!owner",value:""}),{url:null,linkage:t};const c=(i[2]||"").split("/");if(2!==c.length)return t.push({type:`!${o}caip`,value:i[2]||""}),{url:null,linkage:t};const l=c[1],u=new am(c[0],["function tokenURI(uint) view returns (string)","function ownerOf(uint) view returns (address)","function uri(uint) view returns (string)","function balanceOf(address, uint256) view returns (uint)"],this.provider);if("erc721"===o){const e=await u.ownerOf(l);if(a!==e)return t.push({type:"!owner",value:e}),{url:null,linkage:t};t.push({type:"owner",value:e})}else if("erc1155"===o){const e=await u.balanceOf(a,l);if(!e)return t.push({type:"!balance",value:"0"}),{url:null,linkage:t};t.push({type:"balance",value:e.toString()})}let h=await u[s](l);if(null==h||"0x"===h)return t.push({type:"!metadata-url",value:""}),{url:null,linkage:t};t.push({type:"metadata-url-base",value:h}),"erc1155"===o&&(h=h.replace("{id}",va(l,32).substring(2)),t.push({type:"metadata-url-expanded",value:h})),h.match(/^ipfs:/i)&&(h=lm(h)),t.push({type:"metadata-url",value:h});let d={};const f=await new $a(h).send();f.assertOk();try{d=f.bodyJson}catch(e){try{t.push({type:"!metadata",value:f.bodyText})}catch(n){const e=f.body;return e&&t.push({type:"!metadata",value:ia(e)}),{url:null,linkage:t}}return{url:null,linkage:t}}if(!d)return t.push({type:"!metadata",value:""}),{url:null,linkage:t};t.push({type:"metadata",value:JSON.stringify(d)});let p=d.image;if("string"!=typeof p)return t.push({type:"!imageUrl",value:""}),{url:null,linkage:t};if(p.match(/^(https:\/\/|data:)/i));else{if(null==p.match(hm))return t.push({type:"!imageUrl-ipfs",value:p}),{url:null,linkage:t};t.push({type:"imageUrl-ipfs",value:p}),p=lm(p)}return t.push({type:"url",value:p}),{linkage:t,url:p}}}}}catch(e){}return{linkage:t,url:null}}static async getEnsAddress(t){const e=await t.getNetwork(),n=e.getPlugin("org.ethers.plugins.network.Ens");return qo(n,"network does not support ENS","UNSUPPORTED_OPERATION",{operation:"getEnsAddress",info:{network:e}}),n.address}static async getUniversalResolverAddress(t){const e=(await t.getNetwork()).getPlugin("org.ethers.plugins.network.Ens");return e&&e.universalResolver?e.universalResolver:null}static async lookupAddress(e,n,r){const s=null==r?cm:ya(r);fm(s)&&(n=$h(n));const i=await mm(e);if(i)try{const t=(await i.reverse(n,s,{enableCcipRead:!0})).primary;return Xf(t)?t:null}catch(o){if(Wo(o,"CALL_EXCEPTION")&&"ResolverNotFound(bytes)"===o.reason)return null;throw o}qo(s===cm,"lookupAddress coinType requires ENS Universal Resolver","UNSUPPORTED_OPERATION",{operation:"lookupAddress"});try{const r=await t.fromName(e,`${n.toLowerCase().substring(2)}.addr.reverse`);if(!r)return null;const s=await r.getName();if(null==s||!Xf(s))return null;return await e.resolveName(s)!==n?null:s}catch(a){if(Wo(a,"BAD_DATA")&&"0x"===a.value)return null;if(Wo(a,"CALL_EXCEPTION"))return null;throw a}}static async fromName(e,n){var r;const s=await mm(e);if(s){let r;try{r=ep(Zf(n),255)}catch(o){return null}const i=await s.requireResolver(r);return new t(e,i.resolver,n,i.extended)}let i=n;for(;;){if(""===i||"."===i)return null;if("eth"!==n&&"eth"===i)return null;const s=await Ln(r=t,Wt,Kt).call(r,e,i);if(null!=s){const r=new t(e,s,n);return i===n||await r.supportsWildcard()?r:null}i=i.split(".").slice(1).join(".")}}};Gt=new WeakMap,jt=new WeakMap,Ht=new WeakSet,Vt=async function(t,e){e=(e||[]).slice();const n=Pn(this,jt).interface;e.unshift(tp(this.name));let r=null;await this.supportsWildcard()&&(r=n.getFunction(t),qo(r,"missing fragment","UNKNOWN_ERROR",{info:{funcName:t}}),e=[ep(this.name,255),n.encodeFunctionData(r,e)],t="resolve(bytes,bytes)"),e.push({enableCcipRead:!0});try{const s=await Pn(this,jt)[t](...e);return r?n.decodeFunctionResult(r,s)[0]:s}catch(s){if(!Wo(s,"CALL_EXCEPTION"))throw s}return null},Wt=new WeakSet,Kt=async function(t,e){const n=await pm.getEnsAddress(t);try{const r=new am(n,["function resolver(bytes32) view returns (address)"],t),s=await r.resolver(tp(e),{enableCcipRead:!0});return s===Ih?null:s}catch(r){throw r}return null},Dn(pm,Wt);let gm=pm;async function mm(t){const e=await gm.getUniversalResolverAddress(t);return e?new am(e,["function requireResolver(bytes) view returns ((bytes name, uint256 offset, bytes32 node, address resolver, bool extended))","function findResolver(bytes) view returns (address resolver, bytes32 node, uint offset)","function resolve(bytes name, bytes data) view returns (bytes result, address resolver)","function reverse(bytes name, uint coinType) view returns (string primary, address resolver, address reverseResolver)","error ResolverNotFound(bytes name)","error ResolverNotContract(bytes name, address resolver)","error ReverseAddressMismatch(string primary, bytes primaryAddress)","error HttpError(uint16 statusCode, string statusMessage)"],t):null}const ym=BigInt(0);function wm(t,e){return function(n){return null==n?e:t(n)}}function bm(t,e){return n=>{if(e&&null==n)return null;if(!Array.isArray(n))throw new Error("not an array");return n.map((e=>t(e)))}}function Am(t,e){return n=>{const r={};for(const i in t){let o=i;if(e&&i in e&&!(o in n))for(const t of e[i])if(t in n){o=t;break}try{const e=t[i](n[o]);void 0!==e&&(r[i]=e)}catch(s){qo(!1,`invalid value for value.${i} (${s instanceof Error?s.message:"not-an-error"})`,"BAD_DATA",{value:n})}}return r}}function _m(t){return $o(na(t,!0),"invalid data","value",t),t}function vm(t){return $o(na(t,32),"invalid hash","value",t),t}const Em=Am({address:$h,blockHash:vm,blockNumber:_a,data:_m,index:_a,removed:wm((function(t){switch(t){case!0:case"true":return!0;case!1:case"false":return!1}$o(!1,`invalid boolean; ${JSON.stringify(t)}`,"value",t)}),!1),topics:bm(vm),transactionHash:vm,transactionIndex:_a},{index:["logIndex"]});const km=Am({hash:wm(vm),parentHash:vm,parentBeaconBlockRoot:wm(vm,null),number:_a,timestamp:_a,nonce:wm(_m),difficulty:ya,gasLimit:ya,gasUsed:ya,stateRoot:wm(vm,null),receiptsRoot:wm(vm,null),transactionsRoot:wm(vm,null),blobGasUsed:wm(ya,null),excessBlobGas:wm(ya,null),miner:wm($h),prevRandao:wm(vm,null),extraData:_m,baseFeePerGas:wm(ya)},{prevRandao:["mixHash"]});const Sm=Am({transactionIndex:_a,blockNumber:_a,transactionHash:vm,address:$h,topics:bm(vm),data:_m,index:_a,blockHash:vm},{index:["logIndex"]});const Tm=Am({to:wm($h,null),from:wm($h,null),contractAddress:wm($h,null),index:_a,root:wm(ia),gasUsed:ya,blobGasUsed:wm(ya,null),logsBloom:wm(_m),blockHash:vm,hash:vm,logs:bm((function(t){return Sm(t)})),blockNumber:_a,cumulativeGasUsed:ya,effectiveGasPrice:wm(ya),blobGasPrice:wm(ya,null),status:wm(_a),type:wm(_a,0)},{effectiveGasPrice:["gasPrice"],hash:["transactionHash"],index:["transactionIndex"]});function Rm(t){t.to&&ya(t.to)===ym&&(t.to="0x0000000000000000000000000000000000000000");const e=Am({hash:vm,index:wm(_a,void 0),type:t=>"0x"===t||null==t?0:_a(t),accessList:wm(_d,null),blobVersionedHashes:wm(bm(vm,!0),null),authorizationList:wm(bm((t=>{let e;if(t.signature)e=t.signature;else{let n=t.yParity;"0x1b"===n?n=0:"0x1c"===n&&(n=1),e=Object.assign({},t,{yParity:n})}return{address:$h(t.address),chainId:ya(t.chainId),nonce:ya(t.nonce),signature:jh.from(e)}}),!1),null),blockHash:wm(vm,null),blockNumber:wm(_a,null),transactionIndex:wm(_a,null),from:$h,gasPrice:wm(ya),maxPriorityFeePerGas:wm(ya),maxFeePerGas:wm(ya),maxFeePerBlobGas:wm(ya,null),gasLimit:ya,to:wm($h,null),value:ya,nonce:_a,data:_m,creates:wm($h,null),chainId:wm(ya,null)},{data:["input"],gasLimit:["gas"],index:["transactionIndex"]})(t);if(null==e.to&&null==e.creates&&(e.creates=function(t){const e=$h(t.from);let n=ya(t.nonce,"tx.nonce").toString(16);return n="0"===n?"0x":n.length%2?"0x0"+n:"0x"+n,$h(ca(Bl(oc([e,n])),12))}(e)),1!==t.type&&2!==t.type||null!=t.accessList||(e.accessList=[]),t.signature?e.signature=jh.from(t.signature):e.signature=jh.from(t),null==e.chainId){const t=e.signature.legacyChainId;null!=t&&(e.chainId=t)}return e.blockHash&&ya(e.blockHash)===ym&&(e.blockHash=null),e}const Im=Symbol.for("nodejs.util.inspect.custom");class Om{constructor(t){Nn(this,"name"),Ho(this,{name:t})}[Im](){return this.toString()}toString(){return`${this.name} { }`}clone(){return new Om(this.name)}}class Cm extends Om{constructor(t,e){null==t&&(t=0),super(`org.ethers.network.plugins.GasCost#${t||0}`),Nn(this,"effectiveBlock"),Nn(this,"txBase"),Nn(this,"txCreate"),Nn(this,"txDataZero"),Nn(this,"txDataNonzero"),Nn(this,"txAccessListStorageKey"),Nn(this,"txAccessListAddress");const n={effectiveBlock:t};function r(t,r){let s=(e||{})[t];null==s&&(s=r),$o("number"==typeof s,`invalud value for ${t}`,"costs",e),n[t]=s}r("txBase",21e3),r("txCreate",32e3),r("txDataZero",4),r("txDataNonzero",16),r("txAccessListStorageKey",1900),r("txAccessListAddress",2400),Ho(this,n)}toString(){return`${this.name} { txBase: ${this.txBase}, txCreate: ${this.txCreate}, txDataZero: ${this.txDataZero}, txAccessListStorageKey: ${this.txAccessListStorageKey}, txAccessListAddress: ${this.txAccessListAddress} }`}clone(){return new Cm(this.effectiveBlock,this)}}class Nm extends Om{constructor(t,e,n){super("org.ethers.plugins.network.Ens"),Nn(this,"address"),Nn(this,"targetNetwork"),Nn(this,"universalResolver"),Ho(this,{address:t||"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",targetNetwork:null==e?1:e,universalResolver:n})}toString(){return`${this.name} { address: ${this.address}, targetNetwork: ${this.targetNetwork}, universalResolver: ${this.universalResolver} }`}clone(){return new Nm(this.address,this.targetNetwork,this.universalResolver)}}class xm extends Om{constructor(t,e){super("org.ethers.plugins.network.FetchUrlFeeDataPlugin"),Dn(this,zt,void 0),Dn(this,qt,void 0),Bn(this,zt,t),Bn(this,qt,e)}get url(){return Pn(this,zt)}get processFunc(){return Pn(this,qt)}toString(){return`${this.name} { url: ${this.url} }`}clone(){return this}}zt=new WeakMap,qt=new WeakMap;const Pm=Symbol.for("nodejs.util.inspect.custom"),Dm=new Map;$t=new WeakMap,Qt=new WeakMap,Jt=new WeakMap;let Bm=class t{constructor(t,e){Dn(this,$t,void 0),Dn(this,Qt,void 0),Dn(this,Jt,void 0),Bn(this,$t,t),Bn(this,Qt,ya(e)),Bn(this,Jt,new Map)}[Pm](){return this.toString()}toString(){const t=[];for(const e of Pn(this,Jt).values())t.push(e.toString());return`Network { name: ${this.name}, chainId: ${this.chainId}, plugins: [ ${t.join(", ")} ] }`}toJSON(){return{name:this.name,chainId:String(this.chainId)}}get name(){return Pn(this,$t)}set name(t){Bn(this,$t,t)}get chainId(){return Pn(this,Qt)}set chainId(t){Bn(this,Qt,ya(t,"chainId"))}matches(t){if(null==t)return!1;if("string"==typeof t){try{return this.chainId===ya(t)}catch(e){}return this.name===t}if("number"==typeof t||"bigint"==typeof t){try{return this.chainId===ya(t)}catch(e){}return!1}if("object"==typeof t){if(null!=t.chainId){try{return this.chainId===ya(t.chainId)}catch(e){}return!1}return null!=t.name&&this.name===t.name}return!1}get plugins(){return Array.from(Pn(this,Jt).values())}attachPlugin(t){if(Pn(this,Jt).get(t.name))throw new Error(`cannot replace existing plugin: ${t.name} `);return Pn(this,Jt).set(t.name,t.clone()),this}getPlugin(t){return Pn(this,Jt).get(t)||null}getPlugins(t){return this.plugins.filter((e=>e.name.split("#")[0]===t))}clone(){const e=new t(this.name,this.chainId);return this.plugins.forEach((t=>{e.attachPlugin(t.clone())})),e}computeIntrinsicGas(t){const e=this.getPlugin("org.ethers.plugins.network.GasCost")||new Cm;let n=e.txBase;if(null==t.to&&(n+=e.txCreate),t.data)for(let r=2;r<t.data.length;r+=2)"00"===t.data.substring(r,r+2)?n+=e.txDataZero:n+=e.txDataNonzero;if(t.accessList){const r=_d(t.accessList);for(const t in r)n+=e.txAccessListAddress+e.txAccessListStorageKey*r[t].storageKeys.length}return n}static from(e){if(function(){if(Mm)return;function t(t,e,n){const r=function(){const r=new Bm(t,e);return null!=n.ensNetwork&&r.attachPlugin(new Nm(null,n.ensNetwork,n.ensUniversalResolver)),r.attachPlugin(new Cm),(n.plugins||[]).forEach((t=>{r.attachPlugin(t)})),r};Bm.register(t,r),Bm.register(e,r),n.altNames&&n.altNames.forEach((t=>{Bm.register(t,r)}))}Mm=!0;const e="0xeEeEEEeE14D718C2B47D9923Deab1335E144EeEe";t("mainnet",1,{ensUniversalResolver:e,ensNetwork:1,altNames:["homestead"]}),t("ropsten",3,{ensNetwork:3}),t("rinkeby",4,{ensNetwork:4}),t("goerli",5,{ensNetwork:5}),t("kovan",42,{ensNetwork:42}),t("sepolia",11155111,{ensUniversalResolver:e,ensNetwork:11155111}),t("holesky",17e3,{ensNetwork:17e3}),t("classic",61,{}),t("classicKotti",6,{}),t("arbitrum",42161,{ensNetwork:1}),t("arbitrum-goerli",421613,{}),t("arbitrum-sepolia",421614,{}),t("base",8453,{ensNetwork:1}),t("base-goerli",84531,{}),t("base-sepolia",84532,{}),t("bnb",56,{ensNetwork:1}),t("bnbt",97,{}),t("filecoin",314,{}),t("filecoin-calibration",314159,{}),t("linea",59144,{ensNetwork:1}),t("linea-goerli",59140,{}),t("linea-sepolia",59141,{}),t("matic",137,{ensNetwork:1,plugins:[Lm("https://gasstation.polygon.technology/v2")]}),t("matic-amoy",80002,{}),t("matic-mumbai",80001,{altNames:["maticMumbai","maticmum"],plugins:[Lm("https://gasstation-testnet.polygon.technology/v2")]}),t("optimism",10,{ensNetwork:1,plugins:[]}),t("optimism-goerli",420,{}),t("optimism-sepolia",11155420,{}),t("xdai",100,{ensNetwork:1})}(),null==e)return t.from("mainnet");if("number"==typeof e&&(e=BigInt(e)),"string"==typeof e||"bigint"==typeof e){const n=Dm.get(e);if(n)return n();if("bigint"==typeof e)return new t("unknown",e);$o(!1,"unknown network","network",e)}if("function"==typeof e.clone){return e.clone()}if("object"==typeof e){$o("string"==typeof e.name&&"number"==typeof e.chainId,"invalid network object name or chainId","network",e);const n=new t(e.name,e.chainId),r=e;return(r.ensAddress||null!=r.ensNetwork||r.ensUniversalResolver)&&n.attachPlugin(new Nm(r.ensAddress,r.ensNetwork,r.ensUniversalResolver)),n}$o(!1,"invalid network","network",e)}static register(t,e){"number"==typeof t&&(t=BigInt(t));const n=Dm.get(t);n&&$o(!1,`conflicting network for ${JSON.stringify(n.name)}`,"nameOrChainId",t),Dm.set(t,e)}};function Um(t,e){const n=String(t);if(!n.match(/^[0-9.]+$/))throw new Error(`invalid gwei value: ${t}`);const r=n.split(".");if(1===r.length&&r.push(""),2!==r.length)throw new Error(`invalid gwei value: ${t}`);for(;r[1].length<e;)r[1]+="0";if(r[1].length>9){let t=BigInt(r[1].substring(0,9));r[1].substring(9).match(/^0+$/)||t++,r[1]=t.toString()}return BigInt(r[0]+r[1])}function Lm(t){return new xm(t,(async(t,e,n)=>{let r;n.setHeader("User-Agent","ethers");try{const[e,s]=await Promise.all([n.send(),t()]);r=e;const i=r.bodyJson.standard;return{gasPrice:s.gasPrice,maxFeePerGas:Um(i.maxFee,9),maxPriorityFeePerGas:Um(i.maxPriorityFee,9)}}catch(s){qo(!1,`error encountered with polygon gas station (${JSON.stringify(n.url)})`,"SERVER_ERROR",{request:n,response:r,error:s})}}))}let Mm=!1;function Fm(t){return JSON.parse(JSON.stringify(t))}class Gm{constructor(t){Dn(this,ee),Dn(this,Yt,void 0),Dn(this,Zt,void 0),Dn(this,Xt,void 0),Dn(this,te,void 0),Bn(this,Yt,t),Bn(this,Zt,null),Bn(this,Xt,4e3),Bn(this,te,-2)}get pollingInterval(){return Pn(this,Xt)}set pollingInterval(t){Bn(this,Xt,t)}start(){Pn(this,Zt)||(Bn(this,Zt,Pn(this,Yt)._setTimeout(Ln(this,ee,ne).bind(this),Pn(this,Xt))),Ln(this,ee,ne).call(this))}stop(){Pn(this,Zt)&&(Pn(this,Yt)._clearTimeout(Pn(this,Zt)),Bn(this,Zt,null))}pause(t){this.stop(),t&&Bn(this,te,-2)}resume(){this.start()}}Yt=new WeakMap,Zt=new WeakMap,Xt=new WeakMap,te=new WeakMap,ee=new WeakSet,ne=async function(){try{const t=await Pn(this,Yt).getBlockNumber();if(-2===Pn(this,te))return void Bn(this,te,t);if(t!==Pn(this,te)){for(let e=Pn(this,te)+1;e<=t;e++){if(null==Pn(this,Zt))return;await Pn(this,Yt).emit("block",e)}Bn(this,te,t)}}catch(t){}null!=Pn(this,Zt)&&Bn(this,Zt,Pn(this,Yt)._setTimeout(Ln(this,ee,ne).bind(this),Pn(this,Xt)))};class jm{constructor(t){Dn(this,re,void 0),Dn(this,se,void 0),Dn(this,ie,void 0),Bn(this,re,t),Bn(this,ie,!1),Bn(this,se,(t=>{this._poll(t,Pn(this,re))}))}async _poll(t,e){throw new Error("sub-classes must override this")}start(){Pn(this,ie)||(Bn(this,ie,!0),Pn(this,se).call(this,-2),Pn(this,re).on("block",Pn(this,se)))}stop(){Pn(this,ie)&&(Bn(this,ie,!1),Pn(this,re).off("block",Pn(this,se)))}pause(t){this.stop()}resume(){this.start()}}re=new WeakMap,se=new WeakMap,ie=new WeakMap;class Hm extends jm{constructor(t,e){super(t),Dn(this,oe,void 0),Dn(this,ae,void 0),Bn(this,oe,e),Bn(this,ae,-2)}pause(t){t&&Bn(this,ae,-2),super.pause(t)}async _poll(t,e){const n=await e.getBlock(Pn(this,oe));null!=n&&(-2===Pn(this,ae)?Bn(this,ae,n.number):n.number>Pn(this,ae)&&(e.emit(Pn(this,oe),n.number),Bn(this,ae,n.number)))}}oe=new WeakMap,ae=new WeakMap;class Vm extends jm{constructor(t,e){super(t),Dn(this,ce,void 0),Bn(this,ce,Fm(e))}async _poll(t,e){throw new Error("@TODO")}}ce=new WeakMap;class Wm extends jm{constructor(t,e){super(t),Dn(this,le,void 0),Bn(this,le,e)}async _poll(t,e){const n=await e.getTransactionReceipt(Pn(this,le));n&&e.emit(Pn(this,le),n)}}le=new WeakMap;class Km{constructor(t,e){Dn(this,ge),Dn(this,ue,void 0),Dn(this,he,void 0),Dn(this,de,void 0),Dn(this,fe,void 0),Dn(this,pe,void 0),Bn(this,ue,t),Bn(this,he,Fm(e)),Bn(this,de,Ln(this,ge,me).bind(this)),Bn(this,fe,!1),Bn(this,pe,-2)}start(){Pn(this,fe)||(Bn(this,fe,!0),-2===Pn(this,pe)&&Pn(this,ue).getBlockNumber().then((t=>{Bn(this,pe,t)})),Pn(this,ue).on("block",Pn(this,de)))}stop(){Pn(this,fe)&&(Bn(this,fe,!1),Pn(this,ue).off("block",Pn(this,de)))}pause(t){this.stop(),t&&Bn(this,pe,-2)}resume(){this.start()}}ue=new WeakMap,he=new WeakMap,de=new WeakMap,fe=new WeakMap,pe=new WeakMap,ge=new WeakSet,me=async function(t){if(-2===Pn(this,pe))return;const e=Fm(Pn(this,he));e.fromBlock=Pn(this,pe)+1,e.toBlock=t;const n=await Pn(this,ue).getLogs(e);if(0!==n.length)for(const r of n)Pn(this,ue).emit(Pn(this,he),r),Bn(this,pe,r.blockNumber);else Pn(this,pe)<t-60&&Bn(this,pe,t-60)};const zm=BigInt(2);function qm(t){return new Promise((e=>{setTimeout(e,t)}))}function $m(t){return t&&"function"==typeof t.then}function Qm(t,e){return t+":"+JSON.stringify(e,((t,e)=>{if(null==e)return"null";if("bigint"==typeof e)return`bigint:${e.toString()}`;if("string"==typeof e)return e.toLowerCase();if("object"==typeof e&&!Array.isArray(e)){const t=Object.keys(e);return t.sort(),t.reduce(((t,n)=>(t[n]=e[n],t)),{})}return e}))}class Jm{constructor(t){Nn(this,"name"),Ho(this,{name:t})}start(){}stop(){}pause(t){}resume(){}}function Ym(t){return(t=Array.from(new Set(t).values())).sort(),t}async function Zm(t,e){if(null==t)throw new Error("invalid event");if(Array.isArray(t)&&(t={topics:t}),"string"==typeof t)switch(t){case"block":case"debug":case"error":case"finalized":case"network":case"pending":case"safe":return{type:t,tag:t}}if(na(t,32)){const e=t.toLowerCase();return{type:"transaction",tag:Qm("tx",{hash:e}),hash:e}}if(t.orphan){const e=t;return{type:"orphan",tag:Qm("orphan",e),filter:(n=e,JSON.parse(JSON.stringify(n)))}}var n;if(t.address||t.topics){const n=t,r={topics:(n.topics||[]).map((t=>null==t?null:Array.isArray(t)?Ym(t.map((t=>t.toLowerCase()))):t.toLowerCase()))};if(n.address){const t=[],s=[],i=n=>{na(n)?t.push(n):s.push((async()=>{t.push(await Yh(n,e))})())};Array.isArray(n.address)?n.address.forEach(i):i(n.address),s.length&&await Promise.all(s),r.address=Ym(t.map((t=>t.toLowerCase())))}return{filter:r,tag:Qm("event",r),type:"event"}}$o(!1,"unknown ProviderEvent","event",t)}function Xm(){return(new Date).getTime()}const ty={cacheTimeout:250,pollingInterval:4e3};class ey{constructor(t,e){if(Dn(this,Ne),Dn(this,Pe),Dn(this,Be),Dn(this,Le),Dn(this,Fe),Dn(this,je),Dn(this,Ve),Dn(this,Ke),Dn(this,ye,void 0),Dn(this,we,void 0),Dn(this,be,void 0),Dn(this,Ae,void 0),Dn(this,_e,void 0),Dn(this,ve,void 0),Dn(this,Ee,void 0),Dn(this,ke,void 0),Dn(this,Se,void 0),Dn(this,Te,void 0),Dn(this,Re,void 0),Dn(this,Ie,void 0),Dn(this,Oe,void 0),Dn(this,Ce,void 0),Bn(this,Ce,Object.assign({},ty,e||{})),"any"===t)Bn(this,ve,!0),Bn(this,_e,null);else if(t){const e=Bm.from(t);Bn(this,ve,!1),Bn(this,_e,Promise.resolve(e)),setTimeout((()=>{this.emit("network",e,null)}),0)}else Bn(this,ve,!1),Bn(this,_e,null);Bn(this,ke,-1),Bn(this,Ee,new Map),Bn(this,ye,new Map),Bn(this,we,new Map),Bn(this,be,null),Bn(this,Ae,!1),Bn(this,Se,1),Bn(this,Te,new Map),Bn(this,Re,!1),Bn(this,Ie,0),Bn(this,Oe,[])}get _requestRate(){const t=Pn(this,Ie);return 0==t?null:t}set _requestRate(t){(null==t||t<0)&&(t=0),Bn(this,Ie,_a(t))}get pollingInterval(){return Pn(this,Ce).pollingInterval}get provider(){return this}get plugins(){return Array.from(Pn(this,we).values())}attachPlugin(t){if(Pn(this,we).get(t.name))throw new Error(`cannot replace existing plugin: ${t.name} `);return Pn(this,we).set(t.name,t.connect(this)),this}getPlugin(t){return Pn(this,we).get(t)||null}get disableCcipRead(){return Pn(this,Re)}set disableCcipRead(t){Bn(this,Re,!!t)}async ccipReadFetch(t,e,n){if(this.disableCcipRead||0===n.length||null==t.to)return null;const r=t.to.toLowerCase(),s=e.toLowerCase(),i=[];for(let a=0;a<n.length;a++){const e=n[a],c=e.replace("{sender}",r).replace("{data}",s),l=new $a(c);-1===e.indexOf("{data}")&&(l.body={data:s,sender:r}),this.emit("debug",{action:"sendCcipReadFetchRequest",request:l,index:a,urls:n});let u,h="unknown error";try{u=await l.send()}catch(o){i.push(o.message),this.emit("debug",{action:"receiveCcipReadFetchError",request:l,result:{error:o}});continue}try{const t=u.bodyJson;if(t.data)return this.emit("debug",{action:"receiveCcipReadFetchResult",request:l,result:t}),t.data;t.message&&(h=t.message),this.emit("debug",{action:"receiveCcipReadFetchError",request:l,result:t})}catch(o){}qo(u.statusCode<400||u.statusCode>=500,`response not found during CCIP fetch: ${h}`,"OFFCHAIN_FAULT",{reason:"404_MISSING_RESOURCE",transaction:t,info:{url:e,errorMessage:h}}),i.push(h)}qo(!1,`error encountered during CCIP fetch: ${i.map((t=>JSON.stringify(t))).join(", ")}`,"OFFCHAIN_FAULT",{reason:"500_SERVER_ERROR",transaction:t,info:{urls:n,errorMessages:i}})}_wrapBlock(t,e){return new Rg(function(t){const e=km(t);return e.transactions=t.transactions.map((t=>"string"==typeof t?t:Rm(t))),e}(t),this)}_wrapLog(t,e){return new Ig(function(t){return Em(t)}(t),this)}_wrapTransactionReceipt(t,e){return new Og(function(t){return Tm(t)}(t),this)}_wrapTransactionResponse(t,e){return new Cg(Rm(t),this)}_detectNetwork(){qo(!1,"sub-classes must implement this","UNSUPPORTED_OPERATION",{operation:"_detectNetwork"})}async _perform(t){qo(!1,`unsupported method: ${t.method}`,"UNSUPPORTED_OPERATION",{operation:t.method,info:t})}async getBlockNumber(){const t=_a(await Ln(this,Pe,De).call(this,{method:"getBlockNumber"}),"%response");return Pn(this,ke)>=0&&Bn(this,ke,t),t}_getAddress(t){return Yh(t,this)}_getBlockTag(t){if(null==t)return"latest";switch(t){case"earliest":return"0x0";case"finalized":case"latest":case"pending":case"safe":return t}return na(t)?na(t,32)?t:ka(t):("bigint"==typeof t&&(t=_a(t,"blockTag")),"number"==typeof t?t>=0?ka(t):Pn(this,ke)>=0?ka(Pn(this,ke)+t):this.getBlockNumber().then((e=>ka(e+t))):void $o(!1,"invalid blockTag","blockTag",t))}_getFilter(t){const e=(t.topics||[]).map((t=>null==t?null:Array.isArray(t)?Ym(t.map((t=>t.toLowerCase()))):t.toLowerCase())),n="blockHash"in t?t.blockHash:void 0,r=(t,r,s)=>{let i;switch(t.length){case 0:break;case 1:i=t[0];break;default:t.sort(),i=t}if(n&&(null!=r||null!=s))throw new Error("invalid filter");const o={};return i&&(o.address=i),e.length&&(o.topics=e),r&&(o.fromBlock=r),s&&(o.toBlock=s),n&&(o.blockHash=n),o};let s,i,o=[];if(t.address)if(Array.isArray(t.address))for(const a of t.address)o.push(this._getAddress(a));else o.push(this._getAddress(t.address));return"fromBlock"in t&&(s=this._getBlockTag(t.fromBlock)),"toBlock"in t&&(i=this._getBlockTag(t.toBlock)),o.filter((t=>"string"!=typeof t)).length||null!=s&&"string"!=typeof s||null!=i&&"string"!=typeof i?Promise.all([Promise.all(o),s,i]).then((t=>r(t[0],t[1],t[2]))):r(o,s,i)}_getTransactionRequest(t){const e=Tg(t),n=[];if(["to","from"].forEach((t=>{if(null==e[t])return;const r=Yh(e[t],this);$m(r)?n.push(async function(){e[t]=await r}()):e[t]=r})),null!=e.blockTag){const t=this._getBlockTag(e.blockTag);$m(t)?n.push(async function(){e.blockTag=await t}()):e.blockTag=t}return n.length?async function(){return await Promise.all(n),e}():e}async getNetwork(){if(null==Pn(this,_e)){const t=(async()=>{try{const t=await this._detectNetwork();return this.emit("network",t,null),t}catch(e){throw Pn(this,_e)===t&&Bn(this,_e,null),e}})();return Bn(this,_e,t),(await t).clone()}const t=Pn(this,_e),[e,n]=await Promise.all([t,this._detectNetwork()]);return e.chainId!==n.chainId&&(Pn(this,ve)?(this.emit("network",n,e),Pn(this,_e)===t&&Bn(this,_e,Promise.resolve(n))):qo(!1,`network changed: ${e.chainId} => ${n.chainId} `,"NETWORK_ERROR",{event:"changed"})),e.clone()}async getFeeData(){const t=await this.getNetwork(),e=async()=>{const{_block:e,gasPrice:n,priorityFee:r}=await jo({_block:Ln(this,je,He).call(this,"latest",!1),gasPrice:(async()=>{try{return ya(await Ln(this,Pe,De).call(this,{method:"getGasPrice"}),"%response")}catch(t){}return null})(),priorityFee:(async()=>{try{return ya(await Ln(this,Pe,De).call(this,{method:"getPriorityFee"}),"%response")}catch(t){}return null})()});let s=null,i=null;const o=this._wrapBlock(e,t);return o&&o.baseFeePerGas&&(i=null!=r?r:BigInt("1000000000"),s=o.baseFeePerGas*zm+i),new Sg(n,s,i)},n=t.getPlugin("org.ethers.plugins.network.FetchUrlFeeDataPlugin");if(n){const t=new $a(n.url),r=await n.processFunc(e,this,t);return new Sg(r.gasPrice,r.maxFeePerGas,r.maxPriorityFeePerGas)}return await e()}async estimateGas(t){let e=this._getTransactionRequest(t);return $m(e)&&(e=await e),ya(await Ln(this,Pe,De).call(this,{method:"estimateGas",transaction:e}),"%response")}async call(t){const{tx:e,blockTag:n}=await jo({tx:this._getTransactionRequest(t),blockTag:this._getBlockTag(t.blockTag)});return await Ln(this,Le,Me).call(this,Ln(this,Be,Ue).call(this,e,n,t.enableCcipRead?0:-1))}async getBalance(t,e){return ya(await Ln(this,Fe,Ge).call(this,{method:"getBalance"},t,e),"%response")}async getTransactionCount(t,e){return _a(await Ln(this,Fe,Ge).call(this,{method:"getTransactionCount"},t,e),"%response")}async getCode(t,e){return ia(await Ln(this,Fe,Ge).call(this,{method:"getCode"},t,e))}async getStorage(t,e,n){const r=ya(e,"position");return ia(await Ln(this,Fe,Ge).call(this,{method:"getStorage",position:r},t,n))}async broadcastTransaction(t){const{blockNumber:e,hash:n,network:r}=await jo({blockNumber:this.getBlockNumber(),hash:this._perform({method:"broadcastTransaction",signedTransaction:t}),network:this.getNetwork()}),s=Vd.from(t);if(s.hash!==n)throw new Error("@TODO: the returned hash did not match");return this._wrapTransactionResponse(s,r).replaceableTransaction(e)}async getBlock(t,e){const{network:n,params:r}=await jo({network:this.getNetwork(),params:Ln(this,je,He).call(this,t,!!e)});return null==r?null:this._wrapBlock(r,n)}async getTransaction(t){const{network:e,params:n}=await jo({network:this.getNetwork(),params:Ln(this,Pe,De).call(this,{method:"getTransaction",hash:t})});return null==n?null:this._wrapTransactionResponse(n,e)}async getTransactionReceipt(t){const{network:e,params:n}=await jo({network:this.getNetwork(),params:Ln(this,Pe,De).call(this,{method:"getTransactionReceipt",hash:t})});if(null==n)return null;if(null==n.gasPrice&&null==n.effectiveGasPrice){const e=await Ln(this,Pe,De).call(this,{method:"getTransaction",hash:t});if(null==e)throw new Error("report this; could not find tx or effectiveGasPrice");n.effectiveGasPrice=e.gasPrice}return this._wrapTransactionReceipt(n,e)}async getTransactionResult(t){const{result:e}=await jo({network:this.getNetwork(),result:Ln(this,Pe,De).call(this,{method:"getTransactionResult",hash:t})});return null==e?null:ia(e)}async getLogs(t){let e=this._getFilter(t);$m(e)&&(e=await e);const{network:n,params:r}=await jo({network:this.getNetwork(),params:Ln(this,Pe,De).call(this,{method:"getLogs",filter:e})});return r.map((t=>this._wrapLog(t,n)))}_getProvider(t){qo(!1,"provider cannot connect to target network","UNSUPPORTED_OPERATION",{operation:"_getProvider()"})}async getResolver(t){return await gm.fromName(this,t)}async getAvatar(t){const e=await this.getResolver(t);return e?await e.getAvatar():null}async resolveName(t,e){const n=await this.getResolver(t);return n?await n.getAddress(e):null}async lookupAddress(t,e){return await gm.lookupAddress(this,t,e)}async waitForTransaction(t,e,n){const r=null!=e?e:1;return 0===r?this.getTransactionReceipt(t):new Promise((async(e,s)=>{let i=null;const o=async n=>{try{const s=await this.getTransactionReceipt(t);if(null!=s&&n-s.blockNumber+1>=r)return e(s),void(i&&(clearTimeout(i),i=null))}catch(s){console.log("EEE",s)}this.once("block",o)};null!=n&&(i=setTimeout((()=>{null!=i&&(i=null,this.off("block",o),s(zo("timeout","TIMEOUT",{reason:"timeout"})))}),n)),o(await this.getBlockNumber())}))}async waitForBlock(t){qo(!1,"not implemented yet","NOT_IMPLEMENTED",{operation:"waitForBlock"})}_clearTimeout(t){const e=Pn(this,Te).get(t);e&&(e.timer&&clearTimeout(e.timer),Pn(this,Te).delete(t))}_setTimeout(t,e){null==e&&(e=0);const n=Un(this,Se)._++,r=()=>{Pn(this,Te).delete(n),t()};if(this.paused)Pn(this,Te).set(n,{timer:null,func:r,time:e});else{const t=setTimeout(r,e);Pn(this,Te).set(n,{timer:t,func:r,time:Xm()})}return n}_forEachSubscriber(t){for(const e of Pn(this,ye).values())t(e.subscriber)}_getSubscriber(t){switch(t.type){case"debug":case"error":case"network":return new Jm(t.type);case"block":{const t=new Gm(this);return t.pollingInterval=this.pollingInterval,t}case"safe":case"finalized":return new Hm(this,t.type);case"event":return new Km(this,t.filter);case"transaction":return new Wm(this,t.hash);case"orphan":return new Vm(this,t.filter)}throw new Error(`unsupported event: ${t.type}`)}_recoverSubscriber(t,e){for(const n of Pn(this,ye).values())if(n.subscriber===t){n.started&&n.subscriber.stop(),n.subscriber=e,n.started&&e.start(),null!=Pn(this,be)&&e.pause(Pn(this,be));break}}async on(t,e){const n=await Ln(this,Ke,ze).call(this,t);return n.listeners.push({listener:e,once:!1}),n.started||(n.subscriber.start(),n.started=!0,null!=Pn(this,be)&&n.subscriber.pause(Pn(this,be))),this}async once(t,e){const n=await Ln(this,Ke,ze).call(this,t);return n.listeners.push({listener:e,once:!0}),n.started||(n.subscriber.start(),n.started=!0,null!=Pn(this,be)&&n.subscriber.pause(Pn(this,be))),this}async emit(t,...e){const n=await Ln(this,Ve,We).call(this,t,e);if(!n||0===n.listeners.length)return!1;const r=n.listeners.length;return n.listeners=n.listeners.filter((({listener:n,once:r})=>{const s=new Na(this,r?null:n,t);try{n.call(this,...e,s)}catch(i){}return!r})),0===n.listeners.length&&(n.started&&n.subscriber.stop(),Pn(this,ye).delete(n.tag)),r>0}async listenerCount(t){if(t){const e=await Ln(this,Ve,We).call(this,t);return e?e.listeners.length:0}let e=0;for(const{listeners:n}of Pn(this,ye).values())e+=n.length;return e}async listeners(t){if(t){const e=await Ln(this,Ve,We).call(this,t);return e?e.listeners.map((({listener:t})=>t)):[]}let e=[];for(const{listeners:n}of Pn(this,ye).values())e=e.concat(n.map((({listener:t})=>t)));return e}async off(t,e){const n=await Ln(this,Ve,We).call(this,t);if(!n)return this;if(e){const t=n.listeners.map((({listener:t})=>t)).indexOf(e);t>=0&&n.listeners.splice(t,1)}return e&&0!==n.listeners.length||(n.started&&n.subscriber.stop(),Pn(this,ye).delete(n.tag)),this}async removeAllListeners(t){if(t){const{tag:e,started:n,subscriber:r}=await Ln(this,Ke,ze).call(this,t);n&&r.stop(),Pn(this,ye).delete(e)}else for(const[e,{started:n,subscriber:r}]of Pn(this,ye))n&&r.stop(),Pn(this,ye).delete(e);return this}async addListener(t,e){return await this.on(t,e)}async removeListener(t,e){return this.off(t,e)}get destroyed(){return Pn(this,Ae)}destroy(){this.removeAllListeners();for(const t of Pn(this,Te).keys())this._clearTimeout(t);Bn(this,Ae,!0)}get paused(){return null!=Pn(this,be)}set paused(t){!!t!==this.paused&&(this.paused?this.resume():this.pause(!1))}pause(t){if(Bn(this,ke,-1),null!=Pn(this,be)){if(Pn(this,be)==!!t)return;qo(!1,"cannot change pause type; resume first","UNSUPPORTED_OPERATION",{operation:"pause"})}this._forEachSubscriber((e=>e.pause(t))),Bn(this,be,!!t);for(const e of Pn(this,Te).values())e.timer&&clearTimeout(e.timer),e.time=Xm()-e.time}resume(){if(null!=Pn(this,be)){this._forEachSubscriber((t=>t.resume())),Bn(this,be,null);for(const t of Pn(this,Te).values()){let e=t.time;e<0&&(e=0),t.time=Xm(),setTimeout(t.func,e)}}}}function ny(t,e){try{const n=ry(t,e);if(n)return Ba(n)}catch(n){}return null}function ry(t,e){if("0x"===t)return null;try{const n=_a(ca(t,e,e+32)),r=_a(ca(t,n,n+32));return ca(t,n+32,n+32+r)}catch(n){}return null}function sy(t){const e=Ea(t);if(e.length>32)throw new Error("internal; should not happen");const n=new Uint8Array(32);return n.set(e,32-e.length),n}function iy(t){if(t.length%32==0)return t;const e=new Uint8Array(32*Math.ceil(t.length/32));return e.set(t),e}ye=new WeakMap,we=new WeakMap,be=new WeakMap,Ae=new WeakMap,_e=new WeakMap,ve=new WeakMap,Ee=new WeakMap,ke=new WeakMap,Se=new WeakMap,Te=new WeakMap,Re=new WeakMap,Ie=new WeakMap,Oe=new WeakMap,Ce=new WeakMap,Ne=new WeakSet,xe=function(){let t=Pn(this,Ie);if(0===t)return 0;const e=Pn(this,Oe),n=Xm();e.push(n);const r=n-1e3;for(;e.length&&e[0]<r;)e.shift();return e.length<t?0:e[0]+1e3-n},Pe=new WeakSet,De=async function(t){const e=Pn(this,Ce).cacheTimeout;if(e<0){const e=Ln(this,Ne,xe).call(this);return e&&await qm(e),await this._perform(t)}const n=Qm(t.method,t);let r=Pn(this,Ee).get(n);if(!r){const s=Ln(this,Ne,xe).call(this);s&&await qm(s),r=this._perform(t),Pn(this,Ee).set(n,r),setTimeout((()=>{Pn(this,Ee).get(n)===r&&Pn(this,Ee).delete(n)}),e)}return await r},Be=new WeakSet,Ue=async function(t,e,n){qo(n<10,"CCIP read exceeded maximum redirections","OFFCHAIN_FAULT",{reason:"TOO_MANY_REDIRECTS",transaction:Object.assign({},t,{blockTag:e,enableCcipRead:!0})});const r=Tg(t);try{const t=Ln(this,Ne,xe).call(this);return t&&await qm(t),ia(await this._perform({method:"call",transaction:r,blockTag:e}))}catch(s){if(!this.disableCcipRead&&Ko(s)&&s.data&&n>=0&&"latest"===e&&null!=r.to&&"0x556f1830"===ca(s.data,0,4)){const t=s.data,o=await Yh(r.to,this);let a;try{a=function(t){const e={sender:"",urls:[],calldata:"",selector:"",extraData:"",errorArgs:[]};qo(aa(t)>=160,"insufficient OffchainLookup data","OFFCHAIN_FAULT",{reason:"insufficient OffchainLookup data"});const n=ca(t,0,32);qo(ca(n,0,12)===ca(cy,0,12),"corrupt OffchainLookup sender","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup sender"}),e.sender=ca(n,12);try{const n=[],r=_a(ca(t,32,64)),s=_a(ca(t,r,r+32)),i=ca(t,r+32);for(let t=0;t<s;t++){const e=ny(i,32*t);if(null==e)throw new Error("abort");n.push(e)}e.urls=n}catch(s){qo(!1,"corrupt OffchainLookup urls","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup urls"})}try{const n=ry(t,64);if(null==n)throw new Error("abort");e.calldata=n}catch(s){qo(!1,"corrupt OffchainLookup calldata","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup calldata"})}qo(ca(t,100,128)===ca(cy,0,28),"corrupt OffchainLookup callbaackSelector","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup callbaackSelector"}),e.selector=ca(t,96,100);try{const n=ry(t,128);if(null==n)throw new Error("abort");e.extraData=n}catch(s){qo(!1,"corrupt OffchainLookup extraData","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup extraData"})}return e.errorArgs="sender,urls,calldata,selector,extraData".split(/,/).map((t=>e[t])),e}(ca(s.data,4))}catch(i){qo(!1,i.message,"OFFCHAIN_FAULT",{reason:"BAD_DATA",transaction:r,info:{data:t}})}qo(a.sender.toLowerCase()===o.toLowerCase(),"CCIP Read sender mismatch","CALL_EXCEPTION",{action:"call",data:t,reason:"OffchainLookup",transaction:r,invocation:null,revert:{signature:"OffchainLookup(address,string[],bytes,bytes4,bytes)",name:"OffchainLookup",args:a.errorArgs}});const c=await this.ccipReadFetch(r,a.calldata,a.urls);qo(null!=c,"CCIP Read failed to fetch data","OFFCHAIN_FAULT",{reason:"FETCH_FAILED",transaction:r,info:{data:s.data,errorArgs:a.errorArgs}});const l={to:o,data:oa([a.selector,ay([c,a.extraData])])};this.emit("debug",{action:"sendCcipReadCall",transaction:l});try{const t=await Ln(this,Be,Ue).call(this,l,e,n+1);return this.emit("debug",{action:"receiveCcipReadCallResult",transaction:Object.assign({},l),result:t}),t}catch(i){throw this.emit("debug",{action:"receiveCcipReadCallError",transaction:Object.assign({},l),error:i}),i}}throw s}},Le=new WeakSet,Me=async function(t){const{value:e}=await jo({network:this.getNetwork(),value:t});return e},Fe=new WeakSet,Ge=async function(t,e,n){let r=this._getAddress(e),s=this._getBlockTag(n);return"string"==typeof r&&"string"==typeof s||([r,s]=await Promise.all([r,s])),await Ln(this,Le,Me).call(this,Ln(this,Pe,De).call(this,Object.assign(t,{address:r,blockTag:s})))},je=new WeakSet,He=async function(t,e){if(na(t,32))return await Ln(this,Pe,De).call(this,{method:"getBlock",blockHash:t,includeTransactions:e});let n=this._getBlockTag(t);return"string"!=typeof n&&(n=await n),await Ln(this,Pe,De).call(this,{method:"getBlock",blockTag:n,includeTransactions:e})},Ve=new WeakSet,We=async function(t,e){let n=await Zm(t,this);return"event"===n.type&&e&&e.length>0&&!0===e[0].removed&&(n=await Zm({orphan:"drop-log",log:e[0]},this)),Pn(this,ye).get(n.tag)||null},Ke=new WeakSet,ze=async function(t){const e=await Zm(t,this),n=e.tag;let r=Pn(this,ye).get(n);if(!r){r={subscriber:this._getSubscriber(e),tag:n,addressableMap:new WeakMap,nameMap:new Map,started:!1,listeners:[]},Pn(this,ye).set(n,r)}return r};const oy=new Uint8Array([]);function ay(t){const e=[];let n=0;for(let r=0;r<t.length;r++)e.push(oy),n+=32;for(let r=0;r<t.length;r++){const s=ta(t[r]);e[r]=sy(n),e.push(sy(s.length)),e.push(iy(s)),n+=32+32*Math.ceil(s.length/32)}return oa(e)}const cy="0x0000000000000000000000000000000000000000000000000000000000000000";function ly(t,e){if(t.provider)return t.provider;qo(!1,"missing provider","UNSUPPORTED_OPERATION",{operation:e})}async function uy(t,e){let n=Tg(e);if(null!=n.to&&(n.to=Yh(n.to,t)),null!=n.from){const e=n.from;n.from=Promise.all([t.getAddress(),Yh(e,t)]).then((([t,e])=>($o(t.toLowerCase()===e.toLowerCase(),"transaction from mismatch","tx.from",e),t)))}else n.from=t.getAddress();return await jo(n)}class hy{constructor(t){Nn(this,"provider"),Ho(this,{provider:t||null})}async getNonce(t){return ly(this,"getTransactionCount").getTransactionCount(await this.getAddress(),t)}async populateCall(t){return await uy(this,t)}async populateTransaction(t){const e=ly(this,"populateTransaction"),n=await uy(this,t);null==n.nonce&&(n.nonce=await this.getNonce("pending")),null==n.gasLimit&&(n.gasLimit=await this.estimateGas(n));const r=await this.provider.getNetwork();if(null!=n.chainId){$o(ya(n.chainId)===r.chainId,"transaction chainId mismatch","tx.chainId",t.chainId)}else n.chainId=r.chainId;const s=null!=n.maxFeePerGas||null!=n.maxPriorityFeePerGas;if(null==n.gasPrice||2!==n.type&&!s?0!==n.type&&1!==n.type||!s||$o(!1,"pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas","tx",t):$o(!1,"eip-1559 transaction do not support gasPrice","tx",t),2!==n.type&&null!=n.type||null==n.maxFeePerGas||null==n.maxPriorityFeePerGas)if(0===n.type||1===n.type){const t=await e.getFeeData();qo(null!=t.gasPrice,"network does not support gasPrice","UNSUPPORTED_OPERATION",{operation:"getGasPrice"}),null==n.gasPrice&&(n.gasPrice=t.gasPrice)}else{const t=await e.getFeeData();if(null==n.type)if(null!=t.maxFeePerGas&&null!=t.maxPriorityFeePerGas)if(n.authorizationList&&n.authorizationList.length?n.type=4:n.type=2,null!=n.gasPrice){const t=n.gasPrice;delete n.gasPrice,n.maxFeePerGas=t,n.maxPriorityFeePerGas=t}else null==n.maxFeePerGas&&(n.maxFeePerGas=t.maxFeePerGas),null==n.maxPriorityFeePerGas&&(n.maxPriorityFeePerGas=t.maxPriorityFeePerGas);else null!=t.gasPrice?(qo(!s,"network does not support EIP-1559","UNSUPPORTED_OPERATION",{operation:"populateTransaction"}),null==n.gasPrice&&(n.gasPrice=t.gasPrice),n.type=0):qo(!1,"failed to get consistent fee data","UNSUPPORTED_OPERATION",{operation:"signer.getFeeData"});else 2!==n.type&&3!==n.type&&4!==n.type||(null==n.maxFeePerGas&&(n.maxFeePerGas=t.maxFeePerGas),null==n.maxPriorityFeePerGas&&(n.maxPriorityFeePerGas=t.maxPriorityFeePerGas))}else n.type=2;return await jo(n)}async populateAuthorization(t){const e=Object.assign({},t);return null==e.chainId&&(e.chainId=(await ly(this,"getNetwork").getNetwork()).chainId),null==e.nonce&&(e.nonce=await this.getNonce()),e}async estimateGas(t){return ly(this,"estimateGas").estimateGas(await this.populateCall(t))}async call(t){return ly(this,"call").call(await this.populateCall(t))}async resolveName(t){const e=ly(this,"resolveName");return await e.resolveName(t)}async sendTransaction(t){const e=ly(this,"sendTransaction"),n=await this.populateTransaction(t);delete n.from;const r=Vd.from(n);return await e.broadcastTransaction(await this.signTransaction(r))}authorize(t){qo(!1,"authorization not implemented for this signer","UNSUPPORTED_OPERATION",{operation:"authorize"})}}qe=new WeakSet,$e=function(t,e){qo(!1,`VoidSigner cannot sign ${t}`,"UNSUPPORTED_OPERATION",{operation:e})};let dy=class t extends hy{constructor(t,e){super(e),Dn(this,qe),Nn(this,"address"),Ho(this,{address:t})}async getAddress(){return this.address}connect(e){return new t(this.address,e)}async signTransaction(t){Ln(this,qe,$e).call(this,"transactions","signTransaction")}async signMessage(t){Ln(this,qe,$e).call(this,"messages","signMessage")}async signTypedData(t,e,n){Ln(this,qe,$e).call(this,"typed-data","signTypedData")}};class fy{constructor(t){Dn(this,en),Dn(this,rn),Dn(this,Qe,void 0),Dn(this,Je,void 0),Dn(this,Ye,void 0),Dn(this,Ze,void 0),Dn(this,Xe,void 0),Dn(this,tn,void 0),Bn(this,Qe,t),Bn(this,Je,null),Bn(this,Ye,Ln(this,en,nn).bind(this)),Bn(this,Ze,!1),Bn(this,Xe,null),Bn(this,tn,!1)}_subscribe(t){throw new Error("subclasses must override this")}_emitResults(t,e){throw new Error("subclasses must override this")}_recover(t){throw new Error("subclasses must override this")}start(){Pn(this,Ze)||(Bn(this,Ze,!0),Ln(this,en,nn).call(this,-2))}stop(){Pn(this,Ze)&&(Bn(this,Ze,!1),Bn(this,tn,!0),Ln(this,rn,sn).call(this),Pn(this,Qe).off("block",Pn(this,Ye)))}pause(t){t&&Ln(this,rn,sn).call(this),Pn(this,Qe).off("block",Pn(this,Ye))}resume(){this.start()}}Qe=new WeakMap,Je=new WeakMap,Ye=new WeakMap,Ze=new WeakMap,Xe=new WeakMap,tn=new WeakMap,en=new WeakSet,nn=async function(t){try{null==Pn(this,Je)&&Bn(this,Je,this._subscribe(Pn(this,Qe)));let t=null;try{t=await Pn(this,Je)}catch(e){if(!Wo(e,"UNSUPPORTED_OPERATION")||"eth_newFilter"!==e.operation)throw e}if(null==t)return Bn(this,Je,null),void Pn(this,Qe)._recoverSubscriber(this,this._recover(Pn(this,Qe)));const n=await Pn(this,Qe).getNetwork();if(Pn(this,Xe)||Bn(this,Xe,n),Pn(this,Xe).chainId!==n.chainId)throw new Error("chaid changed");if(Pn(this,tn))return;const r=await Pn(this,Qe).send("eth_getFilterChanges",[t]);await this._emitResults(Pn(this,Qe),r)}catch(e){console.log("@TODO",e)}Pn(this,Qe).once("block",Pn(this,Ye))},rn=new WeakSet,sn=function(){const t=Pn(this,Je);t&&(Bn(this,Je,null),t.then((t=>{Pn(this,Qe).destroyed||Pn(this,Qe).send("eth_uninstallFilter",[t])})))};class py extends fy{constructor(t,e){var n;super(t),Dn(this,on,void 0),Bn(this,on,(n=e,JSON.parse(JSON.stringify(n))))}_recover(t){return new Km(t,Pn(this,on))}async _subscribe(t){return await t.send("eth_newFilter",[Pn(this,on)])}async _emitResults(t,e){for(const n of e)t.emit(Pn(this,on),t._wrapLog(n,t._network))}}on=new WeakMap;class gy extends fy{async _subscribe(t){return await t.send("eth_newPendingTransactionFilter",[])}async _emitResults(t,e){for(const n of e)t.emit("pending",n)}}const my="bigint,boolean,function,number,string,symbol".split(/,/g);function yy(t){if(null==t||my.indexOf(typeof t)>=0)return t;if("function"==typeof t.getAddress)return t;if(Array.isArray(t))return t.map(yy);if("object"==typeof t)return Object.keys(t).reduce(((e,n)=>(e[n]=t[n],e)),{});throw new Error(`should not happen: ${t} (${typeof t})`)}function wy(t){return new Promise((e=>{setTimeout(e,t)}))}function by(t){return t?t.toLowerCase():t}function Ay(t){return t&&"number"==typeof t.pollingInterval}const _y={polling:!1,staticNetwork:null,batchStallTime:10,batchMaxSize:1<<20,batchMaxCount:100,cacheTimeout:250,pollingInterval:4e3};class vy extends hy{constructor(t,e){super(t),Nn(this,"address"),Ho(this,{address:e=$h(e)})}connect(t){qo(!1,"cannot reconnect JsonRpcSigner","UNSUPPORTED_OPERATION",{operation:"signer.connect"})}async getAddress(){return this.address}async populateTransaction(t){return await this.populateCall(t)}async sendUncheckedTransaction(t){const e=yy(t),n=[];if(e.from){const r=e.from;n.push((async()=>{const n=await Yh(r,this.provider);$o(null!=n&&n.toLowerCase()===this.address.toLowerCase(),"from address mismatch","transaction",t),e.from=n})())}else e.from=this.address;if(null==e.gasLimit&&n.push((async()=>{e.gasLimit=await this.provider.estimateGas({...e,from:this.address})})()),null!=e.to){const t=e.to;n.push((async()=>{e.to=await Yh(t,this.provider)})())}n.length&&await Promise.all(n);const r=this.provider.getRpcTransaction(e);return this.provider.send("eth_sendTransaction",[r])}async sendTransaction(t){const e=await this.provider.getBlockNumber(),n=await this.sendUncheckedTransaction(t);return await new Promise(((t,r)=>{const s=[1e3,100];let i=0;const o=async()=>{try{const r=await this.provider.getTransaction(n);if(null!=r)return void t(r.replaceableTransaction(e))}catch(a){if(Wo(a,"CANCELLED")||Wo(a,"BAD_DATA")||Wo(a,"NETWORK_ERROR")||Wo(a,"UNSUPPORTED_OPERATION"))return null==a.info&&(a.info={}),a.info.sendTransactionHash=n,void r(a);if(Wo(a,"INVALID_ARGUMENT")&&(i++,null==a.info&&(a.info={}),a.info.sendTransactionHash=n,i>10))return void r(a);this.provider.emit("error",zo("failed to fetch transation after sending (will try again)","UNKNOWN_ERROR",{error:a}))}this.provider._setTimeout((()=>{o()}),s.pop()||4e3)};o()}))}async signTransaction(t){const e=yy(t);if(e.from){const n=await Yh(e.from,this.provider);$o(null!=n&&n.toLowerCase()===this.address.toLowerCase(),"from address mismatch","transaction",t),e.from=n}else e.from=this.address;const n=this.provider.getRpcTransaction(e);return await this.provider.send("eth_signTransaction",[n])}async signMessage(t){const e="string"==typeof t?Da(t):t;return await this.provider.send("personal_sign",[ia(e),this.address.toLowerCase()])}async signTypedData(t,e,n){const r=yy(n),s=await mp.resolveNames(t,e,r,(async t=>{const e=await Yh(t);return $o(null!=e,"TypedData does not support null address","value",t),e}));return await this.provider.send("eth_signTypedData_v4",[this.address.toLowerCase(),JSON.stringify(mp.getPayload(s.domain,e,s.value))])}async unlock(t){return this.provider.send("personal_unlockAccount",[this.address.toLowerCase(),t,null])}async _legacySignMessage(t){const e="string"==typeof t?Da(t):t;return await this.provider.send("eth_sign",[this.address.toLowerCase(),ia(e)])}}class Ey extends ey{constructor(t,e){super(t,e),Dn(this,pn),Dn(this,an,void 0),Dn(this,cn,void 0),Dn(this,ln,void 0),Dn(this,un,void 0),Dn(this,hn,void 0),Dn(this,dn,void 0),Dn(this,fn,void 0),Bn(this,cn,1),Bn(this,an,Object.assign({},_y,e||{})),Bn(this,ln,[]),Bn(this,un,null),Bn(this,dn,null),Bn(this,fn,null);{let t=null;const e=new Promise((e=>{t=e}));Bn(this,hn,{promise:e,resolve:t})}const n=this._getOption("staticNetwork");"boolean"==typeof n?($o(!n||"any"!==t,"staticNetwork cannot be used on special network 'any'","options",e),n&&null!=t&&Bn(this,dn,Bm.from(t))):n&&($o(null==t||n.matches(t),"staticNetwork MUST match network object","options",e),Bn(this,dn,n))}_getOption(t){return Pn(this,an)[t]}get _network(){return qo(Pn(this,dn),"network is not available yet","NETWORK_ERROR"),Pn(this,dn)}async _perform(t){if("call"===t.method||"estimateGas"===t.method){let e=t.transaction;if(e&&null!=e.type&&ya(e.type)&&null==e.maxFeePerGas&&null==e.maxPriorityFeePerGas){const n=await this.getFeeData();null==n.maxFeePerGas&&null==n.maxPriorityFeePerGas&&(t=Object.assign({},t,{transaction:Object.assign({},e,{type:void 0})}))}}const e=this.getRpcRequest(t);return null!=e?await this.send(e.method,e.args):super._perform(t)}async _detectNetwork(){const t=this._getOption("staticNetwork");if(t){if(!0!==t)return t;if(Pn(this,dn))return Pn(this,dn)}return Pn(this,fn)?await Pn(this,fn):this.ready?(Bn(this,fn,(async()=>{try{const t=Bm.from(ya(await this.send("eth_chainId",[])));return Bn(this,fn,null),t}catch(t){throw Bn(this,fn,null),t}})()),await Pn(this,fn)):(Bn(this,fn,(async()=>{const t={id:Un(this,cn)._++,method:"eth_chainId",params:[],jsonrpc:"2.0"};let e;this.emit("debug",{action:"sendRpcPayload",payload:t});try{e=(await this._send(t))[0],Bn(this,fn,null)}catch(n){throw Bn(this,fn,null),this.emit("debug",{action:"receiveRpcError",error:n}),n}if(this.emit("debug",{action:"receiveRpcResult",result:e}),"result"in e)return Bm.from(ya(e.result));throw this.getRpcError(t,e)})()),await Pn(this,fn))}_start(){null!=Pn(this,hn)&&null!=Pn(this,hn).resolve&&(Pn(this,hn).resolve(),Bn(this,hn,null),(async()=>{for(;null==Pn(this,dn)&&!this.destroyed;)try{Bn(this,dn,await this._detectNetwork())}catch(t){if(this.destroyed)break;console.log("JsonRpcProvider failed to detect network and cannot start up; retry in 1s (perhaps the URL is wrong or the node is not started)"),this.emit("error",zo("failed to bootstrap network detection","NETWORK_ERROR",{event:"initial-network-discovery",info:{error:t}})),await wy(1e3)}Ln(this,pn,gn).call(this)})())}async _waitUntilReady(){if(null!=Pn(this,hn))return await Pn(this,hn).promise}_getSubscriber(t){return"pending"===t.type?new gy(this):"event"===t.type?this._getOption("polling")?new Km(this,t.filter):new py(this,t.filter):"orphan"===t.type&&"drop-log"===t.filter.orphan?new Jm("orphan"):super._getSubscriber(t)}get ready(){return null==Pn(this,hn)}getRpcTransaction(t){const e={};return["chainId","gasLimit","gasPrice","type","maxFeePerGas","maxPriorityFeePerGas","nonce","value"].forEach((n=>{if(null==t[n])return;let r=n;"gasLimit"===n&&(r="gas"),e[r]=ka(ya(t[n],`tx.${n}`))})),["from","to","data"].forEach((n=>{null!=t[n]&&(e[n]=ia(t[n]))})),t.accessList&&(e.accessList=_d(t.accessList)),t.blobVersionedHashes&&(e.blobVersionedHashes=t.blobVersionedHashes.map((t=>t.toLowerCase()))),t.authorizationList&&(e.authorizationList=t.authorizationList.map((t=>{const e=vd(t);return{address:e.address,nonce:ka(e.nonce),chainId:ka(e.chainId),yParity:ka(e.signature.yParity),r:ka(e.signature.r),s:ka(e.signature.s)}}))),e}getRpcRequest(t){switch(t.method){case"chainId":return{method:"eth_chainId",args:[]};case"getBlockNumber":return{method:"eth_blockNumber",args:[]};case"getGasPrice":return{method:"eth_gasPrice",args:[]};case"getPriorityFee":return{method:"eth_maxPriorityFeePerGas",args:[]};case"getBalance":return{method:"eth_getBalance",args:[by(t.address),t.blockTag]};case"getTransactionCount":return{method:"eth_getTransactionCount",args:[by(t.address),t.blockTag]};case"getCode":return{method:"eth_getCode",args:[by(t.address),t.blockTag]};case"getStorage":return{method:"eth_getStorageAt",args:[by(t.address),"0x"+t.position.toString(16),t.blockTag]};case"broadcastTransaction":return{method:"eth_sendRawTransaction",args:[t.signedTransaction]};case"getBlock":if("blockTag"in t)return{method:"eth_getBlockByNumber",args:[t.blockTag,!!t.includeTransactions]};if("blockHash"in t)return{method:"eth_getBlockByHash",args:[t.blockHash,!!t.includeTransactions]};break;case"getTransaction":return{method:"eth_getTransactionByHash",args:[t.hash]};case"getTransactionReceipt":return{method:"eth_getTransactionReceipt",args:[t.hash]};case"call":return{method:"eth_call",args:[this.getRpcTransaction(t.transaction),t.blockTag]};case"estimateGas":return{method:"eth_estimateGas",args:[this.getRpcTransaction(t.transaction)]};case"getLogs":return t.filter&&null!=t.filter.address&&(Array.isArray(t.filter.address)?t.filter.address=t.filter.address.map(by):t.filter.address=by(t.filter.address)),{method:"eth_getLogs",args:[t.filter]}}return null}getRpcError(t,e){const{method:n}=t,{error:r}=e;if("eth_estimateGas"===n&&r.message){const e=r.message;if(!e.match(/revert/i)&&e.match(/insufficient funds/i))return zo("insufficient funds","INSUFFICIENT_FUNDS",{transaction:t.params[0],info:{payload:t,error:r}});if(e.match(/nonce/i)&&e.match(/too low/i))return zo("nonce has already been used","NONCE_EXPIRED",{transaction:t.params[0],info:{payload:t,error:r}})}if("eth_call"===n||"eth_estimateGas"===n){const e=Ty(r),s=pg.getBuiltinCallException("eth_call"===n?"call":"estimateGas",t.params[0],e?e.data:null);return s.info={error:r,payload:t},s}const s=JSON.stringify(function(t){const e=[];return Ry(t,e),e}(r));if("string"==typeof r.message&&r.message.match(/user denied|ethers-user-denied/i)){return zo("user rejected action","ACTION_REJECTED",{action:{eth_sign:"signMessage",personal_sign:"signMessage",eth_signTypedData_v4:"signTypedData",eth_signTransaction:"signTransaction",eth_sendTransaction:"sendTransaction",eth_requestAccounts:"requestAccess",wallet_requestAccounts:"requestAccess"}[n]||"unknown",reason:"rejected",info:{payload:t,error:r}})}if("eth_sendRawTransaction"===n||"eth_sendTransaction"===n){const e=t.params[0];if(s.match(/insufficient funds|base fee exceeds gas limit/i))return zo("insufficient funds for intrinsic transaction cost","INSUFFICIENT_FUNDS",{transaction:e,info:{error:r}});if(s.match(/nonce/i)&&s.match(/too low/i))return zo("nonce has already been used","NONCE_EXPIRED",{transaction:e,info:{error:r}});if(s.match(/replacement transaction/i)&&s.match(/underpriced/i))return zo("replacement fee too low","REPLACEMENT_UNDERPRICED",{transaction:e,info:{error:r}});if(s.match(/only replay-protected/i))return zo("legacy pre-eip-155 transactions not supported","UNSUPPORTED_OPERATION",{operation:n,info:{transaction:e,info:{error:r}}})}let i=!!s.match(/the method .* does not exist/i);return i||r&&r.details&&r.details.startsWith("Unauthorized method:")&&(i=!0),i?zo("unsupported operation","UNSUPPORTED_OPERATION",{operation:t.method,info:{error:r,payload:t}}):zo("could not coalesce error","UNKNOWN_ERROR",{error:r,payload:t})}send(t,e){if(this.destroyed)return Promise.reject(zo("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:t}));const n=Un(this,cn)._++,r=new Promise(((r,s)=>{Pn(this,ln).push({resolve:r,reject:s,payload:{method:t,params:e,id:n,jsonrpc:"2.0"}})}));return Ln(this,pn,gn).call(this),r}async getSigner(t){null==t&&(t=0);const e=this.send("eth_accounts",[]);if("number"==typeof t){const n=await e;if(t>=n.length)throw new Error("no such account");return new vy(this,n[t])}const{accounts:n}=await jo({network:this.getNetwork(),accounts:e});t=$h(t);for(const r of n)if($h(r)===t)return new vy(this,t);throw new Error("invalid account")}async listAccounts(){return(await this.send("eth_accounts",[])).map((t=>new vy(this,t)))}destroy(){Pn(this,un)&&(clearTimeout(Pn(this,un)),Bn(this,un,null));for(const{payload:t,reject:e}of Pn(this,ln))e(zo("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:t.method}));Bn(this,ln,[]),super.destroy()}}an=new WeakMap,cn=new WeakMap,ln=new WeakMap,un=new WeakMap,hn=new WeakMap,dn=new WeakMap,fn=new WeakMap,pn=new WeakSet,gn=function(){if(Pn(this,un))return;const t=1===this._getOption("batchMaxCount")?0:this._getOption("batchStallTime");Bn(this,un,setTimeout((()=>{Bn(this,un,null);const t=Pn(this,ln);for(Bn(this,ln,[]);t.length;){const e=[t.shift()];for(;t.length&&e.length!==Pn(this,an).batchMaxCount;){e.push(t.shift());if(JSON.stringify(e.map((t=>t.payload))).length>Pn(this,an).batchMaxSize){t.unshift(e.pop());break}}(async()=>{const t=1===e.length?e[0].payload:e.map((t=>t.payload));this.emit("debug",{action:"sendRpcPayload",payload:t});try{const n=await this._send(t);this.emit("debug",{action:"receiveRpcResult",result:n});for(const{resolve:t,reject:r,payload:s}of e){if(this.destroyed){r(zo("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:s.method}));continue}const e=n.filter((t=>t.id===s.id))[0];if(null!=e)"error"in e?r(this.getRpcError(s,e)):t(e.result);else{const t=zo("missing response for request","BAD_DATA",{value:n,info:{payload:s}});this.emit("error",t),r(t)}}}catch(n){this.emit("debug",{action:"receiveRpcError",error:n});for(const{reject:t}of e)t(n)}})()}}),t))};class ky extends Ey{constructor(t,e){super(t,e),Dn(this,mn,void 0);let n=this._getOption("pollingInterval");null==n&&(n=_y.pollingInterval),Bn(this,mn,n)}_getSubscriber(t){const e=super._getSubscriber(t);return Ay(e)&&(e.pollingInterval=Pn(this,mn)),e}get pollingInterval(){return Pn(this,mn)}set pollingInterval(t){if(!Number.isInteger(t)||t<0)throw new Error("invalid interval");Bn(this,mn,t),this._forEachSubscriber((t=>{Ay(t)&&(t.pollingInterval=Pn(this,mn))}))}}mn=new WeakMap;class Sy extends ky{constructor(t,e,n){null==t&&(t="http://localhost:8545"),super(e,n),Dn(this,yn,void 0),Bn(this,yn,"string"==typeof t?new $a(t):t.clone())}_getConnection(){return Pn(this,yn).clone()}async send(t,e){return await this._start(),await super.send(t,e)}async _send(t){const e=this._getConnection();e.body=JSON.stringify(t),e.setHeader("content-type","application/json");const n=await e.send();n.assertOk();let r=n.bodyJson;return Array.isArray(r)||(r=[r]),r}}function Ty(t){if(null==t)return null;if("string"==typeof t.message&&t.message.match(/revert/i)&&na(t.data))return{message:t.message,data:t.data};if("object"==typeof t){for(const e in t){const n=Ty(t[e]);if(n)return n}return null}if("string"==typeof t)try{return Ty(JSON.parse(t))}catch(e){}return null}function Ry(t,e){if(null!=t){if("string"==typeof t.message&&e.push(t.message),"object"==typeof t)for(const n in t)Ry(t[n],e);if("string"==typeof t)try{return Ry(JSON.parse(t),e)}catch(n){}}}yn=new WeakMap;wn=new WeakMap;let Iy=class t extends hy{constructor(t,e){super(e),Nn(this,"address"),Dn(this,wn,void 0),$o(t&&"function"==typeof t.sign,"invalid private key","privateKey","[ REDACTED ]"),Bn(this,wn,t);Ho(this,{address:Ed(this.signingKey.publicKey)})}get signingKey(){return Pn(this,wn)}get privateKey(){return this.signingKey.privateKey}async getAddress(){return this.address}connect(e){return new t(Pn(this,wn),e)}async signTransaction(t){t=Tg(t);const{to:e,from:n}=await jo({to:t.to?Yh(t.to,this):void 0,from:t.from?Yh(t.from,this):void 0});null!=e&&(t.to=e),null!=n&&(t.from=n),null!=t.from&&($o($h(t.from)===this.address,"transaction from address mismatch","tx.from",t.from),delete t.from);const r=Vd.from(t);return r.signature=this.signingKey.sign(r.unsignedHash),r.serialized}async signMessage(t){return this.signMessageSync(t)}signMessageSync(t){return this.signingKey.sign(function(t){return"string"==typeof t&&(t=Da(t)),Bl(oa([Da("Ethereum Signed Message:\n"),Da(String(t.length)),t]))}(t)).serialized}authorizeSync(t){$o("string"==typeof t.address,"invalid address for authorizeSync","auth.address",t);const e=this.signingKey.sign(function(t){return $o("string"==typeof t.address,"invalid address for hashAuthorization","auth.address",t),Bl(oa(["0x05",oc([null!=t.chainId?Ea(t.chainId):"0x",$h(t.address),null!=t.nonce?Ea(t.nonce):"0x"])]))}(t));return Object.assign({},{address:$h(t.address),nonce:ya(t.nonce||0),chainId:ya(t.chainId||0)},{signature:e})}async authorize(t){return t=Object.assign({},t,{address:await Yh(t.address,this)}),this.authorizeSync(await this.populateAuthorization(t))}async signTypedData(t,e,n){const r=await mp.resolveNames(t,e,n,(async t=>{qo(null!=this.provider,"cannot resolve ENS names without a provider","UNSUPPORTED_OPERATION",{operation:"resolveName",info:{name:t}});const e=await this.provider.resolveName(t);return qo(null!=e,"unconfigured ENS name","UNCONFIGURED_NAME",{value:t}),e}));return this.signingKey.sign(mp.hash(r.domain,e,r.value)).serialized}};const Oy=" !#$%&'()*+,-./<=>?@[]^_`{|}~",Cy=/^[a-z]*$/i;function Ny(t,e){let n=97;return t.reduce(((t,r)=>(r===e?n++:r.match(Cy)?t.push(String.fromCharCode(n)+r):(n=97,t.push(r)),t)),[])}function xy(t){return $o("0"===t[0],"unsupported auwl data","data",t),function(t,e){for(let s=28;s>=0;s--)t=t.split(Oy[s]).join(e.substring(2*s,2*s+2));const n=[],r=t.replace(/(:|([0-9])|([A-Z][a-z]*))/g,((t,e,r,s)=>{if(r)for(let i=parseInt(r);i>=0;i--)n.push(";");else n.push(e.toLowerCase());return""}));if(r)throw new Error(`leftovers: ${JSON.stringify(r)}`);return Ny(Ny(n,";"),":")}(t.substring(59),t.substring(1,59))}class Py{constructor(t){Nn(this,"locale"),Ho(this,{locale:t})}split(t){return t.toLowerCase().split(/\s+/g)}join(t){return t.join(" ")}}class Dy extends Py{constructor(t,e,n){super(t),Dn(this,vn),Dn(this,bn,void 0),Dn(this,An,void 0),Dn(this,_n,void 0),Bn(this,bn,e),Bn(this,An,n),Bn(this,_n,null)}get _data(){return Pn(this,bn)}_decodeWords(){return xy(Pn(this,bn))}getWord(t){const e=Ln(this,vn,En).call(this);return $o(t>=0&&t<e.length,`invalid word index: ${t}`,"index",t),e[t]}getWordIndex(t){return Ln(this,vn,En).call(this).indexOf(t)}}bn=new WeakMap,An=new WeakMap,_n=new WeakMap,vn=new WeakSet,En=function(){if(null==Pn(this,_n)){const t=this._decodeWords();if(Wd(t.join("\n")+"\n")!==Pn(this,An))throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`);Bn(this,_n,t)}return Pn(this,_n)};let By=null;class Uy extends Dy{constructor(){super("en","0erleonalorenseinceregesticitStanvetearctssi#ch2Athck&tneLl0And#Il.yLeOutO=S|S%b/ra@SurdU'0Ce[Cid|CountCu'Hie=IdOu,-Qui*Ro[TT]T%T*[Tu$0AptDD-tD*[Ju,M.UltV<)Vi)0Rob-0FairF%dRaid0A(EEntRee0Ead0MRRp%tS!_rmBumCoholErtI&LLeyLowMo,O}PhaReadySoT Ways0A>urAz(gOngOuntU'd0Aly,Ch%Ci|G G!GryIm$K!Noun)Nu$O` Sw T&naTiqueXietyY1ArtOlogyPe?P!Pro=Ril1ChCt-EaEnaGueMMedM%MyOundR<+Re,Ri=RowTTefa@Ti,Tw%k0KPe@SaultSetSi,SumeThma0H!>OmTa{T&dT.udeTra@0Ct]D.Gu,NtTh%ToTumn0Era+OcadoOid0AkeA*AyEsomeFulKw?d0Is:ByChel%C#D+GL<)Lc#y~MbooN<aNn RRelyRga(R*lSeS-SketTt!3A^AnAutyCau'ComeEfF%eG(Ha=H(dLie=LowLtN^Nef./TrayTt Twe&Y#d3Cyc!DKeNdOlogyRdR`Tt _{AdeAmeAnketA,EakE[IndOodO[omOu'UeUrUsh_rdAtDyIlMbNeNusOkO,Rd R(gRrowSsTtomUn)XY_{etA(AndA[A=EadEezeI{Id+IefIghtIngIskOccoliOk&OnzeOomO` OwnUsh2Bb!DdyD+tFf$oIldLbLkL!tNd!Nk Rd&Rg R,SS(e[SyTt Y Zz:Bba+B(B!CtusGeKe~LmM aMpNN$N)lNdyNn#NoeNvasNy#Pab!P.$Pta(RRb#RdRgoRpetRryRtSeShS(o/!Su$TT$ogT^Teg%yTt!UghtU'Ut]Ve3Il(gL yM|NsusNturyRe$Rta(_irAlkAmp]An+AosApt Ar+A'AtEapE{Ee'EfErryE,I{&IefIldIm}yOi)Oo'R#-U{!UnkUrn0G?Nnam#Rc!Tiz&TyVil_imApArifyAwAyE<ErkEv I{I|IffImbIn-IpO{OgO'O`OudOwnUbUmpU, Ut^_^A,C#utDeFfeeIlInL!@L%LumnMb(eMeMf%tM-Mm#Mp<yNc tNdu@NfirmNg*[N}@Nsid NtrolNv()OkOlPp PyR$ReRnR*@/Tt#U^UntryUp!Ur'Us(V Yo>_{Ad!AftAmA}AshAt AwlAzyEamEd.EekEwI{etImeIspIt-OpO[Ou^OwdUci$UelUi'Umb!Un^UshYY,$2BeLtu*PPbo?dRiousRr|Rta(R=Sh]/omTe3C!:DMa+MpN)Ng R(gShUght WnY3AlBa>BrisCadeCemb CideCl(eC%a>C*a'ErF&'F(eFyG*eLayLiv M<dMi'Ni$Nti,NyP?tP&dPos.P`PutyRi=ScribeS tSignSkSpair/royTailTe@VelopVi)Vo>3AgramAlAm#dAryCeE'lEtFf G.$Gn.yLemmaNn NosaurRe@RtSag*eScov Sea'ShSmi[S%d Splay/<)V tVideV%)Zzy5Ct%Cum|G~Lph(Ma(Na>NkeyN%OrSeUb!Ve_ftAg#AmaA,-AwEamE[IftIllInkIpI=OpUmY2CkMbNeR(g/T^Ty1Arf1Nam-:G G!RlyRnR`Sily/Sy1HoOlogyOnomy0GeItUca>1F%t0G1GhtTh 2BowD E@r-Eg<tEm|Eph<tEvat%I>Se0B?kBodyBra)Er+Ot]PloyPow Pty0Ab!A@DD![D%'EmyErgyF%)Ga+G(eH<)JoyLi,OughR-hRollSu*T Ti*TryVelope1Isode0U$Uip0AA'OdeOs]R%Upt0CapeSayS&)Ta>0Ern$H-s1Id&)IlOkeOl=1A@Amp!Ce[Ch<+C.eCludeCu'Ecu>Erci'Hau,Hib.I!I,ItOt-P<dPe@Pi*Pla(Po'P*[T&dTra0EEbrow:Br-CeCultyDeIntI`~L'MeMilyMousNNcyNtasyRmSh]TT$Th TigueUltV%.e3Atu*Bru?yD $EEdElMa!N)/iv$T^V W3B Ct]EldGu*LeLmLt N$NdNeNg NishReRmR,Sc$ShTT}[X_gAmeAshAtAv%EeIghtIpOatO{O%Ow UidUshY_mCusGIlLd~owOdOtR)Re,R+tRkRtu}RumRw?dSsil/ UndX_gi!AmeEqu|EshI&dIn+OgOntO,OwnOz&U.2ElNNnyRna)RyTu*:D+tInLaxy~ yMePRa+Rba+Rd&Rl-Rm|SSpTeTh U+Ze3N $NiusN*Nt!Nu(e/u*2O,0AntFtGg!Ng RaffeRlVe_dAn)A*A[IdeImp'ObeOomOryO=OwUe_tDde[LdOdO'RillaSpelSsipV nWn_bA)A(AntApeA[Av.yEatE&IdIefItOc yOupOwUnt_rdE[IdeIltIt?N3M:B.IrLfMm M, NdPpyRb%RdRshR=,TVeWkZ?d3AdAl`ArtAvyD+hogIght~oLmetLpNRo3Dd&Gh~NtPRe/%y5BbyCkeyLdLeLiday~owMeNeyOdPeRnRr%R'Sp.$/TelUrV 5BGeM<Mb!M%Nd*dNgryNtRd!RryRtSb<d3Brid:1EOn0EaEntifyLe2N%e4LLeg$L}[0A+Ita>M&'Mu}Pa@Po'Pro=Pul'0ChCludeComeC*a'DexD-a>Do%Du,ryF<tFl-tF%mHa!H .Iti$Je@JuryMa>N Noc|PutQuiryS<eSe@SideSpi*/$lTa@T e,ToVe,V.eVol=3On0L<dOla>Sue0Em1Ory:CketGu?RZz3AlousAns~yWel9BInKeUr}yY5D+I)MpNg!Ni%Nk/:Ng?oo3EnEpT^upY3CkDD}yNdNgdomSsTT^&TeTt&Wi4EeIfeO{Ow:BBelB%Dd DyKeMpNgua+PtopR+T T(UghUndryVaWWnWsu.Y Zy3Ad AfArnA=Ctu*FtGG$G&dIsu*M#NdNg`NsOp?dSs#Tt Vel3ArB tyBr?yC&'FeFtGhtKeMbM.NkOnQuid/Tt!VeZ?d5AdAnB, C$CkG-NelyNgOpTt yUdUn+VeY$5CkyGga+Mb N?N^Xury3R-s:Ch(eDG-G}tIdIlInJ%KeMm$NNa+Nda>NgoNs]Nu$P!Rb!R^Rg(R(eRketRria+SkSs/ T^T i$ThTrixTt XimumZe3AdowAnAsu*AtCh<-D$DiaLodyLtMb M%yNt]NuRcyR+R.RryShSsa+T$Thod3Dd!DnightLk~]M-NdNimumN%Nu>Rac!Rr%S ySs/akeXXedXtu*5Bi!DelDifyMM|N.%NkeyN, N`OnR$ReRn(gSqu.oTh T]T%Unta(U'VeVie5ChFf(LeLtiplySc!SeumShroomS-/Tu$3Self/ yTh:I=MePk(Rrow/yT]Tu*3ArCkEdGati=G!@I` PhewR=/TTw%kUtr$V WsXt3CeGht5B!I'M(eeOd!Rm$R`SeTab!TeTh(gTi)VelW5C!?Mb R'T:K0EyJe@Li+Scu*S =Ta(Vious0CurE<Tob 0Or1FF Fi)T&2L1Ay0DI=Ymp-0It0CeEI#L(eLy1EnEraIn]Po'T]1An+B.Ch?dD D(?yG<I|Ig($Ph<0Tr-h0H 0Tdo%T TputTside0AlEnEr0NN 0Yg&0/ 0O}:CtDd!GeIrLa)LmNdaNelN-N` P RadeR|RkRrotRtySsT^ThTi|TrolTt nU'VeYm|3A)AnutArAs<tL-<NN$tyNcilOp!Pp Rfe@Rm.Rs#T2O}OtoRa'Ys-$0AnoCn-Ctu*E)GGe#~LotNkO} Pe/olT^Zza_)A}tA,-A>AyEa'Ed+U{UgUn+2EmEtIntL?LeLi)NdNyOlPul?Rt]S.]Ssib!/TatoTt yV tyWd W _@i)Ai'Ed-tEf Epa*Es|EttyEv|I)IdeIm?yIntI%.yIs#Iva>IzeOb!mO)[Odu)Of.OgramOje@Omo>OofOp tyOsp O>@OudOvide2Bl-Dd(g~LpL'Mpk(N^PilPpyR^a'R.yRpo'R'ShTZz!3Ramid:99Al.yAntumArt E,]I{ItIzO>:Bb.Cco#CeCkD?DioIlInI'~yMpN^NdomN+PidReTeTh V&WZ%3AdyAlAs#BelBuildC$lCei=CipeC%dCyc!Du)F!@F%mFu'G]G*tGul?Je@LaxLea'LiefLyMa(Memb M(dMo=Nd NewNtOp&PairPeatPla)P%tQui*ScueSemb!Si,Sour)Sp#'SultTi*T*atTurnUn]Ve$ViewW?d2Y`m0BBb#CeChDeD+F!GhtGidNgOtPp!SkTu$V$V 5AdA,BotBu,CketM<)OfOkieOmSeTa>UghUndU>Y$5Bb DeGLeNNwayR$:DDd!D}[FeIlLadLm#L#LtLu>MeMp!NdTisfyToshiU)Usa+VeY1A!AnA*Att E}HemeHoolI&)I[%sOrp]OutRapRe&RiptRub1AAr^As#AtC#dC*tCt]Cur.yEdEkGm|Le@~M(?Ni%N'Nt&)RiesRvi)Ss]Tt!TupV&_dowAftAllowA*EdEllEriffIeldIftI}IpIv O{OeOotOpOrtOuld O=RimpRugUff!Y0Bl(gCkDeE+GhtGnL|Lk~yLv Mil?Mp!N)NgR&/ Tua>XZe1A>Et^IIllInIrtUll0AbAmEepEnd I)IdeIghtImOg<OtOwUsh0AllArtI!OkeOo`0A{AkeApIffOw0ApCc Ci$CkDaFtL?Ldi LidLut]L=Me#eNgOnRryRtUlUndUpUr)U`0A)A*Ati$AwnEakEci$EedEllEndH eI)Id IkeInIr.L.OilOns%O#OrtOtRayReadR(gY0Ua*UeezeUir*l_b!AdiumAffA+AirsAmpAndArtA>AyEakEelEmEpE*oI{IllIngO{Oma^O}OolOryO=Ra>gyReetRikeR#gRugg!Ud|UffUmb!Y!0Bje@Bm.BwayC)[ChDd&Ff G?G+,ItMm NNnyN'tP PplyP*meReRfa)R+Rpri'RroundR=ySpe@/a(1AllowAmpApArmE?EetIftImIngIt^Ord1MbolMptomRup/em:B!Ck!GIlL|LkNkPeR+tSk/eTtooXi3A^Am~NN<tNnisNtRm/Xt_nkAtEmeEnE%yE*EyIngIsOughtReeRi=RowUmbUnd 0CketDeG LtMb MeNyPRedSsueT!5A,BaccoDayDdl EGe` I!tK&MatoM%rowNeNgueNightOlO`PP-Pp!R^RnadoRtoi'SsT$Uri,W?dW WnY_{AdeAff-Ag-A(Ansf ApAshA=lAyEatEeEndI$IbeI{Igg ImIpOphyOub!U{UeUlyUmpetU,U`Y2BeIt]Mb!NaN}lRkeyRnRt!1El=EntyI)InI,O1PeP-$:5Ly5B*lla0Ab!Awa*C!Cov D DoFairFoldHappyIf%mIqueItIv 'KnownLo{TilUsu$Veil1Da>GradeHoldOnP Set1B<Ge0A+EEdEfulE![U$0Il.y:C<tCuumGueLidL!yL=NNishP%Rious/Ult3H-!L=tNd%Ntu*NueRbRifyRs]RyS'lT <3Ab!Br<tCiousCt%yDeoEw~a+Nta+Ol(Rtu$RusSaS.Su$T$Vid5C$I)IdLc<oLumeTeYa+:GeG#ItLk~LnutNtRfa*RmRri%ShSp/eT VeY3Al`Ap#ArA'lA` BDd(gEk&dIrdLcome/T_!AtEatEelEnE*IpIsp 0DeD`FeLd~NNdowNeNgNkNn Nt ReSdomSeShT}[5LfM<Nd OdOlRdRkRldRryR`_pE{E,!I,I>Ong::Rd3Ar~ow9UUngU`:3BraRo9NeO","0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60")}static wordlist(){return null==By&&(By=new Uy),By}}function Ly(t){return(1<<t)-1<<8-t&255}function My(t,e){Yo("NFKD"),null==e&&(e=Uy.wordlist());const n=e.split(t);$o(n.length%3==0&&n.length>=12&&n.length<=24,"invalid mnemonic length","mnemonic","[ REDACTED ]");const r=new Uint8Array(Math.ceil(11*n.length/8));let s=0;for(let a=0;a<n.length;a++){let t=e.getWordIndex(n[a].normalize("NFKD"));$o(t>=0,`invalid mnemonic word at index ${a}`,"mnemonic","[ REDACTED ]");for(let e=0;e<11;e++)t&1<<10-e&&(r[s>>3]|=1<<7-s%8),s++}const i=32*n.length/3,o=Ly(n.length/3);return $o((ta(ku(r.slice(0,i/8)))[0]&o)===(r[r.length-1]&o),"invalid mnemonic checksum","mnemonic","[ REDACTED ]"),ia(r.slice(0,i/8))}function Fy(t,e){$o(t.length%4==0&&t.length>=16&&t.length<=32,"invalid entropy size","entropy","[ REDACTED ]"),null==e&&(e=Uy.wordlist());const n=[0];let r=11;for(let o=0;o<t.length;o++)r>8?(n[n.length-1]<<=8,n[n.length-1]|=t[o],r-=8):(n[n.length-1]<<=r,n[n.length-1]|=t[o]>>8-r,n.push(t[o]&((1<<8-r)-1&255)),r+=3);const s=t.length/4,i=parseInt(ku(t).substring(2,4),16)&Ly(s);return n[n.length-1]<<=s,n[n.length-1]|=i>>8-s,e.join(n.map((t=>e.getWord(t))))}const Gy={};class jy{constructor(t,e,n,r,s){Nn(this,"phrase"),Nn(this,"password"),Nn(this,"wordlist"),Nn(this,"entropy"),null==r&&(r=""),null==s&&(s=Uy.wordlist()),Zo(t,Gy,"Mnemonic"),Ho(this,{phrase:n,password:r,wordlist:s,entropy:e})}computeSeed(){const t=Da("mnemonic"+this.password,"NFKD");return ru(Da(this.phrase,"NFKD"),t,2048,64,"sha512")}static fromPhrase(t,e,n){const r=My(t,n);return t=Fy(ta(r),n),new jy(Gy,r,t,e,n)}static fromEntropy(t,e,n){const r=ta(t,"entropy"),s=Fy(r,n);return new jy(Gy,ia(r),s,e,n)}static entropyToPhrase(t,e){return Fy(ta(t,"entropy"),e)}static phraseToEntropy(t,e){return My(t,e)}static isValidMnemonic(t,e){try{return My(t,e),!0}catch(n){}return!1}}
12
- /*! MIT License. Copyright 2015-2022 Richard Moore <me@ricmoo.com>. See LICENSE.txt. */var Hy,Vy,Wy,Ky=globalThis&&globalThis.__classPrivateFieldGet||function(t,e,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(t):r?r.value:e.get(t)},zy=globalThis&&globalThis.__classPrivateFieldSet||function(t,e,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(t,n):s?s.value=n:e.set(t,n),n};const qy={16:10,24:12,32:14},$y=[1,2,4,8,16,32,64,128,27,54,108,216,171,77,154,47,94,188,99,198,151,53,106,212,179,125,250,239,197,145],Qy=[99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22],Jy=[82,9,106,213,48,54,165,56,191,64,163,158,129,243,215,251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50,166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91,162,73,109,139,209,37,114,248,246,100,134,104,152,22,212,164,92,204,93,101,182,146,108,112,72,80,253,237,185,218,94,21,70,87,167,141,157,132,144,216,171,0,140,188,211,10,247,228,88,5,184,179,69,6,208,44,30,143,202,63,15,2,193,175,189,3,1,19,138,107,58,145,17,65,79,103,220,234,151,242,207,206,240,180,230,115,150,172,116,34,231,173,53,133,226,249,55,232,28,117,223,110,71,241,26,113,29,41,197,137,111,183,98,14,170,24,190,27,252,86,62,75,198,210,121,32,154,219,192,254,120,205,90,244,31,221,168,51,136,7,199,49,177,18,16,89,39,128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224,59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38,225,105,20,99,85,33,12,125],Yy=[3328402341,4168907908,4000806809,4135287693,4294111757,3597364157,3731845041,2445657428,1613770832,33620227,3462883241,1445669757,3892248089,3050821474,1303096294,3967186586,2412431941,528646813,2311702848,4202528135,4026202645,2992200171,2387036105,4226871307,1101901292,3017069671,1604494077,1169141738,597466303,1403299063,3832705686,2613100635,1974974402,3791519004,1033081774,1277568618,1815492186,2118074177,4126668546,2211236943,1748251740,1369810420,3521504564,4193382664,3799085459,2883115123,1647391059,706024767,134480908,2512897874,1176707941,2646852446,806885416,932615841,168101135,798661301,235341577,605164086,461406363,3756188221,3454790438,1311188841,2142417613,3933566367,302582043,495158174,1479289972,874125870,907746093,3698224818,3025820398,1537253627,2756858614,1983593293,3084310113,2108928974,1378429307,3722699582,1580150641,327451799,2790478837,3117535592,0,3253595436,1075847264,3825007647,2041688520,3059440621,3563743934,2378943302,1740553945,1916352843,2487896798,2555137236,2958579944,2244988746,3151024235,3320835882,1336584933,3992714006,2252555205,2588757463,1714631509,293963156,2319795663,3925473552,67240454,4269768577,2689618160,2017213508,631218106,1269344483,2723238387,1571005438,2151694528,93294474,1066570413,563977660,1882732616,4059428100,1673313503,2008463041,2950355573,1109467491,537923632,3858759450,4260623118,3218264685,2177748300,403442708,638784309,3287084079,3193921505,899127202,2286175436,773265209,2479146071,1437050866,4236148354,2050833735,3362022572,3126681063,840505643,3866325909,3227541664,427917720,2655997905,2749160575,1143087718,1412049534,999329963,193497219,2353415882,3354324521,1807268051,672404540,2816401017,3160301282,369822493,2916866934,3688947771,1681011286,1949973070,336202270,2454276571,201721354,1210328172,3093060836,2680341085,3184776046,1135389935,3294782118,965841320,831886756,3554993207,4068047243,3588745010,2345191491,1849112409,3664604599,26054028,2983581028,2622377682,1235855840,3630984372,2891339514,4092916743,3488279077,3395642799,4101667470,1202630377,268961816,1874508501,4034427016,1243948399,1546530418,941366308,1470539505,1941222599,2546386513,3421038627,2715671932,3899946140,1042226977,2521517021,1639824860,227249030,260737669,3765465232,2084453954,1907733956,3429263018,2420656344,100860677,4160157185,470683154,3261161891,1781871967,2924959737,1773779408,394692241,2579611992,974986535,664706745,3655459128,3958962195,731420851,571543859,3530123707,2849626480,126783113,865375399,765172662,1008606754,361203602,3387549984,2278477385,2857719295,1344809080,2782912378,59542671,1503764984,160008576,437062935,1707065306,3622233649,2218934982,3496503480,2185314755,697932208,1512910199,504303377,2075177163,2824099068,1841019862,739644986],Zy=[2781242211,2230877308,2582542199,2381740923,234877682,3184946027,2984144751,1418839493,1348481072,50462977,2848876391,2102799147,434634494,1656084439,3863849899,2599188086,1167051466,2636087938,1082771913,2281340285,368048890,3954334041,3381544775,201060592,3963727277,1739838676,4250903202,3930435503,3206782108,4149453988,2531553906,1536934080,3262494647,484572669,2923271059,1783375398,1517041206,1098792767,49674231,1334037708,1550332980,4098991525,886171109,150598129,2481090929,1940642008,1398944049,1059722517,201851908,1385547719,1699095331,1587397571,674240536,2704774806,252314885,3039795866,151914247,908333586,2602270848,1038082786,651029483,1766729511,3447698098,2682942837,454166793,2652734339,1951935532,775166490,758520603,3000790638,4004797018,4217086112,4137964114,1299594043,1639438038,3464344499,2068982057,1054729187,1901997871,2534638724,4121318227,1757008337,0,750906861,1614815264,535035132,3363418545,3988151131,3201591914,1183697867,3647454910,1265776953,3734260298,3566750796,3903871064,1250283471,1807470800,717615087,3847203498,384695291,3313910595,3617213773,1432761139,2484176261,3481945413,283769337,100925954,2180939647,4037038160,1148730428,3123027871,3813386408,4087501137,4267549603,3229630528,2315620239,2906624658,3156319645,1215313976,82966005,3747855548,3245848246,1974459098,1665278241,807407632,451280895,251524083,1841287890,1283575245,337120268,891687699,801369324,3787349855,2721421207,3431482436,959321879,1469301956,4065699751,2197585534,1199193405,2898814052,3887750493,724703513,2514908019,2696962144,2551808385,3516813135,2141445340,1715741218,2119445034,2872807568,2198571144,3398190662,700968686,3547052216,1009259540,2041044702,3803995742,487983883,1991105499,1004265696,1449407026,1316239930,504629770,3683797321,168560134,1816667172,3837287516,1570751170,1857934291,4014189740,2797888098,2822345105,2754712981,936633572,2347923833,852879335,1133234376,1500395319,3084545389,2348912013,1689376213,3533459022,3762923945,3034082412,4205598294,133428468,634383082,2949277029,2398386810,3913789102,403703816,3580869306,2297460856,1867130149,1918643758,607656988,4049053350,3346248884,1368901318,600565992,2090982877,2632479860,557719327,3717614411,3697393085,2249034635,2232388234,2430627952,1115438654,3295786421,2865522278,3633334344,84280067,33027830,303828494,2747425121,1600795957,4188952407,3496589753,2434238086,1486471617,658119965,3106381470,953803233,334231800,3005978776,857870609,3151128937,1890179545,2298973838,2805175444,3056442267,574365214,2450884487,550103529,1233637070,4289353045,2018519080,2057691103,2399374476,4166623649,2148108681,387583245,3664101311,836232934,3330556482,3100665960,3280093505,2955516313,2002398509,287182607,3413881008,4238890068,3597515707,975967766],Xy=[1671808611,2089089148,2006576759,2072901243,4061003762,1807603307,1873927791,3310653893,810573872,16974337,1739181671,729634347,4263110654,3613570519,2883997099,1989864566,3393556426,2191335298,3376449993,2106063485,4195741690,1508618841,1204391495,4027317232,2917941677,3563566036,2734514082,2951366063,2629772188,2767672228,1922491506,3227229120,3082974647,4246528509,2477669779,644500518,911895606,1061256767,4144166391,3427763148,878471220,2784252325,3845444069,4043897329,1905517169,3631459288,827548209,356461077,67897348,3344078279,593839651,3277757891,405286936,2527147926,84871685,2595565466,118033927,305538066,2157648768,3795705826,3945188843,661212711,2999812018,1973414517,152769033,2208177539,745822252,439235610,455947803,1857215598,1525593178,2700827552,1391895634,994932283,3596728278,3016654259,695947817,3812548067,795958831,2224493444,1408607827,3513301457,0,3979133421,543178784,4229948412,2982705585,1542305371,1790891114,3410398667,3201918910,961245753,1256100938,1289001036,1491644504,3477767631,3496721360,4012557807,2867154858,4212583931,1137018435,1305975373,861234739,2241073541,1171229253,4178635257,33948674,2139225727,1357946960,1011120188,2679776671,2833468328,1374921297,2751356323,1086357568,2408187279,2460827538,2646352285,944271416,4110742005,3168756668,3066132406,3665145818,560153121,271589392,4279952895,4077846003,3530407890,3444343245,202643468,322250259,3962553324,1608629855,2543990167,1154254916,389623319,3294073796,2817676711,2122513534,1028094525,1689045092,1575467613,422261273,1939203699,1621147744,2174228865,1339137615,3699352540,577127458,712922154,2427141008,2290289544,1187679302,3995715566,3100863416,339486740,3732514782,1591917662,186455563,3681988059,3762019296,844522546,978220090,169743370,1239126601,101321734,611076132,1558493276,3260915650,3547250131,2901361580,1655096418,2443721105,2510565781,3828863972,2039214713,3878868455,3359869896,928607799,1840765549,2374762893,3580146133,1322425422,2850048425,1823791212,1459268694,4094161908,3928346602,1706019429,2056189050,2934523822,135794696,3134549946,2022240376,628050469,779246638,472135708,2800834470,3032970164,3327236038,3894660072,3715932637,1956440180,522272287,1272813131,3185336765,2340818315,2323976074,1888542832,1044544574,3049550261,1722469478,1222152264,50660867,4127324150,236067854,1638122081,895445557,1475980887,3117443513,2257655686,3243809217,489110045,2662934430,3778599393,4162055160,2561878936,288563729,1773916777,3648039385,2391345038,2493985684,2612407707,505560094,2274497927,3911240169,3460925390,1442818645,678973480,3749357023,2358182796,2717407649,2306869641,219617805,3218761151,3862026214,1120306242,1756942440,1103331905,2578459033,762796589,252780047,2966125488,1425844308,3151392187,372911126],tw=[1667474886,2088535288,2004326894,2071694838,4075949567,1802223062,1869591006,3318043793,808472672,16843522,1734846926,724270422,4278065639,3621216949,2880169549,1987484396,3402253711,2189597983,3385409673,2105378810,4210693615,1499065266,1195886990,4042263547,2913856577,3570689971,2728590687,2947541573,2627518243,2762274643,1920112356,3233831835,3082273397,4261223649,2475929149,640051788,909531756,1061110142,4160160501,3435941763,875846760,2779116625,3857003729,4059105529,1903268834,3638064043,825316194,353713962,67374088,3351728789,589522246,3284360861,404236336,2526454071,84217610,2593830191,117901582,303183396,2155911963,3806477791,3958056653,656894286,2998062463,1970642922,151591698,2206440989,741110872,437923380,454765878,1852748508,1515908788,2694904667,1381168804,993742198,3604373943,3014905469,690584402,3823320797,791638366,2223281939,1398011302,3520161977,0,3991743681,538992704,4244381667,2981218425,1532751286,1785380564,3419096717,3200178535,960056178,1246420628,1280103576,1482221744,3486468741,3503319995,4025428677,2863326543,4227536621,1128514950,1296947098,859002214,2240123921,1162203018,4193849577,33687044,2139062782,1347481760,1010582648,2678045221,2829640523,1364325282,2745433693,1077985408,2408548869,2459086143,2644360225,943212656,4126475505,3166494563,3065430391,3671750063,555836226,269496352,4294908645,4092792573,3537006015,3452783745,202118168,320025894,3974901699,1600119230,2543297077,1145359496,387397934,3301201811,2812801621,2122220284,1027426170,1684319432,1566435258,421079858,1936954854,1616945344,2172753945,1330631070,3705438115,572679748,707427924,2425400123,2290647819,1179044492,4008585671,3099120491,336870440,3739122087,1583276732,185277718,3688593069,3772791771,842159716,976899700,168435220,1229577106,101059084,606366792,1549591736,3267517855,3553849021,2897014595,1650632388,2442242105,2509612081,3840161747,2038008818,3890688725,3368567691,926374254,1835907034,2374863873,3587531953,1313788572,2846482505,1819063512,1448540844,4109633523,3941213647,1701162954,2054852340,2930698567,134748176,3132806511,2021165296,623210314,774795868,471606328,2795958615,3031746419,3334885783,3907527627,3722280097,1953799400,522133822,1263263126,3183336545,2341176845,2324333839,1886425312,1044267644,3048588401,1718004428,1212733584,50529542,4143317495,235803164,1633788866,892690282,1465383342,3115962473,2256965911,3250673817,488449850,2661202215,3789633753,4177007595,2560144171,286339874,1768537042,3654906025,2391705863,2492770099,2610673197,505291324,2273808917,3924369609,3469625735,1431699370,673740880,3755965093,2358021891,2711746649,2307489801,218961690,3217021541,3873845719,1111672452,1751693520,1094828930,2576986153,757954394,252645662,2964376443,1414855848,3149649517,370555436],ew=[1374988112,2118214995,437757123,975658646,1001089995,530400753,2902087851,1273168787,540080725,2910219766,2295101073,4110568485,1340463100,3307916247,641025152,3043140495,3736164937,632953703,1172967064,1576976609,3274667266,2169303058,2370213795,1809054150,59727847,361929877,3211623147,2505202138,3569255213,1484005843,1239443753,2395588676,1975683434,4102977912,2572697195,666464733,3202437046,4035489047,3374361702,2110667444,1675577880,3843699074,2538681184,1649639237,2976151520,3144396420,4269907996,4178062228,1883793496,2403728665,2497604743,1383856311,2876494627,1917518562,3810496343,1716890410,3001755655,800440835,2261089178,3543599269,807962610,599762354,33778362,3977675356,2328828971,2809771154,4077384432,1315562145,1708848333,101039829,3509871135,3299278474,875451293,2733856160,92987698,2767645557,193195065,1080094634,1584504582,3178106961,1042385657,2531067453,3711829422,1306967366,2438237621,1908694277,67556463,1615861247,429456164,3602770327,2302690252,1742315127,2968011453,126454664,3877198648,2043211483,2709260871,2084704233,4169408201,0,159417987,841739592,504459436,1817866830,4245618683,260388950,1034867998,908933415,168810852,1750902305,2606453969,607530554,202008497,2472011535,3035535058,463180190,2160117071,1641816226,1517767529,470948374,3801332234,3231722213,1008918595,303765277,235474187,4069246893,766945465,337553864,1475418501,2943682380,4003061179,2743034109,4144047775,1551037884,1147550661,1543208500,2336434550,3408119516,3069049960,3102011747,3610369226,1113818384,328671808,2227573024,2236228733,3535486456,2935566865,3341394285,496906059,3702665459,226906860,2009195472,733156972,2842737049,294930682,1206477858,2835123396,2700099354,1451044056,573804783,2269728455,3644379585,2362090238,2564033334,2801107407,2776292904,3669462566,1068351396,742039012,1350078989,1784663195,1417561698,4136440770,2430122216,775550814,2193862645,2673705150,1775276924,1876241833,3475313331,3366754619,270040487,3902563182,3678124923,3441850377,1851332852,3969562369,2203032232,3868552805,2868897406,566021896,4011190502,3135740889,1248802510,3936291284,699432150,832877231,708780849,3332740144,899835584,1951317047,4236429990,3767586992,866637845,4043610186,1106041591,2144161806,395441711,1984812685,1139781709,3433712980,3835036895,2664543715,1282050075,3240894392,1181045119,2640243204,25965917,4203181171,4211818798,3009879386,2463879762,3910161971,1842759443,2597806476,933301370,1509430414,3943906441,3467192302,3076639029,3776767469,2051518780,2631065433,1441952575,404016761,1942435775,1408749034,1610459739,3745345300,2017778566,3400528769,3110650942,941896748,3265478751,371049330,3168937228,675039627,4279080257,967311729,135050206,3635733660,1683407248,2076935265,3576870512,1215061108,3501741890],nw=[1347548327,1400783205,3273267108,2520393566,3409685355,4045380933,2880240216,2471224067,1428173050,4138563181,2441661558,636813900,4233094615,3620022987,2149987652,2411029155,1239331162,1730525723,2554718734,3781033664,46346101,310463728,2743944855,3328955385,3875770207,2501218972,3955191162,3667219033,768917123,3545789473,692707433,1150208456,1786102409,2029293177,1805211710,3710368113,3065962831,401639597,1724457132,3028143674,409198410,2196052529,1620529459,1164071807,3769721975,2226875310,486441376,2499348523,1483753576,428819965,2274680428,3075636216,598438867,3799141122,1474502543,711349675,129166120,53458370,2592523643,2782082824,4063242375,2988687269,3120694122,1559041666,730517276,2460449204,4042459122,2706270690,3446004468,3573941694,533804130,2328143614,2637442643,2695033685,839224033,1973745387,957055980,2856345839,106852767,1371368976,4181598602,1033297158,2933734917,1179510461,3046200461,91341917,1862534868,4284502037,605657339,2547432937,3431546947,2003294622,3182487618,2282195339,954669403,3682191598,1201765386,3917234703,3388507166,0,2198438022,1211247597,2887651696,1315723890,4227665663,1443857720,507358933,657861945,1678381017,560487590,3516619604,975451694,2970356327,261314535,3535072918,2652609425,1333838021,2724322336,1767536459,370938394,182621114,3854606378,1128014560,487725847,185469197,2918353863,3106780840,3356761769,2237133081,1286567175,3152976349,4255350624,2683765030,3160175349,3309594171,878443390,1988838185,3704300486,1756818940,1673061617,3403100636,272786309,1075025698,545572369,2105887268,4174560061,296679730,1841768865,1260232239,4091327024,3960309330,3497509347,1814803222,2578018489,4195456072,575138148,3299409036,446754879,3629546796,4011996048,3347532110,3252238545,4270639778,915985419,3483825537,681933534,651868046,2755636671,3828103837,223377554,2607439820,1649704518,3270937875,3901806776,1580087799,4118987695,3198115200,2087309459,2842678573,3016697106,1003007129,2802849917,1860738147,2077965243,164439672,4100872472,32283319,2827177882,1709610350,2125135846,136428751,3874428392,3652904859,3460984630,3572145929,3593056380,2939266226,824852259,818324884,3224740454,930369212,2801566410,2967507152,355706840,1257309336,4148292826,243256656,790073846,2373340630,1296297904,1422699085,3756299780,3818836405,457992840,3099667487,2135319889,77422314,1560382517,1945798516,788204353,1521706781,1385356242,870912086,325965383,2358957921,2050466060,2388260884,2313884476,4006521127,901210569,3990953189,1014646705,1503449823,1062597235,2031621326,3212035895,3931371469,1533017514,350174575,2256028891,2177544179,1052338372,741876788,1606591296,1914052035,213705253,2334669897,1107234197,1899603969,3725069491,2631447780,2422494913,1635502980,1893020342,1950903388,1120974935],rw=[2807058932,1699970625,2764249623,1586903591,1808481195,1173430173,1487645946,59984867,4199882800,1844882806,1989249228,1277555970,3623636965,3419915562,1149249077,2744104290,1514790577,459744698,244860394,3235995134,1963115311,4027744588,2544078150,4190530515,1608975247,2627016082,2062270317,1507497298,2200818878,567498868,1764313568,3359936201,2305455554,2037970062,1047239e3,1910319033,1337376481,2904027272,2892417312,984907214,1243112415,830661914,861968209,2135253587,2011214180,2927934315,2686254721,731183368,1750626376,4246310725,1820824798,4172763771,3542330227,48394827,2404901663,2871682645,671593195,3254988725,2073724613,145085239,2280796200,2779915199,1790575107,2187128086,472615631,3029510009,4075877127,3802222185,4107101658,3201631749,1646252340,4270507174,1402811438,1436590835,3778151818,3950355702,3963161475,4020912224,2667994737,273792366,2331590177,104699613,95345982,3175501286,2377486676,1560637892,3564045318,369057872,4213447064,3919042237,1137477952,2658625497,1119727848,2340947849,1530455833,4007360968,172466556,266959938,516552836,0,2256734592,3980931627,1890328081,1917742170,4294704398,945164165,3575528878,958871085,3647212047,2787207260,1423022939,775562294,1739656202,3876557655,2530391278,2443058075,3310321856,547512796,1265195639,437656594,3121275539,719700128,3762502690,387781147,218828297,3350065803,2830708150,2848461854,428169201,122466165,3720081049,1627235199,648017665,4122762354,1002783846,2117360635,695634755,3336358691,4234721005,4049844452,3704280881,2232435299,574624663,287343814,612205898,1039717051,840019705,2708326185,793451934,821288114,1391201670,3822090177,376187827,3113855344,1224348052,1679968233,2361698556,1058709744,752375421,2431590963,1321699145,3519142200,2734591178,188127444,2177869557,3727205754,2384911031,3215212461,2648976442,2450346104,3432737375,1180849278,331544205,3102249176,4150144569,2952102595,2159976285,2474404304,766078933,313773861,2570832044,2108100632,1668212892,3145456443,2013908262,418672217,3070356634,2594734927,1852171925,3867060991,3473416636,3907448597,2614737639,919489135,164948639,2094410160,2997825956,590424639,2486224549,1723872674,3157750862,3399941250,3501252752,3625268135,2555048196,3673637356,1343127501,4130281361,3599595085,2957853679,1297403050,81781910,3051593425,2283490410,532201772,1367295589,3926170974,895287692,1953757831,1093597963,492483431,3528626907,1446242576,1192455638,1636604631,209336225,344873464,1015671571,669961897,3375740769,3857572124,2973530695,3747192018,1933530610,3464042516,935293895,3454686199,2858115069,1863638845,3683022916,4085369519,3292445032,875313188,1080017571,3279033885,621591778,1233856572,2504130317,24197544,3017672716,3835484340,3247465558,2220981195,3060847922,1551124588,1463996600],sw=[4104605777,1097159550,396673818,660510266,2875968315,2638606623,4200115116,3808662347,821712160,1986918061,3430322568,38544885,3856137295,718002117,893681702,1654886325,2975484382,3122358053,3926825029,4274053469,796197571,1290801793,1184342925,3556361835,2405426947,2459735317,1836772287,1381620373,3196267988,1948373848,3764988233,3385345166,3263785589,2390325492,1480485785,3111247143,3780097726,2293045232,548169417,3459953789,3746175075,439452389,1362321559,1400849762,1685577905,1806599355,2174754046,137073913,1214797936,1174215055,3731654548,2079897426,1943217067,1258480242,529487843,1437280870,3945269170,3049390895,3313212038,923313619,679998e3,3215307299,57326082,377642221,3474729866,2041877159,133361907,1776460110,3673476453,96392454,878845905,2801699524,777231668,4082475170,2330014213,4142626212,2213296395,1626319424,1906247262,1846563261,562755902,3708173718,1040559837,3871163981,1418573201,3294430577,114585348,1343618912,2566595609,3186202582,1078185097,3651041127,3896688048,2307622919,425408743,3371096953,2081048481,1108339068,2216610296,0,2156299017,736970802,292596766,1517440620,251657213,2235061775,2933202493,758720310,265905162,1554391400,1532285339,908999204,174567692,1474760595,4002861748,2610011675,3234156416,3693126241,2001430874,303699484,2478443234,2687165888,585122620,454499602,151849742,2345119218,3064510765,514443284,4044981591,1963412655,2581445614,2137062819,19308535,1928707164,1715193156,4219352155,1126790795,600235211,3992742070,3841024952,836553431,1669664834,2535604243,3323011204,1243905413,3141400786,4180808110,698445255,2653899549,2989552604,2253581325,3252932727,3004591147,1891211689,2487810577,3915653703,4237083816,4030667424,2100090966,865136418,1229899655,953270745,3399679628,3557504664,4118925222,2061379749,3079546586,2915017791,983426092,2022837584,1607244650,2118541908,2366882550,3635996816,972512814,3283088770,1568718495,3499326569,3576539503,621982671,2895723464,410887952,2623762152,1002142683,645401037,1494807662,2595684844,1335535747,2507040230,4293295786,3167684641,367585007,3885750714,1865862730,2668221674,2960971305,2763173681,1059270954,2777952454,2724642869,1320957812,2194319100,2429595872,2815956275,77089521,3973773121,3444575871,2448830231,1305906550,4021308739,2857194700,2516901860,3518358430,1787304780,740276417,1699839814,1592394909,2352307457,2272556026,188821243,1729977011,3687994002,274084841,3594982253,3613494426,2701949495,4162096729,322734571,2837966542,1640576439,484830689,1202797690,3537852828,4067639125,349075736,3342319475,4157467219,4255800159,1030690015,1155237496,2951971274,1757691577,607398968,2738905026,499347990,3794078908,1011452712,227885567,2818666809,213114376,3034881240,1455525988,3414450555,850817237,1817998408,3092726480],iw=[0,235474187,470948374,303765277,941896748,908933415,607530554,708780849,1883793496,2118214995,1817866830,1649639237,1215061108,1181045119,1417561698,1517767529,3767586992,4003061179,4236429990,4069246893,3635733660,3602770327,3299278474,3400528769,2430122216,2664543715,2362090238,2193862645,2835123396,2801107407,3035535058,3135740889,3678124923,3576870512,3341394285,3374361702,3810496343,3977675356,4279080257,4043610186,2876494627,2776292904,3076639029,3110650942,2472011535,2640243204,2403728665,2169303058,1001089995,899835584,666464733,699432150,59727847,226906860,530400753,294930682,1273168787,1172967064,1475418501,1509430414,1942435775,2110667444,1876241833,1641816226,2910219766,2743034109,2976151520,3211623147,2505202138,2606453969,2302690252,2269728455,3711829422,3543599269,3240894392,3475313331,3843699074,3943906441,4178062228,4144047775,1306967366,1139781709,1374988112,1610459739,1975683434,2076935265,1775276924,1742315127,1034867998,866637845,566021896,800440835,92987698,193195065,429456164,395441711,1984812685,2017778566,1784663195,1683407248,1315562145,1080094634,1383856311,1551037884,101039829,135050206,437757123,337553864,1042385657,807962610,573804783,742039012,2531067453,2564033334,2328828971,2227573024,2935566865,2700099354,3001755655,3168937228,3868552805,3902563182,4203181171,4102977912,3736164937,3501741890,3265478751,3433712980,1106041591,1340463100,1576976609,1408749034,2043211483,2009195472,1708848333,1809054150,832877231,1068351396,766945465,599762354,159417987,126454664,361929877,463180190,2709260871,2943682380,3178106961,3009879386,2572697195,2538681184,2236228733,2336434550,3509871135,3745345300,3441850377,3274667266,3910161971,3877198648,4110568485,4211818798,2597806476,2497604743,2261089178,2295101073,2733856160,2902087851,3202437046,2968011453,3936291284,3835036895,4136440770,4169408201,3535486456,3702665459,3467192302,3231722213,2051518780,1951317047,1716890410,1750902305,1113818384,1282050075,1584504582,1350078989,168810852,67556463,371049330,404016761,841739592,1008918595,775550814,540080725,3969562369,3801332234,4035489047,4269907996,3569255213,3669462566,3366754619,3332740144,2631065433,2463879762,2160117071,2395588676,2767645557,2868897406,3102011747,3069049960,202008497,33778362,270040487,504459436,875451293,975658646,675039627,641025152,2084704233,1917518562,1615861247,1851332852,1147550661,1248802510,1484005843,1451044056,933301370,967311729,733156972,632953703,260388950,25965917,328671808,496906059,1206477858,1239443753,1543208500,1441952575,2144161806,1908694277,1675577880,1842759443,3610369226,3644379585,3408119516,3307916247,4011190502,3776767469,4077384432,4245618683,2809771154,2842737049,3144396420,3043140495,2673705150,2438237621,2203032232,2370213795],ow=[0,185469197,370938394,487725847,741876788,657861945,975451694,824852259,1483753576,1400783205,1315723890,1164071807,1950903388,2135319889,1649704518,1767536459,2967507152,3152976349,2801566410,2918353863,2631447780,2547432937,2328143614,2177544179,3901806776,3818836405,4270639778,4118987695,3299409036,3483825537,3535072918,3652904859,2077965243,1893020342,1841768865,1724457132,1474502543,1559041666,1107234197,1257309336,598438867,681933534,901210569,1052338372,261314535,77422314,428819965,310463728,3409685355,3224740454,3710368113,3593056380,3875770207,3960309330,4045380933,4195456072,2471224067,2554718734,2237133081,2388260884,3212035895,3028143674,2842678573,2724322336,4138563181,4255350624,3769721975,3955191162,3667219033,3516619604,3431546947,3347532110,2933734917,2782082824,3099667487,3016697106,2196052529,2313884476,2499348523,2683765030,1179510461,1296297904,1347548327,1533017514,1786102409,1635502980,2087309459,2003294622,507358933,355706840,136428751,53458370,839224033,957055980,605657339,790073846,2373340630,2256028891,2607439820,2422494913,2706270690,2856345839,3075636216,3160175349,3573941694,3725069491,3273267108,3356761769,4181598602,4063242375,4011996048,3828103837,1033297158,915985419,730517276,545572369,296679730,446754879,129166120,213705253,1709610350,1860738147,1945798516,2029293177,1239331162,1120974935,1606591296,1422699085,4148292826,4233094615,3781033664,3931371469,3682191598,3497509347,3446004468,3328955385,2939266226,2755636671,3106780840,2988687269,2198438022,2282195339,2501218972,2652609425,1201765386,1286567175,1371368976,1521706781,1805211710,1620529459,2105887268,1988838185,533804130,350174575,164439672,46346101,870912086,954669403,636813900,788204353,2358957921,2274680428,2592523643,2441661558,2695033685,2880240216,3065962831,3182487618,3572145929,3756299780,3270937875,3388507166,4174560061,4091327024,4006521127,3854606378,1014646705,930369212,711349675,560487590,272786309,457992840,106852767,223377554,1678381017,1862534868,1914052035,2031621326,1211247597,1128014560,1580087799,1428173050,32283319,182621114,401639597,486441376,768917123,651868046,1003007129,818324884,1503449823,1385356242,1333838021,1150208456,1973745387,2125135846,1673061617,1756818940,2970356327,3120694122,2802849917,2887651696,2637442643,2520393566,2334669897,2149987652,3917234703,3799141122,4284502037,4100872472,3309594171,3460984630,3545789473,3629546796,2050466060,1899603969,1814803222,1730525723,1443857720,1560382517,1075025698,1260232239,575138148,692707433,878443390,1062597235,243256656,91341917,409198410,325965383,3403100636,3252238545,3704300486,3620022987,3874428392,3990953189,4042459122,4227665663,2460449204,2578018489,2226875310,2411029155,3198115200,3046200461,2827177882,2743944855],aw=[0,218828297,437656594,387781147,875313188,958871085,775562294,590424639,1750626376,1699970625,1917742170,2135253587,1551124588,1367295589,1180849278,1265195639,3501252752,3720081049,3399941250,3350065803,3835484340,3919042237,4270507174,4085369519,3102249176,3051593425,2734591178,2952102595,2361698556,2177869557,2530391278,2614737639,3145456443,3060847922,2708326185,2892417312,2404901663,2187128086,2504130317,2555048196,3542330227,3727205754,3375740769,3292445032,3876557655,3926170974,4246310725,4027744588,1808481195,1723872674,1910319033,2094410160,1608975247,1391201670,1173430173,1224348052,59984867,244860394,428169201,344873464,935293895,984907214,766078933,547512796,1844882806,1627235199,2011214180,2062270317,1507497298,1423022939,1137477952,1321699145,95345982,145085239,532201772,313773861,830661914,1015671571,731183368,648017665,3175501286,2957853679,2807058932,2858115069,2305455554,2220981195,2474404304,2658625497,3575528878,3625268135,3473416636,3254988725,3778151818,3963161475,4213447064,4130281361,3599595085,3683022916,3432737375,3247465558,3802222185,4020912224,4172763771,4122762354,3201631749,3017672716,2764249623,2848461854,2331590177,2280796200,2431590963,2648976442,104699613,188127444,472615631,287343814,840019705,1058709744,671593195,621591778,1852171925,1668212892,1953757831,2037970062,1514790577,1463996600,1080017571,1297403050,3673637356,3623636965,3235995134,3454686199,4007360968,3822090177,4107101658,4190530515,2997825956,3215212461,2830708150,2779915199,2256734592,2340947849,2627016082,2443058075,172466556,122466165,273792366,492483431,1047239e3,861968209,612205898,695634755,1646252340,1863638845,2013908262,1963115311,1446242576,1530455833,1277555970,1093597963,1636604631,1820824798,2073724613,1989249228,1436590835,1487645946,1337376481,1119727848,164948639,81781910,331544205,516552836,1039717051,821288114,669961897,719700128,2973530695,3157750862,2871682645,2787207260,2232435299,2283490410,2667994737,2450346104,3647212047,3564045318,3279033885,3464042516,3980931627,3762502690,4150144569,4199882800,3070356634,3121275539,2904027272,2686254721,2200818878,2384911031,2570832044,2486224549,3747192018,3528626907,3310321856,3359936201,3950355702,3867060991,4049844452,4234721005,1739656202,1790575107,2108100632,1890328081,1402811438,1586903591,1233856572,1149249077,266959938,48394827,369057872,418672217,1002783846,919489135,567498868,752375421,209336225,24197544,376187827,459744698,945164165,895287692,574624663,793451934,1679968233,1764313568,2117360635,1933530610,1343127501,1560637892,1243112415,1192455638,3704280881,3519142200,3336358691,3419915562,3907448597,3857572124,4075877127,4294704398,3029510009,3113855344,2927934315,2744104290,2159976285,2377486676,2594734927,2544078150],cw=[0,151849742,303699484,454499602,607398968,758720310,908999204,1059270954,1214797936,1097159550,1517440620,1400849762,1817998408,1699839814,2118541908,2001430874,2429595872,2581445614,2194319100,2345119218,3034881240,3186202582,2801699524,2951971274,3635996816,3518358430,3399679628,3283088770,4237083816,4118925222,4002861748,3885750714,1002142683,850817237,698445255,548169417,529487843,377642221,227885567,77089521,1943217067,2061379749,1640576439,1757691577,1474760595,1592394909,1174215055,1290801793,2875968315,2724642869,3111247143,2960971305,2405426947,2253581325,2638606623,2487810577,3808662347,3926825029,4044981591,4162096729,3342319475,3459953789,3576539503,3693126241,1986918061,2137062819,1685577905,1836772287,1381620373,1532285339,1078185097,1229899655,1040559837,923313619,740276417,621982671,439452389,322734571,137073913,19308535,3871163981,4021308739,4104605777,4255800159,3263785589,3414450555,3499326569,3651041127,2933202493,2815956275,3167684641,3049390895,2330014213,2213296395,2566595609,2448830231,1305906550,1155237496,1607244650,1455525988,1776460110,1626319424,2079897426,1928707164,96392454,213114376,396673818,514443284,562755902,679998e3,865136418,983426092,3708173718,3557504664,3474729866,3323011204,4180808110,4030667424,3945269170,3794078908,2507040230,2623762152,2272556026,2390325492,2975484382,3092726480,2738905026,2857194700,3973773121,3856137295,4274053469,4157467219,3371096953,3252932727,3673476453,3556361835,2763173681,2915017791,3064510765,3215307299,2156299017,2307622919,2459735317,2610011675,2081048481,1963412655,1846563261,1729977011,1480485785,1362321559,1243905413,1126790795,878845905,1030690015,645401037,796197571,274084841,425408743,38544885,188821243,3613494426,3731654548,3313212038,3430322568,4082475170,4200115116,3780097726,3896688048,2668221674,2516901860,2366882550,2216610296,3141400786,2989552604,2837966542,2687165888,1202797690,1320957812,1437280870,1554391400,1669664834,1787304780,1906247262,2022837584,265905162,114585348,499347990,349075736,736970802,585122620,972512814,821712160,2595684844,2478443234,2293045232,2174754046,3196267988,3079546586,2895723464,2777952454,3537852828,3687994002,3234156416,3385345166,4142626212,4293295786,3841024952,3992742070,174567692,57326082,410887952,292596766,777231668,660510266,1011452712,893681702,1108339068,1258480242,1343618912,1494807662,1715193156,1865862730,1948373848,2100090966,2701949495,2818666809,3004591147,3122358053,2235061775,2352307457,2535604243,2653899549,3915653703,3764988233,4219352155,4067639125,3444575871,3294430577,3746175075,3594982253,836553431,953270745,600235211,718002117,367585007,484830689,133361907,251657213,2041877159,1891211689,1806599355,1654886325,1568718495,1418573201,1335535747,1184342925];function lw(t){const e=[];for(let n=0;n<t.length;n+=4)e.push(t[n]<<24|t[n+1]<<16|t[n+2]<<8|t[n+3]);return e}class uw{get key(){return Ky(this,Hy,"f").slice()}constructor(t){if(Hy.set(this,void 0),Vy.set(this,void 0),Wy.set(this,void 0),!(this instanceof uw))throw Error("AES must be instanitated with `new`");zy(this,Hy,new Uint8Array(t),"f");const e=qy[this.key.length];if(null==e)throw new TypeError("invalid key size (must be 16, 24 or 32 bytes)");zy(this,Wy,[],"f"),zy(this,Vy,[],"f");for(let l=0;l<=e;l++)Ky(this,Wy,"f").push([0,0,0,0]),Ky(this,Vy,"f").push([0,0,0,0]);const n=4*(e+1),r=this.key.length/4,s=lw(this.key);let i;for(let l=0;l<r;l++)i=l>>2,Ky(this,Wy,"f")[i][l%4]=s[l],Ky(this,Vy,"f")[e-i][l%4]=s[l];let o,a=0,c=r;for(;c<n;){if(o=s[r-1],s[0]^=Qy[o>>16&255]<<24^Qy[o>>8&255]<<16^Qy[255&o]<<8^Qy[o>>24&255]^$y[a]<<24,a+=1,8!=r)for(let e=1;e<r;e++)s[e]^=s[e-1];else{for(let t=1;t<r/2;t++)s[t]^=s[t-1];o=s[r/2-1],s[r/2]^=Qy[255&o]^Qy[o>>8&255]<<8^Qy[o>>16&255]<<16^Qy[o>>24&255]<<24;for(let t=r/2+1;t<r;t++)s[t]^=s[t-1]}let t,i,l=0;for(;l<r&&c<n;)t=c>>2,i=c%4,Ky(this,Wy,"f")[t][i]=s[l],Ky(this,Vy,"f")[e-t][i]=s[l++],c++}for(let l=1;l<e;l++)for(let t=0;t<4;t++)o=Ky(this,Vy,"f")[l][t],Ky(this,Vy,"f")[l][t]=iw[o>>24&255]^ow[o>>16&255]^aw[o>>8&255]^cw[255&o]}encrypt(t){if(16!=t.length)throw new TypeError("invalid plaintext size (must be 16 bytes)");const e=Ky(this,Wy,"f").length-1,n=[0,0,0,0];let r=lw(t);for(let o=0;o<4;o++)r[o]^=Ky(this,Wy,"f")[0][o];for(let o=1;o<e;o++){for(let t=0;t<4;t++)n[t]=Yy[r[t]>>24&255]^Zy[r[(t+1)%4]>>16&255]^Xy[r[(t+2)%4]>>8&255]^tw[255&r[(t+3)%4]]^Ky(this,Wy,"f")[o][t];r=n.slice()}const s=new Uint8Array(16);let i=0;for(let o=0;o<4;o++)i=Ky(this,Wy,"f")[e][o],s[4*o]=255&(Qy[r[o]>>24&255]^i>>24),s[4*o+1]=255&(Qy[r[(o+1)%4]>>16&255]^i>>16),s[4*o+2]=255&(Qy[r[(o+2)%4]>>8&255]^i>>8),s[4*o+3]=255&(Qy[255&r[(o+3)%4]]^i);return s}decrypt(t){if(16!=t.length)throw new TypeError("invalid ciphertext size (must be 16 bytes)");const e=Ky(this,Vy,"f").length-1,n=[0,0,0,0];let r=lw(t);for(let o=0;o<4;o++)r[o]^=Ky(this,Vy,"f")[0][o];for(let o=1;o<e;o++){for(let t=0;t<4;t++)n[t]=ew[r[t]>>24&255]^nw[r[(t+3)%4]>>16&255]^rw[r[(t+2)%4]>>8&255]^sw[255&r[(t+1)%4]]^Ky(this,Vy,"f")[o][t];r=n.slice()}const s=new Uint8Array(16);let i=0;for(let o=0;o<4;o++)i=Ky(this,Vy,"f")[e][o],s[4*o]=255&(Jy[r[o]>>24&255]^i>>24),s[4*o+1]=255&(Jy[r[(o+3)%4]>>16&255]^i>>16),s[4*o+2]=255&(Jy[r[(o+2)%4]>>8&255]^i>>8),s[4*o+3]=255&(Jy[255&r[(o+1)%4]]^i);return s}}Hy=new WeakMap,Vy=new WeakMap,Wy=new WeakMap;class hw{constructor(t,e,n){if(n&&!(this instanceof n))throw new Error(`${t} must be instantiated with "new"`);Object.defineProperties(this,{aes:{enumerable:!0,value:new uw(e)},name:{enumerable:!0,value:t}})}}var dw,fw,pw=globalThis&&globalThis.__classPrivateFieldSet||function(t,e,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(t,n):s?s.value=n:e.set(t,n),n},gw=globalThis&&globalThis.__classPrivateFieldGet||function(t,e,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(t):r?r.value:e.get(t)};class mw extends hw{constructor(t,e){if(super("ECC",t,mw),dw.set(this,void 0),fw.set(this,void 0),e){if(e.length%16)throw new TypeError("invalid iv size (must be 16 bytes)");pw(this,dw,new Uint8Array(e),"f")}else pw(this,dw,new Uint8Array(16),"f");pw(this,fw,this.iv,"f")}get iv(){return new Uint8Array(gw(this,dw,"f"))}encrypt(t){if(t.length%16)throw new TypeError("invalid plaintext size (must be multiple of 16 bytes)");const e=new Uint8Array(t.length);for(let n=0;n<t.length;n+=16){for(let e=0;e<16;e++)gw(this,fw,"f")[e]^=t[n+e];pw(this,fw,this.aes.encrypt(gw(this,fw,"f")),"f"),e.set(gw(this,fw,"f"),n)}return e}decrypt(t){if(t.length%16)throw new TypeError("invalid ciphertext size (must be multiple of 16 bytes)");const e=new Uint8Array(t.length);for(let n=0;n<t.length;n+=16){const r=this.aes.decrypt(t.subarray(n,n+16));for(let s=0;s<16;s++)e[n+s]=r[s]^gw(this,fw,"f")[s],gw(this,fw,"f")[s]=t[n+s]}return e}}dw=new WeakMap,fw=new WeakMap;var yw,ww,bw,Aw=globalThis&&globalThis.__classPrivateFieldSet||function(t,e,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(t,n):s?s.value=n:e.set(t,n),n},_w=globalThis&&globalThis.__classPrivateFieldGet||function(t,e,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(t):r?r.value:e.get(t)};class vw extends hw{constructor(t,e){super("CTR",t,vw),yw.set(this,void 0),ww.set(this,void 0),bw.set(this,void 0),Aw(this,bw,new Uint8Array(16),"f"),_w(this,bw,"f").fill(0),Aw(this,yw,_w(this,bw,"f"),"f"),Aw(this,ww,16,"f"),null==e&&(e=1),"number"==typeof e?this.setCounterValue(e):this.setCounterBytes(e)}get counter(){return new Uint8Array(_w(this,bw,"f"))}setCounterValue(t){if(!Number.isInteger(t)||t<0||t>Number.MAX_SAFE_INTEGER)throw new TypeError("invalid counter initial integer value");for(let e=15;e>=0;--e)_w(this,bw,"f")[e]=t%256,t=Math.floor(t/256)}setCounterBytes(t){if(16!==t.length)throw new TypeError("invalid counter initial Uint8Array value length");_w(this,bw,"f").set(t)}increment(){for(let t=15;t>=0;t--){if(255!==_w(this,bw,"f")[t]){_w(this,bw,"f")[t]++;break}_w(this,bw,"f")[t]=0}}encrypt(t){var e,n;const r=new Uint8Array(t);for(let s=0;s<r.length;s++)16===_w(this,ww,"f")&&(Aw(this,yw,this.aes.encrypt(_w(this,bw,"f")),"f"),Aw(this,ww,0,"f"),this.increment()),r[s]^=_w(this,yw,"f")[(Aw(this,ww,(n=_w(this,ww,"f"),e=n++,n),"f"),e)];return r}decrypt(t){return this.encrypt(t)}}function Ew(t){return"string"!=typeof t||t.startsWith("0x")||(t="0x"+t),ea(t)}function kw(t,e){for(t=String(t);t.length<e;)t="0"+t;return t}function Sw(t){return"string"==typeof t?Da(t,"NFKC"):ea(t)}function Tw(t,e){const n=e.match(/^([a-z0-9$_.-]*)(:([a-z]+))?(!)?$/i);$o(null!=n,"invalid path","path",e);const r=n[1],s=n[3],i="!"===n[4];let o=t;for(const a of r.toLowerCase().split(".")){if(Array.isArray(o)){if(!a.match(/^[0-9]+$/))break;o=o[parseInt(a)]}else if("object"==typeof o){let t=null;for(const e in o)if(e.toLowerCase()===a){t=o[e];break}o=t}else o=null;if(null==o)break}if($o(!i||null!=o,"missing required value","path",r),s&&null!=o){if("int"===s){if("string"==typeof o&&o.match(/^-?[0-9]+$/))return parseInt(o);if(Number.isSafeInteger(o))return o}if("number"===s&&"string"==typeof o&&o.match(/^-?[0-9.]*$/))return parseFloat(o);if("data"===s&&"string"==typeof o)return Ew(o);if("array"===s&&Array.isArray(o))return o;if(s===typeof o)return o;$o(!1,`wrong type found for ${s} `,"path",r)}return o}yw=new WeakMap,ww=new WeakMap,bw=new WeakMap;const Rw="m/44'/60'/0'/0/0";function Iw(t){try{const e=JSON.parse(t);if(3===(null!=e.version?parseInt(e.version):0))return!0}catch(e){}return!1}function Ow(t,e){const n=ta(e),r=Tw(t,"crypto.ciphertext:data!");$o(ia(Bl(oa([n.slice(16,32),r]))).substring(2)===Tw(t,"crypto.mac:string!").toLowerCase(),"incorrect password","password","[ REDACTED ]");const s=function(t,e,n){if("aes-128-ctr"===Tw(t,"crypto.cipher:string")){const r=Tw(t,"crypto.cipherparams.iv:data!");return ia(new vw(e,r).decrypt(n))}qo(!1,"unsupported cipher","UNSUPPORTED_OPERATION",{operation:"decrypt"})}(t,n.slice(0,16),r),i=Ed(s);if(t.address){let e=t.address.toLowerCase();e.startsWith("0x")||(e="0x"+e),$o($h(e)===i,"keystore address/privateKey mismatch","address",t.address)}const o={address:i,privateKey:s};if("0.1"===Tw(t,"x-ethers.version:string")){const e=n.slice(32,64),r=Tw(t,"x-ethers.mnemonicCiphertext:data!"),s=Tw(t,"x-ethers.mnemonicCounter:data!"),i=new vw(e,s);o.mnemonic={path:Tw(t,"x-ethers.path:string")||Rw,locale:Tw(t,"x-ethers.locale:string")||"en",entropy:ia(ta(i.decrypt(r)))}}return o}function Cw(t){const e=Tw(t,"crypto.kdf:string");if(e&&"string"==typeof e){if("scrypt"===e.toLowerCase()){const n=Tw(t,"crypto.kdfparams.salt:data!"),r=Tw(t,"crypto.kdfparams.n:int!"),s=Tw(t,"crypto.kdfparams.r:int!"),i=Tw(t,"crypto.kdfparams.p:int!");$o(r>0&&!(r&r-1),"invalid kdf.N","kdf.N",r),$o(s>0&&i>0,"invalid kdf","kdf",e);const o=Tw(t,"crypto.kdfparams.dklen:int!");return $o(32===o,"invalid kdf.dklen","kdf.dflen",o),{name:"scrypt",salt:n,N:r,r:s,p:i,dkLen:64}}if("pbkdf2"===e.toLowerCase()){const e=Tw(t,"crypto.kdfparams.salt:data!"),n=Tw(t,"crypto.kdfparams.prf:string!"),r=n.split("-").pop();$o("sha256"===r||"sha512"===r,"invalid kdf.pdf","kdf.pdf",n);const s=Tw(t,"crypto.kdfparams.c:int!"),i=Tw(t,"crypto.kdfparams.dklen:int!");return $o(32===i,"invalid kdf.dklen","kdf.dklen",i),{name:"pbkdf2",salt:e,count:s,dkLen:i,algorithm:r}}}$o(!1,"unsupported key-derivation function","kdf",e)}function Nw(t){return new Promise((e=>{setTimeout((()=>{e()}),t)}))}function xw(t){const e=null!=t.salt?ta(t.salt,"options.salt"):au(32);let n=1<<17,r=8,s=1;return t.scrypt&&(t.scrypt.N&&(n=t.scrypt.N),t.scrypt.r&&(r=t.scrypt.r),t.scrypt.p&&(s=t.scrypt.p)),$o("number"==typeof n&&n>0&&Number.isSafeInteger(n)&&(BigInt(n)&BigInt(n-1))===BigInt(0),"invalid scrypt N parameter","options.N",n),$o("number"==typeof r&&r>0&&Number.isSafeInteger(r),"invalid scrypt r parameter","options.r",r),$o("number"==typeof s&&s>0&&Number.isSafeInteger(s),"invalid scrypt p parameter","options.p",s),{name:"scrypt",dkLen:32,salt:e,N:n,r:r,p:s}}function Pw(t,e,n,r){const s=ta(n.privateKey,"privateKey"),i=null!=r.iv?ta(r.iv,"options.iv"):au(16);$o(16===i.length,"invalid options.iv length","options.iv",r.iv);const o=null!=r.uuid?ta(r.uuid,"options.uuid"):au(16);$o(16===o.length,"invalid options.uuid length","options.uuid",r.iv);const a=t.slice(0,16),c=t.slice(16,32),l=ta(new vw(a,i).encrypt(s)),u=Bl(oa([c,l])),h={address:n.address.substring(2).toLowerCase(),id:ac(o),version:3,Crypto:{cipher:"aes-128-ctr",cipherparams:{iv:ia(i).substring(2)},ciphertext:ia(l).substring(2),kdf:"scrypt",kdfparams:{salt:ia(e.salt).substring(2),n:e.N,dklen:32,p:e.p,r:e.r},mac:u.substring(2)}};if(n.mnemonic){const e=null!=r.client?r.client:`ethers/${Fo}`,s=n.mnemonic.path||Rw,i=n.mnemonic.locale||"en",o=t.slice(32,64),a=ta(n.mnemonic.entropy,"account.mnemonic.entropy"),c=au(16),l=ta(new vw(o,c).encrypt(a)),u=new Date,d="UTC--"+(u.getUTCFullYear()+"-"+kw(u.getUTCMonth()+1,2)+"-"+kw(u.getUTCDate(),2)+"T"+kw(u.getUTCHours(),2)+"-"+kw(u.getUTCMinutes(),2)+"-"+kw(u.getUTCSeconds(),2)+".0Z")+"--"+h.address;h["x-ethers"]={client:e,gethFilename:d,path:s,locale:i,mnemonicCounter:ia(c).substring(2),mnemonicCiphertext:ia(l).substring(2),version:"0.1"}}return JSON.stringify(h)}function Dw(t,e,n){null==n&&(n={});const r=Sw(e),s=xw(n);return Pw(ta(Au(r,s.salt,s.N,s.r,s.p,64)),s,t,n)}async function Bw(t,e,n){null==n&&(n={});const r=Sw(e),s=xw(n);return Pw(ta(await bu(r,s.salt,s.N,s.r,s.p,64,n.progressCallback)),s,t,n)}const Uw="m/44'/60'/0'/0/0",Lw=new Uint8Array([66,105,116,99,111,105,110,32,115,101,101,100]),Mw=2147483648,Fw=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");function Gw(t,e){let n="";for(;t;)n="0123456789abcdef"[t%16]+n,t=Math.trunc(t/16);for(;n.length<2*e;)n="0"+n;return"0x"+n}function jw(t){const e=ta(t);return Ca(oa([e,ca(ku(ku(e)),0,4)]))}const Hw={};function Vw(t,e,n,r){const s=new Uint8Array(37);t&Mw?(qo(null!=r,"cannot derive child of neutered node","UNSUPPORTED_OPERATION",{operation:"deriveChild"}),s.set(ta(r),1)):s.set(ta(n));for(let o=24;o>=0;o-=8)s[33+(o>>3)]=t>>24-o&255;const i=ta(ml("sha512",e,s));return{IL:i.slice(0,32),IR:i.slice(32)}}function Ww(t,e){const n=e.split("/");$o(n.length>0,"invalid path","path",e),"m"===n[0]&&($o(0===t.depth,`cannot derive root path (i.e. path starting with "m/") for a node at non-zero depth ${t.depth}`,"path",e),n.shift());let r=t;for(let s=0;s<n.length;s++){const t=n[s];if(t.match(/^[0-9]+'$/)){const e=parseInt(t.substring(0,t.length-1));$o(e<Mw,"invalid path index",`path[${s}]`,t),r=r.deriveChild(Mw+e)}else if(t.match(/^[0-9]+$/)){const e=parseInt(t);$o(e<Mw,"invalid path index",`path[${s}]`,t),r=r.deriveChild(e)}else $o(!1,"invalid path component",`path[${s}]`,t)}return r}const Kw=class t extends Iy{constructor(t,e,n,r,s,i,o,a,c){super(e,c),Dn(this,kn),Nn(this,"publicKey"),Nn(this,"fingerprint"),Nn(this,"parentFingerprint"),Nn(this,"mnemonic"),Nn(this,"chainCode"),Nn(this,"path"),Nn(this,"index"),Nn(this,"depth"),Zo(t,Hw,"HDNodeWallet"),Ho(this,{publicKey:e.compressedPublicKey});Ho(this,{parentFingerprint:n,fingerprint:ca(Xl(ku(this.publicKey)),0,4),chainCode:r,path:s,index:i,depth:o}),Ho(this,{mnemonic:a})}connect(e){return new t(Hw,this.signingKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,this.mnemonic,e)}async encrypt(t,e){return await Bw(Ln(this,kn,Sn).call(this),t,{progressCallback:e})}encryptSync(t){return Dw(Ln(this,kn,Sn).call(this),t)}get extendedKey(){return qo(this.depth<256,"Depth too deep","UNSUPPORTED_OPERATION",{operation:"extendedKey"}),jw(oa(["0x0488ADE4",Gw(this.depth,1),this.parentFingerprint,Gw(this.index,4),this.chainCode,oa(["0x00",this.privateKey])]))}hasPath(){return null!=this.path}neuter(){return new qw(Hw,this.address,this.publicKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,this.provider)}deriveChild(e){const n=_a(e,"index");$o(n<=4294967295,"invalid index","index",n);let r=this.path;r&&(r+="/"+(2147483647&n),n&Mw&&(r+="'"));const{IR:s,IL:i}=Vw(n,this.chainCode,this.publicKey,this.privateKey),o=new Hh(va((Aa(i)+BigInt(this.privateKey))%Fw,32));return new t(Hw,o,this.fingerprint,ia(s),r,n,this.depth+1,this.mnemonic,this.provider)}derivePath(t){return Ww(this,t)}static fromExtendedKey(e){const n=Ea(function(t){let e=Ia;for(let n=0;n<t.length;n++)e*=Oa,e+=Ra(t[n]);return e}(e));$o(82===n.length||jw(n.slice(0,78))===e,"invalid extended key","extendedKey","[ REDACTED ]");const r=n[4],s=ia(n.slice(5,9)),i=parseInt(ia(n.slice(9,13)).substring(2),16),o=ia(n.slice(13,45)),a=n.slice(45,78);switch(ia(n.slice(0,4))){case"0x0488b21e":case"0x043587cf":{const t=ia(a);return new qw(Hw,Ed(t),t,s,o,null,i,r,null)}case"0x0488ade4":case"0x04358394 ":if(0!==a[0])break;return new t(Hw,new Hh(a.slice(1)),s,o,null,i,r,null,null)}$o(!1,"invalid extended key prefix","extendedKey","[ REDACTED ]")}static createRandom(e,n,r){var s;null==e&&(e=""),null==n&&(n=Uw),null==r&&(r=Uy.wordlist());const i=jy.fromEntropy(au(16),e,r);return Ln(s=t,Tn,Rn).call(s,i.computeSeed(),i).derivePath(n)}static fromMnemonic(e,n){var r;return n||(n=Uw),Ln(r=t,Tn,Rn).call(r,e.computeSeed(),e).derivePath(n)}static fromPhrase(e,n,r,s){var i;null==n&&(n=""),null==r&&(r=Uw),null==s&&(s=Uy.wordlist());const o=jy.fromPhrase(e,n,s);return Ln(i=t,Tn,Rn).call(i,o.computeSeed(),o).derivePath(r)}static fromSeed(e){var n;return Ln(n=t,Tn,Rn).call(n,e,null)}};kn=new WeakSet,Sn=function(){const t={address:this.address,privateKey:this.privateKey},e=this.mnemonic;return this.path&&e&&"en"===e.wordlist.locale&&""===e.password&&(t.mnemonic={path:this.path,locale:"en",entropy:e.entropy}),t},Tn=new WeakSet,Rn=function(t,e){$o(ra(t),"invalid seed","seed","[REDACTED]");const n=ta(t,"seed");$o(n.length>=16&&n.length<=64,"invalid seed","seed","[REDACTED]");const r=ta(ml("sha512",Lw,n)),s=new Hh(ia(r.slice(0,32)));return new Kw(Hw,s,"0x00000000",ia(r.slice(32)),"m",0,0,e,null)},Dn(Kw,Tn);let zw=Kw;class qw extends dy{constructor(t,e,n,r,s,i,o,a,c){super(e,c),Nn(this,"publicKey"),Nn(this,"fingerprint"),Nn(this,"parentFingerprint"),Nn(this,"chainCode"),Nn(this,"path"),Nn(this,"index"),Nn(this,"depth"),Zo(t,Hw,"HDNodeVoidWallet"),Ho(this,{publicKey:n});Ho(this,{publicKey:n,fingerprint:ca(Xl(ku(n)),0,4),parentFingerprint:r,chainCode:s,path:i,index:o,depth:a})}connect(t){return new qw(Hw,this.address,this.publicKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,t)}get extendedKey(){return qo(this.depth<256,"Depth too deep","UNSUPPORTED_OPERATION",{operation:"extendedKey"}),jw(oa(["0x0488B21E",Gw(this.depth,1),this.parentFingerprint,Gw(this.index,4),this.chainCode,this.publicKey]))}hasPath(){return null!=this.path}deriveChild(t){const e=_a(t,"index");$o(e<=4294967295,"invalid index","index",e);let n=this.path;n&&(n+="/"+(2147483647&e),e&Mw&&(n+="'"));const{IR:r,IL:s}=Vw(e,this.chainCode,this.publicKey,null),i=Hh.addPoints(s,this.publicKey,!0),o=Ed(i);return new qw(Hw,o,i,this.fingerprint,ia(r),n,e,this.depth+1,this.provider)}derivePath(t){return Ww(this,t)}}function $w(t){try{if(JSON.parse(t).encseed)return!0}catch(e){}return!1}function Qw(t,e){const n=JSON.parse(t),r=Sw(e),s=$h(Tw(n,"ethaddr:string!")),i=Ew(Tw(n,"encseed:string!"));$o(i&&i.length%16==0,"invalid encseed","json",t);const o=ta(ru(r,r,2e3,32,"sha256")).slice(0,16),a=i.slice(0,16),c=i.slice(16),l=function(t){if(t.length<16)throw new TypeError("PKCS#7 invalid length");const e=t[t.length-1];if(e>16)throw new TypeError("PKCS#7 padding byte out of range");const n=t.length-e;for(let r=0;r<e;r++)if(t[n+r]!==e)throw new TypeError("PKCS#7 invalid padding byte");return new Uint8Array(t.subarray(0,n))}(ta(new mw(o,a).decrypt(c)));let u="";for(let h=0;h<l.length;h++)u+=String.fromCharCode(l[h]);return{address:s,privateKey:Wd(u)}}function Jw(t){return new Promise((e=>{setTimeout((()=>{e()}),t)}))}const Yw=class t extends Iy{constructor(t,e){"string"!=typeof t||t.startsWith("0x")||(t="0x"+t),super("string"==typeof t?new Hh(t):t,e)}connect(e){return new t(this.signingKey,e)}async encrypt(t,e){const n={address:this.address,privateKey:this.privateKey};return await Bw(n,t,{progressCallback:e})}encryptSync(t){return Dw({address:this.address,privateKey:this.privateKey},t)}static async fromEncryptedJson(e,n,r){var s;let i=null;return Iw(e)?i=await async function(t,e,n){const r=JSON.parse(t),s=Sw(e),i=Cw(r);if("pbkdf2"===i.name){n&&(n(0),await Nw(0));const{salt:t,count:e,dkLen:o,algorithm:a}=i,c=ru(s,t,e,o,a);return n&&(n(1),await Nw(0)),Ow(r,c)}qo("scrypt"===i.name,"cannot be reached","UNKNOWN_ERROR",{params:i});const{salt:o,N:a,r:c,p:l,dkLen:u}=i;return Ow(r,await bu(s,o,a,c,l,u,n))}(e,n,r):$w(e)&&(r&&(r(0),await Jw(0)),i=Qw(e,n),r&&(r(1),await Jw(0))),Ln(s=t,In,On).call(s,i)}static fromEncryptedJsonSync(e,n){var r;let s=null;return Iw(e)?s=function(t,e){const n=JSON.parse(t),r=Sw(e),s=Cw(n);if("pbkdf2"===s.name){const{salt:t,count:e,dkLen:i,algorithm:o}=s;return Ow(n,ru(r,t,e,i,o))}qo("scrypt"===s.name,"cannot be reached","UNKNOWN_ERROR",{params:s});const{salt:i,N:o,r:a,p:c,dkLen:l}=s;return Ow(n,Au(r,i,o,a,c,l))}(e,n):$w(e)?s=Qw(e,n):$o(!1,"invalid JSON wallet","json","[ REDACTED ]"),Ln(r=t,In,On).call(r,s)}static createRandom(t){const e=zw.createRandom();return t?e.connect(t):e}static fromPhrase(t,e){const n=zw.fromPhrase(t);return e?n.connect(e):n}};In=new WeakSet,On=function(t){if($o(t,"invalid JSON wallet","json","[ REDACTED ]"),"mnemonic"in t&&t.mnemonic&&"en"===t.mnemonic.locale){const e=jy.fromEntropy(t.mnemonic.entropy),n=zw.fromMnemonic(e,t.mnemonic.path);if(n.address===t.address&&n.privateKey===t.privateKey)return n;console.log("WARNING: JSON mismatch address/privateKey != mnemonic; fallback onto private key")}const e=new Yw(t.privateKey);return $o(e.address===t.address,"address/privateKey mismatch","json","[ REDACTED ]"),e},Dn(Yw,In);let Zw=Yw;const Xw=3000000n,tb=2000000000n,eb=1000000000n,nb=4096,rb="dns_txt",sb=(1n<<64n)-1n,ib=["function publishDocument(string name,string docType,uint64 expectedVersion,(bytes32 storageType,string uri,bytes inlineDocument,bytes32 contentHash,bytes32 schema,bytes32 codec,bytes32 extraHash) document,(uint8 kind,bytes value) controller,(uint8 kind,bytes value) beneficiary,address paymentTarget,uint64 expireAt,bytes32 controllerPolicyHash,bytes32 paymentPolicyHash,bytes32 splitPolicyHash,bytes32 pricePolicyHash,bytes32 rightsPolicyHash,(uint8 role,(uint8 kind,bytes value) actor,bytes32 kid) authority,(uint64 expectedNameSeq,uint64 expectedParentNameSeq) guard) returns (uint64 version)"],ob=new _g(ib),ab=[0,"0x"],cb=function(t){const e=Da(t);if(e.length>31)throw new Error("bytes32 string must be less than 32 bytes");return ha(e,32)}("inline");class lb extends Error{constructor(t,e){super(e),this.name="BnsEvmTxError",this.code=t}}function ub(t,e,n){let r;try{r=BigInt(e)}catch{throw new lb("INVALID_CONFIG",`${t} must be an integer`)}if(r<0n||void 0!==n&&r>n)throw new lb("INVALID_CONFIG",`${t} is out of range`);return r}function hb(t){const e=Mn.canonicalize(t);if("string"!=typeof e)throw new lb("INVALID_DOCUMENT","document cannot be encoded as canonical JSON");const n=Da(e);if(0===n.length||n.length>nb)throw new lb("INVALID_DOCUMENT",`inline document is ${n.length} bytes, max 4096`);return n}function db(t,e){if(!t||"object"!=typeof t||Array.isArray(t))throw new lb("INVALID_DOCUMENT",`${e} must be an object`);const n=t;if(!Number.isInteger(n.ttl)||n.ttl<0||n.ttl>4294967295)throw new lb("INVALID_DOCUMENT",`${e}.ttl must be a u32`);if("string"!=typeof n.value||0===n.value.length)throw new lb("INVALID_DOCUMENT",`${e}.value must be a non-empty string`);return{ttl:n.ttl,value:n.value}}class fb{constructor(t,e,n){if(this.nextNonce=null,this.client=t,this.config=e,this.chainId=ub("chainId",e.chainId,sb),this.contractAddress=$h(e.contractAddress),this.gasLimit=ub("gasLimit",e.gasLimit??Xw,sb),this.maxFeePerGas=ub("maxFeePerGas",e.maxFeePerGas??tb),this.maxPriorityFeePerGas=ub("maxPriorityFeePerGas",e.maxPriorityFeePerGas??eb),!e.rpcEndpoint&&!n)throw new lb("INVALID_CONFIG","rpcEndpoint is required");if(0n===this.chainId||0n===this.gasLimit)throw new lb("INVALID_CONFIG","chainId and gasLimit must be greater than zero");if(this.maxFeePerGas<this.maxPriorityFeePerGas)throw new lb("INVALID_CONFIG","maxFeePerGas must be >= maxPriorityFeePerGas");this.provider=n??new Sy(e.rpcEndpoint,this.chainId,{staticNetwork:!0})}resetNonce(){this.nextNonce=null}async buildAndSign(t,e){const n=new Zw(e),r="publish_document"===t.type?await this.preparePublishedDocument(t.request):await this.prepareDnsTxtDocument(t.request),s=this.encodePublishDocument(r,n.address),i=await this.allocateNonce(n.address);try{return await n.signTransaction({type:2,chainId:this.chainId,nonce:i,to:this.contractAddress,value:0,data:s,gasLimit:this.gasLimit,maxFeePerGas:this.maxFeePerGas,maxPriorityFeePerGas:this.maxPriorityFeePerGas})}catch(o){throw this.resetNonce(),o}}async allocateNonce(t){null===this.nextNonce&&(this.nextNonce=await this.provider.getTransactionCount(t,"pending"));const e=this.nextNonce;return this.nextNonce+=1,e}async preparePublishedDocument(t){if(!t.document||"object"!=typeof t.document||Array.isArray(t.document))throw new lb("INVALID_DOCUMENT","publish_document document must be a JSON object");return this.prepareDocument(t.name,t.doc_type,hb(t.document))}async prepareDnsTxtDocument(t){const e=await this.getCurrentDocument(t.name,rb);let n=[];if(e){if("inline"!==e.document_state.document.storage_type)throw new lb("INVALID_DOCUMENT","DNS TXT helper can only update inline documents");let t;try{t=JSON.parse(function(t){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(new Uint8Array(t));let e="";for(const n of t)e+=String.fromCharCode(n);try{return decodeURIComponent(escape(e))}catch{return e}}(e.document_state.document.inline_document))}catch(s){throw new lb("INVALID_DOCUMENT",`current dns_txt document is not valid JSON: ${s instanceof Error?s.message:String(s)}`)}if(!Array.isArray(t))throw new lb("INVALID_DOCUMENT","current dns_txt document must be an array");n=t.map(((t,e)=>db(t,`dns_txt[${e}]`)))}switch(t.mode){case"add":{if(!t.value)throw new lb("INVALID_OPERATION","publish_dns_txt mode=add requires value");const e=db({ttl:t.ttl??600,value:t.value},"dns_txt");n.some((t=>t.value===e.value))||n.push(e);break}case"remove":if(!t.value)throw new lb("INVALID_OPERATION","publish_dns_txt mode=remove requires value");n=n.filter((e=>e.value!==t.value));break;case"replace":if(!t.records)throw new lb("INVALID_OPERATION","publish_dns_txt mode=replace requires records");n=t.records.map(((t,e)=>db({ttl:t.ttl??600,value:t.value},`dns_txt[${e}]`)));break;default:throw new lb("INVALID_OPERATION",`publish_dns_txt mode \`${t.mode}\` is not supported`)}const r=await this.getNameState(t.name);return{name:xo(t.name),docType:rb,expectedVersion:(null==e?void 0:e.document_state.version)??0,inlineDocument:hb(n),nameState:r}}async prepareDocument(t,e,n){const r=xo(t),s=Po(e),[i,o]=await Promise.all([this.getNameState(r),this.getCurrentDocument(r,s)]);return{name:r,docType:s,expectedVersion:(null==o?void 0:o.document_state.version)??0,inlineDocument:n,nameState:i}}async getNameState(t){const e=await this.client.queryNameState(t);if(!e)throw new lb("NAME_NOT_FOUND",`BNS name \`${t}\` was not found`);return e}async getCurrentDocument(t,e){try{const n=await this.client.resolveDocument(t,e);return"missing"===n.status?null:n}catch(n){if(function(t){return t instanceof Ki&&t.isRegistryCode("DOCUMENT_NOT_FOUND")}(n))return null;throw n}}encodePublishDocument(t,e){const n=this.ownerAuthority(t.nameState,e),r=[cb,"",ia(t.inlineDocument),ku(t.inlineDocument),Oh,Oh,Oh];return ob.encodeFunctionData("publishDocument",[t.name,t.docType,t.expectedVersion,r,ab,ab,Ih,0,Oh,Oh,Oh,Oh,Oh,n,[t.nameState.name_seq,0]])}ownerAuthority(t,e){const n=t.effective_owner;if("chain_account"===n.kind){const s=$h(n.value);if(s!==$h(e))throw new lb("LOCAL_SIGNER_NOT_OWNER",`local signer ${e} is not effective owner ${s} of ${t.name}`);return[1,(r=e,[1,ia(ta(r))]),Oh]}var r;if("bns_name"===n.kind){const e=function(t,e){if(!e)return Oh;const n=ta(e);if(32!==n.length)throw new lb("INVALID_CONFIG",`${t} must be a 32-byte hex value`);return ia(n)}("authorityKid",this.config.authorityKid);if(e===Oh)throw new lb("AUTHORITY_KID_REQUIRED",`authorityKid is required when ${t.name} is controlled by BNS name ${n.value}`);return[1,[2,ia(Da(n.value))],e]}throw new lb("LOCAL_SIGNER_NOT_OWNER",`BNS name ${t.name} has no concrete effective owner`)}}class pb extends Error{constructor(t,e,n){super(n),this.name="BnsTxExecutorError",this.code=t,this.route=e}}function gb(t){if("string"!=typeof t)return null;const e=t.trim();return e.length>0?e:null}function mb(t){return t===Ds.NodeJS||t===Ds.AppClient||t===Ds.AppService}function yb(t){if(!t||"object"!=typeof t||Array.isArray(t))return!1;const e=t;return"boolean"==typeof e.sn_account?e.sn_account:null!==gb(e.sn_username)||null!==gb(e.sn_user_name)}const wb="/kapi/sn",bb="/kapi/sn/auth",Ab="/kapi/sn/deviceinfo",_b="/kapi/sn/bns-proxy",vb="/kapi/sn/bns",Eb="/kapi/sn/region-probe-config.json",kb=1048576,Sb="auth.check_username",Tb="auth.check_active_code",Rb="auth.register",Ib="auth.login",Ob="auth.refresh",Cb="auth.logout",Nb="auth.me",xb="user.get_profile",Pb="user.set_self_cert",Db="user.add_dns_record",Bb="user.remove_dns_record",Ub="user.list_dns_records",Lb="zone.get_info",Mb="domain.bind",Fb="domain.unbind",Gb="device.register",jb="device.update",Hb="device.get",Vb="device.list",Wb="deviceinfo.resolve_ood_by_did",Kb="deviceinfo.resolve_ood_by_hostname",zb="bns.publish_dns_txt",qb="bns.publish_document",$b="owner.remove_bound_zone",Qb=/\[SN:(\d+):([a-z_]+)\]\s*/;class Jb extends Error{constructor(t,e,n=null,r=null,s=null){super(e),this.name="SnClientError",this.kind=t,this.code=n,this.codeName=r,this.detail=s??e}isSnError(t){return"sn"===this.kind&&this.codeName===t}domainProofInfo(){return this.isSnError("domain_proof_failed")?Yb(this.detail):null}bnsWriteInfo(){return this.isSnError("bns_permission_denied")||this.isSnError("bns_name_already_exists")||this.isSnError("bns_write_failed")?Yb(this.detail):null}static fromRpcError(t,e){if(e instanceof Jb)return e;const n=e instanceof Error?e.message:String(e),r=Qb.exec(n);if(r){const e=parseInt(r[1],10),s=r[2],i=n.slice(r.index+r[0].length);return new Jb("sn",`${t} failed: [SN:${e}:${s}] ${i}`,e,s,i)}return new Jb("transport",`${t} failed: ${n}`)}}function Yb(t){try{const e=JSON.parse(t);return null===e||"object"!=typeof e||Array.isArray(e)?null:e}catch{return null}}const Zb={auth:bb,deviceinfo:Ab,"bns-proxy":_b},Xb=[_b,Ab,bb,vb,wb];function tA(t,e){const n=Zb[e],r=t.replace(/\/+$/,"");for(const s of Xb)if(r.endsWith(s))return`${r.slice(0,r.length-s.length)}${n}`;return`${r}${n}`}const eA=[Eb,_b,Ab,bb,vb,wb],nA=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/,rA=/[\u0000-\u001f\u007f-\u009f]/u;function sA(t){throw new Jb("validation",t)}function iA(t){return(new TextEncoder).encode(t).byteLength}function oA(t,e){return(null===t||"object"!=typeof t||Array.isArray(t))&&sA(`${e} must be a JSON object`),t}function aA(t,e){return"string"!=typeof t&&sA(`${e} must be a string`),t}function cA(t,e){return"number"!=typeof t&&sA(`${e} must be a number`),t}function lA(t,e){const n=cA(t,e);return Number.isSafeInteger(n)||sA(`${e} must be a safe integer`),n}function uA(t,e){const n=lA(t,e);return(n<-2147483648||n>2147483647)&&sA(`${e} must fit in a signed 32-bit integer`),n}function hA(t,e){return Array.isArray(t)||sA(`${e} must be an array`),t}function dA(t){return iA(t)<=128&&/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(t)}function fA(t){const e=t.split(".");if(4!==e.length)return null;const n=e.map((t=>Number(t)));return n.some(((t,n)=>!/^\d+$/.test(e[n])||!Number.isInteger(t)||t<0||t>255))?null:n}function pA(t){const e=fA(t);if(!e)return!1;const[n,r,s]=e;return!(0===n||10===n||127===n||100===n&&r>=64&&r<=127||169===n&&254===r||172===n&&r>=16&&r<=31||192===n&&0===r&&0===s||192===n&&0===r&&2===s||192===n&&88===r&&99===s||192===n&&168===r||198===n&&(18===r||19===r)||198===n&&51===r&&100===s||203===n&&0===r&&113===s||n>=224)}function gA(t,e){const n=Date.parse(t);return nA.test(t)&&Number.isFinite(n)||sA(`${e} must be an RFC 3339 timestamp`),n}function mA(t,e=Date.now()){1!==t.schema_version&&sA(`unsupported schema_version ${t.schema_version}, expected 1`),(0===t.config_version.length||iA(t.config_version)>128||t.config_version.trim()!==t.config_version||rA.test(t.config_version))&&sA("config_version must be 1..=128 non-control bytes without surrounding whitespace");const n=gA(t.generated_at,"generated_at"),r=gA(t.expires_at,"expires_at"),s=e instanceof Date?e.getTime():"number"==typeof e?e:Date.parse(e);Number.isFinite(s)||sA("validation time is invalid"),n>=r&&sA("expires_at must be later than generated_at"),r<=s&&sA("region probe config is expired");const i=t.policy;"tcp_connect"!==i.probe_method&&sA(`unsupported probe_method ${JSON.stringify(i.probe_method)}`),"ipv4"!==i.ip_family&&sA(`unsupported ip_family ${JSON.stringify(i.ip_family)}`),(i.samples_per_url<1||i.samples_per_url>3)&&sA("samples_per_url must be in 1..=3"),(i.connect_timeout_ms<1||i.connect_timeout_ms>1e4)&&sA("connect_timeout_ms must be in 1..=10000"),(i.round_timeout_ms<1||i.round_timeout_ms>3e4)&&sA("round_timeout_ms must be in 1..=30000"),(i.max_concurrency<1||i.max_concurrency>32)&&sA("max_concurrency must be in 1..=32"),(i.minimum_valid_urls<2||i.minimum_valid_urls>16)&&sA("minimum_valid_urls must be in 2..=16"),(!Number.isFinite(i.confident_ratio)||i.confident_ratio<=0||i.confident_ratio>1)&&sA("confident_ratio must be finite and in (0, 1]"),(i.cache_ttl_sec<1||i.cache_ttl_sec>21600)&&sA("cache_ttl_sec must be in 1..=21600"),(t.regions.length<1||t.regions.length>64)&&sA("regions must contain 1..=64 entries");const o=new Set,a=new Set,c=new Map;let l=0;for(const h of t.regions){dA(h.region_id)||sA(`invalid canonical region_id ${JSON.stringify(h.region_id)}`),o.has(h.region_id)&&sA(`duplicate region_id ${JSON.stringify(h.region_id)}`),o.add(h.region_id),(h.probe_urls.length<2||h.probe_urls.length>16)&&sA(`region ${h.region_id} must contain 2..=16 probe_urls`),i.minimum_valid_urls>h.probe_urls.length&&sA(`region ${h.region_id} has fewer probe_urls than minimum_valid_urls`),l+=h.probe_urls.length,l>256&&sA("config contains more than 256 probe URLs");for(const t of h.probe_urls){let e;(0===t.id.length||iA(t.id)>128||t.id.trim()!==t.id||rA.test(t.id))&&sA(`probe URL id in region ${h.region_id} must be 1..=128 non-control bytes without surrounding whitespace`),a.has(t.id)&&sA(`duplicate probe URL id ${JSON.stringify(t.id)}`),a.add(t.id);try{e=new URL(t.url)}catch(u){sA(`invalid probe URL ${JSON.stringify(t.url)}: ${String(u)}`)}"https:"!==e.protocol&&sA(`probe URL ${JSON.stringify(t.url)} must use https`),(!e.hostname||e.username||e.password)&&sA(`probe URL ${JSON.stringify(t.url)} must be absolute and must not contain userinfo`),""!==e.port&&sA(`probe URL ${JSON.stringify(t.url)} must use port 443`);const n=fA(e.hostname),r=e.hostname.startsWith("[")&&e.hostname.endsWith("]");(n&&!pA(e.hostname)||r)&&sA(`probe URL ${JSON.stringify(t.url)} has a non-public or unsupported literal IP`);const s=c.get(e.origin);void 0!==s&&(s!==h.region_id&&sA(`probe origin ${e.origin} is assigned to both ${s} and ${h.region_id}`),sA(`probe origin ${e.origin} is duplicated in region ${h.region_id}`)),c.set(e.origin,h.region_id)}}}function yA(t){let e,n;try{e="string"==typeof t?t:new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch(s){sA(`parse region probe config JSON failed: ${String(s)}`)}try{n=JSON.parse(e)}catch(s){sA(`parse region probe config JSON failed: ${String(s)}`)}const r=function(t){const e=oA(t,"region probe config"),n=oA(e.policy,"policy"),r={probe_method:aA(n.probe_method,"policy.probe_method"),samples_per_url:lA(n.samples_per_url,"policy.samples_per_url"),connect_timeout_ms:lA(n.connect_timeout_ms,"policy.connect_timeout_ms"),round_timeout_ms:lA(n.round_timeout_ms,"policy.round_timeout_ms"),max_concurrency:lA(n.max_concurrency,"policy.max_concurrency"),ip_family:aA(n.ip_family,"policy.ip_family"),minimum_valid_urls:lA(n.minimum_valid_urls,"policy.minimum_valid_urls"),confident_ratio:cA(n.confident_ratio,"policy.confident_ratio"),cache_ttl_sec:lA(n.cache_ttl_sec,"policy.cache_ttl_sec")},s=hA(e.regions,"regions").map(((t,e)=>{const n=oA(t,`regions[${e}]`),r=hA(n.probe_urls,`regions[${e}].probe_urls`).map(((t,n)=>{const r=oA(t,`regions[${e}].probe_urls[${n}]`),s={id:aA(r.id,`regions[${e}].probe_urls[${n}].id`),url:aA(r.url,`regions[${e}].probe_urls[${n}].url`)};return void 0!==r.provider&&null!==r.provider&&(s.provider=aA(r.provider,`regions[${e}].probe_urls[${n}].provider`)),s}));return{region_id:aA(n.region_id,`regions[${e}].region_id`),priority:void 0===n.priority?0:uA(n.priority,`regions[${e}].priority`),probe_urls:r}}));return{schema_version:lA(e.schema_version,"schema_version"),config_version:aA(e.config_version,"config_version"),generated_at:aA(e.generated_at,"generated_at"),expires_at:aA(e.expires_at,"expires_at"),policy:r,regions:s}}(n);return mA(r),r}function wA(t){let e;try{e=new URL(t.trim())}catch(s){sA(`invalid SN base URL for region probe config: ${String(s)}`)}"https:"!==e.protocol&&sA("region probe config must be fetched from the target SN over HTTPS"),(!e.hostname||e.username||e.password)&&sA("SN region probe config URL must have a host and no userinfo"),e.search="",e.hash="";const n=e.pathname.replace(/\/+$/,"");let r=n;for(const i of eA)if(n.endsWith(i)){r=n.slice(0,n.length-i.length);break}return e.pathname=`${r}${Eb}`,e.toString()}const bA=async(t,e)=>{if("function"!=typeof globalThis.fetch)throw new Error("fetch is not available in this runtime");return globalThis.fetch(t,e)};const AA="sn-device";function _A(t){return void 0!==t.ttl?{ttl:t.ttl,value:t.value}:{value:t.value}}function vA(t){const e={device_did:t.device_did,domain:t.domain,record_type:t.record_type};return void 0!==t.record&&(e.record=t.record),void 0!==t.ttl&&(e.ttl=t.ttl),void 0!==t.has_cert&&(e.has_cert=t.has_cert),e}function EA(t){return{endpoint_id:t.endpoint_id,protocol:t.protocol,host:t.host,port:t.port,scope:t.scope,priority:t.priority,source:t.source,expires_at:t.expires_at}}function kA(t){const e={device_name:t.device_name,device_ip:t.device_ip,device_info:t.device_info};return void 0!==t.device_did&&(e.device_did=t.device_did),void 0!==t.endpoints&&t.endpoints.length>0&&(e.endpoints=t.endpoints.map(EA)),void 0!==t.report_seq&&(e.report_seq=t.report_seq),void 0!==t.ttl&&(e.ttl=t.ttl),e}const SA=Object.freeze(Object.defineProperty({__proto__:null,LEGACY_SN_BNS_PATH:vb,METHOD_AUTH_CHECK_ACTIVE_CODE:Tb,METHOD_AUTH_CHECK_USERNAME:Sb,METHOD_AUTH_LOGIN:Ib,METHOD_AUTH_LOGOUT:Cb,METHOD_AUTH_ME:Nb,METHOD_AUTH_REFRESH:Ob,METHOD_AUTH_REGISTER:Rb,METHOD_BNS_PUBLISH_DNS_TXT:zb,METHOD_BNS_PUBLISH_DOCUMENT:qb,METHOD_DEVICEINFO_RESOLVE_OOD_BY_DID:Wb,METHOD_DEVICEINFO_RESOLVE_OOD_BY_HOSTNAME:Kb,METHOD_DEVICE_GET:Hb,METHOD_DEVICE_LIST:Vb,METHOD_DEVICE_REGISTER:Gb,METHOD_DEVICE_UPDATE:jb,METHOD_DOMAIN_BIND:Mb,METHOD_DOMAIN_UNBIND:Fb,METHOD_OWNER_REMOVE_BOUND_ZONE:$b,METHOD_USER_ADD_DNS_RECORD:Db,METHOD_USER_GET_PROFILE:xb,METHOD_USER_LIST_DNS_RECORDS:Ub,METHOD_USER_REMOVE_DNS_RECORD:Bb,METHOD_USER_SET_SELF_CERT:Pb,METHOD_ZONE_GET_INFO:Lb,SN_AUTH_PATH:bb,SN_BNS_PROXY_PATH:_b,SN_DEVICEINFO_PATH:Ab,SN_DEVICE_TOKEN_AUD:AA,SN_DEVICE_TOKEN_DEFAULT_TTL_SECS:600,SN_ERROR_CODES:{invalid_params:1e3,invalid_username:1001,username_already_exists:1002,invalid_active_code:1003,user_auth_not_found:1004,invalid_password:1005,auth_required:1006,invalid_token:1007,user_not_found:1008,device_not_found:1012,device_permission_denied:1013,invalid_device_did:1014,invalid_domain:1015,domain_proof_failed:1016,hostname_not_found:1017,cross_user_access_denied:1018,unsupported_password_algo:1019,invalid_password_storage:1020,user_not_activated:1022,bns_permission_denied:1023,bns_name_already_exists:1024,bns_write_failed:1025,bns_proxy_unavailable:1026,bns_controller_unavailable:1027,invalid_email:1028,email_already_bound:1029,internal_error:1099},SN_REGION_PROBE_CONFIG_PATH:Eb,SN_REGION_PROBE_FETCH_TIMEOUT:5e3,SN_REGION_PROBE_MAX_CONFIG_BYTES:kb,SN_REGION_PROBE_MAX_REGIONS:64,SN_REGION_PROBE_MAX_TOTAL_URLS:256,SN_REGION_PROBE_MAX_URLS_PER_REGION:16,SN_REGION_PROBE_SCHEMA_VERSION:1,SN_ROOT_PATH:wb,SnClient:class{constructor(t,e=null,n={}){this.authRpc=new jn(tA(t,"auth"),e,null,n),this.deviceInfoRpc=new jn(tA(t,"deviceinfo"),e,null,n),this.bnsProxyRpc=new jn(tA(t,"bns-proxy"),e,null,n)}setSeq(t){this.authRpc.setSeq(t),this.deviceInfoRpc.setSeq(t),this.bnsProxyRpc.setSeq(t)}syncSessionToken(t){this.authRpc.setSessionToken(t),this.deviceInfoRpc.setSessionToken(t),this.bnsProxyRpc.setSessionToken(t)}getSessionToken(){return this.authRpc.getSessionToken()}async call(t,e,n){try{return await t.call(e,n)}catch(r){throw Jb.fromRpcError(e,r)}}async checkUsername(t){return this.call(this.authRpc,Sb,{name:t})}async checkActiveCode(t){return this.call(this.authRpc,Tb,{active_code:t})}async register(t){const e={name:t.name,email:t.email,pwd_hash:t.pwd_hash,active_code:t.active_code};return void 0!==t.request_id&&(e.request_id=t.request_id),void 0!==t.region&&(e.region=t.region),void 0!==t.asset_owner&&(e.asset_owner=t.asset_owner),void 0!==t.owner_config&&(e.owner_config=t.owner_config),void 0!==t.initial_documents&&(e.initial_documents=function(t){const e={};void 0!==t.zone&&(e.zone=t.zone);void 0!==t.boot&&(e.boot=t.boot);void 0!==t.dns_txt&&(e.dns_txt=t.dns_txt.map((t=>({ttl:t.ttl,value:t.value}))));return e}(t.initial_documents)),this.call(this.authRpc,Rb,e)}async login(t){const e={name:t.name,pwd_hash:t.pwd_hash};return void 0!==t.active_code&&(e.active_code=t.active_code),this.call(this.authRpc,Ib,e)}async refresh(t){return this.call(this.authRpc,Ob,{refresh_token:t})}async logout(t){return this.call(this.authRpc,Cb,{refresh_token:t??null})}async me(){return this.call(this.authRpc,Nb,{})}async getProfile(){return this.call(this.authRpc,xb,{})}async setSelfCert(t,e){return this.call(this.authRpc,Pb,{self_cert:t,device_did:e??null})}async addDnsRecord(t){return this.call(this.authRpc,Db,vA(t))}async removeDnsRecord(t){return this.call(this.authRpc,Bb,vA(t))}async listDnsRecords(){return this.call(this.authRpc,Ub,{})}async getZoneInfo(){return this.call(this.authRpc,Lb,{})}async bindDomain(t){return this.call(this.authRpc,Mb,{domain:t})}async unbindDomain(t){return this.call(this.authRpc,Fb,{domain:t})}async registerDeviceOnline(t){return this.call(this.deviceInfoRpc,Gb,kA(t))}async updateDeviceOnline(t){return this.call(this.deviceInfoRpc,jb,kA(t))}async getDeviceOnline(t){return this.call(this.deviceInfoRpc,Hb,{device_name:t.device_name??null,device_did:t.device_did??null})}async listDevicesOnline(t={}){const e={};return void 0!==t.state&&(e.state=t.state),void 0!==t.offset&&(e.offset=t.offset),void 0!==t.limit&&(e.limit=t.limit),this.call(this.deviceInfoRpc,Vb,e)}async resolveOodByDid(t){return this.call(this.deviceInfoRpc,Wb,{source_device_id:t})}async resolveOodByHostname(t){return this.call(this.deviceInfoRpc,Kb,{dest_host:t})}async publishDnsTxt(t){const e={name:t.name,mode:t.mode};switch(void 0!==t.request_id&&(e.request_id=t.request_id),t.mode){case"add":if(!t.value)throw new Jb("validation","publish_dns_txt mode=add requires value");e.value=t.value,void 0!==t.ttl&&(e.ttl=t.ttl);break;case"remove":if(!t.value)throw new Jb("validation","publish_dns_txt mode=remove requires value");e.value=t.value;break;case"replace":if(!t.records)throw new Jb("validation","publish_dns_txt mode=replace requires records");e.records=t.records.map(_A);break;default:throw new Jb("validation",`publish_dns_txt mode \`${t.mode}\` is not supported`)}return this.call(this.bnsProxyRpc,zb,e)}async publishDocument(t){const e=null!==t.document&&"object"==typeof t.document&&!Array.isArray(t.document),n="string"==typeof t.document?t.document.trim().split("."):[],r=3===n.length&&n.every((t=>t.length>0));if(!e&&!r)throw new Jb("validation","publish_document document must be a JSON object or non-empty compact JWT string");if("owner"===t.doc_type.trim().toLowerCase()&&!e)throw new Jb("validation","owner document must be a JSON object");const s={name:t.name,doc_type:t.doc_type,document:t.document};return void 0!==t.request_id&&(s.request_id=t.request_id),this.call(this.bnsProxyRpc,qb,s)}async removeBoundZone(t){return this.call(this.bnsProxyRpc,$b,{name:t.name,zone_did:t.zone_did,expected_owner_hash:t.expected_owner_hash,request_id:t.request_id,owner_authorization:t.owner_authorization})}},SnClientError:Jb,fetchSnRegionProbeConfig:async function(t,e=null,n={}){const r=wA(t),s={Accept:"application/json"};null!==e&&(/[\u0000-\u001f\u007f]/.test(e)&&sA("invalid cached region probe ETag: header value contains control characters"),s["If-None-Match"]=e);const i=new AbortController,o=setTimeout((()=>i.abort()),5e3);try{let t;try{t=await(n.fetcher??bA)(r,{method:"GET",headers:s,redirect:"manual",credentials:"omit",signal:i.signal})}catch(a){throw new Jb("transport",`fetch SN region probe config from ${r} failed: ${String(a)}`)}if(304===t.status)return{kind:"not_modified"};if(404===t.status)return{kind:"not_configured"};if(200!==t.status)throw new Jb("transport",`fetch SN region probe config from ${r} returned HTTP ${t.status}`);const e=t.headers.get("content-type")??"";if("application/json"!==e.split(";")[0].trim().toLowerCase())throw new Jb("transport",`SN region probe config from ${r} has unsupported Content-Type ${JSON.stringify(e)}`);const o=t.headers.get("content-length");if(null!==o&&/^\d+$/.test(o)&&Number(o)>kb)throw new Jb("transport",`SN region probe config from ${r} exceeds 1048576 bytes`);let c,l;try{c=await async function(t,e){if(!t.body){const n=new Uint8Array(await t.arrayBuffer());if(n.byteLength>kb)throw new Jb("transport",`SN region probe config from ${e} exceeds 1048576 bytes`);return n}const n=t.body.getReader(),r=[];let s=0;for(;;){const{done:t,value:i}=await n.read();if(t)break;if(s+=i.byteLength,s>kb)throw await n.cancel(),new Jb("transport",`SN region probe config from ${e} exceeds 1048576 bytes`);r.push(i)}const i=new Uint8Array(s);let o=0;for(const a of r)i.set(a,o),o+=a.byteLength;return i}(t,r)}catch(a){if(a instanceof Jb)throw a;throw new Jb("transport",`read SN region probe config from ${r} failed: ${String(a)}`)}try{l=yA(c)}catch(a){const t=a instanceof Jb?a.detail:String(a);throw new Jb("validation",`invalid SN region probe config from ${r}: ${t}`)}return{kind:"modified",document:{config:l,etag:t.headers.get("etag"),cache_control:t.headers.get("cache-control")}}}finally{clearTimeout(o)}},generateSnDeviceToken:async function(t,e,n,r=600){const s=Math.floor(Date.now()/1e3);return Mn.signJwtEdDSA({aud:AA,exp:s+r,iss:e,sub:t},n)},isCanonicalSnRegionId:dA,isPublicSnProbeIp:pA,normalizeSnRegionIdHint:function(t){const e=t.trim();if(0===iA(e)||iA(e)>128)return null;let n="",r=!1;for(const s of e)if(/^[A-Za-z0-9]$/.test(s))r&&n.length>0&&(n+="-"),r=!1,n+=s.toLowerCase();else{if("-"!==s&&"_"!==s&&"/"!==s&&"."!==s&&!/^\s$/u.test(s))return null;r=n.length>0}return n.length>0?n:null},normalizeSnRegionProbeUrl:wA,normalizeSnUrl:tA,parseSnRegionProbeConfig:yA,validateSnRegionProbeConfig:mA},Symbol.toStringTag,{value:"Module"}));let TA=null;function RA(t,e){let n=null,r=0;const s=[];return{result:new Promise(((i,o)=>{let a;try{a=new Worker(function(){if(!TA){const t=new Blob(['\n"use strict";\nself.onmessage = async function (e) {\n var file = e.data.file;\n var chunkSize = e.data.chunkSize;\n var fileSize = file.size;\n try {\n var offset = 0;\n var index = 0;\n while (offset < fileSize) {\n var end = Math.min(offset + chunkSize, fileSize);\n var buf = await file.slice(offset, end).arrayBuffer();\n var hashBuf = await crypto.subtle.digest("SHA-256", buf);\n var hash = new Uint8Array(hashBuf);\n self.postMessage(\n { type: "chunk", index: index, hash: hash, offset: offset, length: end - offset },\n [hashBuf]\n );\n offset = end;\n index++;\n }\n self.postMessage({ type: "done" });\n } catch (err) {\n self.postMessage({ type: "error", message: err && err.message ? err.message : String(err) });\n }\n};\n'],{type:"application/javascript"});TA=URL.createObjectURL(t)}return TA}())}catch{return void o(new Error("Failed to create hash worker"))}a.onmessage=t=>{const e=t.data;if("chunk"===e.type){const t={index:e.index,hash:e.hash,offset:e.offset,length:e.length};s.push(t),r+=t.length,n&&n(r)}else"done"===e.type?(a.terminate(),i(s)):"error"===e.type&&(a.terminate(),o(new Error(e.message??"Worker hash error")))},a.onerror=t=>{a.terminate(),o(new Error(t.message??"Worker error"))},a.postMessage({file:t,chunkSize:e})})),onProgress(t){n=t}}}class IA extends Error{constructor(t,e){super(e??t),this.code=t,this.name="NdmError"}}class OA extends Error{constructor(t,e,n,r){super(n??`NDM store API request failed with status ${t}`),this.name="NdmStoreApiError",this.status=t,this.errorCode=e,this.responseBody=r}}const CA=4096,NA=new Map;let xA=0;let PA={getCapabilities:()=>({canRevealRealPath:!1,canUseNDMCache:!1,canUseNDMStore:!1,canPickDirectory:"undefined"!=typeof HTMLInputElement&&"webkitdirectory"in HTMLInputElement.prototype,canPickMixed:!1}),pickFiles(t){return new Promise(((e,n)=>{const r=document.createElement("input");if(r.type="file","single_dir"===t.mode){if(!this.getCapabilities().canPickDirectory)return void n(new IA("DIRECTORY_NOT_SUPPORTED","This browser does not support directory selection"));r.webkitdirectory=!0}else"multi_file"!==t.mode&&"mixed"!==t.mode||(r.multiple=!0);t.accept&&t.accept.length>0&&"single_dir"!==t.mode&&(r.accept=t.accept.join(","));let s=!1;r.addEventListener("change",(()=>{if(s)return;s=!0;const t=r.files;t&&0!==t.length?e(Array.from(t)):n(new IA("USER_CANCELLED","No files selected"))}));const i=()=>{setTimeout((()=>{s||(s=!0,n(new IA("USER_CANCELLED","User cancelled file selection"))),window.removeEventListener("focus",i)}),500)};window.addEventListener("focus",i),r.click()}))}};function DA(t,e){if("undefined"!=typeof window&&"function"==typeof window.fetch)return window.fetch(t,e);if("undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch)return globalThis.fetch(t,e);throw new Error("fetch is not available in this runtime")}function BA(t){return t.replace(/\/+$/,"")}function UA(t){return encodeURIComponent(t).replace(/%3A/gi,":")}function LA(t){if(null==t?void 0:t.endpoint)return BA(t.endpoint);const e=Ri();if(e)return BA(e);throw new IA("STORE_API_ENDPOINT_REQUIRED","NDM structured store endpoint is unknown; pass options.endpoint or call initBuckyOS first")}async function MA(t,e,n){var r;!function(){if(Ti()===Ds.Browser)throw new IA("STORE_API_NOT_SUPPORTED_IN_RUNTIME","NDM structured store APIs are not available in pure Browser runtime")}();const s=LA(n),i=(null==n?void 0:n.fetcher)??DA,o=void 0!==(null==n?void 0:n.sessionToken)?n.sessionToken:await Ii(),a={Accept:"application/json","Content-Type":"application/json",...(null==n?void 0:n.headers)??{}};o&&!a.Authorization&&(a.Authorization=`Bearer ${o}`);const c=await i(`${s}/ndm/v1/store/${t}`,{method:"POST",headers:a,body:JSON.stringify(e),credentials:(null==n?void 0:n.credentials)??"include"});if(204===c.status)return void(await(null==(r=c.body)?void 0:r.cancel()));const l=(c.headers.get("content-type")??"").includes("application/json")?await c.json():await c.text();if(!c.ok){const t=l&&"object"==typeof l&&!Array.isArray(l)?l:null;throw new OA(c.status,null==t?void 0:t.error,(null==t?void 0:t.message)??("string"==typeof l&&l.length>0?l:`NDM store API request failed with status ${c.status}`),l)}return l}async function FA(t,e){const n=[`scope=${UA(t.scope)}`,`quick_hash=${UA(t.quick_hash)}`];t.inner_path&&n.push(`inner_path=${UA(t.inner_path)}`);const r=await async function(t,e){const n=LA(e),r=(null==e?void 0:e.fetcher)??DA,s=void 0!==(null==e?void 0:e.sessionToken)?e.sessionToken:await Ii(),i={Accept:"application/json",...(null==e?void 0:e.headers)??{}};s&&!i.Authorization&&(i.Authorization=`Bearer ${s}`);const o=await r(`${n}${t}`,{method:"GET",headers:i,credentials:(null==e?void 0:e.credentials)??"include"}),a=(o.headers.get("content-type")??"").includes("application/json")?await o.json():await o.text();if(!o.ok){const t=a&&"object"==typeof a&&!Array.isArray(a)?a:null;throw new OA(o.status,null==t?void 0:t.error,(null==t?void 0:t.message)??("string"==typeof a&&a.length>0?a:`NDM zone gateway request failed with status ${o.status}`),a)}return a}(`/ndm/v1/objects/lookup?${n.join("&")}`,e);return function(t){try{return Mn.ObjId.fromString(t).isChunk()}catch{return!1}}(t.quick_hash),r}async function GA(t,e=33554432){const n=t.size,r=[];if(n<=e){const e=new Uint8Array(await t.arrayBuffer()),s=Mn.sha256Bytes(e),i=Mn.ChunkId.fromMix256Result(e.length,s).toString();r.push({chunkId:i,offset:0,length:e.length,uploaded:!1});const o=new Mn.FileObject(t.name,n,i),[a]=o.genObjId();return{objectId:a.toString(),chunks:r,fileObject:o.toJSON()}}const s=new Mn.SimpleChunkList;let i=0;for(;i<n;){const o=Math.min(i+e,n),a=new Uint8Array(await t.slice(i,o).arrayBuffer()),c=Mn.sha256Bytes(a),l=Mn.ChunkId.fromMix256Result(a.length,c);s.appendChunk(l),r.push({chunkId:l.toString(),offset:i,length:a.length,uploaded:!1}),i=o}const[o]=s.genObjId(),a=new Mn.FileObject(t.name,n,o.toString()),[c]=a.genObjId();return{objectId:c.toString(),chunks:r,fileObject:a.toJSON()}}async function jA(t,e,n=33554432){if("undefined"==typeof Worker||"undefined"==typeof Blob||"undefined"==typeof URL||"function"!=typeof URL.createObjectURL||"undefined"==typeof crypto||void 0===crypto.subtle)return GA(t,n);let r;try{const s=RA(t,n);e&&s.onProgress(e);const i=3e5,o=new Promise(((t,e)=>{setTimeout((()=>e(new Error("hash worker timeout"))),i)}));r=await Promise.race([s.result,o])}catch{return GA(t,n)}const s=t.size,i=[];if(1===r.length){const e=r[0],n=Mn.ChunkId.fromMix256Result(e.length,e.hash).toString();i.push({chunkId:n,offset:0,length:e.length,uploaded:!1});const o=new Mn.FileObject(t.name,s,n),[a]=o.genObjId();return{objectId:a.toString(),chunks:i,fileObject:o.toJSON()}}const o=new Mn.SimpleChunkList;for(const u of r){const t=Mn.ChunkId.fromMix256Result(u.length,u.hash);o.appendChunk(t),i.push({chunkId:t.toString(),offset:u.offset,length:u.length,uploaded:!1})}const[a]=o.genObjId(),c=new Mn.FileObject(t.name,s,a.toString()),[l]=c.genObjId();return{objectId:l.toString(),chunks:i,fileObject:c.toJSON()}}function HA(t,e,n){const r=new Mn.FileObject(t,e,n),[s]=r.genObjId();return{objectId:s.toString(),fileObject:r.toJSON()}}async function VA(t){const e=t.size;if(e<12288)return null;const n=new Uint8Array(await t.slice(0,CA).arrayBuffer()),r=Math.floor(e/2),s=new Uint8Array(await t.slice(r,r+CA).arrayBuffer()),i=new Uint8Array(n.length+s.length);i.set(n,0),i.set(s,n.length);const o=Mn.sha256Bytes(i);return Mn.ChunkId.fromMixHashResult(e,o,"qcid").toString()}function WA(t,e){const n=t;if("string"==typeof n.same_as&&n.same_as.length>0)return n.same_as;const r=["chunk_list_id","chunklistid","chunk_id","chunkid","content_id","content"];for(const s of r){const t=n[s];if("string"==typeof t&&t.length>0)return t}return"string"==typeof n.object_id&&n.object_id.length>0&&n.object_id!==e?n.object_id:void 0}async function KA(t){const e=function(){var t;const e=Ri();return e?BA(e):"undefined"!=typeof window&&(null==(t=window.location)?void 0:t.origin)?BA(window.location.origin):void 0}();if(!e)return null;const n=await VA(t);if(!n)return null;for(const s of["app","global"])try{const r=WA(await FA({scope:s,quick_hash:n},{endpoint:e,sessionToken:Ti()===Ds.Browser?null:void 0}),n);if(!r)continue;return{...HA(t.name,t.size,r),locality:"store"}}catch(r){if(r instanceof OA&&404===r.status)continue;return null}return null}function zA(t,e){const n=t[0].webkitRelativePath,r={kind:"dir",objectId:"",name:n?n.split("/")[0]:"directory",children:[]},s=new Map;s.set("",r);for(const i of e){const t=(i.relativePath??i.name).split("/"),e=t.length>1?t.slice(1):t;let n=r;for(let r=0;r<e.length-1;r++){const t=e[r],i=e.slice(0,r+1).join("/");let o=s.get(i);o||(o={kind:"dir",objectId:"",name:t,relativePath:i,children:[]},s.set(i,o),n.children.push(o)),n=o}n.children.push(i)}return qA(r),r}function qA(t){const e=new Mn.DirObject(t.name);if(t.children)for(const r of t.children)if("file"===r.kind){if(!r._ndnFileObject)throw new IA("UPLOAD_FAILED",`Missing NDN FileObject for ${r.name}`);e.addFile(r.name,r._ndnFileObject,r.size)}else{const t=qA(r);e.addDirectory(r.name,Mn.ObjId.fromString(t.objectId),t.totalSize)}const[n]=e.genObjId();return t.objectId=n.toString(),{objectId:t.objectId,totalSize:e.total_size,fileCount:e.file_count,fileSize:e.file_size}}function $A(t,e){if(!e||!e.enabled)return!1;if(!e.forTypes||0===e.forTypes.length)return t.type.startsWith("image/");for(const n of e.forTypes)if(n.endsWith("/*")){const e=n.slice(0,-1);if(t.type.startsWith(e))return!0}else if(n.startsWith(".")){if(t.name.toLowerCase().endsWith(n.toLowerCase()))return!0}else if(t.type===n)return!0;return!1}async function QA(t,e){const n=e.maxWidth??256,r=e.maxHeight??256;try{return t.type.startsWith("image/")?await function(t,e,n){return new Promise((r=>{const s=URL.createObjectURL(t),i=new Image;i.onload=()=>{let t=i.naturalWidth,o=i.naturalHeight;if(t>e||o>n){const r=Math.min(e/t,n/o);t=Math.round(t*r),o=Math.round(o*r)}const a=document.createElement("canvas");a.width=t,a.height=o;a.getContext("2d").drawImage(i,0,0,t,o);const c=a.toDataURL("image/jpeg",.8);URL.revokeObjectURL(s),r({available:!0,url:c,width:t,height:o,mimeType:"image/jpeg"})},i.onerror=()=>{URL.revokeObjectURL(s),r({available:!1,errorCode:"THUMBNAIL_GENERATION_FAILED"})},i.src=s}))}(t,n,r):{available:!1,errorCode:"UNSUPPORTED_TYPE"}}catch{return{available:!1,errorCode:"THUMBNAIL_GENERATION_FAILED"}}}async function JA(t){const e=NA.get(t);if(!e)throw new IA("SESSION_NOT_FOUND",`Session ${t} not found`);const n={};let r=0,s=0;for(const[i,o]of e.objectStates)n[i]={objectId:o.objectId,uploadedBytes:o.uploadedBytes,totalBytes:o.size,state:o.state},r+=o.uploadedBytes,"completed"===o.state&&s++;return{sessionId:t,materializationStatus:e.materializationStatus,uploadStatus:e.uploadStatus,summary:e.summary,progress:{uploadedBytes:r,uploadedObjects:s,totalBytes:e.summary.totalBytes,totalObjects:e.summary.totalFiles},perObjectProgress:n}}async function YA(t,e,n,r,s,i,o,a){const c=e.slice(n.offset,n.offset+n.length),l=new Uint8Array(await c.arrayBuffer()),u=`${s}/${n.chunkId}`;let h;try{h=await Promise.resolve().then((()=>require("./tus_client-d0798623.js")))}catch(d){const t=d instanceof Error?d.message:String(d);throw new IA("UPLOAD_FAILED",`Failed to load tus-js-client: ${t}`)}return new Promise(((c,d)=>{if(null==a?void 0:a.aborted)return void d(new IA("UPLOAD_FAILED","Upload aborted"));const f=new Blob([l]),p=new h.Upload(f,{endpoint:`${t}/ndm/v1/uploads`,chunkSize:l.length,retryDelays:[0,1e3,3e3,5e3],storeFingerprintForResuming:!1,metadata:{app_id:s,logical_path:u,file_name:e.name,file_size:String(e.size),file_hash:i,chunk_index:String(r),chunk_hash:n.chunkId,mime_type:e.type||"application/octet-stream"},onProgress:t=>{o(t)},onSuccess:()=>{o(l.length),c(n.chunkId)},onError:t=>{d(new IA("UPLOAD_FAILED",t.message))}});a&&a.addEventListener("abort",(()=>{p.abort(!0),d(new IA("UPLOAD_FAILED","Upload aborted"))})),p.start()}))}async function ZA(t,e){const n=NA.get(t);if(!n)throw new IA("SESSION_NOT_FOUND",`Session ${t} not found`);if("completed"===n.uploadStatus||"not_required"===n.uploadStatus)return JA(t);if("uploading"===n.uploadStatus)return JA(t);if("all_in_store"===n.materializationStatus)return n.uploadStatus="not_required",JA(t);n.uploadStatus="uploading",n.uploadStartTime=Date.now(),n.abortController=new AbortController;const r=(null==e?void 0:e.concurrency)??3;let s;return s=(null==e?void 0:e.endpoint)?e.endpoint.replace(/\/+$/,""):"undefined"!=typeof window?window.location.origin:"",async function(t,e,n){const r=Array.from(t.objectStates.values()).filter((t=>"completed"!==t.state));let s=0,i=0,o=!1;await new Promise(((a,c)=>{function l(){if(!o){if(i>=r.length&&0===s){const e=Array.from(t.objectStates.values()).every((t=>"completed"===t.state));return t.uploadStatus=e?"completed":"failed",void a()}for(;s<n&&i<r.length;){const n=r[i++];s++,XA(t,e,n).then((()=>{s--,l()})).catch((()=>{s--,o||(o=!0,t.uploadStatus="failed",c(new IA("UPLOAD_FAILED",`Upload of ${n.name} failed`)))}))}}}l()}))}(n,s,r).catch((()=>{})),JA(t)}async function XA(t,e,n){var r;n.state="uploading";for(const[s,i]of n.chunks.entries())i.uploaded||(await YA(e,n.file,i,s,"default",n.objectId,(t=>{const e=n.chunks.filter((t=>t!==i&&t.uploaded)).reduce(((t,e)=>t+e.length),0);n.uploadedBytes=e+t}),null==(r=t.abortController)?void 0:r.signal),i.uploaded=!0);n.uploadedBytes=n.size,n.state="completed"}const t_=Object.freeze(Object.defineProperty({__proto__:null,NdmError:IA,NdmStoreApiError:OA,addChunkBySameAs:async function(t,e){return MA("add_chunk_by_same_as",t,e)},anchorState:async function(t,e){return MA("anchor_state",t,e)},applyEdge:async function(t,e){return MA("apply_edge",t,e)},calculateQcidFromFile:async function(t){const e=await VA(t);if(!e)throw new Error("QCID requires file size >= 12288 bytes");return e},debugDumpExpandState:async function(t,e){return MA("debug_dump_expand_state",t,e)},forcedGcUntil:async function(t,e){return MA("forced_gc_until",t,e)},fsAcquire:async function(t,e){return MA("fs_acquire",t,e)},fsAnchorState:async function(t,e){return MA("fs_anchor_state",t,e)},fsRelease:async function(t,e){return MA("fs_release",t,e)},fsReleaseInode:async function(t,e){return MA("fs_release_inode",t,e)},getDirChild:async function(t,e){return MA("get_dir_child",t,e)},getImportProvider:function(){return PA},getImportSessionStatus:JA,getObject:async function(t,e){return MA("get_object",t,e)},getUploadProgress:async function(t){const e=await JA(t),n={sessionId:t,uploadStatus:e.uploadStatus,totalBytes:e.progress.totalBytes,uploadedBytes:e.progress.uploadedBytes,totalObjects:e.progress.totalObjects,uploadedObjects:e.progress.uploadedObjects,perObjectProgress:e.perObjectProgress},r=NA.get(t);if(r.uploadStartTime&&"uploading"===e.uploadStatus&&(n.elapsedMs=Date.now()-r.uploadStartTime,n.uploadedBytes>0&&n.elapsedMs>0)){n.speedBps=Math.round(1e3*n.uploadedBytes/n.elapsedMs);const t=n.totalBytes-n.uploadedBytes;n.estimatedRemainingMs=Math.round(1e3*t/n.speedBps)}return n},haveChunk:async function(t,e){return MA("have_chunk",t,e)},isObjectExist:async function(t,e){return MA("is_object_exist",t,e)},isObjectStored:async function(t,e){return MA("is_object_stored",t,e)},lookupObject:FA,openObject:async function(t,e){return MA("open_object",t,e)},outboxCount:async function(t){return MA("outbox_count",{},t)},pickupAndImport:async function(t){var e;const n=PA.getCapabilities();if("single_dir"===t.mode&&!n.canPickDirectory)throw new IA("DIRECTORY_NOT_SUPPORTED","Current runtime does not support directory selection");if("mixed"===t.mode&&!n.canPickMixed)throw new IA("MODE_NOT_SUPPORTED_IN_RUNTIME","Current runtime does not support mixed file/directory selection");const r=await PA.pickFiles(t);if(0===r.length)throw new IA("USER_CANCELLED","No files selected");const s=[],i=new Map;let o=!0;const a=t.onProgress,c=r.length;for(let y=0;y<r.length;y++){const n=r[y],l=n.webkitRelativePath||void 0;a&&a({phase:"qcid_lookup",fileIndex:y,fileCount:c,fileName:n.name,fileTotalBytes:n.size});const u=await KA(n);let h=null;u||(a&&a({phase:"materializing",fileIndex:y,fileCount:c,fileName:n.name,bytesProcessed:0,fileTotalBytes:n.size}),h=await jA(n,a?t=>{a({phase:"materializing",fileIndex:y,fileCount:c,fileName:n.name,bytesProcessed:t,fileTotalBytes:n.size})}:void 0));const d=(null==u?void 0:u.objectId)??h.objectId,f=(null==u?void 0:u.fileObject)??h.fileObject,p=u?[]:h.chunks,g={kind:"file",objectId:d,name:n.name,size:n.size,mimeType:n.type||void 0,relativePath:l,locality:(null==u?void 0:u.locality)??"local_only",_file:n,_ndnFileObject:f};if($A(n,t.thumbnails)){a&&a({phase:"thumbnail",fileIndex:y,fileCount:c,fileName:n.name,fileTotalBytes:n.size});!1!==(null==(e=t.thumbnails)?void 0:e.eager)?g.thumbnail=await QA(n,t.thumbnails):(g.thumbnail={available:!1},QA(n,t.thumbnails).then((t=>{g.thumbnail=t})))}s.push(g),u||(o=!1),i.set(d,{objectId:d,name:n.name,size:n.size,file:n,uploadedBytes:u?n.size:0,state:u?"completed":"pending",chunks:p})}let l,u;if("single_dir"===t.mode){const t=zA(r,s);l=[t],u=t}else l=s,u="single_file"===t.mode?s[0]:s;const h=function(t){let e=0,n=0,r=0;return function t(s){for(const i of s)"file"===i.kind?(e++,r+=i.size):(n++,i.children&&t(i.children))}(t),{totalObjects:e+n,totalFiles:e,totalDirs:n,totalBytes:r}}(l),d=(xA+=1,`import-${Date.now()}-${xA}`);let f="ok";o||n.canUseNDMStore?f="all_in_store":n.canUseNDMCache&&(f="on_cache");const p="all_in_store"===f?"not_required":"not_started",g={sessionId:d,items:l,materializationStatus:f,uploadStatus:p,summary:h,objectStates:i};NA.set(d,g);const m={sessionId:d,selection:u,items:l,materializationStatus:f,uploadStatus:p,summary:h};return t.autoStartUpload&&"not_started"===p&&(ZA(d).catch((()=>{})),m.uploadStatus="uploading"),m},pin:async function(t,e){return MA("pin",t,e)},putObject:async function(t,e){return MA("put_object",t,e)},queryChunkState:async function(t,e){return MA("query_chunk_state",t,e)},queryObjectById:async function(t,e){return MA("query_object_by_id",t,e)},removeChunk:async function(t,e){return MA("remove_chunk",t,e)},removeObject:async function(t,e){return MA("remove_object",t,e)},setImportProvider:function(t){PA=t},startUpload:ZA,unpin:async function(t,e){return MA("unpin",t,e)},unpinOwner:async function(t,e){return MA("unpin_owner",t,e)}},Symbol.toStringTag,{value:"Module"})),e_="/ndm/proxy/v1";class n_ extends Error{constructor(t,e,n,r){super(n??`NDM proxy request failed with status ${t}`),this.name="NdmProxyApiError",this.status=t,this.errorCode=e,this.responseBody=r}}class r_ extends Error{constructor(t,e){super(e??t),this.name="NdmProxyError",this.code=t}}function s_(t,e){if("undefined"!=typeof window&&"function"==typeof window.fetch)return window.fetch(t,e);if("undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch)return globalThis.fetch(t,e);throw new Error("fetch is not available in this runtime")}function i_(t){return t.replace(/\/+$/,"")}function o_(){const t=Ti();if(t===Ds.Browser||t===Ds.AppRuntime)throw new r_("PROXY_API_NOT_SUPPORTED_IN_RUNTIME","NDM proxy APIs are not available in Browser/AppRuntime; use ndm_client for browser import/upload flows")}function a_(t){if(null==t?void 0:t.endpoint)return i_(t.endpoint);const e=Ri();if(e)return i_(e);throw new r_("PROXY_API_ENDPOINT_REQUIRED","NDM proxy endpoint is unknown; pass options.endpoint or call initBuckyOS first")}async function c_(t,e){const n=void 0!==(null==t?void 0:t.sessionToken)?t.sessionToken:await Ii(),r={...e,...(null==t?void 0:t.headers)??{}};return n&&!r.Authorization&&(r.Authorization=`Bearer ${n}`),r}async function l_(t){const e=(t.headers.get("content-type")??"").includes("application/json")?await t.json():await t.text(),n=e&&"object"==typeof e&&!Array.isArray(e)?e:null;throw new n_(t.status,null==n?void 0:n.error,(null==n?void 0:n.message)??("string"==typeof e&&e.length>0?e:`NDM proxy request failed with status ${t.status}`),e)}async function u_(t,e,n){var r;o_();const s=a_(n),i=(null==n?void 0:n.fetcher)??s_,o=await c_(n,{Accept:"application/json","Content-Type":"application/json"}),a=await i(`${s}${e_}/rpc/${t}`,{method:"POST",headers:o,body:JSON.stringify(e),credentials:(null==n?void 0:n.credentials)??"include"});if(!a.ok)return l_(a);if(204===a.status)return void(await(null==(r=a.body)?void 0:r.cancel()));if(!(a.headers.get("content-type")??"").includes("application/json")){const t=await a.text();throw new n_(a.status,"invalid_data",t.length>0?t:"NDM proxy JSON RPC returned a non-JSON response",t)}return await a.json()}function h_(t,e){const n=t.get(e);if(null===n||""===n.trim())return null;const r=Number(n);return Number.isFinite(r)?r:null}async function d_(t,e,n){o_();const r=a_(n),s=(null==n?void 0:n.fetcher)??s_,i=await c_(n,{Accept:"application/octet-stream","Content-Type":"application/json"}),o=await s(`${r}${e_}${t}`,{method:"POST",headers:i,body:JSON.stringify(e),credentials:(null==n?void 0:n.credentials)??"include"});return o.ok?{response:o,body:o.body,totalSize:h_(o.headers,"NDM-Total-Size"),resolvedObjectId:o.headers.get("NDM-Resolved-Object-ID")??void 0,readerKind:o.headers.get("NDM-Reader-Kind")??void 0,contentLength:h_(o.headers,"Content-Length"),offset:h_(o.headers,"NDM-Offset")}:l_(o)}async function f_(t){const e=await t.response.arrayBuffer();return new Uint8Array(e)}class p_{constructor(t){this.options=t}getObject(t,e){return w_(t,{...this.options,...e})}openObject(t,e){return b_(t,{...this.options,...e})}getDirChild(t,e){return A_(t,{...this.options,...e})}isObjectStored(t,e){return __(t,{...this.options,...e})}isObjectExist(t,e){return v_(t,{...this.options,...e})}queryObjectById(t,e){return E_(t,{...this.options,...e})}putObject(t,e){return k_(t,{...this.options,...e})}removeObject(t,e){return S_(t,{...this.options,...e})}haveChunk(t,e){return T_(t,{...this.options,...e})}queryChunkState(t,e){return R_(t,{...this.options,...e})}removeChunk(t,e){return I_(t,{...this.options,...e})}addChunkBySameAs(t,e){return O_(t,{...this.options,...e})}applyEdge(t,e){return C_(t,{...this.options,...e})}pin(t,e){return N_(t,{...this.options,...e})}unpin(t,e){return x_(t,{...this.options,...e})}unpinOwner(t,e){return P_(t,{...this.options,...e})}fsAcquire(t,e){return D_(t,{...this.options,...e})}fsRelease(t,e){return B_(t,{...this.options,...e})}fsReleaseInode(t,e){return U_(t,{...this.options,...e})}fsAnchorState(t,e){return L_(t,{...this.options,...e})}forcedGcUntil(t,e){return M_(t,{...this.options,...e})}outboxCount(t){return F_({...this.options,...t})}debugDumpExpandState(t,e){return G_(t,{...this.options,...e})}anchorState(t,e){return j_(t,{...this.options,...e})}}class g_{constructor(t){this.options=t}openChunkReader(t,e){return H_(t,{...this.options,...e})}getChunkData(t,e){return V_(t,{...this.options,...e})}getChunkPiece(t,e){return W_(t,{...this.options,...e})}openChunkListReader(t,e){return K_(t,{...this.options,...e})}openReader(t,e){return z_(t,{...this.options,...e})}}class m_{constructor(t){this.options=t}putChunkByReader(t,e,n){return q_(t,e,{...this.options,...n})}putChunk(t,e,n){return $_(t,e,{...this.options,...n})}}class y_{constructor(t){this.options=t,this.rpc=new p_(t),this.reader=new g_(t),this.writer=new m_(t)}getObject(t,e){return this.rpc.getObject(t,e)}openObject(t,e){return this.rpc.openObject(t,e)}getDirChild(t,e){return this.rpc.getDirChild(t,e)}isObjectStored(t,e){return this.rpc.isObjectStored(t,e)}isObjectExist(t,e){return this.rpc.isObjectExist(t,e)}queryObjectById(t,e){return this.rpc.queryObjectById(t,e)}putObject(t,e){return this.rpc.putObject(t,e)}removeObject(t,e){return this.rpc.removeObject(t,e)}haveChunk(t,e){return this.rpc.haveChunk(t,e)}queryChunkState(t,e){return this.rpc.queryChunkState(t,e)}removeChunk(t,e){return this.rpc.removeChunk(t,e)}addChunkBySameAs(t,e){return this.rpc.addChunkBySameAs(t,e)}applyEdge(t,e){return this.rpc.applyEdge(t,e)}pin(t,e){return this.rpc.pin(t,e)}unpin(t,e){return this.rpc.unpin(t,e)}unpinOwner(t,e){return this.rpc.unpinOwner(t,e)}fsAcquire(t,e){return this.rpc.fsAcquire(t,e)}fsRelease(t,e){return this.rpc.fsRelease(t,e)}fsReleaseInode(t,e){return this.rpc.fsReleaseInode(t,e)}fsAnchorState(t,e){return this.rpc.fsAnchorState(t,e)}forcedGcUntil(t,e){return this.rpc.forcedGcUntil(t,e)}outboxCount(t){return this.rpc.outboxCount(t)}debugDumpExpandState(t,e){return this.rpc.debugDumpExpandState(t,e)}anchorState(t,e){return this.rpc.anchorState(t,e)}openChunkReader(t,e){return this.reader.openChunkReader(t,e)}getChunkData(t,e){return this.reader.getChunkData(t,e)}getChunkPiece(t,e){return this.reader.getChunkPiece(t,e)}openChunkListReader(t,e){return this.reader.openChunkListReader(t,e)}openReader(t,e){return this.reader.openReader(t,e)}putChunkByReader(t,e,n){return this.writer.putChunkByReader(t,e,n)}putChunk(t,e,n){return this.writer.putChunk(t,e,n)}withOptions(t){return new y_({...this.options,...t})}}async function w_(t,e){return u_("get_object",t,e)}async function b_(t,e){return u_("open_object",t,e)}async function A_(t,e){return u_("get_dir_child",t,e)}async function __(t,e){return u_("is_object_stored",t,e)}async function v_(t,e){return u_("is_object_exist",t,e)}async function E_(t,e){return u_("query_object_by_id",t,e)}async function k_(t,e){return u_("put_object",t,e)}async function S_(t,e){return u_("remove_object",t,e)}async function T_(t,e){return u_("have_chunk",t,e)}async function R_(t,e){return u_("query_chunk_state",t,e)}async function I_(t,e){return u_("remove_chunk",t,e)}async function O_(t,e){return u_("add_chunk_by_same_as",t,e)}async function C_(t,e){return u_("apply_edge",t,e)}async function N_(t,e){return u_("pin",t,e)}async function x_(t,e){return u_("unpin",t,e)}async function P_(t,e){return u_("unpin_owner",t,e)}async function D_(t,e){return u_("fs_acquire",t,e)}async function B_(t,e){return u_("fs_release",t,e)}async function U_(t,e){return u_("fs_release_inode",t,e)}async function L_(t,e){return u_("fs_anchor_state",t,e)}async function M_(t,e){return u_("forced_gc_until",t,e)}async function F_(t){return u_("outbox_count",{},t)}async function G_(t,e){return u_("debug_dump_expand_state",t,e)}async function j_(t,e){return u_("anchor_state",t,e)}async function H_(t,e){return d_("/read/chunk/open",t,e)}async function V_(t,e){return f_(await d_("/read/chunk/data",t,e))}async function W_(t,e){return f_(await d_("/read/chunk/piece",t,e))}async function K_(t,e){return d_("/read/chunklist/open",t,e)}async function z_(t,e){return d_("/read/object/open",t,e)}async function q_(t,e,n){var r;o_();const s=a_(n),i=(null==n?void 0:n.fetcher)??s_,o=function(t){return t instanceof Uint8Array||t instanceof ArrayBuffer?t.byteLength:"undefined"!=typeof Blob&&t instanceof Blob?t.size:"string"==typeof t?(new TextEncoder).encode(t).byteLength:null}(e),a=(null==n?void 0:n.chunkSize)??o;if(null===a)throw new r_("PROXY_API_CHUNK_SIZE_REQUIRED","chunkSize is required when the request body length cannot be inferred");const c=await c_(n,{Accept:"application/json","Content-Type":"application/octet-stream","Content-Length":String(a),"NDM-Chunk-Size":String(a)}),l=await i(`${s}${function(t){return`${e_}/write/chunk/${encodeURIComponent(t)}`}(t)}`,{method:"PUT",headers:c,body:e,credentials:(null==n?void 0:n.credentials)??"include"});return l.ok?(await(null==(r=l.body)?void 0:r.cancel()),{chunkSize:h_(l.headers,"NDM-Chunk-Size"),outcome:l.headers.get("NDM-Chunk-Write-Outcome")??void 0,chunkObjectId:l.headers.get("NDM-Chunk-Object-ID")??void 0}):l_(l)}async function $_(t,e,n){return q_(t,e,{...n,chunkSize:(null==n?void 0:n.chunkSize)??e.byteLength})}const Q_=Object.freeze(Object.defineProperty({__proto__:null,NDM_PROXY_V1_PATH:e_,NdmProxyApiError:n_,NdmProxyClient:y_,NdmProxyError:r_,NdmProxyReaderClient:g_,NdmProxyRpcClient:p_,NdmProxyWriterClient:m_,addChunkBySameAs:O_,anchorState:j_,applyEdge:C_,createNdmProxyClient:function(t){return new y_(t)},debugDumpExpandState:G_,forcedGcUntil:M_,fsAcquire:D_,fsAnchorState:L_,fsRelease:B_,fsReleaseInode:U_,getChunkData:V_,getChunkPiece:W_,getDirChild:A_,getObject:w_,haveChunk:T_,isObjectExist:v_,isObjectStored:__,openChunkListReader:K_,openChunkReader:H_,openObject:b_,openReader:z_,outboxCount:F_,pin:N_,putChunk:$_,putChunkByReader:q_,putObject:k_,queryChunkState:R_,queryObjectById:E_,removeChunk:I_,removeObject:S_,unpin:x_,unpinOwner:P_},Symbol.toStringTag,{value:"Module"}));exports.AGENT_DELEGATE_TASK_SCHEMA_ID="agent.delegate/v1",exports.AICC_AI_METHODS=Lr,exports.AICC_COMPUTE_TASK_SCHEMA_ID="aicc.compute/v1",exports.AICC_CORE_METHODS=Mr,exports.AICC_EXECUTION_MODES=jr,exports.AICC_FEATURES={PLAN:"plan",TOOL_CALL:"tool_call",JSON_SCHEMA:"json_schema",WEB_SEARCH:"web_search",VISION:"vision",IMAGE_GENERATION:"image_generation",ASR:"asr",VIDEO_UNDERSTAND:"video_understand"},exports.AICC_MANAGEMENT_METHODS=Fr,exports.AICC_METHODS=Gr,exports.AICC_SERVICE_SERVICE_NAME="aicc",exports.AICC_SERVICE_SERVICE_PORT=4040,exports.AICC_SERVICE_UNIQUE_ID="aicc",exports.APP_INSTALL_TASK_SCHEMA_ID="app.install/v1",exports.APP_START_TASK_SCHEMA_ID="app.start/v1",exports.APP_UNINSTALL_TASK_SCHEMA_ID="app.uninstall/v1",exports.APP_UPDATE_BATCH_TASK_SCHEMA_ID="app.update_batch/v1",exports.APP_UPDATE_TASK_SCHEMA_ID="app.update/v1",exports.AiccClient=Qr,exports.BNS_DNS_TXT_DEFAULT_TTL=600,exports.BNS_DNS_TXT_DOC_TYPE=rb,exports.BNS_EVM_DEFAULT_GAS_LIMIT=Xw,exports.BNS_EVM_DEFAULT_MAX_FEE_PER_GAS=tb,exports.BNS_EVM_DEFAULT_MAX_PRIORITY_FEE_PER_GAS=eb,exports.BNS_MAX_INLINE_DOCUMENT_BYTES=nb,exports.BNS_PUBLISH_DOCUMENT_ABI=ib,exports.BS_SERVICE_TASK_MANAGER="task-manager",exports.BS_SERVICE_VERIFY_HUB="verify-hub",exports.BnsEvmTxBuilder=fb,exports.BnsEvmTxError=lb,exports.BnsTxExecutor=class{constructor(t={}){this.localExecutionTail=Promise.resolve(),this.options=t,this.evmTxBuilder=t.bnsClient&&t.evmConfig?new fb(t.bnsClient,t.evmConfig,t.evmProvider):null}async resolveRoute(){const t=this.getRuntimeType(),e=mb(t)?await this.getLocalPrivateKey():null;return this.resolveRouteFor(t,e)}async resolveRouteFor(t,e){if(mb(t)&&this.options.evmConfig&&e)return"local";if(t===Ds.AppRuntime){const t=await this.getCurrentWalletUser();if(t&&!yb(t))return"wallet"}return"sn-proxy"}async execute(t){const e=this.getRuntimeType(),n=mb(e)?await this.getLocalPrivateKey():null,r=await this.resolveRouteFor(e,n);switch(r){case"local":return this.executeLocally(t,e,n);case"wallet":throw new pb("WALLET_EXECUTION_NOT_IMPLEMENTED",r,`BNS wallet execution is not implemented for operation ${t.type}`);case"sn-proxy":return this.executeWithSn(t)}}publishDnsTxt(t){return this.execute({type:"publish_dns_txt",request:t})}publishDocument(t){return this.execute({type:"publish_document",request:t})}getRuntimeType(){return(this.options.getRuntimeType??Ti)()}getCurrentWalletUser(){return Promise.resolve((this.options.getCurrentWalletUser??wi)())}async getLocalPrivateKey(){const t=this.options.localPrivateKey;return gb("function"==typeof t?await t():t)}async executeWithSn(t){const e=this.options.snClient;if(!e)throw new pb("SN_CLIENT_UNAVAILABLE","sn-proxy",`SN client is required for BNS operation ${t.type}`);const n="publish_dns_txt"===t.type?await e.publishDnsTxt(t.request):await e.publishDocument(t.request);return{route:"sn-proxy",operation:t.type,response:n}}async executeLocally(t,e,n){const r=this.options.bnsClient;if(!r)throw new pb("BNS_CLIENT_UNAVAILABLE","local",`BNS client is required for local operation ${t.type}`);const s=this.evmTxBuilder;if(!n||!s)throw new pb("LOCAL_SIGNING_UNAVAILABLE","local",`Local signing configuration is unavailable for operation ${t.type}`);return this.enqueueLocalExecution((async()=>{try{const e=await s.buildAndSign(t,n),i=await r.submitRawTx(e);return{route:"local",operation:t.type,response:i}}catch(e){throw s.resetNonce(),e}}))}enqueueLocalExecution(t){const e=this.localExecutionTail.then(t,t);return this.localExecutionTail=e.then((()=>{}),(()=>{})),e}},exports.BnsTxExecutorError=pb,exports.BuckyOSSDK=Oi,exports.DEFAULT_CHILD_CONTROL_POLICY={follow_pause:!0,follow_resume:!0,follow_cancel:!0},exports.DOWNLOAD_TASK_SCHEMA_ID="download/v1",exports.HUMAN_APPROVAL_SCHEMA_ID="human.approval/v1",exports.HUMAN_INPUT_TASK_SCHEMA_ID="human.input/v1",exports.KEventClient=gi,exports.KEventReader=ui,exports.MsgCenterClient=fs,exports.MsgQueueClient=as,exports.OPENDAN_ASYNC_TOOL_TASK_SCHEMA_ID="opendan.async_tool/v1",exports.OPENDAN_COMMAND_TASK_SCHEMA_ID="opendan.command/v1",exports.RAW_TASK_SCHEMA_ID="raw/v1",exports.RepoClient=As,exports.RuntimeType=Ds,exports.SCHEDULER_DISPATCH_THUNK_TASK_SCHEMA_ID="scheduler.dispatch_thunk/v1",exports.StorageDomain=mr,exports.SystemConfigClient=Ur,exports.TASK_ERR_ALREADY_COMPLETED=tr,exports.TASK_ERR_CONTROL_ALREADY_PENDING=Xn,exports.TASK_ERR_CONTROL_NOT_AVAILABLE=Zn,exports.TASK_ERR_IDEMPOTENCY_CONFLICT=rr,exports.TASK_ERR_INPUT_SCHEMA_MISMATCH=er,exports.TASK_ERR_INVALID_PHASE=Yn,exports.TASK_ERR_NOT_FOUND=qn,exports.TASK_ERR_PERMISSION_DENIED=$n,exports.TASK_ERR_RESULT_SCHEMA_MISMATCH=nr,exports.TASK_ERR_REVISION_CONFLICT=Qn,exports.TASK_ERR_SCHEMA_NOT_FOUND=sr,exports.TASK_ERR_STALE_RUNNER_EPOCH=Jn,exports.TASK_MANAGER_SERVICE_NAME="task-manager",exports.TASK_MANAGER_SERVICE_PORT=3380,exports.TASK_MANAGER_SERVICE_UNIQUE_ID="task-manager",exports.TASK_MGR_ERROR_CODES=ir,exports.TASK_POLICY_PRESET_COLLABORATIVE_TREE_V1="collaborative-tree/v1",exports.TOOL_EXEC_BASH_TASK_SCHEMA_ID="tool.exec_bash/v1",exports.TaskAction=fr,exports.TaskControlAction=dr,exports.TaskDataScope=gr,exports.TaskEventType=yr,exports.TaskExecutorKind=ar,exports.TaskGrantScope=pr,exports.TaskManagerClient=_r,exports.TaskOutcome=hr,exports.TaskPhase=cr,exports.TaskWaitReasonKind=ur,exports.VerifyHubClient=zn,exports.WEB3_BRIDGE_HOST="web3.buckyos.ai",exports.WORKFLOW_EXECUTE_RPC_TASK_SCHEMA_ID="workflow.execute_rpc/v1",exports.WORKFLOW_MAP_SHARD_TASK_SCHEMA_ID="workflow.map_shard/v1",exports.WORKFLOW_RUN_TARGET_TASK_SCHEMA_ID="workflow.run/v1",exports.WORKFLOW_RUN_TREE_TASK_SCHEMA_ID="workflow.run_tree/v1",exports.WORKFLOW_SCHEDULE_TASK_SCHEMA_ID="workflow.schedule/v1",exports.WORKFLOW_SEND_MESSAGE_TASK_SCHEMA_ID="workflow.send_message/v1",exports.WORKFLOW_SERVICE_NAME="workflow",exports.WORKFLOW_STEP_TASK_SCHEMA_ID="workflow.step/v1",exports.WORKFLOW_THUNK_TASK_SCHEMA_ID="workflow.thunk/v1",exports.WorkflowClient=Dr,exports.WorkflowDefinitionStatus=Tr,exports.WorkflowHumanActionKind=Or,exports.WorkflowJoinMode=kr,exports.WorkflowNodeRunState=Ir,exports.WorkflowOutputMode=Er,exports.WorkflowRetryFallback=Sr,exports.WorkflowRunStatus=Rr,exports.WorkflowScheduledTaskFireStatus=xr,exports.WorkflowScheduledTaskMisfirePolicy=Nr,exports.WorkflowScheduledTaskStatus=Cr,exports.WorkflowStepType=vr,exports.aiccMessageFirstText=function(t){var e;return null==(e=t.content.find((t=>"text"===t.type)))?void 0:e.text},exports.aiccMessageTextContent=function(t){return t.content.filter((t=>"text"===t.type)).map((t=>t.text)).join("\n")},exports.aiccTextMessage=function(t,e){return{role:t,content:[{type:"text",text:e}]}},exports.appDidFromId=function(t){return Mn.DID.fromStr(ks(t)).toString()},exports.appIdFromDid=Es,exports.baselineTaskControlProfile=function(t){return{pause:{kind:"Unavailable"},resume:{kind:"Unavailable"},cancel:{kind:"Interrupt"},updated_at:t}},exports.bns_client=Mo,exports.createAppInstanceId=Ts,exports.createSDKModule=function(t){const e=new Oi(t),n={initBuckyOS:e.initBuckyOS.bind(e),getBuckyOSConfig:e.getBuckyOSConfig.bind(e),getRuntimeType:e.getRuntimeType.bind(e),getAppId:e.getAppId.bind(e),getAppDid:e.getAppDid.bind(e),getAppInstanceId:e.getAppInstanceId.bind(e),getAppDataDir:e.getAppDataDir.bind(e),getKEventClient:e.getKEventClient.bind(e),createEventReader:e.createEventReader.bind(e),create_event_reader:e.create_event_reader.bind(e),subscribeKEvent:e.subscribeKEvent.bind(e),attachEvent:e.attachEvent.bind(e),removeEvent:e.removeEvent.bind(e),getAccountInfo:e.getAccountInfo.bind(e),loginByPassword:e.loginByPassword.bind(e),loginByBrowserSSO:e.loginByBrowserSSO.bind(e),loginByRuntimeSession:e.loginByRuntimeSession.bind(e),login:e.login.bind(e),logout:e.logout.bind(e),getAppSetting:e.getAppSetting.bind(e),setAppSetting:e.setAppSetting.bind(e),getCurrentWalletUser:e.getCurrentWalletUser.bind(e),resolve_did:e.resolve_did.bind(e),walletSignWithActiveDid:e.walletSignWithActiveDid.bind(e),openExternalUrl:e.openExternalUrl.bind(e),getZoneHostName:e.getZoneHostName.bind(e),getZoneServiceURL:e.getZoneServiceURL.bind(e),getServiceRpcClient:e.getServiceRpcClient.bind(e),getVerifyHubClient:e.getVerifyHubClient.bind(e),getSystemConfigClient:e.getSystemConfigClient.bind(e),getTaskManagerClient:e.getTaskManagerClient.bind(e),getWorkflowClient:e.getWorkflowClient.bind(e),getAiccClient:e.getAiccClient.bind(e),getMsgQueueClient:e.getMsgQueueClient.bind(e),getMsgCenterClient:e.getMsgCenterClient.bind(e),getRepoClient:e.getRepoClient.bind(e)};return{...n,buckyos:{kRPCClient:jn,AuthClient:Vn,...n,hashPassword:Mn.hashPassword}}},exports.decisionRequirements=ts,exports.decodeBnsPublishDocumentCalldata=function(t){return ob.decodeFunctionData("publishDocument",t)},exports.getActiveRuntimeType=Ti,exports.getActiveSessionToken=Ii,exports.getActiveZoneGatewayOrigin=Ri,exports.getCurrentWalletUserFromHost=wi,exports.isAiccAiMethod=function(t){return Hr.has(t)},exports.isTerminalTaskPhase=lr,exports.ndm_client=t_,exports.ndm_proxy=Q_,exports.parseAppId=ks,exports.parseAppInstanceId=Rs,exports.parseSessionTokenClaims=Hs,exports.resolveDidFromHost=bi,exports.sn_client=SA,exports.taskMgrErrorCode=or,exports.taskMgrTaskEventPath=function(t){return`/task_mgr/${t}`},exports.taskMgrTreeEventPath=function(t){return`/task_mgr/tree/${t}`},exports.validateAiccMessage=Vr,exports.validateDecisionAnswers=ns,exports.validateDecisionRequest=es,exports.walletUserHasSnAccount=yb;
13
- //# sourceMappingURL=ndm_proxy-357b2a64.js.map
11
+ const _h=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),vh=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Eh=BigInt(1),kh=BigInt(2),Sh=(t,e)=>(t+e/kh)/e;const Th=function(t,e,n=!1,r={}){if(t<=qu)throw new Error(`Expected Field ORDER > 0, got ${t}`);const{nBitLength:s,nByteLength:i}=oh(t,e);if(i>2048)throw new Error("Field lengths over 2048 bytes are not supported");const o=sh(t),a=Object.freeze({ORDER:t,BITS:s,BYTES:i,MASK:Gu(s),ZERO:qu,ONE:$u,create:e=>th(e,t),isValid:e=>{if("bigint"!=typeof e)throw new Error("Invalid field element: expected bigint, got "+typeof e);return qu<=e&&e<t},is0:t=>t===qu,isOdd:t=>(t&$u)===$u,neg:e=>th(-e,t),eql:(t,e)=>t===e,sqr:e=>th(e*e,t),add:(e,n)=>th(e+n,t),sub:(e,n)=>th(e-n,t),mul:(e,n)=>th(e*n,t),pow:(t,e)=>function(t,e,n){if(n<qu)throw new Error("Expected power > 0");if(n===qu)return t.ONE;if(n===$u)return e;let r=t.ONE,s=e;for(;n>qu;)n&$u&&(r=t.mul(r,s)),s=t.sqr(s),n>>=$u;return r}(a,t,e),div:(e,n)=>th(e*rh(n,t),t),sqrN:t=>t*t,addN:(t,e)=>t+e,subN:(t,e)=>t-e,mulN:(t,e)=>t*e,inv:e=>rh(e,t),sqrt:r.sqrt||(t=>o(a,t)),invertBatch:t=>function(t,e){const n=new Array(e.length),r=e.reduce(((e,r,s)=>t.is0(r)?e:(n[s]=e,t.mul(e,r))),t.ONE),s=t.inv(r);return e.reduceRight(((e,r,s)=>t.is0(r)?e:(n[s]=t.mul(e,n[s]),t.mul(e,r))),s),n}(a,t),cmov:(t,e,n)=>n?e:t,toBytes:t=>n?Lu(t,i):Uu(t,i),fromBytes:t=>{if(t.length!==i)throw new Error(`Fp.fromBytes: expected ${i}, got ${t.length}`);return n?Bu(t):Du(t)}});return Object.freeze(a)}(_h,void 0,void 0,{sqrt:function(t){const e=_h,n=BigInt(3),r=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,u=l*l*t%e,h=nh(u,n,e)*u%e,d=nh(h,n,e)*u%e,f=nh(d,kh,e)*l%e,p=nh(f,s,e)*f%e,g=nh(p,i,e)*p%e,m=nh(g,a,e)*g%e,y=nh(m,c,e)*m%e,w=nh(y,a,e)*g%e,b=nh(w,n,e)*u%e,A=nh(b,o,e)*p%e,_=nh(A,r,e)*l%e,v=nh(_,kh,e);if(!Th.eql(Th.sqr(v),t))throw new Error("Cannot find square root");return v}}),Rh=function(t,e){const n=e=>bh({...t,...Ah(e)});return Object.freeze({...n(e),create:n})}({a:BigInt(0),b:BigInt(7),Fp:Th,n:vh,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=vh,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-Eh*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=n,o=BigInt("0x100000000000000000000000000000000"),a=Sh(i*t,e),c=Sh(-r*t,e);let l=th(t-a*n-c*s,e),u=th(-a*r-c*i,e);const h=l>o,d=u>o;if(h&&(l=e-l),d&&(u=e-u),l>o||u>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:h,k1:l,k2neg:d,k2:u}}}},Qc);BigInt(0),Rh.ProjectivePoint;const Ih="0x0000000000000000000000000000000000000000",Oh="0x0000000000000000000000000000000000000000000000000000000000000000",Ch=BigInt(0),xh=BigInt(1),Nh=BigInt(2),Ph=BigInt(27),Dh=BigInt(28),Bh=BigInt(35),Uh=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Lh=Uh/Nh,Mh=Symbol.for("nodejs.util.inspect.custom"),Fh={};function Gh(t){return ua(Ea(t),32)}G=new WeakMap,j=new WeakMap,H=new WeakMap,V=new WeakMap;let jh=class t{constructor(t,e,n,r){Dn(this,G,void 0),Dn(this,j,void 0),Dn(this,H,void 0),Dn(this,V,void 0),Zo(t,Fh,"Signature"),Bn(this,G,e),Bn(this,j,n),Bn(this,H,r),Bn(this,V,null)}get r(){return Pn(this,G)}set r(t){$o(32===aa(t),"invalid r","value",t),Bn(this,G,ia(t))}get s(){return $o(parseInt(Pn(this,j).substring(0,3))<8,"non-canonical s; use ._s","s",Pn(this,j)),Pn(this,j)}set s(t){$o(32===aa(t),"invalid s","value",t),Bn(this,j,ia(t))}get _s(){return Pn(this,j)}isValid(){return BigInt(Pn(this,j))<=Lh}get v(){return Pn(this,H)}set v(t){const e=_a(t,"value");$o(27===e||28===e,"invalid v","v",t),Bn(this,H,e)}get networkV(){return Pn(this,V)}get legacyChainId(){const e=this.networkV;return null==e?null:t.getChainId(e)}get yParity(){return 27===this.v?0:1}get yParityAndS(){const t=ta(this.s);return this.yParity&&(t[0]|=128),ia(t)}get compactSerialized(){return oa([this.r,this.yParityAndS])}get serialized(){return oa([this.r,this.s,this.yParity?"0x1c":"0x1b"])}getCanonical(){if(this.isValid())return this;const e=Uh-BigInt(this._s),n=55-this.v,r=new t(Fh,this.r,Gh(e),n);return this.networkV&&Bn(r,V,this.networkV),r}clone(){const e=new t(Fh,this.r,this._s,this.v);return this.networkV&&Bn(e,V,this.networkV),e}toJSON(){const t=this.networkV;return{_type:"signature",networkV:null!=t?t.toString():null,r:this.r,s:this._s,v:this.v}}[Mh](){return this.toString()}toString(){return this.isValid()?`Signature { r: ${this.r}, s: ${this._s}, v: ${this.v} }`:`Signature { r: ${this.r}, s: ${this._s}, v: ${this.v}, valid: false }`}static getChainId(t){const e=ya(t,"v");return e==Ph||e==Dh?Ch:($o(e>=Bh,"invalid EIP-155 v","v",t),(e-Bh)/Nh)}static getChainIdV(t,e){return ya(t)*Nh+BigInt(35+e-27)}static getNormalizedV(t){const e=ya(t);return e===Ch||e===Ph?27:e===xh||e===Dh?28:($o(e>=Bh,"invalid v","v",t),e&xh?27:28)}static from(e){function n(t,n){$o(t,n,"signature",e)}if(null==e)return new t(Fh,Oh,Oh,27);if("string"==typeof e){const r=ta(e,"signature");if(64===r.length){const e=ia(r.slice(0,32)),n=r.slice(32,64),s=128&n[0]?28:27;return n[0]&=127,new t(Fh,e,ia(n),s)}if(65===r.length){const e=ia(r.slice(0,32)),n=ia(r.slice(32,64)),s=t.getNormalizedV(r[64]);return new t(Fh,e,n,s)}n(!1,"invalid raw signature length")}if(e instanceof t)return e.clone();const r=e.r;n(null!=r,"missing r");const s=Gh(r),i=function(t,e){if(null!=t)return Gh(t);if(null!=e){n(na(e,32),"invalid yParityAndS");const t=ta(e);return t[0]&=127,ia(t)}n(!1,"missing s")}(e.s,e.yParityAndS),{networkV:o,v:a}=function(e,r,s){if(null!=e){const n=ya(e);return{networkV:n>=Bh?n:void 0,v:t.getNormalizedV(n)}}if(null!=r)return n(na(r,32),"invalid yParityAndS"),{v:128&ta(r)[0]?28:27};if(null!=s){switch(_a(s,"sig.yParity")){case 0:return{v:27};case 1:return{v:28}}n(!1,"invalid yParity")}n(!1,"missing v")}(e.v,e.yParityAndS,e.yParity),c=new t(Fh,s,i,a);return o&&Bn(c,V,o),n(null==e.yParity||_a(e.yParity,"sig.yParity")===c.yParity,"yParity mismatch"),n(null==e.yParityAndS||e.yParityAndS===c.yParityAndS,"yParityAndS mismatch"),c}};W=new WeakMap;let Hh=class t{constructor(t){Dn(this,W,void 0),$o(32===aa(t),"invalid private key","privateKey","[REDACTED]"),Bn(this,W,ia(t))}get privateKey(){return Pn(this,W)}get publicKey(){return t.computePublicKey(Pn(this,W))}get compressedPublicKey(){return t.computePublicKey(Pn(this,W),!0)}sign(t){$o(32===aa(t),"invalid digest length","digest",t);const e=Rh.sign(ea(t),ea(Pn(this,W)),{lowS:!0});return jh.from({r:va(e.r,32),s:va(e.s,32),v:e.recovery?28:27})}computeSharedSecret(e){const n=t.computePublicKey(e);return ia(Rh.getSharedSecret(ea(Pn(this,W)),ta(n),!1))}static computePublicKey(t,e){let n=ta(t,"key");if(32===n.length){return ia(Rh.getPublicKey(n,!!e))}if(64===n.length){const t=new Uint8Array(65);t[0]=4,t.set(n,1),n=t}return ia(Rh.ProjectivePoint.fromHex(n).toRawBytes(e))}static recoverPublicKey(t,e){$o(32===aa(t),"invalid digest length","digest",t);const n=jh.from(e);let r=Rh.Signature.fromCompact(ea(oa([n.r,n.s])));r=r.addRecoveryBit(n.yParity);const s=r.recoverPublicKey(ea(t));return $o(null!=s,"invalid signature for digest","signature",e),"0x"+s.toHex(!1)}static addPoints(e,n,r){const s=Rh.ProjectivePoint.fromHex(t.computePublicKey(e).substring(2)),i=Rh.ProjectivePoint.fromHex(t.computePublicKey(n).substring(2));return"0x"+s.add(i).toHex(!!r)}};const Vh=BigInt(0),Wh=BigInt(36);function Kh(t){const e=(t=t.toLowerCase()).substring(2).split(""),n=new Uint8Array(40);for(let s=0;s<40;s++)n[s]=e[s].charCodeAt(0);const r=ta(Bl(n));for(let s=0;s<40;s+=2)r[s>>1]>>4>=8&&(e[s]=e[s].toUpperCase()),(15&r[s>>1])>=8&&(e[s+1]=e[s+1].toUpperCase());return"0x"+e.join("")}const zh={};for(let J_=0;J_<10;J_++)zh[String(J_)]=String(J_);for(let J_=0;J_<26;J_++)zh[String.fromCharCode(65+J_)]=String(10+J_);const qh=function(){const t={};for(let e=0;e<36;e++){t["0123456789abcdefghijklmnopqrstuvwxyz"[e]]=BigInt(e)}return t}();function $h(t){if($o("string"==typeof t,"invalid address","address",t),t.match(/^(0x)?[0-9a-fA-F]{40}$/)){t.startsWith("0x")||(t="0x"+t);const e=Kh(t);return $o(!t.match(/([A-F].*[a-f])|([a-f].*[A-F])/)||e===t,"bad address checksum","address",t),e}if(t.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){$o(t.substring(2,4)===function(t){let e=(t=(t=t.toUpperCase()).substring(4)+t.substring(0,2)+"00").split("").map((t=>zh[t])).join("");for(;e.length>=15;){let t=e.substring(0,15);e=parseInt(t,10)%97+e.substring(t.length)}let n=String(98-parseInt(e,10)%97);for(;n.length<2;)n="0"+n;return n}(t),"bad icap checksum","address",t);let e=function(t){t=t.toLowerCase();let e=Vh;for(let n=0;n<t.length;n++)e=e*Wh+qh[t[n]];return e}(t.substring(4)).toString(16);for(;e.length<40;)e="0"+e;return Kh("0x"+e)}$o(!1,"invalid address","address",t)}function Qh(t){return t&&"function"==typeof t.getAddress}async function Jh(t,e){const n=await e;return null!=n&&"0x0000000000000000000000000000000000000000"!==n||(qo("string"!=typeof t,"unconfigured name","UNCONFIGURED_NAME",{value:t}),$o(!1,"invalid AddressLike value; did not resolve to a value address","target",t)),$h(n)}function Yh(t,e){return"string"==typeof t?t.match(/^0x[0-9a-f]{40}$/i)?$h(t):(qo(null!=e,"ENS resolution requires a provider","UNSUPPORTED_OPERATION",{operation:"resolveName"}),Jh(t,e.resolveName(t))):Qh(t)?Jh(t,t.getAddress()):t&&"function"==typeof t.then?Jh(t,t):void $o(!1,"unsupported addressable value","target",t)}const Zh={};function Xh(t,e){let n=!1;return e<0&&(n=!0,e*=-1),new nd(Zh,`${n?"":"u"}int${e}`,t,{signed:n,width:e})}function td(t,e){return new nd(Zh,`bytes${e||""}`,t,{size:e})}const ed=Symbol.for("_ethers_typed");K=new WeakMap;let nd=class t{constructor(t,e,n,r){xn(this,"type"),xn(this,"value"),Dn(this,K,void 0),xn(this,"_typedSymbol"),null==r&&(r=null),Zo(Zh,t,"Typed"),Ho(this,{_typedSymbol:ed,type:e,value:n}),Bn(this,K,r),this.format()}format(){if("array"===this.type)throw new Error("");if("dynamicArray"===this.type)throw new Error("");return"tuple"===this.type?`tuple(${this.value.map((t=>t.format())).join(",")})`:this.type}defaultValue(){return 0}minValue(){return 0}maxValue(){return 0}isBigInt(){return!!this.type.match(/^u?int[0-9]+$/)}isData(){return this.type.startsWith("bytes")}isString(){return"string"===this.type}get tupleName(){if("tuple"!==this.type)throw TypeError("not a tuple");return Pn(this,K)}get arrayLength(){if("array"!==this.type)throw TypeError("not an array");return!0===Pn(this,K)?-1:!1===Pn(this,K)?this.value.length:null}static from(e,n){return new t(Zh,e,n)}static uint8(t){return Xh(t,8)}static uint16(t){return Xh(t,16)}static uint24(t){return Xh(t,24)}static uint32(t){return Xh(t,32)}static uint40(t){return Xh(t,40)}static uint48(t){return Xh(t,48)}static uint56(t){return Xh(t,56)}static uint64(t){return Xh(t,64)}static uint72(t){return Xh(t,72)}static uint80(t){return Xh(t,80)}static uint88(t){return Xh(t,88)}static uint96(t){return Xh(t,96)}static uint104(t){return Xh(t,104)}static uint112(t){return Xh(t,112)}static uint120(t){return Xh(t,120)}static uint128(t){return Xh(t,128)}static uint136(t){return Xh(t,136)}static uint144(t){return Xh(t,144)}static uint152(t){return Xh(t,152)}static uint160(t){return Xh(t,160)}static uint168(t){return Xh(t,168)}static uint176(t){return Xh(t,176)}static uint184(t){return Xh(t,184)}static uint192(t){return Xh(t,192)}static uint200(t){return Xh(t,200)}static uint208(t){return Xh(t,208)}static uint216(t){return Xh(t,216)}static uint224(t){return Xh(t,224)}static uint232(t){return Xh(t,232)}static uint240(t){return Xh(t,240)}static uint248(t){return Xh(t,248)}static uint256(t){return Xh(t,256)}static uint(t){return Xh(t,256)}static int8(t){return Xh(t,-8)}static int16(t){return Xh(t,-16)}static int24(t){return Xh(t,-24)}static int32(t){return Xh(t,-32)}static int40(t){return Xh(t,-40)}static int48(t){return Xh(t,-48)}static int56(t){return Xh(t,-56)}static int64(t){return Xh(t,-64)}static int72(t){return Xh(t,-72)}static int80(t){return Xh(t,-80)}static int88(t){return Xh(t,-88)}static int96(t){return Xh(t,-96)}static int104(t){return Xh(t,-104)}static int112(t){return Xh(t,-112)}static int120(t){return Xh(t,-120)}static int128(t){return Xh(t,-128)}static int136(t){return Xh(t,-136)}static int144(t){return Xh(t,-144)}static int152(t){return Xh(t,-152)}static int160(t){return Xh(t,-160)}static int168(t){return Xh(t,-168)}static int176(t){return Xh(t,-176)}static int184(t){return Xh(t,-184)}static int192(t){return Xh(t,-192)}static int200(t){return Xh(t,-200)}static int208(t){return Xh(t,-208)}static int216(t){return Xh(t,-216)}static int224(t){return Xh(t,-224)}static int232(t){return Xh(t,-232)}static int240(t){return Xh(t,-240)}static int248(t){return Xh(t,-248)}static int256(t){return Xh(t,-256)}static int(t){return Xh(t,-256)}static bytes1(t){return td(t,1)}static bytes2(t){return td(t,2)}static bytes3(t){return td(t,3)}static bytes4(t){return td(t,4)}static bytes5(t){return td(t,5)}static bytes6(t){return td(t,6)}static bytes7(t){return td(t,7)}static bytes8(t){return td(t,8)}static bytes9(t){return td(t,9)}static bytes10(t){return td(t,10)}static bytes11(t){return td(t,11)}static bytes12(t){return td(t,12)}static bytes13(t){return td(t,13)}static bytes14(t){return td(t,14)}static bytes15(t){return td(t,15)}static bytes16(t){return td(t,16)}static bytes17(t){return td(t,17)}static bytes18(t){return td(t,18)}static bytes19(t){return td(t,19)}static bytes20(t){return td(t,20)}static bytes21(t){return td(t,21)}static bytes22(t){return td(t,22)}static bytes23(t){return td(t,23)}static bytes24(t){return td(t,24)}static bytes25(t){return td(t,25)}static bytes26(t){return td(t,26)}static bytes27(t){return td(t,27)}static bytes28(t){return td(t,28)}static bytes29(t){return td(t,29)}static bytes30(t){return td(t,30)}static bytes31(t){return td(t,31)}static bytes32(t){return td(t,32)}static address(e){return new t(Zh,"address",e)}static bool(e){return new t(Zh,"bool",!!e)}static bytes(e){return new t(Zh,"bytes",e)}static string(e){return new t(Zh,"string",e)}static array(t,e){throw new Error("not implemented yet")}static tuple(t,e){throw new Error("not implemented yet")}static overrides(e){return new t(Zh,"overrides",Object.assign({},e))}static isTyped(t){return t&&"object"==typeof t&&"_typedSymbol"in t&&t._typedSymbol===ed}static dereference(e,n){if(t.isTyped(e)){if(e.type!==n)throw new Error(`invalid type: expecetd ${n}, got ${e.type}`);return e.value}return e}};class rd extends bc{constructor(t){super("address","address",t,!1)}defaultValue(){return"0x0000000000000000000000000000000000000000"}encode(t,e){let n=nd.dereference(e,"string");try{n=$h(n)}catch(r){return this._throwError(r.message,e)}return t.writeValue(n)}decode(t){return $h(va(t.readValue(),20))}}class sd extends bc{constructor(t){super(t.name,t.type,"_",t.dynamic),xn(this,"coder"),this.coder=t}defaultValue(){return this.coder.defaultValue()}encode(t,e){return this.coder.encode(t,e)}decode(t){return this.coder.decode(t)}}function id(t,e,n){let r=[];if(Array.isArray(n))r=n;else if(n&&"object"==typeof n){let t={};r=e.map((e=>{const r=e.localName;return qo(r,"cannot encode object for signature with missing names","INVALID_ARGUMENT",{argument:"values",info:{coder:e},value:n}),qo(!t[r],"cannot encode object for signature with duplicate names","INVALID_ARGUMENT",{argument:"values",info:{coder:e},value:n}),t[r]=!0,n[r]}))}else $o(!1,"invalid tuple value","tuple",n);$o(e.length===r.length,"types/value length mismatch","tuple",n);let s=new Ac,i=new Ac,o=[];e.forEach(((t,e)=>{let n=r[e];if(t.dynamic){let e=i.length;t.encode(i,n);let r=s.writeUpdatableValue();o.push((t=>{r(t+e)}))}else t.encode(s,n)})),o.forEach((t=>{t(s.length)}));let a=t.appendWriter(s);return a+=t.appendWriter(i),a}function od(t,e){let n=[],r=[],s=t.subReader(0);return e.forEach((e=>{let i=null;if(e.dynamic){let n=t.readIndex(),r=s.subReader(n);try{i=e.decode(r)}catch(o){if(Wo(o,"BUFFER_OVERRUN"))throw o;i=o,i.baseType=e.name,i.name=e.localName,i.type=e.type}}else try{i=e.decode(t)}catch(o){if(Wo(o,"BUFFER_OVERRUN"))throw o;i=o,i.baseType=e.name,i.name=e.localName,i.type=e.type}if(null==i)throw new Error("investigate");n.push(i),r.push(e.localName||null)})),yc.fromItems(n,r)}class ad extends bc{constructor(t,e,n){super("array",t.type+"["+(e>=0?e:"")+"]",n,-1===e||t.dynamic),xn(this,"coder"),xn(this,"length"),Ho(this,{coder:t,length:e})}defaultValue(){const t=this.coder.defaultValue(),e=[];for(let n=0;n<this.length;n++)e.push(t);return e}encode(t,e){const n=nd.dereference(e,"array");Array.isArray(n)||this._throwError("expected array value",n);let r=this.length;-1===r&&(r=n.length,t.writeValue(n.length)),Qo(n.length,r,"coder array"+(this.localName?" "+this.localName:""));let s=[];for(let i=0;i<n.length;i++)s.push(this.coder);return id(t,s,n)}decode(t){let e=this.length;-1===e&&(e=t.readIndex(),qo(e*cc<=t.dataLength,"insufficient data length","BUFFER_OVERRUN",{buffer:t.bytes,offset:e*cc,length:t.dataLength}));let n=[];for(let r=0;r<e;r++)n.push(new sd(this.coder));return od(t,n)}}class cd extends bc{constructor(t){super("bool","bool",t,!1)}defaultValue(){return!1}encode(t,e){const n=nd.dereference(e,"bool");return t.writeValue(n?1:0)}decode(t){return!!t.readValue()}}class ld extends bc{constructor(t,e){super(t,t,e,!0)}defaultValue(){return"0x"}encode(t,e){e=ea(e);let n=t.writeValue(e.length);return n+=t.writeBytes(e),n}decode(t){return t.readBytes(t.readIndex(),!0)}}class ud extends ld{constructor(t){super("bytes",t)}decode(t){return ia(super.decode(t))}}class hd extends bc{constructor(t,e){let n="bytes"+String(t);super(n,n,e,!1),xn(this,"size"),Ho(this,{size:t},{size:"number"})}defaultValue(){return"0x0000000000000000000000000000000000000000000000000000000000000000".substring(0,2+2*this.size)}encode(t,e){let n=ea(nd.dereference(e,this.type));return n.length!==this.size&&this._throwError("incorrect data length",e),t.writeBytes(n)}decode(t){return ia(t.readBytes(this.size))}}const dd=new Uint8Array([]);class fd extends bc{constructor(t){super("null","",t,!1)}defaultValue(){return null}encode(t,e){return null!=e&&this._throwError("not null",e),t.writeBytes(dd)}decode(t){return t.readBytes(0),null}}const pd=BigInt(0),gd=BigInt(1),md=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");class yd extends bc{constructor(t,e,n){const r=(e?"int":"uint")+8*t;super(r,r,n,!1),xn(this,"size"),xn(this,"signed"),Ho(this,{size:t,signed:e},{size:"number",signed:"boolean"})}defaultValue(){return 0}encode(t,e){let n=ya(nd.dereference(e,this.type)),r=ma(md,256);if(this.signed){let t=ma(r,8*this.size-1);(n>t||n<-(t+gd))&&this._throwError("value out-of-bounds",e),n=ga(n,256)}else(n<pd||n>ma(r,8*this.size))&&this._throwError("value out-of-bounds",e);return t.writeValue(n)}decode(t){let e=ma(t.readValue(),8*this.size);return this.signed&&(e=function(t,e){const n=wa(t,"value"),r=BigInt(_a(e,"width"));if(qo(n>>r===da,"overflow","NUMERIC_FAULT",{operation:"fromTwos",fault:"overflow",value:t}),n>>r-fa)return-((~n&(fa<<r)-fa)+fa);return n}(e,8*this.size)),e}}class wd extends ld{constructor(t){super("string",t)}defaultValue(){return""}encode(t,e){return super.encode(t,Da(nd.dereference(e,"string")))}decode(t){return Ba(super.decode(t))}}class bd extends bc{constructor(t,e){let n=!1;const r=[];t.forEach((t=>{t.dynamic&&(n=!0),r.push(t.type)}));super("tuple","tuple("+r.join(",")+")",e,n),xn(this,"coders"),Ho(this,{coders:Object.freeze(t.slice())})}defaultValue(){const t=[];this.coders.forEach((e=>{t.push(e.defaultValue())}));const e=this.coders.reduce(((t,e)=>{const n=e.localName;return n&&(t[n]||(t[n]=0),t[n]++),t}),{});return this.coders.forEach(((n,r)=>{let s=n.localName;s&&1===e[s]&&("length"===s&&(s="_length"),null==t[s]&&(t[s]=t[r]))})),Object.freeze(t)}encode(t,e){const n=nd.dereference(e,"tuple");return id(t,this.coders,n)}decode(t){return od(t,this.coders)}}function Ad(t,e){return{address:$h(t),storageKeys:e.map(((t,e)=>($o(na(t,32),"invalid slot",`storageKeys[${e}]`,t),t.toLowerCase())))}}function _d(t){if(Array.isArray(t))return t.map(((e,n)=>Array.isArray(e)?($o(2===e.length,"invalid slot set",`value[${n}]`,e),Ad(e[0],e[1])):($o(null!=e&&"object"==typeof e,"invalid address-slot set","value",t),Ad(e.address,e.storageKeys))));$o(null!=t&&"object"==typeof t,"invalid access list","value",t);const e=Object.keys(t).map((e=>{const n=t[e].reduce(((t,e)=>(t[e]=!0,t)),{});return Ad(e,Object.keys(n).sort())}));return e.sort(((t,e)=>t.address.localeCompare(e.address))),e}function vd(t){return{address:$h(t.address),nonce:ya(null!=t.nonce?t.nonce:0),chainId:ya(null!=t.chainId?t.chainId:0),signature:jh.from(t.signature)}}function Ed(t){let e;return e="string"==typeof t?Hh.computePublicKey(t,!1):t.publicKey,$h(Bl("0x"+e.substring(4)).substring(26))}const kd=BigInt(0),Sd=BigInt(2),Td=BigInt(27),Rd=BigInt(28),Id=BigInt(35),Od=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Cd=Symbol.for("nodejs.util.inspect.custom"),xd=131072,Nd=128;function Pd(t,e){let n=t.toString(16);for(;n.length<2;)n="0"+n;return n+=ku(e).substring(4),"0x"+n}function Dd(t){return"0x"===t?null:$h(t)}function Bd(t,e){try{return _d(t)}catch(n){$o(!1,n.message,e,t)}}function Ud(t,e){try{if(!Array.isArray(t))throw new Error("authorizationList: invalid array");const e=[];for(let n=0;n<t.length;n++){const r=t[n];if(!Array.isArray(r))throw new Error(`authorization[${n}]: invalid array`);if(6!==r.length)throw new Error(`authorization[${n}]: wrong length`);if(!r[1])throw new Error(`authorization[${n}]: null address`);e.push({address:Dd(r[1]),nonce:Md(r[2],"nonce"),chainId:Md(r[0],"chainId"),signature:jh.from({yParity:Ld(r[3],"yParity"),r:ua(r[4],32),s:ua(r[5],32)})})}return e}catch(n){$o(!1,n.message,e,t)}}function Ld(t,e){return"0x"===t?0:_a(t,e)}function Md(t,e){if("0x"===t)return kd;const n=ya(t,e);return $o(n<=Od,"value exceeds uint size",e,n),n}function Fd(t,e){const n=ya(t,"value"),r=Ea(n);return $o(r.length<=32,"value too large",`tx.${e}`,n),r}function Gd(t){return _d(t).map((t=>[t.address,t.storageKeys]))}function jd(t,e){$o(Array.isArray(t),`invalid ${e}`,"value",t);for(let n=0;n<t.length;n++)$o(na(t[n],32),"invalid ${ param } hash",`value[${n}]`,t[n]);return t}function Hd(t,e){let n;try{if(n=Ld(e[0],"yParity"),0!==n&&1!==n)throw new Error("bad yParity")}catch(o){$o(!1,"invalid yParity","yParity",e[0])}const r=ua(e[1],32),s=ua(e[2],32),i=jh.from({r:r,s:s,yParity:n});t.signature=i}z=new WeakMap,q=new WeakMap,$=new WeakMap,Q=new WeakMap,J=new WeakMap,Y=new WeakMap,Z=new WeakMap,X=new WeakMap,tt=new WeakMap,et=new WeakMap,nt=new WeakMap,rt=new WeakMap,st=new WeakMap,it=new WeakMap,ot=new WeakMap,at=new WeakMap,ct=new WeakMap,lt=new WeakMap,ut=new WeakSet,ht=function(t,e){qo(!t||null!=this.signature,"cannot serialize unsigned transaction; maybe you meant .unsignedSerialized","UNSUPPORTED_OPERATION",{operation:".serialized"});const n=t?this.signature:null;switch(this.inferType()){case 0:return function(t,e){const n=[Fd(t.nonce,"nonce"),Fd(t.gasPrice||0,"gasPrice"),Fd(t.gasLimit,"gasLimit"),t.to||"0x",Fd(t.value,"value"),t.data];let r=kd;if(t.chainId!=kd)r=ya(t.chainId,"tx.chainId"),$o(!e||null==e.networkV||e.legacyChainId===r,"tx.chainId/sig.v mismatch","sig",e);else if(t.signature){const e=t.signature.legacyChainId;null!=e&&(r=e)}if(!e)return r!==kd&&(n.push(Ea(r)),n.push("0x"),n.push("0x")),oc(n);let s=BigInt(27+e.yParity);return r!==kd?s=jh.getChainIdV(r,e.v):BigInt(e.v)!==s&&$o(!1,"tx.chainId/sig.v mismatch","sig",e),n.push(Ea(s)),n.push(Ea(e.r)),n.push(Ea(e._s)),oc(n)}(this,n);case 1:return function(t,e){const n=[Fd(t.chainId,"chainId"),Fd(t.nonce,"nonce"),Fd(t.gasPrice||0,"gasPrice"),Fd(t.gasLimit,"gasLimit"),t.to||"0x",Fd(t.value,"value"),t.data,Gd(t.accessList||[])];return e&&(n.push(Fd(e.yParity,"recoveryParam")),n.push(Ea(e.r)),n.push(Ea(e.s))),oa(["0x01",oc(n)])}(this,n);case 2:return function(t,e){const n=[Fd(t.chainId,"chainId"),Fd(t.nonce,"nonce"),Fd(t.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),Fd(t.maxFeePerGas||0,"maxFeePerGas"),Fd(t.gasLimit,"gasLimit"),t.to||"0x",Fd(t.value,"value"),t.data,Gd(t.accessList||[])];return e&&(n.push(Fd(e.yParity,"yParity")),n.push(Ea(e.r)),n.push(Ea(e.s))),oa(["0x02",oc(n)])}(this,n);case 3:return function(t,e,n){const r=[Fd(t.chainId,"chainId"),Fd(t.nonce,"nonce"),Fd(t.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),Fd(t.maxFeePerGas||0,"maxFeePerGas"),Fd(t.gasLimit,"gasLimit"),t.to||Ih,Fd(t.value,"value"),t.data,Gd(t.accessList||[]),Fd(t.maxFeePerBlobGas||0,"maxFeePerBlobGas"),jd(t.blobVersionedHashes||[],"blobVersionedHashes")];if(e&&(r.push(Fd(e.yParity,"yParity")),r.push(Ea(e.r)),r.push(Ea(e.s)),n)){if(null!=t.blobWrapperVersion){const e=Ea(t.blobWrapperVersion),s=[];for(const{proof:t}of n){const e=ta(t),n=e.length/Nd;for(let t=0;t<e.length;t+=n)s.push(e.subarray(t,t+n))}return oa(["0x03",oc([r,e,n.map((t=>t.data)),n.map((t=>t.commitment)),s])])}return oa(["0x03",oc([r,n.map((t=>t.data)),n.map((t=>t.commitment)),n.map((t=>t.proof))])])}return oa(["0x03",oc(r)])}(this,n,e?this.blobs:null);case 4:return function(t,e){const n=[Fd(t.chainId,"chainId"),Fd(t.nonce,"nonce"),Fd(t.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),Fd(t.maxFeePerGas||0,"maxFeePerGas"),Fd(t.gasLimit,"gasLimit"),t.to||"0x",Fd(t.value,"value"),t.data,Gd(t.accessList||[]),(r=t.authorizationList||[],r.map((t=>[Fd(t.chainId,"chainId"),t.address,Fd(t.nonce,"nonce"),Fd(t.signature.yParity,"yParity"),Ea(t.signature.r),Ea(t.signature._s)])))];var r;return e&&(n.push(Fd(e.yParity,"yParity")),n.push(Ea(e.r)),n.push(Ea(e.s))),oa(["0x04",oc(n)])}(this,n)}qo(!1,"unsupported transaction type","UNSUPPORTED_OPERATION",{operation:".serialized"})};let Vd=class t{constructor(){Dn(this,ut),Dn(this,z,void 0),Dn(this,q,void 0),Dn(this,$,void 0),Dn(this,Q,void 0),Dn(this,J,void 0),Dn(this,Y,void 0),Dn(this,Z,void 0),Dn(this,X,void 0),Dn(this,tt,void 0),Dn(this,et,void 0),Dn(this,nt,void 0),Dn(this,rt,void 0),Dn(this,st,void 0),Dn(this,it,void 0),Dn(this,ot,void 0),Dn(this,at,void 0),Dn(this,ct,void 0),Dn(this,lt,void 0),Bn(this,z,null),Bn(this,q,null),Bn(this,Q,0),Bn(this,J,kd),Bn(this,Y,null),Bn(this,Z,null),Bn(this,X,null),Bn(this,$,"0x"),Bn(this,tt,kd),Bn(this,et,kd),Bn(this,nt,null),Bn(this,rt,null),Bn(this,st,null),Bn(this,it,null),Bn(this,ot,null),Bn(this,at,null),Bn(this,ct,null),Bn(this,lt,null)}get type(){return Pn(this,z)}set type(t){switch(t){case null:Bn(this,z,null);break;case 0:case"legacy":Bn(this,z,0);break;case 1:case"berlin":case"eip-2930":Bn(this,z,1);break;case 2:case"london":case"eip-1559":Bn(this,z,2);break;case 3:case"cancun":case"eip-4844":Bn(this,z,3);break;case 4:case"pectra":case"eip-7702":Bn(this,z,4);break;default:$o(!1,"unsupported transaction type","type",t)}}get typeName(){switch(this.type){case 0:return"legacy";case 1:return"eip-2930";case 2:return"eip-1559";case 3:return"eip-4844";case 4:return"eip-7702"}return null}get to(){const t=Pn(this,q);return null==t&&3===this.type?Ih:t}set to(t){Bn(this,q,null==t?null:$h(t))}get nonce(){return Pn(this,Q)}set nonce(t){Bn(this,Q,_a(t,"value"))}get gasLimit(){return Pn(this,J)}set gasLimit(t){Bn(this,J,ya(t))}get gasPrice(){const t=Pn(this,Y);return null!=t||0!==this.type&&1!==this.type?t:kd}set gasPrice(t){Bn(this,Y,null==t?null:ya(t,"gasPrice"))}get maxPriorityFeePerGas(){const t=Pn(this,Z);return null==t?2===this.type||3===this.type?kd:null:t}set maxPriorityFeePerGas(t){Bn(this,Z,null==t?null:ya(t,"maxPriorityFeePerGas"))}get maxFeePerGas(){const t=Pn(this,X);return null==t?2===this.type||3===this.type?kd:null:t}set maxFeePerGas(t){Bn(this,X,null==t?null:ya(t,"maxFeePerGas"))}get data(){return Pn(this,$)}set data(t){Bn(this,$,ia(t))}get value(){return Pn(this,tt)}set value(t){Bn(this,tt,ya(t,"value"))}get chainId(){return Pn(this,et)}set chainId(t){Bn(this,et,ya(t))}get signature(){return Pn(this,nt)||null}set signature(t){Bn(this,nt,null==t?null:jh.from(t))}isValid(){const t=this.signature;if(t&&!t.isValid())return!1;const e=this.authorizationList;if(e)for(const n of e)if(!n.signature.isValid())return!1;return!0}get accessList(){const t=Pn(this,rt)||null;return null==t?1===this.type||2===this.type||3===this.type?[]:null:t}set accessList(t){Bn(this,rt,null==t?null:_d(t))}get authorizationList(){const t=Pn(this,ct)||null;return null==t&&4===this.type?[]:t}set authorizationList(t){Bn(this,ct,null==t?null:t.map((t=>vd(t))))}get maxFeePerBlobGas(){const t=Pn(this,st);return null==t&&3===this.type?kd:t}set maxFeePerBlobGas(t){Bn(this,st,null==t?null:ya(t,"maxFeePerBlobGas"))}get blobVersionedHashes(){let t=Pn(this,it);return null==t&&3===this.type?[]:t}set blobVersionedHashes(t){if(null!=t){$o(Array.isArray(t),"blobVersionedHashes must be an Array","value",t),t=t.slice();for(let e=0;e<t.length;e++)$o(na(t[e],32),"invalid blobVersionedHash",`value[${e}]`,t[e])}Bn(this,it,t)}get blobs(){return null==Pn(this,at)?null:Pn(this,at).map((t=>Object.assign({},t)))}set blobs(t){if(null==t)return void Bn(this,at,null);const e=[],n=[];for(let r=0;r<t.length;r++){const s=t[r];if(ra(s)){qo(Pn(this,ot),"adding a raw blob requires a KZG library","UNSUPPORTED_OPERATION",{operation:"set blobs()"});let t=ta(s);if($o(t.length<=xd,"blob is too large",`blobs[${r}]`,s),t.length!==xd){const e=new Uint8Array(xd);e.set(t),t=e}const i=Pn(this,ot).blobToKzgCommitment(t),o=ia(Pn(this,ot).computeBlobKzgProof(t,i));e.push({data:ia(t),commitment:ia(i),proof:o}),n.push(Pd(1,i))}else{const t=ia(s.data),r=ia(s.commitment),i=ia(s.proof);e.push({data:t,commitment:r,proof:i}),n.push(Pd(1,r))}}Bn(this,at,e),Bn(this,it,n)}get kzg(){return Pn(this,ot)}set kzg(t){Bn(this,ot,null==t?null:function(t){return{blobToKzgCommitment:e=>{if("computeBlobProof"in t){if("blobToKzgCommitment"in t&&"function"==typeof t.blobToKzgCommitment)return ta(t.blobToKzgCommitment(ia(e)))}else if("blobToKzgCommitment"in t&&"function"==typeof t.blobToKzgCommitment)return ta(t.blobToKzgCommitment(e));if("blobToKZGCommitment"in t&&"function"==typeof t.blobToKZGCommitment)return ta(t.blobToKZGCommitment(ia(e)));$o(!1,"unsupported KZG library","kzg",t)},computeBlobKzgProof:(e,n)=>"computeBlobProof"in t&&"function"==typeof t.computeBlobProof?ta(t.computeBlobProof(ia(e),ia(n))):"computeBlobKzgProof"in t&&"function"==typeof t.computeBlobKzgProof?t.computeBlobKzgProof(e,n):"computeBlobKZGProof"in t&&"function"==typeof t.computeBlobKZGProof?ta(t.computeBlobKZGProof(ia(e),ia(n))):void $o(!1,"unsupported KZG library","kzg",t)}}(t))}get blobWrapperVersion(){return Pn(this,lt)}set blobWrapperVersion(t){Bn(this,lt,t)}get hash(){return null==this.signature?null:Bl(Ln(this,ut,ht).call(this,!0,!1))}get unsignedHash(){return Bl(this.unsignedSerialized)}get from(){return null==this.signature?null:(t=this.unsignedHash,e=this.signature.getCanonical(),Ed(Hh.recoverPublicKey(t,e)));var t,e}get fromPublicKey(){return null==this.signature?null:Hh.recoverPublicKey(this.unsignedHash,this.signature.getCanonical())}isSigned(){return null!=this.signature}get serialized(){return Ln(this,ut,ht).call(this,!0,!0)}get unsignedSerialized(){return Ln(this,ut,ht).call(this,!1,!1)}inferType(){const t=this.inferTypes();return t.indexOf(2)>=0?2:t.pop()}inferTypes(){const t=null!=this.gasPrice,e=null!=this.maxFeePerGas||null!=this.maxPriorityFeePerGas,n=null!=this.accessList,r=null!=Pn(this,st)||Pn(this,it);null!=this.maxFeePerGas&&null!=this.maxPriorityFeePerGas&&qo(this.maxFeePerGas>=this.maxPriorityFeePerGas,"priorityFee cannot be more than maxFee","BAD_DATA",{value:this}),qo(!e||0!==this.type&&1!==this.type,"transaction type cannot have maxFeePerGas or maxPriorityFeePerGas","BAD_DATA",{value:this}),qo(0!==this.type||!n,"legacy transaction cannot have accessList","BAD_DATA",{value:this});const s=[];return null!=this.type?s.push(this.type):this.authorizationList&&this.authorizationList.length?s.push(4):e?s.push(2):t?(s.push(1),n||s.push(0)):n?(s.push(1),s.push(2)):(r&&this.to||(s.push(0),s.push(1),s.push(2)),s.push(3)),s.sort(),s}isLegacy(){return 0===this.type}isBerlin(){return 1===this.type}isLondon(){return 2===this.type}isCancun(){return 3===this.type}clone(){return t.from(this)}toJSON(){const t=t=>null==t?null:t.toString();return{type:this.type,to:this.to,data:this.data,nonce:this.nonce,gasLimit:t(this.gasLimit),gasPrice:t(this.gasPrice),maxPriorityFeePerGas:t(this.maxPriorityFeePerGas),maxFeePerGas:t(this.maxFeePerGas),value:t(this.value),chainId:t(this.chainId),sig:this.signature?this.signature.toJSON():null,accessList:this.accessList}}[Cd](){return this.toString()}toString(){const t=[],e=e=>{let n=this[e];"string"==typeof n&&(n=JSON.stringify(n)),t.push(`${e}: ${n}`)};this.type&&e("type"),e("to"),e("data"),e("nonce"),e("gasLimit"),e("value"),null!=this.chainId&&e("chainId"),this.signature&&(e("from"),t.push(`signature: ${this.signature.toString()}`));const n=this.authorizationList;if(n){const e=[];for(const t of n){const n=[];n.push(`address: ${JSON.stringify(t.address)}`),null!=t.nonce&&n.push(`nonce: ${t.nonce}`),null!=t.chainId&&n.push(`chainId: ${t.chainId}`),t.signature&&n.push(`signature: ${t.signature.toString()}`),e.push(`Authorization { ${n.join(", ")} }`)}t.push(`authorizations: [ ${e.join(", ")} ]`)}return`Transaction { ${t.join(", ")} }`}static from(e){if(null==e)return new t;if("string"==typeof e){const n=ta(e);if(n[0]>=127)return t.from(function(t){const e=nc(t);$o(Array.isArray(e)&&(9===e.length||6===e.length),"invalid field count for legacy transaction","data",t);const n={type:0,nonce:Ld(e[0],"nonce"),gasPrice:Md(e[1],"gasPrice"),gasLimit:Md(e[2],"gasLimit"),to:Dd(e[3]),value:Md(e[4],"value"),data:ia(e[5]),chainId:kd};if(6===e.length)return n;const r=Md(e[6],"v"),s=Md(e[7],"r"),i=Md(e[8],"s");if(s===kd&&i===kd)n.chainId=r;else{let t=(r-Id)/Sd;t<kd&&(t=kd),n.chainId=t,$o(t!==kd||r===Td||r===Rd,"non-canonical legacy v","v",e[6]),n.signature=jh.from({r:ua(e[7],32),s:ua(e[8],32),v:r})}return n}(n));switch(n[0]){case 1:return t.from(function(t){const e=nc(ta(t).slice(1));$o(Array.isArray(e)&&(8===e.length||11===e.length),"invalid field count for transaction type: 1","data",ia(t));const n={type:1,chainId:Md(e[0],"chainId"),nonce:Ld(e[1],"nonce"),gasPrice:Md(e[2],"gasPrice"),gasLimit:Md(e[3],"gasLimit"),to:Dd(e[4]),value:Md(e[5],"value"),data:ia(e[6]),accessList:Bd(e[7],"accessList")};return 8===e.length||Hd(n,e.slice(8)),n}(n));case 2:return t.from(function(t){const e=nc(ta(t).slice(1));$o(Array.isArray(e)&&(9===e.length||12===e.length),"invalid field count for transaction type: 2","data",ia(t));const n={type:2,chainId:Md(e[0],"chainId"),nonce:Ld(e[1],"nonce"),maxPriorityFeePerGas:Md(e[2],"maxPriorityFeePerGas"),maxFeePerGas:Md(e[3],"maxFeePerGas"),gasPrice:null,gasLimit:Md(e[4],"gasLimit"),to:Dd(e[5]),value:Md(e[6],"value"),data:ia(e[7]),accessList:Bd(e[8],"accessList")};return 9===e.length||Hd(n,e.slice(9)),n}(n));case 3:return t.from(function(t){let e=nc(ta(t).slice(1)),n="3",r=null,s=null;if(4===e.length&&Array.isArray(e[0])){n="3 (network format)";const t=e[1],r=e[2],i=e[3];$o(Array.isArray(t),"invalid network format: blobs not an array","fields[1]",t),$o(Array.isArray(r),"invalid network format: commitments not an array","fields[2]",r),$o(Array.isArray(i),"invalid network format: proofs not an array","fields[3]",i),$o(t.length===r.length,"invalid network format: blobs/commitments length mismatch","fields",e),$o(t.length===i.length,"invalid network format: blobs/proofs length mismatch","fields",e),s=[];for(let n=0;n<e[1].length;n++)s.push({data:t[n],commitment:r[n],proof:i[n]});e=e[0]}else if(5===e.length&&Array.isArray(e[0])){n="3 (EIP-7594 network format)",r=_a(e[1]);const t=e[2],i=e[3],o=e[4];$o(1===r,`unsupported EIP-7594 network format version: ${r}`,"fields[1]",r),$o(Array.isArray(t),"invalid EIP-7594 network format: blobs not an array","fields[2]",t),$o(Array.isArray(i),"invalid EIP-7594 network format: commitments not an array","fields[3]",i),$o(Array.isArray(o),"invalid EIP-7594 network format: proofs not an array","fields[4]",o),$o(t.length===i.length,"invalid network format: blobs/commitments length mismatch","fields",e),$o(t.length*Nd===o.length,"invalid network format: blobs/proofs length mismatch","fields",e),s=[];for(let e=0;e<t.length;e++){const n=[];for(let t=0;t<Nd;t++)n.push(o[e*Nd+t]);s.push({data:t[e],commitment:i[e],proof:oa(n)})}e=e[0]}$o(Array.isArray(e)&&(11===e.length||14===e.length),`invalid field count for transaction type: ${n}`,"data",ia(t));const i={type:3,chainId:Md(e[0],"chainId"),nonce:Ld(e[1],"nonce"),maxPriorityFeePerGas:Md(e[2],"maxPriorityFeePerGas"),maxFeePerGas:Md(e[3],"maxFeePerGas"),gasPrice:null,gasLimit:Md(e[4],"gasLimit"),to:Dd(e[5]),value:Md(e[6],"value"),data:ia(e[7]),accessList:Bd(e[8],"accessList"),maxFeePerBlobGas:Md(e[9],"maxFeePerBlobGas"),blobVersionedHashes:e[10],blobWrapperVersion:r};s&&(i.blobs=s),$o(null!=i.to,`invalid address for transaction type: ${n}`,"data",t),$o(Array.isArray(i.blobVersionedHashes),"invalid blobVersionedHashes: must be an array","data",t);for(let o=0;o<i.blobVersionedHashes.length;o++)$o(na(i.blobVersionedHashes[o],32),`invalid blobVersionedHash at index ${o}: must be length 32`,"data",t);return 11===e.length||Hd(i,e.slice(11)),i}(n));case 4:return t.from(function(t){const e=nc(ta(t).slice(1));$o(Array.isArray(e)&&(10===e.length||13===e.length),"invalid field count for transaction type: 4","data",ia(t));const n={type:4,chainId:Md(e[0],"chainId"),nonce:Ld(e[1],"nonce"),maxPriorityFeePerGas:Md(e[2],"maxPriorityFeePerGas"),maxFeePerGas:Md(e[3],"maxFeePerGas"),gasPrice:null,gasLimit:Md(e[4],"gasLimit"),to:Dd(e[5]),value:Md(e[6],"value"),data:ia(e[7]),accessList:Bd(e[8],"accessList"),authorizationList:Ud(e[9],"authorizationList")};return 10===e.length||Hd(n,e.slice(10)),n}(n))}qo(!1,"unsupported transaction type","UNSUPPORTED_OPERATION",{operation:"from"})}const n=new t;return null!=e.type&&(n.type=e.type),null!=e.to&&(n.to=e.to),null!=e.nonce&&(n.nonce=e.nonce),null!=e.gasLimit&&(n.gasLimit=e.gasLimit),null!=e.gasPrice&&(n.gasPrice=e.gasPrice),null!=e.maxPriorityFeePerGas&&(n.maxPriorityFeePerGas=e.maxPriorityFeePerGas),null!=e.maxFeePerGas&&(n.maxFeePerGas=e.maxFeePerGas),null!=e.maxFeePerBlobGas&&(n.maxFeePerBlobGas=e.maxFeePerBlobGas),null!=e.data&&(n.data=e.data),null!=e.value&&(n.value=e.value),null!=e.chainId&&(n.chainId=e.chainId),null!=e.signature&&(n.signature=jh.from(e.signature)),null!=e.accessList&&(n.accessList=e.accessList),null!=e.authorizationList&&(n.authorizationList=e.authorizationList),null!=e.blobVersionedHashes&&(n.blobVersionedHashes=e.blobVersionedHashes),null!=e.kzg&&(n.kzg=e.kzg),null!=e.blobWrapperVersion&&(n.blobWrapperVersion=e.blobWrapperVersion),null!=e.blobs&&(n.blobs=e.blobs),null!=e.hash&&($o(n.isSigned(),"unsigned transaction cannot define '.hash'","tx",e),$o(n.hash===e.hash,"hash mismatch","tx",e)),null!=e.from&&($o(n.isSigned(),"unsigned transaction cannot define '.from'","tx",e),$o(n.from.toLowerCase()===(e.from||"").toLowerCase(),"from mismatch","tx",e)),n}};function Wd(t){return Bl(Da(t))}const Kd=new Map([[8217,"apostrophe"],[8260,"fraction slash"],[12539,"middle dot"]]);function zd(t){return function(t){let e=0;return()=>t[e++]}(function(t){let e=0;function n(){return t[e++]<<8|t[e++]}let r=n(),s=1,i=[0,1];for(let A=1;A<r;A++)i.push(s+=n());let o=n(),a=e;e+=o;let c=0,l=0;function u(){return 0==c&&(l=l<<8|t[e++],c=8),l>>--c&1}const h=2**31,d=h>>>1,f=d>>1,p=h-1;let g=0;for(let A=0;A<31;A++)g=g<<1|u();let m=[],y=0,w=h;for(;;){let t=Math.floor(((g-y+1)*s-1)/w),e=0,n=r;for(;n-e>1;){let r=e+n>>>1;t<i[r]?n=r:e=r}if(0==e)break;m.push(e);let o=y+Math.floor(w*i[e]/s),a=y+Math.floor(w*i[e+1]/s)-1;for(;!((o^a)&d);)g=g<<1&p|u(),o=o<<1&p,a=a<<1&p|1;for(;o&~a&f;)g=g&d|g<<1&p>>>1|u(),o=o<<1^d,a=(a^d)<<1|d|1;y=o,w=1+a-o}let b=r-4;return m.map((e=>{switch(e-b){case 3:return b+65792+(t[a++]<<16|t[a++]<<8|t[a++]);case 2:return b+256+(t[a++]<<8|t[a++]);case 1:return b+t[a++];default:return e-1}}))}(function(t){let e=[];[..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"].forEach(((t,n)=>e[t.charCodeAt(0)]=n));let n=t.length,r=new Uint8Array(6*n>>3);for(let s=0,i=0,o=0,a=0;s<n;s++)a=a<<6|e[t.charCodeAt(s)],o+=6,o>=8&&(r[i++]=a>>(o-=8));return r}(t)))}function qd(t){return 1&t?~t>>1:t>>1}function $d(t,e){let n=Array(t);for(let r=0,s=0;r<t;r++)n[r]=s+=qd(e());return n}function Qd(t,e=0){let n=[];for(;;){let r=t(),s=t();if(!s)break;e+=r;for(let t=0;t<s;t++)n.push(e+t);e+=s+1}return n}function Jd(t){return Zd((()=>{let e=Qd(t);if(e.length)return e}))}function Yd(t){let e=[];for(;;){let n=t();if(0==n)break;e.push(tf(n,t))}for(;;){let n=t()-1;if(n<0)break;e.push(ef(n,t))}return e.flat()}function Zd(t){let e=[];for(;;){let n=t(e.length);if(!n)break;e.push(n)}return e}function Xd(t,e,n){let r=Array(t).fill().map((()=>[]));for(let s=0;s<e;s++)$d(t,n).forEach(((t,e)=>r[e].push(t)));return r}function tf(t,e){let n=1+e(),r=e(),s=Zd(e);return Xd(s.length,1+t,e).flatMap(((t,e)=>{let[i,...o]=t;return Array(s[e]).fill().map(((t,e)=>{let s=e*r;return[i+e*n,o.map((t=>t+s))]}))}))}function ef(t,e){return Xd(1+e(),1+t,e).map((t=>[t[0],t.slice(1)]))}function nf(t){return`{${function(t){return t.toString(16).toUpperCase().padStart(2,"0")}(t)}}`}function rf(t){let e=t.length;if(e<4096)return String.fromCodePoint(...t);let n=[];for(let r=0;r<e;)n.push(String.fromCodePoint(...t.slice(r,r+=4096)));return n.join("")}function sf(t,e){let n=t.length,r=n-e.length;for(let s=0;0==r&&s<n;s++)r=t[s]-e[s];return r}const of=44032,af=4352,cf=4449,lf=4519,uf=28,hf=588;function df(t){return t>>24&255}function ff(t){return 16777215&t}let pf,gf,mf,yf;function wf(t){return t>=of&&t<55204}function bf(t,e){if(t>=af&&t<4371&&e>=cf&&e<4470)return of+(t-af)*hf+(e-cf)*uf;if(wf(t)&&e>lf&&e<4547&&(t-of)%uf==0)return t+(e-lf);{let n=yf.get(t);return n&&(n=n.get(e),n)?n:-1}}function Af(t){pf||function(){let t=zd("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");pf=new Map(Jd(t).flatMap(((t,e)=>t.map((t=>[t,e+1<<24]))))),gf=new Set(Qd(t)),mf=new Map,yf=new Map;for(let[e,n]of Yd(t)){if(!gf.has(e)&&2==n.length){let[t,r]=n,s=yf.get(t);s||(s=new Map,yf.set(t,s)),s.set(r,e)}mf.set(e,n.reverse())}}();let e=[],n=[],r=!1;function s(t){let n=pf.get(t);n&&(r=!0,t|=n),e.push(t)}for(let i of t)for(;;){if(i<128)e.push(i);else if(wf(i)){let t=i-of,e=t%hf/uf|0,n=t%uf;s(af+(t/hf|0)),s(cf+e),n>0&&s(lf+n)}else{let t=mf.get(i);t?n.push(...t):s(i)}if(!n.length)break;i=n.pop()}if(r&&e.length>1){let t=df(e[0]);for(let n=1;n<e.length;n++){let r=df(e[n]);if(0==r||t<=r){t=r;continue}let s=n-1;for(;;){let n=e[s+1];if(e[s+1]=e[s],e[s]=n,!s)break;if(t=df(e[--s]),t<=r)break}t=df(e[n])}}return e}function _f(t){return Af(t).map(ff)}function vf(t){return function(t){let e=[],n=[],r=-1,s=0;for(let i of t){let t=df(i),o=ff(i);if(-1==r)0==t?r=o:e.push(o);else if(s>0&&s>=t)0==t?(e.push(r,...n),n.length=0,r=o):n.push(o),s=t;else{let i=bf(r,o);i>=0?r=i:0==s&&0==t?(e.push(r),r=o):(n.push(o),s=t)}}return r>=0&&e.push(r,...n),e}(Af(t))}const Ef=".",kf=t=>Array.from(t);function Sf(t,e){return t.P.has(e)||t.Q.has(e)}class Tf extends Array{get is_emoji(){return!0}}let Rf,If,Of,Cf,xf,Nf,Pf,Df,Bf,Uf,Lf;function Mf(){if(Rf)return;let t=zd("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");const e=()=>Qd(t),n=()=>new Set(e()),r=(t,e)=>e.forEach((e=>t.add(e)));Rf=new Map(Yd(t)),If=n(),Of=e(),Cf=new Set(e().map((t=>Of[t]))),Of=new Set(Of),xf=n(),n();let s=Jd(t),i=t();const o=()=>{let t=new Set;return e().forEach((e=>r(t,s[e]))),r(t,e()),t};Nf=Zd((e=>{let n=Zd(t).map((t=>t+96));if(n.length){let r=e>=i;return n[0]-=32,n=rf(n),r&&(n=`Restricted[${n}]`),{N:n,P:o(),Q:o(),M:!t(),R:r}}})),Pf=n(),Df=new Map;let a=e().concat(kf(Pf)).sort(((t,e)=>t-e));a.forEach(((e,n)=>{let r=t(),s=a[n]=r?a[n-r]:{V:[],M:new Map};s.V.push(e),Pf.has(e)||Df.set(e,s)}));for(let{V:u,M:h}of new Set(Df.values())){let t=[];for(let n of u){let e=Nf.filter((t=>Sf(t,n))),s=t.find((({G:t})=>e.some((e=>t.has(e)))));s||(s={G:new Set,V:[]},t.push(s)),s.V.push(n),r(s.G,e)}let e=t.flatMap((t=>kf(t.G)));for(let{G:n,V:r}of t){let t=new Set(e.filter((t=>!n.has(t))));for(let e of r)h.set(e,t)}}Bf=new Set;let c=new Set;const l=t=>Bf.has(t)?c.add(t):Bf.add(t);for(let u of Nf){for(let t of u.P)l(t);for(let t of u.Q)l(t)}for(let u of Bf)Df.has(u)||c.has(u)||Df.set(u,1);r(Bf,_f(Bf)),Uf=function(t){let e=[],n=Qd(t);return function t({S:n,B:r},s,i){if(!(4&n&&i===s[s.length-1])){2&n&&(i=s[s.length-1]),1&n&&e.push(s);for(let e of r)for(let n of e.Q)t(e,[...s,n],i)}}(function e(r){return{S:t(),B:Zd((()=>{let r=Qd(t).map((t=>n[t]));if(r.length)return e(r)})),Q:r}}([]),[]),e}(t).map((t=>Tf.from(t))).sort(sf),Lf=new Map;for(let u of Uf){let t=[Lf];for(let e of u){let n=t.map((t=>{let n=t.get(e);return n||(n=new Map,t.set(e,n)),n}));65039===e?t.push(...n):t=n}for(let e of t)e.V=u}}function Ff(t){return(Hf(t)?"":`${Gf(jf([t]))} `)+nf(t)}function Gf(t){return`"${t}"‎`}function jf(t,e=1/0,n=nf){let r=[];var s,i;s=t[0],Mf(),(i?Cf.has(s):Of.has(s))&&r.push("◌"),t.length>e&&(e>>=1,t=[...t.slice(0,e),8230,...t.slice(-e)]);let o=0,a=t.length;for(let c=0;c<a;c++){let e=t[c];Hf(e)&&(r.push(rf(t.slice(o,c))),r.push(n(e)),o=c+1)}return r.push(rf(t.slice(o,a))),r.join("")}function Hf(t){return Mf(),xf.has(t)}function Vf(t){return e=function(t,e,n){if(!t)return[];Mf();let r=0;return t.split(Ef).map((t=>{let s=function(t){let e=[];for(let n=0,r=t.length;n<r;){let r=t.codePointAt(n);n+=r<65536?1:2,e.push(r)}return e}(t),i={input:s,offset:r};r+=s.length+1;try{let t,r=i.tokens=function(t,e,n){let r=[],s=[];for(t=t.slice().reverse();t.length;){let i=$f(t);if(i)s.length&&(r.push(e(s)),s=[]),r.push(n(i));else{let e=t.pop();if(Bf.has(e))s.push(e);else{let t=Rf.get(e);if(t)s.push(...t);else if(!If.has(e))throw Wf(e)}}}return s.length&&r.push(e(s)),r}(s,e,n),o=r.length;if(!o)throw new Error("empty label");let a=i.output=r.flat();if(function(t){for(let e=t.lastIndexOf(95);e>0;)if(95!==t[--e])throw new Error("underscore allowed only at start")}(a),!(i.emoji=o>1||r[0].is_emoji)&&a.every((t=>t<128)))!function(t){if(t.length>=4&&45==t[2]&&45==t[3])throw new Error(`invalid label extension: "${rf(t.slice(0,4))}"`)}(a),t="ASCII";else{let e=r.flatMap((t=>t.is_emoji?[]:t));if(e.length){if(Of.has(a[0]))throw zf("leading combining mark");for(let t=1;t<o;t++){let e=r[t];if(!e.is_emoji&&Of.has(e[0]))throw zf(`emoji + combining mark: "${rf(r[t-1])} + ${jf([e[0]])}"`)}!function(t){let e=t[0],n=Kd.get(e);if(n)throw zf(`leading ${n}`);let r=t.length,s=-1;for(let i=1;i<r;i++){e=t[i];let r=Kd.get(e);if(r){if(s==i)throw zf(`${n} + ${r}`);s=i+1,n=r}}if(s==r)throw zf(`trailing ${n}`)}(a);let n=kf(new Set(e)),[s]=function(t){let e=Nf;for(let n of t){let t=e.filter((t=>Sf(t,n)));if(!t.length)throw Nf.some((t=>Sf(t,n)))?Kf(e[0],n):Wf(n);if(e=t,1==t.length)break}return e}(n);!function(t,e){for(let n of e)if(!Sf(t,n))throw Kf(t,n);if(t.M){let t=_f(e);for(let e=1,n=t.length;e<n;e++)if(Cf.has(t[e])){let r=e+1;for(let s;r<n&&Cf.has(s=t[r]);r++)for(let n=e;n<r;n++)if(t[n]==s)throw new Error(`duplicate non-spacing marks: ${Ff(s)}`);if(r-e>4)throw new Error(`excessive non-spacing marks: ${Gf(jf(t.slice(e-1,r)))} (${r-e}/4)`);e=r}}}(s,e),function(t,e){let n,r=[];for(let s of e){let t=Df.get(s);if(1===t)return;if(t){let e=t.M.get(s);if(n=n?n.filter((t=>e.has(t))):kf(e),!n.length)return}else r.push(s)}if(n)for(let s of n)if(r.every((t=>Sf(s,t))))throw new Error(`whole-script confusable: ${t.N}/${s.N}`)}(s,n),t=s.N}else t="Emoji"}i.type=t}catch(o){i.error=o}return i}))}(t,vf,qf),e.map((({input:t,error:n,output:r})=>{if(n){let r=n.message;throw new Error(1==e.length?r:`Invalid label ${Gf(jf(t,63))}: ${r}`)}return rf(r)})).join(Ef);var e}function Wf(t){return new Error(`disallowed character: ${Ff(t)}`)}function Kf(t,e){let n=Ff(e),r=Nf.find((t=>t.P.has(e)));return r&&(n=`${r.N} ${n}`),new Error(`illegal mixture: ${t.N} + ${n}`)}function zf(t){return new Error(`illegal placement: ${t}`)}function qf(t){return t.filter((t=>65039!=t))}function $f(t,e){let n,r=Lf,s=t.length;for(;s&&(r=r.get(t[--s]),r);){let{V:i}=r;i&&(n=i,e&&e.push(...t.slice(s).reverse()),t.length=s)}return n}const Qf=new Uint8Array(32);function Jf(t){return $o(0!==t.length,"invalid ENS name; empty component","comp",t),t}function Yf(t){const e=Da(Zf(t)),n=[];if(0===t.length)return n;let r=0;for(let s=0;s<e.length;s++){46===e[s]&&(n.push(Jf(e.slice(r,s))),r=s+1)}return $o(r<e.length,"invalid ENS name; empty component","name",t),n.push(Jf(e.slice(r))),n}function Zf(t){try{if(0===t.length)throw new Error("empty label");return Vf(t)}catch(e){$o(!1,`invalid ENS name (${e.message})`,"name",t)}}function Xf(t){try{return 0!==Yf(t).length}catch(e){}return!1}function tp(t){$o("string"==typeof t,"invalid ENS name; not a string","name",t),$o(t.length,"invalid ENS name (empty label)","name",t);let e=Qf;const n=Yf(t);for(;n.length;)e=Bl(oa([e,Bl(n.pop())]));return ia(e)}function ep(t,e){const n=null!=e?e:63;return $o(n<=255,"DNS encoded label cannot exceed 255","length",n),ia(oa(Yf(t).map((e=>{$o(e.length<=n,`label ${JSON.stringify(t)} exceeds ${n} bytes`,"name",t);const r=new Uint8Array(e.length+1);return r.set(e,1),r[0]=r.length-1,r}))))+"00"}Qf.fill(0);const np=new Uint8Array(32);np.fill(0);const rp=BigInt(-1),sp=BigInt(0),ip=BigInt(1),op=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");const ap=va(ip,32),cp=va(sp,32),lp={name:"string",version:"string",chainId:"uint256",verifyingContract:"address",salt:"bytes32"},up=["name","version","chainId","verifyingContract","salt"];function hp(t){return function(e){return $o("string"==typeof e,`invalid domain value for ${JSON.stringify(t)}`,`domain.${t}`,e),e}}const dp={name:hp("name"),version:hp("version"),chainId:function(t){const e=ya(t,"domain.chainId");return $o(e>=0,"invalid chain ID","domain.chainId",t),Number.isSafeInteger(e)?Number(e):ka(e)},verifyingContract:function(t){try{return $h(t).toLowerCase()}catch(e){}$o(!1,'invalid domain value "verifyingContract"',"domain.verifyingContract",t)},salt:function(t){const e=ta(t,"domain.salt");return $o(32===e.length,'invalid domain value "salt"',"domain.salt",t),ia(e)}};function fp(t){{const e=t.match(/^(u?)int(\d+)$/);if(e){const n=""===e[1],r=parseInt(e[2]);$o(r%8==0&&0!==r&&r<=256&&e[2]===String(r),"invalid numeric width","type",t);const s=ma(op,n?r-1:r),i=n?(s+ip)*rp:sp;return function(e){const r=ya(e,"value");return $o(r>=i&&r<=s,`value out-of-bounds for ${t}`,"value",r),va(n?ga(r,256):r,32)}}}{const e=t.match(/^bytes(\d+)$/);if(e){const n=parseInt(e[1]);return $o(0!==n&&n<=32&&e[1]===String(n),"invalid bytes width","type",t),function(e){return $o(ta(e).length===n,`invalid length for ${t}`,"value",e),function(t){const e=ta(t),n=e.length%32;return n?oa([e,np.slice(n)]):ia(e)}(e)}}}switch(t){case"address":return function(t){return ua($h(t),32)};case"bool":return function(t){return t?ap:cp};case"bytes":return function(t){return Bl(t)};case"string":return function(t){return Wd(t)}}return null}function pp(t,e){return`${t}(${e.map((({name:t,type:e})=>e+" "+t)).join(",")})`}function gp(t){const e=t.match(/^([^\x5b]*)((\x5b\d*\x5d)*)(\x5b(\d*)\x5d)$/);return e?{base:e[1],index:e[2]+e[4],array:{base:e[1],prefix:e[1]+e[2],count:e[5]?parseInt(e[5]):-1}}:{base:t}}dt=new WeakMap,ft=new WeakMap,pt=new WeakMap,gt=new WeakSet,mt=function(t){{const e=fp(t);if(e)return e}const e=gp(t).array;if(e){const t=e.prefix,n=this.getEncoder(t);return r=>{$o(-1===e.count||e.count===r.length,`array length mismatch; expected length ${e.count}`,"value",r);let s=r.map(n);return Pn(this,ft).has(t)&&(s=s.map(Bl)),Bl(oa(s))}}const n=this.types[t];if(n){const e=Wd(Pn(this,ft).get(t));return t=>{const r=n.map((({name:e,type:n})=>{const r=this.getEncoder(n)(t[e]);return Pn(this,ft).has(n)?Bl(r):r}));return r.unshift(e),oa(r)}}$o(!1,`unknown type: ${t}`,"type",t)};let mp=class t{constructor(t){Dn(this,gt),xn(this,"primaryType"),Dn(this,dt,void 0),Dn(this,ft,void 0),Dn(this,pt,void 0),Bn(this,ft,new Map),Bn(this,pt,new Map);const e=new Map,n=new Map,r=new Map,s={};Object.keys(t).forEach((i=>{s[i]=t[i].map((({name:e,type:n})=>{let{base:r,index:s}=gp(n);return"int"!==r||t.int||(r="int256"),"uint"!==r||t.uint||(r="uint256"),{name:e,type:r+(s||"")}})),e.set(i,new Set),n.set(i,[]),r.set(i,new Set)})),Bn(this,dt,JSON.stringify(s));for(const o in s){const r=new Set;for(const i of s[o]){$o(!r.has(i.name),`duplicate variable name ${JSON.stringify(i.name)} in ${JSON.stringify(o)}`,"types",t),r.add(i.name);const s=gp(i.type).base;$o(s!==o,`circular type reference to ${JSON.stringify(s)}`,"types",t);fp(s)||($o(n.has(s),`unknown type ${JSON.stringify(s)}`,"types",t),n.get(s).push(o),e.get(o).add(s))}}const i=Array.from(n.keys()).filter((t=>0===n.get(t).length));$o(0!==i.length,"missing primary type","types",t),$o(1===i.length,`ambiguous primary types or unused types: ${i.map((t=>JSON.stringify(t))).join(", ")}`,"types",t),Ho(this,{primaryType:i[0]}),function s(i,o){$o(!o.has(i),`circular type reference to ${JSON.stringify(i)}`,"types",t),o.add(i);for(const t of e.get(i))if(n.has(t)){s(t,o);for(const e of o)r.get(e).add(t)}o.delete(i)}(this.primaryType,new Set);for(const[o,a]of r){const t=Array.from(a);t.sort(),Pn(this,ft).set(o,pp(o,s[o])+t.map((t=>pp(t,s[t]))).join(""))}}get types(){return JSON.parse(Pn(this,dt))}getEncoder(t){let e=Pn(this,pt).get(t);return e||(e=Ln(this,gt,mt).call(this,t),Pn(this,pt).set(t,e)),e}encodeType(t){const e=Pn(this,ft).get(t);return $o(e,`unknown type: ${JSON.stringify(t)}`,"name",t),e}encodeData(t,e){return this.getEncoder(t)(e)}hashStruct(t,e){return Bl(this.encodeData(t,e))}encode(t){return this.encodeData(this.primaryType,t)}hash(t){return this.hashStruct(this.primaryType,t)}_visit(t,e,n){if(fp(t))return n(t,e);const r=gp(t).array;if(r)return $o(-1===r.count||r.count===e.length,`array length mismatch; expected length ${r.count}`,"value",e),e.map((t=>this._visit(r.prefix,t,n)));const s=this.types[t];if(s)return s.reduce(((t,{name:r,type:s})=>(t[r]=this._visit(s,e[r],n),t)),{});$o(!1,`unknown type: ${t}`,"type",t)}visit(t,e){return this._visit(this.primaryType,t,e)}static from(e){return new t(e)}static getPrimaryType(e){return t.from(e).primaryType}static hashStruct(e,n,r){return t.from(n).hashStruct(e,r)}static hashDomain(e){const n=[];for(const t in e){if(null==e[t])continue;const r=lp[t];$o(r,`invalid typed-data domain key: ${JSON.stringify(t)}`,"domain",e),n.push({name:t,type:r})}return n.sort(((t,e)=>up.indexOf(t.name)-up.indexOf(e.name))),t.hashStruct("EIP712Domain",{EIP712Domain:n},e)}static encode(e,n,r){return oa(["0x1901",t.hashDomain(e),t.from(n).hash(r)])}static hash(e,n,r){return Bl(t.encode(e,n,r))}static async resolveNames(e,n,r,s){e=Object.assign({},e);for(const t in e)null==e[t]&&delete e[t];const i={};e.verifyingContract&&!na(e.verifyingContract,20)&&(i[e.verifyingContract]="0x");const o=t.from(n);o.visit(r,((t,e)=>("address"!==t||na(e,20)||(i[e]="0x"),e)));for(const t in i)i[t]=await s(t);return e.verifyingContract&&i[e.verifyingContract]&&(e.verifyingContract=i[e.verifyingContract]),{domain:e,value:r=o.visit(r,((t,e)=>"address"===t&&i[e]?i[e]:e))}}static getPayload(e,n,r){t.hashDomain(e);const s={},i=[];up.forEach((t=>{const n=e[t];null!=n&&(s[t]=dp[t](n),i.push({name:t,type:lp[t]}))}));const o=t.from(n);n=o.types;const a=Object.assign({},n);return $o(null==a.EIP712Domain,"types must not contain EIP712Domain type","types.EIP712Domain",n),a.EIP712Domain=i,o.encode(r),{types:a,domain:s,primaryType:o.primaryType,message:o.visit(r,((t,e)=>{if(t.match(/^bytes(\d*)/))return ia(ta(e));if(t.match(/^u?int/))return ya(e).toString();switch(t){case"address":return e.toLowerCase();case"bool":return!!e;case"string":return $o("string"==typeof e,"invalid string","value",e),e}$o(!1,"unsupported type","type",t)}))}}};function yp(t){const e=new Set;return t.forEach((t=>e.add(t))),Object.freeze(e)}const wp=yp("external public payable override".split(" ")),bp="constant external internal payable private public pure view override",Ap=yp(bp.split(" ")),_p="constructor error event fallback function receive struct",vp=yp(_p.split(" ")),Ep="calldata memory storage payable indexed",kp=yp(Ep.split(" ")),Sp=yp([_p,Ep,"tuple returns",bp].join(" ").split(" ")),Tp={"(":"OPEN_PAREN",")":"CLOSE_PAREN","[":"OPEN_BRACKET","]":"CLOSE_BRACKET",",":"COMMA","@":"AT"},Rp=new RegExp("^(\\s*)"),Ip=new RegExp("^([0-9]+)"),Op=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"),Cp=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$"),xp=new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$"),Np=class t{constructor(t){Dn(this,bt),Dn(this,yt,void 0),Dn(this,wt,void 0),Bn(this,yt,0),Bn(this,wt,t.slice())}get offset(){return Pn(this,yt)}get length(){return Pn(this,wt).length-Pn(this,yt)}clone(){return new t(Pn(this,wt))}reset(){Bn(this,yt,0)}popKeyword(t){const e=this.peek();if("KEYWORD"!==e.type||!t.has(e.text))throw new Error(`expected keyword ${e.text}`);return this.pop().text}popType(t){if(this.peek().type!==t){const e=this.peek();throw new Error(`expected ${t}; got ${e.type} ${JSON.stringify(e.text)}`)}return this.pop().text}popParen(){const t=this.peek();if("OPEN_PAREN"!==t.type)throw new Error("bad start");const e=Ln(this,bt,At).call(this,Pn(this,yt)+1,t.match+1);return Bn(this,yt,t.match+1),e}popParams(){const t=this.peek();if("OPEN_PAREN"!==t.type)throw new Error("bad start");const e=[];for(;Pn(this,yt)<t.match-1;){const t=this.peek().linkNext;e.push(Ln(this,bt,At).call(this,Pn(this,yt)+1,t)),Bn(this,yt,t)}return Bn(this,yt,t.match+1),e}peek(){if(Pn(this,yt)>=Pn(this,wt).length)throw new Error("out-of-bounds");return Pn(this,wt)[Pn(this,yt)]}peekKeyword(t){const e=this.peekType("KEYWORD");return null!=e&&t.has(e)?e:null}peekType(t){if(0===this.length)return null;const e=this.peek();return e.type===t?e.text:null}pop(){const t=this.peek();return Un(this,yt)._++,t}toString(){const t=[];for(let e=Pn(this,yt);e<Pn(this,wt).length;e++){const n=Pn(this,wt)[e];t.push(`${n.type}:${n.text}`)}return`<TokenString ${t.join(" ")}>`}};yt=new WeakMap,wt=new WeakMap,bt=new WeakSet,At=function(t=0,e=0){return new Np(Pn(this,wt).slice(t,e).map((e=>Object.freeze(Object.assign({},e,{match:e.match-t,linkBack:e.linkBack-t,linkNext:e.linkNext-t})))))};let Pp=Np;function Dp(t){const e=[],n=e=>{const n=i<t.length?JSON.stringify(t[i]):"$EOI";throw new Error(`invalid token ${n} at ${i}: ${e}`)};let r=[],s=[],i=0;for(;i<t.length;){let o=t.substring(i),a=o.match(Rp);a&&(i+=a[1].length,o=t.substring(i));const c={depth:r.length,linkBack:-1,linkNext:-1,match:-1,type:"",text:"",offset:i,value:-1};e.push(c);let l=Tp[o[0]]||"";if(l){if(c.type=l,c.text=o[0],i++,"OPEN_PAREN"===l)r.push(e.length-1),s.push(e.length-1);else if("CLOSE_PAREN"==l)0===r.length&&n("no matching open bracket"),c.match=r.pop(),e[c.match].match=e.length-1,c.depth--,c.linkBack=s.pop(),e[c.linkBack].linkNext=e.length-1;else if("COMMA"===l)c.linkBack=s.pop(),e[c.linkBack].linkNext=e.length-1,s.push(e.length-1);else if("OPEN_BRACKET"===l)c.type="BRACKET";else if("CLOSE_BRACKET"===l){let t=e.pop().text;if(e.length>0&&"NUMBER"===e[e.length-1].type){const n=e.pop().text;t=n+t,e[e.length-1].value=_a(n)}if(0===e.length||"BRACKET"!==e[e.length-1].type)throw new Error("missing opening bracket");e[e.length-1].text+=t}}else if(a=o.match(Op),a){if(c.text=a[1],i+=c.text.length,Sp.has(c.text)){c.type="KEYWORD";continue}if(c.text.match(xp)){c.type="TYPE";continue}c.type="ID"}else{if(a=o.match(Ip),!a)throw new Error(`unexpected token ${JSON.stringify(o[0])} at position ${i}`);c.text=a[1],c.type="NUMBER",i+=c.text.length}}return new Pp(e.map((t=>Object.freeze(t))))}function Bp(t,e){let n=[];for(const r in e.keys())t.has(r)&&n.push(r);if(n.length>1)throw new Error(`conflicting types: ${n.join(", ")}`)}function Up(t,e){if(e.peekKeyword(vp)){const n=e.pop().text;if(n!==t)throw new Error(`expected ${t}, got ${n}`)}return e.popType("ID")}function Lp(t,e){const n=new Set;for(;;){const r=t.peekType("KEYWORD");if(null==r||e&&!e.has(r))break;if(t.pop(),n.has(r))throw new Error(`duplicate keywords: ${JSON.stringify(r)}`);n.add(r)}return Object.freeze(n)}function Mp(t){let e=Lp(t,Ap);return Bp(e,yp("constant payable nonpayable".split(" "))),Bp(e,yp("pure view payable nonpayable".split(" "))),e.has("view")?"view":e.has("pure")?"pure":e.has("payable")?"payable":e.has("nonpayable")?"nonpayable":e.has("constant")?"view":"nonpayable"}function Fp(t,e){return t.popParams().map((t=>Xp.from(t,e)))}function Gp(t){if(t.peekType("AT")){if(t.pop(),t.peekType("NUMBER"))return ya(t.pop().text);throw new Error("invalid gas")}return null}function jp(t){if(t.length)throw new Error(`unexpected tokens at offset ${t.offset}: ${t.toString()}`)}const Hp=new RegExp(/^(.*)\[([0-9]*)\]$/);function Vp(t){const e=t.match(xp);if($o(e,"invalid type","type",t),"uint"===t)return"uint256";if("int"===t)return"int256";if(e[2]){const n=parseInt(e[2]);$o(0!==n&&n<=32,"invalid bytes length","type",t)}else if(e[3]){const n=parseInt(e[3]);$o(0!==n&&n<=256&&n%8==0,"invalid numeric width","type",t)}return t}const Wp={},Kp=Symbol.for("_ethers_internal"),zp="_ParamTypeInternal",qp="_ErrorInternal",$p="_EventInternal",Qp="_ConstructorInternal",Jp="_FallbackInternal",Yp="_FunctionInternal",Zp="_StructInternal";_t=new WeakSet,vt=function(t,e,n,r){if(this.isArray()){if(!Array.isArray(e))throw new Error("invalid array value");if(-1!==this.arrayLength&&e.length!==this.arrayLength)throw new Error("array is wrong length");const s=this.arrayChildren,i=e.slice();return i.forEach(((e,r)=>{var o;Ln(o=s,_t,vt).call(o,t,e,n,(t=>{i[r]=t}))})),void r(i)}if(this.isTuple()){const s=this.components;let i;if(Array.isArray(e))i=e.slice();else{if(null==e||"object"!=typeof e)throw new Error("invalid tuple value");i=s.map((t=>{if(!t.name)throw new Error("cannot use object value with unnamed components");if(!(t.name in e))throw new Error(`missing value for component ${t.name}`);return e[t.name]}))}if(i.length!==this.components.length)throw new Error("array is wrong length");return i.forEach(((e,r)=>{var o;Ln(o=s[r],_t,vt).call(o,t,e,n,(t=>{i[r]=t}))})),void r(i)}const s=n(this.type,e);s.then?t.push(async function(){r(await s)}()):r(s)};let Xp=class t{constructor(t,e,n,r,s,i,o,a){if(Dn(this,_t),xn(this,"name"),xn(this,"type"),xn(this,"baseType"),xn(this,"indexed"),xn(this,"components"),xn(this,"arrayLength"),xn(this,"arrayChildren"),Zo(t,Wp,"ParamType"),Object.defineProperty(this,Kp,{value:zp}),i&&(i=Object.freeze(i.slice())),"array"===r){if(null==o||null==a)throw new Error("")}else if(null!=o||null!=a)throw new Error("");if("tuple"===r){if(null==i)throw new Error("")}else if(null!=i)throw new Error("");Ho(this,{name:e,type:n,baseType:r,indexed:s,components:i,arrayLength:o,arrayChildren:a})}format(t){if(null==t&&(t="sighash"),"json"===t){const e=this.name||"";if(this.isArray()){const t=JSON.parse(this.arrayChildren.format("json"));return t.name=e,t.type+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`,JSON.stringify(t)}const n={type:"tuple"===this.baseType?"tuple":this.type,name:e};return"boolean"==typeof this.indexed&&(n.indexed=this.indexed),this.isTuple()&&(n.components=this.components.map((e=>JSON.parse(e.format(t))))),JSON.stringify(n)}let e="";return this.isArray()?(e+=this.arrayChildren.format(t),e+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`):this.isTuple()?e+="("+this.components.map((e=>e.format(t))).join("full"===t?", ":",")+")":e+=this.type,"sighash"!==t&&(!0===this.indexed&&(e+=" indexed"),"full"===t&&this.name&&(e+=" "+this.name)),e}isArray(){return"array"===this.baseType}isTuple(){return"tuple"===this.baseType}isIndexable(){return null!=this.indexed}walk(t,e){if(this.isArray()){if(!Array.isArray(t))throw new Error("invalid array value");if(-1!==this.arrayLength&&t.length!==this.arrayLength)throw new Error("array is wrong length");const n=this;return t.map((t=>n.arrayChildren.walk(t,e)))}if(this.isTuple()){if(!Array.isArray(t))throw new Error("invalid tuple value");if(t.length!==this.components.length)throw new Error("array is wrong length");const n=this;return t.map(((t,r)=>n.components[r].walk(t,e)))}return e(this.type,t)}async walkAsync(t,e){const n=[],r=[t];return Ln(this,_t,vt).call(this,n,t,e,(t=>{r[0]=t})),n.length&&await Promise.all(n),r[0]}static from(e,n){if(t.isParamType(e))return e;if("string"==typeof e)try{return t.from(Dp(e),n)}catch(a){$o(!1,"invalid param type","obj",e)}else if(e instanceof Pp){let r="",s="",i=null;Lp(e,yp(["tuple"])).has("tuple")||e.peekType("OPEN_PAREN")?(s="tuple",i=e.popParams().map((e=>t.from(e))),r=`tuple(${i.map((t=>t.format())).join(",")})`):(r=Vp(e.popType("TYPE")),s=r);let o=null,a=null;for(;e.length&&e.peekType("BRACKET");){const n=e.pop();o=new t(Wp,"",r,s,null,i,a,o),a=n.value,r+=n.text,s="array",i=null}let c=null;if(Lp(e,kp).has("indexed")){if(!n)throw new Error("");c=!0}const l=e.peekType("ID")?e.pop().text:"";if(e.length)throw new Error("leftover tokens");return new t(Wp,l,r,s,c,i,a,o)}const r=e.name;$o(!r||"string"==typeof r&&r.match(Cp),"invalid name","obj.name",r);let s=e.indexed;null!=s&&($o(n,"parameter cannot be indexed","obj.indexed",e.indexed),s=!!s);let i=e.type,o=i.match(Hp);if(o){const n=parseInt(o[2]||"-1"),a=t.from({type:o[1],components:e.components});return new t(Wp,r||"",i,"array",s,null,n,a)}if("tuple"===i||i.startsWith("tuple(")||i.startsWith("(")){const n=null!=e.components?e.components.map((e=>t.from(e))):null;return new t(Wp,r||"",i,"tuple",s,n,null,null)}return i=Vp(e.type),new t(Wp,r||"",i,i,s,null,null,null)}static isParamType(t){return t&&t[Kp]===zp}};class tg{constructor(t,e,n){xn(this,"type"),xn(this,"inputs"),Zo(t,Wp,"Fragment"),Ho(this,{type:e,inputs:n=Object.freeze(n.slice())})}static from(t){if("string"==typeof t){try{tg.from(JSON.parse(t))}catch(e){}return tg.from(Dp(t))}if(t instanceof Pp){switch(t.peekKeyword(vp)){case"constructor":return ig.from(t);case"error":return rg.from(t);case"event":return sg.from(t);case"fallback":case"receive":return og.from(t);case"function":return ag.from(t);case"struct":return cg.from(t)}}else if("object"==typeof t){switch(t.type){case"constructor":return ig.from(t);case"error":return rg.from(t);case"event":return sg.from(t);case"fallback":case"receive":return og.from(t);case"function":return ag.from(t);case"struct":return cg.from(t)}qo(!1,`unsupported type: ${t.type}`,"UNSUPPORTED_OPERATION",{operation:"Fragment.from"})}$o(!1,"unsupported frgament object","obj",t)}static isConstructor(t){return ig.isFragment(t)}static isError(t){return rg.isFragment(t)}static isEvent(t){return sg.isFragment(t)}static isFunction(t){return ag.isFragment(t)}static isStruct(t){return cg.isFragment(t)}}class eg extends tg{constructor(t,e,n,r){super(t,e,r),xn(this,"name"),$o("string"==typeof n&&n.match(Cp),"invalid identifier","name",n),r=Object.freeze(r.slice()),Ho(this,{name:n})}}function ng(t,e){return"("+e.map((e=>e.format(t))).join("full"===t?", ":",")+")"}class rg extends eg{constructor(t,e,n){super(t,"error",e,n),Object.defineProperty(this,Kp,{value:qp})}get selector(){return Wd(this.format("sighash")).substring(0,10)}format(t){if(null==t&&(t="sighash"),"json"===t)return JSON.stringify({type:"error",name:this.name,inputs:this.inputs.map((e=>JSON.parse(e.format(t))))});const e=[];return"sighash"!==t&&e.push("error"),e.push(this.name+ng(t,this.inputs)),e.join(" ")}static from(t){if(rg.isFragment(t))return t;if("string"==typeof t)return rg.from(Dp(t));if(t instanceof Pp){const e=Up("error",t),n=Fp(t);return jp(t),new rg(Wp,e,n)}return new rg(Wp,t.name,t.inputs?t.inputs.map(Xp.from):[])}static isFragment(t){return t&&t[Kp]===qp}}class sg extends eg{constructor(t,e,n,r){super(t,"event",e,n),xn(this,"anonymous"),Object.defineProperty(this,Kp,{value:$p}),Ho(this,{anonymous:r})}get topicHash(){return Wd(this.format("sighash"))}format(t){if(null==t&&(t="sighash"),"json"===t)return JSON.stringify({type:"event",anonymous:this.anonymous,name:this.name,inputs:this.inputs.map((e=>JSON.parse(e.format(t))))});const e=[];return"sighash"!==t&&e.push("event"),e.push(this.name+ng(t,this.inputs)),"sighash"!==t&&this.anonymous&&e.push("anonymous"),e.join(" ")}static getTopicHash(t,e){e=(e||[]).map((t=>Xp.from(t)));return new sg(Wp,t,e,!1).topicHash}static from(t){if(sg.isFragment(t))return t;if("string"==typeof t)try{return sg.from(Dp(t))}catch(e){$o(!1,"invalid event fragment","obj",t)}else if(t instanceof Pp){const e=Up("event",t),n=Fp(t,!0),r=!!Lp(t,yp(["anonymous"])).has("anonymous");return jp(t),new sg(Wp,e,n,r)}return new sg(Wp,t.name,t.inputs?t.inputs.map((t=>Xp.from(t,!0))):[],!!t.anonymous)}static isFragment(t){return t&&t[Kp]===$p}}class ig extends tg{constructor(t,e,n,r,s){super(t,e,n),xn(this,"payable"),xn(this,"gas"),Object.defineProperty(this,Kp,{value:Qp}),Ho(this,{payable:r,gas:s})}format(t){if(qo(null!=t&&"sighash"!==t,"cannot format a constructor for sighash","UNSUPPORTED_OPERATION",{operation:"format(sighash)"}),"json"===t)return JSON.stringify({type:"constructor",stateMutability:this.payable?"payable":"undefined",payable:this.payable,gas:null!=this.gas?this.gas:void 0,inputs:this.inputs.map((e=>JSON.parse(e.format(t))))});const e=[`constructor${ng(t,this.inputs)}`];return this.payable&&e.push("payable"),null!=this.gas&&e.push(`@${this.gas.toString()}`),e.join(" ")}static from(t){if(ig.isFragment(t))return t;if("string"==typeof t)try{return ig.from(Dp(t))}catch(e){$o(!1,"invalid constuctor fragment","obj",t)}else if(t instanceof Pp){Lp(t,yp(["constructor"]));const e=Fp(t),n=!!Lp(t,wp).has("payable"),r=Gp(t);return jp(t),new ig(Wp,"constructor",e,n,r)}return new ig(Wp,"constructor",t.inputs?t.inputs.map(Xp.from):[],!!t.payable,null!=t.gas?t.gas:null)}static isFragment(t){return t&&t[Kp]===Qp}}class og extends tg{constructor(t,e,n){super(t,"fallback",e),xn(this,"payable"),Object.defineProperty(this,Kp,{value:Jp}),Ho(this,{payable:n})}format(t){const e=0===this.inputs.length?"receive":"fallback";if("json"===t){const t=this.payable?"payable":"nonpayable";return JSON.stringify({type:e,stateMutability:t})}return`${e}()${this.payable?" payable":""}`}static from(t){if(og.isFragment(t))return t;if("string"==typeof t)try{return og.from(Dp(t))}catch(e){$o(!1,"invalid fallback fragment","obj",t)}else if(t instanceof Pp){const e=t.toString();$o(t.peekKeyword(yp(["fallback","receive"])),"type must be fallback or receive","obj",e);if("receive"===t.popKeyword(yp(["fallback","receive"]))){const e=Fp(t);return $o(0===e.length,"receive cannot have arguments","obj.inputs",e),Lp(t,yp(["payable"])),jp(t),new og(Wp,[],!0)}let n=Fp(t);n.length?$o(1===n.length&&"bytes"===n[0].type,"invalid fallback inputs","obj.inputs",n.map((t=>t.format("minimal"))).join(", ")):n=[Xp.from("bytes")];const r=Mp(t);if($o("nonpayable"===r||"payable"===r,"fallback cannot be constants","obj.stateMutability",r),Lp(t,yp(["returns"])).has("returns")){const e=Fp(t);$o(1===e.length&&"bytes"===e[0].type,"invalid fallback outputs","obj.outputs",e.map((t=>t.format("minimal"))).join(", "))}return jp(t),new og(Wp,n,"payable"===r)}if("receive"===t.type)return new og(Wp,[],!0);if("fallback"===t.type){const e=[Xp.from("bytes")],n="payable"===t.stateMutability;return new og(Wp,e,n)}$o(!1,"invalid fallback description","obj",t)}static isFragment(t){return t&&t[Kp]===Jp}}class ag extends eg{constructor(t,e,n,r,s,i){super(t,"function",e,r),xn(this,"constant"),xn(this,"outputs"),xn(this,"stateMutability"),xn(this,"payable"),xn(this,"gas"),Object.defineProperty(this,Kp,{value:Yp});Ho(this,{constant:"view"===n||"pure"===n,gas:i,outputs:s=Object.freeze(s.slice()),payable:"payable"===n,stateMutability:n})}get selector(){return Wd(this.format("sighash")).substring(0,10)}format(t){if(null==t&&(t="sighash"),"json"===t)return JSON.stringify({type:"function",name:this.name,constant:this.constant,stateMutability:"nonpayable"!==this.stateMutability?this.stateMutability:void 0,payable:this.payable,gas:null!=this.gas?this.gas:void 0,inputs:this.inputs.map((e=>JSON.parse(e.format(t)))),outputs:this.outputs.map((e=>JSON.parse(e.format(t))))});const e=[];return"sighash"!==t&&e.push("function"),e.push(this.name+ng(t,this.inputs)),"sighash"!==t&&("nonpayable"!==this.stateMutability&&e.push(this.stateMutability),this.outputs&&this.outputs.length&&(e.push("returns"),e.push(ng(t,this.outputs))),null!=this.gas&&e.push(`@${this.gas.toString()}`)),e.join(" ")}static getSelector(t,e){e=(e||[]).map((t=>Xp.from(t)));return new ag(Wp,t,"view",e,[],null).selector}static from(t){if(ag.isFragment(t))return t;if("string"==typeof t)try{return ag.from(Dp(t))}catch(n){$o(!1,"invalid function fragment","obj",t)}else if(t instanceof Pp){const e=Up("function",t),n=Fp(t),r=Mp(t);let s=[];Lp(t,yp(["returns"])).has("returns")&&(s=Fp(t));const i=Gp(t);return jp(t),new ag(Wp,e,r,n,s,i)}let e=t.stateMutability;return null==e&&(e="payable","boolean"==typeof t.constant?(e="view",t.constant||(e="payable","boolean"!=typeof t.payable||t.payable||(e="nonpayable"))):"boolean"!=typeof t.payable||t.payable||(e="nonpayable")),new ag(Wp,t.name,e,t.inputs?t.inputs.map(Xp.from):[],t.outputs?t.outputs.map(Xp.from):[],null!=t.gas?t.gas:null)}static isFragment(t){return t&&t[Kp]===Yp}}class cg extends eg{constructor(t,e,n){super(t,"struct",e,n),Object.defineProperty(this,Kp,{value:Zp})}format(){throw new Error("@TODO")}static from(t){if("string"==typeof t)try{return cg.from(Dp(t))}catch(e){$o(!1,"invalid struct fragment","obj",t)}else if(t instanceof Pp){const e=Up("struct",t),n=Fp(t);return jp(t),new cg(Wp,e,n)}return new cg(Wp,t.name,t.inputs?t.inputs.map(Xp.from):[])}static isFragment(t){return t&&t[Kp]===Zp}}const lg=new Map;lg.set(0,"GENERIC_PANIC"),lg.set(1,"ASSERT_FALSE"),lg.set(17,"OVERFLOW"),lg.set(18,"DIVIDE_BY_ZERO"),lg.set(33,"ENUM_RANGE_ERROR"),lg.set(34,"BAD_STORAGE_DATA"),lg.set(49,"STACK_UNDERFLOW"),lg.set(50,"ARRAY_RANGE_ERROR"),lg.set(65,"OUT_OF_MEMORY"),lg.set(81,"UNINITIALIZED_FUNCTION_CALL");const ug=new RegExp(/^bytes([0-9]*)$/),hg=new RegExp(/^(u?int)([0-9]*)$/);let dg=null,fg=1024;Et=new WeakSet,kt=function(t){if(t.isArray())return new ad(Ln(this,Et,kt).call(this,t.arrayChildren),t.arrayLength,t.name);if(t.isTuple())return new bd(t.components.map((t=>Ln(this,Et,kt).call(this,t))),t.name);switch(t.baseType){case"address":return new rd(t.name);case"bool":return new cd(t.name);case"string":return new wd(t.name);case"bytes":return new ud(t.name);case"":return new fd(t.name)}let e=t.type.match(hg);if(e){let n=parseInt(e[2]||"256");return $o(0!==n&&n<=256&&n%8==0,"invalid "+e[1]+" bit length","param",t),new yd(n/8,"int"===e[1],t.name)}if(e=t.type.match(ug),e){let n=parseInt(e[1]);return $o(0!==n&&n<=32,"invalid bytes length","param",t),new hd(n,t.name)}$o(!1,"invalid type","type",t.type)};let pg=class t{constructor(){Dn(this,Et)}getDefaultValue(t){const e=t.map((t=>Ln(this,Et,kt).call(this,Xp.from(t))));return new bd(e,"_").defaultValue()}encode(t,e){Qo(e.length,t.length,"types/values length mismatch");const n=t.map((t=>Ln(this,Et,kt).call(this,Xp.from(t)))),r=new bd(n,"_"),s=new Ac;return r.encode(s,e),s.data}decode(t,e,n){const r=t.map((t=>Ln(this,Et,kt).call(this,Xp.from(t))));return new bd(r,"_").decode(new _c(e,n,fg))}static _setDefaultMaxInflation(t){$o("number"==typeof t&&Number.isInteger(t),"invalid defaultMaxInflation factor","value",t),fg=t}static defaultAbiCoder(){return null==dg&&(dg=new t),dg}static getBuiltinCallException(e,n,r){return function(t,e,n,r){let s="missing revert data",i=null,o=null;if(n){s="execution reverted";const t=ta(n);if(n=ia(n),0===t.length)s+=" (no data present; likely require(false) occurred",i="require(false)";else if(t.length%32!=4)s+=" (could not decode reason; invalid data length)";else if("0x08c379a0"===ia(t.slice(0,4)))try{i=r.decode(["string"],t.slice(4))[0],o={signature:"Error(string)",name:"Error",args:[i]},s+=`: ${JSON.stringify(i)}`}catch(c){s+=" (could not decode reason; invalid string data)"}else if("0x4e487b71"===ia(t.slice(0,4)))try{const e=Number(r.decode(["uint256"],t.slice(4))[0]);o={signature:"Panic(uint256)",name:"Panic",args:[e]},i=`Panic due to ${lg.get(e)||"UNKNOWN"}(${e})`,s+=`: ${i}`}catch(c){s+=" (could not decode panic code)"}else s+=" (unknown custom error)"}const a={to:e.to?$h(e.to):null,data:e.data||"0x"};return e.from&&(a.from=$h(e.from)),zo(s,"CALL_EXCEPTION",{action:t,data:n,reason:i,transaction:a,invocation:null,revert:o})}(e,n,r,t.defaultAbiCoder())}};class gg{constructor(t,e,n){xn(this,"fragment"),xn(this,"name"),xn(this,"signature"),xn(this,"topic"),xn(this,"args");const r=t.name,s=t.format();Ho(this,{fragment:t,name:r,signature:s,topic:e,args:n})}}class mg{constructor(t,e,n,r){xn(this,"fragment"),xn(this,"name"),xn(this,"args"),xn(this,"signature"),xn(this,"selector"),xn(this,"value");const s=t.name,i=t.format();Ho(this,{fragment:t,name:s,args:n,signature:i,selector:e,value:r})}}class yg{constructor(t,e,n){xn(this,"fragment"),xn(this,"name"),xn(this,"args"),xn(this,"signature"),xn(this,"selector");const r=t.name,s=t.format();Ho(this,{fragment:t,name:r,args:n,signature:s,selector:e})}}class wg{constructor(t){xn(this,"hash"),xn(this,"_isIndexed"),Ho(this,{hash:t,_isIndexed:!0})}static isIndexed(t){return!(!t||!t._isIndexed)}}const bg={0:"generic panic",1:"assert(false)",17:"arithmetic overflow",18:"division or modulo by zero",33:"enum overflow",34:"invalid encoded storage byte array accessed",49:"out-of-bounds array access; popping on an empty array",50:"out-of-bounds access of an array or bytesN",65:"out of memory",81:"uninitialized function"},Ag={"0x08c379a0":{signature:"Error(string)",name:"Error",inputs:["string"],reason:t=>`reverted with reason string ${JSON.stringify(t)}`},"0x4e487b71":{signature:"Panic(uint256)",name:"Panic",inputs:["uint256"],reason:t=>{let e="unknown panic code";return t>=0&&t<=255&&bg[t.toString()]&&(e=bg[t.toString()]),`reverted with panic code 0x${t.toString(16)} (${e})`}}};St=new WeakMap,Tt=new WeakMap,Rt=new WeakMap,It=new WeakMap,Ot=new WeakSet,Ct=function(t,e,n){if(na(t)){const e=t.toLowerCase();for(const t of Pn(this,Rt).values())if(e===t.selector)return t;return null}if(-1===t.indexOf("(")){const r=[];for(const[e,n]of Pn(this,Rt))e.split("(")[0]===t&&r.push(n);if(e){const t=e.length>0?e[e.length-1]:null;let n=e.length,s=!0;nd.isTyped(t)&&"overrides"===t.type&&(s=!1,n--);for(let e=r.length-1;e>=0;e--){const t=r[e].inputs.length;t===n||s&&t===n-1||r.splice(e,1)}for(let i=r.length-1;i>=0;i--){const t=r[i].inputs;for(let n=0;n<e.length;n++)if(nd.isTyped(e[n])){if(n>=t.length){if("overrides"===e[n].type)continue;r.splice(i,1);break}if(e[n].type!==t[n].baseType){r.splice(i,1);break}}}}if(1===r.length&&e&&e.length!==r[0].inputs.length){const t=e[e.length-1];(null==t||Array.isArray(t)||"object"!=typeof t)&&r.splice(0,1)}if(0===r.length)return null;if(r.length>1&&n){$o(!1,`ambiguous function description (i.e. matches ${r.map((t=>JSON.stringify(t.format()))).join(", ")})`,"key",t)}return r[0]}const r=Pn(this,Rt).get(ag.from(t).format());return r||null},xt=new WeakSet,Nt=function(t,e,n){if(na(t)){const e=t.toLowerCase();for(const t of Pn(this,Tt).values())if(e===t.topicHash)return t;return null}if(-1===t.indexOf("(")){const r=[];for(const[e,n]of Pn(this,Tt))e.split("(")[0]===t&&r.push(n);if(e){for(let t=r.length-1;t>=0;t--)r[t].inputs.length<e.length&&r.splice(t,1);for(let t=r.length-1;t>=0;t--){const n=r[t].inputs;for(let s=0;s<e.length;s++)if(nd.isTyped(e[s])&&e[s].type!==n[s].baseType){r.splice(t,1);break}}}if(0===r.length)return null;if(r.length>1&&n){$o(!1,`ambiguous event description (i.e. matches ${r.map((t=>JSON.stringify(t.format()))).join(", ")})`,"key",t)}return r[0]}const r=Pn(this,Tt).get(sg.from(t).format());return r||null};let _g=class t{constructor(t){Dn(this,Ot),Dn(this,xt),xn(this,"fragments"),xn(this,"deploy"),xn(this,"fallback"),xn(this,"receive"),Dn(this,St,void 0),Dn(this,Tt,void 0),Dn(this,Rt,void 0),Dn(this,It,void 0);let e=[];e="string"==typeof t?JSON.parse(t):t,Bn(this,Rt,new Map),Bn(this,St,new Map),Bn(this,Tt,new Map);const n=[];for(const o of e)try{n.push(tg.from(o))}catch(i){console.log(`[Warning] Invalid Fragment ${JSON.stringify(o)}:`,i.message)}Ho(this,{fragments:Object.freeze(n)});let r=null,s=!1;Bn(this,It,this.getAbiCoder()),this.fragments.forEach(((t,e)=>{let n;switch(t.type){case"constructor":return this.deploy?void console.log("duplicate definition - constructor"):void Ho(this,{deploy:t});case"fallback":return void(0===t.inputs.length?s=!0:($o(!r||t.payable!==r.payable,"conflicting fallback fragments",`fragments[${e}]`,t),r=t,s=r.payable));case"function":n=Pn(this,Rt);break;case"event":n=Pn(this,Tt);break;case"error":n=Pn(this,St);break;default:return}const i=t.format();n.has(i)||n.set(i,t)})),this.deploy||Ho(this,{deploy:ig.from("constructor()")}),Ho(this,{fallback:r,receive:s})}format(t){const e=t?"minimal":"full";return this.fragments.map((t=>t.format(e)))}formatJson(){const t=this.fragments.map((t=>t.format("json")));return JSON.stringify(t.map((t=>JSON.parse(t))))}getAbiCoder(){return pg.defaultAbiCoder()}getFunctionName(t){const e=Ln(this,Ot,Ct).call(this,t,null,!1);return $o(e,"no matching function","key",t),e.name}hasFunction(t){return!!Ln(this,Ot,Ct).call(this,t,null,!1)}getFunction(t,e){return Ln(this,Ot,Ct).call(this,t,e||null,!0)}forEachFunction(t){const e=Array.from(Pn(this,Rt).keys());e.sort(((t,e)=>t.localeCompare(e)));for(let n=0;n<e.length;n++){const r=e[n];t(Pn(this,Rt).get(r),n)}}getEventName(t){const e=Ln(this,xt,Nt).call(this,t,null,!1);return $o(e,"no matching event","key",t),e.name}hasEvent(t){return!!Ln(this,xt,Nt).call(this,t,null,!1)}getEvent(t,e){return Ln(this,xt,Nt).call(this,t,e||null,!0)}forEachEvent(t){const e=Array.from(Pn(this,Tt).keys());e.sort(((t,e)=>t.localeCompare(e)));for(let n=0;n<e.length;n++){const r=e[n];t(Pn(this,Tt).get(r),n)}}getError(t,e){if(na(t)){const e=t.toLowerCase();if(Ag[e])return rg.from(Ag[e].signature);for(const t of Pn(this,St).values())if(e===t.selector)return t;return null}if(-1===t.indexOf("(")){const e=[];for(const[n,r]of Pn(this,St))n.split("(")[0]===t&&e.push(r);if(0===e.length)return"Error"===t?rg.from("error Error(string)"):"Panic"===t?rg.from("error Panic(uint256)"):null;if(e.length>1){$o(!1,`ambiguous error description (i.e. ${e.map((t=>JSON.stringify(t.format()))).join(", ")})`,"name",t)}return e[0]}if("Error(string)"===(t=rg.from(t).format()))return rg.from("error Error(string)");if("Panic(uint256)"===t)return rg.from("error Panic(uint256)");const n=Pn(this,St).get(t);return n||null}forEachError(t){const e=Array.from(Pn(this,St).keys());e.sort(((t,e)=>t.localeCompare(e)));for(let n=0;n<e.length;n++){const r=e[n];t(Pn(this,St).get(r),n)}}_decodeParams(t,e){return Pn(this,It).decode(t,e)}_encodeParams(t,e){return Pn(this,It).encode(t,e)}encodeDeploy(t){return this._encodeParams(this.deploy.inputs,t||[])}decodeErrorResult(t,e){if("string"==typeof t){const e=this.getError(t);$o(e,"unknown error","fragment",t),t=e}return $o(ca(e,0,4)===t.selector,`data signature does not match error ${t.name}.`,"data",e),this._decodeParams(t.inputs,ca(e,4))}encodeErrorResult(t,e){if("string"==typeof t){const e=this.getError(t);$o(e,"unknown error","fragment",t),t=e}return oa([t.selector,this._encodeParams(t.inputs,e||[])])}decodeFunctionData(t,e){if("string"==typeof t){const e=this.getFunction(t);$o(e,"unknown function","fragment",t),t=e}return $o(ca(e,0,4)===t.selector,`data signature does not match function ${t.name}.`,"data",e),this._decodeParams(t.inputs,ca(e,4))}encodeFunctionData(t,e){if("string"==typeof t){const e=this.getFunction(t);$o(e,"unknown function","fragment",t),t=e}return oa([t.selector,this._encodeParams(t.inputs,e||[])])}decodeFunctionResult(t,e){if("string"==typeof t){const e=this.getFunction(t);$o(e,"unknown function","fragment",t),t=e}let n="invalid length for result data";const r=ea(e);if(r.length%32==0)try{return Pn(this,It).decode(t.outputs,r)}catch(s){n="could not decode result data"}qo(!1,n,"BAD_DATA",{value:ia(r),info:{method:t.name,signature:t.format()}})}makeError(t,e){const n=ta(t,"data"),r=pg.getBuiltinCallException("call",e,n);if(r.message.startsWith("execution reverted (unknown custom error)")){const t=ia(n.slice(0,4)),e=this.getError(t);if(e)try{const t=Pn(this,It).decode(e.inputs,n.slice(4));r.revert={name:e.name,signature:e.format(),args:t},r.reason=r.revert.signature,r.message=`execution reverted: ${r.reason}`}catch(i){r.message="execution reverted (coult not decode custom error)"}}const s=this.parseTransaction(e);return s&&(r.invocation={method:s.name,signature:s.signature,args:s.args}),r}encodeFunctionResult(t,e){if("string"==typeof t){const e=this.getFunction(t);$o(e,"unknown function","fragment",t),t=e}return ia(Pn(this,It).encode(t.outputs,e||[]))}encodeFilterTopics(t,e){if("string"==typeof t){const e=this.getEvent(t);$o(e,"unknown event","eventFragment",t),t=e}qo(e.length<=t.inputs.length,`too many arguments for ${t.format()}`,"UNEXPECTED_ARGUMENT",{count:e.length,expectedCount:t.inputs.length});const n=[];t.anonymous||n.push(t.topicHash);const r=(t,e)=>"string"===t.type?Wd(e):"bytes"===t.type?Bl(ia(e)):("bool"===t.type&&"boolean"==typeof e?e=e?"0x01":"0x00":t.type.match(/^u?int/)?e=va(e):t.type.match(/^bytes/)?e=ha(e,32):"address"===t.type&&Pn(this,It).encode(["address"],[e]),ua(ia(e),32));for(e.forEach(((e,s)=>{const i=t.inputs[s];i.indexed?null==e?n.push(null):"array"===i.baseType||"tuple"===i.baseType?$o(!1,"filtering with tuples or arrays not supported","contract."+i.name,e):Array.isArray(e)?n.push(e.map((t=>r(i,t)))):n.push(r(i,e)):$o(null==e,"cannot filter non-indexed parameters; must be null","contract."+i.name,e)}));n.length&&null===n[n.length-1];)n.pop();return n}encodeEventLog(t,e){if("string"==typeof t){const e=this.getEvent(t);$o(e,"unknown event","eventFragment",t),t=e}const n=[],r=[],s=[];return t.anonymous||n.push(t.topicHash),$o(e.length===t.inputs.length,"event arguments/values mismatch","values",e),t.inputs.forEach(((t,i)=>{const o=e[i];if(t.indexed)if("string"===t.type)n.push(Wd(o));else if("bytes"===t.type)n.push(Bl(o));else{if("tuple"===t.baseType||"array"===t.baseType)throw new Error("not implemented");n.push(Pn(this,It).encode([t.type],[o]))}else r.push(t),s.push(o)})),{data:Pn(this,It).encode(r,s),topics:n}}decodeEventLog(t,e,n){if("string"==typeof t){const e=this.getEvent(t);$o(e,"unknown event","eventFragment",t),t=e}if(null!=n&&!t.anonymous){const e=t.topicHash;$o(na(n[0],32)&&n[0].toLowerCase()===e,"fragment/topic mismatch","topics[0]",n[0]),n=n.slice(1)}const r=[],s=[],i=[];t.inputs.forEach(((t,e)=>{t.indexed?"string"===t.type||"bytes"===t.type||"tuple"===t.baseType||"array"===t.baseType?(r.push(Xp.from({type:"bytes32",name:t.name})),i.push(!0)):(r.push(t),i.push(!1)):(s.push(t),i.push(!1))}));const o=null!=n?Pn(this,It).decode(r,oa(n)):null,a=Pn(this,It).decode(s,e,!0),c=[],l=[];let u=0,h=0;return t.inputs.forEach(((t,e)=>{let n=null;if(t.indexed)if(null==o)n=new wg(null);else if(i[e])n=new wg(o[h++]);else try{n=o[h++]}catch(r){n=r}else try{n=a[u++]}catch(r){n=r}c.push(n),l.push(t.name||null)})),yc.fromItems(c,l)}parseTransaction(t){const e=ta(t.data,"tx.data"),n=ya(null!=t.value?t.value:0,"tx.value"),r=this.getFunction(ia(e.slice(0,4)));if(!r)return null;const s=Pn(this,It).decode(r.inputs,e.slice(4));return new mg(r,r.selector,s,n)}parseCallResult(t){throw new Error("@TODO")}parseLog(t){const e=this.getEvent(t.topics[0]);return!e||e.anonymous?null:new gg(e,e.topicHash,this.decodeEventLog(e,t.data,t.topics))}parseError(t){const e=ia(t),n=this.getError(ca(e,0,4));if(!n)return null;const r=Pn(this,It).decode(n.inputs,ca(e,4));return new yg(n,n.selector,r)}static from(e){return e instanceof t?e:"string"==typeof e?new t(JSON.parse(e)):"function"==typeof e.formatJson?new t(e.formatJson()):"function"==typeof e.format?new t(e.format("json")):new t(e)}};const vg=BigInt(0);function Eg(t){return null==t?null:t}function kg(t){return null==t?null:t.toString()}class Sg{constructor(t,e,n){xn(this,"gasPrice"),xn(this,"maxFeePerGas"),xn(this,"maxPriorityFeePerGas"),Ho(this,{gasPrice:Eg(t),maxFeePerGas:Eg(e),maxPriorityFeePerGas:Eg(n)})}toJSON(){const{gasPrice:t,maxFeePerGas:e,maxPriorityFeePerGas:n}=this;return{_type:"FeeData",gasPrice:kg(t),maxFeePerGas:kg(e),maxPriorityFeePerGas:kg(n)}}}function Tg(t){const e={};t.to&&(e.to=t.to),t.from&&(e.from=t.from),t.data&&(e.data=ia(t.data));const n="chainId,gasLimit,gasPrice,maxFeePerBlobGas,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/);for(const s of n)s in t&&null!=t[s]&&(e[s]=ya(t[s],`request.${s}`));const r="type,nonce".split(/,/);for(const s of r)s in t&&null!=t[s]&&(e[s]=_a(t[s],`request.${s}`));return t.accessList&&(e.accessList=_d(t.accessList)),t.authorizationList&&(e.authorizationList=t.authorizationList.slice()),"blockTag"in t&&(e.blockTag=t.blockTag),"enableCcipRead"in t&&(e.enableCcipRead=!!t.enableCcipRead),"customData"in t&&(e.customData=t.customData),"blobVersionedHashes"in t&&t.blobVersionedHashes&&(e.blobVersionedHashes=t.blobVersionedHashes.slice()),"kzg"in t&&(e.kzg=t.kzg),"blobWrapperVersion"in t&&(e.blobWrapperVersion=t.blobWrapperVersion),"blobs"in t&&t.blobs&&(e.blobs=t.blobs.map((t=>ra(t)?ia(t):Object.assign({},t)))),e}class Rg{constructor(t,e){xn(this,"provider"),xn(this,"number"),xn(this,"hash"),xn(this,"timestamp"),xn(this,"parentHash"),xn(this,"parentBeaconBlockRoot"),xn(this,"nonce"),xn(this,"difficulty"),xn(this,"gasLimit"),xn(this,"gasUsed"),xn(this,"stateRoot"),xn(this,"receiptsRoot"),xn(this,"transactionsRoot"),xn(this,"blobGasUsed"),xn(this,"excessBlobGas"),xn(this,"miner"),xn(this,"prevRandao"),xn(this,"extraData"),xn(this,"baseFeePerGas"),Dn(this,Pt,void 0),Bn(this,Pt,t.transactions.map((t=>"string"!=typeof t?new Cg(t,e):t))),Ho(this,{provider:e,hash:Eg(t.hash),number:t.number,timestamp:t.timestamp,parentHash:t.parentHash,parentBeaconBlockRoot:t.parentBeaconBlockRoot,nonce:t.nonce,difficulty:t.difficulty,gasLimit:t.gasLimit,gasUsed:t.gasUsed,blobGasUsed:t.blobGasUsed,excessBlobGas:t.excessBlobGas,miner:t.miner,prevRandao:Eg(t.prevRandao),extraData:t.extraData,baseFeePerGas:Eg(t.baseFeePerGas),stateRoot:t.stateRoot,receiptsRoot:t.receiptsRoot,transactionsRoot:t.transactionsRoot})}get transactions(){return Pn(this,Pt).map((t=>"string"==typeof t?t:t.hash))}get prefetchedTransactions(){const t=Pn(this,Pt).slice();return 0===t.length?[]:(qo("object"==typeof t[0],"transactions were not prefetched with block request","UNSUPPORTED_OPERATION",{operation:"transactionResponses()"}),t)}toJSON(){const{baseFeePerGas:t,difficulty:e,extraData:n,gasLimit:r,gasUsed:s,hash:i,miner:o,prevRandao:a,nonce:c,number:l,parentHash:u,parentBeaconBlockRoot:h,stateRoot:d,receiptsRoot:f,transactionsRoot:p,timestamp:g,transactions:m}=this;return{_type:"Block",baseFeePerGas:kg(t),difficulty:kg(e),extraData:n,gasLimit:kg(r),gasUsed:kg(s),blobGasUsed:kg(this.blobGasUsed),excessBlobGas:kg(this.excessBlobGas),hash:i,miner:o,prevRandao:a,nonce:c,number:l,parentHash:u,timestamp:g,parentBeaconBlockRoot:h,stateRoot:d,receiptsRoot:f,transactionsRoot:p,transactions:m}}[Symbol.iterator](){let t=0;const e=this.transactions;return{next:()=>t<this.length?{value:e[t++],done:!1}:{value:void 0,done:!0}}}get length(){return Pn(this,Pt).length}get date(){return null==this.timestamp?null:new Date(1e3*this.timestamp)}async getTransaction(t){let e;if("number"==typeof t)e=Pn(this,Pt)[t];else{const n=t.toLowerCase();for(const t of Pn(this,Pt)){if("string"==typeof t){if(t!==n)continue;e=t;break}if(t.hash===n){e=t;break}}}if(null==e)throw new Error("no such tx");return"string"==typeof e?await this.provider.getTransaction(e):e}getPrefetchedTransaction(t){const e=this.prefetchedTransactions;if("number"==typeof t)return e[t];t=t.toLowerCase();for(const n of e)if(n.hash===t)return n;$o(!1,"no matching transaction","indexOrHash",t)}isMined(){return!!this.hash}isLondon(){return!!this.baseFeePerGas}orphanedEvent(){if(!this.isMined())throw new Error("");return{orphan:"drop-block",hash:(t=this).hash,number:t.number};var t}}Pt=new WeakMap;class Ig{constructor(t,e){xn(this,"provider"),xn(this,"transactionHash"),xn(this,"blockHash"),xn(this,"blockNumber"),xn(this,"removed"),xn(this,"address"),xn(this,"data"),xn(this,"topics"),xn(this,"index"),xn(this,"transactionIndex"),this.provider=e;const n=Object.freeze(t.topics.slice());Ho(this,{transactionHash:t.transactionHash,blockHash:t.blockHash,blockNumber:t.blockNumber,removed:t.removed,address:t.address,data:t.data,topics:n,index:t.index,transactionIndex:t.transactionIndex})}toJSON(){const{address:t,blockHash:e,blockNumber:n,data:r,index:s,removed:i,topics:o,transactionHash:a,transactionIndex:c}=this;return{_type:"log",address:t,blockHash:e,blockNumber:n,data:r,index:s,removed:i,topics:o,transactionHash:a,transactionIndex:c}}async getBlock(){const t=await this.provider.getBlock(this.blockHash);return qo(!!t,"failed to find transaction","UNKNOWN_ERROR",{}),t}async getTransaction(){const t=await this.provider.getTransaction(this.transactionHash);return qo(!!t,"failed to find transaction","UNKNOWN_ERROR",{}),t}async getTransactionReceipt(){const t=await this.provider.getTransactionReceipt(this.transactionHash);return qo(!!t,"failed to find transaction receipt","UNKNOWN_ERROR",{}),t}removedEvent(){return{orphan:"drop-log",log:{transactionHash:(t=this).transactionHash,blockHash:t.blockHash,blockNumber:t.blockNumber,address:t.address,data:t.data,topics:Object.freeze(t.topics.slice()),index:t.index}};var t}}class Og{constructor(t,e){xn(this,"provider"),xn(this,"to"),xn(this,"from"),xn(this,"contractAddress"),xn(this,"hash"),xn(this,"index"),xn(this,"blockHash"),xn(this,"blockNumber"),xn(this,"logsBloom"),xn(this,"gasUsed"),xn(this,"blobGasUsed"),xn(this,"cumulativeGasUsed"),xn(this,"gasPrice"),xn(this,"blobGasPrice"),xn(this,"type"),xn(this,"status"),xn(this,"root"),Dn(this,Dt,void 0),Bn(this,Dt,Object.freeze(t.logs.map((t=>new Ig(t,e)))));let n=vg;null!=t.effectiveGasPrice?n=t.effectiveGasPrice:null!=t.gasPrice&&(n=t.gasPrice),Ho(this,{provider:e,to:t.to,from:t.from,contractAddress:t.contractAddress,hash:t.hash,index:t.index,blockHash:t.blockHash,blockNumber:t.blockNumber,logsBloom:t.logsBloom,gasUsed:t.gasUsed,cumulativeGasUsed:t.cumulativeGasUsed,blobGasUsed:t.blobGasUsed,gasPrice:n,blobGasPrice:t.blobGasPrice,type:t.type,status:t.status,root:t.root})}get logs(){return Pn(this,Dt)}toJSON(){const{to:t,from:e,contractAddress:n,hash:r,index:s,blockHash:i,blockNumber:o,logsBloom:a,logs:c,status:l,root:u}=this;return{_type:"TransactionReceipt",blockHash:i,blockNumber:o,contractAddress:n,cumulativeGasUsed:kg(this.cumulativeGasUsed),from:e,gasPrice:kg(this.gasPrice),blobGasUsed:kg(this.blobGasUsed),blobGasPrice:kg(this.blobGasPrice),gasUsed:kg(this.gasUsed),hash:r,index:s,logs:c,logsBloom:a,root:u,status:l,to:t}}get length(){return this.logs.length}[Symbol.iterator](){let t=0;return{next:()=>t<this.length?{value:this.logs[t++],done:!1}:{value:void 0,done:!0}}}get fee(){return this.gasUsed*this.gasPrice}async getBlock(){const t=await this.provider.getBlock(this.blockHash);if(null==t)throw new Error("TODO");return t}async getTransaction(){const t=await this.provider.getTransaction(this.hash);if(null==t)throw new Error("TODO");return t}async getResult(){return await this.provider.getTransactionResult(this.hash)}async confirmations(){return await this.provider.getBlockNumber()-this.blockNumber+1}removedEvent(){return Ng(this)}reorderedEvent(t){return qo(!t||t.isMined(),"unmined 'other' transction cannot be orphaned","UNSUPPORTED_OPERATION",{operation:"reorderedEvent(other)"}),xg(this,t)}}Dt=new WeakMap;Bt=new WeakMap;let Cg=class t{constructor(t,e){xn(this,"provider"),xn(this,"blockNumber"),xn(this,"blockHash"),xn(this,"index"),xn(this,"hash"),xn(this,"type"),xn(this,"to"),xn(this,"from"),xn(this,"nonce"),xn(this,"gasLimit"),xn(this,"gasPrice"),xn(this,"maxPriorityFeePerGas"),xn(this,"maxFeePerGas"),xn(this,"maxFeePerBlobGas"),xn(this,"data"),xn(this,"value"),xn(this,"chainId"),xn(this,"signature"),xn(this,"accessList"),xn(this,"blobVersionedHashes"),xn(this,"authorizationList"),Dn(this,Bt,void 0),this.provider=e,this.blockNumber=null!=t.blockNumber?t.blockNumber:null,this.blockHash=null!=t.blockHash?t.blockHash:null,this.hash=t.hash,this.index=t.index,this.type=t.type,this.from=t.from,this.to=t.to||null,this.gasLimit=t.gasLimit,this.nonce=t.nonce,this.data=t.data,this.value=t.value,this.gasPrice=t.gasPrice,this.maxPriorityFeePerGas=null!=t.maxPriorityFeePerGas?t.maxPriorityFeePerGas:null,this.maxFeePerGas=null!=t.maxFeePerGas?t.maxFeePerGas:null,this.maxFeePerBlobGas=null!=t.maxFeePerBlobGas?t.maxFeePerBlobGas:null,this.chainId=t.chainId,this.signature=t.signature,this.accessList=null!=t.accessList?t.accessList:null,this.blobVersionedHashes=null!=t.blobVersionedHashes?t.blobVersionedHashes:null,this.authorizationList=null!=t.authorizationList?t.authorizationList:null,Bn(this,Bt,-1)}toJSON(){const{blockNumber:t,blockHash:e,index:n,hash:r,type:s,to:i,from:o,nonce:a,data:c,signature:l,accessList:u,blobVersionedHashes:h}=this;return{_type:"TransactionResponse",accessList:u,blockNumber:t,blockHash:e,blobVersionedHashes:h,chainId:kg(this.chainId),data:c,from:o,gasLimit:kg(this.gasLimit),gasPrice:kg(this.gasPrice),hash:r,maxFeePerGas:kg(this.maxFeePerGas),maxPriorityFeePerGas:kg(this.maxPriorityFeePerGas),maxFeePerBlobGas:kg(this.maxFeePerBlobGas),nonce:a,signature:l,to:i,index:n,type:s,value:kg(this.value)}}async getBlock(){let t=this.blockNumber;if(null==t){const e=await this.getTransaction();e&&(t=e.blockNumber)}if(null==t)return null;const e=this.provider.getBlock(t);if(null==e)throw new Error("TODO");return e}async getTransaction(){return this.provider.getTransaction(this.hash)}async confirmations(){if(null==this.blockNumber){const{tx:t,blockNumber:e}=await jo({tx:this.getTransaction(),blockNumber:this.provider.getBlockNumber()});return null==t||null==t.blockNumber?0:e-t.blockNumber+1}return await this.provider.getBlockNumber()-this.blockNumber+1}async wait(t,e){const n=null==t?1:t,r=null==e?0:e;let s=Pn(this,Bt),i=-1,o=-1===s;const a=async()=>{if(o)return null;const{blockNumber:t,nonce:e}=await jo({blockNumber:this.provider.getBlockNumber(),nonce:this.provider.getTransactionCount(this.from)});if(e<this.nonce)return void(s=t);if(o)return null;const r=await this.getTransaction();if(!r||null==r.blockNumber)for(-1===i&&(i=s-3,i<Pn(this,Bt)&&(i=Pn(this,Bt)));i<=t;){if(o)return null;const e=await this.provider.getBlock(i,!0);if(null==e)return;for(const t of e)if(t===this.hash)return;for(let r=0;r<e.length;r++){const i=await e.getTransaction(r);if(i.from===this.from&&i.nonce===this.nonce){if(o)return null;const e=await this.provider.getTransactionReceipt(i.hash);if(null==e)return;if(t-e.blockNumber+1<n)return;let r="replaced";i.data===this.data&&i.to===this.to&&i.value===this.value?r="repriced":"0x"===i.data&&i.from===i.to&&i.value===vg&&(r="cancelled"),qo(!1,"transaction was replaced","TRANSACTION_REPLACED",{cancelled:"replaced"===r||"cancelled"===r,reason:r,replacement:i.replaceableTransaction(s),hash:i.hash,receipt:e})}}i++}},c=t=>{if(null==t||0!==t.status)return t;qo(!1,"transaction execution reverted","CALL_EXCEPTION",{action:"sendTransaction",data:null,reason:null,invocation:null,revert:null,transaction:{to:t.to,from:t.from,data:""},receipt:t})},l=await this.provider.getTransactionReceipt(this.hash);if(0===n)return c(l);if(l){if(1===n||await l.confirmations()>=n)return c(l)}else if(await a(),0===n)return null;const u=new Promise(((t,e)=>{const i=[],l=()=>{i.forEach((t=>t()))};if(i.push((()=>{o=!0})),r>0){const t=setTimeout((()=>{l(),e(zo("wait for transaction timeout","TIMEOUT"))}),r);i.push((()=>{clearTimeout(t)}))}const u=async r=>{if(await r.confirmations()>=n){l();try{t(c(r))}catch(s){e(s)}}};if(i.push((()=>{this.provider.off(this.hash,u)})),this.provider.on(this.hash,u),s>=0){const t=async()=>{try{await a()}catch(n){if(Wo(n,"TRANSACTION_REPLACED"))return l(),void e(n)}o||this.provider.once("block",t)};i.push((()=>{this.provider.off("block",t)})),this.provider.once("block",t)}}));return await u}isMined(){return null!=this.blockHash}isLegacy(){return 0===this.type}isBerlin(){return 1===this.type}isLondon(){return 2===this.type}isCancun(){return 3===this.type}removedEvent(){return qo(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),Ng(this)}reorderedEvent(t){return qo(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),qo(!t||t.isMined(),"unmined 'other' transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),xg(this,t)}replaceableTransaction(e){$o(Number.isInteger(e)&&e>=0,"invalid startBlock","startBlock",e);const n=new t(this,this.provider);return Bn(n,Bt,e),n}};function xg(t,e){return{orphan:"reorder-transaction",tx:t,other:e}}function Ng(t){return{orphan:"drop-transaction",tx:t}}class Pg extends Ig{constructor(t,e,n){super(t,t.provider),xn(this,"interface"),xn(this,"fragment"),xn(this,"args");Ho(this,{args:e.decodeEventLog(n,t.data,t.topics),fragment:n,interface:e})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}class Dg extends Ig{constructor(t,e){super(t,t.provider),xn(this,"error"),Ho(this,{error:e})}}class Bg extends Og{constructor(t,e,n){super(n,e),Dn(this,Ut,void 0),Bn(this,Ut,t)}get logs(){return super.logs.map((t=>{const e=t.topics.length?Pn(this,Ut).getEvent(t.topics[0]):null;if(e)try{return new Pg(t,Pn(this,Ut),e)}catch(n){return new Dg(t,n)}return t}))}}Ut=new WeakMap;class Ug extends Cg{constructor(t,e,n){super(n,e),Dn(this,Lt,void 0),Bn(this,Lt,t)}async wait(t,e){const n=await super.wait(t,e);return null==n?null:new Bg(Pn(this,Lt),this.provider,n)}}Lt=new WeakMap;class Lg extends xa{constructor(t,e,n,r){super(t,e,n),xn(this,"log"),Ho(this,{log:r})}async getBlock(){return await this.log.getBlock()}async getTransaction(){return await this.log.getTransaction()}async getTransactionReceipt(){return await this.log.getTransactionReceipt()}}class Mg extends Lg{constructor(t,e,n,r,s){super(t,e,n,new Pg(s,t.interface,r));Ho(this,{args:t.interface.decodeEventLog(r,this.log.data,this.log.topics),fragment:r})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}const Fg=BigInt(0);function Gg(t){return t&&"function"==typeof t.call}function jg(t){return t&&"function"==typeof t.estimateGas}function Hg(t){return t&&"function"==typeof t.resolveName}function Vg(t){return t&&"function"==typeof t.sendTransaction}function Wg(t){if(null!=t){if(Hg(t))return t;if(t.provider)return t.provider}}class Kg{constructor(t,e,n){if(Dn(this,Mt,void 0),xn(this,"fragment"),Ho(this,{fragment:e}),e.inputs.length<n.length)throw new Error("too many arguments");const r=zg(t.runner,"resolveName"),s=Hg(r)?r:null;Bn(this,Mt,async function(){const r=await Promise.all(e.inputs.map(((t,e)=>null==n[e]?null:t.walkAsync(n[e],((t,e)=>"address"===t?Array.isArray(e)?Promise.all(e.map((t=>Yh(t,s)))):Yh(e,s):e)))));return t.interface.encodeFilterTopics(e,r)}())}getTopicFilter(){return Pn(this,Mt)}}function zg(t,e){return null==t?null:"function"==typeof t[e]?t:t.provider&&"function"==typeof t.provider[e]?t.provider:null}function qg(t){return null==t?null:t.provider||null}async function $g(t,e){const n=nd.dereference(t,"overrides");$o("object"==typeof n,"invalid overrides parameter","overrides",t);const r=Tg(n);return $o(null==r.to||(e||[]).indexOf("to")>=0,"cannot override to","overrides.to",r.to),$o(null==r.data||(e||[]).indexOf("data")>=0,"cannot override data","overrides.data",r.data),r.from&&(r.from=r.from),r}function Qg(t){const e=async function(e){const n=await $g(e,["data"]);n.to=await t.getAddress(),n.from&&(n.from=await Yh(n.from,Wg(t.runner)));const r=t.interface,s=ya(n.value||Fg,"overrides.value")===Fg,i="0x"===(n.data||"0x");!r.fallback||r.fallback.payable||!r.receive||i||s||$o(!1,"cannot send data to receive or send value to non-payable fallback","overrides",e),$o(r.fallback||i,"cannot send data to receive-only contract","overrides.data",n.data);return $o(r.receive||r.fallback&&r.fallback.payable||s,"cannot send value to non-payable fallback","overrides.value",n.value),$o(r.fallback||i,"cannot send data to receive-only contract","overrides.data",n.data),n},n=async function(n){const r=t.runner;qo(Vg(r),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const s=await r.sendTransaction(await e(n)),i=qg(t.runner);return new Ug(t.interface,i,s)},r=async t=>await n(t);return Ho(r,{_contract:t,estimateGas:async function(n){const r=zg(t.runner,"estimateGas");return qo(jg(r),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await r.estimateGas(await e(n))},populateTransaction:e,send:n,staticCall:async function(n){const r=zg(t.runner,"call");qo(Gg(r),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const s=await e(n);try{return await r.call(s)}catch(i){if(Ko(i)&&i.data)throw t.interface.makeError(i.data,s);throw i}}}),r}function Jg(t,e){const n=function(...n){const r=t.interface.getFunction(e,n);return qo(r,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:e,args:n}}),r},r=async function(...e){const r=n(...e);let s={};if(r.inputs.length+1===e.length&&(s=await $g(e.pop()),s.from&&(s.from=await Yh(s.from,Wg(t.runner)))),r.inputs.length!==e.length)throw new Error("internal error: fragment inputs doesn't match arguments; should not happen");const i=await async function(t,e,n){const r=zg(t,"resolveName"),s=Hg(r)?r:null;return await Promise.all(e.map(((t,e)=>t.walkAsync(n[e],((t,e)=>(e=nd.dereference(e,t),"address"===t?Yh(e,s):e))))))}(t.runner,r.inputs,e);return Object.assign({},s,await jo({to:t.getAddress(),data:t.interface.encodeFunctionData(r,i)}))},s=async function(...t){const e=await o(...t);return 1===e.length?e[0]:e},i=async function(...e){const n=t.runner;qo(Vg(n),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const s=await n.sendTransaction(await r(...e)),i=qg(t.runner);return new Ug(t.interface,i,s)},o=async function(...e){const s=zg(t.runner,"call");qo(Gg(s),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const i=await r(...e);let o="0x";try{o=await s.call(i)}catch(c){if(Ko(c)&&c.data)throw t.interface.makeError(c.data,i);throw c}const a=n(...e);return t.interface.decodeFunctionResult(a,o)},a=async(...t)=>n(...t).constant?await s(...t):await i(...t);return Ho(a,{name:t.interface.getFunctionName(e),_contract:t,_key:e,getFragment:n,estimateGas:async function(...e){const n=zg(t.runner,"estimateGas");return qo(jg(n),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await n.estimateGas(await r(...e))},populateTransaction:r,send:i,staticCall:s,staticCallResult:o}),Object.defineProperty(a,"fragment",{configurable:!1,enumerable:!0,get:()=>{const n=t.interface.getFunction(e);return qo(n,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:e}}),n}}),a}Mt=new WeakMap;const Yg=Symbol.for("_ethersInternal_contract"),Zg=new WeakMap;function Xg(t){return Zg.get(t[Yg])}async function tm(t,e){let n,r=null;if(Array.isArray(e)){const r=function(e){if(na(e,32))return e;const n=t.interface.getEvent(e);return $o(n,"unknown fragment","name",e),n.topicHash};n=e.map((t=>null==t?null:Array.isArray(t)?t.map(r):r(t)))}else"*"===e?n=[null]:"string"==typeof e?na(e,32)?n=[e]:(r=t.interface.getEvent(e),$o(r,"unknown fragment","event",e),n=[r.topicHash]):(s=e)&&"object"==typeof s&&"getTopicFilter"in s&&"function"==typeof s.getTopicFilter&&s.fragment?n=await e.getTopicFilter():"fragment"in e?(r=e.fragment,n=[r.topicHash]):$o(!1,"unknown event name","event",e);var s;n=n.map((t=>{if(null==t)return null;if(Array.isArray(t)){const e=Array.from(new Set(t.map((t=>t.toLowerCase()))).values());return 1===e.length?e[0]:(e.sort(),e)}return t.toLowerCase()}));return{fragment:r,tag:n.map((t=>null==t?"null":Array.isArray(t)?t.join("|"):t)).join("&"),topics:n}}async function em(t,e){const{subs:n}=Xg(t);return n.get((await tm(t,e)).tag)||null}async function nm(t,e,n){const r=qg(t.runner);qo(r,"contract runner does not support subscribing","UNSUPPORTED_OPERATION",{operation:e});const{fragment:s,tag:i,topics:o}=await tm(t,n),{addr:a,subs:c}=Xg(t);let l=c.get(i);if(!l){const e={address:a||t,topics:o},u=e=>{let r=s;if(null==r)try{r=t.interface.getEvent(e.topics[0])}catch(i){}if(r){const i=r,o=s?t.interface.decodeEventLog(s,e.data,e.topics):[];sm(t,n,o,(r=>new Mg(t,r,n,i,e)))}else sm(t,n,[],(r=>new Lg(t,r,n,e)))};let h=[];l={tag:i,listeners:[],start:()=>{h.length||h.push(r.on(e,u))},stop:async()=>{if(0==h.length)return;let t=h;h=[],await Promise.all(t),r.off(e,u)}},c.set(i,l)}return l}let rm=Promise.resolve();async function sm(t,e,n,r){try{await rm}catch(i){}const s=async function(t,e,n,r){await rm;const s=await em(t,e);if(!s)return!1;const o=s.listeners.length;return s.listeners=s.listeners.filter((({listener:e,once:s})=>{const o=Array.from(n);r&&o.push(r(s?null:e));try{e.call(t,...o)}catch(i){}return!s})),0===s.listeners.length&&(s.stop(),Xg(t).subs.delete(s.tag)),o>0}(t,e,n,r);return rm=s,await s}const im=["then"];Ft=Yg;let om=class t{constructor(t,e,n,r){xn(this,"target"),xn(this,"interface"),xn(this,"runner"),xn(this,"filters"),xn(this,Ft),xn(this,"fallback"),$o("string"==typeof t||Qh(t),"invalid value for Contract target","target",t),null==n&&(n=null);const s=_g.from(e);let i;Ho(this,{target:t,runner:n,interface:s}),Object.defineProperty(this,Yg,{value:{}});let o=null,a=null;if(r){const t=qg(n);a=new Ug(this.interface,t,r)}let c=new Map;if("string"==typeof t)if(na(t))o=t,i=Promise.resolve(t);else{const e=zg(n,"resolveName");if(!Hg(e))throw zo("contract runner does not support name resolution","UNSUPPORTED_OPERATION",{operation:"resolveName"});i=e.resolveName(t).then((e=>{if(null==e)throw zo("an ENS name used for a contract target must be correctly configured","UNCONFIGURED_NAME",{value:t});return Xg(this).addr=e,e}))}else i=t.getAddress().then((t=>{if(null==t)throw new Error("TODO");return Xg(this).addr=t,t}));var l,u;l=this,u={addrPromise:i,addr:o,deployTx:a,subs:c},Zg.set(l[Yg],u);return Ho(this,{filters:new Proxy({},{get:(t,e,n)=>{if("symbol"==typeof e||im.indexOf(e)>=0)return Reflect.get(t,e,n);try{return this.getEvent(e)}catch(r){if(!Wo(r,"INVALID_ARGUMENT")||"key"!==r.argument)throw r}},has:(t,e)=>im.indexOf(e)>=0?Reflect.has(t,e):Reflect.has(t,e)||this.interface.hasEvent(String(e))})}),Ho(this,{fallback:s.receive||s.fallback?Qg(this):null}),new Proxy(this,{get:(t,e,n)=>{if("symbol"==typeof e||e in t||im.indexOf(e)>=0)return Reflect.get(t,e,n);try{return t.getFunction(e)}catch(r){if(!Wo(r,"INVALID_ARGUMENT")||"key"!==r.argument)throw r}},has:(t,e)=>"symbol"==typeof e||e in t||im.indexOf(e)>=0?Reflect.has(t,e):t.interface.hasFunction(e)})}connect(e){return new t(this.target,this.interface,e)}attach(e){return new t(e,this.interface,this.runner)}async getAddress(){return await Xg(this).addrPromise}async getDeployedCode(){const t=qg(this.runner);qo(t,"runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"getDeployedCode"});const e=await t.getCode(await this.getAddress());return"0x"===e?null:e}async waitForDeployment(){const t=this.deploymentTransaction();if(t)return await t.wait(),this;if(null!=await this.getDeployedCode())return this;const e=qg(this.runner);return qo(null!=e,"contract runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"waitForDeployment"}),new Promise(((t,n)=>{const r=async()=>{try{if(null!=await this.getDeployedCode())return t(this);e.once("block",r)}catch(s){n(s)}};r()}))}deploymentTransaction(){return Xg(this).deployTx}getFunction(t){"string"!=typeof t&&(t=t.format());return Jg(this,t)}getEvent(t){return"string"!=typeof t&&(t=t.format()),function(t,e){const n=function(...n){const r=t.interface.getEvent(e,n);return qo(r,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:e,args:n}}),r},r=function(...e){return new Kg(t,n(...e),e)};return Ho(r,{name:t.interface.getEventName(e),_contract:t,_key:e,getFragment:n}),Object.defineProperty(r,"fragment",{configurable:!1,enumerable:!0,get:()=>{const n=t.interface.getEvent(e);return qo(n,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:e}}),n}}),r}(this,t)}async queryTransaction(t){throw new Error("@TODO")}async queryFilter(t,e,n){null==e&&(e=0),null==n&&(n="latest");const{addr:r,addrPromise:s}=Xg(this),i=r||await s,{fragment:o,topics:a}=await tm(this,t),c={address:i,topics:a,fromBlock:e,toBlock:n},l=qg(this.runner);return qo(l,"contract runner does not have a provider","UNSUPPORTED_OPERATION",{operation:"queryFilter"}),(await l.getLogs(c)).map((t=>{let e=o;if(null==e)try{e=this.interface.getEvent(t.topics[0])}catch(n){}if(e)try{return new Pg(t,this.interface,e)}catch(n){return new Dg(t,n)}return new Ig(t,l)}))}async on(t,e){const n=await nm(this,"on",t);return n.listeners.push({listener:e,once:!1}),n.start(),this}async once(t,e){const n=await nm(this,"once",t);return n.listeners.push({listener:e,once:!0}),n.start(),this}async emit(t,...e){return await sm(this,t,e,null)}async listenerCount(t){if(t){const e=await em(this,t);return e?e.listeners.length:0}const{subs:e}=Xg(this);let n=0;for(const{listeners:r}of e.values())n+=r.length;return n}async listeners(t){if(t){const e=await em(this,t);return e?e.listeners.map((({listener:t})=>t)):[]}const{subs:e}=Xg(this);let n=[];for(const{listeners:r}of e.values())n=n.concat(r.map((({listener:t})=>t)));return n}async off(t,e){const n=await em(this,t);if(!n)return this;if(e){const t=n.listeners.map((({listener:t})=>t)).indexOf(e);t>=0&&n.listeners.splice(t,1)}return null!=e&&0!==n.listeners.length||(n.stop(),Xg(this).subs.delete(n.tag)),this}async removeAllListeners(t){if(t){const e=await em(this,t);if(!e)return this;e.stop(),Xg(this).subs.delete(e.tag)}else{const{subs:t}=Xg(this);for(const{tag:e,stop:n}of t.values())n(),t.delete(e)}return this}async addListener(t,e){return await this.on(t,e)}async removeListener(t,e){return await this.off(t,e)}static buildClass(e){return class extends t{constructor(t,n=null){super(t,e,n)}}}static from(t,e,n){null==n&&(n=null);return new this(t,e,n)}};class am extends(function(){return om}()){}const cm=BigInt(60);function lm(t){return t.match(/^ipfs:\/\/ipfs\//i)?t=t.substring(12):t.match(/^ipfs:\/\//i)?t=t.substring(7):$o(!1,"unsupported IPFS format","link",t),`https://gateway.ipfs.io/ipfs/${t}`}class um{constructor(t){xn(this,"name"),Ho(this,{name:t})}connect(t){return this}supportsCoinType(t){return!1}async encodeAddress(t,e){throw new Error("unsupported coin")}async decodeAddress(t,e){throw new Error("unsupported coin")}}const hm=new RegExp("^(ipfs)://(.*)$","i"),dm=[new RegExp("^(https)://(.*)$","i"),new RegExp("^(data):(.*)$","i"),hm,new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$","i")];function fm(t){return t===cm||t>=2147483648&&t<=4294967295}const pm=class t{constructor(t,e,n,r){Dn(this,Ht),xn(this,"provider"),xn(this,"address"),xn(this,"name"),Dn(this,Gt,void 0),Dn(this,jt,void 0),Ho(this,{provider:t,address:e,name:n}),Bn(this,Gt,null!=r?Promise.resolve(r):null),Bn(this,jt,new am(e,["function supportsInterface(bytes4) view returns (bool)","function resolve(bytes, bytes) view returns (bytes)","function addr(bytes32) view returns (address)","function addr(bytes32, uint) view returns (bytes)","function text(bytes32, string) view returns (string)","function contenthash(bytes32) view returns (bytes)","function name(bytes32) view returns (string)"],t))}async supportsWildcard(){return null==Pn(this,Gt)&&Bn(this,Gt,(async()=>{try{return await Pn(this,jt).supportsInterface("0x9061b923")}catch(t){if(Wo(t,"CALL_EXCEPTION"))return!1;throw Bn(this,Gt,null),t}})()),await Pn(this,Gt)}async getAddress(t){const e=null==t?cm:ya(t);if(e===cm)try{const t=await Ln(this,Ht,Vt).call(this,"addr(bytes32)");return null==t||t===Ih?null:t}catch(s){if(Wo(s,"CALL_EXCEPTION"))return null;throw s}if(fm(e)){const t=await Ln(this,Ht,Vt).call(this,"addr(bytes32,uint)",[e]);return na(t,20)?$h(t):null}if(e>=0&&e<2147483648){let t=e+BigInt(2147483648);const n=await Ln(this,Ht,Vt).call(this,"addr(bytes32,uint)",[t]);if(na(n,20))return $h(n)}let n=null;for(const i of this.provider.plugins)if(i instanceof um&&e<=2147483648&&i.supportsCoinType(Number(e))){n=i;break}if(null==n)return null;const r=await Ln(this,Ht,Vt).call(this,"addr(bytes32,uint)",[e]);if(null==r||"0x"===r)return null;if(e<2147483648){const t=await n.decodeAddress(Number(e),r);if(null!=t)return t}qo(!1,"invalid coin data","UNSUPPORTED_OPERATION",{operation:`getAddress(${e})`,info:{coinType:e,data:r}})}async getText(t){const e=await Ln(this,Ht,Vt).call(this,"text(bytes32,string)",[t]);return null==e||"0x"===e?null:e}async getContentHash(){const t=await Ln(this,Ht,Vt).call(this,"contenthash(bytes32)");if(null==t||"0x"===t)return null;const e=t.match(/^0x(e3010170|e5010172)(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);if(e){const t="e3010170"===e[1]?"ipfs":"ipns",n=parseInt(e[4],16);if(e[5].length===2*n)return`${t}://${Ca("0x"+e[2])}`}const n=t.match(/^0xe40101fa011b20([0-9a-f]*)$/);if(n&&64===n[1].length)return`bzz://${n[1]}`;qo(!1,"invalid or unsupported content hash data","UNSUPPORTED_OPERATION",{operation:"getContentHash()",info:{data:t}})}async getName(){return await Ln(this,Ht,Vt).call(this,"name(bytes32)")}async getAvatar(){return(await this._getAvatar()).url}async _getAvatar(){const t=[{type:"name",value:this.name}];try{const r=await this.getText("avatar");if(null==r)return t.push({type:"!avatar",value:""}),{url:null,linkage:t};t.push({type:"avatar",value:r});for(let s=0;s<dm.length;s++){const i=r.match(dm[s]);if(null==i)continue;const o=i[1].toLowerCase();switch(o){case"https":case"data":return t.push({type:"url",value:r}),{linkage:t,url:r};case"ipfs":{const e=lm(r);return t.push({type:"ipfs",value:r}),t.push({type:"url",value:e}),{linkage:t,url:e}}case"erc721":case"erc1155":{const s="erc721"===o?"tokenURI(uint256)":"uri(uint256)";t.push({type:o,value:r});const a=await this.getAddress();if(null==a)return t.push({type:"!owner",value:""}),{url:null,linkage:t};const c=(i[2]||"").split("/");if(2!==c.length)return t.push({type:`!${o}caip`,value:i[2]||""}),{url:null,linkage:t};const l=c[1],u=new am(c[0],["function tokenURI(uint) view returns (string)","function ownerOf(uint) view returns (address)","function uri(uint) view returns (string)","function balanceOf(address, uint256) view returns (uint)"],this.provider);if("erc721"===o){const e=await u.ownerOf(l);if(a!==e)return t.push({type:"!owner",value:e}),{url:null,linkage:t};t.push({type:"owner",value:e})}else if("erc1155"===o){const e=await u.balanceOf(a,l);if(!e)return t.push({type:"!balance",value:"0"}),{url:null,linkage:t};t.push({type:"balance",value:e.toString()})}let h=await u[s](l);if(null==h||"0x"===h)return t.push({type:"!metadata-url",value:""}),{url:null,linkage:t};t.push({type:"metadata-url-base",value:h}),"erc1155"===o&&(h=h.replace("{id}",va(l,32).substring(2)),t.push({type:"metadata-url-expanded",value:h})),h.match(/^ipfs:/i)&&(h=lm(h)),t.push({type:"metadata-url",value:h});let d={};const f=await new $a(h).send();f.assertOk();try{d=f.bodyJson}catch(e){try{t.push({type:"!metadata",value:f.bodyText})}catch(n){const e=f.body;return e&&t.push({type:"!metadata",value:ia(e)}),{url:null,linkage:t}}return{url:null,linkage:t}}if(!d)return t.push({type:"!metadata",value:""}),{url:null,linkage:t};t.push({type:"metadata",value:JSON.stringify(d)});let p=d.image;if("string"!=typeof p)return t.push({type:"!imageUrl",value:""}),{url:null,linkage:t};if(p.match(/^(https:\/\/|data:)/i));else{if(null==p.match(hm))return t.push({type:"!imageUrl-ipfs",value:p}),{url:null,linkage:t};t.push({type:"imageUrl-ipfs",value:p}),p=lm(p)}return t.push({type:"url",value:p}),{linkage:t,url:p}}}}}catch(e){}return{linkage:t,url:null}}static async getEnsAddress(t){const e=await t.getNetwork(),n=e.getPlugin("org.ethers.plugins.network.Ens");return qo(n,"network does not support ENS","UNSUPPORTED_OPERATION",{operation:"getEnsAddress",info:{network:e}}),n.address}static async getUniversalResolverAddress(t){const e=(await t.getNetwork()).getPlugin("org.ethers.plugins.network.Ens");return e&&e.universalResolver?e.universalResolver:null}static async lookupAddress(e,n,r){const s=null==r?cm:ya(r);fm(s)&&(n=$h(n));const i=await mm(e);if(i)try{const t=(await i.reverse(n,s,{enableCcipRead:!0})).primary;return Xf(t)?t:null}catch(o){if(Wo(o,"CALL_EXCEPTION")&&"ResolverNotFound(bytes)"===o.reason)return null;throw o}qo(s===cm,"lookupAddress coinType requires ENS Universal Resolver","UNSUPPORTED_OPERATION",{operation:"lookupAddress"});try{const r=await t.fromName(e,`${n.toLowerCase().substring(2)}.addr.reverse`);if(!r)return null;const s=await r.getName();if(null==s||!Xf(s))return null;return await e.resolveName(s)!==n?null:s}catch(a){if(Wo(a,"BAD_DATA")&&"0x"===a.value)return null;if(Wo(a,"CALL_EXCEPTION"))return null;throw a}}static async fromName(e,n){var r;const s=await mm(e);if(s){let r;try{r=ep(Zf(n),255)}catch(o){return null}const i=await s.requireResolver(r);return new t(e,i.resolver,n,i.extended)}let i=n;for(;;){if(""===i||"."===i)return null;if("eth"!==n&&"eth"===i)return null;const s=await Ln(r=t,Wt,Kt).call(r,e,i);if(null!=s){const r=new t(e,s,n);return i===n||await r.supportsWildcard()?r:null}i=i.split(".").slice(1).join(".")}}};Gt=new WeakMap,jt=new WeakMap,Ht=new WeakSet,Vt=async function(t,e){e=(e||[]).slice();const n=Pn(this,jt).interface;e.unshift(tp(this.name));let r=null;await this.supportsWildcard()&&(r=n.getFunction(t),qo(r,"missing fragment","UNKNOWN_ERROR",{info:{funcName:t}}),e=[ep(this.name,255),n.encodeFunctionData(r,e)],t="resolve(bytes,bytes)"),e.push({enableCcipRead:!0});try{const s=await Pn(this,jt)[t](...e);return r?n.decodeFunctionResult(r,s)[0]:s}catch(s){if(!Wo(s,"CALL_EXCEPTION"))throw s}return null},Wt=new WeakSet,Kt=async function(t,e){const n=await pm.getEnsAddress(t);try{const r=new am(n,["function resolver(bytes32) view returns (address)"],t),s=await r.resolver(tp(e),{enableCcipRead:!0});return s===Ih?null:s}catch(r){throw r}return null},Dn(pm,Wt);let gm=pm;async function mm(t){const e=await gm.getUniversalResolverAddress(t);return e?new am(e,["function requireResolver(bytes) view returns ((bytes name, uint256 offset, bytes32 node, address resolver, bool extended))","function findResolver(bytes) view returns (address resolver, bytes32 node, uint offset)","function resolve(bytes name, bytes data) view returns (bytes result, address resolver)","function reverse(bytes name, uint coinType) view returns (string primary, address resolver, address reverseResolver)","error ResolverNotFound(bytes name)","error ResolverNotContract(bytes name, address resolver)","error ReverseAddressMismatch(string primary, bytes primaryAddress)","error HttpError(uint16 statusCode, string statusMessage)"],t):null}const ym=BigInt(0);function wm(t,e){return function(n){return null==n?e:t(n)}}function bm(t,e){return n=>{if(e&&null==n)return null;if(!Array.isArray(n))throw new Error("not an array");return n.map((e=>t(e)))}}function Am(t,e){return n=>{const r={};for(const i in t){let o=i;if(e&&i in e&&!(o in n))for(const t of e[i])if(t in n){o=t;break}try{const e=t[i](n[o]);void 0!==e&&(r[i]=e)}catch(s){qo(!1,`invalid value for value.${i} (${s instanceof Error?s.message:"not-an-error"})`,"BAD_DATA",{value:n})}}return r}}function _m(t){return $o(na(t,!0),"invalid data","value",t),t}function vm(t){return $o(na(t,32),"invalid hash","value",t),t}const Em=Am({address:$h,blockHash:vm,blockNumber:_a,data:_m,index:_a,removed:wm((function(t){switch(t){case!0:case"true":return!0;case!1:case"false":return!1}$o(!1,`invalid boolean; ${JSON.stringify(t)}`,"value",t)}),!1),topics:bm(vm),transactionHash:vm,transactionIndex:_a},{index:["logIndex"]});const km=Am({hash:wm(vm),parentHash:vm,parentBeaconBlockRoot:wm(vm,null),number:_a,timestamp:_a,nonce:wm(_m),difficulty:ya,gasLimit:ya,gasUsed:ya,stateRoot:wm(vm,null),receiptsRoot:wm(vm,null),transactionsRoot:wm(vm,null),blobGasUsed:wm(ya,null),excessBlobGas:wm(ya,null),miner:wm($h),prevRandao:wm(vm,null),extraData:_m,baseFeePerGas:wm(ya)},{prevRandao:["mixHash"]});const Sm=Am({transactionIndex:_a,blockNumber:_a,transactionHash:vm,address:$h,topics:bm(vm),data:_m,index:_a,blockHash:vm},{index:["logIndex"]});const Tm=Am({to:wm($h,null),from:wm($h,null),contractAddress:wm($h,null),index:_a,root:wm(ia),gasUsed:ya,blobGasUsed:wm(ya,null),logsBloom:wm(_m),blockHash:vm,hash:vm,logs:bm((function(t){return Sm(t)})),blockNumber:_a,cumulativeGasUsed:ya,effectiveGasPrice:wm(ya),blobGasPrice:wm(ya,null),status:wm(_a),type:wm(_a,0)},{effectiveGasPrice:["gasPrice"],hash:["transactionHash"],index:["transactionIndex"]});function Rm(t){t.to&&ya(t.to)===ym&&(t.to="0x0000000000000000000000000000000000000000");const e=Am({hash:vm,index:wm(_a,void 0),type:t=>"0x"===t||null==t?0:_a(t),accessList:wm(_d,null),blobVersionedHashes:wm(bm(vm,!0),null),authorizationList:wm(bm((t=>{let e;if(t.signature)e=t.signature;else{let n=t.yParity;"0x1b"===n?n=0:"0x1c"===n&&(n=1),e=Object.assign({},t,{yParity:n})}return{address:$h(t.address),chainId:ya(t.chainId),nonce:ya(t.nonce),signature:jh.from(e)}}),!1),null),blockHash:wm(vm,null),blockNumber:wm(_a,null),transactionIndex:wm(_a,null),from:$h,gasPrice:wm(ya),maxPriorityFeePerGas:wm(ya),maxFeePerGas:wm(ya),maxFeePerBlobGas:wm(ya,null),gasLimit:ya,to:wm($h,null),value:ya,nonce:_a,data:_m,creates:wm($h,null),chainId:wm(ya,null)},{data:["input"],gasLimit:["gas"],index:["transactionIndex"]})(t);if(null==e.to&&null==e.creates&&(e.creates=function(t){const e=$h(t.from);let n=ya(t.nonce,"tx.nonce").toString(16);return n="0"===n?"0x":n.length%2?"0x0"+n:"0x"+n,$h(ca(Bl(oc([e,n])),12))}(e)),1!==t.type&&2!==t.type||null!=t.accessList||(e.accessList=[]),t.signature?e.signature=jh.from(t.signature):e.signature=jh.from(t),null==e.chainId){const t=e.signature.legacyChainId;null!=t&&(e.chainId=t)}return e.blockHash&&ya(e.blockHash)===ym&&(e.blockHash=null),e}const Im=Symbol.for("nodejs.util.inspect.custom");class Om{constructor(t){xn(this,"name"),Ho(this,{name:t})}[Im](){return this.toString()}toString(){return`${this.name} { }`}clone(){return new Om(this.name)}}class Cm extends Om{constructor(t,e){null==t&&(t=0),super(`org.ethers.network.plugins.GasCost#${t||0}`),xn(this,"effectiveBlock"),xn(this,"txBase"),xn(this,"txCreate"),xn(this,"txDataZero"),xn(this,"txDataNonzero"),xn(this,"txAccessListStorageKey"),xn(this,"txAccessListAddress");const n={effectiveBlock:t};function r(t,r){let s=(e||{})[t];null==s&&(s=r),$o("number"==typeof s,`invalud value for ${t}`,"costs",e),n[t]=s}r("txBase",21e3),r("txCreate",32e3),r("txDataZero",4),r("txDataNonzero",16),r("txAccessListStorageKey",1900),r("txAccessListAddress",2400),Ho(this,n)}toString(){return`${this.name} { txBase: ${this.txBase}, txCreate: ${this.txCreate}, txDataZero: ${this.txDataZero}, txAccessListStorageKey: ${this.txAccessListStorageKey}, txAccessListAddress: ${this.txAccessListAddress} }`}clone(){return new Cm(this.effectiveBlock,this)}}class xm extends Om{constructor(t,e,n){super("org.ethers.plugins.network.Ens"),xn(this,"address"),xn(this,"targetNetwork"),xn(this,"universalResolver"),Ho(this,{address:t||"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",targetNetwork:null==e?1:e,universalResolver:n})}toString(){return`${this.name} { address: ${this.address}, targetNetwork: ${this.targetNetwork}, universalResolver: ${this.universalResolver} }`}clone(){return new xm(this.address,this.targetNetwork,this.universalResolver)}}class Nm extends Om{constructor(t,e){super("org.ethers.plugins.network.FetchUrlFeeDataPlugin"),Dn(this,zt,void 0),Dn(this,qt,void 0),Bn(this,zt,t),Bn(this,qt,e)}get url(){return Pn(this,zt)}get processFunc(){return Pn(this,qt)}toString(){return`${this.name} { url: ${this.url} }`}clone(){return this}}zt=new WeakMap,qt=new WeakMap;const Pm=Symbol.for("nodejs.util.inspect.custom"),Dm=new Map;$t=new WeakMap,Qt=new WeakMap,Jt=new WeakMap;let Bm=class t{constructor(t,e){Dn(this,$t,void 0),Dn(this,Qt,void 0),Dn(this,Jt,void 0),Bn(this,$t,t),Bn(this,Qt,ya(e)),Bn(this,Jt,new Map)}[Pm](){return this.toString()}toString(){const t=[];for(const e of Pn(this,Jt).values())t.push(e.toString());return`Network { name: ${this.name}, chainId: ${this.chainId}, plugins: [ ${t.join(", ")} ] }`}toJSON(){return{name:this.name,chainId:String(this.chainId)}}get name(){return Pn(this,$t)}set name(t){Bn(this,$t,t)}get chainId(){return Pn(this,Qt)}set chainId(t){Bn(this,Qt,ya(t,"chainId"))}matches(t){if(null==t)return!1;if("string"==typeof t){try{return this.chainId===ya(t)}catch(e){}return this.name===t}if("number"==typeof t||"bigint"==typeof t){try{return this.chainId===ya(t)}catch(e){}return!1}if("object"==typeof t){if(null!=t.chainId){try{return this.chainId===ya(t.chainId)}catch(e){}return!1}return null!=t.name&&this.name===t.name}return!1}get plugins(){return Array.from(Pn(this,Jt).values())}attachPlugin(t){if(Pn(this,Jt).get(t.name))throw new Error(`cannot replace existing plugin: ${t.name} `);return Pn(this,Jt).set(t.name,t.clone()),this}getPlugin(t){return Pn(this,Jt).get(t)||null}getPlugins(t){return this.plugins.filter((e=>e.name.split("#")[0]===t))}clone(){const e=new t(this.name,this.chainId);return this.plugins.forEach((t=>{e.attachPlugin(t.clone())})),e}computeIntrinsicGas(t){const e=this.getPlugin("org.ethers.plugins.network.GasCost")||new Cm;let n=e.txBase;if(null==t.to&&(n+=e.txCreate),t.data)for(let r=2;r<t.data.length;r+=2)"00"===t.data.substring(r,r+2)?n+=e.txDataZero:n+=e.txDataNonzero;if(t.accessList){const r=_d(t.accessList);for(const t in r)n+=e.txAccessListAddress+e.txAccessListStorageKey*r[t].storageKeys.length}return n}static from(e){if(function(){if(Mm)return;function t(t,e,n){const r=function(){const r=new Bm(t,e);return null!=n.ensNetwork&&r.attachPlugin(new xm(null,n.ensNetwork,n.ensUniversalResolver)),r.attachPlugin(new Cm),(n.plugins||[]).forEach((t=>{r.attachPlugin(t)})),r};Bm.register(t,r),Bm.register(e,r),n.altNames&&n.altNames.forEach((t=>{Bm.register(t,r)}))}Mm=!0;const e="0xeEeEEEeE14D718C2B47D9923Deab1335E144EeEe";t("mainnet",1,{ensUniversalResolver:e,ensNetwork:1,altNames:["homestead"]}),t("ropsten",3,{ensNetwork:3}),t("rinkeby",4,{ensNetwork:4}),t("goerli",5,{ensNetwork:5}),t("kovan",42,{ensNetwork:42}),t("sepolia",11155111,{ensUniversalResolver:e,ensNetwork:11155111}),t("holesky",17e3,{ensNetwork:17e3}),t("classic",61,{}),t("classicKotti",6,{}),t("arbitrum",42161,{ensNetwork:1}),t("arbitrum-goerli",421613,{}),t("arbitrum-sepolia",421614,{}),t("base",8453,{ensNetwork:1}),t("base-goerli",84531,{}),t("base-sepolia",84532,{}),t("bnb",56,{ensNetwork:1}),t("bnbt",97,{}),t("filecoin",314,{}),t("filecoin-calibration",314159,{}),t("linea",59144,{ensNetwork:1}),t("linea-goerli",59140,{}),t("linea-sepolia",59141,{}),t("matic",137,{ensNetwork:1,plugins:[Lm("https://gasstation.polygon.technology/v2")]}),t("matic-amoy",80002,{}),t("matic-mumbai",80001,{altNames:["maticMumbai","maticmum"],plugins:[Lm("https://gasstation-testnet.polygon.technology/v2")]}),t("optimism",10,{ensNetwork:1,plugins:[]}),t("optimism-goerli",420,{}),t("optimism-sepolia",11155420,{}),t("xdai",100,{ensNetwork:1})}(),null==e)return t.from("mainnet");if("number"==typeof e&&(e=BigInt(e)),"string"==typeof e||"bigint"==typeof e){const n=Dm.get(e);if(n)return n();if("bigint"==typeof e)return new t("unknown",e);$o(!1,"unknown network","network",e)}if("function"==typeof e.clone){return e.clone()}if("object"==typeof e){$o("string"==typeof e.name&&"number"==typeof e.chainId,"invalid network object name or chainId","network",e);const n=new t(e.name,e.chainId),r=e;return(r.ensAddress||null!=r.ensNetwork||r.ensUniversalResolver)&&n.attachPlugin(new xm(r.ensAddress,r.ensNetwork,r.ensUniversalResolver)),n}$o(!1,"invalid network","network",e)}static register(t,e){"number"==typeof t&&(t=BigInt(t));const n=Dm.get(t);n&&$o(!1,`conflicting network for ${JSON.stringify(n.name)}`,"nameOrChainId",t),Dm.set(t,e)}};function Um(t,e){const n=String(t);if(!n.match(/^[0-9.]+$/))throw new Error(`invalid gwei value: ${t}`);const r=n.split(".");if(1===r.length&&r.push(""),2!==r.length)throw new Error(`invalid gwei value: ${t}`);for(;r[1].length<e;)r[1]+="0";if(r[1].length>9){let t=BigInt(r[1].substring(0,9));r[1].substring(9).match(/^0+$/)||t++,r[1]=t.toString()}return BigInt(r[0]+r[1])}function Lm(t){return new Nm(t,(async(t,e,n)=>{let r;n.setHeader("User-Agent","ethers");try{const[e,s]=await Promise.all([n.send(),t()]);r=e;const i=r.bodyJson.standard;return{gasPrice:s.gasPrice,maxFeePerGas:Um(i.maxFee,9),maxPriorityFeePerGas:Um(i.maxPriorityFee,9)}}catch(s){qo(!1,`error encountered with polygon gas station (${JSON.stringify(n.url)})`,"SERVER_ERROR",{request:n,response:r,error:s})}}))}let Mm=!1;function Fm(t){return JSON.parse(JSON.stringify(t))}class Gm{constructor(t){Dn(this,ee),Dn(this,Yt,void 0),Dn(this,Zt,void 0),Dn(this,Xt,void 0),Dn(this,te,void 0),Bn(this,Yt,t),Bn(this,Zt,null),Bn(this,Xt,4e3),Bn(this,te,-2)}get pollingInterval(){return Pn(this,Xt)}set pollingInterval(t){Bn(this,Xt,t)}start(){Pn(this,Zt)||(Bn(this,Zt,Pn(this,Yt)._setTimeout(Ln(this,ee,ne).bind(this),Pn(this,Xt))),Ln(this,ee,ne).call(this))}stop(){Pn(this,Zt)&&(Pn(this,Yt)._clearTimeout(Pn(this,Zt)),Bn(this,Zt,null))}pause(t){this.stop(),t&&Bn(this,te,-2)}resume(){this.start()}}Yt=new WeakMap,Zt=new WeakMap,Xt=new WeakMap,te=new WeakMap,ee=new WeakSet,ne=async function(){try{const t=await Pn(this,Yt).getBlockNumber();if(-2===Pn(this,te))return void Bn(this,te,t);if(t!==Pn(this,te)){for(let e=Pn(this,te)+1;e<=t;e++){if(null==Pn(this,Zt))return;await Pn(this,Yt).emit("block",e)}Bn(this,te,t)}}catch(t){}null!=Pn(this,Zt)&&Bn(this,Zt,Pn(this,Yt)._setTimeout(Ln(this,ee,ne).bind(this),Pn(this,Xt)))};class jm{constructor(t){Dn(this,re,void 0),Dn(this,se,void 0),Dn(this,ie,void 0),Bn(this,re,t),Bn(this,ie,!1),Bn(this,se,(t=>{this._poll(t,Pn(this,re))}))}async _poll(t,e){throw new Error("sub-classes must override this")}start(){Pn(this,ie)||(Bn(this,ie,!0),Pn(this,se).call(this,-2),Pn(this,re).on("block",Pn(this,se)))}stop(){Pn(this,ie)&&(Bn(this,ie,!1),Pn(this,re).off("block",Pn(this,se)))}pause(t){this.stop()}resume(){this.start()}}re=new WeakMap,se=new WeakMap,ie=new WeakMap;class Hm extends jm{constructor(t,e){super(t),Dn(this,oe,void 0),Dn(this,ae,void 0),Bn(this,oe,e),Bn(this,ae,-2)}pause(t){t&&Bn(this,ae,-2),super.pause(t)}async _poll(t,e){const n=await e.getBlock(Pn(this,oe));null!=n&&(-2===Pn(this,ae)?Bn(this,ae,n.number):n.number>Pn(this,ae)&&(e.emit(Pn(this,oe),n.number),Bn(this,ae,n.number)))}}oe=new WeakMap,ae=new WeakMap;class Vm extends jm{constructor(t,e){super(t),Dn(this,ce,void 0),Bn(this,ce,Fm(e))}async _poll(t,e){throw new Error("@TODO")}}ce=new WeakMap;class Wm extends jm{constructor(t,e){super(t),Dn(this,le,void 0),Bn(this,le,e)}async _poll(t,e){const n=await e.getTransactionReceipt(Pn(this,le));n&&e.emit(Pn(this,le),n)}}le=new WeakMap;class Km{constructor(t,e){Dn(this,ge),Dn(this,ue,void 0),Dn(this,he,void 0),Dn(this,de,void 0),Dn(this,fe,void 0),Dn(this,pe,void 0),Bn(this,ue,t),Bn(this,he,Fm(e)),Bn(this,de,Ln(this,ge,me).bind(this)),Bn(this,fe,!1),Bn(this,pe,-2)}start(){Pn(this,fe)||(Bn(this,fe,!0),-2===Pn(this,pe)&&Pn(this,ue).getBlockNumber().then((t=>{Bn(this,pe,t)})),Pn(this,ue).on("block",Pn(this,de)))}stop(){Pn(this,fe)&&(Bn(this,fe,!1),Pn(this,ue).off("block",Pn(this,de)))}pause(t){this.stop(),t&&Bn(this,pe,-2)}resume(){this.start()}}ue=new WeakMap,he=new WeakMap,de=new WeakMap,fe=new WeakMap,pe=new WeakMap,ge=new WeakSet,me=async function(t){if(-2===Pn(this,pe))return;const e=Fm(Pn(this,he));e.fromBlock=Pn(this,pe)+1,e.toBlock=t;const n=await Pn(this,ue).getLogs(e);if(0!==n.length)for(const r of n)Pn(this,ue).emit(Pn(this,he),r),Bn(this,pe,r.blockNumber);else Pn(this,pe)<t-60&&Bn(this,pe,t-60)};const zm=BigInt(2);function qm(t){return new Promise((e=>{setTimeout(e,t)}))}function $m(t){return t&&"function"==typeof t.then}function Qm(t,e){return t+":"+JSON.stringify(e,((t,e)=>{if(null==e)return"null";if("bigint"==typeof e)return`bigint:${e.toString()}`;if("string"==typeof e)return e.toLowerCase();if("object"==typeof e&&!Array.isArray(e)){const t=Object.keys(e);return t.sort(),t.reduce(((t,n)=>(t[n]=e[n],t)),{})}return e}))}class Jm{constructor(t){xn(this,"name"),Ho(this,{name:t})}start(){}stop(){}pause(t){}resume(){}}function Ym(t){return(t=Array.from(new Set(t).values())).sort(),t}async function Zm(t,e){if(null==t)throw new Error("invalid event");if(Array.isArray(t)&&(t={topics:t}),"string"==typeof t)switch(t){case"block":case"debug":case"error":case"finalized":case"network":case"pending":case"safe":return{type:t,tag:t}}if(na(t,32)){const e=t.toLowerCase();return{type:"transaction",tag:Qm("tx",{hash:e}),hash:e}}if(t.orphan){const e=t;return{type:"orphan",tag:Qm("orphan",e),filter:(n=e,JSON.parse(JSON.stringify(n)))}}var n;if(t.address||t.topics){const n=t,r={topics:(n.topics||[]).map((t=>null==t?null:Array.isArray(t)?Ym(t.map((t=>t.toLowerCase()))):t.toLowerCase()))};if(n.address){const t=[],s=[],i=n=>{na(n)?t.push(n):s.push((async()=>{t.push(await Yh(n,e))})())};Array.isArray(n.address)?n.address.forEach(i):i(n.address),s.length&&await Promise.all(s),r.address=Ym(t.map((t=>t.toLowerCase())))}return{filter:r,tag:Qm("event",r),type:"event"}}$o(!1,"unknown ProviderEvent","event",t)}function Xm(){return(new Date).getTime()}const ty={cacheTimeout:250,pollingInterval:4e3};class ey{constructor(t,e){if(Dn(this,xe),Dn(this,Pe),Dn(this,Be),Dn(this,Le),Dn(this,Fe),Dn(this,je),Dn(this,Ve),Dn(this,Ke),Dn(this,ye,void 0),Dn(this,we,void 0),Dn(this,be,void 0),Dn(this,Ae,void 0),Dn(this,_e,void 0),Dn(this,ve,void 0),Dn(this,Ee,void 0),Dn(this,ke,void 0),Dn(this,Se,void 0),Dn(this,Te,void 0),Dn(this,Re,void 0),Dn(this,Ie,void 0),Dn(this,Oe,void 0),Dn(this,Ce,void 0),Bn(this,Ce,Object.assign({},ty,e||{})),"any"===t)Bn(this,ve,!0),Bn(this,_e,null);else if(t){const e=Bm.from(t);Bn(this,ve,!1),Bn(this,_e,Promise.resolve(e)),setTimeout((()=>{this.emit("network",e,null)}),0)}else Bn(this,ve,!1),Bn(this,_e,null);Bn(this,ke,-1),Bn(this,Ee,new Map),Bn(this,ye,new Map),Bn(this,we,new Map),Bn(this,be,null),Bn(this,Ae,!1),Bn(this,Se,1),Bn(this,Te,new Map),Bn(this,Re,!1),Bn(this,Ie,0),Bn(this,Oe,[])}get _requestRate(){const t=Pn(this,Ie);return 0==t?null:t}set _requestRate(t){(null==t||t<0)&&(t=0),Bn(this,Ie,_a(t))}get pollingInterval(){return Pn(this,Ce).pollingInterval}get provider(){return this}get plugins(){return Array.from(Pn(this,we).values())}attachPlugin(t){if(Pn(this,we).get(t.name))throw new Error(`cannot replace existing plugin: ${t.name} `);return Pn(this,we).set(t.name,t.connect(this)),this}getPlugin(t){return Pn(this,we).get(t)||null}get disableCcipRead(){return Pn(this,Re)}set disableCcipRead(t){Bn(this,Re,!!t)}async ccipReadFetch(t,e,n){if(this.disableCcipRead||0===n.length||null==t.to)return null;const r=t.to.toLowerCase(),s=e.toLowerCase(),i=[];for(let a=0;a<n.length;a++){const e=n[a],c=e.replace("{sender}",r).replace("{data}",s),l=new $a(c);-1===e.indexOf("{data}")&&(l.body={data:s,sender:r}),this.emit("debug",{action:"sendCcipReadFetchRequest",request:l,index:a,urls:n});let u,h="unknown error";try{u=await l.send()}catch(o){i.push(o.message),this.emit("debug",{action:"receiveCcipReadFetchError",request:l,result:{error:o}});continue}try{const t=u.bodyJson;if(t.data)return this.emit("debug",{action:"receiveCcipReadFetchResult",request:l,result:t}),t.data;t.message&&(h=t.message),this.emit("debug",{action:"receiveCcipReadFetchError",request:l,result:t})}catch(o){}qo(u.statusCode<400||u.statusCode>=500,`response not found during CCIP fetch: ${h}`,"OFFCHAIN_FAULT",{reason:"404_MISSING_RESOURCE",transaction:t,info:{url:e,errorMessage:h}}),i.push(h)}qo(!1,`error encountered during CCIP fetch: ${i.map((t=>JSON.stringify(t))).join(", ")}`,"OFFCHAIN_FAULT",{reason:"500_SERVER_ERROR",transaction:t,info:{urls:n,errorMessages:i}})}_wrapBlock(t,e){return new Rg(function(t){const e=km(t);return e.transactions=t.transactions.map((t=>"string"==typeof t?t:Rm(t))),e}(t),this)}_wrapLog(t,e){return new Ig(function(t){return Em(t)}(t),this)}_wrapTransactionReceipt(t,e){return new Og(function(t){return Tm(t)}(t),this)}_wrapTransactionResponse(t,e){return new Cg(Rm(t),this)}_detectNetwork(){qo(!1,"sub-classes must implement this","UNSUPPORTED_OPERATION",{operation:"_detectNetwork"})}async _perform(t){qo(!1,`unsupported method: ${t.method}`,"UNSUPPORTED_OPERATION",{operation:t.method,info:t})}async getBlockNumber(){const t=_a(await Ln(this,Pe,De).call(this,{method:"getBlockNumber"}),"%response");return Pn(this,ke)>=0&&Bn(this,ke,t),t}_getAddress(t){return Yh(t,this)}_getBlockTag(t){if(null==t)return"latest";switch(t){case"earliest":return"0x0";case"finalized":case"latest":case"pending":case"safe":return t}return na(t)?na(t,32)?t:ka(t):("bigint"==typeof t&&(t=_a(t,"blockTag")),"number"==typeof t?t>=0?ka(t):Pn(this,ke)>=0?ka(Pn(this,ke)+t):this.getBlockNumber().then((e=>ka(e+t))):void $o(!1,"invalid blockTag","blockTag",t))}_getFilter(t){const e=(t.topics||[]).map((t=>null==t?null:Array.isArray(t)?Ym(t.map((t=>t.toLowerCase()))):t.toLowerCase())),n="blockHash"in t?t.blockHash:void 0,r=(t,r,s)=>{let i;switch(t.length){case 0:break;case 1:i=t[0];break;default:t.sort(),i=t}if(n&&(null!=r||null!=s))throw new Error("invalid filter");const o={};return i&&(o.address=i),e.length&&(o.topics=e),r&&(o.fromBlock=r),s&&(o.toBlock=s),n&&(o.blockHash=n),o};let s,i,o=[];if(t.address)if(Array.isArray(t.address))for(const a of t.address)o.push(this._getAddress(a));else o.push(this._getAddress(t.address));return"fromBlock"in t&&(s=this._getBlockTag(t.fromBlock)),"toBlock"in t&&(i=this._getBlockTag(t.toBlock)),o.filter((t=>"string"!=typeof t)).length||null!=s&&"string"!=typeof s||null!=i&&"string"!=typeof i?Promise.all([Promise.all(o),s,i]).then((t=>r(t[0],t[1],t[2]))):r(o,s,i)}_getTransactionRequest(t){const e=Tg(t),n=[];if(["to","from"].forEach((t=>{if(null==e[t])return;const r=Yh(e[t],this);$m(r)?n.push(async function(){e[t]=await r}()):e[t]=r})),null!=e.blockTag){const t=this._getBlockTag(e.blockTag);$m(t)?n.push(async function(){e.blockTag=await t}()):e.blockTag=t}return n.length?async function(){return await Promise.all(n),e}():e}async getNetwork(){if(null==Pn(this,_e)){const t=(async()=>{try{const t=await this._detectNetwork();return this.emit("network",t,null),t}catch(e){throw Pn(this,_e)===t&&Bn(this,_e,null),e}})();return Bn(this,_e,t),(await t).clone()}const t=Pn(this,_e),[e,n]=await Promise.all([t,this._detectNetwork()]);return e.chainId!==n.chainId&&(Pn(this,ve)?(this.emit("network",n,e),Pn(this,_e)===t&&Bn(this,_e,Promise.resolve(n))):qo(!1,`network changed: ${e.chainId} => ${n.chainId} `,"NETWORK_ERROR",{event:"changed"})),e.clone()}async getFeeData(){const t=await this.getNetwork(),e=async()=>{const{_block:e,gasPrice:n,priorityFee:r}=await jo({_block:Ln(this,je,He).call(this,"latest",!1),gasPrice:(async()=>{try{return ya(await Ln(this,Pe,De).call(this,{method:"getGasPrice"}),"%response")}catch(t){}return null})(),priorityFee:(async()=>{try{return ya(await Ln(this,Pe,De).call(this,{method:"getPriorityFee"}),"%response")}catch(t){}return null})()});let s=null,i=null;const o=this._wrapBlock(e,t);return o&&o.baseFeePerGas&&(i=null!=r?r:BigInt("1000000000"),s=o.baseFeePerGas*zm+i),new Sg(n,s,i)},n=t.getPlugin("org.ethers.plugins.network.FetchUrlFeeDataPlugin");if(n){const t=new $a(n.url),r=await n.processFunc(e,this,t);return new Sg(r.gasPrice,r.maxFeePerGas,r.maxPriorityFeePerGas)}return await e()}async estimateGas(t){let e=this._getTransactionRequest(t);return $m(e)&&(e=await e),ya(await Ln(this,Pe,De).call(this,{method:"estimateGas",transaction:e}),"%response")}async call(t){const{tx:e,blockTag:n}=await jo({tx:this._getTransactionRequest(t),blockTag:this._getBlockTag(t.blockTag)});return await Ln(this,Le,Me).call(this,Ln(this,Be,Ue).call(this,e,n,t.enableCcipRead?0:-1))}async getBalance(t,e){return ya(await Ln(this,Fe,Ge).call(this,{method:"getBalance"},t,e),"%response")}async getTransactionCount(t,e){return _a(await Ln(this,Fe,Ge).call(this,{method:"getTransactionCount"},t,e),"%response")}async getCode(t,e){return ia(await Ln(this,Fe,Ge).call(this,{method:"getCode"},t,e))}async getStorage(t,e,n){const r=ya(e,"position");return ia(await Ln(this,Fe,Ge).call(this,{method:"getStorage",position:r},t,n))}async broadcastTransaction(t){const{blockNumber:e,hash:n,network:r}=await jo({blockNumber:this.getBlockNumber(),hash:this._perform({method:"broadcastTransaction",signedTransaction:t}),network:this.getNetwork()}),s=Vd.from(t);if(s.hash!==n)throw new Error("@TODO: the returned hash did not match");return this._wrapTransactionResponse(s,r).replaceableTransaction(e)}async getBlock(t,e){const{network:n,params:r}=await jo({network:this.getNetwork(),params:Ln(this,je,He).call(this,t,!!e)});return null==r?null:this._wrapBlock(r,n)}async getTransaction(t){const{network:e,params:n}=await jo({network:this.getNetwork(),params:Ln(this,Pe,De).call(this,{method:"getTransaction",hash:t})});return null==n?null:this._wrapTransactionResponse(n,e)}async getTransactionReceipt(t){const{network:e,params:n}=await jo({network:this.getNetwork(),params:Ln(this,Pe,De).call(this,{method:"getTransactionReceipt",hash:t})});if(null==n)return null;if(null==n.gasPrice&&null==n.effectiveGasPrice){const e=await Ln(this,Pe,De).call(this,{method:"getTransaction",hash:t});if(null==e)throw new Error("report this; could not find tx or effectiveGasPrice");n.effectiveGasPrice=e.gasPrice}return this._wrapTransactionReceipt(n,e)}async getTransactionResult(t){const{result:e}=await jo({network:this.getNetwork(),result:Ln(this,Pe,De).call(this,{method:"getTransactionResult",hash:t})});return null==e?null:ia(e)}async getLogs(t){let e=this._getFilter(t);$m(e)&&(e=await e);const{network:n,params:r}=await jo({network:this.getNetwork(),params:Ln(this,Pe,De).call(this,{method:"getLogs",filter:e})});return r.map((t=>this._wrapLog(t,n)))}_getProvider(t){qo(!1,"provider cannot connect to target network","UNSUPPORTED_OPERATION",{operation:"_getProvider()"})}async getResolver(t){return await gm.fromName(this,t)}async getAvatar(t){const e=await this.getResolver(t);return e?await e.getAvatar():null}async resolveName(t,e){const n=await this.getResolver(t);return n?await n.getAddress(e):null}async lookupAddress(t,e){return await gm.lookupAddress(this,t,e)}async waitForTransaction(t,e,n){const r=null!=e?e:1;return 0===r?this.getTransactionReceipt(t):new Promise((async(e,s)=>{let i=null;const o=async n=>{try{const s=await this.getTransactionReceipt(t);if(null!=s&&n-s.blockNumber+1>=r)return e(s),void(i&&(clearTimeout(i),i=null))}catch(s){console.log("EEE",s)}this.once("block",o)};null!=n&&(i=setTimeout((()=>{null!=i&&(i=null,this.off("block",o),s(zo("timeout","TIMEOUT",{reason:"timeout"})))}),n)),o(await this.getBlockNumber())}))}async waitForBlock(t){qo(!1,"not implemented yet","NOT_IMPLEMENTED",{operation:"waitForBlock"})}_clearTimeout(t){const e=Pn(this,Te).get(t);e&&(e.timer&&clearTimeout(e.timer),Pn(this,Te).delete(t))}_setTimeout(t,e){null==e&&(e=0);const n=Un(this,Se)._++,r=()=>{Pn(this,Te).delete(n),t()};if(this.paused)Pn(this,Te).set(n,{timer:null,func:r,time:e});else{const t=setTimeout(r,e);Pn(this,Te).set(n,{timer:t,func:r,time:Xm()})}return n}_forEachSubscriber(t){for(const e of Pn(this,ye).values())t(e.subscriber)}_getSubscriber(t){switch(t.type){case"debug":case"error":case"network":return new Jm(t.type);case"block":{const t=new Gm(this);return t.pollingInterval=this.pollingInterval,t}case"safe":case"finalized":return new Hm(this,t.type);case"event":return new Km(this,t.filter);case"transaction":return new Wm(this,t.hash);case"orphan":return new Vm(this,t.filter)}throw new Error(`unsupported event: ${t.type}`)}_recoverSubscriber(t,e){for(const n of Pn(this,ye).values())if(n.subscriber===t){n.started&&n.subscriber.stop(),n.subscriber=e,n.started&&e.start(),null!=Pn(this,be)&&e.pause(Pn(this,be));break}}async on(t,e){const n=await Ln(this,Ke,ze).call(this,t);return n.listeners.push({listener:e,once:!1}),n.started||(n.subscriber.start(),n.started=!0,null!=Pn(this,be)&&n.subscriber.pause(Pn(this,be))),this}async once(t,e){const n=await Ln(this,Ke,ze).call(this,t);return n.listeners.push({listener:e,once:!0}),n.started||(n.subscriber.start(),n.started=!0,null!=Pn(this,be)&&n.subscriber.pause(Pn(this,be))),this}async emit(t,...e){const n=await Ln(this,Ve,We).call(this,t,e);if(!n||0===n.listeners.length)return!1;const r=n.listeners.length;return n.listeners=n.listeners.filter((({listener:n,once:r})=>{const s=new xa(this,r?null:n,t);try{n.call(this,...e,s)}catch(i){}return!r})),0===n.listeners.length&&(n.started&&n.subscriber.stop(),Pn(this,ye).delete(n.tag)),r>0}async listenerCount(t){if(t){const e=await Ln(this,Ve,We).call(this,t);return e?e.listeners.length:0}let e=0;for(const{listeners:n}of Pn(this,ye).values())e+=n.length;return e}async listeners(t){if(t){const e=await Ln(this,Ve,We).call(this,t);return e?e.listeners.map((({listener:t})=>t)):[]}let e=[];for(const{listeners:n}of Pn(this,ye).values())e=e.concat(n.map((({listener:t})=>t)));return e}async off(t,e){const n=await Ln(this,Ve,We).call(this,t);if(!n)return this;if(e){const t=n.listeners.map((({listener:t})=>t)).indexOf(e);t>=0&&n.listeners.splice(t,1)}return e&&0!==n.listeners.length||(n.started&&n.subscriber.stop(),Pn(this,ye).delete(n.tag)),this}async removeAllListeners(t){if(t){const{tag:e,started:n,subscriber:r}=await Ln(this,Ke,ze).call(this,t);n&&r.stop(),Pn(this,ye).delete(e)}else for(const[e,{started:n,subscriber:r}]of Pn(this,ye))n&&r.stop(),Pn(this,ye).delete(e);return this}async addListener(t,e){return await this.on(t,e)}async removeListener(t,e){return this.off(t,e)}get destroyed(){return Pn(this,Ae)}destroy(){this.removeAllListeners();for(const t of Pn(this,Te).keys())this._clearTimeout(t);Bn(this,Ae,!0)}get paused(){return null!=Pn(this,be)}set paused(t){!!t!==this.paused&&(this.paused?this.resume():this.pause(!1))}pause(t){if(Bn(this,ke,-1),null!=Pn(this,be)){if(Pn(this,be)==!!t)return;qo(!1,"cannot change pause type; resume first","UNSUPPORTED_OPERATION",{operation:"pause"})}this._forEachSubscriber((e=>e.pause(t))),Bn(this,be,!!t);for(const e of Pn(this,Te).values())e.timer&&clearTimeout(e.timer),e.time=Xm()-e.time}resume(){if(null!=Pn(this,be)){this._forEachSubscriber((t=>t.resume())),Bn(this,be,null);for(const t of Pn(this,Te).values()){let e=t.time;e<0&&(e=0),t.time=Xm(),setTimeout(t.func,e)}}}}function ny(t,e){try{const n=ry(t,e);if(n)return Ba(n)}catch(n){}return null}function ry(t,e){if("0x"===t)return null;try{const n=_a(ca(t,e,e+32)),r=_a(ca(t,n,n+32));return ca(t,n+32,n+32+r)}catch(n){}return null}function sy(t){const e=Ea(t);if(e.length>32)throw new Error("internal; should not happen");const n=new Uint8Array(32);return n.set(e,32-e.length),n}function iy(t){if(t.length%32==0)return t;const e=new Uint8Array(32*Math.ceil(t.length/32));return e.set(t),e}ye=new WeakMap,we=new WeakMap,be=new WeakMap,Ae=new WeakMap,_e=new WeakMap,ve=new WeakMap,Ee=new WeakMap,ke=new WeakMap,Se=new WeakMap,Te=new WeakMap,Re=new WeakMap,Ie=new WeakMap,Oe=new WeakMap,Ce=new WeakMap,xe=new WeakSet,Ne=function(){let t=Pn(this,Ie);if(0===t)return 0;const e=Pn(this,Oe),n=Xm();e.push(n);const r=n-1e3;for(;e.length&&e[0]<r;)e.shift();return e.length<t?0:e[0]+1e3-n},Pe=new WeakSet,De=async function(t){const e=Pn(this,Ce).cacheTimeout;if(e<0){const e=Ln(this,xe,Ne).call(this);return e&&await qm(e),await this._perform(t)}const n=Qm(t.method,t);let r=Pn(this,Ee).get(n);if(!r){const s=Ln(this,xe,Ne).call(this);s&&await qm(s),r=this._perform(t),Pn(this,Ee).set(n,r),setTimeout((()=>{Pn(this,Ee).get(n)===r&&Pn(this,Ee).delete(n)}),e)}return await r},Be=new WeakSet,Ue=async function(t,e,n){qo(n<10,"CCIP read exceeded maximum redirections","OFFCHAIN_FAULT",{reason:"TOO_MANY_REDIRECTS",transaction:Object.assign({},t,{blockTag:e,enableCcipRead:!0})});const r=Tg(t);try{const t=Ln(this,xe,Ne).call(this);return t&&await qm(t),ia(await this._perform({method:"call",transaction:r,blockTag:e}))}catch(s){if(!this.disableCcipRead&&Ko(s)&&s.data&&n>=0&&"latest"===e&&null!=r.to&&"0x556f1830"===ca(s.data,0,4)){const t=s.data,o=await Yh(r.to,this);let a;try{a=function(t){const e={sender:"",urls:[],calldata:"",selector:"",extraData:"",errorArgs:[]};qo(aa(t)>=160,"insufficient OffchainLookup data","OFFCHAIN_FAULT",{reason:"insufficient OffchainLookup data"});const n=ca(t,0,32);qo(ca(n,0,12)===ca(cy,0,12),"corrupt OffchainLookup sender","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup sender"}),e.sender=ca(n,12);try{const n=[],r=_a(ca(t,32,64)),s=_a(ca(t,r,r+32)),i=ca(t,r+32);for(let t=0;t<s;t++){const e=ny(i,32*t);if(null==e)throw new Error("abort");n.push(e)}e.urls=n}catch(s){qo(!1,"corrupt OffchainLookup urls","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup urls"})}try{const n=ry(t,64);if(null==n)throw new Error("abort");e.calldata=n}catch(s){qo(!1,"corrupt OffchainLookup calldata","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup calldata"})}qo(ca(t,100,128)===ca(cy,0,28),"corrupt OffchainLookup callbaackSelector","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup callbaackSelector"}),e.selector=ca(t,96,100);try{const n=ry(t,128);if(null==n)throw new Error("abort");e.extraData=n}catch(s){qo(!1,"corrupt OffchainLookup extraData","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup extraData"})}return e.errorArgs="sender,urls,calldata,selector,extraData".split(/,/).map((t=>e[t])),e}(ca(s.data,4))}catch(i){qo(!1,i.message,"OFFCHAIN_FAULT",{reason:"BAD_DATA",transaction:r,info:{data:t}})}qo(a.sender.toLowerCase()===o.toLowerCase(),"CCIP Read sender mismatch","CALL_EXCEPTION",{action:"call",data:t,reason:"OffchainLookup",transaction:r,invocation:null,revert:{signature:"OffchainLookup(address,string[],bytes,bytes4,bytes)",name:"OffchainLookup",args:a.errorArgs}});const c=await this.ccipReadFetch(r,a.calldata,a.urls);qo(null!=c,"CCIP Read failed to fetch data","OFFCHAIN_FAULT",{reason:"FETCH_FAILED",transaction:r,info:{data:s.data,errorArgs:a.errorArgs}});const l={to:o,data:oa([a.selector,ay([c,a.extraData])])};this.emit("debug",{action:"sendCcipReadCall",transaction:l});try{const t=await Ln(this,Be,Ue).call(this,l,e,n+1);return this.emit("debug",{action:"receiveCcipReadCallResult",transaction:Object.assign({},l),result:t}),t}catch(i){throw this.emit("debug",{action:"receiveCcipReadCallError",transaction:Object.assign({},l),error:i}),i}}throw s}},Le=new WeakSet,Me=async function(t){const{value:e}=await jo({network:this.getNetwork(),value:t});return e},Fe=new WeakSet,Ge=async function(t,e,n){let r=this._getAddress(e),s=this._getBlockTag(n);return"string"==typeof r&&"string"==typeof s||([r,s]=await Promise.all([r,s])),await Ln(this,Le,Me).call(this,Ln(this,Pe,De).call(this,Object.assign(t,{address:r,blockTag:s})))},je=new WeakSet,He=async function(t,e){if(na(t,32))return await Ln(this,Pe,De).call(this,{method:"getBlock",blockHash:t,includeTransactions:e});let n=this._getBlockTag(t);return"string"!=typeof n&&(n=await n),await Ln(this,Pe,De).call(this,{method:"getBlock",blockTag:n,includeTransactions:e})},Ve=new WeakSet,We=async function(t,e){let n=await Zm(t,this);return"event"===n.type&&e&&e.length>0&&!0===e[0].removed&&(n=await Zm({orphan:"drop-log",log:e[0]},this)),Pn(this,ye).get(n.tag)||null},Ke=new WeakSet,ze=async function(t){const e=await Zm(t,this),n=e.tag;let r=Pn(this,ye).get(n);if(!r){r={subscriber:this._getSubscriber(e),tag:n,addressableMap:new WeakMap,nameMap:new Map,started:!1,listeners:[]},Pn(this,ye).set(n,r)}return r};const oy=new Uint8Array([]);function ay(t){const e=[];let n=0;for(let r=0;r<t.length;r++)e.push(oy),n+=32;for(let r=0;r<t.length;r++){const s=ta(t[r]);e[r]=sy(n),e.push(sy(s.length)),e.push(iy(s)),n+=32+32*Math.ceil(s.length/32)}return oa(e)}const cy="0x0000000000000000000000000000000000000000000000000000000000000000";function ly(t,e){if(t.provider)return t.provider;qo(!1,"missing provider","UNSUPPORTED_OPERATION",{operation:e})}async function uy(t,e){let n=Tg(e);if(null!=n.to&&(n.to=Yh(n.to,t)),null!=n.from){const e=n.from;n.from=Promise.all([t.getAddress(),Yh(e,t)]).then((([t,e])=>($o(t.toLowerCase()===e.toLowerCase(),"transaction from mismatch","tx.from",e),t)))}else n.from=t.getAddress();return await jo(n)}class hy{constructor(t){xn(this,"provider"),Ho(this,{provider:t||null})}async getNonce(t){return ly(this,"getTransactionCount").getTransactionCount(await this.getAddress(),t)}async populateCall(t){return await uy(this,t)}async populateTransaction(t){const e=ly(this,"populateTransaction"),n=await uy(this,t);null==n.nonce&&(n.nonce=await this.getNonce("pending")),null==n.gasLimit&&(n.gasLimit=await this.estimateGas(n));const r=await this.provider.getNetwork();if(null!=n.chainId){$o(ya(n.chainId)===r.chainId,"transaction chainId mismatch","tx.chainId",t.chainId)}else n.chainId=r.chainId;const s=null!=n.maxFeePerGas||null!=n.maxPriorityFeePerGas;if(null==n.gasPrice||2!==n.type&&!s?0!==n.type&&1!==n.type||!s||$o(!1,"pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas","tx",t):$o(!1,"eip-1559 transaction do not support gasPrice","tx",t),2!==n.type&&null!=n.type||null==n.maxFeePerGas||null==n.maxPriorityFeePerGas)if(0===n.type||1===n.type){const t=await e.getFeeData();qo(null!=t.gasPrice,"network does not support gasPrice","UNSUPPORTED_OPERATION",{operation:"getGasPrice"}),null==n.gasPrice&&(n.gasPrice=t.gasPrice)}else{const t=await e.getFeeData();if(null==n.type)if(null!=t.maxFeePerGas&&null!=t.maxPriorityFeePerGas)if(n.authorizationList&&n.authorizationList.length?n.type=4:n.type=2,null!=n.gasPrice){const t=n.gasPrice;delete n.gasPrice,n.maxFeePerGas=t,n.maxPriorityFeePerGas=t}else null==n.maxFeePerGas&&(n.maxFeePerGas=t.maxFeePerGas),null==n.maxPriorityFeePerGas&&(n.maxPriorityFeePerGas=t.maxPriorityFeePerGas);else null!=t.gasPrice?(qo(!s,"network does not support EIP-1559","UNSUPPORTED_OPERATION",{operation:"populateTransaction"}),null==n.gasPrice&&(n.gasPrice=t.gasPrice),n.type=0):qo(!1,"failed to get consistent fee data","UNSUPPORTED_OPERATION",{operation:"signer.getFeeData"});else 2!==n.type&&3!==n.type&&4!==n.type||(null==n.maxFeePerGas&&(n.maxFeePerGas=t.maxFeePerGas),null==n.maxPriorityFeePerGas&&(n.maxPriorityFeePerGas=t.maxPriorityFeePerGas))}else n.type=2;return await jo(n)}async populateAuthorization(t){const e=Object.assign({},t);return null==e.chainId&&(e.chainId=(await ly(this,"getNetwork").getNetwork()).chainId),null==e.nonce&&(e.nonce=await this.getNonce()),e}async estimateGas(t){return ly(this,"estimateGas").estimateGas(await this.populateCall(t))}async call(t){return ly(this,"call").call(await this.populateCall(t))}async resolveName(t){const e=ly(this,"resolveName");return await e.resolveName(t)}async sendTransaction(t){const e=ly(this,"sendTransaction"),n=await this.populateTransaction(t);delete n.from;const r=Vd.from(n);return await e.broadcastTransaction(await this.signTransaction(r))}authorize(t){qo(!1,"authorization not implemented for this signer","UNSUPPORTED_OPERATION",{operation:"authorize"})}}qe=new WeakSet,$e=function(t,e){qo(!1,`VoidSigner cannot sign ${t}`,"UNSUPPORTED_OPERATION",{operation:e})};let dy=class t extends hy{constructor(t,e){super(e),Dn(this,qe),xn(this,"address"),Ho(this,{address:t})}async getAddress(){return this.address}connect(e){return new t(this.address,e)}async signTransaction(t){Ln(this,qe,$e).call(this,"transactions","signTransaction")}async signMessage(t){Ln(this,qe,$e).call(this,"messages","signMessage")}async signTypedData(t,e,n){Ln(this,qe,$e).call(this,"typed-data","signTypedData")}};class fy{constructor(t){Dn(this,en),Dn(this,rn),Dn(this,Qe,void 0),Dn(this,Je,void 0),Dn(this,Ye,void 0),Dn(this,Ze,void 0),Dn(this,Xe,void 0),Dn(this,tn,void 0),Bn(this,Qe,t),Bn(this,Je,null),Bn(this,Ye,Ln(this,en,nn).bind(this)),Bn(this,Ze,!1),Bn(this,Xe,null),Bn(this,tn,!1)}_subscribe(t){throw new Error("subclasses must override this")}_emitResults(t,e){throw new Error("subclasses must override this")}_recover(t){throw new Error("subclasses must override this")}start(){Pn(this,Ze)||(Bn(this,Ze,!0),Ln(this,en,nn).call(this,-2))}stop(){Pn(this,Ze)&&(Bn(this,Ze,!1),Bn(this,tn,!0),Ln(this,rn,sn).call(this),Pn(this,Qe).off("block",Pn(this,Ye)))}pause(t){t&&Ln(this,rn,sn).call(this),Pn(this,Qe).off("block",Pn(this,Ye))}resume(){this.start()}}Qe=new WeakMap,Je=new WeakMap,Ye=new WeakMap,Ze=new WeakMap,Xe=new WeakMap,tn=new WeakMap,en=new WeakSet,nn=async function(t){try{null==Pn(this,Je)&&Bn(this,Je,this._subscribe(Pn(this,Qe)));let t=null;try{t=await Pn(this,Je)}catch(e){if(!Wo(e,"UNSUPPORTED_OPERATION")||"eth_newFilter"!==e.operation)throw e}if(null==t)return Bn(this,Je,null),void Pn(this,Qe)._recoverSubscriber(this,this._recover(Pn(this,Qe)));const n=await Pn(this,Qe).getNetwork();if(Pn(this,Xe)||Bn(this,Xe,n),Pn(this,Xe).chainId!==n.chainId)throw new Error("chaid changed");if(Pn(this,tn))return;const r=await Pn(this,Qe).send("eth_getFilterChanges",[t]);await this._emitResults(Pn(this,Qe),r)}catch(e){console.log("@TODO",e)}Pn(this,Qe).once("block",Pn(this,Ye))},rn=new WeakSet,sn=function(){const t=Pn(this,Je);t&&(Bn(this,Je,null),t.then((t=>{Pn(this,Qe).destroyed||Pn(this,Qe).send("eth_uninstallFilter",[t])})))};class py extends fy{constructor(t,e){var n;super(t),Dn(this,on,void 0),Bn(this,on,(n=e,JSON.parse(JSON.stringify(n))))}_recover(t){return new Km(t,Pn(this,on))}async _subscribe(t){return await t.send("eth_newFilter",[Pn(this,on)])}async _emitResults(t,e){for(const n of e)t.emit(Pn(this,on),t._wrapLog(n,t._network))}}on=new WeakMap;class gy extends fy{async _subscribe(t){return await t.send("eth_newPendingTransactionFilter",[])}async _emitResults(t,e){for(const n of e)t.emit("pending",n)}}const my="bigint,boolean,function,number,string,symbol".split(/,/g);function yy(t){if(null==t||my.indexOf(typeof t)>=0)return t;if("function"==typeof t.getAddress)return t;if(Array.isArray(t))return t.map(yy);if("object"==typeof t)return Object.keys(t).reduce(((e,n)=>(e[n]=t[n],e)),{});throw new Error(`should not happen: ${t} (${typeof t})`)}function wy(t){return new Promise((e=>{setTimeout(e,t)}))}function by(t){return t?t.toLowerCase():t}function Ay(t){return t&&"number"==typeof t.pollingInterval}const _y={polling:!1,staticNetwork:null,batchStallTime:10,batchMaxSize:1<<20,batchMaxCount:100,cacheTimeout:250,pollingInterval:4e3};class vy extends hy{constructor(t,e){super(t),xn(this,"address"),Ho(this,{address:e=$h(e)})}connect(t){qo(!1,"cannot reconnect JsonRpcSigner","UNSUPPORTED_OPERATION",{operation:"signer.connect"})}async getAddress(){return this.address}async populateTransaction(t){return await this.populateCall(t)}async sendUncheckedTransaction(t){const e=yy(t),n=[];if(e.from){const r=e.from;n.push((async()=>{const n=await Yh(r,this.provider);$o(null!=n&&n.toLowerCase()===this.address.toLowerCase(),"from address mismatch","transaction",t),e.from=n})())}else e.from=this.address;if(null==e.gasLimit&&n.push((async()=>{e.gasLimit=await this.provider.estimateGas({...e,from:this.address})})()),null!=e.to){const t=e.to;n.push((async()=>{e.to=await Yh(t,this.provider)})())}n.length&&await Promise.all(n);const r=this.provider.getRpcTransaction(e);return this.provider.send("eth_sendTransaction",[r])}async sendTransaction(t){const e=await this.provider.getBlockNumber(),n=await this.sendUncheckedTransaction(t);return await new Promise(((t,r)=>{const s=[1e3,100];let i=0;const o=async()=>{try{const r=await this.provider.getTransaction(n);if(null!=r)return void t(r.replaceableTransaction(e))}catch(a){if(Wo(a,"CANCELLED")||Wo(a,"BAD_DATA")||Wo(a,"NETWORK_ERROR")||Wo(a,"UNSUPPORTED_OPERATION"))return null==a.info&&(a.info={}),a.info.sendTransactionHash=n,void r(a);if(Wo(a,"INVALID_ARGUMENT")&&(i++,null==a.info&&(a.info={}),a.info.sendTransactionHash=n,i>10))return void r(a);this.provider.emit("error",zo("failed to fetch transation after sending (will try again)","UNKNOWN_ERROR",{error:a}))}this.provider._setTimeout((()=>{o()}),s.pop()||4e3)};o()}))}async signTransaction(t){const e=yy(t);if(e.from){const n=await Yh(e.from,this.provider);$o(null!=n&&n.toLowerCase()===this.address.toLowerCase(),"from address mismatch","transaction",t),e.from=n}else e.from=this.address;const n=this.provider.getRpcTransaction(e);return await this.provider.send("eth_signTransaction",[n])}async signMessage(t){const e="string"==typeof t?Da(t):t;return await this.provider.send("personal_sign",[ia(e),this.address.toLowerCase()])}async signTypedData(t,e,n){const r=yy(n),s=await mp.resolveNames(t,e,r,(async t=>{const e=await Yh(t);return $o(null!=e,"TypedData does not support null address","value",t),e}));return await this.provider.send("eth_signTypedData_v4",[this.address.toLowerCase(),JSON.stringify(mp.getPayload(s.domain,e,s.value))])}async unlock(t){return this.provider.send("personal_unlockAccount",[this.address.toLowerCase(),t,null])}async _legacySignMessage(t){const e="string"==typeof t?Da(t):t;return await this.provider.send("eth_sign",[this.address.toLowerCase(),ia(e)])}}class Ey extends ey{constructor(t,e){super(t,e),Dn(this,pn),Dn(this,an,void 0),Dn(this,cn,void 0),Dn(this,ln,void 0),Dn(this,un,void 0),Dn(this,hn,void 0),Dn(this,dn,void 0),Dn(this,fn,void 0),Bn(this,cn,1),Bn(this,an,Object.assign({},_y,e||{})),Bn(this,ln,[]),Bn(this,un,null),Bn(this,dn,null),Bn(this,fn,null);{let t=null;const e=new Promise((e=>{t=e}));Bn(this,hn,{promise:e,resolve:t})}const n=this._getOption("staticNetwork");"boolean"==typeof n?($o(!n||"any"!==t,"staticNetwork cannot be used on special network 'any'","options",e),n&&null!=t&&Bn(this,dn,Bm.from(t))):n&&($o(null==t||n.matches(t),"staticNetwork MUST match network object","options",e),Bn(this,dn,n))}_getOption(t){return Pn(this,an)[t]}get _network(){return qo(Pn(this,dn),"network is not available yet","NETWORK_ERROR"),Pn(this,dn)}async _perform(t){if("call"===t.method||"estimateGas"===t.method){let e=t.transaction;if(e&&null!=e.type&&ya(e.type)&&null==e.maxFeePerGas&&null==e.maxPriorityFeePerGas){const n=await this.getFeeData();null==n.maxFeePerGas&&null==n.maxPriorityFeePerGas&&(t=Object.assign({},t,{transaction:Object.assign({},e,{type:void 0})}))}}const e=this.getRpcRequest(t);return null!=e?await this.send(e.method,e.args):super._perform(t)}async _detectNetwork(){const t=this._getOption("staticNetwork");if(t){if(!0!==t)return t;if(Pn(this,dn))return Pn(this,dn)}return Pn(this,fn)?await Pn(this,fn):this.ready?(Bn(this,fn,(async()=>{try{const t=Bm.from(ya(await this.send("eth_chainId",[])));return Bn(this,fn,null),t}catch(t){throw Bn(this,fn,null),t}})()),await Pn(this,fn)):(Bn(this,fn,(async()=>{const t={id:Un(this,cn)._++,method:"eth_chainId",params:[],jsonrpc:"2.0"};let e;this.emit("debug",{action:"sendRpcPayload",payload:t});try{e=(await this._send(t))[0],Bn(this,fn,null)}catch(n){throw Bn(this,fn,null),this.emit("debug",{action:"receiveRpcError",error:n}),n}if(this.emit("debug",{action:"receiveRpcResult",result:e}),"result"in e)return Bm.from(ya(e.result));throw this.getRpcError(t,e)})()),await Pn(this,fn))}_start(){null!=Pn(this,hn)&&null!=Pn(this,hn).resolve&&(Pn(this,hn).resolve(),Bn(this,hn,null),(async()=>{for(;null==Pn(this,dn)&&!this.destroyed;)try{Bn(this,dn,await this._detectNetwork())}catch(t){if(this.destroyed)break;console.log("JsonRpcProvider failed to detect network and cannot start up; retry in 1s (perhaps the URL is wrong or the node is not started)"),this.emit("error",zo("failed to bootstrap network detection","NETWORK_ERROR",{event:"initial-network-discovery",info:{error:t}})),await wy(1e3)}Ln(this,pn,gn).call(this)})())}async _waitUntilReady(){if(null!=Pn(this,hn))return await Pn(this,hn).promise}_getSubscriber(t){return"pending"===t.type?new gy(this):"event"===t.type?this._getOption("polling")?new Km(this,t.filter):new py(this,t.filter):"orphan"===t.type&&"drop-log"===t.filter.orphan?new Jm("orphan"):super._getSubscriber(t)}get ready(){return null==Pn(this,hn)}getRpcTransaction(t){const e={};return["chainId","gasLimit","gasPrice","type","maxFeePerGas","maxPriorityFeePerGas","nonce","value"].forEach((n=>{if(null==t[n])return;let r=n;"gasLimit"===n&&(r="gas"),e[r]=ka(ya(t[n],`tx.${n}`))})),["from","to","data"].forEach((n=>{null!=t[n]&&(e[n]=ia(t[n]))})),t.accessList&&(e.accessList=_d(t.accessList)),t.blobVersionedHashes&&(e.blobVersionedHashes=t.blobVersionedHashes.map((t=>t.toLowerCase()))),t.authorizationList&&(e.authorizationList=t.authorizationList.map((t=>{const e=vd(t);return{address:e.address,nonce:ka(e.nonce),chainId:ka(e.chainId),yParity:ka(e.signature.yParity),r:ka(e.signature.r),s:ka(e.signature.s)}}))),e}getRpcRequest(t){switch(t.method){case"chainId":return{method:"eth_chainId",args:[]};case"getBlockNumber":return{method:"eth_blockNumber",args:[]};case"getGasPrice":return{method:"eth_gasPrice",args:[]};case"getPriorityFee":return{method:"eth_maxPriorityFeePerGas",args:[]};case"getBalance":return{method:"eth_getBalance",args:[by(t.address),t.blockTag]};case"getTransactionCount":return{method:"eth_getTransactionCount",args:[by(t.address),t.blockTag]};case"getCode":return{method:"eth_getCode",args:[by(t.address),t.blockTag]};case"getStorage":return{method:"eth_getStorageAt",args:[by(t.address),"0x"+t.position.toString(16),t.blockTag]};case"broadcastTransaction":return{method:"eth_sendRawTransaction",args:[t.signedTransaction]};case"getBlock":if("blockTag"in t)return{method:"eth_getBlockByNumber",args:[t.blockTag,!!t.includeTransactions]};if("blockHash"in t)return{method:"eth_getBlockByHash",args:[t.blockHash,!!t.includeTransactions]};break;case"getTransaction":return{method:"eth_getTransactionByHash",args:[t.hash]};case"getTransactionReceipt":return{method:"eth_getTransactionReceipt",args:[t.hash]};case"call":return{method:"eth_call",args:[this.getRpcTransaction(t.transaction),t.blockTag]};case"estimateGas":return{method:"eth_estimateGas",args:[this.getRpcTransaction(t.transaction)]};case"getLogs":return t.filter&&null!=t.filter.address&&(Array.isArray(t.filter.address)?t.filter.address=t.filter.address.map(by):t.filter.address=by(t.filter.address)),{method:"eth_getLogs",args:[t.filter]}}return null}getRpcError(t,e){const{method:n}=t,{error:r}=e;if("eth_estimateGas"===n&&r.message){const e=r.message;if(!e.match(/revert/i)&&e.match(/insufficient funds/i))return zo("insufficient funds","INSUFFICIENT_FUNDS",{transaction:t.params[0],info:{payload:t,error:r}});if(e.match(/nonce/i)&&e.match(/too low/i))return zo("nonce has already been used","NONCE_EXPIRED",{transaction:t.params[0],info:{payload:t,error:r}})}if("eth_call"===n||"eth_estimateGas"===n){const e=Ty(r),s=pg.getBuiltinCallException("eth_call"===n?"call":"estimateGas",t.params[0],e?e.data:null);return s.info={error:r,payload:t},s}const s=JSON.stringify(function(t){const e=[];return Ry(t,e),e}(r));if("string"==typeof r.message&&r.message.match(/user denied|ethers-user-denied/i)){return zo("user rejected action","ACTION_REJECTED",{action:{eth_sign:"signMessage",personal_sign:"signMessage",eth_signTypedData_v4:"signTypedData",eth_signTransaction:"signTransaction",eth_sendTransaction:"sendTransaction",eth_requestAccounts:"requestAccess",wallet_requestAccounts:"requestAccess"}[n]||"unknown",reason:"rejected",info:{payload:t,error:r}})}if("eth_sendRawTransaction"===n||"eth_sendTransaction"===n){const e=t.params[0];if(s.match(/insufficient funds|base fee exceeds gas limit/i))return zo("insufficient funds for intrinsic transaction cost","INSUFFICIENT_FUNDS",{transaction:e,info:{error:r}});if(s.match(/nonce/i)&&s.match(/too low/i))return zo("nonce has already been used","NONCE_EXPIRED",{transaction:e,info:{error:r}});if(s.match(/replacement transaction/i)&&s.match(/underpriced/i))return zo("replacement fee too low","REPLACEMENT_UNDERPRICED",{transaction:e,info:{error:r}});if(s.match(/only replay-protected/i))return zo("legacy pre-eip-155 transactions not supported","UNSUPPORTED_OPERATION",{operation:n,info:{transaction:e,info:{error:r}}})}let i=!!s.match(/the method .* does not exist/i);return i||r&&r.details&&r.details.startsWith("Unauthorized method:")&&(i=!0),i?zo("unsupported operation","UNSUPPORTED_OPERATION",{operation:t.method,info:{error:r,payload:t}}):zo("could not coalesce error","UNKNOWN_ERROR",{error:r,payload:t})}send(t,e){if(this.destroyed)return Promise.reject(zo("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:t}));const n=Un(this,cn)._++,r=new Promise(((r,s)=>{Pn(this,ln).push({resolve:r,reject:s,payload:{method:t,params:e,id:n,jsonrpc:"2.0"}})}));return Ln(this,pn,gn).call(this),r}async getSigner(t){null==t&&(t=0);const e=this.send("eth_accounts",[]);if("number"==typeof t){const n=await e;if(t>=n.length)throw new Error("no such account");return new vy(this,n[t])}const{accounts:n}=await jo({network:this.getNetwork(),accounts:e});t=$h(t);for(const r of n)if($h(r)===t)return new vy(this,t);throw new Error("invalid account")}async listAccounts(){return(await this.send("eth_accounts",[])).map((t=>new vy(this,t)))}destroy(){Pn(this,un)&&(clearTimeout(Pn(this,un)),Bn(this,un,null));for(const{payload:t,reject:e}of Pn(this,ln))e(zo("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:t.method}));Bn(this,ln,[]),super.destroy()}}an=new WeakMap,cn=new WeakMap,ln=new WeakMap,un=new WeakMap,hn=new WeakMap,dn=new WeakMap,fn=new WeakMap,pn=new WeakSet,gn=function(){if(Pn(this,un))return;const t=1===this._getOption("batchMaxCount")?0:this._getOption("batchStallTime");Bn(this,un,setTimeout((()=>{Bn(this,un,null);const t=Pn(this,ln);for(Bn(this,ln,[]);t.length;){const e=[t.shift()];for(;t.length&&e.length!==Pn(this,an).batchMaxCount;){e.push(t.shift());if(JSON.stringify(e.map((t=>t.payload))).length>Pn(this,an).batchMaxSize){t.unshift(e.pop());break}}(async()=>{const t=1===e.length?e[0].payload:e.map((t=>t.payload));this.emit("debug",{action:"sendRpcPayload",payload:t});try{const n=await this._send(t);this.emit("debug",{action:"receiveRpcResult",result:n});for(const{resolve:t,reject:r,payload:s}of e){if(this.destroyed){r(zo("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:s.method}));continue}const e=n.filter((t=>t.id===s.id))[0];if(null!=e)"error"in e?r(this.getRpcError(s,e)):t(e.result);else{const t=zo("missing response for request","BAD_DATA",{value:n,info:{payload:s}});this.emit("error",t),r(t)}}}catch(n){this.emit("debug",{action:"receiveRpcError",error:n});for(const{reject:t}of e)t(n)}})()}}),t))};class ky extends Ey{constructor(t,e){super(t,e),Dn(this,mn,void 0);let n=this._getOption("pollingInterval");null==n&&(n=_y.pollingInterval),Bn(this,mn,n)}_getSubscriber(t){const e=super._getSubscriber(t);return Ay(e)&&(e.pollingInterval=Pn(this,mn)),e}get pollingInterval(){return Pn(this,mn)}set pollingInterval(t){if(!Number.isInteger(t)||t<0)throw new Error("invalid interval");Bn(this,mn,t),this._forEachSubscriber((t=>{Ay(t)&&(t.pollingInterval=Pn(this,mn))}))}}mn=new WeakMap;class Sy extends ky{constructor(t,e,n){null==t&&(t="http://localhost:8545"),super(e,n),Dn(this,yn,void 0),Bn(this,yn,"string"==typeof t?new $a(t):t.clone())}_getConnection(){return Pn(this,yn).clone()}async send(t,e){return await this._start(),await super.send(t,e)}async _send(t){const e=this._getConnection();e.body=JSON.stringify(t),e.setHeader("content-type","application/json");const n=await e.send();n.assertOk();let r=n.bodyJson;return Array.isArray(r)||(r=[r]),r}}function Ty(t){if(null==t)return null;if("string"==typeof t.message&&t.message.match(/revert/i)&&na(t.data))return{message:t.message,data:t.data};if("object"==typeof t){for(const e in t){const n=Ty(t[e]);if(n)return n}return null}if("string"==typeof t)try{return Ty(JSON.parse(t))}catch(e){}return null}function Ry(t,e){if(null!=t){if("string"==typeof t.message&&e.push(t.message),"object"==typeof t)for(const n in t)Ry(t[n],e);if("string"==typeof t)try{return Ry(JSON.parse(t),e)}catch(n){}}}yn=new WeakMap;wn=new WeakMap;let Iy=class t extends hy{constructor(t,e){super(e),xn(this,"address"),Dn(this,wn,void 0),$o(t&&"function"==typeof t.sign,"invalid private key","privateKey","[ REDACTED ]"),Bn(this,wn,t);Ho(this,{address:Ed(this.signingKey.publicKey)})}get signingKey(){return Pn(this,wn)}get privateKey(){return this.signingKey.privateKey}async getAddress(){return this.address}connect(e){return new t(Pn(this,wn),e)}async signTransaction(t){t=Tg(t);const{to:e,from:n}=await jo({to:t.to?Yh(t.to,this):void 0,from:t.from?Yh(t.from,this):void 0});null!=e&&(t.to=e),null!=n&&(t.from=n),null!=t.from&&($o($h(t.from)===this.address,"transaction from address mismatch","tx.from",t.from),delete t.from);const r=Vd.from(t);return r.signature=this.signingKey.sign(r.unsignedHash),r.serialized}async signMessage(t){return this.signMessageSync(t)}signMessageSync(t){return this.signingKey.sign(function(t){return"string"==typeof t&&(t=Da(t)),Bl(oa([Da("Ethereum Signed Message:\n"),Da(String(t.length)),t]))}(t)).serialized}authorizeSync(t){$o("string"==typeof t.address,"invalid address for authorizeSync","auth.address",t);const e=this.signingKey.sign(function(t){return $o("string"==typeof t.address,"invalid address for hashAuthorization","auth.address",t),Bl(oa(["0x05",oc([null!=t.chainId?Ea(t.chainId):"0x",$h(t.address),null!=t.nonce?Ea(t.nonce):"0x"])]))}(t));return Object.assign({},{address:$h(t.address),nonce:ya(t.nonce||0),chainId:ya(t.chainId||0)},{signature:e})}async authorize(t){return t=Object.assign({},t,{address:await Yh(t.address,this)}),this.authorizeSync(await this.populateAuthorization(t))}async signTypedData(t,e,n){const r=await mp.resolveNames(t,e,n,(async t=>{qo(null!=this.provider,"cannot resolve ENS names without a provider","UNSUPPORTED_OPERATION",{operation:"resolveName",info:{name:t}});const e=await this.provider.resolveName(t);return qo(null!=e,"unconfigured ENS name","UNCONFIGURED_NAME",{value:t}),e}));return this.signingKey.sign(mp.hash(r.domain,e,r.value)).serialized}};const Oy=" !#$%&'()*+,-./<=>?@[]^_`{|}~",Cy=/^[a-z]*$/i;function xy(t,e){let n=97;return t.reduce(((t,r)=>(r===e?n++:r.match(Cy)?t.push(String.fromCharCode(n)+r):(n=97,t.push(r)),t)),[])}function Ny(t){return $o("0"===t[0],"unsupported auwl data","data",t),function(t,e){for(let s=28;s>=0;s--)t=t.split(Oy[s]).join(e.substring(2*s,2*s+2));const n=[],r=t.replace(/(:|([0-9])|([A-Z][a-z]*))/g,((t,e,r,s)=>{if(r)for(let i=parseInt(r);i>=0;i--)n.push(";");else n.push(e.toLowerCase());return""}));if(r)throw new Error(`leftovers: ${JSON.stringify(r)}`);return xy(xy(n,";"),":")}(t.substring(59),t.substring(1,59))}class Py{constructor(t){xn(this,"locale"),Ho(this,{locale:t})}split(t){return t.toLowerCase().split(/\s+/g)}join(t){return t.join(" ")}}class Dy extends Py{constructor(t,e,n){super(t),Dn(this,vn),Dn(this,bn,void 0),Dn(this,An,void 0),Dn(this,_n,void 0),Bn(this,bn,e),Bn(this,An,n),Bn(this,_n,null)}get _data(){return Pn(this,bn)}_decodeWords(){return Ny(Pn(this,bn))}getWord(t){const e=Ln(this,vn,En).call(this);return $o(t>=0&&t<e.length,`invalid word index: ${t}`,"index",t),e[t]}getWordIndex(t){return Ln(this,vn,En).call(this).indexOf(t)}}bn=new WeakMap,An=new WeakMap,_n=new WeakMap,vn=new WeakSet,En=function(){if(null==Pn(this,_n)){const t=this._decodeWords();if(Wd(t.join("\n")+"\n")!==Pn(this,An))throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`);Bn(this,_n,t)}return Pn(this,_n)};let By=null;class Uy extends Dy{constructor(){super("en","0erleonalorenseinceregesticitStanvetearctssi#ch2Athck&tneLl0And#Il.yLeOutO=S|S%b/ra@SurdU'0Ce[Cid|CountCu'Hie=IdOu,-Qui*Ro[TT]T%T*[Tu$0AptDD-tD*[Ju,M.UltV<)Vi)0Rob-0FairF%dRaid0A(EEntRee0Ead0MRRp%tS!_rmBumCoholErtI&LLeyLowMo,O}PhaReadySoT Ways0A>urAz(gOngOuntU'd0Aly,Ch%Ci|G G!GryIm$K!Noun)Nu$O` Sw T&naTiqueXietyY1ArtOlogyPe?P!Pro=Ril1ChCt-EaEnaGueMMedM%MyOundR<+Re,Ri=RowTTefa@Ti,Tw%k0KPe@SaultSetSi,SumeThma0H!>OmTa{T&dT.udeTra@0Ct]D.Gu,NtTh%ToTumn0Era+OcadoOid0AkeA*AyEsomeFulKw?d0Is:ByChel%C#D+GL<)Lc#y~MbooN<aNn RRelyRga(R*lSeS-SketTt!3A^AnAutyCau'ComeEfF%eG(Ha=H(dLie=LowLtN^Nef./TrayTt Twe&Y#d3Cyc!DKeNdOlogyRdR`Tt _{AdeAmeAnketA,EakE[IndOodO[omOu'UeUrUsh_rdAtDyIlMbNeNusOkO,Rd R(gRrowSsTtomUn)XY_{etA(AndA[A=EadEezeI{Id+IefIghtIngIskOccoliOk&OnzeOomO` OwnUsh2Bb!DdyD+tFf$oIldLbLkL!tNd!Nk Rd&Rg R,SS(e[SyTt Y Zz:Bba+B(B!CtusGeKe~LmM aMpNN$N)lNdyNn#NoeNvasNy#Pab!P.$Pta(RRb#RdRgoRpetRryRtSeShS(o/!Su$TT$ogT^Teg%yTt!UghtU'Ut]Ve3Il(gL yM|NsusNturyRe$Rta(_irAlkAmp]An+AosApt Ar+A'AtEapE{Ee'EfErryE,I{&IefIldIm}yOi)Oo'R#-U{!UnkUrn0G?Nnam#Rc!Tiz&TyVil_imApArifyAwAyE<ErkEv I{I|IffImbIn-IpO{OgO'O`OudOwnUbUmpU, Ut^_^A,C#utDeFfeeIlInL!@L%LumnMb(eMeMf%tM-Mm#Mp<yNc tNdu@NfirmNg*[N}@Nsid NtrolNv()OkOlPp PyR$ReRnR*@/Tt#U^UntryUp!Ur'Us(V Yo>_{Ad!AftAmA}AshAt AwlAzyEamEd.EekEwI{etImeIspIt-OpO[Ou^OwdUci$UelUi'Umb!Un^UshYY,$2BeLtu*PPbo?dRiousRr|Rta(R=Sh]/omTe3C!:DMa+MpN)Ng R(gShUght WnY3AlBa>BrisCadeCemb CideCl(eC%a>C*a'ErF&'F(eFyG*eLayLiv M<dMi'Ni$Nti,NyP?tP&dPos.P`PutyRi=ScribeS tSignSkSpair/royTailTe@VelopVi)Vo>3AgramAlAm#dAryCeE'lEtFf G.$Gn.yLemmaNn NosaurRe@RtSag*eScov Sea'ShSmi[S%d Splay/<)V tVideV%)Zzy5Ct%Cum|G~Lph(Ma(Na>NkeyN%OrSeUb!Ve_ftAg#AmaA,-AwEamE[IftIllInkIpI=OpUmY2CkMbNeR(g/T^Ty1Arf1Nam-:G G!RlyRnR`Sily/Sy1HoOlogyOnomy0GeItUca>1F%t0G1GhtTh 2BowD E@r-Eg<tEm|Eph<tEvat%I>Se0B?kBodyBra)Er+Ot]PloyPow Pty0Ab!A@DD![D%'EmyErgyF%)Ga+G(eH<)JoyLi,OughR-hRollSu*T Ti*TryVelope1Isode0U$Uip0AA'OdeOs]R%Upt0CapeSayS&)Ta>0Ern$H-s1Id&)IlOkeOl=1A@Amp!Ce[Ch<+C.eCludeCu'Ecu>Erci'Hau,Hib.I!I,ItOt-P<dPe@Pi*Pla(Po'P*[T&dTra0EEbrow:Br-CeCultyDeIntI`~L'MeMilyMousNNcyNtasyRmSh]TT$Th TigueUltV%.e3Atu*Bru?yD $EEdElMa!N)/iv$T^V W3B Ct]EldGu*LeLmLt N$NdNeNg NishReRmR,Sc$ShTT}[X_gAmeAshAtAv%EeIghtIpOatO{O%Ow UidUshY_mCusGIlLd~owOdOtR)Re,R+tRkRtu}RumRw?dSsil/ UndX_gi!AmeEqu|EshI&dIn+OgOntO,OwnOz&U.2ElNNnyRna)RyTu*:D+tInLaxy~ yMePRa+Rba+Rd&Rl-Rm|SSpTeTh U+Ze3N $NiusN*Nt!Nu(e/u*2O,0AntFtGg!Ng RaffeRlVe_dAn)A*A[IdeImp'ObeOomOryO=OwUe_tDde[LdOdO'RillaSpelSsipV nWn_bA)A(AntApeA[Av.yEatE&IdIefItOc yOupOwUnt_rdE[IdeIltIt?N3M:B.IrLfMm M, NdPpyRb%RdRshR=,TVeWkZ?d3AdAl`ArtAvyD+hogIght~oLmetLpNRo3Dd&Gh~NtPRe/%y5BbyCkeyLdLeLiday~owMeNeyOdPeRnRr%R'Sp.$/TelUrV 5BGeM<Mb!M%Nd*dNgryNtRd!RryRtSb<d3Brid:1EOn0EaEntifyLe2N%e4LLeg$L}[0A+Ita>M&'Mu}Pa@Po'Pro=Pul'0ChCludeComeC*a'DexD-a>Do%Du,ryF<tFl-tF%mHa!H .Iti$Je@JuryMa>N Noc|PutQuiryS<eSe@SideSpi*/$lTa@T e,ToVe,V.eVol=3On0L<dOla>Sue0Em1Ory:CketGu?RZz3AlousAns~yWel9BInKeUr}yY5D+I)MpNg!Ni%Nk/:Ng?oo3EnEpT^upY3CkDD}yNdNgdomSsTT^&TeTt&Wi4EeIfeO{Ow:BBelB%Dd DyKeMpNgua+PtopR+T T(UghUndryVaWWnWsu.Y Zy3Ad AfArnA=Ctu*FtGG$G&dIsu*M#NdNg`NsOp?dSs#Tt Vel3ArB tyBr?yC&'FeFtGhtKeMbM.NkOnQuid/Tt!VeZ?d5AdAnB, C$CkG-NelyNgOpTt yUdUn+VeY$5CkyGga+Mb N?N^Xury3R-s:Ch(eDG-G}tIdIlInJ%KeMm$NNa+Nda>NgoNs]Nu$P!Rb!R^Rg(R(eRketRria+SkSs/ T^T i$ThTrixTt XimumZe3AdowAnAsu*AtCh<-D$DiaLodyLtMb M%yNt]NuRcyR+R.RryShSsa+T$Thod3Dd!DnightLk~]M-NdNimumN%Nu>Rac!Rr%S ySs/akeXXedXtu*5Bi!DelDifyMM|N.%NkeyN, N`OnR$ReRn(gSqu.oTh T]T%Unta(U'VeVie5ChFf(LeLtiplySc!SeumShroomS-/Tu$3Self/ yTh:I=MePk(Rrow/yT]Tu*3ArCkEdGati=G!@I` PhewR=/TTw%kUtr$V WsXt3CeGht5B!I'M(eeOd!Rm$R`SeTab!TeTh(gTi)VelW5C!?Mb R'T:K0EyJe@Li+Scu*S =Ta(Vious0CurE<Tob 0Or1FF Fi)T&2L1Ay0DI=Ymp-0It0CeEI#L(eLy1EnEraIn]Po'T]1An+B.Ch?dD D(?yG<I|Ig($Ph<0Tr-h0H 0Tdo%T TputTside0AlEnEr0NN 0Yg&0/ 0O}:CtDd!GeIrLa)LmNdaNelN-N` P RadeR|RkRrotRtySsT^ThTi|TrolTt nU'VeYm|3A)AnutArAs<tL-<NN$tyNcilOp!Pp Rfe@Rm.Rs#T2O}OtoRa'Ys-$0AnoCn-Ctu*E)GGe#~LotNkO} Pe/olT^Zza_)A}tA,-A>AyEa'Ed+U{UgUn+2EmEtIntL?LeLi)NdNyOlPul?Rt]S.]Ssib!/TatoTt yV tyWd W _@i)Ai'Ed-tEf Epa*Es|EttyEv|I)IdeIm?yIntI%.yIs#Iva>IzeOb!mO)[Odu)Of.OgramOje@Omo>OofOp tyOsp O>@OudOvide2Bl-Dd(g~LpL'Mpk(N^PilPpyR^a'R.yRpo'R'ShTZz!3Ramid:99Al.yAntumArt E,]I{ItIzO>:Bb.Cco#CeCkD?DioIlInI'~yMpN^NdomN+PidReTeTh V&WZ%3AdyAlAs#BelBuildC$lCei=CipeC%dCyc!Du)F!@F%mFu'G]G*tGul?Je@LaxLea'LiefLyMa(Memb M(dMo=Nd NewNtOp&PairPeatPla)P%tQui*ScueSemb!Si,Sour)Sp#'SultTi*T*atTurnUn]Ve$ViewW?d2Y`m0BBb#CeChDeD+F!GhtGidNgOtPp!SkTu$V$V 5AdA,BotBu,CketM<)OfOkieOmSeTa>UghUndU>Y$5Bb DeGLeNNwayR$:DDd!D}[FeIlLadLm#L#LtLu>MeMp!NdTisfyToshiU)Usa+VeY1A!AnA*Att E}HemeHoolI&)I[%sOrp]OutRapRe&RiptRub1AAr^As#AtC#dC*tCt]Cur.yEdEkGm|Le@~M(?Ni%N'Nt&)RiesRvi)Ss]Tt!TupV&_dowAftAllowA*EdEllEriffIeldIftI}IpIv O{OeOotOpOrtOuld O=RimpRugUff!Y0Bl(gCkDeE+GhtGnL|Lk~yLv Mil?Mp!N)NgR&/ Tua>XZe1A>Et^IIllInIrtUll0AbAmEepEnd I)IdeIghtImOg<OtOwUsh0AllArtI!OkeOo`0A{AkeApIffOw0ApCc Ci$CkDaFtL?Ldi LidLut]L=Me#eNgOnRryRtUlUndUpUr)U`0A)A*Ati$AwnEakEci$EedEllEndH eI)Id IkeInIr.L.OilOns%O#OrtOtRayReadR(gY0Ua*UeezeUir*l_b!AdiumAffA+AirsAmpAndArtA>AyEakEelEmEpE*oI{IllIngO{Oma^O}OolOryO=Ra>gyReetRikeR#gRugg!Ud|UffUmb!Y!0Bje@Bm.BwayC)[ChDd&Ff G?G+,ItMm NNnyN'tP PplyP*meReRfa)R+Rpri'RroundR=ySpe@/a(1AllowAmpApArmE?EetIftImIngIt^Ord1MbolMptomRup/em:B!Ck!GIlL|LkNkPeR+tSk/eTtooXi3A^Am~NN<tNnisNtRm/Xt_nkAtEmeEnE%yE*EyIngIsOughtReeRi=RowUmbUnd 0CketDeG LtMb MeNyPRedSsueT!5A,BaccoDayDdl EGe` I!tK&MatoM%rowNeNgueNightOlO`PP-Pp!R^RnadoRtoi'SsT$Uri,W?dW WnY_{AdeAff-Ag-A(Ansf ApAshA=lAyEatEeEndI$IbeI{Igg ImIpOphyOub!U{UeUlyUmpetU,U`Y2BeIt]Mb!NaN}lRkeyRnRt!1El=EntyI)InI,O1PeP-$:5Ly5B*lla0Ab!Awa*C!Cov D DoFairFoldHappyIf%mIqueItIv 'KnownLo{TilUsu$Veil1Da>GradeHoldOnP Set1B<Ge0A+EEdEfulE![U$0Il.y:C<tCuumGueLidL!yL=NNishP%Rious/Ult3H-!L=tNd%Ntu*NueRbRifyRs]RyS'lT <3Ab!Br<tCiousCt%yDeoEw~a+Nta+Ol(Rtu$RusSaS.Su$T$Vid5C$I)IdLc<oLumeTeYa+:GeG#ItLk~LnutNtRfa*RmRri%ShSp/eT VeY3Al`Ap#ArA'lA` BDd(gEk&dIrdLcome/T_!AtEatEelEnE*IpIsp 0DeD`FeLd~NNdowNeNgNkNn Nt ReSdomSeShT}[5LfM<Nd OdOlRdRkRldRryR`_pE{E,!I,I>Ong::Rd3Ar~ow9UUngU`:3BraRo9NeO","0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60")}static wordlist(){return null==By&&(By=new Uy),By}}function Ly(t){return(1<<t)-1<<8-t&255}function My(t,e){Yo("NFKD"),null==e&&(e=Uy.wordlist());const n=e.split(t);$o(n.length%3==0&&n.length>=12&&n.length<=24,"invalid mnemonic length","mnemonic","[ REDACTED ]");const r=new Uint8Array(Math.ceil(11*n.length/8));let s=0;for(let a=0;a<n.length;a++){let t=e.getWordIndex(n[a].normalize("NFKD"));$o(t>=0,`invalid mnemonic word at index ${a}`,"mnemonic","[ REDACTED ]");for(let e=0;e<11;e++)t&1<<10-e&&(r[s>>3]|=1<<7-s%8),s++}const i=32*n.length/3,o=Ly(n.length/3);return $o((ta(ku(r.slice(0,i/8)))[0]&o)===(r[r.length-1]&o),"invalid mnemonic checksum","mnemonic","[ REDACTED ]"),ia(r.slice(0,i/8))}function Fy(t,e){$o(t.length%4==0&&t.length>=16&&t.length<=32,"invalid entropy size","entropy","[ REDACTED ]"),null==e&&(e=Uy.wordlist());const n=[0];let r=11;for(let o=0;o<t.length;o++)r>8?(n[n.length-1]<<=8,n[n.length-1]|=t[o],r-=8):(n[n.length-1]<<=r,n[n.length-1]|=t[o]>>8-r,n.push(t[o]&((1<<8-r)-1&255)),r+=3);const s=t.length/4,i=parseInt(ku(t).substring(2,4),16)&Ly(s);return n[n.length-1]<<=s,n[n.length-1]|=i>>8-s,e.join(n.map((t=>e.getWord(t))))}const Gy={};class jy{constructor(t,e,n,r,s){xn(this,"phrase"),xn(this,"password"),xn(this,"wordlist"),xn(this,"entropy"),null==r&&(r=""),null==s&&(s=Uy.wordlist()),Zo(t,Gy,"Mnemonic"),Ho(this,{phrase:n,password:r,wordlist:s,entropy:e})}computeSeed(){const t=Da("mnemonic"+this.password,"NFKD");return ru(Da(this.phrase,"NFKD"),t,2048,64,"sha512")}static fromPhrase(t,e,n){const r=My(t,n);return t=Fy(ta(r),n),new jy(Gy,r,t,e,n)}static fromEntropy(t,e,n){const r=ta(t,"entropy"),s=Fy(r,n);return new jy(Gy,ia(r),s,e,n)}static entropyToPhrase(t,e){return Fy(ta(t,"entropy"),e)}static phraseToEntropy(t,e){return My(t,e)}static isValidMnemonic(t,e){try{return My(t,e),!0}catch(n){}return!1}}
12
+ /*! MIT License. Copyright 2015-2022 Richard Moore <me@ricmoo.com>. See LICENSE.txt. */var Hy,Vy,Wy,Ky=globalThis&&globalThis.__classPrivateFieldGet||function(t,e,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(t):r?r.value:e.get(t)},zy=globalThis&&globalThis.__classPrivateFieldSet||function(t,e,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(t,n):s?s.value=n:e.set(t,n),n};const qy={16:10,24:12,32:14},$y=[1,2,4,8,16,32,64,128,27,54,108,216,171,77,154,47,94,188,99,198,151,53,106,212,179,125,250,239,197,145],Qy=[99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22],Jy=[82,9,106,213,48,54,165,56,191,64,163,158,129,243,215,251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50,166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91,162,73,109,139,209,37,114,248,246,100,134,104,152,22,212,164,92,204,93,101,182,146,108,112,72,80,253,237,185,218,94,21,70,87,167,141,157,132,144,216,171,0,140,188,211,10,247,228,88,5,184,179,69,6,208,44,30,143,202,63,15,2,193,175,189,3,1,19,138,107,58,145,17,65,79,103,220,234,151,242,207,206,240,180,230,115,150,172,116,34,231,173,53,133,226,249,55,232,28,117,223,110,71,241,26,113,29,41,197,137,111,183,98,14,170,24,190,27,252,86,62,75,198,210,121,32,154,219,192,254,120,205,90,244,31,221,168,51,136,7,199,49,177,18,16,89,39,128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224,59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38,225,105,20,99,85,33,12,125],Yy=[3328402341,4168907908,4000806809,4135287693,4294111757,3597364157,3731845041,2445657428,1613770832,33620227,3462883241,1445669757,3892248089,3050821474,1303096294,3967186586,2412431941,528646813,2311702848,4202528135,4026202645,2992200171,2387036105,4226871307,1101901292,3017069671,1604494077,1169141738,597466303,1403299063,3832705686,2613100635,1974974402,3791519004,1033081774,1277568618,1815492186,2118074177,4126668546,2211236943,1748251740,1369810420,3521504564,4193382664,3799085459,2883115123,1647391059,706024767,134480908,2512897874,1176707941,2646852446,806885416,932615841,168101135,798661301,235341577,605164086,461406363,3756188221,3454790438,1311188841,2142417613,3933566367,302582043,495158174,1479289972,874125870,907746093,3698224818,3025820398,1537253627,2756858614,1983593293,3084310113,2108928974,1378429307,3722699582,1580150641,327451799,2790478837,3117535592,0,3253595436,1075847264,3825007647,2041688520,3059440621,3563743934,2378943302,1740553945,1916352843,2487896798,2555137236,2958579944,2244988746,3151024235,3320835882,1336584933,3992714006,2252555205,2588757463,1714631509,293963156,2319795663,3925473552,67240454,4269768577,2689618160,2017213508,631218106,1269344483,2723238387,1571005438,2151694528,93294474,1066570413,563977660,1882732616,4059428100,1673313503,2008463041,2950355573,1109467491,537923632,3858759450,4260623118,3218264685,2177748300,403442708,638784309,3287084079,3193921505,899127202,2286175436,773265209,2479146071,1437050866,4236148354,2050833735,3362022572,3126681063,840505643,3866325909,3227541664,427917720,2655997905,2749160575,1143087718,1412049534,999329963,193497219,2353415882,3354324521,1807268051,672404540,2816401017,3160301282,369822493,2916866934,3688947771,1681011286,1949973070,336202270,2454276571,201721354,1210328172,3093060836,2680341085,3184776046,1135389935,3294782118,965841320,831886756,3554993207,4068047243,3588745010,2345191491,1849112409,3664604599,26054028,2983581028,2622377682,1235855840,3630984372,2891339514,4092916743,3488279077,3395642799,4101667470,1202630377,268961816,1874508501,4034427016,1243948399,1546530418,941366308,1470539505,1941222599,2546386513,3421038627,2715671932,3899946140,1042226977,2521517021,1639824860,227249030,260737669,3765465232,2084453954,1907733956,3429263018,2420656344,100860677,4160157185,470683154,3261161891,1781871967,2924959737,1773779408,394692241,2579611992,974986535,664706745,3655459128,3958962195,731420851,571543859,3530123707,2849626480,126783113,865375399,765172662,1008606754,361203602,3387549984,2278477385,2857719295,1344809080,2782912378,59542671,1503764984,160008576,437062935,1707065306,3622233649,2218934982,3496503480,2185314755,697932208,1512910199,504303377,2075177163,2824099068,1841019862,739644986],Zy=[2781242211,2230877308,2582542199,2381740923,234877682,3184946027,2984144751,1418839493,1348481072,50462977,2848876391,2102799147,434634494,1656084439,3863849899,2599188086,1167051466,2636087938,1082771913,2281340285,368048890,3954334041,3381544775,201060592,3963727277,1739838676,4250903202,3930435503,3206782108,4149453988,2531553906,1536934080,3262494647,484572669,2923271059,1783375398,1517041206,1098792767,49674231,1334037708,1550332980,4098991525,886171109,150598129,2481090929,1940642008,1398944049,1059722517,201851908,1385547719,1699095331,1587397571,674240536,2704774806,252314885,3039795866,151914247,908333586,2602270848,1038082786,651029483,1766729511,3447698098,2682942837,454166793,2652734339,1951935532,775166490,758520603,3000790638,4004797018,4217086112,4137964114,1299594043,1639438038,3464344499,2068982057,1054729187,1901997871,2534638724,4121318227,1757008337,0,750906861,1614815264,535035132,3363418545,3988151131,3201591914,1183697867,3647454910,1265776953,3734260298,3566750796,3903871064,1250283471,1807470800,717615087,3847203498,384695291,3313910595,3617213773,1432761139,2484176261,3481945413,283769337,100925954,2180939647,4037038160,1148730428,3123027871,3813386408,4087501137,4267549603,3229630528,2315620239,2906624658,3156319645,1215313976,82966005,3747855548,3245848246,1974459098,1665278241,807407632,451280895,251524083,1841287890,1283575245,337120268,891687699,801369324,3787349855,2721421207,3431482436,959321879,1469301956,4065699751,2197585534,1199193405,2898814052,3887750493,724703513,2514908019,2696962144,2551808385,3516813135,2141445340,1715741218,2119445034,2872807568,2198571144,3398190662,700968686,3547052216,1009259540,2041044702,3803995742,487983883,1991105499,1004265696,1449407026,1316239930,504629770,3683797321,168560134,1816667172,3837287516,1570751170,1857934291,4014189740,2797888098,2822345105,2754712981,936633572,2347923833,852879335,1133234376,1500395319,3084545389,2348912013,1689376213,3533459022,3762923945,3034082412,4205598294,133428468,634383082,2949277029,2398386810,3913789102,403703816,3580869306,2297460856,1867130149,1918643758,607656988,4049053350,3346248884,1368901318,600565992,2090982877,2632479860,557719327,3717614411,3697393085,2249034635,2232388234,2430627952,1115438654,3295786421,2865522278,3633334344,84280067,33027830,303828494,2747425121,1600795957,4188952407,3496589753,2434238086,1486471617,658119965,3106381470,953803233,334231800,3005978776,857870609,3151128937,1890179545,2298973838,2805175444,3056442267,574365214,2450884487,550103529,1233637070,4289353045,2018519080,2057691103,2399374476,4166623649,2148108681,387583245,3664101311,836232934,3330556482,3100665960,3280093505,2955516313,2002398509,287182607,3413881008,4238890068,3597515707,975967766],Xy=[1671808611,2089089148,2006576759,2072901243,4061003762,1807603307,1873927791,3310653893,810573872,16974337,1739181671,729634347,4263110654,3613570519,2883997099,1989864566,3393556426,2191335298,3376449993,2106063485,4195741690,1508618841,1204391495,4027317232,2917941677,3563566036,2734514082,2951366063,2629772188,2767672228,1922491506,3227229120,3082974647,4246528509,2477669779,644500518,911895606,1061256767,4144166391,3427763148,878471220,2784252325,3845444069,4043897329,1905517169,3631459288,827548209,356461077,67897348,3344078279,593839651,3277757891,405286936,2527147926,84871685,2595565466,118033927,305538066,2157648768,3795705826,3945188843,661212711,2999812018,1973414517,152769033,2208177539,745822252,439235610,455947803,1857215598,1525593178,2700827552,1391895634,994932283,3596728278,3016654259,695947817,3812548067,795958831,2224493444,1408607827,3513301457,0,3979133421,543178784,4229948412,2982705585,1542305371,1790891114,3410398667,3201918910,961245753,1256100938,1289001036,1491644504,3477767631,3496721360,4012557807,2867154858,4212583931,1137018435,1305975373,861234739,2241073541,1171229253,4178635257,33948674,2139225727,1357946960,1011120188,2679776671,2833468328,1374921297,2751356323,1086357568,2408187279,2460827538,2646352285,944271416,4110742005,3168756668,3066132406,3665145818,560153121,271589392,4279952895,4077846003,3530407890,3444343245,202643468,322250259,3962553324,1608629855,2543990167,1154254916,389623319,3294073796,2817676711,2122513534,1028094525,1689045092,1575467613,422261273,1939203699,1621147744,2174228865,1339137615,3699352540,577127458,712922154,2427141008,2290289544,1187679302,3995715566,3100863416,339486740,3732514782,1591917662,186455563,3681988059,3762019296,844522546,978220090,169743370,1239126601,101321734,611076132,1558493276,3260915650,3547250131,2901361580,1655096418,2443721105,2510565781,3828863972,2039214713,3878868455,3359869896,928607799,1840765549,2374762893,3580146133,1322425422,2850048425,1823791212,1459268694,4094161908,3928346602,1706019429,2056189050,2934523822,135794696,3134549946,2022240376,628050469,779246638,472135708,2800834470,3032970164,3327236038,3894660072,3715932637,1956440180,522272287,1272813131,3185336765,2340818315,2323976074,1888542832,1044544574,3049550261,1722469478,1222152264,50660867,4127324150,236067854,1638122081,895445557,1475980887,3117443513,2257655686,3243809217,489110045,2662934430,3778599393,4162055160,2561878936,288563729,1773916777,3648039385,2391345038,2493985684,2612407707,505560094,2274497927,3911240169,3460925390,1442818645,678973480,3749357023,2358182796,2717407649,2306869641,219617805,3218761151,3862026214,1120306242,1756942440,1103331905,2578459033,762796589,252780047,2966125488,1425844308,3151392187,372911126],tw=[1667474886,2088535288,2004326894,2071694838,4075949567,1802223062,1869591006,3318043793,808472672,16843522,1734846926,724270422,4278065639,3621216949,2880169549,1987484396,3402253711,2189597983,3385409673,2105378810,4210693615,1499065266,1195886990,4042263547,2913856577,3570689971,2728590687,2947541573,2627518243,2762274643,1920112356,3233831835,3082273397,4261223649,2475929149,640051788,909531756,1061110142,4160160501,3435941763,875846760,2779116625,3857003729,4059105529,1903268834,3638064043,825316194,353713962,67374088,3351728789,589522246,3284360861,404236336,2526454071,84217610,2593830191,117901582,303183396,2155911963,3806477791,3958056653,656894286,2998062463,1970642922,151591698,2206440989,741110872,437923380,454765878,1852748508,1515908788,2694904667,1381168804,993742198,3604373943,3014905469,690584402,3823320797,791638366,2223281939,1398011302,3520161977,0,3991743681,538992704,4244381667,2981218425,1532751286,1785380564,3419096717,3200178535,960056178,1246420628,1280103576,1482221744,3486468741,3503319995,4025428677,2863326543,4227536621,1128514950,1296947098,859002214,2240123921,1162203018,4193849577,33687044,2139062782,1347481760,1010582648,2678045221,2829640523,1364325282,2745433693,1077985408,2408548869,2459086143,2644360225,943212656,4126475505,3166494563,3065430391,3671750063,555836226,269496352,4294908645,4092792573,3537006015,3452783745,202118168,320025894,3974901699,1600119230,2543297077,1145359496,387397934,3301201811,2812801621,2122220284,1027426170,1684319432,1566435258,421079858,1936954854,1616945344,2172753945,1330631070,3705438115,572679748,707427924,2425400123,2290647819,1179044492,4008585671,3099120491,336870440,3739122087,1583276732,185277718,3688593069,3772791771,842159716,976899700,168435220,1229577106,101059084,606366792,1549591736,3267517855,3553849021,2897014595,1650632388,2442242105,2509612081,3840161747,2038008818,3890688725,3368567691,926374254,1835907034,2374863873,3587531953,1313788572,2846482505,1819063512,1448540844,4109633523,3941213647,1701162954,2054852340,2930698567,134748176,3132806511,2021165296,623210314,774795868,471606328,2795958615,3031746419,3334885783,3907527627,3722280097,1953799400,522133822,1263263126,3183336545,2341176845,2324333839,1886425312,1044267644,3048588401,1718004428,1212733584,50529542,4143317495,235803164,1633788866,892690282,1465383342,3115962473,2256965911,3250673817,488449850,2661202215,3789633753,4177007595,2560144171,286339874,1768537042,3654906025,2391705863,2492770099,2610673197,505291324,2273808917,3924369609,3469625735,1431699370,673740880,3755965093,2358021891,2711746649,2307489801,218961690,3217021541,3873845719,1111672452,1751693520,1094828930,2576986153,757954394,252645662,2964376443,1414855848,3149649517,370555436],ew=[1374988112,2118214995,437757123,975658646,1001089995,530400753,2902087851,1273168787,540080725,2910219766,2295101073,4110568485,1340463100,3307916247,641025152,3043140495,3736164937,632953703,1172967064,1576976609,3274667266,2169303058,2370213795,1809054150,59727847,361929877,3211623147,2505202138,3569255213,1484005843,1239443753,2395588676,1975683434,4102977912,2572697195,666464733,3202437046,4035489047,3374361702,2110667444,1675577880,3843699074,2538681184,1649639237,2976151520,3144396420,4269907996,4178062228,1883793496,2403728665,2497604743,1383856311,2876494627,1917518562,3810496343,1716890410,3001755655,800440835,2261089178,3543599269,807962610,599762354,33778362,3977675356,2328828971,2809771154,4077384432,1315562145,1708848333,101039829,3509871135,3299278474,875451293,2733856160,92987698,2767645557,193195065,1080094634,1584504582,3178106961,1042385657,2531067453,3711829422,1306967366,2438237621,1908694277,67556463,1615861247,429456164,3602770327,2302690252,1742315127,2968011453,126454664,3877198648,2043211483,2709260871,2084704233,4169408201,0,159417987,841739592,504459436,1817866830,4245618683,260388950,1034867998,908933415,168810852,1750902305,2606453969,607530554,202008497,2472011535,3035535058,463180190,2160117071,1641816226,1517767529,470948374,3801332234,3231722213,1008918595,303765277,235474187,4069246893,766945465,337553864,1475418501,2943682380,4003061179,2743034109,4144047775,1551037884,1147550661,1543208500,2336434550,3408119516,3069049960,3102011747,3610369226,1113818384,328671808,2227573024,2236228733,3535486456,2935566865,3341394285,496906059,3702665459,226906860,2009195472,733156972,2842737049,294930682,1206477858,2835123396,2700099354,1451044056,573804783,2269728455,3644379585,2362090238,2564033334,2801107407,2776292904,3669462566,1068351396,742039012,1350078989,1784663195,1417561698,4136440770,2430122216,775550814,2193862645,2673705150,1775276924,1876241833,3475313331,3366754619,270040487,3902563182,3678124923,3441850377,1851332852,3969562369,2203032232,3868552805,2868897406,566021896,4011190502,3135740889,1248802510,3936291284,699432150,832877231,708780849,3332740144,899835584,1951317047,4236429990,3767586992,866637845,4043610186,1106041591,2144161806,395441711,1984812685,1139781709,3433712980,3835036895,2664543715,1282050075,3240894392,1181045119,2640243204,25965917,4203181171,4211818798,3009879386,2463879762,3910161971,1842759443,2597806476,933301370,1509430414,3943906441,3467192302,3076639029,3776767469,2051518780,2631065433,1441952575,404016761,1942435775,1408749034,1610459739,3745345300,2017778566,3400528769,3110650942,941896748,3265478751,371049330,3168937228,675039627,4279080257,967311729,135050206,3635733660,1683407248,2076935265,3576870512,1215061108,3501741890],nw=[1347548327,1400783205,3273267108,2520393566,3409685355,4045380933,2880240216,2471224067,1428173050,4138563181,2441661558,636813900,4233094615,3620022987,2149987652,2411029155,1239331162,1730525723,2554718734,3781033664,46346101,310463728,2743944855,3328955385,3875770207,2501218972,3955191162,3667219033,768917123,3545789473,692707433,1150208456,1786102409,2029293177,1805211710,3710368113,3065962831,401639597,1724457132,3028143674,409198410,2196052529,1620529459,1164071807,3769721975,2226875310,486441376,2499348523,1483753576,428819965,2274680428,3075636216,598438867,3799141122,1474502543,711349675,129166120,53458370,2592523643,2782082824,4063242375,2988687269,3120694122,1559041666,730517276,2460449204,4042459122,2706270690,3446004468,3573941694,533804130,2328143614,2637442643,2695033685,839224033,1973745387,957055980,2856345839,106852767,1371368976,4181598602,1033297158,2933734917,1179510461,3046200461,91341917,1862534868,4284502037,605657339,2547432937,3431546947,2003294622,3182487618,2282195339,954669403,3682191598,1201765386,3917234703,3388507166,0,2198438022,1211247597,2887651696,1315723890,4227665663,1443857720,507358933,657861945,1678381017,560487590,3516619604,975451694,2970356327,261314535,3535072918,2652609425,1333838021,2724322336,1767536459,370938394,182621114,3854606378,1128014560,487725847,185469197,2918353863,3106780840,3356761769,2237133081,1286567175,3152976349,4255350624,2683765030,3160175349,3309594171,878443390,1988838185,3704300486,1756818940,1673061617,3403100636,272786309,1075025698,545572369,2105887268,4174560061,296679730,1841768865,1260232239,4091327024,3960309330,3497509347,1814803222,2578018489,4195456072,575138148,3299409036,446754879,3629546796,4011996048,3347532110,3252238545,4270639778,915985419,3483825537,681933534,651868046,2755636671,3828103837,223377554,2607439820,1649704518,3270937875,3901806776,1580087799,4118987695,3198115200,2087309459,2842678573,3016697106,1003007129,2802849917,1860738147,2077965243,164439672,4100872472,32283319,2827177882,1709610350,2125135846,136428751,3874428392,3652904859,3460984630,3572145929,3593056380,2939266226,824852259,818324884,3224740454,930369212,2801566410,2967507152,355706840,1257309336,4148292826,243256656,790073846,2373340630,1296297904,1422699085,3756299780,3818836405,457992840,3099667487,2135319889,77422314,1560382517,1945798516,788204353,1521706781,1385356242,870912086,325965383,2358957921,2050466060,2388260884,2313884476,4006521127,901210569,3990953189,1014646705,1503449823,1062597235,2031621326,3212035895,3931371469,1533017514,350174575,2256028891,2177544179,1052338372,741876788,1606591296,1914052035,213705253,2334669897,1107234197,1899603969,3725069491,2631447780,2422494913,1635502980,1893020342,1950903388,1120974935],rw=[2807058932,1699970625,2764249623,1586903591,1808481195,1173430173,1487645946,59984867,4199882800,1844882806,1989249228,1277555970,3623636965,3419915562,1149249077,2744104290,1514790577,459744698,244860394,3235995134,1963115311,4027744588,2544078150,4190530515,1608975247,2627016082,2062270317,1507497298,2200818878,567498868,1764313568,3359936201,2305455554,2037970062,1047239e3,1910319033,1337376481,2904027272,2892417312,984907214,1243112415,830661914,861968209,2135253587,2011214180,2927934315,2686254721,731183368,1750626376,4246310725,1820824798,4172763771,3542330227,48394827,2404901663,2871682645,671593195,3254988725,2073724613,145085239,2280796200,2779915199,1790575107,2187128086,472615631,3029510009,4075877127,3802222185,4107101658,3201631749,1646252340,4270507174,1402811438,1436590835,3778151818,3950355702,3963161475,4020912224,2667994737,273792366,2331590177,104699613,95345982,3175501286,2377486676,1560637892,3564045318,369057872,4213447064,3919042237,1137477952,2658625497,1119727848,2340947849,1530455833,4007360968,172466556,266959938,516552836,0,2256734592,3980931627,1890328081,1917742170,4294704398,945164165,3575528878,958871085,3647212047,2787207260,1423022939,775562294,1739656202,3876557655,2530391278,2443058075,3310321856,547512796,1265195639,437656594,3121275539,719700128,3762502690,387781147,218828297,3350065803,2830708150,2848461854,428169201,122466165,3720081049,1627235199,648017665,4122762354,1002783846,2117360635,695634755,3336358691,4234721005,4049844452,3704280881,2232435299,574624663,287343814,612205898,1039717051,840019705,2708326185,793451934,821288114,1391201670,3822090177,376187827,3113855344,1224348052,1679968233,2361698556,1058709744,752375421,2431590963,1321699145,3519142200,2734591178,188127444,2177869557,3727205754,2384911031,3215212461,2648976442,2450346104,3432737375,1180849278,331544205,3102249176,4150144569,2952102595,2159976285,2474404304,766078933,313773861,2570832044,2108100632,1668212892,3145456443,2013908262,418672217,3070356634,2594734927,1852171925,3867060991,3473416636,3907448597,2614737639,919489135,164948639,2094410160,2997825956,590424639,2486224549,1723872674,3157750862,3399941250,3501252752,3625268135,2555048196,3673637356,1343127501,4130281361,3599595085,2957853679,1297403050,81781910,3051593425,2283490410,532201772,1367295589,3926170974,895287692,1953757831,1093597963,492483431,3528626907,1446242576,1192455638,1636604631,209336225,344873464,1015671571,669961897,3375740769,3857572124,2973530695,3747192018,1933530610,3464042516,935293895,3454686199,2858115069,1863638845,3683022916,4085369519,3292445032,875313188,1080017571,3279033885,621591778,1233856572,2504130317,24197544,3017672716,3835484340,3247465558,2220981195,3060847922,1551124588,1463996600],sw=[4104605777,1097159550,396673818,660510266,2875968315,2638606623,4200115116,3808662347,821712160,1986918061,3430322568,38544885,3856137295,718002117,893681702,1654886325,2975484382,3122358053,3926825029,4274053469,796197571,1290801793,1184342925,3556361835,2405426947,2459735317,1836772287,1381620373,3196267988,1948373848,3764988233,3385345166,3263785589,2390325492,1480485785,3111247143,3780097726,2293045232,548169417,3459953789,3746175075,439452389,1362321559,1400849762,1685577905,1806599355,2174754046,137073913,1214797936,1174215055,3731654548,2079897426,1943217067,1258480242,529487843,1437280870,3945269170,3049390895,3313212038,923313619,679998e3,3215307299,57326082,377642221,3474729866,2041877159,133361907,1776460110,3673476453,96392454,878845905,2801699524,777231668,4082475170,2330014213,4142626212,2213296395,1626319424,1906247262,1846563261,562755902,3708173718,1040559837,3871163981,1418573201,3294430577,114585348,1343618912,2566595609,3186202582,1078185097,3651041127,3896688048,2307622919,425408743,3371096953,2081048481,1108339068,2216610296,0,2156299017,736970802,292596766,1517440620,251657213,2235061775,2933202493,758720310,265905162,1554391400,1532285339,908999204,174567692,1474760595,4002861748,2610011675,3234156416,3693126241,2001430874,303699484,2478443234,2687165888,585122620,454499602,151849742,2345119218,3064510765,514443284,4044981591,1963412655,2581445614,2137062819,19308535,1928707164,1715193156,4219352155,1126790795,600235211,3992742070,3841024952,836553431,1669664834,2535604243,3323011204,1243905413,3141400786,4180808110,698445255,2653899549,2989552604,2253581325,3252932727,3004591147,1891211689,2487810577,3915653703,4237083816,4030667424,2100090966,865136418,1229899655,953270745,3399679628,3557504664,4118925222,2061379749,3079546586,2915017791,983426092,2022837584,1607244650,2118541908,2366882550,3635996816,972512814,3283088770,1568718495,3499326569,3576539503,621982671,2895723464,410887952,2623762152,1002142683,645401037,1494807662,2595684844,1335535747,2507040230,4293295786,3167684641,367585007,3885750714,1865862730,2668221674,2960971305,2763173681,1059270954,2777952454,2724642869,1320957812,2194319100,2429595872,2815956275,77089521,3973773121,3444575871,2448830231,1305906550,4021308739,2857194700,2516901860,3518358430,1787304780,740276417,1699839814,1592394909,2352307457,2272556026,188821243,1729977011,3687994002,274084841,3594982253,3613494426,2701949495,4162096729,322734571,2837966542,1640576439,484830689,1202797690,3537852828,4067639125,349075736,3342319475,4157467219,4255800159,1030690015,1155237496,2951971274,1757691577,607398968,2738905026,499347990,3794078908,1011452712,227885567,2818666809,213114376,3034881240,1455525988,3414450555,850817237,1817998408,3092726480],iw=[0,235474187,470948374,303765277,941896748,908933415,607530554,708780849,1883793496,2118214995,1817866830,1649639237,1215061108,1181045119,1417561698,1517767529,3767586992,4003061179,4236429990,4069246893,3635733660,3602770327,3299278474,3400528769,2430122216,2664543715,2362090238,2193862645,2835123396,2801107407,3035535058,3135740889,3678124923,3576870512,3341394285,3374361702,3810496343,3977675356,4279080257,4043610186,2876494627,2776292904,3076639029,3110650942,2472011535,2640243204,2403728665,2169303058,1001089995,899835584,666464733,699432150,59727847,226906860,530400753,294930682,1273168787,1172967064,1475418501,1509430414,1942435775,2110667444,1876241833,1641816226,2910219766,2743034109,2976151520,3211623147,2505202138,2606453969,2302690252,2269728455,3711829422,3543599269,3240894392,3475313331,3843699074,3943906441,4178062228,4144047775,1306967366,1139781709,1374988112,1610459739,1975683434,2076935265,1775276924,1742315127,1034867998,866637845,566021896,800440835,92987698,193195065,429456164,395441711,1984812685,2017778566,1784663195,1683407248,1315562145,1080094634,1383856311,1551037884,101039829,135050206,437757123,337553864,1042385657,807962610,573804783,742039012,2531067453,2564033334,2328828971,2227573024,2935566865,2700099354,3001755655,3168937228,3868552805,3902563182,4203181171,4102977912,3736164937,3501741890,3265478751,3433712980,1106041591,1340463100,1576976609,1408749034,2043211483,2009195472,1708848333,1809054150,832877231,1068351396,766945465,599762354,159417987,126454664,361929877,463180190,2709260871,2943682380,3178106961,3009879386,2572697195,2538681184,2236228733,2336434550,3509871135,3745345300,3441850377,3274667266,3910161971,3877198648,4110568485,4211818798,2597806476,2497604743,2261089178,2295101073,2733856160,2902087851,3202437046,2968011453,3936291284,3835036895,4136440770,4169408201,3535486456,3702665459,3467192302,3231722213,2051518780,1951317047,1716890410,1750902305,1113818384,1282050075,1584504582,1350078989,168810852,67556463,371049330,404016761,841739592,1008918595,775550814,540080725,3969562369,3801332234,4035489047,4269907996,3569255213,3669462566,3366754619,3332740144,2631065433,2463879762,2160117071,2395588676,2767645557,2868897406,3102011747,3069049960,202008497,33778362,270040487,504459436,875451293,975658646,675039627,641025152,2084704233,1917518562,1615861247,1851332852,1147550661,1248802510,1484005843,1451044056,933301370,967311729,733156972,632953703,260388950,25965917,328671808,496906059,1206477858,1239443753,1543208500,1441952575,2144161806,1908694277,1675577880,1842759443,3610369226,3644379585,3408119516,3307916247,4011190502,3776767469,4077384432,4245618683,2809771154,2842737049,3144396420,3043140495,2673705150,2438237621,2203032232,2370213795],ow=[0,185469197,370938394,487725847,741876788,657861945,975451694,824852259,1483753576,1400783205,1315723890,1164071807,1950903388,2135319889,1649704518,1767536459,2967507152,3152976349,2801566410,2918353863,2631447780,2547432937,2328143614,2177544179,3901806776,3818836405,4270639778,4118987695,3299409036,3483825537,3535072918,3652904859,2077965243,1893020342,1841768865,1724457132,1474502543,1559041666,1107234197,1257309336,598438867,681933534,901210569,1052338372,261314535,77422314,428819965,310463728,3409685355,3224740454,3710368113,3593056380,3875770207,3960309330,4045380933,4195456072,2471224067,2554718734,2237133081,2388260884,3212035895,3028143674,2842678573,2724322336,4138563181,4255350624,3769721975,3955191162,3667219033,3516619604,3431546947,3347532110,2933734917,2782082824,3099667487,3016697106,2196052529,2313884476,2499348523,2683765030,1179510461,1296297904,1347548327,1533017514,1786102409,1635502980,2087309459,2003294622,507358933,355706840,136428751,53458370,839224033,957055980,605657339,790073846,2373340630,2256028891,2607439820,2422494913,2706270690,2856345839,3075636216,3160175349,3573941694,3725069491,3273267108,3356761769,4181598602,4063242375,4011996048,3828103837,1033297158,915985419,730517276,545572369,296679730,446754879,129166120,213705253,1709610350,1860738147,1945798516,2029293177,1239331162,1120974935,1606591296,1422699085,4148292826,4233094615,3781033664,3931371469,3682191598,3497509347,3446004468,3328955385,2939266226,2755636671,3106780840,2988687269,2198438022,2282195339,2501218972,2652609425,1201765386,1286567175,1371368976,1521706781,1805211710,1620529459,2105887268,1988838185,533804130,350174575,164439672,46346101,870912086,954669403,636813900,788204353,2358957921,2274680428,2592523643,2441661558,2695033685,2880240216,3065962831,3182487618,3572145929,3756299780,3270937875,3388507166,4174560061,4091327024,4006521127,3854606378,1014646705,930369212,711349675,560487590,272786309,457992840,106852767,223377554,1678381017,1862534868,1914052035,2031621326,1211247597,1128014560,1580087799,1428173050,32283319,182621114,401639597,486441376,768917123,651868046,1003007129,818324884,1503449823,1385356242,1333838021,1150208456,1973745387,2125135846,1673061617,1756818940,2970356327,3120694122,2802849917,2887651696,2637442643,2520393566,2334669897,2149987652,3917234703,3799141122,4284502037,4100872472,3309594171,3460984630,3545789473,3629546796,2050466060,1899603969,1814803222,1730525723,1443857720,1560382517,1075025698,1260232239,575138148,692707433,878443390,1062597235,243256656,91341917,409198410,325965383,3403100636,3252238545,3704300486,3620022987,3874428392,3990953189,4042459122,4227665663,2460449204,2578018489,2226875310,2411029155,3198115200,3046200461,2827177882,2743944855],aw=[0,218828297,437656594,387781147,875313188,958871085,775562294,590424639,1750626376,1699970625,1917742170,2135253587,1551124588,1367295589,1180849278,1265195639,3501252752,3720081049,3399941250,3350065803,3835484340,3919042237,4270507174,4085369519,3102249176,3051593425,2734591178,2952102595,2361698556,2177869557,2530391278,2614737639,3145456443,3060847922,2708326185,2892417312,2404901663,2187128086,2504130317,2555048196,3542330227,3727205754,3375740769,3292445032,3876557655,3926170974,4246310725,4027744588,1808481195,1723872674,1910319033,2094410160,1608975247,1391201670,1173430173,1224348052,59984867,244860394,428169201,344873464,935293895,984907214,766078933,547512796,1844882806,1627235199,2011214180,2062270317,1507497298,1423022939,1137477952,1321699145,95345982,145085239,532201772,313773861,830661914,1015671571,731183368,648017665,3175501286,2957853679,2807058932,2858115069,2305455554,2220981195,2474404304,2658625497,3575528878,3625268135,3473416636,3254988725,3778151818,3963161475,4213447064,4130281361,3599595085,3683022916,3432737375,3247465558,3802222185,4020912224,4172763771,4122762354,3201631749,3017672716,2764249623,2848461854,2331590177,2280796200,2431590963,2648976442,104699613,188127444,472615631,287343814,840019705,1058709744,671593195,621591778,1852171925,1668212892,1953757831,2037970062,1514790577,1463996600,1080017571,1297403050,3673637356,3623636965,3235995134,3454686199,4007360968,3822090177,4107101658,4190530515,2997825956,3215212461,2830708150,2779915199,2256734592,2340947849,2627016082,2443058075,172466556,122466165,273792366,492483431,1047239e3,861968209,612205898,695634755,1646252340,1863638845,2013908262,1963115311,1446242576,1530455833,1277555970,1093597963,1636604631,1820824798,2073724613,1989249228,1436590835,1487645946,1337376481,1119727848,164948639,81781910,331544205,516552836,1039717051,821288114,669961897,719700128,2973530695,3157750862,2871682645,2787207260,2232435299,2283490410,2667994737,2450346104,3647212047,3564045318,3279033885,3464042516,3980931627,3762502690,4150144569,4199882800,3070356634,3121275539,2904027272,2686254721,2200818878,2384911031,2570832044,2486224549,3747192018,3528626907,3310321856,3359936201,3950355702,3867060991,4049844452,4234721005,1739656202,1790575107,2108100632,1890328081,1402811438,1586903591,1233856572,1149249077,266959938,48394827,369057872,418672217,1002783846,919489135,567498868,752375421,209336225,24197544,376187827,459744698,945164165,895287692,574624663,793451934,1679968233,1764313568,2117360635,1933530610,1343127501,1560637892,1243112415,1192455638,3704280881,3519142200,3336358691,3419915562,3907448597,3857572124,4075877127,4294704398,3029510009,3113855344,2927934315,2744104290,2159976285,2377486676,2594734927,2544078150],cw=[0,151849742,303699484,454499602,607398968,758720310,908999204,1059270954,1214797936,1097159550,1517440620,1400849762,1817998408,1699839814,2118541908,2001430874,2429595872,2581445614,2194319100,2345119218,3034881240,3186202582,2801699524,2951971274,3635996816,3518358430,3399679628,3283088770,4237083816,4118925222,4002861748,3885750714,1002142683,850817237,698445255,548169417,529487843,377642221,227885567,77089521,1943217067,2061379749,1640576439,1757691577,1474760595,1592394909,1174215055,1290801793,2875968315,2724642869,3111247143,2960971305,2405426947,2253581325,2638606623,2487810577,3808662347,3926825029,4044981591,4162096729,3342319475,3459953789,3576539503,3693126241,1986918061,2137062819,1685577905,1836772287,1381620373,1532285339,1078185097,1229899655,1040559837,923313619,740276417,621982671,439452389,322734571,137073913,19308535,3871163981,4021308739,4104605777,4255800159,3263785589,3414450555,3499326569,3651041127,2933202493,2815956275,3167684641,3049390895,2330014213,2213296395,2566595609,2448830231,1305906550,1155237496,1607244650,1455525988,1776460110,1626319424,2079897426,1928707164,96392454,213114376,396673818,514443284,562755902,679998e3,865136418,983426092,3708173718,3557504664,3474729866,3323011204,4180808110,4030667424,3945269170,3794078908,2507040230,2623762152,2272556026,2390325492,2975484382,3092726480,2738905026,2857194700,3973773121,3856137295,4274053469,4157467219,3371096953,3252932727,3673476453,3556361835,2763173681,2915017791,3064510765,3215307299,2156299017,2307622919,2459735317,2610011675,2081048481,1963412655,1846563261,1729977011,1480485785,1362321559,1243905413,1126790795,878845905,1030690015,645401037,796197571,274084841,425408743,38544885,188821243,3613494426,3731654548,3313212038,3430322568,4082475170,4200115116,3780097726,3896688048,2668221674,2516901860,2366882550,2216610296,3141400786,2989552604,2837966542,2687165888,1202797690,1320957812,1437280870,1554391400,1669664834,1787304780,1906247262,2022837584,265905162,114585348,499347990,349075736,736970802,585122620,972512814,821712160,2595684844,2478443234,2293045232,2174754046,3196267988,3079546586,2895723464,2777952454,3537852828,3687994002,3234156416,3385345166,4142626212,4293295786,3841024952,3992742070,174567692,57326082,410887952,292596766,777231668,660510266,1011452712,893681702,1108339068,1258480242,1343618912,1494807662,1715193156,1865862730,1948373848,2100090966,2701949495,2818666809,3004591147,3122358053,2235061775,2352307457,2535604243,2653899549,3915653703,3764988233,4219352155,4067639125,3444575871,3294430577,3746175075,3594982253,836553431,953270745,600235211,718002117,367585007,484830689,133361907,251657213,2041877159,1891211689,1806599355,1654886325,1568718495,1418573201,1335535747,1184342925];function lw(t){const e=[];for(let n=0;n<t.length;n+=4)e.push(t[n]<<24|t[n+1]<<16|t[n+2]<<8|t[n+3]);return e}class uw{get key(){return Ky(this,Hy,"f").slice()}constructor(t){if(Hy.set(this,void 0),Vy.set(this,void 0),Wy.set(this,void 0),!(this instanceof uw))throw Error("AES must be instanitated with `new`");zy(this,Hy,new Uint8Array(t),"f");const e=qy[this.key.length];if(null==e)throw new TypeError("invalid key size (must be 16, 24 or 32 bytes)");zy(this,Wy,[],"f"),zy(this,Vy,[],"f");for(let l=0;l<=e;l++)Ky(this,Wy,"f").push([0,0,0,0]),Ky(this,Vy,"f").push([0,0,0,0]);const n=4*(e+1),r=this.key.length/4,s=lw(this.key);let i;for(let l=0;l<r;l++)i=l>>2,Ky(this,Wy,"f")[i][l%4]=s[l],Ky(this,Vy,"f")[e-i][l%4]=s[l];let o,a=0,c=r;for(;c<n;){if(o=s[r-1],s[0]^=Qy[o>>16&255]<<24^Qy[o>>8&255]<<16^Qy[255&o]<<8^Qy[o>>24&255]^$y[a]<<24,a+=1,8!=r)for(let e=1;e<r;e++)s[e]^=s[e-1];else{for(let t=1;t<r/2;t++)s[t]^=s[t-1];o=s[r/2-1],s[r/2]^=Qy[255&o]^Qy[o>>8&255]<<8^Qy[o>>16&255]<<16^Qy[o>>24&255]<<24;for(let t=r/2+1;t<r;t++)s[t]^=s[t-1]}let t,i,l=0;for(;l<r&&c<n;)t=c>>2,i=c%4,Ky(this,Wy,"f")[t][i]=s[l],Ky(this,Vy,"f")[e-t][i]=s[l++],c++}for(let l=1;l<e;l++)for(let t=0;t<4;t++)o=Ky(this,Vy,"f")[l][t],Ky(this,Vy,"f")[l][t]=iw[o>>24&255]^ow[o>>16&255]^aw[o>>8&255]^cw[255&o]}encrypt(t){if(16!=t.length)throw new TypeError("invalid plaintext size (must be 16 bytes)");const e=Ky(this,Wy,"f").length-1,n=[0,0,0,0];let r=lw(t);for(let o=0;o<4;o++)r[o]^=Ky(this,Wy,"f")[0][o];for(let o=1;o<e;o++){for(let t=0;t<4;t++)n[t]=Yy[r[t]>>24&255]^Zy[r[(t+1)%4]>>16&255]^Xy[r[(t+2)%4]>>8&255]^tw[255&r[(t+3)%4]]^Ky(this,Wy,"f")[o][t];r=n.slice()}const s=new Uint8Array(16);let i=0;for(let o=0;o<4;o++)i=Ky(this,Wy,"f")[e][o],s[4*o]=255&(Qy[r[o]>>24&255]^i>>24),s[4*o+1]=255&(Qy[r[(o+1)%4]>>16&255]^i>>16),s[4*o+2]=255&(Qy[r[(o+2)%4]>>8&255]^i>>8),s[4*o+3]=255&(Qy[255&r[(o+3)%4]]^i);return s}decrypt(t){if(16!=t.length)throw new TypeError("invalid ciphertext size (must be 16 bytes)");const e=Ky(this,Vy,"f").length-1,n=[0,0,0,0];let r=lw(t);for(let o=0;o<4;o++)r[o]^=Ky(this,Vy,"f")[0][o];for(let o=1;o<e;o++){for(let t=0;t<4;t++)n[t]=ew[r[t]>>24&255]^nw[r[(t+3)%4]>>16&255]^rw[r[(t+2)%4]>>8&255]^sw[255&r[(t+1)%4]]^Ky(this,Vy,"f")[o][t];r=n.slice()}const s=new Uint8Array(16);let i=0;for(let o=0;o<4;o++)i=Ky(this,Vy,"f")[e][o],s[4*o]=255&(Jy[r[o]>>24&255]^i>>24),s[4*o+1]=255&(Jy[r[(o+3)%4]>>16&255]^i>>16),s[4*o+2]=255&(Jy[r[(o+2)%4]>>8&255]^i>>8),s[4*o+3]=255&(Jy[255&r[(o+1)%4]]^i);return s}}Hy=new WeakMap,Vy=new WeakMap,Wy=new WeakMap;class hw{constructor(t,e,n){if(n&&!(this instanceof n))throw new Error(`${t} must be instantiated with "new"`);Object.defineProperties(this,{aes:{enumerable:!0,value:new uw(e)},name:{enumerable:!0,value:t}})}}var dw,fw,pw=globalThis&&globalThis.__classPrivateFieldSet||function(t,e,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(t,n):s?s.value=n:e.set(t,n),n},gw=globalThis&&globalThis.__classPrivateFieldGet||function(t,e,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(t):r?r.value:e.get(t)};class mw extends hw{constructor(t,e){if(super("ECC",t,mw),dw.set(this,void 0),fw.set(this,void 0),e){if(e.length%16)throw new TypeError("invalid iv size (must be 16 bytes)");pw(this,dw,new Uint8Array(e),"f")}else pw(this,dw,new Uint8Array(16),"f");pw(this,fw,this.iv,"f")}get iv(){return new Uint8Array(gw(this,dw,"f"))}encrypt(t){if(t.length%16)throw new TypeError("invalid plaintext size (must be multiple of 16 bytes)");const e=new Uint8Array(t.length);for(let n=0;n<t.length;n+=16){for(let e=0;e<16;e++)gw(this,fw,"f")[e]^=t[n+e];pw(this,fw,this.aes.encrypt(gw(this,fw,"f")),"f"),e.set(gw(this,fw,"f"),n)}return e}decrypt(t){if(t.length%16)throw new TypeError("invalid ciphertext size (must be multiple of 16 bytes)");const e=new Uint8Array(t.length);for(let n=0;n<t.length;n+=16){const r=this.aes.decrypt(t.subarray(n,n+16));for(let s=0;s<16;s++)e[n+s]=r[s]^gw(this,fw,"f")[s],gw(this,fw,"f")[s]=t[n+s]}return e}}dw=new WeakMap,fw=new WeakMap;var yw,ww,bw,Aw=globalThis&&globalThis.__classPrivateFieldSet||function(t,e,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(t,n):s?s.value=n:e.set(t,n),n},_w=globalThis&&globalThis.__classPrivateFieldGet||function(t,e,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(t):r?r.value:e.get(t)};class vw extends hw{constructor(t,e){super("CTR",t,vw),yw.set(this,void 0),ww.set(this,void 0),bw.set(this,void 0),Aw(this,bw,new Uint8Array(16),"f"),_w(this,bw,"f").fill(0),Aw(this,yw,_w(this,bw,"f"),"f"),Aw(this,ww,16,"f"),null==e&&(e=1),"number"==typeof e?this.setCounterValue(e):this.setCounterBytes(e)}get counter(){return new Uint8Array(_w(this,bw,"f"))}setCounterValue(t){if(!Number.isInteger(t)||t<0||t>Number.MAX_SAFE_INTEGER)throw new TypeError("invalid counter initial integer value");for(let e=15;e>=0;--e)_w(this,bw,"f")[e]=t%256,t=Math.floor(t/256)}setCounterBytes(t){if(16!==t.length)throw new TypeError("invalid counter initial Uint8Array value length");_w(this,bw,"f").set(t)}increment(){for(let t=15;t>=0;t--){if(255!==_w(this,bw,"f")[t]){_w(this,bw,"f")[t]++;break}_w(this,bw,"f")[t]=0}}encrypt(t){var e,n;const r=new Uint8Array(t);for(let s=0;s<r.length;s++)16===_w(this,ww,"f")&&(Aw(this,yw,this.aes.encrypt(_w(this,bw,"f")),"f"),Aw(this,ww,0,"f"),this.increment()),r[s]^=_w(this,yw,"f")[(Aw(this,ww,(n=_w(this,ww,"f"),e=n++,n),"f"),e)];return r}decrypt(t){return this.encrypt(t)}}function Ew(t){return"string"!=typeof t||t.startsWith("0x")||(t="0x"+t),ea(t)}function kw(t,e){for(t=String(t);t.length<e;)t="0"+t;return t}function Sw(t){return"string"==typeof t?Da(t,"NFKC"):ea(t)}function Tw(t,e){const n=e.match(/^([a-z0-9$_.-]*)(:([a-z]+))?(!)?$/i);$o(null!=n,"invalid path","path",e);const r=n[1],s=n[3],i="!"===n[4];let o=t;for(const a of r.toLowerCase().split(".")){if(Array.isArray(o)){if(!a.match(/^[0-9]+$/))break;o=o[parseInt(a)]}else if("object"==typeof o){let t=null;for(const e in o)if(e.toLowerCase()===a){t=o[e];break}o=t}else o=null;if(null==o)break}if($o(!i||null!=o,"missing required value","path",r),s&&null!=o){if("int"===s){if("string"==typeof o&&o.match(/^-?[0-9]+$/))return parseInt(o);if(Number.isSafeInteger(o))return o}if("number"===s&&"string"==typeof o&&o.match(/^-?[0-9.]*$/))return parseFloat(o);if("data"===s&&"string"==typeof o)return Ew(o);if("array"===s&&Array.isArray(o))return o;if(s===typeof o)return o;$o(!1,`wrong type found for ${s} `,"path",r)}return o}yw=new WeakMap,ww=new WeakMap,bw=new WeakMap;const Rw="m/44'/60'/0'/0/0";function Iw(t){try{const e=JSON.parse(t);if(3===(null!=e.version?parseInt(e.version):0))return!0}catch(e){}return!1}function Ow(t,e){const n=ta(e),r=Tw(t,"crypto.ciphertext:data!");$o(ia(Bl(oa([n.slice(16,32),r]))).substring(2)===Tw(t,"crypto.mac:string!").toLowerCase(),"incorrect password","password","[ REDACTED ]");const s=function(t,e,n){if("aes-128-ctr"===Tw(t,"crypto.cipher:string")){const r=Tw(t,"crypto.cipherparams.iv:data!");return ia(new vw(e,r).decrypt(n))}qo(!1,"unsupported cipher","UNSUPPORTED_OPERATION",{operation:"decrypt"})}(t,n.slice(0,16),r),i=Ed(s);if(t.address){let e=t.address.toLowerCase();e.startsWith("0x")||(e="0x"+e),$o($h(e)===i,"keystore address/privateKey mismatch","address",t.address)}const o={address:i,privateKey:s};if("0.1"===Tw(t,"x-ethers.version:string")){const e=n.slice(32,64),r=Tw(t,"x-ethers.mnemonicCiphertext:data!"),s=Tw(t,"x-ethers.mnemonicCounter:data!"),i=new vw(e,s);o.mnemonic={path:Tw(t,"x-ethers.path:string")||Rw,locale:Tw(t,"x-ethers.locale:string")||"en",entropy:ia(ta(i.decrypt(r)))}}return o}function Cw(t){const e=Tw(t,"crypto.kdf:string");if(e&&"string"==typeof e){if("scrypt"===e.toLowerCase()){const n=Tw(t,"crypto.kdfparams.salt:data!"),r=Tw(t,"crypto.kdfparams.n:int!"),s=Tw(t,"crypto.kdfparams.r:int!"),i=Tw(t,"crypto.kdfparams.p:int!");$o(r>0&&!(r&r-1),"invalid kdf.N","kdf.N",r),$o(s>0&&i>0,"invalid kdf","kdf",e);const o=Tw(t,"crypto.kdfparams.dklen:int!");return $o(32===o,"invalid kdf.dklen","kdf.dflen",o),{name:"scrypt",salt:n,N:r,r:s,p:i,dkLen:64}}if("pbkdf2"===e.toLowerCase()){const e=Tw(t,"crypto.kdfparams.salt:data!"),n=Tw(t,"crypto.kdfparams.prf:string!"),r=n.split("-").pop();$o("sha256"===r||"sha512"===r,"invalid kdf.pdf","kdf.pdf",n);const s=Tw(t,"crypto.kdfparams.c:int!"),i=Tw(t,"crypto.kdfparams.dklen:int!");return $o(32===i,"invalid kdf.dklen","kdf.dklen",i),{name:"pbkdf2",salt:e,count:s,dkLen:i,algorithm:r}}}$o(!1,"unsupported key-derivation function","kdf",e)}function xw(t){return new Promise((e=>{setTimeout((()=>{e()}),t)}))}function Nw(t){const e=null!=t.salt?ta(t.salt,"options.salt"):au(32);let n=1<<17,r=8,s=1;return t.scrypt&&(t.scrypt.N&&(n=t.scrypt.N),t.scrypt.r&&(r=t.scrypt.r),t.scrypt.p&&(s=t.scrypt.p)),$o("number"==typeof n&&n>0&&Number.isSafeInteger(n)&&(BigInt(n)&BigInt(n-1))===BigInt(0),"invalid scrypt N parameter","options.N",n),$o("number"==typeof r&&r>0&&Number.isSafeInteger(r),"invalid scrypt r parameter","options.r",r),$o("number"==typeof s&&s>0&&Number.isSafeInteger(s),"invalid scrypt p parameter","options.p",s),{name:"scrypt",dkLen:32,salt:e,N:n,r:r,p:s}}function Pw(t,e,n,r){const s=ta(n.privateKey,"privateKey"),i=null!=r.iv?ta(r.iv,"options.iv"):au(16);$o(16===i.length,"invalid options.iv length","options.iv",r.iv);const o=null!=r.uuid?ta(r.uuid,"options.uuid"):au(16);$o(16===o.length,"invalid options.uuid length","options.uuid",r.iv);const a=t.slice(0,16),c=t.slice(16,32),l=ta(new vw(a,i).encrypt(s)),u=Bl(oa([c,l])),h={address:n.address.substring(2).toLowerCase(),id:ac(o),version:3,Crypto:{cipher:"aes-128-ctr",cipherparams:{iv:ia(i).substring(2)},ciphertext:ia(l).substring(2),kdf:"scrypt",kdfparams:{salt:ia(e.salt).substring(2),n:e.N,dklen:32,p:e.p,r:e.r},mac:u.substring(2)}};if(n.mnemonic){const e=null!=r.client?r.client:`ethers/${Fo}`,s=n.mnemonic.path||Rw,i=n.mnemonic.locale||"en",o=t.slice(32,64),a=ta(n.mnemonic.entropy,"account.mnemonic.entropy"),c=au(16),l=ta(new vw(o,c).encrypt(a)),u=new Date,d="UTC--"+(u.getUTCFullYear()+"-"+kw(u.getUTCMonth()+1,2)+"-"+kw(u.getUTCDate(),2)+"T"+kw(u.getUTCHours(),2)+"-"+kw(u.getUTCMinutes(),2)+"-"+kw(u.getUTCSeconds(),2)+".0Z")+"--"+h.address;h["x-ethers"]={client:e,gethFilename:d,path:s,locale:i,mnemonicCounter:ia(c).substring(2),mnemonicCiphertext:ia(l).substring(2),version:"0.1"}}return JSON.stringify(h)}function Dw(t,e,n){null==n&&(n={});const r=Sw(e),s=Nw(n);return Pw(ta(Au(r,s.salt,s.N,s.r,s.p,64)),s,t,n)}async function Bw(t,e,n){null==n&&(n={});const r=Sw(e),s=Nw(n);return Pw(ta(await bu(r,s.salt,s.N,s.r,s.p,64,n.progressCallback)),s,t,n)}const Uw="m/44'/60'/0'/0/0",Lw=new Uint8Array([66,105,116,99,111,105,110,32,115,101,101,100]),Mw=2147483648,Fw=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");function Gw(t,e){let n="";for(;t;)n="0123456789abcdef"[t%16]+n,t=Math.trunc(t/16);for(;n.length<2*e;)n="0"+n;return"0x"+n}function jw(t){const e=ta(t);return Ca(oa([e,ca(ku(ku(e)),0,4)]))}const Hw={};function Vw(t,e,n,r){const s=new Uint8Array(37);t&Mw?(qo(null!=r,"cannot derive child of neutered node","UNSUPPORTED_OPERATION",{operation:"deriveChild"}),s.set(ta(r),1)):s.set(ta(n));for(let o=24;o>=0;o-=8)s[33+(o>>3)]=t>>24-o&255;const i=ta(ml("sha512",e,s));return{IL:i.slice(0,32),IR:i.slice(32)}}function Ww(t,e){const n=e.split("/");$o(n.length>0,"invalid path","path",e),"m"===n[0]&&($o(0===t.depth,`cannot derive root path (i.e. path starting with "m/") for a node at non-zero depth ${t.depth}`,"path",e),n.shift());let r=t;for(let s=0;s<n.length;s++){const t=n[s];if(t.match(/^[0-9]+'$/)){const e=parseInt(t.substring(0,t.length-1));$o(e<Mw,"invalid path index",`path[${s}]`,t),r=r.deriveChild(Mw+e)}else if(t.match(/^[0-9]+$/)){const e=parseInt(t);$o(e<Mw,"invalid path index",`path[${s}]`,t),r=r.deriveChild(e)}else $o(!1,"invalid path component",`path[${s}]`,t)}return r}const Kw=class t extends Iy{constructor(t,e,n,r,s,i,o,a,c){super(e,c),Dn(this,kn),xn(this,"publicKey"),xn(this,"fingerprint"),xn(this,"parentFingerprint"),xn(this,"mnemonic"),xn(this,"chainCode"),xn(this,"path"),xn(this,"index"),xn(this,"depth"),Zo(t,Hw,"HDNodeWallet"),Ho(this,{publicKey:e.compressedPublicKey});Ho(this,{parentFingerprint:n,fingerprint:ca(Xl(ku(this.publicKey)),0,4),chainCode:r,path:s,index:i,depth:o}),Ho(this,{mnemonic:a})}connect(e){return new t(Hw,this.signingKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,this.mnemonic,e)}async encrypt(t,e){return await Bw(Ln(this,kn,Sn).call(this),t,{progressCallback:e})}encryptSync(t){return Dw(Ln(this,kn,Sn).call(this),t)}get extendedKey(){return qo(this.depth<256,"Depth too deep","UNSUPPORTED_OPERATION",{operation:"extendedKey"}),jw(oa(["0x0488ADE4",Gw(this.depth,1),this.parentFingerprint,Gw(this.index,4),this.chainCode,oa(["0x00",this.privateKey])]))}hasPath(){return null!=this.path}neuter(){return new qw(Hw,this.address,this.publicKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,this.provider)}deriveChild(e){const n=_a(e,"index");$o(n<=4294967295,"invalid index","index",n);let r=this.path;r&&(r+="/"+(2147483647&n),n&Mw&&(r+="'"));const{IR:s,IL:i}=Vw(n,this.chainCode,this.publicKey,this.privateKey),o=new Hh(va((Aa(i)+BigInt(this.privateKey))%Fw,32));return new t(Hw,o,this.fingerprint,ia(s),r,n,this.depth+1,this.mnemonic,this.provider)}derivePath(t){return Ww(this,t)}static fromExtendedKey(e){const n=Ea(function(t){let e=Ia;for(let n=0;n<t.length;n++)e*=Oa,e+=Ra(t[n]);return e}(e));$o(82===n.length||jw(n.slice(0,78))===e,"invalid extended key","extendedKey","[ REDACTED ]");const r=n[4],s=ia(n.slice(5,9)),i=parseInt(ia(n.slice(9,13)).substring(2),16),o=ia(n.slice(13,45)),a=n.slice(45,78);switch(ia(n.slice(0,4))){case"0x0488b21e":case"0x043587cf":{const t=ia(a);return new qw(Hw,Ed(t),t,s,o,null,i,r,null)}case"0x0488ade4":case"0x04358394 ":if(0!==a[0])break;return new t(Hw,new Hh(a.slice(1)),s,o,null,i,r,null,null)}$o(!1,"invalid extended key prefix","extendedKey","[ REDACTED ]")}static createRandom(e,n,r){var s;null==e&&(e=""),null==n&&(n=Uw),null==r&&(r=Uy.wordlist());const i=jy.fromEntropy(au(16),e,r);return Ln(s=t,Tn,Rn).call(s,i.computeSeed(),i).derivePath(n)}static fromMnemonic(e,n){var r;return n||(n=Uw),Ln(r=t,Tn,Rn).call(r,e.computeSeed(),e).derivePath(n)}static fromPhrase(e,n,r,s){var i;null==n&&(n=""),null==r&&(r=Uw),null==s&&(s=Uy.wordlist());const o=jy.fromPhrase(e,n,s);return Ln(i=t,Tn,Rn).call(i,o.computeSeed(),o).derivePath(r)}static fromSeed(e){var n;return Ln(n=t,Tn,Rn).call(n,e,null)}};kn=new WeakSet,Sn=function(){const t={address:this.address,privateKey:this.privateKey},e=this.mnemonic;return this.path&&e&&"en"===e.wordlist.locale&&""===e.password&&(t.mnemonic={path:this.path,locale:"en",entropy:e.entropy}),t},Tn=new WeakSet,Rn=function(t,e){$o(ra(t),"invalid seed","seed","[REDACTED]");const n=ta(t,"seed");$o(n.length>=16&&n.length<=64,"invalid seed","seed","[REDACTED]");const r=ta(ml("sha512",Lw,n)),s=new Hh(ia(r.slice(0,32)));return new Kw(Hw,s,"0x00000000",ia(r.slice(32)),"m",0,0,e,null)},Dn(Kw,Tn);let zw=Kw;class qw extends dy{constructor(t,e,n,r,s,i,o,a,c){super(e,c),xn(this,"publicKey"),xn(this,"fingerprint"),xn(this,"parentFingerprint"),xn(this,"chainCode"),xn(this,"path"),xn(this,"index"),xn(this,"depth"),Zo(t,Hw,"HDNodeVoidWallet"),Ho(this,{publicKey:n});Ho(this,{publicKey:n,fingerprint:ca(Xl(ku(n)),0,4),parentFingerprint:r,chainCode:s,path:i,index:o,depth:a})}connect(t){return new qw(Hw,this.address,this.publicKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,t)}get extendedKey(){return qo(this.depth<256,"Depth too deep","UNSUPPORTED_OPERATION",{operation:"extendedKey"}),jw(oa(["0x0488B21E",Gw(this.depth,1),this.parentFingerprint,Gw(this.index,4),this.chainCode,this.publicKey]))}hasPath(){return null!=this.path}deriveChild(t){const e=_a(t,"index");$o(e<=4294967295,"invalid index","index",e);let n=this.path;n&&(n+="/"+(2147483647&e),e&Mw&&(n+="'"));const{IR:r,IL:s}=Vw(e,this.chainCode,this.publicKey,null),i=Hh.addPoints(s,this.publicKey,!0),o=Ed(i);return new qw(Hw,o,i,this.fingerprint,ia(r),n,e,this.depth+1,this.provider)}derivePath(t){return Ww(this,t)}}function $w(t){try{if(JSON.parse(t).encseed)return!0}catch(e){}return!1}function Qw(t,e){const n=JSON.parse(t),r=Sw(e),s=$h(Tw(n,"ethaddr:string!")),i=Ew(Tw(n,"encseed:string!"));$o(i&&i.length%16==0,"invalid encseed","json",t);const o=ta(ru(r,r,2e3,32,"sha256")).slice(0,16),a=i.slice(0,16),c=i.slice(16),l=function(t){if(t.length<16)throw new TypeError("PKCS#7 invalid length");const e=t[t.length-1];if(e>16)throw new TypeError("PKCS#7 padding byte out of range");const n=t.length-e;for(let r=0;r<e;r++)if(t[n+r]!==e)throw new TypeError("PKCS#7 invalid padding byte");return new Uint8Array(t.subarray(0,n))}(ta(new mw(o,a).decrypt(c)));let u="";for(let h=0;h<l.length;h++)u+=String.fromCharCode(l[h]);return{address:s,privateKey:Wd(u)}}function Jw(t){return new Promise((e=>{setTimeout((()=>{e()}),t)}))}const Yw=class t extends Iy{constructor(t,e){"string"!=typeof t||t.startsWith("0x")||(t="0x"+t),super("string"==typeof t?new Hh(t):t,e)}connect(e){return new t(this.signingKey,e)}async encrypt(t,e){const n={address:this.address,privateKey:this.privateKey};return await Bw(n,t,{progressCallback:e})}encryptSync(t){return Dw({address:this.address,privateKey:this.privateKey},t)}static async fromEncryptedJson(e,n,r){var s;let i=null;return Iw(e)?i=await async function(t,e,n){const r=JSON.parse(t),s=Sw(e),i=Cw(r);if("pbkdf2"===i.name){n&&(n(0),await xw(0));const{salt:t,count:e,dkLen:o,algorithm:a}=i,c=ru(s,t,e,o,a);return n&&(n(1),await xw(0)),Ow(r,c)}qo("scrypt"===i.name,"cannot be reached","UNKNOWN_ERROR",{params:i});const{salt:o,N:a,r:c,p:l,dkLen:u}=i;return Ow(r,await bu(s,o,a,c,l,u,n))}(e,n,r):$w(e)&&(r&&(r(0),await Jw(0)),i=Qw(e,n),r&&(r(1),await Jw(0))),Ln(s=t,In,On).call(s,i)}static fromEncryptedJsonSync(e,n){var r;let s=null;return Iw(e)?s=function(t,e){const n=JSON.parse(t),r=Sw(e),s=Cw(n);if("pbkdf2"===s.name){const{salt:t,count:e,dkLen:i,algorithm:o}=s;return Ow(n,ru(r,t,e,i,o))}qo("scrypt"===s.name,"cannot be reached","UNKNOWN_ERROR",{params:s});const{salt:i,N:o,r:a,p:c,dkLen:l}=s;return Ow(n,Au(r,i,o,a,c,l))}(e,n):$w(e)?s=Qw(e,n):$o(!1,"invalid JSON wallet","json","[ REDACTED ]"),Ln(r=t,In,On).call(r,s)}static createRandom(t){const e=zw.createRandom();return t?e.connect(t):e}static fromPhrase(t,e){const n=zw.fromPhrase(t);return e?n.connect(e):n}};In=new WeakSet,On=function(t){if($o(t,"invalid JSON wallet","json","[ REDACTED ]"),"mnemonic"in t&&t.mnemonic&&"en"===t.mnemonic.locale){const e=jy.fromEntropy(t.mnemonic.entropy),n=zw.fromMnemonic(e,t.mnemonic.path);if(n.address===t.address&&n.privateKey===t.privateKey)return n;console.log("WARNING: JSON mismatch address/privateKey != mnemonic; fallback onto private key")}const e=new Yw(t.privateKey);return $o(e.address===t.address,"address/privateKey mismatch","json","[ REDACTED ]"),e},Dn(Yw,In);let Zw=Yw;const Xw=3000000n,tb=2000000000n,eb=1000000000n,nb=4096,rb="dns_txt",sb=(1n<<64n)-1n,ib=["function publishDocument(string name,string docType,uint64 expectedVersion,(bytes32 storageType,string uri,bytes inlineDocument,bytes32 contentHash,bytes32 schema,bytes32 codec,bytes32 extraHash) document,(uint8 kind,bytes value) controller,(uint8 kind,bytes value) beneficiary,address paymentTarget,uint64 expireAt,bytes32 controllerPolicyHash,bytes32 paymentPolicyHash,bytes32 splitPolicyHash,bytes32 pricePolicyHash,bytes32 rightsPolicyHash,(uint8 role,(uint8 kind,bytes value) actor,bytes32 kid) authority,(uint64 expectedNameSeq,uint64 expectedParentNameSeq) guard) returns (uint64 version)"],ob=new _g(ib),ab=[0,"0x"],cb=function(t){const e=Da(t);if(e.length>31)throw new Error("bytes32 string must be less than 32 bytes");return ha(e,32)}("inline");class lb extends Error{constructor(t,e){super(e),this.name="BnsEvmTxError",this.code=t}}function ub(t,e,n){let r;try{r=BigInt(e)}catch{throw new lb("INVALID_CONFIG",`${t} must be an integer`)}if(r<0n||void 0!==n&&r>n)throw new lb("INVALID_CONFIG",`${t} is out of range`);return r}function hb(t){const e=Mn.canonicalize(t);if("string"!=typeof e)throw new lb("INVALID_DOCUMENT","document cannot be encoded as canonical JSON");const n=Da(e);if(0===n.length||n.length>nb)throw new lb("INVALID_DOCUMENT",`inline document is ${n.length} bytes, max 4096`);return n}function db(t,e){if(!t||"object"!=typeof t||Array.isArray(t))throw new lb("INVALID_DOCUMENT",`${e} must be an object`);const n=t;if(!Number.isInteger(n.ttl)||n.ttl<0||n.ttl>4294967295)throw new lb("INVALID_DOCUMENT",`${e}.ttl must be a u32`);if("string"!=typeof n.value||0===n.value.length)throw new lb("INVALID_DOCUMENT",`${e}.value must be a non-empty string`);return{ttl:n.ttl,value:n.value}}class fb{constructor(t,e,n){if(this.nextNonce=null,this.client=t,this.config=e,this.chainId=ub("chainId",e.chainId,sb),this.contractAddress=$h(e.contractAddress),this.gasLimit=ub("gasLimit",e.gasLimit??Xw,sb),this.maxFeePerGas=ub("maxFeePerGas",e.maxFeePerGas??tb),this.maxPriorityFeePerGas=ub("maxPriorityFeePerGas",e.maxPriorityFeePerGas??eb),!e.rpcEndpoint&&!n)throw new lb("INVALID_CONFIG","rpcEndpoint is required");if(0n===this.chainId||0n===this.gasLimit)throw new lb("INVALID_CONFIG","chainId and gasLimit must be greater than zero");if(this.maxFeePerGas<this.maxPriorityFeePerGas)throw new lb("INVALID_CONFIG","maxFeePerGas must be >= maxPriorityFeePerGas");this.provider=n??new Sy(e.rpcEndpoint,this.chainId,{staticNetwork:!0})}resetNonce(){this.nextNonce=null}async buildAndSign(t,e){const n=new Zw(e),r="publish_document"===t.type?await this.preparePublishedDocument(t.request):await this.prepareDnsTxtDocument(t.request),s=this.encodePublishDocument(r,n.address),i=await this.allocateNonce(n.address);try{return await n.signTransaction({type:2,chainId:this.chainId,nonce:i,to:this.contractAddress,value:0,data:s,gasLimit:this.gasLimit,maxFeePerGas:this.maxFeePerGas,maxPriorityFeePerGas:this.maxPriorityFeePerGas})}catch(o){throw this.resetNonce(),o}}async allocateNonce(t){null===this.nextNonce&&(this.nextNonce=await this.provider.getTransactionCount(t,"pending"));const e=this.nextNonce;return this.nextNonce+=1,e}async preparePublishedDocument(t){if(!t.document||"object"!=typeof t.document||Array.isArray(t.document))throw new lb("INVALID_DOCUMENT","publish_document document must be a JSON object");return this.prepareDocument(t.name,t.doc_type,hb(t.document))}async prepareDnsTxtDocument(t){const e=await this.getCurrentDocument(t.name,rb);let n=[];if(e){if("inline"!==e.document_state.document.storage_type)throw new lb("INVALID_DOCUMENT","DNS TXT helper can only update inline documents");let t;try{t=JSON.parse(function(t){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(new Uint8Array(t));let e="";for(const n of t)e+=String.fromCharCode(n);try{return decodeURIComponent(escape(e))}catch{return e}}(e.document_state.document.inline_document))}catch(s){throw new lb("INVALID_DOCUMENT",`current dns_txt document is not valid JSON: ${s instanceof Error?s.message:String(s)}`)}if(!Array.isArray(t))throw new lb("INVALID_DOCUMENT","current dns_txt document must be an array");n=t.map(((t,e)=>db(t,`dns_txt[${e}]`)))}switch(t.mode){case"add":{if(!t.value)throw new lb("INVALID_OPERATION","publish_dns_txt mode=add requires value");const e=db({ttl:t.ttl??600,value:t.value},"dns_txt");n.some((t=>t.value===e.value))||n.push(e);break}case"remove":if(!t.value)throw new lb("INVALID_OPERATION","publish_dns_txt mode=remove requires value");n=n.filter((e=>e.value!==t.value));break;case"replace":if(!t.records)throw new lb("INVALID_OPERATION","publish_dns_txt mode=replace requires records");n=t.records.map(((t,e)=>db({ttl:t.ttl??600,value:t.value},`dns_txt[${e}]`)));break;default:throw new lb("INVALID_OPERATION",`publish_dns_txt mode \`${t.mode}\` is not supported`)}const r=await this.getNameState(t.name);return{name:No(t.name),docType:rb,expectedVersion:(null==e?void 0:e.document_state.version)??0,inlineDocument:hb(n),nameState:r}}async prepareDocument(t,e,n){const r=No(t),s=Po(e),[i,o]=await Promise.all([this.getNameState(r),this.getCurrentDocument(r,s)]);return{name:r,docType:s,expectedVersion:(null==o?void 0:o.document_state.version)??0,inlineDocument:n,nameState:i}}async getNameState(t){const e=await this.client.queryNameState(t);if(!e)throw new lb("NAME_NOT_FOUND",`BNS name \`${t}\` was not found`);return e}async getCurrentDocument(t,e){try{const n=await this.client.resolveDocument(t,e);return"missing"===n.status?null:n}catch(n){if(function(t){return t instanceof Ki&&t.isRegistryCode("DOCUMENT_NOT_FOUND")}(n))return null;throw n}}encodePublishDocument(t,e){const n=this.ownerAuthority(t.nameState,e),r=[cb,"",ia(t.inlineDocument),ku(t.inlineDocument),Oh,Oh,Oh];return ob.encodeFunctionData("publishDocument",[t.name,t.docType,t.expectedVersion,r,ab,ab,Ih,0,Oh,Oh,Oh,Oh,Oh,n,[t.nameState.name_seq,0]])}ownerAuthority(t,e){const n=t.effective_owner;if("chain_account"===n.kind){const s=$h(n.value);if(s!==$h(e))throw new lb("LOCAL_SIGNER_NOT_OWNER",`local signer ${e} is not effective owner ${s} of ${t.name}`);return[1,(r=e,[1,ia(ta(r))]),Oh]}var r;if("bns_name"===n.kind){const e=function(t,e){if(!e)return Oh;const n=ta(e);if(32!==n.length)throw new lb("INVALID_CONFIG",`${t} must be a 32-byte hex value`);return ia(n)}("authorityKid",this.config.authorityKid);if(e===Oh)throw new lb("AUTHORITY_KID_REQUIRED",`authorityKid is required when ${t.name} is controlled by BNS name ${n.value}`);return[1,[2,ia(Da(n.value))],e]}throw new lb("LOCAL_SIGNER_NOT_OWNER",`BNS name ${t.name} has no concrete effective owner`)}}class pb extends Error{constructor(t,e,n){super(n),this.name="BnsTxExecutorError",this.code=t,this.route=e}}function gb(t){if("string"!=typeof t)return null;const e=t.trim();return e.length>0?e:null}function mb(t){return t===Ds.NodeJS||t===Ds.AppClient||t===Ds.AppService}function yb(t){if(!t||"object"!=typeof t||Array.isArray(t))return!1;const e=t;return"boolean"==typeof e.sn_account?e.sn_account:null!==gb(e.sn_username)||null!==gb(e.sn_user_name)}const wb="/kapi/sn",bb="/kapi/sn/auth",Ab="/kapi/sn/deviceinfo",_b="/kapi/sn/bns-proxy",vb="/kapi/sn/bns",Eb="/kapi/sn/region-probe-config.json",kb=1048576,Sb="auth.check_username",Tb="auth.check_active_code",Rb="auth.register",Ib="auth.login",Ob="auth.refresh",Cb="auth.logout",xb="auth.me",Nb="user.get_profile",Pb="user.set_self_cert",Db="user.add_dns_record",Bb="user.remove_dns_record",Ub="user.list_dns_records",Lb="zone.get_info",Mb="domain.bind",Fb="domain.unbind",Gb="device.register",jb="device.update",Hb="device.get",Vb="device.list",Wb="deviceinfo.resolve_ood_by_did",Kb="deviceinfo.resolve_ood_by_hostname",zb="bns.publish_dns_txt",qb="bns.publish_document",$b="owner.remove_bound_zone",Qb=/\[SN:(\d+):([a-z_]+)\]\s*/;class Jb extends Error{constructor(t,e,n=null,r=null,s=null){super(e),this.name="SnClientError",this.kind=t,this.code=n,this.codeName=r,this.detail=s??e}isSnError(t){return"sn"===this.kind&&this.codeName===t}domainProofInfo(){return this.isSnError("domain_proof_failed")?Yb(this.detail):null}bnsWriteInfo(){return this.isSnError("bns_permission_denied")||this.isSnError("bns_name_already_exists")||this.isSnError("bns_write_failed")?Yb(this.detail):null}static fromRpcError(t,e){if(e instanceof Jb)return e;const n=e instanceof Error?e.message:String(e),r=Qb.exec(n);if(r){const e=parseInt(r[1],10),s=r[2],i=n.slice(r.index+r[0].length);return new Jb("sn",`${t} failed: [SN:${e}:${s}] ${i}`,e,s,i)}return new Jb("transport",`${t} failed: ${n}`)}}function Yb(t){try{const e=JSON.parse(t);return null===e||"object"!=typeof e||Array.isArray(e)?null:e}catch{return null}}const Zb={auth:bb,deviceinfo:Ab,"bns-proxy":_b},Xb=[_b,Ab,bb,vb,wb];function tA(t,e){const n=Zb[e],r=t.replace(/\/+$/,"");for(const s of Xb)if(r.endsWith(s))return`${r.slice(0,r.length-s.length)}${n}`;return`${r}${n}`}const eA=[Eb,_b,Ab,bb,vb,wb],nA=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/,rA=/[\u0000-\u001f\u007f-\u009f]/u;function sA(t){throw new Jb("validation",t)}function iA(t){return(new TextEncoder).encode(t).byteLength}function oA(t,e){return(null===t||"object"!=typeof t||Array.isArray(t))&&sA(`${e} must be a JSON object`),t}function aA(t,e){return"string"!=typeof t&&sA(`${e} must be a string`),t}function cA(t,e){return"number"!=typeof t&&sA(`${e} must be a number`),t}function lA(t,e){const n=cA(t,e);return Number.isSafeInteger(n)||sA(`${e} must be a safe integer`),n}function uA(t,e){const n=lA(t,e);return(n<-2147483648||n>2147483647)&&sA(`${e} must fit in a signed 32-bit integer`),n}function hA(t,e){return Array.isArray(t)||sA(`${e} must be an array`),t}function dA(t){return iA(t)<=128&&/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(t)}function fA(t){const e=t.split(".");if(4!==e.length)return null;const n=e.map((t=>Number(t)));return n.some(((t,n)=>!/^\d+$/.test(e[n])||!Number.isInteger(t)||t<0||t>255))?null:n}function pA(t){const e=fA(t);if(!e)return!1;const[n,r,s]=e;return!(0===n||10===n||127===n||100===n&&r>=64&&r<=127||169===n&&254===r||172===n&&r>=16&&r<=31||192===n&&0===r&&0===s||192===n&&0===r&&2===s||192===n&&88===r&&99===s||192===n&&168===r||198===n&&(18===r||19===r)||198===n&&51===r&&100===s||203===n&&0===r&&113===s||n>=224)}function gA(t,e){const n=Date.parse(t);return nA.test(t)&&Number.isFinite(n)||sA(`${e} must be an RFC 3339 timestamp`),n}function mA(t,e=Date.now()){1!==t.schema_version&&sA(`unsupported schema_version ${t.schema_version}, expected 1`),(0===t.config_version.length||iA(t.config_version)>128||t.config_version.trim()!==t.config_version||rA.test(t.config_version))&&sA("config_version must be 1..=128 non-control bytes without surrounding whitespace");const n=gA(t.generated_at,"generated_at"),r=gA(t.expires_at,"expires_at"),s=e instanceof Date?e.getTime():"number"==typeof e?e:Date.parse(e);Number.isFinite(s)||sA("validation time is invalid"),n>=r&&sA("expires_at must be later than generated_at"),r<=s&&sA("region probe config is expired");const i=t.policy;"tcp_connect"!==i.probe_method&&sA(`unsupported probe_method ${JSON.stringify(i.probe_method)}`),"ipv4"!==i.ip_family&&sA(`unsupported ip_family ${JSON.stringify(i.ip_family)}`),(i.samples_per_url<1||i.samples_per_url>3)&&sA("samples_per_url must be in 1..=3"),(i.connect_timeout_ms<1||i.connect_timeout_ms>1e4)&&sA("connect_timeout_ms must be in 1..=10000"),(i.round_timeout_ms<1||i.round_timeout_ms>3e4)&&sA("round_timeout_ms must be in 1..=30000"),(i.max_concurrency<1||i.max_concurrency>32)&&sA("max_concurrency must be in 1..=32"),(i.minimum_valid_urls<2||i.minimum_valid_urls>16)&&sA("minimum_valid_urls must be in 2..=16"),(!Number.isFinite(i.confident_ratio)||i.confident_ratio<=0||i.confident_ratio>1)&&sA("confident_ratio must be finite and in (0, 1]"),(i.cache_ttl_sec<1||i.cache_ttl_sec>21600)&&sA("cache_ttl_sec must be in 1..=21600"),(t.regions.length<1||t.regions.length>64)&&sA("regions must contain 1..=64 entries");const o=new Set,a=new Set,c=new Map;let l=0;for(const h of t.regions){dA(h.region_id)||sA(`invalid canonical region_id ${JSON.stringify(h.region_id)}`),o.has(h.region_id)&&sA(`duplicate region_id ${JSON.stringify(h.region_id)}`),o.add(h.region_id),(h.probe_urls.length<2||h.probe_urls.length>16)&&sA(`region ${h.region_id} must contain 2..=16 probe_urls`),i.minimum_valid_urls>h.probe_urls.length&&sA(`region ${h.region_id} has fewer probe_urls than minimum_valid_urls`),l+=h.probe_urls.length,l>256&&sA("config contains more than 256 probe URLs");for(const t of h.probe_urls){let e;(0===t.id.length||iA(t.id)>128||t.id.trim()!==t.id||rA.test(t.id))&&sA(`probe URL id in region ${h.region_id} must be 1..=128 non-control bytes without surrounding whitespace`),a.has(t.id)&&sA(`duplicate probe URL id ${JSON.stringify(t.id)}`),a.add(t.id);try{e=new URL(t.url)}catch(u){sA(`invalid probe URL ${JSON.stringify(t.url)}: ${String(u)}`)}"https:"!==e.protocol&&sA(`probe URL ${JSON.stringify(t.url)} must use https`),(!e.hostname||e.username||e.password)&&sA(`probe URL ${JSON.stringify(t.url)} must be absolute and must not contain userinfo`),""!==e.port&&sA(`probe URL ${JSON.stringify(t.url)} must use port 443`);const n=fA(e.hostname),r=e.hostname.startsWith("[")&&e.hostname.endsWith("]");(n&&!pA(e.hostname)||r)&&sA(`probe URL ${JSON.stringify(t.url)} has a non-public or unsupported literal IP`);const s=c.get(e.origin);void 0!==s&&(s!==h.region_id&&sA(`probe origin ${e.origin} is assigned to both ${s} and ${h.region_id}`),sA(`probe origin ${e.origin} is duplicated in region ${h.region_id}`)),c.set(e.origin,h.region_id)}}}function yA(t){let e,n;try{e="string"==typeof t?t:new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch(s){sA(`parse region probe config JSON failed: ${String(s)}`)}try{n=JSON.parse(e)}catch(s){sA(`parse region probe config JSON failed: ${String(s)}`)}const r=function(t){const e=oA(t,"region probe config"),n=oA(e.policy,"policy"),r={probe_method:aA(n.probe_method,"policy.probe_method"),samples_per_url:lA(n.samples_per_url,"policy.samples_per_url"),connect_timeout_ms:lA(n.connect_timeout_ms,"policy.connect_timeout_ms"),round_timeout_ms:lA(n.round_timeout_ms,"policy.round_timeout_ms"),max_concurrency:lA(n.max_concurrency,"policy.max_concurrency"),ip_family:aA(n.ip_family,"policy.ip_family"),minimum_valid_urls:lA(n.minimum_valid_urls,"policy.minimum_valid_urls"),confident_ratio:cA(n.confident_ratio,"policy.confident_ratio"),cache_ttl_sec:lA(n.cache_ttl_sec,"policy.cache_ttl_sec")},s=hA(e.regions,"regions").map(((t,e)=>{const n=oA(t,`regions[${e}]`),r=hA(n.probe_urls,`regions[${e}].probe_urls`).map(((t,n)=>{const r=oA(t,`regions[${e}].probe_urls[${n}]`),s={id:aA(r.id,`regions[${e}].probe_urls[${n}].id`),url:aA(r.url,`regions[${e}].probe_urls[${n}].url`)};return void 0!==r.provider&&null!==r.provider&&(s.provider=aA(r.provider,`regions[${e}].probe_urls[${n}].provider`)),s}));return{region_id:aA(n.region_id,`regions[${e}].region_id`),priority:void 0===n.priority?0:uA(n.priority,`regions[${e}].priority`),probe_urls:r}}));return{schema_version:lA(e.schema_version,"schema_version"),config_version:aA(e.config_version,"config_version"),generated_at:aA(e.generated_at,"generated_at"),expires_at:aA(e.expires_at,"expires_at"),policy:r,regions:s}}(n);return mA(r),r}function wA(t){let e;try{e=new URL(t.trim())}catch(s){sA(`invalid SN base URL for region probe config: ${String(s)}`)}"https:"!==e.protocol&&sA("region probe config must be fetched from the target SN over HTTPS"),(!e.hostname||e.username||e.password)&&sA("SN region probe config URL must have a host and no userinfo"),e.search="",e.hash="";const n=e.pathname.replace(/\/+$/,"");let r=n;for(const i of eA)if(n.endsWith(i)){r=n.slice(0,n.length-i.length);break}return e.pathname=`${r}${Eb}`,e.toString()}const bA=async(t,e)=>{if("function"!=typeof globalThis.fetch)throw new Error("fetch is not available in this runtime");return globalThis.fetch(t,e)};const AA="sn-device";function _A(t){return void 0!==t.ttl?{ttl:t.ttl,value:t.value}:{value:t.value}}function vA(t){const e={device_did:t.device_did,domain:t.domain,record_type:t.record_type};return void 0!==t.record&&(e.record=t.record),void 0!==t.ttl&&(e.ttl=t.ttl),void 0!==t.has_cert&&(e.has_cert=t.has_cert),e}function EA(t){return{endpoint_id:t.endpoint_id,protocol:t.protocol,host:t.host,port:t.port,scope:t.scope,priority:t.priority,source:t.source,expires_at:t.expires_at}}function kA(t){const e={device_name:t.device_name,device_ip:t.device_ip,device_info:t.device_info};return void 0!==t.device_did&&(e.device_did=t.device_did),void 0!==t.endpoints&&t.endpoints.length>0&&(e.endpoints=t.endpoints.map(EA)),void 0!==t.report_seq&&(e.report_seq=t.report_seq),void 0!==t.ttl&&(e.ttl=t.ttl),e}const SA=Object.freeze(Object.defineProperty({__proto__:null,LEGACY_SN_BNS_PATH:vb,METHOD_AUTH_CHECK_ACTIVE_CODE:Tb,METHOD_AUTH_CHECK_USERNAME:Sb,METHOD_AUTH_LOGIN:Ib,METHOD_AUTH_LOGOUT:Cb,METHOD_AUTH_ME:xb,METHOD_AUTH_REFRESH:Ob,METHOD_AUTH_REGISTER:Rb,METHOD_BNS_PUBLISH_DNS_TXT:zb,METHOD_BNS_PUBLISH_DOCUMENT:qb,METHOD_DEVICEINFO_RESOLVE_OOD_BY_DID:Wb,METHOD_DEVICEINFO_RESOLVE_OOD_BY_HOSTNAME:Kb,METHOD_DEVICE_GET:Hb,METHOD_DEVICE_LIST:Vb,METHOD_DEVICE_REGISTER:Gb,METHOD_DEVICE_UPDATE:jb,METHOD_DOMAIN_BIND:Mb,METHOD_DOMAIN_UNBIND:Fb,METHOD_OWNER_REMOVE_BOUND_ZONE:$b,METHOD_USER_ADD_DNS_RECORD:Db,METHOD_USER_GET_PROFILE:Nb,METHOD_USER_LIST_DNS_RECORDS:Ub,METHOD_USER_REMOVE_DNS_RECORD:Bb,METHOD_USER_SET_SELF_CERT:Pb,METHOD_ZONE_GET_INFO:Lb,SN_AUTH_PATH:bb,SN_BNS_PROXY_PATH:_b,SN_DEVICEINFO_PATH:Ab,SN_DEVICE_TOKEN_AUD:AA,SN_DEVICE_TOKEN_DEFAULT_TTL_SECS:600,SN_ERROR_CODES:{invalid_params:1e3,invalid_username:1001,username_already_exists:1002,invalid_active_code:1003,user_auth_not_found:1004,invalid_password:1005,auth_required:1006,invalid_token:1007,user_not_found:1008,device_not_found:1012,device_permission_denied:1013,invalid_device_did:1014,invalid_domain:1015,domain_proof_failed:1016,hostname_not_found:1017,cross_user_access_denied:1018,unsupported_password_algo:1019,invalid_password_storage:1020,user_not_activated:1022,bns_permission_denied:1023,bns_name_already_exists:1024,bns_write_failed:1025,bns_proxy_unavailable:1026,bns_controller_unavailable:1027,invalid_email:1028,email_already_bound:1029,internal_error:1099},SN_REGION_PROBE_CONFIG_PATH:Eb,SN_REGION_PROBE_FETCH_TIMEOUT:5e3,SN_REGION_PROBE_MAX_CONFIG_BYTES:kb,SN_REGION_PROBE_MAX_REGIONS:64,SN_REGION_PROBE_MAX_TOTAL_URLS:256,SN_REGION_PROBE_MAX_URLS_PER_REGION:16,SN_REGION_PROBE_SCHEMA_VERSION:1,SN_ROOT_PATH:wb,SnClient:class{constructor(t,e=null,n={}){this.authRpc=new jn(tA(t,"auth"),e,null,n),this.deviceInfoRpc=new jn(tA(t,"deviceinfo"),e,null,n),this.bnsProxyRpc=new jn(tA(t,"bns-proxy"),e,null,n)}setSeq(t){this.authRpc.setSeq(t),this.deviceInfoRpc.setSeq(t),this.bnsProxyRpc.setSeq(t)}syncSessionToken(t){this.authRpc.setSessionToken(t),this.deviceInfoRpc.setSessionToken(t),this.bnsProxyRpc.setSessionToken(t)}getSessionToken(){return this.authRpc.getSessionToken()}async call(t,e,n){try{return await t.call(e,n)}catch(r){throw Jb.fromRpcError(e,r)}}async checkUsername(t){return this.call(this.authRpc,Sb,{name:t})}async checkActiveCode(t){return this.call(this.authRpc,Tb,{active_code:t})}async register(t){const e={name:t.name,email:t.email,pwd_hash:t.pwd_hash,active_code:t.active_code};return void 0!==t.request_id&&(e.request_id=t.request_id),void 0!==t.region&&(e.region=t.region),void 0!==t.asset_owner&&(e.asset_owner=t.asset_owner),void 0!==t.owner_config&&(e.owner_config=t.owner_config),void 0!==t.initial_documents&&(e.initial_documents=function(t){const e={};void 0!==t.zone&&(e.zone=t.zone);void 0!==t.boot&&(e.boot=t.boot);void 0!==t.dns_txt&&(e.dns_txt=t.dns_txt.map((t=>({ttl:t.ttl,value:t.value}))));return e}(t.initial_documents)),this.call(this.authRpc,Rb,e)}async login(t){const e={name:t.name,pwd_hash:t.pwd_hash};return void 0!==t.active_code&&(e.active_code=t.active_code),this.call(this.authRpc,Ib,e)}async refresh(t){return this.call(this.authRpc,Ob,{refresh_token:t})}async logout(t){return this.call(this.authRpc,Cb,{refresh_token:t??null})}async me(){return this.call(this.authRpc,xb,{})}async getProfile(){return this.call(this.authRpc,Nb,{})}async setSelfCert(t,e){return this.call(this.authRpc,Pb,{self_cert:t,device_did:e??null})}async addDnsRecord(t){return this.call(this.authRpc,Db,vA(t))}async removeDnsRecord(t){return this.call(this.authRpc,Bb,vA(t))}async listDnsRecords(){return this.call(this.authRpc,Ub,{})}async getZoneInfo(){return this.call(this.authRpc,Lb,{})}async bindDomain(t){return this.call(this.authRpc,Mb,{domain:t})}async unbindDomain(t){return this.call(this.authRpc,Fb,{domain:t})}async registerDeviceOnline(t){return this.call(this.deviceInfoRpc,Gb,kA(t))}async updateDeviceOnline(t){return this.call(this.deviceInfoRpc,jb,kA(t))}async getDeviceOnline(t){return this.call(this.deviceInfoRpc,Hb,{device_name:t.device_name??null,device_did:t.device_did??null})}async listDevicesOnline(t={}){const e={};return void 0!==t.state&&(e.state=t.state),void 0!==t.offset&&(e.offset=t.offset),void 0!==t.limit&&(e.limit=t.limit),this.call(this.deviceInfoRpc,Vb,e)}async resolveOodByDid(t){return this.call(this.deviceInfoRpc,Wb,{source_device_id:t})}async resolveOodByHostname(t){return this.call(this.deviceInfoRpc,Kb,{dest_host:t})}async publishDnsTxt(t){const e={name:t.name,mode:t.mode};switch(void 0!==t.request_id&&(e.request_id=t.request_id),t.mode){case"add":if(!t.value)throw new Jb("validation","publish_dns_txt mode=add requires value");e.value=t.value,void 0!==t.ttl&&(e.ttl=t.ttl);break;case"remove":if(!t.value)throw new Jb("validation","publish_dns_txt mode=remove requires value");e.value=t.value;break;case"replace":if(!t.records)throw new Jb("validation","publish_dns_txt mode=replace requires records");e.records=t.records.map(_A);break;default:throw new Jb("validation",`publish_dns_txt mode \`${t.mode}\` is not supported`)}return this.call(this.bnsProxyRpc,zb,e)}async publishDocument(t){const e=null!==t.document&&"object"==typeof t.document&&!Array.isArray(t.document),n="string"==typeof t.document?t.document.trim().split("."):[],r=3===n.length&&n.every((t=>t.length>0));if(!e&&!r)throw new Jb("validation","publish_document document must be a JSON object or non-empty compact JWT string");if("owner"===t.doc_type.trim().toLowerCase()&&!e)throw new Jb("validation","owner document must be a JSON object");const s={name:t.name,doc_type:t.doc_type,document:t.document};return void 0!==t.request_id&&(s.request_id=t.request_id),this.call(this.bnsProxyRpc,qb,s)}async removeBoundZone(t){return this.call(this.bnsProxyRpc,$b,{name:t.name,zone_did:t.zone_did,expected_owner_hash:t.expected_owner_hash,request_id:t.request_id,owner_authorization:t.owner_authorization})}},SnClientError:Jb,fetchSnRegionProbeConfig:async function(t,e=null,n={}){const r=wA(t),s={Accept:"application/json"};null!==e&&(/[\u0000-\u001f\u007f]/.test(e)&&sA("invalid cached region probe ETag: header value contains control characters"),s["If-None-Match"]=e);const i=new AbortController,o=setTimeout((()=>i.abort()),5e3);try{let t;try{t=await(n.fetcher??bA)(r,{method:"GET",headers:s,redirect:"manual",credentials:"omit",signal:i.signal})}catch(a){throw new Jb("transport",`fetch SN region probe config from ${r} failed: ${String(a)}`)}if(304===t.status)return{kind:"not_modified"};if(404===t.status)return{kind:"not_configured"};if(200!==t.status)throw new Jb("transport",`fetch SN region probe config from ${r} returned HTTP ${t.status}`);const e=t.headers.get("content-type")??"";if("application/json"!==e.split(";")[0].trim().toLowerCase())throw new Jb("transport",`SN region probe config from ${r} has unsupported Content-Type ${JSON.stringify(e)}`);const o=t.headers.get("content-length");if(null!==o&&/^\d+$/.test(o)&&Number(o)>kb)throw new Jb("transport",`SN region probe config from ${r} exceeds 1048576 bytes`);let c,l;try{c=await async function(t,e){if(!t.body){const n=new Uint8Array(await t.arrayBuffer());if(n.byteLength>kb)throw new Jb("transport",`SN region probe config from ${e} exceeds 1048576 bytes`);return n}const n=t.body.getReader(),r=[];let s=0;for(;;){const{done:t,value:i}=await n.read();if(t)break;if(s+=i.byteLength,s>kb)throw await n.cancel(),new Jb("transport",`SN region probe config from ${e} exceeds 1048576 bytes`);r.push(i)}const i=new Uint8Array(s);let o=0;for(const a of r)i.set(a,o),o+=a.byteLength;return i}(t,r)}catch(a){if(a instanceof Jb)throw a;throw new Jb("transport",`read SN region probe config from ${r} failed: ${String(a)}`)}try{l=yA(c)}catch(a){const t=a instanceof Jb?a.detail:String(a);throw new Jb("validation",`invalid SN region probe config from ${r}: ${t}`)}return{kind:"modified",document:{config:l,etag:t.headers.get("etag"),cache_control:t.headers.get("cache-control")}}}finally{clearTimeout(o)}},generateSnDeviceToken:async function(t,e,n,r=600){const s=Math.floor(Date.now()/1e3);return Mn.signJwtEdDSA({aud:AA,exp:s+r,iss:e,sub:t},n)},isCanonicalSnRegionId:dA,isPublicSnProbeIp:pA,normalizeSnRegionIdHint:function(t){const e=t.trim();if(0===iA(e)||iA(e)>128)return null;let n="",r=!1;for(const s of e)if(/^[A-Za-z0-9]$/.test(s))r&&n.length>0&&(n+="-"),r=!1,n+=s.toLowerCase();else{if("-"!==s&&"_"!==s&&"/"!==s&&"."!==s&&!/^\s$/u.test(s))return null;r=n.length>0}return n.length>0?n:null},normalizeSnRegionProbeUrl:wA,normalizeSnUrl:tA,parseSnRegionProbeConfig:yA,validateSnRegionProbeConfig:mA},Symbol.toStringTag,{value:"Module"}));let TA=null;function RA(t,e){let n=null,r=0;const s=[];return{result:new Promise(((i,o)=>{let a;try{a=new Worker(function(){if(!TA){const t=new Blob(['\n"use strict";\nself.onmessage = async function (e) {\n var file = e.data.file;\n var chunkSize = e.data.chunkSize;\n var fileSize = file.size;\n try {\n var offset = 0;\n var index = 0;\n while (offset < fileSize) {\n var end = Math.min(offset + chunkSize, fileSize);\n var buf = await file.slice(offset, end).arrayBuffer();\n var hashBuf = await crypto.subtle.digest("SHA-256", buf);\n var hash = new Uint8Array(hashBuf);\n self.postMessage(\n { type: "chunk", index: index, hash: hash, offset: offset, length: end - offset },\n [hashBuf]\n );\n offset = end;\n index++;\n }\n self.postMessage({ type: "done" });\n } catch (err) {\n self.postMessage({ type: "error", message: err && err.message ? err.message : String(err) });\n }\n};\n'],{type:"application/javascript"});TA=URL.createObjectURL(t)}return TA}())}catch{return void o(new Error("Failed to create hash worker"))}a.onmessage=t=>{const e=t.data;if("chunk"===e.type){const t={index:e.index,hash:e.hash,offset:e.offset,length:e.length};s.push(t),r+=t.length,n&&n(r)}else"done"===e.type?(a.terminate(),i(s)):"error"===e.type&&(a.terminate(),o(new Error(e.message??"Worker hash error")))},a.onerror=t=>{a.terminate(),o(new Error(t.message??"Worker error"))},a.postMessage({file:t,chunkSize:e})})),onProgress(t){n=t}}}class IA extends Error{constructor(t,e){super(e??t),this.code=t,this.name="NdmError"}}class OA extends Error{constructor(t,e,n,r){super(n??`NDM store API request failed with status ${t}`),this.name="NdmStoreApiError",this.status=t,this.errorCode=e,this.responseBody=r}}const CA=4096,xA=new Map;let NA=0;let PA={getCapabilities:()=>({canRevealRealPath:!1,canUseNDMCache:!1,canUseNDMStore:!1,canPickDirectory:"undefined"!=typeof HTMLInputElement&&"webkitdirectory"in HTMLInputElement.prototype,canPickMixed:!1}),pickFiles(t){return new Promise(((e,n)=>{const r=document.createElement("input");if(r.type="file","single_dir"===t.mode){if(!this.getCapabilities().canPickDirectory)return void n(new IA("DIRECTORY_NOT_SUPPORTED","This browser does not support directory selection"));r.webkitdirectory=!0}else"multi_file"!==t.mode&&"mixed"!==t.mode||(r.multiple=!0);t.accept&&t.accept.length>0&&"single_dir"!==t.mode&&(r.accept=t.accept.join(","));let s=!1;r.addEventListener("change",(()=>{if(s)return;s=!0;const t=r.files;t&&0!==t.length?e(Array.from(t)):n(new IA("USER_CANCELLED","No files selected"))}));const i=()=>{setTimeout((()=>{s||(s=!0,n(new IA("USER_CANCELLED","User cancelled file selection"))),window.removeEventListener("focus",i)}),500)};window.addEventListener("focus",i),r.click()}))}};function DA(t,e){if("undefined"!=typeof window&&"function"==typeof window.fetch)return window.fetch(t,e);if("undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch)return globalThis.fetch(t,e);throw new Error("fetch is not available in this runtime")}function BA(t){return t.replace(/\/+$/,"")}function UA(t){return encodeURIComponent(t).replace(/%3A/gi,":")}function LA(t){if(null==t?void 0:t.endpoint)return BA(t.endpoint);const e=Ri();if(e)return BA(e);throw new IA("STORE_API_ENDPOINT_REQUIRED","NDM structured store endpoint is unknown; pass options.endpoint or call initBuckyOS first")}async function MA(t,e,n){var r;!function(){if(Ti()===Ds.Browser)throw new IA("STORE_API_NOT_SUPPORTED_IN_RUNTIME","NDM structured store APIs are not available in pure Browser runtime")}();const s=LA(n),i=(null==n?void 0:n.fetcher)??DA,o=void 0!==(null==n?void 0:n.sessionToken)?n.sessionToken:await Ii(),a={Accept:"application/json","Content-Type":"application/json",...(null==n?void 0:n.headers)??{}};o&&!a.Authorization&&(a.Authorization=`Bearer ${o}`);const c=await i(`${s}/ndm/v1/store/${t}`,{method:"POST",headers:a,body:JSON.stringify(e),credentials:(null==n?void 0:n.credentials)??"include"});if(204===c.status)return void(await(null==(r=c.body)?void 0:r.cancel()));const l=(c.headers.get("content-type")??"").includes("application/json")?await c.json():await c.text();if(!c.ok){const t=l&&"object"==typeof l&&!Array.isArray(l)?l:null;throw new OA(c.status,null==t?void 0:t.error,(null==t?void 0:t.message)??("string"==typeof l&&l.length>0?l:`NDM store API request failed with status ${c.status}`),l)}return l}async function FA(t,e){const n=[`scope=${UA(t.scope)}`,`quick_hash=${UA(t.quick_hash)}`];t.inner_path&&n.push(`inner_path=${UA(t.inner_path)}`);const r=await async function(t,e){const n=LA(e),r=(null==e?void 0:e.fetcher)??DA,s=void 0!==(null==e?void 0:e.sessionToken)?e.sessionToken:await Ii(),i={Accept:"application/json",...(null==e?void 0:e.headers)??{}};s&&!i.Authorization&&(i.Authorization=`Bearer ${s}`);const o=await r(`${n}${t}`,{method:"GET",headers:i,credentials:(null==e?void 0:e.credentials)??"include"}),a=(o.headers.get("content-type")??"").includes("application/json")?await o.json():await o.text();if(!o.ok){const t=a&&"object"==typeof a&&!Array.isArray(a)?a:null;throw new OA(o.status,null==t?void 0:t.error,(null==t?void 0:t.message)??("string"==typeof a&&a.length>0?a:`NDM zone gateway request failed with status ${o.status}`),a)}return a}(`/ndm/v1/objects/lookup?${n.join("&")}`,e);return function(t){try{return Mn.ObjId.fromString(t).isChunk()}catch{return!1}}(t.quick_hash),r}async function GA(t,e=33554432){const n=t.size,r=[];if(n<=e){const e=new Uint8Array(await t.arrayBuffer()),s=Mn.sha256Bytes(e),i=Mn.ChunkId.fromMix256Result(e.length,s).toString();r.push({chunkId:i,offset:0,length:e.length,uploaded:!1});const o=new Mn.FileObject(t.name,n,i),[a]=o.genObjId();return{objectId:a.toString(),chunks:r,fileObject:o.toJSON()}}const s=new Mn.SimpleChunkList;let i=0;for(;i<n;){const o=Math.min(i+e,n),a=new Uint8Array(await t.slice(i,o).arrayBuffer()),c=Mn.sha256Bytes(a),l=Mn.ChunkId.fromMix256Result(a.length,c);s.appendChunk(l),r.push({chunkId:l.toString(),offset:i,length:a.length,uploaded:!1}),i=o}const[o]=s.genObjId(),a=new Mn.FileObject(t.name,n,o.toString()),[c]=a.genObjId();return{objectId:c.toString(),chunks:r,fileObject:a.toJSON()}}async function jA(t,e,n=33554432){if("undefined"==typeof Worker||"undefined"==typeof Blob||"undefined"==typeof URL||"function"!=typeof URL.createObjectURL||"undefined"==typeof crypto||void 0===crypto.subtle)return GA(t,n);let r;try{const s=RA(t,n);e&&s.onProgress(e);const i=3e5,o=new Promise(((t,e)=>{setTimeout((()=>e(new Error("hash worker timeout"))),i)}));r=await Promise.race([s.result,o])}catch{return GA(t,n)}const s=t.size,i=[];if(1===r.length){const e=r[0],n=Mn.ChunkId.fromMix256Result(e.length,e.hash).toString();i.push({chunkId:n,offset:0,length:e.length,uploaded:!1});const o=new Mn.FileObject(t.name,s,n),[a]=o.genObjId();return{objectId:a.toString(),chunks:i,fileObject:o.toJSON()}}const o=new Mn.SimpleChunkList;for(const u of r){const t=Mn.ChunkId.fromMix256Result(u.length,u.hash);o.appendChunk(t),i.push({chunkId:t.toString(),offset:u.offset,length:u.length,uploaded:!1})}const[a]=o.genObjId(),c=new Mn.FileObject(t.name,s,a.toString()),[l]=c.genObjId();return{objectId:l.toString(),chunks:i,fileObject:c.toJSON()}}function HA(t,e,n){const r=new Mn.FileObject(t,e,n),[s]=r.genObjId();return{objectId:s.toString(),fileObject:r.toJSON()}}async function VA(t){const e=t.size;if(e<12288)return null;const n=new Uint8Array(await t.slice(0,CA).arrayBuffer()),r=Math.floor(e/2),s=new Uint8Array(await t.slice(r,r+CA).arrayBuffer()),i=new Uint8Array(n.length+s.length);i.set(n,0),i.set(s,n.length);const o=Mn.sha256Bytes(i);return Mn.ChunkId.fromMixHashResult(e,o,"qcid").toString()}function WA(t,e){const n=t;if("string"==typeof n.same_as&&n.same_as.length>0)return n.same_as;const r=["chunk_list_id","chunklistid","chunk_id","chunkid","content_id","content"];for(const s of r){const t=n[s];if("string"==typeof t&&t.length>0)return t}return"string"==typeof n.object_id&&n.object_id.length>0&&n.object_id!==e?n.object_id:void 0}async function KA(t){const e=function(){var t;const e=Ri();return e?BA(e):"undefined"!=typeof window&&(null==(t=window.location)?void 0:t.origin)?BA(window.location.origin):void 0}();if(!e)return null;const n=await VA(t);if(!n)return null;for(const s of["app","global"])try{const r=WA(await FA({scope:s,quick_hash:n},{endpoint:e,sessionToken:Ti()===Ds.Browser?null:void 0}),n);if(!r)continue;return{...HA(t.name,t.size,r),locality:"store"}}catch(r){if(r instanceof OA&&404===r.status)continue;return null}return null}function zA(t,e){const n=t[0].webkitRelativePath,r={kind:"dir",objectId:"",name:n?n.split("/")[0]:"directory",children:[]},s=new Map;s.set("",r);for(const i of e){const t=(i.relativePath??i.name).split("/"),e=t.length>1?t.slice(1):t;let n=r;for(let r=0;r<e.length-1;r++){const t=e[r],i=e.slice(0,r+1).join("/");let o=s.get(i);o||(o={kind:"dir",objectId:"",name:t,relativePath:i,children:[]},s.set(i,o),n.children.push(o)),n=o}n.children.push(i)}return qA(r),r}function qA(t){const e=new Mn.DirObject(t.name);if(t.children)for(const r of t.children)if("file"===r.kind){if(!r._ndnFileObject)throw new IA("UPLOAD_FAILED",`Missing NDN FileObject for ${r.name}`);e.addFile(r.name,r._ndnFileObject,r.size)}else{const t=qA(r);e.addDirectory(r.name,Mn.ObjId.fromString(t.objectId),t.totalSize)}const[n]=e.genObjId();return t.objectId=n.toString(),{objectId:t.objectId,totalSize:e.total_size,fileCount:e.file_count,fileSize:e.file_size}}function $A(t,e){if(!e||!e.enabled)return!1;if(!e.forTypes||0===e.forTypes.length)return t.type.startsWith("image/");for(const n of e.forTypes)if(n.endsWith("/*")){const e=n.slice(0,-1);if(t.type.startsWith(e))return!0}else if(n.startsWith(".")){if(t.name.toLowerCase().endsWith(n.toLowerCase()))return!0}else if(t.type===n)return!0;return!1}async function QA(t,e){const n=e.maxWidth??256,r=e.maxHeight??256;try{return t.type.startsWith("image/")?await function(t,e,n){return new Promise((r=>{const s=URL.createObjectURL(t),i=new Image;i.onload=()=>{let t=i.naturalWidth,o=i.naturalHeight;if(t>e||o>n){const r=Math.min(e/t,n/o);t=Math.round(t*r),o=Math.round(o*r)}const a=document.createElement("canvas");a.width=t,a.height=o;a.getContext("2d").drawImage(i,0,0,t,o);const c=a.toDataURL("image/jpeg",.8);URL.revokeObjectURL(s),r({available:!0,url:c,width:t,height:o,mimeType:"image/jpeg"})},i.onerror=()=>{URL.revokeObjectURL(s),r({available:!1,errorCode:"THUMBNAIL_GENERATION_FAILED"})},i.src=s}))}(t,n,r):{available:!1,errorCode:"UNSUPPORTED_TYPE"}}catch{return{available:!1,errorCode:"THUMBNAIL_GENERATION_FAILED"}}}async function JA(t){const e=xA.get(t);if(!e)throw new IA("SESSION_NOT_FOUND",`Session ${t} not found`);const n={};let r=0,s=0;for(const[i,o]of e.objectStates)n[i]={objectId:o.objectId,uploadedBytes:o.uploadedBytes,totalBytes:o.size,state:o.state},r+=o.uploadedBytes,"completed"===o.state&&s++;return{sessionId:t,materializationStatus:e.materializationStatus,uploadStatus:e.uploadStatus,summary:e.summary,progress:{uploadedBytes:r,uploadedObjects:s,totalBytes:e.summary.totalBytes,totalObjects:e.summary.totalFiles},perObjectProgress:n}}async function YA(t,e,n,r,s,i,o,a){const c=e.slice(n.offset,n.offset+n.length),l=new Uint8Array(await c.arrayBuffer()),u=`${s}/${n.chunkId}`;let h;try{h=await Promise.resolve().then((()=>require("./tus_client-d0798623.js")))}catch(d){const t=d instanceof Error?d.message:String(d);throw new IA("UPLOAD_FAILED",`Failed to load tus-js-client: ${t}`)}return new Promise(((c,d)=>{if(null==a?void 0:a.aborted)return void d(new IA("UPLOAD_FAILED","Upload aborted"));const f=new Blob([l]),p=new h.Upload(f,{endpoint:`${t}/ndm/v1/uploads`,chunkSize:l.length,retryDelays:[0,1e3,3e3,5e3],storeFingerprintForResuming:!1,metadata:{app_id:s,logical_path:u,file_name:e.name,file_size:String(e.size),file_hash:i,chunk_index:String(r),chunk_hash:n.chunkId,mime_type:e.type||"application/octet-stream"},onProgress:t=>{o(t)},onSuccess:()=>{o(l.length),c(n.chunkId)},onError:t=>{d(new IA("UPLOAD_FAILED",t.message))}});a&&a.addEventListener("abort",(()=>{p.abort(!0),d(new IA("UPLOAD_FAILED","Upload aborted"))})),p.start()}))}async function ZA(t,e){const n=xA.get(t);if(!n)throw new IA("SESSION_NOT_FOUND",`Session ${t} not found`);if("completed"===n.uploadStatus||"not_required"===n.uploadStatus)return JA(t);if("uploading"===n.uploadStatus)return JA(t);if("all_in_store"===n.materializationStatus)return n.uploadStatus="not_required",JA(t);n.uploadStatus="uploading",n.uploadStartTime=Date.now(),n.abortController=new AbortController;const r=(null==e?void 0:e.concurrency)??3;let s;return s=(null==e?void 0:e.endpoint)?e.endpoint.replace(/\/+$/,""):"undefined"!=typeof window?window.location.origin:"",async function(t,e,n){const r=Array.from(t.objectStates.values()).filter((t=>"completed"!==t.state));let s=0,i=0,o=!1;await new Promise(((a,c)=>{function l(){if(!o){if(i>=r.length&&0===s){const e=Array.from(t.objectStates.values()).every((t=>"completed"===t.state));return t.uploadStatus=e?"completed":"failed",void a()}for(;s<n&&i<r.length;){const n=r[i++];s++,XA(t,e,n).then((()=>{s--,l()})).catch((()=>{s--,o||(o=!0,t.uploadStatus="failed",c(new IA("UPLOAD_FAILED",`Upload of ${n.name} failed`)))}))}}}l()}))}(n,s,r).catch((()=>{})),JA(t)}async function XA(t,e,n){var r;n.state="uploading";for(const[s,i]of n.chunks.entries())i.uploaded||(await YA(e,n.file,i,s,"default",n.objectId,(t=>{const e=n.chunks.filter((t=>t!==i&&t.uploaded)).reduce(((t,e)=>t+e.length),0);n.uploadedBytes=e+t}),null==(r=t.abortController)?void 0:r.signal),i.uploaded=!0);n.uploadedBytes=n.size,n.state="completed"}const t_=Object.freeze(Object.defineProperty({__proto__:null,NdmError:IA,NdmStoreApiError:OA,addChunkBySameAs:async function(t,e){return MA("add_chunk_by_same_as",t,e)},anchorState:async function(t,e){return MA("anchor_state",t,e)},applyEdge:async function(t,e){return MA("apply_edge",t,e)},calculateQcidFromFile:async function(t){const e=await VA(t);if(!e)throw new Error("QCID requires file size >= 12288 bytes");return e},debugDumpExpandState:async function(t,e){return MA("debug_dump_expand_state",t,e)},forcedGcUntil:async function(t,e){return MA("forced_gc_until",t,e)},fsAcquire:async function(t,e){return MA("fs_acquire",t,e)},fsAnchorState:async function(t,e){return MA("fs_anchor_state",t,e)},fsRelease:async function(t,e){return MA("fs_release",t,e)},fsReleaseInode:async function(t,e){return MA("fs_release_inode",t,e)},getDirChild:async function(t,e){return MA("get_dir_child",t,e)},getImportProvider:function(){return PA},getImportSessionStatus:JA,getObject:async function(t,e){return MA("get_object",t,e)},getUploadProgress:async function(t){const e=await JA(t),n={sessionId:t,uploadStatus:e.uploadStatus,totalBytes:e.progress.totalBytes,uploadedBytes:e.progress.uploadedBytes,totalObjects:e.progress.totalObjects,uploadedObjects:e.progress.uploadedObjects,perObjectProgress:e.perObjectProgress},r=xA.get(t);if(r.uploadStartTime&&"uploading"===e.uploadStatus&&(n.elapsedMs=Date.now()-r.uploadStartTime,n.uploadedBytes>0&&n.elapsedMs>0)){n.speedBps=Math.round(1e3*n.uploadedBytes/n.elapsedMs);const t=n.totalBytes-n.uploadedBytes;n.estimatedRemainingMs=Math.round(1e3*t/n.speedBps)}return n},haveChunk:async function(t,e){return MA("have_chunk",t,e)},isObjectExist:async function(t,e){return MA("is_object_exist",t,e)},isObjectStored:async function(t,e){return MA("is_object_stored",t,e)},lookupObject:FA,openObject:async function(t,e){return MA("open_object",t,e)},outboxCount:async function(t){return MA("outbox_count",{},t)},pickupAndImport:async function(t){var e;const n=PA.getCapabilities();if("single_dir"===t.mode&&!n.canPickDirectory)throw new IA("DIRECTORY_NOT_SUPPORTED","Current runtime does not support directory selection");if("mixed"===t.mode&&!n.canPickMixed)throw new IA("MODE_NOT_SUPPORTED_IN_RUNTIME","Current runtime does not support mixed file/directory selection");const r=await PA.pickFiles(t);if(0===r.length)throw new IA("USER_CANCELLED","No files selected");const s=[],i=new Map;let o=!0;const a=t.onProgress,c=r.length;for(let y=0;y<r.length;y++){const n=r[y],l=n.webkitRelativePath||void 0;a&&a({phase:"qcid_lookup",fileIndex:y,fileCount:c,fileName:n.name,fileTotalBytes:n.size});const u=await KA(n);let h=null;u||(a&&a({phase:"materializing",fileIndex:y,fileCount:c,fileName:n.name,bytesProcessed:0,fileTotalBytes:n.size}),h=await jA(n,a?t=>{a({phase:"materializing",fileIndex:y,fileCount:c,fileName:n.name,bytesProcessed:t,fileTotalBytes:n.size})}:void 0));const d=(null==u?void 0:u.objectId)??h.objectId,f=(null==u?void 0:u.fileObject)??h.fileObject,p=u?[]:h.chunks,g={kind:"file",objectId:d,name:n.name,size:n.size,mimeType:n.type||void 0,relativePath:l,locality:(null==u?void 0:u.locality)??"local_only",_file:n,_ndnFileObject:f};if($A(n,t.thumbnails)){a&&a({phase:"thumbnail",fileIndex:y,fileCount:c,fileName:n.name,fileTotalBytes:n.size});!1!==(null==(e=t.thumbnails)?void 0:e.eager)?g.thumbnail=await QA(n,t.thumbnails):(g.thumbnail={available:!1},QA(n,t.thumbnails).then((t=>{g.thumbnail=t})))}s.push(g),u||(o=!1),i.set(d,{objectId:d,name:n.name,size:n.size,file:n,uploadedBytes:u?n.size:0,state:u?"completed":"pending",chunks:p})}let l,u;if("single_dir"===t.mode){const t=zA(r,s);l=[t],u=t}else l=s,u="single_file"===t.mode?s[0]:s;const h=function(t){let e=0,n=0,r=0;return function t(s){for(const i of s)"file"===i.kind?(e++,r+=i.size):(n++,i.children&&t(i.children))}(t),{totalObjects:e+n,totalFiles:e,totalDirs:n,totalBytes:r}}(l),d=(NA+=1,`import-${Date.now()}-${NA}`);let f="ok";o||n.canUseNDMStore?f="all_in_store":n.canUseNDMCache&&(f="on_cache");const p="all_in_store"===f?"not_required":"not_started",g={sessionId:d,items:l,materializationStatus:f,uploadStatus:p,summary:h,objectStates:i};xA.set(d,g);const m={sessionId:d,selection:u,items:l,materializationStatus:f,uploadStatus:p,summary:h};return t.autoStartUpload&&"not_started"===p&&(ZA(d).catch((()=>{})),m.uploadStatus="uploading"),m},pin:async function(t,e){return MA("pin",t,e)},putObject:async function(t,e){return MA("put_object",t,e)},queryChunkState:async function(t,e){return MA("query_chunk_state",t,e)},queryObjectById:async function(t,e){return MA("query_object_by_id",t,e)},removeChunk:async function(t,e){return MA("remove_chunk",t,e)},removeObject:async function(t,e){return MA("remove_object",t,e)},setImportProvider:function(t){PA=t},startUpload:ZA,unpin:async function(t,e){return MA("unpin",t,e)},unpinOwner:async function(t,e){return MA("unpin_owner",t,e)}},Symbol.toStringTag,{value:"Module"})),e_="/ndm/proxy/v1";class n_ extends Error{constructor(t,e,n,r){super(n??`NDM proxy request failed with status ${t}`),this.name="NdmProxyApiError",this.status=t,this.errorCode=e,this.responseBody=r}}class r_ extends Error{constructor(t,e){super(e??t),this.name="NdmProxyError",this.code=t}}function s_(t,e){if("undefined"!=typeof window&&"function"==typeof window.fetch)return window.fetch(t,e);if("undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch)return globalThis.fetch(t,e);throw new Error("fetch is not available in this runtime")}function i_(t){return t.replace(/\/+$/,"")}function o_(){const t=Ti();if(t===Ds.Browser||t===Ds.AppRuntime)throw new r_("PROXY_API_NOT_SUPPORTED_IN_RUNTIME","NDM proxy APIs are not available in Browser/AppRuntime; use ndm_client for browser import/upload flows")}function a_(t){if(null==t?void 0:t.endpoint)return i_(t.endpoint);const e=Ri();if(e)return i_(e);throw new r_("PROXY_API_ENDPOINT_REQUIRED","NDM proxy endpoint is unknown; pass options.endpoint or call initBuckyOS first")}async function c_(t,e){const n=void 0!==(null==t?void 0:t.sessionToken)?t.sessionToken:await Ii(),r={...e,...(null==t?void 0:t.headers)??{}};return n&&!r.Authorization&&(r.Authorization=`Bearer ${n}`),r}async function l_(t){const e=(t.headers.get("content-type")??"").includes("application/json")?await t.json():await t.text(),n=e&&"object"==typeof e&&!Array.isArray(e)?e:null;throw new n_(t.status,null==n?void 0:n.error,(null==n?void 0:n.message)??("string"==typeof e&&e.length>0?e:`NDM proxy request failed with status ${t.status}`),e)}async function u_(t,e,n){var r;o_();const s=a_(n),i=(null==n?void 0:n.fetcher)??s_,o=await c_(n,{Accept:"application/json","Content-Type":"application/json"}),a=await i(`${s}${e_}/rpc/${t}`,{method:"POST",headers:o,body:JSON.stringify(e),credentials:(null==n?void 0:n.credentials)??"include"});if(!a.ok)return l_(a);if(204===a.status)return void(await(null==(r=a.body)?void 0:r.cancel()));if(!(a.headers.get("content-type")??"").includes("application/json")){const t=await a.text();throw new n_(a.status,"invalid_data",t.length>0?t:"NDM proxy JSON RPC returned a non-JSON response",t)}return await a.json()}function h_(t,e){const n=t.get(e);if(null===n||""===n.trim())return null;const r=Number(n);return Number.isFinite(r)?r:null}async function d_(t,e,n){o_();const r=a_(n),s=(null==n?void 0:n.fetcher)??s_,i=await c_(n,{Accept:"application/octet-stream","Content-Type":"application/json"}),o=await s(`${r}${e_}${t}`,{method:"POST",headers:i,body:JSON.stringify(e),credentials:(null==n?void 0:n.credentials)??"include"});return o.ok?{response:o,body:o.body,totalSize:h_(o.headers,"NDM-Total-Size"),resolvedObjectId:o.headers.get("NDM-Resolved-Object-ID")??void 0,readerKind:o.headers.get("NDM-Reader-Kind")??void 0,contentLength:h_(o.headers,"Content-Length"),offset:h_(o.headers,"NDM-Offset")}:l_(o)}async function f_(t){const e=await t.response.arrayBuffer();return new Uint8Array(e)}class p_{constructor(t){this.options=t}getObject(t,e){return w_(t,{...this.options,...e})}openObject(t,e){return b_(t,{...this.options,...e})}getDirChild(t,e){return A_(t,{...this.options,...e})}isObjectStored(t,e){return __(t,{...this.options,...e})}isObjectExist(t,e){return v_(t,{...this.options,...e})}queryObjectById(t,e){return E_(t,{...this.options,...e})}putObject(t,e){return k_(t,{...this.options,...e})}removeObject(t,e){return S_(t,{...this.options,...e})}haveChunk(t,e){return T_(t,{...this.options,...e})}queryChunkState(t,e){return R_(t,{...this.options,...e})}removeChunk(t,e){return I_(t,{...this.options,...e})}addChunkBySameAs(t,e){return O_(t,{...this.options,...e})}applyEdge(t,e){return C_(t,{...this.options,...e})}pin(t,e){return x_(t,{...this.options,...e})}unpin(t,e){return N_(t,{...this.options,...e})}unpinOwner(t,e){return P_(t,{...this.options,...e})}fsAcquire(t,e){return D_(t,{...this.options,...e})}fsRelease(t,e){return B_(t,{...this.options,...e})}fsReleaseInode(t,e){return U_(t,{...this.options,...e})}fsAnchorState(t,e){return L_(t,{...this.options,...e})}forcedGcUntil(t,e){return M_(t,{...this.options,...e})}outboxCount(t){return F_({...this.options,...t})}debugDumpExpandState(t,e){return G_(t,{...this.options,...e})}anchorState(t,e){return j_(t,{...this.options,...e})}}class g_{constructor(t){this.options=t}openChunkReader(t,e){return H_(t,{...this.options,...e})}getChunkData(t,e){return V_(t,{...this.options,...e})}getChunkPiece(t,e){return W_(t,{...this.options,...e})}openChunkListReader(t,e){return K_(t,{...this.options,...e})}openReader(t,e){return z_(t,{...this.options,...e})}}class m_{constructor(t){this.options=t}putChunkByReader(t,e,n){return q_(t,e,{...this.options,...n})}putChunk(t,e,n){return $_(t,e,{...this.options,...n})}}class y_{constructor(t){this.options=t,this.rpc=new p_(t),this.reader=new g_(t),this.writer=new m_(t)}getObject(t,e){return this.rpc.getObject(t,e)}openObject(t,e){return this.rpc.openObject(t,e)}getDirChild(t,e){return this.rpc.getDirChild(t,e)}isObjectStored(t,e){return this.rpc.isObjectStored(t,e)}isObjectExist(t,e){return this.rpc.isObjectExist(t,e)}queryObjectById(t,e){return this.rpc.queryObjectById(t,e)}putObject(t,e){return this.rpc.putObject(t,e)}removeObject(t,e){return this.rpc.removeObject(t,e)}haveChunk(t,e){return this.rpc.haveChunk(t,e)}queryChunkState(t,e){return this.rpc.queryChunkState(t,e)}removeChunk(t,e){return this.rpc.removeChunk(t,e)}addChunkBySameAs(t,e){return this.rpc.addChunkBySameAs(t,e)}applyEdge(t,e){return this.rpc.applyEdge(t,e)}pin(t,e){return this.rpc.pin(t,e)}unpin(t,e){return this.rpc.unpin(t,e)}unpinOwner(t,e){return this.rpc.unpinOwner(t,e)}fsAcquire(t,e){return this.rpc.fsAcquire(t,e)}fsRelease(t,e){return this.rpc.fsRelease(t,e)}fsReleaseInode(t,e){return this.rpc.fsReleaseInode(t,e)}fsAnchorState(t,e){return this.rpc.fsAnchorState(t,e)}forcedGcUntil(t,e){return this.rpc.forcedGcUntil(t,e)}outboxCount(t){return this.rpc.outboxCount(t)}debugDumpExpandState(t,e){return this.rpc.debugDumpExpandState(t,e)}anchorState(t,e){return this.rpc.anchorState(t,e)}openChunkReader(t,e){return this.reader.openChunkReader(t,e)}getChunkData(t,e){return this.reader.getChunkData(t,e)}getChunkPiece(t,e){return this.reader.getChunkPiece(t,e)}openChunkListReader(t,e){return this.reader.openChunkListReader(t,e)}openReader(t,e){return this.reader.openReader(t,e)}putChunkByReader(t,e,n){return this.writer.putChunkByReader(t,e,n)}putChunk(t,e,n){return this.writer.putChunk(t,e,n)}withOptions(t){return new y_({...this.options,...t})}}async function w_(t,e){return u_("get_object",t,e)}async function b_(t,e){return u_("open_object",t,e)}async function A_(t,e){return u_("get_dir_child",t,e)}async function __(t,e){return u_("is_object_stored",t,e)}async function v_(t,e){return u_("is_object_exist",t,e)}async function E_(t,e){return u_("query_object_by_id",t,e)}async function k_(t,e){return u_("put_object",t,e)}async function S_(t,e){return u_("remove_object",t,e)}async function T_(t,e){return u_("have_chunk",t,e)}async function R_(t,e){return u_("query_chunk_state",t,e)}async function I_(t,e){return u_("remove_chunk",t,e)}async function O_(t,e){return u_("add_chunk_by_same_as",t,e)}async function C_(t,e){return u_("apply_edge",t,e)}async function x_(t,e){return u_("pin",t,e)}async function N_(t,e){return u_("unpin",t,e)}async function P_(t,e){return u_("unpin_owner",t,e)}async function D_(t,e){return u_("fs_acquire",t,e)}async function B_(t,e){return u_("fs_release",t,e)}async function U_(t,e){return u_("fs_release_inode",t,e)}async function L_(t,e){return u_("fs_anchor_state",t,e)}async function M_(t,e){return u_("forced_gc_until",t,e)}async function F_(t){return u_("outbox_count",{},t)}async function G_(t,e){return u_("debug_dump_expand_state",t,e)}async function j_(t,e){return u_("anchor_state",t,e)}async function H_(t,e){return d_("/read/chunk/open",t,e)}async function V_(t,e){return f_(await d_("/read/chunk/data",t,e))}async function W_(t,e){return f_(await d_("/read/chunk/piece",t,e))}async function K_(t,e){return d_("/read/chunklist/open",t,e)}async function z_(t,e){return d_("/read/object/open",t,e)}async function q_(t,e,n){var r;o_();const s=a_(n),i=(null==n?void 0:n.fetcher)??s_,o=function(t){return t instanceof Uint8Array||t instanceof ArrayBuffer?t.byteLength:"undefined"!=typeof Blob&&t instanceof Blob?t.size:"string"==typeof t?(new TextEncoder).encode(t).byteLength:null}(e),a=(null==n?void 0:n.chunkSize)??o;if(null===a)throw new r_("PROXY_API_CHUNK_SIZE_REQUIRED","chunkSize is required when the request body length cannot be inferred");const c=await c_(n,{Accept:"application/json","Content-Type":"application/octet-stream","Content-Length":String(a),"NDM-Chunk-Size":String(a)}),l=await i(`${s}${function(t){return`${e_}/write/chunk/${encodeURIComponent(t)}`}(t)}`,{method:"PUT",headers:c,body:e,credentials:(null==n?void 0:n.credentials)??"include"});return l.ok?(await(null==(r=l.body)?void 0:r.cancel()),{chunkSize:h_(l.headers,"NDM-Chunk-Size"),outcome:l.headers.get("NDM-Chunk-Write-Outcome")??void 0,chunkObjectId:l.headers.get("NDM-Chunk-Object-ID")??void 0}):l_(l)}async function $_(t,e,n){return q_(t,e,{...n,chunkSize:(null==n?void 0:n.chunkSize)??e.byteLength})}const Q_=Object.freeze(Object.defineProperty({__proto__:null,NDM_PROXY_V1_PATH:e_,NdmProxyApiError:n_,NdmProxyClient:y_,NdmProxyError:r_,NdmProxyReaderClient:g_,NdmProxyRpcClient:p_,NdmProxyWriterClient:m_,addChunkBySameAs:O_,anchorState:j_,applyEdge:C_,createNdmProxyClient:function(t){return new y_(t)},debugDumpExpandState:G_,forcedGcUntil:M_,fsAcquire:D_,fsAnchorState:L_,fsRelease:B_,fsReleaseInode:U_,getChunkData:V_,getChunkPiece:W_,getDirChild:A_,getObject:w_,haveChunk:T_,isObjectExist:v_,isObjectStored:__,openChunkListReader:K_,openChunkReader:H_,openObject:b_,openReader:z_,outboxCount:F_,pin:x_,putChunk:$_,putChunkByReader:q_,putObject:k_,queryChunkState:R_,queryObjectById:E_,removeChunk:I_,removeObject:S_,unpin:N_,unpinOwner:P_},Symbol.toStringTag,{value:"Module"}));exports.AGENT_DELEGATE_TASK_SCHEMA_ID="agent.delegate/v1",exports.AICC_AI_METHODS=Lr,exports.AICC_COMPUTE_TASK_SCHEMA_ID="aicc.compute/v1",exports.AICC_CORE_METHODS=Mr,exports.AICC_EXECUTION_MODES=jr,exports.AICC_FEATURES={PLAN:"plan",TOOL_CALL:"tool_call",JSON_SCHEMA:"json_schema",WEB_SEARCH:"web_search",VISION:"vision",IMAGE_GENERATION:"image_generation",ASR:"asr",VIDEO_UNDERSTAND:"video_understand"},exports.AICC_MANAGEMENT_METHODS=Fr,exports.AICC_METHODS=Gr,exports.AICC_SERVICE_SERVICE_NAME="aicc",exports.AICC_SERVICE_SERVICE_PORT=4040,exports.AICC_SERVICE_UNIQUE_ID="aicc",exports.APP_INSTALL_TASK_SCHEMA_ID="app.install/v1",exports.APP_START_TASK_SCHEMA_ID="app.start/v1",exports.APP_UNINSTALL_TASK_SCHEMA_ID="app.uninstall/v1",exports.APP_UPDATE_BATCH_TASK_SCHEMA_ID="app.update_batch/v1",exports.APP_UPDATE_TASK_SCHEMA_ID="app.update/v1",exports.AiccClient=Qr,exports.BNS_DNS_TXT_DEFAULT_TTL=600,exports.BNS_DNS_TXT_DOC_TYPE=rb,exports.BNS_EVM_DEFAULT_GAS_LIMIT=Xw,exports.BNS_EVM_DEFAULT_MAX_FEE_PER_GAS=tb,exports.BNS_EVM_DEFAULT_MAX_PRIORITY_FEE_PER_GAS=eb,exports.BNS_MAX_INLINE_DOCUMENT_BYTES=nb,exports.BNS_PUBLISH_DOCUMENT_ABI=ib,exports.BS_SERVICE_TASK_MANAGER="task-manager",exports.BS_SERVICE_VERIFY_HUB="verify-hub",exports.BnsEvmTxBuilder=fb,exports.BnsEvmTxError=lb,exports.BnsTxExecutor=class{constructor(t={}){this.localExecutionTail=Promise.resolve(),this.options=t,this.evmTxBuilder=t.bnsClient&&t.evmConfig?new fb(t.bnsClient,t.evmConfig,t.evmProvider):null}async resolveRoute(){const t=this.getRuntimeType(),e=mb(t)?await this.getLocalPrivateKey():null;return this.resolveRouteFor(t,e)}async resolveRouteFor(t,e){if(mb(t)&&this.options.evmConfig&&e)return"local";if(t===Ds.AppRuntime){const t=await this.getCurrentWalletUser();if(t&&!yb(t))return"wallet"}return"sn-proxy"}async execute(t){const e=this.getRuntimeType(),n=mb(e)?await this.getLocalPrivateKey():null,r=await this.resolveRouteFor(e,n);switch(r){case"local":return this.executeLocally(t,e,n);case"wallet":throw new pb("WALLET_EXECUTION_NOT_IMPLEMENTED",r,`BNS wallet execution is not implemented for operation ${t.type}`);case"sn-proxy":return this.executeWithSn(t)}}publishDnsTxt(t){return this.execute({type:"publish_dns_txt",request:t})}publishDocument(t){return this.execute({type:"publish_document",request:t})}getRuntimeType(){return(this.options.getRuntimeType??Ti)()}getCurrentWalletUser(){return Promise.resolve((this.options.getCurrentWalletUser??wi)())}async getLocalPrivateKey(){const t=this.options.localPrivateKey;return gb("function"==typeof t?await t():t)}async executeWithSn(t){const e=this.options.snClient;if(!e)throw new pb("SN_CLIENT_UNAVAILABLE","sn-proxy",`SN client is required for BNS operation ${t.type}`);const n="publish_dns_txt"===t.type?await e.publishDnsTxt(t.request):await e.publishDocument(t.request);return{route:"sn-proxy",operation:t.type,response:n}}async executeLocally(t,e,n){const r=this.options.bnsClient;if(!r)throw new pb("BNS_CLIENT_UNAVAILABLE","local",`BNS client is required for local operation ${t.type}`);const s=this.evmTxBuilder;if(!n||!s)throw new pb("LOCAL_SIGNING_UNAVAILABLE","local",`Local signing configuration is unavailable for operation ${t.type}`);return this.enqueueLocalExecution((async()=>{try{const e=await s.buildAndSign(t,n),i=await r.submitRawTx(e);return{route:"local",operation:t.type,response:i}}catch(e){throw s.resetNonce(),e}}))}enqueueLocalExecution(t){const e=this.localExecutionTail.then(t,t);return this.localExecutionTail=e.then((()=>{}),(()=>{})),e}},exports.BnsTxExecutorError=pb,exports.BuckyOSSDK=Oi,exports.DEFAULT_CHILD_CONTROL_POLICY={follow_pause:!0,follow_resume:!0,follow_cancel:!0},exports.DOWNLOAD_TASK_SCHEMA_ID="download/v1",exports.HUMAN_APPROVAL_SCHEMA_ID="human.approval/v1",exports.HUMAN_INPUT_TASK_SCHEMA_ID="human.input/v1",exports.KEventClient=gi,exports.KEventReader=ui,exports.MsgCenterClient=fs,exports.MsgQueueClient=as,exports.OPENDAN_ASYNC_TOOL_TASK_SCHEMA_ID="opendan.async_tool/v1",exports.OPENDAN_COMMAND_TASK_SCHEMA_ID="opendan.command/v1",exports.RAW_TASK_SCHEMA_ID="raw/v1",exports.RepoClient=As,exports.RuntimeType=Ds,exports.SCHEDULER_DISPATCH_THUNK_TASK_SCHEMA_ID="scheduler.dispatch_thunk/v1",exports.StorageDomain=mr,exports.SystemConfigClient=Ur,exports.TASK_ERR_ALREADY_COMPLETED=tr,exports.TASK_ERR_CONTROL_ALREADY_PENDING=Xn,exports.TASK_ERR_CONTROL_NOT_AVAILABLE=Zn,exports.TASK_ERR_IDEMPOTENCY_CONFLICT=rr,exports.TASK_ERR_INPUT_SCHEMA_MISMATCH=er,exports.TASK_ERR_INVALID_PHASE=Yn,exports.TASK_ERR_NOT_FOUND=qn,exports.TASK_ERR_PERMISSION_DENIED=$n,exports.TASK_ERR_RESULT_SCHEMA_MISMATCH=nr,exports.TASK_ERR_REVISION_CONFLICT=Qn,exports.TASK_ERR_SCHEMA_NOT_FOUND=sr,exports.TASK_ERR_STALE_RUNNER_EPOCH=Jn,exports.TASK_MANAGER_SERVICE_NAME="task-manager",exports.TASK_MANAGER_SERVICE_PORT=3380,exports.TASK_MANAGER_SERVICE_UNIQUE_ID="task-manager",exports.TASK_MGR_ERROR_CODES=ir,exports.TASK_POLICY_PRESET_COLLABORATIVE_TREE_V1="collaborative-tree/v1",exports.TOOL_EXEC_BASH_TASK_SCHEMA_ID="tool.exec_bash/v1",exports.TaskAction=fr,exports.TaskControlAction=dr,exports.TaskDataScope=gr,exports.TaskEventType=yr,exports.TaskExecutorKind=ar,exports.TaskGrantScope=pr,exports.TaskManagerClient=_r,exports.TaskOutcome=hr,exports.TaskPhase=cr,exports.TaskWaitReasonKind=ur,exports.VerifyHubClient=zn,exports.WEB3_BRIDGE_HOST="web3.buckyos.ai",exports.WORKFLOW_EXECUTE_RPC_TASK_SCHEMA_ID="workflow.execute_rpc/v1",exports.WORKFLOW_MAP_SHARD_TASK_SCHEMA_ID="workflow.map_shard/v1",exports.WORKFLOW_RUN_TARGET_TASK_SCHEMA_ID="workflow.run/v1",exports.WORKFLOW_RUN_TREE_TASK_SCHEMA_ID="workflow.run_tree/v1",exports.WORKFLOW_SCHEDULE_TASK_SCHEMA_ID="workflow.schedule/v1",exports.WORKFLOW_SEND_MESSAGE_TASK_SCHEMA_ID="workflow.send_message/v1",exports.WORKFLOW_SERVICE_NAME="workflow",exports.WORKFLOW_STEP_TASK_SCHEMA_ID="workflow.step/v1",exports.WORKFLOW_THUNK_TASK_SCHEMA_ID="workflow.thunk/v1",exports.WorkflowClient=Dr,exports.WorkflowDefinitionStatus=Tr,exports.WorkflowHumanActionKind=Or,exports.WorkflowJoinMode=kr,exports.WorkflowNodeRunState=Ir,exports.WorkflowOutputMode=Er,exports.WorkflowRetryFallback=Sr,exports.WorkflowRunStatus=Rr,exports.WorkflowScheduledTaskFireStatus=Nr,exports.WorkflowScheduledTaskMisfirePolicy=xr,exports.WorkflowScheduledTaskStatus=Cr,exports.WorkflowStepType=vr,exports.aiccMessageFirstText=function(t){var e;return null==(e=t.content.find((t=>"text"===t.type)))?void 0:e.text},exports.aiccMessageTextContent=function(t){return t.content.filter((t=>"text"===t.type)).map((t=>t.text)).join("\n")},exports.aiccTextMessage=function(t,e){return{role:t,content:[{type:"text",text:e}]}},exports.appDidFromId=function(t){return Mn.DID.fromStr(ks(t)).toString()},exports.appIdFromDid=Es,exports.baselineTaskControlProfile=function(t){return{pause:{kind:"Unavailable"},resume:{kind:"Unavailable"},cancel:{kind:"Interrupt"},updated_at:t}},exports.bns_client=Mo,exports.createAppInstanceId=Ts,exports.createSDKModule=function(t){const e=new Oi(t),n={initBuckyOS:e.initBuckyOS.bind(e),getBuckyOSConfig:e.getBuckyOSConfig.bind(e),getRuntimeType:e.getRuntimeType.bind(e),getAppId:e.getAppId.bind(e),getAppDid:e.getAppDid.bind(e),getAppInstanceId:e.getAppInstanceId.bind(e),getAppDataDir:e.getAppDataDir.bind(e),getKEventClient:e.getKEventClient.bind(e),createEventReader:e.createEventReader.bind(e),create_event_reader:e.create_event_reader.bind(e),subscribeKEvent:e.subscribeKEvent.bind(e),attachEvent:e.attachEvent.bind(e),removeEvent:e.removeEvent.bind(e),getAccountInfo:e.getAccountInfo.bind(e),loginByPassword:e.loginByPassword.bind(e),loginByBrowserSSO:e.loginByBrowserSSO.bind(e),loginByRuntimeSession:e.loginByRuntimeSession.bind(e),login:e.login.bind(e),logout:e.logout.bind(e),getAppSetting:e.getAppSetting.bind(e),setAppSetting:e.setAppSetting.bind(e),getCurrentWalletUser:e.getCurrentWalletUser.bind(e),resolve_did:e.resolve_did.bind(e),walletSignWithActiveDid:e.walletSignWithActiveDid.bind(e),openExternalUrl:e.openExternalUrl.bind(e),getZoneHostName:e.getZoneHostName.bind(e),getZoneServiceURL:e.getZoneServiceURL.bind(e),getServiceRpcClient:e.getServiceRpcClient.bind(e),getVerifyHubClient:e.getVerifyHubClient.bind(e),getSystemConfigClient:e.getSystemConfigClient.bind(e),getTaskManagerClient:e.getTaskManagerClient.bind(e),getWorkflowClient:e.getWorkflowClient.bind(e),getAiccClient:e.getAiccClient.bind(e),getMsgQueueClient:e.getMsgQueueClient.bind(e),getMsgCenterClient:e.getMsgCenterClient.bind(e),getRepoClient:e.getRepoClient.bind(e)};return{...n,buckyos:{kRPCClient:jn,AuthClient:Vn,...n,hashPassword:Mn.hashPassword}}},exports.decisionRequirements=ts,exports.decodeBnsPublishDocumentCalldata=function(t){return ob.decodeFunctionData("publishDocument",t)},exports.getActiveRuntimeType=Ti,exports.getActiveSessionToken=Ii,exports.getActiveZoneGatewayOrigin=Ri,exports.getCurrentWalletUserFromHost=wi,exports.isAiccAiMethod=function(t){return Hr.has(t)},exports.isTerminalTaskPhase=lr,exports.mailboxAddress=function(t,e){if(!/^did:[^:]+:.+$/.test(t)||/[\s\x00-\x1f\x7f-\x9f/\\?#*|]/.test(t))throw new Fn("mailbox owner must be a bare DID");if(void 0===e)return t;if(!e||e.trim()!==e||[...e].length>200||"."===e||".."===e||/[\x00-\x1f\x7f-\x9f]/.test(e))throw new Fn("invalid mailbox session_id");return`${t}/${encodeURIComponent(e).replace(/[!'()*]/g,(t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`)).replace(/%3A/g,":").replace(/%40/g,"@")}`},exports.mailboxResource=function(t,e){const n=encodeURIComponent(t).replace(/[!'()*.]/g,(t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`)).replace(/%3A/g,":").replace(/%40/g,"@").replace(/%2F/g,"/");return`obj://msg-center/${e.toLowerCase()}/${n}`},exports.ndm_client=t_,exports.ndm_proxy=Q_,exports.parseAppId=ks,exports.parseAppInstanceId=Rs,exports.parseSessionTokenClaims=Hs,exports.resolveDidFromHost=bi,exports.sn_client=SA,exports.taskMgrErrorCode=or,exports.taskMgrTaskEventPath=function(t){return`/task_mgr/${t}`},exports.taskMgrTreeEventPath=function(t){return`/task_mgr/tree/${t}`},exports.validateAiccMessage=Vr,exports.validateDecisionAnswers=ns,exports.validateDecisionRequest=es,exports.walletUserHasSnAccount=yb;
13
+ //# sourceMappingURL=ndm_proxy-b5bcc7f0.js.map