buckyos 0.7.140 → 0.7.142
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli/core/auth.ts +2 -3
- package/cli/dist/cli.mjs +3 -4
- package/cli/dist/cli.mjs.map +1 -1
- package/cli/version.ts +1 -1
- package/dist/account.d.ts +0 -2
- package/dist/account.d.ts.map +1 -1
- package/dist/browser.cjs +1 -1
- package/dist/browser.mjs +14 -15
- package/dist/{executor_client-978a8e1b.js → executor_client-b3ff97ba.js} +8 -8
- package/dist/executor_client-b3ff97ba.js.map +1 -0
- package/dist/{executor_client-d2c9e854.mjs → executor_client-eb372968.mjs} +56 -152
- package/dist/executor_client-eb372968.mjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +14 -15
- package/dist/namelib.d.ts +1 -10
- package/dist/namelib.d.ts.map +1 -1
- package/dist/ndn_types-08dc9ef1.js +2 -0
- package/dist/ndn_types-08dc9ef1.js.map +1 -0
- package/dist/{ndn_types-dcb74613.mjs → ndn_types-bbb1f6a6.mjs} +54 -101
- package/dist/ndn_types-bbb1f6a6.mjs.map +1 -0
- package/dist/node.cjs +1 -1
- package/dist/node.mjs +14 -15
- package/dist/provision.cjs +2 -2
- package/dist/provision.cjs.map +1 -1
- package/dist/provision.mjs +18 -12
- package/dist/provision.mjs.map +1 -1
- package/dist/provision_activate.d.ts.map +1 -1
- package/dist/runtime.d.ts +1 -4
- package/dist/runtime.d.ts.map +1 -1
- package/dist/sdk_core.d.ts.map +1 -1
- package/dist/{tus_client-a2f73d53.js → tus_client-65c5fc5e.js} +2 -2
- package/dist/{tus_client-a2f73d53.js.map → tus_client-65c5fc5e.js.map} +1 -1
- package/dist/{tus_client-8fd4d937.mjs → tus_client-d313689e.mjs} +2 -2
- package/dist/{tus_client-8fd4d937.mjs.map → tus_client-d313689e.mjs.map} +1 -1
- package/dist/types.d.ts +0 -9
- package/dist/types.d.ts.map +1 -1
- package/dist/verify-hub-client.d.ts +1 -9
- package/dist/verify-hub-client.d.ts.map +1 -1
- package/package.json +1 -1
- package/dist/executor_client-978a8e1b.js.map +0 -1
- package/dist/executor_client-d2c9e854.mjs.map +0 -1
- package/dist/ndn_types-324121ae.js +0 -2
- package/dist/ndn_types-324121ae.js.map +0 -1
- package/dist/ndn_types-dcb74613.mjs.map +0 -1
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
"use strict";var e,t,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,C,O,x,N,P,D,B,U,L,M,F,j,G,H,V,q,W,z,K,$,Q,J,Y,Z,X,ee,te,ne,re,se,ie,oe,ae,ce,le,ue,he,de,fe,pe,ge,me,ye,we,be,_e,Ae,ve,Ee,ke,Se,Te,Re,Ie,Ce,Oe,xe,Ne,Pe,De,Be,Ue,Le,Me,Fe,je,Ge,He,Ve,qe,We,ze,Ke,$e,Qe,Je,Ye,Ze,Xe,et,tt,nt,rt,st,it,ot,at,ct,lt,ut,ht,dt,ft,pt,gt,mt,yt,wt,bt,_t,At,vt,Et,kt,St,Tt,Rt,It,Ct,Ot,xt,Nt,Pt,Dt,Bt,Ut,Lt,Mt,Ft,jt,Gt,Ht,Vt,qt,Wt,zt,Kt,$t,Qt,Jt,Yt,Zt,Xt,en,tn,nn,rn,sn,on,an,cn,ln,un,hn,dn,fn,pn,gn,mn,yn,wn,bn,_n,An,vn,En,kn,Sn,Tn,Rn,In,Cn,On=Object.defineProperty,xn=(e,t,n)=>(((e,t,n)=>{t in e?On(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n})(e,"symbol"!=typeof t?t+"":t,n),n),Nn=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Pn=(e,t,n)=>(Nn(e,t,"read from private field"),n?n.call(e):t.get(e)),Dn=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},Bn=(e,t,n,r)=>(Nn(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),Un=(e,t,n,r)=>({set _(r){Bn(e,t,r,n)},get _(){return Pn(e,t,r)}}),Ln=(e,t,n)=>(Nn(e,t,"access private method"),n);const Mn=require("./ndn_types-324121ae.js");class Fn extends Error{constructor(e,t,n){super(e),this.name="RPCError",this.code=t,this.data=n}}const jn=async(e,t)=>{if("undefined"!=typeof window&&"function"==typeof window.fetch)return window.fetch(e,t);if("undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch)return globalThis.fetch(e,t);throw new Fn("fetch is not available in this runtime")};class Gn{constructor(e,t=null,n=null,r={}){this.serverUrl=e,this.protocolType="HttpPostJson",this.seq=n??Date.now(),this.sessionToken=t||null,this.initToken=t||null,this.traceId=r.traceId||null,this.fetcher=r.fetcher??jn,this.sessionTokenProvider=r.sessionTokenProvider??null,this.sessionTokenOverride=void 0}async call(e,t,n={}){return this._call(e,t,n)}async callWithSessionToken(e,t,n){return this._call(t,n,{sessionToken:e})}setSeq(e){this.seq=e}resetSessionToken(){this.sessionToken=this.initToken,this.sessionTokenOverride=void 0}setSessionToken(e){this.sessionToken=e||null,this.sessionTokenOverride=e||null}getSessionToken(){return this.sessionToken}setTraceId(e){this.traceId=e||null}getTraceId(){return this.traceId}buildRequest(e,t,n,r,s){let i;return i=s?[n,r,s]:r?[n,r]:[n],{method:e,params:t,sys:i}}parseResponseSys(e,t){if(null==e)return null;if(!Array.isArray(e))throw new Fn("sys is not array");if(e.length<1)throw new Fn("sys is empty");const n=e[0];if("number"!=typeof n)throw new Fn("sys[0] is not number");if(n!==t)throw new Fn(`seq not match: ${n}!=${t}`);if(e.length>=2){const t=e[1];if("string"!=typeof t)throw new Fn("sys[1] trace_id is not string");return t}return null}async prepareSessionToken(e){if(Object.prototype.hasOwnProperty.call(e,"sessionToken"))return e.sessionToken||null;if(void 0!==this.sessionTokenOverride)return this.sessionTokenOverride;if(this.sessionTokenProvider){const e=await this.sessionTokenProvider();void 0!==e&&(this.sessionToken=e||null)}return this.sessionToken}prepareTraceId(e){return Object.prototype.hasOwnProperty.call(e,"traceId")?e.traceId||null:this.traceId}async _call(e,t,n){const r=await this.prepareSessionToken(n),s=this.prepareTraceId(n),i=this.seq;this.seq+=1;const o=this.buildRequest(e,t,i,r,s);try{const e=await this.fetcher(this.serverUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!e.ok)throw new Fn(`RPC call error: ${e.status}`);const t=await e.json();if(this.parseResponseSys(t.sys,i),"error"in t&&t.error)throw new Fn(`RPC call error: ${t.error}`,"string"==typeof t.code?t.code:void 0,t.data);if(!("result"in t)||void 0===t.result)throw new Fn("RPC response missing result");return t.result}catch(a){if(a instanceof Fn)throw a;const e=a instanceof Error?a.message:String(a);throw new Fn(`RPC call failed: ${e}`)}}}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(e,t={}){Hn(),this.zoneHostname=e,this.navigate=t.navigate??(e=>{window.location.assign(e)})}buildLoginURL(e=null){Hn();const t=e??window.location.href;return`${`${window.location.protocol}//sys.${this.zoneHostname}/login`}?redirect_url=${encodeURIComponent(t)}`}async login(e=null){const t=this.buildLoginURL(e);this.navigate(t)}}const qn=["session_kind_not_allowed","session_ceiling_exceeded","resource_grant_missing","entry_unavailable","zone_method_disabled","account_state","credential_state","source_revoked","authorization_unavailable"],Wn="access_denied";function zn(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function Kn(e){if(!zn(e)||"string"!=typeof e.reason)return null;if(!qn.includes(e.reason))return null;return(zn(e.adjust)&&"string"==typeof e.adjust.party?e.adjust:null)?e:null}const $n={kind:"anonymous"};function Qn(e){if(!zn(e))return null;if("anonymous"===e.kind)return $n;const t=t=>"string"==typeof e[t]?e[t]:null;if("account"===e.kind){const n=t("user_id"),r=t("did"),s=t("user_type");return n&&r&&s&&"boolean"==typeof e.restricted?e:null}return"external"===e.kind&&t("did")&&"boolean"==typeof e.restricted?e:null}function Jn(e){switch(e.kind){case"account":return`${e.zone_host}|account|${e.user_id}`;case"external":return`${e.zone_host}|external|${e.did}`;default:return"anonymous"}}const Yn="https://jump.buckyos.org",Zn={app_installer:"/sysdlg/app_installer"};function Xn(e){const t=e.trim().toLowerCase().replace(/\.$/,"");if(!t||t.length>253)return null;if(/[^a-z0-9.-]/.test(t))return null;const n=t.split(".");if(n.length<2)return null;for(const r of n)if(!r||r.length>63||r.startsWith("-")||r.endsWith("-"))return null;return t}const er="aiworkspace";class tr extends Error{constructor(e){super(`${e.code}${e.sub_code?`/${e.sub_code}`:""}: ${e.detail}`),this.name="AiwsFailure",this.code=e.code,this.subCode=e.sub_code,this.data=e.data}}class nr{constructor(e){this.rpcClient=e}async call(e,t){const n=await this.rpcClient.call(e,t);if(n&&"object"==typeof n&&!1===n.ok)throw new tr(n.error);return n}list(){return this.call("ws.list",{})}info(e){return this.call("ws.get_info",{workspace_id:e})}getUserState(e){return this.call("ws.get_user_state",{workspace_id:e})}setUserState(e,t,n){return this.call("ws.set_user_state",{workspace_id:e,entries:t,...n?{expect:n}:{}})}resolve(e,t){return this.call("doc.resolve",{workspace_id:e,reference:t})}resolvePath(e,t){return this.call("doc.resolve",{workspace_id:e,path:t})}read(e,t,n){return this.call("doc.read",{workspace_id:e,entity_id:t,...n?{selector:n}:{}})}query(e,t){return this.call("doc.query",{workspace_id:e,...t})}outline(e){return this.call("doc.outline",{workspace_id:e})}prepare(e,t){return this.rpcClient.call("doc.prepare",{workspace_id:e,...t})}commit(e,t){return this.rpcClient.call("doc.commit",{workspace_id:e,...t})}getSubmission(e,t,n){return this.call("doc.get_submission",{workspace_id:e,epoch:t,idempotency_key:n})}runStart(e,t,n,r){return this.call("proc.start",{workspace_id:e,program:t,params:n,idempotency_key:r})}runGet(e,t,n){return this.call("proc.get",{workspace_id:e,run_id:t,...n?{choices:n}:{}})}runList(e,t,n){return this.call("proc.list",{workspace_id:e,...t?{wish_id:t}:{},...n?{limit:n}:{}})}runClaim(e,t,n,r){return this.call("proc.claim",{workspace_id:e,run_id:t,claim_token:n,...r?{executor:r}:{}})}runHeartbeat(e,t,n,r){return this.call("proc.heartbeat",{workspace_id:e,run_id:t,attempt:n,...r?{progress:r}:{}})}runReport(e,t){return this.call("proc.report",{workspace_id:e,...t})}runApply(e,t,n,r){return this.call("proc.apply",{workspace_id:e,run_id:t,plan_digest:n,...r?{session_id:r}:{}})}runCancel(e,t){return this.call("proc.cancel",{workspace_id:e,run_id:t})}}function rr(e){if(!e||"object"!=typeof e)throw new Fn("verify-hub auth target is required");if("app"===e.kind&&"string"==typeof e.app_instance_id&&e.app_instance_id.length>0)return{kind:"app",app_instance_id:e.app_instance_id};if("system"===e.kind&&"string"==typeof e.service_id&&e.service_id.length>0)return{kind:"system",service_id:e.service_id};throw new Fn("invalid verify-hub auth target")}function sr(e){const t=rr(e);if("system"===t.kind)return t.service_id;const n=t.app_instance_id.lastIndexOf("@");if(n<=0||n===t.app_instance_id.length-1)throw new Fn("app auth target must use `<appId>@<ownerUserId>`");return t.app_instance_id.slice(0,n)}class ir{constructor(e){this.rpcClient=e}setSeq(e){this.rpcClient.setSeq(e)}async loginByJwt(e){return this.rpcClient.resetSessionToken(),this.rpcClient.call("login_by_jwt",{type:"jwt",jwt:e.jwt,target:rr(e.target)})}async loginByPassword(e){this.rpcClient.resetSessionToken();const t={type:"password",username:e.username,password:e.password,target:rr(e.target)};return void 0!==e.login_nonce&&(t.login_nonce=e.login_nonce),e.source_url&&(t.source_url=e.source_url),this.rpcClient.call("login_by_password",t)}async sudoByPassword(e){this.rpcClient.resetSessionToken();const t={username:e.username,password:e.password,target:rr(e.target)};return void 0!==e.aud&&(t.aud=e.aud),void 0!==e.login_nonce&&(t.login_nonce=e.login_nonce),this.rpcClient.call("sudo_by_password",t)}async refreshToken(e){return this.rpcClient.call("refresh_token",{refresh_token:e.refresh_token})}async verifyToken(e){const t={session_token:e.session_token};return void 0!==e.expected_target&&(t.expected_target=rr(e.expected_target)),this.rpcClient.call("verify_token",t)}static normalizeLoginResponse(e){if("user_info"in e)return{user_name:e.user_info.show_name,user_id:e.user_info.user_id,user_type:e.user_info.user_type,session_token:e.session_token,refresh_token:e.refresh_token};if(!e.session_token)throw new Fn("login_by_password response missing session_token");return e}}const or="task_not_found",ar="permission_denied",cr="revision_conflict",lr="stale_runner_epoch",ur="invalid_task_phase",hr="control_not_available",dr="control_already_pending",fr="task_already_completed",pr="input_schema_mismatch",gr="result_schema_mismatch",mr="idempotency_conflict",yr="task_schema_not_found",wr=[or,ar,cr,lr,ur,hr,dr,fr,pr,gr,mr,yr];function br(e){return`/task_mgr/${e}`}function _r(e){const t=e instanceof Error?e.message:String(e);for(const n of wr){const e=t.indexOf(n);if(e<0)continue;const r=0===e?"":t[e-1],s=t[e+n.length]??"";if((!r||/[\s:]/.test(r))&&(!s||/[\s:]/.test(s)))return n}return null}var Ar=(e=>(e.Unbound="Unbound",e.App="App",e.HumanSet="HumanSet",e))(Ar||{}),vr=(e=>(e.Promised="Promised",e.Accepted="Accepted",e.Running="Running",e.Waiting="Waiting",e.Paused="Paused",e.Terminal="Terminal",e))(vr||{});function Er(e){return"Terminal"===e}var kr=(e=>(e.Dispatch="Dispatch",e.Capacity="Capacity",e.Authorization="Authorization",e.HumanInput="HumanInput",e.ChildTask="ChildTask",e.Dependency="Dependency",e.External="External",e.Other="Other",e))(kr||{}),Sr=(e=>(e.Succeeded="Succeeded",e.Failed="Failed",e.Canceled="Canceled",e))(Sr||{}),Tr=(e=>(e.Pause="Pause",e.Resume="Resume",e.Cancel="Cancel",e))(Tr||{});var Rr=(e=>(e.ReadMeta="ReadMeta",e.ReadInput="ReadInput",e.ReadResult="ReadResult",e.ReportProgress="ReportProgress",e.Control="Control",e.Commit="Commit",e.CreateChild="CreateChild",e.Reassign="Reassign",e.Grant="Grant",e.Archive="Archive",e))(Rr||{}),Ir=(e=>(e.SelfOnly="SelfOnly",e.Subtree="Subtree",e.WholeTree="WholeTree",e))(Ir||{}),Cr=(e=>(e.MetaOnly="MetaOnly",e.Payload="Payload",e.Full="Full",e))(Cr||{}),Or=(e=>(e.User="User",e.System="System",e))(Or||{}),xr=(e=>(e.TaskCreated="TaskCreated",e.RunnerBound="RunnerBound",e.RunnerReleased="RunnerReleased",e.PhaseChanged="PhaseChanged",e.WaitReasonChanged="WaitReasonChanged",e.ProgressReported="ProgressReported",e.ControlProfileChanged="ControlProfileChanged",e.ControlRequested="ControlRequested",e.ControlSuperseded="ControlSuperseded",e.ControlApplied="ControlApplied",e.ControlRejected="ControlRejected",e.AssigneesChanged="AssigneesChanged",e.AccessGranted="AccessGranted",e.AccessRevoked="AccessRevoked",e.ResultCommitted="ResultCommitted",e.TaskFailed="TaskFailed",e.TaskCanceled="TaskCanceled",e.TaskArchived="TaskArchived",e.PayloadRedacted="PayloadRedacted",e))(xr||{});function Nr(e,t,n){const r=function(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw new Fn(`Expected ${t} in TaskMgr response`);return e}(e,n);if(!(t in r))throw new Fn(`Expected ${t} in TaskMgr response`);return r[t]}function Pr(e){const t=Nr(e,"task","task result");if(!t||"object"!=typeof t||"string"!=typeof t.task_id)throw new Fn("Expected a string task_id in TaskMgr response");return t}function Dr(){const e=globalThis.crypto;if(e&&"function"==typeof e.getRandomValues){const t=new Uint8Array(16);return e.getRandomValues(t),`ctl-${Array.from(t,(e=>e.toString(16).padStart(2,"0"))).join("")}`}return`ctl-${Date.now().toString(16)}${Math.random().toString(16).slice(2)}`}class Br{constructor(e){this.rpcClient=e}setSeq(e){this.rpcClient.setSeq(e)}async callTask(e,t){return Pr(await this.rpcClient.call(e,t))}async createTask(e){return this.callTask("create_task",e)}async getTask(e){return Pr(await this.rpcClient.call("get_task",{task_id:e}))}async listTasks(e={}){const t=await this.rpcClient.call("list_tasks",e),n=Nr(t,"tasks","task summary page");if(!Array.isArray(n))throw new Fn("Expected tasks array in TaskMgr response");return t}async getTaskTree(e){const t=await this.rpcClient.call("get_task_tree",e),n=Nr(t,"tasks","task tree page");if(!Array.isArray(n))throw new Fn("Expected tasks array in TaskMgr response");return t}async getSubtasks(e){const t=await this.rpcClient.call("get_subtasks",e),n=Nr(t,"tasks","subtask page");if(!Array.isArray(n))throw new Fn("Expected tasks array in TaskMgr response");return t}async archiveTask(e){return this.callTask("archive_task",e)}async requestControl(e){const t=await this.rpcClient.call("request_control",e),n=Nr(t,"kind","control result");if("Task"!==n&&"Batch"!==n)throw new Fn(`Invalid TaskMgr control result kind: ${n}`);return t}async updateAssignees(e){return this.callTask("update_assignees",e)}async grantTaskAccess(e){return this.callTask("grant_task_access",e)}async revokeTaskAccess(e){return this.callTask("revoke_task_access",e)}async listTaskAccess(e){const t=Nr(await this.rpcClient.call("list_task_access",{task_id:e}),"grants","task access result");if(!Array.isArray(t))throw new Fn("Expected grants array in TaskMgr response");return t}async reportStarted(e){return this.callTask("report_started",e)}async reportProgress(e){return this.callTask("report_progress",e)}async reportWaiting(e){return this.callTask("report_waiting",e)}async reportRunning(e){return this.callTask("report_running",e)}async updateControlProfile(e){return this.callTask("update_control_profile",e)}async ackControl(e){return this.callTask("ack_control",e)}async commitResult(e){return this.callTask("commit_result",e)}async failTask(e){return this.callTask("fail_task",e)}async createPromisedTask(e){return this.callTask("create_promised_task",e)}async setPromiseWait(e){return this.callTask("set_promise_wait",e)}async bindAppExecutor(e){return this.callTask("bind_app_executor",e)}async releaseAppExecutor(e){return this.callTask("release_app_executor",e)}async finishPromiseFailure(e){return this.callTask("finish_promise_failure",e)}async cancelPromisedTask(e){return this.callTask("cancel_promised_task",e)}async registerTaskSchema(e){return this.rpcClient.call("register_task_schema",{definition:e})}async getTaskSchema(e,t){return this.rpcClient.call("get_task_schema",{schema_id:e,schema_version:t})}async listTaskSchemas(e={}){const t=Nr(await this.rpcClient.call("list_task_schemas",e),"schemas","task schema list");if(!Array.isArray(t))throw new Fn("Expected schemas array in TaskMgr response");return t}async setTaskSchemaEnabled(e,t,n){return this.rpcClient.call("set_task_schema_enabled",{schema_id:e,schema_version:t,enabled:n})}async listTaskEvents(e){const t=await this.rpcClient.call("list_task_events",e),n=Nr(t,"events","task event list");if(!Array.isArray(n))throw new Fn("Expected events array in TaskMgr response");return t}async addTaskNote(e){return Nr(await this.rpcClient.call("add_task_note",e),"note","add task note result")}async listTaskNotes(e){const t=Nr(await this.rpcClient.call("list_task_notes",{task_id:e}),"notes","task note list");if(!Array.isArray(t))throw new Fn("Expected notes array in TaskMgr response");return t}async cancelTask(e,t=!1){return this.requestControl({task_id:e,action:"Cancel",request_id:Dr(),recursive:t})}snapshotEnvelope(e){return{task_id:e.task_id,app_instance_id:"App"===e.executor.kind?e.executor.app_instance_id:void 0,runner_epoch:e.runner_epoch,expected_revision:e.revision}}async runnerStart(e){const t=await this.getTask(e);let n;if("Accepted"===t.phase)n=this.reportStarted(this.snapshotEnvelope(t));else{if("Waiting"!==t.phase)return t;n=this.reportRunning(this.snapshotEnvelope(t))}try{return await n}catch(r){const t=_r(r);if(t===cr||t===ur)return this.getTask(e);throw r}}async runnerProgress(e,t,n){const r=await this.getTask(e);if(Er(r.phase))return r;try{return await this.reportProgress({...this.snapshotEnvelope(r),progress:t,message:n})}catch(s){if(_r(s)!==cr)throw s;const r=await this.getTask(e);return this.reportProgress({...this.snapshotEnvelope(r),progress:t,message:n})}}async runnerWait(e,t){const n=await this.runnerStart(e);return"Running"!==n.phase?n:this.reportWaiting({...this.snapshotEnvelope(n),reason:t})}async runnerComplete(e,t){const n=await this.getTask(e);if(Er(n.phase))return n;try{return await this.commitResult({task_id:n.task_id,result:t,app_instance_id:this.snapshotEnvelope(n).app_instance_id,runner_epoch:n.runner_epoch,expected_revision:n.revision})}catch(r){if(_r(r)!==cr)throw r;const n=await this.getTask(e);return Er(n.phase)?n:this.commitResult({task_id:n.task_id,result:t,app_instance_id:this.snapshotEnvelope(n).app_instance_id,runner_epoch:n.runner_epoch,expected_revision:n.revision})}}async runnerFail(e,t,n,r){const s=await this.getTask(e);return Er(s.phase)?s:this.failTask({...this.snapshotEnvelope(s),error:{code:t,message:n,detail:r}})}}var Ur=(e=>(e.Autonomous="autonomous",e.HumanConfirm="human_confirm",e.HumanRequired="human_required",e))(Ur||{}),Lr=(e=>(e.Single="single",e.FiniteSeekable="finite_seekable",e.FiniteSequential="finite_sequential",e))(Lr||{}),Mr=(e=>(e.All="all",e.Any="any",e.NOfM="n_of_m",e))(Mr||{}),Fr=(e=>(e.Human="human",e.Abort="abort",e))(Fr||{}),jr=(e=>(e.Draft="draft",e.Active="active",e.Archived="archived",e))(jr||{}),Gr=(e=>(e.Created="created",e.Running="running",e.WaitingHuman="waiting_human",e.Completed="completed",e.Failed="failed",e.Paused="paused",e.Aborted="aborted",e.BudgetExhausted="budget_exhausted",e))(Gr||{}),Hr=(e=>(e.Pending="pending",e.Ready="ready",e.Running="running",e.Completed="completed",e.Failed="failed",e.Retrying="retrying",e.WaitingHuman="waiting_human",e.Skipped="skipped",e.Aborted="aborted",e.Cancelled="cancelled",e))(Hr||{}),Vr=(e=>(e.Approve="approve",e.Modify="modify",e.Reject="reject",e.Retry="retry",e.Skip="skip",e.Abort="abort",e.Rollback="rollback",e))(Vr||{}),qr=(e=>(e.Enabled="enabled",e.Paused="paused",e.Archived="archived",e.Error="error",e))(qr||{}),Wr=(e=>(e.Skip="skip",e.RunOnce="run_once",e.CatchUp="catch_up",e.Manual="manual",e))(Wr||{}),zr=(e=>(e.Created="created",e.TaskCreated="task_created",e.Skipped="skipped",e.Failed="failed",e))(zr||{});function Kr(e,t){if(!(t in e))throw new Fn(`Expected ${t} in workflow response`);return e[t]}class $r{constructor(e){this.rpcClient=e}setSeq(e){this.rpcClient.setSeq(e)}async callOk(e,t){const n=function(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new Fn("Invalid workflow RPC response format");return e}(await this.rpcClient.call(e,t));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(e){const t=await this.callOk("submit_definition",e);return{workflow_id:Kr(t,"workflow_id"),version:Kr(t,"version"),analysis:Kr(t,"analysis"),definition:Kr(t,"definition")}}async getDefinition(e){return Kr(await this.callOk("get_definition",{workflow_id:e}),"definition")}async listDefinitions(e={}){return Kr(await this.callOk("list_definitions",e),"definitions")}async archiveDefinition(e){return Kr(await this.callOk("archive_definition",{workflow_id:e}),"status")}async dryRun(e){const t=await this.callOk("dry_run",{definition:e});return{analysis:Kr(t,"analysis"),graph:Kr(t,"graph")}}async createRun(e){return await this.callOk("create_run",e)}async startRun(e){return await this.callOk("start_run",{run_id:e})}async tickRun(e){return await this.callOk("tick_run",{run_id:e})}async getRunGraph(e){return await this.callOk("get_run_graph",{run_id:e})}async listRuns(e={}){return Kr(await this.callOk("list_runs",e),"runs")}async submitStepOutput(e){return await this.callOk("submit_step_output",e)}async reportStepProgress(e){return await this.callOk("report_step_progress",e)}async requestHuman(e){return await this.callOk("request_human",e)}async submitAmendment(e){return Kr(await this.callOk("submit_amendment",e),"amendment")}async approveAmendment(e){const t=await this.callOk("approve_amendment",e);return{amendment:Kr(t,"amendment"),plan_version:Kr(t,"plan_version")}}async rejectAmendment(e){const t=await this.callOk("reject_amendment",e);return{amendment:Kr(t,"amendment"),plan_version:Kr(t,"plan_version")}}async getHistory(e){return await this.callOk("get_history",e)}async subscribeEvents(e){return await this.callOk("subscribe_events",e)}async createScheduledTask(e){return Kr(await this.callOk("create_scheduled_task",e),"schedule")}async updateScheduledTask(e){return Kr(await this.callOk("update_scheduled_task",e),"schedule")}async getScheduledTask(e){return Kr(await this.callOk("get_scheduled_task",{schedule_id:e}),"schedule")}async listScheduledTasks(e={}){return Kr(await this.callOk("list_scheduled_tasks",e),"schedules")}async pauseScheduledTask(e){return Kr(await this.callOk("pause_scheduled_task",{schedule_id:e}),"schedule")}async resumeScheduledTask(e){return Kr(await this.callOk("resume_scheduled_task",{schedule_id:e}),"schedule")}async archiveScheduledTask(e){return Kr(await this.callOk("archive_scheduled_task",{schedule_id:e}),"schedule")}async runScheduledTaskNow(e){return Kr(await this.callOk("run_scheduled_task_now",e),"fire")}async getScheduledTaskHistory(e){return Kr(await this.callOk("get_scheduled_task_history",e),"fires")}async validateScheduledTask(e){return await this.callOk("validate_scheduled_task",e)}}const Qr=["services/","system/rbac/"];class Jr{constructor(e,t=null,n={}){this.configCache=new Map,this.rpcClient=new Gn(e,t,null,n)}setSeq(e){this.rpcClient.setSeq(e)}async syncSessionToken(e){this.rpcClient.setSessionToken(e)}getSessionToken(){return this.rpcClient.getSessionToken()}needCache(e){return Qr.some((t=>e.startsWith(t)))}getUnixTimestamp(){return Math.floor(Date.now()/1e3)}getConfigCache(e){const t=this.configCache.get(e);return t?t.cachedAt+10<this.getUnixTimestamp()?(this.configCache.delete(e),null):t:null}setConfigCache(e,t,n){if(!this.needCache(e))return!0;const r=this.configCache.get(e);return this.configCache.set(e,{value:t,version:n,cachedAt:this.getUnixTimestamp()}),!r||(r.value!==t||r.version!==n)}removeConfigCache(e){this.configCache.delete(e)}async get(e){const t=this.getConfigCache(e);if(null!=t)return{value:t.value,version:t.version,is_changed:!1};const n=await this.rpcClient.call("sys_config_get",{key:e});if(null==n)throw new Error(`system_config key not found: ${e}`);if("string"!=typeof n.value||"number"!=typeof n.version)throw new Error(`invalid sys_config_get response for key: ${e}`);const r=this.setConfigCache(e,n.value,n.version);return{value:n.value,version:n.version,is_changed:r}}async set(e,t){if(!e||!t)throw new Error("key or value is empty");if(e.includes(":"))throw new Error("key can not contain ':'");return await this.rpcClient.call("sys_config_set",{key:e,value:t}),this.removeConfigCache(e),0}async setByJsonPath(e,t,n){return await this.rpcClient.call("sys_config_set_by_json_path",{key:e,json_path:t,value:n}),this.removeConfigCache(e),0}async create(e,t){return await this.rpcClient.call("sys_config_create",{key:e,value:t}),this.removeConfigCache(e),0}async delete(e){return await this.rpcClient.call("sys_config_delete",{key:e}),this.removeConfigCache(e),0}async append(e,t){return await this.rpcClient.call("sys_config_append",{key:e,append_value:t}),this.removeConfigCache(e),0}async list(e){return this.rpcClient.call("sys_config_list",{key:e})}async execTx(e,t){const n={actions:e};t&&(n.main_key=`${t[0]}:${t[1]}`),await this.rpcClient.call("sys_config_exec_tx",n);for(const r of Object.keys(e))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 Yr={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_GENERATE:"video.generate",VIDEO_EDIT:"video.edit",VIDEO_EXTEND:"video.extend",VIDEO_UPSCALE:"video.upscale",AGENT_COMPUTER_USE:"agent.computer_use"},Zr={ROUTE_RESOLVE:"route.resolve",HELPER_LLM_CHAT:"helper.llm_chat",HELPER_TEXT_TO_IMAGE:"helper.text_to_image",HELPER_VIDEO_GENERATE:"helper.video_generate",CANCEL:"cancel"},Xr={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"},es={RULE_LIST:"quota.rule.list",RULE_GET:"quota.rule.get",RULE_PREVIEW:"quota.rule.preview",RULE_CREATE:"quota.rule.create",RULE_UPDATE:"quota.rule.update",RULE_DELETE:"quota.rule.delete",ACCOUNT_GET:"quota.account.get",ACCOUNT_RECHARGE:"quota.account.recharge",RECHARGE_GET:"quota.recharge.get",VISIBILITY_GET:"visibility.get",VISIBILITY_UPDATE:"visibility.update",VISIBILITY_PREVIEW:"visibility.preview"},ts={...Yr,...Zr,...Xr,...es},ns={IMMEDIATE:"immediate",STREAM:"stream"},rs=["quota_exhausted","quota_budget_exceeded","quota_unavailable","resource_not_permitted","attribution_unavailable"];const ss=new Set(Object.values(Yr));function is(e){const t={system:["text"],developer:["text"],user:["text","image","document"],assistant:["text","image","document","tool_use","thinking","provider_state"],tool:["tool_result"]};if(!e||!Array.isArray(e.content)||!t[e.role])throw new Fn("invalid AiMessage");if("tool"===e.role&&(1!==e.content.length||"tool_result"!==e.content[0].type))throw new Fn("role Tool requires exactly one ToolResult block");for(const n of e.content){if(!t[e.role].includes(n.type))throw new Fn(`AiMessage role ${e.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 os(e){if(!e||2!==e.split("@").length||e.startsWith("@")||e.endsWith("@"))throw new Fn("exact_model must be `<provider_model_id>[:<variant>]@<provider_instance_name>`")}function as(e){if(!(null==e?void 0:e.trim())||e.includes("@"))throw new Fn("logical_model must be a non-empty logical path without `@`")}function cs(e,t){for(const s of Object.keys(e))if(!t.includes(s))throw new Fn(`unknown field \`${s}\``);const n=e.execution_mode;if(void 0!==n&&n!==ns.IMMEDIATE&&n!==ns.STREAM)throw new Fn("execution_mode must be `immediate` or `stream`");const r=e.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 ls=["exact_model","trace_id","execution_mode","idempotency_key","task_options","session_id"],us={[Yr.CHAT_COMPLETIONS_CREATE]:[...ls,"web_search","messages","tools","response_format","temperature","top_p","max_output_tokens","seed","stop","output"],[Yr.IMAGES_GENERATE]:[...ls,"prompt","negative_prompt","n","aspect_ratio","size","quality","style","seed","output"],[Yr.EMBEDDING_TEXT]:[...ls,"items","chunking","embedding_space_id","dimensions","normalize","prefer_artifact"],[Yr.EMBEDDING_MULTIMODAL]:[...ls,"items","dimensions","normalize"],[Yr.DECISION_EVALUATE]:[...ls,"state","questions"],[Yr.RERANK]:[...ls,"query","documents","n","return_documents"],[Yr.IMAGE_IMG2IMG]:[...ls,"images","prompt","strength","output"],[Yr.IMAGE_INPAINT]:[...ls,"image","mask","prompt","mask_semantics","output"],[Yr.IMAGE_UPSCALE]:[...ls,"image","scale","target_width","target_height","preserve_faces","output"],[Yr.IMAGE_BG_REMOVE]:[...ls,"image","mode","output"],[Yr.VISION_OCR]:[...ls,"document","level","language_hints","return_layout","return_artifacts"],[Yr.VISION_CAPTION]:[...ls,"image","style","language","n"],[Yr.VISION_DETECT]:[...ls,"image","classes","score_threshold","bbox_spec"],[Yr.VISION_SEGMENT]:[...ls,"image","prompt","mask_format","return_bitmap_mask"],[Yr.AUDIO_TTS]:[...ls,"text","voice","speed","output"],[Yr.AUDIO_ASR]:[...ls,"audio","language","timestamps","diarization","output_formats"],[Yr.AUDIO_MUSIC]:[...ls,"prompt","duration_seconds","instrumental","lyrics","seed","output"],[Yr.AUDIO_ENHANCE]:[...ls,"audio","task","strength","return_stems"],[Yr.VIDEO_GENERATE]:[...ls,"prompt","negative_prompt","conditions","output","seed"],[Yr.VIDEO_EDIT]:[...ls,"video","prompt","output"],[Yr.VIDEO_EXTEND]:[...ls,"video","prompt","continuation_handle","duration_seconds","resolution"],[Yr.VIDEO_UPSCALE]:[...ls,"video","target_resolution","denoise","sharpen","output"],[Yr.AGENT_COMPUTER_USE]:[...ls,"task","environment","allowed_actions"],[Zr.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"],[Zr.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"],[Zr.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"],[Zr.HELPER_VIDEO_GENERATE]:["logical_model","trace_id","execution_mode","requirements","disable","policy","prompt","negative_prompt","conditions","output","seed","idempotency_key","task_options","session_overlay","session_id"],[Zr.CANCEL]:["task_id"],[Xr.SERVICE_RELOAD_SETTINGS]:[],[Xr.QUOTA_QUERY]:["app_id"],[Xr.USAGE_QUERY]:["time_range","filters","group_by","time_bucket","output_mode","limit","cursor","zone_wide"],[Xr.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"],[Xr.ROUTING_GET]:[],[Xr.ROUTING_PREVIEW]:["paths","explain","requirements"],[Xr.ROUTING_UPDATE]:["settings_revision","provider_weights"],[Xr.PROVIDER_CATALOG]:[],[Xr.PROTOCOL_ADAPTER_LIST]:[],[Xr.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"],[Xr.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"],[Xr.PROVIDER_LIST]:["method","view"],[Xr.PROVIDER_HEALTH]:["exact_model"],[Xr.PROVIDER_UPDATE]:["provider_instance_name","settings_revision","enabled","base_url","credential","provider_profile_id","protocol_adapter_id","discovery","instance_rules"],[Xr.PROVIDER_DELETE]:["provider_instance_name"],[Xr.PROVIDER_REFRESH_MODELS]:["provider_instance_name"],[Xr.MODELS_LIST]:["view"],[Xr.DRIVER_METADATA_UPDATE_GET]:[],[Xr.DRIVER_METADATA_UPDATE_SET]:["enabled","source_url","interval_secs"]};class hs{constructor(e){this.rpcClient=e}setSeq(e){this.rpcClient.setSeq(e)}call(e,t){const n=us[e],r=(null==n?void 0:n.includes("execution_mode"))&&void 0===t.execution_mode?{...t,execution_mode:ns.IMMEDIATE}:t;return n&&cs(r,n),this.rpcClient.call(e,r)}inference(e,t){return os(t.exact_model),this.call(e,t)}routeResolve(e){return as(e.logical_model),this.call(Zr.ROUTE_RESOLVE,e)}chatCompletionsCreate(e){return e.messages.forEach(is),this.inference(Yr.CHAT_COMPLETIONS_CREATE,e)}imagesGenerate(e){return this.inference(Yr.IMAGES_GENERATE,e)}helperLlmChat(e){return as(e.logical_model),e.messages.forEach(is),this.call(Zr.HELPER_LLM_CHAT,e)}helperTextToImage(e){return as(e.logical_model),this.call(Zr.HELPER_TEXT_TO_IMAGE,e)}embeddingText(e){return this.inference(Yr.EMBEDDING_TEXT,e)}embeddingMultimodal(e){return this.inference(Yr.EMBEDDING_MULTIMODAL,e)}async decisionEvaluate(e){ys(e);const t=await this.inference(Yr.DECISION_EVALUATE,e);return"succeeded"===t.status&&ws(e,t.answers??[]),t}rerank(e){return this.inference(Yr.RERANK,e)}imageToImage(e){return this.inference(Yr.IMAGE_IMG2IMG,e)}imageInpaint(e){return this.inference(Yr.IMAGE_INPAINT,e)}imageUpscale(e){return this.inference(Yr.IMAGE_UPSCALE,e)}imageBackgroundRemove(e){return this.inference(Yr.IMAGE_BG_REMOVE,e)}visionOcr(e){return this.inference(Yr.VISION_OCR,e)}visionCaption(e){return this.inference(Yr.VISION_CAPTION,e)}visionDetect(e){return this.inference(Yr.VISION_DETECT,e)}visionSegment(e){return this.inference(Yr.VISION_SEGMENT,e)}audioTextToSpeech(e){return this.inference(Yr.AUDIO_TTS,e)}audioSpeechRecognition(e){return this.inference(Yr.AUDIO_ASR,e)}audioMusic(e){return this.inference(Yr.AUDIO_MUSIC,e)}audioEnhance(e){return this.inference(Yr.AUDIO_ENHANCE,e)}videoGenerate(e){return Cs(e),this.inference(Yr.VIDEO_GENERATE,e)}helperVideoGenerate(e){return as(e.logical_model),Cs(e),xs(e),this.call(Zr.HELPER_VIDEO_GENERATE,e)}videoEdit(e){return Os(e),this.inference(Yr.VIDEO_EDIT,e)}videoExtend(e){return this.inference(Yr.VIDEO_EXTEND,e)}videoUpscale(e){return this.inference(Yr.VIDEO_UPSCALE,e)}computerUse(e){return this.inference(Yr.AGENT_COMPUTER_USE,e)}cancel(e){if(!e)throw new Fn("cancel requires non-empty task_id");return this.call(Zr.CANCEL,{task_id:e})}reloadSettings(){return this.call(Xr.SERVICE_RELOAD_SETTINGS,{})}queryQuota(e={}){return this.call(Xr.QUOTA_QUERY,e)}queryUsage(e){return this.call(Xr.USAGE_QUERY,e)}queryTrace(e={}){return this.call(Xr.TRACE_QUERY,e)}previewRouting(e={}){return this.call(Xr.ROUTING_PREVIEW,e)}getRouting(){return this.call(Xr.ROUTING_GET,{})}updateRouting(e){return this.call(Xr.ROUTING_UPDATE,e)}providerCatalog(){return this.call(Xr.PROVIDER_CATALOG,{})}listProtocolAdapters(){return this.call(Xr.PROTOCOL_ADAPTER_LIST,{})}validateProvider(e){return this.call(Xr.PROVIDER_VALIDATE,e)}addProvider(e){return this.call(Xr.PROVIDER_ADD,e)}listProviders(e={}){return this.call(Xr.PROVIDER_LIST,e)}providerHealth(e){return os(e.exact_model),this.call(Xr.PROVIDER_HEALTH,e)}updateProvider(e){return this.call(Xr.PROVIDER_UPDATE,e)}deleteProvider(e){return this.call(Xr.PROVIDER_DELETE,e)}refreshProviderModels(e){return this.call(Xr.PROVIDER_REFRESH_MODELS,e)}listModels(e={}){return this.call(Xr.MODELS_LIST,e)}listQuotaRules(e={}){return this.call(es.RULE_LIST,e)}getQuotaRule(e){return this.call(es.RULE_GET,{rule_id:e})}previewQuotaRule(e){return this.call(es.RULE_PREVIEW,{draft:e})}createQuotaRule(e){return this.call(es.RULE_CREATE,{draft:e})}updateQuotaRule(e){return this.call(es.RULE_UPDATE,e)}deleteQuotaRule(e,t){return this.call(es.RULE_DELETE,{rule_id:e,expected_version:t})}getQuotaAccount(e){return this.call(es.ACCOUNT_GET,{account_id:e})}rechargeQuotaAccount(e){return this.call(es.ACCOUNT_RECHARGE,e)}getQuotaRecharge(e){return this.call(es.RECHARGE_GET,{recharge_id:e})}getVisibility(){return this.call(es.VISIBILITY_GET,{})}updateVisibility(e){return this.call(es.VISIBILITY_UPDATE,e)}previewVisibility(e={}){return this.call(es.VISIBILITY_PREVIEW,e)}getDriverMetadataUpdate(){return this.call(Xr.DRIVER_METADATA_UPDATE_GET,{})}setDriverMetadataUpdate(e){return this.call(Xr.DRIVER_METADATA_UPDATE_SET,e)}}function ds(e,t=!0){return"string"==typeof e?!t||e.trim().length>0:null!==e&&"object"==typeof e&&(!t||Object.keys(e).length>0)}function fs(e){return"string"==typeof e&&/^[A-Za-z0-9_.-]{1,128}$/.test(e)}function ps(e){return null===e||"object"!=typeof e?JSON.stringify(e):Array.isArray(e)?`[${e.map(ps).join(",")}]`:`{${Object.keys(e).sort().map((t=>`${JSON.stringify(t)}:${ps(e[t])}`)).join(",")}}`}function gs(e){return(new TextEncoder).encode(JSON.stringify(e)).length}function ms(e){const t=gs(e.state),n={question_types:[],structured_state:"string"!=typeof e.state,structured_rules:!1,question_count:e.questions.length,max_options:0,max_levels:0,input_bytes:t+gs(e.questions),max_state_question_bytes:0};for(const r of e.questions){n.question_types.includes(r.type)||n.question_types.push(r.type);const e=[r.instructions];"choice"===r.type?(n.max_options=Math.max(n.max_options,r.options.length),e.push(...r.options.map((e=>e.description)))):"score"===r.type?(n.max_levels=Math.max(n.max_levels,r.levels.length),e.push(...r.levels)):r.criteria&&e.push(...Object.values(r.criteria)),n.structured_rules||(n.structured_rules=e.some((e=>null!==e&&"object"==typeof e))),n.max_state_question_bytes=Math.max(n.max_state_question_bytes,t+gs(r))}return{decision:n}}function ys(e){if(os(e.exact_model),cs(e,us[Yr.DECISION_EVALUATE]),!ds(e.state,!1)||!Array.isArray(e.questions)||!e.questions.length||e.questions.length>1024)throw new Fn("decision requires a text/JSON state and 1..1024 questions");const t=new Set;for(const n of e.questions){if(!n||!fs(n.id)||t.has(n.id)||!ds(n.instructions))throw new Fn("invalid decision question");if(t.add(n.id),"choice"===n.type){if(cs(n,["type","id","instructions","options"]),!Array.isArray(n.options)||!n.options.length||n.options.length>1024)throw new Fn("invalid decision options");const e=new Set;for(const t of n.options){if(cs(t,["id","description"]),!fs(t.id)||e.has(t.id)||null!==t.description&&!ds(t.description))throw new Fn("invalid decision option");e.add(t.id)}}else if("score"===n.type){if(cs(n,["type","id","instructions","levels"]),!Array.isArray(n.levels)||n.levels.length<2||n.levels.length>1024||n.levels.some((e=>!ds(e)))||new Set(n.levels.map(ps)).size!==n.levels.length)throw new Fn("invalid decision levels")}else{if("boolean"!==n.type)throw new Fn("invalid decision question type");if(cs(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(cs(n.criteria,["true","false"]),Object.values(n.criteria).some((e=>!ds(e))))throw new Fn("invalid decision criteria")}}}if(ms(e).decision.input_bytes>1048576)throw new Fn("decision input exceeds 1 MiB")}function ws(e,t){const n=e=>"number"==typeof e&&Number.isFinite(e)&&e>=0&&e<=1,r=()=>{throw new Fn("invalid or incomplete decision answers")};Array.isArray(t)&&t.length===e.questions.length||r();const s=new Set;for(const i of t){i&&!s.has(i.id)||r(),s.add(i.id);const t=e.questions.find((e=>e.id===i.id));if(!t)throw new Fn("unknown decision question ID");if((t.type!==i.type||void 0!==i.confidence&&!n(i.confidence))&&r(),"boolean"===i.type){cs(i,["type","id","probability_true","confidence"]),n(i.probability_true)||r();continue}cs(i,"choice"===i.type?["type","id","selected","probabilities","confidence"]:["type","id","score","levels","probabilities","confidence"]);const o="choice"===t.type?t.options.map((e=>e.id)):"score"===t.type?t.levels.map(((e,t)=>String(t))):[];if((!i.probabilities||Array.isArray(i.probabilities)||Object.keys(i.probabilities).length!==o.length||o.some((e=>!Object.prototype.hasOwnProperty.call(i.probabilities,e)||!n(i.probabilities[e])))||Math.abs(Object.values(i.probabilities).reduce(((e,t)=>e+t),0)-1)>1e-4)&&r(),"choice"===i.type)o.includes(i.selected)&&!Object.values(i.probabilities).some((e=>e>i.probabilities[i.selected]+1e-4))||r();else if("score"===i.type&&"score"===t.type){const e=o.reduce(((e,t,n)=>e+n*i.probabilities[t]),0);(!Number.isFinite(i.score)||i.score<0||i.score>o.length-1||Math.abs(i.score-e)>1e-4*(o.length-1)||ps(i.levels)!==ps(t.levels))&&r()}else r()}}const bs=32,_s=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,As={reference_image:["type","id","resource"],reference_video:["type","id","resource","time_range","include_audio"],reference_audio:["type","id","resource","time_range"],keyframe:["type","id","resource","position"]},vs=["start","end"];function Es(e){const t=[];let n="";for(let r=0;r<e.length;r++){const s=e[r+1];if("@"!==e[r])n+=e[r];else if("@"===s)n+="@",r++;else if("{"!==s)n+="@";else{const s=e.indexOf("}",r+2);if(s<0)throw new Fn("prompt reference `@{` is not closed");const i=e.slice(r+2,s);if(!_s.test(i))throw new Fn(`prompt reference \`${i}\` is not a valid condition id`);n&&t.push({text:n}),n="",t.push({reference:i}),r=s}}return n&&t.push({text:n}),t}function ks(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Ss(e,t,n){return"number"==typeof e&&Number.isFinite(e)&&e>t&&e<=n}function Ts(e,t){const n=(e,t)=>0===t?e:n(t,e%t),r=Math.max(n(e,t),1);return`${e/r}:${t/r}`}function Rs(e,t){const n={url:["kind","url","mime_hint"],base64:["kind","mime","data_base64"],named_object:["kind","obj_id"]};if(!ks(e)||"string"!=typeof e.kind||!n[e.kind])throw new Fn(`${t} must be a ResourceRef`);cs(e,n[e.kind])}function Is(e,t="output"){if(!ks(e))throw new Fn(`${t} must be an object`);if(cs(e,["duration_seconds","aspect_ratio","size","fps","audio","media_type"]),void 0!==e.duration_seconds&&!Ss(e.duration_seconds,0,600))throw new Fn(`${t}.duration_seconds must be a number in (0, 600]`);const n=void 0===e.aspect_ratio?void 0:function(e){const t="string"==typeof e?/^(\d{1,3}):(\d{1,3})$/.exec(e):null,[n,r]=t?[Number(t[1]),Number(t[2])]:[0,0];return n>=1&&n<=100&&r>=1&&r<=100?[n,r]:void 0}(e.aspect_ratio);if(void 0!==e.aspect_ratio&&!n)throw new Fn(`${t}.aspect_ratio must be \`W:H\` with integers in 1..100`);const r=(e,n)=>{if(!Number.isInteger(e)||e<16||e>8192)throw new Fn(`${t}.size.${n} must be an integer in 16..8192`)},s=e.size;if(void 0!==s){if(!ks(s))throw new Fn(`${t}.size must be { short_edge } or { width, height }`);if("short_edge"in s)cs(s,["short_edge"]),r(s.short_edge,"short_edge");else if(cs(s,["width","height"]),r(s.width,"width"),r(s.height,"height"),n&&Ts(s.width,s.height)!==Ts(...n))throw new Fn(`${t}.size conflicts with aspect_ratio`)}if(void 0!==e.fps&&!Ss(e.fps,0,240))throw new Fn(`${t}.fps must be a number in (0, 240]`);if(void 0!==e.audio&&!["auto","generate","none"].includes(e.audio))throw new Fn(`${t}.audio must be auto, generate or none`);if(void 0!==e.media_type&&("string"!=typeof e.media_type||!/^video\/[a-z0-9.+-]+$/.test(e.media_type)))throw new Fn(`${t}.media_type must be a lowercase video/* MIME type`)}function Cs(e){const{prompt:t,negative_prompt:n,seed:r}=e,s=e.conditions??[];if(void 0!==t&&"string"!=typeof t)throw new Fn("prompt must be a string");if(!Array.isArray(s))throw new Fn("conditions must be an array");if(!(null==t?void 0:t.trim())&&!s.length)throw new Fn("video generation requires a non-blank prompt or at least one condition");if(void 0!==n&&("string"!=typeof n||!n.trim()))throw new Fn("negative_prompt must not be blank when present");if(void 0!==r&&!(Number.isSafeInteger(r)&&r>=0))throw new Fn("seed must be a non-negative integer");if(s.length>bs)throw new Fn(`video generation accepts at most ${bs} conditions`);const i=new Set,o=new Set;s.forEach(((e,t)=>{const n=`conditions[${t}]`;if(!ks(e)||!(e.type in As))throw new Fn(`${n}.type must be a video condition type`);if(cs(e,As[e.type]),"string"!=typeof e.id||!_s.test(e.id))throw new Fn(`${n}.id must match ${_s}`);if(i.has(e.id.toLowerCase()))throw new Fn(`${n}.id \`${e.id}\` is not unique (compared case-insensitively)`);if(i.add(e.id.toLowerCase()),Rs(e.resource,`${n}.resource`),"keyframe"===e.type){if(!vs.includes(e.position))throw new Fn(`${n}.position must be start or end`);if(o.has(e.position))throw new Fn(`${n}: at most one keyframe is allowed per position`);o.add(e.position)}if(void 0!==e.include_audio&&"boolean"!=typeof e.include_audio)throw new Fn(`${n}.include_audio must be a boolean`);const r=e.time_range;if(void 0!==r){if(!ks(r))throw new Fn(`${n}.time_range must be an object`);cs(r,["start_seconds","end_seconds"]);const{start_seconds:e,end_seconds:t}=r;if("number"!=typeof e||"number"!=typeof t||!Number.isFinite(e)||!Number.isFinite(t)||e<0||e>=t)throw new Fn(`${n}.time_range must be finite, non-negative and start before it ends`)}}));for(const a of t?Es(t):[])if("reference"in a&&!(e.conditions??[]).some((e=>e.id===a.reference)))throw new Fn(`prompt references unknown condition \`${a.reference}\``);void 0!==e.output&&Is(e.output)}function Os(e){if("string"!=typeof e.prompt||!e.prompt.trim())throw new Fn("video edit requires a non-blank prompt");Rs(e.video,"video"),void 0!==e.output&&Is(e.output)}function xs(e){var t,n;const r=e.conditions??[],s=e=>r.filter((t=>t.type===e)).length,i=(null==(t=e.requirements)?void 0:t.video)??{},o={},a=(e,t)=>{(t||i[e])&&(o[e]=!0)};a("prompt",!!(null==(n=e.prompt)?void 0:n.trim())),a("negative_prompt",void 0!==e.negative_prompt),a("seed",void 0!==e.seed);for(const[u,h]of[["reference_images","reference_image"],["reference_videos","reference_video"],["reference_audios","reference_audio"]]){const e=Math.max(s(h),i[u]??0);e&&(o[u]=e)}const c=vs.filter((e=>{var t;return(null==(t=i.keyframes)?void 0:t.includes(e))||r.some((t=>"keyframe"===t.type&&t.position===e))}));c.length&&(o.keyframes=c),a("reference_video_audio",r.some((e=>"reference_video"===e.type&&!0===e.include_audio))),a("time_ranges",r.some((e=>"time_range"in e&&void 0!==e.time_range)));const l=e.output&&Object.values(e.output).some((e=>void 0!==e))?e.output:void 0;if(l&&i.output&&ps(l)!==ps(i.output))throw new Fn("requirements.video.output conflicts with the request output");return!l&&i.output&&Is(i.output,"requirements.video.output"),(l??i.output)&&(o.output=l??i.output),o}const Ns={max_messages:null,retention_seconds:null,sync_write:!1,keep_acked:!1,other_app_can_read:!0,other_app_can_write:!1,other_user_can_read:!1,other_user_can_write:!1};function Ps(e,t){if("number"!=typeof e||!Number.isFinite(e))throw new Fn(`expected ${t} to be a number`);return e}function Ds(e,t){if("string"!=typeof e)throw new Fn(`expected ${t} to be a string`);return e}function Bs(e){if(!Array.isArray(e))throw new Fn("expected message list to be an array");return e.map(((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw new Fn(`message[${t}] is not an object`);const n=e;return{index:Ps(n.index,`message[${t}].index`),created_at:Ps(n.created_at,`message[${t}].created_at`),payload:Array.isArray(n.payload)?n.payload:[],headers:n.headers&&"object"==typeof n.headers&&!Array.isArray(n.headers)?n.headers:{}}}))}class Us{constructor(e){this.rpcClient=e}setSeq(e){this.rpcClient.setSeq(e)}async createQueue(e,t,n,r={...Ns}){return Ds(await this.rpcClient.call("create_queue",{name:e,appid:t,app_owner:n,config:r}),"queue_urn")}async deleteQueue(e){await this.rpcClient.call("delete_queue",{queue_urn:e})}async getQueueStats(e){const t=await this.rpcClient.call("get_queue_stats",{queue_urn:e});if(!t||"object"!=typeof t)throw new Fn("invalid get_queue_stats response");const n=t;return{message_count:Ps(n.message_count,"message_count"),first_index:Ps(n.first_index,"first_index"),last_index:Ps(n.last_index,"last_index"),size_bytes:Ps(n.size_bytes,"size_bytes")}}async updateQueueConfig(e,t){await this.rpcClient.call("update_queue_config",{queue_urn:e,config:t})}async postMessage(e,t){return Ps(await this.rpcClient.call("post_message",{queue_urn:e,message:t}),"msg_index")}async subscribe(e){return Ds(await this.rpcClient.call("subscribe",{queue_urn:e.queueUrn,userid:e.userId,appid:e.appId,sub_id:e.subId??null,position:e.position}),"subscription_id")}async unsubscribe(e){await this.rpcClient.call("unsubscribe",{sub_id:e})}async fetchMessages(e,t,n){return Bs(await this.rpcClient.call("fetch_messages",{sub_id:e,length:t,auto_commit:n}))}async readMessage(e,t,n){return Bs(await this.rpcClient.call("read_message",{queue_urn:e,cursor:t,length:n}))}async commitAck(e,t){await this.rpcClient.call("commit_ack",{sub_id:e,index:t})}async seek(e,t){await this.rpcClient.call("seek",{sub_id:e,index:t})}async deleteMessageBefore(e,t){return Ps(await this.rpcClient.call("delete_message_before",{queue_urn:e,index:t}),"deleted_count")}}const Ls="zone_user",Ms="zone_agent",Fs="homestation.following",js=[{key:Ls,kind:"system",user_editable:!1},{key:Ms,kind:"system",user_editable:!1},{key:Fs,kind:"app",app:"homestation",user_editable:!1}];function Gs(e){const t=/^([a-z][a-z0-9_-]*)\.([a-z0-9_.-]+)$/.exec(e);return t?t[1]:null}const Hs="type:",Vs="group:";function qs(e){return e.startsWith(Hs)||e.startsWith(Vs)}const Ws="buckyos.notify",zs="sysnotify:",Ks="option",$s="text",Qs="answer",Js="dismiss",Ys="/messagehub";function Zs(e){return"open"!==e&&"read"!==e}function Xs(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(t[n]=r);return t}function ei(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw new Fn(`expected ${t} to be an object`);return e}function ti(e,t){return null==e?null:ei(e,t)}function ni(e,t){if(!Array.isArray(e))throw new Fn(`expected ${t} to be an array`);return e}function ri(e,t){if("string"!=typeof e)throw new Fn(`${t} expected to return a DID string`);return e}function si(e){const t=ei(e,"NotifyView");if("string"!=typeof t.notify_id||"string"!=typeof t.status)throw new Fn("Invalid NotifyView");return t}class ii{constructor(e){this.rpcClient=e}setSeq(e){this.rpcClient.setSeq(e)}call(e,t){return this.rpcClient.call(e,t)}async dispatch(e,t,n){return ei(await this.call("msg.dispatch",Xs({msg:e,ingress_ctx:t,idempotency_key:n})),"DispatchResult")}async postSend(e,t){return ei(await this.call("msg.post_send",Xs({msg:e,idempotency_key:t})),"PostSendResult")}async listMailboxes(e,t){return ni(await this.call("msg.list_mailboxes",{owner:e,box_kind:t}),"Vec<MailboxAddress>")}async moveRecord(e,t){return ei(await this.call("msg.move_record",{record_id:e,mailbox:t}),"MailboxRecord")}async getNext(e){return ti(await this.call("msg.get_next",Xs({...e})),"MailboxRecordWithObject")}async getNextDelivery(e){return ti(await this.call("msg.get_next_delivery",Xs({...e})),"DeliveryRecordWithObject")}async peekBox(e){return ni(await this.call("msg.peek_box",Xs({...e})),"Vec<MailboxRecordWithObject>")}async listBoxByTime(e){const t=ei(await this.call("msg.list_box_by_time",Xs({...e})),"MailboxRecordPage");return{...t,items:Array.isArray(t.items)?t.items:[]}}async listSessions(e){const t=ei(await this.call("msg.list_sessions",Xs({...e})),"SessionSummaryPage");return{...t,items:Array.isArray(t.items)?t.items:[]}}async listSession(e){const t=ei(await this.call("msg.list_session",Xs({...e})),"SessionMessagePage");return{...t,items:Array.isArray(t.items)?t.items:[]}}async updateRecordState(e,t){return ei(await this.call("msg.update_record_state",{record_id:e,new_state:t}),"MailboxRecord")}async updateRecordSession(e,t){return ei(await this.call("msg.update_record_session",{record_id:e,session_id:t}),"MailboxRecord")}async reportDelivery(e,t){return ei(await this.call("msg.report_delivery",{delivery_id:e,result:t}),"DeliveryRecord")}async setReadState(e){return ei(await this.call("msg.set_read_state",Xs({...e})),"MsgReceiptObj")}async listReadReceipts(e){return ni(await this.call("msg.list_read_receipts",Xs({...e})),"Vec<MsgReceiptObj>")}async getRecord(e,t){return ti(await this.call("msg.get_record",Xs({record_id:e,with_object:t})),"MailboxRecordWithObject")}async getMessage(e){return ti(await this.call("msg.get_message",{msg_id:e}),"MsgObject")}async updateUiSessionState(e,t,n){return ei(await this.call("ui_session.update_state",{session_id:e,key:t,value:n}),"UiSessionStateEntry")}async getUiSessionState(e,t){return ti(await this.call("ui_session.get_state",{session_id:e,key:t}),"UiSessionStateEntry")}async listUiSessionState(e){return ni(await this.call("ui_session.list_state",{session_id:e}),"Vec<UiSessionStateEntry>")}async resolveDid(e,t,n,r){return ri(await this.call("contact.resolve_did",Xs({platform:e,account_id:t,profile_hint:n,contact_mgr_owner:r})),"contact.resolve_did")}async resolveEndpointDid(e,t,n,r,s){return ri(await this.call("contact.resolve_endpoint_did",Xs({platform:e,account_id:t,account_type:n,tunnel_instance_id:r,contact_mgr_owner:s})),"contact.resolve_endpoint_did")}async resolveTarget(e,t,n){return ri(await this.call("contact.resolve_target",Xs({contact_did:e,selector:t,contact_mgr_owner:n})),"contact.resolve_target")}async resolveContactForEndpoint(e,t){const n=await this.call("contact.resolve_contact_for_endpoint",Xs({endpoint_did:e,contact_mgr_owner:t}));return s="contact.resolve_contact_for_endpoint",null==(r=n)?null:ri(r,s);var r,s}async resolveCanonicalDid(e,t){return ri(await this.call("contact.resolve_canonical_did",Xs({did:e,contact_mgr_owner:t})),"contact.resolve_canonical_did")}async listAliasDids(e,t){return ni(await this.call("contact.list_alias_dids",Xs({canonical_did:e,contact_mgr_owner:t})),"Vec<DID>")}async getPreferredBinding(e,t){return ei(await this.call("contact.get_preferred_binding",Xs({did:e,contact_mgr_owner:t})),"AccountBinding")}async checkAccessPermission(e,t,n){return ei(await this.call("contact.check_access_permission",Xs({did:e,context_id:t,contact_mgr_owner:n})),"AccessDecision")}async grantTemporaryAccess(e,t,n,r){const s=ei(await this.call("contact.grant_temporary_access",Xs({dids:e,context_id:t,duration_secs:n,contact_mgr_owner:r})),"GrantTemporaryAccessResult");return{updated:Array.isArray(s.updated)?s.updated:[]}}async blockContact(e,t,n){await this.call("contact.block_contact",Xs({did:e,reason:t,contact_mgr_owner:n}))}async importContacts(e,t,n){return ei(await this.call("contact.import_contacts",Xs({contacts:e,upgrade_to_friend:t,contact_mgr_owner:n})),"ImportReport")}async mergeContacts(e,t,n){return ei(await this.call("contact.merge_contacts",Xs({target_did:e,source_did:t,contact_mgr_owner:n})),"Contact")}async updateContact(e,t,n){return ei(await this.call("contact.update_contact",Xs({did:e,patch:t,contact_mgr_owner:n})),"Contact")}async getContact(e,t){return ti(await this.call("contact.get_contact",Xs({did:e,contact_mgr_owner:t})),"Contact")}async listContacts(e,t){return ni(await this.call("contact.list_contacts",Xs({query:e,contact_mgr_owner:t})),"Vec<Contact>")}async getGroupSubscribers(e,t,n,r){return ni(await this.call("contact.get_group_subscribers",Xs({group_id:e,limit:t,offset:n,contact_mgr_owner:r})),"Vec<DID>")}async setGroupSubscribers(e,t,n){const r=ei(await this.call("contact.set_group_subscribers",Xs({group_id:e,subscribers:t,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 lookup(e){const t=ei(await this.call("contact.lookup",Xs({...e})),"LookupResult");return{...t,candidates:Array.isArray(t.candidates)?t.candidates:[]}}async updateContactTags(e,t,n){return ei(await this.call("contact.update_tags",Xs({did:e,add:t.add,remove:t.remove,contact_mgr_owner:n})),"Contact")}async removeContact(e,t){await this.call("contact.remove_contact",Xs({did:e,contact_mgr_owner:t}))}async unblockContact(e,t){return ei(await this.call("contact.unblock_contact",Xs({did:e,contact_mgr_owner:t})),"Contact")}async sendFriendRequest(e,t,n){return ei(await this.call("contact.send_friend_request",Xs({did:e,message:t,contact_mgr_owner:n})),"FriendRequestResult")}async respondFriendRequest(e,t,n){return ei(await this.call("contact.respond_friend_request",Xs({request_id:e,decision:t,contact_mgr_owner:n})),"FriendRequestResult")}async cancelFriendRequest(e,t){return ei(await this.call("contact.cancel_friend_request",Xs({request_id:e,contact_mgr_owner:t})),"FriendRequestResult")}async removeFriend(e,t,n){return ei(await this.call("contact.remove_friend",Xs({did:e,notify:t,contact_mgr_owner:n})),"FriendRequestResult")}async listFriendRequests(e={}){const t=ti(await this.call("contact.list_friend_requests",Xs({...e})),"FriendRequestPage");return t&&Array.isArray(t.items)?t.items:[]}async notifySend(e){return si(await this.call("notify.send",Xs({...e})))}async notifyGet(e){return si(await this.call("notify.get",{notify_id:e}))}async notifyList(e={}){const t=ei(await this.call("notify.list",Xs({...e})),"NotifyListResult");return{...t,items:ni(t.items,"Vec<NotifyView>").map(si)}}async notifyAck(e,t){return si(await this.call("notify.ack",Xs({notify_id:e,on_behalf:t})))}async notifyDismiss(e){return si(await this.call("notify.dismiss",{notify_id:e}))}async notifyCancel(e,t){return si(await this.call("notify.cancel",Xs({notify_id:e,reason:t})))}}function oi(e){for(const t of e.controls??[])if("choice"===t.kind&&t.id===Ks)return t.options??[];return[]}function ai(e,t,n){const r={};return e.option&&(r[Ks]=e.option),e.text&&e.text.trim()&&(r[$s]=e.text),{kind:"human",action:e.dismiss?Js:Qs,...Object.keys(r).length>0?{values:r}:{},submitted_by:t,submitted_at:n}}function ci(e,t){if(e.dismiss)return null;const n=oi(t),r=(t.controls??[]).some((e=>"text_input"===e.kind&&e.id===$s));if(null!=e.option&&!n.some((t=>t.value===e.option)))return`no option '${e.option}'; options: ${n.map((e=>e.value)).join(", ")}`;const s=!!e.text&&""!==e.text.trim();return s&&!r?"this question takes one of its options, not free text":null!=e.option||s?null:"an answer needs an option or a text"}function li(e,t){const n=null==e?void 0:e.content;if(!n||"object"!=typeof n)return null;const r=n.machine;if(!r||"object"!=typeof r||r.intent!==t)return null;const s=r.data;return s&&"object"==typeof s&&!Array.isArray(s)?s:null}async function ui(e,t,n,r,s=Date.now()){for(let a=0;a<3;a+=1){const i=await e.getTask(t);if(Er(i.phase)||null!=i.result)return{kind:"already_closed",task:i};try{return{kind:"committed",task:await e.commitResult({task_id:t,result:ai(n,r,s),expected_revision:i.revision})}}catch(o){const n=_r(o);if(n===fr)return{kind:"already_closed",task:await e.getTask(t)};if(n!==cr)throw o}}const i=await e.getTask(t);if(Er(i.phase))return{kind:"already_closed",task:i};throw new Fn(`task ${t} keeps changing; answer not committed`)}async function hi(e,t){const n=Date.now();if(t)try{if(await t.pullEvent(e))return}catch{}const r=e-(Date.now()-n);r>0&&await function(e){return new Promise((t=>setTimeout(t,e)))}(r)}function di(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(t[n]=r);return t}function fi(e,t){if("string"!=typeof e)throw new Fn(`expected ${t} to be a string`);return e}function pi(e,t){if("boolean"!=typeof e)throw new Fn(`expected ${t} to be a boolean`);return e}function gi(e,t){if("number"!=typeof e||!Number.isFinite(e))throw new Fn(`expected ${t} to be a number`);return e}function mi(e,t){if(!Array.isArray(e))throw new Fn(`expected ${t} to be an array`);return e}function yi(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw new Fn(`expected ${t} to be an object`);return e}class wi{constructor(e){this.rpcClient=e}setSeq(e){this.rpcClient.setSeq(e)}async store(e){return fi(await this.rpcClient.call("store",{content_id:e}),"ObjId")}async collect(e,t){return fi(await this.rpcClient.call("collect",di({content_meta:e,referral_proof:t})),"content_id")}async pin(e,t){return pi(await this.rpcClient.call("pin",{content_id:e,download_proof:t}),"pin response")}async unpin(e,t=!1){return pi(await this.rpcClient.call("unpin",{content_id:e,force:t}),"unpin response")}async uncollect(e,t=!1){return pi(await this.rpcClient.call("uncollect",{content_id:e,force:t}),"uncollect response")}async addProof(e){return fi(await this.rpcClient.call("add_proof",{proof:e}),"proof_id")}async getProofs(e,t){return mi(await this.rpcClient.call("get_proofs",di({content_id:e,filter:t})),"Vec<RepoProof>").map(((e,t)=>{const n=yi(e,`RepoProof[${t}]`);if("Action"!==n.kind&&"Collection"!==n.kind)throw new Fn(`RepoProof[${t}] has unknown kind: ${String(n.kind)}`);return n}))}async resolve(e){return mi(await this.rpcClient.call("resolve",{content_name:e}),"Vec<ObjId>").map(((e,t)=>fi(e,`ObjId[${t}]`)))}async list(e){return mi(await this.rpcClient.call("list",di({filter:e})),"Vec<RepoRecord>").map(((e,t)=>{const n=yi(e,`RepoRecord[${t}]`);return{content_id:fi(n.content_id,`RepoRecord[${t}].content_id`),content_name:"string"==typeof n.content_name?n.content_name:void 0,status:fi(n.status,`RepoRecord[${t}].status`),origin:fi(n.origin,`RepoRecord[${t}].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:fi(n.access_policy,`RepoRecord[${t}].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 e=yi(await this.rpcClient.call("stat",{}),"RepoStat");return{total_objects:gi(e.total_objects,"RepoStat.total_objects"),collected_objects:gi(e.collected_objects,"RepoStat.collected_objects"),pinned_objects:gi(e.pinned_objects,"RepoStat.pinned_objects"),local_objects:gi(e.local_objects,"RepoStat.local_objects"),remote_objects:gi(e.remote_objects,"RepoStat.remote_objects"),total_content_bytes:gi(e.total_content_bytes,"RepoStat.total_content_bytes"),total_proofs:gi(e.total_proofs,"RepoStat.total_proofs")}}async serve(e,t){const n=yi(await this.rpcClient.call("serve",{content_id:e,request_context:t}),"RepoServeResult");return{status:fi(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(e){return pi(await this.rpcClient.call("announce",{content_id:e}),"announce response")}}function bi(e){if(!e||e.length>253||e.includes("@"))throw new Error("hostname must be 1..=253 bytes and must not contain `@`");if(e!==e.toLowerCase()||!/^[\x00-\x7f]+$/.test(e))throw new Error("hostname must be canonical lowercase ASCII");for(const t of e.split("."))if(!t||t.length>63||t.startsWith("-")||t.endsWith("-")||!/^[a-z0-9-]+$/.test(t))throw new Error(`invalid DNS label \`${t}\``)}function _i(e){const t=/^did:([^:]+):(.+)$/.exec(e);if(!t)throw new Error("AppDID must be a canonical DID");const[,n,r]=t;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(bi(s),"web"===n&&s.endsWith(".did"))throw new Error("AppDID did:web hostnames ending in `.did` are reserved");if(Mn.DID.fromStr(s).toString()!==e)throw new Error("AppDID raw hostname does not round-trip");return s}function Ai(e){return _i(e.trim())}function vi(e){const t=e.trim();bi(t);const n=_i(Mn.DID.fromStr(t).toString());if(n!==t)throw new Error("AppId is not a canonical AppDID raw hostname");return n}function Ei(e){if(!e||e.length>64||!/^[a-z0-9._-]+$/.test(e))throw new Error("owner_user_id must be lowercase ASCII and contain only [a-z0-9._-]")}function ki(e,t){const n=vi(e);return Ei(t),`${n}@${t}`}function Si(e){const t=e.trim(),n=t.lastIndexOf("@");if(n<=0||n===t.length-1)throw new Error("AppInstanceId must be `{app_id}@{owner_user_id}`");const r=vi(t.slice(0,n)),s=t.slice(n+1);return Ei(s),{appId:r,ownerUserId:s}}const Ti="BUCKYOS_APP_DID",Ri="BUCKYOS_APP_ID",Ii="BUCKYOS_APP_INSTANCE_ID",Ci="BUCKYOS_OWNER_USER_ID",Oi="BUCKYOS_DATA_DIR",xi="BUCKYOS_APP_TOKEN";var Ni=(e=>(e.Browser="Browser",e.NodeJS="NodeJS",e.AppRuntime="AppRuntime",e.AppClient="AppClient",e.AppService="AppService",e.Unknown="Unknown",e))(Ni||{});const Pi=["admin","user","limited","root"];const Di="external";const Bi={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 Ui(){const e=globalThis.process;return(null==e?void 0:e.env)??{}}function Li(){var e;const t=globalThis.process;return Boolean(null==(e=null==t?void 0:t.versions)?void 0:e.node)}function Mi(){return"undefined"!=typeof localStorage}function Fi(){return"function"==typeof fetch}function ji(){const e=globalThis.Buffer;if(!e||"function"!=typeof e)throw new Error("Buffer is not available in this runtime");return e}function Gi(e){const t=ji();return("string"==typeof e?t.from(e,"utf8").toString("base64"):t.from(e).toString("base64")).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Hi(e){if(!e)return null;const t=e.split(".");if(t.length<2)return null;try{return JSON.parse(function(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t+"=".repeat((4-t.length%4)%4);return"function"==typeof atob?atob(n):ji().from(n,"base64").toString("utf8")}(t[1]))}catch{return null}}function Vi(e){if("string"!=typeof e)return null;const t=e.trim();return t.length>0?t:null}function qi(e){const t=Vi(e);return t?t.startsWith("did:web:")?t.slice(8).replace(/:/g,"."):t.startsWith("did:bns:")?t.slice(8):null:null}async function Wi(e){if(Li()&&"function"==typeof require)return require(e);return Function("name","return import(name)")(e)}class zi{async initialize(e){await e.resolveAppServiceIdentityFromEnv(),await e.resolveZoneHostFromLocalConfig()}async login(e){await e.initialize(),e.startAutoRenewIfNeeded()}supportsManagedSessionRenewal(){return!1}shouldSkipVerifyHubRenewal(e){return!1}async getVerifyHubLoginJwt(e,t){return t}}class Ki extends zi{getRelativeZoneServiceURL(e){return`/kapi/${e}/`}getRelativeSystemConfigServiceURL(){return"/kapi/system_config"}getServiceSettingsPath(e){var t;const n=null==(t=Mn.getBrowserUserInfo())?void 0:t.user_id;if(!n)throw new Error("Login is required for App settings");return`users/${n}/apps/${e.getAppId()}/settings`}getZoneServiceURL(e,t){return this.getRelativeZoneServiceURL(t)}getSystemConfigServiceURL(e){return this.getRelativeSystemConfigServiceURL()}getMySettingsPath(e){return this.getServiceSettingsPath(e)}}class $i extends Ki{}class Qi extends zi{async login(e){await e.initialize(),await e.renewTokenFromVerifyHub(),e.startAutoRenewIfNeeded()}supportsManagedSessionRenewal(){return!0}}class Ji extends Qi{async initialize(e){await super.initialize(e),await e.ensureAppClientSessionToken()}getZoneGatewayServiceURL(e,t){const n=Vi(e.getZoneHostName());if(!n)throw new Error("zoneHost is required in AppClient mode");return`${e.getDefaultProtocol()}${n}/kapi/${t}`}getZoneSystemConfigURL(e){const t=Vi(e.getZoneHostName());if(!t)throw new Error("zoneHost is required in AppClient mode");return`${e.getDefaultProtocol()}${t}/kapi/system_config`}getZoneServiceURL(e,t){return this.getZoneGatewayServiceURL(e,t)}getSystemConfigServiceURL(e){return this.getZoneSystemConfigURL(e)}getMySettingsPath(){throw new Error("AppClient not support getMySettingsPath")}shouldSkipVerifyHubRenewal(e){return!Vi(e.getZoneHostName())&&!e.getConfiguredVerifyHubServiceUrl()}async getVerifyHubLoginJwt(e,t){return e.createAppClientSessionToken()}}class Yi extends Qi{async initialize(e){await super.initialize(e),e.ensureAppServiceSessionToken()}getNodeGatewayServiceURL(e,t){const n=e.getNodeGatewayPort();return`http://${e.resolveAppServiceGatewayHost()}:${n}/kapi/${t}`}getNodeGatewaySystemConfigURL(e){const t=e.getNodeGatewayPort();return`http://${e.resolveAppServiceGatewayHost()}:${t}/kapi/system_config`}getUserAppSettingsPath(e){const t=e.getOwnerUserId();if(!t)throw new Error("ownerUserId is required for AppService settings");return`users/${t}/apps/${e.getAppId()}/settings`}getZoneServiceURL(e,t){return this.getNodeGatewayServiceURL(e,t)}getSystemConfigServiceURL(e){return this.getNodeGatewaySystemConfigURL(e)}getMySettingsPath(e){return this.getUserAppSettingsPath(e)}}function Zi(e){switch(e){case"AppClient":return new Ji;case"AppService":return new Yi;case"AppRuntime":return new $i;default:return new Ki}}class Xi{constructor(e){const t=Vi(e.ownerUserId)??Vi(e.userid);this.config={...Bi,...e,appId:e.appId,appDid:Vi(e.appDid),appInstanceId:Vi(e.appInstanceId),dataDir:Vi(e.dataDir),userid:t,ownerUserId:t,zoneHost:e.zoneHost??"",defaultProtocol:e.defaultProtocol??Bi.defaultProtocol},this.sessionToken=Vi(e.sessionToken),this.refreshToken=Vi(e.refreshToken),this.renewTimer=null,this.browserRefreshPromise=null,this.authStateRevision=0,this.initialized=!1,this.profile=Zi(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(e){const t=Vi(e.ownerUserId)??Vi(e.userid);this.config={...Bi,...e,appId:e.appId,appDid:Vi(e.appDid),appInstanceId:Vi(e.appInstanceId),dataDir:Vi(e.dataDir),userid:t,ownerUserId:t},this.profile=Zi(this.config.runtimeType)}getConfig(){return{...this.config}}getAppId(){return this.config.appId}getOwnerUserId(){return Vi(this.config.ownerUserId)}getAppDid(){return Vi(this.config.appDid)}getAppInstanceId(){return Vi(this.config.appInstanceId)}getDataDir(){return Vi(this.config.dataDir)}getAuthTarget(){if(this.config.authTarget){const e=sr(this.config.authTarget);if(e!==this.config.appId)throw new Error(`auth target appid mismatch: ${e} != ${this.config.appId}`);return{...this.config.authTarget}}const e=this.getAppInstanceId();if(e){const t=Si(e);if(t.appId!==this.config.appId)throw new Error(`auth target appid mismatch: ${t.appId} != ${this.config.appId}`);return{kind:"app",app_instance_id:e}}if("AppClient"===this.config.runtimeType||"AppService"===this.config.runtimeType){const e=this.getOwnerUserId();if(!e)throw new Error("ownerUserId is required to build an App auth target");return{kind:"app",app_instance_id:ki(this.config.appId,e)}}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 Vi(this.config.verifyHubServiceUrl)}getZoneServiceURL(e){const t=function(e){return"system-config"===e?"system_config":e}(e);return this.profile.getZoneServiceURL(this,t)}getSystemConfigServiceURL(){const e=this.getConfiguredSystemConfigServiceUrl();return e||this.profile.getSystemConfigServiceURL(this)}setSessionToken(e){const t=Vi(e);t!==this.sessionToken&&(this.authStateRevision+=1),this.sessionToken=t}setRefreshToken(e){this.refreshToken=Vi(e)}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(e){return new Gn(this.getZoneServiceURL(e),this.sessionToken,null,{sessionTokenProvider:this.ensureSessionTokenReady.bind(this),onSessionTokenChanged:this.setSessionToken.bind(this)})}getSystemConfigClient(){return new Jr(this.getSystemConfigServiceURL(),this.sessionToken,{sessionTokenProvider:this.ensureSessionTokenReady.bind(this),onSessionTokenChanged:this.setSessionToken.bind(this)})}getVerifyHubClient(){const e=this.getConfiguredVerifyHubServiceUrl(),t=new Gn(e??this.getZoneServiceURL("verify-hub"),this.sessionToken);return new ir(t)}getTaskManagerClient(){const e=this.getServiceRpcClient("task-manager");return new Br(e)}getWorkflowClient(){const e=this.getServiceRpcClient("workflow");return new $r(e)}getAiccClient(){return new hs(this.getServiceRpcClient("aicc"))}getAiWorkspaceClient(){return new nr(this.getServiceRpcClient(er))}getMsgQueueClient(){return new Us(this.getServiceRpcClient("kmsg"))}getMsgCenterClient(){return new ii(this.getServiceRpcClient("msg-center"))}getRepoClient(){return new wi(this.getServiceRpcClient("repo-service"))}async getMySettings(){const e=this.getMySettingsPath(),t=await this.getSystemConfigClient().get(e);return JSON.parse(t.value)}async updateMySettings(e,t){const n=this.getMySettingsPath(),r=JSON.stringify(t);await this.getSystemConfigClient().setByJsonPath(n,e,r)}async updateAllMySettings(e){const t=this.getMySettingsPath(),n=JSON.stringify(e);await this.getSystemConfigClient().set(t,n)}async renewTokenFromVerifyHub(){if(!this.profile.supportsManagedSessionRenewal())return;const e=this.sessionToken;if(!e)return;const t=Hi(e);if(!t||!this.needsRenew(t))return;if(this.profile.shouldSkipVerifyHubRenewal(this))return;const n=this.getVerifyHubClient(),r="verify-hub"===t.iss?this.refreshToken?await n.refreshToken({refresh_token:this.refreshToken}):await n.loginByJwt({jwt:await this.profile.getVerifyHubLoginJwt(this,e),target:this.getAuthTarget()}):await n.loginByJwt({jwt:e,target:this.getAuthTarget()});this.sessionToken=Vi(r.session_token),this.refreshToken=Vi(r.refresh_token),this.validateSessionToken()}async ensureSessionTokenReady(){if(this.usesBrowserSessionRefresh()){const e=await this.ensureBrowserSessionToken();return e&&this.startAutoRenewIfNeeded(),e}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(!Li())return;if("AppService"!==this.config.runtimeType)return;const e=Ui(),t=t=>{const n=Vi(e[t]);if(!n)throw new Error(`${t} is required for AppService runtime`);return n},n=t(Ti),r=vi(t(Ri)),s=t(Ii),i=t(Ci),o=t(Oi),a=Si(s);if(!(await Wi("node:path")).isAbsolute(o))throw new Error(`${Oi} must be an absolute path`);if(Ai(n)!==r||a.appId!==r||a.ownerUserId!==i||ki(r,i)!==s)throw new Error("AppService identity environment variables are inconsistent");const c=Vi(this.config.appId),l=Vi(this.config.appDid),u=Vi(this.config.appInstanceId),h=this.getOwnerUserId(),d=Vi(this.config.dataDir);if(c&&c!==r)throw new Error(`runtime appId ${c} does not match ${Ri} ${r}`);if(l&&l!==n)throw new Error(`runtime appDid ${l} does not match ${Ti} ${n}`);if(u&&u!==s)throw new Error(`runtime appInstanceId ${u} does not match ${Ii} ${s}`);if(h&&h!==i)throw new Error(`runtime ownerUserId ${h} does not match ${Ci} ${i}`);if(d&&d!==o)throw new Error(`runtime dataDir ${d} does not match ${Oi} ${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(!Li())return;if(Vi(this.config.zoneHost))return;const e=await this.getPrivateKeySearchRoots(),t=await this.tryResolveZoneHostFromSearchRoots(e);t&&(this.config.zoneHost=t)}validateSessionToken(){if(!this.sessionToken)return;const e=Hi(this.sessionToken);if("AppService"===this.config.runtimeType&&!e)throw new Error("AppService session token must be a JWT with identity claims");const t="string"==typeof(null==e?void 0:e.appid)?e.appid:"string"==typeof(null==e?void 0:e.aud)?e.aud:null;if(t&&t!==this.config.appId)throw new Error(`session token appid mismatch: ${t} != ${this.config.appId}`);if("AppService"===this.config.runtimeType&&e){const t=this.getAppInstanceId();if(!t||e.app_instance_id!==t)throw new Error(`session token app_instance_id mismatch: ${String(e.app_instance_id)} != ${String(t)}`);const n=this.getOwnerUserId();if(!n||e.app_owner_user_id!==n)throw new Error(`session token app_owner_user_id mismatch: ${String(e.app_owner_user_id)} != ${String(n)}`)}}async ensureBrowserSessionToken(){const e=Hi(this.sessionToken);return this.sessionToken&&e&&!this.needsRenew(e)?this.sessionToken:this.refreshBrowserSessionToken()}storeBrowserIdentity(e){if(!Mi())return;const t=Qn(Mn.getBrowserIdentityRaw());t&&Jn(t)!==Jn(e)&&Mn.clearBrowserUserInfo(),Mn.saveBrowserIdentity(e),"account"===e.kind?Mn.saveBrowserUserInfo({user_name:e.show_name||e.user_id,user_id:e.user_id,user_type:e.user_type}):Mn.clearBrowserUserInfo()}async getCurrentIdentity(){var e;const t=await this.ensureSessionTokenReady();if(!t||!Mi())return $n;const n=Qn(Mn.getBrowserIdentityRaw()),r=null==(e=Hi(t))?void 0:e.sub,s="account"===(null==n?void 0:n.kind)?n.user_id:"external"===(null==n?void 0:n.kind)?n.did:null;return n&&r&&s===r?n:$n}async refreshBrowserSession(){return await this.refreshBrowserSessionToken()&&Mi()?Mn.getBrowserUserInfo():null}async logoutBrowserSSO(){if(("Browser"===this.config.runtimeType||"AppRuntime"===this.config.runtimeType)&&Fi())try{const e=await fetch("/sso_logout",{method:"POST",credentials:"include",cache:"no-store",keepalive:!0});e.ok||console.warn("BuckyOS browser sso_logout failed:",e.status)}catch(e){console.warn("BuckyOS browser sso_logout failed:",e)}}async refreshBrowserSessionToken(){if(this.browserRefreshPromise)return this.browserRefreshPromise;const e=this.authStateRevision,t=this.requestBrowserSessionToken(e);this.browserRefreshPromise=t;try{return await t}finally{this.browserRefreshPromise===t&&(this.browserRefreshPromise=null)}}async requestBrowserSessionToken(e){if(!Fi())return this.sessionToken;try{const t=await fetch("/sso_refresh",{method:"POST",credentials:"include",cache:"no-store"});if(!t.ok)return e===this.authStateRevision&&(this.sessionToken=null,401===t.status&&Mi()&&(Mn.clearBrowserIdentity(),Mn.clearBrowserUserInfo())),null;const n=await t.json(),r=Vi("string"==typeof n.session_token?n.session_token:null),s=Qn(n.identity);return r&&s&&"anonymous"!==s.kind?e!==this.authStateRevision?null:(this.sessionToken=r,this.refreshToken=null,this.storeBrowserIdentity(s),this.validateSessionToken(),this.sessionToken):(e===this.authStateRevision&&(this.sessionToken=null),null)}catch(t){return console.warn("BuckyOS browser sso_refresh failed:",t),e===this.authStateRevision&&(this.sessionToken=null),null}}usesBrowserSessionRefresh(){return"Browser"===this.config.runtimeType||"AppRuntime"===this.config.runtimeType}needsRenew(e){if(e.iss&&"verify-hub"!==e.iss)return!0;if("number"!=typeof e.exp)return!1;return Math.floor(Date.now()/1e3)>=e.exp-30}startAutoRenewIfNeeded(){const e=this.usesBrowserSessionRefresh();if(!e&&!this.profile.supportsManagedSessionRenewal()||!1===this.config.autoRenew)return;if(this.renewTimer)return;const t=this.config.renewIntervalMs??5e3,n=async()=>{try{if(e){await this.ensureBrowserSessionToken()||this.stopAutoRenew()}else await this.renewTokenFromVerifyHub()}catch(t){console.warn("BuckyOS token renew failed:",t)}};this.renewTimer=setInterval((()=>{n()}),t),n()}loadAppServiceSessionTokenFromEnv(){const e=Vi(Ui()[xi]);if(e)return e;throw new Error(`${xi} is required for AppService runtime`)}loadAppClientSessionTokenFromEnv(){return Vi(Ui().BUCKYOS_APPCLIENT_SESSION_TOKEN)}async createAppClientSessionToken(){if(!Li())throw new Error("AppClient mode requires Node.js");const e=await this.loadLocalSigningMaterial(),t=Math.floor(Date.now()/1e3),n={token_type:"Normal",appid:this.config.appId,jti:String(t),session:t,sub:e.subject,userid:e.subject,iss:e.issuer,exp:t+900,extra:{}};return this.signJwtWithEd25519({alg:"EdDSA",kid:e.issuer},n,e.keyPem)}async loadLocalSigningMaterial(){await Wi("node:fs/promises");const e=await Wi("node:path"),t=this.getOwnerUserId();if(!t){const t=await this.getBuckyOSEtcDir(),n=await this.readDeviceNameFromNodeIdentityPath(e.join(t,"node_identity.json"));if(!n)throw new Error(`failed to resolve userid from ${e.join(t,"node_identity.json")} device_mini_doc_jwt`);const r=await this.readPemFile(e.join(t,"node_private_key.pem"));if(!r)throw new Error(`failed to load node_private_key.pem from ${t}`);return this.config.userid=n,this.config.ownerUserId=n,{keyPem:r,issuer:n,subject:n,sourcePath:e.join(t,"node_private_key.pem")}}const n=await this.getPrivateKeySearchRoots(),r=await this.tryLoadDeviceSigningMaterial(t,n);if(r)return r;const s=await this.tryLoadUserSigningMaterial(t,n);if(s)return s;throw new Error(`failed to find AppClient private key for userid=${t} in search roots: ${n.join(", ")}`)}async getPrivateKeySearchRoots(){var e;const t=Ui(),n=await Wi("node:path"),r=await Wi("node:os"),s=[];for(const c of this.config.privateKeySearchPaths??[]){const e=Vi(c);e&&s.push(e)}const i=Vi(t.BUCKYOS_APP_CLIENT_DIR);i&&s.push(i);const o=Vi(t.HOME)??Vi(t.USERPROFILE)??Vi(null==(e=r.homedir)?void 0:e.call(r));o&&(s.push(n.join(o,".buckyos")),s.push(n.join(o,".buckycli")));const a=Vi(this.config.rootDir)??Vi(t.BUCKYOS_ROOT)??"/opt/buckyos";return s.push(a),s.push(n.join(a,"etc")),Array.from(new Set(s))}async getBuckyOSRootDir(){const e=Ui();return Vi(this.config.rootDir)??Vi(e.BUCKYOS_ROOT)??"/opt/buckyos"}async getBuckyOSEtcDir(){return(await Wi("node:path")).join(await this.getBuckyOSRootDir(),"etc")}async readPemFile(e){const t=await Wi("node:fs/promises");try{return(await t.readFile(e,"utf8")).trim()||null}catch{return null}}async readNodeIdentityMetadata(e){const t=await Wi("node:fs/promises");try{const n=await t.readFile(e,"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(e){const t="string"==typeof e.device_name?e.device_name.trim():"";if(t)return t;const n=Hi("string"==typeof e.device_mini_doc_jwt?e.device_mini_doc_jwt:null),r="string"==typeof(null==n?void 0:n.n)?n.n.trim():"";if(r)return r;const s=Hi("string"==typeof e.device_doc_jwt?e.device_doc_jwt:null);for(const i of["name","sub"]){const e=null==s?void 0:s[i],t="string"==typeof e?e.trim():"";if(t)return t}return null}async readDeviceNameFromNodeIdentityPath(e){const t=await this.readNodeIdentityMetadata(e);return(null==t?void 0:t.deviceName)??null}async tryLoadDeviceSigningMaterial(e,t){const n=await Wi("node:path"),r=[await this.getBuckyOSEtcDir(),...t.filter((e=>!e.endsWith(".pem")))];for(const s of Array.from(new Set(r))){const t=await this.readNodeIdentityMetadata(n.join(s,"node_identity.json")),r=(null==t?void 0:t.deviceName)??null;if(r&&r===e)for(const e of await this.deviceKeyPathCandidates(s,(null==t?void 0:t.deviceDid)??null)){const t=await this.readPemFile(e);if(t)return{keyPem:t,issuer:r,subject:r,sourcePath:e}}}return null}async deviceKeyPathCandidates(e,t){const n=await Wi("node:path"),r=[];if(t)try{const s=Mn.DID.fromStr(t).toFilename(),i="authentication.private.pem";r.push(n.join(e,"security",s,i));const o=Ui(),a=Vi(o.BUCKYOS_SECURITY_ROOT)??n.join(Vi(o.BUCKYOS_ROOT)??"/opt/buckyos","security");r.push(n.join(a,s,i))}catch{}return r.push(n.join(e,"node_private_key.pem")),r}async tryLoadUserSigningMaterial(e,t){var n;const r=await Wi("node:fs/promises"),s=await Wi("node:path");for(const i of t){const t=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!==e)continue;const c=await this.readPemFile(t);if(!c)continue;return{keyPem:c,issuer:e,subject:e,sourcePath:t}}catch{}}return null}async tryResolveDeviceNameFromSearchRoots(e){const t=await Wi("node:path"),n=Ui(),r=Vi(n.BUCKYOS_THIS_DEVICE_NAME);if(r)return r;for(const s of["BUCKYOS_THIS_DEVICE","BUCKYOS_THIS_DEVICE_INFO"]){const e=Vi(n[s]);if(e)try{const t=JSON.parse(e);if("string"==typeof t.name&&t.name.trim().length>0)return t.name.trim()}catch{}}for(const s of e){const e=t.join(s,"node_identity.json"),n=await this.readDeviceNameFromNodeIdentityPath(e);if(n)return n}return null}async tryResolveZoneHostFromSearchRoots(e){var t;const n=await Wi("node:fs/promises"),r=await Wi("node:path"),s=Vi(Ui().BUCKYOS_ZONE_HOST);if(s)return s;for(const i of e){const e=r.join(i,"node_identity.json"),t=await this.readNodeIdentityMetadata(e);if(t){if(t.zoneName)return t.zoneName;if(t.zoneDid)return qi(t.zoneDid)}}for(const i of e){const e=r.join(i,"user_config.json");try{const r=await n.readFile(e,"utf8"),s=Mn.parseBuckyOSOwnerDocument(JSON.parse(r)),i=qi(null==(t=null==s?void 0:s.binded_zone_list)?void 0:t[0]);if(!i)continue;return i}catch{}}return null}getMySettingsPath(){return this.profile.getMySettingsPath(this)}getConfiguredSystemConfigServiceUrl(){return Vi(this.config.systemConfigServiceUrl)}resolveAppServiceGatewayHost(){return Vi(Ui().BUCKYOS_HOST_GATEWAY)??"host.docker.internal"}async signJwtWithEd25519(e,t,n){const r=await Wi("node:crypto"),s=ji(),i=`${Gi(JSON.stringify(e))}.${Gi(JSON.stringify(t))}`;return`${i}.${Gi(r.sign(null,s.from(i,"utf8"),r.createPrivateKey({key:n,format:"pem"})))}`}}const eo=1048576;class to extends Error{constructor(e,t){super(t),this.name="KEventProtocolError",this.code=e}}const no=async(e,t)=>{if("function"!=typeof fetch)throw new Error("fetch is not available in this runtime");return fetch(e,t)};function ro(){var e;const t=globalThis.process;return Boolean(null==(e=null==t?void 0:t.versions)?void 0:e.node)}function so(e){const t=(Array.isArray(e)?e:[e]).map((e=>"string"==typeof e?e.trim():"")).filter((e=>e.length>0));if(0===t.length)throw new Error("kevent patterns must not be empty");for(const n of t)if(!n.startsWith("/"))throw new Error(`kevent only supports global patterns: ${n}`);return t}function io(e,t){return(null==t?void 0:t.aborted)?Promise.reject(new Error("Operation aborted")):new Promise(((n,r)=>{const s=setTimeout((()=>{o(),n()}),e),i=()=>{clearTimeout(s),o(),r(new Error("Operation aborted"))},o=()=>{t&&t.removeEventListener("abort",i)};t&&t.addEventListener("abort",i,{once:!0})}))}function oo(e){return e instanceof Error?e.message:String(e)}function ao(e){if("ok"===e.status)return e;throw new to(e.code||"INTERNAL",e.message||"Unknown kevent error")}function co(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new Error("Invalid kevent event payload");const t=e;if("string"!=typeof t.eventid||"string"!=typeof t.source_node||"number"!=typeof t.source_pid||"number"!=typeof t.timestamp)throw new Error("Invalid kevent event payload");return{eventid:t.eventid,source_node:t.source_node,source_pid:t.source_pid,ingress_node:"string"==typeof t.ingress_node?t.ingress_node:null,timestamp:t.timestamp,data:"data"in t?t.data:null}}class lo{constructor(){this.items=[],this.waiters=[],this.closed=!1}push(e){if(this.closed)return;const t=this.waiters.shift();if(t)return t.timeout&&clearTimeout(t.timeout),void t.resolve(e);this.items.push(e)}async shift(e){return this.items.length>0?this.items.shift()??null:this.closed||0===e?null:new Promise((t=>{const n={resolve:e=>{r(),t(e)},timeout:null},r=()=>{n.timeout&&(clearTimeout(n.timeout),n.timeout=null);const e=this.waiters.indexOf(n);e>=0&&this.waiters.splice(e,1)};"number"==typeof e&&e>0&&(n.timeout=setTimeout((()=>{r(),t(null)}),e)),this.waiters.push(n)}))}close(){if(!this.closed)for(this.closed=!0;this.waiters.length>0;){const e=this.waiters.shift();e&&(e.timeout&&clearTimeout(e.timeout),e.resolve(null))}}}class uo{constructor(){this.queue=new lo,this.closed=!1,this.closePromise=null}async pullEvent(e){return this.queue.shift(e)}async pull_event(e){return this.pullEvent(e)}enqueue(e){this.queue.push(e)}isClosed(){return this.closed}markClosed(){this.closed=!0,this.queue.close()}async close(){return this.closePromise||(this.markClosed(),this.closePromise=this.closeTransport().catch((e=>{console.warn("kevent reader close failed:",e)})).then((()=>{}))),this.closePromise}}class ho extends uo{constructor(e,t,n,r,s,i){super(),this.streamUrl=e,this.patterns=t,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 e={"Content-Type":"application/json"};if(this.sessionTokenProvider){const t=await this.sessionTokenProvider();"string"==typeof t&&t.trim().length>0&&(e.Authorization=`Bearer ${t.trim()}`)}const t=await this.fetcher(this.streamUrl,{method:"POST",headers:e,body:JSON.stringify({patterns:this.patterns,keepalive_ms:this.keepaliveMs}),cache:"no-store",credentials:"include",signal:this.controller.signal});if(!t.ok){let e="";try{e=await t.text()}catch{e=""}throw new Error(`kevent stream request failed: ${t.status}${e?` ${e}`:""}`)}if(!t.body)throw new Error("kevent stream response missing body");let n=!1,r=null,s=null;const i=new Promise(((e,t)=>{r=e,s=t}));this.streamTask=this.consumeStream(t.body,(e=>{if("ack"===e.type)return n=!0,void(null==r||r());if("event"!==e.type){if("error"===e.type){const t=new Error(e.error||"kevent stream error");n?console.warn("kevent stream error:",t.message):null==s||s(t)}}else this.enqueue(co(e.event))})).then((()=>{n||null==s||s(new Error("kevent stream closed before ack"))})).catch((e=>{n?this.controller.signal.aborted||console.warn("kevent browser stream stopped with error:",e):null==s||s(e instanceof Error?e:new Error(oo(e)))})).finally((()=>{this.markClosed()})),await i}async consumeStream(e,t){const n=e.getReader(),r=new TextDecoder;let s="";try{for(;!this.controller.signal.aborted;){const{value:e,done:i}=await n.read();if(i)break;s+=r.decode(e,{stream:!0}),s=this.processFrameBuffer(s,t)}s+=r.decode(),s=this.processFrameBuffer(s,t),s.trim().length>0&&this.handleFrameLine(s,t)}finally{try{await n.cancel()}catch{}}}processFrameBuffer(e,t){let n=e;for(;;){const e=n.indexOf("\n");if(e<0)return n;const r=n.slice(0,e);n=n.slice(e+1),this.handleFrameLine(r,t)}}handleFrameLine(e,t){const n=e.trim();if(!n)return;t(JSON.parse(n))}async closeTransport(){if(this.controller.abort(),this.streamTask)try{await this.streamTask}catch(e){this.controller.signal.aborted||console.warn("kevent browser stream stopped with error:",e)}}}class fo{constructor(e,t,n,r){this.host=e,this.port=t,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(e){const t=this.serial.then((()=>this.callInternal(e)));return this.serial=t.then((()=>{}),(()=>{})),t}async close(){if(this.closed=!0,this.rejectAllPending(new Error("kevent native connection closed")),this.socket){const e=this.socket;this.socket=null,e.end()}}async callInternal(e){if(this.closed)throw new Error("kevent native connection is closed");await this.ensureConnected();const t=this.socket;if(!t)throw new Error("kevent native socket is not connected");const n=(new TextEncoder).encode(JSON.stringify(e));if(0===n.length||n.length>eo)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(((e,n)=>{const s={resolve:e,reject:n};this.pending.push(s),t.write(r,(e=>{if(!e)return;const t=this.pending.indexOf(s);t>=0&&this.pending.splice(t,1),n(e instanceof Error?e:new Error(oo(e)))}))}))}async ensureConnected(){this.socket||(this.connectPromise||(this.connectPromise=this.connect().finally((()=>{this.connectPromise=null}))),await this.connectPromise)}async connect(){const e=await this.connector(this.host,this.port,this.connectTimeoutMs);this.socket=e,"function"==typeof e.setNoDelay&&e.setNoDelay(!0),e.on("data",(e=>{try{this.handleSocketData(function(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);throw new Error("Unsupported socket data chunk")}(e))}catch(t){this.handleSocketFailure(t instanceof Error?t:new Error(oo(t)))}})),e.once("end",(()=>{this.handleSocketFailure(new Error("kevent native socket ended"))})),e.once("close",(()=>{this.handleSocketFailure(new Error("kevent native socket closed"))})),e.once("error",(e=>{this.handleSocketFailure(e)}))}handleSocketData(e){for(this.readBuffer=function(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}(this.readBuffer,e);this.readBuffer.length>=4;){const e=new DataView(this.readBuffer.buffer,this.readBuffer.byteOffset,this.readBuffer.byteLength).getUint32(0);if(0===e||e>eo)throw new Error(`invalid kevent native frame length: ${e}`);if(this.readBuffer.length<4+e)return;const t=this.readBuffer.slice(4,4+e);this.readBuffer=this.readBuffer.slice(4+e);const n=JSON.parse((new TextDecoder).decode(t)),r=this.pending.shift();r&&r.resolve(n)}}handleSocketFailure(e){if(this.socket){const t=this.socket;this.socket=null;try{t.destroy(e)}catch{}}this.closed||this.rejectAllPending(e)}rejectAllPending(e){for(;this.pending.length>0;){const t=this.pending.shift();null==t||t.reject(e)}}}class po extends uo{constructor(e,t){super(),this.client=e,this.readerId=t}static async create(e,t){const n=new fo(t.nativeHost,t.nativePort,t.nativeConnectTimeoutMs,t.nativeConnector),r=`ts_kevent_${Date.now()}_${Math.random().toString(36).slice(2,10)}`;try{return ao(await n.call({op:"register_reader",reader_id:r,patterns:e})),new po(n,r)}catch(s){throw await n.close(),s}}async pullEvent(e){if(this.isClosed())return null;const t=ao(await this.client.call({op:"pull_event",reader_id:this.readerId,timeout_ms:"number"==typeof e?Math.max(0,Math.floor(e)):void 0}));return t.event?co(t.event):null}async closeTransport(){try{ao(await this.client.call({op:"unregister_reader",reader_id:this.readerId}))}catch(e){e instanceof Error&&/closed/i.test(e.message)||console.warn("kevent unregister failed:",e)}finally{await this.client.close()}}}async function go(e,t,n){if(!ro())throw new Error("native kevent requires Node.js");const r=await async function(e){return ro()&&"function"==typeof require?require(e):Function("name","return import(name)")(e)}("node:net");return new Promise(((s,i)=>{const o=r.createConnection({host:e,port:t});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=e=>{if(!a){a=!0,h();try{o.destroy(e)}catch{}i(e)}},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 mo{constructor(e){this.mode=e.mode,this.streamUrl=`${(e.streamUrl??"/kapi/kevent").replace(/\/+$/,"")}/stream`,this.nativeHost=e.nativeHost??"127.0.0.1",this.nativePort=e.nativePort??3183,this.nativeConnectTimeoutMs=e.nativeConnectTimeoutMs??5e3,this.fetcher=e.fetcher??no,this.sessionTokenProvider=e.sessionTokenProvider??null,this.nativeConnector=e.nativeConnector??go}async createEventReader(e,t={}){const n=so(e);if("browser"===this.mode){const e=new ho(this.streamUrl,n,"number"!=typeof(r=t.keepaliveMs)||!Number.isFinite(r)||r<=0?15e3:Math.floor(r),this.fetcher,this.sessionTokenProvider,t.signal);try{return await e.waitUntilReady(),e}catch(s){throw await e.close(),s}}var r;return po.create(n,{nativeHost:this.nativeHost,nativePort:this.nativePort,nativeConnectTimeoutMs:this.nativeConnectTimeoutMs,nativeConnector:this.nativeConnector})}async create_event_reader(e,t={}){return this.createEventReader(e,t)}async subscribe(e,t,n={}){const r=so(e),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 t(n)}catch(e){console.error("kevent callback failed:",e)}}}catch(e){a||s.signal.aborted||console.warn("kevent subscription disconnected, will retry:",e)}finally{const e=o;o=null,e&&await e.close()}if(a||s.signal.aborted)break;try{await io(i,s.signal)}catch{break}}})();return{close:async()=>{if(a)return;a=!0,s.abort();const e=o;o=null,e&&await e.close(),await c.catch((()=>{}))}}}}const yo={runtime:null};function wo(){if("undefined"==typeof window)return null;const e=window.BuckyApi;return e&&"object"==typeof e?e:null}async function bo(){const e=wo(),t=null==e?void 0:e.getCurrentUser;if("function"!=typeof t)return null;const n=await t.call(e);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 _o(e,t=null){const n=wo(),r=null==n?void 0:n.resolve_did;if("function"!=typeof r)return null;const s=await r.call(n,e,t);return 0===(null==s?void 0:s.code)&&function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"json"===t.type&&Object.prototype.hasOwnProperty.call(t,"value")||"jwt"===t.type&&"string"==typeof t.jwt}(s.data)?s.data:(console.error("BuckyApi.resolve_did failed: ",null==s?void 0:s.message),null)}function Ao(){return"undefined"!=typeof window}function vo(){const e=globalThis.process;return(null==e?void 0:e.env)??{}}function Eo(e){if("string"!=typeof e)return null;const t=e.trim();return t.length>0?t:null}function ko(){return"undefined"!=typeof localStorage}function So(e){return e?e.split(/[./]/).map((e=>e.trim())).filter((e=>e.length>0)):[]}function To(){return Eo(vo().BUCKYOS_APP_INSTANCE_ID)?Ni.AppService:Ni.AppClient}function Ro(){var e;return(null==(e=yo.runtime)?void 0:e.getConfig().runtimeType)??function(){var e;if("undefined"!=typeof window)return window.BuckyApi?Ni.AppRuntime:Ni.Browser;const t=globalThis.process;return(null==(e=null==t?void 0:t.versions)?void 0:e.node)?Ni.NodeJS:Ni.Unknown}()}function Io(){var e;const t=yo.runtime;return t?function(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost";return new URL(e,t).origin}catch{return null}}(t.getSystemConfigServiceURL()):"undefined"!=typeof window&&(null==(e=window.location)?void 0:e.origin)?window.location.origin:null}async function Co(){const e=yo.runtime;return e?e.ensureSessionTokenReady():null}class Oo{constructor(e){this.currentRuntime=null,this.currentAccountInfo=null,this.currentKEventClient=null,this.target=e}async initBuckyOS(e="",t=null){var n;const r=this.buildRuntimeConfig(e,t);if("node"!==this.target&&Ao()&&!t){localStorage.removeItem("zone_host_name");let t=localStorage.getItem("zone_host_name_v2");t||(t=await this.tryGetZoneHostName(e,window.location.host,r.defaultProtocol),localStorage.setItem("zone_host_name_v2",t)),r.zoneHost=t}var s;null==(n=this.currentRuntime)||n.stopAutoRenew(),this.currentKEventClient=null,this.currentAccountInfo=null,this.currentRuntime=new Xi(r),await this.currentRuntime.initialize(),s=this.currentRuntime,yo.runtime=s,this.syncCurrentAccountInfoFromRuntime()}getBuckyOSConfig(){var e;return(null==(e=this.currentRuntime)?void 0:e.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 e;return(null==(e=this.currentRuntime)?void 0:e.getAppDid())??null}getAppInstanceId(){var e;return(null==(e=this.currentRuntime)?void 0:e.getAppInstanceId())??null}getAppDataDir(){var e;return(null==(e=this.currentRuntime)?void 0:e.getDataDir())??null}attachEvent(e,t){}removeEvent(e){}getKEventClient(){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");if(this.currentKEventClient)return this.currentKEventClient;const e=this.currentRuntime.getConfig().runtimeType,t=e===Ni.Browser||e===Ni.AppRuntime?"browser":"native";return this.currentKEventClient=new mo({mode:t,streamUrl:this.currentRuntime.getZoneServiceURL("kevent"),sessionTokenProvider:this.currentRuntime.ensureSessionTokenReady.bind(this.currentRuntime)}),this.currentKEventClient}async createEventReader(e,t={}){return this.getKEventClient().createEventReader(e,t)}async create_event_reader(e,t={}){return this.createEventReader(e,t)}async subscribeKEvent(e,t,n={}){return this.getKEventClient().subscribe(e,t,n)}async getCurrentIdentity(){if(null==this.currentRuntime)return console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),$n;const e=this.currentRuntime.getConfig().runtimeType;return e!==Ni.Browser&&e!==Ni.AppRuntime?$n:this.currentRuntime.getCurrentIdentity()}async getAccountInfo(){if(null==this.currentRuntime)return console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),null;this.syncCurrentAccountInfoFromRuntime();const e=this.currentRuntime.getConfig().runtimeType;if(e!==Ni.Browser&&e!==Ni.AppRuntime)return this.currentAccountInfo;const t=await this.currentRuntime.ensureSessionTokenReady(),n=ko()?Mn.getBrowserUserInfo():null;return t&&n?(this.currentAccountInfo={user_name:n.user_name,user_id:n.user_id,user_type:n.user_type,session_token:t,refresh_token:void 0},this.currentAccountInfo):(this.currentAccountInfo=null,null)}async loginByPassword(e,t,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=sr(a);if(c!==o)throw new Error(`auth target appid mismatch: ${c} != ${o}`);const l=Date.now(),u=Mn.hashPassword(e,t,l);ko()&&localStorage.removeItem(`buckyos.account_info.${o}`);try{const t=this.getVerifyHubClient();t.setSeq(l);const n=await t.loginByPassword({username:e,password:u,target:a,login_nonce:l,source_url:"undefined"!=typeof window?window.location.href:void 0}),r=ir.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 ko()&&(Mn.saveLocalAccountInfo(o,c),Mn.clearBrowserIdentity(),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 e=this.currentRuntime;return null==e?(console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),null):(await e.login(),this.syncCurrentAccountInfoFromRuntime(),this.currentAccountInfo)}async loginByBrowserSSO(){if(null==this.currentRuntime)return void console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first");const e=this.getAppId();if(null==e)return void console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first");ko()&&Mn.cleanLocalAccountInfo(e);const t=this.getZoneHostName();if(null!=t)try{const e=new Vn(t);await e.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(e=!0){if(null==this.currentRuntime)return void console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first");const t=this.getAppId();null!=t?(e&&this.currentRuntime.logoutBrowserSSO(),e&&ko()&&Mn.cleanLocalAccountInfo(t),this.currentAccountInfo=null,this.currentKEventClient=null,this.currentRuntime.clearAuthState()):console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first")}async getAppSetting(e=null){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return function(e,t){const n=So(t);if(0===n.length)return e;let r=e;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(),e)}async setAppSetting(e=null,t){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");const n=await this.currentRuntime.getMySettings(),r=function(e,t,n){const r=So(t);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(e)?{}:{...e};let i=s;for(let o=0;o<r.length-1;o+=1){const e=r[o],t=i[e],n=t&&"object"==typeof t&&!Array.isArray(t)?{...t}:{};i[e]=n,i=n}return i[r[r.length-1]]=n,s}(n&&"object"==typeof n&&!Array.isArray(n)?{...n}:{},e,function(e){try{return JSON.parse(e)}catch{return e}}(t));await this.currentRuntime.updateAllMySettings(r)}getCurrentWalletUser(){if("undefined"==typeof window)throw new Error("BuckyApi is only available in browser runtime");return bo()}resolve_did(e,t=null){if("undefined"==typeof window)throw new Error("BuckyApi is only available in browser runtime");return _o(e,t)}walletSignWithActiveDid(e){if("undefined"==typeof window)throw new Error("BuckyApi is only available in browser runtime");return(async()=>{var t,n;const r=await window.BuckyApi.signJsonWithActiveDid(e);return 0===r.code?{signatures:Array.isArray(null==(t=r.data)?void 0:t.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(e){if("undefined"==typeof window)throw new Error("openExternalUrl is only available in browser runtime");const t=window.BuckyApi;"function"!=typeof(null==t?void 0:t.openExternalUrl)?window.open(e,"_blank","noopener,noreferrer"):await t.openExternalUrl(e)}getZoneHostName(){return null==this.currentRuntime?(console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),null):this.currentRuntime.getZoneHostName()}getZoneServiceURL(e){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return this.currentRuntime.getZoneServiceURL(e)}getServiceRpcClient(e){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(e)}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()}getAiWorkspaceClient(){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return this.currentRuntime.getAiWorkspaceClient()}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(e,t){if(t){let n=t.runtimeType;return n===Ni.NodeJS&&"browser"!==this.target&&(n=To()),{...Bi,...t,appId:t.appId||e,runtimeType:n}}return"browser"===this.target?{...Bi,appId:e,runtimeType:this.detectEnvironmentRuntimeType(),defaultProtocol:"undefined"!=typeof window?window.location.protocol+"//":"http://"}:"node"===this.target?{...Bi,appId:e,runtimeType:To(),defaultProtocol:"https://",zoneHost:Eo(vo().BUCKYOS_ZONE_HOST)??""}:Ao()?{...Bi,appId:e,runtimeType:this.detectEnvironmentRuntimeType(),defaultProtocol:window.location.protocol+"//"}:{...Bi,appId:e,runtimeType:To(),defaultProtocol:"https://",zoneHost:Eo(vo().BUCKYOS_ZONE_HOST)??""}}async tryGetZoneHostName(e,t,n){const r=await this.fetchZoneHostFromIdentifierDoc(n+t+"/1.0/identifiers/self");if(r)return r;const s=t.split(".").slice(1).join(".");if(!s)return t;const i=await this.fetchZoneHostFromIdentifierDoc(n+s+"/1.0/identifiers/self");return i||t}async fetchZoneHostFromIdentifierDoc(e){try{const t=await fetch(e);if(200!==t.status)return null;const n=await t.json(),r="string"==typeof n.hostname?n.hostname.trim():"";if(r.length>0)return r;if("string"==typeof n.id){const e=n.id.match(/^did:web:([^/?#]+)/);if(e&&e[1])return e[1]}return null}catch{return null}}syncCurrentAccountInfoFromRuntime(){if(null==this.currentRuntime)return;const e=this.currentRuntime.getSessionToken();if(!e)return;const t=Hi(e),n="string"==typeof(null==t?void 0:t.sub)?t.sub:"string"==typeof(null==t?void 0:t.userid)?t.userid:this.currentRuntime.getOwnerUserId()??"root",r="string"==typeof(null==t?void 0:t.user_type)?t.user_type:this.currentRuntime.getConfig().runtimeType===Ni.AppService?"service":void 0;this.currentAccountInfo={user_name:n,user_id:n,user_type:r,session_token:e,refresh_token:this.currentRuntime.getRefreshToken()??void 0}}usesRuntimeManagedSession(){if(null==this.currentRuntime)return!1;const e=this.currentRuntime.getConfig().runtimeType;return e===Ni.AppClient||e===Ni.AppService}detectEnvironmentRuntimeType(){var e,t;if("browser"===this.target)return"undefined"!=typeof window&&window.BuckyApi?Ni.AppRuntime:"undefined"!=typeof window?Ni.Browser:Ni.Unknown;if("node"===this.target){const t=globalThis.process;return(null==(e=null==t?void 0:t.versions)?void 0:e.node)?To():Ni.Unknown}if("undefined"!=typeof window)return window.BuckyApi?Ni.AppRuntime:Ni.Browser;const n=globalThis.process;return(null==(t=null==n?void 0:n.versions)?void 0:t.node)?Ni.NodeJS:Ni.Unknown}}const xo="/kapi/bns",No="/kapi/bns-indexer",Po="did:bns:",Do="name.query_state",Bo="name.resolve_owner",Uo="authority.get_set",Lo="authority.get_key",Mo="document.resolve",Fo="document.get_version",jo="name.query_by_addr",Go="tx.query_state",Ho="tx.submit_raw",Vo="events.list",qo="checkpoint.latest",Wo={transport:"RPC_TRANSPORT_ERROR",serialization:"SERIALIZATION_ERROR",invalid_response:"INVALID_RESPONSE",timeout:"TX_WAIT_TIMEOUT"};class zo extends Error{constructor(e,t,n=null){super(t),this.name="BnsClientError",this.kind=e,this.info=n}get code(){var e;return"registry"===this.kind?(null==(e=this.info)?void 0:e.code)??"UNKNOWN_BNS_ERROR":Wo[this.kind]}isRegistryCode(e){return"registry"===this.kind&&this.code===e}static registry(e){return new zo("registry",`${e.code}: ${e.message}`,e)}static registryCode(e,t,n={}){return zo.registry({code:e,message:t,name:null,doc_type:null,expected:null,actual:null,...n})}}class Ko extends Error{constructor(e,t){super(`${e}: ${t}`),this.path=e,this.reason=t,this.name="BnsDecodeError"}}function $o(e,t){throw new Ko(e,t)}const Qo=(e,t)=>"string"==typeof e?e:$o(t,"expected string"),Jo=(e,t)=>"boolean"==typeof e?e:$o(t,"expected boolean"),Yo=(e,t)=>"number"==typeof e&&Number.isInteger(e)&&e>=0?e:$o(t,"expected u64"),Zo=(e,t)=>"number"==typeof e&&Number.isInteger(e)&&e>=0&&e<=4294967295?e:$o(t,"expected u32"),Xo=(e,t)=>{Array.isArray(e)||$o(t,"expected byte array");for(let n=0;n<e.length;n++){const r=e[n];("number"!=typeof r||!Number.isInteger(r)||r<0||r>255)&&$o(`${t}[${n}]`,"expected u8")}return e};function ea(...e){return(t,n)=>"string"==typeof t&&e.includes(t)?t:$o(n,`expected one of ${e.join("|")}`)}function ta(e){return(t,n)=>(Array.isArray(t)||$o(n,"expected array"),t.map(((t,r)=>e(t,`${n}[${r}]`))))}function na(e,t){const n=(t,n)=>e(t,n);return n.onMissing=t,n}function ra(e){return na(((t,n)=>null===t?null:e(t,n)),(()=>null))}const sa=na(Yo,(()=>0));function ia(e,t){const n=Object.keys(t);return(r,s)=>{(null===r||"object"!=typeof r||Array.isArray(r))&&$o(s,`expected ${e} object`);const i=r,o={};for(const e of n){const n=t[e],r=`${s}.${e}`,a=i[e];if(void 0===a&&!(e in i)){if(n.onMissing){o[e]=n.onMissing();continue}$o(r,"missing field")}o[e]=n(a,r)}return o}}const oa=ea("available","active","expired","released","tombstoned"),aa=ea("missing","active","revoked","expired","migrated","tombstoned"),ca=ea("none","alias","migrated_to","canonical"),la=ea("release_after_grace","tombstone_forever"),ua=ea("unset","chain_account","bns_name"),ha=ea("none","asset_owner_fallback","explicit_semantic_owner","parent_inherited"),da=ea("missing","active","revoked","expired"),fa=ea("not_found","pending","succeeded","reverted"),pa=ia("Principal",{kind:ua,value:Qo}),ga=ia("NameState",{name:Qo,asset_owner:Qo,semantic_owner:pa,effective_owner:pa,owner_source:ha,standard_transfer_enabled:Jo,status:oa,registered_at:Yo,expire_at:Yo,grace_until:Yo,updated_at:Yo,name_seq:Yo,owner_document_version:Yo,min_document_iat:sa,owner_policy_seq:sa,lineage_epoch:Yo,renewable:Jo,transferable:Jo,allow_delegated_subnames:Jo,namespace_policy_hash:Qo,payment_policy_hash:Qo,alias_state_hash:Qo}),ma=ia("OwnerResolution",{effective_owner:pa,source:ha,authority_root:Qo,authority_seq:Yo}),ya=ia("AuthoritySetState",{name:Qo,authority_seq:Yo,authority_root:Qo,active_key_count:Zo}),wa=ia("AuthorityKey",{kid:Qo,verification_method:Qo,key_data:Xo,purposes:Zo,valid_from:Yo,valid_until:Yo,status:da,metadata_hash:Qo}),ba=ia("DocumentRef",{storage_type:Qo,uri:Qo,inline_document:Xo,content_hash:Qo,schema:Qo,codec:Qo,extra_hash:Qo}),_a=ia("DocumentState",{name:Qo,doc_type:Qo,version:Yo,previous_version:Yo,status:aa,document:ba,controller:pa,beneficiary:pa,payment_target:Qo,valid_from:Yo,expire_at:Yo,revoked_at:Yo,controller_policy_hash:Qo,payment_policy_hash:Qo,split_policy_hash:Qo,price_policy_hash:Qo,rights_policy_hash:Qo,document_state_hash:Qo}),Aa=ia("ResolveResult",{name_state:ga,document_state:_a,owner:ma,effective_controller:pa,status:aa,alias_kind:ca,alias_target_did:Qo,proof_root:Qo}),va=ia("BnsNamePage",{names:ta(Qo),next_cursor:ra(Qo)}),Ea=ia("BnsTxState",{tx_hash:Qo,state:fa,block_number:ra(Yo),confirmations:Yo}),ka=ia("BnsSubmitRawTxResp",{tx_hash:Qo}),Sa=ia("LogCheckpoint",{log_root:Qo,last_seq:Yo,issued_at:Yo,issuer:pa,external_anchor:Qo}),Ta={name_registered:ia("name_registered",{name:Qo,asset_owner:Qo,expire_at:Yo,lineage_epoch:Yo,name_seq:Yo}),name_renewed:ia("name_renewed",{name:Qo,expire_at:Yo,name_seq:Yo}),name_asset_transferred:ia("name_asset_transferred",{name:Qo,old_asset_owner:Qo,new_asset_owner:Qo,standard_transfer:Jo,name_seq:Yo}),name_owner_updated:ia("name_owner_updated",{name:Qo,owner:pa,owner_source:ha,standard_transfer_enabled:Jo,name_seq:Yo}),authority_keys_updated:ia("authority_keys_updated",{name:Qo,authority_seq:Yo,authority_root:Qo}),name_released:ia("name_released",{name:Qo,mode:la,reason_hash:Qo,name_seq:Yo}),document_published:ia("document_published",{name:Qo,doc_type:Qo,version:Yo,content_hash:Qo,document_state_hash:Qo}),document_revoked:ia("document_revoked",{name:Qo,doc_type:Qo,previous_version:Yo,new_version:Yo,reason_hash:Qo}),owner_document_iat_floor_updated:ia("owner_document_iat_floor_updated",{name:Qo,previous_min_document_iat:Yo,new_min_document_iat:Yo,owner_policy_seq:Yo,name_seq:Yo,reason_hash:Qo}),controller_policy_updated:ia("controller_policy_updated",{name:Qo,policy_hash:Qo,name_seq:Yo}),namespace_policy_updated:ia("namespace_policy_updated",{name:Qo,allow_delegated_subnames:Jo,namespace_policy_hash:Qo,name_seq:Yo}),did_alias_set:ia("did_alias_set",{name:Qo,target_did:Qo,kind:ca,proof_hash:Qo,name_seq:Yo}),payment_target_updated:ia("payment_target_updated",{name:Qo,doc_type:Qo,payment_target:Qo,payment_policy_hash:Qo,version:Yo}),log_checkpoint_published:ia("log_checkpoint_published",{log_root:Qo,last_seq:Yo,issued_at:Yo,external_anchor:Qo})},Ra=ta(ia("EventLogRecord",{seq:Yo,event_type:Qo,observed_at:Yo,event_hash:Qo,previous_log_root:Qo,log_root:Qo,event:(e,t)=>{(null===e||"object"!=typeof e||Array.isArray(e))&&$o(t,"expected RegistryEvent object");const n=e;"string"!=typeof n.type&&$o(`${t}.type`,"expected string event tag");const r=Ta[n.type];return r||$o(`${t}.type`,`unknown event type \`${n.type}\``),"data"in n&&void 0!==n.data||$o(`${t}.data`,"missing field"),{type:n.type,data:r(n.data,`${t}.data`)}}})),Ia=ia("BnsRpcErrorInfo",{code:Qo,message:Qo,name:ra(Qo),doc_type:ra(Qo),expected:ra(Yo),actual:ra(Yo)});function Ca(e){const t=e.split("://"),n=t.length>1?t.slice(1).join("://"):e,r=n.indexOf("/");return!(r<0)&&""!==n.slice(r+1).replace(/\/+$/,"")}function Oa(e){const t=e.replace(/\/+$/,"");return Ca(t)?t:`${t}${xo}`}function xa(e){const t=e.replace(/\/+$/,"");return Ca(t)?t:`${t}${No}`}function Na(e){const t=t=>zo.registryCode("INVALID_NAME",`invalid BNS name \`${e}\`: ${t}`,{name:e});if(!e)throw t("name is empty");if(e.trim()!==e)throw t("name must not contain leading or trailing whitespace");if(e.startsWith(Po))throw t("contract names must not include did:bns: prefix");if(e.length>253)throw t("name must be at most 253 bytes");for(const n of e.split(".")){if(!n)throw t("empty label");if(n.length>126)throw t("label must be at most 126 bytes");if(n.startsWith("-")||n.endsWith("-"))throw t("label must not start or end with '-'");if(!/^[a-z0-9-]+$/.test(n))throw t("only lower-case ASCII letters, digits, '-' and '.' are supported")}return e}function Pa(e){const t=t=>zo.registryCode("INVALID_DOC_TYPE",`invalid doc_type \`${e}\`: ${t}`,{doc_type:e});if(!e)throw t("doc_type is empty");if(e.length>32)throw t("doc_type must be at most 32 bytes");if(!/^[a-z0-9_-]+$/.test(e))throw t("only lower-case ASCII letters, digits, '-' and '_' are supported");return e}const Da="0123456789abcdef";function Ba(e){if(e instanceof Uint8Array){if(0===e.length)throw new zo("serialization","raw_tx must not be empty");return`0x${function(e){let t="";for(let n=0;n<e.length;n++)t+=Da[e[n]>>4]+Da[15&e[n]];return t}(e)}`}const t=e.trim();if(!t)throw new zo("serialization","raw_tx must not be empty");const n=t.startsWith("0x")?t.slice(2):t;if(!n||n.length%2!=0)throw new zo("serialization",`raw_tx must be even-length hex, got \`${e}\``);if(!/^[0-9a-fA-F]+$/.test(n))throw new zo("serialization",`invalid raw_tx hex \`${e}\``);return`0x${n}`}function Ua(e,t){if("number"!=typeof t||!Number.isInteger(t)||t<0)throw new zo("serialization",`waitTx ${e} must be a non-negative integer, got ${t}`);return Math.max(1,t)}class La{constructor(e,t=null,n={}){this.rpcClient=new Gn(Oa(e),t,null,n)}static forIndexer(e,t=null,n={}){return new La(xa(e),t,n)}setSeq(e){this.rpcClient.setSeq(e)}async syncSessionToken(e){this.rpcClient.setSessionToken(e)}getSessionToken(){return this.rpcClient.getSessionToken()}setTraceId(e){this.rpcClient.setTraceId(e)}getTraceId(){return this.rpcClient.getTraceId()}async callEnvelope(e,t){let n;try{n=await this.rpcClient.call(e,t)}catch(s){const t=s instanceof Error?s.message:String(s);throw new zo("transport",`${e} failed: ${t}`)}if(null===n||"object"!=typeof n||Array.isArray(n))throw new zo("invalid_response",`invalid BNS RPC envelope for ${e}`);const r=n;if("boolean"!=typeof r.ok)throw new zo("invalid_response",`invalid BNS RPC envelope for ${e}`);if(!r.ok){if(void 0!==r.result&&null!==r.result)throw new zo("invalid_response",`unexpected result in failed BNS envelope for ${e}`);if(void 0===r.error||null===r.error)throw zo.registryCode("UNKNOWN_BNS_ERROR","BNS RPC envelope missing error");let t;try{t=Ia(r.error,"error")}catch(s){const t=s instanceof Ko?s.message:String(s);throw new zo("invalid_response",`invalid BNS error info for ${e}: ${t}`)}throw zo.registry(t)}if(void 0!==r.error&&null!==r.error)throw new zo("invalid_response",`unexpected error in successful BNS envelope for ${e}`);if(void 0===r.result)throw new zo("invalid_response",`BNS RPC envelope missing result for ${e}`);return r.result}decodeResult(e,t,n){try{return t(n,"result")}catch(r){const t=r instanceof Ko?r.message:String(r);throw new zo("invalid_response",`invalid ${e} result: ${t}`)}}async call(e,t,n){const r=await this.callEnvelope(e,t);if(null===r)throw new zo("invalid_response",`BNS RPC envelope missing result for ${e}`);return this.decodeResult(e,n,r)}async callNullable(e,t,n){const r=await this.callEnvelope(e,t);return null===r?null:this.decodeResult(e,n,r)}async queryNameState(e){return this.callNullable(Do,{name:e},ga)}async resolveOwner(e){return this.call(Bo,{name:e},ma)}async getAuthoritySet(e){return this.call(Uo,{name:e},ya)}async getAuthorityKey(e,t){return this.callNullable(Lo,{name:e,kid:t},wa)}async resolveDocument(e,t){return this.call(Mo,{name:e,doc_type:t},Aa)}async getDocumentVersion(e,t,n){return this.callNullable(Fo,{name:e,doc_type:t,version:n},_a)}async queryNamesByAddress(e,t=null,n=100){return this.call(jo,{address:e,cursor:t,limit:n},va)}async*iterNamesByAddress(e,t=100){let n=null;do{const r=await this.queryNamesByAddress(e,n,t);yield*r.names,n=r.next_cursor}while(null!==n)}async queryTxState(e){return this.call(Go,{tx_hash:e},Ea)}async submitRawTx(e){return this.call(Ho,{raw_tx:Ba(e)},ka)}async waitTx(e,t={}){const n=Ua("confirmations",t.confirmations??1),r=Ua("intervalMs",t.intervalMs??2e3),s=Ua("timeoutMs",t.timeoutMs??12e4),i=Date.now();for(;;){const t=await this.queryTxState(e);if("reverted"===t.state)return t;if("succeeded"===t.state&&t.confirmations>=n)return t;if(Date.now()-i>=s)throw new zo("timeout",`timed out waiting for tx ${e} (last state: ${t.state})`);await new Promise((e=>setTimeout(e,r)))}}async listEvents(e,t=100){return this.call(Vo,{from_seq:e,limit:t},Ra)}async latestCheckpoint(){return this.callNullable(qo,{},Sa)}}const Ma=Object.freeze(Object.defineProperty({__proto__:null,BNS_INDEXER_RPC_PATH:No,BNS_SERVER_RPC_PATH:xo,BnsClient:La,BnsClientError:zo,DID_BNS_PREFIX:Po,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:Lo,METHOD_GET_AUTHORITY_SET:Uo,METHOD_GET_DOCUMENT_VERSION:Fo,METHOD_LATEST_CHECKPOINT:qo,METHOD_LIST_EVENTS:Vo,METHOD_QUERY_NAMES_BY_ADDRESS:jo,METHOD_QUERY_NAME_STATE:Do,METHOD_QUERY_TX_STATE:Go,METHOD_RESOLVE_DOCUMENT:Mo,METHOD_RESOLVE_OWNER:Bo,METHOD_SUBMIT_RAW_TX:Ho,ZERO_HASH:"0x0000000000000000000000000000000000000000000000000000000000000000",canonicalBnsName:Na,canonicalDocType:Pa,didBnsFromName:function(e){return`${Po}${Na(e)}`},nameFromDidBns:function(e){if(!e.startsWith(Po))throw zo.registryCode("INVALID_NAME",`invalid BNS name \`${e}\`: DID must start with did:bns:`,{name:e});return Na(e.slice(8))},normalizeBnsIndexerUrl:xa,normalizeBnsServerUrl:Oa,normalizeRawTx:Ba},Symbol.toStringTag,{value:"Module"})),Fa="6.17.0";function ja(e,t,n){const r=t.split("|").map((e=>e.trim()));for(let i=0;i<r.length;i++)switch(t){case"any":return;case"bigint":case"boolean":case"number":case"string":if(typeof e===t)return}const s=new Error(`invalid value for type ${t}`);throw s.code="INVALID_ARGUMENT",s.argument=`value.${n}`,s.value=e,s}async function Ga(e){const t=Object.keys(e);return(await Promise.all(t.map((t=>Promise.resolve(e[t]))))).reduce(((e,n,r)=>(e[t[r]]=n,e)),{})}function Ha(e,t,n){for(let r in t){let s=t[r];const i=n?n[r]:null;i&&ja(s,i,r),Object.defineProperty(e,r,{enumerable:!0,value:s,writable:!1})}}function Va(e,t){if(null==e)return"null";if(null==t&&(t=new Set),"object"==typeof e){if(t.has(e))return"[Circular]";t.add(e)}if(Array.isArray(e))return"[ "+e.map((e=>Va(e,t))).join(", ")+" ]";if(e instanceof Uint8Array){const t="0123456789abcdef";let n="0x";for(let r=0;r<e.length;r++)n+=t[e[r]>>4],n+=t[15&e[r]];return n}if("object"==typeof e&&"function"==typeof e.toJSON)return Va(e.toJSON(),t);switch(typeof e){case"boolean":case"number":case"symbol":return e.toString();case"bigint":return BigInt(e).toString();case"string":return JSON.stringify(e);case"object":{const n=Object.keys(e);return n.sort(),"{ "+n.map((n=>`${Va(n,t)}: ${Va(e[n],t)}`)).join(", ")+" }"}}return"[ COULD NOT SERIALIZE ]"}function qa(e,t){return e&&e.code===t}function Wa(e){return qa(e,"CALL_EXCEPTION")}function za(e,t,n){let r,s=e;{const r=[];if(n){if("message"in n||"code"in n||"name"in n)throw new Error(`value will overwrite populated values: ${Va(n)}`);for(const e in n){if("shortMessage"===e)continue;const t=n[e];r.push(e+"="+Va(t))}}r.push(`code=${t}`),r.push(`version=${Fa}`),r.length&&(e+=" ("+r.join(", ")+")")}switch(t){case"INVALID_ARGUMENT":r=new TypeError(e);break;case"NUMERIC_FAULT":case"BUFFER_OVERRUN":r=new RangeError(e);break;default:r=new Error(e)}return Ha(r,{code:t}),n&&Object.assign(r,n),null==r.shortMessage&&Ha(r,{shortMessage:s}),r}function Ka(e,t,n,r){if(!e)throw za(t,n,r)}function $a(e,t,n,r){Ka(e,t,"INVALID_ARGUMENT",{argument:n,value:r})}function Qa(e,t,n){null==n&&(n=""),n&&(n=": "+n),Ka(e>=t,"missing argument"+n,"MISSING_ARGUMENT",{count:e,expectedCount:t}),Ka(e<=t,"too many arguments"+n,"UNEXPECTED_ARGUMENT",{count:e,expectedCount:t})}const Ja=["NFD","NFC","NFKD","NFKC"].reduce(((e,t)=>{try{if("test"!=="test".normalize(t))throw new Error("bad");if("NFD"===t){const e=String.fromCharCode(233).normalize("NFD");if(e!==String.fromCharCode(101,769))throw new Error("broken")}e.push(t)}catch(n){}return e}),[]);function Ya(e){Ka(Ja.indexOf(e)>=0,"platform missing String.prototype.normalize","UNSUPPORTED_OPERATION",{operation:"String.prototype.normalize",info:{form:e}})}function Za(e,t,n){if(null==n&&(n=""),e!==t){let e=n,t="new";n&&(e+=".",t+=" "+n),Ka(!1,`private constructor; use ${e}from* methods`,"UNSUPPORTED_OPERATION",{operation:t})}}function Xa(e,t,n){if(e instanceof Uint8Array)return n?new Uint8Array(e):e;if("string"==typeof e&&e.length%2==0&&e.match(/^0x[0-9a-f]*$/i)){const t=new Uint8Array((e.length-2)/2);let n=2;for(let r=0;r<t.length;r++)t[r]=parseInt(e.substring(n,n+2),16),n+=2;return t}$a(!1,"invalid BytesLike value",t||"value",e)}function ec(e,t){return Xa(e,t,!1)}function tc(e,t){return Xa(e,t,!0)}function nc(e,t){return!("string"!=typeof e||!e.match(/^0x[0-9A-Fa-f]*$/))&&(("number"!=typeof t||e.length===2+2*t)&&(!0!==t||e.length%2==0))}function rc(e){return nc(e,!0)||e instanceof Uint8Array}const sc="0123456789abcdef";function ic(e){const t=ec(e);let n="0x";for(let r=0;r<t.length;r++){const e=t[r];n+=sc[(240&e)>>4]+sc[15&e]}return n}function oc(e){return"0x"+e.map((e=>ic(e).substring(2))).join("")}function ac(e){return nc(e,!0)?(e.length-2)/2:ec(e).length}function cc(e,t,n){const r=ec(e);return null!=n&&n>r.length&&Ka(!1,"cannot slice beyond data bounds","BUFFER_OVERRUN",{buffer:r,length:r.length,offset:n}),ic(r.slice(null==t?0:t,null==n?r.length:n))}function lc(e,t,n){const r=ec(e);Ka(t>=r.length,"padding exceeds data length","BUFFER_OVERRUN",{buffer:new Uint8Array(r),length:t,offset:t+1});const s=new Uint8Array(t);return s.fill(0),n?s.set(r,t-r.length):s.set(r,0),ic(s)}function uc(e,t){return lc(e,t,!0)}function hc(e,t){return lc(e,t,!1)}const dc=BigInt(0),fc=BigInt(1),pc=9007199254740991;function gc(e,t){let n=yc(e,"value");const r=BigInt(Ac(t,"width")),s=fc<<r-fc;if(n<dc){n=-n,Ka(n<=s,"too low","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:e});return(~n&(fc<<r)-fc)+fc}return Ka(n<s,"too high","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:e}),n}function mc(e,t){const n=wc(e,"value"),r=BigInt(Ac(t,"bits"));return n&(fc<<r)-fc}function yc(e,t){switch(typeof e){case"bigint":return e;case"number":return $a(Number.isInteger(e),"underflow",t||"value",e),$a(e>=-pc&&e<=pc,"overflow",t||"value",e),BigInt(e);case"string":try{if(""===e)throw new Error("empty string");return"-"===e[0]&&"-"!==e[1]?-BigInt(e.substring(1)):BigInt(e)}catch(n){$a(!1,`invalid BigNumberish string: ${n.message}`,t||"value",e)}}$a(!1,"invalid BigNumberish value",t||"value",e)}function wc(e,t){const n=yc(e,t);return Ka(n>=dc,"unsigned value cannot be negative","NUMERIC_FAULT",{fault:"overflow",operation:"getUint",value:e}),n}const bc="0123456789abcdef";function _c(e){if(e instanceof Uint8Array){let t="0x0";for(const n of e)t+=bc[n>>4],t+=bc[15&n];return BigInt(t)}return yc(e)}function Ac(e,t){switch(typeof e){case"bigint":return $a(e>=-pc&&e<=pc,"overflow",t||"value",e),Number(e);case"number":return $a(Number.isInteger(e),"underflow",t||"value",e),$a(e>=-pc&&e<=pc,"overflow",t||"value",e),e;case"string":try{if(""===e)throw new Error("empty string");return Ac(BigInt(e),t)}catch(n){$a(!1,`invalid numeric string: ${n.message}`,t||"value",e)}}$a(!1,"invalid numeric value",t||"value",e)}function vc(e,t){const n=wc(e,"value");let r=n.toString(16);if(null==t)r.length%2&&(r="0"+r);else{const s=Ac(t,"width");if(0===s&&n===dc)return"0x";for(Ka(2*s>=r.length,`value exceeds width (${s} bytes)`,"NUMERIC_FAULT",{operation:"toBeHex",fault:"overflow",value:e});r.length<2*s;)r="0"+r}return"0x"+r}function Ec(e,t){const n=wc(e,"value");if(n===dc){const e=null!=t?Ac(t,"width"):0;return new Uint8Array(e)}let r=n.toString(16);if(r.length%2&&(r="0"+r),null!=t){const n=Ac(t,"width");for(;r.length<2*n;)r="00"+r;Ka(2*n===r.length,`value exceeds width (${n} bytes)`,"NUMERIC_FAULT",{operation:"toBeArray",fault:"overflow",value:e})}const s=new Uint8Array(r.length/2);for(let i=0;i<s.length;i++){const e=2*i;s[i]=parseInt(r.substring(e,e+2),16)}return s}function kc(e){let t=ic(rc(e)?e:Ec(e)).substring(2);for(;t.startsWith("0");)t=t.substring(1);return""===t&&(t="0"),"0x"+t}const Sc="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";let Tc=null;function Rc(e){if(null==Tc){Tc={};for(let e=0;e<58;e++)Tc[Sc[e]]=BigInt(e)}const t=Tc[e];return $a(null!=t,"invalid base58 value","letter",e),t}const Ic=BigInt(0),Cc=BigInt(58);function Oc(e){const t=ec(e);let n=_c(t),r="";for(;n;)r=Sc[Number(n%Cc)]+r,n/=Cc;for(let s=0;s<t.length&&!t[s];s++)r=Sc[0]+r;return r}class xc{constructor(t,n,r){xn(this,"filter"),xn(this,"emitter"),Dn(this,e,void 0),Bn(this,e,n),Ha(this,{emitter:t,filter:r})}async removeListener(){null!=Pn(this,e)&&await this.emitter.off(this.filter,Pn(this,e))}}function Nc(e,t,n,r,s){if("BAD_PREFIX"===e||"UNEXPECTED_CONTINUE"===e){let e=0;for(let r=t+1;r<n.length&&n[r]>>6==2;r++)e++;return e}return"OVERRUN"===e?n.length-t-1:0}e=new WeakMap;const Pc=Object.freeze({error:function(e,t,n,r,s){$a(!1,`invalid codepoint at offset ${t}; ${e}`,"bytes",n)},ignore:Nc,replace:function(e,t,n,r,s){return"OVERLONG"===e?($a("number"==typeof s,"invalid bad code point for replacement","badCodepoint",s),r.push(s),0):(r.push(65533),Nc(e,t,n))}});function Dc(e,t){$a("string"==typeof e,"invalid string value","str",e),null!=t&&(Ya(t),e=e.normalize(t));let n=[];for(let r=0;r<e.length;r++){const t=e.charCodeAt(r);if(t<128)n.push(t);else if(t<2048)n.push(t>>6|192),n.push(63&t|128);else if(55296==(64512&t)){r++;const s=e.charCodeAt(r);$a(r<e.length&&56320==(64512&s),"invalid surrogate pair","str",e);const i=65536+((1023&t)<<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(t>>12|224),n.push(t>>6&63|128),n.push(63&t|128)}return new Uint8Array(n)}function Bc(e,t){return n=function(e,t){null==t&&(t=Pc.error);const n=ec(e,"bytes"),r=[];let s=0;for(;s<n.length;){const e=n[s++];if(!(e>>7)){r.push(e);continue}let i=null,o=null;if(192==(224&e))i=1,o=127;else if(224==(240&e))i=2,o=2047;else{if(240!=(248&e)){s+=t(128==(192&e)?"UNEXPECTED_CONTINUE":"BAD_PREFIX",s-1,n,r);continue}i=3,o=65535}if(s-1+i>=n.length){s+=t("OVERRUN",s-1,n,r);continue}let a=e&(1<<8-i-1)-1;for(let c=0;c<i;c++){let e=n[s];if(128!=(192&e)){s+=t("MISSING_CONTINUE",s,n,r),a=null;break}a=a<<6|63&e,s++}null!==a&&(a>1114111?s+=t("OUT_OF_RANGE",s-1-i,n,r,a):a>=55296&&a<=57343?s+=t("UTF16_SURROGATE",s-1-i,n,r,a):a<=o?s+=t("OVERLONG",s-1-i,n,r,a):r.push(a))}return r}(e,t),n.map((e=>e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode(55296+(e>>10&1023),56320+(1023&e))))).join("");var n}function Uc(e){return async function(t,n){Ka(null==n||!n.cancelled,"request cancelled before sending","CANCELLED");const r=t.url.split(":")[0].toLowerCase();Ka("http"===r||"https"===r,`unsupported protocol ${r}`,"UNSUPPORTED_OPERATION",{info:{protocol:r},operation:"request"}),Ka("https"===r||!t.credentials||t.allowInsecureAuthentication,"insecure authorized connections unsupported","UNSUPPORTED_OPERATION",{operation:"request"});let s=null;const i=new AbortController,o=setTimeout((()=>{s=za("request timeout","TIMEOUT"),i.abort()}),t.timeout);n&&n.addListener((()=>{s=za("request cancelled","CANCELLED"),i.abort()}));const a=Object.assign({},e,{method:t.method,headers:new Headers(Array.from(t)),body:t.body||void 0,signal:i.signal});let c;try{c=await fetch(t.url,a)}catch(d){if(clearTimeout(o),s)throw s;throw d}clearTimeout(o);const l={};c.headers.forEach(((e,t)=>{l[t.toLowerCase()]=e}));const u=await c.arrayBuffer(),h=null==u?null:new Uint8Array(u);return{statusCode:c.status,statusMessage:c.statusText,headers:l,body:h}}}let Lc=Uc();const Mc=new RegExp("^data:([^;:]*)?(;base64)?,(.*)$","i"),Fc=new RegExp("^ipfs://(ipfs/)?(.*)$","i");let jc=!1;async function Gc(e,t){try{const t=e.match(Mc);if(!t)throw new Error("invalid data");return new Jc(200,"OK",{"content-type":t[1]||"text/plain"},t[2]?function(e){e=atob(e);const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return ec(t)}(t[3]):Dc(t[3].replace(/%([0-9a-f][0-9a-f])/gi,((e,t)=>String.fromCharCode(parseInt(t,16))))))}catch(n){return new Jc(599,"BAD REQUEST (invalid data: URI)",{},null,new $c(e))}}function Hc(e){return async function(t,n){try{const n=t.match(Fc);if(!n)throw new Error("invalid link");return new $c(`${e}${n[2]}`)}catch(r){return new Jc(599,"BAD REQUEST (invalid IPFS URI)",{},null,new $c(t))}}}const Vc={data:Gc,ipfs:Hc("https://gateway.ipfs.io/ipfs/")},qc=new WeakMap;class Wc{constructor(e){Dn(this,t,void 0),Dn(this,n,void 0),Bn(this,t,[]),Bn(this,n,!1),qc.set(e,(()=>{if(!Pn(this,n)){Bn(this,n,!0);for(const e of Pn(this,t))setTimeout((()=>{e()}),0);Bn(this,t,[])}}))}addListener(e){Ka(!Pn(this,n),"singal already cancelled","UNSUPPORTED_OPERATION",{operation:"fetchCancelSignal.addCancelListener"}),Pn(this,t).push(e)}get cancelled(){return Pn(this,n)}checkSignal(){Ka(!this.cancelled,"cancelled","CANCELLED",{})}}function zc(e){if(null==e)throw new Error("missing signal; should not happen");return e.checkSignal(),e}t=new WeakMap,n=new WeakMap;const Kc=class e{constructor(e){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(e)),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(e){Bn(this,c,String(e))}get body(){return null==Pn(this,l)?null:new Uint8Array(Pn(this,l))}set body(e){if(null==e)Bn(this,l,void 0),Bn(this,u,void 0);else if("string"==typeof e)Bn(this,l,Dc(e)),Bn(this,u,"text/plain");else if(e instanceof Uint8Array)Bn(this,l,e),Bn(this,u,"application/octet-stream");else{if("object"!=typeof e)throw new Error("invalid body");Bn(this,l,Dc(JSON.stringify(e))),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(e){null==e&&(e=""),Bn(this,o,String(e).toUpperCase())}get headers(){const e=Object.assign({},Pn(this,i));return Pn(this,h)&&(e.authorization=`Basic ${function(e){const t=ec(e);let n="";for(let r=0;r<t.length;r++)n+=String.fromCharCode(t[r]);return btoa(n)}(Dc(Pn(this,h)))}`),this.allowGzip&&(e["accept-encoding"]="gzip"),null==e["content-type"]&&Pn(this,u)&&(e["content-type"]=Pn(this,u)),this.body&&(e["content-length"]=String(this.body.length)),e}getHeader(e){return this.headers[e.toLowerCase()]}setHeader(e,t){Pn(this,i)[String(e).toLowerCase()]=String(t)}clearHeaders(){Bn(this,i,{})}[Symbol.iterator](){const e=this.headers,t=Object.keys(e);let n=0;return{next:()=>{if(n<t.length){const r=t[n++];return{value:[r,e[r]],done:!1}}return{value:void 0,done:!0}}}}get credentials(){return Pn(this,h)||null}setCredentials(e,t){$a(!e.match(/:/),"invalid basic authentication username","username","[REDACTED]"),Bn(this,h,`${e}:${t}`)}get allowGzip(){return Pn(this,s)}set allowGzip(e){Bn(this,s,!!e)}get allowInsecureAuthentication(){return!!Pn(this,r)}set allowInsecureAuthentication(e){Bn(this,r,!!e)}get timeout(){return Pn(this,a)}set timeout(e){$a(e>=0,"timeout must be non-zero","timeout",e),Bn(this,a,e)}get preflightFunc(){return Pn(this,d)||null}set preflightFunc(e){Bn(this,d,e)}get processFunc(){return Pn(this,f)||null}set processFunc(e){Bn(this,f,e)}get retryFunc(){return Pn(this,p)||null}set retryFunc(e){Bn(this,p,e)}get getUrlFunc(){return Pn(this,y)||Lc}set getUrlFunc(e){Bn(this,y,e)}toString(){return`<FetchRequest method=${JSON.stringify(this.method)} url=${JSON.stringify(this.url)} headers=${JSON.stringify(this.headers)} body=${Pn(this,l)?ic(Pn(this,l)):"null"}>`}setThrottleParams(e){null!=e.slotInterval&&(Pn(this,m).slotInterval=e.slotInterval),null!=e.maxAttempts&&(Pn(this,m).maxAttempts=e.maxAttempts)}send(){return Ka(null==Pn(this,g),"request already sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.send"}),Bn(this,g,new Wc(this)),Ln(this,w,b).call(this,0,Yc()+this.timeout,0,this,new Jc(0,"",{},null,this))}cancel(){Ka(null!=Pn(this,g),"request has not been sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.cancel"});const e=qc.get(this);if(!e)throw new Error("missing signal; should not happen");e()}redirect(t){const n=this.url.split(":")[0].toLowerCase(),r=t.split(":")[0].toLowerCase();Ka(("https"!==n||"http"!==r)&&t.match(/^https?:/),"unsupported redirect","UNSUPPORTED_OPERATION",{operation:`redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(t)})`});const s=new e(t);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 t=new e(this.url);return Bn(t,o,Pn(this,o)),Pn(this,l)&&Bn(t,l,Pn(this,l)),Bn(t,u,Pn(this,u)),Bn(t,i,Object.assign({},Pn(this,i))),Bn(t,h,Pn(this,h)),this.allowGzip&&(t.allowGzip=!0),t.timeout=this.timeout,this.allowInsecureAuthentication&&(t.allowInsecureAuthentication=!0),Bn(t,d,Pn(this,d)),Bn(t,f,Pn(this,f)),Bn(t,p,Pn(this,p)),Bn(t,m,Object.assign({},Pn(this,m))),Bn(t,y,Pn(this,y)),t}static lockConfig(){jc=!0}static getGateway(e){return Vc[e.toLowerCase()]||null}static registerGateway(e,t){if("http"===(e=e.toLowerCase())||"https"===e)throw new Error(`cannot intercept ${e}; use registerGetUrl`);if(jc)throw new Error("gateways locked");Vc[e]=t}static registerGetUrl(e){if(jc)throw new Error("gateways locked");Lc=e}static createGetUrlFunc(e){return Uc(e)}static createDataGateway(){return Gc}static createIpfsGatewayFunc(e){return Hc(e)}};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(e,t,n,r,s){var i,o,a;if(e>=Pn(this,m).maxAttempts)return s.makeServerError("exceeded maximum retry limit");Ka(Yc()<=t,"timeout","TIMEOUT",{operation:"request.send",reason:"timeout",request:r}),n>0&&await function(e){return new Promise((t=>setTimeout(t,e)))}(n);let c=this.clone();const l=(c.url.split(":")[0]||"").toLowerCase();if(l in Vc){const e=await Vc[l](c.url,zc(Pn(r,g)));if(e instanceof Jc){let t=e;if(this.processFunc){zc(Pn(r,g));try{t=await this.processFunc(c,t)}catch(d){null!=d.throttle&&"number"==typeof d.stall||t.makeServerError("error in post-processing function",d).assertOk()}}return t}c=e}this.preflightFunc&&(c=await this.preflightFunc(c));const u=await this.getUrlFunc(c,zc(Pn(r,g)));let h=new Jc(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,e+1,t,0,r,h)}catch(d){}return h}if(429===h.statusCode&&(null==this.retryFunc||await this.retryFunc(c,h,e))){const n=h.headers["retry-after"];let s=Pn(this,m).slotInterval*Math.trunc(Math.random()*Math.pow(2,e));return"string"==typeof n&&n.match(/^[1-9][0-9]*$/)&&(s=parseInt(n)),Ln(o=c.clone(),w,b).call(o,e+1,t,s,r,h)}if(this.processFunc){zc(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,e));return d.stall>=0&&(n=d.stall),Ln(a=c.clone(),w,b).call(a,e+1,t,n,r,h)}}return h};let $c=Kc;const Qc=class e{constructor(e,t,n,r,s){Dn(this,_,void 0),Dn(this,A,void 0),Dn(this,v,void 0),Dn(this,E,void 0),Dn(this,k,void 0),Dn(this,S,void 0),Bn(this,_,e),Bn(this,A,t),Bn(this,v,Object.keys(n).reduce(((e,t)=>(e[t.toLowerCase()]=String(n[t]),e)),{})),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)?ic(Pn(this,E)):"null"}>`}get statusCode(){return Pn(this,_)}get statusMessage(){return Pn(this,A)}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)?"":Bc(Pn(this,E))}catch(e){Ka(!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(e){Ka(!1,"response body is not valid JSON","UNSUPPORTED_OPERATION",{operation:"bodyJson",info:{response:this}})}}[Symbol.iterator](){const e=this.headers,t=Object.keys(e);let n=0;return{next:()=>{if(n<t.length){const r=t[n++];return{value:[r,e[r]],done:!1}}return{value:void 0,done:!0}}}}makeServerError(t,n){let r;r=t?`CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${t})`:`CLIENT ESCALATED SERVER ERROR (${t=`${this.statusCode} ${this.statusMessage}`})`;const s=new e(599,r,this.headers,this.body,Pn(this,k)||void 0);return Bn(s,S,{message:t,error:n}),s}throwThrottleError(e,t){null==t?t=-1:$a(Number.isInteger(t)&&t>=0,"invalid stall timeout","stall",t);const n=new Error(e||"throttling requests");throw Ha(n,{stall:t,throttle:!0}),n}getHeader(e){return this.headers[e.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:e,error:t}=Pn(this,S);""===e&&(e=`server response ${this.statusCode} ${this.statusMessage}`);let n=null;this.request&&(n=this.request.url);let r=null;try{Pn(this,E)&&(r=Bc(Pn(this,E)))}catch(s){}Ka(!1,e,"SERVER_ERROR",{request:this.request||"unknown request",response:this,error:t,info:{requestUrl:n,responseBody:r,responseStatus:`${this.statusCode} ${this.statusMessage}`}})}};_=new WeakMap,A=new WeakMap,v=new WeakMap,E=new WeakMap,k=new WeakMap,S=new WeakMap;let Jc=Qc;function Yc(){return(new Date).getTime()}function Zc(e){let t=e.toString(16);for(;t.length<2;)t="0"+t;return"0x"+t}function Xc(e,t,n){let r=0;for(let s=0;s<n;s++)r=256*r+e[t+s];return r}function el(e,t,n,r){const s=[];for(;n<t+1+r;){const i=tl(e,n);s.push(i.result),Ka((n+=i.consumed)<=t+1+r,"child data too short","BUFFER_OVERRUN",{buffer:e,length:r,offset:t})}return{consumed:1+r,result:s}}function tl(e,t){Ka(0!==e.length,"data too short","BUFFER_OVERRUN",{buffer:e,length:0,offset:1});const n=t=>{Ka(t<=e.length,"data short segment too short","BUFFER_OVERRUN",{buffer:e,length:e.length,offset:t})};if(e[t]>=248){const r=e[t]-247;n(t+1+r);const s=Xc(e,t+1,r);return n(t+1+r+s),el(e,t,t+1+r,r+s)}if(e[t]>=192){const r=e[t]-192;return n(t+1+r),el(e,t,t+1,r)}if(e[t]>=184){const r=e[t]-183;n(t+1+r);const s=Xc(e,t+1,r);n(t+1+r+s);return{consumed:1+r+s,result:ic(e.slice(t+1+r,t+1+r+s))}}if(e[t]>=128){const r=e[t]-128;n(t+1+r);return{consumed:1+r,result:ic(e.slice(t+1,t+1+r))}}return{consumed:1,result:Zc(e[t])}}function nl(e){const t=ec(e,"data"),n=tl(t,0);return $a(n.consumed===t.length,"unexpected junk after rlp payload","data",e),n.result}function rl(e){const t=[];for(;e;)t.unshift(255&e),e>>=8;return t}function sl(e){if(Array.isArray(e)){let t=[];if(e.forEach((function(e){t=t.concat(sl(e))})),t.length<=55)return t.unshift(192+t.length),t;const n=rl(t.length);return n.unshift(247+n.length),n.concat(t)}const t=Array.prototype.slice.call(ec(e,"object"));if(1===t.length&&t[0]<=127)return t;if(t.length<=55)return t.unshift(128+t.length),t;const n=rl(t.length);return n.unshift(183+n.length),n.concat(t)}const il="0123456789abcdef";function ol(e){let t="0x";for(const n of sl(e))t+=il[n>>4],t+=il[15&n];return t}function al(e){const t=ec(e,"randomBytes");t[6]=15&t[6]|64,t[8]=63&t[8]|128;const n=ic(t);return[n.substring(2,10),n.substring(10,14),n.substring(14,18),n.substring(18,22),n.substring(22,34)].join("-")}const cl=32,ll=new Uint8Array(cl),ul=["then"],hl={},dl=new WeakMap;function fl(e){return dl.get(e)}function pl(e,t){dl.set(e,t)}function gl(e,t){const n=new Error(`deferred error during ABI decoding triggered accessing ${e}`);throw n.error=t,n}function ml(e,t,n){return e.indexOf(null)>=0?t.map(((e,t)=>e instanceof yl?ml(fl(e),e,n):e)):e.reduce(((e,r,s)=>{let i=t.getValue(r);return r in e||(n&&i instanceof yl&&(i=ml(fl(i),i,n)),e[r]=i),e}),{})}T=new WeakMap;let yl=class e extends Array{constructor(...e){const t=e[0];let n=e[1],r=(e[2]||[]).slice(),s=!0;t!==hl&&(n=e,r=[],s=!1),super(n.length),Dn(this,T,void 0),n.forEach(((e,t)=>{this[t]=e}));const i=r.reduce(((e,t)=>("string"==typeof t&&e.set(t,(e.get(t)||0)+1),e)),new Map);if(pl(this,Object.freeze(n.map(((e,t)=>{const n=r[t];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:(e,t,n)=>{if("string"==typeof t){if(t.match(/^[0-9]+$/)){const n=Ac(t,"%index");if(n<0||n>=this.length)throw new RangeError("out of result range");const r=e[n];return r instanceof Error&&gl(`index ${n}`,r),r}if(ul.indexOf(t)>=0)return Reflect.get(e,t,n);const r=e[t];if(r instanceof Function)return function(...t){return r.apply(this===n?e:this,t)};if(!(t in e))return e.getValue.apply(this===n?e:this,[t])}return Reflect.get(e,t,n)}});return pl(o,fl(this)),o}toArray(t){const n=[];return this.forEach(((r,s)=>{r instanceof Error&&gl(`index ${s}`,r),t&&r instanceof e&&(r=r.toArray(t)),n.push(r)})),n}toObject(e){const t=fl(this);return t.reduce(((n,r,s)=>(Ka(null!=r,`value at index ${s} unnamed`,"UNSUPPORTED_OPERATION",{operation:"toObject()"}),ml(t,this,e))),{})}slice(t,n){null==t&&(t=0),t<0&&(t+=this.length)<0&&(t=0),null==n&&(n=this.length),n<0&&(n+=this.length)<0&&(n=0),n>this.length&&(n=this.length);const r=fl(this),s=[],i=[];for(let e=t;e<n;e++)s.push(this[e]),i.push(r[e]);return new e(hl,s,i)}filter(t,n){const r=fl(this),s=[],i=[];for(let e=0;e<this.length;e++){const o=this[e];o instanceof Error&&gl(`index ${e}`,o),t.call(n,o,e,this)&&(s.push(o),i.push(r[e]))}return new e(hl,s,i)}map(e,t){const n=[];for(let r=0;r<this.length;r++){const s=this[r];s instanceof Error&&gl(`index ${r}`,s),n.push(e.call(t,s,r,this))}return n}getValue(e){const t=fl(this).indexOf(e);if(-1===t)return;const n=this[t];return n instanceof Error&&gl(`property ${JSON.stringify(e)}`,n.error),n}static fromItems(t,n){return new e(hl,t,n)}};function wl(e){let t=Ec(e);return Ka(t.length<=cl,"value out-of-bounds","BUFFER_OVERRUN",{buffer:t,length:cl,offset:t.length}),t.length!==cl&&(t=tc(oc([ll.slice(t.length%cl),t]))),t}class bl{constructor(e,t,n,r){xn(this,"name"),xn(this,"type"),xn(this,"localName"),xn(this,"dynamic"),Ha(this,{name:e,type:t,localName:n,dynamic:r},{name:"string",type:"string",localName:"string",dynamic:"boolean"})}_throwError(e,t){$a(!1,e,this.localName,t)}}class _l{constructor(){Dn(this,C),Dn(this,R,void 0),Dn(this,I,void 0),Bn(this,R,[]),Bn(this,I,0)}get data(){return oc(Pn(this,R))}get length(){return Pn(this,I)}appendWriter(e){return Ln(this,C,O).call(this,tc(e.data))}writeBytes(e){let t=tc(e);const n=t.length%cl;return n&&(t=tc(oc([t,ll.slice(n)]))),Ln(this,C,O).call(this,t)}writeValue(e){return Ln(this,C,O).call(this,wl(e))}writeUpdatableValue(){const e=Pn(this,R).length;return Pn(this,R).push(ll),Bn(this,I,Pn(this,I)+cl),t=>{Pn(this,R)[e]=wl(t)}}}R=new WeakMap,I=new WeakMap,C=new WeakSet,O=function(e){return Pn(this,R).push(e),Bn(this,I,Pn(this,I)+e.length),e.length};x=new WeakMap,N=new WeakMap,P=new WeakMap,D=new WeakMap,B=new WeakMap,U=new WeakSet,L=function(e){var t;if(Pn(this,D))return Ln(t=Pn(this,D),U,L).call(t,e);Bn(this,P,Pn(this,P)+e),Ka(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:tc(Pn(this,x)),offset:Pn(this,N),length:e,info:{bytesRead:Pn(this,P),dataLength:this.dataLength}})},M=new WeakSet,F=function(e,t,n){let r=Math.ceil(t/cl)*cl;return Pn(this,N)+r>Pn(this,x).length&&(this.allowLoose&&n&&Pn(this,N)+t<=Pn(this,x).length?r=t:Ka(!1,"data out-of-bounds","BUFFER_OVERRUN",{buffer:tc(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 Al=class e{constructor(e,t,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),Ha(this,{allowLoose:!!t}),Bn(this,x,tc(e)),Bn(this,P,0),Bn(this,D,null),Bn(this,B,null!=n?n:1024),Bn(this,N,0)}get data(){return ic(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(t){const n=new e(Pn(this,x).slice(Pn(this,N)+t),this.allowLoose,Pn(this,B));return Bn(n,D,this),n}readBytes(e,t){let n=Ln(this,M,F).call(this,0,e,!!t);return Ln(this,U,L).call(this,e),Bn(this,N,Pn(this,N)+n.length),n.slice(0,e)}readValue(){return _c(this.readBytes(cl))}readIndex(){return Ac(_c(this.readBytes(cl)))}};function vl(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function El(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function kl(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");vl(e.outputLen),vl(e.blockLen)}function Sl(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Tl(e,t){El(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}const Rl="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,Il=e=>e instanceof Uint8Array,Cl=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),Ol=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),xl=(e,t)=>e<<32-t|e>>>t;
|
|
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 Nl=async()=>{};async function Pl(e,t,n){let r=Date.now();for(let s=0;s<e;s++){n(s);const e=Date.now()-r;e>=0&&e<t||(await Nl(),r+=e)}}function Dl(e){if("string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e)),!Il(e))throw new Error("expected Uint8Array, got "+typeof e);return e}class Bl{clone(){return this._cloneInto()}}const Ul={}.toString;function Ll(e,t){if(void 0!==t&&"[object Object]"!==Ul.call(t))throw new Error("Options should be object or undefined");return Object.assign(e,t)}function Ml(e){const t=t=>e().update(Dl(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Fl(e=32){if(Rl&&"function"==typeof Rl.getRandomValues)return Rl.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}class jl extends Bl{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,kl(e);const n=Dl(t);if(this.iHash=e.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?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(e){return Sl(this),this.iHash.update(e),this}digestInto(e){Sl(this),El(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:n,finished:r,destroyed:s,blockLen:i,outputLen:o}=this;return e.finished=r,e.destroyed=s,e.blockLen=i,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Gl=(e,t,n)=>new jl(e,t).update(n).digest();function Hl(e,t,n,r){const{c:s,dkLen:i,DK:o,PRF:a,PRFSalt:c}=function(e,t,n,r){kl(e);const s=Ll({dkLen:32,asyncTick:10},r),{c:i,dkLen:o,asyncTick:a}=s;if(vl(i),vl(o),vl(a),i<1)throw new Error("PBKDF2: iterations (c) should be >= 1");const c=Dl(t),l=Dl(n),u=new Uint8Array(o),h=Gl.create(e,c),d=h._cloneInto().update(l);return{c:i,dkLen:o,asyncTick:a,DK:u,PRF:h,PRFSalt:d}}(e,t,n,r);let l;const u=new Uint8Array(4),h=Ol(u),d=new Uint8Array(a.outputLen);for(let f=1,p=0;p<i;f++,p+=a.outputLen){const e=o.subarray(p,p+a.outputLen);h.setInt32(0,f,!1),(l=c._cloneInto(l)).update(u).digestInto(d),e.set(d.subarray(0,e.length));for(let t=1;t<s;t++){a._cloneInto(l).update(d).digestInto(d);for(let t=0;t<e.length;t++)e[t]^=d[t]}}return function(e,t,n,r,s){return e.destroy(),t.destroy(),r&&r.destroy(),s.fill(0),n}(a,c,o,l,d)}Gl.create=(e,t)=>new jl(e,t);class Vl extends Bl{constructor(e,t,n,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Ol(this.buffer)}update(e){Sl(this);const{view:t,buffer:n,blockLen:r}=this,s=(e=Dl(e)).length;for(let i=0;i<s;){const o=Math.min(r-this.pos,s-i);if(o!==r)n.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===r&&(this.process(t,0),this.pos=0);else{const t=Ol(e);for(;r<=s-i;i+=r)this.process(t,i)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){Sl(this),Tl(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:s}=this;let{pos:i}=this;t[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++)t[u]=0;!function(e,t,n,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,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;e.setUint32(t+c,o,r),e.setUint32(t+l,a,r)}(n,r-8,BigInt(8*this.length),s),this.process(n,0);const o=Ol(e),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:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:r,finished:s,destroyed:i,pos:o}=this;return e.length=r,e.pos=o,e.finished=s,e.destroyed=i,r%t&&e.buffer.set(n),e}}const ql=(e,t,n)=>e&t^e&n^t&n,Wl=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]),zl=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Kl=new Uint32Array(64);class $l extends Vl{constructor(){super(64,32,8,!1),this.A=0|zl[0],this.B=0|zl[1],this.C=0|zl[2],this.D=0|zl[3],this.E=0|zl[4],this.F=0|zl[5],this.G=0|zl[6],this.H=0|zl[7]}get(){const{A:e,B:t,C:n,D:r,E:s,F:i,G:o,H:a}=this;return[e,t,n,r,s,i,o,a]}set(e,t,n,r,s,i,o,a){this.A=0|e,this.B=0|t,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(e,t){for(let h=0;h<16;h++,t+=4)Kl[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){const e=Kl[h-15],t=Kl[h-2],n=xl(e,7)^xl(e,18)^e>>>3,r=xl(t,17)^xl(t,19)^t>>>10;Kl[h]=r+Kl[h-7]+n+Kl[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 e=l+(xl(o,6)^xl(o,11)^xl(o,25))+((u=o)&a^~u&c)+Wl[h]+Kl[h]|0,t=(xl(n,2)^xl(n,13)^xl(n,22))+ql(n,r,s)|0;l=c,c=a,a=o,o=i+e|0,i=s,s=r,r=n,n=e+t|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(){Kl.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const Ql=Ml((()=>new $l)),Jl=BigInt(2**32-1),Yl=BigInt(32);function Zl(e,t=!1){return t?{h:Number(e&Jl),l:Number(e>>Yl&Jl)}:{h:0|Number(e>>Yl&Jl),l:0|Number(e&Jl)}}function Xl(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let s=0;s<e.length;s++){const{h:i,l:o}=Zl(e[s],t);[n[s],r[s]]=[i,o]}return[n,r]}const eu=(e,t,n)=>e<<n|t>>>32-n,tu=(e,t,n)=>t<<n|e>>>32-n,nu=(e,t,n)=>t<<n-32|e>>>64-n,ru=(e,t,n)=>e<<n-32|t>>>64-n;const su={fromBig:Zl,split:Xl,toBig:(e,t)=>BigInt(e>>>0)<<Yl|BigInt(t>>>0),shrSH:(e,t,n)=>e>>>n,shrSL:(e,t,n)=>e<<32-n|t>>>n,rotrSH:(e,t,n)=>e>>>n|t<<32-n,rotrSL:(e,t,n)=>e<<32-n|t>>>n,rotrBH:(e,t,n)=>e<<64-n|t>>>n-32,rotrBL:(e,t,n)=>e>>>n-32|t<<64-n,rotr32H:(e,t)=>t,rotr32L:(e,t)=>e,rotlSH:eu,rotlSL:tu,rotlBH:nu,rotlBL:ru,add:function(e,t,n,r){const s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:0|s}},add3L:(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),add3H:(e,t,n,r)=>t+n+r+(e/2**32|0)|0,add4L:(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),add4H:(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,add5H:(e,t,n,r,s,i)=>t+n+r+s+i+(e/2**32|0)|0,add5L:(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0)},[iu,ou]=(()=>su.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((e=>BigInt(e)))))(),au=new Uint32Array(80),cu=new Uint32Array(80);class lu extends Vl{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:e,Al:t,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[e,t,n,r,s,i,o,a,c,l,u,h,d,f,p,g]}set(e,t,n,r,s,i,o,a,c,l,u,h,d,f,p,g){this.Ah=0|e,this.Al=0|t,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(e,t){for(let w=0;w<16;w++,t+=4)au[w]=e.getUint32(t),cu[w]=e.getUint32(t+=4);for(let w=16;w<80;w++){const e=0|au[w-15],t=0|cu[w-15],n=su.rotrSH(e,t,1)^su.rotrSH(e,t,8)^su.shrSH(e,t,7),r=su.rotrSL(e,t,1)^su.rotrSL(e,t,8)^su.shrSL(e,t,7),s=0|au[w-2],i=0|cu[w-2],o=su.rotrSH(s,i,19)^su.rotrBH(s,i,61)^su.shrSH(s,i,6),a=su.rotrSL(s,i,19)^su.rotrBL(s,i,61)^su.shrSL(s,i,6),c=su.add4L(r,a,cu[w-7],cu[w-16]),l=su.add4H(c,n,o,au[w-7],au[w-16]);au[w]=0|l,cu[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 e=su.rotrSH(u,h,14)^su.rotrSH(u,h,18)^su.rotrBH(u,h,41),t=su.rotrSL(u,h,14)^su.rotrSL(u,h,18)^su.rotrBL(u,h,41),b=u&d^~u&p,_=h&f^~h&g,A=su.add5L(y,t,_,ou[w],cu[w]),v=su.add5H(A,m,e,b,iu[w],au[w]),E=0|A,k=su.rotrSH(n,r,28)^su.rotrBH(n,r,34)^su.rotrBH(n,r,39),S=su.rotrSL(n,r,28)^su.rotrBL(n,r,34)^su.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}=su.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=su.add3L(E,S,R);n=su.add3H(I,v,k,T),r=0|I}({h:n,l:r}=su.add(0|this.Ah,0|this.Al,0|n,0|r)),({h:s,l:i}=su.add(0|this.Bh,0|this.Bl,0|s,0|i)),({h:o,l:a}=su.add(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l:l}=su.add(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:h}=su.add(0|this.Eh,0|this.El,0|u,0|h)),({h:d,l:f}=su.add(0|this.Fh,0|this.Fl,0|d,0|f)),({h:p,l:g}=su.add(0|this.Gh,0|this.Gl,0|p,0|g)),({h:m,l:y}=su.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(){au.fill(0),cu.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 uu=Ml((()=>new lu));const hu=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")}(),du=hu.crypto||hu.msCrypto;let fu=!1;const pu=function(e,t,n){return function(e,t){const n={sha256:Ql,sha512:uu}[e];return $a(null!=n,"invalid hmac algorithm","algorithm",e),Gl.create(n,t)}(e,t).update(n).digest()};let gu=pu;function mu(e,t,n){const r=ec(t,"key"),s=ec(n,"data");return ic(gu(e,r,s))}mu._=pu,mu.lock=function(){fu=!0},mu.register=function(e){if(fu)throw new Error("computeHmac is locked");gu=e},Object.freeze(mu);const[yu,wu,bu]=[[],[],[]],_u=BigInt(0),Au=BigInt(1),vu=BigInt(2),Eu=BigInt(7),ku=BigInt(256),Su=BigInt(113);for(let uE=0,hE=Au,dE=1,fE=0;uE<24;uE++){[dE,fE]=[fE,(2*dE+3*fE)%5],yu.push(2*(5*fE+dE)),wu.push((uE+1)*(uE+2)/2%64);let e=_u;for(let t=0;t<7;t++)hE=(hE<<Au^(hE>>Eu)*Su)%ku,hE&vu&&(e^=Au<<(Au<<BigInt(t))-Au);bu.push(e)}const[Tu,Ru]=Xl(bu,!0),Iu=(e,t,n)=>n>32?nu(e,t,n):eu(e,t,n),Cu=(e,t,n)=>n>32?ru(e,t,n):tu(e,t,n);class Ou extends Bl{constructor(e,t,n,r=!1,s=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=r,this.rounds=s,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,vl(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Cl(this.state)}keccak(){!function(e,t=24){const n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let r=0;r<10;r++)n[r]=e[r]^e[r+10]^e[r+20]^e[r+30]^e[r+40];for(let r=0;r<10;r+=2){const t=(r+8)%10,s=(r+2)%10,i=n[s],o=n[s+1],a=Iu(i,o,1)^n[t],c=Cu(i,o,1)^n[t+1];for(let n=0;n<50;n+=10)e[r+n]^=a,e[r+n+1]^=c}let t=e[2],s=e[3];for(let n=0;n<24;n++){const r=wu[n],i=Iu(t,s,r),o=Cu(t,s,r),a=yu[n];t=e[a],s=e[a+1],e[a]=i,e[a+1]=o}for(let r=0;r<50;r+=10){for(let t=0;t<10;t++)n[t]=e[r+t];for(let t=0;t<10;t++)e[r+t]^=~n[(t+2)%10]&n[(t+4)%10]}e[0]^=Tu[r],e[1]^=Ru[r]}n.fill(0)}(this.state32,this.rounds),this.posOut=0,this.pos=0}update(e){Sl(this);const{blockLen:t,state:n}=this,r=(e=Dl(e)).length;for(let s=0;s<r;){const i=Math.min(t-this.pos,r-s);for(let t=0;t<i;t++)n[this.pos++]^=e[s++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:r}=this;e[n]^=t,128&t&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Sl(this,!1),El(e),this.finish();const t=this.state,{blockLen:n}=this;for(let r=0,s=e.length;r<s;){this.posOut>=n&&this.keccak();const i=Math.min(n-this.posOut,s-r);e.set(t.subarray(this.posOut,this.posOut+i),r),this.posOut+=i,r+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return vl(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Tl(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:r,rounds:s,enableXOF:i}=this;return e||(e=new Ou(t,n,r,i,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=n,e.outputLen=r,e.enableXOF=i,e.destroyed=this.destroyed,e}}const xu=((e,t,n)=>Ml((()=>new Ou(t,e,n))))(1,136,32);let Nu=!1;const Pu=function(e){return xu(e)};let Du=Pu;function Bu(e){const t=ec(e,"data");return ic(Du(t))}Bu._=Pu,Bu.lock=function(){Nu=!0},Bu.register=function(e){if(Nu)throw new TypeError("keccak256 is locked");Du=e},Object.freeze(Bu);const Uu=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Lu=Uint8Array.from({length:16},((e,t)=>t));let Mu=[Lu],Fu=[Lu.map((e=>(9*e+5)%16))];for(let uE=0;uE<4;uE++)for(let e of[Mu,Fu])e.push(e[uE].map((e=>Uu[e])));const ju=[[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((e=>new Uint8Array(e))),Gu=Mu.map(((e,t)=>e.map((e=>ju[t][e])))),Hu=Fu.map(((e,t)=>e.map((e=>ju[t][e])))),Vu=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),qu=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]),Wu=(e,t)=>e<<t|e>>>32-t;function zu(e,t,n,r){return 0===e?t^n^r:1===e?t&n|~t&r:2===e?(t|~n)^r:3===e?t&r|n&~r:t^(n|~r)}const Ku=new Uint32Array(16);class $u extends Vl{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:e,h1:t,h2:n,h3:r,h4:s}=this;return[e,t,n,r,s]}set(e,t,n,r,s){this.h0=0|e,this.h1=0|t,this.h2=0|n,this.h3=0|r,this.h4=0|s}process(e,t){for(let d=0;d<16;d++,t+=4)Ku[d]=e.getUint32(t,!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 e=4-d,t=Vu[d],f=qu[d],p=Mu[d],g=Fu[d],m=Gu[d],y=Hu[d];for(let r=0;r<16;r++){const e=Wu(n+zu(d,s,o,c)+Ku[p[r]]+t,m[r])+u|0;n=u,u=c,c=0|Wu(o,10),o=s,s=e}for(let n=0;n<16;n++){const t=Wu(r+zu(e,i,a,l)+Ku[g[n]]+f,y[n])+h|0;r=h,h=l,l=0|Wu(a,10),a=i,i=t}}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(){Ku.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}}const Qu=Ml((()=>new $u));let Ju=!1;const Yu=function(e){return Qu(e)};let Zu=Yu;function Xu(e){const t=ec(e,"data");return ic(Zu(t))}Xu._=Yu,Xu.lock=function(){Ju=!0},Xu.register=function(e){if(Ju)throw new TypeError("ripemd160 is locked");Zu=e},Object.freeze(Xu);let eh=!1;const th=function(e,t,n,r,s){return function(e,t,n,r,s){const i={sha256:Ql,sha512:uu}[s];return $a(null!=i,"invalid pbkdf2 algorithm","algorithm",s),Hl(i,e,t,{c:n,dkLen:r})}(e,t,n,r,s)};let nh=th;function rh(e,t,n,r,s){const i=ec(e,"password"),o=ec(t,"salt");return ic(nh(i,o,n,r,s))}rh._=th,rh.lock=function(){eh=!0},rh.register=function(e){if(eh)throw new Error("pbkdf2 is locked");nh=e},Object.freeze(rh);let sh=!1;const ih=function(e){return new Uint8Array(function(e){Ka(null!=du,"platform does not support secure random numbers","UNSUPPORTED_OPERATION",{operation:"randomBytes"}),$a(Number.isInteger(e)&&e>0&&e<=1024,"invalid length","length",e);const t=new Uint8Array(e);return du.getRandomValues(t),t}(e))};let oh=ih;function ah(e){return oh(e)}ah._=ih,ah.lock=function(){sh=!0},ah.register=function(e){if(sh)throw new Error("randomBytes is locked");oh=e},Object.freeze(ah);const ch=(e,t)=>e<<t|e>>>32-t;function lh(e,t,n,r,s,i){let o=e[t++]^n[r++],a=e[t++]^n[r++],c=e[t++]^n[r++],l=e[t++]^n[r++],u=e[t++]^n[r++],h=e[t++]^n[r++],d=e[t++]^n[r++],f=e[t++]^n[r++],p=e[t++]^n[r++],g=e[t++]^n[r++],m=e[t++]^n[r++],y=e[t++]^n[r++],w=e[t++]^n[r++],b=e[t++]^n[r++],_=e[t++]^n[r++],A=e[t++]^n[r++],v=o,E=a,k=c,S=l,T=u,R=h,I=d,C=f,O=p,x=g,N=m,P=y,D=w,B=b,U=_,L=A;for(let M=0;M<8;M+=2)T^=ch(v+D|0,7),O^=ch(T+v|0,9),D^=ch(O+T|0,13),v^=ch(D+O|0,18),x^=ch(R+E|0,7),B^=ch(x+R|0,9),E^=ch(B+x|0,13),R^=ch(E+B|0,18),U^=ch(N+I|0,7),k^=ch(U+N|0,9),I^=ch(k+U|0,13),N^=ch(I+k|0,18),S^=ch(L+P|0,7),C^=ch(S+L|0,9),P^=ch(C+S|0,13),L^=ch(P+C|0,18),E^=ch(v+S|0,7),k^=ch(E+v|0,9),S^=ch(k+E|0,13),v^=ch(S+k|0,18),I^=ch(R+T|0,7),C^=ch(I+R|0,9),T^=ch(C+I|0,13),R^=ch(T+C|0,18),P^=ch(N+x|0,7),O^=ch(P+N|0,9),x^=ch(O+P|0,13),N^=ch(x+O|0,18),D^=ch(L+U|0,7),B^=ch(D+L|0,9),U^=ch(B+D|0,13),L^=ch(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+C|0,s[i++]=p+O|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++]=_+U|0,s[i++]=A+L|0}function uh(e,t,n,r,s){let i=r+0,o=r+16*s;for(let a=0;a<16;a++)n[o+a]=e[t+16*(2*s-1)+a];for(let a=0;a<s;a++,i+=16,t+=16)lh(n,o,e,t,n,i),a>0&&(o+=16),lh(n,i,e,t+=16,n,o)}function hh(e,t,n){const r=Ll({dkLen:32,asyncTick:10,maxmem:1073742848},n),{N:s,r:i,p:o,dkLen:a,asyncTick:c,maxmem:l,onProgress:u}=r;if(vl(s),vl(i),vl(o),vl(a),vl(c),vl(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=Hl(Ql,e,t,{c:1,dkLen:h*o}),g=Cl(p),m=Cl(new Uint8Array(h*s)),y=Cl(new Uint8Array(h));let w=()=>{};if(u){const e=2*s*o,t=Math.max(Math.floor(e/1e4),1);let n=0;w=()=>{n++,!u||n%t&&n!==e||u(n/e)}}return{N:s,r:i,p:o,dkLen:a,blockSize32:d,V:m,B32:g,B:p,tmp:y,blockMixCb:w,asyncTick:c}}function dh(e,t,n,r,s){const i=Hl(Ql,e,n,{c:1,dkLen:t});return n.fill(0),r.fill(0),s.fill(0),i}let fh=!1,ph=!1;const gh=async function(e,t,n,r,s,i,o){return await async function(e,t,n){const{N:r,r:s,p:i,dkLen:o,blockSize32:a,V:c,B32:l,B:u,tmp:h,blockMixCb:d,asyncTick:f}=hh(e,t,n);for(let p=0;p<i;p++){const e=a*p;for(let n=0;n<a;n++)c[n]=l[e+n];let t=0;await Pl(r-1,f,(()=>{uh(c,t,c,t+=a,s),d()})),uh(c,(r-1)*a,l,e,s),d(),await Pl(r,f,(()=>{const t=l[e+a-16]%r;for(let n=0;n<a;n++)h[n]=l[e+n]^c[t*a+n];uh(h,0,l,e,s),d()}))}return dh(e,o,u,c,h)}(e,t,{N:n,r:r,p:s,dkLen:i,onProgress:o})},mh=function(e,t,n,r,s,i){return function(e,t,n){const{N:r,r:s,p:i,dkLen:o,blockSize32:a,V:c,B32:l,B:u,tmp:h,blockMixCb:d}=hh(e,t,n);for(let f=0;f<i;f++){const e=a*f;for(let t=0;t<a;t++)c[t]=l[e+t];for(let t=0,n=0;t<r-1;t++)uh(c,n,c,n+=a,s),d();uh(c,(r-1)*a,l,e,s),d();for(let t=0;t<r;t++){const t=l[e+a-16]%r;for(let n=0;n<a;n++)h[n]=l[e+n]^c[t*a+n];uh(h,0,l,e,s),d()}}return dh(e,o,u,c,h)}(e,t,{N:n,r:r,p:s,dkLen:i})};let yh=gh,wh=mh;async function bh(e,t,n,r,s,i,o){const a=ec(e,"passwd"),c=ec(t,"salt");return ic(await yh(a,c,n,r,s,i,o))}function _h(e,t,n,r,s,i){const o=ec(e,"passwd"),a=ec(t,"salt");return ic(wh(o,a,n,r,s,i))}bh._=gh,bh.lock=function(){ph=!0},bh.register=function(e){if(ph)throw new Error("scrypt is locked");yh=e},Object.freeze(bh),_h._=mh,_h.lock=function(){fh=!0},_h.register=function(e){if(fh)throw new Error("scryptSync is locked");wh=e},Object.freeze(_h);const Ah=function(e){return function(e){switch(e){case"sha256":return Ql.create();case"sha512":return uu.create()}$a(!1,"invalid hashing algorithm name","algorithm",e)}("sha256").update(e).digest()};let vh=Ah,Eh=!1;function kh(e){const t=ec(e,"data");return ic(vh(t))}kh._=Ah,kh.lock=function(){Eh=!0},kh.register=function(e){if(Eh)throw new Error("sha256 is locked");vh=e},Object.freeze(kh),Object.freeze(kh);
|
|
1
|
+
"use strict";var e,t,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,C,O,x,N,P,D,B,U,L,M,F,j,G,H,V,q,W,z,$,K,Q,J,Y,Z,X,ee,te,ne,re,se,ie,oe,ae,ce,le,ue,he,de,fe,pe,ge,me,ye,we,be,_e,Ae,ve,Ee,ke,Se,Te,Re,Ie,Ce,Oe,xe,Ne,Pe,De,Be,Ue,Le,Me,Fe,je,Ge,He,Ve,qe,We,ze,$e,Ke,Qe,Je,Ye,Ze,Xe,et,tt,nt,rt,st,it,ot,at,ct,lt,ut,ht,dt,ft,pt,gt,mt,yt,wt,bt,_t,At,vt,Et,kt,St,Tt,Rt,It,Ct,Ot,xt,Nt,Pt,Dt,Bt,Ut,Lt,Mt,Ft,jt,Gt,Ht,Vt,qt,Wt,zt,$t,Kt,Qt,Jt,Yt,Zt,Xt,en,tn,nn,rn,sn,on,an,cn,ln,un,hn,dn,fn,pn,gn,mn,yn,wn,bn,_n,An,vn,En,kn,Sn,Tn,Rn,In,Cn,On=Object.defineProperty,xn=(e,t,n)=>(((e,t,n)=>{t in e?On(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n})(e,"symbol"!=typeof t?t+"":t,n),n),Nn=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Pn=(e,t,n)=>(Nn(e,t,"read from private field"),n?n.call(e):t.get(e)),Dn=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},Bn=(e,t,n,r)=>(Nn(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),Un=(e,t,n,r)=>({set _(r){Bn(e,t,r,n)},get _(){return Pn(e,t,r)}}),Ln=(e,t,n)=>(Nn(e,t,"access private method"),n);const Mn=require("./ndn_types-08dc9ef1.js");class Fn extends Error{constructor(e,t,n){super(e),this.name="RPCError",this.code=t,this.data=n}}const jn=async(e,t)=>{if("undefined"!=typeof window&&"function"==typeof window.fetch)return window.fetch(e,t);if("undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch)return globalThis.fetch(e,t);throw new Fn("fetch is not available in this runtime")};class Gn{constructor(e,t=null,n=null,r={}){this.serverUrl=e,this.protocolType="HttpPostJson",this.seq=n??Date.now(),this.sessionToken=t||null,this.initToken=t||null,this.traceId=r.traceId||null,this.fetcher=r.fetcher??jn,this.sessionTokenProvider=r.sessionTokenProvider??null,this.sessionTokenOverride=void 0}async call(e,t,n={}){return this._call(e,t,n)}async callWithSessionToken(e,t,n){return this._call(t,n,{sessionToken:e})}setSeq(e){this.seq=e}resetSessionToken(){this.sessionToken=this.initToken,this.sessionTokenOverride=void 0}setSessionToken(e){this.sessionToken=e||null,this.sessionTokenOverride=e||null}getSessionToken(){return this.sessionToken}setTraceId(e){this.traceId=e||null}getTraceId(){return this.traceId}buildRequest(e,t,n,r,s){let i;return i=s?[n,r,s]:r?[n,r]:[n],{method:e,params:t,sys:i}}parseResponseSys(e,t){if(null==e)return null;if(!Array.isArray(e))throw new Fn("sys is not array");if(e.length<1)throw new Fn("sys is empty");const n=e[0];if("number"!=typeof n)throw new Fn("sys[0] is not number");if(n!==t)throw new Fn(`seq not match: ${n}!=${t}`);if(e.length>=2){const t=e[1];if("string"!=typeof t)throw new Fn("sys[1] trace_id is not string");return t}return null}async prepareSessionToken(e){if(Object.prototype.hasOwnProperty.call(e,"sessionToken"))return e.sessionToken||null;if(void 0!==this.sessionTokenOverride)return this.sessionTokenOverride;if(this.sessionTokenProvider){const e=await this.sessionTokenProvider();void 0!==e&&(this.sessionToken=e||null)}return this.sessionToken}prepareTraceId(e){return Object.prototype.hasOwnProperty.call(e,"traceId")?e.traceId||null:this.traceId}async _call(e,t,n){const r=await this.prepareSessionToken(n),s=this.prepareTraceId(n),i=this.seq;this.seq+=1;const o=this.buildRequest(e,t,i,r,s);try{const e=await this.fetcher(this.serverUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!e.ok)throw new Fn(`RPC call error: ${e.status}`);const t=await e.json();if(this.parseResponseSys(t.sys,i),"error"in t&&t.error)throw new Fn(`RPC call error: ${t.error}`,"string"==typeof t.code?t.code:void 0,t.data);if(!("result"in t)||void 0===t.result)throw new Fn("RPC response missing result");return t.result}catch(a){if(a instanceof Fn)throw a;const e=a instanceof Error?a.message:String(a);throw new Fn(`RPC call failed: ${e}`)}}}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(e,t={}){Hn(),this.zoneHostname=e,this.navigate=t.navigate??(e=>{window.location.assign(e)})}buildLoginURL(e=null){Hn();const t=e??window.location.href;return`${`${window.location.protocol}//sys.${this.zoneHostname}/login`}?redirect_url=${encodeURIComponent(t)}`}async login(e=null){const t=this.buildLoginURL(e);this.navigate(t)}}const qn=["session_kind_not_allowed","session_ceiling_exceeded","resource_grant_missing","entry_unavailable","zone_method_disabled","account_state","credential_state","source_revoked","authorization_unavailable"],Wn="access_denied";function zn(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function $n(e){if(!zn(e)||"string"!=typeof e.reason)return null;if(!qn.includes(e.reason))return null;return(zn(e.adjust)&&"string"==typeof e.adjust.party?e.adjust:null)?e:null}const Kn={kind:"anonymous"};function Qn(e){if(!zn(e))return null;if("anonymous"===e.kind)return Kn;const t=t=>"string"==typeof e[t]?e[t]:null;if("account"===e.kind){const n=t("user_id"),r=t("did"),s=t("user_type");return n&&r&&s&&"boolean"==typeof e.restricted?e:null}return"external"===e.kind&&t("did")&&"boolean"==typeof e.restricted?e:null}function Jn(e){switch(e.kind){case"account":return`${e.zone_host}|account|${e.user_id}`;case"external":return`${e.zone_host}|external|${e.did}`;default:return"anonymous"}}const Yn="https://jump.buckyos.org",Zn={app_installer:"/sysdlg/app_installer"};function Xn(e){const t=e.trim().toLowerCase().replace(/\.$/,"");if(!t||t.length>253)return null;if(/[^a-z0-9.-]/.test(t))return null;const n=t.split(".");if(n.length<2)return null;for(const r of n)if(!r||r.length>63||r.startsWith("-")||r.endsWith("-"))return null;return t}const er="aiworkspace";class tr extends Error{constructor(e){super(`${e.code}${e.sub_code?`/${e.sub_code}`:""}: ${e.detail}`),this.name="AiwsFailure",this.code=e.code,this.subCode=e.sub_code,this.data=e.data}}class nr{constructor(e){this.rpcClient=e}async call(e,t){const n=await this.rpcClient.call(e,t);if(n&&"object"==typeof n&&!1===n.ok)throw new tr(n.error);return n}list(){return this.call("ws.list",{})}info(e){return this.call("ws.get_info",{workspace_id:e})}getUserState(e){return this.call("ws.get_user_state",{workspace_id:e})}setUserState(e,t,n){return this.call("ws.set_user_state",{workspace_id:e,entries:t,...n?{expect:n}:{}})}resolve(e,t){return this.call("doc.resolve",{workspace_id:e,reference:t})}resolvePath(e,t){return this.call("doc.resolve",{workspace_id:e,path:t})}read(e,t,n){return this.call("doc.read",{workspace_id:e,entity_id:t,...n?{selector:n}:{}})}query(e,t){return this.call("doc.query",{workspace_id:e,...t})}outline(e){return this.call("doc.outline",{workspace_id:e})}prepare(e,t){return this.rpcClient.call("doc.prepare",{workspace_id:e,...t})}commit(e,t){return this.rpcClient.call("doc.commit",{workspace_id:e,...t})}getSubmission(e,t,n){return this.call("doc.get_submission",{workspace_id:e,epoch:t,idempotency_key:n})}runStart(e,t,n,r){return this.call("proc.start",{workspace_id:e,program:t,params:n,idempotency_key:r})}runGet(e,t,n){return this.call("proc.get",{workspace_id:e,run_id:t,...n?{choices:n}:{}})}runList(e,t,n){return this.call("proc.list",{workspace_id:e,...t?{wish_id:t}:{},...n?{limit:n}:{}})}runClaim(e,t,n,r){return this.call("proc.claim",{workspace_id:e,run_id:t,claim_token:n,...r?{executor:r}:{}})}runHeartbeat(e,t,n,r){return this.call("proc.heartbeat",{workspace_id:e,run_id:t,attempt:n,...r?{progress:r}:{}})}runReport(e,t){return this.call("proc.report",{workspace_id:e,...t})}runApply(e,t,n,r){return this.call("proc.apply",{workspace_id:e,run_id:t,plan_digest:n,...r?{session_id:r}:{}})}runCancel(e,t){return this.call("proc.cancel",{workspace_id:e,run_id:t})}}function rr(e){if(!e||"object"!=typeof e)throw new Fn("verify-hub auth target is required");if("app"===e.kind&&"string"==typeof e.app_instance_id&&e.app_instance_id.length>0)return{kind:"app",app_instance_id:e.app_instance_id};if("system"===e.kind&&"string"==typeof e.service_id&&e.service_id.length>0)return{kind:"system",service_id:e.service_id};throw new Fn("invalid verify-hub auth target")}function sr(e){const t=rr(e);if("system"===t.kind)return t.service_id;const n=t.app_instance_id.lastIndexOf("@");if(n<=0||n===t.app_instance_id.length-1)throw new Fn("app auth target must use `<appId>@<ownerUserId>`");return t.app_instance_id.slice(0,n)}class ir{constructor(e){this.rpcClient=e}setSeq(e){this.rpcClient.setSeq(e)}async loginByJwt(e){return this.rpcClient.resetSessionToken(),this.rpcClient.call("login_by_jwt",{type:"jwt",jwt:e.jwt,target:rr(e.target)})}async loginByPassword(e){this.rpcClient.resetSessionToken();const t={type:"password",username:e.username,password:e.password,target:rr(e.target)};return void 0!==e.login_nonce&&(t.login_nonce=e.login_nonce),e.source_url&&(t.source_url=e.source_url),this.rpcClient.call("login_by_password",t)}async sudoByPassword(e){this.rpcClient.resetSessionToken();const t={username:e.username,password:e.password,target:rr(e.target)};return void 0!==e.aud&&(t.aud=e.aud),void 0!==e.login_nonce&&(t.login_nonce=e.login_nonce),this.rpcClient.call("sudo_by_password",t)}async refreshToken(e){return this.rpcClient.call("refresh_token",{refresh_token:e.refresh_token})}async verifyToken(e){const t={session_token:e.session_token};return void 0!==e.expected_target&&(t.expected_target=rr(e.expected_target)),this.rpcClient.call("verify_token",t)}}const or="task_not_found",ar="permission_denied",cr="revision_conflict",lr="stale_runner_epoch",ur="invalid_task_phase",hr="control_not_available",dr="control_already_pending",fr="task_already_completed",pr="input_schema_mismatch",gr="result_schema_mismatch",mr="idempotency_conflict",yr="task_schema_not_found",wr=[or,ar,cr,lr,ur,hr,dr,fr,pr,gr,mr,yr];function br(e){return`/task_mgr/${e}`}function _r(e){const t=e instanceof Error?e.message:String(e);for(const n of wr){const e=t.indexOf(n);if(e<0)continue;const r=0===e?"":t[e-1],s=t[e+n.length]??"";if((!r||/[\s:]/.test(r))&&(!s||/[\s:]/.test(s)))return n}return null}var Ar=(e=>(e.Unbound="Unbound",e.App="App",e.HumanSet="HumanSet",e))(Ar||{}),vr=(e=>(e.Promised="Promised",e.Accepted="Accepted",e.Running="Running",e.Waiting="Waiting",e.Paused="Paused",e.Terminal="Terminal",e))(vr||{});function Er(e){return"Terminal"===e}var kr=(e=>(e.Dispatch="Dispatch",e.Capacity="Capacity",e.Authorization="Authorization",e.HumanInput="HumanInput",e.ChildTask="ChildTask",e.Dependency="Dependency",e.External="External",e.Other="Other",e))(kr||{}),Sr=(e=>(e.Succeeded="Succeeded",e.Failed="Failed",e.Canceled="Canceled",e))(Sr||{}),Tr=(e=>(e.Pause="Pause",e.Resume="Resume",e.Cancel="Cancel",e))(Tr||{});var Rr=(e=>(e.ReadMeta="ReadMeta",e.ReadInput="ReadInput",e.ReadResult="ReadResult",e.ReportProgress="ReportProgress",e.Control="Control",e.Commit="Commit",e.CreateChild="CreateChild",e.Reassign="Reassign",e.Grant="Grant",e.Archive="Archive",e))(Rr||{}),Ir=(e=>(e.SelfOnly="SelfOnly",e.Subtree="Subtree",e.WholeTree="WholeTree",e))(Ir||{}),Cr=(e=>(e.MetaOnly="MetaOnly",e.Payload="Payload",e.Full="Full",e))(Cr||{}),Or=(e=>(e.User="User",e.System="System",e))(Or||{}),xr=(e=>(e.TaskCreated="TaskCreated",e.RunnerBound="RunnerBound",e.RunnerReleased="RunnerReleased",e.PhaseChanged="PhaseChanged",e.WaitReasonChanged="WaitReasonChanged",e.ProgressReported="ProgressReported",e.ControlProfileChanged="ControlProfileChanged",e.ControlRequested="ControlRequested",e.ControlSuperseded="ControlSuperseded",e.ControlApplied="ControlApplied",e.ControlRejected="ControlRejected",e.AssigneesChanged="AssigneesChanged",e.AccessGranted="AccessGranted",e.AccessRevoked="AccessRevoked",e.ResultCommitted="ResultCommitted",e.TaskFailed="TaskFailed",e.TaskCanceled="TaskCanceled",e.TaskArchived="TaskArchived",e.PayloadRedacted="PayloadRedacted",e))(xr||{});function Nr(e,t,n){const r=function(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw new Fn(`Expected ${t} in TaskMgr response`);return e}(e,n);if(!(t in r))throw new Fn(`Expected ${t} in TaskMgr response`);return r[t]}function Pr(e){const t=Nr(e,"task","task result");if(!t||"object"!=typeof t||"string"!=typeof t.task_id)throw new Fn("Expected a string task_id in TaskMgr response");return t}function Dr(){const e=globalThis.crypto;if(e&&"function"==typeof e.getRandomValues){const t=new Uint8Array(16);return e.getRandomValues(t),`ctl-${Array.from(t,(e=>e.toString(16).padStart(2,"0"))).join("")}`}return`ctl-${Date.now().toString(16)}${Math.random().toString(16).slice(2)}`}class Br{constructor(e){this.rpcClient=e}setSeq(e){this.rpcClient.setSeq(e)}async callTask(e,t){return Pr(await this.rpcClient.call(e,t))}async createTask(e){return this.callTask("create_task",e)}async getTask(e){return Pr(await this.rpcClient.call("get_task",{task_id:e}))}async listTasks(e={}){const t=await this.rpcClient.call("list_tasks",e),n=Nr(t,"tasks","task summary page");if(!Array.isArray(n))throw new Fn("Expected tasks array in TaskMgr response");return t}async getTaskTree(e){const t=await this.rpcClient.call("get_task_tree",e),n=Nr(t,"tasks","task tree page");if(!Array.isArray(n))throw new Fn("Expected tasks array in TaskMgr response");return t}async getSubtasks(e){const t=await this.rpcClient.call("get_subtasks",e),n=Nr(t,"tasks","subtask page");if(!Array.isArray(n))throw new Fn("Expected tasks array in TaskMgr response");return t}async archiveTask(e){return this.callTask("archive_task",e)}async requestControl(e){const t=await this.rpcClient.call("request_control",e),n=Nr(t,"kind","control result");if("Task"!==n&&"Batch"!==n)throw new Fn(`Invalid TaskMgr control result kind: ${n}`);return t}async updateAssignees(e){return this.callTask("update_assignees",e)}async grantTaskAccess(e){return this.callTask("grant_task_access",e)}async revokeTaskAccess(e){return this.callTask("revoke_task_access",e)}async listTaskAccess(e){const t=Nr(await this.rpcClient.call("list_task_access",{task_id:e}),"grants","task access result");if(!Array.isArray(t))throw new Fn("Expected grants array in TaskMgr response");return t}async reportStarted(e){return this.callTask("report_started",e)}async reportProgress(e){return this.callTask("report_progress",e)}async reportWaiting(e){return this.callTask("report_waiting",e)}async reportRunning(e){return this.callTask("report_running",e)}async updateControlProfile(e){return this.callTask("update_control_profile",e)}async ackControl(e){return this.callTask("ack_control",e)}async commitResult(e){return this.callTask("commit_result",e)}async failTask(e){return this.callTask("fail_task",e)}async createPromisedTask(e){return this.callTask("create_promised_task",e)}async setPromiseWait(e){return this.callTask("set_promise_wait",e)}async bindAppExecutor(e){return this.callTask("bind_app_executor",e)}async releaseAppExecutor(e){return this.callTask("release_app_executor",e)}async finishPromiseFailure(e){return this.callTask("finish_promise_failure",e)}async cancelPromisedTask(e){return this.callTask("cancel_promised_task",e)}async registerTaskSchema(e){return this.rpcClient.call("register_task_schema",{definition:e})}async getTaskSchema(e,t){return this.rpcClient.call("get_task_schema",{schema_id:e,schema_version:t})}async listTaskSchemas(e={}){const t=Nr(await this.rpcClient.call("list_task_schemas",e),"schemas","task schema list");if(!Array.isArray(t))throw new Fn("Expected schemas array in TaskMgr response");return t}async setTaskSchemaEnabled(e,t,n){return this.rpcClient.call("set_task_schema_enabled",{schema_id:e,schema_version:t,enabled:n})}async listTaskEvents(e){const t=await this.rpcClient.call("list_task_events",e),n=Nr(t,"events","task event list");if(!Array.isArray(n))throw new Fn("Expected events array in TaskMgr response");return t}async addTaskNote(e){return Nr(await this.rpcClient.call("add_task_note",e),"note","add task note result")}async listTaskNotes(e){const t=Nr(await this.rpcClient.call("list_task_notes",{task_id:e}),"notes","task note list");if(!Array.isArray(t))throw new Fn("Expected notes array in TaskMgr response");return t}async cancelTask(e,t=!1){return this.requestControl({task_id:e,action:"Cancel",request_id:Dr(),recursive:t})}snapshotEnvelope(e){return{task_id:e.task_id,app_instance_id:"App"===e.executor.kind?e.executor.app_instance_id:void 0,runner_epoch:e.runner_epoch,expected_revision:e.revision}}async runnerStart(e){const t=await this.getTask(e);let n;if("Accepted"===t.phase)n=this.reportStarted(this.snapshotEnvelope(t));else{if("Waiting"!==t.phase)return t;n=this.reportRunning(this.snapshotEnvelope(t))}try{return await n}catch(r){const t=_r(r);if(t===cr||t===ur)return this.getTask(e);throw r}}async runnerProgress(e,t,n){const r=await this.getTask(e);if(Er(r.phase))return r;try{return await this.reportProgress({...this.snapshotEnvelope(r),progress:t,message:n})}catch(s){if(_r(s)!==cr)throw s;const r=await this.getTask(e);return this.reportProgress({...this.snapshotEnvelope(r),progress:t,message:n})}}async runnerWait(e,t){const n=await this.runnerStart(e);return"Running"!==n.phase?n:this.reportWaiting({...this.snapshotEnvelope(n),reason:t})}async runnerComplete(e,t){const n=await this.getTask(e);if(Er(n.phase))return n;try{return await this.commitResult({task_id:n.task_id,result:t,app_instance_id:this.snapshotEnvelope(n).app_instance_id,runner_epoch:n.runner_epoch,expected_revision:n.revision})}catch(r){if(_r(r)!==cr)throw r;const n=await this.getTask(e);return Er(n.phase)?n:this.commitResult({task_id:n.task_id,result:t,app_instance_id:this.snapshotEnvelope(n).app_instance_id,runner_epoch:n.runner_epoch,expected_revision:n.revision})}}async runnerFail(e,t,n,r){const s=await this.getTask(e);return Er(s.phase)?s:this.failTask({...this.snapshotEnvelope(s),error:{code:t,message:n,detail:r}})}}var Ur=(e=>(e.Autonomous="autonomous",e.HumanConfirm="human_confirm",e.HumanRequired="human_required",e))(Ur||{}),Lr=(e=>(e.Single="single",e.FiniteSeekable="finite_seekable",e.FiniteSequential="finite_sequential",e))(Lr||{}),Mr=(e=>(e.All="all",e.Any="any",e.NOfM="n_of_m",e))(Mr||{}),Fr=(e=>(e.Human="human",e.Abort="abort",e))(Fr||{}),jr=(e=>(e.Draft="draft",e.Active="active",e.Archived="archived",e))(jr||{}),Gr=(e=>(e.Created="created",e.Running="running",e.WaitingHuman="waiting_human",e.Completed="completed",e.Failed="failed",e.Paused="paused",e.Aborted="aborted",e.BudgetExhausted="budget_exhausted",e))(Gr||{}),Hr=(e=>(e.Pending="pending",e.Ready="ready",e.Running="running",e.Completed="completed",e.Failed="failed",e.Retrying="retrying",e.WaitingHuman="waiting_human",e.Skipped="skipped",e.Aborted="aborted",e.Cancelled="cancelled",e))(Hr||{}),Vr=(e=>(e.Approve="approve",e.Modify="modify",e.Reject="reject",e.Retry="retry",e.Skip="skip",e.Abort="abort",e.Rollback="rollback",e))(Vr||{}),qr=(e=>(e.Enabled="enabled",e.Paused="paused",e.Archived="archived",e.Error="error",e))(qr||{}),Wr=(e=>(e.Skip="skip",e.RunOnce="run_once",e.CatchUp="catch_up",e.Manual="manual",e))(Wr||{}),zr=(e=>(e.Created="created",e.TaskCreated="task_created",e.Skipped="skipped",e.Failed="failed",e))(zr||{});function $r(e,t){if(!(t in e))throw new Fn(`Expected ${t} in workflow response`);return e[t]}class Kr{constructor(e){this.rpcClient=e}setSeq(e){this.rpcClient.setSeq(e)}async callOk(e,t){const n=function(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new Fn("Invalid workflow RPC response format");return e}(await this.rpcClient.call(e,t));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(e){const t=await this.callOk("submit_definition",e);return{workflow_id:$r(t,"workflow_id"),version:$r(t,"version"),analysis:$r(t,"analysis"),definition:$r(t,"definition")}}async getDefinition(e){return $r(await this.callOk("get_definition",{workflow_id:e}),"definition")}async listDefinitions(e={}){return $r(await this.callOk("list_definitions",e),"definitions")}async archiveDefinition(e){return $r(await this.callOk("archive_definition",{workflow_id:e}),"status")}async dryRun(e){const t=await this.callOk("dry_run",{definition:e});return{analysis:$r(t,"analysis"),graph:$r(t,"graph")}}async createRun(e){return await this.callOk("create_run",e)}async startRun(e){return await this.callOk("start_run",{run_id:e})}async tickRun(e){return await this.callOk("tick_run",{run_id:e})}async getRunGraph(e){return await this.callOk("get_run_graph",{run_id:e})}async listRuns(e={}){return $r(await this.callOk("list_runs",e),"runs")}async submitStepOutput(e){return await this.callOk("submit_step_output",e)}async reportStepProgress(e){return await this.callOk("report_step_progress",e)}async requestHuman(e){return await this.callOk("request_human",e)}async submitAmendment(e){return $r(await this.callOk("submit_amendment",e),"amendment")}async approveAmendment(e){const t=await this.callOk("approve_amendment",e);return{amendment:$r(t,"amendment"),plan_version:$r(t,"plan_version")}}async rejectAmendment(e){const t=await this.callOk("reject_amendment",e);return{amendment:$r(t,"amendment"),plan_version:$r(t,"plan_version")}}async getHistory(e){return await this.callOk("get_history",e)}async subscribeEvents(e){return await this.callOk("subscribe_events",e)}async createScheduledTask(e){return $r(await this.callOk("create_scheduled_task",e),"schedule")}async updateScheduledTask(e){return $r(await this.callOk("update_scheduled_task",e),"schedule")}async getScheduledTask(e){return $r(await this.callOk("get_scheduled_task",{schedule_id:e}),"schedule")}async listScheduledTasks(e={}){return $r(await this.callOk("list_scheduled_tasks",e),"schedules")}async pauseScheduledTask(e){return $r(await this.callOk("pause_scheduled_task",{schedule_id:e}),"schedule")}async resumeScheduledTask(e){return $r(await this.callOk("resume_scheduled_task",{schedule_id:e}),"schedule")}async archiveScheduledTask(e){return $r(await this.callOk("archive_scheduled_task",{schedule_id:e}),"schedule")}async runScheduledTaskNow(e){return $r(await this.callOk("run_scheduled_task_now",e),"fire")}async getScheduledTaskHistory(e){return $r(await this.callOk("get_scheduled_task_history",e),"fires")}async validateScheduledTask(e){return await this.callOk("validate_scheduled_task",e)}}const Qr=["services/","system/rbac/"];class Jr{constructor(e,t=null,n={}){this.configCache=new Map,this.rpcClient=new Gn(e,t,null,n)}setSeq(e){this.rpcClient.setSeq(e)}async syncSessionToken(e){this.rpcClient.setSessionToken(e)}getSessionToken(){return this.rpcClient.getSessionToken()}needCache(e){return Qr.some((t=>e.startsWith(t)))}getUnixTimestamp(){return Math.floor(Date.now()/1e3)}getConfigCache(e){const t=this.configCache.get(e);return t?t.cachedAt+10<this.getUnixTimestamp()?(this.configCache.delete(e),null):t:null}setConfigCache(e,t,n){if(!this.needCache(e))return!0;const r=this.configCache.get(e);return this.configCache.set(e,{value:t,version:n,cachedAt:this.getUnixTimestamp()}),!r||(r.value!==t||r.version!==n)}removeConfigCache(e){this.configCache.delete(e)}async get(e){const t=this.getConfigCache(e);if(null!=t)return{value:t.value,version:t.version,is_changed:!1};const n=await this.rpcClient.call("sys_config_get",{key:e});if(null==n)throw new Error(`system_config key not found: ${e}`);if("string"!=typeof n.value||"number"!=typeof n.version)throw new Error(`invalid sys_config_get response for key: ${e}`);const r=this.setConfigCache(e,n.value,n.version);return{value:n.value,version:n.version,is_changed:r}}async set(e,t){if(!e||!t)throw new Error("key or value is empty");if(e.includes(":"))throw new Error("key can not contain ':'");return await this.rpcClient.call("sys_config_set",{key:e,value:t}),this.removeConfigCache(e),0}async setByJsonPath(e,t,n){return await this.rpcClient.call("sys_config_set_by_json_path",{key:e,json_path:t,value:n}),this.removeConfigCache(e),0}async create(e,t){return await this.rpcClient.call("sys_config_create",{key:e,value:t}),this.removeConfigCache(e),0}async delete(e){return await this.rpcClient.call("sys_config_delete",{key:e}),this.removeConfigCache(e),0}async append(e,t){return await this.rpcClient.call("sys_config_append",{key:e,append_value:t}),this.removeConfigCache(e),0}async list(e){return this.rpcClient.call("sys_config_list",{key:e})}async execTx(e,t){const n={actions:e};t&&(n.main_key=`${t[0]}:${t[1]}`),await this.rpcClient.call("sys_config_exec_tx",n);for(const r of Object.keys(e))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 Yr={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_GENERATE:"video.generate",VIDEO_EDIT:"video.edit",VIDEO_EXTEND:"video.extend",VIDEO_UPSCALE:"video.upscale",AGENT_COMPUTER_USE:"agent.computer_use"},Zr={ROUTE_RESOLVE:"route.resolve",HELPER_LLM_CHAT:"helper.llm_chat",HELPER_TEXT_TO_IMAGE:"helper.text_to_image",HELPER_VIDEO_GENERATE:"helper.video_generate",CANCEL:"cancel"},Xr={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"},es={RULE_LIST:"quota.rule.list",RULE_GET:"quota.rule.get",RULE_PREVIEW:"quota.rule.preview",RULE_CREATE:"quota.rule.create",RULE_UPDATE:"quota.rule.update",RULE_DELETE:"quota.rule.delete",ACCOUNT_GET:"quota.account.get",ACCOUNT_RECHARGE:"quota.account.recharge",RECHARGE_GET:"quota.recharge.get",VISIBILITY_GET:"visibility.get",VISIBILITY_UPDATE:"visibility.update",VISIBILITY_PREVIEW:"visibility.preview"},ts={...Yr,...Zr,...Xr,...es},ns={IMMEDIATE:"immediate",STREAM:"stream"},rs=["quota_exhausted","quota_budget_exceeded","quota_unavailable","resource_not_permitted","attribution_unavailable"];const ss=new Set(Object.values(Yr));function is(e){const t={system:["text"],developer:["text"],user:["text","image","document"],assistant:["text","image","document","tool_use","thinking","provider_state"],tool:["tool_result"]};if(!e||!Array.isArray(e.content)||!t[e.role])throw new Fn("invalid AiMessage");if("tool"===e.role&&(1!==e.content.length||"tool_result"!==e.content[0].type))throw new Fn("role Tool requires exactly one ToolResult block");for(const n of e.content){if(!t[e.role].includes(n.type))throw new Fn(`AiMessage role ${e.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 os(e){if(!e||2!==e.split("@").length||e.startsWith("@")||e.endsWith("@"))throw new Fn("exact_model must be `<provider_model_id>[:<variant>]@<provider_instance_name>`")}function as(e){if(!(null==e?void 0:e.trim())||e.includes("@"))throw new Fn("logical_model must be a non-empty logical path without `@`")}function cs(e,t){for(const s of Object.keys(e))if(!t.includes(s))throw new Fn(`unknown field \`${s}\``);const n=e.execution_mode;if(void 0!==n&&n!==ns.IMMEDIATE&&n!==ns.STREAM)throw new Fn("execution_mode must be `immediate` or `stream`");const r=e.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 ls=["exact_model","trace_id","execution_mode","idempotency_key","task_options","session_id"],us={[Yr.CHAT_COMPLETIONS_CREATE]:[...ls,"web_search","messages","tools","response_format","temperature","top_p","max_output_tokens","seed","stop","output"],[Yr.IMAGES_GENERATE]:[...ls,"prompt","negative_prompt","n","aspect_ratio","size","quality","style","seed","output"],[Yr.EMBEDDING_TEXT]:[...ls,"items","chunking","embedding_space_id","dimensions","normalize","prefer_artifact"],[Yr.EMBEDDING_MULTIMODAL]:[...ls,"items","dimensions","normalize"],[Yr.DECISION_EVALUATE]:[...ls,"state","questions"],[Yr.RERANK]:[...ls,"query","documents","n","return_documents"],[Yr.IMAGE_IMG2IMG]:[...ls,"images","prompt","strength","output"],[Yr.IMAGE_INPAINT]:[...ls,"image","mask","prompt","mask_semantics","output"],[Yr.IMAGE_UPSCALE]:[...ls,"image","scale","target_width","target_height","preserve_faces","output"],[Yr.IMAGE_BG_REMOVE]:[...ls,"image","mode","output"],[Yr.VISION_OCR]:[...ls,"document","level","language_hints","return_layout","return_artifacts"],[Yr.VISION_CAPTION]:[...ls,"image","style","language","n"],[Yr.VISION_DETECT]:[...ls,"image","classes","score_threshold","bbox_spec"],[Yr.VISION_SEGMENT]:[...ls,"image","prompt","mask_format","return_bitmap_mask"],[Yr.AUDIO_TTS]:[...ls,"text","voice","speed","output"],[Yr.AUDIO_ASR]:[...ls,"audio","language","timestamps","diarization","output_formats"],[Yr.AUDIO_MUSIC]:[...ls,"prompt","duration_seconds","instrumental","lyrics","seed","output"],[Yr.AUDIO_ENHANCE]:[...ls,"audio","task","strength","return_stems"],[Yr.VIDEO_GENERATE]:[...ls,"prompt","negative_prompt","conditions","output","seed"],[Yr.VIDEO_EDIT]:[...ls,"video","prompt","output"],[Yr.VIDEO_EXTEND]:[...ls,"video","prompt","continuation_handle","duration_seconds","resolution"],[Yr.VIDEO_UPSCALE]:[...ls,"video","target_resolution","denoise","sharpen","output"],[Yr.AGENT_COMPUTER_USE]:[...ls,"task","environment","allowed_actions"],[Zr.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"],[Zr.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"],[Zr.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"],[Zr.HELPER_VIDEO_GENERATE]:["logical_model","trace_id","execution_mode","requirements","disable","policy","prompt","negative_prompt","conditions","output","seed","idempotency_key","task_options","session_overlay","session_id"],[Zr.CANCEL]:["task_id"],[Xr.SERVICE_RELOAD_SETTINGS]:[],[Xr.QUOTA_QUERY]:["app_id"],[Xr.USAGE_QUERY]:["time_range","filters","group_by","time_bucket","output_mode","limit","cursor","zone_wide"],[Xr.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"],[Xr.ROUTING_GET]:[],[Xr.ROUTING_PREVIEW]:["paths","explain","requirements"],[Xr.ROUTING_UPDATE]:["settings_revision","provider_weights"],[Xr.PROVIDER_CATALOG]:[],[Xr.PROTOCOL_ADAPTER_LIST]:[],[Xr.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"],[Xr.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"],[Xr.PROVIDER_LIST]:["method","view"],[Xr.PROVIDER_HEALTH]:["exact_model"],[Xr.PROVIDER_UPDATE]:["provider_instance_name","settings_revision","enabled","base_url","credential","provider_profile_id","protocol_adapter_id","discovery","instance_rules"],[Xr.PROVIDER_DELETE]:["provider_instance_name"],[Xr.PROVIDER_REFRESH_MODELS]:["provider_instance_name"],[Xr.MODELS_LIST]:["view"],[Xr.DRIVER_METADATA_UPDATE_GET]:[],[Xr.DRIVER_METADATA_UPDATE_SET]:["enabled","source_url","interval_secs"]};class hs{constructor(e){this.rpcClient=e}setSeq(e){this.rpcClient.setSeq(e)}call(e,t){const n=us[e],r=(null==n?void 0:n.includes("execution_mode"))&&void 0===t.execution_mode?{...t,execution_mode:ns.IMMEDIATE}:t;return n&&cs(r,n),this.rpcClient.call(e,r)}inference(e,t){return os(t.exact_model),this.call(e,t)}routeResolve(e){return as(e.logical_model),this.call(Zr.ROUTE_RESOLVE,e)}chatCompletionsCreate(e){return e.messages.forEach(is),this.inference(Yr.CHAT_COMPLETIONS_CREATE,e)}imagesGenerate(e){return this.inference(Yr.IMAGES_GENERATE,e)}helperLlmChat(e){return as(e.logical_model),e.messages.forEach(is),this.call(Zr.HELPER_LLM_CHAT,e)}helperTextToImage(e){return as(e.logical_model),this.call(Zr.HELPER_TEXT_TO_IMAGE,e)}embeddingText(e){return this.inference(Yr.EMBEDDING_TEXT,e)}embeddingMultimodal(e){return this.inference(Yr.EMBEDDING_MULTIMODAL,e)}async decisionEvaluate(e){ys(e);const t=await this.inference(Yr.DECISION_EVALUATE,e);return"succeeded"===t.status&&ws(e,t.answers??[]),t}rerank(e){return this.inference(Yr.RERANK,e)}imageToImage(e){return this.inference(Yr.IMAGE_IMG2IMG,e)}imageInpaint(e){return this.inference(Yr.IMAGE_INPAINT,e)}imageUpscale(e){return this.inference(Yr.IMAGE_UPSCALE,e)}imageBackgroundRemove(e){return this.inference(Yr.IMAGE_BG_REMOVE,e)}visionOcr(e){return this.inference(Yr.VISION_OCR,e)}visionCaption(e){return this.inference(Yr.VISION_CAPTION,e)}visionDetect(e){return this.inference(Yr.VISION_DETECT,e)}visionSegment(e){return this.inference(Yr.VISION_SEGMENT,e)}audioTextToSpeech(e){return this.inference(Yr.AUDIO_TTS,e)}audioSpeechRecognition(e){return this.inference(Yr.AUDIO_ASR,e)}audioMusic(e){return this.inference(Yr.AUDIO_MUSIC,e)}audioEnhance(e){return this.inference(Yr.AUDIO_ENHANCE,e)}videoGenerate(e){return Cs(e),this.inference(Yr.VIDEO_GENERATE,e)}helperVideoGenerate(e){return as(e.logical_model),Cs(e),xs(e),this.call(Zr.HELPER_VIDEO_GENERATE,e)}videoEdit(e){return Os(e),this.inference(Yr.VIDEO_EDIT,e)}videoExtend(e){return this.inference(Yr.VIDEO_EXTEND,e)}videoUpscale(e){return this.inference(Yr.VIDEO_UPSCALE,e)}computerUse(e){return this.inference(Yr.AGENT_COMPUTER_USE,e)}cancel(e){if(!e)throw new Fn("cancel requires non-empty task_id");return this.call(Zr.CANCEL,{task_id:e})}reloadSettings(){return this.call(Xr.SERVICE_RELOAD_SETTINGS,{})}queryQuota(e={}){return this.call(Xr.QUOTA_QUERY,e)}queryUsage(e){return this.call(Xr.USAGE_QUERY,e)}queryTrace(e={}){return this.call(Xr.TRACE_QUERY,e)}previewRouting(e={}){return this.call(Xr.ROUTING_PREVIEW,e)}getRouting(){return this.call(Xr.ROUTING_GET,{})}updateRouting(e){return this.call(Xr.ROUTING_UPDATE,e)}providerCatalog(){return this.call(Xr.PROVIDER_CATALOG,{})}listProtocolAdapters(){return this.call(Xr.PROTOCOL_ADAPTER_LIST,{})}validateProvider(e){return this.call(Xr.PROVIDER_VALIDATE,e)}addProvider(e){return this.call(Xr.PROVIDER_ADD,e)}listProviders(e={}){return this.call(Xr.PROVIDER_LIST,e)}providerHealth(e){return os(e.exact_model),this.call(Xr.PROVIDER_HEALTH,e)}updateProvider(e){return this.call(Xr.PROVIDER_UPDATE,e)}deleteProvider(e){return this.call(Xr.PROVIDER_DELETE,e)}refreshProviderModels(e){return this.call(Xr.PROVIDER_REFRESH_MODELS,e)}listModels(e={}){return this.call(Xr.MODELS_LIST,e)}listQuotaRules(e={}){return this.call(es.RULE_LIST,e)}getQuotaRule(e){return this.call(es.RULE_GET,{rule_id:e})}previewQuotaRule(e){return this.call(es.RULE_PREVIEW,{draft:e})}createQuotaRule(e){return this.call(es.RULE_CREATE,{draft:e})}updateQuotaRule(e){return this.call(es.RULE_UPDATE,e)}deleteQuotaRule(e,t){return this.call(es.RULE_DELETE,{rule_id:e,expected_version:t})}getQuotaAccount(e){return this.call(es.ACCOUNT_GET,{account_id:e})}rechargeQuotaAccount(e){return this.call(es.ACCOUNT_RECHARGE,e)}getQuotaRecharge(e){return this.call(es.RECHARGE_GET,{recharge_id:e})}getVisibility(){return this.call(es.VISIBILITY_GET,{})}updateVisibility(e){return this.call(es.VISIBILITY_UPDATE,e)}previewVisibility(e={}){return this.call(es.VISIBILITY_PREVIEW,e)}getDriverMetadataUpdate(){return this.call(Xr.DRIVER_METADATA_UPDATE_GET,{})}setDriverMetadataUpdate(e){return this.call(Xr.DRIVER_METADATA_UPDATE_SET,e)}}function ds(e,t=!0){return"string"==typeof e?!t||e.trim().length>0:null!==e&&"object"==typeof e&&(!t||Object.keys(e).length>0)}function fs(e){return"string"==typeof e&&/^[A-Za-z0-9_.-]{1,128}$/.test(e)}function ps(e){return null===e||"object"!=typeof e?JSON.stringify(e):Array.isArray(e)?`[${e.map(ps).join(",")}]`:`{${Object.keys(e).sort().map((t=>`${JSON.stringify(t)}:${ps(e[t])}`)).join(",")}}`}function gs(e){return(new TextEncoder).encode(JSON.stringify(e)).length}function ms(e){const t=gs(e.state),n={question_types:[],structured_state:"string"!=typeof e.state,structured_rules:!1,question_count:e.questions.length,max_options:0,max_levels:0,input_bytes:t+gs(e.questions),max_state_question_bytes:0};for(const r of e.questions){n.question_types.includes(r.type)||n.question_types.push(r.type);const e=[r.instructions];"choice"===r.type?(n.max_options=Math.max(n.max_options,r.options.length),e.push(...r.options.map((e=>e.description)))):"score"===r.type?(n.max_levels=Math.max(n.max_levels,r.levels.length),e.push(...r.levels)):r.criteria&&e.push(...Object.values(r.criteria)),n.structured_rules||(n.structured_rules=e.some((e=>null!==e&&"object"==typeof e))),n.max_state_question_bytes=Math.max(n.max_state_question_bytes,t+gs(r))}return{decision:n}}function ys(e){if(os(e.exact_model),cs(e,us[Yr.DECISION_EVALUATE]),!ds(e.state,!1)||!Array.isArray(e.questions)||!e.questions.length||e.questions.length>1024)throw new Fn("decision requires a text/JSON state and 1..1024 questions");const t=new Set;for(const n of e.questions){if(!n||!fs(n.id)||t.has(n.id)||!ds(n.instructions))throw new Fn("invalid decision question");if(t.add(n.id),"choice"===n.type){if(cs(n,["type","id","instructions","options"]),!Array.isArray(n.options)||!n.options.length||n.options.length>1024)throw new Fn("invalid decision options");const e=new Set;for(const t of n.options){if(cs(t,["id","description"]),!fs(t.id)||e.has(t.id)||null!==t.description&&!ds(t.description))throw new Fn("invalid decision option");e.add(t.id)}}else if("score"===n.type){if(cs(n,["type","id","instructions","levels"]),!Array.isArray(n.levels)||n.levels.length<2||n.levels.length>1024||n.levels.some((e=>!ds(e)))||new Set(n.levels.map(ps)).size!==n.levels.length)throw new Fn("invalid decision levels")}else{if("boolean"!==n.type)throw new Fn("invalid decision question type");if(cs(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(cs(n.criteria,["true","false"]),Object.values(n.criteria).some((e=>!ds(e))))throw new Fn("invalid decision criteria")}}}if(ms(e).decision.input_bytes>1048576)throw new Fn("decision input exceeds 1 MiB")}function ws(e,t){const n=e=>"number"==typeof e&&Number.isFinite(e)&&e>=0&&e<=1,r=()=>{throw new Fn("invalid or incomplete decision answers")};Array.isArray(t)&&t.length===e.questions.length||r();const s=new Set;for(const i of t){i&&!s.has(i.id)||r(),s.add(i.id);const t=e.questions.find((e=>e.id===i.id));if(!t)throw new Fn("unknown decision question ID");if((t.type!==i.type||void 0!==i.confidence&&!n(i.confidence))&&r(),"boolean"===i.type){cs(i,["type","id","probability_true","confidence"]),n(i.probability_true)||r();continue}cs(i,"choice"===i.type?["type","id","selected","probabilities","confidence"]:["type","id","score","levels","probabilities","confidence"]);const o="choice"===t.type?t.options.map((e=>e.id)):"score"===t.type?t.levels.map(((e,t)=>String(t))):[];if((!i.probabilities||Array.isArray(i.probabilities)||Object.keys(i.probabilities).length!==o.length||o.some((e=>!Object.prototype.hasOwnProperty.call(i.probabilities,e)||!n(i.probabilities[e])))||Math.abs(Object.values(i.probabilities).reduce(((e,t)=>e+t),0)-1)>1e-4)&&r(),"choice"===i.type)o.includes(i.selected)&&!Object.values(i.probabilities).some((e=>e>i.probabilities[i.selected]+1e-4))||r();else if("score"===i.type&&"score"===t.type){const e=o.reduce(((e,t,n)=>e+n*i.probabilities[t]),0);(!Number.isFinite(i.score)||i.score<0||i.score>o.length-1||Math.abs(i.score-e)>1e-4*(o.length-1)||ps(i.levels)!==ps(t.levels))&&r()}else r()}}const bs=32,_s=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,As={reference_image:["type","id","resource"],reference_video:["type","id","resource","time_range","include_audio"],reference_audio:["type","id","resource","time_range"],keyframe:["type","id","resource","position"]},vs=["start","end"];function Es(e){const t=[];let n="";for(let r=0;r<e.length;r++){const s=e[r+1];if("@"!==e[r])n+=e[r];else if("@"===s)n+="@",r++;else if("{"!==s)n+="@";else{const s=e.indexOf("}",r+2);if(s<0)throw new Fn("prompt reference `@{` is not closed");const i=e.slice(r+2,s);if(!_s.test(i))throw new Fn(`prompt reference \`${i}\` is not a valid condition id`);n&&t.push({text:n}),n="",t.push({reference:i}),r=s}}return n&&t.push({text:n}),t}function ks(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Ss(e,t,n){return"number"==typeof e&&Number.isFinite(e)&&e>t&&e<=n}function Ts(e,t){const n=(e,t)=>0===t?e:n(t,e%t),r=Math.max(n(e,t),1);return`${e/r}:${t/r}`}function Rs(e,t){const n={url:["kind","url","mime_hint"],base64:["kind","mime","data_base64"],named_object:["kind","obj_id"]};if(!ks(e)||"string"!=typeof e.kind||!n[e.kind])throw new Fn(`${t} must be a ResourceRef`);cs(e,n[e.kind])}function Is(e,t="output"){if(!ks(e))throw new Fn(`${t} must be an object`);if(cs(e,["duration_seconds","aspect_ratio","size","fps","audio","media_type"]),void 0!==e.duration_seconds&&!Ss(e.duration_seconds,0,600))throw new Fn(`${t}.duration_seconds must be a number in (0, 600]`);const n=void 0===e.aspect_ratio?void 0:function(e){const t="string"==typeof e?/^(\d{1,3}):(\d{1,3})$/.exec(e):null,[n,r]=t?[Number(t[1]),Number(t[2])]:[0,0];return n>=1&&n<=100&&r>=1&&r<=100?[n,r]:void 0}(e.aspect_ratio);if(void 0!==e.aspect_ratio&&!n)throw new Fn(`${t}.aspect_ratio must be \`W:H\` with integers in 1..100`);const r=(e,n)=>{if(!Number.isInteger(e)||e<16||e>8192)throw new Fn(`${t}.size.${n} must be an integer in 16..8192`)},s=e.size;if(void 0!==s){if(!ks(s))throw new Fn(`${t}.size must be { short_edge } or { width, height }`);if("short_edge"in s)cs(s,["short_edge"]),r(s.short_edge,"short_edge");else if(cs(s,["width","height"]),r(s.width,"width"),r(s.height,"height"),n&&Ts(s.width,s.height)!==Ts(...n))throw new Fn(`${t}.size conflicts with aspect_ratio`)}if(void 0!==e.fps&&!Ss(e.fps,0,240))throw new Fn(`${t}.fps must be a number in (0, 240]`);if(void 0!==e.audio&&!["auto","generate","none"].includes(e.audio))throw new Fn(`${t}.audio must be auto, generate or none`);if(void 0!==e.media_type&&("string"!=typeof e.media_type||!/^video\/[a-z0-9.+-]+$/.test(e.media_type)))throw new Fn(`${t}.media_type must be a lowercase video/* MIME type`)}function Cs(e){const{prompt:t,negative_prompt:n,seed:r}=e,s=e.conditions??[];if(void 0!==t&&"string"!=typeof t)throw new Fn("prompt must be a string");if(!Array.isArray(s))throw new Fn("conditions must be an array");if(!(null==t?void 0:t.trim())&&!s.length)throw new Fn("video generation requires a non-blank prompt or at least one condition");if(void 0!==n&&("string"!=typeof n||!n.trim()))throw new Fn("negative_prompt must not be blank when present");if(void 0!==r&&!(Number.isSafeInteger(r)&&r>=0))throw new Fn("seed must be a non-negative integer");if(s.length>bs)throw new Fn(`video generation accepts at most ${bs} conditions`);const i=new Set,o=new Set;s.forEach(((e,t)=>{const n=`conditions[${t}]`;if(!ks(e)||!(e.type in As))throw new Fn(`${n}.type must be a video condition type`);if(cs(e,As[e.type]),"string"!=typeof e.id||!_s.test(e.id))throw new Fn(`${n}.id must match ${_s}`);if(i.has(e.id.toLowerCase()))throw new Fn(`${n}.id \`${e.id}\` is not unique (compared case-insensitively)`);if(i.add(e.id.toLowerCase()),Rs(e.resource,`${n}.resource`),"keyframe"===e.type){if(!vs.includes(e.position))throw new Fn(`${n}.position must be start or end`);if(o.has(e.position))throw new Fn(`${n}: at most one keyframe is allowed per position`);o.add(e.position)}if(void 0!==e.include_audio&&"boolean"!=typeof e.include_audio)throw new Fn(`${n}.include_audio must be a boolean`);const r=e.time_range;if(void 0!==r){if(!ks(r))throw new Fn(`${n}.time_range must be an object`);cs(r,["start_seconds","end_seconds"]);const{start_seconds:e,end_seconds:t}=r;if("number"!=typeof e||"number"!=typeof t||!Number.isFinite(e)||!Number.isFinite(t)||e<0||e>=t)throw new Fn(`${n}.time_range must be finite, non-negative and start before it ends`)}}));for(const a of t?Es(t):[])if("reference"in a&&!(e.conditions??[]).some((e=>e.id===a.reference)))throw new Fn(`prompt references unknown condition \`${a.reference}\``);void 0!==e.output&&Is(e.output)}function Os(e){if("string"!=typeof e.prompt||!e.prompt.trim())throw new Fn("video edit requires a non-blank prompt");Rs(e.video,"video"),void 0!==e.output&&Is(e.output)}function xs(e){var t,n;const r=e.conditions??[],s=e=>r.filter((t=>t.type===e)).length,i=(null==(t=e.requirements)?void 0:t.video)??{},o={},a=(e,t)=>{(t||i[e])&&(o[e]=!0)};a("prompt",!!(null==(n=e.prompt)?void 0:n.trim())),a("negative_prompt",void 0!==e.negative_prompt),a("seed",void 0!==e.seed);for(const[u,h]of[["reference_images","reference_image"],["reference_videos","reference_video"],["reference_audios","reference_audio"]]){const e=Math.max(s(h),i[u]??0);e&&(o[u]=e)}const c=vs.filter((e=>{var t;return(null==(t=i.keyframes)?void 0:t.includes(e))||r.some((t=>"keyframe"===t.type&&t.position===e))}));c.length&&(o.keyframes=c),a("reference_video_audio",r.some((e=>"reference_video"===e.type&&!0===e.include_audio))),a("time_ranges",r.some((e=>"time_range"in e&&void 0!==e.time_range)));const l=e.output&&Object.values(e.output).some((e=>void 0!==e))?e.output:void 0;if(l&&i.output&&ps(l)!==ps(i.output))throw new Fn("requirements.video.output conflicts with the request output");return!l&&i.output&&Is(i.output,"requirements.video.output"),(l??i.output)&&(o.output=l??i.output),o}const Ns={max_messages:null,retention_seconds:null,sync_write:!1,keep_acked:!1,other_app_can_read:!0,other_app_can_write:!1,other_user_can_read:!1,other_user_can_write:!1};function Ps(e,t){if("number"!=typeof e||!Number.isFinite(e))throw new Fn(`expected ${t} to be a number`);return e}function Ds(e,t){if("string"!=typeof e)throw new Fn(`expected ${t} to be a string`);return e}function Bs(e){if(!Array.isArray(e))throw new Fn("expected message list to be an array");return e.map(((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw new Fn(`message[${t}] is not an object`);const n=e;return{index:Ps(n.index,`message[${t}].index`),created_at:Ps(n.created_at,`message[${t}].created_at`),payload:Array.isArray(n.payload)?n.payload:[],headers:n.headers&&"object"==typeof n.headers&&!Array.isArray(n.headers)?n.headers:{}}}))}class Us{constructor(e){this.rpcClient=e}setSeq(e){this.rpcClient.setSeq(e)}async createQueue(e,t,n,r={...Ns}){return Ds(await this.rpcClient.call("create_queue",{name:e,appid:t,app_owner:n,config:r}),"queue_urn")}async deleteQueue(e){await this.rpcClient.call("delete_queue",{queue_urn:e})}async getQueueStats(e){const t=await this.rpcClient.call("get_queue_stats",{queue_urn:e});if(!t||"object"!=typeof t)throw new Fn("invalid get_queue_stats response");const n=t;return{message_count:Ps(n.message_count,"message_count"),first_index:Ps(n.first_index,"first_index"),last_index:Ps(n.last_index,"last_index"),size_bytes:Ps(n.size_bytes,"size_bytes")}}async updateQueueConfig(e,t){await this.rpcClient.call("update_queue_config",{queue_urn:e,config:t})}async postMessage(e,t){return Ps(await this.rpcClient.call("post_message",{queue_urn:e,message:t}),"msg_index")}async subscribe(e){return Ds(await this.rpcClient.call("subscribe",{queue_urn:e.queueUrn,userid:e.userId,appid:e.appId,sub_id:e.subId??null,position:e.position}),"subscription_id")}async unsubscribe(e){await this.rpcClient.call("unsubscribe",{sub_id:e})}async fetchMessages(e,t,n){return Bs(await this.rpcClient.call("fetch_messages",{sub_id:e,length:t,auto_commit:n}))}async readMessage(e,t,n){return Bs(await this.rpcClient.call("read_message",{queue_urn:e,cursor:t,length:n}))}async commitAck(e,t){await this.rpcClient.call("commit_ack",{sub_id:e,index:t})}async seek(e,t){await this.rpcClient.call("seek",{sub_id:e,index:t})}async deleteMessageBefore(e,t){return Ps(await this.rpcClient.call("delete_message_before",{queue_urn:e,index:t}),"deleted_count")}}const Ls="zone_user",Ms="zone_agent",Fs="homestation.following",js=[{key:Ls,kind:"system",user_editable:!1},{key:Ms,kind:"system",user_editable:!1},{key:Fs,kind:"app",app:"homestation",user_editable:!1}];function Gs(e){const t=/^([a-z][a-z0-9_-]*)\.([a-z0-9_.-]+)$/.exec(e);return t?t[1]:null}const Hs="type:",Vs="group:";function qs(e){return e.startsWith(Hs)||e.startsWith(Vs)}const Ws="buckyos.notify",zs="sysnotify:",$s="option",Ks="text",Qs="answer",Js="dismiss",Ys="/messagehub";function Zs(e){return"open"!==e&&"read"!==e}function Xs(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(t[n]=r);return t}function ei(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw new Fn(`expected ${t} to be an object`);return e}function ti(e,t){return null==e?null:ei(e,t)}function ni(e,t){if(!Array.isArray(e))throw new Fn(`expected ${t} to be an array`);return e}function ri(e,t){if("string"!=typeof e)throw new Fn(`${t} expected to return a DID string`);return e}function si(e){const t=ei(e,"NotifyView");if("string"!=typeof t.notify_id||"string"!=typeof t.status)throw new Fn("Invalid NotifyView");return t}class ii{constructor(e){this.rpcClient=e}setSeq(e){this.rpcClient.setSeq(e)}call(e,t){return this.rpcClient.call(e,t)}async dispatch(e,t,n){return ei(await this.call("msg.dispatch",Xs({msg:e,ingress_ctx:t,idempotency_key:n})),"DispatchResult")}async postSend(e,t){return ei(await this.call("msg.post_send",Xs({msg:e,idempotency_key:t})),"PostSendResult")}async listMailboxes(e,t){return ni(await this.call("msg.list_mailboxes",{owner:e,box_kind:t}),"Vec<MailboxAddress>")}async moveRecord(e,t){return ei(await this.call("msg.move_record",{record_id:e,mailbox:t}),"MailboxRecord")}async getNext(e){return ti(await this.call("msg.get_next",Xs({...e})),"MailboxRecordWithObject")}async getNextDelivery(e){return ti(await this.call("msg.get_next_delivery",Xs({...e})),"DeliveryRecordWithObject")}async peekBox(e){return ni(await this.call("msg.peek_box",Xs({...e})),"Vec<MailboxRecordWithObject>")}async listBoxByTime(e){const t=ei(await this.call("msg.list_box_by_time",Xs({...e})),"MailboxRecordPage");return{...t,items:Array.isArray(t.items)?t.items:[]}}async listSessions(e){const t=ei(await this.call("msg.list_sessions",Xs({...e})),"SessionSummaryPage");return{...t,items:Array.isArray(t.items)?t.items:[]}}async listSession(e){const t=ei(await this.call("msg.list_session",Xs({...e})),"SessionMessagePage");return{...t,items:Array.isArray(t.items)?t.items:[]}}async updateRecordState(e,t){return ei(await this.call("msg.update_record_state",{record_id:e,new_state:t}),"MailboxRecord")}async updateRecordSession(e,t){return ei(await this.call("msg.update_record_session",{record_id:e,session_id:t}),"MailboxRecord")}async reportDelivery(e,t){return ei(await this.call("msg.report_delivery",{delivery_id:e,result:t}),"DeliveryRecord")}async setReadState(e){return ei(await this.call("msg.set_read_state",Xs({...e})),"MsgReceiptObj")}async listReadReceipts(e){return ni(await this.call("msg.list_read_receipts",Xs({...e})),"Vec<MsgReceiptObj>")}async getRecord(e,t){return ti(await this.call("msg.get_record",Xs({record_id:e,with_object:t})),"MailboxRecordWithObject")}async getMessage(e){return ti(await this.call("msg.get_message",{msg_id:e}),"MsgObject")}async updateUiSessionState(e,t,n){return ei(await this.call("ui_session.update_state",{session_id:e,key:t,value:n}),"UiSessionStateEntry")}async getUiSessionState(e,t){return ti(await this.call("ui_session.get_state",{session_id:e,key:t}),"UiSessionStateEntry")}async listUiSessionState(e){return ni(await this.call("ui_session.list_state",{session_id:e}),"Vec<UiSessionStateEntry>")}async resolveDid(e,t,n,r){return ri(await this.call("contact.resolve_did",Xs({platform:e,account_id:t,profile_hint:n,contact_mgr_owner:r})),"contact.resolve_did")}async resolveEndpointDid(e,t,n,r,s){return ri(await this.call("contact.resolve_endpoint_did",Xs({platform:e,account_id:t,account_type:n,tunnel_instance_id:r,contact_mgr_owner:s})),"contact.resolve_endpoint_did")}async resolveTarget(e,t,n){return ri(await this.call("contact.resolve_target",Xs({contact_did:e,selector:t,contact_mgr_owner:n})),"contact.resolve_target")}async resolveContactForEndpoint(e,t){const n=await this.call("contact.resolve_contact_for_endpoint",Xs({endpoint_did:e,contact_mgr_owner:t}));return s="contact.resolve_contact_for_endpoint",null==(r=n)?null:ri(r,s);var r,s}async resolveCanonicalDid(e,t){return ri(await this.call("contact.resolve_canonical_did",Xs({did:e,contact_mgr_owner:t})),"contact.resolve_canonical_did")}async listAliasDids(e,t){return ni(await this.call("contact.list_alias_dids",Xs({canonical_did:e,contact_mgr_owner:t})),"Vec<DID>")}async getPreferredBinding(e,t){return ei(await this.call("contact.get_preferred_binding",Xs({did:e,contact_mgr_owner:t})),"AccountBinding")}async checkAccessPermission(e,t,n){return ei(await this.call("contact.check_access_permission",Xs({did:e,context_id:t,contact_mgr_owner:n})),"AccessDecision")}async grantTemporaryAccess(e,t,n,r){const s=ei(await this.call("contact.grant_temporary_access",Xs({dids:e,context_id:t,duration_secs:n,contact_mgr_owner:r})),"GrantTemporaryAccessResult");return{updated:Array.isArray(s.updated)?s.updated:[]}}async blockContact(e,t,n){await this.call("contact.block_contact",Xs({did:e,reason:t,contact_mgr_owner:n}))}async importContacts(e,t,n){return ei(await this.call("contact.import_contacts",Xs({contacts:e,upgrade_to_friend:t,contact_mgr_owner:n})),"ImportReport")}async mergeContacts(e,t,n){return ei(await this.call("contact.merge_contacts",Xs({target_did:e,source_did:t,contact_mgr_owner:n})),"Contact")}async updateContact(e,t,n){return ei(await this.call("contact.update_contact",Xs({did:e,patch:t,contact_mgr_owner:n})),"Contact")}async getContact(e,t){return ti(await this.call("contact.get_contact",Xs({did:e,contact_mgr_owner:t})),"Contact")}async listContacts(e,t){return ni(await this.call("contact.list_contacts",Xs({query:e,contact_mgr_owner:t})),"Vec<Contact>")}async getGroupSubscribers(e,t,n,r){return ni(await this.call("contact.get_group_subscribers",Xs({group_id:e,limit:t,offset:n,contact_mgr_owner:r})),"Vec<DID>")}async setGroupSubscribers(e,t,n){const r=ei(await this.call("contact.set_group_subscribers",Xs({group_id:e,subscribers:t,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 lookup(e){const t=ei(await this.call("contact.lookup",Xs({...e})),"LookupResult");return{...t,candidates:Array.isArray(t.candidates)?t.candidates:[]}}async updateContactTags(e,t,n){return ei(await this.call("contact.update_tags",Xs({did:e,add:t.add,remove:t.remove,contact_mgr_owner:n})),"Contact")}async removeContact(e,t){await this.call("contact.remove_contact",Xs({did:e,contact_mgr_owner:t}))}async unblockContact(e,t){return ei(await this.call("contact.unblock_contact",Xs({did:e,contact_mgr_owner:t})),"Contact")}async sendFriendRequest(e,t,n){return ei(await this.call("contact.send_friend_request",Xs({did:e,message:t,contact_mgr_owner:n})),"FriendRequestResult")}async respondFriendRequest(e,t,n){return ei(await this.call("contact.respond_friend_request",Xs({request_id:e,decision:t,contact_mgr_owner:n})),"FriendRequestResult")}async cancelFriendRequest(e,t){return ei(await this.call("contact.cancel_friend_request",Xs({request_id:e,contact_mgr_owner:t})),"FriendRequestResult")}async removeFriend(e,t,n){return ei(await this.call("contact.remove_friend",Xs({did:e,notify:t,contact_mgr_owner:n})),"FriendRequestResult")}async listFriendRequests(e={}){const t=ti(await this.call("contact.list_friend_requests",Xs({...e})),"FriendRequestPage");return t&&Array.isArray(t.items)?t.items:[]}async notifySend(e){return si(await this.call("notify.send",Xs({...e})))}async notifyGet(e){return si(await this.call("notify.get",{notify_id:e}))}async notifyList(e={}){const t=ei(await this.call("notify.list",Xs({...e})),"NotifyListResult");return{...t,items:ni(t.items,"Vec<NotifyView>").map(si)}}async notifyAck(e,t){return si(await this.call("notify.ack",Xs({notify_id:e,on_behalf:t})))}async notifyDismiss(e){return si(await this.call("notify.dismiss",{notify_id:e}))}async notifyCancel(e,t){return si(await this.call("notify.cancel",Xs({notify_id:e,reason:t})))}}function oi(e){for(const t of e.controls??[])if("choice"===t.kind&&t.id===$s)return t.options??[];return[]}function ai(e,t,n){const r={};return e.option&&(r[$s]=e.option),e.text&&e.text.trim()&&(r[Ks]=e.text),{kind:"human",action:e.dismiss?Js:Qs,...Object.keys(r).length>0?{values:r}:{},submitted_by:t,submitted_at:n}}function ci(e,t){if(e.dismiss)return null;const n=oi(t),r=(t.controls??[]).some((e=>"text_input"===e.kind&&e.id===Ks));if(null!=e.option&&!n.some((t=>t.value===e.option)))return`no option '${e.option}'; options: ${n.map((e=>e.value)).join(", ")}`;const s=!!e.text&&""!==e.text.trim();return s&&!r?"this question takes one of its options, not free text":null!=e.option||s?null:"an answer needs an option or a text"}function li(e,t){const n=null==e?void 0:e.content;if(!n||"object"!=typeof n)return null;const r=n.machine;if(!r||"object"!=typeof r||r.intent!==t)return null;const s=r.data;return s&&"object"==typeof s&&!Array.isArray(s)?s:null}async function ui(e,t,n,r,s=Date.now()){for(let a=0;a<3;a+=1){const i=await e.getTask(t);if(Er(i.phase)||null!=i.result)return{kind:"already_closed",task:i};try{return{kind:"committed",task:await e.commitResult({task_id:t,result:ai(n,r,s),expected_revision:i.revision})}}catch(o){const n=_r(o);if(n===fr)return{kind:"already_closed",task:await e.getTask(t)};if(n!==cr)throw o}}const i=await e.getTask(t);if(Er(i.phase))return{kind:"already_closed",task:i};throw new Fn(`task ${t} keeps changing; answer not committed`)}async function hi(e,t){const n=Date.now();if(t)try{if(await t.pullEvent(e))return}catch{}const r=e-(Date.now()-n);r>0&&await function(e){return new Promise((t=>setTimeout(t,e)))}(r)}function di(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(t[n]=r);return t}function fi(e,t){if("string"!=typeof e)throw new Fn(`expected ${t} to be a string`);return e}function pi(e,t){if("boolean"!=typeof e)throw new Fn(`expected ${t} to be a boolean`);return e}function gi(e,t){if("number"!=typeof e||!Number.isFinite(e))throw new Fn(`expected ${t} to be a number`);return e}function mi(e,t){if(!Array.isArray(e))throw new Fn(`expected ${t} to be an array`);return e}function yi(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw new Fn(`expected ${t} to be an object`);return e}class wi{constructor(e){this.rpcClient=e}setSeq(e){this.rpcClient.setSeq(e)}async store(e){return fi(await this.rpcClient.call("store",{content_id:e}),"ObjId")}async collect(e,t){return fi(await this.rpcClient.call("collect",di({content_meta:e,referral_proof:t})),"content_id")}async pin(e,t){return pi(await this.rpcClient.call("pin",{content_id:e,download_proof:t}),"pin response")}async unpin(e,t=!1){return pi(await this.rpcClient.call("unpin",{content_id:e,force:t}),"unpin response")}async uncollect(e,t=!1){return pi(await this.rpcClient.call("uncollect",{content_id:e,force:t}),"uncollect response")}async addProof(e){return fi(await this.rpcClient.call("add_proof",{proof:e}),"proof_id")}async getProofs(e,t){return mi(await this.rpcClient.call("get_proofs",di({content_id:e,filter:t})),"Vec<RepoProof>").map(((e,t)=>{const n=yi(e,`RepoProof[${t}]`);if("Action"!==n.kind&&"Collection"!==n.kind)throw new Fn(`RepoProof[${t}] has unknown kind: ${String(n.kind)}`);return n}))}async resolve(e){return mi(await this.rpcClient.call("resolve",{content_name:e}),"Vec<ObjId>").map(((e,t)=>fi(e,`ObjId[${t}]`)))}async list(e){return mi(await this.rpcClient.call("list",di({filter:e})),"Vec<RepoRecord>").map(((e,t)=>{const n=yi(e,`RepoRecord[${t}]`);return{content_id:fi(n.content_id,`RepoRecord[${t}].content_id`),content_name:"string"==typeof n.content_name?n.content_name:void 0,status:fi(n.status,`RepoRecord[${t}].status`),origin:fi(n.origin,`RepoRecord[${t}].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:fi(n.access_policy,`RepoRecord[${t}].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 e=yi(await this.rpcClient.call("stat",{}),"RepoStat");return{total_objects:gi(e.total_objects,"RepoStat.total_objects"),collected_objects:gi(e.collected_objects,"RepoStat.collected_objects"),pinned_objects:gi(e.pinned_objects,"RepoStat.pinned_objects"),local_objects:gi(e.local_objects,"RepoStat.local_objects"),remote_objects:gi(e.remote_objects,"RepoStat.remote_objects"),total_content_bytes:gi(e.total_content_bytes,"RepoStat.total_content_bytes"),total_proofs:gi(e.total_proofs,"RepoStat.total_proofs")}}async serve(e,t){const n=yi(await this.rpcClient.call("serve",{content_id:e,request_context:t}),"RepoServeResult");return{status:fi(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(e){return pi(await this.rpcClient.call("announce",{content_id:e}),"announce response")}}function bi(e){if(!e||e.length>253||e.includes("@"))throw new Error("hostname must be 1..=253 bytes and must not contain `@`");if(e!==e.toLowerCase()||!/^[\x00-\x7f]+$/.test(e))throw new Error("hostname must be canonical lowercase ASCII");for(const t of e.split("."))if(!t||t.length>63||t.startsWith("-")||t.endsWith("-")||!/^[a-z0-9-]+$/.test(t))throw new Error(`invalid DNS label \`${t}\``)}function _i(e){const t=/^did:([^:]+):(.+)$/.exec(e);if(!t)throw new Error("AppDID must be a canonical DID");const[,n,r]=t;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(bi(s),"web"===n&&s.endsWith(".did"))throw new Error("AppDID did:web hostnames ending in `.did` are reserved");if(Mn.DID.fromStr(s).toString()!==e)throw new Error("AppDID raw hostname does not round-trip");return s}function Ai(e){return _i(e.trim())}function vi(e){const t=e.trim();bi(t);const n=_i(Mn.DID.fromStr(t).toString());if(n!==t)throw new Error("AppId is not a canonical AppDID raw hostname");return n}function Ei(e){if(!e||e.length>64||!/^[a-z0-9._-]+$/.test(e))throw new Error("owner_user_id must be lowercase ASCII and contain only [a-z0-9._-]")}function ki(e,t){const n=vi(e);return Ei(t),`${n}@${t}`}function Si(e){const t=e.trim(),n=t.lastIndexOf("@");if(n<=0||n===t.length-1)throw new Error("AppInstanceId must be `{app_id}@{owner_user_id}`");const r=vi(t.slice(0,n)),s=t.slice(n+1);return Ei(s),{appId:r,ownerUserId:s}}const Ti="BUCKYOS_APP_DID",Ri="BUCKYOS_APP_ID",Ii="BUCKYOS_APP_INSTANCE_ID",Ci="BUCKYOS_OWNER_USER_ID",Oi="BUCKYOS_DATA_DIR",xi="BUCKYOS_APP_TOKEN";var Ni=(e=>(e.Browser="Browser",e.NodeJS="NodeJS",e.AppRuntime="AppRuntime",e.AppClient="AppClient",e.AppService="AppService",e.Unknown="Unknown",e))(Ni||{});const Pi=["admin","user","limited","root"];const Di="external";const Bi={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 Ui(){const e=globalThis.process;return(null==e?void 0:e.env)??{}}function Li(){var e;const t=globalThis.process;return Boolean(null==(e=null==t?void 0:t.versions)?void 0:e.node)}function Mi(){return"undefined"!=typeof localStorage}function Fi(){return"function"==typeof fetch}function ji(){const e=globalThis.Buffer;if(!e||"function"!=typeof e)throw new Error("Buffer is not available in this runtime");return e}function Gi(e){const t=ji();return("string"==typeof e?t.from(e,"utf8").toString("base64"):t.from(e).toString("base64")).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Hi(e){if(!e)return null;const t=e.split(".");if(t.length<2)return null;try{return JSON.parse(function(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t+"=".repeat((4-t.length%4)%4);return"function"==typeof atob?atob(n):ji().from(n,"base64").toString("utf8")}(t[1]))}catch{return null}}function Vi(e){if("string"!=typeof e)return null;const t=e.trim();return t.length>0?t:null}function qi(e){const t=Vi(e);return t?t.startsWith("did:web:")?t.slice(8).replace(/:/g,"."):t.startsWith("did:bns:")?t.slice(8):null:null}async function Wi(e){if(Li()&&"function"==typeof require)return require(e);return Function("name","return import(name)")(e)}class zi{async initialize(e){await e.resolveAppServiceIdentityFromEnv(),await e.resolveZoneHostFromLocalConfig()}async login(e){await e.initialize(),e.startAutoRenewIfNeeded()}supportsManagedSessionRenewal(){return!1}shouldSkipVerifyHubRenewal(e){return!1}async getVerifyHubLoginJwt(e,t){return t}}class $i extends zi{getRelativeZoneServiceURL(e){return`/kapi/${e}/`}getRelativeSystemConfigServiceURL(){return"/kapi/system_config"}getServiceSettingsPath(e){var t;const n=null==(t=Mn.getBrowserUserInfo())?void 0:t.user_id;if(!n)throw new Error("Login is required for App settings");return`users/${n}/apps/${e.getAppId()}/settings`}getZoneServiceURL(e,t){return this.getRelativeZoneServiceURL(t)}getSystemConfigServiceURL(e){return this.getRelativeSystemConfigServiceURL()}getMySettingsPath(e){return this.getServiceSettingsPath(e)}}class Ki extends $i{}class Qi extends zi{async login(e){await e.initialize(),await e.renewTokenFromVerifyHub(),e.startAutoRenewIfNeeded()}supportsManagedSessionRenewal(){return!0}}class Ji extends Qi{async initialize(e){await super.initialize(e),await e.ensureAppClientSessionToken()}getZoneGatewayServiceURL(e,t){const n=Vi(e.getZoneHostName());if(!n)throw new Error("zoneHost is required in AppClient mode");return`${e.getDefaultProtocol()}${n}/kapi/${t}`}getZoneSystemConfigURL(e){const t=Vi(e.getZoneHostName());if(!t)throw new Error("zoneHost is required in AppClient mode");return`${e.getDefaultProtocol()}${t}/kapi/system_config`}getZoneServiceURL(e,t){return this.getZoneGatewayServiceURL(e,t)}getSystemConfigServiceURL(e){return this.getZoneSystemConfigURL(e)}getMySettingsPath(){throw new Error("AppClient not support getMySettingsPath")}shouldSkipVerifyHubRenewal(e){return!Vi(e.getZoneHostName())&&!e.getConfiguredVerifyHubServiceUrl()}async getVerifyHubLoginJwt(e,t){return e.createAppClientSessionToken()}}class Yi extends Qi{async initialize(e){await super.initialize(e),e.ensureAppServiceSessionToken()}getNodeGatewayServiceURL(e,t){const n=e.getNodeGatewayPort();return`http://${e.resolveAppServiceGatewayHost()}:${n}/kapi/${t}`}getNodeGatewaySystemConfigURL(e){const t=e.getNodeGatewayPort();return`http://${e.resolveAppServiceGatewayHost()}:${t}/kapi/system_config`}getUserAppSettingsPath(e){const t=e.getOwnerUserId();if(!t)throw new Error("ownerUserId is required for AppService settings");return`users/${t}/apps/${e.getAppId()}/settings`}getZoneServiceURL(e,t){return this.getNodeGatewayServiceURL(e,t)}getSystemConfigServiceURL(e){return this.getNodeGatewaySystemConfigURL(e)}getMySettingsPath(e){return this.getUserAppSettingsPath(e)}}function Zi(e){switch(e){case"AppClient":return new Ji;case"AppService":return new Yi;case"AppRuntime":return new Ki;default:return new $i}}class Xi{constructor(e){const t=Vi(e.ownerUserId)??Vi(e.userid);this.config={...Bi,...e,appId:e.appId,appDid:Vi(e.appDid),appInstanceId:Vi(e.appInstanceId),dataDir:Vi(e.dataDir),userid:t,ownerUserId:t,zoneHost:e.zoneHost??"",defaultProtocol:e.defaultProtocol??Bi.defaultProtocol},this.sessionToken=Vi(e.sessionToken),this.refreshToken=Vi(e.refreshToken),this.renewTimer=null,this.browserRefreshPromise=null,this.authStateRevision=0,this.initialized=!1,this.profile=Zi(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(e){const t=Vi(e.ownerUserId)??Vi(e.userid);this.config={...Bi,...e,appId:e.appId,appDid:Vi(e.appDid),appInstanceId:Vi(e.appInstanceId),dataDir:Vi(e.dataDir),userid:t,ownerUserId:t},this.profile=Zi(this.config.runtimeType)}getConfig(){return{...this.config}}getAppId(){return this.config.appId}getOwnerUserId(){return Vi(this.config.ownerUserId)}getAppDid(){return Vi(this.config.appDid)}getAppInstanceId(){return Vi(this.config.appInstanceId)}getDataDir(){return Vi(this.config.dataDir)}getAuthTarget(){if(this.config.authTarget){const e=sr(this.config.authTarget);if(e!==this.config.appId)throw new Error(`auth target appid mismatch: ${e} != ${this.config.appId}`);return{...this.config.authTarget}}const e=this.getAppInstanceId();if(e){const t=Si(e);if(t.appId!==this.config.appId)throw new Error(`auth target appid mismatch: ${t.appId} != ${this.config.appId}`);return{kind:"app",app_instance_id:e}}if("AppClient"===this.config.runtimeType||"AppService"===this.config.runtimeType){const e=this.getOwnerUserId();if(!e)throw new Error("ownerUserId is required to build an App auth target");return{kind:"app",app_instance_id:ki(this.config.appId,e)}}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 Vi(this.config.verifyHubServiceUrl)}getZoneServiceURL(e){const t=function(e){return"system-config"===e?"system_config":e}(e);return this.profile.getZoneServiceURL(this,t)}getSystemConfigServiceURL(){const e=this.getConfiguredSystemConfigServiceUrl();return e||this.profile.getSystemConfigServiceURL(this)}setSessionToken(e){const t=Vi(e);t!==this.sessionToken&&(this.authStateRevision+=1),this.sessionToken=t}setRefreshToken(e){this.refreshToken=Vi(e)}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(e){return new Gn(this.getZoneServiceURL(e),this.sessionToken,null,{sessionTokenProvider:this.ensureSessionTokenReady.bind(this),onSessionTokenChanged:this.setSessionToken.bind(this)})}getSystemConfigClient(){return new Jr(this.getSystemConfigServiceURL(),this.sessionToken,{sessionTokenProvider:this.ensureSessionTokenReady.bind(this),onSessionTokenChanged:this.setSessionToken.bind(this)})}getVerifyHubClient(){const e=this.getConfiguredVerifyHubServiceUrl(),t=new Gn(e??this.getZoneServiceURL("verify-hub"),this.sessionToken);return new ir(t)}getTaskManagerClient(){const e=this.getServiceRpcClient("task-manager");return new Br(e)}getWorkflowClient(){const e=this.getServiceRpcClient("workflow");return new Kr(e)}getAiccClient(){return new hs(this.getServiceRpcClient("aicc"))}getAiWorkspaceClient(){return new nr(this.getServiceRpcClient(er))}getMsgQueueClient(){return new Us(this.getServiceRpcClient("kmsg"))}getMsgCenterClient(){return new ii(this.getServiceRpcClient("msg-center"))}getRepoClient(){return new wi(this.getServiceRpcClient("repo-service"))}async getMySettings(){const e=this.getMySettingsPath(),t=await this.getSystemConfigClient().get(e);return JSON.parse(t.value)}async updateMySettings(e,t){const n=this.getMySettingsPath(),r=JSON.stringify(t);await this.getSystemConfigClient().setByJsonPath(n,e,r)}async updateAllMySettings(e){const t=this.getMySettingsPath(),n=JSON.stringify(e);await this.getSystemConfigClient().set(t,n)}async renewTokenFromVerifyHub(){if(!this.profile.supportsManagedSessionRenewal())return;const e=this.sessionToken;if(!e)return;const t=Hi(e);if(!t||!this.needsRenew(t))return;if(this.profile.shouldSkipVerifyHubRenewal(this))return;const n=this.getVerifyHubClient(),r="verify-hub"===t.iss?this.refreshToken?await n.refreshToken({refresh_token:this.refreshToken}):await n.loginByJwt({jwt:await this.profile.getVerifyHubLoginJwt(this,e),target:this.getAuthTarget()}):await n.loginByJwt({jwt:e,target:this.getAuthTarget()});this.sessionToken=Vi(r.session_token),this.refreshToken=Vi(r.refresh_token),this.validateSessionToken()}async ensureSessionTokenReady(){if(this.usesBrowserSessionRefresh()){const e=await this.ensureBrowserSessionToken();return e&&this.startAutoRenewIfNeeded(),e}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(!Li())return;if("AppService"!==this.config.runtimeType)return;const e=Ui(),t=t=>{const n=Vi(e[t]);if(!n)throw new Error(`${t} is required for AppService runtime`);return n},n=t(Ti),r=vi(t(Ri)),s=t(Ii),i=t(Ci),o=t(Oi),a=Si(s);if(!(await Wi("node:path")).isAbsolute(o))throw new Error(`${Oi} must be an absolute path`);if(Ai(n)!==r||a.appId!==r||a.ownerUserId!==i||ki(r,i)!==s)throw new Error("AppService identity environment variables are inconsistent");const c=Vi(this.config.appId),l=Vi(this.config.appDid),u=Vi(this.config.appInstanceId),h=this.getOwnerUserId(),d=Vi(this.config.dataDir);if(c&&c!==r)throw new Error(`runtime appId ${c} does not match ${Ri} ${r}`);if(l&&l!==n)throw new Error(`runtime appDid ${l} does not match ${Ti} ${n}`);if(u&&u!==s)throw new Error(`runtime appInstanceId ${u} does not match ${Ii} ${s}`);if(h&&h!==i)throw new Error(`runtime ownerUserId ${h} does not match ${Ci} ${i}`);if(d&&d!==o)throw new Error(`runtime dataDir ${d} does not match ${Oi} ${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(!Li())return;if(Vi(this.config.zoneHost))return;const e=await this.getPrivateKeySearchRoots(),t=await this.tryResolveZoneHostFromSearchRoots(e);t&&(this.config.zoneHost=t)}validateSessionToken(){if(!this.sessionToken)return;const e=Hi(this.sessionToken);if("AppService"===this.config.runtimeType&&!e)throw new Error("AppService session token must be a JWT with identity claims");const t="string"==typeof(null==e?void 0:e.appid)?e.appid:"string"==typeof(null==e?void 0:e.aud)?e.aud:null;if(t&&t!==this.config.appId)throw new Error(`session token appid mismatch: ${t} != ${this.config.appId}`);if("AppService"===this.config.runtimeType&&e){const t=this.getAppInstanceId();if(!t||e.app_instance_id!==t)throw new Error(`session token app_instance_id mismatch: ${String(e.app_instance_id)} != ${String(t)}`);const n=this.getOwnerUserId();if(!n||e.app_owner_user_id!==n)throw new Error(`session token app_owner_user_id mismatch: ${String(e.app_owner_user_id)} != ${String(n)}`)}}async ensureBrowserSessionToken(){const e=Hi(this.sessionToken);return this.sessionToken&&e&&!this.needsRenew(e)?this.sessionToken:this.refreshBrowserSessionToken()}storeBrowserIdentity(e){if(!Mi())return;const t=Qn(Mn.getBrowserIdentityRaw());t&&Jn(t)!==Jn(e)&&Mn.clearBrowserUserInfo(),Mn.saveBrowserIdentity(e),"account"===e.kind?Mn.saveBrowserUserInfo({user_name:e.show_name||e.user_id,user_id:e.user_id,user_type:e.user_type}):Mn.clearBrowserUserInfo()}async getCurrentIdentity(){var e;const t=await this.ensureSessionTokenReady();if(!t||!Mi())return Kn;const n=Qn(Mn.getBrowserIdentityRaw()),r=null==(e=Hi(t))?void 0:e.sub,s="account"===(null==n?void 0:n.kind)?n.user_id:"external"===(null==n?void 0:n.kind)?n.did:null;return n&&r&&s===r?n:Kn}async refreshBrowserSession(){return await this.refreshBrowserSessionToken()&&Mi()?Mn.getBrowserUserInfo():null}async logoutBrowserSSO(){if(("Browser"===this.config.runtimeType||"AppRuntime"===this.config.runtimeType)&&Fi())try{const e=await fetch("/sso_logout",{method:"POST",credentials:"include",cache:"no-store",keepalive:!0});e.ok||console.warn("BuckyOS browser sso_logout failed:",e.status)}catch(e){console.warn("BuckyOS browser sso_logout failed:",e)}}async refreshBrowserSessionToken(){if(this.browserRefreshPromise)return this.browserRefreshPromise;const e=this.authStateRevision,t=this.requestBrowserSessionToken(e);this.browserRefreshPromise=t;try{return await t}finally{this.browserRefreshPromise===t&&(this.browserRefreshPromise=null)}}async requestBrowserSessionToken(e){if(!Fi())return this.sessionToken;try{const t=await fetch("/sso_refresh",{method:"POST",credentials:"include",cache:"no-store"});if(!t.ok)return e===this.authStateRevision&&(this.sessionToken=null,401===t.status&&Mi()&&(Mn.clearBrowserIdentity(),Mn.clearBrowserUserInfo())),null;const n=await t.json(),r=Vi("string"==typeof n.session_token?n.session_token:null),s=Qn(n.identity);return r&&s&&"anonymous"!==s.kind?e!==this.authStateRevision?null:(this.sessionToken=r,this.refreshToken=null,this.storeBrowserIdentity(s),this.validateSessionToken(),this.sessionToken):(e===this.authStateRevision&&(this.sessionToken=null),null)}catch(t){return console.warn("BuckyOS browser sso_refresh failed:",t),e===this.authStateRevision&&(this.sessionToken=null),null}}usesBrowserSessionRefresh(){return"Browser"===this.config.runtimeType||"AppRuntime"===this.config.runtimeType}needsRenew(e){if(e.iss&&"verify-hub"!==e.iss)return!0;if("number"!=typeof e.exp)return!1;return Math.floor(Date.now()/1e3)>=e.exp-30}startAutoRenewIfNeeded(){const e=this.usesBrowserSessionRefresh();if(!e&&!this.profile.supportsManagedSessionRenewal()||!1===this.config.autoRenew)return;if(this.renewTimer)return;const t=this.config.renewIntervalMs??5e3,n=async()=>{try{if(e){await this.ensureBrowserSessionToken()||this.stopAutoRenew()}else await this.renewTokenFromVerifyHub()}catch(t){console.warn("BuckyOS token renew failed:",t)}};this.renewTimer=setInterval((()=>{n()}),t),n()}loadAppServiceSessionTokenFromEnv(){const e=Vi(Ui()[xi]);if(e)return e;throw new Error(`${xi} is required for AppService runtime`)}loadAppClientSessionTokenFromEnv(){return Vi(Ui().BUCKYOS_APPCLIENT_SESSION_TOKEN)}async createAppClientSessionToken(){if(!Li())throw new Error("AppClient mode requires Node.js");const e=await this.loadLocalSigningMaterial(),t=Math.floor(Date.now()/1e3),n={token_type:"Normal",appid:this.config.appId,jti:String(t),session:t,sub:e.subject,userid:e.subject,iss:e.issuer,exp:t+900,extra:{}};return this.signJwtWithEd25519({alg:"EdDSA",kid:e.issuer},n,e.keyPem)}async loadLocalSigningMaterial(){const e=await Wi("node:path"),t=this.getOwnerUserId();if(!t){const t=await this.getBuckyOSEtcDir(),n=e.join(t,"node_identity.json"),r=await this.readNodeIdentityMetadata(n);if(!r)throw new Error(`failed to load ${Mn.NODE_IDENTITY_SCHEMA_V2} node identity from ${n}`);const s=await this.loadDeviceSigningMaterial(t,r);if(!s)throw new Error(`failed to load authentication private key of ${r.deviceDid}`);return this.config.userid=r.deviceName,this.config.ownerUserId=r.deviceName,s}const n=await this.getPrivateKeySearchRoots(),r=await this.tryLoadDeviceSigningMaterial(t,n);if(r)return r;const s=await this.tryLoadUserSigningMaterial(t,n);if(s)return s;throw new Error(`failed to find AppClient private key for userid=${t} in search roots: ${n.join(", ")}`)}async getPrivateKeySearchRoots(){var e;const t=Ui(),n=await Wi("node:path"),r=await Wi("node:os"),s=[];for(const c of this.config.privateKeySearchPaths??[]){const e=Vi(c);e&&s.push(e)}const i=Vi(t.BUCKYOS_APP_CLIENT_DIR);i&&s.push(i);const o=Vi(t.HOME)??Vi(t.USERPROFILE)??Vi(null==(e=r.homedir)?void 0:e.call(r));o&&(s.push(n.join(o,".buckyos")),s.push(n.join(o,".buckycli")));const a=Vi(this.config.rootDir)??Vi(t.BUCKYOS_ROOT)??"/opt/buckyos";return s.push(a),s.push(n.join(a,"etc")),Array.from(new Set(s))}async getBuckyOSRootDir(){const e=Ui();return Vi(this.config.rootDir)??Vi(e.BUCKYOS_ROOT)??"/opt/buckyos"}async getBuckyOSEtcDir(){return(await Wi("node:path")).join(await this.getBuckyOSRootDir(),"etc")}async readPemFile(e){const t=await Wi("node:fs/promises");try{return(await t.readFile(e,"utf8")).trim()||null}catch{return null}}async readNodeIdentityMetadata(e){const t=await Wi("node:fs/promises");try{const n=JSON.parse(await t.readFile(e,"utf8"));return Mn.isBuckyOSLocalNodeIdentityConfig(n)?{deviceName:n.device_name,deviceDid:n.device_did,zoneDid:n.zone_did}:null}catch{return null}}async tryLoadDeviceSigningMaterial(e,t){const n=await Wi("node:path"),r=[await this.getBuckyOSEtcDir(),...t.filter((e=>!e.endsWith(".pem")))];for(const s of Array.from(new Set(r))){const t=await this.readNodeIdentityMetadata(n.join(s,"node_identity.json"));if(!t||t.deviceName!==e)continue;const r=await this.loadDeviceSigningMaterial(s,t);if(r)return r}return null}async loadDeviceSigningMaterial(e,t){const n=await Wi("node:path"),r=Mn.DID.fromStr(t.deviceDid).toFilename(),s="authentication.private.pem",i=Vi(Ui().BUCKYOS_SECURITY_ROOT)??n.join(await this.getBuckyOSRootDir(),"security"),o=[n.join(e,"security",r,s),n.join(i,r,s)];for(const a of o){const e=await this.readPemFile(a);if(e)return{keyPem:e,issuer:t.deviceName,subject:t.deviceName,sourcePath:a}}return null}async tryLoadUserSigningMaterial(e,t){var n;const r=await Wi("node:fs/promises"),s=await Wi("node:path");for(const i of t){const t=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!==e)continue;const c=await this.readPemFile(t);if(!c)continue;return{keyPem:c,issuer:e,subject:e,sourcePath:t}}catch{}}return null}async tryResolveZoneHostFromSearchRoots(e){var t;const n=await Wi("node:fs/promises"),r=await Wi("node:path"),s=Vi(Ui().BUCKYOS_ZONE_HOST);if(s)return s;for(const i of e){const e=r.join(i,"node_identity.json"),t=await this.readNodeIdentityMetadata(e);if(t)return qi(t.zoneDid)}for(const i of e){const e=r.join(i,"user_config.json");try{const r=await n.readFile(e,"utf8"),s=Mn.parseBuckyOSOwnerDocument(JSON.parse(r)),i=qi(null==(t=null==s?void 0:s.binded_zone_list)?void 0:t[0]);if(!i)continue;return i}catch{}}return null}getMySettingsPath(){return this.profile.getMySettingsPath(this)}getConfiguredSystemConfigServiceUrl(){return Vi(this.config.systemConfigServiceUrl)}resolveAppServiceGatewayHost(){return Vi(Ui().BUCKYOS_HOST_GATEWAY)??"host.docker.internal"}async signJwtWithEd25519(e,t,n){const r=await Wi("node:crypto"),s=ji(),i=`${Gi(JSON.stringify(e))}.${Gi(JSON.stringify(t))}`;return`${i}.${Gi(r.sign(null,s.from(i,"utf8"),r.createPrivateKey({key:n,format:"pem"})))}`}}const eo=1048576;class to extends Error{constructor(e,t){super(t),this.name="KEventProtocolError",this.code=e}}const no=async(e,t)=>{if("function"!=typeof fetch)throw new Error("fetch is not available in this runtime");return fetch(e,t)};function ro(){var e;const t=globalThis.process;return Boolean(null==(e=null==t?void 0:t.versions)?void 0:e.node)}function so(e){const t=(Array.isArray(e)?e:[e]).map((e=>"string"==typeof e?e.trim():"")).filter((e=>e.length>0));if(0===t.length)throw new Error("kevent patterns must not be empty");for(const n of t)if(!n.startsWith("/"))throw new Error(`kevent only supports global patterns: ${n}`);return t}function io(e,t){return(null==t?void 0:t.aborted)?Promise.reject(new Error("Operation aborted")):new Promise(((n,r)=>{const s=setTimeout((()=>{o(),n()}),e),i=()=>{clearTimeout(s),o(),r(new Error("Operation aborted"))},o=()=>{t&&t.removeEventListener("abort",i)};t&&t.addEventListener("abort",i,{once:!0})}))}function oo(e){return e instanceof Error?e.message:String(e)}function ao(e){if("ok"===e.status)return e;throw new to(e.code||"INTERNAL",e.message||"Unknown kevent error")}function co(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new Error("Invalid kevent event payload");const t=e;if("string"!=typeof t.eventid||"string"!=typeof t.source_node||"number"!=typeof t.source_pid||"number"!=typeof t.timestamp)throw new Error("Invalid kevent event payload");return{eventid:t.eventid,source_node:t.source_node,source_pid:t.source_pid,ingress_node:"string"==typeof t.ingress_node?t.ingress_node:null,timestamp:t.timestamp,data:"data"in t?t.data:null}}class lo{constructor(){this.items=[],this.waiters=[],this.closed=!1}push(e){if(this.closed)return;const t=this.waiters.shift();if(t)return t.timeout&&clearTimeout(t.timeout),void t.resolve(e);this.items.push(e)}async shift(e){return this.items.length>0?this.items.shift()??null:this.closed||0===e?null:new Promise((t=>{const n={resolve:e=>{r(),t(e)},timeout:null},r=()=>{n.timeout&&(clearTimeout(n.timeout),n.timeout=null);const e=this.waiters.indexOf(n);e>=0&&this.waiters.splice(e,1)};"number"==typeof e&&e>0&&(n.timeout=setTimeout((()=>{r(),t(null)}),e)),this.waiters.push(n)}))}close(){if(!this.closed)for(this.closed=!0;this.waiters.length>0;){const e=this.waiters.shift();e&&(e.timeout&&clearTimeout(e.timeout),e.resolve(null))}}}class uo{constructor(){this.queue=new lo,this.closed=!1,this.closePromise=null}async pullEvent(e){return this.queue.shift(e)}async pull_event(e){return this.pullEvent(e)}enqueue(e){this.queue.push(e)}isClosed(){return this.closed}markClosed(){this.closed=!0,this.queue.close()}async close(){return this.closePromise||(this.markClosed(),this.closePromise=this.closeTransport().catch((e=>{console.warn("kevent reader close failed:",e)})).then((()=>{}))),this.closePromise}}class ho extends uo{constructor(e,t,n,r,s,i){super(),this.streamUrl=e,this.patterns=t,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 e={"Content-Type":"application/json"};if(this.sessionTokenProvider){const t=await this.sessionTokenProvider();"string"==typeof t&&t.trim().length>0&&(e.Authorization=`Bearer ${t.trim()}`)}const t=await this.fetcher(this.streamUrl,{method:"POST",headers:e,body:JSON.stringify({patterns:this.patterns,keepalive_ms:this.keepaliveMs}),cache:"no-store",credentials:"include",signal:this.controller.signal});if(!t.ok){let e="";try{e=await t.text()}catch{e=""}throw new Error(`kevent stream request failed: ${t.status}${e?` ${e}`:""}`)}if(!t.body)throw new Error("kevent stream response missing body");let n=!1,r=null,s=null;const i=new Promise(((e,t)=>{r=e,s=t}));this.streamTask=this.consumeStream(t.body,(e=>{if("ack"===e.type)return n=!0,void(null==r||r());if("event"!==e.type){if("error"===e.type){const t=new Error(e.error||"kevent stream error");n?console.warn("kevent stream error:",t.message):null==s||s(t)}}else this.enqueue(co(e.event))})).then((()=>{n||null==s||s(new Error("kevent stream closed before ack"))})).catch((e=>{n?this.controller.signal.aborted||console.warn("kevent browser stream stopped with error:",e):null==s||s(e instanceof Error?e:new Error(oo(e)))})).finally((()=>{this.markClosed()})),await i}async consumeStream(e,t){const n=e.getReader(),r=new TextDecoder;let s="";try{for(;!this.controller.signal.aborted;){const{value:e,done:i}=await n.read();if(i)break;s+=r.decode(e,{stream:!0}),s=this.processFrameBuffer(s,t)}s+=r.decode(),s=this.processFrameBuffer(s,t),s.trim().length>0&&this.handleFrameLine(s,t)}finally{try{await n.cancel()}catch{}}}processFrameBuffer(e,t){let n=e;for(;;){const e=n.indexOf("\n");if(e<0)return n;const r=n.slice(0,e);n=n.slice(e+1),this.handleFrameLine(r,t)}}handleFrameLine(e,t){const n=e.trim();if(!n)return;t(JSON.parse(n))}async closeTransport(){if(this.controller.abort(),this.streamTask)try{await this.streamTask}catch(e){this.controller.signal.aborted||console.warn("kevent browser stream stopped with error:",e)}}}class fo{constructor(e,t,n,r){this.host=e,this.port=t,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(e){const t=this.serial.then((()=>this.callInternal(e)));return this.serial=t.then((()=>{}),(()=>{})),t}async close(){if(this.closed=!0,this.rejectAllPending(new Error("kevent native connection closed")),this.socket){const e=this.socket;this.socket=null,e.end()}}async callInternal(e){if(this.closed)throw new Error("kevent native connection is closed");await this.ensureConnected();const t=this.socket;if(!t)throw new Error("kevent native socket is not connected");const n=(new TextEncoder).encode(JSON.stringify(e));if(0===n.length||n.length>eo)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(((e,n)=>{const s={resolve:e,reject:n};this.pending.push(s),t.write(r,(e=>{if(!e)return;const t=this.pending.indexOf(s);t>=0&&this.pending.splice(t,1),n(e instanceof Error?e:new Error(oo(e)))}))}))}async ensureConnected(){this.socket||(this.connectPromise||(this.connectPromise=this.connect().finally((()=>{this.connectPromise=null}))),await this.connectPromise)}async connect(){const e=await this.connector(this.host,this.port,this.connectTimeoutMs);this.socket=e,"function"==typeof e.setNoDelay&&e.setNoDelay(!0),e.on("data",(e=>{try{this.handleSocketData(function(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);throw new Error("Unsupported socket data chunk")}(e))}catch(t){this.handleSocketFailure(t instanceof Error?t:new Error(oo(t)))}})),e.once("end",(()=>{this.handleSocketFailure(new Error("kevent native socket ended"))})),e.once("close",(()=>{this.handleSocketFailure(new Error("kevent native socket closed"))})),e.once("error",(e=>{this.handleSocketFailure(e)}))}handleSocketData(e){for(this.readBuffer=function(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}(this.readBuffer,e);this.readBuffer.length>=4;){const e=new DataView(this.readBuffer.buffer,this.readBuffer.byteOffset,this.readBuffer.byteLength).getUint32(0);if(0===e||e>eo)throw new Error(`invalid kevent native frame length: ${e}`);if(this.readBuffer.length<4+e)return;const t=this.readBuffer.slice(4,4+e);this.readBuffer=this.readBuffer.slice(4+e);const n=JSON.parse((new TextDecoder).decode(t)),r=this.pending.shift();r&&r.resolve(n)}}handleSocketFailure(e){if(this.socket){const t=this.socket;this.socket=null;try{t.destroy(e)}catch{}}this.closed||this.rejectAllPending(e)}rejectAllPending(e){for(;this.pending.length>0;){const t=this.pending.shift();null==t||t.reject(e)}}}class po extends uo{constructor(e,t){super(),this.client=e,this.readerId=t}static async create(e,t){const n=new fo(t.nativeHost,t.nativePort,t.nativeConnectTimeoutMs,t.nativeConnector),r=`ts_kevent_${Date.now()}_${Math.random().toString(36).slice(2,10)}`;try{return ao(await n.call({op:"register_reader",reader_id:r,patterns:e})),new po(n,r)}catch(s){throw await n.close(),s}}async pullEvent(e){if(this.isClosed())return null;const t=ao(await this.client.call({op:"pull_event",reader_id:this.readerId,timeout_ms:"number"==typeof e?Math.max(0,Math.floor(e)):void 0}));return t.event?co(t.event):null}async closeTransport(){try{ao(await this.client.call({op:"unregister_reader",reader_id:this.readerId}))}catch(e){e instanceof Error&&/closed/i.test(e.message)||console.warn("kevent unregister failed:",e)}finally{await this.client.close()}}}async function go(e,t,n){if(!ro())throw new Error("native kevent requires Node.js");const r=await async function(e){return ro()&&"function"==typeof require?require(e):Function("name","return import(name)")(e)}("node:net");return new Promise(((s,i)=>{const o=r.createConnection({host:e,port:t});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=e=>{if(!a){a=!0,h();try{o.destroy(e)}catch{}i(e)}},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 mo{constructor(e){this.mode=e.mode,this.streamUrl=`${(e.streamUrl??"/kapi/kevent").replace(/\/+$/,"")}/stream`,this.nativeHost=e.nativeHost??"127.0.0.1",this.nativePort=e.nativePort??3183,this.nativeConnectTimeoutMs=e.nativeConnectTimeoutMs??5e3,this.fetcher=e.fetcher??no,this.sessionTokenProvider=e.sessionTokenProvider??null,this.nativeConnector=e.nativeConnector??go}async createEventReader(e,t={}){const n=so(e);if("browser"===this.mode){const e=new ho(this.streamUrl,n,"number"!=typeof(r=t.keepaliveMs)||!Number.isFinite(r)||r<=0?15e3:Math.floor(r),this.fetcher,this.sessionTokenProvider,t.signal);try{return await e.waitUntilReady(),e}catch(s){throw await e.close(),s}}var r;return po.create(n,{nativeHost:this.nativeHost,nativePort:this.nativePort,nativeConnectTimeoutMs:this.nativeConnectTimeoutMs,nativeConnector:this.nativeConnector})}async create_event_reader(e,t={}){return this.createEventReader(e,t)}async subscribe(e,t,n={}){const r=so(e),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 t(n)}catch(e){console.error("kevent callback failed:",e)}}}catch(e){a||s.signal.aborted||console.warn("kevent subscription disconnected, will retry:",e)}finally{const e=o;o=null,e&&await e.close()}if(a||s.signal.aborted)break;try{await io(i,s.signal)}catch{break}}})();return{close:async()=>{if(a)return;a=!0,s.abort();const e=o;o=null,e&&await e.close(),await c.catch((()=>{}))}}}}const yo={runtime:null};function wo(){if("undefined"==typeof window)return null;const e=window.BuckyApi;return e&&"object"==typeof e?e:null}async function bo(){const e=wo(),t=null==e?void 0:e.getCurrentUser;if("function"!=typeof t)return null;const n=await t.call(e);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 _o(e,t=null){const n=wo(),r=null==n?void 0:n.resolve_did;if("function"!=typeof r)return null;const s=await r.call(n,e,t);return 0===(null==s?void 0:s.code)&&function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"json"===t.type&&Object.prototype.hasOwnProperty.call(t,"value")||"jwt"===t.type&&"string"==typeof t.jwt}(s.data)?s.data:(console.error("BuckyApi.resolve_did failed: ",null==s?void 0:s.message),null)}function Ao(){return"undefined"!=typeof window}function vo(){const e=globalThis.process;return(null==e?void 0:e.env)??{}}function Eo(e){if("string"!=typeof e)return null;const t=e.trim();return t.length>0?t:null}function ko(){return"undefined"!=typeof localStorage}function So(e){return e?e.split(/[./]/).map((e=>e.trim())).filter((e=>e.length>0)):[]}function To(){return Eo(vo().BUCKYOS_APP_INSTANCE_ID)?Ni.AppService:Ni.AppClient}function Ro(){var e;return(null==(e=yo.runtime)?void 0:e.getConfig().runtimeType)??function(){var e;if("undefined"!=typeof window)return window.BuckyApi?Ni.AppRuntime:Ni.Browser;const t=globalThis.process;return(null==(e=null==t?void 0:t.versions)?void 0:e.node)?Ni.NodeJS:Ni.Unknown}()}function Io(){var e;const t=yo.runtime;return t?function(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost";return new URL(e,t).origin}catch{return null}}(t.getSystemConfigServiceURL()):"undefined"!=typeof window&&(null==(e=window.location)?void 0:e.origin)?window.location.origin:null}async function Co(){const e=yo.runtime;return e?e.ensureSessionTokenReady():null}class Oo{constructor(e){this.currentRuntime=null,this.currentAccountInfo=null,this.currentKEventClient=null,this.target=e}async initBuckyOS(e="",t=null){var n;const r=this.buildRuntimeConfig(e,t);if("node"!==this.target&&Ao()&&!t){let t=localStorage.getItem("zone_host_name_v2");t||(t=await this.tryGetZoneHostName(e,window.location.host,r.defaultProtocol),localStorage.setItem("zone_host_name_v2",t)),r.zoneHost=t}var s;null==(n=this.currentRuntime)||n.stopAutoRenew(),this.currentKEventClient=null,this.currentAccountInfo=null,this.currentRuntime=new Xi(r),await this.currentRuntime.initialize(),s=this.currentRuntime,yo.runtime=s,this.syncCurrentAccountInfoFromRuntime()}getBuckyOSConfig(){var e;return(null==(e=this.currentRuntime)?void 0:e.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 e;return(null==(e=this.currentRuntime)?void 0:e.getAppDid())??null}getAppInstanceId(){var e;return(null==(e=this.currentRuntime)?void 0:e.getAppInstanceId())??null}getAppDataDir(){var e;return(null==(e=this.currentRuntime)?void 0:e.getDataDir())??null}attachEvent(e,t){}removeEvent(e){}getKEventClient(){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");if(this.currentKEventClient)return this.currentKEventClient;const e=this.currentRuntime.getConfig().runtimeType,t=e===Ni.Browser||e===Ni.AppRuntime?"browser":"native";return this.currentKEventClient=new mo({mode:t,streamUrl:this.currentRuntime.getZoneServiceURL("kevent"),sessionTokenProvider:this.currentRuntime.ensureSessionTokenReady.bind(this.currentRuntime)}),this.currentKEventClient}async createEventReader(e,t={}){return this.getKEventClient().createEventReader(e,t)}async create_event_reader(e,t={}){return this.createEventReader(e,t)}async subscribeKEvent(e,t,n={}){return this.getKEventClient().subscribe(e,t,n)}async getCurrentIdentity(){if(null==this.currentRuntime)return console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),Kn;const e=this.currentRuntime.getConfig().runtimeType;return e!==Ni.Browser&&e!==Ni.AppRuntime?Kn:this.currentRuntime.getCurrentIdentity()}async getAccountInfo(){if(null==this.currentRuntime)return console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),null;this.syncCurrentAccountInfoFromRuntime();const e=this.currentRuntime.getConfig().runtimeType;if(e!==Ni.Browser&&e!==Ni.AppRuntime)return this.currentAccountInfo;const t=await this.currentRuntime.ensureSessionTokenReady(),n=ko()?Mn.getBrowserUserInfo():null;return t&&n?(this.currentAccountInfo={user_name:n.user_name,user_id:n.user_id,user_type:n.user_type,session_token:t,refresh_token:void 0},this.currentAccountInfo):(this.currentAccountInfo=null,null)}async loginByPassword(e,t,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=sr(a);if(c!==o)throw new Error(`auth target appid mismatch: ${c} != ${o}`);const l=Date.now(),u=Mn.hashPassword(e,t,l);ko()&&localStorage.removeItem(`buckyos.account_info.${o}`);try{const t=this.getVerifyHubClient();t.setSeq(l);const n=await t.loginByPassword({username:e,password:u,target:a,login_nonce:l,source_url:"undefined"!=typeof window?window.location.href:void 0}),r={user_name:n.user_info.show_name,user_id:n.user_info.user_id,user_type:n.user_info.user_type,session_token:n.session_token,refresh_token:n.refresh_token};return ko()&&(Mn.saveLocalAccountInfo(o,r),Mn.clearBrowserIdentity(),Mn.saveBrowserUserInfo({user_name:r.user_name,user_id:r.user_id,user_type:n.user_info.user_type})),this.currentAccountInfo=r,null==(s=this.currentRuntime)||s.setSessionToken(r.session_token),null==(i=this.currentRuntime)||i.setRefreshToken(r.refresh_token??null),r}catch(h){throw console.error("login failed: ",h),h}}async loginByRuntimeSession(){const e=this.currentRuntime;return null==e?(console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),null):(await e.login(),this.syncCurrentAccountInfoFromRuntime(),this.currentAccountInfo)}async loginByBrowserSSO(){if(null==this.currentRuntime)return void console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first");const e=this.getAppId();if(null==e)return void console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first");ko()&&Mn.cleanLocalAccountInfo(e);const t=this.getZoneHostName();if(null!=t)try{const e=new Vn(t);await e.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(e=!0){if(null==this.currentRuntime)return void console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first");const t=this.getAppId();null!=t?(e&&this.currentRuntime.logoutBrowserSSO(),e&&ko()&&Mn.cleanLocalAccountInfo(t),this.currentAccountInfo=null,this.currentKEventClient=null,this.currentRuntime.clearAuthState()):console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first")}async getAppSetting(e=null){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return function(e,t){const n=So(t);if(0===n.length)return e;let r=e;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(),e)}async setAppSetting(e=null,t){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");const n=await this.currentRuntime.getMySettings(),r=function(e,t,n){const r=So(t);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(e)?{}:{...e};let i=s;for(let o=0;o<r.length-1;o+=1){const e=r[o],t=i[e],n=t&&"object"==typeof t&&!Array.isArray(t)?{...t}:{};i[e]=n,i=n}return i[r[r.length-1]]=n,s}(n&&"object"==typeof n&&!Array.isArray(n)?{...n}:{},e,function(e){try{return JSON.parse(e)}catch{return e}}(t));await this.currentRuntime.updateAllMySettings(r)}getCurrentWalletUser(){if("undefined"==typeof window)throw new Error("BuckyApi is only available in browser runtime");return bo()}resolve_did(e,t=null){if("undefined"==typeof window)throw new Error("BuckyApi is only available in browser runtime");return _o(e,t)}walletSignWithActiveDid(e){if("undefined"==typeof window)throw new Error("BuckyApi is only available in browser runtime");return(async()=>{var t,n;const r=await window.BuckyApi.signJsonWithActiveDid(e);return 0===r.code?{signatures:Array.isArray(null==(t=r.data)?void 0:t.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(e){if("undefined"==typeof window)throw new Error("openExternalUrl is only available in browser runtime");const t=window.BuckyApi;"function"!=typeof(null==t?void 0:t.openExternalUrl)?window.open(e,"_blank","noopener,noreferrer"):await t.openExternalUrl(e)}getZoneHostName(){return null==this.currentRuntime?(console.error("BuckyOS WebSDK is not initialized,call initBuckyOS first"),null):this.currentRuntime.getZoneHostName()}getZoneServiceURL(e){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return this.currentRuntime.getZoneServiceURL(e)}getServiceRpcClient(e){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(e)}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()}getAiWorkspaceClient(){if(null==this.currentRuntime)throw new Error("BuckyOS WebSDK is not initialized,call initBuckyOS first");return this.currentRuntime.getAiWorkspaceClient()}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(e,t){if(t){let n=t.runtimeType;return n===Ni.NodeJS&&"browser"!==this.target&&(n=To()),{...Bi,...t,appId:t.appId||e,runtimeType:n}}return"browser"===this.target?{...Bi,appId:e,runtimeType:this.detectEnvironmentRuntimeType(),defaultProtocol:"undefined"!=typeof window?window.location.protocol+"//":"http://"}:"node"===this.target?{...Bi,appId:e,runtimeType:To(),defaultProtocol:"https://",zoneHost:Eo(vo().BUCKYOS_ZONE_HOST)??""}:Ao()?{...Bi,appId:e,runtimeType:this.detectEnvironmentRuntimeType(),defaultProtocol:window.location.protocol+"//"}:{...Bi,appId:e,runtimeType:To(),defaultProtocol:"https://",zoneHost:Eo(vo().BUCKYOS_ZONE_HOST)??""}}async tryGetZoneHostName(e,t,n){const r=await this.fetchZoneHostFromIdentifierDoc(n+t+"/1.0/identifiers/self");if(r)return r;const s=t.split(".").slice(1).join(".");if(!s)return t;const i=await this.fetchZoneHostFromIdentifierDoc(n+s+"/1.0/identifiers/self");return i||t}async fetchZoneHostFromIdentifierDoc(e){try{const t=await fetch(e);if(200!==t.status)return null;const n=await t.json(),r="string"==typeof n.hostname?n.hostname.trim():"";return r.length>0?r:null}catch{return null}}syncCurrentAccountInfoFromRuntime(){if(null==this.currentRuntime)return;const e=this.currentRuntime.getSessionToken();if(!e)return;const t=Hi(e),n="string"==typeof(null==t?void 0:t.sub)?t.sub:"string"==typeof(null==t?void 0:t.userid)?t.userid:this.currentRuntime.getOwnerUserId()??"root",r="string"==typeof(null==t?void 0:t.user_type)?t.user_type:this.currentRuntime.getConfig().runtimeType===Ni.AppService?"service":void 0;this.currentAccountInfo={user_name:n,user_id:n,user_type:r,session_token:e,refresh_token:this.currentRuntime.getRefreshToken()??void 0}}usesRuntimeManagedSession(){if(null==this.currentRuntime)return!1;const e=this.currentRuntime.getConfig().runtimeType;return e===Ni.AppClient||e===Ni.AppService}detectEnvironmentRuntimeType(){var e,t;if("browser"===this.target)return"undefined"!=typeof window&&window.BuckyApi?Ni.AppRuntime:"undefined"!=typeof window?Ni.Browser:Ni.Unknown;if("node"===this.target){const t=globalThis.process;return(null==(e=null==t?void 0:t.versions)?void 0:e.node)?To():Ni.Unknown}if("undefined"!=typeof window)return window.BuckyApi?Ni.AppRuntime:Ni.Browser;const n=globalThis.process;return(null==(t=null==n?void 0:n.versions)?void 0:t.node)?Ni.NodeJS:Ni.Unknown}}const xo="/kapi/bns",No="/kapi/bns-indexer",Po="did:bns:",Do="name.query_state",Bo="name.resolve_owner",Uo="authority.get_set",Lo="authority.get_key",Mo="document.resolve",Fo="document.get_version",jo="name.query_by_addr",Go="tx.query_state",Ho="tx.submit_raw",Vo="events.list",qo="checkpoint.latest",Wo={transport:"RPC_TRANSPORT_ERROR",serialization:"SERIALIZATION_ERROR",invalid_response:"INVALID_RESPONSE",timeout:"TX_WAIT_TIMEOUT"};class zo extends Error{constructor(e,t,n=null){super(t),this.name="BnsClientError",this.kind=e,this.info=n}get code(){var e;return"registry"===this.kind?(null==(e=this.info)?void 0:e.code)??"UNKNOWN_BNS_ERROR":Wo[this.kind]}isRegistryCode(e){return"registry"===this.kind&&this.code===e}static registry(e){return new zo("registry",`${e.code}: ${e.message}`,e)}static registryCode(e,t,n={}){return zo.registry({code:e,message:t,name:null,doc_type:null,expected:null,actual:null,...n})}}class $o extends Error{constructor(e,t){super(`${e}: ${t}`),this.path=e,this.reason=t,this.name="BnsDecodeError"}}function Ko(e,t){throw new $o(e,t)}const Qo=(e,t)=>"string"==typeof e?e:Ko(t,"expected string"),Jo=(e,t)=>"boolean"==typeof e?e:Ko(t,"expected boolean"),Yo=(e,t)=>"number"==typeof e&&Number.isInteger(e)&&e>=0?e:Ko(t,"expected u64"),Zo=(e,t)=>"number"==typeof e&&Number.isInteger(e)&&e>=0&&e<=4294967295?e:Ko(t,"expected u32"),Xo=(e,t)=>{Array.isArray(e)||Ko(t,"expected byte array");for(let n=0;n<e.length;n++){const r=e[n];("number"!=typeof r||!Number.isInteger(r)||r<0||r>255)&&Ko(`${t}[${n}]`,"expected u8")}return e};function ea(...e){return(t,n)=>"string"==typeof t&&e.includes(t)?t:Ko(n,`expected one of ${e.join("|")}`)}function ta(e){return(t,n)=>(Array.isArray(t)||Ko(n,"expected array"),t.map(((t,r)=>e(t,`${n}[${r}]`))))}function na(e,t){const n=(t,n)=>e(t,n);return n.onMissing=t,n}function ra(e){return na(((t,n)=>null===t?null:e(t,n)),(()=>null))}const sa=na(Yo,(()=>0));function ia(e,t){const n=Object.keys(t);return(r,s)=>{(null===r||"object"!=typeof r||Array.isArray(r))&&Ko(s,`expected ${e} object`);const i=r,o={};for(const e of n){const n=t[e],r=`${s}.${e}`,a=i[e];if(void 0===a&&!(e in i)){if(n.onMissing){o[e]=n.onMissing();continue}Ko(r,"missing field")}o[e]=n(a,r)}return o}}const oa=ea("available","active","expired","released","tombstoned"),aa=ea("missing","active","revoked","expired","migrated","tombstoned"),ca=ea("none","alias","migrated_to","canonical"),la=ea("release_after_grace","tombstone_forever"),ua=ea("unset","chain_account","bns_name"),ha=ea("none","asset_owner_fallback","explicit_semantic_owner","parent_inherited"),da=ea("missing","active","revoked","expired"),fa=ea("not_found","pending","succeeded","reverted"),pa=ia("Principal",{kind:ua,value:Qo}),ga=ia("NameState",{name:Qo,asset_owner:Qo,semantic_owner:pa,effective_owner:pa,owner_source:ha,standard_transfer_enabled:Jo,status:oa,registered_at:Yo,expire_at:Yo,grace_until:Yo,updated_at:Yo,name_seq:Yo,owner_document_version:Yo,min_document_iat:sa,owner_policy_seq:sa,lineage_epoch:Yo,renewable:Jo,transferable:Jo,allow_delegated_subnames:Jo,namespace_policy_hash:Qo,payment_policy_hash:Qo,alias_state_hash:Qo}),ma=ia("OwnerResolution",{effective_owner:pa,source:ha,authority_root:Qo,authority_seq:Yo}),ya=ia("AuthoritySetState",{name:Qo,authority_seq:Yo,authority_root:Qo,active_key_count:Zo}),wa=ia("AuthorityKey",{kid:Qo,verification_method:Qo,key_data:Xo,purposes:Zo,valid_from:Yo,valid_until:Yo,status:da,metadata_hash:Qo}),ba=ia("DocumentRef",{storage_type:Qo,uri:Qo,inline_document:Xo,content_hash:Qo,schema:Qo,codec:Qo,extra_hash:Qo}),_a=ia("DocumentState",{name:Qo,doc_type:Qo,version:Yo,previous_version:Yo,status:aa,document:ba,controller:pa,beneficiary:pa,payment_target:Qo,valid_from:Yo,expire_at:Yo,revoked_at:Yo,controller_policy_hash:Qo,payment_policy_hash:Qo,split_policy_hash:Qo,price_policy_hash:Qo,rights_policy_hash:Qo,document_state_hash:Qo}),Aa=ia("ResolveResult",{name_state:ga,document_state:_a,owner:ma,effective_controller:pa,status:aa,alias_kind:ca,alias_target_did:Qo,proof_root:Qo}),va=ia("BnsNamePage",{names:ta(Qo),next_cursor:ra(Qo)}),Ea=ia("BnsTxState",{tx_hash:Qo,state:fa,block_number:ra(Yo),confirmations:Yo}),ka=ia("BnsSubmitRawTxResp",{tx_hash:Qo}),Sa=ia("LogCheckpoint",{log_root:Qo,last_seq:Yo,issued_at:Yo,issuer:pa,external_anchor:Qo}),Ta={name_registered:ia("name_registered",{name:Qo,asset_owner:Qo,expire_at:Yo,lineage_epoch:Yo,name_seq:Yo}),name_renewed:ia("name_renewed",{name:Qo,expire_at:Yo,name_seq:Yo}),name_asset_transferred:ia("name_asset_transferred",{name:Qo,old_asset_owner:Qo,new_asset_owner:Qo,standard_transfer:Jo,name_seq:Yo}),name_owner_updated:ia("name_owner_updated",{name:Qo,owner:pa,owner_source:ha,standard_transfer_enabled:Jo,name_seq:Yo}),authority_keys_updated:ia("authority_keys_updated",{name:Qo,authority_seq:Yo,authority_root:Qo}),name_released:ia("name_released",{name:Qo,mode:la,reason_hash:Qo,name_seq:Yo}),document_published:ia("document_published",{name:Qo,doc_type:Qo,version:Yo,content_hash:Qo,document_state_hash:Qo}),document_revoked:ia("document_revoked",{name:Qo,doc_type:Qo,previous_version:Yo,new_version:Yo,reason_hash:Qo}),owner_document_iat_floor_updated:ia("owner_document_iat_floor_updated",{name:Qo,previous_min_document_iat:Yo,new_min_document_iat:Yo,owner_policy_seq:Yo,name_seq:Yo,reason_hash:Qo}),controller_policy_updated:ia("controller_policy_updated",{name:Qo,policy_hash:Qo,name_seq:Yo}),namespace_policy_updated:ia("namespace_policy_updated",{name:Qo,allow_delegated_subnames:Jo,namespace_policy_hash:Qo,name_seq:Yo}),did_alias_set:ia("did_alias_set",{name:Qo,target_did:Qo,kind:ca,proof_hash:Qo,name_seq:Yo}),payment_target_updated:ia("payment_target_updated",{name:Qo,doc_type:Qo,payment_target:Qo,payment_policy_hash:Qo,version:Yo}),log_checkpoint_published:ia("log_checkpoint_published",{log_root:Qo,last_seq:Yo,issued_at:Yo,external_anchor:Qo})},Ra=ta(ia("EventLogRecord",{seq:Yo,event_type:Qo,observed_at:Yo,event_hash:Qo,previous_log_root:Qo,log_root:Qo,event:(e,t)=>{(null===e||"object"!=typeof e||Array.isArray(e))&&Ko(t,"expected RegistryEvent object");const n=e;"string"!=typeof n.type&&Ko(`${t}.type`,"expected string event tag");const r=Ta[n.type];return r||Ko(`${t}.type`,`unknown event type \`${n.type}\``),"data"in n&&void 0!==n.data||Ko(`${t}.data`,"missing field"),{type:n.type,data:r(n.data,`${t}.data`)}}})),Ia=ia("BnsRpcErrorInfo",{code:Qo,message:Qo,name:ra(Qo),doc_type:ra(Qo),expected:ra(Yo),actual:ra(Yo)});function Ca(e){const t=e.split("://"),n=t.length>1?t.slice(1).join("://"):e,r=n.indexOf("/");return!(r<0)&&""!==n.slice(r+1).replace(/\/+$/,"")}function Oa(e){const t=e.replace(/\/+$/,"");return Ca(t)?t:`${t}${xo}`}function xa(e){const t=e.replace(/\/+$/,"");return Ca(t)?t:`${t}${No}`}function Na(e){const t=t=>zo.registryCode("INVALID_NAME",`invalid BNS name \`${e}\`: ${t}`,{name:e});if(!e)throw t("name is empty");if(e.trim()!==e)throw t("name must not contain leading or trailing whitespace");if(e.startsWith(Po))throw t("contract names must not include did:bns: prefix");if(e.length>253)throw t("name must be at most 253 bytes");for(const n of e.split(".")){if(!n)throw t("empty label");if(n.length>126)throw t("label must be at most 126 bytes");if(n.startsWith("-")||n.endsWith("-"))throw t("label must not start or end with '-'");if(!/^[a-z0-9-]+$/.test(n))throw t("only lower-case ASCII letters, digits, '-' and '.' are supported")}return e}function Pa(e){const t=t=>zo.registryCode("INVALID_DOC_TYPE",`invalid doc_type \`${e}\`: ${t}`,{doc_type:e});if(!e)throw t("doc_type is empty");if(e.length>32)throw t("doc_type must be at most 32 bytes");if(!/^[a-z0-9_-]+$/.test(e))throw t("only lower-case ASCII letters, digits, '-' and '_' are supported");return e}const Da="0123456789abcdef";function Ba(e){if(e instanceof Uint8Array){if(0===e.length)throw new zo("serialization","raw_tx must not be empty");return`0x${function(e){let t="";for(let n=0;n<e.length;n++)t+=Da[e[n]>>4]+Da[15&e[n]];return t}(e)}`}const t=e.trim();if(!t)throw new zo("serialization","raw_tx must not be empty");const n=t.startsWith("0x")?t.slice(2):t;if(!n||n.length%2!=0)throw new zo("serialization",`raw_tx must be even-length hex, got \`${e}\``);if(!/^[0-9a-fA-F]+$/.test(n))throw new zo("serialization",`invalid raw_tx hex \`${e}\``);return`0x${n}`}function Ua(e,t){if("number"!=typeof t||!Number.isInteger(t)||t<0)throw new zo("serialization",`waitTx ${e} must be a non-negative integer, got ${t}`);return Math.max(1,t)}class La{constructor(e,t=null,n={}){this.rpcClient=new Gn(Oa(e),t,null,n)}static forIndexer(e,t=null,n={}){return new La(xa(e),t,n)}setSeq(e){this.rpcClient.setSeq(e)}async syncSessionToken(e){this.rpcClient.setSessionToken(e)}getSessionToken(){return this.rpcClient.getSessionToken()}setTraceId(e){this.rpcClient.setTraceId(e)}getTraceId(){return this.rpcClient.getTraceId()}async callEnvelope(e,t){let n;try{n=await this.rpcClient.call(e,t)}catch(s){const t=s instanceof Error?s.message:String(s);throw new zo("transport",`${e} failed: ${t}`)}if(null===n||"object"!=typeof n||Array.isArray(n))throw new zo("invalid_response",`invalid BNS RPC envelope for ${e}`);const r=n;if("boolean"!=typeof r.ok)throw new zo("invalid_response",`invalid BNS RPC envelope for ${e}`);if(!r.ok){if(void 0!==r.result&&null!==r.result)throw new zo("invalid_response",`unexpected result in failed BNS envelope for ${e}`);if(void 0===r.error||null===r.error)throw zo.registryCode("UNKNOWN_BNS_ERROR","BNS RPC envelope missing error");let t;try{t=Ia(r.error,"error")}catch(s){const t=s instanceof $o?s.message:String(s);throw new zo("invalid_response",`invalid BNS error info for ${e}: ${t}`)}throw zo.registry(t)}if(void 0!==r.error&&null!==r.error)throw new zo("invalid_response",`unexpected error in successful BNS envelope for ${e}`);if(void 0===r.result)throw new zo("invalid_response",`BNS RPC envelope missing result for ${e}`);return r.result}decodeResult(e,t,n){try{return t(n,"result")}catch(r){const t=r instanceof $o?r.message:String(r);throw new zo("invalid_response",`invalid ${e} result: ${t}`)}}async call(e,t,n){const r=await this.callEnvelope(e,t);if(null===r)throw new zo("invalid_response",`BNS RPC envelope missing result for ${e}`);return this.decodeResult(e,n,r)}async callNullable(e,t,n){const r=await this.callEnvelope(e,t);return null===r?null:this.decodeResult(e,n,r)}async queryNameState(e){return this.callNullable(Do,{name:e},ga)}async resolveOwner(e){return this.call(Bo,{name:e},ma)}async getAuthoritySet(e){return this.call(Uo,{name:e},ya)}async getAuthorityKey(e,t){return this.callNullable(Lo,{name:e,kid:t},wa)}async resolveDocument(e,t){return this.call(Mo,{name:e,doc_type:t},Aa)}async getDocumentVersion(e,t,n){return this.callNullable(Fo,{name:e,doc_type:t,version:n},_a)}async queryNamesByAddress(e,t=null,n=100){return this.call(jo,{address:e,cursor:t,limit:n},va)}async*iterNamesByAddress(e,t=100){let n=null;do{const r=await this.queryNamesByAddress(e,n,t);yield*r.names,n=r.next_cursor}while(null!==n)}async queryTxState(e){return this.call(Go,{tx_hash:e},Ea)}async submitRawTx(e){return this.call(Ho,{raw_tx:Ba(e)},ka)}async waitTx(e,t={}){const n=Ua("confirmations",t.confirmations??1),r=Ua("intervalMs",t.intervalMs??2e3),s=Ua("timeoutMs",t.timeoutMs??12e4),i=Date.now();for(;;){const t=await this.queryTxState(e);if("reverted"===t.state)return t;if("succeeded"===t.state&&t.confirmations>=n)return t;if(Date.now()-i>=s)throw new zo("timeout",`timed out waiting for tx ${e} (last state: ${t.state})`);await new Promise((e=>setTimeout(e,r)))}}async listEvents(e,t=100){return this.call(Vo,{from_seq:e,limit:t},Ra)}async latestCheckpoint(){return this.callNullable(qo,{},Sa)}}const Ma=Object.freeze(Object.defineProperty({__proto__:null,BNS_INDEXER_RPC_PATH:No,BNS_SERVER_RPC_PATH:xo,BnsClient:La,BnsClientError:zo,DID_BNS_PREFIX:Po,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:Lo,METHOD_GET_AUTHORITY_SET:Uo,METHOD_GET_DOCUMENT_VERSION:Fo,METHOD_LATEST_CHECKPOINT:qo,METHOD_LIST_EVENTS:Vo,METHOD_QUERY_NAMES_BY_ADDRESS:jo,METHOD_QUERY_NAME_STATE:Do,METHOD_QUERY_TX_STATE:Go,METHOD_RESOLVE_DOCUMENT:Mo,METHOD_RESOLVE_OWNER:Bo,METHOD_SUBMIT_RAW_TX:Ho,ZERO_HASH:"0x0000000000000000000000000000000000000000000000000000000000000000",canonicalBnsName:Na,canonicalDocType:Pa,didBnsFromName:function(e){return`${Po}${Na(e)}`},nameFromDidBns:function(e){if(!e.startsWith(Po))throw zo.registryCode("INVALID_NAME",`invalid BNS name \`${e}\`: DID must start with did:bns:`,{name:e});return Na(e.slice(8))},normalizeBnsIndexerUrl:xa,normalizeBnsServerUrl:Oa,normalizeRawTx:Ba},Symbol.toStringTag,{value:"Module"})),Fa="6.17.0";function ja(e,t,n){const r=t.split("|").map((e=>e.trim()));for(let i=0;i<r.length;i++)switch(t){case"any":return;case"bigint":case"boolean":case"number":case"string":if(typeof e===t)return}const s=new Error(`invalid value for type ${t}`);throw s.code="INVALID_ARGUMENT",s.argument=`value.${n}`,s.value=e,s}async function Ga(e){const t=Object.keys(e);return(await Promise.all(t.map((t=>Promise.resolve(e[t]))))).reduce(((e,n,r)=>(e[t[r]]=n,e)),{})}function Ha(e,t,n){for(let r in t){let s=t[r];const i=n?n[r]:null;i&&ja(s,i,r),Object.defineProperty(e,r,{enumerable:!0,value:s,writable:!1})}}function Va(e,t){if(null==e)return"null";if(null==t&&(t=new Set),"object"==typeof e){if(t.has(e))return"[Circular]";t.add(e)}if(Array.isArray(e))return"[ "+e.map((e=>Va(e,t))).join(", ")+" ]";if(e instanceof Uint8Array){const t="0123456789abcdef";let n="0x";for(let r=0;r<e.length;r++)n+=t[e[r]>>4],n+=t[15&e[r]];return n}if("object"==typeof e&&"function"==typeof e.toJSON)return Va(e.toJSON(),t);switch(typeof e){case"boolean":case"number":case"symbol":return e.toString();case"bigint":return BigInt(e).toString();case"string":return JSON.stringify(e);case"object":{const n=Object.keys(e);return n.sort(),"{ "+n.map((n=>`${Va(n,t)}: ${Va(e[n],t)}`)).join(", ")+" }"}}return"[ COULD NOT SERIALIZE ]"}function qa(e,t){return e&&e.code===t}function Wa(e){return qa(e,"CALL_EXCEPTION")}function za(e,t,n){let r,s=e;{const r=[];if(n){if("message"in n||"code"in n||"name"in n)throw new Error(`value will overwrite populated values: ${Va(n)}`);for(const e in n){if("shortMessage"===e)continue;const t=n[e];r.push(e+"="+Va(t))}}r.push(`code=${t}`),r.push(`version=${Fa}`),r.length&&(e+=" ("+r.join(", ")+")")}switch(t){case"INVALID_ARGUMENT":r=new TypeError(e);break;case"NUMERIC_FAULT":case"BUFFER_OVERRUN":r=new RangeError(e);break;default:r=new Error(e)}return Ha(r,{code:t}),n&&Object.assign(r,n),null==r.shortMessage&&Ha(r,{shortMessage:s}),r}function $a(e,t,n,r){if(!e)throw za(t,n,r)}function Ka(e,t,n,r){$a(e,t,"INVALID_ARGUMENT",{argument:n,value:r})}function Qa(e,t,n){null==n&&(n=""),n&&(n=": "+n),$a(e>=t,"missing argument"+n,"MISSING_ARGUMENT",{count:e,expectedCount:t}),$a(e<=t,"too many arguments"+n,"UNEXPECTED_ARGUMENT",{count:e,expectedCount:t})}const Ja=["NFD","NFC","NFKD","NFKC"].reduce(((e,t)=>{try{if("test"!=="test".normalize(t))throw new Error("bad");if("NFD"===t){const e=String.fromCharCode(233).normalize("NFD");if(e!==String.fromCharCode(101,769))throw new Error("broken")}e.push(t)}catch(n){}return e}),[]);function Ya(e){$a(Ja.indexOf(e)>=0,"platform missing String.prototype.normalize","UNSUPPORTED_OPERATION",{operation:"String.prototype.normalize",info:{form:e}})}function Za(e,t,n){if(null==n&&(n=""),e!==t){let e=n,t="new";n&&(e+=".",t+=" "+n),$a(!1,`private constructor; use ${e}from* methods`,"UNSUPPORTED_OPERATION",{operation:t})}}function Xa(e,t,n){if(e instanceof Uint8Array)return n?new Uint8Array(e):e;if("string"==typeof e&&e.length%2==0&&e.match(/^0x[0-9a-f]*$/i)){const t=new Uint8Array((e.length-2)/2);let n=2;for(let r=0;r<t.length;r++)t[r]=parseInt(e.substring(n,n+2),16),n+=2;return t}Ka(!1,"invalid BytesLike value",t||"value",e)}function ec(e,t){return Xa(e,t,!1)}function tc(e,t){return Xa(e,t,!0)}function nc(e,t){return!("string"!=typeof e||!e.match(/^0x[0-9A-Fa-f]*$/))&&(("number"!=typeof t||e.length===2+2*t)&&(!0!==t||e.length%2==0))}function rc(e){return nc(e,!0)||e instanceof Uint8Array}const sc="0123456789abcdef";function ic(e){const t=ec(e);let n="0x";for(let r=0;r<t.length;r++){const e=t[r];n+=sc[(240&e)>>4]+sc[15&e]}return n}function oc(e){return"0x"+e.map((e=>ic(e).substring(2))).join("")}function ac(e){return nc(e,!0)?(e.length-2)/2:ec(e).length}function cc(e,t,n){const r=ec(e);return null!=n&&n>r.length&&$a(!1,"cannot slice beyond data bounds","BUFFER_OVERRUN",{buffer:r,length:r.length,offset:n}),ic(r.slice(null==t?0:t,null==n?r.length:n))}function lc(e,t,n){const r=ec(e);$a(t>=r.length,"padding exceeds data length","BUFFER_OVERRUN",{buffer:new Uint8Array(r),length:t,offset:t+1});const s=new Uint8Array(t);return s.fill(0),n?s.set(r,t-r.length):s.set(r,0),ic(s)}function uc(e,t){return lc(e,t,!0)}function hc(e,t){return lc(e,t,!1)}const dc=BigInt(0),fc=BigInt(1),pc=9007199254740991;function gc(e,t){let n=yc(e,"value");const r=BigInt(Ac(t,"width")),s=fc<<r-fc;if(n<dc){n=-n,$a(n<=s,"too low","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:e});return(~n&(fc<<r)-fc)+fc}return $a(n<s,"too high","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:e}),n}function mc(e,t){const n=wc(e,"value"),r=BigInt(Ac(t,"bits"));return n&(fc<<r)-fc}function yc(e,t){switch(typeof e){case"bigint":return e;case"number":return Ka(Number.isInteger(e),"underflow",t||"value",e),Ka(e>=-pc&&e<=pc,"overflow",t||"value",e),BigInt(e);case"string":try{if(""===e)throw new Error("empty string");return"-"===e[0]&&"-"!==e[1]?-BigInt(e.substring(1)):BigInt(e)}catch(n){Ka(!1,`invalid BigNumberish string: ${n.message}`,t||"value",e)}}Ka(!1,"invalid BigNumberish value",t||"value",e)}function wc(e,t){const n=yc(e,t);return $a(n>=dc,"unsigned value cannot be negative","NUMERIC_FAULT",{fault:"overflow",operation:"getUint",value:e}),n}const bc="0123456789abcdef";function _c(e){if(e instanceof Uint8Array){let t="0x0";for(const n of e)t+=bc[n>>4],t+=bc[15&n];return BigInt(t)}return yc(e)}function Ac(e,t){switch(typeof e){case"bigint":return Ka(e>=-pc&&e<=pc,"overflow",t||"value",e),Number(e);case"number":return Ka(Number.isInteger(e),"underflow",t||"value",e),Ka(e>=-pc&&e<=pc,"overflow",t||"value",e),e;case"string":try{if(""===e)throw new Error("empty string");return Ac(BigInt(e),t)}catch(n){Ka(!1,`invalid numeric string: ${n.message}`,t||"value",e)}}Ka(!1,"invalid numeric value",t||"value",e)}function vc(e,t){const n=wc(e,"value");let r=n.toString(16);if(null==t)r.length%2&&(r="0"+r);else{const s=Ac(t,"width");if(0===s&&n===dc)return"0x";for($a(2*s>=r.length,`value exceeds width (${s} bytes)`,"NUMERIC_FAULT",{operation:"toBeHex",fault:"overflow",value:e});r.length<2*s;)r="0"+r}return"0x"+r}function Ec(e,t){const n=wc(e,"value");if(n===dc){const e=null!=t?Ac(t,"width"):0;return new Uint8Array(e)}let r=n.toString(16);if(r.length%2&&(r="0"+r),null!=t){const n=Ac(t,"width");for(;r.length<2*n;)r="00"+r;$a(2*n===r.length,`value exceeds width (${n} bytes)`,"NUMERIC_FAULT",{operation:"toBeArray",fault:"overflow",value:e})}const s=new Uint8Array(r.length/2);for(let i=0;i<s.length;i++){const e=2*i;s[i]=parseInt(r.substring(e,e+2),16)}return s}function kc(e){let t=ic(rc(e)?e:Ec(e)).substring(2);for(;t.startsWith("0");)t=t.substring(1);return""===t&&(t="0"),"0x"+t}const Sc="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";let Tc=null;function Rc(e){if(null==Tc){Tc={};for(let e=0;e<58;e++)Tc[Sc[e]]=BigInt(e)}const t=Tc[e];return Ka(null!=t,"invalid base58 value","letter",e),t}const Ic=BigInt(0),Cc=BigInt(58);function Oc(e){const t=ec(e);let n=_c(t),r="";for(;n;)r=Sc[Number(n%Cc)]+r,n/=Cc;for(let s=0;s<t.length&&!t[s];s++)r=Sc[0]+r;return r}class xc{constructor(t,n,r){xn(this,"filter"),xn(this,"emitter"),Dn(this,e,void 0),Bn(this,e,n),Ha(this,{emitter:t,filter:r})}async removeListener(){null!=Pn(this,e)&&await this.emitter.off(this.filter,Pn(this,e))}}function Nc(e,t,n,r,s){if("BAD_PREFIX"===e||"UNEXPECTED_CONTINUE"===e){let e=0;for(let r=t+1;r<n.length&&n[r]>>6==2;r++)e++;return e}return"OVERRUN"===e?n.length-t-1:0}e=new WeakMap;const Pc=Object.freeze({error:function(e,t,n,r,s){Ka(!1,`invalid codepoint at offset ${t}; ${e}`,"bytes",n)},ignore:Nc,replace:function(e,t,n,r,s){return"OVERLONG"===e?(Ka("number"==typeof s,"invalid bad code point for replacement","badCodepoint",s),r.push(s),0):(r.push(65533),Nc(e,t,n))}});function Dc(e,t){Ka("string"==typeof e,"invalid string value","str",e),null!=t&&(Ya(t),e=e.normalize(t));let n=[];for(let r=0;r<e.length;r++){const t=e.charCodeAt(r);if(t<128)n.push(t);else if(t<2048)n.push(t>>6|192),n.push(63&t|128);else if(55296==(64512&t)){r++;const s=e.charCodeAt(r);Ka(r<e.length&&56320==(64512&s),"invalid surrogate pair","str",e);const i=65536+((1023&t)<<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(t>>12|224),n.push(t>>6&63|128),n.push(63&t|128)}return new Uint8Array(n)}function Bc(e,t){return n=function(e,t){null==t&&(t=Pc.error);const n=ec(e,"bytes"),r=[];let s=0;for(;s<n.length;){const e=n[s++];if(!(e>>7)){r.push(e);continue}let i=null,o=null;if(192==(224&e))i=1,o=127;else if(224==(240&e))i=2,o=2047;else{if(240!=(248&e)){s+=t(128==(192&e)?"UNEXPECTED_CONTINUE":"BAD_PREFIX",s-1,n,r);continue}i=3,o=65535}if(s-1+i>=n.length){s+=t("OVERRUN",s-1,n,r);continue}let a=e&(1<<8-i-1)-1;for(let c=0;c<i;c++){let e=n[s];if(128!=(192&e)){s+=t("MISSING_CONTINUE",s,n,r),a=null;break}a=a<<6|63&e,s++}null!==a&&(a>1114111?s+=t("OUT_OF_RANGE",s-1-i,n,r,a):a>=55296&&a<=57343?s+=t("UTF16_SURROGATE",s-1-i,n,r,a):a<=o?s+=t("OVERLONG",s-1-i,n,r,a):r.push(a))}return r}(e,t),n.map((e=>e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode(55296+(e>>10&1023),56320+(1023&e))))).join("");var n}function Uc(e){return async function(t,n){$a(null==n||!n.cancelled,"request cancelled before sending","CANCELLED");const r=t.url.split(":")[0].toLowerCase();$a("http"===r||"https"===r,`unsupported protocol ${r}`,"UNSUPPORTED_OPERATION",{info:{protocol:r},operation:"request"}),$a("https"===r||!t.credentials||t.allowInsecureAuthentication,"insecure authorized connections unsupported","UNSUPPORTED_OPERATION",{operation:"request"});let s=null;const i=new AbortController,o=setTimeout((()=>{s=za("request timeout","TIMEOUT"),i.abort()}),t.timeout);n&&n.addListener((()=>{s=za("request cancelled","CANCELLED"),i.abort()}));const a=Object.assign({},e,{method:t.method,headers:new Headers(Array.from(t)),body:t.body||void 0,signal:i.signal});let c;try{c=await fetch(t.url,a)}catch(d){if(clearTimeout(o),s)throw s;throw d}clearTimeout(o);const l={};c.headers.forEach(((e,t)=>{l[t.toLowerCase()]=e}));const u=await c.arrayBuffer(),h=null==u?null:new Uint8Array(u);return{statusCode:c.status,statusMessage:c.statusText,headers:l,body:h}}}let Lc=Uc();const Mc=new RegExp("^data:([^;:]*)?(;base64)?,(.*)$","i"),Fc=new RegExp("^ipfs://(ipfs/)?(.*)$","i");let jc=!1;async function Gc(e,t){try{const t=e.match(Mc);if(!t)throw new Error("invalid data");return new Jc(200,"OK",{"content-type":t[1]||"text/plain"},t[2]?function(e){e=atob(e);const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return ec(t)}(t[3]):Dc(t[3].replace(/%([0-9a-f][0-9a-f])/gi,((e,t)=>String.fromCharCode(parseInt(t,16))))))}catch(n){return new Jc(599,"BAD REQUEST (invalid data: URI)",{},null,new Kc(e))}}function Hc(e){return async function(t,n){try{const n=t.match(Fc);if(!n)throw new Error("invalid link");return new Kc(`${e}${n[2]}`)}catch(r){return new Jc(599,"BAD REQUEST (invalid IPFS URI)",{},null,new Kc(t))}}}const Vc={data:Gc,ipfs:Hc("https://gateway.ipfs.io/ipfs/")},qc=new WeakMap;class Wc{constructor(e){Dn(this,t,void 0),Dn(this,n,void 0),Bn(this,t,[]),Bn(this,n,!1),qc.set(e,(()=>{if(!Pn(this,n)){Bn(this,n,!0);for(const e of Pn(this,t))setTimeout((()=>{e()}),0);Bn(this,t,[])}}))}addListener(e){$a(!Pn(this,n),"singal already cancelled","UNSUPPORTED_OPERATION",{operation:"fetchCancelSignal.addCancelListener"}),Pn(this,t).push(e)}get cancelled(){return Pn(this,n)}checkSignal(){$a(!this.cancelled,"cancelled","CANCELLED",{})}}function zc(e){if(null==e)throw new Error("missing signal; should not happen");return e.checkSignal(),e}t=new WeakMap,n=new WeakMap;const $c=class e{constructor(e){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(e)),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(e){Bn(this,c,String(e))}get body(){return null==Pn(this,l)?null:new Uint8Array(Pn(this,l))}set body(e){if(null==e)Bn(this,l,void 0),Bn(this,u,void 0);else if("string"==typeof e)Bn(this,l,Dc(e)),Bn(this,u,"text/plain");else if(e instanceof Uint8Array)Bn(this,l,e),Bn(this,u,"application/octet-stream");else{if("object"!=typeof e)throw new Error("invalid body");Bn(this,l,Dc(JSON.stringify(e))),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(e){null==e&&(e=""),Bn(this,o,String(e).toUpperCase())}get headers(){const e=Object.assign({},Pn(this,i));return Pn(this,h)&&(e.authorization=`Basic ${function(e){const t=ec(e);let n="";for(let r=0;r<t.length;r++)n+=String.fromCharCode(t[r]);return btoa(n)}(Dc(Pn(this,h)))}`),this.allowGzip&&(e["accept-encoding"]="gzip"),null==e["content-type"]&&Pn(this,u)&&(e["content-type"]=Pn(this,u)),this.body&&(e["content-length"]=String(this.body.length)),e}getHeader(e){return this.headers[e.toLowerCase()]}setHeader(e,t){Pn(this,i)[String(e).toLowerCase()]=String(t)}clearHeaders(){Bn(this,i,{})}[Symbol.iterator](){const e=this.headers,t=Object.keys(e);let n=0;return{next:()=>{if(n<t.length){const r=t[n++];return{value:[r,e[r]],done:!1}}return{value:void 0,done:!0}}}}get credentials(){return Pn(this,h)||null}setCredentials(e,t){Ka(!e.match(/:/),"invalid basic authentication username","username","[REDACTED]"),Bn(this,h,`${e}:${t}`)}get allowGzip(){return Pn(this,s)}set allowGzip(e){Bn(this,s,!!e)}get allowInsecureAuthentication(){return!!Pn(this,r)}set allowInsecureAuthentication(e){Bn(this,r,!!e)}get timeout(){return Pn(this,a)}set timeout(e){Ka(e>=0,"timeout must be non-zero","timeout",e),Bn(this,a,e)}get preflightFunc(){return Pn(this,d)||null}set preflightFunc(e){Bn(this,d,e)}get processFunc(){return Pn(this,f)||null}set processFunc(e){Bn(this,f,e)}get retryFunc(){return Pn(this,p)||null}set retryFunc(e){Bn(this,p,e)}get getUrlFunc(){return Pn(this,y)||Lc}set getUrlFunc(e){Bn(this,y,e)}toString(){return`<FetchRequest method=${JSON.stringify(this.method)} url=${JSON.stringify(this.url)} headers=${JSON.stringify(this.headers)} body=${Pn(this,l)?ic(Pn(this,l)):"null"}>`}setThrottleParams(e){null!=e.slotInterval&&(Pn(this,m).slotInterval=e.slotInterval),null!=e.maxAttempts&&(Pn(this,m).maxAttempts=e.maxAttempts)}send(){return $a(null==Pn(this,g),"request already sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.send"}),Bn(this,g,new Wc(this)),Ln(this,w,b).call(this,0,Yc()+this.timeout,0,this,new Jc(0,"",{},null,this))}cancel(){$a(null!=Pn(this,g),"request has not been sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.cancel"});const e=qc.get(this);if(!e)throw new Error("missing signal; should not happen");e()}redirect(t){const n=this.url.split(":")[0].toLowerCase(),r=t.split(":")[0].toLowerCase();$a(("https"!==n||"http"!==r)&&t.match(/^https?:/),"unsupported redirect","UNSUPPORTED_OPERATION",{operation:`redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(t)})`});const s=new e(t);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 t=new e(this.url);return Bn(t,o,Pn(this,o)),Pn(this,l)&&Bn(t,l,Pn(this,l)),Bn(t,u,Pn(this,u)),Bn(t,i,Object.assign({},Pn(this,i))),Bn(t,h,Pn(this,h)),this.allowGzip&&(t.allowGzip=!0),t.timeout=this.timeout,this.allowInsecureAuthentication&&(t.allowInsecureAuthentication=!0),Bn(t,d,Pn(this,d)),Bn(t,f,Pn(this,f)),Bn(t,p,Pn(this,p)),Bn(t,m,Object.assign({},Pn(this,m))),Bn(t,y,Pn(this,y)),t}static lockConfig(){jc=!0}static getGateway(e){return Vc[e.toLowerCase()]||null}static registerGateway(e,t){if("http"===(e=e.toLowerCase())||"https"===e)throw new Error(`cannot intercept ${e}; use registerGetUrl`);if(jc)throw new Error("gateways locked");Vc[e]=t}static registerGetUrl(e){if(jc)throw new Error("gateways locked");Lc=e}static createGetUrlFunc(e){return Uc(e)}static createDataGateway(){return Gc}static createIpfsGatewayFunc(e){return Hc(e)}};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(e,t,n,r,s){var i,o,a;if(e>=Pn(this,m).maxAttempts)return s.makeServerError("exceeded maximum retry limit");$a(Yc()<=t,"timeout","TIMEOUT",{operation:"request.send",reason:"timeout",request:r}),n>0&&await function(e){return new Promise((t=>setTimeout(t,e)))}(n);let c=this.clone();const l=(c.url.split(":")[0]||"").toLowerCase();if(l in Vc){const e=await Vc[l](c.url,zc(Pn(r,g)));if(e instanceof Jc){let t=e;if(this.processFunc){zc(Pn(r,g));try{t=await this.processFunc(c,t)}catch(d){null!=d.throttle&&"number"==typeof d.stall||t.makeServerError("error in post-processing function",d).assertOk()}}return t}c=e}this.preflightFunc&&(c=await this.preflightFunc(c));const u=await this.getUrlFunc(c,zc(Pn(r,g)));let h=new Jc(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,e+1,t,0,r,h)}catch(d){}return h}if(429===h.statusCode&&(null==this.retryFunc||await this.retryFunc(c,h,e))){const n=h.headers["retry-after"];let s=Pn(this,m).slotInterval*Math.trunc(Math.random()*Math.pow(2,e));return"string"==typeof n&&n.match(/^[1-9][0-9]*$/)&&(s=parseInt(n)),Ln(o=c.clone(),w,b).call(o,e+1,t,s,r,h)}if(this.processFunc){zc(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,e));return d.stall>=0&&(n=d.stall),Ln(a=c.clone(),w,b).call(a,e+1,t,n,r,h)}}return h};let Kc=$c;const Qc=class e{constructor(e,t,n,r,s){Dn(this,_,void 0),Dn(this,A,void 0),Dn(this,v,void 0),Dn(this,E,void 0),Dn(this,k,void 0),Dn(this,S,void 0),Bn(this,_,e),Bn(this,A,t),Bn(this,v,Object.keys(n).reduce(((e,t)=>(e[t.toLowerCase()]=String(n[t]),e)),{})),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)?ic(Pn(this,E)):"null"}>`}get statusCode(){return Pn(this,_)}get statusMessage(){return Pn(this,A)}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)?"":Bc(Pn(this,E))}catch(e){$a(!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(e){$a(!1,"response body is not valid JSON","UNSUPPORTED_OPERATION",{operation:"bodyJson",info:{response:this}})}}[Symbol.iterator](){const e=this.headers,t=Object.keys(e);let n=0;return{next:()=>{if(n<t.length){const r=t[n++];return{value:[r,e[r]],done:!1}}return{value:void 0,done:!0}}}}makeServerError(t,n){let r;r=t?`CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${t})`:`CLIENT ESCALATED SERVER ERROR (${t=`${this.statusCode} ${this.statusMessage}`})`;const s=new e(599,r,this.headers,this.body,Pn(this,k)||void 0);return Bn(s,S,{message:t,error:n}),s}throwThrottleError(e,t){null==t?t=-1:Ka(Number.isInteger(t)&&t>=0,"invalid stall timeout","stall",t);const n=new Error(e||"throttling requests");throw Ha(n,{stall:t,throttle:!0}),n}getHeader(e){return this.headers[e.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:e,error:t}=Pn(this,S);""===e&&(e=`server response ${this.statusCode} ${this.statusMessage}`);let n=null;this.request&&(n=this.request.url);let r=null;try{Pn(this,E)&&(r=Bc(Pn(this,E)))}catch(s){}$a(!1,e,"SERVER_ERROR",{request:this.request||"unknown request",response:this,error:t,info:{requestUrl:n,responseBody:r,responseStatus:`${this.statusCode} ${this.statusMessage}`}})}};_=new WeakMap,A=new WeakMap,v=new WeakMap,E=new WeakMap,k=new WeakMap,S=new WeakMap;let Jc=Qc;function Yc(){return(new Date).getTime()}function Zc(e){let t=e.toString(16);for(;t.length<2;)t="0"+t;return"0x"+t}function Xc(e,t,n){let r=0;for(let s=0;s<n;s++)r=256*r+e[t+s];return r}function el(e,t,n,r){const s=[];for(;n<t+1+r;){const i=tl(e,n);s.push(i.result),$a((n+=i.consumed)<=t+1+r,"child data too short","BUFFER_OVERRUN",{buffer:e,length:r,offset:t})}return{consumed:1+r,result:s}}function tl(e,t){$a(0!==e.length,"data too short","BUFFER_OVERRUN",{buffer:e,length:0,offset:1});const n=t=>{$a(t<=e.length,"data short segment too short","BUFFER_OVERRUN",{buffer:e,length:e.length,offset:t})};if(e[t]>=248){const r=e[t]-247;n(t+1+r);const s=Xc(e,t+1,r);return n(t+1+r+s),el(e,t,t+1+r,r+s)}if(e[t]>=192){const r=e[t]-192;return n(t+1+r),el(e,t,t+1,r)}if(e[t]>=184){const r=e[t]-183;n(t+1+r);const s=Xc(e,t+1,r);n(t+1+r+s);return{consumed:1+r+s,result:ic(e.slice(t+1+r,t+1+r+s))}}if(e[t]>=128){const r=e[t]-128;n(t+1+r);return{consumed:1+r,result:ic(e.slice(t+1,t+1+r))}}return{consumed:1,result:Zc(e[t])}}function nl(e){const t=ec(e,"data"),n=tl(t,0);return Ka(n.consumed===t.length,"unexpected junk after rlp payload","data",e),n.result}function rl(e){const t=[];for(;e;)t.unshift(255&e),e>>=8;return t}function sl(e){if(Array.isArray(e)){let t=[];if(e.forEach((function(e){t=t.concat(sl(e))})),t.length<=55)return t.unshift(192+t.length),t;const n=rl(t.length);return n.unshift(247+n.length),n.concat(t)}const t=Array.prototype.slice.call(ec(e,"object"));if(1===t.length&&t[0]<=127)return t;if(t.length<=55)return t.unshift(128+t.length),t;const n=rl(t.length);return n.unshift(183+n.length),n.concat(t)}const il="0123456789abcdef";function ol(e){let t="0x";for(const n of sl(e))t+=il[n>>4],t+=il[15&n];return t}function al(e){const t=ec(e,"randomBytes");t[6]=15&t[6]|64,t[8]=63&t[8]|128;const n=ic(t);return[n.substring(2,10),n.substring(10,14),n.substring(14,18),n.substring(18,22),n.substring(22,34)].join("-")}const cl=32,ll=new Uint8Array(cl),ul=["then"],hl={},dl=new WeakMap;function fl(e){return dl.get(e)}function pl(e,t){dl.set(e,t)}function gl(e,t){const n=new Error(`deferred error during ABI decoding triggered accessing ${e}`);throw n.error=t,n}function ml(e,t,n){return e.indexOf(null)>=0?t.map(((e,t)=>e instanceof yl?ml(fl(e),e,n):e)):e.reduce(((e,r,s)=>{let i=t.getValue(r);return r in e||(n&&i instanceof yl&&(i=ml(fl(i),i,n)),e[r]=i),e}),{})}T=new WeakMap;let yl=class e extends Array{constructor(...e){const t=e[0];let n=e[1],r=(e[2]||[]).slice(),s=!0;t!==hl&&(n=e,r=[],s=!1),super(n.length),Dn(this,T,void 0),n.forEach(((e,t)=>{this[t]=e}));const i=r.reduce(((e,t)=>("string"==typeof t&&e.set(t,(e.get(t)||0)+1),e)),new Map);if(pl(this,Object.freeze(n.map(((e,t)=>{const n=r[t];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:(e,t,n)=>{if("string"==typeof t){if(t.match(/^[0-9]+$/)){const n=Ac(t,"%index");if(n<0||n>=this.length)throw new RangeError("out of result range");const r=e[n];return r instanceof Error&&gl(`index ${n}`,r),r}if(ul.indexOf(t)>=0)return Reflect.get(e,t,n);const r=e[t];if(r instanceof Function)return function(...t){return r.apply(this===n?e:this,t)};if(!(t in e))return e.getValue.apply(this===n?e:this,[t])}return Reflect.get(e,t,n)}});return pl(o,fl(this)),o}toArray(t){const n=[];return this.forEach(((r,s)=>{r instanceof Error&&gl(`index ${s}`,r),t&&r instanceof e&&(r=r.toArray(t)),n.push(r)})),n}toObject(e){const t=fl(this);return t.reduce(((n,r,s)=>($a(null!=r,`value at index ${s} unnamed`,"UNSUPPORTED_OPERATION",{operation:"toObject()"}),ml(t,this,e))),{})}slice(t,n){null==t&&(t=0),t<0&&(t+=this.length)<0&&(t=0),null==n&&(n=this.length),n<0&&(n+=this.length)<0&&(n=0),n>this.length&&(n=this.length);const r=fl(this),s=[],i=[];for(let e=t;e<n;e++)s.push(this[e]),i.push(r[e]);return new e(hl,s,i)}filter(t,n){const r=fl(this),s=[],i=[];for(let e=0;e<this.length;e++){const o=this[e];o instanceof Error&&gl(`index ${e}`,o),t.call(n,o,e,this)&&(s.push(o),i.push(r[e]))}return new e(hl,s,i)}map(e,t){const n=[];for(let r=0;r<this.length;r++){const s=this[r];s instanceof Error&&gl(`index ${r}`,s),n.push(e.call(t,s,r,this))}return n}getValue(e){const t=fl(this).indexOf(e);if(-1===t)return;const n=this[t];return n instanceof Error&&gl(`property ${JSON.stringify(e)}`,n.error),n}static fromItems(t,n){return new e(hl,t,n)}};function wl(e){let t=Ec(e);return $a(t.length<=cl,"value out-of-bounds","BUFFER_OVERRUN",{buffer:t,length:cl,offset:t.length}),t.length!==cl&&(t=tc(oc([ll.slice(t.length%cl),t]))),t}class bl{constructor(e,t,n,r){xn(this,"name"),xn(this,"type"),xn(this,"localName"),xn(this,"dynamic"),Ha(this,{name:e,type:t,localName:n,dynamic:r},{name:"string",type:"string",localName:"string",dynamic:"boolean"})}_throwError(e,t){Ka(!1,e,this.localName,t)}}class _l{constructor(){Dn(this,C),Dn(this,R,void 0),Dn(this,I,void 0),Bn(this,R,[]),Bn(this,I,0)}get data(){return oc(Pn(this,R))}get length(){return Pn(this,I)}appendWriter(e){return Ln(this,C,O).call(this,tc(e.data))}writeBytes(e){let t=tc(e);const n=t.length%cl;return n&&(t=tc(oc([t,ll.slice(n)]))),Ln(this,C,O).call(this,t)}writeValue(e){return Ln(this,C,O).call(this,wl(e))}writeUpdatableValue(){const e=Pn(this,R).length;return Pn(this,R).push(ll),Bn(this,I,Pn(this,I)+cl),t=>{Pn(this,R)[e]=wl(t)}}}R=new WeakMap,I=new WeakMap,C=new WeakSet,O=function(e){return Pn(this,R).push(e),Bn(this,I,Pn(this,I)+e.length),e.length};x=new WeakMap,N=new WeakMap,P=new WeakMap,D=new WeakMap,B=new WeakMap,U=new WeakSet,L=function(e){var t;if(Pn(this,D))return Ln(t=Pn(this,D),U,L).call(t,e);Bn(this,P,Pn(this,P)+e),$a(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:tc(Pn(this,x)),offset:Pn(this,N),length:e,info:{bytesRead:Pn(this,P),dataLength:this.dataLength}})},M=new WeakSet,F=function(e,t,n){let r=Math.ceil(t/cl)*cl;return Pn(this,N)+r>Pn(this,x).length&&(this.allowLoose&&n&&Pn(this,N)+t<=Pn(this,x).length?r=t:$a(!1,"data out-of-bounds","BUFFER_OVERRUN",{buffer:tc(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 Al=class e{constructor(e,t,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),Ha(this,{allowLoose:!!t}),Bn(this,x,tc(e)),Bn(this,P,0),Bn(this,D,null),Bn(this,B,null!=n?n:1024),Bn(this,N,0)}get data(){return ic(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(t){const n=new e(Pn(this,x).slice(Pn(this,N)+t),this.allowLoose,Pn(this,B));return Bn(n,D,this),n}readBytes(e,t){let n=Ln(this,M,F).call(this,0,e,!!t);return Ln(this,U,L).call(this,e),Bn(this,N,Pn(this,N)+n.length),n.slice(0,e)}readValue(){return _c(this.readBytes(cl))}readIndex(){return Ac(_c(this.readBytes(cl)))}};function vl(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function El(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function kl(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");vl(e.outputLen),vl(e.blockLen)}function Sl(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Tl(e,t){El(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}const Rl="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,Il=e=>e instanceof Uint8Array,Cl=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),Ol=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),xl=(e,t)=>e<<32-t|e>>>t;
|
|
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 Nl=async()=>{};async function Pl(e,t,n){let r=Date.now();for(let s=0;s<e;s++){n(s);const e=Date.now()-r;e>=0&&e<t||(await Nl(),r+=e)}}function Dl(e){if("string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e)),!Il(e))throw new Error("expected Uint8Array, got "+typeof e);return e}class Bl{clone(){return this._cloneInto()}}const Ul={}.toString;function Ll(e,t){if(void 0!==t&&"[object Object]"!==Ul.call(t))throw new Error("Options should be object or undefined");return Object.assign(e,t)}function Ml(e){const t=t=>e().update(Dl(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Fl(e=32){if(Rl&&"function"==typeof Rl.getRandomValues)return Rl.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}class jl extends Bl{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,kl(e);const n=Dl(t);if(this.iHash=e.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?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(e){return Sl(this),this.iHash.update(e),this}digestInto(e){Sl(this),El(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:n,finished:r,destroyed:s,blockLen:i,outputLen:o}=this;return e.finished=r,e.destroyed=s,e.blockLen=i,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Gl=(e,t,n)=>new jl(e,t).update(n).digest();function Hl(e,t,n,r){const{c:s,dkLen:i,DK:o,PRF:a,PRFSalt:c}=function(e,t,n,r){kl(e);const s=Ll({dkLen:32,asyncTick:10},r),{c:i,dkLen:o,asyncTick:a}=s;if(vl(i),vl(o),vl(a),i<1)throw new Error("PBKDF2: iterations (c) should be >= 1");const c=Dl(t),l=Dl(n),u=new Uint8Array(o),h=Gl.create(e,c),d=h._cloneInto().update(l);return{c:i,dkLen:o,asyncTick:a,DK:u,PRF:h,PRFSalt:d}}(e,t,n,r);let l;const u=new Uint8Array(4),h=Ol(u),d=new Uint8Array(a.outputLen);for(let f=1,p=0;p<i;f++,p+=a.outputLen){const e=o.subarray(p,p+a.outputLen);h.setInt32(0,f,!1),(l=c._cloneInto(l)).update(u).digestInto(d),e.set(d.subarray(0,e.length));for(let t=1;t<s;t++){a._cloneInto(l).update(d).digestInto(d);for(let t=0;t<e.length;t++)e[t]^=d[t]}}return function(e,t,n,r,s){return e.destroy(),t.destroy(),r&&r.destroy(),s.fill(0),n}(a,c,o,l,d)}Gl.create=(e,t)=>new jl(e,t);class Vl extends Bl{constructor(e,t,n,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Ol(this.buffer)}update(e){Sl(this);const{view:t,buffer:n,blockLen:r}=this,s=(e=Dl(e)).length;for(let i=0;i<s;){const o=Math.min(r-this.pos,s-i);if(o!==r)n.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===r&&(this.process(t,0),this.pos=0);else{const t=Ol(e);for(;r<=s-i;i+=r)this.process(t,i)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){Sl(this),Tl(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:s}=this;let{pos:i}=this;t[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++)t[u]=0;!function(e,t,n,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,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;e.setUint32(t+c,o,r),e.setUint32(t+l,a,r)}(n,r-8,BigInt(8*this.length),s),this.process(n,0);const o=Ol(e),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:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:r,finished:s,destroyed:i,pos:o}=this;return e.length=r,e.pos=o,e.finished=s,e.destroyed=i,r%t&&e.buffer.set(n),e}}const ql=(e,t,n)=>e&t^e&n^t&n,Wl=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]),zl=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),$l=new Uint32Array(64);class Kl extends Vl{constructor(){super(64,32,8,!1),this.A=0|zl[0],this.B=0|zl[1],this.C=0|zl[2],this.D=0|zl[3],this.E=0|zl[4],this.F=0|zl[5],this.G=0|zl[6],this.H=0|zl[7]}get(){const{A:e,B:t,C:n,D:r,E:s,F:i,G:o,H:a}=this;return[e,t,n,r,s,i,o,a]}set(e,t,n,r,s,i,o,a){this.A=0|e,this.B=0|t,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(e,t){for(let h=0;h<16;h++,t+=4)$l[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){const e=$l[h-15],t=$l[h-2],n=xl(e,7)^xl(e,18)^e>>>3,r=xl(t,17)^xl(t,19)^t>>>10;$l[h]=r+$l[h-7]+n+$l[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 e=l+(xl(o,6)^xl(o,11)^xl(o,25))+((u=o)&a^~u&c)+Wl[h]+$l[h]|0,t=(xl(n,2)^xl(n,13)^xl(n,22))+ql(n,r,s)|0;l=c,c=a,a=o,o=i+e|0,i=s,s=r,r=n,n=e+t|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(){$l.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const Ql=Ml((()=>new Kl)),Jl=BigInt(2**32-1),Yl=BigInt(32);function Zl(e,t=!1){return t?{h:Number(e&Jl),l:Number(e>>Yl&Jl)}:{h:0|Number(e>>Yl&Jl),l:0|Number(e&Jl)}}function Xl(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let s=0;s<e.length;s++){const{h:i,l:o}=Zl(e[s],t);[n[s],r[s]]=[i,o]}return[n,r]}const eu=(e,t,n)=>e<<n|t>>>32-n,tu=(e,t,n)=>t<<n|e>>>32-n,nu=(e,t,n)=>t<<n-32|e>>>64-n,ru=(e,t,n)=>e<<n-32|t>>>64-n;const su={fromBig:Zl,split:Xl,toBig:(e,t)=>BigInt(e>>>0)<<Yl|BigInt(t>>>0),shrSH:(e,t,n)=>e>>>n,shrSL:(e,t,n)=>e<<32-n|t>>>n,rotrSH:(e,t,n)=>e>>>n|t<<32-n,rotrSL:(e,t,n)=>e<<32-n|t>>>n,rotrBH:(e,t,n)=>e<<64-n|t>>>n-32,rotrBL:(e,t,n)=>e>>>n-32|t<<64-n,rotr32H:(e,t)=>t,rotr32L:(e,t)=>e,rotlSH:eu,rotlSL:tu,rotlBH:nu,rotlBL:ru,add:function(e,t,n,r){const s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:0|s}},add3L:(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),add3H:(e,t,n,r)=>t+n+r+(e/2**32|0)|0,add4L:(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),add4H:(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,add5H:(e,t,n,r,s,i)=>t+n+r+s+i+(e/2**32|0)|0,add5L:(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0)},[iu,ou]=(()=>su.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((e=>BigInt(e)))))(),au=new Uint32Array(80),cu=new Uint32Array(80);class lu extends Vl{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:e,Al:t,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[e,t,n,r,s,i,o,a,c,l,u,h,d,f,p,g]}set(e,t,n,r,s,i,o,a,c,l,u,h,d,f,p,g){this.Ah=0|e,this.Al=0|t,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(e,t){for(let w=0;w<16;w++,t+=4)au[w]=e.getUint32(t),cu[w]=e.getUint32(t+=4);for(let w=16;w<80;w++){const e=0|au[w-15],t=0|cu[w-15],n=su.rotrSH(e,t,1)^su.rotrSH(e,t,8)^su.shrSH(e,t,7),r=su.rotrSL(e,t,1)^su.rotrSL(e,t,8)^su.shrSL(e,t,7),s=0|au[w-2],i=0|cu[w-2],o=su.rotrSH(s,i,19)^su.rotrBH(s,i,61)^su.shrSH(s,i,6),a=su.rotrSL(s,i,19)^su.rotrBL(s,i,61)^su.shrSL(s,i,6),c=su.add4L(r,a,cu[w-7],cu[w-16]),l=su.add4H(c,n,o,au[w-7],au[w-16]);au[w]=0|l,cu[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 e=su.rotrSH(u,h,14)^su.rotrSH(u,h,18)^su.rotrBH(u,h,41),t=su.rotrSL(u,h,14)^su.rotrSL(u,h,18)^su.rotrBL(u,h,41),b=u&d^~u&p,_=h&f^~h&g,A=su.add5L(y,t,_,ou[w],cu[w]),v=su.add5H(A,m,e,b,iu[w],au[w]),E=0|A,k=su.rotrSH(n,r,28)^su.rotrBH(n,r,34)^su.rotrBH(n,r,39),S=su.rotrSL(n,r,28)^su.rotrBL(n,r,34)^su.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}=su.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=su.add3L(E,S,R);n=su.add3H(I,v,k,T),r=0|I}({h:n,l:r}=su.add(0|this.Ah,0|this.Al,0|n,0|r)),({h:s,l:i}=su.add(0|this.Bh,0|this.Bl,0|s,0|i)),({h:o,l:a}=su.add(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l:l}=su.add(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:h}=su.add(0|this.Eh,0|this.El,0|u,0|h)),({h:d,l:f}=su.add(0|this.Fh,0|this.Fl,0|d,0|f)),({h:p,l:g}=su.add(0|this.Gh,0|this.Gl,0|p,0|g)),({h:m,l:y}=su.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(){au.fill(0),cu.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 uu=Ml((()=>new lu));const hu=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")}(),du=hu.crypto||hu.msCrypto;let fu=!1;const pu=function(e,t,n){return function(e,t){const n={sha256:Ql,sha512:uu}[e];return Ka(null!=n,"invalid hmac algorithm","algorithm",e),Gl.create(n,t)}(e,t).update(n).digest()};let gu=pu;function mu(e,t,n){const r=ec(t,"key"),s=ec(n,"data");return ic(gu(e,r,s))}mu._=pu,mu.lock=function(){fu=!0},mu.register=function(e){if(fu)throw new Error("computeHmac is locked");gu=e},Object.freeze(mu);const[yu,wu,bu]=[[],[],[]],_u=BigInt(0),Au=BigInt(1),vu=BigInt(2),Eu=BigInt(7),ku=BigInt(256),Su=BigInt(113);for(let uE=0,hE=Au,dE=1,fE=0;uE<24;uE++){[dE,fE]=[fE,(2*dE+3*fE)%5],yu.push(2*(5*fE+dE)),wu.push((uE+1)*(uE+2)/2%64);let e=_u;for(let t=0;t<7;t++)hE=(hE<<Au^(hE>>Eu)*Su)%ku,hE&vu&&(e^=Au<<(Au<<BigInt(t))-Au);bu.push(e)}const[Tu,Ru]=Xl(bu,!0),Iu=(e,t,n)=>n>32?nu(e,t,n):eu(e,t,n),Cu=(e,t,n)=>n>32?ru(e,t,n):tu(e,t,n);class Ou extends Bl{constructor(e,t,n,r=!1,s=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=r,this.rounds=s,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,vl(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Cl(this.state)}keccak(){!function(e,t=24){const n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let r=0;r<10;r++)n[r]=e[r]^e[r+10]^e[r+20]^e[r+30]^e[r+40];for(let r=0;r<10;r+=2){const t=(r+8)%10,s=(r+2)%10,i=n[s],o=n[s+1],a=Iu(i,o,1)^n[t],c=Cu(i,o,1)^n[t+1];for(let n=0;n<50;n+=10)e[r+n]^=a,e[r+n+1]^=c}let t=e[2],s=e[3];for(let n=0;n<24;n++){const r=wu[n],i=Iu(t,s,r),o=Cu(t,s,r),a=yu[n];t=e[a],s=e[a+1],e[a]=i,e[a+1]=o}for(let r=0;r<50;r+=10){for(let t=0;t<10;t++)n[t]=e[r+t];for(let t=0;t<10;t++)e[r+t]^=~n[(t+2)%10]&n[(t+4)%10]}e[0]^=Tu[r],e[1]^=Ru[r]}n.fill(0)}(this.state32,this.rounds),this.posOut=0,this.pos=0}update(e){Sl(this);const{blockLen:t,state:n}=this,r=(e=Dl(e)).length;for(let s=0;s<r;){const i=Math.min(t-this.pos,r-s);for(let t=0;t<i;t++)n[this.pos++]^=e[s++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:r}=this;e[n]^=t,128&t&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Sl(this,!1),El(e),this.finish();const t=this.state,{blockLen:n}=this;for(let r=0,s=e.length;r<s;){this.posOut>=n&&this.keccak();const i=Math.min(n-this.posOut,s-r);e.set(t.subarray(this.posOut,this.posOut+i),r),this.posOut+=i,r+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return vl(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Tl(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:r,rounds:s,enableXOF:i}=this;return e||(e=new Ou(t,n,r,i,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=n,e.outputLen=r,e.enableXOF=i,e.destroyed=this.destroyed,e}}const xu=((e,t,n)=>Ml((()=>new Ou(t,e,n))))(1,136,32);let Nu=!1;const Pu=function(e){return xu(e)};let Du=Pu;function Bu(e){const t=ec(e,"data");return ic(Du(t))}Bu._=Pu,Bu.lock=function(){Nu=!0},Bu.register=function(e){if(Nu)throw new TypeError("keccak256 is locked");Du=e},Object.freeze(Bu);const Uu=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Lu=Uint8Array.from({length:16},((e,t)=>t));let Mu=[Lu],Fu=[Lu.map((e=>(9*e+5)%16))];for(let uE=0;uE<4;uE++)for(let e of[Mu,Fu])e.push(e[uE].map((e=>Uu[e])));const ju=[[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((e=>new Uint8Array(e))),Gu=Mu.map(((e,t)=>e.map((e=>ju[t][e])))),Hu=Fu.map(((e,t)=>e.map((e=>ju[t][e])))),Vu=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),qu=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]),Wu=(e,t)=>e<<t|e>>>32-t;function zu(e,t,n,r){return 0===e?t^n^r:1===e?t&n|~t&r:2===e?(t|~n)^r:3===e?t&r|n&~r:t^(n|~r)}const $u=new Uint32Array(16);class Ku extends Vl{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:e,h1:t,h2:n,h3:r,h4:s}=this;return[e,t,n,r,s]}set(e,t,n,r,s){this.h0=0|e,this.h1=0|t,this.h2=0|n,this.h3=0|r,this.h4=0|s}process(e,t){for(let d=0;d<16;d++,t+=4)$u[d]=e.getUint32(t,!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 e=4-d,t=Vu[d],f=qu[d],p=Mu[d],g=Fu[d],m=Gu[d],y=Hu[d];for(let r=0;r<16;r++){const e=Wu(n+zu(d,s,o,c)+$u[p[r]]+t,m[r])+u|0;n=u,u=c,c=0|Wu(o,10),o=s,s=e}for(let n=0;n<16;n++){const t=Wu(r+zu(e,i,a,l)+$u[g[n]]+f,y[n])+h|0;r=h,h=l,l=0|Wu(a,10),a=i,i=t}}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(){$u.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}}const Qu=Ml((()=>new Ku));let Ju=!1;const Yu=function(e){return Qu(e)};let Zu=Yu;function Xu(e){const t=ec(e,"data");return ic(Zu(t))}Xu._=Yu,Xu.lock=function(){Ju=!0},Xu.register=function(e){if(Ju)throw new TypeError("ripemd160 is locked");Zu=e},Object.freeze(Xu);let eh=!1;const th=function(e,t,n,r,s){return function(e,t,n,r,s){const i={sha256:Ql,sha512:uu}[s];return Ka(null!=i,"invalid pbkdf2 algorithm","algorithm",s),Hl(i,e,t,{c:n,dkLen:r})}(e,t,n,r,s)};let nh=th;function rh(e,t,n,r,s){const i=ec(e,"password"),o=ec(t,"salt");return ic(nh(i,o,n,r,s))}rh._=th,rh.lock=function(){eh=!0},rh.register=function(e){if(eh)throw new Error("pbkdf2 is locked");nh=e},Object.freeze(rh);let sh=!1;const ih=function(e){return new Uint8Array(function(e){$a(null!=du,"platform does not support secure random numbers","UNSUPPORTED_OPERATION",{operation:"randomBytes"}),Ka(Number.isInteger(e)&&e>0&&e<=1024,"invalid length","length",e);const t=new Uint8Array(e);return du.getRandomValues(t),t}(e))};let oh=ih;function ah(e){return oh(e)}ah._=ih,ah.lock=function(){sh=!0},ah.register=function(e){if(sh)throw new Error("randomBytes is locked");oh=e},Object.freeze(ah);const ch=(e,t)=>e<<t|e>>>32-t;function lh(e,t,n,r,s,i){let o=e[t++]^n[r++],a=e[t++]^n[r++],c=e[t++]^n[r++],l=e[t++]^n[r++],u=e[t++]^n[r++],h=e[t++]^n[r++],d=e[t++]^n[r++],f=e[t++]^n[r++],p=e[t++]^n[r++],g=e[t++]^n[r++],m=e[t++]^n[r++],y=e[t++]^n[r++],w=e[t++]^n[r++],b=e[t++]^n[r++],_=e[t++]^n[r++],A=e[t++]^n[r++],v=o,E=a,k=c,S=l,T=u,R=h,I=d,C=f,O=p,x=g,N=m,P=y,D=w,B=b,U=_,L=A;for(let M=0;M<8;M+=2)T^=ch(v+D|0,7),O^=ch(T+v|0,9),D^=ch(O+T|0,13),v^=ch(D+O|0,18),x^=ch(R+E|0,7),B^=ch(x+R|0,9),E^=ch(B+x|0,13),R^=ch(E+B|0,18),U^=ch(N+I|0,7),k^=ch(U+N|0,9),I^=ch(k+U|0,13),N^=ch(I+k|0,18),S^=ch(L+P|0,7),C^=ch(S+L|0,9),P^=ch(C+S|0,13),L^=ch(P+C|0,18),E^=ch(v+S|0,7),k^=ch(E+v|0,9),S^=ch(k+E|0,13),v^=ch(S+k|0,18),I^=ch(R+T|0,7),C^=ch(I+R|0,9),T^=ch(C+I|0,13),R^=ch(T+C|0,18),P^=ch(N+x|0,7),O^=ch(P+N|0,9),x^=ch(O+P|0,13),N^=ch(x+O|0,18),D^=ch(L+U|0,7),B^=ch(D+L|0,9),U^=ch(B+D|0,13),L^=ch(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+C|0,s[i++]=p+O|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++]=_+U|0,s[i++]=A+L|0}function uh(e,t,n,r,s){let i=r+0,o=r+16*s;for(let a=0;a<16;a++)n[o+a]=e[t+16*(2*s-1)+a];for(let a=0;a<s;a++,i+=16,t+=16)lh(n,o,e,t,n,i),a>0&&(o+=16),lh(n,i,e,t+=16,n,o)}function hh(e,t,n){const r=Ll({dkLen:32,asyncTick:10,maxmem:1073742848},n),{N:s,r:i,p:o,dkLen:a,asyncTick:c,maxmem:l,onProgress:u}=r;if(vl(s),vl(i),vl(o),vl(a),vl(c),vl(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=Hl(Ql,e,t,{c:1,dkLen:h*o}),g=Cl(p),m=Cl(new Uint8Array(h*s)),y=Cl(new Uint8Array(h));let w=()=>{};if(u){const e=2*s*o,t=Math.max(Math.floor(e/1e4),1);let n=0;w=()=>{n++,!u||n%t&&n!==e||u(n/e)}}return{N:s,r:i,p:o,dkLen:a,blockSize32:d,V:m,B32:g,B:p,tmp:y,blockMixCb:w,asyncTick:c}}function dh(e,t,n,r,s){const i=Hl(Ql,e,n,{c:1,dkLen:t});return n.fill(0),r.fill(0),s.fill(0),i}let fh=!1,ph=!1;const gh=async function(e,t,n,r,s,i,o){return await async function(e,t,n){const{N:r,r:s,p:i,dkLen:o,blockSize32:a,V:c,B32:l,B:u,tmp:h,blockMixCb:d,asyncTick:f}=hh(e,t,n);for(let p=0;p<i;p++){const e=a*p;for(let n=0;n<a;n++)c[n]=l[e+n];let t=0;await Pl(r-1,f,(()=>{uh(c,t,c,t+=a,s),d()})),uh(c,(r-1)*a,l,e,s),d(),await Pl(r,f,(()=>{const t=l[e+a-16]%r;for(let n=0;n<a;n++)h[n]=l[e+n]^c[t*a+n];uh(h,0,l,e,s),d()}))}return dh(e,o,u,c,h)}(e,t,{N:n,r:r,p:s,dkLen:i,onProgress:o})},mh=function(e,t,n,r,s,i){return function(e,t,n){const{N:r,r:s,p:i,dkLen:o,blockSize32:a,V:c,B32:l,B:u,tmp:h,blockMixCb:d}=hh(e,t,n);for(let f=0;f<i;f++){const e=a*f;for(let t=0;t<a;t++)c[t]=l[e+t];for(let t=0,n=0;t<r-1;t++)uh(c,n,c,n+=a,s),d();uh(c,(r-1)*a,l,e,s),d();for(let t=0;t<r;t++){const t=l[e+a-16]%r;for(let n=0;n<a;n++)h[n]=l[e+n]^c[t*a+n];uh(h,0,l,e,s),d()}}return dh(e,o,u,c,h)}(e,t,{N:n,r:r,p:s,dkLen:i})};let yh=gh,wh=mh;async function bh(e,t,n,r,s,i,o){const a=ec(e,"passwd"),c=ec(t,"salt");return ic(await yh(a,c,n,r,s,i,o))}function _h(e,t,n,r,s,i){const o=ec(e,"passwd"),a=ec(t,"salt");return ic(wh(o,a,n,r,s,i))}bh._=gh,bh.lock=function(){ph=!0},bh.register=function(e){if(ph)throw new Error("scrypt is locked");yh=e},Object.freeze(bh),_h._=mh,_h.lock=function(){fh=!0},_h.register=function(e){if(fh)throw new Error("scryptSync is locked");wh=e},Object.freeze(_h);const Ah=function(e){return function(e){switch(e){case"sha256":return Ql.create();case"sha512":return uu.create()}Ka(!1,"invalid hashing algorithm name","algorithm",e)}("sha256").update(e).digest()};let vh=Ah,Eh=!1;function kh(e){const t=ec(e,"data");return ic(vh(t))}kh._=Ah,kh.lock=function(){Eh=!0},kh.register=function(e){if(Eh)throw new Error("sha256 is locked");vh=e},Object.freeze(kh),Object.freeze(kh);
|
|
3
3
|
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
4
|
-
const Sh=BigInt(0),Th=BigInt(1),Rh=BigInt(2),Ih=e=>e instanceof Uint8Array,Ch=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Oh(e){if(!Ih(e))throw new Error("Uint8Array expected");let t="";for(let n=0;n<e.length;n++)t+=Ch[e[n]];return t}function xh(e){const t=e.toString(16);return 1&t.length?`0${t}`:t}function Nh(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return BigInt(""===e?"0":`0x${e}`)}function Ph(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(t/2);for(let r=0;r<n.length;r++){const t=2*r,s=e.slice(t,t+2),i=Number.parseInt(s,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[r]=i}return n}function Dh(e){return Nh(Oh(e))}function Bh(e){if(!Ih(e))throw new Error("Uint8Array expected");return Nh(Oh(Uint8Array.from(e).reverse()))}function Uh(e,t){return Ph(e.toString(16).padStart(2*t,"0"))}function Lh(e,t){return Uh(e,t).reverse()}function Mh(e,t,n){let r;if("string"==typeof t)try{r=Ph(t)}catch(i){throw new Error(`${e} must be valid hex string, got "${t}". Cause: ${i}`)}else{if(!Ih(t))throw new Error(`${e} must be hex string or Uint8Array`);r=Uint8Array.from(t)}const s=r.length;if("number"==typeof n&&s!==n)throw new Error(`${e} expected ${n} bytes, got ${s}`);return r}function Fh(...e){const t=new Uint8Array(e.reduce(((e,t)=>e+t.length),0));let n=0;return e.forEach((e=>{if(!Ih(e))throw new Error("Uint8Array expected");t.set(e,n),n+=e.length})),t}const jh=e=>(Rh<<BigInt(e-1))-Th,Gh=e=>new Uint8Array(e),Hh=e=>Uint8Array.from(e);function Vh(e,t,n){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof n)throw new Error("hmacFn must be a function");let r=Gh(e),s=Gh(e),i=0;const o=()=>{r.fill(1),s.fill(0),i=0},a=(...e)=>n(s,r,...e),c=(e=Gh())=>{s=a(Hh([0]),e),r=a(),0!==e.length&&(s=a(Hh([1]),e),r=a())},l=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const n=[];for(;e<t;){r=a();const t=r.slice();n.push(t),e+=r.length}return Fh(...n)};return(e,t)=>{let n;for(o(),c(e);!(n=t(l()));)c();return o(),n}}const qh={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||e instanceof Uint8Array,isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function Wh(e,t,n={}){const r=(t,n,r)=>{const s=qh[n];if("function"!=typeof s)throw new Error(`Invalid validator "${n}", expected function`);const i=e[t];if(!(r&&void 0===i||s(i,e)))throw new Error(`Invalid param ${String(t)}=${i} (${typeof i}), expected ${n}`)};for(const[s,i]of Object.entries(t))r(s,i,!1);for(const[s,i]of Object.entries(n))r(s,i,!0);return e}const zh=Object.freeze(Object.defineProperty({__proto__:null,bitGet:function(e,t){return e>>BigInt(t)&Th},bitLen:function(e){let t;for(t=0;e>Sh;e>>=Th,t+=1);return t},bitMask:jh,bitSet:(e,t,n)=>e|(n?Th:Sh)<<BigInt(t),bytesToHex:Oh,bytesToNumberBE:Dh,bytesToNumberLE:Bh,concatBytes:Fh,createHmacDrbg:Vh,ensureBytes:Mh,equalBytes:function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},hexToBytes:Ph,hexToNumber:Nh,numberToBytesBE:Uh,numberToBytesLE:Lh,numberToHexUnpadded:xh,numberToVarBytesBE:function(e){return Ph(xh(e))},utf8ToBytes:function(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))},validateObject:Wh},Symbol.toStringTag,{value:"Module"}))
|
|
5
|
-
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ed(e,t){const n=e%t;return n
|
|
4
|
+
const Sh=BigInt(0),Th=BigInt(1),Rh=BigInt(2),Ih=e=>e instanceof Uint8Array,Ch=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Oh(e){if(!Ih(e))throw new Error("Uint8Array expected");let t="";for(let n=0;n<e.length;n++)t+=Ch[e[n]];return t}function xh(e){const t=e.toString(16);return 1&t.length?`0${t}`:t}function Nh(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return BigInt(""===e?"0":`0x${e}`)}function Ph(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(t/2);for(let r=0;r<n.length;r++){const t=2*r,s=e.slice(t,t+2),i=Number.parseInt(s,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[r]=i}return n}function Dh(e){return Nh(Oh(e))}function Bh(e){if(!Ih(e))throw new Error("Uint8Array expected");return Nh(Oh(Uint8Array.from(e).reverse()))}function Uh(e,t){return Ph(e.toString(16).padStart(2*t,"0"))}function Lh(e,t){return Uh(e,t).reverse()}function Mh(e,t,n){let r;if("string"==typeof t)try{r=Ph(t)}catch(i){throw new Error(`${e} must be valid hex string, got "${t}". Cause: ${i}`)}else{if(!Ih(t))throw new Error(`${e} must be hex string or Uint8Array`);r=Uint8Array.from(t)}const s=r.length;if("number"==typeof n&&s!==n)throw new Error(`${e} expected ${n} bytes, got ${s}`);return r}function Fh(...e){const t=new Uint8Array(e.reduce(((e,t)=>e+t.length),0));let n=0;return e.forEach((e=>{if(!Ih(e))throw new Error("Uint8Array expected");t.set(e,n),n+=e.length})),t}const jh=e=>(Rh<<BigInt(e-1))-Th,Gh=e=>new Uint8Array(e),Hh=e=>Uint8Array.from(e);function Vh(e,t,n){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof n)throw new Error("hmacFn must be a function");let r=Gh(e),s=Gh(e),i=0;const o=()=>{r.fill(1),s.fill(0),i=0},a=(...e)=>n(s,r,...e),c=(e=Gh())=>{s=a(Hh([0]),e),r=a(),0!==e.length&&(s=a(Hh([1]),e),r=a())},l=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const n=[];for(;e<t;){r=a();const t=r.slice();n.push(t),e+=r.length}return Fh(...n)};return(e,t)=>{let n;for(o(),c(e);!(n=t(l()));)c();return o(),n}}const qh={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||e instanceof Uint8Array,isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function Wh(e,t,n={}){const r=(t,n,r)=>{const s=qh[n];if("function"!=typeof s)throw new Error(`Invalid validator "${n}", expected function`);const i=e[t];if(!(r&&void 0===i||s(i,e)))throw new Error(`Invalid param ${String(t)}=${i} (${typeof i}), expected ${n}`)};for(const[s,i]of Object.entries(t))r(s,i,!1);for(const[s,i]of Object.entries(n))r(s,i,!0);return e}const zh=Object.freeze(Object.defineProperty({__proto__:null,bitGet:function(e,t){return e>>BigInt(t)&Th},bitLen:function(e){let t;for(t=0;e>Sh;e>>=Th,t+=1);return t},bitMask:jh,bitSet:(e,t,n)=>e|(n?Th:Sh)<<BigInt(t),bytesToHex:Oh,bytesToNumberBE:Dh,bytesToNumberLE:Bh,concatBytes:Fh,createHmacDrbg:Vh,ensureBytes:Mh,equalBytes:function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},hexToBytes:Ph,hexToNumber:Nh,numberToBytesBE:Uh,numberToBytesLE:Lh,numberToHexUnpadded:xh,numberToVarBytesBE:function(e){return Ph(xh(e))},utf8ToBytes:function(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))},validateObject:Wh},Symbol.toStringTag,{value:"Module"})),$h=BigInt(0),Kh=BigInt(1),Qh=BigInt(2),Jh=BigInt(3),Yh=BigInt(4),Zh=BigInt(5),Xh=BigInt(8);
|
|
5
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ed(e,t){const n=e%t;return n>=$h?n:t+n}function td(e,t,n){if(n<=$h||t<$h)throw new Error("Expected power/modulo > 0");if(n===Kh)return $h;let r=Kh;for(;t>$h;)t&Kh&&(r=r*e%n),e=e*e%n,t>>=Kh;return r}function nd(e,t,n){let r=e;for(;t-- >$h;)r*=r,r%=n;return r}function rd(e,t){if(e===$h||t<=$h)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let n=ed(e,t),r=t,s=$h,i=Kh;for(;n!==$h;){const e=r%n,t=s-i*(r/n);r=n,n=e,s=i,i=t}if(r!==Kh)throw new Error("invert: does not exist");return ed(s,t)}function sd(e){if(e%Yh===Jh){const t=(e+Kh)/Yh;return function(e,n){const r=e.pow(n,t);if(!e.eql(e.sqr(r),n))throw new Error("Cannot find square root");return r}}if(e%Xh===Zh){const t=(e-Zh)/Xh;return function(e,n){const r=e.mul(n,Qh),s=e.pow(r,t),i=e.mul(n,s),o=e.mul(e.mul(i,Qh),s),a=e.mul(i,e.sub(o,e.ONE));if(!e.eql(e.sqr(a),n))throw new Error("Cannot find square root");return a}}return function(e){const t=(e-Kh)/Qh;let n,r,s;for(n=e-Kh,r=0;n%Qh===$h;n/=Qh,r++);for(s=Qh;s<e&&td(s,t,e)!==e-Kh;s++);if(1===r){const t=(e+Kh)/Yh;return function(e,n){const r=e.pow(n,t);if(!e.eql(e.sqr(r),n))throw new Error("Cannot find square root");return r}}const i=(n+Kh)/Qh;return function(e,o){if(e.pow(o,t)===e.neg(e.ONE))throw new Error("Cannot find square root");let a=r,c=e.pow(e.mul(e.ONE,s),n),l=e.pow(o,i),u=e.pow(o,n);for(;!e.eql(u,e.ONE);){if(e.eql(u,e.ZERO))return e.ZERO;let t=1;for(let r=e.sqr(u);t<a&&!e.eql(r,e.ONE);t++)r=e.sqr(r);const n=e.pow(c,Kh<<BigInt(a-t-1));c=e.sqr(n),l=e.mul(l,n),u=e.mul(u,c),a=t}return l}}(e)}BigInt(9),BigInt(16);const id=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function od(e,t){const n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function ad(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function cd(e){const t=ad(e);return t+Math.ceil(t/2)}
|
|
6
6
|
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
7
7
|
const ld=BigInt(0),ud=BigInt(1);function hd(e){return Wh(e.Fp,id.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"})),Wh(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...od(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}
|
|
8
|
-
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const{bytesToNumberBE:dd,hexToBytes:fd}=zh,pd={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(e){const{Err:t}=pd;if(e.length<2||2!==e[0])throw new t("Invalid signature integer tag");const n=e[1],r=e.subarray(2,n+2);if(!n||r.length!==n)throw new t("Invalid signature integer: wrong length");if(128&r[0])throw new t("Invalid signature integer: negative");if(0===r[0]&&!(128&r[1]))throw new t("Invalid signature integer: unnecessary leading zero");return{d:dd(r),l:e.subarray(n+2)}},toSig(e){const{Err:t}=pd,n="string"==typeof e?fd(e):e;if(!(n instanceof Uint8Array))throw new Error("ui8a expected");let r=n.length;if(r<2||48!=n[0])throw new t("Invalid signature tag");if(n[1]!==r-2)throw new t("Invalid signature: incorrect length");const{d:s,l:i}=pd._parseInt(n.subarray(2)),{d:o,l:a}=pd._parseInt(i);if(a.length)throw new t("Invalid signature: left bytes after parsing");return{r:s,s:o}},hexFromSig(e){const t=e=>8&Number.parseInt(e[0],16)?"00"+e:e,n=e=>{const t=e.toString(16);return 1&t.length?`0${t}`:t},r=t(n(e.s)),s=t(n(e.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}`}},gd=BigInt(0),md=BigInt(1);BigInt(2);const yd=BigInt(3);function wd(e){const t=function(e){const t=hd(e);Wh(t,{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}=t;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({...t})}(e),{Fp:n}=t,r=t.toBytes||((e,t,r)=>{const s=t.toAffine();return Fh(Uint8Array.from([4]),n.toBytes(s.x),n.toBytes(s.y))}),s=t.fromBytes||(e=>{const t=e.subarray(1);return{x:n.fromBytes(t.subarray(0,n.BYTES)),y:n.fromBytes(t.subarray(n.BYTES,2*n.BYTES))}});function i(e){const{a:r,b:s}=t,i=n.sqr(e),o=n.mul(i,e);return n.add(n.add(o,n.mul(e,r)),s)}if(!n.eql(n.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function o(e){return"bigint"==typeof e&&gd<e&&e<t.n}function a(e){if(!o(e))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(e){const{allowedPrivateKeyLengths:n,nByteLength:r,wrapPrivateKey:s,n:i}=t;if(n&&"bigint"!=typeof e){if(e instanceof Uint8Array&&(e=Oh(e)),"string"!=typeof e||!n.includes(e.length))throw new Error("Invalid key");e=e.padStart(2*r,"0")}let o;try{o="bigint"==typeof e?e:Dh(Mh("private key",e,r))}catch(c){throw new Error(`private key must be ${r} bytes, hex or bigint, not ${typeof e}`)}return s&&(o=ed(o,i)),a(o),o}const l=new Map;function u(e){if(!(e instanceof h))throw new Error("ProjectivePoint expected")}class h{constructor(e,t,r){if(this.px=e,this.py=t,this.pz=r,null==e||!n.isValid(e))throw new Error("x required");if(null==t||!n.isValid(t))throw new Error("y required");if(null==r||!n.isValid(r))throw new Error("z required")}static fromAffine(e){const{x:t,y:r}=e||{};if(!e||!n.isValid(t)||!n.isValid(r))throw new Error("invalid affine point");if(e instanceof h)throw new Error("projective point not allowed");const s=e=>n.eql(e,n.ZERO);return s(t)&&s(r)?h.ZERO:new h(t,r,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){const t=n.invertBatch(e.map((e=>e.pz)));return e.map(((e,n)=>e.toAffine(t[n]))).map(h.fromAffine)}static fromHex(e){const t=h.fromAffine(s(Mh("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return h.BASE.multiply(c(e))}_setWindowSize(e){this._WINDOW_SIZE=e,l.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint&&!n.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:e,y:r}=this.toAffine();if(!n.isValid(e)||!n.isValid(r))throw new Error("bad point: x or y not FE");const s=n.sqr(r),o=i(e);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:e}=this.toAffine();if(n.isOdd)return!n.isOdd(e);throw new Error("Field doesn't support isOdd")}equals(e){u(e);const{px:t,py:r,pz:s}=this,{px:i,py:o,pz:a}=e,c=n.eql(n.mul(t,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:e,b:r}=t,s=n.mul(r,yd),{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(e,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(e,p),g=n.sub(d,p),g=n.mul(e,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(e){u(e);const{px:r,py:s,pz:i}=this,{px:o,py:a,pz:c}=e;let l=n.ZERO,d=n.ZERO,f=n.ZERO;const p=t.a,g=n.mul(t.b,yd);let m=n.mul(r,o),y=n.mul(s,a),w=n.mul(i,c),b=n.add(r,s),_=n.add(o,a);b=n.mul(b,_),_=n.add(m,y),b=n.sub(b,_),_=n.add(r,i);let A=n.add(o,c);return _=n.mul(_,A),A=n.add(m,w),_=n.sub(_,A),A=n.add(s,i),l=n.add(a,c),A=n.mul(A,l),l=n.add(y,w),A=n.sub(A,l),f=n.mul(p,_),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),_=n.mul(g,_),y=n.add(y,w),w=n.sub(m,w),w=n.mul(p,w),_=n.add(_,w),m=n.mul(y,_),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(A,f),f=n.add(f,m),new h(l,d,f)}subtract(e){return this.add(e.negate())}is0(){return this.equals(h.ZERO)}wNAF(e){return f.wNAFCached(this,l,e,(e=>{const t=n.invertBatch(e.map((e=>e.pz)));return e.map(((e,n)=>e.toAffine(t[n]))).map(h.fromAffine)}))}multiplyUnsafe(e){const r=h.ZERO;if(e===gd)return r;if(a(e),e===md)return this;const{endo:s}=t;if(!s)return f.unsafeLadder(this,e);let{k1neg:i,k1:o,k2neg:c,k2:l}=s.splitScalar(e),u=r,d=r,p=this;for(;o>gd||l>gd;)o&md&&(u=u.add(p)),l&md&&(d=d.add(p)),p=p.double(),o>>=md,l>>=md;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(e){a(e);let r,s,i=e;const{endo:o}=t;if(o){const{k1neg:e,k1:t,k2neg:a,k2:c}=o.splitScalar(i);let{p:l,f:u}=this.wNAF(t),{p:d,f:p}=this.wNAF(c);l=f.constTimeNegate(e,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:e,f:t}=this.wNAF(i);r=e,s=t}return h.normalizeZ([r,s])[0]}multiplyAndAddUnsafe(e,t,n){const r=h.BASE,s=(e,t)=>t!==gd&&t!==md&&e.equals(r)?e.multiply(t):e.multiplyUnsafe(t),i=s(this,t).add(s(e,n));return i.is0()?void 0:i}toAffine(e){const{px:t,py:r,pz:s}=this,i=this.is0();null==e&&(e=i?n.ONE:n.inv(s));const o=n.mul(t,e),a=n.mul(r,e),c=n.mul(s,e);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:e,isTorsionFree:n}=t;if(e===md)return!0;if(n)return n(h,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:e,clearCofactor:n}=t;return e===md?this:n?n(h,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return this.assertValidity(),r(h,this,e)}toHex(e=!0){return Oh(this.toRawBytes(e))}}h.BASE=new h(t.Gx,t.Gy,n.ONE),h.ZERO=new h(n.ZERO,n.ONE,n.ZERO);const d=t.nBitLength,f=function(e,t){const n=(e,t)=>{const n=t.negate();return e?n:t},r=e=>({windows:Math.ceil(t/e)+1,windowSize:2**(e-1)});return{constTimeNegate:n,unsafeLadder(t,n){let r=e.ZERO,s=t;for(;n>ld;)n&ud&&(r=r.add(s)),s=s.double(),n>>=ud;return r},precomputeWindow(e,t){const{windows:n,windowSize:s}=r(t),i=[];let o=e,a=o;for(let r=0;r<n;r++){a=o,i.push(a);for(let e=1;e<s;e++)a=a.add(o),i.push(a);o=a.double()}return i},wNAF(t,s,i){const{windows:o,windowSize:a}=r(t);let c=e.ZERO,l=e.BASE;const u=BigInt(2**t-1),h=2**t,d=BigInt(t);for(let e=0;e<o;e++){const t=e*a;let r=Number(i&u);i>>=d,r>a&&(r-=h,i+=ud);const o=t,f=t+Math.abs(r)-1,p=e%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(e,t,n,r){const s=e._WINDOW_SIZE||1;let i=t.get(e);return i||(i=this.precomputeWindow(e,s),1!==s&&t.set(e,r(i))),this.wNAF(s,i,n)}}}(h,t.endo?Math.ceil(d/2):d);return{CURVE:t,ProjectivePoint:h,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:o}}function bd(e){const t=function(e){const t=hd(e);return Wh(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}(e),{Fp:n,n:r}=t,s=n.BYTES+1,i=2*n.BYTES+1;function o(e){return ed(e,r)}function a(e){return rd(e,r)}const{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:h}=wd({...t,toBytes(e,t,r){const s=t.toAffine(),i=n.toBytes(s.x),o=Fh;return r?o(Uint8Array.from([t.hasEvenY()?2:3]),i):o(Uint8Array.from([4]),i,n.toBytes(s.y))},fromBytes(e){const t=e.length,r=e[0],o=e.subarray(1);if(t!==s||2!==r&&3!==r){if(t===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 ${t} was invalid. Expected ${s} compressed bytes or ${i} uncompressed bytes`)}{const e=Dh(o);if(!(gd<(a=e)&&a<n.ORDER))throw new Error("Point is not on curve");const t=u(e);let s=n.sqrt(t);return!(1&~r)!==((s&md)===md)&&(s=n.neg(s)),{x:e,y:s}}var a}}),d=e=>Oh(Uh(e,t.nByteLength));function f(e){return e>r>>md}const p=(e,t,n)=>Dh(e.slice(t,n));class g{constructor(e,t,n){this.r=e,this.s=t,this.recovery=n,this.assertValidity()}static fromCompact(e){const n=t.nByteLength;return e=Mh("compactSignature",e,2*n),new g(p(e,0,n),p(e,n,2*n))}static fromDER(e){const{r:t,s:n}=pd.toSig(Mh("DER",e));return new g(t,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(e){return new g(this.r,this.s,e)}recoverPublicKey(e){const{r:r,s:s,recovery:i}=this,l=b(Mh("msgHash",e));if(null==i||![0,1,2,3].includes(i))throw new Error("recovery id invalid");const u=2===i||3===i?r+t.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 Ph(this.toDERHex())}toDERHex(){return pd.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Ph(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}const m={isValidPrivateKey(e){try{return l(e),!0}catch(t){return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const e=cd(t.n);return function(e,t,n=!1){const r=e.length,s=ad(t),i=cd(t);if(r<16||r<i||r>1024)throw new Error(`expected ${i}-1024 bytes of input, got ${r}`);const o=ed(n?Dh(e):Bh(e),t-$h)+$h;return n?Lh(o,s):Uh(o,s)}(t.randomBytes(e),t.n)},precompute:(e=8,t=c.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)};function y(e){const t=e instanceof Uint8Array,n="string"==typeof e,r=(t||n)&&e.length;return t?r===s||r===i:n?r===2*s||r===2*i:e instanceof c}const w=t.bits2int||function(e){const n=Dh(e),r=8*e.length-t.nBitLength;return r>0?n>>BigInt(r):n},b=t.bits2int_modN||function(e){return o(w(e))},_=jh(t.nBitLength);function A(e){if("bigint"!=typeof e)throw new Error("bigint expected");if(!(gd<=e&&e<_))throw new Error(`bigint expected < 2^${t.nBitLength}`);return Uh(e,t.nByteLength)}function v(e,r,s=E){if(["recovered","canonical"].some((e=>e in s)))throw new Error("sign() legacy options not supported");const{hash:i,randomBytes:u}=t;let{lowS:d,prehash:p,extraEntropy:m}=s;null==d&&(d=!0),e=Mh("msgHash",e),p&&(e=Mh("prehashed msgHash",i(e)));const y=b(e),_=l(r),v=[A(_),A(y)];if(null!=m){const e=!0===m?u(n.BYTES):m;v.push(Mh("extraEntropy",e))}const k=Fh(...v),S=y;return{seed:k,k2sig:function(e){const t=w(e);if(!h(t))return;const n=a(t),r=c.BASE.multiply(t).toAffine(),s=o(r.x);if(s===gd)return;const i=o(n*o(S+s*_));if(i===gd)return;let l=(r.x===s?0:2)|Number(r.y&md),u=i;return d&&f(i)&&(u=function(e){return f(e)?o(-e):e}(i),l^=1),new g(s,u,l)}}}const E={lowS:t.lowS,prehash:!1},k={lowS:t.lowS,prehash:!1};return c.BASE._setWindowSize(8),{CURVE:t,getPublicKey:function(e,t=!0){return c.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t,n=!0){if(y(e))throw new Error("first arg must be private key");if(!y(t))throw new Error("second arg must be public key");return c.fromHex(t).multiply(l(e)).toRawBytes(n)},sign:function(e,n,r=E){const{seed:s,k2sig:i}=v(e,n,r),o=t;return Vh(o.hash.outputLen,o.nByteLength,o.hmac)(s,i)},verify:function(e,n,r,s=k){var i;const l=e;if(n=Mh("msgHash",n),r=Mh("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 pd.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:e,s:t}=l;d=new g(e,t)}}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=t.hash(n));const{r:p,s:m}=d,y=b(n),w=a(m),_=o(y*w),A=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}}
|
|
8
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const{bytesToNumberBE:dd,hexToBytes:fd}=zh,pd={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(e){const{Err:t}=pd;if(e.length<2||2!==e[0])throw new t("Invalid signature integer tag");const n=e[1],r=e.subarray(2,n+2);if(!n||r.length!==n)throw new t("Invalid signature integer: wrong length");if(128&r[0])throw new t("Invalid signature integer: negative");if(0===r[0]&&!(128&r[1]))throw new t("Invalid signature integer: unnecessary leading zero");return{d:dd(r),l:e.subarray(n+2)}},toSig(e){const{Err:t}=pd,n="string"==typeof e?fd(e):e;if(!(n instanceof Uint8Array))throw new Error("ui8a expected");let r=n.length;if(r<2||48!=n[0])throw new t("Invalid signature tag");if(n[1]!==r-2)throw new t("Invalid signature: incorrect length");const{d:s,l:i}=pd._parseInt(n.subarray(2)),{d:o,l:a}=pd._parseInt(i);if(a.length)throw new t("Invalid signature: left bytes after parsing");return{r:s,s:o}},hexFromSig(e){const t=e=>8&Number.parseInt(e[0],16)?"00"+e:e,n=e=>{const t=e.toString(16);return 1&t.length?`0${t}`:t},r=t(n(e.s)),s=t(n(e.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}`}},gd=BigInt(0),md=BigInt(1);BigInt(2);const yd=BigInt(3);function wd(e){const t=function(e){const t=hd(e);Wh(t,{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}=t;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({...t})}(e),{Fp:n}=t,r=t.toBytes||((e,t,r)=>{const s=t.toAffine();return Fh(Uint8Array.from([4]),n.toBytes(s.x),n.toBytes(s.y))}),s=t.fromBytes||(e=>{const t=e.subarray(1);return{x:n.fromBytes(t.subarray(0,n.BYTES)),y:n.fromBytes(t.subarray(n.BYTES,2*n.BYTES))}});function i(e){const{a:r,b:s}=t,i=n.sqr(e),o=n.mul(i,e);return n.add(n.add(o,n.mul(e,r)),s)}if(!n.eql(n.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function o(e){return"bigint"==typeof e&&gd<e&&e<t.n}function a(e){if(!o(e))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(e){const{allowedPrivateKeyLengths:n,nByteLength:r,wrapPrivateKey:s,n:i}=t;if(n&&"bigint"!=typeof e){if(e instanceof Uint8Array&&(e=Oh(e)),"string"!=typeof e||!n.includes(e.length))throw new Error("Invalid key");e=e.padStart(2*r,"0")}let o;try{o="bigint"==typeof e?e:Dh(Mh("private key",e,r))}catch(c){throw new Error(`private key must be ${r} bytes, hex or bigint, not ${typeof e}`)}return s&&(o=ed(o,i)),a(o),o}const l=new Map;function u(e){if(!(e instanceof h))throw new Error("ProjectivePoint expected")}class h{constructor(e,t,r){if(this.px=e,this.py=t,this.pz=r,null==e||!n.isValid(e))throw new Error("x required");if(null==t||!n.isValid(t))throw new Error("y required");if(null==r||!n.isValid(r))throw new Error("z required")}static fromAffine(e){const{x:t,y:r}=e||{};if(!e||!n.isValid(t)||!n.isValid(r))throw new Error("invalid affine point");if(e instanceof h)throw new Error("projective point not allowed");const s=e=>n.eql(e,n.ZERO);return s(t)&&s(r)?h.ZERO:new h(t,r,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){const t=n.invertBatch(e.map((e=>e.pz)));return e.map(((e,n)=>e.toAffine(t[n]))).map(h.fromAffine)}static fromHex(e){const t=h.fromAffine(s(Mh("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return h.BASE.multiply(c(e))}_setWindowSize(e){this._WINDOW_SIZE=e,l.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint&&!n.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:e,y:r}=this.toAffine();if(!n.isValid(e)||!n.isValid(r))throw new Error("bad point: x or y not FE");const s=n.sqr(r),o=i(e);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:e}=this.toAffine();if(n.isOdd)return!n.isOdd(e);throw new Error("Field doesn't support isOdd")}equals(e){u(e);const{px:t,py:r,pz:s}=this,{px:i,py:o,pz:a}=e,c=n.eql(n.mul(t,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:e,b:r}=t,s=n.mul(r,yd),{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(e,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(e,p),g=n.sub(d,p),g=n.mul(e,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(e){u(e);const{px:r,py:s,pz:i}=this,{px:o,py:a,pz:c}=e;let l=n.ZERO,d=n.ZERO,f=n.ZERO;const p=t.a,g=n.mul(t.b,yd);let m=n.mul(r,o),y=n.mul(s,a),w=n.mul(i,c),b=n.add(r,s),_=n.add(o,a);b=n.mul(b,_),_=n.add(m,y),b=n.sub(b,_),_=n.add(r,i);let A=n.add(o,c);return _=n.mul(_,A),A=n.add(m,w),_=n.sub(_,A),A=n.add(s,i),l=n.add(a,c),A=n.mul(A,l),l=n.add(y,w),A=n.sub(A,l),f=n.mul(p,_),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),_=n.mul(g,_),y=n.add(y,w),w=n.sub(m,w),w=n.mul(p,w),_=n.add(_,w),m=n.mul(y,_),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(A,f),f=n.add(f,m),new h(l,d,f)}subtract(e){return this.add(e.negate())}is0(){return this.equals(h.ZERO)}wNAF(e){return f.wNAFCached(this,l,e,(e=>{const t=n.invertBatch(e.map((e=>e.pz)));return e.map(((e,n)=>e.toAffine(t[n]))).map(h.fromAffine)}))}multiplyUnsafe(e){const r=h.ZERO;if(e===gd)return r;if(a(e),e===md)return this;const{endo:s}=t;if(!s)return f.unsafeLadder(this,e);let{k1neg:i,k1:o,k2neg:c,k2:l}=s.splitScalar(e),u=r,d=r,p=this;for(;o>gd||l>gd;)o&md&&(u=u.add(p)),l&md&&(d=d.add(p)),p=p.double(),o>>=md,l>>=md;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(e){a(e);let r,s,i=e;const{endo:o}=t;if(o){const{k1neg:e,k1:t,k2neg:a,k2:c}=o.splitScalar(i);let{p:l,f:u}=this.wNAF(t),{p:d,f:p}=this.wNAF(c);l=f.constTimeNegate(e,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:e,f:t}=this.wNAF(i);r=e,s=t}return h.normalizeZ([r,s])[0]}multiplyAndAddUnsafe(e,t,n){const r=h.BASE,s=(e,t)=>t!==gd&&t!==md&&e.equals(r)?e.multiply(t):e.multiplyUnsafe(t),i=s(this,t).add(s(e,n));return i.is0()?void 0:i}toAffine(e){const{px:t,py:r,pz:s}=this,i=this.is0();null==e&&(e=i?n.ONE:n.inv(s));const o=n.mul(t,e),a=n.mul(r,e),c=n.mul(s,e);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:e,isTorsionFree:n}=t;if(e===md)return!0;if(n)return n(h,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:e,clearCofactor:n}=t;return e===md?this:n?n(h,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return this.assertValidity(),r(h,this,e)}toHex(e=!0){return Oh(this.toRawBytes(e))}}h.BASE=new h(t.Gx,t.Gy,n.ONE),h.ZERO=new h(n.ZERO,n.ONE,n.ZERO);const d=t.nBitLength,f=function(e,t){const n=(e,t)=>{const n=t.negate();return e?n:t},r=e=>({windows:Math.ceil(t/e)+1,windowSize:2**(e-1)});return{constTimeNegate:n,unsafeLadder(t,n){let r=e.ZERO,s=t;for(;n>ld;)n&ud&&(r=r.add(s)),s=s.double(),n>>=ud;return r},precomputeWindow(e,t){const{windows:n,windowSize:s}=r(t),i=[];let o=e,a=o;for(let r=0;r<n;r++){a=o,i.push(a);for(let e=1;e<s;e++)a=a.add(o),i.push(a);o=a.double()}return i},wNAF(t,s,i){const{windows:o,windowSize:a}=r(t);let c=e.ZERO,l=e.BASE;const u=BigInt(2**t-1),h=2**t,d=BigInt(t);for(let e=0;e<o;e++){const t=e*a;let r=Number(i&u);i>>=d,r>a&&(r-=h,i+=ud);const o=t,f=t+Math.abs(r)-1,p=e%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(e,t,n,r){const s=e._WINDOW_SIZE||1;let i=t.get(e);return i||(i=this.precomputeWindow(e,s),1!==s&&t.set(e,r(i))),this.wNAF(s,i,n)}}}(h,t.endo?Math.ceil(d/2):d);return{CURVE:t,ProjectivePoint:h,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:o}}function bd(e){const t=function(e){const t=hd(e);return Wh(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}(e),{Fp:n,n:r}=t,s=n.BYTES+1,i=2*n.BYTES+1;function o(e){return ed(e,r)}function a(e){return rd(e,r)}const{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:h}=wd({...t,toBytes(e,t,r){const s=t.toAffine(),i=n.toBytes(s.x),o=Fh;return r?o(Uint8Array.from([t.hasEvenY()?2:3]),i):o(Uint8Array.from([4]),i,n.toBytes(s.y))},fromBytes(e){const t=e.length,r=e[0],o=e.subarray(1);if(t!==s||2!==r&&3!==r){if(t===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 ${t} was invalid. Expected ${s} compressed bytes or ${i} uncompressed bytes`)}{const e=Dh(o);if(!(gd<(a=e)&&a<n.ORDER))throw new Error("Point is not on curve");const t=u(e);let s=n.sqrt(t);return!(1&~r)!==((s&md)===md)&&(s=n.neg(s)),{x:e,y:s}}var a}}),d=e=>Oh(Uh(e,t.nByteLength));function f(e){return e>r>>md}const p=(e,t,n)=>Dh(e.slice(t,n));class g{constructor(e,t,n){this.r=e,this.s=t,this.recovery=n,this.assertValidity()}static fromCompact(e){const n=t.nByteLength;return e=Mh("compactSignature",e,2*n),new g(p(e,0,n),p(e,n,2*n))}static fromDER(e){const{r:t,s:n}=pd.toSig(Mh("DER",e));return new g(t,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(e){return new g(this.r,this.s,e)}recoverPublicKey(e){const{r:r,s:s,recovery:i}=this,l=b(Mh("msgHash",e));if(null==i||![0,1,2,3].includes(i))throw new Error("recovery id invalid");const u=2===i||3===i?r+t.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 Ph(this.toDERHex())}toDERHex(){return pd.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Ph(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}const m={isValidPrivateKey(e){try{return l(e),!0}catch(t){return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const e=cd(t.n);return function(e,t,n=!1){const r=e.length,s=ad(t),i=cd(t);if(r<16||r<i||r>1024)throw new Error(`expected ${i}-1024 bytes of input, got ${r}`);const o=ed(n?Dh(e):Bh(e),t-Kh)+Kh;return n?Lh(o,s):Uh(o,s)}(t.randomBytes(e),t.n)},precompute:(e=8,t=c.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)};function y(e){const t=e instanceof Uint8Array,n="string"==typeof e,r=(t||n)&&e.length;return t?r===s||r===i:n?r===2*s||r===2*i:e instanceof c}const w=t.bits2int||function(e){const n=Dh(e),r=8*e.length-t.nBitLength;return r>0?n>>BigInt(r):n},b=t.bits2int_modN||function(e){return o(w(e))},_=jh(t.nBitLength);function A(e){if("bigint"!=typeof e)throw new Error("bigint expected");if(!(gd<=e&&e<_))throw new Error(`bigint expected < 2^${t.nBitLength}`);return Uh(e,t.nByteLength)}function v(e,r,s=E){if(["recovered","canonical"].some((e=>e in s)))throw new Error("sign() legacy options not supported");const{hash:i,randomBytes:u}=t;let{lowS:d,prehash:p,extraEntropy:m}=s;null==d&&(d=!0),e=Mh("msgHash",e),p&&(e=Mh("prehashed msgHash",i(e)));const y=b(e),_=l(r),v=[A(_),A(y)];if(null!=m){const e=!0===m?u(n.BYTES):m;v.push(Mh("extraEntropy",e))}const k=Fh(...v),S=y;return{seed:k,k2sig:function(e){const t=w(e);if(!h(t))return;const n=a(t),r=c.BASE.multiply(t).toAffine(),s=o(r.x);if(s===gd)return;const i=o(n*o(S+s*_));if(i===gd)return;let l=(r.x===s?0:2)|Number(r.y&md),u=i;return d&&f(i)&&(u=function(e){return f(e)?o(-e):e}(i),l^=1),new g(s,u,l)}}}const E={lowS:t.lowS,prehash:!1},k={lowS:t.lowS,prehash:!1};return c.BASE._setWindowSize(8),{CURVE:t,getPublicKey:function(e,t=!0){return c.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t,n=!0){if(y(e))throw new Error("first arg must be private key");if(!y(t))throw new Error("second arg must be public key");return c.fromHex(t).multiply(l(e)).toRawBytes(n)},sign:function(e,n,r=E){const{seed:s,k2sig:i}=v(e,n,r),o=t;return Vh(o.hash.outputLen,o.nByteLength,o.hmac)(s,i)},verify:function(e,n,r,s=k){var i;const l=e;if(n=Mh("msgHash",n),r=Mh("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 pd.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:e,s:t}=l;d=new g(e,t)}}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=t.hash(n));const{r:p,s:m}=d,y=b(n),w=a(m),_=o(y*w),A=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 _d(e){return{hash:e,hmac:(t,...n)=>Gl(e,t,function(...e){const t=new Uint8Array(e.reduce(((e,t)=>e+t.length),0));let n=0;return e.forEach((e=>{if(!Il(e))throw new Error("Uint8Array expected");t.set(e,n),n+=e.length})),t}(...n)),randomBytes:Fl}}BigInt(4);
|
|
10
10
|
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
11
|
-
const Ad=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),vd=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Ed=BigInt(1),kd=BigInt(2),Sd=(e,t)=>(e+t/kd)/t;const Td=function(e,t,n=!1,r={}){if(e<=Kh)throw new Error(`Expected Field ORDER > 0, got ${e}`);const{nBitLength:s,nByteLength:i}=od(e,t);if(i>2048)throw new Error("Field lengths over 2048 bytes are not supported");const o=sd(e),a=Object.freeze({ORDER:e,BITS:s,BYTES:i,MASK:jh(s),ZERO:Kh,ONE:$h,create:t=>ed(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("Invalid field element: expected bigint, got "+typeof t);return Kh<=t&&t<e},is0:e=>e===Kh,isOdd:e=>(e&$h)===$h,neg:t=>ed(-t,e),eql:(e,t)=>e===t,sqr:t=>ed(t*t,e),add:(t,n)=>ed(t+n,e),sub:(t,n)=>ed(t-n,e),mul:(t,n)=>ed(t*n,e),pow:(e,t)=>function(e,t,n){if(n<Kh)throw new Error("Expected power > 0");if(n===Kh)return e.ONE;if(n===$h)return t;let r=e.ONE,s=t;for(;n>Kh;)n&$h&&(r=e.mul(r,s)),s=e.sqr(s),n>>=$h;return r}(a,e,t),div:(t,n)=>ed(t*rd(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>rd(t,e),sqrt:r.sqrt||(e=>o(a,e)),invertBatch:e=>function(e,t){const n=new Array(t.length),r=t.reduce(((t,r,s)=>e.is0(r)?t:(n[s]=t,e.mul(t,r))),e.ONE),s=e.inv(r);return t.reduceRight(((t,r,s)=>e.is0(r)?t:(n[s]=e.mul(t,n[s]),e.mul(t,r))),s),n}(a,e),cmov:(e,t,n)=>n?t:e,toBytes:e=>n?Lh(e,i):Uh(e,i),fromBytes:e=>{if(e.length!==i)throw new Error(`Fp.fromBytes: expected ${i}, got ${e.length}`);return n?Bh(e):Dh(e)}});return Object.freeze(a)}(Ad,void 0,void 0,{sqrt:function(e){const t=Ad,n=BigInt(3),r=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,h=nd(u,n,t)*u%t,d=nd(h,n,t)*u%t,f=nd(d,kd,t)*l%t,p=nd(f,s,t)*f%t,g=nd(p,i,t)*p%t,m=nd(g,a,t)*g%t,y=nd(m,c,t)*m%t,w=nd(y,a,t)*g%t,b=nd(w,n,t)*u%t,_=nd(b,o,t)*p%t,A=nd(_,r,t)*l%t,v=nd(A,kd,t);if(!Td.eql(Td.sqr(v),e))throw new Error("Cannot find square root");return v}}),Rd=function(e,t){const n=t=>bd({...e,..._d(t)});return Object.freeze({...n(t),create:n})}({a:BigInt(0),b:BigInt(7),Fp:Td,n:vd,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=vd,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-Ed*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=n,o=BigInt("0x100000000000000000000000000000000"),a=Sd(i*e,t),c=Sd(-r*e,t);let l=ed(e-a*n-c*s,t),u=ed(-a*r-c*i,t);const h=l>o,d=u>o;if(h&&(l=t-l),d&&(u=t-u),l>o||u>o)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}}},Ql);BigInt(0),Rd.ProjectivePoint;const Id="0x0000000000000000000000000000000000000000",Cd="0x0000000000000000000000000000000000000000000000000000000000000000",Od=BigInt(0),xd=BigInt(1),Nd=BigInt(2),Pd=BigInt(27),Dd=BigInt(28),Bd=BigInt(35),Ud=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Ld=Ud/Nd,Md=Symbol.for("nodejs.util.inspect.custom"),Fd={};function jd(e){return uc(Ec(e),32)}j=new WeakMap,G=new WeakMap,H=new WeakMap,V=new WeakMap;let Gd=class e{constructor(e,t,n,r){Dn(this,j,void 0),Dn(this,G,void 0),Dn(this,H,void 0),Dn(this,V,void 0),Za(e,Fd,"Signature"),Bn(this,j,t),Bn(this,G,n),Bn(this,H,r),Bn(this,V,null)}get r(){return Pn(this,j)}set r(e){$a(32===ac(e),"invalid r","value",e),Bn(this,j,ic(e))}get s(){return $a(parseInt(Pn(this,G).substring(0,3))<8,"non-canonical s; use ._s","s",Pn(this,G)),Pn(this,G)}set s(e){$a(32===ac(e),"invalid s","value",e),Bn(this,G,ic(e))}get _s(){return Pn(this,G)}isValid(){return BigInt(Pn(this,G))<=Ld}get v(){return Pn(this,H)}set v(e){const t=Ac(e,"value");$a(27===t||28===t,"invalid v","v",e),Bn(this,H,t)}get networkV(){return Pn(this,V)}get legacyChainId(){const t=this.networkV;return null==t?null:e.getChainId(t)}get yParity(){return 27===this.v?0:1}get yParityAndS(){const e=ec(this.s);return this.yParity&&(e[0]|=128),ic(e)}get compactSerialized(){return oc([this.r,this.yParityAndS])}get serialized(){return oc([this.r,this.s,this.yParity?"0x1c":"0x1b"])}getCanonical(){if(this.isValid())return this;const t=Ud-BigInt(this._s),n=55-this.v,r=new e(Fd,this.r,jd(t),n);return this.networkV&&Bn(r,V,this.networkV),r}clone(){const t=new e(Fd,this.r,this._s,this.v);return this.networkV&&Bn(t,V,this.networkV),t}toJSON(){const e=this.networkV;return{_type:"signature",networkV:null!=e?e.toString():null,r:this.r,s:this._s,v:this.v}}[Md](){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(e){const t=yc(e,"v");return t==Pd||t==Dd?Od:($a(t>=Bd,"invalid EIP-155 v","v",e),(t-Bd)/Nd)}static getChainIdV(e,t){return yc(e)*Nd+BigInt(35+t-27)}static getNormalizedV(e){const t=yc(e);return t===Od||t===Pd?27:t===xd||t===Dd?28:($a(t>=Bd,"invalid v","v",e),t&xd?27:28)}static from(t){function n(e,n){$a(e,n,"signature",t)}if(null==t)return new e(Fd,Cd,Cd,27);if("string"==typeof t){const r=ec(t,"signature");if(64===r.length){const t=ic(r.slice(0,32)),n=r.slice(32,64),s=128&n[0]?28:27;return n[0]&=127,new e(Fd,t,ic(n),s)}if(65===r.length){const t=ic(r.slice(0,32)),n=ic(r.slice(32,64)),s=e.getNormalizedV(r[64]);return new e(Fd,t,n,s)}n(!1,"invalid raw signature length")}if(t instanceof e)return t.clone();const r=t.r;n(null!=r,"missing r");const s=jd(r),i=function(e,t){if(null!=e)return jd(e);if(null!=t){n(nc(t,32),"invalid yParityAndS");const e=ec(t);return e[0]&=127,ic(e)}n(!1,"missing s")}(t.s,t.yParityAndS),{networkV:o,v:a}=function(t,r,s){if(null!=t){const n=yc(t);return{networkV:n>=Bd?n:void 0,v:e.getNormalizedV(n)}}if(null!=r)return n(nc(r,32),"invalid yParityAndS"),{v:128&ec(r)[0]?28:27};if(null!=s){switch(Ac(s,"sig.yParity")){case 0:return{v:27};case 1:return{v:28}}n(!1,"invalid yParity")}n(!1,"missing v")}(t.v,t.yParityAndS,t.yParity),c=new e(Fd,s,i,a);return o&&Bn(c,V,o),n(null==t.yParity||Ac(t.yParity,"sig.yParity")===c.yParity,"yParity mismatch"),n(null==t.yParityAndS||t.yParityAndS===c.yParityAndS,"yParityAndS mismatch"),c}};q=new WeakMap;let Hd=class e{constructor(e){Dn(this,q,void 0),$a(32===ac(e),"invalid private key","privateKey","[REDACTED]"),Bn(this,q,ic(e))}get privateKey(){return Pn(this,q)}get publicKey(){return e.computePublicKey(Pn(this,q))}get compressedPublicKey(){return e.computePublicKey(Pn(this,q),!0)}sign(e){$a(32===ac(e),"invalid digest length","digest",e);const t=Rd.sign(tc(e),tc(Pn(this,q)),{lowS:!0});return Gd.from({r:vc(t.r,32),s:vc(t.s,32),v:t.recovery?28:27})}computeSharedSecret(t){const n=e.computePublicKey(t);return ic(Rd.getSharedSecret(tc(Pn(this,q)),ec(n),!1))}static computePublicKey(e,t){let n=ec(e,"key");if(32===n.length){return ic(Rd.getPublicKey(n,!!t))}if(64===n.length){const e=new Uint8Array(65);e[0]=4,e.set(n,1),n=e}return ic(Rd.ProjectivePoint.fromHex(n).toRawBytes(t))}static recoverPublicKey(e,t){$a(32===ac(e),"invalid digest length","digest",e);const n=Gd.from(t);let r=Rd.Signature.fromCompact(tc(oc([n.r,n.s])));r=r.addRecoveryBit(n.yParity);const s=r.recoverPublicKey(tc(e));return $a(null!=s,"invalid signature for digest","signature",t),"0x"+s.toHex(!1)}static addPoints(t,n,r){const s=Rd.ProjectivePoint.fromHex(e.computePublicKey(t).substring(2)),i=Rd.ProjectivePoint.fromHex(e.computePublicKey(n).substring(2));return"0x"+s.add(i).toHex(!!r)}};const Vd=BigInt(0),qd=BigInt(36);function Wd(e){const t=(e=e.toLowerCase()).substring(2).split(""),n=new Uint8Array(40);for(let s=0;s<40;s++)n[s]=t[s].charCodeAt(0);const r=ec(Bu(n));for(let s=0;s<40;s+=2)r[s>>1]>>4>=8&&(t[s]=t[s].toUpperCase()),(15&r[s>>1])>=8&&(t[s+1]=t[s+1].toUpperCase());return"0x"+t.join("")}const zd={};for(let uE=0;uE<10;uE++)zd[String(uE)]=String(uE);for(let uE=0;uE<26;uE++)zd[String.fromCharCode(65+uE)]=String(10+uE);const Kd=function(){const e={};for(let t=0;t<36;t++){e["0123456789abcdefghijklmnopqrstuvwxyz"[t]]=BigInt(t)}return e}();function $d(e){if($a("string"==typeof e,"invalid address","address",e),e.match(/^(0x)?[0-9a-fA-F]{40}$/)){e.startsWith("0x")||(e="0x"+e);const t=Wd(e);return $a(!e.match(/([A-F].*[a-f])|([a-f].*[A-F])/)||t===e,"bad address checksum","address",e),t}if(e.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){$a(e.substring(2,4)===function(e){let t=(e=(e=e.toUpperCase()).substring(4)+e.substring(0,2)+"00").split("").map((e=>zd[e])).join("");for(;t.length>=15;){let e=t.substring(0,15);t=parseInt(e,10)%97+t.substring(e.length)}let n=String(98-parseInt(t,10)%97);for(;n.length<2;)n="0"+n;return n}(e),"bad icap checksum","address",e);let t=function(e){e=e.toLowerCase();let t=Vd;for(let n=0;n<e.length;n++)t=t*qd+Kd[e[n]];return t}(e.substring(4)).toString(16);for(;t.length<40;)t="0"+t;return Wd("0x"+t)}$a(!1,"invalid address","address",e)}function Qd(e){return e&&"function"==typeof e.getAddress}async function Jd(e,t){const n=await t;return null!=n&&"0x0000000000000000000000000000000000000000"!==n||(Ka("string"!=typeof e,"unconfigured name","UNCONFIGURED_NAME",{value:e}),$a(!1,"invalid AddressLike value; did not resolve to a value address","target",e)),$d(n)}function Yd(e,t){return"string"==typeof e?e.match(/^0x[0-9a-f]{40}$/i)?$d(e):(Ka(null!=t,"ENS resolution requires a provider","UNSUPPORTED_OPERATION",{operation:"resolveName"}),Jd(e,t.resolveName(e))):Qd(e)?Jd(e,e.getAddress()):e&&"function"==typeof e.then?Jd(e,e):void $a(!1,"unsupported addressable value","target",e)}const Zd={};function Xd(e,t){let n=!1;return t<0&&(n=!0,t*=-1),new nf(Zd,`${n?"":"u"}int${t}`,e,{signed:n,width:t})}function ef(e,t){return new nf(Zd,`bytes${t||""}`,e,{size:t})}const tf=Symbol.for("_ethers_typed");W=new WeakMap;let nf=class e{constructor(e,t,n,r){xn(this,"type"),xn(this,"value"),Dn(this,W,void 0),xn(this,"_typedSymbol"),null==r&&(r=null),Za(Zd,e,"Typed"),Ha(this,{_typedSymbol:tf,type:t,value:n}),Bn(this,W,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((e=>e.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,W)}get arrayLength(){if("array"!==this.type)throw TypeError("not an array");return!0===Pn(this,W)?-1:!1===Pn(this,W)?this.value.length:null}static from(t,n){return new e(Zd,t,n)}static uint8(e){return Xd(e,8)}static uint16(e){return Xd(e,16)}static uint24(e){return Xd(e,24)}static uint32(e){return Xd(e,32)}static uint40(e){return Xd(e,40)}static uint48(e){return Xd(e,48)}static uint56(e){return Xd(e,56)}static uint64(e){return Xd(e,64)}static uint72(e){return Xd(e,72)}static uint80(e){return Xd(e,80)}static uint88(e){return Xd(e,88)}static uint96(e){return Xd(e,96)}static uint104(e){return Xd(e,104)}static uint112(e){return Xd(e,112)}static uint120(e){return Xd(e,120)}static uint128(e){return Xd(e,128)}static uint136(e){return Xd(e,136)}static uint144(e){return Xd(e,144)}static uint152(e){return Xd(e,152)}static uint160(e){return Xd(e,160)}static uint168(e){return Xd(e,168)}static uint176(e){return Xd(e,176)}static uint184(e){return Xd(e,184)}static uint192(e){return Xd(e,192)}static uint200(e){return Xd(e,200)}static uint208(e){return Xd(e,208)}static uint216(e){return Xd(e,216)}static uint224(e){return Xd(e,224)}static uint232(e){return Xd(e,232)}static uint240(e){return Xd(e,240)}static uint248(e){return Xd(e,248)}static uint256(e){return Xd(e,256)}static uint(e){return Xd(e,256)}static int8(e){return Xd(e,-8)}static int16(e){return Xd(e,-16)}static int24(e){return Xd(e,-24)}static int32(e){return Xd(e,-32)}static int40(e){return Xd(e,-40)}static int48(e){return Xd(e,-48)}static int56(e){return Xd(e,-56)}static int64(e){return Xd(e,-64)}static int72(e){return Xd(e,-72)}static int80(e){return Xd(e,-80)}static int88(e){return Xd(e,-88)}static int96(e){return Xd(e,-96)}static int104(e){return Xd(e,-104)}static int112(e){return Xd(e,-112)}static int120(e){return Xd(e,-120)}static int128(e){return Xd(e,-128)}static int136(e){return Xd(e,-136)}static int144(e){return Xd(e,-144)}static int152(e){return Xd(e,-152)}static int160(e){return Xd(e,-160)}static int168(e){return Xd(e,-168)}static int176(e){return Xd(e,-176)}static int184(e){return Xd(e,-184)}static int192(e){return Xd(e,-192)}static int200(e){return Xd(e,-200)}static int208(e){return Xd(e,-208)}static int216(e){return Xd(e,-216)}static int224(e){return Xd(e,-224)}static int232(e){return Xd(e,-232)}static int240(e){return Xd(e,-240)}static int248(e){return Xd(e,-248)}static int256(e){return Xd(e,-256)}static int(e){return Xd(e,-256)}static bytes1(e){return ef(e,1)}static bytes2(e){return ef(e,2)}static bytes3(e){return ef(e,3)}static bytes4(e){return ef(e,4)}static bytes5(e){return ef(e,5)}static bytes6(e){return ef(e,6)}static bytes7(e){return ef(e,7)}static bytes8(e){return ef(e,8)}static bytes9(e){return ef(e,9)}static bytes10(e){return ef(e,10)}static bytes11(e){return ef(e,11)}static bytes12(e){return ef(e,12)}static bytes13(e){return ef(e,13)}static bytes14(e){return ef(e,14)}static bytes15(e){return ef(e,15)}static bytes16(e){return ef(e,16)}static bytes17(e){return ef(e,17)}static bytes18(e){return ef(e,18)}static bytes19(e){return ef(e,19)}static bytes20(e){return ef(e,20)}static bytes21(e){return ef(e,21)}static bytes22(e){return ef(e,22)}static bytes23(e){return ef(e,23)}static bytes24(e){return ef(e,24)}static bytes25(e){return ef(e,25)}static bytes26(e){return ef(e,26)}static bytes27(e){return ef(e,27)}static bytes28(e){return ef(e,28)}static bytes29(e){return ef(e,29)}static bytes30(e){return ef(e,30)}static bytes31(e){return ef(e,31)}static bytes32(e){return ef(e,32)}static address(t){return new e(Zd,"address",t)}static bool(t){return new e(Zd,"bool",!!t)}static bytes(t){return new e(Zd,"bytes",t)}static string(t){return new e(Zd,"string",t)}static array(e,t){throw new Error("not implemented yet")}static tuple(e,t){throw new Error("not implemented yet")}static overrides(t){return new e(Zd,"overrides",Object.assign({},t))}static isTyped(e){return e&&"object"==typeof e&&"_typedSymbol"in e&&e._typedSymbol===tf}static dereference(t,n){if(e.isTyped(t)){if(t.type!==n)throw new Error(`invalid type: expecetd ${n}, got ${t.type}`);return t.value}return t}};class rf extends bl{constructor(e){super("address","address",e,!1)}defaultValue(){return"0x0000000000000000000000000000000000000000"}encode(e,t){let n=nf.dereference(t,"string");try{n=$d(n)}catch(r){return this._throwError(r.message,t)}return e.writeValue(n)}decode(e){return $d(vc(e.readValue(),20))}}class sf extends bl{constructor(e){super(e.name,e.type,"_",e.dynamic),xn(this,"coder"),this.coder=e}defaultValue(){return this.coder.defaultValue()}encode(e,t){return this.coder.encode(e,t)}decode(e){return this.coder.decode(e)}}function of(e,t,n){let r=[];if(Array.isArray(n))r=n;else if(n&&"object"==typeof n){let e={};r=t.map((t=>{const r=t.localName;return Ka(r,"cannot encode object for signature with missing names","INVALID_ARGUMENT",{argument:"values",info:{coder:t},value:n}),Ka(!e[r],"cannot encode object for signature with duplicate names","INVALID_ARGUMENT",{argument:"values",info:{coder:t},value:n}),e[r]=!0,n[r]}))}else $a(!1,"invalid tuple value","tuple",n);$a(t.length===r.length,"types/value length mismatch","tuple",n);let s=new _l,i=new _l,o=[];t.forEach(((e,t)=>{let n=r[t];if(e.dynamic){let t=i.length;e.encode(i,n);let r=s.writeUpdatableValue();o.push((e=>{r(e+t)}))}else e.encode(s,n)})),o.forEach((e=>{e(s.length)}));let a=e.appendWriter(s);return a+=e.appendWriter(i),a}function af(e,t){let n=[],r=[],s=e.subReader(0);return t.forEach((t=>{let i=null;if(t.dynamic){let n=e.readIndex(),r=s.subReader(n);try{i=t.decode(r)}catch(o){if(qa(o,"BUFFER_OVERRUN"))throw o;i=o,i.baseType=t.name,i.name=t.localName,i.type=t.type}}else try{i=t.decode(e)}catch(o){if(qa(o,"BUFFER_OVERRUN"))throw o;i=o,i.baseType=t.name,i.name=t.localName,i.type=t.type}if(null==i)throw new Error("investigate");n.push(i),r.push(t.localName||null)})),yl.fromItems(n,r)}class cf extends bl{constructor(e,t,n){super("array",e.type+"["+(t>=0?t:"")+"]",n,-1===t||e.dynamic),xn(this,"coder"),xn(this,"length"),Ha(this,{coder:e,length:t})}defaultValue(){const e=this.coder.defaultValue(),t=[];for(let n=0;n<this.length;n++)t.push(e);return t}encode(e,t){const n=nf.dereference(t,"array");Array.isArray(n)||this._throwError("expected array value",n);let r=this.length;-1===r&&(r=n.length,e.writeValue(n.length)),Qa(n.length,r,"coder array"+(this.localName?" "+this.localName:""));let s=[];for(let i=0;i<n.length;i++)s.push(this.coder);return of(e,s,n)}decode(e){let t=this.length;-1===t&&(t=e.readIndex(),Ka(t*cl<=e.dataLength,"insufficient data length","BUFFER_OVERRUN",{buffer:e.bytes,offset:t*cl,length:e.dataLength}));let n=[];for(let r=0;r<t;r++)n.push(new sf(this.coder));return af(e,n)}}class lf extends bl{constructor(e){super("bool","bool",e,!1)}defaultValue(){return!1}encode(e,t){const n=nf.dereference(t,"bool");return e.writeValue(n?1:0)}decode(e){return!!e.readValue()}}class uf extends bl{constructor(e,t){super(e,e,t,!0)}defaultValue(){return"0x"}encode(e,t){t=tc(t);let n=e.writeValue(t.length);return n+=e.writeBytes(t),n}decode(e){return e.readBytes(e.readIndex(),!0)}}class hf extends uf{constructor(e){super("bytes",e)}decode(e){return ic(super.decode(e))}}class df extends bl{constructor(e,t){let n="bytes"+String(e);super(n,n,t,!1),xn(this,"size"),Ha(this,{size:e},{size:"number"})}defaultValue(){return"0x0000000000000000000000000000000000000000000000000000000000000000".substring(0,2+2*this.size)}encode(e,t){let n=tc(nf.dereference(t,this.type));return n.length!==this.size&&this._throwError("incorrect data length",t),e.writeBytes(n)}decode(e){return ic(e.readBytes(this.size))}}const ff=new Uint8Array([]);class pf extends bl{constructor(e){super("null","",e,!1)}defaultValue(){return null}encode(e,t){return null!=t&&this._throwError("not null",t),e.writeBytes(ff)}decode(e){return e.readBytes(0),null}}const gf=BigInt(0),mf=BigInt(1),yf=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");class wf extends bl{constructor(e,t,n){const r=(t?"int":"uint")+8*e;super(r,r,n,!1),xn(this,"size"),xn(this,"signed"),Ha(this,{size:e,signed:t},{size:"number",signed:"boolean"})}defaultValue(){return 0}encode(e,t){let n=yc(nf.dereference(t,this.type)),r=mc(yf,256);if(this.signed){let e=mc(r,8*this.size-1);(n>e||n<-(e+mf))&&this._throwError("value out-of-bounds",t),n=gc(n,256)}else(n<gf||n>mc(r,8*this.size))&&this._throwError("value out-of-bounds",t);return e.writeValue(n)}decode(e){let t=mc(e.readValue(),8*this.size);return this.signed&&(t=function(e,t){const n=wc(e,"value"),r=BigInt(Ac(t,"width"));if(Ka(n>>r===dc,"overflow","NUMERIC_FAULT",{operation:"fromTwos",fault:"overflow",value:e}),n>>r-fc)return-((~n&(fc<<r)-fc)+fc);return n}(t,8*this.size)),t}}class bf extends uf{constructor(e){super("string",e)}defaultValue(){return""}encode(e,t){return super.encode(e,Dc(nf.dereference(t,"string")))}decode(e){return Bc(super.decode(e))}}class _f extends bl{constructor(e,t){let n=!1;const r=[];e.forEach((e=>{e.dynamic&&(n=!0),r.push(e.type)}));super("tuple","tuple("+r.join(",")+")",t,n),xn(this,"coders"),Ha(this,{coders:Object.freeze(e.slice())})}defaultValue(){const e=[];this.coders.forEach((t=>{e.push(t.defaultValue())}));const t=this.coders.reduce(((e,t)=>{const n=t.localName;return n&&(e[n]||(e[n]=0),e[n]++),e}),{});return this.coders.forEach(((n,r)=>{let s=n.localName;s&&1===t[s]&&("length"===s&&(s="_length"),null==e[s]&&(e[s]=e[r]))})),Object.freeze(e)}encode(e,t){const n=nf.dereference(t,"tuple");return of(e,this.coders,n)}decode(e){return af(e,this.coders)}}function Af(e,t){return{address:$d(e),storageKeys:t.map(((e,t)=>($a(nc(e,32),"invalid slot",`storageKeys[${t}]`,e),e.toLowerCase())))}}function vf(e){if(Array.isArray(e))return e.map(((t,n)=>Array.isArray(t)?($a(2===t.length,"invalid slot set",`value[${n}]`,t),Af(t[0],t[1])):($a(null!=t&&"object"==typeof t,"invalid address-slot set","value",e),Af(t.address,t.storageKeys))));$a(null!=e&&"object"==typeof e,"invalid access list","value",e);const t=Object.keys(e).map((t=>{const n=e[t].reduce(((e,t)=>(e[t]=!0,e)),{});return Af(t,Object.keys(n).sort())}));return t.sort(((e,t)=>e.address.localeCompare(t.address))),t}function Ef(e){return{address:$d(e.address),nonce:yc(null!=e.nonce?e.nonce:0),chainId:yc(null!=e.chainId?e.chainId:0),signature:Gd.from(e.signature)}}function kf(e){let t;return t="string"==typeof e?Hd.computePublicKey(e,!1):e.publicKey,$d(Bu("0x"+t.substring(4)).substring(26))}const Sf=BigInt(0),Tf=BigInt(2),Rf=BigInt(27),If=BigInt(28),Cf=BigInt(35),Of=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),xf=Symbol.for("nodejs.util.inspect.custom"),Nf=131072,Pf=128;function Df(e,t){let n=e.toString(16);for(;n.length<2;)n="0"+n;return n+=kh(t).substring(4),"0x"+n}function Bf(e){return"0x"===e?null:$d(e)}function Uf(e,t){try{return vf(e)}catch(n){$a(!1,n.message,t,e)}}function Lf(e,t){try{if(!Array.isArray(e))throw new Error("authorizationList: invalid array");const t=[];for(let n=0;n<e.length;n++){const r=e[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`);t.push({address:Bf(r[1]),nonce:Ff(r[2],"nonce"),chainId:Ff(r[0],"chainId"),signature:Gd.from({yParity:Mf(r[3],"yParity"),r:uc(r[4],32),s:uc(r[5],32)})})}return t}catch(n){$a(!1,n.message,t,e)}}function Mf(e,t){return"0x"===e?0:Ac(e,t)}function Ff(e,t){if("0x"===e)return Sf;const n=yc(e,t);return $a(n<=Of,"value exceeds uint size",t,n),n}function jf(e,t){const n=yc(e,"value"),r=Ec(n);return $a(r.length<=32,"value too large",`tx.${t}`,n),r}function Gf(e){return vf(e).map((e=>[e.address,e.storageKeys]))}function Hf(e,t){$a(Array.isArray(e),`invalid ${t}`,"value",e);for(let n=0;n<e.length;n++)$a(nc(e[n],32),"invalid ${ param } hash",`value[${n}]`,e[n]);return e}function Vf(e,t){let n;try{if(n=Mf(t[0],"yParity"),0!==n&&1!==n)throw new Error("bad yParity")}catch(o){$a(!1,"invalid yParity","yParity",t[0])}const r=uc(t[1],32),s=uc(t[2],32),i=Gd.from({r:r,s:s,yParity:n});e.signature=i}z=new WeakMap,K=new WeakMap,$=new WeakMap,Q=new WeakMap,J=new WeakMap,Y=new WeakMap,Z=new WeakMap,X=new WeakMap,ee=new WeakMap,te=new WeakMap,ne=new WeakMap,re=new WeakMap,se=new WeakMap,ie=new WeakMap,oe=new WeakMap,ae=new WeakMap,ce=new WeakMap,le=new WeakMap,ue=new WeakSet,he=function(e,t){Ka(!e||null!=this.signature,"cannot serialize unsigned transaction; maybe you meant .unsignedSerialized","UNSUPPORTED_OPERATION",{operation:".serialized"});const n=e?this.signature:null;switch(this.inferType()){case 0:return function(e,t){const n=[jf(e.nonce,"nonce"),jf(e.gasPrice||0,"gasPrice"),jf(e.gasLimit,"gasLimit"),e.to||"0x",jf(e.value,"value"),e.data];let r=Sf;if(e.chainId!=Sf)r=yc(e.chainId,"tx.chainId"),$a(!t||null==t.networkV||t.legacyChainId===r,"tx.chainId/sig.v mismatch","sig",t);else if(e.signature){const t=e.signature.legacyChainId;null!=t&&(r=t)}if(!t)return r!==Sf&&(n.push(Ec(r)),n.push("0x"),n.push("0x")),ol(n);let s=BigInt(27+t.yParity);return r!==Sf?s=Gd.getChainIdV(r,t.v):BigInt(t.v)!==s&&$a(!1,"tx.chainId/sig.v mismatch","sig",t),n.push(Ec(s)),n.push(Ec(t.r)),n.push(Ec(t._s)),ol(n)}(this,n);case 1:return function(e,t){const n=[jf(e.chainId,"chainId"),jf(e.nonce,"nonce"),jf(e.gasPrice||0,"gasPrice"),jf(e.gasLimit,"gasLimit"),e.to||"0x",jf(e.value,"value"),e.data,Gf(e.accessList||[])];return t&&(n.push(jf(t.yParity,"recoveryParam")),n.push(Ec(t.r)),n.push(Ec(t.s))),oc(["0x01",ol(n)])}(this,n);case 2:return function(e,t){const n=[jf(e.chainId,"chainId"),jf(e.nonce,"nonce"),jf(e.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),jf(e.maxFeePerGas||0,"maxFeePerGas"),jf(e.gasLimit,"gasLimit"),e.to||"0x",jf(e.value,"value"),e.data,Gf(e.accessList||[])];return t&&(n.push(jf(t.yParity,"yParity")),n.push(Ec(t.r)),n.push(Ec(t.s))),oc(["0x02",ol(n)])}(this,n);case 3:return function(e,t,n){const r=[jf(e.chainId,"chainId"),jf(e.nonce,"nonce"),jf(e.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),jf(e.maxFeePerGas||0,"maxFeePerGas"),jf(e.gasLimit,"gasLimit"),e.to||Id,jf(e.value,"value"),e.data,Gf(e.accessList||[]),jf(e.maxFeePerBlobGas||0,"maxFeePerBlobGas"),Hf(e.blobVersionedHashes||[],"blobVersionedHashes")];if(t&&(r.push(jf(t.yParity,"yParity")),r.push(Ec(t.r)),r.push(Ec(t.s)),n)){if(null!=e.blobWrapperVersion){const t=Ec(e.blobWrapperVersion),s=[];for(const{proof:e}of n){const t=ec(e),n=t.length/Pf;for(let e=0;e<t.length;e+=n)s.push(t.subarray(e,e+n))}return oc(["0x03",ol([r,t,n.map((e=>e.data)),n.map((e=>e.commitment)),s])])}return oc(["0x03",ol([r,n.map((e=>e.data)),n.map((e=>e.commitment)),n.map((e=>e.proof))])])}return oc(["0x03",ol(r)])}(this,n,t?this.blobs:null);case 4:return function(e,t){const n=[jf(e.chainId,"chainId"),jf(e.nonce,"nonce"),jf(e.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),jf(e.maxFeePerGas||0,"maxFeePerGas"),jf(e.gasLimit,"gasLimit"),e.to||"0x",jf(e.value,"value"),e.data,Gf(e.accessList||[]),(r=e.authorizationList||[],r.map((e=>[jf(e.chainId,"chainId"),e.address,jf(e.nonce,"nonce"),jf(e.signature.yParity,"yParity"),Ec(e.signature.r),Ec(e.signature._s)])))];var r;return t&&(n.push(jf(t.yParity,"yParity")),n.push(Ec(t.r)),n.push(Ec(t.s))),oc(["0x04",ol(n)])}(this,n)}Ka(!1,"unsupported transaction type","UNSUPPORTED_OPERATION",{operation:".serialized"})};let qf=class e{constructor(){Dn(this,ue),Dn(this,z,void 0),Dn(this,K,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,ee,void 0),Dn(this,te,void 0),Dn(this,ne,void 0),Dn(this,re,void 0),Dn(this,se,void 0),Dn(this,ie,void 0),Dn(this,oe,void 0),Dn(this,ae,void 0),Dn(this,ce,void 0),Dn(this,le,void 0),Bn(this,z,null),Bn(this,K,null),Bn(this,Q,0),Bn(this,J,Sf),Bn(this,Y,null),Bn(this,Z,null),Bn(this,X,null),Bn(this,$,"0x"),Bn(this,ee,Sf),Bn(this,te,Sf),Bn(this,ne,null),Bn(this,re,null),Bn(this,se,null),Bn(this,ie,null),Bn(this,oe,null),Bn(this,ae,null),Bn(this,ce,null),Bn(this,le,null)}get type(){return Pn(this,z)}set type(e){switch(e){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:$a(!1,"unsupported transaction type","type",e)}}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 e=Pn(this,K);return null==e&&3===this.type?Id:e}set to(e){Bn(this,K,null==e?null:$d(e))}get nonce(){return Pn(this,Q)}set nonce(e){Bn(this,Q,Ac(e,"value"))}get gasLimit(){return Pn(this,J)}set gasLimit(e){Bn(this,J,yc(e))}get gasPrice(){const e=Pn(this,Y);return null!=e||0!==this.type&&1!==this.type?e:Sf}set gasPrice(e){Bn(this,Y,null==e?null:yc(e,"gasPrice"))}get maxPriorityFeePerGas(){const e=Pn(this,Z);return null==e?2===this.type||3===this.type?Sf:null:e}set maxPriorityFeePerGas(e){Bn(this,Z,null==e?null:yc(e,"maxPriorityFeePerGas"))}get maxFeePerGas(){const e=Pn(this,X);return null==e?2===this.type||3===this.type?Sf:null:e}set maxFeePerGas(e){Bn(this,X,null==e?null:yc(e,"maxFeePerGas"))}get data(){return Pn(this,$)}set data(e){Bn(this,$,ic(e))}get value(){return Pn(this,ee)}set value(e){Bn(this,ee,yc(e,"value"))}get chainId(){return Pn(this,te)}set chainId(e){Bn(this,te,yc(e))}get signature(){return Pn(this,ne)||null}set signature(e){Bn(this,ne,null==e?null:Gd.from(e))}isValid(){const e=this.signature;if(e&&!e.isValid())return!1;const t=this.authorizationList;if(t)for(const n of t)if(!n.signature.isValid())return!1;return!0}get accessList(){const e=Pn(this,re)||null;return null==e?1===this.type||2===this.type||3===this.type?[]:null:e}set accessList(e){Bn(this,re,null==e?null:vf(e))}get authorizationList(){const e=Pn(this,ce)||null;return null==e&&4===this.type?[]:e}set authorizationList(e){Bn(this,ce,null==e?null:e.map((e=>Ef(e))))}get maxFeePerBlobGas(){const e=Pn(this,se);return null==e&&3===this.type?Sf:e}set maxFeePerBlobGas(e){Bn(this,se,null==e?null:yc(e,"maxFeePerBlobGas"))}get blobVersionedHashes(){let e=Pn(this,ie);return null==e&&3===this.type?[]:e}set blobVersionedHashes(e){if(null!=e){$a(Array.isArray(e),"blobVersionedHashes must be an Array","value",e),e=e.slice();for(let t=0;t<e.length;t++)$a(nc(e[t],32),"invalid blobVersionedHash",`value[${t}]`,e[t])}Bn(this,ie,e)}get blobs(){return null==Pn(this,ae)?null:Pn(this,ae).map((e=>Object.assign({},e)))}set blobs(e){if(null==e)return void Bn(this,ae,null);const t=[],n=[];for(let r=0;r<e.length;r++){const s=e[r];if(rc(s)){Ka(Pn(this,oe),"adding a raw blob requires a KZG library","UNSUPPORTED_OPERATION",{operation:"set blobs()"});let e=ec(s);if($a(e.length<=Nf,"blob is too large",`blobs[${r}]`,s),e.length!==Nf){const t=new Uint8Array(Nf);t.set(e),e=t}const i=Pn(this,oe).blobToKzgCommitment(e),o=ic(Pn(this,oe).computeBlobKzgProof(e,i));t.push({data:ic(e),commitment:ic(i),proof:o}),n.push(Df(1,i))}else{const e=ic(s.data),r=ic(s.commitment),i=ic(s.proof);t.push({data:e,commitment:r,proof:i}),n.push(Df(1,r))}}Bn(this,ae,t),Bn(this,ie,n)}get kzg(){return Pn(this,oe)}set kzg(e){Bn(this,oe,null==e?null:function(e){return{blobToKzgCommitment:t=>{if("computeBlobProof"in e){if("blobToKzgCommitment"in e&&"function"==typeof e.blobToKzgCommitment)return ec(e.blobToKzgCommitment(ic(t)))}else if("blobToKzgCommitment"in e&&"function"==typeof e.blobToKzgCommitment)return ec(e.blobToKzgCommitment(t));if("blobToKZGCommitment"in e&&"function"==typeof e.blobToKZGCommitment)return ec(e.blobToKZGCommitment(ic(t)));$a(!1,"unsupported KZG library","kzg",e)},computeBlobKzgProof:(t,n)=>"computeBlobProof"in e&&"function"==typeof e.computeBlobProof?ec(e.computeBlobProof(ic(t),ic(n))):"computeBlobKzgProof"in e&&"function"==typeof e.computeBlobKzgProof?e.computeBlobKzgProof(t,n):"computeBlobKZGProof"in e&&"function"==typeof e.computeBlobKZGProof?ec(e.computeBlobKZGProof(ic(t),ic(n))):void $a(!1,"unsupported KZG library","kzg",e)}}(e))}get blobWrapperVersion(){return Pn(this,le)}set blobWrapperVersion(e){Bn(this,le,e)}get hash(){return null==this.signature?null:Bu(Ln(this,ue,he).call(this,!0,!1))}get unsignedHash(){return Bu(this.unsignedSerialized)}get from(){return null==this.signature?null:(e=this.unsignedHash,t=this.signature.getCanonical(),kf(Hd.recoverPublicKey(e,t)));var e,t}get fromPublicKey(){return null==this.signature?null:Hd.recoverPublicKey(this.unsignedHash,this.signature.getCanonical())}isSigned(){return null!=this.signature}get serialized(){return Ln(this,ue,he).call(this,!0,!0)}get unsignedSerialized(){return Ln(this,ue,he).call(this,!1,!1)}inferType(){const e=this.inferTypes();return e.indexOf(2)>=0?2:e.pop()}inferTypes(){const e=null!=this.gasPrice,t=null!=this.maxFeePerGas||null!=this.maxPriorityFeePerGas,n=null!=this.accessList,r=null!=Pn(this,se)||Pn(this,ie);null!=this.maxFeePerGas&&null!=this.maxPriorityFeePerGas&&Ka(this.maxFeePerGas>=this.maxPriorityFeePerGas,"priorityFee cannot be more than maxFee","BAD_DATA",{value:this}),Ka(!t||0!==this.type&&1!==this.type,"transaction type cannot have maxFeePerGas or maxPriorityFeePerGas","BAD_DATA",{value:this}),Ka(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):t?s.push(2):e?(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 e.from(this)}toJSON(){const e=e=>null==e?null:e.toString();return{type:this.type,to:this.to,data:this.data,nonce:this.nonce,gasLimit:e(this.gasLimit),gasPrice:e(this.gasPrice),maxPriorityFeePerGas:e(this.maxPriorityFeePerGas),maxFeePerGas:e(this.maxFeePerGas),value:e(this.value),chainId:e(this.chainId),sig:this.signature?this.signature.toJSON():null,accessList:this.accessList}}[xf](){return this.toString()}toString(){const e=[],t=t=>{let n=this[t];"string"==typeof n&&(n=JSON.stringify(n)),e.push(`${t}: ${n}`)};this.type&&t("type"),t("to"),t("data"),t("nonce"),t("gasLimit"),t("value"),null!=this.chainId&&t("chainId"),this.signature&&(t("from"),e.push(`signature: ${this.signature.toString()}`));const n=this.authorizationList;if(n){const t=[];for(const e of n){const n=[];n.push(`address: ${JSON.stringify(e.address)}`),null!=e.nonce&&n.push(`nonce: ${e.nonce}`),null!=e.chainId&&n.push(`chainId: ${e.chainId}`),e.signature&&n.push(`signature: ${e.signature.toString()}`),t.push(`Authorization { ${n.join(", ")} }`)}e.push(`authorizations: [ ${t.join(", ")} ]`)}return`Transaction { ${e.join(", ")} }`}static from(t){if(null==t)return new e;if("string"==typeof t){const n=ec(t);if(n[0]>=127)return e.from(function(e){const t=nl(e);$a(Array.isArray(t)&&(9===t.length||6===t.length),"invalid field count for legacy transaction","data",e);const n={type:0,nonce:Mf(t[0],"nonce"),gasPrice:Ff(t[1],"gasPrice"),gasLimit:Ff(t[2],"gasLimit"),to:Bf(t[3]),value:Ff(t[4],"value"),data:ic(t[5]),chainId:Sf};if(6===t.length)return n;const r=Ff(t[6],"v"),s=Ff(t[7],"r"),i=Ff(t[8],"s");if(s===Sf&&i===Sf)n.chainId=r;else{let e=(r-Cf)/Tf;e<Sf&&(e=Sf),n.chainId=e,$a(e!==Sf||r===Rf||r===If,"non-canonical legacy v","v",t[6]),n.signature=Gd.from({r:uc(t[7],32),s:uc(t[8],32),v:r})}return n}(n));switch(n[0]){case 1:return e.from(function(e){const t=nl(ec(e).slice(1));$a(Array.isArray(t)&&(8===t.length||11===t.length),"invalid field count for transaction type: 1","data",ic(e));const n={type:1,chainId:Ff(t[0],"chainId"),nonce:Mf(t[1],"nonce"),gasPrice:Ff(t[2],"gasPrice"),gasLimit:Ff(t[3],"gasLimit"),to:Bf(t[4]),value:Ff(t[5],"value"),data:ic(t[6]),accessList:Uf(t[7],"accessList")};return 8===t.length||Vf(n,t.slice(8)),n}(n));case 2:return e.from(function(e){const t=nl(ec(e).slice(1));$a(Array.isArray(t)&&(9===t.length||12===t.length),"invalid field count for transaction type: 2","data",ic(e));const n={type:2,chainId:Ff(t[0],"chainId"),nonce:Mf(t[1],"nonce"),maxPriorityFeePerGas:Ff(t[2],"maxPriorityFeePerGas"),maxFeePerGas:Ff(t[3],"maxFeePerGas"),gasPrice:null,gasLimit:Ff(t[4],"gasLimit"),to:Bf(t[5]),value:Ff(t[6],"value"),data:ic(t[7]),accessList:Uf(t[8],"accessList")};return 9===t.length||Vf(n,t.slice(9)),n}(n));case 3:return e.from(function(e){let t=nl(ec(e).slice(1)),n="3",r=null,s=null;if(4===t.length&&Array.isArray(t[0])){n="3 (network format)";const e=t[1],r=t[2],i=t[3];$a(Array.isArray(e),"invalid network format: blobs not an array","fields[1]",e),$a(Array.isArray(r),"invalid network format: commitments not an array","fields[2]",r),$a(Array.isArray(i),"invalid network format: proofs not an array","fields[3]",i),$a(e.length===r.length,"invalid network format: blobs/commitments length mismatch","fields",t),$a(e.length===i.length,"invalid network format: blobs/proofs length mismatch","fields",t),s=[];for(let n=0;n<t[1].length;n++)s.push({data:e[n],commitment:r[n],proof:i[n]});t=t[0]}else if(5===t.length&&Array.isArray(t[0])){n="3 (EIP-7594 network format)",r=Ac(t[1]);const e=t[2],i=t[3],o=t[4];$a(1===r,`unsupported EIP-7594 network format version: ${r}`,"fields[1]",r),$a(Array.isArray(e),"invalid EIP-7594 network format: blobs not an array","fields[2]",e),$a(Array.isArray(i),"invalid EIP-7594 network format: commitments not an array","fields[3]",i),$a(Array.isArray(o),"invalid EIP-7594 network format: proofs not an array","fields[4]",o),$a(e.length===i.length,"invalid network format: blobs/commitments length mismatch","fields",t),$a(e.length*Pf===o.length,"invalid network format: blobs/proofs length mismatch","fields",t),s=[];for(let t=0;t<e.length;t++){const n=[];for(let e=0;e<Pf;e++)n.push(o[t*Pf+e]);s.push({data:e[t],commitment:i[t],proof:oc(n)})}t=t[0]}$a(Array.isArray(t)&&(11===t.length||14===t.length),`invalid field count for transaction type: ${n}`,"data",ic(e));const i={type:3,chainId:Ff(t[0],"chainId"),nonce:Mf(t[1],"nonce"),maxPriorityFeePerGas:Ff(t[2],"maxPriorityFeePerGas"),maxFeePerGas:Ff(t[3],"maxFeePerGas"),gasPrice:null,gasLimit:Ff(t[4],"gasLimit"),to:Bf(t[5]),value:Ff(t[6],"value"),data:ic(t[7]),accessList:Uf(t[8],"accessList"),maxFeePerBlobGas:Ff(t[9],"maxFeePerBlobGas"),blobVersionedHashes:t[10],blobWrapperVersion:r};s&&(i.blobs=s),$a(null!=i.to,`invalid address for transaction type: ${n}`,"data",e),$a(Array.isArray(i.blobVersionedHashes),"invalid blobVersionedHashes: must be an array","data",e);for(let o=0;o<i.blobVersionedHashes.length;o++)$a(nc(i.blobVersionedHashes[o],32),`invalid blobVersionedHash at index ${o}: must be length 32`,"data",e);return 11===t.length||Vf(i,t.slice(11)),i}(n));case 4:return e.from(function(e){const t=nl(ec(e).slice(1));$a(Array.isArray(t)&&(10===t.length||13===t.length),"invalid field count for transaction type: 4","data",ic(e));const n={type:4,chainId:Ff(t[0],"chainId"),nonce:Mf(t[1],"nonce"),maxPriorityFeePerGas:Ff(t[2],"maxPriorityFeePerGas"),maxFeePerGas:Ff(t[3],"maxFeePerGas"),gasPrice:null,gasLimit:Ff(t[4],"gasLimit"),to:Bf(t[5]),value:Ff(t[6],"value"),data:ic(t[7]),accessList:Uf(t[8],"accessList"),authorizationList:Lf(t[9],"authorizationList")};return 10===t.length||Vf(n,t.slice(10)),n}(n))}Ka(!1,"unsupported transaction type","UNSUPPORTED_OPERATION",{operation:"from"})}const n=new e;return null!=t.type&&(n.type=t.type),null!=t.to&&(n.to=t.to),null!=t.nonce&&(n.nonce=t.nonce),null!=t.gasLimit&&(n.gasLimit=t.gasLimit),null!=t.gasPrice&&(n.gasPrice=t.gasPrice),null!=t.maxPriorityFeePerGas&&(n.maxPriorityFeePerGas=t.maxPriorityFeePerGas),null!=t.maxFeePerGas&&(n.maxFeePerGas=t.maxFeePerGas),null!=t.maxFeePerBlobGas&&(n.maxFeePerBlobGas=t.maxFeePerBlobGas),null!=t.data&&(n.data=t.data),null!=t.value&&(n.value=t.value),null!=t.chainId&&(n.chainId=t.chainId),null!=t.signature&&(n.signature=Gd.from(t.signature)),null!=t.accessList&&(n.accessList=t.accessList),null!=t.authorizationList&&(n.authorizationList=t.authorizationList),null!=t.blobVersionedHashes&&(n.blobVersionedHashes=t.blobVersionedHashes),null!=t.kzg&&(n.kzg=t.kzg),null!=t.blobWrapperVersion&&(n.blobWrapperVersion=t.blobWrapperVersion),null!=t.blobs&&(n.blobs=t.blobs),null!=t.hash&&($a(n.isSigned(),"unsigned transaction cannot define '.hash'","tx",t),$a(n.hash===t.hash,"hash mismatch","tx",t)),null!=t.from&&($a(n.isSigned(),"unsigned transaction cannot define '.from'","tx",t),$a(n.from.toLowerCase()===(t.from||"").toLowerCase(),"from mismatch","tx",t)),n}};function Wf(e){return Bu(Dc(e))}const zf=new Map([[8217,"apostrophe"],[8260,"fraction slash"],[12539,"middle dot"]]);function Kf(e){return function(e){let t=0;return()=>e[t++]}(function(e){let t=0;function n(){return e[t++]<<8|e[t++]}let r=n(),s=1,i=[0,1];for(let _=1;_<r;_++)i.push(s+=n());let o=n(),a=t;t+=o;let c=0,l=0;function u(){return 0==c&&(l=l<<8|e[t++],c=8),l>>--c&1}const h=2**31,d=h>>>1,f=d>>1,p=h-1;let g=0;for(let _=0;_<31;_++)g=g<<1|u();let m=[],y=0,w=h;for(;;){let e=Math.floor(((g-y+1)*s-1)/w),t=0,n=r;for(;n-t>1;){let r=t+n>>>1;e<i[r]?n=r:t=r}if(0==t)break;m.push(t);let o=y+Math.floor(w*i[t]/s),a=y+Math.floor(w*i[t+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((t=>{switch(t-b){case 3:return b+65792+(e[a++]<<16|e[a++]<<8|e[a++]);case 2:return b+256+(e[a++]<<8|e[a++]);case 1:return b+e[a++];default:return t-1}}))}(function(e){let t=[];[..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"].forEach(((e,n)=>t[e.charCodeAt(0)]=n));let n=e.length,r=new Uint8Array(6*n>>3);for(let s=0,i=0,o=0,a=0;s<n;s++)a=a<<6|t[e.charCodeAt(s)],o+=6,o>=8&&(r[i++]=a>>(o-=8));return r}(e)))}function $f(e){return 1&e?~e>>1:e>>1}function Qf(e,t){let n=Array(e);for(let r=0,s=0;r<e;r++)n[r]=s+=$f(t());return n}function Jf(e,t=0){let n=[];for(;;){let r=e(),s=e();if(!s)break;t+=r;for(let e=0;e<s;e++)n.push(t+e);t+=s+1}return n}function Yf(e){return Xf((()=>{let t=Jf(e);if(t.length)return t}))}function Zf(e){let t=[];for(;;){let n=e();if(0==n)break;t.push(tp(n,e))}for(;;){let n=e()-1;if(n<0)break;t.push(np(n,e))}return t.flat()}function Xf(e){let t=[];for(;;){let n=e(t.length);if(!n)break;t.push(n)}return t}function ep(e,t,n){let r=Array(e).fill().map((()=>[]));for(let s=0;s<t;s++)Qf(e,n).forEach(((e,t)=>r[t].push(e)));return r}function tp(e,t){let n=1+t(),r=t(),s=Xf(t);return ep(s.length,1+e,t).flatMap(((e,t)=>{let[i,...o]=e;return Array(s[t]).fill().map(((e,t)=>{let s=t*r;return[i+t*n,o.map((e=>e+s))]}))}))}function np(e,t){return ep(1+t(),1+e,t).map((e=>[e[0],e.slice(1)]))}function rp(e){return`{${function(e){return e.toString(16).toUpperCase().padStart(2,"0")}(e)}}`}function sp(e){let t=e.length;if(t<4096)return String.fromCodePoint(...e);let n=[];for(let r=0;r<t;)n.push(String.fromCodePoint(...e.slice(r,r+=4096)));return n.join("")}function ip(e,t){let n=e.length,r=n-t.length;for(let s=0;0==r&&s<n;s++)r=e[s]-t[s];return r}const op=44032,ap=4352,cp=4449,lp=4519,up=28,hp=588;function dp(e){return e>>24&255}function fp(e){return 16777215&e}let pp,gp,mp,yp;function wp(e){return e>=op&&e<55204}function bp(e,t){if(e>=ap&&e<4371&&t>=cp&&t<4470)return op+(e-ap)*hp+(t-cp)*up;if(wp(e)&&t>lp&&t<4547&&(e-op)%up==0)return e+(t-lp);{let n=yp.get(e);return n&&(n=n.get(t),n)?n:-1}}function _p(e){pp||function(){let e=Kf("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");pp=new Map(Yf(e).flatMap(((e,t)=>e.map((e=>[e,t+1<<24]))))),gp=new Set(Jf(e)),mp=new Map,yp=new Map;for(let[t,n]of Zf(e)){if(!gp.has(t)&&2==n.length){let[e,r]=n,s=yp.get(e);s||(s=new Map,yp.set(e,s)),s.set(r,t)}mp.set(t,n.reverse())}}();let t=[],n=[],r=!1;function s(e){let n=pp.get(e);n&&(r=!0,e|=n),t.push(e)}for(let i of e)for(;;){if(i<128)t.push(i);else if(wp(i)){let e=i-op,t=e%hp/up|0,n=e%up;s(ap+(e/hp|0)),s(cp+t),n>0&&s(lp+n)}else{let e=mp.get(i);e?n.push(...e):s(i)}if(!n.length)break;i=n.pop()}if(r&&t.length>1){let e=dp(t[0]);for(let n=1;n<t.length;n++){let r=dp(t[n]);if(0==r||e<=r){e=r;continue}let s=n-1;for(;;){let n=t[s+1];if(t[s+1]=t[s],t[s]=n,!s)break;if(e=dp(t[--s]),e<=r)break}e=dp(t[n])}}return t}function Ap(e){return _p(e).map(fp)}function vp(e){return function(e){let t=[],n=[],r=-1,s=0;for(let i of e){let e=dp(i),o=fp(i);if(-1==r)0==e?r=o:t.push(o);else if(s>0&&s>=e)0==e?(t.push(r,...n),n.length=0,r=o):n.push(o),s=e;else{let i=bp(r,o);i>=0?r=i:0==s&&0==e?(t.push(r),r=o):(n.push(o),s=e)}}return r>=0&&t.push(r,...n),t}(_p(e))}const Ep=".",kp=e=>Array.from(e);function Sp(e,t){return e.P.has(t)||e.Q.has(t)}class Tp extends Array{get is_emoji(){return!0}}let Rp,Ip,Cp,Op,xp,Np,Pp,Dp,Bp,Up,Lp;function Mp(){if(Rp)return;let e=Kf("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");const t=()=>Jf(e),n=()=>new Set(t()),r=(e,t)=>t.forEach((t=>e.add(t)));Rp=new Map(Zf(e)),Ip=n(),Cp=t(),Op=new Set(t().map((e=>Cp[e]))),Cp=new Set(Cp),xp=n(),n();let s=Yf(e),i=e();const o=()=>{let e=new Set;return t().forEach((t=>r(e,s[t]))),r(e,t()),e};Np=Xf((t=>{let n=Xf(e).map((e=>e+96));if(n.length){let r=t>=i;return n[0]-=32,n=sp(n),r&&(n=`Restricted[${n}]`),{N:n,P:o(),Q:o(),M:!e(),R:r}}})),Pp=n(),Dp=new Map;let a=t().concat(kp(Pp)).sort(((e,t)=>e-t));a.forEach(((t,n)=>{let r=e(),s=a[n]=r?a[n-r]:{V:[],M:new Map};s.V.push(t),Pp.has(t)||Dp.set(t,s)}));for(let{V:u,M:h}of new Set(Dp.values())){let e=[];for(let n of u){let t=Np.filter((e=>Sp(e,n))),s=e.find((({G:e})=>t.some((t=>e.has(t)))));s||(s={G:new Set,V:[]},e.push(s)),s.V.push(n),r(s.G,t)}let t=e.flatMap((e=>kp(e.G)));for(let{G:n,V:r}of e){let e=new Set(t.filter((e=>!n.has(e))));for(let t of r)h.set(t,e)}}Bp=new Set;let c=new Set;const l=e=>Bp.has(e)?c.add(e):Bp.add(e);for(let u of Np){for(let e of u.P)l(e);for(let e of u.Q)l(e)}for(let u of Bp)Dp.has(u)||c.has(u)||Dp.set(u,1);r(Bp,Ap(Bp)),Up=function(e){let t=[],n=Jf(e);return function e({S:n,B:r},s,i){if(!(4&n&&i===s[s.length-1])){2&n&&(i=s[s.length-1]),1&n&&t.push(s);for(let t of r)for(let n of t.Q)e(t,[...s,n],i)}}(function t(r){return{S:e(),B:Xf((()=>{let r=Jf(e).map((e=>n[e]));if(r.length)return t(r)})),Q:r}}([]),[]),t}(e).map((e=>Tp.from(e))).sort(ip),Lp=new Map;for(let u of Up){let e=[Lp];for(let t of u){let n=e.map((e=>{let n=e.get(t);return n||(n=new Map,e.set(t,n)),n}));65039===t?e.push(...n):e=n}for(let t of e)t.V=u}}function Fp(e){return(Hp(e)?"":`${jp(Gp([e]))} `)+rp(e)}function jp(e){return`"${e}"`}function Gp(e,t=1/0,n=rp){let r=[];var s,i;s=e[0],Mp(),(i?Op.has(s):Cp.has(s))&&r.push("◌"),e.length>t&&(t>>=1,e=[...e.slice(0,t),8230,...e.slice(-t)]);let o=0,a=e.length;for(let c=0;c<a;c++){let t=e[c];Hp(t)&&(r.push(sp(e.slice(o,c))),r.push(n(t)),o=c+1)}return r.push(sp(e.slice(o,a))),r.join("")}function Hp(e){return Mp(),xp.has(e)}function Vp(e){return t=function(e,t,n){if(!e)return[];Mp();let r=0;return e.split(Ep).map((e=>{let s=function(e){let t=[];for(let n=0,r=e.length;n<r;){let r=e.codePointAt(n);n+=r<65536?1:2,t.push(r)}return t}(e),i={input:s,offset:r};r+=s.length+1;try{let e,r=i.tokens=function(e,t,n){let r=[],s=[];for(e=e.slice().reverse();e.length;){let i=$p(e);if(i)s.length&&(r.push(t(s)),s=[]),r.push(n(i));else{let t=e.pop();if(Bp.has(t))s.push(t);else{let e=Rp.get(t);if(e)s.push(...e);else if(!Ip.has(t))throw qp(t)}}}return s.length&&r.push(t(s)),r}(s,t,n),o=r.length;if(!o)throw new Error("empty label");let a=i.output=r.flat();if(function(e){for(let t=e.lastIndexOf(95);t>0;)if(95!==e[--t])throw new Error("underscore allowed only at start")}(a),!(i.emoji=o>1||r[0].is_emoji)&&a.every((e=>e<128)))!function(e){if(e.length>=4&&45==e[2]&&45==e[3])throw new Error(`invalid label extension: "${sp(e.slice(0,4))}"`)}(a),e="ASCII";else{let t=r.flatMap((e=>e.is_emoji?[]:e));if(t.length){if(Cp.has(a[0]))throw zp("leading combining mark");for(let e=1;e<o;e++){let t=r[e];if(!t.is_emoji&&Cp.has(t[0]))throw zp(`emoji + combining mark: "${sp(r[e-1])} + ${Gp([t[0]])}"`)}!function(e){let t=e[0],n=zf.get(t);if(n)throw zp(`leading ${n}`);let r=e.length,s=-1;for(let i=1;i<r;i++){t=e[i];let r=zf.get(t);if(r){if(s==i)throw zp(`${n} + ${r}`);s=i+1,n=r}}if(s==r)throw zp(`trailing ${n}`)}(a);let n=kp(new Set(t)),[s]=function(e){let t=Np;for(let n of e){let e=t.filter((e=>Sp(e,n)));if(!e.length)throw Np.some((e=>Sp(e,n)))?Wp(t[0],n):qp(n);if(t=e,1==e.length)break}return t}(n);!function(e,t){for(let n of t)if(!Sp(e,n))throw Wp(e,n);if(e.M){let e=Ap(t);for(let t=1,n=e.length;t<n;t++)if(Op.has(e[t])){let r=t+1;for(let s;r<n&&Op.has(s=e[r]);r++)for(let n=t;n<r;n++)if(e[n]==s)throw new Error(`duplicate non-spacing marks: ${Fp(s)}`);if(r-t>4)throw new Error(`excessive non-spacing marks: ${jp(Gp(e.slice(t-1,r)))} (${r-t}/4)`);t=r}}}(s,t),function(e,t){let n,r=[];for(let s of t){let e=Dp.get(s);if(1===e)return;if(e){let t=e.M.get(s);if(n=n?n.filter((e=>t.has(e))):kp(t),!n.length)return}else r.push(s)}if(n)for(let s of n)if(r.every((e=>Sp(s,e))))throw new Error(`whole-script confusable: ${e.N}/${s.N}`)}(s,n),e=s.N}else e="Emoji"}i.type=e}catch(o){i.error=o}return i}))}(e,vp,Kp),t.map((({input:e,error:n,output:r})=>{if(n){let r=n.message;throw new Error(1==t.length?r:`Invalid label ${jp(Gp(e,63))}: ${r}`)}return sp(r)})).join(Ep);var t}function qp(e){return new Error(`disallowed character: ${Fp(e)}`)}function Wp(e,t){let n=Fp(t),r=Np.find((e=>e.P.has(t)));return r&&(n=`${r.N} ${n}`),new Error(`illegal mixture: ${e.N} + ${n}`)}function zp(e){return new Error(`illegal placement: ${e}`)}function Kp(e){return e.filter((e=>65039!=e))}function $p(e,t){let n,r=Lp,s=e.length;for(;s&&(r=r.get(e[--s]),r);){let{V:i}=r;i&&(n=i,t&&t.push(...e.slice(s).reverse()),e.length=s)}return n}const Qp=new Uint8Array(32);function Jp(e){return $a(0!==e.length,"invalid ENS name; empty component","comp",e),e}function Yp(e){const t=Dc(Zp(e)),n=[];if(0===e.length)return n;let r=0;for(let s=0;s<t.length;s++){46===t[s]&&(n.push(Jp(t.slice(r,s))),r=s+1)}return $a(r<t.length,"invalid ENS name; empty component","name",e),n.push(Jp(t.slice(r))),n}function Zp(e){try{if(0===e.length)throw new Error("empty label");return Vp(e)}catch(t){$a(!1,`invalid ENS name (${t.message})`,"name",e)}}function Xp(e){try{return 0!==Yp(e).length}catch(t){}return!1}function eg(e){$a("string"==typeof e,"invalid ENS name; not a string","name",e),$a(e.length,"invalid ENS name (empty label)","name",e);let t=Qp;const n=Yp(e);for(;n.length;)t=Bu(oc([t,Bu(n.pop())]));return ic(t)}function tg(e,t){const n=null!=t?t:63;return $a(n<=255,"DNS encoded label cannot exceed 255","length",n),ic(oc(Yp(e).map((t=>{$a(t.length<=n,`label ${JSON.stringify(e)} exceeds ${n} bytes`,"name",e);const r=new Uint8Array(t.length+1);return r.set(t,1),r[0]=r.length-1,r}))))+"00"}Qp.fill(0);const ng=new Uint8Array(32);ng.fill(0);const rg=BigInt(-1),sg=BigInt(0),ig=BigInt(1),og=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");const ag=vc(ig,32),cg=vc(sg,32),lg={name:"string",version:"string",chainId:"uint256",verifyingContract:"address",salt:"bytes32"},ug=["name","version","chainId","verifyingContract","salt"];function hg(e){return function(t){return $a("string"==typeof t,`invalid domain value for ${JSON.stringify(e)}`,`domain.${e}`,t),t}}const dg={name:hg("name"),version:hg("version"),chainId:function(e){const t=yc(e,"domain.chainId");return $a(t>=0,"invalid chain ID","domain.chainId",e),Number.isSafeInteger(t)?Number(t):kc(t)},verifyingContract:function(e){try{return $d(e).toLowerCase()}catch(t){}$a(!1,'invalid domain value "verifyingContract"',"domain.verifyingContract",e)},salt:function(e){const t=ec(e,"domain.salt");return $a(32===t.length,'invalid domain value "salt"',"domain.salt",e),ic(t)}};function fg(e){{const t=e.match(/^(u?)int(\d+)$/);if(t){const n=""===t[1],r=parseInt(t[2]);$a(r%8==0&&0!==r&&r<=256&&t[2]===String(r),"invalid numeric width","type",e);const s=mc(og,n?r-1:r),i=n?(s+ig)*rg:sg;return function(t){const r=yc(t,"value");return $a(r>=i&&r<=s,`value out-of-bounds for ${e}`,"value",r),vc(n?gc(r,256):r,32)}}}{const t=e.match(/^bytes(\d+)$/);if(t){const n=parseInt(t[1]);return $a(0!==n&&n<=32&&t[1]===String(n),"invalid bytes width","type",e),function(t){return $a(ec(t).length===n,`invalid length for ${e}`,"value",t),function(e){const t=ec(e),n=t.length%32;return n?oc([t,ng.slice(n)]):ic(t)}(t)}}}switch(e){case"address":return function(e){return uc($d(e),32)};case"bool":return function(e){return e?ag:cg};case"bytes":return function(e){return Bu(e)};case"string":return function(e){return Wf(e)}}return null}function pg(e,t){return`${e}(${t.map((({name:e,type:t})=>t+" "+e)).join(",")})`}function gg(e){const t=e.match(/^([^\x5b]*)((\x5b\d*\x5d)*)(\x5b(\d*)\x5d)$/);return t?{base:t[1],index:t[2]+t[4],array:{base:t[1],prefix:t[1]+t[2],count:t[5]?parseInt(t[5]):-1}}:{base:e}}de=new WeakMap,fe=new WeakMap,pe=new WeakMap,ge=new WeakSet,me=function(e){{const t=fg(e);if(t)return t}const t=gg(e).array;if(t){const e=t.prefix,n=this.getEncoder(e);return r=>{$a(-1===t.count||t.count===r.length,`array length mismatch; expected length ${t.count}`,"value",r);let s=r.map(n);return Pn(this,fe).has(e)&&(s=s.map(Bu)),Bu(oc(s))}}const n=this.types[e];if(n){const t=Wf(Pn(this,fe).get(e));return e=>{const r=n.map((({name:t,type:n})=>{const r=this.getEncoder(n)(e[t]);return Pn(this,fe).has(n)?Bu(r):r}));return r.unshift(t),oc(r)}}$a(!1,`unknown type: ${e}`,"type",e)};let mg=class e{constructor(e){Dn(this,ge),xn(this,"primaryType"),Dn(this,de,void 0),Dn(this,fe,void 0),Dn(this,pe,void 0),Bn(this,fe,new Map),Bn(this,pe,new Map);const t=new Map,n=new Map,r=new Map,s={};Object.keys(e).forEach((i=>{s[i]=e[i].map((({name:t,type:n})=>{let{base:r,index:s}=gg(n);return"int"!==r||e.int||(r="int256"),"uint"!==r||e.uint||(r="uint256"),{name:t,type:r+(s||"")}})),t.set(i,new Set),n.set(i,[]),r.set(i,new Set)})),Bn(this,de,JSON.stringify(s));for(const o in s){const r=new Set;for(const i of s[o]){$a(!r.has(i.name),`duplicate variable name ${JSON.stringify(i.name)} in ${JSON.stringify(o)}`,"types",e),r.add(i.name);const s=gg(i.type).base;$a(s!==o,`circular type reference to ${JSON.stringify(s)}`,"types",e);fg(s)||($a(n.has(s),`unknown type ${JSON.stringify(s)}`,"types",e),n.get(s).push(o),t.get(o).add(s))}}const i=Array.from(n.keys()).filter((e=>0===n.get(e).length));$a(0!==i.length,"missing primary type","types",e),$a(1===i.length,`ambiguous primary types or unused types: ${i.map((e=>JSON.stringify(e))).join(", ")}`,"types",e),Ha(this,{primaryType:i[0]}),function s(i,o){$a(!o.has(i),`circular type reference to ${JSON.stringify(i)}`,"types",e),o.add(i);for(const e of t.get(i))if(n.has(e)){s(e,o);for(const t of o)r.get(t).add(e)}o.delete(i)}(this.primaryType,new Set);for(const[o,a]of r){const e=Array.from(a);e.sort(),Pn(this,fe).set(o,pg(o,s[o])+e.map((e=>pg(e,s[e]))).join(""))}}get types(){return JSON.parse(Pn(this,de))}getEncoder(e){let t=Pn(this,pe).get(e);return t||(t=Ln(this,ge,me).call(this,e),Pn(this,pe).set(e,t)),t}encodeType(e){const t=Pn(this,fe).get(e);return $a(t,`unknown type: ${JSON.stringify(e)}`,"name",e),t}encodeData(e,t){return this.getEncoder(e)(t)}hashStruct(e,t){return Bu(this.encodeData(e,t))}encode(e){return this.encodeData(this.primaryType,e)}hash(e){return this.hashStruct(this.primaryType,e)}_visit(e,t,n){if(fg(e))return n(e,t);const r=gg(e).array;if(r)return $a(-1===r.count||r.count===t.length,`array length mismatch; expected length ${r.count}`,"value",t),t.map((e=>this._visit(r.prefix,e,n)));const s=this.types[e];if(s)return s.reduce(((e,{name:r,type:s})=>(e[r]=this._visit(s,t[r],n),e)),{});$a(!1,`unknown type: ${e}`,"type",e)}visit(e,t){return this._visit(this.primaryType,e,t)}static from(t){return new e(t)}static getPrimaryType(t){return e.from(t).primaryType}static hashStruct(t,n,r){return e.from(n).hashStruct(t,r)}static hashDomain(t){const n=[];for(const e in t){if(null==t[e])continue;const r=lg[e];$a(r,`invalid typed-data domain key: ${JSON.stringify(e)}`,"domain",t),n.push({name:e,type:r})}return n.sort(((e,t)=>ug.indexOf(e.name)-ug.indexOf(t.name))),e.hashStruct("EIP712Domain",{EIP712Domain:n},t)}static encode(t,n,r){return oc(["0x1901",e.hashDomain(t),e.from(n).hash(r)])}static hash(t,n,r){return Bu(e.encode(t,n,r))}static async resolveNames(t,n,r,s){t=Object.assign({},t);for(const e in t)null==t[e]&&delete t[e];const i={};t.verifyingContract&&!nc(t.verifyingContract,20)&&(i[t.verifyingContract]="0x");const o=e.from(n);o.visit(r,((e,t)=>("address"!==e||nc(t,20)||(i[t]="0x"),t)));for(const e in i)i[e]=await s(e);return t.verifyingContract&&i[t.verifyingContract]&&(t.verifyingContract=i[t.verifyingContract]),{domain:t,value:r=o.visit(r,((e,t)=>"address"===e&&i[t]?i[t]:t))}}static getPayload(t,n,r){e.hashDomain(t);const s={},i=[];ug.forEach((e=>{const n=t[e];null!=n&&(s[e]=dg[e](n),i.push({name:e,type:lg[e]}))}));const o=e.from(n);n=o.types;const a=Object.assign({},n);return $a(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,((e,t)=>{if(e.match(/^bytes(\d*)/))return ic(ec(t));if(e.match(/^u?int/))return yc(t).toString();switch(e){case"address":return t.toLowerCase();case"bool":return!!t;case"string":return $a("string"==typeof t,"invalid string","value",t),t}$a(!1,"unsupported type","type",e)}))}}};function yg(e){const t=new Set;return e.forEach((e=>t.add(e))),Object.freeze(t)}const wg=yg("external public payable override".split(" ")),bg="constant external internal payable private public pure view override",_g=yg(bg.split(" ")),Ag="constructor error event fallback function receive struct",vg=yg(Ag.split(" ")),Eg="calldata memory storage payable indexed",kg=yg(Eg.split(" ")),Sg=yg([Ag,Eg,"tuple returns",bg].join(" ").split(" ")),Tg={"(":"OPEN_PAREN",")":"CLOSE_PAREN","[":"OPEN_BRACKET","]":"CLOSE_BRACKET",",":"COMMA","@":"AT"},Rg=new RegExp("^(\\s*)"),Ig=new RegExp("^([0-9]+)"),Cg=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"),Og=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$"),xg=new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$"),Ng=class e{constructor(e){Dn(this,be),Dn(this,ye,void 0),Dn(this,we,void 0),Bn(this,ye,0),Bn(this,we,e.slice())}get offset(){return Pn(this,ye)}get length(){return Pn(this,we).length-Pn(this,ye)}clone(){return new e(Pn(this,we))}reset(){Bn(this,ye,0)}popKeyword(e){const t=this.peek();if("KEYWORD"!==t.type||!e.has(t.text))throw new Error(`expected keyword ${t.text}`);return this.pop().text}popType(e){if(this.peek().type!==e){const t=this.peek();throw new Error(`expected ${e}; got ${t.type} ${JSON.stringify(t.text)}`)}return this.pop().text}popParen(){const e=this.peek();if("OPEN_PAREN"!==e.type)throw new Error("bad start");const t=Ln(this,be,_e).call(this,Pn(this,ye)+1,e.match+1);return Bn(this,ye,e.match+1),t}popParams(){const e=this.peek();if("OPEN_PAREN"!==e.type)throw new Error("bad start");const t=[];for(;Pn(this,ye)<e.match-1;){const e=this.peek().linkNext;t.push(Ln(this,be,_e).call(this,Pn(this,ye)+1,e)),Bn(this,ye,e)}return Bn(this,ye,e.match+1),t}peek(){if(Pn(this,ye)>=Pn(this,we).length)throw new Error("out-of-bounds");return Pn(this,we)[Pn(this,ye)]}peekKeyword(e){const t=this.peekType("KEYWORD");return null!=t&&e.has(t)?t:null}peekType(e){if(0===this.length)return null;const t=this.peek();return t.type===e?t.text:null}pop(){const e=this.peek();return Un(this,ye)._++,e}toString(){const e=[];for(let t=Pn(this,ye);t<Pn(this,we).length;t++){const n=Pn(this,we)[t];e.push(`${n.type}:${n.text}`)}return`<TokenString ${e.join(" ")}>`}};ye=new WeakMap,we=new WeakMap,be=new WeakSet,_e=function(e=0,t=0){return new Ng(Pn(this,we).slice(e,t).map((t=>Object.freeze(Object.assign({},t,{match:t.match-e,linkBack:t.linkBack-e,linkNext:t.linkNext-e})))))};let Pg=Ng;function Dg(e){const t=[],n=t=>{const n=i<e.length?JSON.stringify(e[i]):"$EOI";throw new Error(`invalid token ${n} at ${i}: ${t}`)};let r=[],s=[],i=0;for(;i<e.length;){let o=e.substring(i),a=o.match(Rg);a&&(i+=a[1].length,o=e.substring(i));const c={depth:r.length,linkBack:-1,linkNext:-1,match:-1,type:"",text:"",offset:i,value:-1};t.push(c);let l=Tg[o[0]]||"";if(l){if(c.type=l,c.text=o[0],i++,"OPEN_PAREN"===l)r.push(t.length-1),s.push(t.length-1);else if("CLOSE_PAREN"==l)0===r.length&&n("no matching open bracket"),c.match=r.pop(),t[c.match].match=t.length-1,c.depth--,c.linkBack=s.pop(),t[c.linkBack].linkNext=t.length-1;else if("COMMA"===l)c.linkBack=s.pop(),t[c.linkBack].linkNext=t.length-1,s.push(t.length-1);else if("OPEN_BRACKET"===l)c.type="BRACKET";else if("CLOSE_BRACKET"===l){let e=t.pop().text;if(t.length>0&&"NUMBER"===t[t.length-1].type){const n=t.pop().text;e=n+e,t[t.length-1].value=Ac(n)}if(0===t.length||"BRACKET"!==t[t.length-1].type)throw new Error("missing opening bracket");t[t.length-1].text+=e}}else if(a=o.match(Cg),a){if(c.text=a[1],i+=c.text.length,Sg.has(c.text)){c.type="KEYWORD";continue}if(c.text.match(xg)){c.type="TYPE";continue}c.type="ID"}else{if(a=o.match(Ig),!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 Pg(t.map((e=>Object.freeze(e))))}function Bg(e,t){let n=[];for(const r in t.keys())e.has(r)&&n.push(r);if(n.length>1)throw new Error(`conflicting types: ${n.join(", ")}`)}function Ug(e,t){if(t.peekKeyword(vg)){const n=t.pop().text;if(n!==e)throw new Error(`expected ${e}, got ${n}`)}return t.popType("ID")}function Lg(e,t){const n=new Set;for(;;){const r=e.peekType("KEYWORD");if(null==r||t&&!t.has(r))break;if(e.pop(),n.has(r))throw new Error(`duplicate keywords: ${JSON.stringify(r)}`);n.add(r)}return Object.freeze(n)}function Mg(e){let t=Lg(e,_g);return Bg(t,yg("constant payable nonpayable".split(" "))),Bg(t,yg("pure view payable nonpayable".split(" "))),t.has("view")?"view":t.has("pure")?"pure":t.has("payable")?"payable":t.has("nonpayable")?"nonpayable":t.has("constant")?"view":"nonpayable"}function Fg(e,t){return e.popParams().map((e=>Xg.from(e,t)))}function jg(e){if(e.peekType("AT")){if(e.pop(),e.peekType("NUMBER"))return yc(e.pop().text);throw new Error("invalid gas")}return null}function Gg(e){if(e.length)throw new Error(`unexpected tokens at offset ${e.offset}: ${e.toString()}`)}const Hg=new RegExp(/^(.*)\[([0-9]*)\]$/);function Vg(e){const t=e.match(xg);if($a(t,"invalid type","type",e),"uint"===e)return"uint256";if("int"===e)return"int256";if(t[2]){const n=parseInt(t[2]);$a(0!==n&&n<=32,"invalid bytes length","type",e)}else if(t[3]){const n=parseInt(t[3]);$a(0!==n&&n<=256&&n%8==0,"invalid numeric width","type",e)}return e}const qg={},Wg=Symbol.for("_ethers_internal"),zg="_ParamTypeInternal",Kg="_ErrorInternal",$g="_EventInternal",Qg="_ConstructorInternal",Jg="_FallbackInternal",Yg="_FunctionInternal",Zg="_StructInternal";Ae=new WeakSet,ve=function(e,t,n,r){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 s=this.arrayChildren,i=t.slice();return i.forEach(((t,r)=>{var o;Ln(o=s,Ae,ve).call(o,e,t,n,(e=>{i[r]=e}))})),void r(i)}if(this.isTuple()){const s=this.components;let i;if(Array.isArray(t))i=t.slice();else{if(null==t||"object"!=typeof t)throw new Error("invalid tuple value");i=s.map((e=>{if(!e.name)throw new Error("cannot use object value with unnamed components");if(!(e.name in t))throw new Error(`missing value for component ${e.name}`);return t[e.name]}))}if(i.length!==this.components.length)throw new Error("array is wrong length");return i.forEach(((t,r)=>{var o;Ln(o=s[r],Ae,ve).call(o,e,t,n,(e=>{i[r]=e}))})),void r(i)}const s=n(this.type,t);s.then?e.push(async function(){r(await s)}()):r(s)};let Xg=class e{constructor(e,t,n,r,s,i,o,a){if(Dn(this,Ae),xn(this,"name"),xn(this,"type"),xn(this,"baseType"),xn(this,"indexed"),xn(this,"components"),xn(this,"arrayLength"),xn(this,"arrayChildren"),Za(e,qg,"ParamType"),Object.defineProperty(this,Wg,{value:zg}),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("");Ha(this,{name:t,type:n,baseType:r,indexed:s,components:i,arrayLength:o,arrayChildren:a})}format(e){if(null==e&&(e="sighash"),"json"===e){const t=this.name||"";if(this.isArray()){const e=JSON.parse(this.arrayChildren.format("json"));return e.name=t,e.type+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`,JSON.stringify(e)}const n={type:"tuple"===this.baseType?"tuple":this.type,name:t};return"boolean"==typeof this.indexed&&(n.indexed=this.indexed),this.isTuple()&&(n.components=this.components.map((t=>JSON.parse(t.format(e))))),JSON.stringify(n)}let t="";return this.isArray()?(t+=this.arrayChildren.format(e),t+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`):this.isTuple()?t+="("+this.components.map((t=>t.format(e))).join("full"===e?", ":",")+")":t+=this.type,"sighash"!==e&&(!0===this.indexed&&(t+=" indexed"),"full"===e&&this.name&&(t+=" "+this.name)),t}isArray(){return"array"===this.baseType}isTuple(){return"tuple"===this.baseType}isIndexable(){return null!=this.indexed}walk(e,t){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 n=this;return e.map((e=>n.arrayChildren.walk(e,t)))}if(this.isTuple()){if(!Array.isArray(e))throw new Error("invalid tuple value");if(e.length!==this.components.length)throw new Error("array is wrong length");const n=this;return e.map(((e,r)=>n.components[r].walk(e,t)))}return t(this.type,e)}async walkAsync(e,t){const n=[],r=[e];return Ln(this,Ae,ve).call(this,n,e,t,(e=>{r[0]=e})),n.length&&await Promise.all(n),r[0]}static from(t,n){if(e.isParamType(t))return t;if("string"==typeof t)try{return e.from(Dg(t),n)}catch(a){$a(!1,"invalid param type","obj",t)}else if(t instanceof Pg){let r="",s="",i=null;Lg(t,yg(["tuple"])).has("tuple")||t.peekType("OPEN_PAREN")?(s="tuple",i=t.popParams().map((t=>e.from(t))),r=`tuple(${i.map((e=>e.format())).join(",")})`):(r=Vg(t.popType("TYPE")),s=r);let o=null,a=null;for(;t.length&&t.peekType("BRACKET");){const n=t.pop();o=new e(qg,"",r,s,null,i,a,o),a=n.value,r+=n.text,s="array",i=null}let c=null;if(Lg(t,kg).has("indexed")){if(!n)throw new Error("");c=!0}const l=t.peekType("ID")?t.pop().text:"";if(t.length)throw new Error("leftover tokens");return new e(qg,l,r,s,c,i,a,o)}const r=t.name;$a(!r||"string"==typeof r&&r.match(Og),"invalid name","obj.name",r);let s=t.indexed;null!=s&&($a(n,"parameter cannot be indexed","obj.indexed",t.indexed),s=!!s);let i=t.type,o=i.match(Hg);if(o){const n=parseInt(o[2]||"-1"),a=e.from({type:o[1],components:t.components});return new e(qg,r||"",i,"array",s,null,n,a)}if("tuple"===i||i.startsWith("tuple(")||i.startsWith("(")){const n=null!=t.components?t.components.map((t=>e.from(t))):null;return new e(qg,r||"",i,"tuple",s,n,null,null)}return i=Vg(t.type),new e(qg,r||"",i,i,s,null,null,null)}static isParamType(e){return e&&e[Wg]===zg}};class em{constructor(e,t,n){xn(this,"type"),xn(this,"inputs"),Za(e,qg,"Fragment"),Ha(this,{type:t,inputs:n=Object.freeze(n.slice())})}static from(e){if("string"==typeof e){try{em.from(JSON.parse(e))}catch(t){}return em.from(Dg(e))}if(e instanceof Pg){switch(e.peekKeyword(vg)){case"constructor":return im.from(e);case"error":return rm.from(e);case"event":return sm.from(e);case"fallback":case"receive":return om.from(e);case"function":return am.from(e);case"struct":return cm.from(e)}}else if("object"==typeof e){switch(e.type){case"constructor":return im.from(e);case"error":return rm.from(e);case"event":return sm.from(e);case"fallback":case"receive":return om.from(e);case"function":return am.from(e);case"struct":return cm.from(e)}Ka(!1,`unsupported type: ${e.type}`,"UNSUPPORTED_OPERATION",{operation:"Fragment.from"})}$a(!1,"unsupported frgament object","obj",e)}static isConstructor(e){return im.isFragment(e)}static isError(e){return rm.isFragment(e)}static isEvent(e){return sm.isFragment(e)}static isFunction(e){return am.isFragment(e)}static isStruct(e){return cm.isFragment(e)}}class tm extends em{constructor(e,t,n,r){super(e,t,r),xn(this,"name"),$a("string"==typeof n&&n.match(Og),"invalid identifier","name",n),r=Object.freeze(r.slice()),Ha(this,{name:n})}}function nm(e,t){return"("+t.map((t=>t.format(e))).join("full"===e?", ":",")+")"}class rm extends tm{constructor(e,t,n){super(e,"error",t,n),Object.defineProperty(this,Wg,{value:Kg})}get selector(){return Wf(this.format("sighash")).substring(0,10)}format(e){if(null==e&&(e="sighash"),"json"===e)return JSON.stringify({type:"error",name:this.name,inputs:this.inputs.map((t=>JSON.parse(t.format(e))))});const t=[];return"sighash"!==e&&t.push("error"),t.push(this.name+nm(e,this.inputs)),t.join(" ")}static from(e){if(rm.isFragment(e))return e;if("string"==typeof e)return rm.from(Dg(e));if(e instanceof Pg){const t=Ug("error",e),n=Fg(e);return Gg(e),new rm(qg,t,n)}return new rm(qg,e.name,e.inputs?e.inputs.map(Xg.from):[])}static isFragment(e){return e&&e[Wg]===Kg}}class sm extends tm{constructor(e,t,n,r){super(e,"event",t,n),xn(this,"anonymous"),Object.defineProperty(this,Wg,{value:$g}),Ha(this,{anonymous:r})}get topicHash(){return Wf(this.format("sighash"))}format(e){if(null==e&&(e="sighash"),"json"===e)return JSON.stringify({type:"event",anonymous:this.anonymous,name:this.name,inputs:this.inputs.map((t=>JSON.parse(t.format(e))))});const t=[];return"sighash"!==e&&t.push("event"),t.push(this.name+nm(e,this.inputs)),"sighash"!==e&&this.anonymous&&t.push("anonymous"),t.join(" ")}static getTopicHash(e,t){t=(t||[]).map((e=>Xg.from(e)));return new sm(qg,e,t,!1).topicHash}static from(e){if(sm.isFragment(e))return e;if("string"==typeof e)try{return sm.from(Dg(e))}catch(t){$a(!1,"invalid event fragment","obj",e)}else if(e instanceof Pg){const t=Ug("event",e),n=Fg(e,!0),r=!!Lg(e,yg(["anonymous"])).has("anonymous");return Gg(e),new sm(qg,t,n,r)}return new sm(qg,e.name,e.inputs?e.inputs.map((e=>Xg.from(e,!0))):[],!!e.anonymous)}static isFragment(e){return e&&e[Wg]===$g}}class im extends em{constructor(e,t,n,r,s){super(e,t,n),xn(this,"payable"),xn(this,"gas"),Object.defineProperty(this,Wg,{value:Qg}),Ha(this,{payable:r,gas:s})}format(e){if(Ka(null!=e&&"sighash"!==e,"cannot format a constructor for sighash","UNSUPPORTED_OPERATION",{operation:"format(sighash)"}),"json"===e)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((t=>JSON.parse(t.format(e))))});const t=[`constructor${nm(e,this.inputs)}`];return this.payable&&t.push("payable"),null!=this.gas&&t.push(`@${this.gas.toString()}`),t.join(" ")}static from(e){if(im.isFragment(e))return e;if("string"==typeof e)try{return im.from(Dg(e))}catch(t){$a(!1,"invalid constuctor fragment","obj",e)}else if(e instanceof Pg){Lg(e,yg(["constructor"]));const t=Fg(e),n=!!Lg(e,wg).has("payable"),r=jg(e);return Gg(e),new im(qg,"constructor",t,n,r)}return new im(qg,"constructor",e.inputs?e.inputs.map(Xg.from):[],!!e.payable,null!=e.gas?e.gas:null)}static isFragment(e){return e&&e[Wg]===Qg}}class om extends em{constructor(e,t,n){super(e,"fallback",t),xn(this,"payable"),Object.defineProperty(this,Wg,{value:Jg}),Ha(this,{payable:n})}format(e){const t=0===this.inputs.length?"receive":"fallback";if("json"===e){const e=this.payable?"payable":"nonpayable";return JSON.stringify({type:t,stateMutability:e})}return`${t}()${this.payable?" payable":""}`}static from(e){if(om.isFragment(e))return e;if("string"==typeof e)try{return om.from(Dg(e))}catch(t){$a(!1,"invalid fallback fragment","obj",e)}else if(e instanceof Pg){const t=e.toString();$a(e.peekKeyword(yg(["fallback","receive"])),"type must be fallback or receive","obj",t);if("receive"===e.popKeyword(yg(["fallback","receive"]))){const t=Fg(e);return $a(0===t.length,"receive cannot have arguments","obj.inputs",t),Lg(e,yg(["payable"])),Gg(e),new om(qg,[],!0)}let n=Fg(e);n.length?$a(1===n.length&&"bytes"===n[0].type,"invalid fallback inputs","obj.inputs",n.map((e=>e.format("minimal"))).join(", ")):n=[Xg.from("bytes")];const r=Mg(e);if($a("nonpayable"===r||"payable"===r,"fallback cannot be constants","obj.stateMutability",r),Lg(e,yg(["returns"])).has("returns")){const t=Fg(e);$a(1===t.length&&"bytes"===t[0].type,"invalid fallback outputs","obj.outputs",t.map((e=>e.format("minimal"))).join(", "))}return Gg(e),new om(qg,n,"payable"===r)}if("receive"===e.type)return new om(qg,[],!0);if("fallback"===e.type){const t=[Xg.from("bytes")],n="payable"===e.stateMutability;return new om(qg,t,n)}$a(!1,"invalid fallback description","obj",e)}static isFragment(e){return e&&e[Wg]===Jg}}class am extends tm{constructor(e,t,n,r,s,i){super(e,"function",t,r),xn(this,"constant"),xn(this,"outputs"),xn(this,"stateMutability"),xn(this,"payable"),xn(this,"gas"),Object.defineProperty(this,Wg,{value:Yg});Ha(this,{constant:"view"===n||"pure"===n,gas:i,outputs:s=Object.freeze(s.slice()),payable:"payable"===n,stateMutability:n})}get selector(){return Wf(this.format("sighash")).substring(0,10)}format(e){if(null==e&&(e="sighash"),"json"===e)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((t=>JSON.parse(t.format(e)))),outputs:this.outputs.map((t=>JSON.parse(t.format(e))))});const t=[];return"sighash"!==e&&t.push("function"),t.push(this.name+nm(e,this.inputs)),"sighash"!==e&&("nonpayable"!==this.stateMutability&&t.push(this.stateMutability),this.outputs&&this.outputs.length&&(t.push("returns"),t.push(nm(e,this.outputs))),null!=this.gas&&t.push(`@${this.gas.toString()}`)),t.join(" ")}static getSelector(e,t){t=(t||[]).map((e=>Xg.from(e)));return new am(qg,e,"view",t,[],null).selector}static from(e){if(am.isFragment(e))return e;if("string"==typeof e)try{return am.from(Dg(e))}catch(n){$a(!1,"invalid function fragment","obj",e)}else if(e instanceof Pg){const t=Ug("function",e),n=Fg(e),r=Mg(e);let s=[];Lg(e,yg(["returns"])).has("returns")&&(s=Fg(e));const i=jg(e);return Gg(e),new am(qg,t,r,n,s,i)}let t=e.stateMutability;return null==t&&(t="payable","boolean"==typeof e.constant?(t="view",e.constant||(t="payable","boolean"!=typeof e.payable||e.payable||(t="nonpayable"))):"boolean"!=typeof e.payable||e.payable||(t="nonpayable")),new am(qg,e.name,t,e.inputs?e.inputs.map(Xg.from):[],e.outputs?e.outputs.map(Xg.from):[],null!=e.gas?e.gas:null)}static isFragment(e){return e&&e[Wg]===Yg}}class cm extends tm{constructor(e,t,n){super(e,"struct",t,n),Object.defineProperty(this,Wg,{value:Zg})}format(){throw new Error("@TODO")}static from(e){if("string"==typeof e)try{return cm.from(Dg(e))}catch(t){$a(!1,"invalid struct fragment","obj",e)}else if(e instanceof Pg){const t=Ug("struct",e),n=Fg(e);return Gg(e),new cm(qg,t,n)}return new cm(qg,e.name,e.inputs?e.inputs.map(Xg.from):[])}static isFragment(e){return e&&e[Wg]===Zg}}const lm=new Map;lm.set(0,"GENERIC_PANIC"),lm.set(1,"ASSERT_FALSE"),lm.set(17,"OVERFLOW"),lm.set(18,"DIVIDE_BY_ZERO"),lm.set(33,"ENUM_RANGE_ERROR"),lm.set(34,"BAD_STORAGE_DATA"),lm.set(49,"STACK_UNDERFLOW"),lm.set(50,"ARRAY_RANGE_ERROR"),lm.set(65,"OUT_OF_MEMORY"),lm.set(81,"UNINITIALIZED_FUNCTION_CALL");const um=new RegExp(/^bytes([0-9]*)$/),hm=new RegExp(/^(u?int)([0-9]*)$/);let dm=null,fm=1024;Ee=new WeakSet,ke=function(e){if(e.isArray())return new cf(Ln(this,Ee,ke).call(this,e.arrayChildren),e.arrayLength,e.name);if(e.isTuple())return new _f(e.components.map((e=>Ln(this,Ee,ke).call(this,e))),e.name);switch(e.baseType){case"address":return new rf(e.name);case"bool":return new lf(e.name);case"string":return new bf(e.name);case"bytes":return new hf(e.name);case"":return new pf(e.name)}let t=e.type.match(hm);if(t){let n=parseInt(t[2]||"256");return $a(0!==n&&n<=256&&n%8==0,"invalid "+t[1]+" bit length","param",e),new wf(n/8,"int"===t[1],e.name)}if(t=e.type.match(um),t){let n=parseInt(t[1]);return $a(0!==n&&n<=32,"invalid bytes length","param",e),new df(n,e.name)}$a(!1,"invalid type","type",e.type)};let pm=class e{constructor(){Dn(this,Ee)}getDefaultValue(e){const t=e.map((e=>Ln(this,Ee,ke).call(this,Xg.from(e))));return new _f(t,"_").defaultValue()}encode(e,t){Qa(t.length,e.length,"types/values length mismatch");const n=e.map((e=>Ln(this,Ee,ke).call(this,Xg.from(e)))),r=new _f(n,"_"),s=new _l;return r.encode(s,t),s.data}decode(e,t,n){const r=e.map((e=>Ln(this,Ee,ke).call(this,Xg.from(e))));return new _f(r,"_").decode(new Al(t,n,fm))}static _setDefaultMaxInflation(e){$a("number"==typeof e&&Number.isInteger(e),"invalid defaultMaxInflation factor","value",e),fm=e}static defaultAbiCoder(){return null==dm&&(dm=new e),dm}static getBuiltinCallException(t,n,r){return function(e,t,n,r){let s="missing revert data",i=null,o=null;if(n){s="execution reverted";const e=ec(n);if(n=ic(n),0===e.length)s+=" (no data present; likely require(false) occurred",i="require(false)";else if(e.length%32!=4)s+=" (could not decode reason; invalid data length)";else if("0x08c379a0"===ic(e.slice(0,4)))try{i=r.decode(["string"],e.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"===ic(e.slice(0,4)))try{const t=Number(r.decode(["uint256"],e.slice(4))[0]);o={signature:"Panic(uint256)",name:"Panic",args:[t]},i=`Panic due to ${lm.get(t)||"UNKNOWN"}(${t})`,s+=`: ${i}`}catch(c){s+=" (could not decode panic code)"}else s+=" (unknown custom error)"}const a={to:t.to?$d(t.to):null,data:t.data||"0x"};return t.from&&(a.from=$d(t.from)),za(s,"CALL_EXCEPTION",{action:e,data:n,reason:i,transaction:a,invocation:null,revert:o})}(t,n,r,e.defaultAbiCoder())}};class gm{constructor(e,t,n){xn(this,"fragment"),xn(this,"name"),xn(this,"signature"),xn(this,"topic"),xn(this,"args");const r=e.name,s=e.format();Ha(this,{fragment:e,name:r,signature:s,topic:t,args:n})}}class mm{constructor(e,t,n,r){xn(this,"fragment"),xn(this,"name"),xn(this,"args"),xn(this,"signature"),xn(this,"selector"),xn(this,"value");const s=e.name,i=e.format();Ha(this,{fragment:e,name:s,args:n,signature:i,selector:t,value:r})}}class ym{constructor(e,t,n){xn(this,"fragment"),xn(this,"name"),xn(this,"args"),xn(this,"signature"),xn(this,"selector");const r=e.name,s=e.format();Ha(this,{fragment:e,name:r,args:n,signature:s,selector:t})}}class wm{constructor(e){xn(this,"hash"),xn(this,"_isIndexed"),Ha(this,{hash:e,_isIndexed:!0})}static isIndexed(e){return!(!e||!e._isIndexed)}}const bm={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"},_m={"0x08c379a0":{signature:"Error(string)",name:"Error",inputs:["string"],reason:e=>`reverted with reason string ${JSON.stringify(e)}`},"0x4e487b71":{signature:"Panic(uint256)",name:"Panic",inputs:["uint256"],reason:e=>{let t="unknown panic code";return e>=0&&e<=255&&bm[e.toString()]&&(t=bm[e.toString()]),`reverted with panic code 0x${e.toString(16)} (${t})`}}};Se=new WeakMap,Te=new WeakMap,Re=new WeakMap,Ie=new WeakMap,Ce=new WeakSet,Oe=function(e,t,n){if(nc(e)){const t=e.toLowerCase();for(const e of Pn(this,Re).values())if(t===e.selector)return e;return null}if(-1===e.indexOf("(")){const r=[];for(const[t,n]of Pn(this,Re))t.split("(")[0]===e&&r.push(n);if(t){const e=t.length>0?t[t.length-1]:null;let n=t.length,s=!0;nf.isTyped(e)&&"overrides"===e.type&&(s=!1,n--);for(let t=r.length-1;t>=0;t--){const e=r[t].inputs.length;e===n||s&&e===n-1||r.splice(t,1)}for(let i=r.length-1;i>=0;i--){const e=r[i].inputs;for(let n=0;n<t.length;n++)if(nf.isTyped(t[n])){if(n>=e.length){if("overrides"===t[n].type)continue;r.splice(i,1);break}if(t[n].type!==e[n].baseType){r.splice(i,1);break}}}}if(1===r.length&&t&&t.length!==r[0].inputs.length){const e=t[t.length-1];(null==e||Array.isArray(e)||"object"!=typeof e)&&r.splice(0,1)}if(0===r.length)return null;if(r.length>1&&n){$a(!1,`ambiguous function description (i.e. matches ${r.map((e=>JSON.stringify(e.format()))).join(", ")})`,"key",e)}return r[0]}const r=Pn(this,Re).get(am.from(e).format());return r||null},xe=new WeakSet,Ne=function(e,t,n){if(nc(e)){const t=e.toLowerCase();for(const e of Pn(this,Te).values())if(t===e.topicHash)return e;return null}if(-1===e.indexOf("(")){const r=[];for(const[t,n]of Pn(this,Te))t.split("(")[0]===e&&r.push(n);if(t){for(let e=r.length-1;e>=0;e--)r[e].inputs.length<t.length&&r.splice(e,1);for(let e=r.length-1;e>=0;e--){const n=r[e].inputs;for(let s=0;s<t.length;s++)if(nf.isTyped(t[s])&&t[s].type!==n[s].baseType){r.splice(e,1);break}}}if(0===r.length)return null;if(r.length>1&&n){$a(!1,`ambiguous event description (i.e. matches ${r.map((e=>JSON.stringify(e.format()))).join(", ")})`,"key",e)}return r[0]}const r=Pn(this,Te).get(sm.from(e).format());return r||null};let Am=class e{constructor(e){Dn(this,Ce),Dn(this,xe),xn(this,"fragments"),xn(this,"deploy"),xn(this,"fallback"),xn(this,"receive"),Dn(this,Se,void 0),Dn(this,Te,void 0),Dn(this,Re,void 0),Dn(this,Ie,void 0);let t=[];t="string"==typeof e?JSON.parse(e):e,Bn(this,Re,new Map),Bn(this,Se,new Map),Bn(this,Te,new Map);const n=[];for(const o of t)try{n.push(em.from(o))}catch(i){console.log(`[Warning] Invalid Fragment ${JSON.stringify(o)}:`,i.message)}Ha(this,{fragments:Object.freeze(n)});let r=null,s=!1;Bn(this,Ie,this.getAbiCoder()),this.fragments.forEach(((e,t)=>{let n;switch(e.type){case"constructor":return this.deploy?void console.log("duplicate definition - constructor"):void Ha(this,{deploy:e});case"fallback":return void(0===e.inputs.length?s=!0:($a(!r||e.payable!==r.payable,"conflicting fallback fragments",`fragments[${t}]`,e),r=e,s=r.payable));case"function":n=Pn(this,Re);break;case"event":n=Pn(this,Te);break;case"error":n=Pn(this,Se);break;default:return}const i=e.format();n.has(i)||n.set(i,e)})),this.deploy||Ha(this,{deploy:im.from("constructor()")}),Ha(this,{fallback:r,receive:s})}format(e){const t=e?"minimal":"full";return this.fragments.map((e=>e.format(t)))}formatJson(){const e=this.fragments.map((e=>e.format("json")));return JSON.stringify(e.map((e=>JSON.parse(e))))}getAbiCoder(){return pm.defaultAbiCoder()}getFunctionName(e){const t=Ln(this,Ce,Oe).call(this,e,null,!1);return $a(t,"no matching function","key",e),t.name}hasFunction(e){return!!Ln(this,Ce,Oe).call(this,e,null,!1)}getFunction(e,t){return Ln(this,Ce,Oe).call(this,e,t||null,!0)}forEachFunction(e){const t=Array.from(Pn(this,Re).keys());t.sort(((e,t)=>e.localeCompare(t)));for(let n=0;n<t.length;n++){const r=t[n];e(Pn(this,Re).get(r),n)}}getEventName(e){const t=Ln(this,xe,Ne).call(this,e,null,!1);return $a(t,"no matching event","key",e),t.name}hasEvent(e){return!!Ln(this,xe,Ne).call(this,e,null,!1)}getEvent(e,t){return Ln(this,xe,Ne).call(this,e,t||null,!0)}forEachEvent(e){const t=Array.from(Pn(this,Te).keys());t.sort(((e,t)=>e.localeCompare(t)));for(let n=0;n<t.length;n++){const r=t[n];e(Pn(this,Te).get(r),n)}}getError(e,t){if(nc(e)){const t=e.toLowerCase();if(_m[t])return rm.from(_m[t].signature);for(const e of Pn(this,Se).values())if(t===e.selector)return e;return null}if(-1===e.indexOf("(")){const t=[];for(const[n,r]of Pn(this,Se))n.split("(")[0]===e&&t.push(r);if(0===t.length)return"Error"===e?rm.from("error Error(string)"):"Panic"===e?rm.from("error Panic(uint256)"):null;if(t.length>1){$a(!1,`ambiguous error description (i.e. ${t.map((e=>JSON.stringify(e.format()))).join(", ")})`,"name",e)}return t[0]}if("Error(string)"===(e=rm.from(e).format()))return rm.from("error Error(string)");if("Panic(uint256)"===e)return rm.from("error Panic(uint256)");const n=Pn(this,Se).get(e);return n||null}forEachError(e){const t=Array.from(Pn(this,Se).keys());t.sort(((e,t)=>e.localeCompare(t)));for(let n=0;n<t.length;n++){const r=t[n];e(Pn(this,Se).get(r),n)}}_decodeParams(e,t){return Pn(this,Ie).decode(e,t)}_encodeParams(e,t){return Pn(this,Ie).encode(e,t)}encodeDeploy(e){return this._encodeParams(this.deploy.inputs,e||[])}decodeErrorResult(e,t){if("string"==typeof e){const t=this.getError(e);$a(t,"unknown error","fragment",e),e=t}return $a(cc(t,0,4)===e.selector,`data signature does not match error ${e.name}.`,"data",t),this._decodeParams(e.inputs,cc(t,4))}encodeErrorResult(e,t){if("string"==typeof e){const t=this.getError(e);$a(t,"unknown error","fragment",e),e=t}return oc([e.selector,this._encodeParams(e.inputs,t||[])])}decodeFunctionData(e,t){if("string"==typeof e){const t=this.getFunction(e);$a(t,"unknown function","fragment",e),e=t}return $a(cc(t,0,4)===e.selector,`data signature does not match function ${e.name}.`,"data",t),this._decodeParams(e.inputs,cc(t,4))}encodeFunctionData(e,t){if("string"==typeof e){const t=this.getFunction(e);$a(t,"unknown function","fragment",e),e=t}return oc([e.selector,this._encodeParams(e.inputs,t||[])])}decodeFunctionResult(e,t){if("string"==typeof e){const t=this.getFunction(e);$a(t,"unknown function","fragment",e),e=t}let n="invalid length for result data";const r=tc(t);if(r.length%32==0)try{return Pn(this,Ie).decode(e.outputs,r)}catch(s){n="could not decode result data"}Ka(!1,n,"BAD_DATA",{value:ic(r),info:{method:e.name,signature:e.format()}})}makeError(e,t){const n=ec(e,"data"),r=pm.getBuiltinCallException("call",t,n);if(r.message.startsWith("execution reverted (unknown custom error)")){const e=ic(n.slice(0,4)),t=this.getError(e);if(t)try{const e=Pn(this,Ie).decode(t.inputs,n.slice(4));r.revert={name:t.name,signature:t.format(),args:e},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(t);return s&&(r.invocation={method:s.name,signature:s.signature,args:s.args}),r}encodeFunctionResult(e,t){if("string"==typeof e){const t=this.getFunction(e);$a(t,"unknown function","fragment",e),e=t}return ic(Pn(this,Ie).encode(e.outputs,t||[]))}encodeFilterTopics(e,t){if("string"==typeof e){const t=this.getEvent(e);$a(t,"unknown event","eventFragment",e),e=t}Ka(t.length<=e.inputs.length,`too many arguments for ${e.format()}`,"UNEXPECTED_ARGUMENT",{count:t.length,expectedCount:e.inputs.length});const n=[];e.anonymous||n.push(e.topicHash);const r=(e,t)=>"string"===e.type?Wf(t):"bytes"===e.type?Bu(ic(t)):("bool"===e.type&&"boolean"==typeof t?t=t?"0x01":"0x00":e.type.match(/^u?int/)?t=vc(t):e.type.match(/^bytes/)?t=hc(t,32):"address"===e.type&&Pn(this,Ie).encode(["address"],[t]),uc(ic(t),32));for(t.forEach(((t,s)=>{const i=e.inputs[s];i.indexed?null==t?n.push(null):"array"===i.baseType||"tuple"===i.baseType?$a(!1,"filtering with tuples or arrays not supported","contract."+i.name,t):Array.isArray(t)?n.push(t.map((e=>r(i,e)))):n.push(r(i,t)):$a(null==t,"cannot filter non-indexed parameters; must be null","contract."+i.name,t)}));n.length&&null===n[n.length-1];)n.pop();return n}encodeEventLog(e,t){if("string"==typeof e){const t=this.getEvent(e);$a(t,"unknown event","eventFragment",e),e=t}const n=[],r=[],s=[];return e.anonymous||n.push(e.topicHash),$a(t.length===e.inputs.length,"event arguments/values mismatch","values",t),e.inputs.forEach(((e,i)=>{const o=t[i];if(e.indexed)if("string"===e.type)n.push(Wf(o));else if("bytes"===e.type)n.push(Bu(o));else{if("tuple"===e.baseType||"array"===e.baseType)throw new Error("not implemented");n.push(Pn(this,Ie).encode([e.type],[o]))}else r.push(e),s.push(o)})),{data:Pn(this,Ie).encode(r,s),topics:n}}decodeEventLog(e,t,n){if("string"==typeof e){const t=this.getEvent(e);$a(t,"unknown event","eventFragment",e),e=t}if(null!=n&&!e.anonymous){const t=e.topicHash;$a(nc(n[0],32)&&n[0].toLowerCase()===t,"fragment/topic mismatch","topics[0]",n[0]),n=n.slice(1)}const r=[],s=[],i=[];e.inputs.forEach(((e,t)=>{e.indexed?"string"===e.type||"bytes"===e.type||"tuple"===e.baseType||"array"===e.baseType?(r.push(Xg.from({type:"bytes32",name:e.name})),i.push(!0)):(r.push(e),i.push(!1)):(s.push(e),i.push(!1))}));const o=null!=n?Pn(this,Ie).decode(r,oc(n)):null,a=Pn(this,Ie).decode(s,t,!0),c=[],l=[];let u=0,h=0;return e.inputs.forEach(((e,t)=>{let n=null;if(e.indexed)if(null==o)n=new wm(null);else if(i[t])n=new wm(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(e.name||null)})),yl.fromItems(c,l)}parseTransaction(e){const t=ec(e.data,"tx.data"),n=yc(null!=e.value?e.value:0,"tx.value"),r=this.getFunction(ic(t.slice(0,4)));if(!r)return null;const s=Pn(this,Ie).decode(r.inputs,t.slice(4));return new mm(r,r.selector,s,n)}parseCallResult(e){throw new Error("@TODO")}parseLog(e){const t=this.getEvent(e.topics[0]);return!t||t.anonymous?null:new gm(t,t.topicHash,this.decodeEventLog(t,e.data,e.topics))}parseError(e){const t=ic(e),n=this.getError(cc(t,0,4));if(!n)return null;const r=Pn(this,Ie).decode(n.inputs,cc(t,4));return new ym(n,n.selector,r)}static from(t){return t instanceof e?t:"string"==typeof t?new e(JSON.parse(t)):"function"==typeof t.formatJson?new e(t.formatJson()):"function"==typeof t.format?new e(t.format("json")):new e(t)}};const vm=BigInt(0);function Em(e){return null==e?null:e}function km(e){return null==e?null:e.toString()}class Sm{constructor(e,t,n){xn(this,"gasPrice"),xn(this,"maxFeePerGas"),xn(this,"maxPriorityFeePerGas"),Ha(this,{gasPrice:Em(e),maxFeePerGas:Em(t),maxPriorityFeePerGas:Em(n)})}toJSON(){const{gasPrice:e,maxFeePerGas:t,maxPriorityFeePerGas:n}=this;return{_type:"FeeData",gasPrice:km(e),maxFeePerGas:km(t),maxPriorityFeePerGas:km(n)}}}function Tm(e){const t={};e.to&&(t.to=e.to),e.from&&(t.from=e.from),e.data&&(t.data=ic(e.data));const n="chainId,gasLimit,gasPrice,maxFeePerBlobGas,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/);for(const s of n)s in e&&null!=e[s]&&(t[s]=yc(e[s],`request.${s}`));const r="type,nonce".split(/,/);for(const s of r)s in e&&null!=e[s]&&(t[s]=Ac(e[s],`request.${s}`));return e.accessList&&(t.accessList=vf(e.accessList)),e.authorizationList&&(t.authorizationList=e.authorizationList.slice()),"blockTag"in e&&(t.blockTag=e.blockTag),"enableCcipRead"in e&&(t.enableCcipRead=!!e.enableCcipRead),"customData"in e&&(t.customData=e.customData),"blobVersionedHashes"in e&&e.blobVersionedHashes&&(t.blobVersionedHashes=e.blobVersionedHashes.slice()),"kzg"in e&&(t.kzg=e.kzg),"blobWrapperVersion"in e&&(t.blobWrapperVersion=e.blobWrapperVersion),"blobs"in e&&e.blobs&&(t.blobs=e.blobs.map((e=>rc(e)?ic(e):Object.assign({},e)))),t}class Rm{constructor(e,t){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,Pe,void 0),Bn(this,Pe,e.transactions.map((e=>"string"!=typeof e?new Om(e,t):e))),Ha(this,{provider:t,hash:Em(e.hash),number:e.number,timestamp:e.timestamp,parentHash:e.parentHash,parentBeaconBlockRoot:e.parentBeaconBlockRoot,nonce:e.nonce,difficulty:e.difficulty,gasLimit:e.gasLimit,gasUsed:e.gasUsed,blobGasUsed:e.blobGasUsed,excessBlobGas:e.excessBlobGas,miner:e.miner,prevRandao:Em(e.prevRandao),extraData:e.extraData,baseFeePerGas:Em(e.baseFeePerGas),stateRoot:e.stateRoot,receiptsRoot:e.receiptsRoot,transactionsRoot:e.transactionsRoot})}get transactions(){return Pn(this,Pe).map((e=>"string"==typeof e?e:e.hash))}get prefetchedTransactions(){const e=Pn(this,Pe).slice();return 0===e.length?[]:(Ka("object"==typeof e[0],"transactions were not prefetched with block request","UNSUPPORTED_OPERATION",{operation:"transactionResponses()"}),e)}toJSON(){const{baseFeePerGas:e,difficulty:t,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:km(e),difficulty:km(t),extraData:n,gasLimit:km(r),gasUsed:km(s),blobGasUsed:km(this.blobGasUsed),excessBlobGas:km(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 e=0;const t=this.transactions;return{next:()=>e<this.length?{value:t[e++],done:!1}:{value:void 0,done:!0}}}get length(){return Pn(this,Pe).length}get date(){return null==this.timestamp?null:new Date(1e3*this.timestamp)}async getTransaction(e){let t;if("number"==typeof e)t=Pn(this,Pe)[e];else{const n=e.toLowerCase();for(const e of Pn(this,Pe)){if("string"==typeof e){if(e!==n)continue;t=e;break}if(e.hash===n){t=e;break}}}if(null==t)throw new Error("no such tx");return"string"==typeof t?await this.provider.getTransaction(t):t}getPrefetchedTransaction(e){const t=this.prefetchedTransactions;if("number"==typeof e)return t[e];e=e.toLowerCase();for(const n of t)if(n.hash===e)return n;$a(!1,"no matching transaction","indexOrHash",e)}isMined(){return!!this.hash}isLondon(){return!!this.baseFeePerGas}orphanedEvent(){if(!this.isMined())throw new Error("");return{orphan:"drop-block",hash:(e=this).hash,number:e.number};var e}}Pe=new WeakMap;class Im{constructor(e,t){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=t;const n=Object.freeze(e.topics.slice());Ha(this,{transactionHash:e.transactionHash,blockHash:e.blockHash,blockNumber:e.blockNumber,removed:e.removed,address:e.address,data:e.data,topics:n,index:e.index,transactionIndex:e.transactionIndex})}toJSON(){const{address:e,blockHash:t,blockNumber:n,data:r,index:s,removed:i,topics:o,transactionHash:a,transactionIndex:c}=this;return{_type:"log",address:e,blockHash:t,blockNumber:n,data:r,index:s,removed:i,topics:o,transactionHash:a,transactionIndex:c}}async getBlock(){const e=await this.provider.getBlock(this.blockHash);return Ka(!!e,"failed to find transaction","UNKNOWN_ERROR",{}),e}async getTransaction(){const e=await this.provider.getTransaction(this.transactionHash);return Ka(!!e,"failed to find transaction","UNKNOWN_ERROR",{}),e}async getTransactionReceipt(){const e=await this.provider.getTransactionReceipt(this.transactionHash);return Ka(!!e,"failed to find transaction receipt","UNKNOWN_ERROR",{}),e}removedEvent(){return{orphan:"drop-log",log:{transactionHash:(e=this).transactionHash,blockHash:e.blockHash,blockNumber:e.blockNumber,address:e.address,data:e.data,topics:Object.freeze(e.topics.slice()),index:e.index}};var e}}class Cm{constructor(e,t){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,De,void 0),Bn(this,De,Object.freeze(e.logs.map((e=>new Im(e,t)))));let n=vm;null!=e.effectiveGasPrice?n=e.effectiveGasPrice:null!=e.gasPrice&&(n=e.gasPrice),Ha(this,{provider:t,to:e.to,from:e.from,contractAddress:e.contractAddress,hash:e.hash,index:e.index,blockHash:e.blockHash,blockNumber:e.blockNumber,logsBloom:e.logsBloom,gasUsed:e.gasUsed,cumulativeGasUsed:e.cumulativeGasUsed,blobGasUsed:e.blobGasUsed,gasPrice:n,blobGasPrice:e.blobGasPrice,type:e.type,status:e.status,root:e.root})}get logs(){return Pn(this,De)}toJSON(){const{to:e,from:t,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:km(this.cumulativeGasUsed),from:t,gasPrice:km(this.gasPrice),blobGasUsed:km(this.blobGasUsed),blobGasPrice:km(this.blobGasPrice),gasUsed:km(this.gasUsed),hash:r,index:s,logs:c,logsBloom:a,root:u,status:l,to:e}}get length(){return this.logs.length}[Symbol.iterator](){let e=0;return{next:()=>e<this.length?{value:this.logs[e++],done:!1}:{value:void 0,done:!0}}}get fee(){return this.gasUsed*this.gasPrice}async getBlock(){const e=await this.provider.getBlock(this.blockHash);if(null==e)throw new Error("TODO");return e}async getTransaction(){const e=await this.provider.getTransaction(this.hash);if(null==e)throw new Error("TODO");return e}async getResult(){return await this.provider.getTransactionResult(this.hash)}async confirmations(){return await this.provider.getBlockNumber()-this.blockNumber+1}removedEvent(){return Nm(this)}reorderedEvent(e){return Ka(!e||e.isMined(),"unmined 'other' transction cannot be orphaned","UNSUPPORTED_OPERATION",{operation:"reorderedEvent(other)"}),xm(this,e)}}De=new WeakMap;Be=new WeakMap;let Om=class e{constructor(e,t){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,Be,void 0),this.provider=t,this.blockNumber=null!=e.blockNumber?e.blockNumber:null,this.blockHash=null!=e.blockHash?e.blockHash:null,this.hash=e.hash,this.index=e.index,this.type=e.type,this.from=e.from,this.to=e.to||null,this.gasLimit=e.gasLimit,this.nonce=e.nonce,this.data=e.data,this.value=e.value,this.gasPrice=e.gasPrice,this.maxPriorityFeePerGas=null!=e.maxPriorityFeePerGas?e.maxPriorityFeePerGas:null,this.maxFeePerGas=null!=e.maxFeePerGas?e.maxFeePerGas:null,this.maxFeePerBlobGas=null!=e.maxFeePerBlobGas?e.maxFeePerBlobGas:null,this.chainId=e.chainId,this.signature=e.signature,this.accessList=null!=e.accessList?e.accessList:null,this.blobVersionedHashes=null!=e.blobVersionedHashes?e.blobVersionedHashes:null,this.authorizationList=null!=e.authorizationList?e.authorizationList:null,Bn(this,Be,-1)}toJSON(){const{blockNumber:e,blockHash:t,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:e,blockHash:t,blobVersionedHashes:h,chainId:km(this.chainId),data:c,from:o,gasLimit:km(this.gasLimit),gasPrice:km(this.gasPrice),hash:r,maxFeePerGas:km(this.maxFeePerGas),maxPriorityFeePerGas:km(this.maxPriorityFeePerGas),maxFeePerBlobGas:km(this.maxFeePerBlobGas),nonce:a,signature:l,to:i,index:n,type:s,value:km(this.value)}}async getBlock(){let e=this.blockNumber;if(null==e){const t=await this.getTransaction();t&&(e=t.blockNumber)}if(null==e)return null;const t=this.provider.getBlock(e);if(null==t)throw new Error("TODO");return t}async getTransaction(){return this.provider.getTransaction(this.hash)}async confirmations(){if(null==this.blockNumber){const{tx:e,blockNumber:t}=await Ga({tx:this.getTransaction(),blockNumber:this.provider.getBlockNumber()});return null==e||null==e.blockNumber?0:t-e.blockNumber+1}return await this.provider.getBlockNumber()-this.blockNumber+1}async wait(e,t){const n=null==e?1:e,r=null==t?0:t;let s=Pn(this,Be),i=-1,o=-1===s;const a=async()=>{if(o)return null;const{blockNumber:e,nonce:t}=await Ga({blockNumber:this.provider.getBlockNumber(),nonce:this.provider.getTransactionCount(this.from)});if(t<this.nonce)return void(s=e);if(o)return null;const r=await this.getTransaction();if(!r||null==r.blockNumber)for(-1===i&&(i=s-3,i<Pn(this,Be)&&(i=Pn(this,Be)));i<=e;){if(o)return null;const t=await this.provider.getBlock(i,!0);if(null==t)return;for(const e of t)if(e===this.hash)return;for(let r=0;r<t.length;r++){const i=await t.getTransaction(r);if(i.from===this.from&&i.nonce===this.nonce){if(o)return null;const t=await this.provider.getTransactionReceipt(i.hash);if(null==t)return;if(e-t.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===vm&&(r="cancelled"),Ka(!1,"transaction was replaced","TRANSACTION_REPLACED",{cancelled:"replaced"===r||"cancelled"===r,reason:r,replacement:i.replaceableTransaction(s),hash:i.hash,receipt:t})}}i++}},c=e=>{if(null==e||0!==e.status)return e;Ka(!1,"transaction execution reverted","CALL_EXCEPTION",{action:"sendTransaction",data:null,reason:null,invocation:null,revert:null,transaction:{to:e.to,from:e.from,data:""},receipt:e})},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(((e,t)=>{const i=[],l=()=>{i.forEach((e=>e()))};if(i.push((()=>{o=!0})),r>0){const e=setTimeout((()=>{l(),t(za("wait for transaction timeout","TIMEOUT"))}),r);i.push((()=>{clearTimeout(e)}))}const u=async r=>{if(await r.confirmations()>=n){l();try{e(c(r))}catch(s){t(s)}}};if(i.push((()=>{this.provider.off(this.hash,u)})),this.provider.on(this.hash,u),s>=0){const e=async()=>{try{await a()}catch(n){if(qa(n,"TRANSACTION_REPLACED"))return l(),void t(n)}o||this.provider.once("block",e)};i.push((()=>{this.provider.off("block",e)})),this.provider.once("block",e)}}));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 Ka(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),Nm(this)}reorderedEvent(e){return Ka(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),Ka(!e||e.isMined(),"unmined 'other' transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),xm(this,e)}replaceableTransaction(t){$a(Number.isInteger(t)&&t>=0,"invalid startBlock","startBlock",t);const n=new e(this,this.provider);return Bn(n,Be,t),n}};function xm(e,t){return{orphan:"reorder-transaction",tx:e,other:t}}function Nm(e){return{orphan:"drop-transaction",tx:e}}class Pm extends Im{constructor(e,t,n){super(e,e.provider),xn(this,"interface"),xn(this,"fragment"),xn(this,"args");Ha(this,{args:t.decodeEventLog(n,e.data,e.topics),fragment:n,interface:t})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}class Dm extends Im{constructor(e,t){super(e,e.provider),xn(this,"error"),Ha(this,{error:t})}}class Bm extends Cm{constructor(e,t,n){super(n,t),Dn(this,Ue,void 0),Bn(this,Ue,e)}get logs(){return super.logs.map((e=>{const t=e.topics.length?Pn(this,Ue).getEvent(e.topics[0]):null;if(t)try{return new Pm(e,Pn(this,Ue),t)}catch(n){return new Dm(e,n)}return e}))}}Ue=new WeakMap;class Um extends Om{constructor(e,t,n){super(n,t),Dn(this,Le,void 0),Bn(this,Le,e)}async wait(e,t){const n=await super.wait(e,t);return null==n?null:new Bm(Pn(this,Le),this.provider,n)}}Le=new WeakMap;class Lm extends xc{constructor(e,t,n,r){super(e,t,n),xn(this,"log"),Ha(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 Mm extends Lm{constructor(e,t,n,r,s){super(e,t,n,new Pm(s,e.interface,r));Ha(this,{args:e.interface.decodeEventLog(r,this.log.data,this.log.topics),fragment:r})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}const Fm=BigInt(0);function jm(e){return e&&"function"==typeof e.call}function Gm(e){return e&&"function"==typeof e.estimateGas}function Hm(e){return e&&"function"==typeof e.resolveName}function Vm(e){return e&&"function"==typeof e.sendTransaction}function qm(e){if(null!=e){if(Hm(e))return e;if(e.provider)return e.provider}}class Wm{constructor(e,t,n){if(Dn(this,Me,void 0),xn(this,"fragment"),Ha(this,{fragment:t}),t.inputs.length<n.length)throw new Error("too many arguments");const r=zm(e.runner,"resolveName"),s=Hm(r)?r:null;Bn(this,Me,async function(){const r=await Promise.all(t.inputs.map(((e,t)=>null==n[t]?null:e.walkAsync(n[t],((e,t)=>"address"===e?Array.isArray(t)?Promise.all(t.map((e=>Yd(e,s)))):Yd(t,s):t)))));return e.interface.encodeFilterTopics(t,r)}())}getTopicFilter(){return Pn(this,Me)}}function zm(e,t){return null==e?null:"function"==typeof e[t]?e:e.provider&&"function"==typeof e.provider[t]?e.provider:null}function Km(e){return null==e?null:e.provider||null}async function $m(e,t){const n=nf.dereference(e,"overrides");$a("object"==typeof n,"invalid overrides parameter","overrides",e);const r=Tm(n);return $a(null==r.to||(t||[]).indexOf("to")>=0,"cannot override to","overrides.to",r.to),$a(null==r.data||(t||[]).indexOf("data")>=0,"cannot override data","overrides.data",r.data),r.from&&(r.from=r.from),r}function Qm(e){const t=async function(t){const n=await $m(t,["data"]);n.to=await e.getAddress(),n.from&&(n.from=await Yd(n.from,qm(e.runner)));const r=e.interface,s=yc(n.value||Fm,"overrides.value")===Fm,i="0x"===(n.data||"0x");!r.fallback||r.fallback.payable||!r.receive||i||s||$a(!1,"cannot send data to receive or send value to non-payable fallback","overrides",t),$a(r.fallback||i,"cannot send data to receive-only contract","overrides.data",n.data);return $a(r.receive||r.fallback&&r.fallback.payable||s,"cannot send value to non-payable fallback","overrides.value",n.value),$a(r.fallback||i,"cannot send data to receive-only contract","overrides.data",n.data),n},n=async function(n){const r=e.runner;Ka(Vm(r),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const s=await r.sendTransaction(await t(n)),i=Km(e.runner);return new Um(e.interface,i,s)},r=async e=>await n(e);return Ha(r,{_contract:e,estimateGas:async function(n){const r=zm(e.runner,"estimateGas");return Ka(Gm(r),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await r.estimateGas(await t(n))},populateTransaction:t,send:n,staticCall:async function(n){const r=zm(e.runner,"call");Ka(jm(r),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const s=await t(n);try{return await r.call(s)}catch(i){if(Wa(i)&&i.data)throw e.interface.makeError(i.data,s);throw i}}}),r}function Jm(e,t){const n=function(...n){const r=e.interface.getFunction(t,n);return Ka(r,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:t,args:n}}),r},r=async function(...t){const r=n(...t);let s={};if(r.inputs.length+1===t.length&&(s=await $m(t.pop()),s.from&&(s.from=await Yd(s.from,qm(e.runner)))),r.inputs.length!==t.length)throw new Error("internal error: fragment inputs doesn't match arguments; should not happen");const i=await async function(e,t,n){const r=zm(e,"resolveName"),s=Hm(r)?r:null;return await Promise.all(t.map(((e,t)=>e.walkAsync(n[t],((e,t)=>(t=nf.dereference(t,e),"address"===e?Yd(t,s):t))))))}(e.runner,r.inputs,t);return Object.assign({},s,await Ga({to:e.getAddress(),data:e.interface.encodeFunctionData(r,i)}))},s=async function(...e){const t=await o(...e);return 1===t.length?t[0]:t},i=async function(...t){const n=e.runner;Ka(Vm(n),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const s=await n.sendTransaction(await r(...t)),i=Km(e.runner);return new Um(e.interface,i,s)},o=async function(...t){const s=zm(e.runner,"call");Ka(jm(s),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const i=await r(...t);let o="0x";try{o=await s.call(i)}catch(c){if(Wa(c)&&c.data)throw e.interface.makeError(c.data,i);throw c}const a=n(...t);return e.interface.decodeFunctionResult(a,o)},a=async(...e)=>n(...e).constant?await s(...e):await i(...e);return Ha(a,{name:e.interface.getFunctionName(t),_contract:e,_key:t,getFragment:n,estimateGas:async function(...t){const n=zm(e.runner,"estimateGas");return Ka(Gm(n),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await n.estimateGas(await r(...t))},populateTransaction:r,send:i,staticCall:s,staticCallResult:o}),Object.defineProperty(a,"fragment",{configurable:!1,enumerable:!0,get:()=>{const n=e.interface.getFunction(t);return Ka(n,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:t}}),n}}),a}Me=new WeakMap;const Ym=Symbol.for("_ethersInternal_contract"),Zm=new WeakMap;function Xm(e){return Zm.get(e[Ym])}async function ey(e,t){let n,r=null;if(Array.isArray(t)){const r=function(t){if(nc(t,32))return t;const n=e.interface.getEvent(t);return $a(n,"unknown fragment","name",t),n.topicHash};n=t.map((e=>null==e?null:Array.isArray(e)?e.map(r):r(e)))}else"*"===t?n=[null]:"string"==typeof t?nc(t,32)?n=[t]:(r=e.interface.getEvent(t),$a(r,"unknown fragment","event",t),n=[r.topicHash]):(s=t)&&"object"==typeof s&&"getTopicFilter"in s&&"function"==typeof s.getTopicFilter&&s.fragment?n=await t.getTopicFilter():"fragment"in t?(r=t.fragment,n=[r.topicHash]):$a(!1,"unknown event name","event",t);var s;n=n.map((e=>{if(null==e)return null;if(Array.isArray(e)){const t=Array.from(new Set(e.map((e=>e.toLowerCase()))).values());return 1===t.length?t[0]:(t.sort(),t)}return e.toLowerCase()}));return{fragment:r,tag:n.map((e=>null==e?"null":Array.isArray(e)?e.join("|"):e)).join("&"),topics:n}}async function ty(e,t){const{subs:n}=Xm(e);return n.get((await ey(e,t)).tag)||null}async function ny(e,t,n){const r=Km(e.runner);Ka(r,"contract runner does not support subscribing","UNSUPPORTED_OPERATION",{operation:t});const{fragment:s,tag:i,topics:o}=await ey(e,n),{addr:a,subs:c}=Xm(e);let l=c.get(i);if(!l){const t={address:a||e,topics:o},u=t=>{let r=s;if(null==r)try{r=e.interface.getEvent(t.topics[0])}catch(i){}if(r){const i=r,o=s?e.interface.decodeEventLog(s,t.data,t.topics):[];sy(e,n,o,(r=>new Mm(e,r,n,i,t)))}else sy(e,n,[],(r=>new Lm(e,r,n,t)))};let h=[];l={tag:i,listeners:[],start:()=>{h.length||h.push(r.on(t,u))},stop:async()=>{if(0==h.length)return;let e=h;h=[],await Promise.all(e),r.off(t,u)}},c.set(i,l)}return l}let ry=Promise.resolve();async function sy(e,t,n,r){try{await ry}catch(i){}const s=async function(e,t,n,r){await ry;const s=await ty(e,t);if(!s)return!1;const o=s.listeners.length;return s.listeners=s.listeners.filter((({listener:t,once:s})=>{const o=Array.from(n);r&&o.push(r(s?null:t));try{t.call(e,...o)}catch(i){}return!s})),0===s.listeners.length&&(s.stop(),Xm(e).subs.delete(s.tag)),o>0}(e,t,n,r);return ry=s,await s}const iy=["then"];Fe=Ym;let oy=class e{constructor(e,t,n,r){xn(this,"target"),xn(this,"interface"),xn(this,"runner"),xn(this,"filters"),xn(this,Fe),xn(this,"fallback"),$a("string"==typeof e||Qd(e),"invalid value for Contract target","target",e),null==n&&(n=null);const s=Am.from(t);let i;Ha(this,{target:e,runner:n,interface:s}),Object.defineProperty(this,Ym,{value:{}});let o=null,a=null;if(r){const e=Km(n);a=new Um(this.interface,e,r)}let c=new Map;if("string"==typeof e)if(nc(e))o=e,i=Promise.resolve(e);else{const t=zm(n,"resolveName");if(!Hm(t))throw za("contract runner does not support name resolution","UNSUPPORTED_OPERATION",{operation:"resolveName"});i=t.resolveName(e).then((t=>{if(null==t)throw za("an ENS name used for a contract target must be correctly configured","UNCONFIGURED_NAME",{value:e});return Xm(this).addr=t,t}))}else i=e.getAddress().then((e=>{if(null==e)throw new Error("TODO");return Xm(this).addr=e,e}));var l,u;l=this,u={addrPromise:i,addr:o,deployTx:a,subs:c},Zm.set(l[Ym],u);return Ha(this,{filters:new Proxy({},{get:(e,t,n)=>{if("symbol"==typeof t||iy.indexOf(t)>=0)return Reflect.get(e,t,n);try{return this.getEvent(t)}catch(r){if(!qa(r,"INVALID_ARGUMENT")||"key"!==r.argument)throw r}},has:(e,t)=>iy.indexOf(t)>=0?Reflect.has(e,t):Reflect.has(e,t)||this.interface.hasEvent(String(t))})}),Ha(this,{fallback:s.receive||s.fallback?Qm(this):null}),new Proxy(this,{get:(e,t,n)=>{if("symbol"==typeof t||t in e||iy.indexOf(t)>=0)return Reflect.get(e,t,n);try{return e.getFunction(t)}catch(r){if(!qa(r,"INVALID_ARGUMENT")||"key"!==r.argument)throw r}},has:(e,t)=>"symbol"==typeof t||t in e||iy.indexOf(t)>=0?Reflect.has(e,t):e.interface.hasFunction(t)})}connect(t){return new e(this.target,this.interface,t)}attach(t){return new e(t,this.interface,this.runner)}async getAddress(){return await Xm(this).addrPromise}async getDeployedCode(){const e=Km(this.runner);Ka(e,"runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"getDeployedCode"});const t=await e.getCode(await this.getAddress());return"0x"===t?null:t}async waitForDeployment(){const e=this.deploymentTransaction();if(e)return await e.wait(),this;if(null!=await this.getDeployedCode())return this;const t=Km(this.runner);return Ka(null!=t,"contract runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"waitForDeployment"}),new Promise(((e,n)=>{const r=async()=>{try{if(null!=await this.getDeployedCode())return e(this);t.once("block",r)}catch(s){n(s)}};r()}))}deploymentTransaction(){return Xm(this).deployTx}getFunction(e){"string"!=typeof e&&(e=e.format());return Jm(this,e)}getEvent(e){return"string"!=typeof e&&(e=e.format()),function(e,t){const n=function(...n){const r=e.interface.getEvent(t,n);return Ka(r,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:t,args:n}}),r},r=function(...t){return new Wm(e,n(...t),t)};return Ha(r,{name:e.interface.getEventName(t),_contract:e,_key:t,getFragment:n}),Object.defineProperty(r,"fragment",{configurable:!1,enumerable:!0,get:()=>{const n=e.interface.getEvent(t);return Ka(n,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:t}}),n}}),r}(this,e)}async queryTransaction(e){throw new Error("@TODO")}async queryFilter(e,t,n){null==t&&(t=0),null==n&&(n="latest");const{addr:r,addrPromise:s}=Xm(this),i=r||await s,{fragment:o,topics:a}=await ey(this,e),c={address:i,topics:a,fromBlock:t,toBlock:n},l=Km(this.runner);return Ka(l,"contract runner does not have a provider","UNSUPPORTED_OPERATION",{operation:"queryFilter"}),(await l.getLogs(c)).map((e=>{let t=o;if(null==t)try{t=this.interface.getEvent(e.topics[0])}catch(n){}if(t)try{return new Pm(e,this.interface,t)}catch(n){return new Dm(e,n)}return new Im(e,l)}))}async on(e,t){const n=await ny(this,"on",e);return n.listeners.push({listener:t,once:!1}),n.start(),this}async once(e,t){const n=await ny(this,"once",e);return n.listeners.push({listener:t,once:!0}),n.start(),this}async emit(e,...t){return await sy(this,e,t,null)}async listenerCount(e){if(e){const t=await ty(this,e);return t?t.listeners.length:0}const{subs:t}=Xm(this);let n=0;for(const{listeners:r}of t.values())n+=r.length;return n}async listeners(e){if(e){const t=await ty(this,e);return t?t.listeners.map((({listener:e})=>e)):[]}const{subs:t}=Xm(this);let n=[];for(const{listeners:r}of t.values())n=n.concat(r.map((({listener:e})=>e)));return n}async off(e,t){const n=await ty(this,e);if(!n)return this;if(t){const e=n.listeners.map((({listener:e})=>e)).indexOf(t);e>=0&&n.listeners.splice(e,1)}return null!=t&&0!==n.listeners.length||(n.stop(),Xm(this).subs.delete(n.tag)),this}async removeAllListeners(e){if(e){const t=await ty(this,e);if(!t)return this;t.stop(),Xm(this).subs.delete(t.tag)}else{const{subs:e}=Xm(this);for(const{tag:t,stop:n}of e.values())n(),e.delete(t)}return this}async addListener(e,t){return await this.on(e,t)}async removeListener(e,t){return await this.off(e,t)}static buildClass(t){return class extends e{constructor(e,n=null){super(e,t,n)}}}static from(e,t,n){null==n&&(n=null);return new this(e,t,n)}};class ay extends(function(){return oy}()){}const cy=BigInt(60);function ly(e){return e.match(/^ipfs:\/\/ipfs\//i)?e=e.substring(12):e.match(/^ipfs:\/\//i)?e=e.substring(7):$a(!1,"unsupported IPFS format","link",e),`https://gateway.ipfs.io/ipfs/${e}`}class uy{constructor(e){xn(this,"name"),Ha(this,{name:e})}connect(e){return this}supportsCoinType(e){return!1}async encodeAddress(e,t){throw new Error("unsupported coin")}async decodeAddress(e,t){throw new Error("unsupported coin")}}const hy=new RegExp("^(ipfs)://(.*)$","i"),dy=[new RegExp("^(https)://(.*)$","i"),new RegExp("^(data):(.*)$","i"),hy,new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$","i")];function fy(e){return e===cy||e>=2147483648&&e<=4294967295}const py=class e{constructor(e,t,n,r){Dn(this,He),xn(this,"provider"),xn(this,"address"),xn(this,"name"),Dn(this,je,void 0),Dn(this,Ge,void 0),Ha(this,{provider:e,address:t,name:n}),Bn(this,je,null!=r?Promise.resolve(r):null),Bn(this,Ge,new ay(t,["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)"],e))}async supportsWildcard(){return null==Pn(this,je)&&Bn(this,je,(async()=>{try{return await Pn(this,Ge).supportsInterface("0x9061b923")}catch(e){if(qa(e,"CALL_EXCEPTION"))return!1;throw Bn(this,je,null),e}})()),await Pn(this,je)}async getAddress(e){const t=null==e?cy:yc(e);if(t===cy)try{const e=await Ln(this,He,Ve).call(this,"addr(bytes32)");return null==e||e===Id?null:e}catch(s){if(qa(s,"CALL_EXCEPTION"))return null;throw s}if(fy(t)){const e=await Ln(this,He,Ve).call(this,"addr(bytes32,uint)",[t]);return nc(e,20)?$d(e):null}if(t>=0&&t<2147483648){let e=t+BigInt(2147483648);const n=await Ln(this,He,Ve).call(this,"addr(bytes32,uint)",[e]);if(nc(n,20))return $d(n)}let n=null;for(const i of this.provider.plugins)if(i instanceof uy&&t<=2147483648&&i.supportsCoinType(Number(t))){n=i;break}if(null==n)return null;const r=await Ln(this,He,Ve).call(this,"addr(bytes32,uint)",[t]);if(null==r||"0x"===r)return null;if(t<2147483648){const e=await n.decodeAddress(Number(t),r);if(null!=e)return e}Ka(!1,"invalid coin data","UNSUPPORTED_OPERATION",{operation:`getAddress(${t})`,info:{coinType:t,data:r}})}async getText(e){const t=await Ln(this,He,Ve).call(this,"text(bytes32,string)",[e]);return null==t||"0x"===t?null:t}async getContentHash(){const e=await Ln(this,He,Ve).call(this,"contenthash(bytes32)");if(null==e||"0x"===e)return null;const t=e.match(/^0x(e3010170|e5010172)(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);if(t){const e="e3010170"===t[1]?"ipfs":"ipns",n=parseInt(t[4],16);if(t[5].length===2*n)return`${e}://${Oc("0x"+t[2])}`}const n=e.match(/^0xe40101fa011b20([0-9a-f]*)$/);if(n&&64===n[1].length)return`bzz://${n[1]}`;Ka(!1,"invalid or unsupported content hash data","UNSUPPORTED_OPERATION",{operation:"getContentHash()",info:{data:e}})}async getName(){return await Ln(this,He,Ve).call(this,"name(bytes32)")}async getAvatar(){return(await this._getAvatar()).url}async _getAvatar(){const e=[{type:"name",value:this.name}];try{const r=await this.getText("avatar");if(null==r)return e.push({type:"!avatar",value:""}),{url:null,linkage:e};e.push({type:"avatar",value:r});for(let s=0;s<dy.length;s++){const i=r.match(dy[s]);if(null==i)continue;const o=i[1].toLowerCase();switch(o){case"https":case"data":return e.push({type:"url",value:r}),{linkage:e,url:r};case"ipfs":{const t=ly(r);return e.push({type:"ipfs",value:r}),e.push({type:"url",value:t}),{linkage:e,url:t}}case"erc721":case"erc1155":{const s="erc721"===o?"tokenURI(uint256)":"uri(uint256)";e.push({type:o,value:r});const a=await this.getAddress();if(null==a)return e.push({type:"!owner",value:""}),{url:null,linkage:e};const c=(i[2]||"").split("/");if(2!==c.length)return e.push({type:`!${o}caip`,value:i[2]||""}),{url:null,linkage:e};const l=c[1],u=new ay(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 t=await u.ownerOf(l);if(a!==t)return e.push({type:"!owner",value:t}),{url:null,linkage:e};e.push({type:"owner",value:t})}else if("erc1155"===o){const t=await u.balanceOf(a,l);if(!t)return e.push({type:"!balance",value:"0"}),{url:null,linkage:e};e.push({type:"balance",value:t.toString()})}let h=await u[s](l);if(null==h||"0x"===h)return e.push({type:"!metadata-url",value:""}),{url:null,linkage:e};e.push({type:"metadata-url-base",value:h}),"erc1155"===o&&(h=h.replace("{id}",vc(l,32).substring(2)),e.push({type:"metadata-url-expanded",value:h})),h.match(/^ipfs:/i)&&(h=ly(h)),e.push({type:"metadata-url",value:h});let d={};const f=await new $c(h).send();f.assertOk();try{d=f.bodyJson}catch(t){try{e.push({type:"!metadata",value:f.bodyText})}catch(n){const t=f.body;return t&&e.push({type:"!metadata",value:ic(t)}),{url:null,linkage:e}}return{url:null,linkage:e}}if(!d)return e.push({type:"!metadata",value:""}),{url:null,linkage:e};e.push({type:"metadata",value:JSON.stringify(d)});let p=d.image;if("string"!=typeof p)return e.push({type:"!imageUrl",value:""}),{url:null,linkage:e};if(p.match(/^(https:\/\/|data:)/i));else{if(null==p.match(hy))return e.push({type:"!imageUrl-ipfs",value:p}),{url:null,linkage:e};e.push({type:"imageUrl-ipfs",value:p}),p=ly(p)}return e.push({type:"url",value:p}),{linkage:e,url:p}}}}}catch(t){}return{linkage:e,url:null}}static async getEnsAddress(e){const t=await e.getNetwork(),n=t.getPlugin("org.ethers.plugins.network.Ens");return Ka(n,"network does not support ENS","UNSUPPORTED_OPERATION",{operation:"getEnsAddress",info:{network:t}}),n.address}static async getUniversalResolverAddress(e){const t=(await e.getNetwork()).getPlugin("org.ethers.plugins.network.Ens");return t&&t.universalResolver?t.universalResolver:null}static async lookupAddress(t,n,r){const s=null==r?cy:yc(r);fy(s)&&(n=$d(n));const i=await my(t);if(i)try{const e=(await i.reverse(n,s,{enableCcipRead:!0})).primary;return Xp(e)?e:null}catch(o){if(qa(o,"CALL_EXCEPTION")&&"ResolverNotFound(bytes)"===o.reason)return null;throw o}Ka(s===cy,"lookupAddress coinType requires ENS Universal Resolver","UNSUPPORTED_OPERATION",{operation:"lookupAddress"});try{const r=await e.fromName(t,`${n.toLowerCase().substring(2)}.addr.reverse`);if(!r)return null;const s=await r.getName();if(null==s||!Xp(s))return null;return await t.resolveName(s)!==n?null:s}catch(a){if(qa(a,"BAD_DATA")&&"0x"===a.value)return null;if(qa(a,"CALL_EXCEPTION"))return null;throw a}}static async fromName(t,n){var r;const s=await my(t);if(s){let r;try{r=tg(Zp(n),255)}catch(o){return null}const i=await s.requireResolver(r);return new e(t,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=e,qe,We).call(r,t,i);if(null!=s){const r=new e(t,s,n);return i===n||await r.supportsWildcard()?r:null}i=i.split(".").slice(1).join(".")}}};je=new WeakMap,Ge=new WeakMap,He=new WeakSet,Ve=async function(e,t){t=(t||[]).slice();const n=Pn(this,Ge).interface;t.unshift(eg(this.name));let r=null;await this.supportsWildcard()&&(r=n.getFunction(e),Ka(r,"missing fragment","UNKNOWN_ERROR",{info:{funcName:e}}),t=[tg(this.name,255),n.encodeFunctionData(r,t)],e="resolve(bytes,bytes)"),t.push({enableCcipRead:!0});try{const s=await Pn(this,Ge)[e](...t);return r?n.decodeFunctionResult(r,s)[0]:s}catch(s){if(!qa(s,"CALL_EXCEPTION"))throw s}return null},qe=new WeakSet,We=async function(e,t){const n=await py.getEnsAddress(e);try{const r=new ay(n,["function resolver(bytes32) view returns (address)"],e),s=await r.resolver(eg(t),{enableCcipRead:!0});return s===Id?null:s}catch(r){throw r}return null},Dn(py,qe);let gy=py;async function my(e){const t=await gy.getUniversalResolverAddress(e);return t?new ay(t,["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)"],e):null}const yy=BigInt(0);function wy(e,t){return function(n){return null==n?t:e(n)}}function by(e,t){return n=>{if(t&&null==n)return null;if(!Array.isArray(n))throw new Error("not an array");return n.map((t=>e(t)))}}function _y(e,t){return n=>{const r={};for(const i in e){let o=i;if(t&&i in t&&!(o in n))for(const e of t[i])if(e in n){o=e;break}try{const t=e[i](n[o]);void 0!==t&&(r[i]=t)}catch(s){Ka(!1,`invalid value for value.${i} (${s instanceof Error?s.message:"not-an-error"})`,"BAD_DATA",{value:n})}}return r}}function Ay(e){return $a(nc(e,!0),"invalid data","value",e),e}function vy(e){return $a(nc(e,32),"invalid hash","value",e),e}const Ey=_y({address:$d,blockHash:vy,blockNumber:Ac,data:Ay,index:Ac,removed:wy((function(e){switch(e){case!0:case"true":return!0;case!1:case"false":return!1}$a(!1,`invalid boolean; ${JSON.stringify(e)}`,"value",e)}),!1),topics:by(vy),transactionHash:vy,transactionIndex:Ac},{index:["logIndex"]});const ky=_y({hash:wy(vy),parentHash:vy,parentBeaconBlockRoot:wy(vy,null),number:Ac,timestamp:Ac,nonce:wy(Ay),difficulty:yc,gasLimit:yc,gasUsed:yc,stateRoot:wy(vy,null),receiptsRoot:wy(vy,null),transactionsRoot:wy(vy,null),blobGasUsed:wy(yc,null),excessBlobGas:wy(yc,null),miner:wy($d),prevRandao:wy(vy,null),extraData:Ay,baseFeePerGas:wy(yc)},{prevRandao:["mixHash"]});const Sy=_y({transactionIndex:Ac,blockNumber:Ac,transactionHash:vy,address:$d,topics:by(vy),data:Ay,index:Ac,blockHash:vy},{index:["logIndex"]});const Ty=_y({to:wy($d,null),from:wy($d,null),contractAddress:wy($d,null),index:Ac,root:wy(ic),gasUsed:yc,blobGasUsed:wy(yc,null),logsBloom:wy(Ay),blockHash:vy,hash:vy,logs:by((function(e){return Sy(e)})),blockNumber:Ac,cumulativeGasUsed:yc,effectiveGasPrice:wy(yc),blobGasPrice:wy(yc,null),status:wy(Ac),type:wy(Ac,0)},{effectiveGasPrice:["gasPrice"],hash:["transactionHash"],index:["transactionIndex"]});function Ry(e){e.to&&yc(e.to)===yy&&(e.to="0x0000000000000000000000000000000000000000");const t=_y({hash:vy,index:wy(Ac,void 0),type:e=>"0x"===e||null==e?0:Ac(e),accessList:wy(vf,null),blobVersionedHashes:wy(by(vy,!0),null),authorizationList:wy(by((e=>{let t;if(e.signature)t=e.signature;else{let n=e.yParity;"0x1b"===n?n=0:"0x1c"===n&&(n=1),t=Object.assign({},e,{yParity:n})}return{address:$d(e.address),chainId:yc(e.chainId),nonce:yc(e.nonce),signature:Gd.from(t)}}),!1),null),blockHash:wy(vy,null),blockNumber:wy(Ac,null),transactionIndex:wy(Ac,null),from:$d,gasPrice:wy(yc),maxPriorityFeePerGas:wy(yc),maxFeePerGas:wy(yc),maxFeePerBlobGas:wy(yc,null),gasLimit:yc,to:wy($d,null),value:yc,nonce:Ac,data:Ay,creates:wy($d,null),chainId:wy(yc,null)},{data:["input"],gasLimit:["gas"],index:["transactionIndex"]})(e);if(null==t.to&&null==t.creates&&(t.creates=function(e){const t=$d(e.from);let n=yc(e.nonce,"tx.nonce").toString(16);return n="0"===n?"0x":n.length%2?"0x0"+n:"0x"+n,$d(cc(Bu(ol([t,n])),12))}(t)),1!==e.type&&2!==e.type||null!=e.accessList||(t.accessList=[]),e.signature?t.signature=Gd.from(e.signature):t.signature=Gd.from(e),null==t.chainId){const e=t.signature.legacyChainId;null!=e&&(t.chainId=e)}return t.blockHash&&yc(t.blockHash)===yy&&(t.blockHash=null),t}const Iy=Symbol.for("nodejs.util.inspect.custom");class Cy{constructor(e){xn(this,"name"),Ha(this,{name:e})}[Iy](){return this.toString()}toString(){return`${this.name} { }`}clone(){return new Cy(this.name)}}class Oy extends Cy{constructor(e,t){null==e&&(e=0),super(`org.ethers.network.plugins.GasCost#${e||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:e};function r(e,r){let s=(t||{})[e];null==s&&(s=r),$a("number"==typeof s,`invalud value for ${e}`,"costs",t),n[e]=s}r("txBase",21e3),r("txCreate",32e3),r("txDataZero",4),r("txDataNonzero",16),r("txAccessListStorageKey",1900),r("txAccessListAddress",2400),Ha(this,n)}toString(){return`${this.name} { txBase: ${this.txBase}, txCreate: ${this.txCreate}, txDataZero: ${this.txDataZero}, txAccessListStorageKey: ${this.txAccessListStorageKey}, txAccessListAddress: ${this.txAccessListAddress} }`}clone(){return new Oy(this.effectiveBlock,this)}}class xy extends Cy{constructor(e,t,n){super("org.ethers.plugins.network.Ens"),xn(this,"address"),xn(this,"targetNetwork"),xn(this,"universalResolver"),Ha(this,{address:e||"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",targetNetwork:null==t?1:t,universalResolver:n})}toString(){return`${this.name} { address: ${this.address}, targetNetwork: ${this.targetNetwork}, universalResolver: ${this.universalResolver} }`}clone(){return new xy(this.address,this.targetNetwork,this.universalResolver)}}class Ny extends Cy{constructor(e,t){super("org.ethers.plugins.network.FetchUrlFeeDataPlugin"),Dn(this,ze,void 0),Dn(this,Ke,void 0),Bn(this,ze,e),Bn(this,Ke,t)}get url(){return Pn(this,ze)}get processFunc(){return Pn(this,Ke)}toString(){return`${this.name} { url: ${this.url} }`}clone(){return this}}ze=new WeakMap,Ke=new WeakMap;const Py=Symbol.for("nodejs.util.inspect.custom"),Dy=new Map;$e=new WeakMap,Qe=new WeakMap,Je=new WeakMap;let By=class e{constructor(e,t){Dn(this,$e,void 0),Dn(this,Qe,void 0),Dn(this,Je,void 0),Bn(this,$e,e),Bn(this,Qe,yc(t)),Bn(this,Je,new Map)}[Py](){return this.toString()}toString(){const e=[];for(const t of Pn(this,Je).values())e.push(t.toString());return`Network { name: ${this.name}, chainId: ${this.chainId}, plugins: [ ${e.join(", ")} ] }`}toJSON(){return{name:this.name,chainId:String(this.chainId)}}get name(){return Pn(this,$e)}set name(e){Bn(this,$e,e)}get chainId(){return Pn(this,Qe)}set chainId(e){Bn(this,Qe,yc(e,"chainId"))}matches(e){if(null==e)return!1;if("string"==typeof e){try{return this.chainId===yc(e)}catch(t){}return this.name===e}if("number"==typeof e||"bigint"==typeof e){try{return this.chainId===yc(e)}catch(t){}return!1}if("object"==typeof e){if(null!=e.chainId){try{return this.chainId===yc(e.chainId)}catch(t){}return!1}return null!=e.name&&this.name===e.name}return!1}get plugins(){return Array.from(Pn(this,Je).values())}attachPlugin(e){if(Pn(this,Je).get(e.name))throw new Error(`cannot replace existing plugin: ${e.name} `);return Pn(this,Je).set(e.name,e.clone()),this}getPlugin(e){return Pn(this,Je).get(e)||null}getPlugins(e){return this.plugins.filter((t=>t.name.split("#")[0]===e))}clone(){const t=new e(this.name,this.chainId);return this.plugins.forEach((e=>{t.attachPlugin(e.clone())})),t}computeIntrinsicGas(e){const t=this.getPlugin("org.ethers.plugins.network.GasCost")||new Oy;let n=t.txBase;if(null==e.to&&(n+=t.txCreate),e.data)for(let r=2;r<e.data.length;r+=2)"00"===e.data.substring(r,r+2)?n+=t.txDataZero:n+=t.txDataNonzero;if(e.accessList){const r=vf(e.accessList);for(const e in r)n+=t.txAccessListAddress+t.txAccessListStorageKey*r[e].storageKeys.length}return n}static from(t){if(function(){if(My)return;function e(e,t,n){const r=function(){const r=new By(e,t);return null!=n.ensNetwork&&r.attachPlugin(new xy(null,n.ensNetwork,n.ensUniversalResolver)),r.attachPlugin(new Oy),(n.plugins||[]).forEach((e=>{r.attachPlugin(e)})),r};By.register(e,r),By.register(t,r),n.altNames&&n.altNames.forEach((e=>{By.register(e,r)}))}My=!0;const t="0xeEeEEEeE14D718C2B47D9923Deab1335E144EeEe";e("mainnet",1,{ensUniversalResolver:t,ensNetwork:1,altNames:["homestead"]}),e("ropsten",3,{ensNetwork:3}),e("rinkeby",4,{ensNetwork:4}),e("goerli",5,{ensNetwork:5}),e("kovan",42,{ensNetwork:42}),e("sepolia",11155111,{ensUniversalResolver:t,ensNetwork:11155111}),e("holesky",17e3,{ensNetwork:17e3}),e("classic",61,{}),e("classicKotti",6,{}),e("arbitrum",42161,{ensNetwork:1}),e("arbitrum-goerli",421613,{}),e("arbitrum-sepolia",421614,{}),e("base",8453,{ensNetwork:1}),e("base-goerli",84531,{}),e("base-sepolia",84532,{}),e("bnb",56,{ensNetwork:1}),e("bnbt",97,{}),e("filecoin",314,{}),e("filecoin-calibration",314159,{}),e("linea",59144,{ensNetwork:1}),e("linea-goerli",59140,{}),e("linea-sepolia",59141,{}),e("matic",137,{ensNetwork:1,plugins:[Ly("https://gasstation.polygon.technology/v2")]}),e("matic-amoy",80002,{}),e("matic-mumbai",80001,{altNames:["maticMumbai","maticmum"],plugins:[Ly("https://gasstation-testnet.polygon.technology/v2")]}),e("optimism",10,{ensNetwork:1,plugins:[]}),e("optimism-goerli",420,{}),e("optimism-sepolia",11155420,{}),e("xdai",100,{ensNetwork:1})}(),null==t)return e.from("mainnet");if("number"==typeof t&&(t=BigInt(t)),"string"==typeof t||"bigint"==typeof t){const n=Dy.get(t);if(n)return n();if("bigint"==typeof t)return new e("unknown",t);$a(!1,"unknown network","network",t)}if("function"==typeof t.clone){return t.clone()}if("object"==typeof t){$a("string"==typeof t.name&&"number"==typeof t.chainId,"invalid network object name or chainId","network",t);const n=new e(t.name,t.chainId),r=t;return(r.ensAddress||null!=r.ensNetwork||r.ensUniversalResolver)&&n.attachPlugin(new xy(r.ensAddress,r.ensNetwork,r.ensUniversalResolver)),n}$a(!1,"invalid network","network",t)}static register(e,t){"number"==typeof e&&(e=BigInt(e));const n=Dy.get(e);n&&$a(!1,`conflicting network for ${JSON.stringify(n.name)}`,"nameOrChainId",e),Dy.set(e,t)}};function Uy(e,t){const n=String(e);if(!n.match(/^[0-9.]+$/))throw new Error(`invalid gwei value: ${e}`);const r=n.split(".");if(1===r.length&&r.push(""),2!==r.length)throw new Error(`invalid gwei value: ${e}`);for(;r[1].length<t;)r[1]+="0";if(r[1].length>9){let e=BigInt(r[1].substring(0,9));r[1].substring(9).match(/^0+$/)||e++,r[1]=e.toString()}return BigInt(r[0]+r[1])}function Ly(e){return new Ny(e,(async(e,t,n)=>{let r;n.setHeader("User-Agent","ethers");try{const[t,s]=await Promise.all([n.send(),e()]);r=t;const i=r.bodyJson.standard;return{gasPrice:s.gasPrice,maxFeePerGas:Uy(i.maxFee,9),maxPriorityFeePerGas:Uy(i.maxPriorityFee,9)}}catch(s){Ka(!1,`error encountered with polygon gas station (${JSON.stringify(n.url)})`,"SERVER_ERROR",{request:n,response:r,error:s})}}))}let My=!1;function Fy(e){return JSON.parse(JSON.stringify(e))}class jy{constructor(e){Dn(this,tt),Dn(this,Ye,void 0),Dn(this,Ze,void 0),Dn(this,Xe,void 0),Dn(this,et,void 0),Bn(this,Ye,e),Bn(this,Ze,null),Bn(this,Xe,4e3),Bn(this,et,-2)}get pollingInterval(){return Pn(this,Xe)}set pollingInterval(e){Bn(this,Xe,e)}start(){Pn(this,Ze)||(Bn(this,Ze,Pn(this,Ye)._setTimeout(Ln(this,tt,nt).bind(this),Pn(this,Xe))),Ln(this,tt,nt).call(this))}stop(){Pn(this,Ze)&&(Pn(this,Ye)._clearTimeout(Pn(this,Ze)),Bn(this,Ze,null))}pause(e){this.stop(),e&&Bn(this,et,-2)}resume(){this.start()}}Ye=new WeakMap,Ze=new WeakMap,Xe=new WeakMap,et=new WeakMap,tt=new WeakSet,nt=async function(){try{const e=await Pn(this,Ye).getBlockNumber();if(-2===Pn(this,et))return void Bn(this,et,e);if(e!==Pn(this,et)){for(let t=Pn(this,et)+1;t<=e;t++){if(null==Pn(this,Ze))return;await Pn(this,Ye).emit("block",t)}Bn(this,et,e)}}catch(e){}null!=Pn(this,Ze)&&Bn(this,Ze,Pn(this,Ye)._setTimeout(Ln(this,tt,nt).bind(this),Pn(this,Xe)))};class Gy{constructor(e){Dn(this,rt,void 0),Dn(this,st,void 0),Dn(this,it,void 0),Bn(this,rt,e),Bn(this,it,!1),Bn(this,st,(e=>{this._poll(e,Pn(this,rt))}))}async _poll(e,t){throw new Error("sub-classes must override this")}start(){Pn(this,it)||(Bn(this,it,!0),Pn(this,st).call(this,-2),Pn(this,rt).on("block",Pn(this,st)))}stop(){Pn(this,it)&&(Bn(this,it,!1),Pn(this,rt).off("block",Pn(this,st)))}pause(e){this.stop()}resume(){this.start()}}rt=new WeakMap,st=new WeakMap,it=new WeakMap;class Hy extends Gy{constructor(e,t){super(e),Dn(this,ot,void 0),Dn(this,at,void 0),Bn(this,ot,t),Bn(this,at,-2)}pause(e){e&&Bn(this,at,-2),super.pause(e)}async _poll(e,t){const n=await t.getBlock(Pn(this,ot));null!=n&&(-2===Pn(this,at)?Bn(this,at,n.number):n.number>Pn(this,at)&&(t.emit(Pn(this,ot),n.number),Bn(this,at,n.number)))}}ot=new WeakMap,at=new WeakMap;class Vy extends Gy{constructor(e,t){super(e),Dn(this,ct,void 0),Bn(this,ct,Fy(t))}async _poll(e,t){throw new Error("@TODO")}}ct=new WeakMap;class qy extends Gy{constructor(e,t){super(e),Dn(this,lt,void 0),Bn(this,lt,t)}async _poll(e,t){const n=await t.getTransactionReceipt(Pn(this,lt));n&&t.emit(Pn(this,lt),n)}}lt=new WeakMap;class Wy{constructor(e,t){Dn(this,gt),Dn(this,ut,void 0),Dn(this,ht,void 0),Dn(this,dt,void 0),Dn(this,ft,void 0),Dn(this,pt,void 0),Bn(this,ut,e),Bn(this,ht,Fy(t)),Bn(this,dt,Ln(this,gt,mt).bind(this)),Bn(this,ft,!1),Bn(this,pt,-2)}start(){Pn(this,ft)||(Bn(this,ft,!0),-2===Pn(this,pt)&&Pn(this,ut).getBlockNumber().then((e=>{Bn(this,pt,e)})),Pn(this,ut).on("block",Pn(this,dt)))}stop(){Pn(this,ft)&&(Bn(this,ft,!1),Pn(this,ut).off("block",Pn(this,dt)))}pause(e){this.stop(),e&&Bn(this,pt,-2)}resume(){this.start()}}ut=new WeakMap,ht=new WeakMap,dt=new WeakMap,ft=new WeakMap,pt=new WeakMap,gt=new WeakSet,mt=async function(e){if(-2===Pn(this,pt))return;const t=Fy(Pn(this,ht));t.fromBlock=Pn(this,pt)+1,t.toBlock=e;const n=await Pn(this,ut).getLogs(t);if(0!==n.length)for(const r of n)Pn(this,ut).emit(Pn(this,ht),r),Bn(this,pt,r.blockNumber);else Pn(this,pt)<e-60&&Bn(this,pt,e-60)};const zy=BigInt(2);function Ky(e){return new Promise((t=>{setTimeout(t,e)}))}function $y(e){return e&&"function"==typeof e.then}function Qy(e,t){return e+":"+JSON.stringify(t,((e,t)=>{if(null==t)return"null";if("bigint"==typeof t)return`bigint:${t.toString()}`;if("string"==typeof t)return t.toLowerCase();if("object"==typeof t&&!Array.isArray(t)){const e=Object.keys(t);return e.sort(),e.reduce(((e,n)=>(e[n]=t[n],e)),{})}return t}))}class Jy{constructor(e){xn(this,"name"),Ha(this,{name:e})}start(){}stop(){}pause(e){}resume(){}}function Yy(e){return(e=Array.from(new Set(e).values())).sort(),e}async function Zy(e,t){if(null==e)throw new Error("invalid event");if(Array.isArray(e)&&(e={topics:e}),"string"==typeof e)switch(e){case"block":case"debug":case"error":case"finalized":case"network":case"pending":case"safe":return{type:e,tag:e}}if(nc(e,32)){const t=e.toLowerCase();return{type:"transaction",tag:Qy("tx",{hash:t}),hash:t}}if(e.orphan){const t=e;return{type:"orphan",tag:Qy("orphan",t),filter:(n=t,JSON.parse(JSON.stringify(n)))}}var n;if(e.address||e.topics){const n=e,r={topics:(n.topics||[]).map((e=>null==e?null:Array.isArray(e)?Yy(e.map((e=>e.toLowerCase()))):e.toLowerCase()))};if(n.address){const e=[],s=[],i=n=>{nc(n)?e.push(n):s.push((async()=>{e.push(await Yd(n,t))})())};Array.isArray(n.address)?n.address.forEach(i):i(n.address),s.length&&await Promise.all(s),r.address=Yy(e.map((e=>e.toLowerCase())))}return{filter:r,tag:Qy("event",r),type:"event"}}$a(!1,"unknown ProviderEvent","event",e)}function Xy(){return(new Date).getTime()}const ew={cacheTimeout:250,pollingInterval:4e3};class tw{constructor(e,t){if(Dn(this,xt),Dn(this,Pt),Dn(this,Bt),Dn(this,Lt),Dn(this,Ft),Dn(this,Gt),Dn(this,Vt),Dn(this,Wt),Dn(this,yt,void 0),Dn(this,wt,void 0),Dn(this,bt,void 0),Dn(this,_t,void 0),Dn(this,At,void 0),Dn(this,vt,void 0),Dn(this,Et,void 0),Dn(this,kt,void 0),Dn(this,St,void 0),Dn(this,Tt,void 0),Dn(this,Rt,void 0),Dn(this,It,void 0),Dn(this,Ct,void 0),Dn(this,Ot,void 0),Bn(this,Ot,Object.assign({},ew,t||{})),"any"===e)Bn(this,vt,!0),Bn(this,At,null);else if(e){const t=By.from(e);Bn(this,vt,!1),Bn(this,At,Promise.resolve(t)),setTimeout((()=>{this.emit("network",t,null)}),0)}else Bn(this,vt,!1),Bn(this,At,null);Bn(this,kt,-1),Bn(this,Et,new Map),Bn(this,yt,new Map),Bn(this,wt,new Map),Bn(this,bt,null),Bn(this,_t,!1),Bn(this,St,1),Bn(this,Tt,new Map),Bn(this,Rt,!1),Bn(this,It,0),Bn(this,Ct,[])}get _requestRate(){const e=Pn(this,It);return 0==e?null:e}set _requestRate(e){(null==e||e<0)&&(e=0),Bn(this,It,Ac(e))}get pollingInterval(){return Pn(this,Ot).pollingInterval}get provider(){return this}get plugins(){return Array.from(Pn(this,wt).values())}attachPlugin(e){if(Pn(this,wt).get(e.name))throw new Error(`cannot replace existing plugin: ${e.name} `);return Pn(this,wt).set(e.name,e.connect(this)),this}getPlugin(e){return Pn(this,wt).get(e)||null}get disableCcipRead(){return Pn(this,Rt)}set disableCcipRead(e){Bn(this,Rt,!!e)}async ccipReadFetch(e,t,n){if(this.disableCcipRead||0===n.length||null==e.to)return null;const r=e.to.toLowerCase(),s=t.toLowerCase(),i=[];for(let a=0;a<n.length;a++){const t=n[a],c=t.replace("{sender}",r).replace("{data}",s),l=new $c(c);-1===t.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 e=u.bodyJson;if(e.data)return this.emit("debug",{action:"receiveCcipReadFetchResult",request:l,result:e}),e.data;e.message&&(h=e.message),this.emit("debug",{action:"receiveCcipReadFetchError",request:l,result:e})}catch(o){}Ka(u.statusCode<400||u.statusCode>=500,`response not found during CCIP fetch: ${h}`,"OFFCHAIN_FAULT",{reason:"404_MISSING_RESOURCE",transaction:e,info:{url:t,errorMessage:h}}),i.push(h)}Ka(!1,`error encountered during CCIP fetch: ${i.map((e=>JSON.stringify(e))).join(", ")}`,"OFFCHAIN_FAULT",{reason:"500_SERVER_ERROR",transaction:e,info:{urls:n,errorMessages:i}})}_wrapBlock(e,t){return new Rm(function(e){const t=ky(e);return t.transactions=e.transactions.map((e=>"string"==typeof e?e:Ry(e))),t}(e),this)}_wrapLog(e,t){return new Im(function(e){return Ey(e)}(e),this)}_wrapTransactionReceipt(e,t){return new Cm(function(e){return Ty(e)}(e),this)}_wrapTransactionResponse(e,t){return new Om(Ry(e),this)}_detectNetwork(){Ka(!1,"sub-classes must implement this","UNSUPPORTED_OPERATION",{operation:"_detectNetwork"})}async _perform(e){Ka(!1,`unsupported method: ${e.method}`,"UNSUPPORTED_OPERATION",{operation:e.method,info:e})}async getBlockNumber(){const e=Ac(await Ln(this,Pt,Dt).call(this,{method:"getBlockNumber"}),"%response");return Pn(this,kt)>=0&&Bn(this,kt,e),e}_getAddress(e){return Yd(e,this)}_getBlockTag(e){if(null==e)return"latest";switch(e){case"earliest":return"0x0";case"finalized":case"latest":case"pending":case"safe":return e}return nc(e)?nc(e,32)?e:kc(e):("bigint"==typeof e&&(e=Ac(e,"blockTag")),"number"==typeof e?e>=0?kc(e):Pn(this,kt)>=0?kc(Pn(this,kt)+e):this.getBlockNumber().then((t=>kc(t+e))):void $a(!1,"invalid blockTag","blockTag",e))}_getFilter(e){const t=(e.topics||[]).map((e=>null==e?null:Array.isArray(e)?Yy(e.map((e=>e.toLowerCase()))):e.toLowerCase())),n="blockHash"in e?e.blockHash:void 0,r=(e,r,s)=>{let i;switch(e.length){case 0:break;case 1:i=e[0];break;default:e.sort(),i=e}if(n&&(null!=r||null!=s))throw new Error("invalid filter");const o={};return i&&(o.address=i),t.length&&(o.topics=t),r&&(o.fromBlock=r),s&&(o.toBlock=s),n&&(o.blockHash=n),o};let s,i,o=[];if(e.address)if(Array.isArray(e.address))for(const a of e.address)o.push(this._getAddress(a));else o.push(this._getAddress(e.address));return"fromBlock"in e&&(s=this._getBlockTag(e.fromBlock)),"toBlock"in e&&(i=this._getBlockTag(e.toBlock)),o.filter((e=>"string"!=typeof e)).length||null!=s&&"string"!=typeof s||null!=i&&"string"!=typeof i?Promise.all([Promise.all(o),s,i]).then((e=>r(e[0],e[1],e[2]))):r(o,s,i)}_getTransactionRequest(e){const t=Tm(e),n=[];if(["to","from"].forEach((e=>{if(null==t[e])return;const r=Yd(t[e],this);$y(r)?n.push(async function(){t[e]=await r}()):t[e]=r})),null!=t.blockTag){const e=this._getBlockTag(t.blockTag);$y(e)?n.push(async function(){t.blockTag=await e}()):t.blockTag=e}return n.length?async function(){return await Promise.all(n),t}():t}async getNetwork(){if(null==Pn(this,At)){const e=(async()=>{try{const e=await this._detectNetwork();return this.emit("network",e,null),e}catch(t){throw Pn(this,At)===e&&Bn(this,At,null),t}})();return Bn(this,At,e),(await e).clone()}const e=Pn(this,At),[t,n]=await Promise.all([e,this._detectNetwork()]);return t.chainId!==n.chainId&&(Pn(this,vt)?(this.emit("network",n,t),Pn(this,At)===e&&Bn(this,At,Promise.resolve(n))):Ka(!1,`network changed: ${t.chainId} => ${n.chainId} `,"NETWORK_ERROR",{event:"changed"})),t.clone()}async getFeeData(){const e=await this.getNetwork(),t=async()=>{const{_block:t,gasPrice:n,priorityFee:r}=await Ga({_block:Ln(this,Gt,Ht).call(this,"latest",!1),gasPrice:(async()=>{try{return yc(await Ln(this,Pt,Dt).call(this,{method:"getGasPrice"}),"%response")}catch(e){}return null})(),priorityFee:(async()=>{try{return yc(await Ln(this,Pt,Dt).call(this,{method:"getPriorityFee"}),"%response")}catch(e){}return null})()});let s=null,i=null;const o=this._wrapBlock(t,e);return o&&o.baseFeePerGas&&(i=null!=r?r:BigInt("1000000000"),s=o.baseFeePerGas*zy+i),new Sm(n,s,i)},n=e.getPlugin("org.ethers.plugins.network.FetchUrlFeeDataPlugin");if(n){const e=new $c(n.url),r=await n.processFunc(t,this,e);return new Sm(r.gasPrice,r.maxFeePerGas,r.maxPriorityFeePerGas)}return await t()}async estimateGas(e){let t=this._getTransactionRequest(e);return $y(t)&&(t=await t),yc(await Ln(this,Pt,Dt).call(this,{method:"estimateGas",transaction:t}),"%response")}async call(e){const{tx:t,blockTag:n}=await Ga({tx:this._getTransactionRequest(e),blockTag:this._getBlockTag(e.blockTag)});return await Ln(this,Lt,Mt).call(this,Ln(this,Bt,Ut).call(this,t,n,e.enableCcipRead?0:-1))}async getBalance(e,t){return yc(await Ln(this,Ft,jt).call(this,{method:"getBalance"},e,t),"%response")}async getTransactionCount(e,t){return Ac(await Ln(this,Ft,jt).call(this,{method:"getTransactionCount"},e,t),"%response")}async getCode(e,t){return ic(await Ln(this,Ft,jt).call(this,{method:"getCode"},e,t))}async getStorage(e,t,n){const r=yc(t,"position");return ic(await Ln(this,Ft,jt).call(this,{method:"getStorage",position:r},e,n))}async broadcastTransaction(e){const{blockNumber:t,hash:n,network:r}=await Ga({blockNumber:this.getBlockNumber(),hash:this._perform({method:"broadcastTransaction",signedTransaction:e}),network:this.getNetwork()}),s=qf.from(e);if(s.hash!==n)throw new Error("@TODO: the returned hash did not match");return this._wrapTransactionResponse(s,r).replaceableTransaction(t)}async getBlock(e,t){const{network:n,params:r}=await Ga({network:this.getNetwork(),params:Ln(this,Gt,Ht).call(this,e,!!t)});return null==r?null:this._wrapBlock(r,n)}async getTransaction(e){const{network:t,params:n}=await Ga({network:this.getNetwork(),params:Ln(this,Pt,Dt).call(this,{method:"getTransaction",hash:e})});return null==n?null:this._wrapTransactionResponse(n,t)}async getTransactionReceipt(e){const{network:t,params:n}=await Ga({network:this.getNetwork(),params:Ln(this,Pt,Dt).call(this,{method:"getTransactionReceipt",hash:e})});if(null==n)return null;if(null==n.gasPrice&&null==n.effectiveGasPrice){const t=await Ln(this,Pt,Dt).call(this,{method:"getTransaction",hash:e});if(null==t)throw new Error("report this; could not find tx or effectiveGasPrice");n.effectiveGasPrice=t.gasPrice}return this._wrapTransactionReceipt(n,t)}async getTransactionResult(e){const{result:t}=await Ga({network:this.getNetwork(),result:Ln(this,Pt,Dt).call(this,{method:"getTransactionResult",hash:e})});return null==t?null:ic(t)}async getLogs(e){let t=this._getFilter(e);$y(t)&&(t=await t);const{network:n,params:r}=await Ga({network:this.getNetwork(),params:Ln(this,Pt,Dt).call(this,{method:"getLogs",filter:t})});return r.map((e=>this._wrapLog(e,n)))}_getProvider(e){Ka(!1,"provider cannot connect to target network","UNSUPPORTED_OPERATION",{operation:"_getProvider()"})}async getResolver(e){return await gy.fromName(this,e)}async getAvatar(e){const t=await this.getResolver(e);return t?await t.getAvatar():null}async resolveName(e,t){const n=await this.getResolver(e);return n?await n.getAddress(t):null}async lookupAddress(e,t){return await gy.lookupAddress(this,e,t)}async waitForTransaction(e,t,n){const r=null!=t?t:1;return 0===r?this.getTransactionReceipt(e):new Promise((async(t,s)=>{let i=null;const o=async n=>{try{const s=await this.getTransactionReceipt(e);if(null!=s&&n-s.blockNumber+1>=r)return t(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(za("timeout","TIMEOUT",{reason:"timeout"})))}),n)),o(await this.getBlockNumber())}))}async waitForBlock(e){Ka(!1,"not implemented yet","NOT_IMPLEMENTED",{operation:"waitForBlock"})}_clearTimeout(e){const t=Pn(this,Tt).get(e);t&&(t.timer&&clearTimeout(t.timer),Pn(this,Tt).delete(e))}_setTimeout(e,t){null==t&&(t=0);const n=Un(this,St)._++,r=()=>{Pn(this,Tt).delete(n),e()};if(this.paused)Pn(this,Tt).set(n,{timer:null,func:r,time:t});else{const e=setTimeout(r,t);Pn(this,Tt).set(n,{timer:e,func:r,time:Xy()})}return n}_forEachSubscriber(e){for(const t of Pn(this,yt).values())e(t.subscriber)}_getSubscriber(e){switch(e.type){case"debug":case"error":case"network":return new Jy(e.type);case"block":{const e=new jy(this);return e.pollingInterval=this.pollingInterval,e}case"safe":case"finalized":return new Hy(this,e.type);case"event":return new Wy(this,e.filter);case"transaction":return new qy(this,e.hash);case"orphan":return new Vy(this,e.filter)}throw new Error(`unsupported event: ${e.type}`)}_recoverSubscriber(e,t){for(const n of Pn(this,yt).values())if(n.subscriber===e){n.started&&n.subscriber.stop(),n.subscriber=t,n.started&&t.start(),null!=Pn(this,bt)&&t.pause(Pn(this,bt));break}}async on(e,t){const n=await Ln(this,Wt,zt).call(this,e);return n.listeners.push({listener:t,once:!1}),n.started||(n.subscriber.start(),n.started=!0,null!=Pn(this,bt)&&n.subscriber.pause(Pn(this,bt))),this}async once(e,t){const n=await Ln(this,Wt,zt).call(this,e);return n.listeners.push({listener:t,once:!0}),n.started||(n.subscriber.start(),n.started=!0,null!=Pn(this,bt)&&n.subscriber.pause(Pn(this,bt))),this}async emit(e,...t){const n=await Ln(this,Vt,qt).call(this,e,t);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 xc(this,r?null:n,e);try{n.call(this,...t,s)}catch(i){}return!r})),0===n.listeners.length&&(n.started&&n.subscriber.stop(),Pn(this,yt).delete(n.tag)),r>0}async listenerCount(e){if(e){const t=await Ln(this,Vt,qt).call(this,e);return t?t.listeners.length:0}let t=0;for(const{listeners:n}of Pn(this,yt).values())t+=n.length;return t}async listeners(e){if(e){const t=await Ln(this,Vt,qt).call(this,e);return t?t.listeners.map((({listener:e})=>e)):[]}let t=[];for(const{listeners:n}of Pn(this,yt).values())t=t.concat(n.map((({listener:e})=>e)));return t}async off(e,t){const n=await Ln(this,Vt,qt).call(this,e);if(!n)return this;if(t){const e=n.listeners.map((({listener:e})=>e)).indexOf(t);e>=0&&n.listeners.splice(e,1)}return t&&0!==n.listeners.length||(n.started&&n.subscriber.stop(),Pn(this,yt).delete(n.tag)),this}async removeAllListeners(e){if(e){const{tag:t,started:n,subscriber:r}=await Ln(this,Wt,zt).call(this,e);n&&r.stop(),Pn(this,yt).delete(t)}else for(const[t,{started:n,subscriber:r}]of Pn(this,yt))n&&r.stop(),Pn(this,yt).delete(t);return this}async addListener(e,t){return await this.on(e,t)}async removeListener(e,t){return this.off(e,t)}get destroyed(){return Pn(this,_t)}destroy(){this.removeAllListeners();for(const e of Pn(this,Tt).keys())this._clearTimeout(e);Bn(this,_t,!0)}get paused(){return null!=Pn(this,bt)}set paused(e){!!e!==this.paused&&(this.paused?this.resume():this.pause(!1))}pause(e){if(Bn(this,kt,-1),null!=Pn(this,bt)){if(Pn(this,bt)==!!e)return;Ka(!1,"cannot change pause type; resume first","UNSUPPORTED_OPERATION",{operation:"pause"})}this._forEachSubscriber((t=>t.pause(e))),Bn(this,bt,!!e);for(const t of Pn(this,Tt).values())t.timer&&clearTimeout(t.timer),t.time=Xy()-t.time}resume(){if(null!=Pn(this,bt)){this._forEachSubscriber((e=>e.resume())),Bn(this,bt,null);for(const e of Pn(this,Tt).values()){let t=e.time;t<0&&(t=0),e.time=Xy(),setTimeout(e.func,t)}}}}function nw(e,t){try{const n=rw(e,t);if(n)return Bc(n)}catch(n){}return null}function rw(e,t){if("0x"===e)return null;try{const n=Ac(cc(e,t,t+32)),r=Ac(cc(e,n,n+32));return cc(e,n+32,n+32+r)}catch(n){}return null}function sw(e){const t=Ec(e);if(t.length>32)throw new Error("internal; should not happen");const n=new Uint8Array(32);return n.set(t,32-t.length),n}function iw(e){if(e.length%32==0)return e;const t=new Uint8Array(32*Math.ceil(e.length/32));return t.set(e),t}yt=new WeakMap,wt=new WeakMap,bt=new WeakMap,_t=new WeakMap,At=new WeakMap,vt=new WeakMap,Et=new WeakMap,kt=new WeakMap,St=new WeakMap,Tt=new WeakMap,Rt=new WeakMap,It=new WeakMap,Ct=new WeakMap,Ot=new WeakMap,xt=new WeakSet,Nt=function(){let e=Pn(this,It);if(0===e)return 0;const t=Pn(this,Ct),n=Xy();t.push(n);const r=n-1e3;for(;t.length&&t[0]<r;)t.shift();return t.length<e?0:t[0]+1e3-n},Pt=new WeakSet,Dt=async function(e){const t=Pn(this,Ot).cacheTimeout;if(t<0){const t=Ln(this,xt,Nt).call(this);return t&&await Ky(t),await this._perform(e)}const n=Qy(e.method,e);let r=Pn(this,Et).get(n);if(!r){const s=Ln(this,xt,Nt).call(this);s&&await Ky(s),r=this._perform(e),Pn(this,Et).set(n,r),setTimeout((()=>{Pn(this,Et).get(n)===r&&Pn(this,Et).delete(n)}),t)}return await r},Bt=new WeakSet,Ut=async function(e,t,n){Ka(n<10,"CCIP read exceeded maximum redirections","OFFCHAIN_FAULT",{reason:"TOO_MANY_REDIRECTS",transaction:Object.assign({},e,{blockTag:t,enableCcipRead:!0})});const r=Tm(e);try{const e=Ln(this,xt,Nt).call(this);return e&&await Ky(e),ic(await this._perform({method:"call",transaction:r,blockTag:t}))}catch(s){if(!this.disableCcipRead&&Wa(s)&&s.data&&n>=0&&"latest"===t&&null!=r.to&&"0x556f1830"===cc(s.data,0,4)){const e=s.data,o=await Yd(r.to,this);let a;try{a=function(e){const t={sender:"",urls:[],calldata:"",selector:"",extraData:"",errorArgs:[]};Ka(ac(e)>=160,"insufficient OffchainLookup data","OFFCHAIN_FAULT",{reason:"insufficient OffchainLookup data"});const n=cc(e,0,32);Ka(cc(n,0,12)===cc(cw,0,12),"corrupt OffchainLookup sender","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup sender"}),t.sender=cc(n,12);try{const n=[],r=Ac(cc(e,32,64)),s=Ac(cc(e,r,r+32)),i=cc(e,r+32);for(let e=0;e<s;e++){const t=nw(i,32*e);if(null==t)throw new Error("abort");n.push(t)}t.urls=n}catch(s){Ka(!1,"corrupt OffchainLookup urls","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup urls"})}try{const n=rw(e,64);if(null==n)throw new Error("abort");t.calldata=n}catch(s){Ka(!1,"corrupt OffchainLookup calldata","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup calldata"})}Ka(cc(e,100,128)===cc(cw,0,28),"corrupt OffchainLookup callbaackSelector","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup callbaackSelector"}),t.selector=cc(e,96,100);try{const n=rw(e,128);if(null==n)throw new Error("abort");t.extraData=n}catch(s){Ka(!1,"corrupt OffchainLookup extraData","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup extraData"})}return t.errorArgs="sender,urls,calldata,selector,extraData".split(/,/).map((e=>t[e])),t}(cc(s.data,4))}catch(i){Ka(!1,i.message,"OFFCHAIN_FAULT",{reason:"BAD_DATA",transaction:r,info:{data:e}})}Ka(a.sender.toLowerCase()===o.toLowerCase(),"CCIP Read sender mismatch","CALL_EXCEPTION",{action:"call",data:e,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);Ka(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:oc([a.selector,aw([c,a.extraData])])};this.emit("debug",{action:"sendCcipReadCall",transaction:l});try{const e=await Ln(this,Bt,Ut).call(this,l,t,n+1);return this.emit("debug",{action:"receiveCcipReadCallResult",transaction:Object.assign({},l),result:e}),e}catch(i){throw this.emit("debug",{action:"receiveCcipReadCallError",transaction:Object.assign({},l),error:i}),i}}throw s}},Lt=new WeakSet,Mt=async function(e){const{value:t}=await Ga({network:this.getNetwork(),value:e});return t},Ft=new WeakSet,jt=async function(e,t,n){let r=this._getAddress(t),s=this._getBlockTag(n);return"string"==typeof r&&"string"==typeof s||([r,s]=await Promise.all([r,s])),await Ln(this,Lt,Mt).call(this,Ln(this,Pt,Dt).call(this,Object.assign(e,{address:r,blockTag:s})))},Gt=new WeakSet,Ht=async function(e,t){if(nc(e,32))return await Ln(this,Pt,Dt).call(this,{method:"getBlock",blockHash:e,includeTransactions:t});let n=this._getBlockTag(e);return"string"!=typeof n&&(n=await n),await Ln(this,Pt,Dt).call(this,{method:"getBlock",blockTag:n,includeTransactions:t})},Vt=new WeakSet,qt=async function(e,t){let n=await Zy(e,this);return"event"===n.type&&t&&t.length>0&&!0===t[0].removed&&(n=await Zy({orphan:"drop-log",log:t[0]},this)),Pn(this,yt).get(n.tag)||null},Wt=new WeakSet,zt=async function(e){const t=await Zy(e,this),n=t.tag;let r=Pn(this,yt).get(n);if(!r){r={subscriber:this._getSubscriber(t),tag:n,addressableMap:new WeakMap,nameMap:new Map,started:!1,listeners:[]},Pn(this,yt).set(n,r)}return r};const ow=new Uint8Array([]);function aw(e){const t=[];let n=0;for(let r=0;r<e.length;r++)t.push(ow),n+=32;for(let r=0;r<e.length;r++){const s=ec(e[r]);t[r]=sw(n),t.push(sw(s.length)),t.push(iw(s)),n+=32+32*Math.ceil(s.length/32)}return oc(t)}const cw="0x0000000000000000000000000000000000000000000000000000000000000000";function lw(e,t){if(e.provider)return e.provider;Ka(!1,"missing provider","UNSUPPORTED_OPERATION",{operation:t})}async function uw(e,t){let n=Tm(t);if(null!=n.to&&(n.to=Yd(n.to,e)),null!=n.from){const t=n.from;n.from=Promise.all([e.getAddress(),Yd(t,e)]).then((([e,t])=>($a(e.toLowerCase()===t.toLowerCase(),"transaction from mismatch","tx.from",t),e)))}else n.from=e.getAddress();return await Ga(n)}class hw{constructor(e){xn(this,"provider"),Ha(this,{provider:e||null})}async getNonce(e){return lw(this,"getTransactionCount").getTransactionCount(await this.getAddress(),e)}async populateCall(e){return await uw(this,e)}async populateTransaction(e){const t=lw(this,"populateTransaction"),n=await uw(this,e);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){$a(yc(n.chainId)===r.chainId,"transaction chainId mismatch","tx.chainId",e.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||$a(!1,"pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas","tx",e):$a(!1,"eip-1559 transaction do not support gasPrice","tx",e),2!==n.type&&null!=n.type||null==n.maxFeePerGas||null==n.maxPriorityFeePerGas)if(0===n.type||1===n.type){const e=await t.getFeeData();Ka(null!=e.gasPrice,"network does not support gasPrice","UNSUPPORTED_OPERATION",{operation:"getGasPrice"}),null==n.gasPrice&&(n.gasPrice=e.gasPrice)}else{const e=await t.getFeeData();if(null==n.type)if(null!=e.maxFeePerGas&&null!=e.maxPriorityFeePerGas)if(n.authorizationList&&n.authorizationList.length?n.type=4:n.type=2,null!=n.gasPrice){const e=n.gasPrice;delete n.gasPrice,n.maxFeePerGas=e,n.maxPriorityFeePerGas=e}else null==n.maxFeePerGas&&(n.maxFeePerGas=e.maxFeePerGas),null==n.maxPriorityFeePerGas&&(n.maxPriorityFeePerGas=e.maxPriorityFeePerGas);else null!=e.gasPrice?(Ka(!s,"network does not support EIP-1559","UNSUPPORTED_OPERATION",{operation:"populateTransaction"}),null==n.gasPrice&&(n.gasPrice=e.gasPrice),n.type=0):Ka(!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=e.maxFeePerGas),null==n.maxPriorityFeePerGas&&(n.maxPriorityFeePerGas=e.maxPriorityFeePerGas))}else n.type=2;return await Ga(n)}async populateAuthorization(e){const t=Object.assign({},e);return null==t.chainId&&(t.chainId=(await lw(this,"getNetwork").getNetwork()).chainId),null==t.nonce&&(t.nonce=await this.getNonce()),t}async estimateGas(e){return lw(this,"estimateGas").estimateGas(await this.populateCall(e))}async call(e){return lw(this,"call").call(await this.populateCall(e))}async resolveName(e){const t=lw(this,"resolveName");return await t.resolveName(e)}async sendTransaction(e){const t=lw(this,"sendTransaction"),n=await this.populateTransaction(e);delete n.from;const r=qf.from(n);return await t.broadcastTransaction(await this.signTransaction(r))}authorize(e){Ka(!1,"authorization not implemented for this signer","UNSUPPORTED_OPERATION",{operation:"authorize"})}}Kt=new WeakSet,$t=function(e,t){Ka(!1,`VoidSigner cannot sign ${e}`,"UNSUPPORTED_OPERATION",{operation:t})};let dw=class e extends hw{constructor(e,t){super(t),Dn(this,Kt),xn(this,"address"),Ha(this,{address:e})}async getAddress(){return this.address}connect(t){return new e(this.address,t)}async signTransaction(e){Ln(this,Kt,$t).call(this,"transactions","signTransaction")}async signMessage(e){Ln(this,Kt,$t).call(this,"messages","signMessage")}async signTypedData(e,t,n){Ln(this,Kt,$t).call(this,"typed-data","signTypedData")}};class fw{constructor(e){Dn(this,tn),Dn(this,rn),Dn(this,Qt,void 0),Dn(this,Jt,void 0),Dn(this,Yt,void 0),Dn(this,Zt,void 0),Dn(this,Xt,void 0),Dn(this,en,void 0),Bn(this,Qt,e),Bn(this,Jt,null),Bn(this,Yt,Ln(this,tn,nn).bind(this)),Bn(this,Zt,!1),Bn(this,Xt,null),Bn(this,en,!1)}_subscribe(e){throw new Error("subclasses must override this")}_emitResults(e,t){throw new Error("subclasses must override this")}_recover(e){throw new Error("subclasses must override this")}start(){Pn(this,Zt)||(Bn(this,Zt,!0),Ln(this,tn,nn).call(this,-2))}stop(){Pn(this,Zt)&&(Bn(this,Zt,!1),Bn(this,en,!0),Ln(this,rn,sn).call(this),Pn(this,Qt).off("block",Pn(this,Yt)))}pause(e){e&&Ln(this,rn,sn).call(this),Pn(this,Qt).off("block",Pn(this,Yt))}resume(){this.start()}}Qt=new WeakMap,Jt=new WeakMap,Yt=new WeakMap,Zt=new WeakMap,Xt=new WeakMap,en=new WeakMap,tn=new WeakSet,nn=async function(e){try{null==Pn(this,Jt)&&Bn(this,Jt,this._subscribe(Pn(this,Qt)));let e=null;try{e=await Pn(this,Jt)}catch(t){if(!qa(t,"UNSUPPORTED_OPERATION")||"eth_newFilter"!==t.operation)throw t}if(null==e)return Bn(this,Jt,null),void Pn(this,Qt)._recoverSubscriber(this,this._recover(Pn(this,Qt)));const n=await Pn(this,Qt).getNetwork();if(Pn(this,Xt)||Bn(this,Xt,n),Pn(this,Xt).chainId!==n.chainId)throw new Error("chaid changed");if(Pn(this,en))return;const r=await Pn(this,Qt).send("eth_getFilterChanges",[e]);await this._emitResults(Pn(this,Qt),r)}catch(t){console.log("@TODO",t)}Pn(this,Qt).once("block",Pn(this,Yt))},rn=new WeakSet,sn=function(){const e=Pn(this,Jt);e&&(Bn(this,Jt,null),e.then((e=>{Pn(this,Qt).destroyed||Pn(this,Qt).send("eth_uninstallFilter",[e])})))};class pw extends fw{constructor(e,t){var n;super(e),Dn(this,on,void 0),Bn(this,on,(n=t,JSON.parse(JSON.stringify(n))))}_recover(e){return new Wy(e,Pn(this,on))}async _subscribe(e){return await e.send("eth_newFilter",[Pn(this,on)])}async _emitResults(e,t){for(const n of t)e.emit(Pn(this,on),e._wrapLog(n,e._network))}}on=new WeakMap;class gw extends fw{async _subscribe(e){return await e.send("eth_newPendingTransactionFilter",[])}async _emitResults(e,t){for(const n of t)e.emit("pending",n)}}const mw="bigint,boolean,function,number,string,symbol".split(/,/g);function yw(e){if(null==e||mw.indexOf(typeof e)>=0)return e;if("function"==typeof e.getAddress)return e;if(Array.isArray(e))return e.map(yw);if("object"==typeof e)return Object.keys(e).reduce(((t,n)=>(t[n]=e[n],t)),{});throw new Error(`should not happen: ${e} (${typeof e})`)}function ww(e){return new Promise((t=>{setTimeout(t,e)}))}function bw(e){return e?e.toLowerCase():e}function _w(e){return e&&"number"==typeof e.pollingInterval}const Aw={polling:!1,staticNetwork:null,batchStallTime:10,batchMaxSize:1<<20,batchMaxCount:100,cacheTimeout:250,pollingInterval:4e3};class vw extends hw{constructor(e,t){super(e),xn(this,"address"),Ha(this,{address:t=$d(t)})}connect(e){Ka(!1,"cannot reconnect JsonRpcSigner","UNSUPPORTED_OPERATION",{operation:"signer.connect"})}async getAddress(){return this.address}async populateTransaction(e){return await this.populateCall(e)}async sendUncheckedTransaction(e){const t=yw(e),n=[];if(t.from){const r=t.from;n.push((async()=>{const n=await Yd(r,this.provider);$a(null!=n&&n.toLowerCase()===this.address.toLowerCase(),"from address mismatch","transaction",e),t.from=n})())}else t.from=this.address;if(null==t.gasLimit&&n.push((async()=>{t.gasLimit=await this.provider.estimateGas({...t,from:this.address})})()),null!=t.to){const e=t.to;n.push((async()=>{t.to=await Yd(e,this.provider)})())}n.length&&await Promise.all(n);const r=this.provider.getRpcTransaction(t);return this.provider.send("eth_sendTransaction",[r])}async sendTransaction(e){const t=await this.provider.getBlockNumber(),n=await this.sendUncheckedTransaction(e);return await new Promise(((e,r)=>{const s=[1e3,100];let i=0;const o=async()=>{try{const r=await this.provider.getTransaction(n);if(null!=r)return void e(r.replaceableTransaction(t))}catch(a){if(qa(a,"CANCELLED")||qa(a,"BAD_DATA")||qa(a,"NETWORK_ERROR")||qa(a,"UNSUPPORTED_OPERATION"))return null==a.info&&(a.info={}),a.info.sendTransactionHash=n,void r(a);if(qa(a,"INVALID_ARGUMENT")&&(i++,null==a.info&&(a.info={}),a.info.sendTransactionHash=n,i>10))return void r(a);this.provider.emit("error",za("failed to fetch transation after sending (will try again)","UNKNOWN_ERROR",{error:a}))}this.provider._setTimeout((()=>{o()}),s.pop()||4e3)};o()}))}async signTransaction(e){const t=yw(e);if(t.from){const n=await Yd(t.from,this.provider);$a(null!=n&&n.toLowerCase()===this.address.toLowerCase(),"from address mismatch","transaction",e),t.from=n}else t.from=this.address;const n=this.provider.getRpcTransaction(t);return await this.provider.send("eth_signTransaction",[n])}async signMessage(e){const t="string"==typeof e?Dc(e):e;return await this.provider.send("personal_sign",[ic(t),this.address.toLowerCase()])}async signTypedData(e,t,n){const r=yw(n),s=await mg.resolveNames(e,t,r,(async e=>{const t=await Yd(e);return $a(null!=t,"TypedData does not support null address","value",e),t}));return await this.provider.send("eth_signTypedData_v4",[this.address.toLowerCase(),JSON.stringify(mg.getPayload(s.domain,t,s.value))])}async unlock(e){return this.provider.send("personal_unlockAccount",[this.address.toLowerCase(),e,null])}async _legacySignMessage(e){const t="string"==typeof e?Dc(e):e;return await this.provider.send("eth_sign",[this.address.toLowerCase(),ic(t)])}}class Ew extends tw{constructor(e,t){super(e,t),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({},Aw,t||{})),Bn(this,ln,[]),Bn(this,un,null),Bn(this,dn,null),Bn(this,fn,null);{let e=null;const t=new Promise((t=>{e=t}));Bn(this,hn,{promise:t,resolve:e})}const n=this._getOption("staticNetwork");"boolean"==typeof n?($a(!n||"any"!==e,"staticNetwork cannot be used on special network 'any'","options",t),n&&null!=e&&Bn(this,dn,By.from(e))):n&&($a(null==e||n.matches(e),"staticNetwork MUST match network object","options",t),Bn(this,dn,n))}_getOption(e){return Pn(this,an)[e]}get _network(){return Ka(Pn(this,dn),"network is not available yet","NETWORK_ERROR"),Pn(this,dn)}async _perform(e){if("call"===e.method||"estimateGas"===e.method){let t=e.transaction;if(t&&null!=t.type&&yc(t.type)&&null==t.maxFeePerGas&&null==t.maxPriorityFeePerGas){const n=await this.getFeeData();null==n.maxFeePerGas&&null==n.maxPriorityFeePerGas&&(e=Object.assign({},e,{transaction:Object.assign({},t,{type:void 0})}))}}const t=this.getRpcRequest(e);return null!=t?await this.send(t.method,t.args):super._perform(e)}async _detectNetwork(){const e=this._getOption("staticNetwork");if(e){if(!0!==e)return e;if(Pn(this,dn))return Pn(this,dn)}return Pn(this,fn)?await Pn(this,fn):this.ready?(Bn(this,fn,(async()=>{try{const e=By.from(yc(await this.send("eth_chainId",[])));return Bn(this,fn,null),e}catch(e){throw Bn(this,fn,null),e}})()),await Pn(this,fn)):(Bn(this,fn,(async()=>{const e={id:Un(this,cn)._++,method:"eth_chainId",params:[],jsonrpc:"2.0"};let t;this.emit("debug",{action:"sendRpcPayload",payload:e});try{t=(await this._send(e))[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:t}),"result"in t)return By.from(yc(t.result));throw this.getRpcError(e,t)})()),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(e){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",za("failed to bootstrap network detection","NETWORK_ERROR",{event:"initial-network-discovery",info:{error:e}})),await ww(1e3)}Ln(this,pn,gn).call(this)})())}async _waitUntilReady(){if(null!=Pn(this,hn))return await Pn(this,hn).promise}_getSubscriber(e){return"pending"===e.type?new gw(this):"event"===e.type?this._getOption("polling")?new Wy(this,e.filter):new pw(this,e.filter):"orphan"===e.type&&"drop-log"===e.filter.orphan?new Jy("orphan"):super._getSubscriber(e)}get ready(){return null==Pn(this,hn)}getRpcTransaction(e){const t={};return["chainId","gasLimit","gasPrice","type","maxFeePerGas","maxPriorityFeePerGas","nonce","value"].forEach((n=>{if(null==e[n])return;let r=n;"gasLimit"===n&&(r="gas"),t[r]=kc(yc(e[n],`tx.${n}`))})),["from","to","data"].forEach((n=>{null!=e[n]&&(t[n]=ic(e[n]))})),e.accessList&&(t.accessList=vf(e.accessList)),e.blobVersionedHashes&&(t.blobVersionedHashes=e.blobVersionedHashes.map((e=>e.toLowerCase()))),e.authorizationList&&(t.authorizationList=e.authorizationList.map((e=>{const t=Ef(e);return{address:t.address,nonce:kc(t.nonce),chainId:kc(t.chainId),yParity:kc(t.signature.yParity),r:kc(t.signature.r),s:kc(t.signature.s)}}))),t}getRpcRequest(e){switch(e.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:[bw(e.address),e.blockTag]};case"getTransactionCount":return{method:"eth_getTransactionCount",args:[bw(e.address),e.blockTag]};case"getCode":return{method:"eth_getCode",args:[bw(e.address),e.blockTag]};case"getStorage":return{method:"eth_getStorageAt",args:[bw(e.address),"0x"+e.position.toString(16),e.blockTag]};case"broadcastTransaction":return{method:"eth_sendRawTransaction",args:[e.signedTransaction]};case"getBlock":if("blockTag"in e)return{method:"eth_getBlockByNumber",args:[e.blockTag,!!e.includeTransactions]};if("blockHash"in e)return{method:"eth_getBlockByHash",args:[e.blockHash,!!e.includeTransactions]};break;case"getTransaction":return{method:"eth_getTransactionByHash",args:[e.hash]};case"getTransactionReceipt":return{method:"eth_getTransactionReceipt",args:[e.hash]};case"call":return{method:"eth_call",args:[this.getRpcTransaction(e.transaction),e.blockTag]};case"estimateGas":return{method:"eth_estimateGas",args:[this.getRpcTransaction(e.transaction)]};case"getLogs":return e.filter&&null!=e.filter.address&&(Array.isArray(e.filter.address)?e.filter.address=e.filter.address.map(bw):e.filter.address=bw(e.filter.address)),{method:"eth_getLogs",args:[e.filter]}}return null}getRpcError(e,t){const{method:n}=e,{error:r}=t;if("eth_estimateGas"===n&&r.message){const t=r.message;if(!t.match(/revert/i)&&t.match(/insufficient funds/i))return za("insufficient funds","INSUFFICIENT_FUNDS",{transaction:e.params[0],info:{payload:e,error:r}});if(t.match(/nonce/i)&&t.match(/too low/i))return za("nonce has already been used","NONCE_EXPIRED",{transaction:e.params[0],info:{payload:e,error:r}})}if("eth_call"===n||"eth_estimateGas"===n){const t=Tw(r),s=pm.getBuiltinCallException("eth_call"===n?"call":"estimateGas",e.params[0],t?t.data:null);return s.info={error:r,payload:e},s}const s=JSON.stringify(function(e){const t=[];return Rw(e,t),t}(r));if("string"==typeof r.message&&r.message.match(/user denied|ethers-user-denied/i)){return za("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:e,error:r}})}if("eth_sendRawTransaction"===n||"eth_sendTransaction"===n){const t=e.params[0];if(s.match(/insufficient funds|base fee exceeds gas limit/i))return za("insufficient funds for intrinsic transaction cost","INSUFFICIENT_FUNDS",{transaction:t,info:{error:r}});if(s.match(/nonce/i)&&s.match(/too low/i))return za("nonce has already been used","NONCE_EXPIRED",{transaction:t,info:{error:r}});if(s.match(/replacement transaction/i)&&s.match(/underpriced/i))return za("replacement fee too low","REPLACEMENT_UNDERPRICED",{transaction:t,info:{error:r}});if(s.match(/only replay-protected/i))return za("legacy pre-eip-155 transactions not supported","UNSUPPORTED_OPERATION",{operation:n,info:{transaction:t,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?za("unsupported operation","UNSUPPORTED_OPERATION",{operation:e.method,info:{error:r,payload:e}}):za("could not coalesce error","UNKNOWN_ERROR",{error:r,payload:e})}send(e,t){if(this.destroyed)return Promise.reject(za("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:e}));const n=Un(this,cn)._++,r=new Promise(((r,s)=>{Pn(this,ln).push({resolve:r,reject:s,payload:{method:e,params:t,id:n,jsonrpc:"2.0"}})}));return Ln(this,pn,gn).call(this),r}async getSigner(e){null==e&&(e=0);const t=this.send("eth_accounts",[]);if("number"==typeof e){const n=await t;if(e>=n.length)throw new Error("no such account");return new vw(this,n[e])}const{accounts:n}=await Ga({network:this.getNetwork(),accounts:t});e=$d(e);for(const r of n)if($d(r)===e)return new vw(this,e);throw new Error("invalid account")}async listAccounts(){return(await this.send("eth_accounts",[])).map((e=>new vw(this,e)))}destroy(){Pn(this,un)&&(clearTimeout(Pn(this,un)),Bn(this,un,null));for(const{payload:e,reject:t}of Pn(this,ln))t(za("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:e.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 e=1===this._getOption("batchMaxCount")?0:this._getOption("batchStallTime");Bn(this,un,setTimeout((()=>{Bn(this,un,null);const e=Pn(this,ln);for(Bn(this,ln,[]);e.length;){const t=[e.shift()];for(;e.length&&t.length!==Pn(this,an).batchMaxCount;){t.push(e.shift());if(JSON.stringify(t.map((e=>e.payload))).length>Pn(this,an).batchMaxSize){e.unshift(t.pop());break}}(async()=>{const e=1===t.length?t[0].payload:t.map((e=>e.payload));this.emit("debug",{action:"sendRpcPayload",payload:e});try{const n=await this._send(e);this.emit("debug",{action:"receiveRpcResult",result:n});for(const{resolve:e,reject:r,payload:s}of t){if(this.destroyed){r(za("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:s.method}));continue}const t=n.filter((e=>e.id===s.id))[0];if(null!=t)"error"in t?r(this.getRpcError(s,t)):e(t.result);else{const e=za("missing response for request","BAD_DATA",{value:n,info:{payload:s}});this.emit("error",e),r(e)}}}catch(n){this.emit("debug",{action:"receiveRpcError",error:n});for(const{reject:e}of t)e(n)}})()}}),e))};class kw extends Ew{constructor(e,t){super(e,t),Dn(this,mn,void 0);let n=this._getOption("pollingInterval");null==n&&(n=Aw.pollingInterval),Bn(this,mn,n)}_getSubscriber(e){const t=super._getSubscriber(e);return _w(t)&&(t.pollingInterval=Pn(this,mn)),t}get pollingInterval(){return Pn(this,mn)}set pollingInterval(e){if(!Number.isInteger(e)||e<0)throw new Error("invalid interval");Bn(this,mn,e),this._forEachSubscriber((e=>{_w(e)&&(e.pollingInterval=Pn(this,mn))}))}}mn=new WeakMap;class Sw extends kw{constructor(e,t,n){null==e&&(e="http://localhost:8545"),super(t,n),Dn(this,yn,void 0),Bn(this,yn,"string"==typeof e?new $c(e):e.clone())}_getConnection(){return Pn(this,yn).clone()}async send(e,t){return await this._start(),await super.send(e,t)}async _send(e){const t=this._getConnection();t.body=JSON.stringify(e),t.setHeader("content-type","application/json");const n=await t.send();n.assertOk();let r=n.bodyJson;return Array.isArray(r)||(r=[r]),r}}function Tw(e){if(null==e)return null;if("string"==typeof e.message&&e.message.match(/revert/i)&&nc(e.data))return{message:e.message,data:e.data};if("object"==typeof e){for(const t in e){const n=Tw(e[t]);if(n)return n}return null}if("string"==typeof e)try{return Tw(JSON.parse(e))}catch(t){}return null}function Rw(e,t){if(null!=e){if("string"==typeof e.message&&t.push(e.message),"object"==typeof e)for(const n in e)Rw(e[n],t);if("string"==typeof e)try{return Rw(JSON.parse(e),t)}catch(n){}}}yn=new WeakMap;wn=new WeakMap;let Iw=class e extends hw{constructor(e,t){super(t),xn(this,"address"),Dn(this,wn,void 0),$a(e&&"function"==typeof e.sign,"invalid private key","privateKey","[ REDACTED ]"),Bn(this,wn,e);Ha(this,{address:kf(this.signingKey.publicKey)})}get signingKey(){return Pn(this,wn)}get privateKey(){return this.signingKey.privateKey}async getAddress(){return this.address}connect(t){return new e(Pn(this,wn),t)}async signTransaction(e){e=Tm(e);const{to:t,from:n}=await Ga({to:e.to?Yd(e.to,this):void 0,from:e.from?Yd(e.from,this):void 0});null!=t&&(e.to=t),null!=n&&(e.from=n),null!=e.from&&($a($d(e.from)===this.address,"transaction from address mismatch","tx.from",e.from),delete e.from);const r=qf.from(e);return r.signature=this.signingKey.sign(r.unsignedHash),r.serialized}async signMessage(e){return this.signMessageSync(e)}signMessageSync(e){return this.signingKey.sign(function(e){return"string"==typeof e&&(e=Dc(e)),Bu(oc([Dc("Ethereum Signed Message:\n"),Dc(String(e.length)),e]))}(e)).serialized}authorizeSync(e){$a("string"==typeof e.address,"invalid address for authorizeSync","auth.address",e);const t=this.signingKey.sign(function(e){return $a("string"==typeof e.address,"invalid address for hashAuthorization","auth.address",e),Bu(oc(["0x05",ol([null!=e.chainId?Ec(e.chainId):"0x",$d(e.address),null!=e.nonce?Ec(e.nonce):"0x"])]))}(e));return Object.assign({},{address:$d(e.address),nonce:yc(e.nonce||0),chainId:yc(e.chainId||0)},{signature:t})}async authorize(e){return e=Object.assign({},e,{address:await Yd(e.address,this)}),this.authorizeSync(await this.populateAuthorization(e))}async signTypedData(e,t,n){const r=await mg.resolveNames(e,t,n,(async e=>{Ka(null!=this.provider,"cannot resolve ENS names without a provider","UNSUPPORTED_OPERATION",{operation:"resolveName",info:{name:e}});const t=await this.provider.resolveName(e);return Ka(null!=t,"unconfigured ENS name","UNCONFIGURED_NAME",{value:e}),t}));return this.signingKey.sign(mg.hash(r.domain,t,r.value)).serialized}};const Cw=" !#$%&'()*+,-./<=>?@[]^_`{|}~",Ow=/^[a-z]*$/i;function xw(e,t){let n=97;return e.reduce(((e,r)=>(r===t?n++:r.match(Ow)?e.push(String.fromCharCode(n)+r):(n=97,e.push(r)),e)),[])}function Nw(e){return $a("0"===e[0],"unsupported auwl data","data",e),function(e,t){for(let s=28;s>=0;s--)e=e.split(Cw[s]).join(t.substring(2*s,2*s+2));const n=[],r=e.replace(/(:|([0-9])|([A-Z][a-z]*))/g,((e,t,r,s)=>{if(r)for(let i=parseInt(r);i>=0;i--)n.push(";");else n.push(t.toLowerCase());return""}));if(r)throw new Error(`leftovers: ${JSON.stringify(r)}`);return xw(xw(n,";"),":")}(e.substring(59),e.substring(1,59))}class Pw{constructor(e){xn(this,"locale"),Ha(this,{locale:e})}split(e){return e.toLowerCase().split(/\s+/g)}join(e){return e.join(" ")}}class Dw extends Pw{constructor(e,t,n){super(e),Dn(this,vn),Dn(this,bn,void 0),Dn(this,_n,void 0),Dn(this,An,void 0),Bn(this,bn,t),Bn(this,_n,n),Bn(this,An,null)}get _data(){return Pn(this,bn)}_decodeWords(){return Nw(Pn(this,bn))}getWord(e){const t=Ln(this,vn,En).call(this);return $a(e>=0&&e<t.length,`invalid word index: ${e}`,"index",e),t[e]}getWordIndex(e){return Ln(this,vn,En).call(this).indexOf(e)}}bn=new WeakMap,_n=new WeakMap,An=new WeakMap,vn=new WeakSet,En=function(){if(null==Pn(this,An)){const e=this._decodeWords();if(Wf(e.join("\n")+"\n")!==Pn(this,_n))throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`);Bn(this,An,e)}return Pn(this,An)};let Bw=null;class Uw extends Dw{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==Bw&&(Bw=new Uw),Bw}}function Lw(e){return(1<<e)-1<<8-e&255}function Mw(e,t){Ya("NFKD"),null==t&&(t=Uw.wordlist());const n=t.split(e);$a(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 e=t.getWordIndex(n[a].normalize("NFKD"));$a(e>=0,`invalid mnemonic word at index ${a}`,"mnemonic","[ REDACTED ]");for(let t=0;t<11;t++)e&1<<10-t&&(r[s>>3]|=1<<7-s%8),s++}const i=32*n.length/3,o=Lw(n.length/3);return $a((ec(kh(r.slice(0,i/8)))[0]&o)===(r[r.length-1]&o),"invalid mnemonic checksum","mnemonic","[ REDACTED ]"),ic(r.slice(0,i/8))}function Fw(e,t){$a(e.length%4==0&&e.length>=16&&e.length<=32,"invalid entropy size","entropy","[ REDACTED ]"),null==t&&(t=Uw.wordlist());const n=[0];let r=11;for(let o=0;o<e.length;o++)r>8?(n[n.length-1]<<=8,n[n.length-1]|=e[o],r-=8):(n[n.length-1]<<=r,n[n.length-1]|=e[o]>>8-r,n.push(e[o]&((1<<8-r)-1&255)),r+=3);const s=e.length/4,i=parseInt(kh(e).substring(2,4),16)&Lw(s);return n[n.length-1]<<=s,n[n.length-1]|=i>>8-s,t.join(n.map((e=>t.getWord(e))))}const jw={};class Gw{constructor(e,t,n,r,s){xn(this,"phrase"),xn(this,"password"),xn(this,"wordlist"),xn(this,"entropy"),null==r&&(r=""),null==s&&(s=Uw.wordlist()),Za(e,jw,"Mnemonic"),Ha(this,{phrase:n,password:r,wordlist:s,entropy:t})}computeSeed(){const e=Dc("mnemonic"+this.password,"NFKD");return rh(Dc(this.phrase,"NFKD"),e,2048,64,"sha512")}static fromPhrase(e,t,n){const r=Mw(e,n);return e=Fw(ec(r),n),new Gw(jw,r,e,t,n)}static fromEntropy(e,t,n){const r=ec(e,"entropy"),s=Fw(r,n);return new Gw(jw,ic(r),s,t,n)}static entropyToPhrase(e,t){return Fw(ec(e,"entropy"),t)}static phraseToEntropy(e,t){return Mw(e,t)}static isValidMnemonic(e,t){try{return Mw(e,t),!0}catch(n){}return!1}}
|
|
12
|
-
/*! MIT License. Copyright 2015-2022 Richard Moore <me@ricmoo.com>. See LICENSE.txt. */var Hw,Vw,qw,Ww=globalThis&&globalThis.__classPrivateFieldGet||function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)},zw=globalThis&&globalThis.__classPrivateFieldSet||function(e,t,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 t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,n):s?s.value=n:t.set(e,n),n};const Kw={16:10,24:12,32:14},$w=[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],Qw=[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],Jw=[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],Yw=[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],Zw=[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],Xw=[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],eb=[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],tb=[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],nb=[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],rb=[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],sb=[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],ib=[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],ob=[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],ab=[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],cb=[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 lb(e){const t=[];for(let n=0;n<e.length;n+=4)t.push(e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3]);return t}class ub{get key(){return Ww(this,Hw,"f").slice()}constructor(e){if(Hw.set(this,void 0),Vw.set(this,void 0),qw.set(this,void 0),!(this instanceof ub))throw Error("AES must be instanitated with `new`");zw(this,Hw,new Uint8Array(e),"f");const t=Kw[this.key.length];if(null==t)throw new TypeError("invalid key size (must be 16, 24 or 32 bytes)");zw(this,qw,[],"f"),zw(this,Vw,[],"f");for(let l=0;l<=t;l++)Ww(this,qw,"f").push([0,0,0,0]),Ww(this,Vw,"f").push([0,0,0,0]);const n=4*(t+1),r=this.key.length/4,s=lb(this.key);let i;for(let l=0;l<r;l++)i=l>>2,Ww(this,qw,"f")[i][l%4]=s[l],Ww(this,Vw,"f")[t-i][l%4]=s[l];let o,a=0,c=r;for(;c<n;){if(o=s[r-1],s[0]^=Qw[o>>16&255]<<24^Qw[o>>8&255]<<16^Qw[255&o]<<8^Qw[o>>24&255]^$w[a]<<24,a+=1,8!=r)for(let t=1;t<r;t++)s[t]^=s[t-1];else{for(let e=1;e<r/2;e++)s[e]^=s[e-1];o=s[r/2-1],s[r/2]^=Qw[255&o]^Qw[o>>8&255]<<8^Qw[o>>16&255]<<16^Qw[o>>24&255]<<24;for(let e=r/2+1;e<r;e++)s[e]^=s[e-1]}let e,i,l=0;for(;l<r&&c<n;)e=c>>2,i=c%4,Ww(this,qw,"f")[e][i]=s[l],Ww(this,Vw,"f")[t-e][i]=s[l++],c++}for(let l=1;l<t;l++)for(let e=0;e<4;e++)o=Ww(this,Vw,"f")[l][e],Ww(this,Vw,"f")[l][e]=ib[o>>24&255]^ob[o>>16&255]^ab[o>>8&255]^cb[255&o]}encrypt(e){if(16!=e.length)throw new TypeError("invalid plaintext size (must be 16 bytes)");const t=Ww(this,qw,"f").length-1,n=[0,0,0,0];let r=lb(e);for(let o=0;o<4;o++)r[o]^=Ww(this,qw,"f")[0][o];for(let o=1;o<t;o++){for(let e=0;e<4;e++)n[e]=Yw[r[e]>>24&255]^Zw[r[(e+1)%4]>>16&255]^Xw[r[(e+2)%4]>>8&255]^eb[255&r[(e+3)%4]]^Ww(this,qw,"f")[o][e];r=n.slice()}const s=new Uint8Array(16);let i=0;for(let o=0;o<4;o++)i=Ww(this,qw,"f")[t][o],s[4*o]=255&(Qw[r[o]>>24&255]^i>>24),s[4*o+1]=255&(Qw[r[(o+1)%4]>>16&255]^i>>16),s[4*o+2]=255&(Qw[r[(o+2)%4]>>8&255]^i>>8),s[4*o+3]=255&(Qw[255&r[(o+3)%4]]^i);return s}decrypt(e){if(16!=e.length)throw new TypeError("invalid ciphertext size (must be 16 bytes)");const t=Ww(this,Vw,"f").length-1,n=[0,0,0,0];let r=lb(e);for(let o=0;o<4;o++)r[o]^=Ww(this,Vw,"f")[0][o];for(let o=1;o<t;o++){for(let e=0;e<4;e++)n[e]=tb[r[e]>>24&255]^nb[r[(e+3)%4]>>16&255]^rb[r[(e+2)%4]>>8&255]^sb[255&r[(e+1)%4]]^Ww(this,Vw,"f")[o][e];r=n.slice()}const s=new Uint8Array(16);let i=0;for(let o=0;o<4;o++)i=Ww(this,Vw,"f")[t][o],s[4*o]=255&(Jw[r[o]>>24&255]^i>>24),s[4*o+1]=255&(Jw[r[(o+3)%4]>>16&255]^i>>16),s[4*o+2]=255&(Jw[r[(o+2)%4]>>8&255]^i>>8),s[4*o+3]=255&(Jw[255&r[(o+1)%4]]^i);return s}}Hw=new WeakMap,Vw=new WeakMap,qw=new WeakMap;class hb{constructor(e,t,n){if(n&&!(this instanceof n))throw new Error(`${e} must be instantiated with "new"`);Object.defineProperties(this,{aes:{enumerable:!0,value:new ub(t)},name:{enumerable:!0,value:e}})}}var db,fb,pb=globalThis&&globalThis.__classPrivateFieldSet||function(e,t,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 t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,n):s?s.value=n:t.set(e,n),n},gb=globalThis&&globalThis.__classPrivateFieldGet||function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};class mb extends hb{constructor(e,t){if(super("ECC",e,mb),db.set(this,void 0),fb.set(this,void 0),t){if(t.length%16)throw new TypeError("invalid iv size (must be 16 bytes)");pb(this,db,new Uint8Array(t),"f")}else pb(this,db,new Uint8Array(16),"f");pb(this,fb,this.iv,"f")}get iv(){return new Uint8Array(gb(this,db,"f"))}encrypt(e){if(e.length%16)throw new TypeError("invalid plaintext size (must be multiple of 16 bytes)");const t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=16){for(let t=0;t<16;t++)gb(this,fb,"f")[t]^=e[n+t];pb(this,fb,this.aes.encrypt(gb(this,fb,"f")),"f"),t.set(gb(this,fb,"f"),n)}return t}decrypt(e){if(e.length%16)throw new TypeError("invalid ciphertext size (must be multiple of 16 bytes)");const t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=16){const r=this.aes.decrypt(e.subarray(n,n+16));for(let s=0;s<16;s++)t[n+s]=r[s]^gb(this,fb,"f")[s],gb(this,fb,"f")[s]=e[n+s]}return t}}db=new WeakMap,fb=new WeakMap;var yb,wb,bb,_b=globalThis&&globalThis.__classPrivateFieldSet||function(e,t,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 t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,n):s?s.value=n:t.set(e,n),n},Ab=globalThis&&globalThis.__classPrivateFieldGet||function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};class vb extends hb{constructor(e,t){super("CTR",e,vb),yb.set(this,void 0),wb.set(this,void 0),bb.set(this,void 0),_b(this,bb,new Uint8Array(16),"f"),Ab(this,bb,"f").fill(0),_b(this,yb,Ab(this,bb,"f"),"f"),_b(this,wb,16,"f"),null==t&&(t=1),"number"==typeof t?this.setCounterValue(t):this.setCounterBytes(t)}get counter(){return new Uint8Array(Ab(this,bb,"f"))}setCounterValue(e){if(!Number.isInteger(e)||e<0||e>Number.MAX_SAFE_INTEGER)throw new TypeError("invalid counter initial integer value");for(let t=15;t>=0;--t)Ab(this,bb,"f")[t]=e%256,e=Math.floor(e/256)}setCounterBytes(e){if(16!==e.length)throw new TypeError("invalid counter initial Uint8Array value length");Ab(this,bb,"f").set(e)}increment(){for(let e=15;e>=0;e--){if(255!==Ab(this,bb,"f")[e]){Ab(this,bb,"f")[e]++;break}Ab(this,bb,"f")[e]=0}}encrypt(e){var t,n;const r=new Uint8Array(e);for(let s=0;s<r.length;s++)16===Ab(this,wb,"f")&&(_b(this,yb,this.aes.encrypt(Ab(this,bb,"f")),"f"),_b(this,wb,0,"f"),this.increment()),r[s]^=Ab(this,yb,"f")[(_b(this,wb,(n=Ab(this,wb,"f"),t=n++,n),"f"),t)];return r}decrypt(e){return this.encrypt(e)}}function Eb(e){return"string"!=typeof e||e.startsWith("0x")||(e="0x"+e),tc(e)}function kb(e,t){for(e=String(e);e.length<t;)e="0"+e;return e}function Sb(e){return"string"==typeof e?Dc(e,"NFKC"):tc(e)}function Tb(e,t){const n=t.match(/^([a-z0-9$_.-]*)(:([a-z]+))?(!)?$/i);$a(null!=n,"invalid path","path",t);const r=n[1],s=n[3],i="!"===n[4];let o=e;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 e=null;for(const t in o)if(t.toLowerCase()===a){e=o[t];break}o=e}else o=null;if(null==o)break}if($a(!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 Eb(o);if("array"===s&&Array.isArray(o))return o;if(s===typeof o)return o;$a(!1,`wrong type found for ${s} `,"path",r)}return o}yb=new WeakMap,wb=new WeakMap,bb=new WeakMap;const Rb="m/44'/60'/0'/0/0";function Ib(e){try{const t=JSON.parse(e);if(3===(null!=t.version?parseInt(t.version):0))return!0}catch(t){}return!1}function Cb(e,t){const n=ec(t),r=Tb(e,"crypto.ciphertext:data!");$a(ic(Bu(oc([n.slice(16,32),r]))).substring(2)===Tb(e,"crypto.mac:string!").toLowerCase(),"incorrect password","password","[ REDACTED ]");const s=function(e,t,n){if("aes-128-ctr"===Tb(e,"crypto.cipher:string")){const r=Tb(e,"crypto.cipherparams.iv:data!");return ic(new vb(t,r).decrypt(n))}Ka(!1,"unsupported cipher","UNSUPPORTED_OPERATION",{operation:"decrypt"})}(e,n.slice(0,16),r),i=kf(s);if(e.address){let t=e.address.toLowerCase();t.startsWith("0x")||(t="0x"+t),$a($d(t)===i,"keystore address/privateKey mismatch","address",e.address)}const o={address:i,privateKey:s};if("0.1"===Tb(e,"x-ethers.version:string")){const t=n.slice(32,64),r=Tb(e,"x-ethers.mnemonicCiphertext:data!"),s=Tb(e,"x-ethers.mnemonicCounter:data!"),i=new vb(t,s);o.mnemonic={path:Tb(e,"x-ethers.path:string")||Rb,locale:Tb(e,"x-ethers.locale:string")||"en",entropy:ic(ec(i.decrypt(r)))}}return o}function Ob(e){const t=Tb(e,"crypto.kdf:string");if(t&&"string"==typeof t){if("scrypt"===t.toLowerCase()){const n=Tb(e,"crypto.kdfparams.salt:data!"),r=Tb(e,"crypto.kdfparams.n:int!"),s=Tb(e,"crypto.kdfparams.r:int!"),i=Tb(e,"crypto.kdfparams.p:int!");$a(r>0&&!(r&r-1),"invalid kdf.N","kdf.N",r),$a(s>0&&i>0,"invalid kdf","kdf",t);const o=Tb(e,"crypto.kdfparams.dklen:int!");return $a(32===o,"invalid kdf.dklen","kdf.dflen",o),{name:"scrypt",salt:n,N:r,r:s,p:i,dkLen:64}}if("pbkdf2"===t.toLowerCase()){const t=Tb(e,"crypto.kdfparams.salt:data!"),n=Tb(e,"crypto.kdfparams.prf:string!"),r=n.split("-").pop();$a("sha256"===r||"sha512"===r,"invalid kdf.pdf","kdf.pdf",n);const s=Tb(e,"crypto.kdfparams.c:int!"),i=Tb(e,"crypto.kdfparams.dklen:int!");return $a(32===i,"invalid kdf.dklen","kdf.dklen",i),{name:"pbkdf2",salt:t,count:s,dkLen:i,algorithm:r}}}$a(!1,"unsupported key-derivation function","kdf",t)}function xb(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}function Nb(e){const t=null!=e.salt?ec(e.salt,"options.salt"):ah(32);let n=1<<17,r=8,s=1;return e.scrypt&&(e.scrypt.N&&(n=e.scrypt.N),e.scrypt.r&&(r=e.scrypt.r),e.scrypt.p&&(s=e.scrypt.p)),$a("number"==typeof n&&n>0&&Number.isSafeInteger(n)&&(BigInt(n)&BigInt(n-1))===BigInt(0),"invalid scrypt N parameter","options.N",n),$a("number"==typeof r&&r>0&&Number.isSafeInteger(r),"invalid scrypt r parameter","options.r",r),$a("number"==typeof s&&s>0&&Number.isSafeInteger(s),"invalid scrypt p parameter","options.p",s),{name:"scrypt",dkLen:32,salt:t,N:n,r:r,p:s}}function Pb(e,t,n,r){const s=ec(n.privateKey,"privateKey"),i=null!=r.iv?ec(r.iv,"options.iv"):ah(16);$a(16===i.length,"invalid options.iv length","options.iv",r.iv);const o=null!=r.uuid?ec(r.uuid,"options.uuid"):ah(16);$a(16===o.length,"invalid options.uuid length","options.uuid",r.iv);const a=e.slice(0,16),c=e.slice(16,32),l=ec(new vb(a,i).encrypt(s)),u=Bu(oc([c,l])),h={address:n.address.substring(2).toLowerCase(),id:al(o),version:3,Crypto:{cipher:"aes-128-ctr",cipherparams:{iv:ic(i).substring(2)},ciphertext:ic(l).substring(2),kdf:"scrypt",kdfparams:{salt:ic(t.salt).substring(2),n:t.N,dklen:32,p:t.p,r:t.r},mac:u.substring(2)}};if(n.mnemonic){const t=null!=r.client?r.client:`ethers/${Fa}`,s=n.mnemonic.path||Rb,i=n.mnemonic.locale||"en",o=e.slice(32,64),a=ec(n.mnemonic.entropy,"account.mnemonic.entropy"),c=ah(16),l=ec(new vb(o,c).encrypt(a)),u=new Date,d="UTC--"+(u.getUTCFullYear()+"-"+kb(u.getUTCMonth()+1,2)+"-"+kb(u.getUTCDate(),2)+"T"+kb(u.getUTCHours(),2)+"-"+kb(u.getUTCMinutes(),2)+"-"+kb(u.getUTCSeconds(),2)+".0Z")+"--"+h.address;h["x-ethers"]={client:t,gethFilename:d,path:s,locale:i,mnemonicCounter:ic(c).substring(2),mnemonicCiphertext:ic(l).substring(2),version:"0.1"}}return JSON.stringify(h)}function Db(e,t,n){null==n&&(n={});const r=Sb(t),s=Nb(n);return Pb(ec(_h(r,s.salt,s.N,s.r,s.p,64)),s,e,n)}async function Bb(e,t,n){null==n&&(n={});const r=Sb(t),s=Nb(n);return Pb(ec(await bh(r,s.salt,s.N,s.r,s.p,64,n.progressCallback)),s,e,n)}const Ub="m/44'/60'/0'/0/0",Lb=new Uint8Array([66,105,116,99,111,105,110,32,115,101,101,100]),Mb=2147483648,Fb=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");function jb(e,t){let n="";for(;e;)n="0123456789abcdef"[e%16]+n,e=Math.trunc(e/16);for(;n.length<2*t;)n="0"+n;return"0x"+n}function Gb(e){const t=ec(e);return Oc(oc([t,cc(kh(kh(t)),0,4)]))}const Hb={};function Vb(e,t,n,r){const s=new Uint8Array(37);e&Mb?(Ka(null!=r,"cannot derive child of neutered node","UNSUPPORTED_OPERATION",{operation:"deriveChild"}),s.set(ec(r),1)):s.set(ec(n));for(let o=24;o>=0;o-=8)s[33+(o>>3)]=e>>24-o&255;const i=ec(mu("sha512",t,s));return{IL:i.slice(0,32),IR:i.slice(32)}}function qb(e,t){const n=t.split("/");$a(n.length>0,"invalid path","path",t),"m"===n[0]&&($a(0===e.depth,`cannot derive root path (i.e. path starting with "m/") for a node at non-zero depth ${e.depth}`,"path",t),n.shift());let r=e;for(let s=0;s<n.length;s++){const e=n[s];if(e.match(/^[0-9]+'$/)){const t=parseInt(e.substring(0,e.length-1));$a(t<Mb,"invalid path index",`path[${s}]`,e),r=r.deriveChild(Mb+t)}else if(e.match(/^[0-9]+$/)){const t=parseInt(e);$a(t<Mb,"invalid path index",`path[${s}]`,e),r=r.deriveChild(t)}else $a(!1,"invalid path component",`path[${s}]`,e)}return r}const Wb=class e extends Iw{constructor(e,t,n,r,s,i,o,a,c){super(t,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"),Za(e,Hb,"HDNodeWallet"),Ha(this,{publicKey:t.compressedPublicKey});Ha(this,{parentFingerprint:n,fingerprint:cc(Xu(kh(this.publicKey)),0,4),chainCode:r,path:s,index:i,depth:o}),Ha(this,{mnemonic:a})}connect(t){return new e(Hb,this.signingKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,this.mnemonic,t)}async encrypt(e,t){return await Bb(Ln(this,kn,Sn).call(this),e,{progressCallback:t})}encryptSync(e){return Db(Ln(this,kn,Sn).call(this),e)}get extendedKey(){return Ka(this.depth<256,"Depth too deep","UNSUPPORTED_OPERATION",{operation:"extendedKey"}),Gb(oc(["0x0488ADE4",jb(this.depth,1),this.parentFingerprint,jb(this.index,4),this.chainCode,oc(["0x00",this.privateKey])]))}hasPath(){return null!=this.path}neuter(){return new Kb(Hb,this.address,this.publicKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,this.provider)}deriveChild(t){const n=Ac(t,"index");$a(n<=4294967295,"invalid index","index",n);let r=this.path;r&&(r+="/"+(2147483647&n),n&Mb&&(r+="'"));const{IR:s,IL:i}=Vb(n,this.chainCode,this.publicKey,this.privateKey),o=new Hd(vc((_c(i)+BigInt(this.privateKey))%Fb,32));return new e(Hb,o,this.fingerprint,ic(s),r,n,this.depth+1,this.mnemonic,this.provider)}derivePath(e){return qb(this,e)}static fromExtendedKey(t){const n=Ec(function(e){let t=Ic;for(let n=0;n<e.length;n++)t*=Cc,t+=Rc(e[n]);return t}(t));$a(82===n.length||Gb(n.slice(0,78))===t,"invalid extended key","extendedKey","[ REDACTED ]");const r=n[4],s=ic(n.slice(5,9)),i=parseInt(ic(n.slice(9,13)).substring(2),16),o=ic(n.slice(13,45)),a=n.slice(45,78);switch(ic(n.slice(0,4))){case"0x0488b21e":case"0x043587cf":{const e=ic(a);return new Kb(Hb,kf(e),e,s,o,null,i,r,null)}case"0x0488ade4":case"0x04358394 ":if(0!==a[0])break;return new e(Hb,new Hd(a.slice(1)),s,o,null,i,r,null,null)}$a(!1,"invalid extended key prefix","extendedKey","[ REDACTED ]")}static createRandom(t,n,r){var s;null==t&&(t=""),null==n&&(n=Ub),null==r&&(r=Uw.wordlist());const i=Gw.fromEntropy(ah(16),t,r);return Ln(s=e,Tn,Rn).call(s,i.computeSeed(),i).derivePath(n)}static fromMnemonic(t,n){var r;return n||(n=Ub),Ln(r=e,Tn,Rn).call(r,t.computeSeed(),t).derivePath(n)}static fromPhrase(t,n,r,s){var i;null==n&&(n=""),null==r&&(r=Ub),null==s&&(s=Uw.wordlist());const o=Gw.fromPhrase(t,n,s);return Ln(i=e,Tn,Rn).call(i,o.computeSeed(),o).derivePath(r)}static fromSeed(t){var n;return Ln(n=e,Tn,Rn).call(n,t,null)}};kn=new WeakSet,Sn=function(){const e={address:this.address,privateKey:this.privateKey},t=this.mnemonic;return this.path&&t&&"en"===t.wordlist.locale&&""===t.password&&(e.mnemonic={path:this.path,locale:"en",entropy:t.entropy}),e},Tn=new WeakSet,Rn=function(e,t){$a(rc(e),"invalid seed","seed","[REDACTED]");const n=ec(e,"seed");$a(n.length>=16&&n.length<=64,"invalid seed","seed","[REDACTED]");const r=ec(mu("sha512",Lb,n)),s=new Hd(ic(r.slice(0,32)));return new Wb(Hb,s,"0x00000000",ic(r.slice(32)),"m",0,0,t,null)},Dn(Wb,Tn);let zb=Wb;class Kb extends dw{constructor(e,t,n,r,s,i,o,a,c){super(t,c),xn(this,"publicKey"),xn(this,"fingerprint"),xn(this,"parentFingerprint"),xn(this,"chainCode"),xn(this,"path"),xn(this,"index"),xn(this,"depth"),Za(e,Hb,"HDNodeVoidWallet"),Ha(this,{publicKey:n});Ha(this,{publicKey:n,fingerprint:cc(Xu(kh(n)),0,4),parentFingerprint:r,chainCode:s,path:i,index:o,depth:a})}connect(e){return new Kb(Hb,this.address,this.publicKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,e)}get extendedKey(){return Ka(this.depth<256,"Depth too deep","UNSUPPORTED_OPERATION",{operation:"extendedKey"}),Gb(oc(["0x0488B21E",jb(this.depth,1),this.parentFingerprint,jb(this.index,4),this.chainCode,this.publicKey]))}hasPath(){return null!=this.path}deriveChild(e){const t=Ac(e,"index");$a(t<=4294967295,"invalid index","index",t);let n=this.path;n&&(n+="/"+(2147483647&t),t&Mb&&(n+="'"));const{IR:r,IL:s}=Vb(t,this.chainCode,this.publicKey,null),i=Hd.addPoints(s,this.publicKey,!0),o=kf(i);return new Kb(Hb,o,i,this.fingerprint,ic(r),n,t,this.depth+1,this.provider)}derivePath(e){return qb(this,e)}}function $b(e){try{if(JSON.parse(e).encseed)return!0}catch(t){}return!1}function Qb(e,t){const n=JSON.parse(e),r=Sb(t),s=$d(Tb(n,"ethaddr:string!")),i=Eb(Tb(n,"encseed:string!"));$a(i&&i.length%16==0,"invalid encseed","json",e);const o=ec(rh(r,r,2e3,32,"sha256")).slice(0,16),a=i.slice(0,16),c=i.slice(16),l=function(e){if(e.length<16)throw new TypeError("PKCS#7 invalid length");const t=e[e.length-1];if(t>16)throw new TypeError("PKCS#7 padding byte out of range");const n=e.length-t;for(let r=0;r<t;r++)if(e[n+r]!==t)throw new TypeError("PKCS#7 invalid padding byte");return new Uint8Array(e.subarray(0,n))}(ec(new mb(o,a).decrypt(c)));let u="";for(let h=0;h<l.length;h++)u+=String.fromCharCode(l[h]);return{address:s,privateKey:Wf(u)}}function Jb(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}const Yb=class e extends Iw{constructor(e,t){"string"!=typeof e||e.startsWith("0x")||(e="0x"+e),super("string"==typeof e?new Hd(e):e,t)}connect(t){return new e(this.signingKey,t)}async encrypt(e,t){const n={address:this.address,privateKey:this.privateKey};return await Bb(n,e,{progressCallback:t})}encryptSync(e){return Db({address:this.address,privateKey:this.privateKey},e)}static async fromEncryptedJson(t,n,r){var s;let i=null;return Ib(t)?i=await async function(e,t,n){const r=JSON.parse(e),s=Sb(t),i=Ob(r);if("pbkdf2"===i.name){n&&(n(0),await xb(0));const{salt:e,count:t,dkLen:o,algorithm:a}=i,c=rh(s,e,t,o,a);return n&&(n(1),await xb(0)),Cb(r,c)}Ka("scrypt"===i.name,"cannot be reached","UNKNOWN_ERROR",{params:i});const{salt:o,N:a,r:c,p:l,dkLen:u}=i;return Cb(r,await bh(s,o,a,c,l,u,n))}(t,n,r):$b(t)&&(r&&(r(0),await Jb(0)),i=Qb(t,n),r&&(r(1),await Jb(0))),Ln(s=e,In,Cn).call(s,i)}static fromEncryptedJsonSync(t,n){var r;let s=null;return Ib(t)?s=function(e,t){const n=JSON.parse(e),r=Sb(t),s=Ob(n);if("pbkdf2"===s.name){const{salt:e,count:t,dkLen:i,algorithm:o}=s;return Cb(n,rh(r,e,t,i,o))}Ka("scrypt"===s.name,"cannot be reached","UNKNOWN_ERROR",{params:s});const{salt:i,N:o,r:a,p:c,dkLen:l}=s;return Cb(n,_h(r,i,o,a,c,l))}(t,n):$b(t)?s=Qb(t,n):$a(!1,"invalid JSON wallet","json","[ REDACTED ]"),Ln(r=e,In,Cn).call(r,s)}static createRandom(e){const t=zb.createRandom();return e?t.connect(e):t}static fromPhrase(e,t){const n=zb.fromPhrase(e);return t?n.connect(t):n}};In=new WeakSet,Cn=function(e){if($a(e,"invalid JSON wallet","json","[ REDACTED ]"),"mnemonic"in e&&e.mnemonic&&"en"===e.mnemonic.locale){const t=Gw.fromEntropy(e.mnemonic.entropy),n=zb.fromMnemonic(t,e.mnemonic.path);if(n.address===e.address&&n.privateKey===e.privateKey)return n;console.log("WARNING: JSON mismatch address/privateKey != mnemonic; fallback onto private key")}const t=new Yb(e.privateKey);return $a(t.address===e.address,"address/privateKey mismatch","json","[ REDACTED ]"),t},Dn(Yb,In);let Zb=Yb;const Xb=3000000n,e_=2000000000n,t_=1000000000n,n_=4096,r_="dns_txt",s_=(1n<<64n)-1n,i_=["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)"],o_=new Am(i_),a_=[0,"0x"],c_=function(e){const t=Dc(e);if(t.length>31)throw new Error("bytes32 string must be less than 32 bytes");return hc(t,32)}("inline");class l_ extends Error{constructor(e,t){super(t),this.name="BnsEvmTxError",this.code=e}}function u_(e,t,n){let r;try{r=BigInt(t)}catch{throw new l_("INVALID_CONFIG",`${e} must be an integer`)}if(r<0n||void 0!==n&&r>n)throw new l_("INVALID_CONFIG",`${e} is out of range`);return r}function h_(e){const t=Mn.canonicalize(e);if("string"!=typeof t)throw new l_("INVALID_DOCUMENT","document cannot be encoded as canonical JSON");const n=Dc(t);if(0===n.length||n.length>n_)throw new l_("INVALID_DOCUMENT",`inline document is ${n.length} bytes, max 4096`);return n}function d_(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw new l_("INVALID_DOCUMENT",`${t} must be an object`);const n=e;if(!Number.isInteger(n.ttl)||n.ttl<0||n.ttl>4294967295)throw new l_("INVALID_DOCUMENT",`${t}.ttl must be a u32`);if("string"!=typeof n.value||0===n.value.length)throw new l_("INVALID_DOCUMENT",`${t}.value must be a non-empty string`);return{ttl:n.ttl,value:n.value}}class f_{constructor(e,t,n){if(this.nextNonce=null,this.client=e,this.config=t,this.chainId=u_("chainId",t.chainId,s_),this.contractAddress=$d(t.contractAddress),this.gasLimit=u_("gasLimit",t.gasLimit??Xb,s_),this.maxFeePerGas=u_("maxFeePerGas",t.maxFeePerGas??e_),this.maxPriorityFeePerGas=u_("maxPriorityFeePerGas",t.maxPriorityFeePerGas??t_),!t.rpcEndpoint&&!n)throw new l_("INVALID_CONFIG","rpcEndpoint is required");if(0n===this.chainId||0n===this.gasLimit)throw new l_("INVALID_CONFIG","chainId and gasLimit must be greater than zero");if(this.maxFeePerGas<this.maxPriorityFeePerGas)throw new l_("INVALID_CONFIG","maxFeePerGas must be >= maxPriorityFeePerGas");this.provider=n??new Sw(t.rpcEndpoint,this.chainId,{staticNetwork:!0})}resetNonce(){this.nextNonce=null}async buildAndSign(e,t){const n=new Zb(t),r="publish_document"===e.type?await this.preparePublishedDocument(e.request):await this.prepareDnsTxtDocument(e.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(e){null===this.nextNonce&&(this.nextNonce=await this.provider.getTransactionCount(e,"pending"));const t=this.nextNonce;return this.nextNonce+=1,t}async preparePublishedDocument(e){if(!e.document||"object"!=typeof e.document||Array.isArray(e.document))throw new l_("INVALID_DOCUMENT","publish_document document must be a JSON object");return this.prepareDocument(e.name,e.doc_type,h_(e.document))}async prepareDnsTxtDocument(e){const t=await this.getCurrentDocument(e.name,r_);let n=[];if(t){if("inline"!==t.document_state.document.storage_type)throw new l_("INVALID_DOCUMENT","DNS TXT helper can only update inline documents");let e;try{e=JSON.parse(function(e){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(new Uint8Array(e));let t="";for(const n of e)t+=String.fromCharCode(n);try{return decodeURIComponent(escape(t))}catch{return t}}(t.document_state.document.inline_document))}catch(s){throw new l_("INVALID_DOCUMENT",`current dns_txt document is not valid JSON: ${s instanceof Error?s.message:String(s)}`)}if(!Array.isArray(e))throw new l_("INVALID_DOCUMENT","current dns_txt document must be an array");n=e.map(((e,t)=>d_(e,`dns_txt[${t}]`)))}switch(e.mode){case"add":{if(!e.value)throw new l_("INVALID_OPERATION","publish_dns_txt mode=add requires value");const t=d_({ttl:e.ttl??600,value:e.value},"dns_txt");n.some((e=>e.value===t.value))||n.push(t);break}case"remove":if(!e.value)throw new l_("INVALID_OPERATION","publish_dns_txt mode=remove requires value");n=n.filter((t=>t.value!==e.value));break;case"replace":if(!e.records)throw new l_("INVALID_OPERATION","publish_dns_txt mode=replace requires records");n=e.records.map(((e,t)=>d_({ttl:e.ttl??600,value:e.value},`dns_txt[${t}]`)));break;default:throw new l_("INVALID_OPERATION",`publish_dns_txt mode \`${e.mode}\` is not supported`)}const r=await this.getNameState(e.name);return{name:Na(e.name),docType:r_,expectedVersion:(null==t?void 0:t.document_state.version)??0,inlineDocument:h_(n),nameState:r}}async prepareDocument(e,t,n){const r=Na(e),s=Pa(t),[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(e){const t=await this.client.queryNameState(e);if(!t)throw new l_("NAME_NOT_FOUND",`BNS name \`${e}\` was not found`);return t}async getCurrentDocument(e,t){try{const n=await this.client.resolveDocument(e,t);return"missing"===n.status?null:n}catch(n){if(function(e){return e instanceof zo&&e.isRegistryCode("DOCUMENT_NOT_FOUND")}(n))return null;throw n}}encodePublishDocument(e,t){const n=this.ownerAuthority(e.nameState,t),r=[c_,"",ic(e.inlineDocument),kh(e.inlineDocument),Cd,Cd,Cd];return o_.encodeFunctionData("publishDocument",[e.name,e.docType,e.expectedVersion,r,a_,a_,Id,0,Cd,Cd,Cd,Cd,Cd,n,[e.nameState.name_seq,0]])}ownerAuthority(e,t){const n=e.effective_owner;if("chain_account"===n.kind){const s=$d(n.value);if(s!==$d(t))throw new l_("LOCAL_SIGNER_NOT_OWNER",`local signer ${t} is not effective owner ${s} of ${e.name}`);return[1,(r=t,[1,ic(ec(r))]),Cd]}var r;if("bns_name"===n.kind){const t=function(e,t){if(!t)return Cd;const n=ec(t);if(32!==n.length)throw new l_("INVALID_CONFIG",`${e} must be a 32-byte hex value`);return ic(n)}("authorityKid",this.config.authorityKid);if(t===Cd)throw new l_("AUTHORITY_KID_REQUIRED",`authorityKid is required when ${e.name} is controlled by BNS name ${n.value}`);return[1,[2,ic(Dc(n.value))],t]}throw new l_("LOCAL_SIGNER_NOT_OWNER",`BNS name ${e.name} has no concrete effective owner`)}}class p_ extends Error{constructor(e,t,n){super(n),this.name="BnsTxExecutorError",this.code=e,this.route=t}}function g_(e){if("string"!=typeof e)return null;const t=e.trim();return t.length>0?t:null}function m_(e){return e===Ni.NodeJS||e===Ni.AppClient||e===Ni.AppService}function y_(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"boolean"==typeof t.sn_account?t.sn_account:null!==g_(t.sn_username)||null!==g_(t.sn_user_name)}const w_="/kapi/sn",b_="/kapi/sn/auth",__="/kapi/sn/deviceinfo",A_="/kapi/sn/bns-proxy",v_="/kapi/sn/bns",E_="/kapi/sn/region-probe-config.json",k_=1048576,S_="auth.check_username",T_="auth.check_active_code",R_="auth.register",I_="auth.login",C_="auth.refresh",O_="auth.logout",x_="auth.me",N_="user.get_profile",P_="user.set_self_cert",D_="user.add_dns_record",B_="user.remove_dns_record",U_="user.list_dns_records",L_="zone.get_info",M_="domain.bind",F_="domain.unbind",j_="device.register",G_="device.update",H_="device.get",V_="device.list",q_="deviceinfo.resolve_ood_by_did",W_="deviceinfo.resolve_ood_by_hostname",z_="bns.publish_dns_txt",K_="bns.publish_document",$_="owner.remove_bound_zone",Q_=/\[SN:(\d+):([a-z_]+)\]\s*/;class J_ extends Error{constructor(e,t,n=null,r=null,s=null){super(t),this.name="SnClientError",this.kind=e,this.code=n,this.codeName=r,this.detail=s??t}isSnError(e){return"sn"===this.kind&&this.codeName===e}domainProofInfo(){return this.isSnError("domain_proof_failed")?Y_(this.detail):null}bnsWriteInfo(){return this.isSnError("bns_permission_denied")||this.isSnError("bns_name_already_exists")||this.isSnError("bns_write_failed")?Y_(this.detail):null}static fromRpcError(e,t){if(t instanceof J_)return t;const n=t instanceof Error?t.message:String(t),r=Q_.exec(n);if(r){const t=parseInt(r[1],10),s=r[2],i=n.slice(r.index+r[0].length);return new J_("sn",`${e} failed: [SN:${t}:${s}] ${i}`,t,s,i)}return new J_("transport",`${e} failed: ${n}`)}}function Y_(e){try{const t=JSON.parse(e);return null===t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}}const Z_={auth:b_,deviceinfo:__,"bns-proxy":A_},X_=[A_,__,b_,v_,w_];function eA(e,t){const n=Z_[t],r=e.replace(/\/+$/,"");for(const s of X_)if(r.endsWith(s))return`${r.slice(0,r.length-s.length)}${n}`;return`${r}${n}`}const tA=[E_,A_,__,b_,v_,w_],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(e){throw new J_("validation",e)}function iA(e){return(new TextEncoder).encode(e).byteLength}function oA(e,t){return(null===e||"object"!=typeof e||Array.isArray(e))&&sA(`${t} must be a JSON object`),e}function aA(e,t){return"string"!=typeof e&&sA(`${t} must be a string`),e}function cA(e,t){return"number"!=typeof e&&sA(`${t} must be a number`),e}function lA(e,t){const n=cA(e,t);return Number.isSafeInteger(n)||sA(`${t} must be a safe integer`),n}function uA(e,t){const n=lA(e,t);return(n<-2147483648||n>2147483647)&&sA(`${t} must fit in a signed 32-bit integer`),n}function hA(e,t){return Array.isArray(e)||sA(`${t} must be an array`),e}function dA(e){return iA(e)<=128&&/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e)}function fA(e){const t=e.split(".");if(4!==t.length)return null;const n=t.map((e=>Number(e)));return n.some(((e,n)=>!/^\d+$/.test(t[n])||!Number.isInteger(e)||e<0||e>255))?null:n}function pA(e){const t=fA(e);if(!t)return!1;const[n,r,s]=t;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(e,t){const n=Date.parse(e);return nA.test(e)&&Number.isFinite(n)||sA(`${t} must be an RFC 3339 timestamp`),n}function mA(e,t=Date.now()){1!==e.schema_version&&sA(`unsupported schema_version ${e.schema_version}, expected 1`),(0===e.config_version.length||iA(e.config_version)>128||e.config_version.trim()!==e.config_version||rA.test(e.config_version))&&sA("config_version must be 1..=128 non-control bytes without surrounding whitespace");const n=gA(e.generated_at,"generated_at"),r=gA(e.expires_at,"expires_at"),s=t instanceof Date?t.getTime():"number"==typeof t?t:Date.parse(t);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=e.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"),(e.regions.length<1||e.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 e.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 e of h.probe_urls){let t;(0===e.id.length||iA(e.id)>128||e.id.trim()!==e.id||rA.test(e.id))&&sA(`probe URL id in region ${h.region_id} must be 1..=128 non-control bytes without surrounding whitespace`),a.has(e.id)&&sA(`duplicate probe URL id ${JSON.stringify(e.id)}`),a.add(e.id);try{t=new URL(e.url)}catch(u){sA(`invalid probe URL ${JSON.stringify(e.url)}: ${String(u)}`)}"https:"!==t.protocol&&sA(`probe URL ${JSON.stringify(e.url)} must use https`),(!t.hostname||t.username||t.password)&&sA(`probe URL ${JSON.stringify(e.url)} must be absolute and must not contain userinfo`),""!==t.port&&sA(`probe URL ${JSON.stringify(e.url)} must use port 443`);const n=fA(t.hostname),r=t.hostname.startsWith("[")&&t.hostname.endsWith("]");(n&&!pA(t.hostname)||r)&&sA(`probe URL ${JSON.stringify(e.url)} has a non-public or unsupported literal IP`);const s=c.get(t.origin);void 0!==s&&(s!==h.region_id&&sA(`probe origin ${t.origin} is assigned to both ${s} and ${h.region_id}`),sA(`probe origin ${t.origin} is duplicated in region ${h.region_id}`)),c.set(t.origin,h.region_id)}}}function yA(e){let t,n;try{t="string"==typeof e?e:new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(s){sA(`parse region probe config JSON failed: ${String(s)}`)}try{n=JSON.parse(t)}catch(s){sA(`parse region probe config JSON failed: ${String(s)}`)}const r=function(e){const t=oA(e,"region probe config"),n=oA(t.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(t.regions,"regions").map(((e,t)=>{const n=oA(e,`regions[${t}]`),r=hA(n.probe_urls,`regions[${t}].probe_urls`).map(((e,n)=>{const r=oA(e,`regions[${t}].probe_urls[${n}]`),s={id:aA(r.id,`regions[${t}].probe_urls[${n}].id`),url:aA(r.url,`regions[${t}].probe_urls[${n}].url`)};return void 0!==r.provider&&null!==r.provider&&(s.provider=aA(r.provider,`regions[${t}].probe_urls[${n}].provider`)),s}));return{region_id:aA(n.region_id,`regions[${t}].region_id`),priority:void 0===n.priority?0:uA(n.priority,`regions[${t}].priority`),probe_urls:r}}));return{schema_version:lA(t.schema_version,"schema_version"),config_version:aA(t.config_version,"config_version"),generated_at:aA(t.generated_at,"generated_at"),expires_at:aA(t.expires_at,"expires_at"),policy:r,regions:s}}(n);return mA(r),r}function wA(e){let t;try{t=new URL(e.trim())}catch(s){sA(`invalid SN base URL for region probe config: ${String(s)}`)}"https:"!==t.protocol&&sA("region probe config must be fetched from the target SN over HTTPS"),(!t.hostname||t.username||t.password)&&sA("SN region probe config URL must have a host and no userinfo"),t.search="",t.hash="";const n=t.pathname.replace(/\/+$/,"");let r=n;for(const i of tA)if(n.endsWith(i)){r=n.slice(0,n.length-i.length);break}return t.pathname=`${r}${E_}`,t.toString()}const bA=async(e,t)=>{if("function"!=typeof globalThis.fetch)throw new Error("fetch is not available in this runtime");return globalThis.fetch(e,t)};const _A="sn-device";function AA(e){return void 0!==e.ttl?{ttl:e.ttl,value:e.value}:{value:e.value}}function vA(e){const t={device_did:e.device_did,domain:e.domain,record_type:e.record_type};return void 0!==e.record&&(t.record=e.record),void 0!==e.ttl&&(t.ttl=e.ttl),void 0!==e.has_cert&&(t.has_cert=e.has_cert),t}function EA(e){return{endpoint_id:e.endpoint_id,protocol:e.protocol,host:e.host,port:e.port,scope:e.scope,priority:e.priority,source:e.source,expires_at:e.expires_at}}function kA(e){const t={device_name:e.device_name,device_ip:e.device_ip,device_info:e.device_info};return void 0!==e.device_did&&(t.device_did=e.device_did),void 0!==e.endpoints&&e.endpoints.length>0&&(t.endpoints=e.endpoints.map(EA)),void 0!==e.report_seq&&(t.report_seq=e.report_seq),void 0!==e.ttl&&(t.ttl=e.ttl),t}const SA=Object.freeze(Object.defineProperty({__proto__:null,LEGACY_SN_BNS_PATH:v_,METHOD_AUTH_CHECK_ACTIVE_CODE:T_,METHOD_AUTH_CHECK_USERNAME:S_,METHOD_AUTH_LOGIN:I_,METHOD_AUTH_LOGOUT:O_,METHOD_AUTH_ME:x_,METHOD_AUTH_REFRESH:C_,METHOD_AUTH_REGISTER:R_,METHOD_BNS_PUBLISH_DNS_TXT:z_,METHOD_BNS_PUBLISH_DOCUMENT:K_,METHOD_DEVICEINFO_RESOLVE_OOD_BY_DID:q_,METHOD_DEVICEINFO_RESOLVE_OOD_BY_HOSTNAME:W_,METHOD_DEVICE_GET:H_,METHOD_DEVICE_LIST:V_,METHOD_DEVICE_REGISTER:j_,METHOD_DEVICE_UPDATE:G_,METHOD_DOMAIN_BIND:M_,METHOD_DOMAIN_UNBIND:F_,METHOD_OWNER_REMOVE_BOUND_ZONE:$_,METHOD_USER_ADD_DNS_RECORD:D_,METHOD_USER_GET_PROFILE:N_,METHOD_USER_LIST_DNS_RECORDS:U_,METHOD_USER_REMOVE_DNS_RECORD:B_,METHOD_USER_SET_SELF_CERT:P_,METHOD_ZONE_GET_INFO:L_,SN_AUTH_PATH:b_,SN_BNS_PROXY_PATH:A_,SN_DEVICEINFO_PATH:__,SN_DEVICE_TOKEN_AUD:_A,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:E_,SN_REGION_PROBE_FETCH_TIMEOUT:5e3,SN_REGION_PROBE_MAX_CONFIG_BYTES:k_,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:w_,SnClient:class{constructor(e,t=null,n={}){this.authRpc=new Gn(eA(e,"auth"),t,null,n),this.deviceInfoRpc=new Gn(eA(e,"deviceinfo"),t,null,n),this.bnsProxyRpc=new Gn(eA(e,"bns-proxy"),t,null,n)}setSeq(e){this.authRpc.setSeq(e),this.deviceInfoRpc.setSeq(e),this.bnsProxyRpc.setSeq(e)}syncSessionToken(e){this.authRpc.setSessionToken(e),this.deviceInfoRpc.setSessionToken(e),this.bnsProxyRpc.setSessionToken(e)}getSessionToken(){return this.authRpc.getSessionToken()}async call(e,t,n){try{return await e.call(t,n)}catch(r){throw J_.fromRpcError(t,r)}}async checkUsername(e){return this.call(this.authRpc,S_,{name:e})}async checkActiveCode(e){return this.call(this.authRpc,T_,{active_code:e})}async register(e){const t={name:e.name,email:e.email,pwd_hash:e.pwd_hash,active_code:e.active_code};return void 0!==e.request_id&&(t.request_id=e.request_id),void 0!==e.region&&(t.region=e.region),void 0!==e.asset_owner&&(t.asset_owner=e.asset_owner),void 0!==e.owner_config&&(t.owner_config=e.owner_config),void 0!==e.initial_documents&&(t.initial_documents=function(e){const t={};void 0!==e.zone&&(t.zone=e.zone);void 0!==e.boot&&(t.boot=e.boot);void 0!==e.dns_txt&&(t.dns_txt=e.dns_txt.map((e=>({ttl:e.ttl,value:e.value}))));return t}(e.initial_documents)),this.call(this.authRpc,R_,t)}async login(e){const t={name:e.name,pwd_hash:e.pwd_hash};return void 0!==e.active_code&&(t.active_code=e.active_code),this.call(this.authRpc,I_,t)}async refresh(e){return this.call(this.authRpc,C_,{refresh_token:e})}async logout(e){return this.call(this.authRpc,O_,{refresh_token:e??null})}async me(){return this.call(this.authRpc,x_,{})}async getProfile(){return this.call(this.authRpc,N_,{})}async setSelfCert(e,t){return this.call(this.authRpc,P_,{self_cert:e,device_did:t??null})}async addDnsRecord(e){return this.call(this.authRpc,D_,vA(e))}async removeDnsRecord(e){return this.call(this.authRpc,B_,vA(e))}async listDnsRecords(){return this.call(this.authRpc,U_,{})}async getZoneInfo(){return this.call(this.authRpc,L_,{})}async bindDomain(e){return this.call(this.authRpc,M_,{domain:e})}async unbindDomain(e){return this.call(this.authRpc,F_,{domain:e})}async registerDeviceOnline(e){return this.call(this.deviceInfoRpc,j_,kA(e))}async updateDeviceOnline(e){return this.call(this.deviceInfoRpc,G_,kA(e))}async getDeviceOnline(e){return this.call(this.deviceInfoRpc,H_,{device_name:e.device_name??null,device_did:e.device_did??null})}async listDevicesOnline(e={}){const t={};return void 0!==e.state&&(t.state=e.state),void 0!==e.offset&&(t.offset=e.offset),void 0!==e.limit&&(t.limit=e.limit),this.call(this.deviceInfoRpc,V_,t)}async resolveOodByDid(e){return this.call(this.deviceInfoRpc,q_,{source_device_id:e})}async resolveOodByHostname(e){return this.call(this.deviceInfoRpc,W_,{dest_host:e})}async publishDnsTxt(e){const t={name:e.name,mode:e.mode};switch(void 0!==e.request_id&&(t.request_id=e.request_id),e.mode){case"add":if(!e.value)throw new J_("validation","publish_dns_txt mode=add requires value");t.value=e.value,void 0!==e.ttl&&(t.ttl=e.ttl);break;case"remove":if(!e.value)throw new J_("validation","publish_dns_txt mode=remove requires value");t.value=e.value;break;case"replace":if(!e.records)throw new J_("validation","publish_dns_txt mode=replace requires records");t.records=e.records.map(AA);break;default:throw new J_("validation",`publish_dns_txt mode \`${e.mode}\` is not supported`)}return this.call(this.bnsProxyRpc,z_,t)}async publishDocument(e){const t=null!==e.document&&"object"==typeof e.document&&!Array.isArray(e.document),n="string"==typeof e.document?e.document.trim().split("."):[],r=3===n.length&&n.every((e=>e.length>0));if(!t&&!r)throw new J_("validation","publish_document document must be a JSON object or non-empty compact JWT string");if("owner"===e.doc_type.trim().toLowerCase()&&!t)throw new J_("validation","owner document must be a JSON object");const s={name:e.name,doc_type:e.doc_type,document:e.document};return void 0!==e.request_id&&(s.request_id=e.request_id),this.call(this.bnsProxyRpc,K_,s)}async removeBoundZone(e){return this.call(this.bnsProxyRpc,$_,{name:e.name,zone_did:e.zone_did,expected_owner_hash:e.expected_owner_hash,request_id:e.request_id,owner_authorization:e.owner_authorization})}},SnClientError:J_,fetchSnRegionProbeConfig:async function(e,t=null,n={}){const r=wA(e),s={Accept:"application/json"};null!==t&&(/[\u0000-\u001f\u007f]/.test(t)&&sA("invalid cached region probe ETag: header value contains control characters"),s["If-None-Match"]=t);const i=new AbortController,o=setTimeout((()=>i.abort()),5e3);try{let e;try{e=await(n.fetcher??bA)(r,{method:"GET",headers:s,redirect:"manual",credentials:"omit",signal:i.signal})}catch(a){throw new J_("transport",`fetch SN region probe config from ${r} failed: ${String(a)}`)}if(304===e.status)return{kind:"not_modified"};if(404===e.status)return{kind:"not_configured"};if(200!==e.status)throw new J_("transport",`fetch SN region probe config from ${r} returned HTTP ${e.status}`);const t=e.headers.get("content-type")??"";if("application/json"!==t.split(";")[0].trim().toLowerCase())throw new J_("transport",`SN region probe config from ${r} has unsupported Content-Type ${JSON.stringify(t)}`);const o=e.headers.get("content-length");if(null!==o&&/^\d+$/.test(o)&&Number(o)>k_)throw new J_("transport",`SN region probe config from ${r} exceeds 1048576 bytes`);let c,l;try{c=await async function(e,t){if(!e.body){const n=new Uint8Array(await e.arrayBuffer());if(n.byteLength>k_)throw new J_("transport",`SN region probe config from ${t} exceeds 1048576 bytes`);return n}const n=e.body.getReader(),r=[];let s=0;for(;;){const{done:e,value:i}=await n.read();if(e)break;if(s+=i.byteLength,s>k_)throw await n.cancel(),new J_("transport",`SN region probe config from ${t} 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}(e,r)}catch(a){if(a instanceof J_)throw a;throw new J_("transport",`read SN region probe config from ${r} failed: ${String(a)}`)}try{l=yA(c)}catch(a){const e=a instanceof J_?a.detail:String(a);throw new J_("validation",`invalid SN region probe config from ${r}: ${e}`)}return{kind:"modified",document:{config:l,etag:e.headers.get("etag"),cache_control:e.headers.get("cache-control")}}}finally{clearTimeout(o)}},generateSnDeviceToken:async function(e,t,n,r=600){const s=Math.floor(Date.now()/1e3);return Mn.signJwtEdDSA({aud:_A,exp:s+r,iss:t,sub:e},n)},isCanonicalSnRegionId:dA,isPublicSnProbeIp:pA,normalizeSnRegionIdHint:function(e){const t=e.trim();if(0===iA(t)||iA(t)>128)return null;let n="",r=!1;for(const s of t)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:eA,parseSnRegionProbeConfig:yA,validateSnRegionProbeConfig:mA},Symbol.toStringTag,{value:"Module"}));let TA=null;function RA(e,t,n){let r=()=>{},s=null,i=0;const o=[];return{result:new Promise(((a,c)=>{let l;try{l=new Worker(function(){if(!TA){const e=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(e)}return TA}())}catch{return void c(new Error("Failed to create hash worker"))}r=()=>{l.terminate(),null==n||n.removeEventListener("abort",r),c(new Error("Hash cancelled"))},(null==n?void 0:n.aborted)?r():(null==n||n.addEventListener("abort",r,{once:!0}),l.onmessage=e=>{const t=e.data;if("chunk"===t.type){const e={index:t.index,hash:t.hash,offset:t.offset,length:t.length};o.push(e),i+=e.length,s&&s(i)}else"done"===t.type?(null==n||n.removeEventListener("abort",r),l.terminate(),a(o)):"error"===t.type&&(null==n||n.removeEventListener("abort",r),l.terminate(),c(new Error(t.message??"Worker hash error")))},l.onerror=e=>{null==n||n.removeEventListener("abort",r),l.terminate(),c(new Error(e.message??"Worker error"))},l.postMessage({file:e,chunkSize:t}))})),cancel:()=>r(),onProgress(e){s=e}}}class IA extends Error{constructor(e,t){super(t??e),this.code=e,this.name="NdmError"}}class CA extends Error{constructor(e,t,n,r){super(n??`NDM store API request failed with status ${e}`),this.name="NdmStoreApiError",this.status=e,this.errorCode=t,this.responseBody=r}}const OA=33554432,xA=4096,NA=new Map;let PA=0;let DA={getCapabilities:()=>({canRevealRealPath:!1,canUseNDMCache:!1,canUseNDMStore:!1,canPickDirectory:"undefined"!=typeof HTMLInputElement&&"webkitdirectory"in HTMLInputElement.prototype,canPickMixed:!1}),pickFiles(e){return new Promise(((t,n)=>{var r,s;const i=document.createElement("input");if(i.type="file","single_dir"===e.mode){if(!this.getCapabilities().canPickDirectory)return void n(new IA("DIRECTORY_NOT_SUPPORTED","This browser does not support directory selection"));i.webkitdirectory=!0}else"multi_file"!==e.mode&&"mixed"!==e.mode||(i.multiple=!0);e.accept&&e.accept.length>0&&"single_dir"!==e.mode&&(i.accept=e.accept.join(","));let o=!1;const a=()=>{var t;window.removeEventListener("focus",u),null==(t=e.signal)||t.removeEventListener("abort",l)},c=e=>{o||(o=!0,a(),n(e))},l=()=>c(new IA("USER_CANCELLED","Import cancelled")),u=()=>{setTimeout((()=>{o||c(new IA("USER_CANCELLED","User cancelled file selection"))}),500)};i.addEventListener("change",(()=>{if(o)return;const n=i.files;n&&0!==n.length?(o=!0,a(),t(Array.from(n))):c(new IA("single_dir"===e.mode?"EMPTY_DIRECTORY_UNAVAILABLE":"USER_CANCELLED","single_dir"===e.mode?"FileList cannot represent an empty directory; use a directory-tree provider":"No files selected"))})),i.addEventListener("cancel",l),window.addEventListener("focus",u),(null==(r=e.signal)?void 0:r.aborted)?l():(null==(s=e.signal)||s.addEventListener("abort",l,{once:!0}),i.click())}))}};function BA(e,t){if("undefined"!=typeof window&&"function"==typeof window.fetch)return window.fetch(e,t);if("undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch)return globalThis.fetch(e,t);throw new Error("fetch is not available in this runtime")}function UA(e){return e.replace(/\/+$/,"")}function LA(e){return encodeURIComponent(e).replace(/%3A/gi,":")}function MA(e){if(null==e?void 0:e.endpoint)return UA(e.endpoint);const t=Io();if(t)return UA(t);throw new IA("STORE_API_ENDPOINT_REQUIRED","NDM structured store endpoint is unknown; pass options.endpoint or call initBuckyOS first")}async function FA(e,t,n){var r;!function(){if(Ro()===Ni.Browser)throw new IA("STORE_API_NOT_SUPPORTED_IN_RUNTIME","NDM structured store APIs are not available in pure Browser runtime")}();const s=MA(n),i=(null==n?void 0:n.fetcher)??BA,o=void 0!==(null==n?void 0:n.sessionToken)?n.sessionToken:await Co(),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/${e}`,{method:"POST",headers:a,body:JSON.stringify(t),credentials:(null==n?void 0:n.credentials)??"include",signal:null==n?void 0:n.signal});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 e=l&&"object"==typeof l&&!Array.isArray(l)?l:null;throw new CA(c.status,null==e?void 0:e.error,(null==e?void 0:e.message)??("string"==typeof l&&l.length>0?l:`NDM store API request failed with status ${c.status}`),l)}return l}async function jA(e,t){const n=[`scope=${LA(e.scope)}`,`quick_hash=${LA(e.quick_hash)}`];e.inner_path&&n.push(`inner_path=${LA(e.inner_path)}`);const r=await async function(e,t){const n=MA(t),r=(null==t?void 0:t.fetcher)??BA,s=void 0!==(null==t?void 0:t.sessionToken)?t.sessionToken:await Co(),i={Accept:"application/json",...(null==t?void 0:t.headers)??{}};s&&!i.Authorization&&(i.Authorization=`Bearer ${s}`);const o=await r(`${n}${e}`,{method:"GET",headers:i,credentials:(null==t?void 0:t.credentials)??"include",signal:null==t?void 0:t.signal}),a=(o.headers.get("content-type")??"").includes("application/json")?await o.json():await o.text();if(!o.ok){const e=a&&"object"==typeof a&&!Array.isArray(a)?a:null;throw new CA(o.status,null==e?void 0:e.error,(null==e?void 0:e.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("&")}`,t);return function(e){try{return Mn.ObjId.fromString(e).isChunk()}catch{return!1}}(e.quick_hash),r}async function GA(e,t=33554432,n){iv(n);const r=e.size,s=[];if(r<=t){const t=new Uint8Array(await e.arrayBuffer()),i=Mn.sha256Bytes(t),o=Mn.ChunkId.fromMix256Result(t.length,i).toString();s.push({chunkId:o,offset:0,length:t.length,uploaded:!1});const a=new Mn.FileObject(e.name,r,o),[c,l]=a.genObjId();return iv(n),{objectId:c.toString(),chunks:s,fileObject:a.toJSON(),objects:[{obj_id:c.toString(),obj_data:l}]}}const i=new Mn.SimpleChunkList;let o=0;for(;o<r;){iv(n);const a=Math.min(o+t,r),c=new Uint8Array(await e.slice(o,a).arrayBuffer()),l=Mn.sha256Bytes(c),u=Mn.ChunkId.fromMix256Result(c.length,l);i.appendChunk(u),s.push({chunkId:u.toString(),offset:o,length:c.length,uploaded:!1}),o=a}const[a,c]=i.genObjId(),l=new Mn.FileObject(e.name,r,a.toString()),[u,h]=l.genObjId();return iv(n),{objectId:u.toString(),chunks:s,fileObject:l.toJSON(),objects:[{obj_id:a.toString(),obj_data:c},{obj_id:u.toString(),obj_data:h}]}}async function HA(e,t,n=33554432,r){if("undefined"==typeof Worker||"undefined"==typeof Blob||"undefined"==typeof URL||"function"!=typeof URL.createObjectURL||"undefined"==typeof crypto||void 0===crypto.subtle||0===e.size){const s=await GA(e,n,r);return null==t||t(e.size),s}let s,i;const o=RA(e,n,r);try{t&&o.onProgress(t);const e=new Promise(((e,t)=>{i=setTimeout((()=>{o.cancel(),t(new Error("hash worker timeout"))}),3e5)}));s=await Promise.race([o.result,e])}catch{return iv(r),GA(e,n,r)}finally{i&&clearTimeout(i)}iv(r);const a=e.size,c=[];if(1===s.length){const t=s[0],n=Mn.ChunkId.fromMix256Result(t.length,t.hash).toString();c.push({chunkId:n,offset:0,length:t.length,uploaded:!1});const i=new Mn.FileObject(e.name,a,n),[o,l]=i.genObjId();return iv(r),{objectId:o.toString(),chunks:c,fileObject:i.toJSON(),objects:[{obj_id:o.toString(),obj_data:l}]}}const l=new Mn.SimpleChunkList;for(const g of s){const e=Mn.ChunkId.fromMix256Result(g.length,g.hash);l.appendChunk(e),c.push({chunkId:e.toString(),offset:g.offset,length:g.length,uploaded:!1})}const[u,h]=l.genObjId(),d=new Mn.FileObject(e.name,a,u.toString()),[f,p]=d.genObjId();return iv(r),{objectId:f.toString(),chunks:c,fileObject:d.toJSON(),objects:[{obj_id:u.toString(),obj_data:h},{obj_id:f.toString(),obj_data:p}]}}function VA(e,t,n){const r=new Mn.FileObject(e,t,n),[s]=r.genObjId();return{objectId:s.toString(),fileObject:r.toJSON()}}function qA(){var e;const t=Io();return t?UA(t):"undefined"!=typeof window&&(null==(e=window.location)?void 0:e.origin)?UA(window.location.origin):void 0}async function WA(e){return e.size<12288?null:zA(e)}async function zA(e){const t=e.size;let n;if(t<12288)n=new Uint8Array(await e.arrayBuffer());else{n=new Uint8Array(12288);const r=[0,Math.floor((t-xA)/2),t-xA];for(let t=0;t<r.length;t++)n.set(new Uint8Array(await e.slice(r[t],r[t]+xA).arrayBuffer()),t*xA)}return Mn.ChunkId.fromMixHashResult(t,Mn.sha256Bytes(n),"qcid").toString()}async function KA(e,t,n){const r=t.endpoint??qA();if(!r)return null;const s=await WA(e);if(iv(t.signal),!s)return null;try{const n=await jA({scope:"app",quick_hash:s},{...t,endpoint:r});if(!0!==n.reusable||!("state"in n)||!["completed","same_as","local_link"].includes(n.state))return null;if(n.chunk_size!==e.size)return null;const i=function(e,t){const n=e;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 e=n[s];if("string"==typeof e&&e.length>0)return e}return"string"==typeof n.object_id&&n.object_id.length>0&&n.object_id!==t?n.object_id:void 0}(n,s);return!i||!Mn.ObjId.fromString(i).isChunk()&&!Mn.ObjId.fromString(i).isChunkList()||i.startsWith("qcid:")?null:{...VA(e.name,e.size,i),locality:"store",qcid:s}}catch(i){return iv(t.signal),i instanceof CA&&404===i.status||n.push(`QCID lookup for ${e.name}: ${sv(i)}`),null}}function $A(e){if(!e||"."===e||".."===e||/[\\/\x00-\x1f]/.test(e)||/^[a-z]:/i.test(e))throw new IA("INVALID_IMPORT_PATH",`Invalid file or directory name: ${e}`)}function QA(e){const t=e.split("/");return t.forEach($A),t}function JA(e,t){if(0===e.length)throw new IA("EMPTY_DIRECTORY_UNAVAILABLE","FileList cannot represent an empty directory; use importDirectory with directory nodes");const n=e.map((e=>QA(e.webkitRelativePath||e.name)));if(n.some((e=>e.length<2||e[0]!==n[0][0])))throw new IA("INVALID_IMPORT_PATH","Folder selection must contain one root directory in webkitRelativePath");const r={kind:"dir",objectId:"",name:n[0][0],children:[]};for(let s=0;s<n.length;s++){const e=n[s].slice(1);let i=r;for(let r=0;r<e.length;r++){const o=e[r],a=i.children.find((e=>e.name===o));if(r===e.length-1){if(a)throw new IA("IMPORT_PATH_CONFLICT",`Duplicate file or directory: ${n[s].join("/")}`);if(o!==t[s].name)throw new IA("INVALID_IMPORT_PATH","Relative path basename must match File.name");i.children.push(t[s])}else{if("file"===(null==a?void 0:a.kind))throw new IA("IMPORT_PATH_CONFLICT",`File used as directory: ${o}`);const t=a??{kind:"dir",objectId:"",name:o,relativePath:e.slice(0,r+1).join("/"),children:[]};a||i.children.push(t),i=t}}}return r}function YA(e,t){const n=new Mn.DirObject(e.name);if(e.children)for(const i of e.children)if("file"===i.kind){if(!i._ndnFileObject)throw new IA("UPLOAD_FAILED",`Missing NDN FileObject for ${i.name}`);n.addFile(i.name,i._ndnFileObject,i.size)}else{const e=YA(i,t);n.addDirectory(i.name,Mn.ObjId.fromString(e.objectId),e.totalSize)}const[r,s]=n.genObjId();return e.objectId=r.toString(),t.set(e.objectId,{obj_id:e.objectId,obj_data:s}),{objectId:e.objectId,totalSize:n.total_size,fileCount:n.file_count,fileSize:n.file_size}}function ZA(e,t){if(!t||!t.enabled)return!1;if(!t.forTypes||0===t.forTypes.length)return e.type.startsWith("image/");for(const n of t.forTypes)if(n.endsWith("/*")){const t=n.slice(0,-1);if(e.type.startsWith(t))return!0}else if(n.startsWith(".")){if(e.name.toLowerCase().endsWith(n.toLowerCase()))return!0}else if(e.type===n)return!0;return!1}async function XA(e,t){const n=t.maxWidth??256,r=t.maxHeight??256;try{return e.type.startsWith("image/")?await function(e,t,n){return new Promise((r=>{const s=URL.createObjectURL(e),i=new Image;i.onload=()=>{let e=i.naturalWidth,o=i.naturalHeight;if(e>t||o>n){const r=Math.min(t/e,n/o);e=Math.round(e*r),o=Math.round(o*r)}const a=document.createElement("canvas");a.width=e,a.height=o;a.getContext("2d").drawImage(i,0,0,e,o);const c=a.toDataURL("image/jpeg",.8);URL.revokeObjectURL(s),r({available:!0,url:c,width:e,height:o,mimeType:"image/jpeg"})},i.onerror=()=>{URL.revokeObjectURL(s),r({available:!1,errorCode:"THUMBNAIL_GENERATION_FAILED"})},i.src=s}))}(e,n,r):{available:!1,errorCode:"UNSUPPORTED_TYPE"}}catch{return{available:!1,errorCode:"THUMBNAIL_GENERATION_FAILED"}}}async function ev(e,t){return tv(e,t)}async function tv(e,t,n){var r;iv(t.signal);const s=[...e],i=[];if(n){const e=(t,n)=>{$A(t.name);const r=new Set;for(const o of t.children){const t="file"===o.kind?o.file.name:o.name;if($A(t),r.has(t))throw new IA("IMPORT_PATH_CONFLICT",`Duplicate child: ${n}/${t}`);r.add(t),"file"===o.kind?(s.push(o.file),i.push(`${n}/${t}`)):e(o,`${n}/${o.name}`)}};e(n,n.name)}if(!n&&0===s.length)throw new IA("single_dir"===t.mode?"EMPTY_DIRECTORY_UNAVAILABLE":"USER_CANCELLED","single_dir"===t.mode?"FileList cannot represent empty directories; use importDirectory":"No files selected");if("single_file"===t.mode&&1!==s.length)throw new IA("INVALID_IMPORT_PATH","single_file requires exactly one file");s.forEach((e=>{$A(e.name),e.webkitRelativePath&&QA(e.webkitRelativePath)})),n||"single_dir"!==t.mode||JA(s,s.map((e=>({kind:"file",objectId:"",name:e.name,size:e.size}))));const o=[];n||"single_dir"!==t.mode||o.push("FileList selections cannot preserve empty directories");const a=new Map,c=[],l={endpoint:t.endpoint,sessionToken:t.sessionToken,fetcher:t.fetcher,headers:t.headers,signal:t.signal},u=[],h=new Map;let d=!0;const f=t.onProgress,p=s.length;for(let E=0;E<s.length;E++){const e=s[E];iv(t.signal);const n=i[E]||e.webkitRelativePath||void 0;f&&f({phase:"qcid_lookup",fileIndex:E,fileCount:p,fileName:e.name,fileTotalBytes:e.size});const g=await KA(e,l,o);let m=null;g||(f&&f({phase:"materializing",fileIndex:E,fileCount:p,fileName:e.name,bytesProcessed:0,fileTotalBytes:e.size}),m=await HA(e,f?t=>{f({phase:"materializing",fileIndex:E,fileCount:p,fileName:e.name,bytesProcessed:t,fileTotalBytes:e.size})}:void 0,OA,t.signal));const y=(null==g?void 0:g.objectId)??m.objectId,w=(null==g?void 0:g.fileObject)??m.fileObject,b=g?[]:m.chunks;if(m)for(const t of m.objects)a.set(t.obj_id,t);else{const[,t]=new Mn.FileObject(e.name,e.size,w.content).genObjId();a.set(y,{obj_id:y,obj_data:t})}const _=(null==g?void 0:g.qcid)??await WA(e);_&&c.push({qcid:_,content_id:w.content,size:e.size}),iv(t.signal);const A={kind:"file",objectId:y,name:e.name,size:e.size,mimeType:e.type||void 0,relativePath:n,locality:(null==g?void 0:g.locality)??"local_only",_file:e,_ndnFileObject:w};if(ZA(e,t.thumbnails)){f&&f({phase:"thumbnail",fileIndex:E,fileCount:p,fileName:e.name,fileTotalBytes:e.size});!1!==(null==(r=t.thumbnails)?void 0:r.eager)?A.thumbnail=await XA(e,t.thumbnails):(A.thumbnail={available:!1},XA(e,t.thumbnails).then((e=>{A.thumbnail=e})))}u.push(A),g||(d=!1),h.set(y,{objectId:y,name:e.name,size:e.size,file:e,uploadedBytes:g?e.size:0,state:g?"completed":"pending",chunks:b})}let g,m;if("single_dir"===t.mode){let e=0;const t=n=>({kind:"dir",name:n.name,objectId:"",children:n.children.map((n=>"file"===n.kind?u[e++]:t(n)))}),r=n?t(n):JA(s,u);YA(r,a),g=[r],m=r}else g=u,m="single_file"===t.mode?u[0]:u;const y=function(e){let t=0,n=0,r=0;return function e(s){for(const i of s)"file"===i.kind?(t++,r+=i.size):(n++,i.children&&e(i.children))}(e),{totalObjects:t+n,totalFiles:t,totalDirs:n,totalBytes:r}}(g),w=(PA+=1,`import-${Date.now()}-${PA}`),b=d?"all_in_store":"ok",_="not_started",A={sessionId:w,items:g,materializationStatus:b,uploadStatus:_,summary:y,objectStates:h,objectStatus:"pending",warnings:o,manifest:a,qcidLinks:c,requestOptions:l,transmittedBytes:0};NA.set(w,A);const v={sessionId:w,selection:m,items:g,objectStatus:"pending",warnings:o,materializationStatus:b,uploadStatus:_,summary:y};return t.autoStartUpload&&(av(w,{endpoint:t.endpoint,sessionToken:t.sessionToken,fetcher:t.fetcher,headers:t.headers,signal:t.signal}).catch((()=>{})),v.uploadStatus="uploading"),v}async function nv(e){const t=NA.get(e);if(!t)throw new IA("SESSION_NOT_FOUND",`Session ${e} not found`);const n={};let r=0,s=0;const i=e=>{for(const o of e){if("dir"===o.kind){i(o.children??[]);continue}const e=t.objectStates.get(o.objectId);n[o.objectId]={objectId:o.objectId,uploadedBytes:e.uploadedBytes,totalBytes:e.size,state:e.state},r+=e.uploadedBytes,"completed"===e.state&&s++}};return i(t.items),{sessionId:e,materializationStatus:t.materializationStatus,uploadStatus:t.uploadStatus,objectStatus:t.objectStatus,error:t.error,warnings:[...t.warnings],summary:t.summary,progress:{uploadedBytes:r,uploadedObjects:s,totalBytes:t.summary.totalBytes,totalObjects:t.summary.totalFiles},perObjectProgress:n}}async function rv(e){const t=await nv(e),n={sessionId:e,uploadStatus:t.uploadStatus,objectStatus:t.objectStatus,error:t.error,warnings:t.warnings,transmittedBytes:ov(e).transmittedBytes,totalBytes:t.progress.totalBytes,uploadedBytes:t.progress.uploadedBytes,totalObjects:t.progress.totalObjects,uploadedObjects:t.progress.uploadedObjects,perObjectProgress:t.perObjectProgress},r=NA.get(e);if(r.uploadStartTime&&"uploading"===t.uploadStatus&&(n.elapsedMs=Date.now()-r.uploadStartTime,n.uploadedBytes>0&&n.elapsedMs>0)){n.speedBps=Math.round(1e3*n.uploadedBytes/n.elapsedMs);const e=n.totalBytes-n.uploadedBytes;n.estimatedRemainingMs=Math.round(1e3*e/n.speedBps)}return n}function sv(e){return e instanceof Error?e.message:String(e)}function iv(e){if(null==e?void 0:e.aborted)throw new IA("USER_CANCELLED","Import cancelled")}function ov(e){const t=NA.get(e);if(!t)throw new IA("SESSION_NOT_FOUND",`Session ${e} not found`);return t}async function av(e,t={}){var n;const r=ov(e);if("ready"===r.objectStatus||r.uploadPromise)return nv(e);const s=t.concurrency??3;if(!Number.isInteger(s)||s<1)throw new IA("UPLOAD_FAILED","concurrency must be a positive integer");iv(t.signal),r.requestOptions={...r.requestOptions,...Object.fromEntries(Object.entries({endpoint:t.endpoint,sessionToken:t.sessionToken,fetcher:t.fetcher,headers:t.headers}).filter((([,e])=>void 0!==e)))};const i=r.requestOptions.endpoint??qA();if(!i)throw new IA("STORE_API_ENDPOINT_REQUIRED","Pass endpoint or initialize the SDK before uploading");r.requestOptions.endpoint=UA(i),r.abortController=new AbortController;const o=()=>{var e;return null==(e=r.abortController)?void 0:e.abort()};return null==(n=t.signal)||n.addEventListener("abort",o,{once:!0}),r.requestOptions.signal=r.abortController.signal,r.uploadStatus="uploading",r.objectStatus="pending",r.error=void 0,r.onProgress=t.onProgress,r.uploadStartTime=Date.now(),r.uploadPromise=async function(e,t){var n;const r=[...e.objectStates.values()],s=new Map;let i,o=0;const a=Array.from({length:Math.min(t,r.length)},(async()=>{for(var t,n;o<r.length&&!i;){const c=r[o++];try{if(iv(null==(t=e.abortController)?void 0:t.signal),"completed"===c.state)continue;c.state="uploading";for(const[t,r]of c.chunks.entries()){if(iv(null==(n=e.abortController)?void 0:n.signal),r.uploaded)continue;let i=s.get(r.chunkId);i||(i=uv(e,c,r,t),s.set(r.chunkId,i)),await i,r.uploaded=!0,c.uploadedBytes=c.chunks.filter((e=>e.uploaded)).reduce(((e,t)=>e+t.length),0),lv(e)}c.uploadedBytes=c.size,c.state="completed"}catch(a){c.state="failed",i=a}}}));if(await Promise.all(a),i)throw i;iv(null==(n=e.abortController)?void 0:n.signal),e.objectStatus="finalizing",lv(e);const c=e.requestOptions,l=void 0!==c.sessionToken?c.sessionToken:await Co(),u=await(c.fetcher??BA)(`${c.endpoint}/ndm/v1/import/finalize`,{method:"POST",credentials:"include",signal:c.signal,headers:{...c.headers,"Content-Type":"application/json",...l?{Authorization:`Bearer ${l}`}:{}},body:JSON.stringify({objects:[...e.manifest.values()],roots:e.items.map((e=>e.objectId)),qcid_links:e.qcidLinks})}),h=await u.json();if(!u.ok)throw new CA(u.status,h.error,h.message??"Object registration failed",h);iv(c.signal),Array.isArray(h.warnings)&&e.warnings.push(...h.warnings.map(String));if(!0!==h.ready||!Array.isArray(h.roots)||e.items.some((e=>!h.roots.some((t=>t.obj_id===e.objectId&&!0===t.ready)))))throw new IA("OBJECT_NOT_READY","NDM did not confirm all root objects and their dependencies are ready");e.objectStatus="ready",e.uploadStatus=0===e.transmittedBytes?"not_required":"completed",e.materializationStatus="all_in_store",lv(e)}(r,s).catch((e=>{var t;r.error=sv(e);const n=null==(t=r.abortController)?void 0:t.signal.aborted;throw r.uploadStatus=n?"cancelled":"failed",r.objectStatus=n?"cancelled":"failed",e})).finally((()=>{var e;r.uploadPromise=void 0,null==(e=t.signal)||e.removeEventListener("abort",o),lv(r)})),r.uploadPromise.catch((()=>{})),nv(e)}function cv(e){var t;const n=ov(e);"ready"!==n.objectStatus&&(null==(t=n.abortController)||t.abort(),n.uploadStatus="cancelled",n.objectStatus="cancelled")}function lv(e){e.onProgress&&NA.has(e.sessionId)&&rv(e.sessionId).then((t=>{var n;return null==(n=e.onProgress)?void 0:n.call(e,t)})).catch((()=>{}))}async function uv(e,t,n,r){var s,i;try{const t=await jA({scope:"app",quick_hash:n.chunkId},e.requestOptions);if(!0===t.reusable&&"state"in t&&["completed","same_as","local_link"].includes(t.state)&&t.chunk_size===n.length)return}catch(a){iv(null==(s=e.abortController)?void 0:s.signal),a instanceof CA&&404===a.status||e.warnings.push(`Chunk lookup: ${sv(a)}`)}const o=void 0!==e.requestOptions.sessionToken?e.requestOptions.sessionToken:await Co();await async function(e,t,n,r,s,i,o,c,l){const u=t.slice(n.offset,n.offset+n.length),h=new Uint8Array(await u.arrayBuffer()),d=n.chunkId;let f;try{f=await Promise.resolve().then((()=>require("./tus_client-a2f73d53.js")))}catch(a){const t=a instanceof Error?a.message:String(a);throw new IA("UPLOAD_FAILED",`Failed to load tus-js-client: ${t}`)}return new Promise(((a,u)=>{if(null==l?void 0:l.aborted)return void u(new IA("UPLOAD_FAILED","Upload aborted"));const p=new Blob([h]),g=new f.Upload(p,{endpoint:`${e}/ndm/v1/uploads`,..."undefined"==typeof XMLHttpRequest?{httpStack:f.fetchHttpStack}:{},headers:{...o,...i?{Authorization:`Bearer ${i}`}:{}},chunkSize:h.length,retryDelays:[0,1e3,3e3,5e3],storeFingerprintForResuming:!1,metadata:{logical_path:d,file_name:t.name,file_size:String(t.size),file_hash:s,chunk_index:String(r),chunk_hash:n.chunkId,mime_type:t.type||"application/octet-stream"},onProgress:e=>{c(e)},onSuccess:()=>{c(h.length),null==l||l.removeEventListener("abort",m),a(n.chunkId)},onError:e=>{null==l||l.removeEventListener("abort",m),u(new IA("UPLOAD_FAILED",e.message))}}),m=()=>{Promise.resolve(g.abort(!0)).catch((()=>{})),u(new IA("USER_CANCELLED","Upload cancelled"))};null==l||l.addEventListener("abort",m,{once:!0}),g.start()}))}(e.requestOptions.endpoint,t.file,n,r,t.objectId,o,e.requestOptions.headers,(n=>{t.uploadedBytes=t.chunks.filter((e=>e.uploaded)).reduce(((e,t)=>e+t.length),0)+n,lv(e)}),null==(i=e.abortController)?void 0:i.signal),e.transmittedBytes+=n.length}const hv=Object.freeze(Object.defineProperty({__proto__:null,NdmError:IA,NdmStoreApiError:CA,addChunkBySameAs:async function(e,t){return FA("add_chunk_by_same_as",e,t)},anchorState:async function(e,t){return FA("anchor_state",e,t)},applyEdge:async function(e,t){return FA("apply_edge",e,t)},calculateQcidFromFile:zA,cancelImportSession:cv,debugDumpExpandState:async function(e,t){return FA("debug_dump_expand_state",e,t)},ensureUploaded:async function(e,t={}){await av(e,t);const n=ov(e);if(await n.uploadPromise,"ready"!==n.objectStatus)throw new IA("OBJECT_NOT_READY",n.error??"Objects are not ready");return nv(e)},forcedGcUntil:async function(e,t){return FA("forced_gc_until",e,t)},fsAcquire:async function(e,t){return FA("fs_acquire",e,t)},fsAnchorState:async function(e,t){return FA("fs_anchor_state",e,t)},fsRelease:async function(e,t){return FA("fs_release",e,t)},fsReleaseInode:async function(e,t){return FA("fs_release_inode",e,t)},getDirChild:async function(e,t){return FA("get_dir_child",e,t)},getImportProvider:function(){return DA},getImportSessionStatus:nv,getObject:async function(e,t){return FA("get_object",e,t)},getUploadProgress:rv,haveChunk:async function(e,t){return FA("have_chunk",e,t)},importDirectory:async function(e,t={}){return tv([],{...t,mode:"single_dir"},e)},importFiles:ev,isObjectExist:async function(e,t){return FA("is_object_exist",e,t)},isObjectStored:async function(e,t){return FA("is_object_stored",e,t)},lookupObject:jA,openObject:async function(e,t){return FA("open_object",e,t)},outboxCount:async function(e){return FA("outbox_count",{},e)},pickupAndImport:async function(e){const t=e.provider??DA,n=t.getCapabilities();if("single_dir"===e.mode&&!n.canPickDirectory)throw new IA("DIRECTORY_NOT_SUPPORTED");if("mixed"===e.mode&&!n.canPickMixed)throw new IA("MODE_NOT_SUPPORTED_IN_RUNTIME");return iv(e.signal),ev(await t.pickFiles(e),e)},pin:async function(e,t){return FA("pin",e,t)},putObject:async function(e,t){return FA("put_object",e,t)},queryChunkState:async function(e,t){return FA("query_chunk_state",e,t)},queryObjectById:async function(e,t){return FA("query_object_by_id",e,t)},releaseImportSession:function(e){const t=ov(e);cv(e),NA.delete(e);const n=e=>e.forEach((e=>{"dir"===e.kind?n(e.children??[]):(delete e._file,delete e._ndnFileObject)}));n(t.items)},removeChunk:async function(e,t){return FA("remove_chunk",e,t)},removeObject:async function(e,t){return FA("remove_object",e,t)},setImportProvider:function(e){DA=e},startUpload:av,unpin:async function(e,t){return FA("unpin",e,t)},unpinOwner:async function(e,t){return FA("unpin_owner",e,t)}},Symbol.toStringTag,{value:"Module"})),dv="/ndm/proxy/v1";class fv extends Error{constructor(e,t,n,r){super(n??`NDM proxy request failed with status ${e}`),this.name="NdmProxyApiError",this.status=e,this.errorCode=t,this.responseBody=r}}class pv extends Error{constructor(e,t){super(t??e),this.name="NdmProxyError",this.code=e}}function gv(e,t){if("undefined"!=typeof window&&"function"==typeof window.fetch)return window.fetch(e,t);if("undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch)return globalThis.fetch(e,t);throw new Error("fetch is not available in this runtime")}function mv(e){return e.replace(/\/+$/,"")}function yv(){const e=Ro();if(e===Ni.Browser||e===Ni.AppRuntime)throw new pv("PROXY_API_NOT_SUPPORTED_IN_RUNTIME","NDM proxy APIs are not available in Browser/AppRuntime; use ndm_client for browser import/upload flows")}function wv(e){if(null==e?void 0:e.endpoint)return mv(e.endpoint);const t=Io();if(t)return mv(t);throw new pv("PROXY_API_ENDPOINT_REQUIRED","NDM proxy endpoint is unknown; pass options.endpoint or call initBuckyOS first")}async function bv(e,t){const n=void 0!==(null==e?void 0:e.sessionToken)?e.sessionToken:await Co(),r={...t,...(null==e?void 0:e.headers)??{}};return n&&!r.Authorization&&(r.Authorization=`Bearer ${n}`),r}async function _v(e){const t=(e.headers.get("content-type")??"").includes("application/json")?await e.json():await e.text(),n=t&&"object"==typeof t&&!Array.isArray(t)?t:null;throw new fv(e.status,null==n?void 0:n.error,(null==n?void 0:n.message)??("string"==typeof t&&t.length>0?t:`NDM proxy request failed with status ${e.status}`),t)}async function Av(e,t,n){var r;yv();const s=wv(n),i=(null==n?void 0:n.fetcher)??gv,o=await bv(n,{Accept:"application/json","Content-Type":"application/json"}),a=await i(`${s}${dv}/rpc/${e}`,{method:"POST",headers:o,body:JSON.stringify(t),credentials:(null==n?void 0:n.credentials)??"include"});if(!a.ok)return _v(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 e=await a.text();throw new fv(a.status,"invalid_data",e.length>0?e:"NDM proxy JSON RPC returned a non-JSON response",e)}return await a.json()}function vv(e,t){const n=e.get(t);if(null===n||""===n.trim())return null;const r=Number(n);return Number.isFinite(r)?r:null}async function Ev(e,t,n){yv();const r=wv(n),s=(null==n?void 0:n.fetcher)??gv,i=await bv(n,{Accept:"application/octet-stream","Content-Type":"application/json"}),o=await s(`${r}${dv}${e}`,{method:"POST",headers:i,body:JSON.stringify(t),credentials:(null==n?void 0:n.credentials)??"include"});return o.ok?{response:o,body:o.body,totalSize:vv(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:vv(o.headers,"Content-Length"),offset:vv(o.headers,"NDM-Offset")}:_v(o)}async function kv(e){const t=await e.response.arrayBuffer();return new Uint8Array(t)}class Sv{constructor(e){this.options=e}getObject(e,t){return Cv(e,{...this.options,...t})}openObject(e,t){return Ov(e,{...this.options,...t})}getDirChild(e,t){return xv(e,{...this.options,...t})}isObjectStored(e,t){return Nv(e,{...this.options,...t})}isObjectExist(e,t){return Pv(e,{...this.options,...t})}queryObjectById(e,t){return Dv(e,{...this.options,...t})}putObject(e,t){return Bv(e,{...this.options,...t})}removeObject(e,t){return Uv(e,{...this.options,...t})}haveChunk(e,t){return Lv(e,{...this.options,...t})}queryChunkState(e,t){return Mv(e,{...this.options,...t})}removeChunk(e,t){return Fv(e,{...this.options,...t})}addChunkBySameAs(e,t){return jv(e,{...this.options,...t})}applyEdge(e,t){return Gv(e,{...this.options,...t})}pin(e,t){return Hv(e,{...this.options,...t})}unpin(e,t){return Vv(e,{...this.options,...t})}unpinOwner(e,t){return qv(e,{...this.options,...t})}fsAcquire(e,t){return Wv(e,{...this.options,...t})}fsRelease(e,t){return zv(e,{...this.options,...t})}fsReleaseInode(e,t){return Kv(e,{...this.options,...t})}fsAnchorState(e,t){return $v(e,{...this.options,...t})}forcedGcUntil(e,t){return Qv(e,{...this.options,...t})}outboxCount(e){return Jv({...this.options,...e})}debugDumpExpandState(e,t){return Yv(e,{...this.options,...t})}anchorState(e,t){return Zv(e,{...this.options,...t})}}class Tv{constructor(e){this.options=e}openChunkReader(e,t){return Xv(e,{...this.options,...t})}getChunkData(e,t){return eE(e,{...this.options,...t})}getChunkPiece(e,t){return tE(e,{...this.options,...t})}openChunkListReader(e,t){return nE(e,{...this.options,...t})}openReader(e,t){return rE(e,{...this.options,...t})}}class Rv{constructor(e){this.options=e}putChunkByReader(e,t,n){return sE(e,t,{...this.options,...n})}putChunk(e,t,n){return iE(e,t,{...this.options,...n})}}class Iv{constructor(e){this.options=e,this.rpc=new Sv(e),this.reader=new Tv(e),this.writer=new Rv(e)}getObject(e,t){return this.rpc.getObject(e,t)}openObject(e,t){return this.rpc.openObject(e,t)}getDirChild(e,t){return this.rpc.getDirChild(e,t)}isObjectStored(e,t){return this.rpc.isObjectStored(e,t)}isObjectExist(e,t){return this.rpc.isObjectExist(e,t)}queryObjectById(e,t){return this.rpc.queryObjectById(e,t)}putObject(e,t){return this.rpc.putObject(e,t)}removeObject(e,t){return this.rpc.removeObject(e,t)}haveChunk(e,t){return this.rpc.haveChunk(e,t)}queryChunkState(e,t){return this.rpc.queryChunkState(e,t)}removeChunk(e,t){return this.rpc.removeChunk(e,t)}addChunkBySameAs(e,t){return this.rpc.addChunkBySameAs(e,t)}applyEdge(e,t){return this.rpc.applyEdge(e,t)}pin(e,t){return this.rpc.pin(e,t)}unpin(e,t){return this.rpc.unpin(e,t)}unpinOwner(e,t){return this.rpc.unpinOwner(e,t)}fsAcquire(e,t){return this.rpc.fsAcquire(e,t)}fsRelease(e,t){return this.rpc.fsRelease(e,t)}fsReleaseInode(e,t){return this.rpc.fsReleaseInode(e,t)}fsAnchorState(e,t){return this.rpc.fsAnchorState(e,t)}forcedGcUntil(e,t){return this.rpc.forcedGcUntil(e,t)}outboxCount(e){return this.rpc.outboxCount(e)}debugDumpExpandState(e,t){return this.rpc.debugDumpExpandState(e,t)}anchorState(e,t){return this.rpc.anchorState(e,t)}openChunkReader(e,t){return this.reader.openChunkReader(e,t)}getChunkData(e,t){return this.reader.getChunkData(e,t)}getChunkPiece(e,t){return this.reader.getChunkPiece(e,t)}openChunkListReader(e,t){return this.reader.openChunkListReader(e,t)}openReader(e,t){return this.reader.openReader(e,t)}putChunkByReader(e,t,n){return this.writer.putChunkByReader(e,t,n)}putChunk(e,t,n){return this.writer.putChunk(e,t,n)}withOptions(e){return new Iv({...this.options,...e})}}async function Cv(e,t){return Av("get_object",e,t)}async function Ov(e,t){return Av("open_object",e,t)}async function xv(e,t){return Av("get_dir_child",e,t)}async function Nv(e,t){return Av("is_object_stored",e,t)}async function Pv(e,t){return Av("is_object_exist",e,t)}async function Dv(e,t){return Av("query_object_by_id",e,t)}async function Bv(e,t){return Av("put_object",e,t)}async function Uv(e,t){return Av("remove_object",e,t)}async function Lv(e,t){return Av("have_chunk",e,t)}async function Mv(e,t){return Av("query_chunk_state",e,t)}async function Fv(e,t){return Av("remove_chunk",e,t)}async function jv(e,t){return Av("add_chunk_by_same_as",e,t)}async function Gv(e,t){return Av("apply_edge",e,t)}async function Hv(e,t){return Av("pin",e,t)}async function Vv(e,t){return Av("unpin",e,t)}async function qv(e,t){return Av("unpin_owner",e,t)}async function Wv(e,t){return Av("fs_acquire",e,t)}async function zv(e,t){return Av("fs_release",e,t)}async function Kv(e,t){return Av("fs_release_inode",e,t)}async function $v(e,t){return Av("fs_anchor_state",e,t)}async function Qv(e,t){return Av("forced_gc_until",e,t)}async function Jv(e){return Av("outbox_count",{},e)}async function Yv(e,t){return Av("debug_dump_expand_state",e,t)}async function Zv(e,t){return Av("anchor_state",e,t)}async function Xv(e,t){return Ev("/read/chunk/open",e,t)}async function eE(e,t){return kv(await Ev("/read/chunk/data",e,t))}async function tE(e,t){return kv(await Ev("/read/chunk/piece",e,t))}async function nE(e,t){return Ev("/read/chunklist/open",e,t)}async function rE(e,t){return Ev("/read/object/open",e,t)}async function sE(e,t,n){var r;yv();const s=wv(n),i=(null==n?void 0:n.fetcher)??gv,o=function(e){return e instanceof Uint8Array||e instanceof ArrayBuffer?e.byteLength:"undefined"!=typeof Blob&&e instanceof Blob?e.size:"string"==typeof e?(new TextEncoder).encode(e).byteLength:null}(t),a=(null==n?void 0:n.chunkSize)??o;if(null===a)throw new pv("PROXY_API_CHUNK_SIZE_REQUIRED","chunkSize is required when the request body length cannot be inferred");const c=await bv(n,{Accept:"application/json","Content-Type":"application/octet-stream","Content-Length":String(a),"NDM-Chunk-Size":String(a)}),l=await i(`${s}${function(e){return`${dv}/write/chunk/${encodeURIComponent(e)}`}(e)}`,{method:"PUT",headers:c,body:t,credentials:(null==n?void 0:n.credentials)??"include"});return l.ok?(await(null==(r=l.body)?void 0:r.cancel()),{chunkSize:vv(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}):_v(l)}async function iE(e,t,n){return sE(e,t,{...n,chunkSize:(null==n?void 0:n.chunkSize)??t.byteLength})}const oE=Object.freeze(Object.defineProperty({__proto__:null,NDM_PROXY_V1_PATH:dv,NdmProxyApiError:fv,NdmProxyClient:Iv,NdmProxyError:pv,NdmProxyReaderClient:Tv,NdmProxyRpcClient:Sv,NdmProxyWriterClient:Rv,addChunkBySameAs:jv,anchorState:Zv,applyEdge:Gv,createNdmProxyClient:function(e){return new Iv(e)},debugDumpExpandState:Yv,forcedGcUntil:Qv,fsAcquire:Wv,fsAnchorState:$v,fsRelease:zv,fsReleaseInode:Kv,getChunkData:eE,getChunkPiece:tE,getDirChild:xv,getObject:Cv,haveChunk:Lv,isObjectExist:Pv,isObjectStored:Nv,openChunkListReader:nE,openChunkReader:Xv,openObject:Ov,openReader:rE,outboxCount:Jv,pin:Hv,putChunk:iE,putChunkByReader:sE,putObject:Bv,queryChunkState:Mv,queryObjectById:Dv,removeChunk:Fv,removeObject:Uv,unpin:Vv,unpinOwner:qv},Symbol.toStringTag,{value:"Module"}));class aE extends Error{constructor(e,t="unavailable",n=!1){super(e),this.code=t,this.effectUnknown=n,this.name="ExecutorStreamError"}}function cE(e){const t=(new TextEncoder).encode(JSON.stringify(e));if(t.length>1048576)throw new Error("Executor control frame exceeds 1 MiB");const n=new Uint8Array(5+t.length);return n[0]=1,new DataView(n.buffer).setUint32(1,t.length),n.set(t,5),n}class lE{constructor(e,t,n){this.socket=e,this.target=t,this.runId=n,this.buffer=new Uint8Array,this.sequence=0,this.pending=new Map,this.closed=!1,e.binaryType="arraybuffer",e.onmessage=e=>{if(e.data instanceof ArrayBuffer)try{this.receive(new Uint8Array(e.data))}catch{this.fail(new aE("Invalid Command Stream frame","protocol"))}else this.fail(new aE("Expected binary Command Stream"))},e.onclose=()=>this.fail(new aE("Executor disconnected; query the persisted operation locator before taking further action","unavailable",!0)),e.onerror=()=>this.fail(new aE("Executor transport failed","unavailable",!0))}static async connect(e,t,n,r,s){if(e.executor_id!==t.executor_id||e.generation!==t.generation||e.profile_id!==t.profile_id||e.expires_at_ms<=Date.now())throw new aE("Route does not match the requested active executor","stale_target");const i=new URL(e.ws_url);if("wss:"!==i.protocol&&("ws:"!==i.protocol||!["localhost","127.0.0.1","[::1]"].includes(i.hostname)))throw new aE("Executor routes require WSS");if(i.username||i.password||i.hash)throw new aE("Invalid executor route URL");const o=new WebSocket(i);await new Promise(((t,n)=>{const r=setTimeout((()=>{o.close(),n(new aE("Route authentication timed out"))}),1e4);o.onopen=()=>o.send(JSON.stringify({ticket:e.ticket})),o.onmessage=e=>{try{if("string"!=typeof e.data||!0!==JSON.parse(e.data).ready)throw new Error;clearTimeout(r),t()}catch{clearTimeout(r),o.close(),n(new aE("Route authentication failed"))}},o.onerror=o.onclose=()=>{clearTimeout(r),n(new aE("Unable to connect executor route"))}}));const a=new lE(o,t,s);try{const e=await a.request("login",{v:1,token:n,profile:t.profile_id,client:{runtime_id:r,run_id:s}});if("login_ok"!==e.type||e.store_id!==t.store_id)throw new aE("Executor ledger changed","store_mismatch");return a}catch(c){throw a.close(),c}}receive(e){const t=new Uint8Array(this.buffer.length+e.length);for(t.set(this.buffer),t.set(e,this.buffer.length),this.buffer=t;this.buffer.length>=5;){const e=new DataView(this.buffer.buffer,this.buffer.byteOffset).getUint32(1);if(e>1048576||![1,2].includes(this.buffer[0]))throw new Error;if(this.buffer.length<e+5)return;const t=this.buffer[0],n=this.buffer.slice(5,e+5);if(this.buffer=this.buffer.slice(e+5),1!==t)continue;const r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n));if("closing"===r.type)return void this.fail(new aE("Executor stopped accepting requests"));const s=r.request_id&&this.pending.get(r.request_id);s&&(this.pending.delete(r.request_id),clearTimeout(s.timer),r.error?s.reject(new aE(r.error.message,r.error.code,r.error.effect_unknown)):s.resolve(r))}}fail(e){if(!this.closed){this.closed=!0;for(const t of this.pending.values())clearTimeout(t.timer),t.reject(e);this.pending.clear(),this.socket.close()}}close(){this.fail(new aE("Executor stream closed","unavailable",!0))}request(e,t={},n=4e4){if(this.closed)return Promise.reject(new aE("Executor stream is closed"));const r="q"+ ++this.sequence;return new Promise(((s,i)=>{const o=setTimeout((()=>{this.pending.delete(r),i(new aE("Executor response timed out; query operation before retrying","unavailable",!0))}),n);this.pending.set(r,{resolve:s,reject:i,timer:o});try{this.socket.send(cE({...t,type:e,request_id:r}))}catch{clearTimeout(o),this.pending.delete(r),i(new aE("Unable to send request","unavailable",!0))}}))}operation(e){if(e.executor_id!==this.target.executor_id||e.store_id!==this.target.store_id||e.profile_id!==this.target.profile_id)throw new aE("Operation locator belongs to another executor, profile or ledger","store_mismatch");return{store_id:e.store_id,op_id:e.op_id,run_id:e.run_id,call_id:e.call_id}}fresh(e){if(e.generation!==this.target.generation)throw new aE("Cannot dispatch an old operation to a new connection generation","stale_target");return this.operation(e)}async describe(e){const t=await this.request("describe",{workdir:e}),n=t.target;if("describe_ok"!==t.type||(null==n?void 0:n.executor_id)!==this.target.executor_id||(null==n?void 0:n.node_did)||(null==n?void 0:n.profile_id)!==this.target.profile_id||(null==n?void 0:n.store_id)!==this.target.store_id)throw new aE("Executor describe target changed","stale_target");return t}exec(e,t,n,r={},s=6e4){return this.request("exec",{...this.fresh(e),cmd:t,cwd:n,env_overrides:r,execution_timeout_ms:s})}read(e,t){return this.request("read",{...this.fresh(e),path:t,offset:0})}edit(e,t,n){return this.request("edit",{...this.fresh(e),path:t,edits:n})}async write(e,t,n,r="replace"){const s=this.fresh(e),i=(new TextEncoder).encode(e.op_id);if(0===i.length||i.length>128)throw new Error("Invalid operation ID");const o=Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",n))).map((e=>e.toString(16).padStart(2,"0"))).join(""),a=this.request("write",{...s,path:t,mode:r,content_length:n.length,content_hash:`sha256:${o}`});for(let c=0;c<n.length;c+=16384){const e=n.subarray(c,c+16384),t=new Uint8Array(16+i.length+e.length),r=new DataView(t.buffer);t[0]=2,r.setUint32(1,t.length-5),t[5]=4,r.setBigUint64(6,BigInt(c)),r.setUint16(14,i.length),t.set(i,16),t.set(e,16+i.length),this.socket.send(t)}return this.socket.send(cE({type:"upload_end",request_id:"end"+ ++this.sequence,op_id:e.op_id})),a}query(e,t,n=0,r=0){return this.operation(e),this.request("query",{store_id:e.store_id,op_id:e.op_id,channel:t,offset:n,max_bytes:262144,wait_ms:r})}cancel(e){return this.operation(e),this.request("cancel",{store_id:e.store_id,op_id:e.op_id})}}exports.ACCESS_DENIED_ERROR_CODE=Wn,exports.AGENT_DELEGATE_TASK_SCHEMA_ID="agent.delegate/v1",exports.AICC_AI_METHODS=Yr,exports.AICC_COMPUTE_TASK_SCHEMA_ID="aicc.compute/v1",exports.AICC_CORE_METHODS=Zr,exports.AICC_EXECUTION_MODES=ns,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=Xr,exports.AICC_METHODS=ts,exports.AICC_POLICY_REFUSAL_CODES=rs,exports.AICC_QUOTA_METHODS=es,exports.AICC_SERVICE_SERVICE_NAME="aicc",exports.AICC_SERVICE_SERVICE_PORT=4040,exports.AICC_SERVICE_UNIQUE_ID="aicc",exports.AIWORKSPACE_SERVICE_NAME=er,exports.ANONYMOUS_IDENTITY=$n,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.AiWorkspaceClient=nr,exports.AiccClient=hs,exports.AiwsFailure=tr,exports.BNS_DNS_TXT_DEFAULT_TTL=600,exports.BNS_DNS_TXT_DOC_TYPE=r_,exports.BNS_EVM_DEFAULT_GAS_LIMIT=Xb,exports.BNS_EVM_DEFAULT_MAX_FEE_PER_GAS=e_,exports.BNS_EVM_DEFAULT_MAX_PRIORITY_FEE_PER_GAS=t_,exports.BNS_MAX_INLINE_DOCUMENT_BYTES=n_,exports.BNS_PUBLISH_DOCUMENT_ABI=i_,exports.BS_SERVICE_TASK_MANAGER="task-manager",exports.BS_SERVICE_VERIFY_HUB="verify-hub",exports.BnsEvmTxBuilder=f_,exports.BnsEvmTxError=l_,exports.BnsTxExecutor=class{constructor(e={}){this.localExecutionTail=Promise.resolve(),this.options=e,this.evmTxBuilder=e.bnsClient&&e.evmConfig?new f_(e.bnsClient,e.evmConfig,e.evmProvider):null}async resolveRoute(){const e=this.getRuntimeType(),t=m_(e)?await this.getLocalPrivateKey():null;return this.resolveRouteFor(e,t)}async resolveRouteFor(e,t){if(m_(e)&&this.options.evmConfig&&t)return"local";if(e===Ni.AppRuntime){const e=await this.getCurrentWalletUser();if(e&&!y_(e))return"wallet"}return"sn-proxy"}async execute(e){const t=this.getRuntimeType(),n=m_(t)?await this.getLocalPrivateKey():null,r=await this.resolveRouteFor(t,n);switch(r){case"local":return this.executeLocally(e,t,n);case"wallet":throw new p_("WALLET_EXECUTION_NOT_IMPLEMENTED",r,`BNS wallet execution is not implemented for operation ${e.type}`);case"sn-proxy":return this.executeWithSn(e)}}publishDnsTxt(e){return this.execute({type:"publish_dns_txt",request:e})}publishDocument(e){return this.execute({type:"publish_document",request:e})}getRuntimeType(){return(this.options.getRuntimeType??Ro)()}getCurrentWalletUser(){return Promise.resolve((this.options.getCurrentWalletUser??bo)())}async getLocalPrivateKey(){const e=this.options.localPrivateKey;return g_("function"==typeof e?await e():e)}async executeWithSn(e){const t=this.options.snClient;if(!t)throw new p_("SN_CLIENT_UNAVAILABLE","sn-proxy",`SN client is required for BNS operation ${e.type}`);const n="publish_dns_txt"===e.type?await t.publishDnsTxt(e.request):await t.publishDocument(e.request);return{route:"sn-proxy",operation:e.type,response:n}}async executeLocally(e,t,n){const r=this.options.bnsClient;if(!r)throw new p_("BNS_CLIENT_UNAVAILABLE","local",`BNS client is required for local operation ${e.type}`);const s=this.evmTxBuilder;if(!n||!s)throw new p_("LOCAL_SIGNING_UNAVAILABLE","local",`Local signing configuration is unavailable for operation ${e.type}`);return this.enqueueLocalExecution((async()=>{try{const t=await s.buildAndSign(e,n),i=await r.submitRawTx(t);return{route:"local",operation:e.type,response:i}}catch(t){throw s.resetNonce(),t}}))}enqueueLocalExecution(e){const t=this.localExecutionTail.then(e,e);return this.localExecutionTail=t.then((()=>{}),(()=>{})),t}},exports.BnsTxExecutorError=p_,exports.BuckyOSSDK=Oo,exports.CONTACT_CHANGED_EVENT_BOX="CONTACTS",exports.CONTACT_TAG_HOMESTATION_FOLLOWING=Fs,exports.CONTACT_TAG_ZONE_AGENT=Ms,exports.CONTACT_TAG_ZONE_USER=Ls,exports.DEFAULT_CHILD_CONTROL_POLICY={follow_pause:!0,follow_resume:!0,follow_cancel:!0},exports.DEFAULT_JUMP_BASE_URL=Yn,exports.DENY_REASONS=qn,exports.DOWNLOAD_TASK_SCHEMA_ID="download/v1",exports.EXTERNAL_PRINCIPAL_CLAIM=Di,exports.ExecutorClient=class{constructor(e,t=null,n={}){this.rpc=new Gn(e,t,null,n)}syncSessionToken(e){this.rpc.setSessionToken(e)}createDevice(e){return this.rpc.call("executor.device.create",e)}listDevices(){return this.rpc.call("executor.device.list",{})}issueAccess(e,t){return this.rpc.call("executor.device.issue",{executor_id:e,expires_at_ms:t})}revokeAccess(e){return this.rpc.call("executor.device.revoke",{executor_id:e})}deleteDevice(e){return this.rpc.call("executor.device.delete",{executor_id:e})}listOnline(){return this.rpc.call("executor.online.list",{})}async*watchOnline(e,t=5e3){if(t<250)throw new Error("Watch interval must be at least 250 ms");let n="";for(;!(null==e?void 0:e.aborted);){const{executors:r}=await this.listOnline(),s=JSON.stringify(r);s!==n&&(n=s,yield r),await new Promise((n=>{const r=()=>{clearTimeout(s),null==e||e.removeEventListener("abort",r),n()},s=setTimeout(r,t);null==e||e.addEventListener("abort",r,{once:!0}),(null==e?void 0:e.aborted)&&r()}))}}openRoute(e){return this.rpc.call("executor.stream.open",{executor_id:e.executor_id,generation:e.generation,profile_id:e.profile_id})}async connect(e,t,n,r){const s=await this.openRoute(e);return lE.connect(s,e,t,n,r)}},exports.ExecutorCommandStream=lE,exports.ExecutorStreamError=aE,exports.FRIEND_INTENT="buckyos.friend",exports.HUMAN_APPROVAL_SCHEMA_ID="human.approval/v1",exports.HUMAN_INPUT_TASK_SCHEMA_ID="human.input/v1",exports.JUMP_ACTION_PATHS=Zn,exports.KEventClient=mo,exports.KEventReader=uo,exports.MsgCenterClient=ii,exports.MsgQueueClient=Us,exports.NOTIFY_ACTION_ANSWER=Qs,exports.NOTIFY_ACTION_DISMISS=Js,exports.NOTIFY_CHOICE_CONTROL_ID=Ks,exports.NOTIFY_DATA_VERSION=1,exports.NOTIFY_DELIVERED_INTENT="buckyos.notify.delivered",exports.NOTIFY_INTENT=Ws,exports.NOTIFY_LINK_PATH=Ys,exports.NOTIFY_SESSION_PREFIX=zs,exports.NOTIFY_TEXT_CONTROL_ID=$s,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.RPCError=Fn,exports.RepoClient=wi,exports.RuntimeType=Ni,exports.SCHEDULER_DISPATCH_THUNK_TASK_SCHEMA_ID="scheduler.dispatch_thunk/v1",exports.StorageDomain=Or,exports.SystemConfigClient=Jr,exports.TASK_ERR_ALREADY_COMPLETED=fr,exports.TASK_ERR_CONTROL_ALREADY_PENDING=dr,exports.TASK_ERR_CONTROL_NOT_AVAILABLE=hr,exports.TASK_ERR_IDEMPOTENCY_CONFLICT=mr,exports.TASK_ERR_INPUT_SCHEMA_MISMATCH=pr,exports.TASK_ERR_INVALID_PHASE=ur,exports.TASK_ERR_NOT_FOUND=or,exports.TASK_ERR_PERMISSION_DENIED=ar,exports.TASK_ERR_RESULT_SCHEMA_MISMATCH=gr,exports.TASK_ERR_REVISION_CONFLICT=cr,exports.TASK_ERR_SCHEMA_NOT_FOUND=yr,exports.TASK_ERR_STALE_RUNNER_EPOCH=lr,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=wr,exports.TASK_POLICY_PRESET_COLLABORATIVE_TREE_V1="collaborative-tree/v1",exports.TOOL_EXEC_BASH_TASK_SCHEMA_ID="tool.exec_bash/v1",exports.TaskAction=Rr,exports.TaskControlAction=Tr,exports.TaskDataScope=Cr,exports.TaskEventType=xr,exports.TaskExecutorKind=Ar,exports.TaskGrantScope=Ir,exports.TaskManagerClient=Br,exports.TaskOutcome=Sr,exports.TaskPhase=vr,exports.TaskWaitReasonKind=kr,exports.USER_GROUP_REF_PREFIX=Vs,exports.USER_TYPE_GROUP_REF_PREFIX=Hs,exports.VerifyHubClient=ir,exports.WEB3_BRIDGE_HOST="web3.buckyos.ai",exports.WELL_KNOWN_CONTACT_TAGS=js,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=$r,exports.WorkflowDefinitionStatus=jr,exports.WorkflowHumanActionKind=Vr,exports.WorkflowJoinMode=Mr,exports.WorkflowNodeRunState=Hr,exports.WorkflowOutputMode=Lr,exports.WorkflowRetryFallback=Fr,exports.WorkflowRunStatus=Gr,exports.WorkflowScheduledTaskFireStatus=zr,exports.WorkflowScheduledTaskMisfirePolicy=Wr,exports.WorkflowScheduledTaskStatus=qr,exports.WorkflowStepType=Ur,exports.ZONE_USER_TYPES=Pi,exports.accessDenialOf=function(e){return e instanceof Fn&&e.code===Wn?Kn(e.data):null},exports.aiccMessageFirstText=function(e){var t;return null==(t=e.content.find((e=>"text"===e.type)))?void 0:t.text},exports.aiccMessageTextContent=function(e){return e.content.filter((e=>"text"===e.type)).map((e=>e.text)).join("\n")},exports.aiccRefusalOf=function(e){if(!(e instanceof Fn&&rs.includes(e.code)))return;const t=e.data;return{code:e.code,message:(null==t?void 0:t.message)??e.message,retriable:null==t?void 0:t.retriable,details:null==t?void 0:t.details}},exports.aiccTextMessage=function(e,t){return{role:e,content:[{type:"text",text:t}]}},exports.answerNotify=async function(e,t,n,r,s){const i=await e.notifyGet(n);if("notice"===i.kind)return r.dismiss?e.notifyDismiss(n):e.notifyAck(n);if(!i.task_id)throw new Fn(`notification ${n} has no task`);if(Zs(i.status))return i;const o=ci(r,i.prompt);if(o)throw new Fn(o);return await ui(t,i.task_id,r,s??i.to_user),e.notifyGet(n)},exports.appDidFromId=function(e){return Mn.DID.fromStr(vi(e)).toString()},exports.appIdFromDid=Ai,exports.baselineTaskControlProfile=function(e){return{pause:{kind:"Unavailable"},resume:{kind:"Unavailable"},cancel:{kind:"Interrupt"},updated_at:e}},exports.bns_client=Ma,exports.buildJumpUrl=function(e,t,n=Yn){const r=Zn[e];if(!r)throw new Error(`unregistered jump action: ${e}`);const s=new URL(n||Yn);if("https:"!==s.protocol&&"localhost"!==s.hostname)throw new Error("jump base must be https");const i=new URLSearchParams(t).toString();return`${s.origin}${r}${i?`#${i}`:""}`},exports.commitNotifyAnswer=ui,exports.contactTagApp=Gs,exports.contactTagKind=function(e){return e===Ls||e===Ms||qs(e)?"system":Gs(e)?"app":"user"},exports.createAppInstanceId=ki,exports.createSDKModule=function(e){const t=new Oo(e),n={initBuckyOS:t.initBuckyOS.bind(t),getBuckyOSConfig:t.getBuckyOSConfig.bind(t),getRuntimeType:t.getRuntimeType.bind(t),getAppId:t.getAppId.bind(t),getAppDid:t.getAppDid.bind(t),getAppInstanceId:t.getAppInstanceId.bind(t),getAppDataDir:t.getAppDataDir.bind(t),getKEventClient:t.getKEventClient.bind(t),createEventReader:t.createEventReader.bind(t),create_event_reader:t.create_event_reader.bind(t),subscribeKEvent:t.subscribeKEvent.bind(t),attachEvent:t.attachEvent.bind(t),removeEvent:t.removeEvent.bind(t),getAccountInfo:t.getAccountInfo.bind(t),loginByPassword:t.loginByPassword.bind(t),loginByBrowserSSO:t.loginByBrowserSSO.bind(t),loginByRuntimeSession:t.loginByRuntimeSession.bind(t),login:t.login.bind(t),logout:t.logout.bind(t),getAppSetting:t.getAppSetting.bind(t),setAppSetting:t.setAppSetting.bind(t),getCurrentWalletUser:t.getCurrentWalletUser.bind(t),getCurrentIdentity:t.getCurrentIdentity.bind(t),resolve_did:t.resolve_did.bind(t),walletSignWithActiveDid:t.walletSignWithActiveDid.bind(t),openExternalUrl:t.openExternalUrl.bind(t),getZoneHostName:t.getZoneHostName.bind(t),getZoneServiceURL:t.getZoneServiceURL.bind(t),getServiceRpcClient:t.getServiceRpcClient.bind(t),getVerifyHubClient:t.getVerifyHubClient.bind(t),getSystemConfigClient:t.getSystemConfigClient.bind(t),getTaskManagerClient:t.getTaskManagerClient.bind(t),getWorkflowClient:t.getWorkflowClient.bind(t),getAiccClient:t.getAiccClient.bind(t),getAiWorkspaceClient:t.getAiWorkspaceClient.bind(t),getMsgQueueClient:t.getMsgQueueClient.bind(t),getMsgCenterClient:t.getMsgCenterClient.bind(t),getRepoClient:t.getRepoClient.bind(t)};return{...n,buckyos:{kRPCClient:Gn,AuthClient:Vn,...n,hashPassword:Mn.hashPassword}}},exports.decisionRequirements=ms,exports.decodeBnsPublishDocumentCalldata=function(e){return o_.decodeFunctionData("publishDocument",e)},exports.encodeExecutorControl=cE,exports.getActiveRuntimeType=Ro,exports.getActiveSessionToken=Co,exports.getActiveZoneGatewayOrigin=Io,exports.getCurrentWalletUserFromHost=bo,exports.identityAllows=function(e,t){return"anonymous"!==e.kind&&(!e.restricted||(e.scopes??[]).includes(t))},exports.identityKey=Jn,exports.inputPrompt=function(e,t,n,r=!1){const s=[],i=n.length>0;return i&&s.push({kind:"choice",id:Ks,options:n,multiple:!1,required:!r}),i&&!r||s.push({kind:"text_input",id:$s,multiline:!0,required:!i}),t?{title:e,message:t,controls:s}:{title:e,controls:s}},exports.isAiccAiMethod=function(e){return ss.has(e)},exports.isExternalPrincipal=function(e){return"user"===(null==e?void 0:e.principal_kind)&&!0===e[Di]},exports.isNotifyClosed=Zs,exports.isTerminalTaskPhase=Er,exports.isUserGroupRefTag=qs,exports.mailboxAddress=function(e,t){if(!/^did:[^:]+:.+$/.test(e)||/[\s\x00-\x1f\x7f-\x9f/\\?#*|]/.test(e))throw new Fn("mailbox owner must be a bare DID");if(void 0===t)return e;if(!t||t.trim()!==t||[...t].length>200||"."===t||".."===t||/[\x00-\x1f\x7f-\x9f]/.test(t))throw new Fn("invalid mailbox session_id");return`${e}/${encodeURIComponent(t).replace(/[!'()*]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)).replace(/%3A/g,":").replace(/%40/g,"@")}`},exports.mailboxResource=function(e,t){const n=encodeURIComponent(e).replace(/[!'()*.]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)).replace(/%3A/g,":").replace(/%40/g,"@").replace(/%2F/g,"/");return`obj://msg-center/${t.toLowerCase()}/${n}`},exports.msgMachineData=li,exports.ndm_client=hv,exports.ndm_proxy=oE,exports.normalizeZoneHostname=Xn,exports.notifyAnswerToTaskResult=ai,exports.notifyCategoryFromSessionId=function(e){if(!e.startsWith(zs))return null;const t=e.slice(10);return"todo"===t||"agent"===t||"app"===t?t:null},exports.notifyCategorySessionId=function(e){return`${zs}${e}`},exports.notifyMessageData=function(e){const t=li(e,Ws);return t&&"string"==typeof t.notify_id?t:null},exports.notifyUrl=function(e,t){const n=`${Ys}?notify=${t}`,r=null==e?void 0:e.trim();return r?`https://${r}${n}`:n},exports.parseAccessDenial=Kn,exports.parseAppId=vi,exports.parseAppInstanceId=Si,exports.parseCurrentIdentity=Qn,exports.parseSessionTokenClaims=Hi,exports.parseVideoPrompt=Es,exports.parseZoneUserType=function(e){const t="string"==typeof e?e.trim().toLowerCase():"";return Pi.includes(t)?t:null},exports.promptOptions=oi,exports.resolveDidFromHost=_o,exports.sn_client=SA,exports.taskMgrErrorCode=_r,exports.taskMgrTaskEventPath=br,exports.taskMgrTreeEventPath=function(e){return`/task_mgr/tree/${e}`},exports.validateAiccMessage=is,exports.validateDecisionAnswers=ws,exports.validateDecisionRequest=ys,exports.validateNotifyAnswer=ci,exports.validateVideoEdit=Os,exports.validateVideoGeneration=Cs,exports.validateVideoOutput=Is,exports.videoGenerationRequirement=xs,exports.waitNotify=async function(e,t,n,r={}){let s=await e.notifyGet(t),i=null,o=!1;r.kevent&&s.task_id&&!Zs(s.status)&&r.kevent.createEventReader([br(s.task_id)]).then((e=>{o?e.close().catch((()=>{})):i=e}),(()=>{}));try{let r=500;for(;;){if(Zs(s.status))return s;const o=Date.now();if(o>=n)return s;await hi(Math.min(r,n-o),i),r=Math.min(2*r,3e4),s=await e.notifyGet(t)}}finally{o=!0;const e=i;e&&await e.close().catch((()=>{}))}},exports.walletUserHasSnAccount=y_,exports.zoneActionUrl=function(e,t){const n=Xn(e),r=Zn[t];return n&&r?`https://${n}${r}`:null};
|
|
13
|
-
//# sourceMappingURL=executor_client-
|
|
11
|
+
const Ad=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),vd=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Ed=BigInt(1),kd=BigInt(2),Sd=(e,t)=>(e+t/kd)/t;const Td=function(e,t,n=!1,r={}){if(e<=$h)throw new Error(`Expected Field ORDER > 0, got ${e}`);const{nBitLength:s,nByteLength:i}=od(e,t);if(i>2048)throw new Error("Field lengths over 2048 bytes are not supported");const o=sd(e),a=Object.freeze({ORDER:e,BITS:s,BYTES:i,MASK:jh(s),ZERO:$h,ONE:Kh,create:t=>ed(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("Invalid field element: expected bigint, got "+typeof t);return $h<=t&&t<e},is0:e=>e===$h,isOdd:e=>(e&Kh)===Kh,neg:t=>ed(-t,e),eql:(e,t)=>e===t,sqr:t=>ed(t*t,e),add:(t,n)=>ed(t+n,e),sub:(t,n)=>ed(t-n,e),mul:(t,n)=>ed(t*n,e),pow:(e,t)=>function(e,t,n){if(n<$h)throw new Error("Expected power > 0");if(n===$h)return e.ONE;if(n===Kh)return t;let r=e.ONE,s=t;for(;n>$h;)n&Kh&&(r=e.mul(r,s)),s=e.sqr(s),n>>=Kh;return r}(a,e,t),div:(t,n)=>ed(t*rd(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>rd(t,e),sqrt:r.sqrt||(e=>o(a,e)),invertBatch:e=>function(e,t){const n=new Array(t.length),r=t.reduce(((t,r,s)=>e.is0(r)?t:(n[s]=t,e.mul(t,r))),e.ONE),s=e.inv(r);return t.reduceRight(((t,r,s)=>e.is0(r)?t:(n[s]=e.mul(t,n[s]),e.mul(t,r))),s),n}(a,e),cmov:(e,t,n)=>n?t:e,toBytes:e=>n?Lh(e,i):Uh(e,i),fromBytes:e=>{if(e.length!==i)throw new Error(`Fp.fromBytes: expected ${i}, got ${e.length}`);return n?Bh(e):Dh(e)}});return Object.freeze(a)}(Ad,void 0,void 0,{sqrt:function(e){const t=Ad,n=BigInt(3),r=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,h=nd(u,n,t)*u%t,d=nd(h,n,t)*u%t,f=nd(d,kd,t)*l%t,p=nd(f,s,t)*f%t,g=nd(p,i,t)*p%t,m=nd(g,a,t)*g%t,y=nd(m,c,t)*m%t,w=nd(y,a,t)*g%t,b=nd(w,n,t)*u%t,_=nd(b,o,t)*p%t,A=nd(_,r,t)*l%t,v=nd(A,kd,t);if(!Td.eql(Td.sqr(v),e))throw new Error("Cannot find square root");return v}}),Rd=function(e,t){const n=t=>bd({...e,..._d(t)});return Object.freeze({...n(t),create:n})}({a:BigInt(0),b:BigInt(7),Fp:Td,n:vd,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=vd,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-Ed*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=n,o=BigInt("0x100000000000000000000000000000000"),a=Sd(i*e,t),c=Sd(-r*e,t);let l=ed(e-a*n-c*s,t),u=ed(-a*r-c*i,t);const h=l>o,d=u>o;if(h&&(l=t-l),d&&(u=t-u),l>o||u>o)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}}},Ql);BigInt(0),Rd.ProjectivePoint;const Id="0x0000000000000000000000000000000000000000",Cd="0x0000000000000000000000000000000000000000000000000000000000000000",Od=BigInt(0),xd=BigInt(1),Nd=BigInt(2),Pd=BigInt(27),Dd=BigInt(28),Bd=BigInt(35),Ud=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Ld=Ud/Nd,Md=Symbol.for("nodejs.util.inspect.custom"),Fd={};function jd(e){return uc(Ec(e),32)}j=new WeakMap,G=new WeakMap,H=new WeakMap,V=new WeakMap;let Gd=class e{constructor(e,t,n,r){Dn(this,j,void 0),Dn(this,G,void 0),Dn(this,H,void 0),Dn(this,V,void 0),Za(e,Fd,"Signature"),Bn(this,j,t),Bn(this,G,n),Bn(this,H,r),Bn(this,V,null)}get r(){return Pn(this,j)}set r(e){Ka(32===ac(e),"invalid r","value",e),Bn(this,j,ic(e))}get s(){return Ka(parseInt(Pn(this,G).substring(0,3))<8,"non-canonical s; use ._s","s",Pn(this,G)),Pn(this,G)}set s(e){Ka(32===ac(e),"invalid s","value",e),Bn(this,G,ic(e))}get _s(){return Pn(this,G)}isValid(){return BigInt(Pn(this,G))<=Ld}get v(){return Pn(this,H)}set v(e){const t=Ac(e,"value");Ka(27===t||28===t,"invalid v","v",e),Bn(this,H,t)}get networkV(){return Pn(this,V)}get legacyChainId(){const t=this.networkV;return null==t?null:e.getChainId(t)}get yParity(){return 27===this.v?0:1}get yParityAndS(){const e=ec(this.s);return this.yParity&&(e[0]|=128),ic(e)}get compactSerialized(){return oc([this.r,this.yParityAndS])}get serialized(){return oc([this.r,this.s,this.yParity?"0x1c":"0x1b"])}getCanonical(){if(this.isValid())return this;const t=Ud-BigInt(this._s),n=55-this.v,r=new e(Fd,this.r,jd(t),n);return this.networkV&&Bn(r,V,this.networkV),r}clone(){const t=new e(Fd,this.r,this._s,this.v);return this.networkV&&Bn(t,V,this.networkV),t}toJSON(){const e=this.networkV;return{_type:"signature",networkV:null!=e?e.toString():null,r:this.r,s:this._s,v:this.v}}[Md](){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(e){const t=yc(e,"v");return t==Pd||t==Dd?Od:(Ka(t>=Bd,"invalid EIP-155 v","v",e),(t-Bd)/Nd)}static getChainIdV(e,t){return yc(e)*Nd+BigInt(35+t-27)}static getNormalizedV(e){const t=yc(e);return t===Od||t===Pd?27:t===xd||t===Dd?28:(Ka(t>=Bd,"invalid v","v",e),t&xd?27:28)}static from(t){function n(e,n){Ka(e,n,"signature",t)}if(null==t)return new e(Fd,Cd,Cd,27);if("string"==typeof t){const r=ec(t,"signature");if(64===r.length){const t=ic(r.slice(0,32)),n=r.slice(32,64),s=128&n[0]?28:27;return n[0]&=127,new e(Fd,t,ic(n),s)}if(65===r.length){const t=ic(r.slice(0,32)),n=ic(r.slice(32,64)),s=e.getNormalizedV(r[64]);return new e(Fd,t,n,s)}n(!1,"invalid raw signature length")}if(t instanceof e)return t.clone();const r=t.r;n(null!=r,"missing r");const s=jd(r),i=function(e,t){if(null!=e)return jd(e);if(null!=t){n(nc(t,32),"invalid yParityAndS");const e=ec(t);return e[0]&=127,ic(e)}n(!1,"missing s")}(t.s,t.yParityAndS),{networkV:o,v:a}=function(t,r,s){if(null!=t){const n=yc(t);return{networkV:n>=Bd?n:void 0,v:e.getNormalizedV(n)}}if(null!=r)return n(nc(r,32),"invalid yParityAndS"),{v:128&ec(r)[0]?28:27};if(null!=s){switch(Ac(s,"sig.yParity")){case 0:return{v:27};case 1:return{v:28}}n(!1,"invalid yParity")}n(!1,"missing v")}(t.v,t.yParityAndS,t.yParity),c=new e(Fd,s,i,a);return o&&Bn(c,V,o),n(null==t.yParity||Ac(t.yParity,"sig.yParity")===c.yParity,"yParity mismatch"),n(null==t.yParityAndS||t.yParityAndS===c.yParityAndS,"yParityAndS mismatch"),c}};q=new WeakMap;let Hd=class e{constructor(e){Dn(this,q,void 0),Ka(32===ac(e),"invalid private key","privateKey","[REDACTED]"),Bn(this,q,ic(e))}get privateKey(){return Pn(this,q)}get publicKey(){return e.computePublicKey(Pn(this,q))}get compressedPublicKey(){return e.computePublicKey(Pn(this,q),!0)}sign(e){Ka(32===ac(e),"invalid digest length","digest",e);const t=Rd.sign(tc(e),tc(Pn(this,q)),{lowS:!0});return Gd.from({r:vc(t.r,32),s:vc(t.s,32),v:t.recovery?28:27})}computeSharedSecret(t){const n=e.computePublicKey(t);return ic(Rd.getSharedSecret(tc(Pn(this,q)),ec(n),!1))}static computePublicKey(e,t){let n=ec(e,"key");if(32===n.length){return ic(Rd.getPublicKey(n,!!t))}if(64===n.length){const e=new Uint8Array(65);e[0]=4,e.set(n,1),n=e}return ic(Rd.ProjectivePoint.fromHex(n).toRawBytes(t))}static recoverPublicKey(e,t){Ka(32===ac(e),"invalid digest length","digest",e);const n=Gd.from(t);let r=Rd.Signature.fromCompact(tc(oc([n.r,n.s])));r=r.addRecoveryBit(n.yParity);const s=r.recoverPublicKey(tc(e));return Ka(null!=s,"invalid signature for digest","signature",t),"0x"+s.toHex(!1)}static addPoints(t,n,r){const s=Rd.ProjectivePoint.fromHex(e.computePublicKey(t).substring(2)),i=Rd.ProjectivePoint.fromHex(e.computePublicKey(n).substring(2));return"0x"+s.add(i).toHex(!!r)}};const Vd=BigInt(0),qd=BigInt(36);function Wd(e){const t=(e=e.toLowerCase()).substring(2).split(""),n=new Uint8Array(40);for(let s=0;s<40;s++)n[s]=t[s].charCodeAt(0);const r=ec(Bu(n));for(let s=0;s<40;s+=2)r[s>>1]>>4>=8&&(t[s]=t[s].toUpperCase()),(15&r[s>>1])>=8&&(t[s+1]=t[s+1].toUpperCase());return"0x"+t.join("")}const zd={};for(let uE=0;uE<10;uE++)zd[String(uE)]=String(uE);for(let uE=0;uE<26;uE++)zd[String.fromCharCode(65+uE)]=String(10+uE);const $d=function(){const e={};for(let t=0;t<36;t++){e["0123456789abcdefghijklmnopqrstuvwxyz"[t]]=BigInt(t)}return e}();function Kd(e){if(Ka("string"==typeof e,"invalid address","address",e),e.match(/^(0x)?[0-9a-fA-F]{40}$/)){e.startsWith("0x")||(e="0x"+e);const t=Wd(e);return Ka(!e.match(/([A-F].*[a-f])|([a-f].*[A-F])/)||t===e,"bad address checksum","address",e),t}if(e.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){Ka(e.substring(2,4)===function(e){let t=(e=(e=e.toUpperCase()).substring(4)+e.substring(0,2)+"00").split("").map((e=>zd[e])).join("");for(;t.length>=15;){let e=t.substring(0,15);t=parseInt(e,10)%97+t.substring(e.length)}let n=String(98-parseInt(t,10)%97);for(;n.length<2;)n="0"+n;return n}(e),"bad icap checksum","address",e);let t=function(e){e=e.toLowerCase();let t=Vd;for(let n=0;n<e.length;n++)t=t*qd+$d[e[n]];return t}(e.substring(4)).toString(16);for(;t.length<40;)t="0"+t;return Wd("0x"+t)}Ka(!1,"invalid address","address",e)}function Qd(e){return e&&"function"==typeof e.getAddress}async function Jd(e,t){const n=await t;return null!=n&&"0x0000000000000000000000000000000000000000"!==n||($a("string"!=typeof e,"unconfigured name","UNCONFIGURED_NAME",{value:e}),Ka(!1,"invalid AddressLike value; did not resolve to a value address","target",e)),Kd(n)}function Yd(e,t){return"string"==typeof e?e.match(/^0x[0-9a-f]{40}$/i)?Kd(e):($a(null!=t,"ENS resolution requires a provider","UNSUPPORTED_OPERATION",{operation:"resolveName"}),Jd(e,t.resolveName(e))):Qd(e)?Jd(e,e.getAddress()):e&&"function"==typeof e.then?Jd(e,e):void Ka(!1,"unsupported addressable value","target",e)}const Zd={};function Xd(e,t){let n=!1;return t<0&&(n=!0,t*=-1),new nf(Zd,`${n?"":"u"}int${t}`,e,{signed:n,width:t})}function ef(e,t){return new nf(Zd,`bytes${t||""}`,e,{size:t})}const tf=Symbol.for("_ethers_typed");W=new WeakMap;let nf=class e{constructor(e,t,n,r){xn(this,"type"),xn(this,"value"),Dn(this,W,void 0),xn(this,"_typedSymbol"),null==r&&(r=null),Za(Zd,e,"Typed"),Ha(this,{_typedSymbol:tf,type:t,value:n}),Bn(this,W,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((e=>e.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,W)}get arrayLength(){if("array"!==this.type)throw TypeError("not an array");return!0===Pn(this,W)?-1:!1===Pn(this,W)?this.value.length:null}static from(t,n){return new e(Zd,t,n)}static uint8(e){return Xd(e,8)}static uint16(e){return Xd(e,16)}static uint24(e){return Xd(e,24)}static uint32(e){return Xd(e,32)}static uint40(e){return Xd(e,40)}static uint48(e){return Xd(e,48)}static uint56(e){return Xd(e,56)}static uint64(e){return Xd(e,64)}static uint72(e){return Xd(e,72)}static uint80(e){return Xd(e,80)}static uint88(e){return Xd(e,88)}static uint96(e){return Xd(e,96)}static uint104(e){return Xd(e,104)}static uint112(e){return Xd(e,112)}static uint120(e){return Xd(e,120)}static uint128(e){return Xd(e,128)}static uint136(e){return Xd(e,136)}static uint144(e){return Xd(e,144)}static uint152(e){return Xd(e,152)}static uint160(e){return Xd(e,160)}static uint168(e){return Xd(e,168)}static uint176(e){return Xd(e,176)}static uint184(e){return Xd(e,184)}static uint192(e){return Xd(e,192)}static uint200(e){return Xd(e,200)}static uint208(e){return Xd(e,208)}static uint216(e){return Xd(e,216)}static uint224(e){return Xd(e,224)}static uint232(e){return Xd(e,232)}static uint240(e){return Xd(e,240)}static uint248(e){return Xd(e,248)}static uint256(e){return Xd(e,256)}static uint(e){return Xd(e,256)}static int8(e){return Xd(e,-8)}static int16(e){return Xd(e,-16)}static int24(e){return Xd(e,-24)}static int32(e){return Xd(e,-32)}static int40(e){return Xd(e,-40)}static int48(e){return Xd(e,-48)}static int56(e){return Xd(e,-56)}static int64(e){return Xd(e,-64)}static int72(e){return Xd(e,-72)}static int80(e){return Xd(e,-80)}static int88(e){return Xd(e,-88)}static int96(e){return Xd(e,-96)}static int104(e){return Xd(e,-104)}static int112(e){return Xd(e,-112)}static int120(e){return Xd(e,-120)}static int128(e){return Xd(e,-128)}static int136(e){return Xd(e,-136)}static int144(e){return Xd(e,-144)}static int152(e){return Xd(e,-152)}static int160(e){return Xd(e,-160)}static int168(e){return Xd(e,-168)}static int176(e){return Xd(e,-176)}static int184(e){return Xd(e,-184)}static int192(e){return Xd(e,-192)}static int200(e){return Xd(e,-200)}static int208(e){return Xd(e,-208)}static int216(e){return Xd(e,-216)}static int224(e){return Xd(e,-224)}static int232(e){return Xd(e,-232)}static int240(e){return Xd(e,-240)}static int248(e){return Xd(e,-248)}static int256(e){return Xd(e,-256)}static int(e){return Xd(e,-256)}static bytes1(e){return ef(e,1)}static bytes2(e){return ef(e,2)}static bytes3(e){return ef(e,3)}static bytes4(e){return ef(e,4)}static bytes5(e){return ef(e,5)}static bytes6(e){return ef(e,6)}static bytes7(e){return ef(e,7)}static bytes8(e){return ef(e,8)}static bytes9(e){return ef(e,9)}static bytes10(e){return ef(e,10)}static bytes11(e){return ef(e,11)}static bytes12(e){return ef(e,12)}static bytes13(e){return ef(e,13)}static bytes14(e){return ef(e,14)}static bytes15(e){return ef(e,15)}static bytes16(e){return ef(e,16)}static bytes17(e){return ef(e,17)}static bytes18(e){return ef(e,18)}static bytes19(e){return ef(e,19)}static bytes20(e){return ef(e,20)}static bytes21(e){return ef(e,21)}static bytes22(e){return ef(e,22)}static bytes23(e){return ef(e,23)}static bytes24(e){return ef(e,24)}static bytes25(e){return ef(e,25)}static bytes26(e){return ef(e,26)}static bytes27(e){return ef(e,27)}static bytes28(e){return ef(e,28)}static bytes29(e){return ef(e,29)}static bytes30(e){return ef(e,30)}static bytes31(e){return ef(e,31)}static bytes32(e){return ef(e,32)}static address(t){return new e(Zd,"address",t)}static bool(t){return new e(Zd,"bool",!!t)}static bytes(t){return new e(Zd,"bytes",t)}static string(t){return new e(Zd,"string",t)}static array(e,t){throw new Error("not implemented yet")}static tuple(e,t){throw new Error("not implemented yet")}static overrides(t){return new e(Zd,"overrides",Object.assign({},t))}static isTyped(e){return e&&"object"==typeof e&&"_typedSymbol"in e&&e._typedSymbol===tf}static dereference(t,n){if(e.isTyped(t)){if(t.type!==n)throw new Error(`invalid type: expecetd ${n}, got ${t.type}`);return t.value}return t}};class rf extends bl{constructor(e){super("address","address",e,!1)}defaultValue(){return"0x0000000000000000000000000000000000000000"}encode(e,t){let n=nf.dereference(t,"string");try{n=Kd(n)}catch(r){return this._throwError(r.message,t)}return e.writeValue(n)}decode(e){return Kd(vc(e.readValue(),20))}}class sf extends bl{constructor(e){super(e.name,e.type,"_",e.dynamic),xn(this,"coder"),this.coder=e}defaultValue(){return this.coder.defaultValue()}encode(e,t){return this.coder.encode(e,t)}decode(e){return this.coder.decode(e)}}function of(e,t,n){let r=[];if(Array.isArray(n))r=n;else if(n&&"object"==typeof n){let e={};r=t.map((t=>{const r=t.localName;return $a(r,"cannot encode object for signature with missing names","INVALID_ARGUMENT",{argument:"values",info:{coder:t},value:n}),$a(!e[r],"cannot encode object for signature with duplicate names","INVALID_ARGUMENT",{argument:"values",info:{coder:t},value:n}),e[r]=!0,n[r]}))}else Ka(!1,"invalid tuple value","tuple",n);Ka(t.length===r.length,"types/value length mismatch","tuple",n);let s=new _l,i=new _l,o=[];t.forEach(((e,t)=>{let n=r[t];if(e.dynamic){let t=i.length;e.encode(i,n);let r=s.writeUpdatableValue();o.push((e=>{r(e+t)}))}else e.encode(s,n)})),o.forEach((e=>{e(s.length)}));let a=e.appendWriter(s);return a+=e.appendWriter(i),a}function af(e,t){let n=[],r=[],s=e.subReader(0);return t.forEach((t=>{let i=null;if(t.dynamic){let n=e.readIndex(),r=s.subReader(n);try{i=t.decode(r)}catch(o){if(qa(o,"BUFFER_OVERRUN"))throw o;i=o,i.baseType=t.name,i.name=t.localName,i.type=t.type}}else try{i=t.decode(e)}catch(o){if(qa(o,"BUFFER_OVERRUN"))throw o;i=o,i.baseType=t.name,i.name=t.localName,i.type=t.type}if(null==i)throw new Error("investigate");n.push(i),r.push(t.localName||null)})),yl.fromItems(n,r)}class cf extends bl{constructor(e,t,n){super("array",e.type+"["+(t>=0?t:"")+"]",n,-1===t||e.dynamic),xn(this,"coder"),xn(this,"length"),Ha(this,{coder:e,length:t})}defaultValue(){const e=this.coder.defaultValue(),t=[];for(let n=0;n<this.length;n++)t.push(e);return t}encode(e,t){const n=nf.dereference(t,"array");Array.isArray(n)||this._throwError("expected array value",n);let r=this.length;-1===r&&(r=n.length,e.writeValue(n.length)),Qa(n.length,r,"coder array"+(this.localName?" "+this.localName:""));let s=[];for(let i=0;i<n.length;i++)s.push(this.coder);return of(e,s,n)}decode(e){let t=this.length;-1===t&&(t=e.readIndex(),$a(t*cl<=e.dataLength,"insufficient data length","BUFFER_OVERRUN",{buffer:e.bytes,offset:t*cl,length:e.dataLength}));let n=[];for(let r=0;r<t;r++)n.push(new sf(this.coder));return af(e,n)}}class lf extends bl{constructor(e){super("bool","bool",e,!1)}defaultValue(){return!1}encode(e,t){const n=nf.dereference(t,"bool");return e.writeValue(n?1:0)}decode(e){return!!e.readValue()}}class uf extends bl{constructor(e,t){super(e,e,t,!0)}defaultValue(){return"0x"}encode(e,t){t=tc(t);let n=e.writeValue(t.length);return n+=e.writeBytes(t),n}decode(e){return e.readBytes(e.readIndex(),!0)}}class hf extends uf{constructor(e){super("bytes",e)}decode(e){return ic(super.decode(e))}}class df extends bl{constructor(e,t){let n="bytes"+String(e);super(n,n,t,!1),xn(this,"size"),Ha(this,{size:e},{size:"number"})}defaultValue(){return"0x0000000000000000000000000000000000000000000000000000000000000000".substring(0,2+2*this.size)}encode(e,t){let n=tc(nf.dereference(t,this.type));return n.length!==this.size&&this._throwError("incorrect data length",t),e.writeBytes(n)}decode(e){return ic(e.readBytes(this.size))}}const ff=new Uint8Array([]);class pf extends bl{constructor(e){super("null","",e,!1)}defaultValue(){return null}encode(e,t){return null!=t&&this._throwError("not null",t),e.writeBytes(ff)}decode(e){return e.readBytes(0),null}}const gf=BigInt(0),mf=BigInt(1),yf=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");class wf extends bl{constructor(e,t,n){const r=(t?"int":"uint")+8*e;super(r,r,n,!1),xn(this,"size"),xn(this,"signed"),Ha(this,{size:e,signed:t},{size:"number",signed:"boolean"})}defaultValue(){return 0}encode(e,t){let n=yc(nf.dereference(t,this.type)),r=mc(yf,256);if(this.signed){let e=mc(r,8*this.size-1);(n>e||n<-(e+mf))&&this._throwError("value out-of-bounds",t),n=gc(n,256)}else(n<gf||n>mc(r,8*this.size))&&this._throwError("value out-of-bounds",t);return e.writeValue(n)}decode(e){let t=mc(e.readValue(),8*this.size);return this.signed&&(t=function(e,t){const n=wc(e,"value"),r=BigInt(Ac(t,"width"));if($a(n>>r===dc,"overflow","NUMERIC_FAULT",{operation:"fromTwos",fault:"overflow",value:e}),n>>r-fc)return-((~n&(fc<<r)-fc)+fc);return n}(t,8*this.size)),t}}class bf extends uf{constructor(e){super("string",e)}defaultValue(){return""}encode(e,t){return super.encode(e,Dc(nf.dereference(t,"string")))}decode(e){return Bc(super.decode(e))}}class _f extends bl{constructor(e,t){let n=!1;const r=[];e.forEach((e=>{e.dynamic&&(n=!0),r.push(e.type)}));super("tuple","tuple("+r.join(",")+")",t,n),xn(this,"coders"),Ha(this,{coders:Object.freeze(e.slice())})}defaultValue(){const e=[];this.coders.forEach((t=>{e.push(t.defaultValue())}));const t=this.coders.reduce(((e,t)=>{const n=t.localName;return n&&(e[n]||(e[n]=0),e[n]++),e}),{});return this.coders.forEach(((n,r)=>{let s=n.localName;s&&1===t[s]&&("length"===s&&(s="_length"),null==e[s]&&(e[s]=e[r]))})),Object.freeze(e)}encode(e,t){const n=nf.dereference(t,"tuple");return of(e,this.coders,n)}decode(e){return af(e,this.coders)}}function Af(e,t){return{address:Kd(e),storageKeys:t.map(((e,t)=>(Ka(nc(e,32),"invalid slot",`storageKeys[${t}]`,e),e.toLowerCase())))}}function vf(e){if(Array.isArray(e))return e.map(((t,n)=>Array.isArray(t)?(Ka(2===t.length,"invalid slot set",`value[${n}]`,t),Af(t[0],t[1])):(Ka(null!=t&&"object"==typeof t,"invalid address-slot set","value",e),Af(t.address,t.storageKeys))));Ka(null!=e&&"object"==typeof e,"invalid access list","value",e);const t=Object.keys(e).map((t=>{const n=e[t].reduce(((e,t)=>(e[t]=!0,e)),{});return Af(t,Object.keys(n).sort())}));return t.sort(((e,t)=>e.address.localeCompare(t.address))),t}function Ef(e){return{address:Kd(e.address),nonce:yc(null!=e.nonce?e.nonce:0),chainId:yc(null!=e.chainId?e.chainId:0),signature:Gd.from(e.signature)}}function kf(e){let t;return t="string"==typeof e?Hd.computePublicKey(e,!1):e.publicKey,Kd(Bu("0x"+t.substring(4)).substring(26))}const Sf=BigInt(0),Tf=BigInt(2),Rf=BigInt(27),If=BigInt(28),Cf=BigInt(35),Of=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),xf=Symbol.for("nodejs.util.inspect.custom"),Nf=131072,Pf=128;function Df(e,t){let n=e.toString(16);for(;n.length<2;)n="0"+n;return n+=kh(t).substring(4),"0x"+n}function Bf(e){return"0x"===e?null:Kd(e)}function Uf(e,t){try{return vf(e)}catch(n){Ka(!1,n.message,t,e)}}function Lf(e,t){try{if(!Array.isArray(e))throw new Error("authorizationList: invalid array");const t=[];for(let n=0;n<e.length;n++){const r=e[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`);t.push({address:Bf(r[1]),nonce:Ff(r[2],"nonce"),chainId:Ff(r[0],"chainId"),signature:Gd.from({yParity:Mf(r[3],"yParity"),r:uc(r[4],32),s:uc(r[5],32)})})}return t}catch(n){Ka(!1,n.message,t,e)}}function Mf(e,t){return"0x"===e?0:Ac(e,t)}function Ff(e,t){if("0x"===e)return Sf;const n=yc(e,t);return Ka(n<=Of,"value exceeds uint size",t,n),n}function jf(e,t){const n=yc(e,"value"),r=Ec(n);return Ka(r.length<=32,"value too large",`tx.${t}`,n),r}function Gf(e){return vf(e).map((e=>[e.address,e.storageKeys]))}function Hf(e,t){Ka(Array.isArray(e),`invalid ${t}`,"value",e);for(let n=0;n<e.length;n++)Ka(nc(e[n],32),"invalid ${ param } hash",`value[${n}]`,e[n]);return e}function Vf(e,t){let n;try{if(n=Mf(t[0],"yParity"),0!==n&&1!==n)throw new Error("bad yParity")}catch(o){Ka(!1,"invalid yParity","yParity",t[0])}const r=uc(t[1],32),s=uc(t[2],32),i=Gd.from({r:r,s:s,yParity:n});e.signature=i}z=new WeakMap,$=new WeakMap,K=new WeakMap,Q=new WeakMap,J=new WeakMap,Y=new WeakMap,Z=new WeakMap,X=new WeakMap,ee=new WeakMap,te=new WeakMap,ne=new WeakMap,re=new WeakMap,se=new WeakMap,ie=new WeakMap,oe=new WeakMap,ae=new WeakMap,ce=new WeakMap,le=new WeakMap,ue=new WeakSet,he=function(e,t){$a(!e||null!=this.signature,"cannot serialize unsigned transaction; maybe you meant .unsignedSerialized","UNSUPPORTED_OPERATION",{operation:".serialized"});const n=e?this.signature:null;switch(this.inferType()){case 0:return function(e,t){const n=[jf(e.nonce,"nonce"),jf(e.gasPrice||0,"gasPrice"),jf(e.gasLimit,"gasLimit"),e.to||"0x",jf(e.value,"value"),e.data];let r=Sf;if(e.chainId!=Sf)r=yc(e.chainId,"tx.chainId"),Ka(!t||null==t.networkV||t.legacyChainId===r,"tx.chainId/sig.v mismatch","sig",t);else if(e.signature){const t=e.signature.legacyChainId;null!=t&&(r=t)}if(!t)return r!==Sf&&(n.push(Ec(r)),n.push("0x"),n.push("0x")),ol(n);let s=BigInt(27+t.yParity);return r!==Sf?s=Gd.getChainIdV(r,t.v):BigInt(t.v)!==s&&Ka(!1,"tx.chainId/sig.v mismatch","sig",t),n.push(Ec(s)),n.push(Ec(t.r)),n.push(Ec(t._s)),ol(n)}(this,n);case 1:return function(e,t){const n=[jf(e.chainId,"chainId"),jf(e.nonce,"nonce"),jf(e.gasPrice||0,"gasPrice"),jf(e.gasLimit,"gasLimit"),e.to||"0x",jf(e.value,"value"),e.data,Gf(e.accessList||[])];return t&&(n.push(jf(t.yParity,"recoveryParam")),n.push(Ec(t.r)),n.push(Ec(t.s))),oc(["0x01",ol(n)])}(this,n);case 2:return function(e,t){const n=[jf(e.chainId,"chainId"),jf(e.nonce,"nonce"),jf(e.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),jf(e.maxFeePerGas||0,"maxFeePerGas"),jf(e.gasLimit,"gasLimit"),e.to||"0x",jf(e.value,"value"),e.data,Gf(e.accessList||[])];return t&&(n.push(jf(t.yParity,"yParity")),n.push(Ec(t.r)),n.push(Ec(t.s))),oc(["0x02",ol(n)])}(this,n);case 3:return function(e,t,n){const r=[jf(e.chainId,"chainId"),jf(e.nonce,"nonce"),jf(e.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),jf(e.maxFeePerGas||0,"maxFeePerGas"),jf(e.gasLimit,"gasLimit"),e.to||Id,jf(e.value,"value"),e.data,Gf(e.accessList||[]),jf(e.maxFeePerBlobGas||0,"maxFeePerBlobGas"),Hf(e.blobVersionedHashes||[],"blobVersionedHashes")];if(t&&(r.push(jf(t.yParity,"yParity")),r.push(Ec(t.r)),r.push(Ec(t.s)),n)){if(null!=e.blobWrapperVersion){const t=Ec(e.blobWrapperVersion),s=[];for(const{proof:e}of n){const t=ec(e),n=t.length/Pf;for(let e=0;e<t.length;e+=n)s.push(t.subarray(e,e+n))}return oc(["0x03",ol([r,t,n.map((e=>e.data)),n.map((e=>e.commitment)),s])])}return oc(["0x03",ol([r,n.map((e=>e.data)),n.map((e=>e.commitment)),n.map((e=>e.proof))])])}return oc(["0x03",ol(r)])}(this,n,t?this.blobs:null);case 4:return function(e,t){const n=[jf(e.chainId,"chainId"),jf(e.nonce,"nonce"),jf(e.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),jf(e.maxFeePerGas||0,"maxFeePerGas"),jf(e.gasLimit,"gasLimit"),e.to||"0x",jf(e.value,"value"),e.data,Gf(e.accessList||[]),(r=e.authorizationList||[],r.map((e=>[jf(e.chainId,"chainId"),e.address,jf(e.nonce,"nonce"),jf(e.signature.yParity,"yParity"),Ec(e.signature.r),Ec(e.signature._s)])))];var r;return t&&(n.push(jf(t.yParity,"yParity")),n.push(Ec(t.r)),n.push(Ec(t.s))),oc(["0x04",ol(n)])}(this,n)}$a(!1,"unsupported transaction type","UNSUPPORTED_OPERATION",{operation:".serialized"})};let qf=class e{constructor(){Dn(this,ue),Dn(this,z,void 0),Dn(this,$,void 0),Dn(this,K,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,ee,void 0),Dn(this,te,void 0),Dn(this,ne,void 0),Dn(this,re,void 0),Dn(this,se,void 0),Dn(this,ie,void 0),Dn(this,oe,void 0),Dn(this,ae,void 0),Dn(this,ce,void 0),Dn(this,le,void 0),Bn(this,z,null),Bn(this,$,null),Bn(this,Q,0),Bn(this,J,Sf),Bn(this,Y,null),Bn(this,Z,null),Bn(this,X,null),Bn(this,K,"0x"),Bn(this,ee,Sf),Bn(this,te,Sf),Bn(this,ne,null),Bn(this,re,null),Bn(this,se,null),Bn(this,ie,null),Bn(this,oe,null),Bn(this,ae,null),Bn(this,ce,null),Bn(this,le,null)}get type(){return Pn(this,z)}set type(e){switch(e){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:Ka(!1,"unsupported transaction type","type",e)}}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 e=Pn(this,$);return null==e&&3===this.type?Id:e}set to(e){Bn(this,$,null==e?null:Kd(e))}get nonce(){return Pn(this,Q)}set nonce(e){Bn(this,Q,Ac(e,"value"))}get gasLimit(){return Pn(this,J)}set gasLimit(e){Bn(this,J,yc(e))}get gasPrice(){const e=Pn(this,Y);return null!=e||0!==this.type&&1!==this.type?e:Sf}set gasPrice(e){Bn(this,Y,null==e?null:yc(e,"gasPrice"))}get maxPriorityFeePerGas(){const e=Pn(this,Z);return null==e?2===this.type||3===this.type?Sf:null:e}set maxPriorityFeePerGas(e){Bn(this,Z,null==e?null:yc(e,"maxPriorityFeePerGas"))}get maxFeePerGas(){const e=Pn(this,X);return null==e?2===this.type||3===this.type?Sf:null:e}set maxFeePerGas(e){Bn(this,X,null==e?null:yc(e,"maxFeePerGas"))}get data(){return Pn(this,K)}set data(e){Bn(this,K,ic(e))}get value(){return Pn(this,ee)}set value(e){Bn(this,ee,yc(e,"value"))}get chainId(){return Pn(this,te)}set chainId(e){Bn(this,te,yc(e))}get signature(){return Pn(this,ne)||null}set signature(e){Bn(this,ne,null==e?null:Gd.from(e))}isValid(){const e=this.signature;if(e&&!e.isValid())return!1;const t=this.authorizationList;if(t)for(const n of t)if(!n.signature.isValid())return!1;return!0}get accessList(){const e=Pn(this,re)||null;return null==e?1===this.type||2===this.type||3===this.type?[]:null:e}set accessList(e){Bn(this,re,null==e?null:vf(e))}get authorizationList(){const e=Pn(this,ce)||null;return null==e&&4===this.type?[]:e}set authorizationList(e){Bn(this,ce,null==e?null:e.map((e=>Ef(e))))}get maxFeePerBlobGas(){const e=Pn(this,se);return null==e&&3===this.type?Sf:e}set maxFeePerBlobGas(e){Bn(this,se,null==e?null:yc(e,"maxFeePerBlobGas"))}get blobVersionedHashes(){let e=Pn(this,ie);return null==e&&3===this.type?[]:e}set blobVersionedHashes(e){if(null!=e){Ka(Array.isArray(e),"blobVersionedHashes must be an Array","value",e),e=e.slice();for(let t=0;t<e.length;t++)Ka(nc(e[t],32),"invalid blobVersionedHash",`value[${t}]`,e[t])}Bn(this,ie,e)}get blobs(){return null==Pn(this,ae)?null:Pn(this,ae).map((e=>Object.assign({},e)))}set blobs(e){if(null==e)return void Bn(this,ae,null);const t=[],n=[];for(let r=0;r<e.length;r++){const s=e[r];if(rc(s)){$a(Pn(this,oe),"adding a raw blob requires a KZG library","UNSUPPORTED_OPERATION",{operation:"set blobs()"});let e=ec(s);if(Ka(e.length<=Nf,"blob is too large",`blobs[${r}]`,s),e.length!==Nf){const t=new Uint8Array(Nf);t.set(e),e=t}const i=Pn(this,oe).blobToKzgCommitment(e),o=ic(Pn(this,oe).computeBlobKzgProof(e,i));t.push({data:ic(e),commitment:ic(i),proof:o}),n.push(Df(1,i))}else{const e=ic(s.data),r=ic(s.commitment),i=ic(s.proof);t.push({data:e,commitment:r,proof:i}),n.push(Df(1,r))}}Bn(this,ae,t),Bn(this,ie,n)}get kzg(){return Pn(this,oe)}set kzg(e){Bn(this,oe,null==e?null:function(e){return{blobToKzgCommitment:t=>{if("computeBlobProof"in e){if("blobToKzgCommitment"in e&&"function"==typeof e.blobToKzgCommitment)return ec(e.blobToKzgCommitment(ic(t)))}else if("blobToKzgCommitment"in e&&"function"==typeof e.blobToKzgCommitment)return ec(e.blobToKzgCommitment(t));if("blobToKZGCommitment"in e&&"function"==typeof e.blobToKZGCommitment)return ec(e.blobToKZGCommitment(ic(t)));Ka(!1,"unsupported KZG library","kzg",e)},computeBlobKzgProof:(t,n)=>"computeBlobProof"in e&&"function"==typeof e.computeBlobProof?ec(e.computeBlobProof(ic(t),ic(n))):"computeBlobKzgProof"in e&&"function"==typeof e.computeBlobKzgProof?e.computeBlobKzgProof(t,n):"computeBlobKZGProof"in e&&"function"==typeof e.computeBlobKZGProof?ec(e.computeBlobKZGProof(ic(t),ic(n))):void Ka(!1,"unsupported KZG library","kzg",e)}}(e))}get blobWrapperVersion(){return Pn(this,le)}set blobWrapperVersion(e){Bn(this,le,e)}get hash(){return null==this.signature?null:Bu(Ln(this,ue,he).call(this,!0,!1))}get unsignedHash(){return Bu(this.unsignedSerialized)}get from(){return null==this.signature?null:(e=this.unsignedHash,t=this.signature.getCanonical(),kf(Hd.recoverPublicKey(e,t)));var e,t}get fromPublicKey(){return null==this.signature?null:Hd.recoverPublicKey(this.unsignedHash,this.signature.getCanonical())}isSigned(){return null!=this.signature}get serialized(){return Ln(this,ue,he).call(this,!0,!0)}get unsignedSerialized(){return Ln(this,ue,he).call(this,!1,!1)}inferType(){const e=this.inferTypes();return e.indexOf(2)>=0?2:e.pop()}inferTypes(){const e=null!=this.gasPrice,t=null!=this.maxFeePerGas||null!=this.maxPriorityFeePerGas,n=null!=this.accessList,r=null!=Pn(this,se)||Pn(this,ie);null!=this.maxFeePerGas&&null!=this.maxPriorityFeePerGas&&$a(this.maxFeePerGas>=this.maxPriorityFeePerGas,"priorityFee cannot be more than maxFee","BAD_DATA",{value:this}),$a(!t||0!==this.type&&1!==this.type,"transaction type cannot have maxFeePerGas or maxPriorityFeePerGas","BAD_DATA",{value:this}),$a(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):t?s.push(2):e?(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 e.from(this)}toJSON(){const e=e=>null==e?null:e.toString();return{type:this.type,to:this.to,data:this.data,nonce:this.nonce,gasLimit:e(this.gasLimit),gasPrice:e(this.gasPrice),maxPriorityFeePerGas:e(this.maxPriorityFeePerGas),maxFeePerGas:e(this.maxFeePerGas),value:e(this.value),chainId:e(this.chainId),sig:this.signature?this.signature.toJSON():null,accessList:this.accessList}}[xf](){return this.toString()}toString(){const e=[],t=t=>{let n=this[t];"string"==typeof n&&(n=JSON.stringify(n)),e.push(`${t}: ${n}`)};this.type&&t("type"),t("to"),t("data"),t("nonce"),t("gasLimit"),t("value"),null!=this.chainId&&t("chainId"),this.signature&&(t("from"),e.push(`signature: ${this.signature.toString()}`));const n=this.authorizationList;if(n){const t=[];for(const e of n){const n=[];n.push(`address: ${JSON.stringify(e.address)}`),null!=e.nonce&&n.push(`nonce: ${e.nonce}`),null!=e.chainId&&n.push(`chainId: ${e.chainId}`),e.signature&&n.push(`signature: ${e.signature.toString()}`),t.push(`Authorization { ${n.join(", ")} }`)}e.push(`authorizations: [ ${t.join(", ")} ]`)}return`Transaction { ${e.join(", ")} }`}static from(t){if(null==t)return new e;if("string"==typeof t){const n=ec(t);if(n[0]>=127)return e.from(function(e){const t=nl(e);Ka(Array.isArray(t)&&(9===t.length||6===t.length),"invalid field count for legacy transaction","data",e);const n={type:0,nonce:Mf(t[0],"nonce"),gasPrice:Ff(t[1],"gasPrice"),gasLimit:Ff(t[2],"gasLimit"),to:Bf(t[3]),value:Ff(t[4],"value"),data:ic(t[5]),chainId:Sf};if(6===t.length)return n;const r=Ff(t[6],"v"),s=Ff(t[7],"r"),i=Ff(t[8],"s");if(s===Sf&&i===Sf)n.chainId=r;else{let e=(r-Cf)/Tf;e<Sf&&(e=Sf),n.chainId=e,Ka(e!==Sf||r===Rf||r===If,"non-canonical legacy v","v",t[6]),n.signature=Gd.from({r:uc(t[7],32),s:uc(t[8],32),v:r})}return n}(n));switch(n[0]){case 1:return e.from(function(e){const t=nl(ec(e).slice(1));Ka(Array.isArray(t)&&(8===t.length||11===t.length),"invalid field count for transaction type: 1","data",ic(e));const n={type:1,chainId:Ff(t[0],"chainId"),nonce:Mf(t[1],"nonce"),gasPrice:Ff(t[2],"gasPrice"),gasLimit:Ff(t[3],"gasLimit"),to:Bf(t[4]),value:Ff(t[5],"value"),data:ic(t[6]),accessList:Uf(t[7],"accessList")};return 8===t.length||Vf(n,t.slice(8)),n}(n));case 2:return e.from(function(e){const t=nl(ec(e).slice(1));Ka(Array.isArray(t)&&(9===t.length||12===t.length),"invalid field count for transaction type: 2","data",ic(e));const n={type:2,chainId:Ff(t[0],"chainId"),nonce:Mf(t[1],"nonce"),maxPriorityFeePerGas:Ff(t[2],"maxPriorityFeePerGas"),maxFeePerGas:Ff(t[3],"maxFeePerGas"),gasPrice:null,gasLimit:Ff(t[4],"gasLimit"),to:Bf(t[5]),value:Ff(t[6],"value"),data:ic(t[7]),accessList:Uf(t[8],"accessList")};return 9===t.length||Vf(n,t.slice(9)),n}(n));case 3:return e.from(function(e){let t=nl(ec(e).slice(1)),n="3",r=null,s=null;if(4===t.length&&Array.isArray(t[0])){n="3 (network format)";const e=t[1],r=t[2],i=t[3];Ka(Array.isArray(e),"invalid network format: blobs not an array","fields[1]",e),Ka(Array.isArray(r),"invalid network format: commitments not an array","fields[2]",r),Ka(Array.isArray(i),"invalid network format: proofs not an array","fields[3]",i),Ka(e.length===r.length,"invalid network format: blobs/commitments length mismatch","fields",t),Ka(e.length===i.length,"invalid network format: blobs/proofs length mismatch","fields",t),s=[];for(let n=0;n<t[1].length;n++)s.push({data:e[n],commitment:r[n],proof:i[n]});t=t[0]}else if(5===t.length&&Array.isArray(t[0])){n="3 (EIP-7594 network format)",r=Ac(t[1]);const e=t[2],i=t[3],o=t[4];Ka(1===r,`unsupported EIP-7594 network format version: ${r}`,"fields[1]",r),Ka(Array.isArray(e),"invalid EIP-7594 network format: blobs not an array","fields[2]",e),Ka(Array.isArray(i),"invalid EIP-7594 network format: commitments not an array","fields[3]",i),Ka(Array.isArray(o),"invalid EIP-7594 network format: proofs not an array","fields[4]",o),Ka(e.length===i.length,"invalid network format: blobs/commitments length mismatch","fields",t),Ka(e.length*Pf===o.length,"invalid network format: blobs/proofs length mismatch","fields",t),s=[];for(let t=0;t<e.length;t++){const n=[];for(let e=0;e<Pf;e++)n.push(o[t*Pf+e]);s.push({data:e[t],commitment:i[t],proof:oc(n)})}t=t[0]}Ka(Array.isArray(t)&&(11===t.length||14===t.length),`invalid field count for transaction type: ${n}`,"data",ic(e));const i={type:3,chainId:Ff(t[0],"chainId"),nonce:Mf(t[1],"nonce"),maxPriorityFeePerGas:Ff(t[2],"maxPriorityFeePerGas"),maxFeePerGas:Ff(t[3],"maxFeePerGas"),gasPrice:null,gasLimit:Ff(t[4],"gasLimit"),to:Bf(t[5]),value:Ff(t[6],"value"),data:ic(t[7]),accessList:Uf(t[8],"accessList"),maxFeePerBlobGas:Ff(t[9],"maxFeePerBlobGas"),blobVersionedHashes:t[10],blobWrapperVersion:r};s&&(i.blobs=s),Ka(null!=i.to,`invalid address for transaction type: ${n}`,"data",e),Ka(Array.isArray(i.blobVersionedHashes),"invalid blobVersionedHashes: must be an array","data",e);for(let o=0;o<i.blobVersionedHashes.length;o++)Ka(nc(i.blobVersionedHashes[o],32),`invalid blobVersionedHash at index ${o}: must be length 32`,"data",e);return 11===t.length||Vf(i,t.slice(11)),i}(n));case 4:return e.from(function(e){const t=nl(ec(e).slice(1));Ka(Array.isArray(t)&&(10===t.length||13===t.length),"invalid field count for transaction type: 4","data",ic(e));const n={type:4,chainId:Ff(t[0],"chainId"),nonce:Mf(t[1],"nonce"),maxPriorityFeePerGas:Ff(t[2],"maxPriorityFeePerGas"),maxFeePerGas:Ff(t[3],"maxFeePerGas"),gasPrice:null,gasLimit:Ff(t[4],"gasLimit"),to:Bf(t[5]),value:Ff(t[6],"value"),data:ic(t[7]),accessList:Uf(t[8],"accessList"),authorizationList:Lf(t[9],"authorizationList")};return 10===t.length||Vf(n,t.slice(10)),n}(n))}$a(!1,"unsupported transaction type","UNSUPPORTED_OPERATION",{operation:"from"})}const n=new e;return null!=t.type&&(n.type=t.type),null!=t.to&&(n.to=t.to),null!=t.nonce&&(n.nonce=t.nonce),null!=t.gasLimit&&(n.gasLimit=t.gasLimit),null!=t.gasPrice&&(n.gasPrice=t.gasPrice),null!=t.maxPriorityFeePerGas&&(n.maxPriorityFeePerGas=t.maxPriorityFeePerGas),null!=t.maxFeePerGas&&(n.maxFeePerGas=t.maxFeePerGas),null!=t.maxFeePerBlobGas&&(n.maxFeePerBlobGas=t.maxFeePerBlobGas),null!=t.data&&(n.data=t.data),null!=t.value&&(n.value=t.value),null!=t.chainId&&(n.chainId=t.chainId),null!=t.signature&&(n.signature=Gd.from(t.signature)),null!=t.accessList&&(n.accessList=t.accessList),null!=t.authorizationList&&(n.authorizationList=t.authorizationList),null!=t.blobVersionedHashes&&(n.blobVersionedHashes=t.blobVersionedHashes),null!=t.kzg&&(n.kzg=t.kzg),null!=t.blobWrapperVersion&&(n.blobWrapperVersion=t.blobWrapperVersion),null!=t.blobs&&(n.blobs=t.blobs),null!=t.hash&&(Ka(n.isSigned(),"unsigned transaction cannot define '.hash'","tx",t),Ka(n.hash===t.hash,"hash mismatch","tx",t)),null!=t.from&&(Ka(n.isSigned(),"unsigned transaction cannot define '.from'","tx",t),Ka(n.from.toLowerCase()===(t.from||"").toLowerCase(),"from mismatch","tx",t)),n}};function Wf(e){return Bu(Dc(e))}const zf=new Map([[8217,"apostrophe"],[8260,"fraction slash"],[12539,"middle dot"]]);function $f(e){return function(e){let t=0;return()=>e[t++]}(function(e){let t=0;function n(){return e[t++]<<8|e[t++]}let r=n(),s=1,i=[0,1];for(let _=1;_<r;_++)i.push(s+=n());let o=n(),a=t;t+=o;let c=0,l=0;function u(){return 0==c&&(l=l<<8|e[t++],c=8),l>>--c&1}const h=2**31,d=h>>>1,f=d>>1,p=h-1;let g=0;for(let _=0;_<31;_++)g=g<<1|u();let m=[],y=0,w=h;for(;;){let e=Math.floor(((g-y+1)*s-1)/w),t=0,n=r;for(;n-t>1;){let r=t+n>>>1;e<i[r]?n=r:t=r}if(0==t)break;m.push(t);let o=y+Math.floor(w*i[t]/s),a=y+Math.floor(w*i[t+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((t=>{switch(t-b){case 3:return b+65792+(e[a++]<<16|e[a++]<<8|e[a++]);case 2:return b+256+(e[a++]<<8|e[a++]);case 1:return b+e[a++];default:return t-1}}))}(function(e){let t=[];[..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"].forEach(((e,n)=>t[e.charCodeAt(0)]=n));let n=e.length,r=new Uint8Array(6*n>>3);for(let s=0,i=0,o=0,a=0;s<n;s++)a=a<<6|t[e.charCodeAt(s)],o+=6,o>=8&&(r[i++]=a>>(o-=8));return r}(e)))}function Kf(e){return 1&e?~e>>1:e>>1}function Qf(e,t){let n=Array(e);for(let r=0,s=0;r<e;r++)n[r]=s+=Kf(t());return n}function Jf(e,t=0){let n=[];for(;;){let r=e(),s=e();if(!s)break;t+=r;for(let e=0;e<s;e++)n.push(t+e);t+=s+1}return n}function Yf(e){return Xf((()=>{let t=Jf(e);if(t.length)return t}))}function Zf(e){let t=[];for(;;){let n=e();if(0==n)break;t.push(tp(n,e))}for(;;){let n=e()-1;if(n<0)break;t.push(np(n,e))}return t.flat()}function Xf(e){let t=[];for(;;){let n=e(t.length);if(!n)break;t.push(n)}return t}function ep(e,t,n){let r=Array(e).fill().map((()=>[]));for(let s=0;s<t;s++)Qf(e,n).forEach(((e,t)=>r[t].push(e)));return r}function tp(e,t){let n=1+t(),r=t(),s=Xf(t);return ep(s.length,1+e,t).flatMap(((e,t)=>{let[i,...o]=e;return Array(s[t]).fill().map(((e,t)=>{let s=t*r;return[i+t*n,o.map((e=>e+s))]}))}))}function np(e,t){return ep(1+t(),1+e,t).map((e=>[e[0],e.slice(1)]))}function rp(e){return`{${function(e){return e.toString(16).toUpperCase().padStart(2,"0")}(e)}}`}function sp(e){let t=e.length;if(t<4096)return String.fromCodePoint(...e);let n=[];for(let r=0;r<t;)n.push(String.fromCodePoint(...e.slice(r,r+=4096)));return n.join("")}function ip(e,t){let n=e.length,r=n-t.length;for(let s=0;0==r&&s<n;s++)r=e[s]-t[s];return r}const op=44032,ap=4352,cp=4449,lp=4519,up=28,hp=588;function dp(e){return e>>24&255}function fp(e){return 16777215&e}let pp,gp,mp,yp;function wp(e){return e>=op&&e<55204}function bp(e,t){if(e>=ap&&e<4371&&t>=cp&&t<4470)return op+(e-ap)*hp+(t-cp)*up;if(wp(e)&&t>lp&&t<4547&&(e-op)%up==0)return e+(t-lp);{let n=yp.get(e);return n&&(n=n.get(t),n)?n:-1}}function _p(e){pp||function(){let e=$f("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");pp=new Map(Yf(e).flatMap(((e,t)=>e.map((e=>[e,t+1<<24]))))),gp=new Set(Jf(e)),mp=new Map,yp=new Map;for(let[t,n]of Zf(e)){if(!gp.has(t)&&2==n.length){let[e,r]=n,s=yp.get(e);s||(s=new Map,yp.set(e,s)),s.set(r,t)}mp.set(t,n.reverse())}}();let t=[],n=[],r=!1;function s(e){let n=pp.get(e);n&&(r=!0,e|=n),t.push(e)}for(let i of e)for(;;){if(i<128)t.push(i);else if(wp(i)){let e=i-op,t=e%hp/up|0,n=e%up;s(ap+(e/hp|0)),s(cp+t),n>0&&s(lp+n)}else{let e=mp.get(i);e?n.push(...e):s(i)}if(!n.length)break;i=n.pop()}if(r&&t.length>1){let e=dp(t[0]);for(let n=1;n<t.length;n++){let r=dp(t[n]);if(0==r||e<=r){e=r;continue}let s=n-1;for(;;){let n=t[s+1];if(t[s+1]=t[s],t[s]=n,!s)break;if(e=dp(t[--s]),e<=r)break}e=dp(t[n])}}return t}function Ap(e){return _p(e).map(fp)}function vp(e){return function(e){let t=[],n=[],r=-1,s=0;for(let i of e){let e=dp(i),o=fp(i);if(-1==r)0==e?r=o:t.push(o);else if(s>0&&s>=e)0==e?(t.push(r,...n),n.length=0,r=o):n.push(o),s=e;else{let i=bp(r,o);i>=0?r=i:0==s&&0==e?(t.push(r),r=o):(n.push(o),s=e)}}return r>=0&&t.push(r,...n),t}(_p(e))}const Ep=".",kp=e=>Array.from(e);function Sp(e,t){return e.P.has(t)||e.Q.has(t)}class Tp extends Array{get is_emoji(){return!0}}let Rp,Ip,Cp,Op,xp,Np,Pp,Dp,Bp,Up,Lp;function Mp(){if(Rp)return;let e=$f("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");const t=()=>Jf(e),n=()=>new Set(t()),r=(e,t)=>t.forEach((t=>e.add(t)));Rp=new Map(Zf(e)),Ip=n(),Cp=t(),Op=new Set(t().map((e=>Cp[e]))),Cp=new Set(Cp),xp=n(),n();let s=Yf(e),i=e();const o=()=>{let e=new Set;return t().forEach((t=>r(e,s[t]))),r(e,t()),e};Np=Xf((t=>{let n=Xf(e).map((e=>e+96));if(n.length){let r=t>=i;return n[0]-=32,n=sp(n),r&&(n=`Restricted[${n}]`),{N:n,P:o(),Q:o(),M:!e(),R:r}}})),Pp=n(),Dp=new Map;let a=t().concat(kp(Pp)).sort(((e,t)=>e-t));a.forEach(((t,n)=>{let r=e(),s=a[n]=r?a[n-r]:{V:[],M:new Map};s.V.push(t),Pp.has(t)||Dp.set(t,s)}));for(let{V:u,M:h}of new Set(Dp.values())){let e=[];for(let n of u){let t=Np.filter((e=>Sp(e,n))),s=e.find((({G:e})=>t.some((t=>e.has(t)))));s||(s={G:new Set,V:[]},e.push(s)),s.V.push(n),r(s.G,t)}let t=e.flatMap((e=>kp(e.G)));for(let{G:n,V:r}of e){let e=new Set(t.filter((e=>!n.has(e))));for(let t of r)h.set(t,e)}}Bp=new Set;let c=new Set;const l=e=>Bp.has(e)?c.add(e):Bp.add(e);for(let u of Np){for(let e of u.P)l(e);for(let e of u.Q)l(e)}for(let u of Bp)Dp.has(u)||c.has(u)||Dp.set(u,1);r(Bp,Ap(Bp)),Up=function(e){let t=[],n=Jf(e);return function e({S:n,B:r},s,i){if(!(4&n&&i===s[s.length-1])){2&n&&(i=s[s.length-1]),1&n&&t.push(s);for(let t of r)for(let n of t.Q)e(t,[...s,n],i)}}(function t(r){return{S:e(),B:Xf((()=>{let r=Jf(e).map((e=>n[e]));if(r.length)return t(r)})),Q:r}}([]),[]),t}(e).map((e=>Tp.from(e))).sort(ip),Lp=new Map;for(let u of Up){let e=[Lp];for(let t of u){let n=e.map((e=>{let n=e.get(t);return n||(n=new Map,e.set(t,n)),n}));65039===t?e.push(...n):e=n}for(let t of e)t.V=u}}function Fp(e){return(Hp(e)?"":`${jp(Gp([e]))} `)+rp(e)}function jp(e){return`"${e}"`}function Gp(e,t=1/0,n=rp){let r=[];var s,i;s=e[0],Mp(),(i?Op.has(s):Cp.has(s))&&r.push("◌"),e.length>t&&(t>>=1,e=[...e.slice(0,t),8230,...e.slice(-t)]);let o=0,a=e.length;for(let c=0;c<a;c++){let t=e[c];Hp(t)&&(r.push(sp(e.slice(o,c))),r.push(n(t)),o=c+1)}return r.push(sp(e.slice(o,a))),r.join("")}function Hp(e){return Mp(),xp.has(e)}function Vp(e){return t=function(e,t,n){if(!e)return[];Mp();let r=0;return e.split(Ep).map((e=>{let s=function(e){let t=[];for(let n=0,r=e.length;n<r;){let r=e.codePointAt(n);n+=r<65536?1:2,t.push(r)}return t}(e),i={input:s,offset:r};r+=s.length+1;try{let e,r=i.tokens=function(e,t,n){let r=[],s=[];for(e=e.slice().reverse();e.length;){let i=Kp(e);if(i)s.length&&(r.push(t(s)),s=[]),r.push(n(i));else{let t=e.pop();if(Bp.has(t))s.push(t);else{let e=Rp.get(t);if(e)s.push(...e);else if(!Ip.has(t))throw qp(t)}}}return s.length&&r.push(t(s)),r}(s,t,n),o=r.length;if(!o)throw new Error("empty label");let a=i.output=r.flat();if(function(e){for(let t=e.lastIndexOf(95);t>0;)if(95!==e[--t])throw new Error("underscore allowed only at start")}(a),!(i.emoji=o>1||r[0].is_emoji)&&a.every((e=>e<128)))!function(e){if(e.length>=4&&45==e[2]&&45==e[3])throw new Error(`invalid label extension: "${sp(e.slice(0,4))}"`)}(a),e="ASCII";else{let t=r.flatMap((e=>e.is_emoji?[]:e));if(t.length){if(Cp.has(a[0]))throw zp("leading combining mark");for(let e=1;e<o;e++){let t=r[e];if(!t.is_emoji&&Cp.has(t[0]))throw zp(`emoji + combining mark: "${sp(r[e-1])} + ${Gp([t[0]])}"`)}!function(e){let t=e[0],n=zf.get(t);if(n)throw zp(`leading ${n}`);let r=e.length,s=-1;for(let i=1;i<r;i++){t=e[i];let r=zf.get(t);if(r){if(s==i)throw zp(`${n} + ${r}`);s=i+1,n=r}}if(s==r)throw zp(`trailing ${n}`)}(a);let n=kp(new Set(t)),[s]=function(e){let t=Np;for(let n of e){let e=t.filter((e=>Sp(e,n)));if(!e.length)throw Np.some((e=>Sp(e,n)))?Wp(t[0],n):qp(n);if(t=e,1==e.length)break}return t}(n);!function(e,t){for(let n of t)if(!Sp(e,n))throw Wp(e,n);if(e.M){let e=Ap(t);for(let t=1,n=e.length;t<n;t++)if(Op.has(e[t])){let r=t+1;for(let s;r<n&&Op.has(s=e[r]);r++)for(let n=t;n<r;n++)if(e[n]==s)throw new Error(`duplicate non-spacing marks: ${Fp(s)}`);if(r-t>4)throw new Error(`excessive non-spacing marks: ${jp(Gp(e.slice(t-1,r)))} (${r-t}/4)`);t=r}}}(s,t),function(e,t){let n,r=[];for(let s of t){let e=Dp.get(s);if(1===e)return;if(e){let t=e.M.get(s);if(n=n?n.filter((e=>t.has(e))):kp(t),!n.length)return}else r.push(s)}if(n)for(let s of n)if(r.every((e=>Sp(s,e))))throw new Error(`whole-script confusable: ${e.N}/${s.N}`)}(s,n),e=s.N}else e="Emoji"}i.type=e}catch(o){i.error=o}return i}))}(e,vp,$p),t.map((({input:e,error:n,output:r})=>{if(n){let r=n.message;throw new Error(1==t.length?r:`Invalid label ${jp(Gp(e,63))}: ${r}`)}return sp(r)})).join(Ep);var t}function qp(e){return new Error(`disallowed character: ${Fp(e)}`)}function Wp(e,t){let n=Fp(t),r=Np.find((e=>e.P.has(t)));return r&&(n=`${r.N} ${n}`),new Error(`illegal mixture: ${e.N} + ${n}`)}function zp(e){return new Error(`illegal placement: ${e}`)}function $p(e){return e.filter((e=>65039!=e))}function Kp(e,t){let n,r=Lp,s=e.length;for(;s&&(r=r.get(e[--s]),r);){let{V:i}=r;i&&(n=i,t&&t.push(...e.slice(s).reverse()),e.length=s)}return n}const Qp=new Uint8Array(32);function Jp(e){return Ka(0!==e.length,"invalid ENS name; empty component","comp",e),e}function Yp(e){const t=Dc(Zp(e)),n=[];if(0===e.length)return n;let r=0;for(let s=0;s<t.length;s++){46===t[s]&&(n.push(Jp(t.slice(r,s))),r=s+1)}return Ka(r<t.length,"invalid ENS name; empty component","name",e),n.push(Jp(t.slice(r))),n}function Zp(e){try{if(0===e.length)throw new Error("empty label");return Vp(e)}catch(t){Ka(!1,`invalid ENS name (${t.message})`,"name",e)}}function Xp(e){try{return 0!==Yp(e).length}catch(t){}return!1}function eg(e){Ka("string"==typeof e,"invalid ENS name; not a string","name",e),Ka(e.length,"invalid ENS name (empty label)","name",e);let t=Qp;const n=Yp(e);for(;n.length;)t=Bu(oc([t,Bu(n.pop())]));return ic(t)}function tg(e,t){const n=null!=t?t:63;return Ka(n<=255,"DNS encoded label cannot exceed 255","length",n),ic(oc(Yp(e).map((t=>{Ka(t.length<=n,`label ${JSON.stringify(e)} exceeds ${n} bytes`,"name",e);const r=new Uint8Array(t.length+1);return r.set(t,1),r[0]=r.length-1,r}))))+"00"}Qp.fill(0);const ng=new Uint8Array(32);ng.fill(0);const rg=BigInt(-1),sg=BigInt(0),ig=BigInt(1),og=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");const ag=vc(ig,32),cg=vc(sg,32),lg={name:"string",version:"string",chainId:"uint256",verifyingContract:"address",salt:"bytes32"},ug=["name","version","chainId","verifyingContract","salt"];function hg(e){return function(t){return Ka("string"==typeof t,`invalid domain value for ${JSON.stringify(e)}`,`domain.${e}`,t),t}}const dg={name:hg("name"),version:hg("version"),chainId:function(e){const t=yc(e,"domain.chainId");return Ka(t>=0,"invalid chain ID","domain.chainId",e),Number.isSafeInteger(t)?Number(t):kc(t)},verifyingContract:function(e){try{return Kd(e).toLowerCase()}catch(t){}Ka(!1,'invalid domain value "verifyingContract"',"domain.verifyingContract",e)},salt:function(e){const t=ec(e,"domain.salt");return Ka(32===t.length,'invalid domain value "salt"',"domain.salt",e),ic(t)}};function fg(e){{const t=e.match(/^(u?)int(\d+)$/);if(t){const n=""===t[1],r=parseInt(t[2]);Ka(r%8==0&&0!==r&&r<=256&&t[2]===String(r),"invalid numeric width","type",e);const s=mc(og,n?r-1:r),i=n?(s+ig)*rg:sg;return function(t){const r=yc(t,"value");return Ka(r>=i&&r<=s,`value out-of-bounds for ${e}`,"value",r),vc(n?gc(r,256):r,32)}}}{const t=e.match(/^bytes(\d+)$/);if(t){const n=parseInt(t[1]);return Ka(0!==n&&n<=32&&t[1]===String(n),"invalid bytes width","type",e),function(t){return Ka(ec(t).length===n,`invalid length for ${e}`,"value",t),function(e){const t=ec(e),n=t.length%32;return n?oc([t,ng.slice(n)]):ic(t)}(t)}}}switch(e){case"address":return function(e){return uc(Kd(e),32)};case"bool":return function(e){return e?ag:cg};case"bytes":return function(e){return Bu(e)};case"string":return function(e){return Wf(e)}}return null}function pg(e,t){return`${e}(${t.map((({name:e,type:t})=>t+" "+e)).join(",")})`}function gg(e){const t=e.match(/^([^\x5b]*)((\x5b\d*\x5d)*)(\x5b(\d*)\x5d)$/);return t?{base:t[1],index:t[2]+t[4],array:{base:t[1],prefix:t[1]+t[2],count:t[5]?parseInt(t[5]):-1}}:{base:e}}de=new WeakMap,fe=new WeakMap,pe=new WeakMap,ge=new WeakSet,me=function(e){{const t=fg(e);if(t)return t}const t=gg(e).array;if(t){const e=t.prefix,n=this.getEncoder(e);return r=>{Ka(-1===t.count||t.count===r.length,`array length mismatch; expected length ${t.count}`,"value",r);let s=r.map(n);return Pn(this,fe).has(e)&&(s=s.map(Bu)),Bu(oc(s))}}const n=this.types[e];if(n){const t=Wf(Pn(this,fe).get(e));return e=>{const r=n.map((({name:t,type:n})=>{const r=this.getEncoder(n)(e[t]);return Pn(this,fe).has(n)?Bu(r):r}));return r.unshift(t),oc(r)}}Ka(!1,`unknown type: ${e}`,"type",e)};let mg=class e{constructor(e){Dn(this,ge),xn(this,"primaryType"),Dn(this,de,void 0),Dn(this,fe,void 0),Dn(this,pe,void 0),Bn(this,fe,new Map),Bn(this,pe,new Map);const t=new Map,n=new Map,r=new Map,s={};Object.keys(e).forEach((i=>{s[i]=e[i].map((({name:t,type:n})=>{let{base:r,index:s}=gg(n);return"int"!==r||e.int||(r="int256"),"uint"!==r||e.uint||(r="uint256"),{name:t,type:r+(s||"")}})),t.set(i,new Set),n.set(i,[]),r.set(i,new Set)})),Bn(this,de,JSON.stringify(s));for(const o in s){const r=new Set;for(const i of s[o]){Ka(!r.has(i.name),`duplicate variable name ${JSON.stringify(i.name)} in ${JSON.stringify(o)}`,"types",e),r.add(i.name);const s=gg(i.type).base;Ka(s!==o,`circular type reference to ${JSON.stringify(s)}`,"types",e);fg(s)||(Ka(n.has(s),`unknown type ${JSON.stringify(s)}`,"types",e),n.get(s).push(o),t.get(o).add(s))}}const i=Array.from(n.keys()).filter((e=>0===n.get(e).length));Ka(0!==i.length,"missing primary type","types",e),Ka(1===i.length,`ambiguous primary types or unused types: ${i.map((e=>JSON.stringify(e))).join(", ")}`,"types",e),Ha(this,{primaryType:i[0]}),function s(i,o){Ka(!o.has(i),`circular type reference to ${JSON.stringify(i)}`,"types",e),o.add(i);for(const e of t.get(i))if(n.has(e)){s(e,o);for(const t of o)r.get(t).add(e)}o.delete(i)}(this.primaryType,new Set);for(const[o,a]of r){const e=Array.from(a);e.sort(),Pn(this,fe).set(o,pg(o,s[o])+e.map((e=>pg(e,s[e]))).join(""))}}get types(){return JSON.parse(Pn(this,de))}getEncoder(e){let t=Pn(this,pe).get(e);return t||(t=Ln(this,ge,me).call(this,e),Pn(this,pe).set(e,t)),t}encodeType(e){const t=Pn(this,fe).get(e);return Ka(t,`unknown type: ${JSON.stringify(e)}`,"name",e),t}encodeData(e,t){return this.getEncoder(e)(t)}hashStruct(e,t){return Bu(this.encodeData(e,t))}encode(e){return this.encodeData(this.primaryType,e)}hash(e){return this.hashStruct(this.primaryType,e)}_visit(e,t,n){if(fg(e))return n(e,t);const r=gg(e).array;if(r)return Ka(-1===r.count||r.count===t.length,`array length mismatch; expected length ${r.count}`,"value",t),t.map((e=>this._visit(r.prefix,e,n)));const s=this.types[e];if(s)return s.reduce(((e,{name:r,type:s})=>(e[r]=this._visit(s,t[r],n),e)),{});Ka(!1,`unknown type: ${e}`,"type",e)}visit(e,t){return this._visit(this.primaryType,e,t)}static from(t){return new e(t)}static getPrimaryType(t){return e.from(t).primaryType}static hashStruct(t,n,r){return e.from(n).hashStruct(t,r)}static hashDomain(t){const n=[];for(const e in t){if(null==t[e])continue;const r=lg[e];Ka(r,`invalid typed-data domain key: ${JSON.stringify(e)}`,"domain",t),n.push({name:e,type:r})}return n.sort(((e,t)=>ug.indexOf(e.name)-ug.indexOf(t.name))),e.hashStruct("EIP712Domain",{EIP712Domain:n},t)}static encode(t,n,r){return oc(["0x1901",e.hashDomain(t),e.from(n).hash(r)])}static hash(t,n,r){return Bu(e.encode(t,n,r))}static async resolveNames(t,n,r,s){t=Object.assign({},t);for(const e in t)null==t[e]&&delete t[e];const i={};t.verifyingContract&&!nc(t.verifyingContract,20)&&(i[t.verifyingContract]="0x");const o=e.from(n);o.visit(r,((e,t)=>("address"!==e||nc(t,20)||(i[t]="0x"),t)));for(const e in i)i[e]=await s(e);return t.verifyingContract&&i[t.verifyingContract]&&(t.verifyingContract=i[t.verifyingContract]),{domain:t,value:r=o.visit(r,((e,t)=>"address"===e&&i[t]?i[t]:t))}}static getPayload(t,n,r){e.hashDomain(t);const s={},i=[];ug.forEach((e=>{const n=t[e];null!=n&&(s[e]=dg[e](n),i.push({name:e,type:lg[e]}))}));const o=e.from(n);n=o.types;const a=Object.assign({},n);return Ka(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,((e,t)=>{if(e.match(/^bytes(\d*)/))return ic(ec(t));if(e.match(/^u?int/))return yc(t).toString();switch(e){case"address":return t.toLowerCase();case"bool":return!!t;case"string":return Ka("string"==typeof t,"invalid string","value",t),t}Ka(!1,"unsupported type","type",e)}))}}};function yg(e){const t=new Set;return e.forEach((e=>t.add(e))),Object.freeze(t)}const wg=yg("external public payable override".split(" ")),bg="constant external internal payable private public pure view override",_g=yg(bg.split(" ")),Ag="constructor error event fallback function receive struct",vg=yg(Ag.split(" ")),Eg="calldata memory storage payable indexed",kg=yg(Eg.split(" ")),Sg=yg([Ag,Eg,"tuple returns",bg].join(" ").split(" ")),Tg={"(":"OPEN_PAREN",")":"CLOSE_PAREN","[":"OPEN_BRACKET","]":"CLOSE_BRACKET",",":"COMMA","@":"AT"},Rg=new RegExp("^(\\s*)"),Ig=new RegExp("^([0-9]+)"),Cg=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"),Og=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$"),xg=new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$"),Ng=class e{constructor(e){Dn(this,be),Dn(this,ye,void 0),Dn(this,we,void 0),Bn(this,ye,0),Bn(this,we,e.slice())}get offset(){return Pn(this,ye)}get length(){return Pn(this,we).length-Pn(this,ye)}clone(){return new e(Pn(this,we))}reset(){Bn(this,ye,0)}popKeyword(e){const t=this.peek();if("KEYWORD"!==t.type||!e.has(t.text))throw new Error(`expected keyword ${t.text}`);return this.pop().text}popType(e){if(this.peek().type!==e){const t=this.peek();throw new Error(`expected ${e}; got ${t.type} ${JSON.stringify(t.text)}`)}return this.pop().text}popParen(){const e=this.peek();if("OPEN_PAREN"!==e.type)throw new Error("bad start");const t=Ln(this,be,_e).call(this,Pn(this,ye)+1,e.match+1);return Bn(this,ye,e.match+1),t}popParams(){const e=this.peek();if("OPEN_PAREN"!==e.type)throw new Error("bad start");const t=[];for(;Pn(this,ye)<e.match-1;){const e=this.peek().linkNext;t.push(Ln(this,be,_e).call(this,Pn(this,ye)+1,e)),Bn(this,ye,e)}return Bn(this,ye,e.match+1),t}peek(){if(Pn(this,ye)>=Pn(this,we).length)throw new Error("out-of-bounds");return Pn(this,we)[Pn(this,ye)]}peekKeyword(e){const t=this.peekType("KEYWORD");return null!=t&&e.has(t)?t:null}peekType(e){if(0===this.length)return null;const t=this.peek();return t.type===e?t.text:null}pop(){const e=this.peek();return Un(this,ye)._++,e}toString(){const e=[];for(let t=Pn(this,ye);t<Pn(this,we).length;t++){const n=Pn(this,we)[t];e.push(`${n.type}:${n.text}`)}return`<TokenString ${e.join(" ")}>`}};ye=new WeakMap,we=new WeakMap,be=new WeakSet,_e=function(e=0,t=0){return new Ng(Pn(this,we).slice(e,t).map((t=>Object.freeze(Object.assign({},t,{match:t.match-e,linkBack:t.linkBack-e,linkNext:t.linkNext-e})))))};let Pg=Ng;function Dg(e){const t=[],n=t=>{const n=i<e.length?JSON.stringify(e[i]):"$EOI";throw new Error(`invalid token ${n} at ${i}: ${t}`)};let r=[],s=[],i=0;for(;i<e.length;){let o=e.substring(i),a=o.match(Rg);a&&(i+=a[1].length,o=e.substring(i));const c={depth:r.length,linkBack:-1,linkNext:-1,match:-1,type:"",text:"",offset:i,value:-1};t.push(c);let l=Tg[o[0]]||"";if(l){if(c.type=l,c.text=o[0],i++,"OPEN_PAREN"===l)r.push(t.length-1),s.push(t.length-1);else if("CLOSE_PAREN"==l)0===r.length&&n("no matching open bracket"),c.match=r.pop(),t[c.match].match=t.length-1,c.depth--,c.linkBack=s.pop(),t[c.linkBack].linkNext=t.length-1;else if("COMMA"===l)c.linkBack=s.pop(),t[c.linkBack].linkNext=t.length-1,s.push(t.length-1);else if("OPEN_BRACKET"===l)c.type="BRACKET";else if("CLOSE_BRACKET"===l){let e=t.pop().text;if(t.length>0&&"NUMBER"===t[t.length-1].type){const n=t.pop().text;e=n+e,t[t.length-1].value=Ac(n)}if(0===t.length||"BRACKET"!==t[t.length-1].type)throw new Error("missing opening bracket");t[t.length-1].text+=e}}else if(a=o.match(Cg),a){if(c.text=a[1],i+=c.text.length,Sg.has(c.text)){c.type="KEYWORD";continue}if(c.text.match(xg)){c.type="TYPE";continue}c.type="ID"}else{if(a=o.match(Ig),!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 Pg(t.map((e=>Object.freeze(e))))}function Bg(e,t){let n=[];for(const r in t.keys())e.has(r)&&n.push(r);if(n.length>1)throw new Error(`conflicting types: ${n.join(", ")}`)}function Ug(e,t){if(t.peekKeyword(vg)){const n=t.pop().text;if(n!==e)throw new Error(`expected ${e}, got ${n}`)}return t.popType("ID")}function Lg(e,t){const n=new Set;for(;;){const r=e.peekType("KEYWORD");if(null==r||t&&!t.has(r))break;if(e.pop(),n.has(r))throw new Error(`duplicate keywords: ${JSON.stringify(r)}`);n.add(r)}return Object.freeze(n)}function Mg(e){let t=Lg(e,_g);return Bg(t,yg("constant payable nonpayable".split(" "))),Bg(t,yg("pure view payable nonpayable".split(" "))),t.has("view")?"view":t.has("pure")?"pure":t.has("payable")?"payable":t.has("nonpayable")?"nonpayable":t.has("constant")?"view":"nonpayable"}function Fg(e,t){return e.popParams().map((e=>Xg.from(e,t)))}function jg(e){if(e.peekType("AT")){if(e.pop(),e.peekType("NUMBER"))return yc(e.pop().text);throw new Error("invalid gas")}return null}function Gg(e){if(e.length)throw new Error(`unexpected tokens at offset ${e.offset}: ${e.toString()}`)}const Hg=new RegExp(/^(.*)\[([0-9]*)\]$/);function Vg(e){const t=e.match(xg);if(Ka(t,"invalid type","type",e),"uint"===e)return"uint256";if("int"===e)return"int256";if(t[2]){const n=parseInt(t[2]);Ka(0!==n&&n<=32,"invalid bytes length","type",e)}else if(t[3]){const n=parseInt(t[3]);Ka(0!==n&&n<=256&&n%8==0,"invalid numeric width","type",e)}return e}const qg={},Wg=Symbol.for("_ethers_internal"),zg="_ParamTypeInternal",$g="_ErrorInternal",Kg="_EventInternal",Qg="_ConstructorInternal",Jg="_FallbackInternal",Yg="_FunctionInternal",Zg="_StructInternal";Ae=new WeakSet,ve=function(e,t,n,r){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 s=this.arrayChildren,i=t.slice();return i.forEach(((t,r)=>{var o;Ln(o=s,Ae,ve).call(o,e,t,n,(e=>{i[r]=e}))})),void r(i)}if(this.isTuple()){const s=this.components;let i;if(Array.isArray(t))i=t.slice();else{if(null==t||"object"!=typeof t)throw new Error("invalid tuple value");i=s.map((e=>{if(!e.name)throw new Error("cannot use object value with unnamed components");if(!(e.name in t))throw new Error(`missing value for component ${e.name}`);return t[e.name]}))}if(i.length!==this.components.length)throw new Error("array is wrong length");return i.forEach(((t,r)=>{var o;Ln(o=s[r],Ae,ve).call(o,e,t,n,(e=>{i[r]=e}))})),void r(i)}const s=n(this.type,t);s.then?e.push(async function(){r(await s)}()):r(s)};let Xg=class e{constructor(e,t,n,r,s,i,o,a){if(Dn(this,Ae),xn(this,"name"),xn(this,"type"),xn(this,"baseType"),xn(this,"indexed"),xn(this,"components"),xn(this,"arrayLength"),xn(this,"arrayChildren"),Za(e,qg,"ParamType"),Object.defineProperty(this,Wg,{value:zg}),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("");Ha(this,{name:t,type:n,baseType:r,indexed:s,components:i,arrayLength:o,arrayChildren:a})}format(e){if(null==e&&(e="sighash"),"json"===e){const t=this.name||"";if(this.isArray()){const e=JSON.parse(this.arrayChildren.format("json"));return e.name=t,e.type+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`,JSON.stringify(e)}const n={type:"tuple"===this.baseType?"tuple":this.type,name:t};return"boolean"==typeof this.indexed&&(n.indexed=this.indexed),this.isTuple()&&(n.components=this.components.map((t=>JSON.parse(t.format(e))))),JSON.stringify(n)}let t="";return this.isArray()?(t+=this.arrayChildren.format(e),t+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`):this.isTuple()?t+="("+this.components.map((t=>t.format(e))).join("full"===e?", ":",")+")":t+=this.type,"sighash"!==e&&(!0===this.indexed&&(t+=" indexed"),"full"===e&&this.name&&(t+=" "+this.name)),t}isArray(){return"array"===this.baseType}isTuple(){return"tuple"===this.baseType}isIndexable(){return null!=this.indexed}walk(e,t){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 n=this;return e.map((e=>n.arrayChildren.walk(e,t)))}if(this.isTuple()){if(!Array.isArray(e))throw new Error("invalid tuple value");if(e.length!==this.components.length)throw new Error("array is wrong length");const n=this;return e.map(((e,r)=>n.components[r].walk(e,t)))}return t(this.type,e)}async walkAsync(e,t){const n=[],r=[e];return Ln(this,Ae,ve).call(this,n,e,t,(e=>{r[0]=e})),n.length&&await Promise.all(n),r[0]}static from(t,n){if(e.isParamType(t))return t;if("string"==typeof t)try{return e.from(Dg(t),n)}catch(a){Ka(!1,"invalid param type","obj",t)}else if(t instanceof Pg){let r="",s="",i=null;Lg(t,yg(["tuple"])).has("tuple")||t.peekType("OPEN_PAREN")?(s="tuple",i=t.popParams().map((t=>e.from(t))),r=`tuple(${i.map((e=>e.format())).join(",")})`):(r=Vg(t.popType("TYPE")),s=r);let o=null,a=null;for(;t.length&&t.peekType("BRACKET");){const n=t.pop();o=new e(qg,"",r,s,null,i,a,o),a=n.value,r+=n.text,s="array",i=null}let c=null;if(Lg(t,kg).has("indexed")){if(!n)throw new Error("");c=!0}const l=t.peekType("ID")?t.pop().text:"";if(t.length)throw new Error("leftover tokens");return new e(qg,l,r,s,c,i,a,o)}const r=t.name;Ka(!r||"string"==typeof r&&r.match(Og),"invalid name","obj.name",r);let s=t.indexed;null!=s&&(Ka(n,"parameter cannot be indexed","obj.indexed",t.indexed),s=!!s);let i=t.type,o=i.match(Hg);if(o){const n=parseInt(o[2]||"-1"),a=e.from({type:o[1],components:t.components});return new e(qg,r||"",i,"array",s,null,n,a)}if("tuple"===i||i.startsWith("tuple(")||i.startsWith("(")){const n=null!=t.components?t.components.map((t=>e.from(t))):null;return new e(qg,r||"",i,"tuple",s,n,null,null)}return i=Vg(t.type),new e(qg,r||"",i,i,s,null,null,null)}static isParamType(e){return e&&e[Wg]===zg}};class em{constructor(e,t,n){xn(this,"type"),xn(this,"inputs"),Za(e,qg,"Fragment"),Ha(this,{type:t,inputs:n=Object.freeze(n.slice())})}static from(e){if("string"==typeof e){try{em.from(JSON.parse(e))}catch(t){}return em.from(Dg(e))}if(e instanceof Pg){switch(e.peekKeyword(vg)){case"constructor":return im.from(e);case"error":return rm.from(e);case"event":return sm.from(e);case"fallback":case"receive":return om.from(e);case"function":return am.from(e);case"struct":return cm.from(e)}}else if("object"==typeof e){switch(e.type){case"constructor":return im.from(e);case"error":return rm.from(e);case"event":return sm.from(e);case"fallback":case"receive":return om.from(e);case"function":return am.from(e);case"struct":return cm.from(e)}$a(!1,`unsupported type: ${e.type}`,"UNSUPPORTED_OPERATION",{operation:"Fragment.from"})}Ka(!1,"unsupported frgament object","obj",e)}static isConstructor(e){return im.isFragment(e)}static isError(e){return rm.isFragment(e)}static isEvent(e){return sm.isFragment(e)}static isFunction(e){return am.isFragment(e)}static isStruct(e){return cm.isFragment(e)}}class tm extends em{constructor(e,t,n,r){super(e,t,r),xn(this,"name"),Ka("string"==typeof n&&n.match(Og),"invalid identifier","name",n),r=Object.freeze(r.slice()),Ha(this,{name:n})}}function nm(e,t){return"("+t.map((t=>t.format(e))).join("full"===e?", ":",")+")"}class rm extends tm{constructor(e,t,n){super(e,"error",t,n),Object.defineProperty(this,Wg,{value:$g})}get selector(){return Wf(this.format("sighash")).substring(0,10)}format(e){if(null==e&&(e="sighash"),"json"===e)return JSON.stringify({type:"error",name:this.name,inputs:this.inputs.map((t=>JSON.parse(t.format(e))))});const t=[];return"sighash"!==e&&t.push("error"),t.push(this.name+nm(e,this.inputs)),t.join(" ")}static from(e){if(rm.isFragment(e))return e;if("string"==typeof e)return rm.from(Dg(e));if(e instanceof Pg){const t=Ug("error",e),n=Fg(e);return Gg(e),new rm(qg,t,n)}return new rm(qg,e.name,e.inputs?e.inputs.map(Xg.from):[])}static isFragment(e){return e&&e[Wg]===$g}}class sm extends tm{constructor(e,t,n,r){super(e,"event",t,n),xn(this,"anonymous"),Object.defineProperty(this,Wg,{value:Kg}),Ha(this,{anonymous:r})}get topicHash(){return Wf(this.format("sighash"))}format(e){if(null==e&&(e="sighash"),"json"===e)return JSON.stringify({type:"event",anonymous:this.anonymous,name:this.name,inputs:this.inputs.map((t=>JSON.parse(t.format(e))))});const t=[];return"sighash"!==e&&t.push("event"),t.push(this.name+nm(e,this.inputs)),"sighash"!==e&&this.anonymous&&t.push("anonymous"),t.join(" ")}static getTopicHash(e,t){t=(t||[]).map((e=>Xg.from(e)));return new sm(qg,e,t,!1).topicHash}static from(e){if(sm.isFragment(e))return e;if("string"==typeof e)try{return sm.from(Dg(e))}catch(t){Ka(!1,"invalid event fragment","obj",e)}else if(e instanceof Pg){const t=Ug("event",e),n=Fg(e,!0),r=!!Lg(e,yg(["anonymous"])).has("anonymous");return Gg(e),new sm(qg,t,n,r)}return new sm(qg,e.name,e.inputs?e.inputs.map((e=>Xg.from(e,!0))):[],!!e.anonymous)}static isFragment(e){return e&&e[Wg]===Kg}}class im extends em{constructor(e,t,n,r,s){super(e,t,n),xn(this,"payable"),xn(this,"gas"),Object.defineProperty(this,Wg,{value:Qg}),Ha(this,{payable:r,gas:s})}format(e){if($a(null!=e&&"sighash"!==e,"cannot format a constructor for sighash","UNSUPPORTED_OPERATION",{operation:"format(sighash)"}),"json"===e)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((t=>JSON.parse(t.format(e))))});const t=[`constructor${nm(e,this.inputs)}`];return this.payable&&t.push("payable"),null!=this.gas&&t.push(`@${this.gas.toString()}`),t.join(" ")}static from(e){if(im.isFragment(e))return e;if("string"==typeof e)try{return im.from(Dg(e))}catch(t){Ka(!1,"invalid constuctor fragment","obj",e)}else if(e instanceof Pg){Lg(e,yg(["constructor"]));const t=Fg(e),n=!!Lg(e,wg).has("payable"),r=jg(e);return Gg(e),new im(qg,"constructor",t,n,r)}return new im(qg,"constructor",e.inputs?e.inputs.map(Xg.from):[],!!e.payable,null!=e.gas?e.gas:null)}static isFragment(e){return e&&e[Wg]===Qg}}class om extends em{constructor(e,t,n){super(e,"fallback",t),xn(this,"payable"),Object.defineProperty(this,Wg,{value:Jg}),Ha(this,{payable:n})}format(e){const t=0===this.inputs.length?"receive":"fallback";if("json"===e){const e=this.payable?"payable":"nonpayable";return JSON.stringify({type:t,stateMutability:e})}return`${t}()${this.payable?" payable":""}`}static from(e){if(om.isFragment(e))return e;if("string"==typeof e)try{return om.from(Dg(e))}catch(t){Ka(!1,"invalid fallback fragment","obj",e)}else if(e instanceof Pg){const t=e.toString();Ka(e.peekKeyword(yg(["fallback","receive"])),"type must be fallback or receive","obj",t);if("receive"===e.popKeyword(yg(["fallback","receive"]))){const t=Fg(e);return Ka(0===t.length,"receive cannot have arguments","obj.inputs",t),Lg(e,yg(["payable"])),Gg(e),new om(qg,[],!0)}let n=Fg(e);n.length?Ka(1===n.length&&"bytes"===n[0].type,"invalid fallback inputs","obj.inputs",n.map((e=>e.format("minimal"))).join(", ")):n=[Xg.from("bytes")];const r=Mg(e);if(Ka("nonpayable"===r||"payable"===r,"fallback cannot be constants","obj.stateMutability",r),Lg(e,yg(["returns"])).has("returns")){const t=Fg(e);Ka(1===t.length&&"bytes"===t[0].type,"invalid fallback outputs","obj.outputs",t.map((e=>e.format("minimal"))).join(", "))}return Gg(e),new om(qg,n,"payable"===r)}if("receive"===e.type)return new om(qg,[],!0);if("fallback"===e.type){const t=[Xg.from("bytes")],n="payable"===e.stateMutability;return new om(qg,t,n)}Ka(!1,"invalid fallback description","obj",e)}static isFragment(e){return e&&e[Wg]===Jg}}class am extends tm{constructor(e,t,n,r,s,i){super(e,"function",t,r),xn(this,"constant"),xn(this,"outputs"),xn(this,"stateMutability"),xn(this,"payable"),xn(this,"gas"),Object.defineProperty(this,Wg,{value:Yg});Ha(this,{constant:"view"===n||"pure"===n,gas:i,outputs:s=Object.freeze(s.slice()),payable:"payable"===n,stateMutability:n})}get selector(){return Wf(this.format("sighash")).substring(0,10)}format(e){if(null==e&&(e="sighash"),"json"===e)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((t=>JSON.parse(t.format(e)))),outputs:this.outputs.map((t=>JSON.parse(t.format(e))))});const t=[];return"sighash"!==e&&t.push("function"),t.push(this.name+nm(e,this.inputs)),"sighash"!==e&&("nonpayable"!==this.stateMutability&&t.push(this.stateMutability),this.outputs&&this.outputs.length&&(t.push("returns"),t.push(nm(e,this.outputs))),null!=this.gas&&t.push(`@${this.gas.toString()}`)),t.join(" ")}static getSelector(e,t){t=(t||[]).map((e=>Xg.from(e)));return new am(qg,e,"view",t,[],null).selector}static from(e){if(am.isFragment(e))return e;if("string"==typeof e)try{return am.from(Dg(e))}catch(n){Ka(!1,"invalid function fragment","obj",e)}else if(e instanceof Pg){const t=Ug("function",e),n=Fg(e),r=Mg(e);let s=[];Lg(e,yg(["returns"])).has("returns")&&(s=Fg(e));const i=jg(e);return Gg(e),new am(qg,t,r,n,s,i)}let t=e.stateMutability;return null==t&&(t="payable","boolean"==typeof e.constant?(t="view",e.constant||(t="payable","boolean"!=typeof e.payable||e.payable||(t="nonpayable"))):"boolean"!=typeof e.payable||e.payable||(t="nonpayable")),new am(qg,e.name,t,e.inputs?e.inputs.map(Xg.from):[],e.outputs?e.outputs.map(Xg.from):[],null!=e.gas?e.gas:null)}static isFragment(e){return e&&e[Wg]===Yg}}class cm extends tm{constructor(e,t,n){super(e,"struct",t,n),Object.defineProperty(this,Wg,{value:Zg})}format(){throw new Error("@TODO")}static from(e){if("string"==typeof e)try{return cm.from(Dg(e))}catch(t){Ka(!1,"invalid struct fragment","obj",e)}else if(e instanceof Pg){const t=Ug("struct",e),n=Fg(e);return Gg(e),new cm(qg,t,n)}return new cm(qg,e.name,e.inputs?e.inputs.map(Xg.from):[])}static isFragment(e){return e&&e[Wg]===Zg}}const lm=new Map;lm.set(0,"GENERIC_PANIC"),lm.set(1,"ASSERT_FALSE"),lm.set(17,"OVERFLOW"),lm.set(18,"DIVIDE_BY_ZERO"),lm.set(33,"ENUM_RANGE_ERROR"),lm.set(34,"BAD_STORAGE_DATA"),lm.set(49,"STACK_UNDERFLOW"),lm.set(50,"ARRAY_RANGE_ERROR"),lm.set(65,"OUT_OF_MEMORY"),lm.set(81,"UNINITIALIZED_FUNCTION_CALL");const um=new RegExp(/^bytes([0-9]*)$/),hm=new RegExp(/^(u?int)([0-9]*)$/);let dm=null,fm=1024;Ee=new WeakSet,ke=function(e){if(e.isArray())return new cf(Ln(this,Ee,ke).call(this,e.arrayChildren),e.arrayLength,e.name);if(e.isTuple())return new _f(e.components.map((e=>Ln(this,Ee,ke).call(this,e))),e.name);switch(e.baseType){case"address":return new rf(e.name);case"bool":return new lf(e.name);case"string":return new bf(e.name);case"bytes":return new hf(e.name);case"":return new pf(e.name)}let t=e.type.match(hm);if(t){let n=parseInt(t[2]||"256");return Ka(0!==n&&n<=256&&n%8==0,"invalid "+t[1]+" bit length","param",e),new wf(n/8,"int"===t[1],e.name)}if(t=e.type.match(um),t){let n=parseInt(t[1]);return Ka(0!==n&&n<=32,"invalid bytes length","param",e),new df(n,e.name)}Ka(!1,"invalid type","type",e.type)};let pm=class e{constructor(){Dn(this,Ee)}getDefaultValue(e){const t=e.map((e=>Ln(this,Ee,ke).call(this,Xg.from(e))));return new _f(t,"_").defaultValue()}encode(e,t){Qa(t.length,e.length,"types/values length mismatch");const n=e.map((e=>Ln(this,Ee,ke).call(this,Xg.from(e)))),r=new _f(n,"_"),s=new _l;return r.encode(s,t),s.data}decode(e,t,n){const r=e.map((e=>Ln(this,Ee,ke).call(this,Xg.from(e))));return new _f(r,"_").decode(new Al(t,n,fm))}static _setDefaultMaxInflation(e){Ka("number"==typeof e&&Number.isInteger(e),"invalid defaultMaxInflation factor","value",e),fm=e}static defaultAbiCoder(){return null==dm&&(dm=new e),dm}static getBuiltinCallException(t,n,r){return function(e,t,n,r){let s="missing revert data",i=null,o=null;if(n){s="execution reverted";const e=ec(n);if(n=ic(n),0===e.length)s+=" (no data present; likely require(false) occurred",i="require(false)";else if(e.length%32!=4)s+=" (could not decode reason; invalid data length)";else if("0x08c379a0"===ic(e.slice(0,4)))try{i=r.decode(["string"],e.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"===ic(e.slice(0,4)))try{const t=Number(r.decode(["uint256"],e.slice(4))[0]);o={signature:"Panic(uint256)",name:"Panic",args:[t]},i=`Panic due to ${lm.get(t)||"UNKNOWN"}(${t})`,s+=`: ${i}`}catch(c){s+=" (could not decode panic code)"}else s+=" (unknown custom error)"}const a={to:t.to?Kd(t.to):null,data:t.data||"0x"};return t.from&&(a.from=Kd(t.from)),za(s,"CALL_EXCEPTION",{action:e,data:n,reason:i,transaction:a,invocation:null,revert:o})}(t,n,r,e.defaultAbiCoder())}};class gm{constructor(e,t,n){xn(this,"fragment"),xn(this,"name"),xn(this,"signature"),xn(this,"topic"),xn(this,"args");const r=e.name,s=e.format();Ha(this,{fragment:e,name:r,signature:s,topic:t,args:n})}}class mm{constructor(e,t,n,r){xn(this,"fragment"),xn(this,"name"),xn(this,"args"),xn(this,"signature"),xn(this,"selector"),xn(this,"value");const s=e.name,i=e.format();Ha(this,{fragment:e,name:s,args:n,signature:i,selector:t,value:r})}}class ym{constructor(e,t,n){xn(this,"fragment"),xn(this,"name"),xn(this,"args"),xn(this,"signature"),xn(this,"selector");const r=e.name,s=e.format();Ha(this,{fragment:e,name:r,args:n,signature:s,selector:t})}}class wm{constructor(e){xn(this,"hash"),xn(this,"_isIndexed"),Ha(this,{hash:e,_isIndexed:!0})}static isIndexed(e){return!(!e||!e._isIndexed)}}const bm={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"},_m={"0x08c379a0":{signature:"Error(string)",name:"Error",inputs:["string"],reason:e=>`reverted with reason string ${JSON.stringify(e)}`},"0x4e487b71":{signature:"Panic(uint256)",name:"Panic",inputs:["uint256"],reason:e=>{let t="unknown panic code";return e>=0&&e<=255&&bm[e.toString()]&&(t=bm[e.toString()]),`reverted with panic code 0x${e.toString(16)} (${t})`}}};Se=new WeakMap,Te=new WeakMap,Re=new WeakMap,Ie=new WeakMap,Ce=new WeakSet,Oe=function(e,t,n){if(nc(e)){const t=e.toLowerCase();for(const e of Pn(this,Re).values())if(t===e.selector)return e;return null}if(-1===e.indexOf("(")){const r=[];for(const[t,n]of Pn(this,Re))t.split("(")[0]===e&&r.push(n);if(t){const e=t.length>0?t[t.length-1]:null;let n=t.length,s=!0;nf.isTyped(e)&&"overrides"===e.type&&(s=!1,n--);for(let t=r.length-1;t>=0;t--){const e=r[t].inputs.length;e===n||s&&e===n-1||r.splice(t,1)}for(let i=r.length-1;i>=0;i--){const e=r[i].inputs;for(let n=0;n<t.length;n++)if(nf.isTyped(t[n])){if(n>=e.length){if("overrides"===t[n].type)continue;r.splice(i,1);break}if(t[n].type!==e[n].baseType){r.splice(i,1);break}}}}if(1===r.length&&t&&t.length!==r[0].inputs.length){const e=t[t.length-1];(null==e||Array.isArray(e)||"object"!=typeof e)&&r.splice(0,1)}if(0===r.length)return null;if(r.length>1&&n){Ka(!1,`ambiguous function description (i.e. matches ${r.map((e=>JSON.stringify(e.format()))).join(", ")})`,"key",e)}return r[0]}const r=Pn(this,Re).get(am.from(e).format());return r||null},xe=new WeakSet,Ne=function(e,t,n){if(nc(e)){const t=e.toLowerCase();for(const e of Pn(this,Te).values())if(t===e.topicHash)return e;return null}if(-1===e.indexOf("(")){const r=[];for(const[t,n]of Pn(this,Te))t.split("(")[0]===e&&r.push(n);if(t){for(let e=r.length-1;e>=0;e--)r[e].inputs.length<t.length&&r.splice(e,1);for(let e=r.length-1;e>=0;e--){const n=r[e].inputs;for(let s=0;s<t.length;s++)if(nf.isTyped(t[s])&&t[s].type!==n[s].baseType){r.splice(e,1);break}}}if(0===r.length)return null;if(r.length>1&&n){Ka(!1,`ambiguous event description (i.e. matches ${r.map((e=>JSON.stringify(e.format()))).join(", ")})`,"key",e)}return r[0]}const r=Pn(this,Te).get(sm.from(e).format());return r||null};let Am=class e{constructor(e){Dn(this,Ce),Dn(this,xe),xn(this,"fragments"),xn(this,"deploy"),xn(this,"fallback"),xn(this,"receive"),Dn(this,Se,void 0),Dn(this,Te,void 0),Dn(this,Re,void 0),Dn(this,Ie,void 0);let t=[];t="string"==typeof e?JSON.parse(e):e,Bn(this,Re,new Map),Bn(this,Se,new Map),Bn(this,Te,new Map);const n=[];for(const o of t)try{n.push(em.from(o))}catch(i){console.log(`[Warning] Invalid Fragment ${JSON.stringify(o)}:`,i.message)}Ha(this,{fragments:Object.freeze(n)});let r=null,s=!1;Bn(this,Ie,this.getAbiCoder()),this.fragments.forEach(((e,t)=>{let n;switch(e.type){case"constructor":return this.deploy?void console.log("duplicate definition - constructor"):void Ha(this,{deploy:e});case"fallback":return void(0===e.inputs.length?s=!0:(Ka(!r||e.payable!==r.payable,"conflicting fallback fragments",`fragments[${t}]`,e),r=e,s=r.payable));case"function":n=Pn(this,Re);break;case"event":n=Pn(this,Te);break;case"error":n=Pn(this,Se);break;default:return}const i=e.format();n.has(i)||n.set(i,e)})),this.deploy||Ha(this,{deploy:im.from("constructor()")}),Ha(this,{fallback:r,receive:s})}format(e){const t=e?"minimal":"full";return this.fragments.map((e=>e.format(t)))}formatJson(){const e=this.fragments.map((e=>e.format("json")));return JSON.stringify(e.map((e=>JSON.parse(e))))}getAbiCoder(){return pm.defaultAbiCoder()}getFunctionName(e){const t=Ln(this,Ce,Oe).call(this,e,null,!1);return Ka(t,"no matching function","key",e),t.name}hasFunction(e){return!!Ln(this,Ce,Oe).call(this,e,null,!1)}getFunction(e,t){return Ln(this,Ce,Oe).call(this,e,t||null,!0)}forEachFunction(e){const t=Array.from(Pn(this,Re).keys());t.sort(((e,t)=>e.localeCompare(t)));for(let n=0;n<t.length;n++){const r=t[n];e(Pn(this,Re).get(r),n)}}getEventName(e){const t=Ln(this,xe,Ne).call(this,e,null,!1);return Ka(t,"no matching event","key",e),t.name}hasEvent(e){return!!Ln(this,xe,Ne).call(this,e,null,!1)}getEvent(e,t){return Ln(this,xe,Ne).call(this,e,t||null,!0)}forEachEvent(e){const t=Array.from(Pn(this,Te).keys());t.sort(((e,t)=>e.localeCompare(t)));for(let n=0;n<t.length;n++){const r=t[n];e(Pn(this,Te).get(r),n)}}getError(e,t){if(nc(e)){const t=e.toLowerCase();if(_m[t])return rm.from(_m[t].signature);for(const e of Pn(this,Se).values())if(t===e.selector)return e;return null}if(-1===e.indexOf("(")){const t=[];for(const[n,r]of Pn(this,Se))n.split("(")[0]===e&&t.push(r);if(0===t.length)return"Error"===e?rm.from("error Error(string)"):"Panic"===e?rm.from("error Panic(uint256)"):null;if(t.length>1){Ka(!1,`ambiguous error description (i.e. ${t.map((e=>JSON.stringify(e.format()))).join(", ")})`,"name",e)}return t[0]}if("Error(string)"===(e=rm.from(e).format()))return rm.from("error Error(string)");if("Panic(uint256)"===e)return rm.from("error Panic(uint256)");const n=Pn(this,Se).get(e);return n||null}forEachError(e){const t=Array.from(Pn(this,Se).keys());t.sort(((e,t)=>e.localeCompare(t)));for(let n=0;n<t.length;n++){const r=t[n];e(Pn(this,Se).get(r),n)}}_decodeParams(e,t){return Pn(this,Ie).decode(e,t)}_encodeParams(e,t){return Pn(this,Ie).encode(e,t)}encodeDeploy(e){return this._encodeParams(this.deploy.inputs,e||[])}decodeErrorResult(e,t){if("string"==typeof e){const t=this.getError(e);Ka(t,"unknown error","fragment",e),e=t}return Ka(cc(t,0,4)===e.selector,`data signature does not match error ${e.name}.`,"data",t),this._decodeParams(e.inputs,cc(t,4))}encodeErrorResult(e,t){if("string"==typeof e){const t=this.getError(e);Ka(t,"unknown error","fragment",e),e=t}return oc([e.selector,this._encodeParams(e.inputs,t||[])])}decodeFunctionData(e,t){if("string"==typeof e){const t=this.getFunction(e);Ka(t,"unknown function","fragment",e),e=t}return Ka(cc(t,0,4)===e.selector,`data signature does not match function ${e.name}.`,"data",t),this._decodeParams(e.inputs,cc(t,4))}encodeFunctionData(e,t){if("string"==typeof e){const t=this.getFunction(e);Ka(t,"unknown function","fragment",e),e=t}return oc([e.selector,this._encodeParams(e.inputs,t||[])])}decodeFunctionResult(e,t){if("string"==typeof e){const t=this.getFunction(e);Ka(t,"unknown function","fragment",e),e=t}let n="invalid length for result data";const r=tc(t);if(r.length%32==0)try{return Pn(this,Ie).decode(e.outputs,r)}catch(s){n="could not decode result data"}$a(!1,n,"BAD_DATA",{value:ic(r),info:{method:e.name,signature:e.format()}})}makeError(e,t){const n=ec(e,"data"),r=pm.getBuiltinCallException("call",t,n);if(r.message.startsWith("execution reverted (unknown custom error)")){const e=ic(n.slice(0,4)),t=this.getError(e);if(t)try{const e=Pn(this,Ie).decode(t.inputs,n.slice(4));r.revert={name:t.name,signature:t.format(),args:e},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(t);return s&&(r.invocation={method:s.name,signature:s.signature,args:s.args}),r}encodeFunctionResult(e,t){if("string"==typeof e){const t=this.getFunction(e);Ka(t,"unknown function","fragment",e),e=t}return ic(Pn(this,Ie).encode(e.outputs,t||[]))}encodeFilterTopics(e,t){if("string"==typeof e){const t=this.getEvent(e);Ka(t,"unknown event","eventFragment",e),e=t}$a(t.length<=e.inputs.length,`too many arguments for ${e.format()}`,"UNEXPECTED_ARGUMENT",{count:t.length,expectedCount:e.inputs.length});const n=[];e.anonymous||n.push(e.topicHash);const r=(e,t)=>"string"===e.type?Wf(t):"bytes"===e.type?Bu(ic(t)):("bool"===e.type&&"boolean"==typeof t?t=t?"0x01":"0x00":e.type.match(/^u?int/)?t=vc(t):e.type.match(/^bytes/)?t=hc(t,32):"address"===e.type&&Pn(this,Ie).encode(["address"],[t]),uc(ic(t),32));for(t.forEach(((t,s)=>{const i=e.inputs[s];i.indexed?null==t?n.push(null):"array"===i.baseType||"tuple"===i.baseType?Ka(!1,"filtering with tuples or arrays not supported","contract."+i.name,t):Array.isArray(t)?n.push(t.map((e=>r(i,e)))):n.push(r(i,t)):Ka(null==t,"cannot filter non-indexed parameters; must be null","contract."+i.name,t)}));n.length&&null===n[n.length-1];)n.pop();return n}encodeEventLog(e,t){if("string"==typeof e){const t=this.getEvent(e);Ka(t,"unknown event","eventFragment",e),e=t}const n=[],r=[],s=[];return e.anonymous||n.push(e.topicHash),Ka(t.length===e.inputs.length,"event arguments/values mismatch","values",t),e.inputs.forEach(((e,i)=>{const o=t[i];if(e.indexed)if("string"===e.type)n.push(Wf(o));else if("bytes"===e.type)n.push(Bu(o));else{if("tuple"===e.baseType||"array"===e.baseType)throw new Error("not implemented");n.push(Pn(this,Ie).encode([e.type],[o]))}else r.push(e),s.push(o)})),{data:Pn(this,Ie).encode(r,s),topics:n}}decodeEventLog(e,t,n){if("string"==typeof e){const t=this.getEvent(e);Ka(t,"unknown event","eventFragment",e),e=t}if(null!=n&&!e.anonymous){const t=e.topicHash;Ka(nc(n[0],32)&&n[0].toLowerCase()===t,"fragment/topic mismatch","topics[0]",n[0]),n=n.slice(1)}const r=[],s=[],i=[];e.inputs.forEach(((e,t)=>{e.indexed?"string"===e.type||"bytes"===e.type||"tuple"===e.baseType||"array"===e.baseType?(r.push(Xg.from({type:"bytes32",name:e.name})),i.push(!0)):(r.push(e),i.push(!1)):(s.push(e),i.push(!1))}));const o=null!=n?Pn(this,Ie).decode(r,oc(n)):null,a=Pn(this,Ie).decode(s,t,!0),c=[],l=[];let u=0,h=0;return e.inputs.forEach(((e,t)=>{let n=null;if(e.indexed)if(null==o)n=new wm(null);else if(i[t])n=new wm(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(e.name||null)})),yl.fromItems(c,l)}parseTransaction(e){const t=ec(e.data,"tx.data"),n=yc(null!=e.value?e.value:0,"tx.value"),r=this.getFunction(ic(t.slice(0,4)));if(!r)return null;const s=Pn(this,Ie).decode(r.inputs,t.slice(4));return new mm(r,r.selector,s,n)}parseCallResult(e){throw new Error("@TODO")}parseLog(e){const t=this.getEvent(e.topics[0]);return!t||t.anonymous?null:new gm(t,t.topicHash,this.decodeEventLog(t,e.data,e.topics))}parseError(e){const t=ic(e),n=this.getError(cc(t,0,4));if(!n)return null;const r=Pn(this,Ie).decode(n.inputs,cc(t,4));return new ym(n,n.selector,r)}static from(t){return t instanceof e?t:"string"==typeof t?new e(JSON.parse(t)):"function"==typeof t.formatJson?new e(t.formatJson()):"function"==typeof t.format?new e(t.format("json")):new e(t)}};const vm=BigInt(0);function Em(e){return null==e?null:e}function km(e){return null==e?null:e.toString()}class Sm{constructor(e,t,n){xn(this,"gasPrice"),xn(this,"maxFeePerGas"),xn(this,"maxPriorityFeePerGas"),Ha(this,{gasPrice:Em(e),maxFeePerGas:Em(t),maxPriorityFeePerGas:Em(n)})}toJSON(){const{gasPrice:e,maxFeePerGas:t,maxPriorityFeePerGas:n}=this;return{_type:"FeeData",gasPrice:km(e),maxFeePerGas:km(t),maxPriorityFeePerGas:km(n)}}}function Tm(e){const t={};e.to&&(t.to=e.to),e.from&&(t.from=e.from),e.data&&(t.data=ic(e.data));const n="chainId,gasLimit,gasPrice,maxFeePerBlobGas,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/);for(const s of n)s in e&&null!=e[s]&&(t[s]=yc(e[s],`request.${s}`));const r="type,nonce".split(/,/);for(const s of r)s in e&&null!=e[s]&&(t[s]=Ac(e[s],`request.${s}`));return e.accessList&&(t.accessList=vf(e.accessList)),e.authorizationList&&(t.authorizationList=e.authorizationList.slice()),"blockTag"in e&&(t.blockTag=e.blockTag),"enableCcipRead"in e&&(t.enableCcipRead=!!e.enableCcipRead),"customData"in e&&(t.customData=e.customData),"blobVersionedHashes"in e&&e.blobVersionedHashes&&(t.blobVersionedHashes=e.blobVersionedHashes.slice()),"kzg"in e&&(t.kzg=e.kzg),"blobWrapperVersion"in e&&(t.blobWrapperVersion=e.blobWrapperVersion),"blobs"in e&&e.blobs&&(t.blobs=e.blobs.map((e=>rc(e)?ic(e):Object.assign({},e)))),t}class Rm{constructor(e,t){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,Pe,void 0),Bn(this,Pe,e.transactions.map((e=>"string"!=typeof e?new Om(e,t):e))),Ha(this,{provider:t,hash:Em(e.hash),number:e.number,timestamp:e.timestamp,parentHash:e.parentHash,parentBeaconBlockRoot:e.parentBeaconBlockRoot,nonce:e.nonce,difficulty:e.difficulty,gasLimit:e.gasLimit,gasUsed:e.gasUsed,blobGasUsed:e.blobGasUsed,excessBlobGas:e.excessBlobGas,miner:e.miner,prevRandao:Em(e.prevRandao),extraData:e.extraData,baseFeePerGas:Em(e.baseFeePerGas),stateRoot:e.stateRoot,receiptsRoot:e.receiptsRoot,transactionsRoot:e.transactionsRoot})}get transactions(){return Pn(this,Pe).map((e=>"string"==typeof e?e:e.hash))}get prefetchedTransactions(){const e=Pn(this,Pe).slice();return 0===e.length?[]:($a("object"==typeof e[0],"transactions were not prefetched with block request","UNSUPPORTED_OPERATION",{operation:"transactionResponses()"}),e)}toJSON(){const{baseFeePerGas:e,difficulty:t,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:km(e),difficulty:km(t),extraData:n,gasLimit:km(r),gasUsed:km(s),blobGasUsed:km(this.blobGasUsed),excessBlobGas:km(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 e=0;const t=this.transactions;return{next:()=>e<this.length?{value:t[e++],done:!1}:{value:void 0,done:!0}}}get length(){return Pn(this,Pe).length}get date(){return null==this.timestamp?null:new Date(1e3*this.timestamp)}async getTransaction(e){let t;if("number"==typeof e)t=Pn(this,Pe)[e];else{const n=e.toLowerCase();for(const e of Pn(this,Pe)){if("string"==typeof e){if(e!==n)continue;t=e;break}if(e.hash===n){t=e;break}}}if(null==t)throw new Error("no such tx");return"string"==typeof t?await this.provider.getTransaction(t):t}getPrefetchedTransaction(e){const t=this.prefetchedTransactions;if("number"==typeof e)return t[e];e=e.toLowerCase();for(const n of t)if(n.hash===e)return n;Ka(!1,"no matching transaction","indexOrHash",e)}isMined(){return!!this.hash}isLondon(){return!!this.baseFeePerGas}orphanedEvent(){if(!this.isMined())throw new Error("");return{orphan:"drop-block",hash:(e=this).hash,number:e.number};var e}}Pe=new WeakMap;class Im{constructor(e,t){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=t;const n=Object.freeze(e.topics.slice());Ha(this,{transactionHash:e.transactionHash,blockHash:e.blockHash,blockNumber:e.blockNumber,removed:e.removed,address:e.address,data:e.data,topics:n,index:e.index,transactionIndex:e.transactionIndex})}toJSON(){const{address:e,blockHash:t,blockNumber:n,data:r,index:s,removed:i,topics:o,transactionHash:a,transactionIndex:c}=this;return{_type:"log",address:e,blockHash:t,blockNumber:n,data:r,index:s,removed:i,topics:o,transactionHash:a,transactionIndex:c}}async getBlock(){const e=await this.provider.getBlock(this.blockHash);return $a(!!e,"failed to find transaction","UNKNOWN_ERROR",{}),e}async getTransaction(){const e=await this.provider.getTransaction(this.transactionHash);return $a(!!e,"failed to find transaction","UNKNOWN_ERROR",{}),e}async getTransactionReceipt(){const e=await this.provider.getTransactionReceipt(this.transactionHash);return $a(!!e,"failed to find transaction receipt","UNKNOWN_ERROR",{}),e}removedEvent(){return{orphan:"drop-log",log:{transactionHash:(e=this).transactionHash,blockHash:e.blockHash,blockNumber:e.blockNumber,address:e.address,data:e.data,topics:Object.freeze(e.topics.slice()),index:e.index}};var e}}class Cm{constructor(e,t){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,De,void 0),Bn(this,De,Object.freeze(e.logs.map((e=>new Im(e,t)))));let n=vm;null!=e.effectiveGasPrice?n=e.effectiveGasPrice:null!=e.gasPrice&&(n=e.gasPrice),Ha(this,{provider:t,to:e.to,from:e.from,contractAddress:e.contractAddress,hash:e.hash,index:e.index,blockHash:e.blockHash,blockNumber:e.blockNumber,logsBloom:e.logsBloom,gasUsed:e.gasUsed,cumulativeGasUsed:e.cumulativeGasUsed,blobGasUsed:e.blobGasUsed,gasPrice:n,blobGasPrice:e.blobGasPrice,type:e.type,status:e.status,root:e.root})}get logs(){return Pn(this,De)}toJSON(){const{to:e,from:t,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:km(this.cumulativeGasUsed),from:t,gasPrice:km(this.gasPrice),blobGasUsed:km(this.blobGasUsed),blobGasPrice:km(this.blobGasPrice),gasUsed:km(this.gasUsed),hash:r,index:s,logs:c,logsBloom:a,root:u,status:l,to:e}}get length(){return this.logs.length}[Symbol.iterator](){let e=0;return{next:()=>e<this.length?{value:this.logs[e++],done:!1}:{value:void 0,done:!0}}}get fee(){return this.gasUsed*this.gasPrice}async getBlock(){const e=await this.provider.getBlock(this.blockHash);if(null==e)throw new Error("TODO");return e}async getTransaction(){const e=await this.provider.getTransaction(this.hash);if(null==e)throw new Error("TODO");return e}async getResult(){return await this.provider.getTransactionResult(this.hash)}async confirmations(){return await this.provider.getBlockNumber()-this.blockNumber+1}removedEvent(){return Nm(this)}reorderedEvent(e){return $a(!e||e.isMined(),"unmined 'other' transction cannot be orphaned","UNSUPPORTED_OPERATION",{operation:"reorderedEvent(other)"}),xm(this,e)}}De=new WeakMap;Be=new WeakMap;let Om=class e{constructor(e,t){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,Be,void 0),this.provider=t,this.blockNumber=null!=e.blockNumber?e.blockNumber:null,this.blockHash=null!=e.blockHash?e.blockHash:null,this.hash=e.hash,this.index=e.index,this.type=e.type,this.from=e.from,this.to=e.to||null,this.gasLimit=e.gasLimit,this.nonce=e.nonce,this.data=e.data,this.value=e.value,this.gasPrice=e.gasPrice,this.maxPriorityFeePerGas=null!=e.maxPriorityFeePerGas?e.maxPriorityFeePerGas:null,this.maxFeePerGas=null!=e.maxFeePerGas?e.maxFeePerGas:null,this.maxFeePerBlobGas=null!=e.maxFeePerBlobGas?e.maxFeePerBlobGas:null,this.chainId=e.chainId,this.signature=e.signature,this.accessList=null!=e.accessList?e.accessList:null,this.blobVersionedHashes=null!=e.blobVersionedHashes?e.blobVersionedHashes:null,this.authorizationList=null!=e.authorizationList?e.authorizationList:null,Bn(this,Be,-1)}toJSON(){const{blockNumber:e,blockHash:t,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:e,blockHash:t,blobVersionedHashes:h,chainId:km(this.chainId),data:c,from:o,gasLimit:km(this.gasLimit),gasPrice:km(this.gasPrice),hash:r,maxFeePerGas:km(this.maxFeePerGas),maxPriorityFeePerGas:km(this.maxPriorityFeePerGas),maxFeePerBlobGas:km(this.maxFeePerBlobGas),nonce:a,signature:l,to:i,index:n,type:s,value:km(this.value)}}async getBlock(){let e=this.blockNumber;if(null==e){const t=await this.getTransaction();t&&(e=t.blockNumber)}if(null==e)return null;const t=this.provider.getBlock(e);if(null==t)throw new Error("TODO");return t}async getTransaction(){return this.provider.getTransaction(this.hash)}async confirmations(){if(null==this.blockNumber){const{tx:e,blockNumber:t}=await Ga({tx:this.getTransaction(),blockNumber:this.provider.getBlockNumber()});return null==e||null==e.blockNumber?0:t-e.blockNumber+1}return await this.provider.getBlockNumber()-this.blockNumber+1}async wait(e,t){const n=null==e?1:e,r=null==t?0:t;let s=Pn(this,Be),i=-1,o=-1===s;const a=async()=>{if(o)return null;const{blockNumber:e,nonce:t}=await Ga({blockNumber:this.provider.getBlockNumber(),nonce:this.provider.getTransactionCount(this.from)});if(t<this.nonce)return void(s=e);if(o)return null;const r=await this.getTransaction();if(!r||null==r.blockNumber)for(-1===i&&(i=s-3,i<Pn(this,Be)&&(i=Pn(this,Be)));i<=e;){if(o)return null;const t=await this.provider.getBlock(i,!0);if(null==t)return;for(const e of t)if(e===this.hash)return;for(let r=0;r<t.length;r++){const i=await t.getTransaction(r);if(i.from===this.from&&i.nonce===this.nonce){if(o)return null;const t=await this.provider.getTransactionReceipt(i.hash);if(null==t)return;if(e-t.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===vm&&(r="cancelled"),$a(!1,"transaction was replaced","TRANSACTION_REPLACED",{cancelled:"replaced"===r||"cancelled"===r,reason:r,replacement:i.replaceableTransaction(s),hash:i.hash,receipt:t})}}i++}},c=e=>{if(null==e||0!==e.status)return e;$a(!1,"transaction execution reverted","CALL_EXCEPTION",{action:"sendTransaction",data:null,reason:null,invocation:null,revert:null,transaction:{to:e.to,from:e.from,data:""},receipt:e})},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(((e,t)=>{const i=[],l=()=>{i.forEach((e=>e()))};if(i.push((()=>{o=!0})),r>0){const e=setTimeout((()=>{l(),t(za("wait for transaction timeout","TIMEOUT"))}),r);i.push((()=>{clearTimeout(e)}))}const u=async r=>{if(await r.confirmations()>=n){l();try{e(c(r))}catch(s){t(s)}}};if(i.push((()=>{this.provider.off(this.hash,u)})),this.provider.on(this.hash,u),s>=0){const e=async()=>{try{await a()}catch(n){if(qa(n,"TRANSACTION_REPLACED"))return l(),void t(n)}o||this.provider.once("block",e)};i.push((()=>{this.provider.off("block",e)})),this.provider.once("block",e)}}));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 $a(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),Nm(this)}reorderedEvent(e){return $a(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),$a(!e||e.isMined(),"unmined 'other' transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),xm(this,e)}replaceableTransaction(t){Ka(Number.isInteger(t)&&t>=0,"invalid startBlock","startBlock",t);const n=new e(this,this.provider);return Bn(n,Be,t),n}};function xm(e,t){return{orphan:"reorder-transaction",tx:e,other:t}}function Nm(e){return{orphan:"drop-transaction",tx:e}}class Pm extends Im{constructor(e,t,n){super(e,e.provider),xn(this,"interface"),xn(this,"fragment"),xn(this,"args");Ha(this,{args:t.decodeEventLog(n,e.data,e.topics),fragment:n,interface:t})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}class Dm extends Im{constructor(e,t){super(e,e.provider),xn(this,"error"),Ha(this,{error:t})}}class Bm extends Cm{constructor(e,t,n){super(n,t),Dn(this,Ue,void 0),Bn(this,Ue,e)}get logs(){return super.logs.map((e=>{const t=e.topics.length?Pn(this,Ue).getEvent(e.topics[0]):null;if(t)try{return new Pm(e,Pn(this,Ue),t)}catch(n){return new Dm(e,n)}return e}))}}Ue=new WeakMap;class Um extends Om{constructor(e,t,n){super(n,t),Dn(this,Le,void 0),Bn(this,Le,e)}async wait(e,t){const n=await super.wait(e,t);return null==n?null:new Bm(Pn(this,Le),this.provider,n)}}Le=new WeakMap;class Lm extends xc{constructor(e,t,n,r){super(e,t,n),xn(this,"log"),Ha(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 Mm extends Lm{constructor(e,t,n,r,s){super(e,t,n,new Pm(s,e.interface,r));Ha(this,{args:e.interface.decodeEventLog(r,this.log.data,this.log.topics),fragment:r})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}const Fm=BigInt(0);function jm(e){return e&&"function"==typeof e.call}function Gm(e){return e&&"function"==typeof e.estimateGas}function Hm(e){return e&&"function"==typeof e.resolveName}function Vm(e){return e&&"function"==typeof e.sendTransaction}function qm(e){if(null!=e){if(Hm(e))return e;if(e.provider)return e.provider}}class Wm{constructor(e,t,n){if(Dn(this,Me,void 0),xn(this,"fragment"),Ha(this,{fragment:t}),t.inputs.length<n.length)throw new Error("too many arguments");const r=zm(e.runner,"resolveName"),s=Hm(r)?r:null;Bn(this,Me,async function(){const r=await Promise.all(t.inputs.map(((e,t)=>null==n[t]?null:e.walkAsync(n[t],((e,t)=>"address"===e?Array.isArray(t)?Promise.all(t.map((e=>Yd(e,s)))):Yd(t,s):t)))));return e.interface.encodeFilterTopics(t,r)}())}getTopicFilter(){return Pn(this,Me)}}function zm(e,t){return null==e?null:"function"==typeof e[t]?e:e.provider&&"function"==typeof e.provider[t]?e.provider:null}function $m(e){return null==e?null:e.provider||null}async function Km(e,t){const n=nf.dereference(e,"overrides");Ka("object"==typeof n,"invalid overrides parameter","overrides",e);const r=Tm(n);return Ka(null==r.to||(t||[]).indexOf("to")>=0,"cannot override to","overrides.to",r.to),Ka(null==r.data||(t||[]).indexOf("data")>=0,"cannot override data","overrides.data",r.data),r.from&&(r.from=r.from),r}function Qm(e){const t=async function(t){const n=await Km(t,["data"]);n.to=await e.getAddress(),n.from&&(n.from=await Yd(n.from,qm(e.runner)));const r=e.interface,s=yc(n.value||Fm,"overrides.value")===Fm,i="0x"===(n.data||"0x");!r.fallback||r.fallback.payable||!r.receive||i||s||Ka(!1,"cannot send data to receive or send value to non-payable fallback","overrides",t),Ka(r.fallback||i,"cannot send data to receive-only contract","overrides.data",n.data);return Ka(r.receive||r.fallback&&r.fallback.payable||s,"cannot send value to non-payable fallback","overrides.value",n.value),Ka(r.fallback||i,"cannot send data to receive-only contract","overrides.data",n.data),n},n=async function(n){const r=e.runner;$a(Vm(r),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const s=await r.sendTransaction(await t(n)),i=$m(e.runner);return new Um(e.interface,i,s)},r=async e=>await n(e);return Ha(r,{_contract:e,estimateGas:async function(n){const r=zm(e.runner,"estimateGas");return $a(Gm(r),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await r.estimateGas(await t(n))},populateTransaction:t,send:n,staticCall:async function(n){const r=zm(e.runner,"call");$a(jm(r),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const s=await t(n);try{return await r.call(s)}catch(i){if(Wa(i)&&i.data)throw e.interface.makeError(i.data,s);throw i}}}),r}function Jm(e,t){const n=function(...n){const r=e.interface.getFunction(t,n);return $a(r,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:t,args:n}}),r},r=async function(...t){const r=n(...t);let s={};if(r.inputs.length+1===t.length&&(s=await Km(t.pop()),s.from&&(s.from=await Yd(s.from,qm(e.runner)))),r.inputs.length!==t.length)throw new Error("internal error: fragment inputs doesn't match arguments; should not happen");const i=await async function(e,t,n){const r=zm(e,"resolveName"),s=Hm(r)?r:null;return await Promise.all(t.map(((e,t)=>e.walkAsync(n[t],((e,t)=>(t=nf.dereference(t,e),"address"===e?Yd(t,s):t))))))}(e.runner,r.inputs,t);return Object.assign({},s,await Ga({to:e.getAddress(),data:e.interface.encodeFunctionData(r,i)}))},s=async function(...e){const t=await o(...e);return 1===t.length?t[0]:t},i=async function(...t){const n=e.runner;$a(Vm(n),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const s=await n.sendTransaction(await r(...t)),i=$m(e.runner);return new Um(e.interface,i,s)},o=async function(...t){const s=zm(e.runner,"call");$a(jm(s),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const i=await r(...t);let o="0x";try{o=await s.call(i)}catch(c){if(Wa(c)&&c.data)throw e.interface.makeError(c.data,i);throw c}const a=n(...t);return e.interface.decodeFunctionResult(a,o)},a=async(...e)=>n(...e).constant?await s(...e):await i(...e);return Ha(a,{name:e.interface.getFunctionName(t),_contract:e,_key:t,getFragment:n,estimateGas:async function(...t){const n=zm(e.runner,"estimateGas");return $a(Gm(n),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await n.estimateGas(await r(...t))},populateTransaction:r,send:i,staticCall:s,staticCallResult:o}),Object.defineProperty(a,"fragment",{configurable:!1,enumerable:!0,get:()=>{const n=e.interface.getFunction(t);return $a(n,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:t}}),n}}),a}Me=new WeakMap;const Ym=Symbol.for("_ethersInternal_contract"),Zm=new WeakMap;function Xm(e){return Zm.get(e[Ym])}async function ey(e,t){let n,r=null;if(Array.isArray(t)){const r=function(t){if(nc(t,32))return t;const n=e.interface.getEvent(t);return Ka(n,"unknown fragment","name",t),n.topicHash};n=t.map((e=>null==e?null:Array.isArray(e)?e.map(r):r(e)))}else"*"===t?n=[null]:"string"==typeof t?nc(t,32)?n=[t]:(r=e.interface.getEvent(t),Ka(r,"unknown fragment","event",t),n=[r.topicHash]):(s=t)&&"object"==typeof s&&"getTopicFilter"in s&&"function"==typeof s.getTopicFilter&&s.fragment?n=await t.getTopicFilter():"fragment"in t?(r=t.fragment,n=[r.topicHash]):Ka(!1,"unknown event name","event",t);var s;n=n.map((e=>{if(null==e)return null;if(Array.isArray(e)){const t=Array.from(new Set(e.map((e=>e.toLowerCase()))).values());return 1===t.length?t[0]:(t.sort(),t)}return e.toLowerCase()}));return{fragment:r,tag:n.map((e=>null==e?"null":Array.isArray(e)?e.join("|"):e)).join("&"),topics:n}}async function ty(e,t){const{subs:n}=Xm(e);return n.get((await ey(e,t)).tag)||null}async function ny(e,t,n){const r=$m(e.runner);$a(r,"contract runner does not support subscribing","UNSUPPORTED_OPERATION",{operation:t});const{fragment:s,tag:i,topics:o}=await ey(e,n),{addr:a,subs:c}=Xm(e);let l=c.get(i);if(!l){const t={address:a||e,topics:o},u=t=>{let r=s;if(null==r)try{r=e.interface.getEvent(t.topics[0])}catch(i){}if(r){const i=r,o=s?e.interface.decodeEventLog(s,t.data,t.topics):[];sy(e,n,o,(r=>new Mm(e,r,n,i,t)))}else sy(e,n,[],(r=>new Lm(e,r,n,t)))};let h=[];l={tag:i,listeners:[],start:()=>{h.length||h.push(r.on(t,u))},stop:async()=>{if(0==h.length)return;let e=h;h=[],await Promise.all(e),r.off(t,u)}},c.set(i,l)}return l}let ry=Promise.resolve();async function sy(e,t,n,r){try{await ry}catch(i){}const s=async function(e,t,n,r){await ry;const s=await ty(e,t);if(!s)return!1;const o=s.listeners.length;return s.listeners=s.listeners.filter((({listener:t,once:s})=>{const o=Array.from(n);r&&o.push(r(s?null:t));try{t.call(e,...o)}catch(i){}return!s})),0===s.listeners.length&&(s.stop(),Xm(e).subs.delete(s.tag)),o>0}(e,t,n,r);return ry=s,await s}const iy=["then"];Fe=Ym;let oy=class e{constructor(e,t,n,r){xn(this,"target"),xn(this,"interface"),xn(this,"runner"),xn(this,"filters"),xn(this,Fe),xn(this,"fallback"),Ka("string"==typeof e||Qd(e),"invalid value for Contract target","target",e),null==n&&(n=null);const s=Am.from(t);let i;Ha(this,{target:e,runner:n,interface:s}),Object.defineProperty(this,Ym,{value:{}});let o=null,a=null;if(r){const e=$m(n);a=new Um(this.interface,e,r)}let c=new Map;if("string"==typeof e)if(nc(e))o=e,i=Promise.resolve(e);else{const t=zm(n,"resolveName");if(!Hm(t))throw za("contract runner does not support name resolution","UNSUPPORTED_OPERATION",{operation:"resolveName"});i=t.resolveName(e).then((t=>{if(null==t)throw za("an ENS name used for a contract target must be correctly configured","UNCONFIGURED_NAME",{value:e});return Xm(this).addr=t,t}))}else i=e.getAddress().then((e=>{if(null==e)throw new Error("TODO");return Xm(this).addr=e,e}));var l,u;l=this,u={addrPromise:i,addr:o,deployTx:a,subs:c},Zm.set(l[Ym],u);return Ha(this,{filters:new Proxy({},{get:(e,t,n)=>{if("symbol"==typeof t||iy.indexOf(t)>=0)return Reflect.get(e,t,n);try{return this.getEvent(t)}catch(r){if(!qa(r,"INVALID_ARGUMENT")||"key"!==r.argument)throw r}},has:(e,t)=>iy.indexOf(t)>=0?Reflect.has(e,t):Reflect.has(e,t)||this.interface.hasEvent(String(t))})}),Ha(this,{fallback:s.receive||s.fallback?Qm(this):null}),new Proxy(this,{get:(e,t,n)=>{if("symbol"==typeof t||t in e||iy.indexOf(t)>=0)return Reflect.get(e,t,n);try{return e.getFunction(t)}catch(r){if(!qa(r,"INVALID_ARGUMENT")||"key"!==r.argument)throw r}},has:(e,t)=>"symbol"==typeof t||t in e||iy.indexOf(t)>=0?Reflect.has(e,t):e.interface.hasFunction(t)})}connect(t){return new e(this.target,this.interface,t)}attach(t){return new e(t,this.interface,this.runner)}async getAddress(){return await Xm(this).addrPromise}async getDeployedCode(){const e=$m(this.runner);$a(e,"runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"getDeployedCode"});const t=await e.getCode(await this.getAddress());return"0x"===t?null:t}async waitForDeployment(){const e=this.deploymentTransaction();if(e)return await e.wait(),this;if(null!=await this.getDeployedCode())return this;const t=$m(this.runner);return $a(null!=t,"contract runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"waitForDeployment"}),new Promise(((e,n)=>{const r=async()=>{try{if(null!=await this.getDeployedCode())return e(this);t.once("block",r)}catch(s){n(s)}};r()}))}deploymentTransaction(){return Xm(this).deployTx}getFunction(e){"string"!=typeof e&&(e=e.format());return Jm(this,e)}getEvent(e){return"string"!=typeof e&&(e=e.format()),function(e,t){const n=function(...n){const r=e.interface.getEvent(t,n);return $a(r,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:t,args:n}}),r},r=function(...t){return new Wm(e,n(...t),t)};return Ha(r,{name:e.interface.getEventName(t),_contract:e,_key:t,getFragment:n}),Object.defineProperty(r,"fragment",{configurable:!1,enumerable:!0,get:()=>{const n=e.interface.getEvent(t);return $a(n,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:t}}),n}}),r}(this,e)}async queryTransaction(e){throw new Error("@TODO")}async queryFilter(e,t,n){null==t&&(t=0),null==n&&(n="latest");const{addr:r,addrPromise:s}=Xm(this),i=r||await s,{fragment:o,topics:a}=await ey(this,e),c={address:i,topics:a,fromBlock:t,toBlock:n},l=$m(this.runner);return $a(l,"contract runner does not have a provider","UNSUPPORTED_OPERATION",{operation:"queryFilter"}),(await l.getLogs(c)).map((e=>{let t=o;if(null==t)try{t=this.interface.getEvent(e.topics[0])}catch(n){}if(t)try{return new Pm(e,this.interface,t)}catch(n){return new Dm(e,n)}return new Im(e,l)}))}async on(e,t){const n=await ny(this,"on",e);return n.listeners.push({listener:t,once:!1}),n.start(),this}async once(e,t){const n=await ny(this,"once",e);return n.listeners.push({listener:t,once:!0}),n.start(),this}async emit(e,...t){return await sy(this,e,t,null)}async listenerCount(e){if(e){const t=await ty(this,e);return t?t.listeners.length:0}const{subs:t}=Xm(this);let n=0;for(const{listeners:r}of t.values())n+=r.length;return n}async listeners(e){if(e){const t=await ty(this,e);return t?t.listeners.map((({listener:e})=>e)):[]}const{subs:t}=Xm(this);let n=[];for(const{listeners:r}of t.values())n=n.concat(r.map((({listener:e})=>e)));return n}async off(e,t){const n=await ty(this,e);if(!n)return this;if(t){const e=n.listeners.map((({listener:e})=>e)).indexOf(t);e>=0&&n.listeners.splice(e,1)}return null!=t&&0!==n.listeners.length||(n.stop(),Xm(this).subs.delete(n.tag)),this}async removeAllListeners(e){if(e){const t=await ty(this,e);if(!t)return this;t.stop(),Xm(this).subs.delete(t.tag)}else{const{subs:e}=Xm(this);for(const{tag:t,stop:n}of e.values())n(),e.delete(t)}return this}async addListener(e,t){return await this.on(e,t)}async removeListener(e,t){return await this.off(e,t)}static buildClass(t){return class extends e{constructor(e,n=null){super(e,t,n)}}}static from(e,t,n){null==n&&(n=null);return new this(e,t,n)}};class ay extends(function(){return oy}()){}const cy=BigInt(60);function ly(e){return e.match(/^ipfs:\/\/ipfs\//i)?e=e.substring(12):e.match(/^ipfs:\/\//i)?e=e.substring(7):Ka(!1,"unsupported IPFS format","link",e),`https://gateway.ipfs.io/ipfs/${e}`}class uy{constructor(e){xn(this,"name"),Ha(this,{name:e})}connect(e){return this}supportsCoinType(e){return!1}async encodeAddress(e,t){throw new Error("unsupported coin")}async decodeAddress(e,t){throw new Error("unsupported coin")}}const hy=new RegExp("^(ipfs)://(.*)$","i"),dy=[new RegExp("^(https)://(.*)$","i"),new RegExp("^(data):(.*)$","i"),hy,new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$","i")];function fy(e){return e===cy||e>=2147483648&&e<=4294967295}const py=class e{constructor(e,t,n,r){Dn(this,He),xn(this,"provider"),xn(this,"address"),xn(this,"name"),Dn(this,je,void 0),Dn(this,Ge,void 0),Ha(this,{provider:e,address:t,name:n}),Bn(this,je,null!=r?Promise.resolve(r):null),Bn(this,Ge,new ay(t,["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)"],e))}async supportsWildcard(){return null==Pn(this,je)&&Bn(this,je,(async()=>{try{return await Pn(this,Ge).supportsInterface("0x9061b923")}catch(e){if(qa(e,"CALL_EXCEPTION"))return!1;throw Bn(this,je,null),e}})()),await Pn(this,je)}async getAddress(e){const t=null==e?cy:yc(e);if(t===cy)try{const e=await Ln(this,He,Ve).call(this,"addr(bytes32)");return null==e||e===Id?null:e}catch(s){if(qa(s,"CALL_EXCEPTION"))return null;throw s}if(fy(t)){const e=await Ln(this,He,Ve).call(this,"addr(bytes32,uint)",[t]);return nc(e,20)?Kd(e):null}if(t>=0&&t<2147483648){let e=t+BigInt(2147483648);const n=await Ln(this,He,Ve).call(this,"addr(bytes32,uint)",[e]);if(nc(n,20))return Kd(n)}let n=null;for(const i of this.provider.plugins)if(i instanceof uy&&t<=2147483648&&i.supportsCoinType(Number(t))){n=i;break}if(null==n)return null;const r=await Ln(this,He,Ve).call(this,"addr(bytes32,uint)",[t]);if(null==r||"0x"===r)return null;if(t<2147483648){const e=await n.decodeAddress(Number(t),r);if(null!=e)return e}$a(!1,"invalid coin data","UNSUPPORTED_OPERATION",{operation:`getAddress(${t})`,info:{coinType:t,data:r}})}async getText(e){const t=await Ln(this,He,Ve).call(this,"text(bytes32,string)",[e]);return null==t||"0x"===t?null:t}async getContentHash(){const e=await Ln(this,He,Ve).call(this,"contenthash(bytes32)");if(null==e||"0x"===e)return null;const t=e.match(/^0x(e3010170|e5010172)(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);if(t){const e="e3010170"===t[1]?"ipfs":"ipns",n=parseInt(t[4],16);if(t[5].length===2*n)return`${e}://${Oc("0x"+t[2])}`}const n=e.match(/^0xe40101fa011b20([0-9a-f]*)$/);if(n&&64===n[1].length)return`bzz://${n[1]}`;$a(!1,"invalid or unsupported content hash data","UNSUPPORTED_OPERATION",{operation:"getContentHash()",info:{data:e}})}async getName(){return await Ln(this,He,Ve).call(this,"name(bytes32)")}async getAvatar(){return(await this._getAvatar()).url}async _getAvatar(){const e=[{type:"name",value:this.name}];try{const r=await this.getText("avatar");if(null==r)return e.push({type:"!avatar",value:""}),{url:null,linkage:e};e.push({type:"avatar",value:r});for(let s=0;s<dy.length;s++){const i=r.match(dy[s]);if(null==i)continue;const o=i[1].toLowerCase();switch(o){case"https":case"data":return e.push({type:"url",value:r}),{linkage:e,url:r};case"ipfs":{const t=ly(r);return e.push({type:"ipfs",value:r}),e.push({type:"url",value:t}),{linkage:e,url:t}}case"erc721":case"erc1155":{const s="erc721"===o?"tokenURI(uint256)":"uri(uint256)";e.push({type:o,value:r});const a=await this.getAddress();if(null==a)return e.push({type:"!owner",value:""}),{url:null,linkage:e};const c=(i[2]||"").split("/");if(2!==c.length)return e.push({type:`!${o}caip`,value:i[2]||""}),{url:null,linkage:e};const l=c[1],u=new ay(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 t=await u.ownerOf(l);if(a!==t)return e.push({type:"!owner",value:t}),{url:null,linkage:e};e.push({type:"owner",value:t})}else if("erc1155"===o){const t=await u.balanceOf(a,l);if(!t)return e.push({type:"!balance",value:"0"}),{url:null,linkage:e};e.push({type:"balance",value:t.toString()})}let h=await u[s](l);if(null==h||"0x"===h)return e.push({type:"!metadata-url",value:""}),{url:null,linkage:e};e.push({type:"metadata-url-base",value:h}),"erc1155"===o&&(h=h.replace("{id}",vc(l,32).substring(2)),e.push({type:"metadata-url-expanded",value:h})),h.match(/^ipfs:/i)&&(h=ly(h)),e.push({type:"metadata-url",value:h});let d={};const f=await new Kc(h).send();f.assertOk();try{d=f.bodyJson}catch(t){try{e.push({type:"!metadata",value:f.bodyText})}catch(n){const t=f.body;return t&&e.push({type:"!metadata",value:ic(t)}),{url:null,linkage:e}}return{url:null,linkage:e}}if(!d)return e.push({type:"!metadata",value:""}),{url:null,linkage:e};e.push({type:"metadata",value:JSON.stringify(d)});let p=d.image;if("string"!=typeof p)return e.push({type:"!imageUrl",value:""}),{url:null,linkage:e};if(p.match(/^(https:\/\/|data:)/i));else{if(null==p.match(hy))return e.push({type:"!imageUrl-ipfs",value:p}),{url:null,linkage:e};e.push({type:"imageUrl-ipfs",value:p}),p=ly(p)}return e.push({type:"url",value:p}),{linkage:e,url:p}}}}}catch(t){}return{linkage:e,url:null}}static async getEnsAddress(e){const t=await e.getNetwork(),n=t.getPlugin("org.ethers.plugins.network.Ens");return $a(n,"network does not support ENS","UNSUPPORTED_OPERATION",{operation:"getEnsAddress",info:{network:t}}),n.address}static async getUniversalResolverAddress(e){const t=(await e.getNetwork()).getPlugin("org.ethers.plugins.network.Ens");return t&&t.universalResolver?t.universalResolver:null}static async lookupAddress(t,n,r){const s=null==r?cy:yc(r);fy(s)&&(n=Kd(n));const i=await my(t);if(i)try{const e=(await i.reverse(n,s,{enableCcipRead:!0})).primary;return Xp(e)?e:null}catch(o){if(qa(o,"CALL_EXCEPTION")&&"ResolverNotFound(bytes)"===o.reason)return null;throw o}$a(s===cy,"lookupAddress coinType requires ENS Universal Resolver","UNSUPPORTED_OPERATION",{operation:"lookupAddress"});try{const r=await e.fromName(t,`${n.toLowerCase().substring(2)}.addr.reverse`);if(!r)return null;const s=await r.getName();if(null==s||!Xp(s))return null;return await t.resolveName(s)!==n?null:s}catch(a){if(qa(a,"BAD_DATA")&&"0x"===a.value)return null;if(qa(a,"CALL_EXCEPTION"))return null;throw a}}static async fromName(t,n){var r;const s=await my(t);if(s){let r;try{r=tg(Zp(n),255)}catch(o){return null}const i=await s.requireResolver(r);return new e(t,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=e,qe,We).call(r,t,i);if(null!=s){const r=new e(t,s,n);return i===n||await r.supportsWildcard()?r:null}i=i.split(".").slice(1).join(".")}}};je=new WeakMap,Ge=new WeakMap,He=new WeakSet,Ve=async function(e,t){t=(t||[]).slice();const n=Pn(this,Ge).interface;t.unshift(eg(this.name));let r=null;await this.supportsWildcard()&&(r=n.getFunction(e),$a(r,"missing fragment","UNKNOWN_ERROR",{info:{funcName:e}}),t=[tg(this.name,255),n.encodeFunctionData(r,t)],e="resolve(bytes,bytes)"),t.push({enableCcipRead:!0});try{const s=await Pn(this,Ge)[e](...t);return r?n.decodeFunctionResult(r,s)[0]:s}catch(s){if(!qa(s,"CALL_EXCEPTION"))throw s}return null},qe=new WeakSet,We=async function(e,t){const n=await py.getEnsAddress(e);try{const r=new ay(n,["function resolver(bytes32) view returns (address)"],e),s=await r.resolver(eg(t),{enableCcipRead:!0});return s===Id?null:s}catch(r){throw r}return null},Dn(py,qe);let gy=py;async function my(e){const t=await gy.getUniversalResolverAddress(e);return t?new ay(t,["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)"],e):null}const yy=BigInt(0);function wy(e,t){return function(n){return null==n?t:e(n)}}function by(e,t){return n=>{if(t&&null==n)return null;if(!Array.isArray(n))throw new Error("not an array");return n.map((t=>e(t)))}}function _y(e,t){return n=>{const r={};for(const i in e){let o=i;if(t&&i in t&&!(o in n))for(const e of t[i])if(e in n){o=e;break}try{const t=e[i](n[o]);void 0!==t&&(r[i]=t)}catch(s){$a(!1,`invalid value for value.${i} (${s instanceof Error?s.message:"not-an-error"})`,"BAD_DATA",{value:n})}}return r}}function Ay(e){return Ka(nc(e,!0),"invalid data","value",e),e}function vy(e){return Ka(nc(e,32),"invalid hash","value",e),e}const Ey=_y({address:Kd,blockHash:vy,blockNumber:Ac,data:Ay,index:Ac,removed:wy((function(e){switch(e){case!0:case"true":return!0;case!1:case"false":return!1}Ka(!1,`invalid boolean; ${JSON.stringify(e)}`,"value",e)}),!1),topics:by(vy),transactionHash:vy,transactionIndex:Ac},{index:["logIndex"]});const ky=_y({hash:wy(vy),parentHash:vy,parentBeaconBlockRoot:wy(vy,null),number:Ac,timestamp:Ac,nonce:wy(Ay),difficulty:yc,gasLimit:yc,gasUsed:yc,stateRoot:wy(vy,null),receiptsRoot:wy(vy,null),transactionsRoot:wy(vy,null),blobGasUsed:wy(yc,null),excessBlobGas:wy(yc,null),miner:wy(Kd),prevRandao:wy(vy,null),extraData:Ay,baseFeePerGas:wy(yc)},{prevRandao:["mixHash"]});const Sy=_y({transactionIndex:Ac,blockNumber:Ac,transactionHash:vy,address:Kd,topics:by(vy),data:Ay,index:Ac,blockHash:vy},{index:["logIndex"]});const Ty=_y({to:wy(Kd,null),from:wy(Kd,null),contractAddress:wy(Kd,null),index:Ac,root:wy(ic),gasUsed:yc,blobGasUsed:wy(yc,null),logsBloom:wy(Ay),blockHash:vy,hash:vy,logs:by((function(e){return Sy(e)})),blockNumber:Ac,cumulativeGasUsed:yc,effectiveGasPrice:wy(yc),blobGasPrice:wy(yc,null),status:wy(Ac),type:wy(Ac,0)},{effectiveGasPrice:["gasPrice"],hash:["transactionHash"],index:["transactionIndex"]});function Ry(e){e.to&&yc(e.to)===yy&&(e.to="0x0000000000000000000000000000000000000000");const t=_y({hash:vy,index:wy(Ac,void 0),type:e=>"0x"===e||null==e?0:Ac(e),accessList:wy(vf,null),blobVersionedHashes:wy(by(vy,!0),null),authorizationList:wy(by((e=>{let t;if(e.signature)t=e.signature;else{let n=e.yParity;"0x1b"===n?n=0:"0x1c"===n&&(n=1),t=Object.assign({},e,{yParity:n})}return{address:Kd(e.address),chainId:yc(e.chainId),nonce:yc(e.nonce),signature:Gd.from(t)}}),!1),null),blockHash:wy(vy,null),blockNumber:wy(Ac,null),transactionIndex:wy(Ac,null),from:Kd,gasPrice:wy(yc),maxPriorityFeePerGas:wy(yc),maxFeePerGas:wy(yc),maxFeePerBlobGas:wy(yc,null),gasLimit:yc,to:wy(Kd,null),value:yc,nonce:Ac,data:Ay,creates:wy(Kd,null),chainId:wy(yc,null)},{data:["input"],gasLimit:["gas"],index:["transactionIndex"]})(e);if(null==t.to&&null==t.creates&&(t.creates=function(e){const t=Kd(e.from);let n=yc(e.nonce,"tx.nonce").toString(16);return n="0"===n?"0x":n.length%2?"0x0"+n:"0x"+n,Kd(cc(Bu(ol([t,n])),12))}(t)),1!==e.type&&2!==e.type||null!=e.accessList||(t.accessList=[]),e.signature?t.signature=Gd.from(e.signature):t.signature=Gd.from(e),null==t.chainId){const e=t.signature.legacyChainId;null!=e&&(t.chainId=e)}return t.blockHash&&yc(t.blockHash)===yy&&(t.blockHash=null),t}const Iy=Symbol.for("nodejs.util.inspect.custom");class Cy{constructor(e){xn(this,"name"),Ha(this,{name:e})}[Iy](){return this.toString()}toString(){return`${this.name} { }`}clone(){return new Cy(this.name)}}class Oy extends Cy{constructor(e,t){null==e&&(e=0),super(`org.ethers.network.plugins.GasCost#${e||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:e};function r(e,r){let s=(t||{})[e];null==s&&(s=r),Ka("number"==typeof s,`invalud value for ${e}`,"costs",t),n[e]=s}r("txBase",21e3),r("txCreate",32e3),r("txDataZero",4),r("txDataNonzero",16),r("txAccessListStorageKey",1900),r("txAccessListAddress",2400),Ha(this,n)}toString(){return`${this.name} { txBase: ${this.txBase}, txCreate: ${this.txCreate}, txDataZero: ${this.txDataZero}, txAccessListStorageKey: ${this.txAccessListStorageKey}, txAccessListAddress: ${this.txAccessListAddress} }`}clone(){return new Oy(this.effectiveBlock,this)}}class xy extends Cy{constructor(e,t,n){super("org.ethers.plugins.network.Ens"),xn(this,"address"),xn(this,"targetNetwork"),xn(this,"universalResolver"),Ha(this,{address:e||"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",targetNetwork:null==t?1:t,universalResolver:n})}toString(){return`${this.name} { address: ${this.address}, targetNetwork: ${this.targetNetwork}, universalResolver: ${this.universalResolver} }`}clone(){return new xy(this.address,this.targetNetwork,this.universalResolver)}}class Ny extends Cy{constructor(e,t){super("org.ethers.plugins.network.FetchUrlFeeDataPlugin"),Dn(this,ze,void 0),Dn(this,$e,void 0),Bn(this,ze,e),Bn(this,$e,t)}get url(){return Pn(this,ze)}get processFunc(){return Pn(this,$e)}toString(){return`${this.name} { url: ${this.url} }`}clone(){return this}}ze=new WeakMap,$e=new WeakMap;const Py=Symbol.for("nodejs.util.inspect.custom"),Dy=new Map;Ke=new WeakMap,Qe=new WeakMap,Je=new WeakMap;let By=class e{constructor(e,t){Dn(this,Ke,void 0),Dn(this,Qe,void 0),Dn(this,Je,void 0),Bn(this,Ke,e),Bn(this,Qe,yc(t)),Bn(this,Je,new Map)}[Py](){return this.toString()}toString(){const e=[];for(const t of Pn(this,Je).values())e.push(t.toString());return`Network { name: ${this.name}, chainId: ${this.chainId}, plugins: [ ${e.join(", ")} ] }`}toJSON(){return{name:this.name,chainId:String(this.chainId)}}get name(){return Pn(this,Ke)}set name(e){Bn(this,Ke,e)}get chainId(){return Pn(this,Qe)}set chainId(e){Bn(this,Qe,yc(e,"chainId"))}matches(e){if(null==e)return!1;if("string"==typeof e){try{return this.chainId===yc(e)}catch(t){}return this.name===e}if("number"==typeof e||"bigint"==typeof e){try{return this.chainId===yc(e)}catch(t){}return!1}if("object"==typeof e){if(null!=e.chainId){try{return this.chainId===yc(e.chainId)}catch(t){}return!1}return null!=e.name&&this.name===e.name}return!1}get plugins(){return Array.from(Pn(this,Je).values())}attachPlugin(e){if(Pn(this,Je).get(e.name))throw new Error(`cannot replace existing plugin: ${e.name} `);return Pn(this,Je).set(e.name,e.clone()),this}getPlugin(e){return Pn(this,Je).get(e)||null}getPlugins(e){return this.plugins.filter((t=>t.name.split("#")[0]===e))}clone(){const t=new e(this.name,this.chainId);return this.plugins.forEach((e=>{t.attachPlugin(e.clone())})),t}computeIntrinsicGas(e){const t=this.getPlugin("org.ethers.plugins.network.GasCost")||new Oy;let n=t.txBase;if(null==e.to&&(n+=t.txCreate),e.data)for(let r=2;r<e.data.length;r+=2)"00"===e.data.substring(r,r+2)?n+=t.txDataZero:n+=t.txDataNonzero;if(e.accessList){const r=vf(e.accessList);for(const e in r)n+=t.txAccessListAddress+t.txAccessListStorageKey*r[e].storageKeys.length}return n}static from(t){if(function(){if(My)return;function e(e,t,n){const r=function(){const r=new By(e,t);return null!=n.ensNetwork&&r.attachPlugin(new xy(null,n.ensNetwork,n.ensUniversalResolver)),r.attachPlugin(new Oy),(n.plugins||[]).forEach((e=>{r.attachPlugin(e)})),r};By.register(e,r),By.register(t,r),n.altNames&&n.altNames.forEach((e=>{By.register(e,r)}))}My=!0;const t="0xeEeEEEeE14D718C2B47D9923Deab1335E144EeEe";e("mainnet",1,{ensUniversalResolver:t,ensNetwork:1,altNames:["homestead"]}),e("ropsten",3,{ensNetwork:3}),e("rinkeby",4,{ensNetwork:4}),e("goerli",5,{ensNetwork:5}),e("kovan",42,{ensNetwork:42}),e("sepolia",11155111,{ensUniversalResolver:t,ensNetwork:11155111}),e("holesky",17e3,{ensNetwork:17e3}),e("classic",61,{}),e("classicKotti",6,{}),e("arbitrum",42161,{ensNetwork:1}),e("arbitrum-goerli",421613,{}),e("arbitrum-sepolia",421614,{}),e("base",8453,{ensNetwork:1}),e("base-goerli",84531,{}),e("base-sepolia",84532,{}),e("bnb",56,{ensNetwork:1}),e("bnbt",97,{}),e("filecoin",314,{}),e("filecoin-calibration",314159,{}),e("linea",59144,{ensNetwork:1}),e("linea-goerli",59140,{}),e("linea-sepolia",59141,{}),e("matic",137,{ensNetwork:1,plugins:[Ly("https://gasstation.polygon.technology/v2")]}),e("matic-amoy",80002,{}),e("matic-mumbai",80001,{altNames:["maticMumbai","maticmum"],plugins:[Ly("https://gasstation-testnet.polygon.technology/v2")]}),e("optimism",10,{ensNetwork:1,plugins:[]}),e("optimism-goerli",420,{}),e("optimism-sepolia",11155420,{}),e("xdai",100,{ensNetwork:1})}(),null==t)return e.from("mainnet");if("number"==typeof t&&(t=BigInt(t)),"string"==typeof t||"bigint"==typeof t){const n=Dy.get(t);if(n)return n();if("bigint"==typeof t)return new e("unknown",t);Ka(!1,"unknown network","network",t)}if("function"==typeof t.clone){return t.clone()}if("object"==typeof t){Ka("string"==typeof t.name&&"number"==typeof t.chainId,"invalid network object name or chainId","network",t);const n=new e(t.name,t.chainId),r=t;return(r.ensAddress||null!=r.ensNetwork||r.ensUniversalResolver)&&n.attachPlugin(new xy(r.ensAddress,r.ensNetwork,r.ensUniversalResolver)),n}Ka(!1,"invalid network","network",t)}static register(e,t){"number"==typeof e&&(e=BigInt(e));const n=Dy.get(e);n&&Ka(!1,`conflicting network for ${JSON.stringify(n.name)}`,"nameOrChainId",e),Dy.set(e,t)}};function Uy(e,t){const n=String(e);if(!n.match(/^[0-9.]+$/))throw new Error(`invalid gwei value: ${e}`);const r=n.split(".");if(1===r.length&&r.push(""),2!==r.length)throw new Error(`invalid gwei value: ${e}`);for(;r[1].length<t;)r[1]+="0";if(r[1].length>9){let e=BigInt(r[1].substring(0,9));r[1].substring(9).match(/^0+$/)||e++,r[1]=e.toString()}return BigInt(r[0]+r[1])}function Ly(e){return new Ny(e,(async(e,t,n)=>{let r;n.setHeader("User-Agent","ethers");try{const[t,s]=await Promise.all([n.send(),e()]);r=t;const i=r.bodyJson.standard;return{gasPrice:s.gasPrice,maxFeePerGas:Uy(i.maxFee,9),maxPriorityFeePerGas:Uy(i.maxPriorityFee,9)}}catch(s){$a(!1,`error encountered with polygon gas station (${JSON.stringify(n.url)})`,"SERVER_ERROR",{request:n,response:r,error:s})}}))}let My=!1;function Fy(e){return JSON.parse(JSON.stringify(e))}class jy{constructor(e){Dn(this,tt),Dn(this,Ye,void 0),Dn(this,Ze,void 0),Dn(this,Xe,void 0),Dn(this,et,void 0),Bn(this,Ye,e),Bn(this,Ze,null),Bn(this,Xe,4e3),Bn(this,et,-2)}get pollingInterval(){return Pn(this,Xe)}set pollingInterval(e){Bn(this,Xe,e)}start(){Pn(this,Ze)||(Bn(this,Ze,Pn(this,Ye)._setTimeout(Ln(this,tt,nt).bind(this),Pn(this,Xe))),Ln(this,tt,nt).call(this))}stop(){Pn(this,Ze)&&(Pn(this,Ye)._clearTimeout(Pn(this,Ze)),Bn(this,Ze,null))}pause(e){this.stop(),e&&Bn(this,et,-2)}resume(){this.start()}}Ye=new WeakMap,Ze=new WeakMap,Xe=new WeakMap,et=new WeakMap,tt=new WeakSet,nt=async function(){try{const e=await Pn(this,Ye).getBlockNumber();if(-2===Pn(this,et))return void Bn(this,et,e);if(e!==Pn(this,et)){for(let t=Pn(this,et)+1;t<=e;t++){if(null==Pn(this,Ze))return;await Pn(this,Ye).emit("block",t)}Bn(this,et,e)}}catch(e){}null!=Pn(this,Ze)&&Bn(this,Ze,Pn(this,Ye)._setTimeout(Ln(this,tt,nt).bind(this),Pn(this,Xe)))};class Gy{constructor(e){Dn(this,rt,void 0),Dn(this,st,void 0),Dn(this,it,void 0),Bn(this,rt,e),Bn(this,it,!1),Bn(this,st,(e=>{this._poll(e,Pn(this,rt))}))}async _poll(e,t){throw new Error("sub-classes must override this")}start(){Pn(this,it)||(Bn(this,it,!0),Pn(this,st).call(this,-2),Pn(this,rt).on("block",Pn(this,st)))}stop(){Pn(this,it)&&(Bn(this,it,!1),Pn(this,rt).off("block",Pn(this,st)))}pause(e){this.stop()}resume(){this.start()}}rt=new WeakMap,st=new WeakMap,it=new WeakMap;class Hy extends Gy{constructor(e,t){super(e),Dn(this,ot,void 0),Dn(this,at,void 0),Bn(this,ot,t),Bn(this,at,-2)}pause(e){e&&Bn(this,at,-2),super.pause(e)}async _poll(e,t){const n=await t.getBlock(Pn(this,ot));null!=n&&(-2===Pn(this,at)?Bn(this,at,n.number):n.number>Pn(this,at)&&(t.emit(Pn(this,ot),n.number),Bn(this,at,n.number)))}}ot=new WeakMap,at=new WeakMap;class Vy extends Gy{constructor(e,t){super(e),Dn(this,ct,void 0),Bn(this,ct,Fy(t))}async _poll(e,t){throw new Error("@TODO")}}ct=new WeakMap;class qy extends Gy{constructor(e,t){super(e),Dn(this,lt,void 0),Bn(this,lt,t)}async _poll(e,t){const n=await t.getTransactionReceipt(Pn(this,lt));n&&t.emit(Pn(this,lt),n)}}lt=new WeakMap;class Wy{constructor(e,t){Dn(this,gt),Dn(this,ut,void 0),Dn(this,ht,void 0),Dn(this,dt,void 0),Dn(this,ft,void 0),Dn(this,pt,void 0),Bn(this,ut,e),Bn(this,ht,Fy(t)),Bn(this,dt,Ln(this,gt,mt).bind(this)),Bn(this,ft,!1),Bn(this,pt,-2)}start(){Pn(this,ft)||(Bn(this,ft,!0),-2===Pn(this,pt)&&Pn(this,ut).getBlockNumber().then((e=>{Bn(this,pt,e)})),Pn(this,ut).on("block",Pn(this,dt)))}stop(){Pn(this,ft)&&(Bn(this,ft,!1),Pn(this,ut).off("block",Pn(this,dt)))}pause(e){this.stop(),e&&Bn(this,pt,-2)}resume(){this.start()}}ut=new WeakMap,ht=new WeakMap,dt=new WeakMap,ft=new WeakMap,pt=new WeakMap,gt=new WeakSet,mt=async function(e){if(-2===Pn(this,pt))return;const t=Fy(Pn(this,ht));t.fromBlock=Pn(this,pt)+1,t.toBlock=e;const n=await Pn(this,ut).getLogs(t);if(0!==n.length)for(const r of n)Pn(this,ut).emit(Pn(this,ht),r),Bn(this,pt,r.blockNumber);else Pn(this,pt)<e-60&&Bn(this,pt,e-60)};const zy=BigInt(2);function $y(e){return new Promise((t=>{setTimeout(t,e)}))}function Ky(e){return e&&"function"==typeof e.then}function Qy(e,t){return e+":"+JSON.stringify(t,((e,t)=>{if(null==t)return"null";if("bigint"==typeof t)return`bigint:${t.toString()}`;if("string"==typeof t)return t.toLowerCase();if("object"==typeof t&&!Array.isArray(t)){const e=Object.keys(t);return e.sort(),e.reduce(((e,n)=>(e[n]=t[n],e)),{})}return t}))}class Jy{constructor(e){xn(this,"name"),Ha(this,{name:e})}start(){}stop(){}pause(e){}resume(){}}function Yy(e){return(e=Array.from(new Set(e).values())).sort(),e}async function Zy(e,t){if(null==e)throw new Error("invalid event");if(Array.isArray(e)&&(e={topics:e}),"string"==typeof e)switch(e){case"block":case"debug":case"error":case"finalized":case"network":case"pending":case"safe":return{type:e,tag:e}}if(nc(e,32)){const t=e.toLowerCase();return{type:"transaction",tag:Qy("tx",{hash:t}),hash:t}}if(e.orphan){const t=e;return{type:"orphan",tag:Qy("orphan",t),filter:(n=t,JSON.parse(JSON.stringify(n)))}}var n;if(e.address||e.topics){const n=e,r={topics:(n.topics||[]).map((e=>null==e?null:Array.isArray(e)?Yy(e.map((e=>e.toLowerCase()))):e.toLowerCase()))};if(n.address){const e=[],s=[],i=n=>{nc(n)?e.push(n):s.push((async()=>{e.push(await Yd(n,t))})())};Array.isArray(n.address)?n.address.forEach(i):i(n.address),s.length&&await Promise.all(s),r.address=Yy(e.map((e=>e.toLowerCase())))}return{filter:r,tag:Qy("event",r),type:"event"}}Ka(!1,"unknown ProviderEvent","event",e)}function Xy(){return(new Date).getTime()}const ew={cacheTimeout:250,pollingInterval:4e3};class tw{constructor(e,t){if(Dn(this,xt),Dn(this,Pt),Dn(this,Bt),Dn(this,Lt),Dn(this,Ft),Dn(this,Gt),Dn(this,Vt),Dn(this,Wt),Dn(this,yt,void 0),Dn(this,wt,void 0),Dn(this,bt,void 0),Dn(this,_t,void 0),Dn(this,At,void 0),Dn(this,vt,void 0),Dn(this,Et,void 0),Dn(this,kt,void 0),Dn(this,St,void 0),Dn(this,Tt,void 0),Dn(this,Rt,void 0),Dn(this,It,void 0),Dn(this,Ct,void 0),Dn(this,Ot,void 0),Bn(this,Ot,Object.assign({},ew,t||{})),"any"===e)Bn(this,vt,!0),Bn(this,At,null);else if(e){const t=By.from(e);Bn(this,vt,!1),Bn(this,At,Promise.resolve(t)),setTimeout((()=>{this.emit("network",t,null)}),0)}else Bn(this,vt,!1),Bn(this,At,null);Bn(this,kt,-1),Bn(this,Et,new Map),Bn(this,yt,new Map),Bn(this,wt,new Map),Bn(this,bt,null),Bn(this,_t,!1),Bn(this,St,1),Bn(this,Tt,new Map),Bn(this,Rt,!1),Bn(this,It,0),Bn(this,Ct,[])}get _requestRate(){const e=Pn(this,It);return 0==e?null:e}set _requestRate(e){(null==e||e<0)&&(e=0),Bn(this,It,Ac(e))}get pollingInterval(){return Pn(this,Ot).pollingInterval}get provider(){return this}get plugins(){return Array.from(Pn(this,wt).values())}attachPlugin(e){if(Pn(this,wt).get(e.name))throw new Error(`cannot replace existing plugin: ${e.name} `);return Pn(this,wt).set(e.name,e.connect(this)),this}getPlugin(e){return Pn(this,wt).get(e)||null}get disableCcipRead(){return Pn(this,Rt)}set disableCcipRead(e){Bn(this,Rt,!!e)}async ccipReadFetch(e,t,n){if(this.disableCcipRead||0===n.length||null==e.to)return null;const r=e.to.toLowerCase(),s=t.toLowerCase(),i=[];for(let a=0;a<n.length;a++){const t=n[a],c=t.replace("{sender}",r).replace("{data}",s),l=new Kc(c);-1===t.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 e=u.bodyJson;if(e.data)return this.emit("debug",{action:"receiveCcipReadFetchResult",request:l,result:e}),e.data;e.message&&(h=e.message),this.emit("debug",{action:"receiveCcipReadFetchError",request:l,result:e})}catch(o){}$a(u.statusCode<400||u.statusCode>=500,`response not found during CCIP fetch: ${h}`,"OFFCHAIN_FAULT",{reason:"404_MISSING_RESOURCE",transaction:e,info:{url:t,errorMessage:h}}),i.push(h)}$a(!1,`error encountered during CCIP fetch: ${i.map((e=>JSON.stringify(e))).join(", ")}`,"OFFCHAIN_FAULT",{reason:"500_SERVER_ERROR",transaction:e,info:{urls:n,errorMessages:i}})}_wrapBlock(e,t){return new Rm(function(e){const t=ky(e);return t.transactions=e.transactions.map((e=>"string"==typeof e?e:Ry(e))),t}(e),this)}_wrapLog(e,t){return new Im(function(e){return Ey(e)}(e),this)}_wrapTransactionReceipt(e,t){return new Cm(function(e){return Ty(e)}(e),this)}_wrapTransactionResponse(e,t){return new Om(Ry(e),this)}_detectNetwork(){$a(!1,"sub-classes must implement this","UNSUPPORTED_OPERATION",{operation:"_detectNetwork"})}async _perform(e){$a(!1,`unsupported method: ${e.method}`,"UNSUPPORTED_OPERATION",{operation:e.method,info:e})}async getBlockNumber(){const e=Ac(await Ln(this,Pt,Dt).call(this,{method:"getBlockNumber"}),"%response");return Pn(this,kt)>=0&&Bn(this,kt,e),e}_getAddress(e){return Yd(e,this)}_getBlockTag(e){if(null==e)return"latest";switch(e){case"earliest":return"0x0";case"finalized":case"latest":case"pending":case"safe":return e}return nc(e)?nc(e,32)?e:kc(e):("bigint"==typeof e&&(e=Ac(e,"blockTag")),"number"==typeof e?e>=0?kc(e):Pn(this,kt)>=0?kc(Pn(this,kt)+e):this.getBlockNumber().then((t=>kc(t+e))):void Ka(!1,"invalid blockTag","blockTag",e))}_getFilter(e){const t=(e.topics||[]).map((e=>null==e?null:Array.isArray(e)?Yy(e.map((e=>e.toLowerCase()))):e.toLowerCase())),n="blockHash"in e?e.blockHash:void 0,r=(e,r,s)=>{let i;switch(e.length){case 0:break;case 1:i=e[0];break;default:e.sort(),i=e}if(n&&(null!=r||null!=s))throw new Error("invalid filter");const o={};return i&&(o.address=i),t.length&&(o.topics=t),r&&(o.fromBlock=r),s&&(o.toBlock=s),n&&(o.blockHash=n),o};let s,i,o=[];if(e.address)if(Array.isArray(e.address))for(const a of e.address)o.push(this._getAddress(a));else o.push(this._getAddress(e.address));return"fromBlock"in e&&(s=this._getBlockTag(e.fromBlock)),"toBlock"in e&&(i=this._getBlockTag(e.toBlock)),o.filter((e=>"string"!=typeof e)).length||null!=s&&"string"!=typeof s||null!=i&&"string"!=typeof i?Promise.all([Promise.all(o),s,i]).then((e=>r(e[0],e[1],e[2]))):r(o,s,i)}_getTransactionRequest(e){const t=Tm(e),n=[];if(["to","from"].forEach((e=>{if(null==t[e])return;const r=Yd(t[e],this);Ky(r)?n.push(async function(){t[e]=await r}()):t[e]=r})),null!=t.blockTag){const e=this._getBlockTag(t.blockTag);Ky(e)?n.push(async function(){t.blockTag=await e}()):t.blockTag=e}return n.length?async function(){return await Promise.all(n),t}():t}async getNetwork(){if(null==Pn(this,At)){const e=(async()=>{try{const e=await this._detectNetwork();return this.emit("network",e,null),e}catch(t){throw Pn(this,At)===e&&Bn(this,At,null),t}})();return Bn(this,At,e),(await e).clone()}const e=Pn(this,At),[t,n]=await Promise.all([e,this._detectNetwork()]);return t.chainId!==n.chainId&&(Pn(this,vt)?(this.emit("network",n,t),Pn(this,At)===e&&Bn(this,At,Promise.resolve(n))):$a(!1,`network changed: ${t.chainId} => ${n.chainId} `,"NETWORK_ERROR",{event:"changed"})),t.clone()}async getFeeData(){const e=await this.getNetwork(),t=async()=>{const{_block:t,gasPrice:n,priorityFee:r}=await Ga({_block:Ln(this,Gt,Ht).call(this,"latest",!1),gasPrice:(async()=>{try{return yc(await Ln(this,Pt,Dt).call(this,{method:"getGasPrice"}),"%response")}catch(e){}return null})(),priorityFee:(async()=>{try{return yc(await Ln(this,Pt,Dt).call(this,{method:"getPriorityFee"}),"%response")}catch(e){}return null})()});let s=null,i=null;const o=this._wrapBlock(t,e);return o&&o.baseFeePerGas&&(i=null!=r?r:BigInt("1000000000"),s=o.baseFeePerGas*zy+i),new Sm(n,s,i)},n=e.getPlugin("org.ethers.plugins.network.FetchUrlFeeDataPlugin");if(n){const e=new Kc(n.url),r=await n.processFunc(t,this,e);return new Sm(r.gasPrice,r.maxFeePerGas,r.maxPriorityFeePerGas)}return await t()}async estimateGas(e){let t=this._getTransactionRequest(e);return Ky(t)&&(t=await t),yc(await Ln(this,Pt,Dt).call(this,{method:"estimateGas",transaction:t}),"%response")}async call(e){const{tx:t,blockTag:n}=await Ga({tx:this._getTransactionRequest(e),blockTag:this._getBlockTag(e.blockTag)});return await Ln(this,Lt,Mt).call(this,Ln(this,Bt,Ut).call(this,t,n,e.enableCcipRead?0:-1))}async getBalance(e,t){return yc(await Ln(this,Ft,jt).call(this,{method:"getBalance"},e,t),"%response")}async getTransactionCount(e,t){return Ac(await Ln(this,Ft,jt).call(this,{method:"getTransactionCount"},e,t),"%response")}async getCode(e,t){return ic(await Ln(this,Ft,jt).call(this,{method:"getCode"},e,t))}async getStorage(e,t,n){const r=yc(t,"position");return ic(await Ln(this,Ft,jt).call(this,{method:"getStorage",position:r},e,n))}async broadcastTransaction(e){const{blockNumber:t,hash:n,network:r}=await Ga({blockNumber:this.getBlockNumber(),hash:this._perform({method:"broadcastTransaction",signedTransaction:e}),network:this.getNetwork()}),s=qf.from(e);if(s.hash!==n)throw new Error("@TODO: the returned hash did not match");return this._wrapTransactionResponse(s,r).replaceableTransaction(t)}async getBlock(e,t){const{network:n,params:r}=await Ga({network:this.getNetwork(),params:Ln(this,Gt,Ht).call(this,e,!!t)});return null==r?null:this._wrapBlock(r,n)}async getTransaction(e){const{network:t,params:n}=await Ga({network:this.getNetwork(),params:Ln(this,Pt,Dt).call(this,{method:"getTransaction",hash:e})});return null==n?null:this._wrapTransactionResponse(n,t)}async getTransactionReceipt(e){const{network:t,params:n}=await Ga({network:this.getNetwork(),params:Ln(this,Pt,Dt).call(this,{method:"getTransactionReceipt",hash:e})});if(null==n)return null;if(null==n.gasPrice&&null==n.effectiveGasPrice){const t=await Ln(this,Pt,Dt).call(this,{method:"getTransaction",hash:e});if(null==t)throw new Error("report this; could not find tx or effectiveGasPrice");n.effectiveGasPrice=t.gasPrice}return this._wrapTransactionReceipt(n,t)}async getTransactionResult(e){const{result:t}=await Ga({network:this.getNetwork(),result:Ln(this,Pt,Dt).call(this,{method:"getTransactionResult",hash:e})});return null==t?null:ic(t)}async getLogs(e){let t=this._getFilter(e);Ky(t)&&(t=await t);const{network:n,params:r}=await Ga({network:this.getNetwork(),params:Ln(this,Pt,Dt).call(this,{method:"getLogs",filter:t})});return r.map((e=>this._wrapLog(e,n)))}_getProvider(e){$a(!1,"provider cannot connect to target network","UNSUPPORTED_OPERATION",{operation:"_getProvider()"})}async getResolver(e){return await gy.fromName(this,e)}async getAvatar(e){const t=await this.getResolver(e);return t?await t.getAvatar():null}async resolveName(e,t){const n=await this.getResolver(e);return n?await n.getAddress(t):null}async lookupAddress(e,t){return await gy.lookupAddress(this,e,t)}async waitForTransaction(e,t,n){const r=null!=t?t:1;return 0===r?this.getTransactionReceipt(e):new Promise((async(t,s)=>{let i=null;const o=async n=>{try{const s=await this.getTransactionReceipt(e);if(null!=s&&n-s.blockNumber+1>=r)return t(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(za("timeout","TIMEOUT",{reason:"timeout"})))}),n)),o(await this.getBlockNumber())}))}async waitForBlock(e){$a(!1,"not implemented yet","NOT_IMPLEMENTED",{operation:"waitForBlock"})}_clearTimeout(e){const t=Pn(this,Tt).get(e);t&&(t.timer&&clearTimeout(t.timer),Pn(this,Tt).delete(e))}_setTimeout(e,t){null==t&&(t=0);const n=Un(this,St)._++,r=()=>{Pn(this,Tt).delete(n),e()};if(this.paused)Pn(this,Tt).set(n,{timer:null,func:r,time:t});else{const e=setTimeout(r,t);Pn(this,Tt).set(n,{timer:e,func:r,time:Xy()})}return n}_forEachSubscriber(e){for(const t of Pn(this,yt).values())e(t.subscriber)}_getSubscriber(e){switch(e.type){case"debug":case"error":case"network":return new Jy(e.type);case"block":{const e=new jy(this);return e.pollingInterval=this.pollingInterval,e}case"safe":case"finalized":return new Hy(this,e.type);case"event":return new Wy(this,e.filter);case"transaction":return new qy(this,e.hash);case"orphan":return new Vy(this,e.filter)}throw new Error(`unsupported event: ${e.type}`)}_recoverSubscriber(e,t){for(const n of Pn(this,yt).values())if(n.subscriber===e){n.started&&n.subscriber.stop(),n.subscriber=t,n.started&&t.start(),null!=Pn(this,bt)&&t.pause(Pn(this,bt));break}}async on(e,t){const n=await Ln(this,Wt,zt).call(this,e);return n.listeners.push({listener:t,once:!1}),n.started||(n.subscriber.start(),n.started=!0,null!=Pn(this,bt)&&n.subscriber.pause(Pn(this,bt))),this}async once(e,t){const n=await Ln(this,Wt,zt).call(this,e);return n.listeners.push({listener:t,once:!0}),n.started||(n.subscriber.start(),n.started=!0,null!=Pn(this,bt)&&n.subscriber.pause(Pn(this,bt))),this}async emit(e,...t){const n=await Ln(this,Vt,qt).call(this,e,t);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 xc(this,r?null:n,e);try{n.call(this,...t,s)}catch(i){}return!r})),0===n.listeners.length&&(n.started&&n.subscriber.stop(),Pn(this,yt).delete(n.tag)),r>0}async listenerCount(e){if(e){const t=await Ln(this,Vt,qt).call(this,e);return t?t.listeners.length:0}let t=0;for(const{listeners:n}of Pn(this,yt).values())t+=n.length;return t}async listeners(e){if(e){const t=await Ln(this,Vt,qt).call(this,e);return t?t.listeners.map((({listener:e})=>e)):[]}let t=[];for(const{listeners:n}of Pn(this,yt).values())t=t.concat(n.map((({listener:e})=>e)));return t}async off(e,t){const n=await Ln(this,Vt,qt).call(this,e);if(!n)return this;if(t){const e=n.listeners.map((({listener:e})=>e)).indexOf(t);e>=0&&n.listeners.splice(e,1)}return t&&0!==n.listeners.length||(n.started&&n.subscriber.stop(),Pn(this,yt).delete(n.tag)),this}async removeAllListeners(e){if(e){const{tag:t,started:n,subscriber:r}=await Ln(this,Wt,zt).call(this,e);n&&r.stop(),Pn(this,yt).delete(t)}else for(const[t,{started:n,subscriber:r}]of Pn(this,yt))n&&r.stop(),Pn(this,yt).delete(t);return this}async addListener(e,t){return await this.on(e,t)}async removeListener(e,t){return this.off(e,t)}get destroyed(){return Pn(this,_t)}destroy(){this.removeAllListeners();for(const e of Pn(this,Tt).keys())this._clearTimeout(e);Bn(this,_t,!0)}get paused(){return null!=Pn(this,bt)}set paused(e){!!e!==this.paused&&(this.paused?this.resume():this.pause(!1))}pause(e){if(Bn(this,kt,-1),null!=Pn(this,bt)){if(Pn(this,bt)==!!e)return;$a(!1,"cannot change pause type; resume first","UNSUPPORTED_OPERATION",{operation:"pause"})}this._forEachSubscriber((t=>t.pause(e))),Bn(this,bt,!!e);for(const t of Pn(this,Tt).values())t.timer&&clearTimeout(t.timer),t.time=Xy()-t.time}resume(){if(null!=Pn(this,bt)){this._forEachSubscriber((e=>e.resume())),Bn(this,bt,null);for(const e of Pn(this,Tt).values()){let t=e.time;t<0&&(t=0),e.time=Xy(),setTimeout(e.func,t)}}}}function nw(e,t){try{const n=rw(e,t);if(n)return Bc(n)}catch(n){}return null}function rw(e,t){if("0x"===e)return null;try{const n=Ac(cc(e,t,t+32)),r=Ac(cc(e,n,n+32));return cc(e,n+32,n+32+r)}catch(n){}return null}function sw(e){const t=Ec(e);if(t.length>32)throw new Error("internal; should not happen");const n=new Uint8Array(32);return n.set(t,32-t.length),n}function iw(e){if(e.length%32==0)return e;const t=new Uint8Array(32*Math.ceil(e.length/32));return t.set(e),t}yt=new WeakMap,wt=new WeakMap,bt=new WeakMap,_t=new WeakMap,At=new WeakMap,vt=new WeakMap,Et=new WeakMap,kt=new WeakMap,St=new WeakMap,Tt=new WeakMap,Rt=new WeakMap,It=new WeakMap,Ct=new WeakMap,Ot=new WeakMap,xt=new WeakSet,Nt=function(){let e=Pn(this,It);if(0===e)return 0;const t=Pn(this,Ct),n=Xy();t.push(n);const r=n-1e3;for(;t.length&&t[0]<r;)t.shift();return t.length<e?0:t[0]+1e3-n},Pt=new WeakSet,Dt=async function(e){const t=Pn(this,Ot).cacheTimeout;if(t<0){const t=Ln(this,xt,Nt).call(this);return t&&await $y(t),await this._perform(e)}const n=Qy(e.method,e);let r=Pn(this,Et).get(n);if(!r){const s=Ln(this,xt,Nt).call(this);s&&await $y(s),r=this._perform(e),Pn(this,Et).set(n,r),setTimeout((()=>{Pn(this,Et).get(n)===r&&Pn(this,Et).delete(n)}),t)}return await r},Bt=new WeakSet,Ut=async function(e,t,n){$a(n<10,"CCIP read exceeded maximum redirections","OFFCHAIN_FAULT",{reason:"TOO_MANY_REDIRECTS",transaction:Object.assign({},e,{blockTag:t,enableCcipRead:!0})});const r=Tm(e);try{const e=Ln(this,xt,Nt).call(this);return e&&await $y(e),ic(await this._perform({method:"call",transaction:r,blockTag:t}))}catch(s){if(!this.disableCcipRead&&Wa(s)&&s.data&&n>=0&&"latest"===t&&null!=r.to&&"0x556f1830"===cc(s.data,0,4)){const e=s.data,o=await Yd(r.to,this);let a;try{a=function(e){const t={sender:"",urls:[],calldata:"",selector:"",extraData:"",errorArgs:[]};$a(ac(e)>=160,"insufficient OffchainLookup data","OFFCHAIN_FAULT",{reason:"insufficient OffchainLookup data"});const n=cc(e,0,32);$a(cc(n,0,12)===cc(cw,0,12),"corrupt OffchainLookup sender","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup sender"}),t.sender=cc(n,12);try{const n=[],r=Ac(cc(e,32,64)),s=Ac(cc(e,r,r+32)),i=cc(e,r+32);for(let e=0;e<s;e++){const t=nw(i,32*e);if(null==t)throw new Error("abort");n.push(t)}t.urls=n}catch(s){$a(!1,"corrupt OffchainLookup urls","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup urls"})}try{const n=rw(e,64);if(null==n)throw new Error("abort");t.calldata=n}catch(s){$a(!1,"corrupt OffchainLookup calldata","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup calldata"})}$a(cc(e,100,128)===cc(cw,0,28),"corrupt OffchainLookup callbaackSelector","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup callbaackSelector"}),t.selector=cc(e,96,100);try{const n=rw(e,128);if(null==n)throw new Error("abort");t.extraData=n}catch(s){$a(!1,"corrupt OffchainLookup extraData","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup extraData"})}return t.errorArgs="sender,urls,calldata,selector,extraData".split(/,/).map((e=>t[e])),t}(cc(s.data,4))}catch(i){$a(!1,i.message,"OFFCHAIN_FAULT",{reason:"BAD_DATA",transaction:r,info:{data:e}})}$a(a.sender.toLowerCase()===o.toLowerCase(),"CCIP Read sender mismatch","CALL_EXCEPTION",{action:"call",data:e,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);$a(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:oc([a.selector,aw([c,a.extraData])])};this.emit("debug",{action:"sendCcipReadCall",transaction:l});try{const e=await Ln(this,Bt,Ut).call(this,l,t,n+1);return this.emit("debug",{action:"receiveCcipReadCallResult",transaction:Object.assign({},l),result:e}),e}catch(i){throw this.emit("debug",{action:"receiveCcipReadCallError",transaction:Object.assign({},l),error:i}),i}}throw s}},Lt=new WeakSet,Mt=async function(e){const{value:t}=await Ga({network:this.getNetwork(),value:e});return t},Ft=new WeakSet,jt=async function(e,t,n){let r=this._getAddress(t),s=this._getBlockTag(n);return"string"==typeof r&&"string"==typeof s||([r,s]=await Promise.all([r,s])),await Ln(this,Lt,Mt).call(this,Ln(this,Pt,Dt).call(this,Object.assign(e,{address:r,blockTag:s})))},Gt=new WeakSet,Ht=async function(e,t){if(nc(e,32))return await Ln(this,Pt,Dt).call(this,{method:"getBlock",blockHash:e,includeTransactions:t});let n=this._getBlockTag(e);return"string"!=typeof n&&(n=await n),await Ln(this,Pt,Dt).call(this,{method:"getBlock",blockTag:n,includeTransactions:t})},Vt=new WeakSet,qt=async function(e,t){let n=await Zy(e,this);return"event"===n.type&&t&&t.length>0&&!0===t[0].removed&&(n=await Zy({orphan:"drop-log",log:t[0]},this)),Pn(this,yt).get(n.tag)||null},Wt=new WeakSet,zt=async function(e){const t=await Zy(e,this),n=t.tag;let r=Pn(this,yt).get(n);if(!r){r={subscriber:this._getSubscriber(t),tag:n,addressableMap:new WeakMap,nameMap:new Map,started:!1,listeners:[]},Pn(this,yt).set(n,r)}return r};const ow=new Uint8Array([]);function aw(e){const t=[];let n=0;for(let r=0;r<e.length;r++)t.push(ow),n+=32;for(let r=0;r<e.length;r++){const s=ec(e[r]);t[r]=sw(n),t.push(sw(s.length)),t.push(iw(s)),n+=32+32*Math.ceil(s.length/32)}return oc(t)}const cw="0x0000000000000000000000000000000000000000000000000000000000000000";function lw(e,t){if(e.provider)return e.provider;$a(!1,"missing provider","UNSUPPORTED_OPERATION",{operation:t})}async function uw(e,t){let n=Tm(t);if(null!=n.to&&(n.to=Yd(n.to,e)),null!=n.from){const t=n.from;n.from=Promise.all([e.getAddress(),Yd(t,e)]).then((([e,t])=>(Ka(e.toLowerCase()===t.toLowerCase(),"transaction from mismatch","tx.from",t),e)))}else n.from=e.getAddress();return await Ga(n)}class hw{constructor(e){xn(this,"provider"),Ha(this,{provider:e||null})}async getNonce(e){return lw(this,"getTransactionCount").getTransactionCount(await this.getAddress(),e)}async populateCall(e){return await uw(this,e)}async populateTransaction(e){const t=lw(this,"populateTransaction"),n=await uw(this,e);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){Ka(yc(n.chainId)===r.chainId,"transaction chainId mismatch","tx.chainId",e.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||Ka(!1,"pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas","tx",e):Ka(!1,"eip-1559 transaction do not support gasPrice","tx",e),2!==n.type&&null!=n.type||null==n.maxFeePerGas||null==n.maxPriorityFeePerGas)if(0===n.type||1===n.type){const e=await t.getFeeData();$a(null!=e.gasPrice,"network does not support gasPrice","UNSUPPORTED_OPERATION",{operation:"getGasPrice"}),null==n.gasPrice&&(n.gasPrice=e.gasPrice)}else{const e=await t.getFeeData();if(null==n.type)if(null!=e.maxFeePerGas&&null!=e.maxPriorityFeePerGas)if(n.authorizationList&&n.authorizationList.length?n.type=4:n.type=2,null!=n.gasPrice){const e=n.gasPrice;delete n.gasPrice,n.maxFeePerGas=e,n.maxPriorityFeePerGas=e}else null==n.maxFeePerGas&&(n.maxFeePerGas=e.maxFeePerGas),null==n.maxPriorityFeePerGas&&(n.maxPriorityFeePerGas=e.maxPriorityFeePerGas);else null!=e.gasPrice?($a(!s,"network does not support EIP-1559","UNSUPPORTED_OPERATION",{operation:"populateTransaction"}),null==n.gasPrice&&(n.gasPrice=e.gasPrice),n.type=0):$a(!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=e.maxFeePerGas),null==n.maxPriorityFeePerGas&&(n.maxPriorityFeePerGas=e.maxPriorityFeePerGas))}else n.type=2;return await Ga(n)}async populateAuthorization(e){const t=Object.assign({},e);return null==t.chainId&&(t.chainId=(await lw(this,"getNetwork").getNetwork()).chainId),null==t.nonce&&(t.nonce=await this.getNonce()),t}async estimateGas(e){return lw(this,"estimateGas").estimateGas(await this.populateCall(e))}async call(e){return lw(this,"call").call(await this.populateCall(e))}async resolveName(e){const t=lw(this,"resolveName");return await t.resolveName(e)}async sendTransaction(e){const t=lw(this,"sendTransaction"),n=await this.populateTransaction(e);delete n.from;const r=qf.from(n);return await t.broadcastTransaction(await this.signTransaction(r))}authorize(e){$a(!1,"authorization not implemented for this signer","UNSUPPORTED_OPERATION",{operation:"authorize"})}}$t=new WeakSet,Kt=function(e,t){$a(!1,`VoidSigner cannot sign ${e}`,"UNSUPPORTED_OPERATION",{operation:t})};let dw=class e extends hw{constructor(e,t){super(t),Dn(this,$t),xn(this,"address"),Ha(this,{address:e})}async getAddress(){return this.address}connect(t){return new e(this.address,t)}async signTransaction(e){Ln(this,$t,Kt).call(this,"transactions","signTransaction")}async signMessage(e){Ln(this,$t,Kt).call(this,"messages","signMessage")}async signTypedData(e,t,n){Ln(this,$t,Kt).call(this,"typed-data","signTypedData")}};class fw{constructor(e){Dn(this,tn),Dn(this,rn),Dn(this,Qt,void 0),Dn(this,Jt,void 0),Dn(this,Yt,void 0),Dn(this,Zt,void 0),Dn(this,Xt,void 0),Dn(this,en,void 0),Bn(this,Qt,e),Bn(this,Jt,null),Bn(this,Yt,Ln(this,tn,nn).bind(this)),Bn(this,Zt,!1),Bn(this,Xt,null),Bn(this,en,!1)}_subscribe(e){throw new Error("subclasses must override this")}_emitResults(e,t){throw new Error("subclasses must override this")}_recover(e){throw new Error("subclasses must override this")}start(){Pn(this,Zt)||(Bn(this,Zt,!0),Ln(this,tn,nn).call(this,-2))}stop(){Pn(this,Zt)&&(Bn(this,Zt,!1),Bn(this,en,!0),Ln(this,rn,sn).call(this),Pn(this,Qt).off("block",Pn(this,Yt)))}pause(e){e&&Ln(this,rn,sn).call(this),Pn(this,Qt).off("block",Pn(this,Yt))}resume(){this.start()}}Qt=new WeakMap,Jt=new WeakMap,Yt=new WeakMap,Zt=new WeakMap,Xt=new WeakMap,en=new WeakMap,tn=new WeakSet,nn=async function(e){try{null==Pn(this,Jt)&&Bn(this,Jt,this._subscribe(Pn(this,Qt)));let e=null;try{e=await Pn(this,Jt)}catch(t){if(!qa(t,"UNSUPPORTED_OPERATION")||"eth_newFilter"!==t.operation)throw t}if(null==e)return Bn(this,Jt,null),void Pn(this,Qt)._recoverSubscriber(this,this._recover(Pn(this,Qt)));const n=await Pn(this,Qt).getNetwork();if(Pn(this,Xt)||Bn(this,Xt,n),Pn(this,Xt).chainId!==n.chainId)throw new Error("chaid changed");if(Pn(this,en))return;const r=await Pn(this,Qt).send("eth_getFilterChanges",[e]);await this._emitResults(Pn(this,Qt),r)}catch(t){console.log("@TODO",t)}Pn(this,Qt).once("block",Pn(this,Yt))},rn=new WeakSet,sn=function(){const e=Pn(this,Jt);e&&(Bn(this,Jt,null),e.then((e=>{Pn(this,Qt).destroyed||Pn(this,Qt).send("eth_uninstallFilter",[e])})))};class pw extends fw{constructor(e,t){var n;super(e),Dn(this,on,void 0),Bn(this,on,(n=t,JSON.parse(JSON.stringify(n))))}_recover(e){return new Wy(e,Pn(this,on))}async _subscribe(e){return await e.send("eth_newFilter",[Pn(this,on)])}async _emitResults(e,t){for(const n of t)e.emit(Pn(this,on),e._wrapLog(n,e._network))}}on=new WeakMap;class gw extends fw{async _subscribe(e){return await e.send("eth_newPendingTransactionFilter",[])}async _emitResults(e,t){for(const n of t)e.emit("pending",n)}}const mw="bigint,boolean,function,number,string,symbol".split(/,/g);function yw(e){if(null==e||mw.indexOf(typeof e)>=0)return e;if("function"==typeof e.getAddress)return e;if(Array.isArray(e))return e.map(yw);if("object"==typeof e)return Object.keys(e).reduce(((t,n)=>(t[n]=e[n],t)),{});throw new Error(`should not happen: ${e} (${typeof e})`)}function ww(e){return new Promise((t=>{setTimeout(t,e)}))}function bw(e){return e?e.toLowerCase():e}function _w(e){return e&&"number"==typeof e.pollingInterval}const Aw={polling:!1,staticNetwork:null,batchStallTime:10,batchMaxSize:1<<20,batchMaxCount:100,cacheTimeout:250,pollingInterval:4e3};class vw extends hw{constructor(e,t){super(e),xn(this,"address"),Ha(this,{address:t=Kd(t)})}connect(e){$a(!1,"cannot reconnect JsonRpcSigner","UNSUPPORTED_OPERATION",{operation:"signer.connect"})}async getAddress(){return this.address}async populateTransaction(e){return await this.populateCall(e)}async sendUncheckedTransaction(e){const t=yw(e),n=[];if(t.from){const r=t.from;n.push((async()=>{const n=await Yd(r,this.provider);Ka(null!=n&&n.toLowerCase()===this.address.toLowerCase(),"from address mismatch","transaction",e),t.from=n})())}else t.from=this.address;if(null==t.gasLimit&&n.push((async()=>{t.gasLimit=await this.provider.estimateGas({...t,from:this.address})})()),null!=t.to){const e=t.to;n.push((async()=>{t.to=await Yd(e,this.provider)})())}n.length&&await Promise.all(n);const r=this.provider.getRpcTransaction(t);return this.provider.send("eth_sendTransaction",[r])}async sendTransaction(e){const t=await this.provider.getBlockNumber(),n=await this.sendUncheckedTransaction(e);return await new Promise(((e,r)=>{const s=[1e3,100];let i=0;const o=async()=>{try{const r=await this.provider.getTransaction(n);if(null!=r)return void e(r.replaceableTransaction(t))}catch(a){if(qa(a,"CANCELLED")||qa(a,"BAD_DATA")||qa(a,"NETWORK_ERROR")||qa(a,"UNSUPPORTED_OPERATION"))return null==a.info&&(a.info={}),a.info.sendTransactionHash=n,void r(a);if(qa(a,"INVALID_ARGUMENT")&&(i++,null==a.info&&(a.info={}),a.info.sendTransactionHash=n,i>10))return void r(a);this.provider.emit("error",za("failed to fetch transation after sending (will try again)","UNKNOWN_ERROR",{error:a}))}this.provider._setTimeout((()=>{o()}),s.pop()||4e3)};o()}))}async signTransaction(e){const t=yw(e);if(t.from){const n=await Yd(t.from,this.provider);Ka(null!=n&&n.toLowerCase()===this.address.toLowerCase(),"from address mismatch","transaction",e),t.from=n}else t.from=this.address;const n=this.provider.getRpcTransaction(t);return await this.provider.send("eth_signTransaction",[n])}async signMessage(e){const t="string"==typeof e?Dc(e):e;return await this.provider.send("personal_sign",[ic(t),this.address.toLowerCase()])}async signTypedData(e,t,n){const r=yw(n),s=await mg.resolveNames(e,t,r,(async e=>{const t=await Yd(e);return Ka(null!=t,"TypedData does not support null address","value",e),t}));return await this.provider.send("eth_signTypedData_v4",[this.address.toLowerCase(),JSON.stringify(mg.getPayload(s.domain,t,s.value))])}async unlock(e){return this.provider.send("personal_unlockAccount",[this.address.toLowerCase(),e,null])}async _legacySignMessage(e){const t="string"==typeof e?Dc(e):e;return await this.provider.send("eth_sign",[this.address.toLowerCase(),ic(t)])}}class Ew extends tw{constructor(e,t){super(e,t),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({},Aw,t||{})),Bn(this,ln,[]),Bn(this,un,null),Bn(this,dn,null),Bn(this,fn,null);{let e=null;const t=new Promise((t=>{e=t}));Bn(this,hn,{promise:t,resolve:e})}const n=this._getOption("staticNetwork");"boolean"==typeof n?(Ka(!n||"any"!==e,"staticNetwork cannot be used on special network 'any'","options",t),n&&null!=e&&Bn(this,dn,By.from(e))):n&&(Ka(null==e||n.matches(e),"staticNetwork MUST match network object","options",t),Bn(this,dn,n))}_getOption(e){return Pn(this,an)[e]}get _network(){return $a(Pn(this,dn),"network is not available yet","NETWORK_ERROR"),Pn(this,dn)}async _perform(e){if("call"===e.method||"estimateGas"===e.method){let t=e.transaction;if(t&&null!=t.type&&yc(t.type)&&null==t.maxFeePerGas&&null==t.maxPriorityFeePerGas){const n=await this.getFeeData();null==n.maxFeePerGas&&null==n.maxPriorityFeePerGas&&(e=Object.assign({},e,{transaction:Object.assign({},t,{type:void 0})}))}}const t=this.getRpcRequest(e);return null!=t?await this.send(t.method,t.args):super._perform(e)}async _detectNetwork(){const e=this._getOption("staticNetwork");if(e){if(!0!==e)return e;if(Pn(this,dn))return Pn(this,dn)}return Pn(this,fn)?await Pn(this,fn):this.ready?(Bn(this,fn,(async()=>{try{const e=By.from(yc(await this.send("eth_chainId",[])));return Bn(this,fn,null),e}catch(e){throw Bn(this,fn,null),e}})()),await Pn(this,fn)):(Bn(this,fn,(async()=>{const e={id:Un(this,cn)._++,method:"eth_chainId",params:[],jsonrpc:"2.0"};let t;this.emit("debug",{action:"sendRpcPayload",payload:e});try{t=(await this._send(e))[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:t}),"result"in t)return By.from(yc(t.result));throw this.getRpcError(e,t)})()),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(e){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",za("failed to bootstrap network detection","NETWORK_ERROR",{event:"initial-network-discovery",info:{error:e}})),await ww(1e3)}Ln(this,pn,gn).call(this)})())}async _waitUntilReady(){if(null!=Pn(this,hn))return await Pn(this,hn).promise}_getSubscriber(e){return"pending"===e.type?new gw(this):"event"===e.type?this._getOption("polling")?new Wy(this,e.filter):new pw(this,e.filter):"orphan"===e.type&&"drop-log"===e.filter.orphan?new Jy("orphan"):super._getSubscriber(e)}get ready(){return null==Pn(this,hn)}getRpcTransaction(e){const t={};return["chainId","gasLimit","gasPrice","type","maxFeePerGas","maxPriorityFeePerGas","nonce","value"].forEach((n=>{if(null==e[n])return;let r=n;"gasLimit"===n&&(r="gas"),t[r]=kc(yc(e[n],`tx.${n}`))})),["from","to","data"].forEach((n=>{null!=e[n]&&(t[n]=ic(e[n]))})),e.accessList&&(t.accessList=vf(e.accessList)),e.blobVersionedHashes&&(t.blobVersionedHashes=e.blobVersionedHashes.map((e=>e.toLowerCase()))),e.authorizationList&&(t.authorizationList=e.authorizationList.map((e=>{const t=Ef(e);return{address:t.address,nonce:kc(t.nonce),chainId:kc(t.chainId),yParity:kc(t.signature.yParity),r:kc(t.signature.r),s:kc(t.signature.s)}}))),t}getRpcRequest(e){switch(e.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:[bw(e.address),e.blockTag]};case"getTransactionCount":return{method:"eth_getTransactionCount",args:[bw(e.address),e.blockTag]};case"getCode":return{method:"eth_getCode",args:[bw(e.address),e.blockTag]};case"getStorage":return{method:"eth_getStorageAt",args:[bw(e.address),"0x"+e.position.toString(16),e.blockTag]};case"broadcastTransaction":return{method:"eth_sendRawTransaction",args:[e.signedTransaction]};case"getBlock":if("blockTag"in e)return{method:"eth_getBlockByNumber",args:[e.blockTag,!!e.includeTransactions]};if("blockHash"in e)return{method:"eth_getBlockByHash",args:[e.blockHash,!!e.includeTransactions]};break;case"getTransaction":return{method:"eth_getTransactionByHash",args:[e.hash]};case"getTransactionReceipt":return{method:"eth_getTransactionReceipt",args:[e.hash]};case"call":return{method:"eth_call",args:[this.getRpcTransaction(e.transaction),e.blockTag]};case"estimateGas":return{method:"eth_estimateGas",args:[this.getRpcTransaction(e.transaction)]};case"getLogs":return e.filter&&null!=e.filter.address&&(Array.isArray(e.filter.address)?e.filter.address=e.filter.address.map(bw):e.filter.address=bw(e.filter.address)),{method:"eth_getLogs",args:[e.filter]}}return null}getRpcError(e,t){const{method:n}=e,{error:r}=t;if("eth_estimateGas"===n&&r.message){const t=r.message;if(!t.match(/revert/i)&&t.match(/insufficient funds/i))return za("insufficient funds","INSUFFICIENT_FUNDS",{transaction:e.params[0],info:{payload:e,error:r}});if(t.match(/nonce/i)&&t.match(/too low/i))return za("nonce has already been used","NONCE_EXPIRED",{transaction:e.params[0],info:{payload:e,error:r}})}if("eth_call"===n||"eth_estimateGas"===n){const t=Tw(r),s=pm.getBuiltinCallException("eth_call"===n?"call":"estimateGas",e.params[0],t?t.data:null);return s.info={error:r,payload:e},s}const s=JSON.stringify(function(e){const t=[];return Rw(e,t),t}(r));if("string"==typeof r.message&&r.message.match(/user denied|ethers-user-denied/i)){return za("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:e,error:r}})}if("eth_sendRawTransaction"===n||"eth_sendTransaction"===n){const t=e.params[0];if(s.match(/insufficient funds|base fee exceeds gas limit/i))return za("insufficient funds for intrinsic transaction cost","INSUFFICIENT_FUNDS",{transaction:t,info:{error:r}});if(s.match(/nonce/i)&&s.match(/too low/i))return za("nonce has already been used","NONCE_EXPIRED",{transaction:t,info:{error:r}});if(s.match(/replacement transaction/i)&&s.match(/underpriced/i))return za("replacement fee too low","REPLACEMENT_UNDERPRICED",{transaction:t,info:{error:r}});if(s.match(/only replay-protected/i))return za("legacy pre-eip-155 transactions not supported","UNSUPPORTED_OPERATION",{operation:n,info:{transaction:t,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?za("unsupported operation","UNSUPPORTED_OPERATION",{operation:e.method,info:{error:r,payload:e}}):za("could not coalesce error","UNKNOWN_ERROR",{error:r,payload:e})}send(e,t){if(this.destroyed)return Promise.reject(za("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:e}));const n=Un(this,cn)._++,r=new Promise(((r,s)=>{Pn(this,ln).push({resolve:r,reject:s,payload:{method:e,params:t,id:n,jsonrpc:"2.0"}})}));return Ln(this,pn,gn).call(this),r}async getSigner(e){null==e&&(e=0);const t=this.send("eth_accounts",[]);if("number"==typeof e){const n=await t;if(e>=n.length)throw new Error("no such account");return new vw(this,n[e])}const{accounts:n}=await Ga({network:this.getNetwork(),accounts:t});e=Kd(e);for(const r of n)if(Kd(r)===e)return new vw(this,e);throw new Error("invalid account")}async listAccounts(){return(await this.send("eth_accounts",[])).map((e=>new vw(this,e)))}destroy(){Pn(this,un)&&(clearTimeout(Pn(this,un)),Bn(this,un,null));for(const{payload:e,reject:t}of Pn(this,ln))t(za("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:e.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 e=1===this._getOption("batchMaxCount")?0:this._getOption("batchStallTime");Bn(this,un,setTimeout((()=>{Bn(this,un,null);const e=Pn(this,ln);for(Bn(this,ln,[]);e.length;){const t=[e.shift()];for(;e.length&&t.length!==Pn(this,an).batchMaxCount;){t.push(e.shift());if(JSON.stringify(t.map((e=>e.payload))).length>Pn(this,an).batchMaxSize){e.unshift(t.pop());break}}(async()=>{const e=1===t.length?t[0].payload:t.map((e=>e.payload));this.emit("debug",{action:"sendRpcPayload",payload:e});try{const n=await this._send(e);this.emit("debug",{action:"receiveRpcResult",result:n});for(const{resolve:e,reject:r,payload:s}of t){if(this.destroyed){r(za("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:s.method}));continue}const t=n.filter((e=>e.id===s.id))[0];if(null!=t)"error"in t?r(this.getRpcError(s,t)):e(t.result);else{const e=za("missing response for request","BAD_DATA",{value:n,info:{payload:s}});this.emit("error",e),r(e)}}}catch(n){this.emit("debug",{action:"receiveRpcError",error:n});for(const{reject:e}of t)e(n)}})()}}),e))};class kw extends Ew{constructor(e,t){super(e,t),Dn(this,mn,void 0);let n=this._getOption("pollingInterval");null==n&&(n=Aw.pollingInterval),Bn(this,mn,n)}_getSubscriber(e){const t=super._getSubscriber(e);return _w(t)&&(t.pollingInterval=Pn(this,mn)),t}get pollingInterval(){return Pn(this,mn)}set pollingInterval(e){if(!Number.isInteger(e)||e<0)throw new Error("invalid interval");Bn(this,mn,e),this._forEachSubscriber((e=>{_w(e)&&(e.pollingInterval=Pn(this,mn))}))}}mn=new WeakMap;class Sw extends kw{constructor(e,t,n){null==e&&(e="http://localhost:8545"),super(t,n),Dn(this,yn,void 0),Bn(this,yn,"string"==typeof e?new Kc(e):e.clone())}_getConnection(){return Pn(this,yn).clone()}async send(e,t){return await this._start(),await super.send(e,t)}async _send(e){const t=this._getConnection();t.body=JSON.stringify(e),t.setHeader("content-type","application/json");const n=await t.send();n.assertOk();let r=n.bodyJson;return Array.isArray(r)||(r=[r]),r}}function Tw(e){if(null==e)return null;if("string"==typeof e.message&&e.message.match(/revert/i)&&nc(e.data))return{message:e.message,data:e.data};if("object"==typeof e){for(const t in e){const n=Tw(e[t]);if(n)return n}return null}if("string"==typeof e)try{return Tw(JSON.parse(e))}catch(t){}return null}function Rw(e,t){if(null!=e){if("string"==typeof e.message&&t.push(e.message),"object"==typeof e)for(const n in e)Rw(e[n],t);if("string"==typeof e)try{return Rw(JSON.parse(e),t)}catch(n){}}}yn=new WeakMap;wn=new WeakMap;let Iw=class e extends hw{constructor(e,t){super(t),xn(this,"address"),Dn(this,wn,void 0),Ka(e&&"function"==typeof e.sign,"invalid private key","privateKey","[ REDACTED ]"),Bn(this,wn,e);Ha(this,{address:kf(this.signingKey.publicKey)})}get signingKey(){return Pn(this,wn)}get privateKey(){return this.signingKey.privateKey}async getAddress(){return this.address}connect(t){return new e(Pn(this,wn),t)}async signTransaction(e){e=Tm(e);const{to:t,from:n}=await Ga({to:e.to?Yd(e.to,this):void 0,from:e.from?Yd(e.from,this):void 0});null!=t&&(e.to=t),null!=n&&(e.from=n),null!=e.from&&(Ka(Kd(e.from)===this.address,"transaction from address mismatch","tx.from",e.from),delete e.from);const r=qf.from(e);return r.signature=this.signingKey.sign(r.unsignedHash),r.serialized}async signMessage(e){return this.signMessageSync(e)}signMessageSync(e){return this.signingKey.sign(function(e){return"string"==typeof e&&(e=Dc(e)),Bu(oc([Dc("Ethereum Signed Message:\n"),Dc(String(e.length)),e]))}(e)).serialized}authorizeSync(e){Ka("string"==typeof e.address,"invalid address for authorizeSync","auth.address",e);const t=this.signingKey.sign(function(e){return Ka("string"==typeof e.address,"invalid address for hashAuthorization","auth.address",e),Bu(oc(["0x05",ol([null!=e.chainId?Ec(e.chainId):"0x",Kd(e.address),null!=e.nonce?Ec(e.nonce):"0x"])]))}(e));return Object.assign({},{address:Kd(e.address),nonce:yc(e.nonce||0),chainId:yc(e.chainId||0)},{signature:t})}async authorize(e){return e=Object.assign({},e,{address:await Yd(e.address,this)}),this.authorizeSync(await this.populateAuthorization(e))}async signTypedData(e,t,n){const r=await mg.resolveNames(e,t,n,(async e=>{$a(null!=this.provider,"cannot resolve ENS names without a provider","UNSUPPORTED_OPERATION",{operation:"resolveName",info:{name:e}});const t=await this.provider.resolveName(e);return $a(null!=t,"unconfigured ENS name","UNCONFIGURED_NAME",{value:e}),t}));return this.signingKey.sign(mg.hash(r.domain,t,r.value)).serialized}};const Cw=" !#$%&'()*+,-./<=>?@[]^_`{|}~",Ow=/^[a-z]*$/i;function xw(e,t){let n=97;return e.reduce(((e,r)=>(r===t?n++:r.match(Ow)?e.push(String.fromCharCode(n)+r):(n=97,e.push(r)),e)),[])}function Nw(e){return Ka("0"===e[0],"unsupported auwl data","data",e),function(e,t){for(let s=28;s>=0;s--)e=e.split(Cw[s]).join(t.substring(2*s,2*s+2));const n=[],r=e.replace(/(:|([0-9])|([A-Z][a-z]*))/g,((e,t,r,s)=>{if(r)for(let i=parseInt(r);i>=0;i--)n.push(";");else n.push(t.toLowerCase());return""}));if(r)throw new Error(`leftovers: ${JSON.stringify(r)}`);return xw(xw(n,";"),":")}(e.substring(59),e.substring(1,59))}class Pw{constructor(e){xn(this,"locale"),Ha(this,{locale:e})}split(e){return e.toLowerCase().split(/\s+/g)}join(e){return e.join(" ")}}class Dw extends Pw{constructor(e,t,n){super(e),Dn(this,vn),Dn(this,bn,void 0),Dn(this,_n,void 0),Dn(this,An,void 0),Bn(this,bn,t),Bn(this,_n,n),Bn(this,An,null)}get _data(){return Pn(this,bn)}_decodeWords(){return Nw(Pn(this,bn))}getWord(e){const t=Ln(this,vn,En).call(this);return Ka(e>=0&&e<t.length,`invalid word index: ${e}`,"index",e),t[e]}getWordIndex(e){return Ln(this,vn,En).call(this).indexOf(e)}}bn=new WeakMap,_n=new WeakMap,An=new WeakMap,vn=new WeakSet,En=function(){if(null==Pn(this,An)){const e=this._decodeWords();if(Wf(e.join("\n")+"\n")!==Pn(this,_n))throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`);Bn(this,An,e)}return Pn(this,An)};let Bw=null;class Uw extends Dw{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==Bw&&(Bw=new Uw),Bw}}function Lw(e){return(1<<e)-1<<8-e&255}function Mw(e,t){Ya("NFKD"),null==t&&(t=Uw.wordlist());const n=t.split(e);Ka(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 e=t.getWordIndex(n[a].normalize("NFKD"));Ka(e>=0,`invalid mnemonic word at index ${a}`,"mnemonic","[ REDACTED ]");for(let t=0;t<11;t++)e&1<<10-t&&(r[s>>3]|=1<<7-s%8),s++}const i=32*n.length/3,o=Lw(n.length/3);return Ka((ec(kh(r.slice(0,i/8)))[0]&o)===(r[r.length-1]&o),"invalid mnemonic checksum","mnemonic","[ REDACTED ]"),ic(r.slice(0,i/8))}function Fw(e,t){Ka(e.length%4==0&&e.length>=16&&e.length<=32,"invalid entropy size","entropy","[ REDACTED ]"),null==t&&(t=Uw.wordlist());const n=[0];let r=11;for(let o=0;o<e.length;o++)r>8?(n[n.length-1]<<=8,n[n.length-1]|=e[o],r-=8):(n[n.length-1]<<=r,n[n.length-1]|=e[o]>>8-r,n.push(e[o]&((1<<8-r)-1&255)),r+=3);const s=e.length/4,i=parseInt(kh(e).substring(2,4),16)&Lw(s);return n[n.length-1]<<=s,n[n.length-1]|=i>>8-s,t.join(n.map((e=>t.getWord(e))))}const jw={};class Gw{constructor(e,t,n,r,s){xn(this,"phrase"),xn(this,"password"),xn(this,"wordlist"),xn(this,"entropy"),null==r&&(r=""),null==s&&(s=Uw.wordlist()),Za(e,jw,"Mnemonic"),Ha(this,{phrase:n,password:r,wordlist:s,entropy:t})}computeSeed(){const e=Dc("mnemonic"+this.password,"NFKD");return rh(Dc(this.phrase,"NFKD"),e,2048,64,"sha512")}static fromPhrase(e,t,n){const r=Mw(e,n);return e=Fw(ec(r),n),new Gw(jw,r,e,t,n)}static fromEntropy(e,t,n){const r=ec(e,"entropy"),s=Fw(r,n);return new Gw(jw,ic(r),s,t,n)}static entropyToPhrase(e,t){return Fw(ec(e,"entropy"),t)}static phraseToEntropy(e,t){return Mw(e,t)}static isValidMnemonic(e,t){try{return Mw(e,t),!0}catch(n){}return!1}}
|
|
12
|
+
/*! MIT License. Copyright 2015-2022 Richard Moore <me@ricmoo.com>. See LICENSE.txt. */var Hw,Vw,qw,Ww=globalThis&&globalThis.__classPrivateFieldGet||function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)},zw=globalThis&&globalThis.__classPrivateFieldSet||function(e,t,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 t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,n):s?s.value=n:t.set(e,n),n};const $w={16:10,24:12,32:14},Kw=[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],Qw=[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],Jw=[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],Yw=[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],Zw=[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],Xw=[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],eb=[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],tb=[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],nb=[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],rb=[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],sb=[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],ib=[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],ob=[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],ab=[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],cb=[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 lb(e){const t=[];for(let n=0;n<e.length;n+=4)t.push(e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3]);return t}class ub{get key(){return Ww(this,Hw,"f").slice()}constructor(e){if(Hw.set(this,void 0),Vw.set(this,void 0),qw.set(this,void 0),!(this instanceof ub))throw Error("AES must be instanitated with `new`");zw(this,Hw,new Uint8Array(e),"f");const t=$w[this.key.length];if(null==t)throw new TypeError("invalid key size (must be 16, 24 or 32 bytes)");zw(this,qw,[],"f"),zw(this,Vw,[],"f");for(let l=0;l<=t;l++)Ww(this,qw,"f").push([0,0,0,0]),Ww(this,Vw,"f").push([0,0,0,0]);const n=4*(t+1),r=this.key.length/4,s=lb(this.key);let i;for(let l=0;l<r;l++)i=l>>2,Ww(this,qw,"f")[i][l%4]=s[l],Ww(this,Vw,"f")[t-i][l%4]=s[l];let o,a=0,c=r;for(;c<n;){if(o=s[r-1],s[0]^=Qw[o>>16&255]<<24^Qw[o>>8&255]<<16^Qw[255&o]<<8^Qw[o>>24&255]^Kw[a]<<24,a+=1,8!=r)for(let t=1;t<r;t++)s[t]^=s[t-1];else{for(let e=1;e<r/2;e++)s[e]^=s[e-1];o=s[r/2-1],s[r/2]^=Qw[255&o]^Qw[o>>8&255]<<8^Qw[o>>16&255]<<16^Qw[o>>24&255]<<24;for(let e=r/2+1;e<r;e++)s[e]^=s[e-1]}let e,i,l=0;for(;l<r&&c<n;)e=c>>2,i=c%4,Ww(this,qw,"f")[e][i]=s[l],Ww(this,Vw,"f")[t-e][i]=s[l++],c++}for(let l=1;l<t;l++)for(let e=0;e<4;e++)o=Ww(this,Vw,"f")[l][e],Ww(this,Vw,"f")[l][e]=ib[o>>24&255]^ob[o>>16&255]^ab[o>>8&255]^cb[255&o]}encrypt(e){if(16!=e.length)throw new TypeError("invalid plaintext size (must be 16 bytes)");const t=Ww(this,qw,"f").length-1,n=[0,0,0,0];let r=lb(e);for(let o=0;o<4;o++)r[o]^=Ww(this,qw,"f")[0][o];for(let o=1;o<t;o++){for(let e=0;e<4;e++)n[e]=Yw[r[e]>>24&255]^Zw[r[(e+1)%4]>>16&255]^Xw[r[(e+2)%4]>>8&255]^eb[255&r[(e+3)%4]]^Ww(this,qw,"f")[o][e];r=n.slice()}const s=new Uint8Array(16);let i=0;for(let o=0;o<4;o++)i=Ww(this,qw,"f")[t][o],s[4*o]=255&(Qw[r[o]>>24&255]^i>>24),s[4*o+1]=255&(Qw[r[(o+1)%4]>>16&255]^i>>16),s[4*o+2]=255&(Qw[r[(o+2)%4]>>8&255]^i>>8),s[4*o+3]=255&(Qw[255&r[(o+3)%4]]^i);return s}decrypt(e){if(16!=e.length)throw new TypeError("invalid ciphertext size (must be 16 bytes)");const t=Ww(this,Vw,"f").length-1,n=[0,0,0,0];let r=lb(e);for(let o=0;o<4;o++)r[o]^=Ww(this,Vw,"f")[0][o];for(let o=1;o<t;o++){for(let e=0;e<4;e++)n[e]=tb[r[e]>>24&255]^nb[r[(e+3)%4]>>16&255]^rb[r[(e+2)%4]>>8&255]^sb[255&r[(e+1)%4]]^Ww(this,Vw,"f")[o][e];r=n.slice()}const s=new Uint8Array(16);let i=0;for(let o=0;o<4;o++)i=Ww(this,Vw,"f")[t][o],s[4*o]=255&(Jw[r[o]>>24&255]^i>>24),s[4*o+1]=255&(Jw[r[(o+3)%4]>>16&255]^i>>16),s[4*o+2]=255&(Jw[r[(o+2)%4]>>8&255]^i>>8),s[4*o+3]=255&(Jw[255&r[(o+1)%4]]^i);return s}}Hw=new WeakMap,Vw=new WeakMap,qw=new WeakMap;class hb{constructor(e,t,n){if(n&&!(this instanceof n))throw new Error(`${e} must be instantiated with "new"`);Object.defineProperties(this,{aes:{enumerable:!0,value:new ub(t)},name:{enumerable:!0,value:e}})}}var db,fb,pb=globalThis&&globalThis.__classPrivateFieldSet||function(e,t,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 t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,n):s?s.value=n:t.set(e,n),n},gb=globalThis&&globalThis.__classPrivateFieldGet||function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};class mb extends hb{constructor(e,t){if(super("ECC",e,mb),db.set(this,void 0),fb.set(this,void 0),t){if(t.length%16)throw new TypeError("invalid iv size (must be 16 bytes)");pb(this,db,new Uint8Array(t),"f")}else pb(this,db,new Uint8Array(16),"f");pb(this,fb,this.iv,"f")}get iv(){return new Uint8Array(gb(this,db,"f"))}encrypt(e){if(e.length%16)throw new TypeError("invalid plaintext size (must be multiple of 16 bytes)");const t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=16){for(let t=0;t<16;t++)gb(this,fb,"f")[t]^=e[n+t];pb(this,fb,this.aes.encrypt(gb(this,fb,"f")),"f"),t.set(gb(this,fb,"f"),n)}return t}decrypt(e){if(e.length%16)throw new TypeError("invalid ciphertext size (must be multiple of 16 bytes)");const t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=16){const r=this.aes.decrypt(e.subarray(n,n+16));for(let s=0;s<16;s++)t[n+s]=r[s]^gb(this,fb,"f")[s],gb(this,fb,"f")[s]=e[n+s]}return t}}db=new WeakMap,fb=new WeakMap;var yb,wb,bb,_b=globalThis&&globalThis.__classPrivateFieldSet||function(e,t,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 t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,n):s?s.value=n:t.set(e,n),n},Ab=globalThis&&globalThis.__classPrivateFieldGet||function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};class vb extends hb{constructor(e,t){super("CTR",e,vb),yb.set(this,void 0),wb.set(this,void 0),bb.set(this,void 0),_b(this,bb,new Uint8Array(16),"f"),Ab(this,bb,"f").fill(0),_b(this,yb,Ab(this,bb,"f"),"f"),_b(this,wb,16,"f"),null==t&&(t=1),"number"==typeof t?this.setCounterValue(t):this.setCounterBytes(t)}get counter(){return new Uint8Array(Ab(this,bb,"f"))}setCounterValue(e){if(!Number.isInteger(e)||e<0||e>Number.MAX_SAFE_INTEGER)throw new TypeError("invalid counter initial integer value");for(let t=15;t>=0;--t)Ab(this,bb,"f")[t]=e%256,e=Math.floor(e/256)}setCounterBytes(e){if(16!==e.length)throw new TypeError("invalid counter initial Uint8Array value length");Ab(this,bb,"f").set(e)}increment(){for(let e=15;e>=0;e--){if(255!==Ab(this,bb,"f")[e]){Ab(this,bb,"f")[e]++;break}Ab(this,bb,"f")[e]=0}}encrypt(e){var t,n;const r=new Uint8Array(e);for(let s=0;s<r.length;s++)16===Ab(this,wb,"f")&&(_b(this,yb,this.aes.encrypt(Ab(this,bb,"f")),"f"),_b(this,wb,0,"f"),this.increment()),r[s]^=Ab(this,yb,"f")[(_b(this,wb,(n=Ab(this,wb,"f"),t=n++,n),"f"),t)];return r}decrypt(e){return this.encrypt(e)}}function Eb(e){return"string"!=typeof e||e.startsWith("0x")||(e="0x"+e),tc(e)}function kb(e,t){for(e=String(e);e.length<t;)e="0"+e;return e}function Sb(e){return"string"==typeof e?Dc(e,"NFKC"):tc(e)}function Tb(e,t){const n=t.match(/^([a-z0-9$_.-]*)(:([a-z]+))?(!)?$/i);Ka(null!=n,"invalid path","path",t);const r=n[1],s=n[3],i="!"===n[4];let o=e;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 e=null;for(const t in o)if(t.toLowerCase()===a){e=o[t];break}o=e}else o=null;if(null==o)break}if(Ka(!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 Eb(o);if("array"===s&&Array.isArray(o))return o;if(s===typeof o)return o;Ka(!1,`wrong type found for ${s} `,"path",r)}return o}yb=new WeakMap,wb=new WeakMap,bb=new WeakMap;const Rb="m/44'/60'/0'/0/0";function Ib(e){try{const t=JSON.parse(e);if(3===(null!=t.version?parseInt(t.version):0))return!0}catch(t){}return!1}function Cb(e,t){const n=ec(t),r=Tb(e,"crypto.ciphertext:data!");Ka(ic(Bu(oc([n.slice(16,32),r]))).substring(2)===Tb(e,"crypto.mac:string!").toLowerCase(),"incorrect password","password","[ REDACTED ]");const s=function(e,t,n){if("aes-128-ctr"===Tb(e,"crypto.cipher:string")){const r=Tb(e,"crypto.cipherparams.iv:data!");return ic(new vb(t,r).decrypt(n))}$a(!1,"unsupported cipher","UNSUPPORTED_OPERATION",{operation:"decrypt"})}(e,n.slice(0,16),r),i=kf(s);if(e.address){let t=e.address.toLowerCase();t.startsWith("0x")||(t="0x"+t),Ka(Kd(t)===i,"keystore address/privateKey mismatch","address",e.address)}const o={address:i,privateKey:s};if("0.1"===Tb(e,"x-ethers.version:string")){const t=n.slice(32,64),r=Tb(e,"x-ethers.mnemonicCiphertext:data!"),s=Tb(e,"x-ethers.mnemonicCounter:data!"),i=new vb(t,s);o.mnemonic={path:Tb(e,"x-ethers.path:string")||Rb,locale:Tb(e,"x-ethers.locale:string")||"en",entropy:ic(ec(i.decrypt(r)))}}return o}function Ob(e){const t=Tb(e,"crypto.kdf:string");if(t&&"string"==typeof t){if("scrypt"===t.toLowerCase()){const n=Tb(e,"crypto.kdfparams.salt:data!"),r=Tb(e,"crypto.kdfparams.n:int!"),s=Tb(e,"crypto.kdfparams.r:int!"),i=Tb(e,"crypto.kdfparams.p:int!");Ka(r>0&&!(r&r-1),"invalid kdf.N","kdf.N",r),Ka(s>0&&i>0,"invalid kdf","kdf",t);const o=Tb(e,"crypto.kdfparams.dklen:int!");return Ka(32===o,"invalid kdf.dklen","kdf.dflen",o),{name:"scrypt",salt:n,N:r,r:s,p:i,dkLen:64}}if("pbkdf2"===t.toLowerCase()){const t=Tb(e,"crypto.kdfparams.salt:data!"),n=Tb(e,"crypto.kdfparams.prf:string!"),r=n.split("-").pop();Ka("sha256"===r||"sha512"===r,"invalid kdf.pdf","kdf.pdf",n);const s=Tb(e,"crypto.kdfparams.c:int!"),i=Tb(e,"crypto.kdfparams.dklen:int!");return Ka(32===i,"invalid kdf.dklen","kdf.dklen",i),{name:"pbkdf2",salt:t,count:s,dkLen:i,algorithm:r}}}Ka(!1,"unsupported key-derivation function","kdf",t)}function xb(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}function Nb(e){const t=null!=e.salt?ec(e.salt,"options.salt"):ah(32);let n=1<<17,r=8,s=1;return e.scrypt&&(e.scrypt.N&&(n=e.scrypt.N),e.scrypt.r&&(r=e.scrypt.r),e.scrypt.p&&(s=e.scrypt.p)),Ka("number"==typeof n&&n>0&&Number.isSafeInteger(n)&&(BigInt(n)&BigInt(n-1))===BigInt(0),"invalid scrypt N parameter","options.N",n),Ka("number"==typeof r&&r>0&&Number.isSafeInteger(r),"invalid scrypt r parameter","options.r",r),Ka("number"==typeof s&&s>0&&Number.isSafeInteger(s),"invalid scrypt p parameter","options.p",s),{name:"scrypt",dkLen:32,salt:t,N:n,r:r,p:s}}function Pb(e,t,n,r){const s=ec(n.privateKey,"privateKey"),i=null!=r.iv?ec(r.iv,"options.iv"):ah(16);Ka(16===i.length,"invalid options.iv length","options.iv",r.iv);const o=null!=r.uuid?ec(r.uuid,"options.uuid"):ah(16);Ka(16===o.length,"invalid options.uuid length","options.uuid",r.iv);const a=e.slice(0,16),c=e.slice(16,32),l=ec(new vb(a,i).encrypt(s)),u=Bu(oc([c,l])),h={address:n.address.substring(2).toLowerCase(),id:al(o),version:3,Crypto:{cipher:"aes-128-ctr",cipherparams:{iv:ic(i).substring(2)},ciphertext:ic(l).substring(2),kdf:"scrypt",kdfparams:{salt:ic(t.salt).substring(2),n:t.N,dklen:32,p:t.p,r:t.r},mac:u.substring(2)}};if(n.mnemonic){const t=null!=r.client?r.client:`ethers/${Fa}`,s=n.mnemonic.path||Rb,i=n.mnemonic.locale||"en",o=e.slice(32,64),a=ec(n.mnemonic.entropy,"account.mnemonic.entropy"),c=ah(16),l=ec(new vb(o,c).encrypt(a)),u=new Date,d="UTC--"+(u.getUTCFullYear()+"-"+kb(u.getUTCMonth()+1,2)+"-"+kb(u.getUTCDate(),2)+"T"+kb(u.getUTCHours(),2)+"-"+kb(u.getUTCMinutes(),2)+"-"+kb(u.getUTCSeconds(),2)+".0Z")+"--"+h.address;h["x-ethers"]={client:t,gethFilename:d,path:s,locale:i,mnemonicCounter:ic(c).substring(2),mnemonicCiphertext:ic(l).substring(2),version:"0.1"}}return JSON.stringify(h)}function Db(e,t,n){null==n&&(n={});const r=Sb(t),s=Nb(n);return Pb(ec(_h(r,s.salt,s.N,s.r,s.p,64)),s,e,n)}async function Bb(e,t,n){null==n&&(n={});const r=Sb(t),s=Nb(n);return Pb(ec(await bh(r,s.salt,s.N,s.r,s.p,64,n.progressCallback)),s,e,n)}const Ub="m/44'/60'/0'/0/0",Lb=new Uint8Array([66,105,116,99,111,105,110,32,115,101,101,100]),Mb=2147483648,Fb=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");function jb(e,t){let n="";for(;e;)n="0123456789abcdef"[e%16]+n,e=Math.trunc(e/16);for(;n.length<2*t;)n="0"+n;return"0x"+n}function Gb(e){const t=ec(e);return Oc(oc([t,cc(kh(kh(t)),0,4)]))}const Hb={};function Vb(e,t,n,r){const s=new Uint8Array(37);e&Mb?($a(null!=r,"cannot derive child of neutered node","UNSUPPORTED_OPERATION",{operation:"deriveChild"}),s.set(ec(r),1)):s.set(ec(n));for(let o=24;o>=0;o-=8)s[33+(o>>3)]=e>>24-o&255;const i=ec(mu("sha512",t,s));return{IL:i.slice(0,32),IR:i.slice(32)}}function qb(e,t){const n=t.split("/");Ka(n.length>0,"invalid path","path",t),"m"===n[0]&&(Ka(0===e.depth,`cannot derive root path (i.e. path starting with "m/") for a node at non-zero depth ${e.depth}`,"path",t),n.shift());let r=e;for(let s=0;s<n.length;s++){const e=n[s];if(e.match(/^[0-9]+'$/)){const t=parseInt(e.substring(0,e.length-1));Ka(t<Mb,"invalid path index",`path[${s}]`,e),r=r.deriveChild(Mb+t)}else if(e.match(/^[0-9]+$/)){const t=parseInt(e);Ka(t<Mb,"invalid path index",`path[${s}]`,e),r=r.deriveChild(t)}else Ka(!1,"invalid path component",`path[${s}]`,e)}return r}const Wb=class e extends Iw{constructor(e,t,n,r,s,i,o,a,c){super(t,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"),Za(e,Hb,"HDNodeWallet"),Ha(this,{publicKey:t.compressedPublicKey});Ha(this,{parentFingerprint:n,fingerprint:cc(Xu(kh(this.publicKey)),0,4),chainCode:r,path:s,index:i,depth:o}),Ha(this,{mnemonic:a})}connect(t){return new e(Hb,this.signingKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,this.mnemonic,t)}async encrypt(e,t){return await Bb(Ln(this,kn,Sn).call(this),e,{progressCallback:t})}encryptSync(e){return Db(Ln(this,kn,Sn).call(this),e)}get extendedKey(){return $a(this.depth<256,"Depth too deep","UNSUPPORTED_OPERATION",{operation:"extendedKey"}),Gb(oc(["0x0488ADE4",jb(this.depth,1),this.parentFingerprint,jb(this.index,4),this.chainCode,oc(["0x00",this.privateKey])]))}hasPath(){return null!=this.path}neuter(){return new $b(Hb,this.address,this.publicKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,this.provider)}deriveChild(t){const n=Ac(t,"index");Ka(n<=4294967295,"invalid index","index",n);let r=this.path;r&&(r+="/"+(2147483647&n),n&Mb&&(r+="'"));const{IR:s,IL:i}=Vb(n,this.chainCode,this.publicKey,this.privateKey),o=new Hd(vc((_c(i)+BigInt(this.privateKey))%Fb,32));return new e(Hb,o,this.fingerprint,ic(s),r,n,this.depth+1,this.mnemonic,this.provider)}derivePath(e){return qb(this,e)}static fromExtendedKey(t){const n=Ec(function(e){let t=Ic;for(let n=0;n<e.length;n++)t*=Cc,t+=Rc(e[n]);return t}(t));Ka(82===n.length||Gb(n.slice(0,78))===t,"invalid extended key","extendedKey","[ REDACTED ]");const r=n[4],s=ic(n.slice(5,9)),i=parseInt(ic(n.slice(9,13)).substring(2),16),o=ic(n.slice(13,45)),a=n.slice(45,78);switch(ic(n.slice(0,4))){case"0x0488b21e":case"0x043587cf":{const e=ic(a);return new $b(Hb,kf(e),e,s,o,null,i,r,null)}case"0x0488ade4":case"0x04358394 ":if(0!==a[0])break;return new e(Hb,new Hd(a.slice(1)),s,o,null,i,r,null,null)}Ka(!1,"invalid extended key prefix","extendedKey","[ REDACTED ]")}static createRandom(t,n,r){var s;null==t&&(t=""),null==n&&(n=Ub),null==r&&(r=Uw.wordlist());const i=Gw.fromEntropy(ah(16),t,r);return Ln(s=e,Tn,Rn).call(s,i.computeSeed(),i).derivePath(n)}static fromMnemonic(t,n){var r;return n||(n=Ub),Ln(r=e,Tn,Rn).call(r,t.computeSeed(),t).derivePath(n)}static fromPhrase(t,n,r,s){var i;null==n&&(n=""),null==r&&(r=Ub),null==s&&(s=Uw.wordlist());const o=Gw.fromPhrase(t,n,s);return Ln(i=e,Tn,Rn).call(i,o.computeSeed(),o).derivePath(r)}static fromSeed(t){var n;return Ln(n=e,Tn,Rn).call(n,t,null)}};kn=new WeakSet,Sn=function(){const e={address:this.address,privateKey:this.privateKey},t=this.mnemonic;return this.path&&t&&"en"===t.wordlist.locale&&""===t.password&&(e.mnemonic={path:this.path,locale:"en",entropy:t.entropy}),e},Tn=new WeakSet,Rn=function(e,t){Ka(rc(e),"invalid seed","seed","[REDACTED]");const n=ec(e,"seed");Ka(n.length>=16&&n.length<=64,"invalid seed","seed","[REDACTED]");const r=ec(mu("sha512",Lb,n)),s=new Hd(ic(r.slice(0,32)));return new Wb(Hb,s,"0x00000000",ic(r.slice(32)),"m",0,0,t,null)},Dn(Wb,Tn);let zb=Wb;class $b extends dw{constructor(e,t,n,r,s,i,o,a,c){super(t,c),xn(this,"publicKey"),xn(this,"fingerprint"),xn(this,"parentFingerprint"),xn(this,"chainCode"),xn(this,"path"),xn(this,"index"),xn(this,"depth"),Za(e,Hb,"HDNodeVoidWallet"),Ha(this,{publicKey:n});Ha(this,{publicKey:n,fingerprint:cc(Xu(kh(n)),0,4),parentFingerprint:r,chainCode:s,path:i,index:o,depth:a})}connect(e){return new $b(Hb,this.address,this.publicKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,e)}get extendedKey(){return $a(this.depth<256,"Depth too deep","UNSUPPORTED_OPERATION",{operation:"extendedKey"}),Gb(oc(["0x0488B21E",jb(this.depth,1),this.parentFingerprint,jb(this.index,4),this.chainCode,this.publicKey]))}hasPath(){return null!=this.path}deriveChild(e){const t=Ac(e,"index");Ka(t<=4294967295,"invalid index","index",t);let n=this.path;n&&(n+="/"+(2147483647&t),t&Mb&&(n+="'"));const{IR:r,IL:s}=Vb(t,this.chainCode,this.publicKey,null),i=Hd.addPoints(s,this.publicKey,!0),o=kf(i);return new $b(Hb,o,i,this.fingerprint,ic(r),n,t,this.depth+1,this.provider)}derivePath(e){return qb(this,e)}}function Kb(e){try{if(JSON.parse(e).encseed)return!0}catch(t){}return!1}function Qb(e,t){const n=JSON.parse(e),r=Sb(t),s=Kd(Tb(n,"ethaddr:string!")),i=Eb(Tb(n,"encseed:string!"));Ka(i&&i.length%16==0,"invalid encseed","json",e);const o=ec(rh(r,r,2e3,32,"sha256")).slice(0,16),a=i.slice(0,16),c=i.slice(16),l=function(e){if(e.length<16)throw new TypeError("PKCS#7 invalid length");const t=e[e.length-1];if(t>16)throw new TypeError("PKCS#7 padding byte out of range");const n=e.length-t;for(let r=0;r<t;r++)if(e[n+r]!==t)throw new TypeError("PKCS#7 invalid padding byte");return new Uint8Array(e.subarray(0,n))}(ec(new mb(o,a).decrypt(c)));let u="";for(let h=0;h<l.length;h++)u+=String.fromCharCode(l[h]);return{address:s,privateKey:Wf(u)}}function Jb(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}const Yb=class e extends Iw{constructor(e,t){"string"!=typeof e||e.startsWith("0x")||(e="0x"+e),super("string"==typeof e?new Hd(e):e,t)}connect(t){return new e(this.signingKey,t)}async encrypt(e,t){const n={address:this.address,privateKey:this.privateKey};return await Bb(n,e,{progressCallback:t})}encryptSync(e){return Db({address:this.address,privateKey:this.privateKey},e)}static async fromEncryptedJson(t,n,r){var s;let i=null;return Ib(t)?i=await async function(e,t,n){const r=JSON.parse(e),s=Sb(t),i=Ob(r);if("pbkdf2"===i.name){n&&(n(0),await xb(0));const{salt:e,count:t,dkLen:o,algorithm:a}=i,c=rh(s,e,t,o,a);return n&&(n(1),await xb(0)),Cb(r,c)}$a("scrypt"===i.name,"cannot be reached","UNKNOWN_ERROR",{params:i});const{salt:o,N:a,r:c,p:l,dkLen:u}=i;return Cb(r,await bh(s,o,a,c,l,u,n))}(t,n,r):Kb(t)&&(r&&(r(0),await Jb(0)),i=Qb(t,n),r&&(r(1),await Jb(0))),Ln(s=e,In,Cn).call(s,i)}static fromEncryptedJsonSync(t,n){var r;let s=null;return Ib(t)?s=function(e,t){const n=JSON.parse(e),r=Sb(t),s=Ob(n);if("pbkdf2"===s.name){const{salt:e,count:t,dkLen:i,algorithm:o}=s;return Cb(n,rh(r,e,t,i,o))}$a("scrypt"===s.name,"cannot be reached","UNKNOWN_ERROR",{params:s});const{salt:i,N:o,r:a,p:c,dkLen:l}=s;return Cb(n,_h(r,i,o,a,c,l))}(t,n):Kb(t)?s=Qb(t,n):Ka(!1,"invalid JSON wallet","json","[ REDACTED ]"),Ln(r=e,In,Cn).call(r,s)}static createRandom(e){const t=zb.createRandom();return e?t.connect(e):t}static fromPhrase(e,t){const n=zb.fromPhrase(e);return t?n.connect(t):n}};In=new WeakSet,Cn=function(e){if(Ka(e,"invalid JSON wallet","json","[ REDACTED ]"),"mnemonic"in e&&e.mnemonic&&"en"===e.mnemonic.locale){const t=Gw.fromEntropy(e.mnemonic.entropy),n=zb.fromMnemonic(t,e.mnemonic.path);if(n.address===e.address&&n.privateKey===e.privateKey)return n;console.log("WARNING: JSON mismatch address/privateKey != mnemonic; fallback onto private key")}const t=new Yb(e.privateKey);return Ka(t.address===e.address,"address/privateKey mismatch","json","[ REDACTED ]"),t},Dn(Yb,In);let Zb=Yb;const Xb=3000000n,e_=2000000000n,t_=1000000000n,n_=4096,r_="dns_txt",s_=(1n<<64n)-1n,i_=["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)"],o_=new Am(i_),a_=[0,"0x"],c_=function(e){const t=Dc(e);if(t.length>31)throw new Error("bytes32 string must be less than 32 bytes");return hc(t,32)}("inline");class l_ extends Error{constructor(e,t){super(t),this.name="BnsEvmTxError",this.code=e}}function u_(e,t,n){let r;try{r=BigInt(t)}catch{throw new l_("INVALID_CONFIG",`${e} must be an integer`)}if(r<0n||void 0!==n&&r>n)throw new l_("INVALID_CONFIG",`${e} is out of range`);return r}function h_(e){const t=Mn.canonicalize(e);if("string"!=typeof t)throw new l_("INVALID_DOCUMENT","document cannot be encoded as canonical JSON");const n=Dc(t);if(0===n.length||n.length>n_)throw new l_("INVALID_DOCUMENT",`inline document is ${n.length} bytes, max 4096`);return n}function d_(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw new l_("INVALID_DOCUMENT",`${t} must be an object`);const n=e;if(!Number.isInteger(n.ttl)||n.ttl<0||n.ttl>4294967295)throw new l_("INVALID_DOCUMENT",`${t}.ttl must be a u32`);if("string"!=typeof n.value||0===n.value.length)throw new l_("INVALID_DOCUMENT",`${t}.value must be a non-empty string`);return{ttl:n.ttl,value:n.value}}class f_{constructor(e,t,n){if(this.nextNonce=null,this.client=e,this.config=t,this.chainId=u_("chainId",t.chainId,s_),this.contractAddress=Kd(t.contractAddress),this.gasLimit=u_("gasLimit",t.gasLimit??Xb,s_),this.maxFeePerGas=u_("maxFeePerGas",t.maxFeePerGas??e_),this.maxPriorityFeePerGas=u_("maxPriorityFeePerGas",t.maxPriorityFeePerGas??t_),!t.rpcEndpoint&&!n)throw new l_("INVALID_CONFIG","rpcEndpoint is required");if(0n===this.chainId||0n===this.gasLimit)throw new l_("INVALID_CONFIG","chainId and gasLimit must be greater than zero");if(this.maxFeePerGas<this.maxPriorityFeePerGas)throw new l_("INVALID_CONFIG","maxFeePerGas must be >= maxPriorityFeePerGas");this.provider=n??new Sw(t.rpcEndpoint,this.chainId,{staticNetwork:!0})}resetNonce(){this.nextNonce=null}async buildAndSign(e,t){const n=new Zb(t),r="publish_document"===e.type?await this.preparePublishedDocument(e.request):await this.prepareDnsTxtDocument(e.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(e){null===this.nextNonce&&(this.nextNonce=await this.provider.getTransactionCount(e,"pending"));const t=this.nextNonce;return this.nextNonce+=1,t}async preparePublishedDocument(e){if(!e.document||"object"!=typeof e.document||Array.isArray(e.document))throw new l_("INVALID_DOCUMENT","publish_document document must be a JSON object");return this.prepareDocument(e.name,e.doc_type,h_(e.document))}async prepareDnsTxtDocument(e){const t=await this.getCurrentDocument(e.name,r_);let n=[];if(t){if("inline"!==t.document_state.document.storage_type)throw new l_("INVALID_DOCUMENT","DNS TXT helper can only update inline documents");let e;try{e=JSON.parse(function(e){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(new Uint8Array(e));let t="";for(const n of e)t+=String.fromCharCode(n);try{return decodeURIComponent(escape(t))}catch{return t}}(t.document_state.document.inline_document))}catch(s){throw new l_("INVALID_DOCUMENT",`current dns_txt document is not valid JSON: ${s instanceof Error?s.message:String(s)}`)}if(!Array.isArray(e))throw new l_("INVALID_DOCUMENT","current dns_txt document must be an array");n=e.map(((e,t)=>d_(e,`dns_txt[${t}]`)))}switch(e.mode){case"add":{if(!e.value)throw new l_("INVALID_OPERATION","publish_dns_txt mode=add requires value");const t=d_({ttl:e.ttl??600,value:e.value},"dns_txt");n.some((e=>e.value===t.value))||n.push(t);break}case"remove":if(!e.value)throw new l_("INVALID_OPERATION","publish_dns_txt mode=remove requires value");n=n.filter((t=>t.value!==e.value));break;case"replace":if(!e.records)throw new l_("INVALID_OPERATION","publish_dns_txt mode=replace requires records");n=e.records.map(((e,t)=>d_({ttl:e.ttl??600,value:e.value},`dns_txt[${t}]`)));break;default:throw new l_("INVALID_OPERATION",`publish_dns_txt mode \`${e.mode}\` is not supported`)}const r=await this.getNameState(e.name);return{name:Na(e.name),docType:r_,expectedVersion:(null==t?void 0:t.document_state.version)??0,inlineDocument:h_(n),nameState:r}}async prepareDocument(e,t,n){const r=Na(e),s=Pa(t),[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(e){const t=await this.client.queryNameState(e);if(!t)throw new l_("NAME_NOT_FOUND",`BNS name \`${e}\` was not found`);return t}async getCurrentDocument(e,t){try{const n=await this.client.resolveDocument(e,t);return"missing"===n.status?null:n}catch(n){if(function(e){return e instanceof zo&&e.isRegistryCode("DOCUMENT_NOT_FOUND")}(n))return null;throw n}}encodePublishDocument(e,t){const n=this.ownerAuthority(e.nameState,t),r=[c_,"",ic(e.inlineDocument),kh(e.inlineDocument),Cd,Cd,Cd];return o_.encodeFunctionData("publishDocument",[e.name,e.docType,e.expectedVersion,r,a_,a_,Id,0,Cd,Cd,Cd,Cd,Cd,n,[e.nameState.name_seq,0]])}ownerAuthority(e,t){const n=e.effective_owner;if("chain_account"===n.kind){const s=Kd(n.value);if(s!==Kd(t))throw new l_("LOCAL_SIGNER_NOT_OWNER",`local signer ${t} is not effective owner ${s} of ${e.name}`);return[1,(r=t,[1,ic(ec(r))]),Cd]}var r;if("bns_name"===n.kind){const t=function(e,t){if(!t)return Cd;const n=ec(t);if(32!==n.length)throw new l_("INVALID_CONFIG",`${e} must be a 32-byte hex value`);return ic(n)}("authorityKid",this.config.authorityKid);if(t===Cd)throw new l_("AUTHORITY_KID_REQUIRED",`authorityKid is required when ${e.name} is controlled by BNS name ${n.value}`);return[1,[2,ic(Dc(n.value))],t]}throw new l_("LOCAL_SIGNER_NOT_OWNER",`BNS name ${e.name} has no concrete effective owner`)}}class p_ extends Error{constructor(e,t,n){super(n),this.name="BnsTxExecutorError",this.code=e,this.route=t}}function g_(e){if("string"!=typeof e)return null;const t=e.trim();return t.length>0?t:null}function m_(e){return e===Ni.NodeJS||e===Ni.AppClient||e===Ni.AppService}function y_(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"boolean"==typeof t.sn_account?t.sn_account:null!==g_(t.sn_username)||null!==g_(t.sn_user_name)}const w_="/kapi/sn",b_="/kapi/sn/auth",__="/kapi/sn/deviceinfo",A_="/kapi/sn/bns-proxy",v_="/kapi/sn/bns",E_="/kapi/sn/region-probe-config.json",k_=1048576,S_="auth.check_username",T_="auth.check_active_code",R_="auth.register",I_="auth.login",C_="auth.refresh",O_="auth.logout",x_="auth.me",N_="user.get_profile",P_="user.set_self_cert",D_="user.add_dns_record",B_="user.remove_dns_record",U_="user.list_dns_records",L_="zone.get_info",M_="domain.bind",F_="domain.unbind",j_="device.register",G_="device.update",H_="device.get",V_="device.list",q_="deviceinfo.resolve_ood_by_did",W_="deviceinfo.resolve_ood_by_hostname",z_="bns.publish_dns_txt",$_="bns.publish_document",K_="owner.remove_bound_zone",Q_=/\[SN:(\d+):([a-z_]+)\]\s*/;class J_ extends Error{constructor(e,t,n=null,r=null,s=null){super(t),this.name="SnClientError",this.kind=e,this.code=n,this.codeName=r,this.detail=s??t}isSnError(e){return"sn"===this.kind&&this.codeName===e}domainProofInfo(){return this.isSnError("domain_proof_failed")?Y_(this.detail):null}bnsWriteInfo(){return this.isSnError("bns_permission_denied")||this.isSnError("bns_name_already_exists")||this.isSnError("bns_write_failed")?Y_(this.detail):null}static fromRpcError(e,t){if(t instanceof J_)return t;const n=t instanceof Error?t.message:String(t),r=Q_.exec(n);if(r){const t=parseInt(r[1],10),s=r[2],i=n.slice(r.index+r[0].length);return new J_("sn",`${e} failed: [SN:${t}:${s}] ${i}`,t,s,i)}return new J_("transport",`${e} failed: ${n}`)}}function Y_(e){try{const t=JSON.parse(e);return null===t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}}const Z_={auth:b_,deviceinfo:__,"bns-proxy":A_},X_=[A_,__,b_,v_,w_];function eA(e,t){const n=Z_[t],r=e.replace(/\/+$/,"");for(const s of X_)if(r.endsWith(s))return`${r.slice(0,r.length-s.length)}${n}`;return`${r}${n}`}const tA=[E_,A_,__,b_,v_,w_],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(e){throw new J_("validation",e)}function iA(e){return(new TextEncoder).encode(e).byteLength}function oA(e,t){return(null===e||"object"!=typeof e||Array.isArray(e))&&sA(`${t} must be a JSON object`),e}function aA(e,t){return"string"!=typeof e&&sA(`${t} must be a string`),e}function cA(e,t){return"number"!=typeof e&&sA(`${t} must be a number`),e}function lA(e,t){const n=cA(e,t);return Number.isSafeInteger(n)||sA(`${t} must be a safe integer`),n}function uA(e,t){const n=lA(e,t);return(n<-2147483648||n>2147483647)&&sA(`${t} must fit in a signed 32-bit integer`),n}function hA(e,t){return Array.isArray(e)||sA(`${t} must be an array`),e}function dA(e){return iA(e)<=128&&/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e)}function fA(e){const t=e.split(".");if(4!==t.length)return null;const n=t.map((e=>Number(e)));return n.some(((e,n)=>!/^\d+$/.test(t[n])||!Number.isInteger(e)||e<0||e>255))?null:n}function pA(e){const t=fA(e);if(!t)return!1;const[n,r,s]=t;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(e,t){const n=Date.parse(e);return nA.test(e)&&Number.isFinite(n)||sA(`${t} must be an RFC 3339 timestamp`),n}function mA(e,t=Date.now()){1!==e.schema_version&&sA(`unsupported schema_version ${e.schema_version}, expected 1`),(0===e.config_version.length||iA(e.config_version)>128||e.config_version.trim()!==e.config_version||rA.test(e.config_version))&&sA("config_version must be 1..=128 non-control bytes without surrounding whitespace");const n=gA(e.generated_at,"generated_at"),r=gA(e.expires_at,"expires_at"),s=t instanceof Date?t.getTime():"number"==typeof t?t:Date.parse(t);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=e.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"),(e.regions.length<1||e.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 e.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 e of h.probe_urls){let t;(0===e.id.length||iA(e.id)>128||e.id.trim()!==e.id||rA.test(e.id))&&sA(`probe URL id in region ${h.region_id} must be 1..=128 non-control bytes without surrounding whitespace`),a.has(e.id)&&sA(`duplicate probe URL id ${JSON.stringify(e.id)}`),a.add(e.id);try{t=new URL(e.url)}catch(u){sA(`invalid probe URL ${JSON.stringify(e.url)}: ${String(u)}`)}"https:"!==t.protocol&&sA(`probe URL ${JSON.stringify(e.url)} must use https`),(!t.hostname||t.username||t.password)&&sA(`probe URL ${JSON.stringify(e.url)} must be absolute and must not contain userinfo`),""!==t.port&&sA(`probe URL ${JSON.stringify(e.url)} must use port 443`);const n=fA(t.hostname),r=t.hostname.startsWith("[")&&t.hostname.endsWith("]");(n&&!pA(t.hostname)||r)&&sA(`probe URL ${JSON.stringify(e.url)} has a non-public or unsupported literal IP`);const s=c.get(t.origin);void 0!==s&&(s!==h.region_id&&sA(`probe origin ${t.origin} is assigned to both ${s} and ${h.region_id}`),sA(`probe origin ${t.origin} is duplicated in region ${h.region_id}`)),c.set(t.origin,h.region_id)}}}function yA(e){let t,n;try{t="string"==typeof e?e:new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(s){sA(`parse region probe config JSON failed: ${String(s)}`)}try{n=JSON.parse(t)}catch(s){sA(`parse region probe config JSON failed: ${String(s)}`)}const r=function(e){const t=oA(e,"region probe config"),n=oA(t.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(t.regions,"regions").map(((e,t)=>{const n=oA(e,`regions[${t}]`),r=hA(n.probe_urls,`regions[${t}].probe_urls`).map(((e,n)=>{const r=oA(e,`regions[${t}].probe_urls[${n}]`),s={id:aA(r.id,`regions[${t}].probe_urls[${n}].id`),url:aA(r.url,`regions[${t}].probe_urls[${n}].url`)};return void 0!==r.provider&&null!==r.provider&&(s.provider=aA(r.provider,`regions[${t}].probe_urls[${n}].provider`)),s}));return{region_id:aA(n.region_id,`regions[${t}].region_id`),priority:void 0===n.priority?0:uA(n.priority,`regions[${t}].priority`),probe_urls:r}}));return{schema_version:lA(t.schema_version,"schema_version"),config_version:aA(t.config_version,"config_version"),generated_at:aA(t.generated_at,"generated_at"),expires_at:aA(t.expires_at,"expires_at"),policy:r,regions:s}}(n);return mA(r),r}function wA(e){let t;try{t=new URL(e.trim())}catch(s){sA(`invalid SN base URL for region probe config: ${String(s)}`)}"https:"!==t.protocol&&sA("region probe config must be fetched from the target SN over HTTPS"),(!t.hostname||t.username||t.password)&&sA("SN region probe config URL must have a host and no userinfo"),t.search="",t.hash="";const n=t.pathname.replace(/\/+$/,"");let r=n;for(const i of tA)if(n.endsWith(i)){r=n.slice(0,n.length-i.length);break}return t.pathname=`${r}${E_}`,t.toString()}const bA=async(e,t)=>{if("function"!=typeof globalThis.fetch)throw new Error("fetch is not available in this runtime");return globalThis.fetch(e,t)};const _A="sn-device";function AA(e){return void 0!==e.ttl?{ttl:e.ttl,value:e.value}:{value:e.value}}function vA(e){const t={device_did:e.device_did,domain:e.domain,record_type:e.record_type};return void 0!==e.record&&(t.record=e.record),void 0!==e.ttl&&(t.ttl=e.ttl),void 0!==e.has_cert&&(t.has_cert=e.has_cert),t}function EA(e){return{endpoint_id:e.endpoint_id,protocol:e.protocol,host:e.host,port:e.port,scope:e.scope,priority:e.priority,source:e.source,expires_at:e.expires_at}}function kA(e){const t={device_name:e.device_name,device_ip:e.device_ip,device_info:e.device_info};return void 0!==e.device_did&&(t.device_did=e.device_did),void 0!==e.endpoints&&e.endpoints.length>0&&(t.endpoints=e.endpoints.map(EA)),void 0!==e.report_seq&&(t.report_seq=e.report_seq),void 0!==e.ttl&&(t.ttl=e.ttl),t}const SA=Object.freeze(Object.defineProperty({__proto__:null,LEGACY_SN_BNS_PATH:v_,METHOD_AUTH_CHECK_ACTIVE_CODE:T_,METHOD_AUTH_CHECK_USERNAME:S_,METHOD_AUTH_LOGIN:I_,METHOD_AUTH_LOGOUT:O_,METHOD_AUTH_ME:x_,METHOD_AUTH_REFRESH:C_,METHOD_AUTH_REGISTER:R_,METHOD_BNS_PUBLISH_DNS_TXT:z_,METHOD_BNS_PUBLISH_DOCUMENT:$_,METHOD_DEVICEINFO_RESOLVE_OOD_BY_DID:q_,METHOD_DEVICEINFO_RESOLVE_OOD_BY_HOSTNAME:W_,METHOD_DEVICE_GET:H_,METHOD_DEVICE_LIST:V_,METHOD_DEVICE_REGISTER:j_,METHOD_DEVICE_UPDATE:G_,METHOD_DOMAIN_BIND:M_,METHOD_DOMAIN_UNBIND:F_,METHOD_OWNER_REMOVE_BOUND_ZONE:K_,METHOD_USER_ADD_DNS_RECORD:D_,METHOD_USER_GET_PROFILE:N_,METHOD_USER_LIST_DNS_RECORDS:U_,METHOD_USER_REMOVE_DNS_RECORD:B_,METHOD_USER_SET_SELF_CERT:P_,METHOD_ZONE_GET_INFO:L_,SN_AUTH_PATH:b_,SN_BNS_PROXY_PATH:A_,SN_DEVICEINFO_PATH:__,SN_DEVICE_TOKEN_AUD:_A,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:E_,SN_REGION_PROBE_FETCH_TIMEOUT:5e3,SN_REGION_PROBE_MAX_CONFIG_BYTES:k_,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:w_,SnClient:class{constructor(e,t=null,n={}){this.authRpc=new Gn(eA(e,"auth"),t,null,n),this.deviceInfoRpc=new Gn(eA(e,"deviceinfo"),t,null,n),this.bnsProxyRpc=new Gn(eA(e,"bns-proxy"),t,null,n)}setSeq(e){this.authRpc.setSeq(e),this.deviceInfoRpc.setSeq(e),this.bnsProxyRpc.setSeq(e)}syncSessionToken(e){this.authRpc.setSessionToken(e),this.deviceInfoRpc.setSessionToken(e),this.bnsProxyRpc.setSessionToken(e)}getSessionToken(){return this.authRpc.getSessionToken()}async call(e,t,n){try{return await e.call(t,n)}catch(r){throw J_.fromRpcError(t,r)}}async checkUsername(e){return this.call(this.authRpc,S_,{name:e})}async checkActiveCode(e){return this.call(this.authRpc,T_,{active_code:e})}async register(e){const t={name:e.name,email:e.email,pwd_hash:e.pwd_hash,active_code:e.active_code};return void 0!==e.request_id&&(t.request_id=e.request_id),void 0!==e.region&&(t.region=e.region),void 0!==e.asset_owner&&(t.asset_owner=e.asset_owner),void 0!==e.owner_config&&(t.owner_config=e.owner_config),void 0!==e.initial_documents&&(t.initial_documents=function(e){const t={};void 0!==e.zone&&(t.zone=e.zone);void 0!==e.boot&&(t.boot=e.boot);void 0!==e.dns_txt&&(t.dns_txt=e.dns_txt.map((e=>({ttl:e.ttl,value:e.value}))));return t}(e.initial_documents)),this.call(this.authRpc,R_,t)}async login(e){const t={name:e.name,pwd_hash:e.pwd_hash};return void 0!==e.active_code&&(t.active_code=e.active_code),this.call(this.authRpc,I_,t)}async refresh(e){return this.call(this.authRpc,C_,{refresh_token:e})}async logout(e){return this.call(this.authRpc,O_,{refresh_token:e??null})}async me(){return this.call(this.authRpc,x_,{})}async getProfile(){return this.call(this.authRpc,N_,{})}async setSelfCert(e,t){return this.call(this.authRpc,P_,{self_cert:e,device_did:t??null})}async addDnsRecord(e){return this.call(this.authRpc,D_,vA(e))}async removeDnsRecord(e){return this.call(this.authRpc,B_,vA(e))}async listDnsRecords(){return this.call(this.authRpc,U_,{})}async getZoneInfo(){return this.call(this.authRpc,L_,{})}async bindDomain(e){return this.call(this.authRpc,M_,{domain:e})}async unbindDomain(e){return this.call(this.authRpc,F_,{domain:e})}async registerDeviceOnline(e){return this.call(this.deviceInfoRpc,j_,kA(e))}async updateDeviceOnline(e){return this.call(this.deviceInfoRpc,G_,kA(e))}async getDeviceOnline(e){return this.call(this.deviceInfoRpc,H_,{device_name:e.device_name??null,device_did:e.device_did??null})}async listDevicesOnline(e={}){const t={};return void 0!==e.state&&(t.state=e.state),void 0!==e.offset&&(t.offset=e.offset),void 0!==e.limit&&(t.limit=e.limit),this.call(this.deviceInfoRpc,V_,t)}async resolveOodByDid(e){return this.call(this.deviceInfoRpc,q_,{source_device_id:e})}async resolveOodByHostname(e){return this.call(this.deviceInfoRpc,W_,{dest_host:e})}async publishDnsTxt(e){const t={name:e.name,mode:e.mode};switch(void 0!==e.request_id&&(t.request_id=e.request_id),e.mode){case"add":if(!e.value)throw new J_("validation","publish_dns_txt mode=add requires value");t.value=e.value,void 0!==e.ttl&&(t.ttl=e.ttl);break;case"remove":if(!e.value)throw new J_("validation","publish_dns_txt mode=remove requires value");t.value=e.value;break;case"replace":if(!e.records)throw new J_("validation","publish_dns_txt mode=replace requires records");t.records=e.records.map(AA);break;default:throw new J_("validation",`publish_dns_txt mode \`${e.mode}\` is not supported`)}return this.call(this.bnsProxyRpc,z_,t)}async publishDocument(e){const t=null!==e.document&&"object"==typeof e.document&&!Array.isArray(e.document),n="string"==typeof e.document?e.document.trim().split("."):[],r=3===n.length&&n.every((e=>e.length>0));if(!t&&!r)throw new J_("validation","publish_document document must be a JSON object or non-empty compact JWT string");if("owner"===e.doc_type.trim().toLowerCase()&&!t)throw new J_("validation","owner document must be a JSON object");const s={name:e.name,doc_type:e.doc_type,document:e.document};return void 0!==e.request_id&&(s.request_id=e.request_id),this.call(this.bnsProxyRpc,$_,s)}async removeBoundZone(e){return this.call(this.bnsProxyRpc,K_,{name:e.name,zone_did:e.zone_did,expected_owner_hash:e.expected_owner_hash,request_id:e.request_id,owner_authorization:e.owner_authorization})}},SnClientError:J_,fetchSnRegionProbeConfig:async function(e,t=null,n={}){const r=wA(e),s={Accept:"application/json"};null!==t&&(/[\u0000-\u001f\u007f]/.test(t)&&sA("invalid cached region probe ETag: header value contains control characters"),s["If-None-Match"]=t);const i=new AbortController,o=setTimeout((()=>i.abort()),5e3);try{let e;try{e=await(n.fetcher??bA)(r,{method:"GET",headers:s,redirect:"manual",credentials:"omit",signal:i.signal})}catch(a){throw new J_("transport",`fetch SN region probe config from ${r} failed: ${String(a)}`)}if(304===e.status)return{kind:"not_modified"};if(404===e.status)return{kind:"not_configured"};if(200!==e.status)throw new J_("transport",`fetch SN region probe config from ${r} returned HTTP ${e.status}`);const t=e.headers.get("content-type")??"";if("application/json"!==t.split(";")[0].trim().toLowerCase())throw new J_("transport",`SN region probe config from ${r} has unsupported Content-Type ${JSON.stringify(t)}`);const o=e.headers.get("content-length");if(null!==o&&/^\d+$/.test(o)&&Number(o)>k_)throw new J_("transport",`SN region probe config from ${r} exceeds 1048576 bytes`);let c,l;try{c=await async function(e,t){if(!e.body){const n=new Uint8Array(await e.arrayBuffer());if(n.byteLength>k_)throw new J_("transport",`SN region probe config from ${t} exceeds 1048576 bytes`);return n}const n=e.body.getReader(),r=[];let s=0;for(;;){const{done:e,value:i}=await n.read();if(e)break;if(s+=i.byteLength,s>k_)throw await n.cancel(),new J_("transport",`SN region probe config from ${t} 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}(e,r)}catch(a){if(a instanceof J_)throw a;throw new J_("transport",`read SN region probe config from ${r} failed: ${String(a)}`)}try{l=yA(c)}catch(a){const e=a instanceof J_?a.detail:String(a);throw new J_("validation",`invalid SN region probe config from ${r}: ${e}`)}return{kind:"modified",document:{config:l,etag:e.headers.get("etag"),cache_control:e.headers.get("cache-control")}}}finally{clearTimeout(o)}},generateSnDeviceToken:async function(e,t,n,r=600){const s=Math.floor(Date.now()/1e3);return Mn.signJwtEdDSA({aud:_A,exp:s+r,iss:t,sub:e},n)},isCanonicalSnRegionId:dA,isPublicSnProbeIp:pA,normalizeSnRegionIdHint:function(e){const t=e.trim();if(0===iA(t)||iA(t)>128)return null;let n="",r=!1;for(const s of t)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:eA,parseSnRegionProbeConfig:yA,validateSnRegionProbeConfig:mA},Symbol.toStringTag,{value:"Module"}));let TA=null;function RA(e,t,n){let r=()=>{},s=null,i=0;const o=[];return{result:new Promise(((a,c)=>{let l;try{l=new Worker(function(){if(!TA){const e=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(e)}return TA}())}catch{return void c(new Error("Failed to create hash worker"))}r=()=>{l.terminate(),null==n||n.removeEventListener("abort",r),c(new Error("Hash cancelled"))},(null==n?void 0:n.aborted)?r():(null==n||n.addEventListener("abort",r,{once:!0}),l.onmessage=e=>{const t=e.data;if("chunk"===t.type){const e={index:t.index,hash:t.hash,offset:t.offset,length:t.length};o.push(e),i+=e.length,s&&s(i)}else"done"===t.type?(null==n||n.removeEventListener("abort",r),l.terminate(),a(o)):"error"===t.type&&(null==n||n.removeEventListener("abort",r),l.terminate(),c(new Error(t.message??"Worker hash error")))},l.onerror=e=>{null==n||n.removeEventListener("abort",r),l.terminate(),c(new Error(e.message??"Worker error"))},l.postMessage({file:e,chunkSize:t}))})),cancel:()=>r(),onProgress(e){s=e}}}class IA extends Error{constructor(e,t){super(t??e),this.code=e,this.name="NdmError"}}class CA extends Error{constructor(e,t,n,r){super(n??`NDM store API request failed with status ${e}`),this.name="NdmStoreApiError",this.status=e,this.errorCode=t,this.responseBody=r}}const OA=33554432,xA=4096,NA=new Map;let PA=0;let DA={getCapabilities:()=>({canRevealRealPath:!1,canUseNDMCache:!1,canUseNDMStore:!1,canPickDirectory:"undefined"!=typeof HTMLInputElement&&"webkitdirectory"in HTMLInputElement.prototype,canPickMixed:!1}),pickFiles(e){return new Promise(((t,n)=>{var r,s;const i=document.createElement("input");if(i.type="file","single_dir"===e.mode){if(!this.getCapabilities().canPickDirectory)return void n(new IA("DIRECTORY_NOT_SUPPORTED","This browser does not support directory selection"));i.webkitdirectory=!0}else"multi_file"!==e.mode&&"mixed"!==e.mode||(i.multiple=!0);e.accept&&e.accept.length>0&&"single_dir"!==e.mode&&(i.accept=e.accept.join(","));let o=!1;const a=()=>{var t;window.removeEventListener("focus",u),null==(t=e.signal)||t.removeEventListener("abort",l)},c=e=>{o||(o=!0,a(),n(e))},l=()=>c(new IA("USER_CANCELLED","Import cancelled")),u=()=>{setTimeout((()=>{o||c(new IA("USER_CANCELLED","User cancelled file selection"))}),500)};i.addEventListener("change",(()=>{if(o)return;const n=i.files;n&&0!==n.length?(o=!0,a(),t(Array.from(n))):c(new IA("single_dir"===e.mode?"EMPTY_DIRECTORY_UNAVAILABLE":"USER_CANCELLED","single_dir"===e.mode?"FileList cannot represent an empty directory; use a directory-tree provider":"No files selected"))})),i.addEventListener("cancel",l),window.addEventListener("focus",u),(null==(r=e.signal)?void 0:r.aborted)?l():(null==(s=e.signal)||s.addEventListener("abort",l,{once:!0}),i.click())}))}};function BA(e,t){if("undefined"!=typeof window&&"function"==typeof window.fetch)return window.fetch(e,t);if("undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch)return globalThis.fetch(e,t);throw new Error("fetch is not available in this runtime")}function UA(e){return e.replace(/\/+$/,"")}function LA(e){return encodeURIComponent(e).replace(/%3A/gi,":")}function MA(e){if(null==e?void 0:e.endpoint)return UA(e.endpoint);const t=Io();if(t)return UA(t);throw new IA("STORE_API_ENDPOINT_REQUIRED","NDM structured store endpoint is unknown; pass options.endpoint or call initBuckyOS first")}async function FA(e,t,n){var r;!function(){if(Ro()===Ni.Browser)throw new IA("STORE_API_NOT_SUPPORTED_IN_RUNTIME","NDM structured store APIs are not available in pure Browser runtime")}();const s=MA(n),i=(null==n?void 0:n.fetcher)??BA,o=void 0!==(null==n?void 0:n.sessionToken)?n.sessionToken:await Co(),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/${e}`,{method:"POST",headers:a,body:JSON.stringify(t),credentials:(null==n?void 0:n.credentials)??"include",signal:null==n?void 0:n.signal});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 e=l&&"object"==typeof l&&!Array.isArray(l)?l:null;throw new CA(c.status,null==e?void 0:e.error,(null==e?void 0:e.message)??("string"==typeof l&&l.length>0?l:`NDM store API request failed with status ${c.status}`),l)}return l}async function jA(e,t){const n=[`scope=${LA(e.scope)}`,`quick_hash=${LA(e.quick_hash)}`];e.inner_path&&n.push(`inner_path=${LA(e.inner_path)}`);const r=await async function(e,t){const n=MA(t),r=(null==t?void 0:t.fetcher)??BA,s=void 0!==(null==t?void 0:t.sessionToken)?t.sessionToken:await Co(),i={Accept:"application/json",...(null==t?void 0:t.headers)??{}};s&&!i.Authorization&&(i.Authorization=`Bearer ${s}`);const o=await r(`${n}${e}`,{method:"GET",headers:i,credentials:(null==t?void 0:t.credentials)??"include",signal:null==t?void 0:t.signal}),a=(o.headers.get("content-type")??"").includes("application/json")?await o.json():await o.text();if(!o.ok){const e=a&&"object"==typeof a&&!Array.isArray(a)?a:null;throw new CA(o.status,null==e?void 0:e.error,(null==e?void 0:e.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("&")}`,t);return function(e){try{return Mn.ObjId.fromString(e).isChunk()}catch{return!1}}(e.quick_hash),r}async function GA(e,t=33554432,n){iv(n);const r=e.size,s=[];if(r<=t){const t=new Uint8Array(await e.arrayBuffer()),i=Mn.sha256Bytes(t),o=Mn.ChunkId.fromMix256Result(t.length,i).toString();s.push({chunkId:o,offset:0,length:t.length,uploaded:!1});const a=new Mn.FileObject(e.name,r,o),[c,l]=a.genObjId();return iv(n),{objectId:c.toString(),chunks:s,fileObject:a.toJSON(),objects:[{obj_id:c.toString(),obj_data:l}]}}const i=new Mn.SimpleChunkList;let o=0;for(;o<r;){iv(n);const a=Math.min(o+t,r),c=new Uint8Array(await e.slice(o,a).arrayBuffer()),l=Mn.sha256Bytes(c),u=Mn.ChunkId.fromMix256Result(c.length,l);i.appendChunk(u),s.push({chunkId:u.toString(),offset:o,length:c.length,uploaded:!1}),o=a}const[a,c]=i.genObjId(),l=new Mn.FileObject(e.name,r,a.toString()),[u,h]=l.genObjId();return iv(n),{objectId:u.toString(),chunks:s,fileObject:l.toJSON(),objects:[{obj_id:a.toString(),obj_data:c},{obj_id:u.toString(),obj_data:h}]}}async function HA(e,t,n=33554432,r){if("undefined"==typeof Worker||"undefined"==typeof Blob||"undefined"==typeof URL||"function"!=typeof URL.createObjectURL||"undefined"==typeof crypto||void 0===crypto.subtle||0===e.size){const s=await GA(e,n,r);return null==t||t(e.size),s}let s,i;const o=RA(e,n,r);try{t&&o.onProgress(t);const e=new Promise(((e,t)=>{i=setTimeout((()=>{o.cancel(),t(new Error("hash worker timeout"))}),3e5)}));s=await Promise.race([o.result,e])}catch{return iv(r),GA(e,n,r)}finally{i&&clearTimeout(i)}iv(r);const a=e.size,c=[];if(1===s.length){const t=s[0],n=Mn.ChunkId.fromMix256Result(t.length,t.hash).toString();c.push({chunkId:n,offset:0,length:t.length,uploaded:!1});const i=new Mn.FileObject(e.name,a,n),[o,l]=i.genObjId();return iv(r),{objectId:o.toString(),chunks:c,fileObject:i.toJSON(),objects:[{obj_id:o.toString(),obj_data:l}]}}const l=new Mn.SimpleChunkList;for(const g of s){const e=Mn.ChunkId.fromMix256Result(g.length,g.hash);l.appendChunk(e),c.push({chunkId:e.toString(),offset:g.offset,length:g.length,uploaded:!1})}const[u,h]=l.genObjId(),d=new Mn.FileObject(e.name,a,u.toString()),[f,p]=d.genObjId();return iv(r),{objectId:f.toString(),chunks:c,fileObject:d.toJSON(),objects:[{obj_id:u.toString(),obj_data:h},{obj_id:f.toString(),obj_data:p}]}}function VA(e,t,n){const r=new Mn.FileObject(e,t,n),[s]=r.genObjId();return{objectId:s.toString(),fileObject:r.toJSON()}}function qA(){var e;const t=Io();return t?UA(t):"undefined"!=typeof window&&(null==(e=window.location)?void 0:e.origin)?UA(window.location.origin):void 0}async function WA(e){return e.size<12288?null:zA(e)}async function zA(e){const t=e.size;let n;if(t<12288)n=new Uint8Array(await e.arrayBuffer());else{n=new Uint8Array(12288);const r=[0,Math.floor((t-xA)/2),t-xA];for(let t=0;t<r.length;t++)n.set(new Uint8Array(await e.slice(r[t],r[t]+xA).arrayBuffer()),t*xA)}return Mn.ChunkId.fromMixHashResult(t,Mn.sha256Bytes(n),"qcid").toString()}async function $A(e,t,n){const r=t.endpoint??qA();if(!r)return null;const s=await WA(e);if(iv(t.signal),!s)return null;try{const n=await jA({scope:"app",quick_hash:s},{...t,endpoint:r});if(!0!==n.reusable||!("state"in n)||!["completed","same_as","local_link"].includes(n.state))return null;if(n.chunk_size!==e.size)return null;const i=function(e,t){const n=e;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 e=n[s];if("string"==typeof e&&e.length>0)return e}return"string"==typeof n.object_id&&n.object_id.length>0&&n.object_id!==t?n.object_id:void 0}(n,s);return!i||!Mn.ObjId.fromString(i).isChunk()&&!Mn.ObjId.fromString(i).isChunkList()||i.startsWith("qcid:")?null:{...VA(e.name,e.size,i),locality:"store",qcid:s}}catch(i){return iv(t.signal),i instanceof CA&&404===i.status||n.push(`QCID lookup for ${e.name}: ${sv(i)}`),null}}function KA(e){if(!e||"."===e||".."===e||/[\\/\x00-\x1f]/.test(e)||/^[a-z]:/i.test(e))throw new IA("INVALID_IMPORT_PATH",`Invalid file or directory name: ${e}`)}function QA(e){const t=e.split("/");return t.forEach(KA),t}function JA(e,t){if(0===e.length)throw new IA("EMPTY_DIRECTORY_UNAVAILABLE","FileList cannot represent an empty directory; use importDirectory with directory nodes");const n=e.map((e=>QA(e.webkitRelativePath||e.name)));if(n.some((e=>e.length<2||e[0]!==n[0][0])))throw new IA("INVALID_IMPORT_PATH","Folder selection must contain one root directory in webkitRelativePath");const r={kind:"dir",objectId:"",name:n[0][0],children:[]};for(let s=0;s<n.length;s++){const e=n[s].slice(1);let i=r;for(let r=0;r<e.length;r++){const o=e[r],a=i.children.find((e=>e.name===o));if(r===e.length-1){if(a)throw new IA("IMPORT_PATH_CONFLICT",`Duplicate file or directory: ${n[s].join("/")}`);if(o!==t[s].name)throw new IA("INVALID_IMPORT_PATH","Relative path basename must match File.name");i.children.push(t[s])}else{if("file"===(null==a?void 0:a.kind))throw new IA("IMPORT_PATH_CONFLICT",`File used as directory: ${o}`);const t=a??{kind:"dir",objectId:"",name:o,relativePath:e.slice(0,r+1).join("/"),children:[]};a||i.children.push(t),i=t}}}return r}function YA(e,t){const n=new Mn.DirObject(e.name);if(e.children)for(const i of e.children)if("file"===i.kind){if(!i._ndnFileObject)throw new IA("UPLOAD_FAILED",`Missing NDN FileObject for ${i.name}`);n.addFile(i.name,i._ndnFileObject,i.size)}else{const e=YA(i,t);n.addDirectory(i.name,Mn.ObjId.fromString(e.objectId),e.totalSize)}const[r,s]=n.genObjId();return e.objectId=r.toString(),t.set(e.objectId,{obj_id:e.objectId,obj_data:s}),{objectId:e.objectId,totalSize:n.total_size,fileCount:n.file_count,fileSize:n.file_size}}function ZA(e,t){if(!t||!t.enabled)return!1;if(!t.forTypes||0===t.forTypes.length)return e.type.startsWith("image/");for(const n of t.forTypes)if(n.endsWith("/*")){const t=n.slice(0,-1);if(e.type.startsWith(t))return!0}else if(n.startsWith(".")){if(e.name.toLowerCase().endsWith(n.toLowerCase()))return!0}else if(e.type===n)return!0;return!1}async function XA(e,t){const n=t.maxWidth??256,r=t.maxHeight??256;try{return e.type.startsWith("image/")?await function(e,t,n){return new Promise((r=>{const s=URL.createObjectURL(e),i=new Image;i.onload=()=>{let e=i.naturalWidth,o=i.naturalHeight;if(e>t||o>n){const r=Math.min(t/e,n/o);e=Math.round(e*r),o=Math.round(o*r)}const a=document.createElement("canvas");a.width=e,a.height=o;a.getContext("2d").drawImage(i,0,0,e,o);const c=a.toDataURL("image/jpeg",.8);URL.revokeObjectURL(s),r({available:!0,url:c,width:e,height:o,mimeType:"image/jpeg"})},i.onerror=()=>{URL.revokeObjectURL(s),r({available:!1,errorCode:"THUMBNAIL_GENERATION_FAILED"})},i.src=s}))}(e,n,r):{available:!1,errorCode:"UNSUPPORTED_TYPE"}}catch{return{available:!1,errorCode:"THUMBNAIL_GENERATION_FAILED"}}}async function ev(e,t){return tv(e,t)}async function tv(e,t,n){var r;iv(t.signal);const s=[...e],i=[];if(n){const e=(t,n)=>{KA(t.name);const r=new Set;for(const o of t.children){const t="file"===o.kind?o.file.name:o.name;if(KA(t),r.has(t))throw new IA("IMPORT_PATH_CONFLICT",`Duplicate child: ${n}/${t}`);r.add(t),"file"===o.kind?(s.push(o.file),i.push(`${n}/${t}`)):e(o,`${n}/${o.name}`)}};e(n,n.name)}if(!n&&0===s.length)throw new IA("single_dir"===t.mode?"EMPTY_DIRECTORY_UNAVAILABLE":"USER_CANCELLED","single_dir"===t.mode?"FileList cannot represent empty directories; use importDirectory":"No files selected");if("single_file"===t.mode&&1!==s.length)throw new IA("INVALID_IMPORT_PATH","single_file requires exactly one file");s.forEach((e=>{KA(e.name),e.webkitRelativePath&&QA(e.webkitRelativePath)})),n||"single_dir"!==t.mode||JA(s,s.map((e=>({kind:"file",objectId:"",name:e.name,size:e.size}))));const o=[];n||"single_dir"!==t.mode||o.push("FileList selections cannot preserve empty directories");const a=new Map,c=[],l={endpoint:t.endpoint,sessionToken:t.sessionToken,fetcher:t.fetcher,headers:t.headers,signal:t.signal},u=[],h=new Map;let d=!0;const f=t.onProgress,p=s.length;for(let E=0;E<s.length;E++){const e=s[E];iv(t.signal);const n=i[E]||e.webkitRelativePath||void 0;f&&f({phase:"qcid_lookup",fileIndex:E,fileCount:p,fileName:e.name,fileTotalBytes:e.size});const g=await $A(e,l,o);let m=null;g||(f&&f({phase:"materializing",fileIndex:E,fileCount:p,fileName:e.name,bytesProcessed:0,fileTotalBytes:e.size}),m=await HA(e,f?t=>{f({phase:"materializing",fileIndex:E,fileCount:p,fileName:e.name,bytesProcessed:t,fileTotalBytes:e.size})}:void 0,OA,t.signal));const y=(null==g?void 0:g.objectId)??m.objectId,w=(null==g?void 0:g.fileObject)??m.fileObject,b=g?[]:m.chunks;if(m)for(const t of m.objects)a.set(t.obj_id,t);else{const[,t]=new Mn.FileObject(e.name,e.size,w.content).genObjId();a.set(y,{obj_id:y,obj_data:t})}const _=(null==g?void 0:g.qcid)??await WA(e);_&&c.push({qcid:_,content_id:w.content,size:e.size}),iv(t.signal);const A={kind:"file",objectId:y,name:e.name,size:e.size,mimeType:e.type||void 0,relativePath:n,locality:(null==g?void 0:g.locality)??"local_only",_file:e,_ndnFileObject:w};if(ZA(e,t.thumbnails)){f&&f({phase:"thumbnail",fileIndex:E,fileCount:p,fileName:e.name,fileTotalBytes:e.size});!1!==(null==(r=t.thumbnails)?void 0:r.eager)?A.thumbnail=await XA(e,t.thumbnails):(A.thumbnail={available:!1},XA(e,t.thumbnails).then((e=>{A.thumbnail=e})))}u.push(A),g||(d=!1),h.set(y,{objectId:y,name:e.name,size:e.size,file:e,uploadedBytes:g?e.size:0,state:g?"completed":"pending",chunks:b})}let g,m;if("single_dir"===t.mode){let e=0;const t=n=>({kind:"dir",name:n.name,objectId:"",children:n.children.map((n=>"file"===n.kind?u[e++]:t(n)))}),r=n?t(n):JA(s,u);YA(r,a),g=[r],m=r}else g=u,m="single_file"===t.mode?u[0]:u;const y=function(e){let t=0,n=0,r=0;return function e(s){for(const i of s)"file"===i.kind?(t++,r+=i.size):(n++,i.children&&e(i.children))}(e),{totalObjects:t+n,totalFiles:t,totalDirs:n,totalBytes:r}}(g),w=(PA+=1,`import-${Date.now()}-${PA}`),b=d?"all_in_store":"ok",_="not_started",A={sessionId:w,items:g,materializationStatus:b,uploadStatus:_,summary:y,objectStates:h,objectStatus:"pending",warnings:o,manifest:a,qcidLinks:c,requestOptions:l,transmittedBytes:0};NA.set(w,A);const v={sessionId:w,selection:m,items:g,objectStatus:"pending",warnings:o,materializationStatus:b,uploadStatus:_,summary:y};return t.autoStartUpload&&(av(w,{endpoint:t.endpoint,sessionToken:t.sessionToken,fetcher:t.fetcher,headers:t.headers,signal:t.signal}).catch((()=>{})),v.uploadStatus="uploading"),v}async function nv(e){const t=NA.get(e);if(!t)throw new IA("SESSION_NOT_FOUND",`Session ${e} not found`);const n={};let r=0,s=0;const i=e=>{for(const o of e){if("dir"===o.kind){i(o.children??[]);continue}const e=t.objectStates.get(o.objectId);n[o.objectId]={objectId:o.objectId,uploadedBytes:e.uploadedBytes,totalBytes:e.size,state:e.state},r+=e.uploadedBytes,"completed"===e.state&&s++}};return i(t.items),{sessionId:e,materializationStatus:t.materializationStatus,uploadStatus:t.uploadStatus,objectStatus:t.objectStatus,error:t.error,warnings:[...t.warnings],summary:t.summary,progress:{uploadedBytes:r,uploadedObjects:s,totalBytes:t.summary.totalBytes,totalObjects:t.summary.totalFiles},perObjectProgress:n}}async function rv(e){const t=await nv(e),n={sessionId:e,uploadStatus:t.uploadStatus,objectStatus:t.objectStatus,error:t.error,warnings:t.warnings,transmittedBytes:ov(e).transmittedBytes,totalBytes:t.progress.totalBytes,uploadedBytes:t.progress.uploadedBytes,totalObjects:t.progress.totalObjects,uploadedObjects:t.progress.uploadedObjects,perObjectProgress:t.perObjectProgress},r=NA.get(e);if(r.uploadStartTime&&"uploading"===t.uploadStatus&&(n.elapsedMs=Date.now()-r.uploadStartTime,n.uploadedBytes>0&&n.elapsedMs>0)){n.speedBps=Math.round(1e3*n.uploadedBytes/n.elapsedMs);const e=n.totalBytes-n.uploadedBytes;n.estimatedRemainingMs=Math.round(1e3*e/n.speedBps)}return n}function sv(e){return e instanceof Error?e.message:String(e)}function iv(e){if(null==e?void 0:e.aborted)throw new IA("USER_CANCELLED","Import cancelled")}function ov(e){const t=NA.get(e);if(!t)throw new IA("SESSION_NOT_FOUND",`Session ${e} not found`);return t}async function av(e,t={}){var n;const r=ov(e);if("ready"===r.objectStatus||r.uploadPromise)return nv(e);const s=t.concurrency??3;if(!Number.isInteger(s)||s<1)throw new IA("UPLOAD_FAILED","concurrency must be a positive integer");iv(t.signal),r.requestOptions={...r.requestOptions,...Object.fromEntries(Object.entries({endpoint:t.endpoint,sessionToken:t.sessionToken,fetcher:t.fetcher,headers:t.headers}).filter((([,e])=>void 0!==e)))};const i=r.requestOptions.endpoint??qA();if(!i)throw new IA("STORE_API_ENDPOINT_REQUIRED","Pass endpoint or initialize the SDK before uploading");r.requestOptions.endpoint=UA(i),r.abortController=new AbortController;const o=()=>{var e;return null==(e=r.abortController)?void 0:e.abort()};return null==(n=t.signal)||n.addEventListener("abort",o,{once:!0}),r.requestOptions.signal=r.abortController.signal,r.uploadStatus="uploading",r.objectStatus="pending",r.error=void 0,r.onProgress=t.onProgress,r.uploadStartTime=Date.now(),r.uploadPromise=async function(e,t){var n;const r=[...e.objectStates.values()],s=new Map;let i,o=0;const a=Array.from({length:Math.min(t,r.length)},(async()=>{for(var t,n;o<r.length&&!i;){const c=r[o++];try{if(iv(null==(t=e.abortController)?void 0:t.signal),"completed"===c.state)continue;c.state="uploading";for(const[t,r]of c.chunks.entries()){if(iv(null==(n=e.abortController)?void 0:n.signal),r.uploaded)continue;let i=s.get(r.chunkId);i||(i=uv(e,c,r,t),s.set(r.chunkId,i)),await i,r.uploaded=!0,c.uploadedBytes=c.chunks.filter((e=>e.uploaded)).reduce(((e,t)=>e+t.length),0),lv(e)}c.uploadedBytes=c.size,c.state="completed"}catch(a){c.state="failed",i=a}}}));if(await Promise.all(a),i)throw i;iv(null==(n=e.abortController)?void 0:n.signal),e.objectStatus="finalizing",lv(e);const c=e.requestOptions,l=void 0!==c.sessionToken?c.sessionToken:await Co(),u=await(c.fetcher??BA)(`${c.endpoint}/ndm/v1/import/finalize`,{method:"POST",credentials:"include",signal:c.signal,headers:{...c.headers,"Content-Type":"application/json",...l?{Authorization:`Bearer ${l}`}:{}},body:JSON.stringify({objects:[...e.manifest.values()],roots:e.items.map((e=>e.objectId)),qcid_links:e.qcidLinks})}),h=await u.json();if(!u.ok)throw new CA(u.status,h.error,h.message??"Object registration failed",h);iv(c.signal),Array.isArray(h.warnings)&&e.warnings.push(...h.warnings.map(String));if(!0!==h.ready||!Array.isArray(h.roots)||e.items.some((e=>!h.roots.some((t=>t.obj_id===e.objectId&&!0===t.ready)))))throw new IA("OBJECT_NOT_READY","NDM did not confirm all root objects and their dependencies are ready");e.objectStatus="ready",e.uploadStatus=0===e.transmittedBytes?"not_required":"completed",e.materializationStatus="all_in_store",lv(e)}(r,s).catch((e=>{var t;r.error=sv(e);const n=null==(t=r.abortController)?void 0:t.signal.aborted;throw r.uploadStatus=n?"cancelled":"failed",r.objectStatus=n?"cancelled":"failed",e})).finally((()=>{var e;r.uploadPromise=void 0,null==(e=t.signal)||e.removeEventListener("abort",o),lv(r)})),r.uploadPromise.catch((()=>{})),nv(e)}function cv(e){var t;const n=ov(e);"ready"!==n.objectStatus&&(null==(t=n.abortController)||t.abort(),n.uploadStatus="cancelled",n.objectStatus="cancelled")}function lv(e){e.onProgress&&NA.has(e.sessionId)&&rv(e.sessionId).then((t=>{var n;return null==(n=e.onProgress)?void 0:n.call(e,t)})).catch((()=>{}))}async function uv(e,t,n,r){var s,i;try{const t=await jA({scope:"app",quick_hash:n.chunkId},e.requestOptions);if(!0===t.reusable&&"state"in t&&["completed","same_as","local_link"].includes(t.state)&&t.chunk_size===n.length)return}catch(a){iv(null==(s=e.abortController)?void 0:s.signal),a instanceof CA&&404===a.status||e.warnings.push(`Chunk lookup: ${sv(a)}`)}const o=void 0!==e.requestOptions.sessionToken?e.requestOptions.sessionToken:await Co();await async function(e,t,n,r,s,i,o,c,l){const u=t.slice(n.offset,n.offset+n.length),h=new Uint8Array(await u.arrayBuffer()),d=n.chunkId;let f;try{f=await Promise.resolve().then((()=>require("./tus_client-65c5fc5e.js")))}catch(a){const t=a instanceof Error?a.message:String(a);throw new IA("UPLOAD_FAILED",`Failed to load tus-js-client: ${t}`)}return new Promise(((a,u)=>{if(null==l?void 0:l.aborted)return void u(new IA("UPLOAD_FAILED","Upload aborted"));const p=new Blob([h]),g=new f.Upload(p,{endpoint:`${e}/ndm/v1/uploads`,..."undefined"==typeof XMLHttpRequest?{httpStack:f.fetchHttpStack}:{},headers:{...o,...i?{Authorization:`Bearer ${i}`}:{}},chunkSize:h.length,retryDelays:[0,1e3,3e3,5e3],storeFingerprintForResuming:!1,metadata:{logical_path:d,file_name:t.name,file_size:String(t.size),file_hash:s,chunk_index:String(r),chunk_hash:n.chunkId,mime_type:t.type||"application/octet-stream"},onProgress:e=>{c(e)},onSuccess:()=>{c(h.length),null==l||l.removeEventListener("abort",m),a(n.chunkId)},onError:e=>{null==l||l.removeEventListener("abort",m),u(new IA("UPLOAD_FAILED",e.message))}}),m=()=>{Promise.resolve(g.abort(!0)).catch((()=>{})),u(new IA("USER_CANCELLED","Upload cancelled"))};null==l||l.addEventListener("abort",m,{once:!0}),g.start()}))}(e.requestOptions.endpoint,t.file,n,r,t.objectId,o,e.requestOptions.headers,(n=>{t.uploadedBytes=t.chunks.filter((e=>e.uploaded)).reduce(((e,t)=>e+t.length),0)+n,lv(e)}),null==(i=e.abortController)?void 0:i.signal),e.transmittedBytes+=n.length}const hv=Object.freeze(Object.defineProperty({__proto__:null,NdmError:IA,NdmStoreApiError:CA,addChunkBySameAs:async function(e,t){return FA("add_chunk_by_same_as",e,t)},anchorState:async function(e,t){return FA("anchor_state",e,t)},applyEdge:async function(e,t){return FA("apply_edge",e,t)},calculateQcidFromFile:zA,cancelImportSession:cv,debugDumpExpandState:async function(e,t){return FA("debug_dump_expand_state",e,t)},ensureUploaded:async function(e,t={}){await av(e,t);const n=ov(e);if(await n.uploadPromise,"ready"!==n.objectStatus)throw new IA("OBJECT_NOT_READY",n.error??"Objects are not ready");return nv(e)},forcedGcUntil:async function(e,t){return FA("forced_gc_until",e,t)},fsAcquire:async function(e,t){return FA("fs_acquire",e,t)},fsAnchorState:async function(e,t){return FA("fs_anchor_state",e,t)},fsRelease:async function(e,t){return FA("fs_release",e,t)},fsReleaseInode:async function(e,t){return FA("fs_release_inode",e,t)},getDirChild:async function(e,t){return FA("get_dir_child",e,t)},getImportProvider:function(){return DA},getImportSessionStatus:nv,getObject:async function(e,t){return FA("get_object",e,t)},getUploadProgress:rv,haveChunk:async function(e,t){return FA("have_chunk",e,t)},importDirectory:async function(e,t={}){return tv([],{...t,mode:"single_dir"},e)},importFiles:ev,isObjectExist:async function(e,t){return FA("is_object_exist",e,t)},isObjectStored:async function(e,t){return FA("is_object_stored",e,t)},lookupObject:jA,openObject:async function(e,t){return FA("open_object",e,t)},outboxCount:async function(e){return FA("outbox_count",{},e)},pickupAndImport:async function(e){const t=e.provider??DA,n=t.getCapabilities();if("single_dir"===e.mode&&!n.canPickDirectory)throw new IA("DIRECTORY_NOT_SUPPORTED");if("mixed"===e.mode&&!n.canPickMixed)throw new IA("MODE_NOT_SUPPORTED_IN_RUNTIME");return iv(e.signal),ev(await t.pickFiles(e),e)},pin:async function(e,t){return FA("pin",e,t)},putObject:async function(e,t){return FA("put_object",e,t)},queryChunkState:async function(e,t){return FA("query_chunk_state",e,t)},queryObjectById:async function(e,t){return FA("query_object_by_id",e,t)},releaseImportSession:function(e){const t=ov(e);cv(e),NA.delete(e);const n=e=>e.forEach((e=>{"dir"===e.kind?n(e.children??[]):(delete e._file,delete e._ndnFileObject)}));n(t.items)},removeChunk:async function(e,t){return FA("remove_chunk",e,t)},removeObject:async function(e,t){return FA("remove_object",e,t)},setImportProvider:function(e){DA=e},startUpload:av,unpin:async function(e,t){return FA("unpin",e,t)},unpinOwner:async function(e,t){return FA("unpin_owner",e,t)}},Symbol.toStringTag,{value:"Module"})),dv="/ndm/proxy/v1";class fv extends Error{constructor(e,t,n,r){super(n??`NDM proxy request failed with status ${e}`),this.name="NdmProxyApiError",this.status=e,this.errorCode=t,this.responseBody=r}}class pv extends Error{constructor(e,t){super(t??e),this.name="NdmProxyError",this.code=e}}function gv(e,t){if("undefined"!=typeof window&&"function"==typeof window.fetch)return window.fetch(e,t);if("undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch)return globalThis.fetch(e,t);throw new Error("fetch is not available in this runtime")}function mv(e){return e.replace(/\/+$/,"")}function yv(){const e=Ro();if(e===Ni.Browser||e===Ni.AppRuntime)throw new pv("PROXY_API_NOT_SUPPORTED_IN_RUNTIME","NDM proxy APIs are not available in Browser/AppRuntime; use ndm_client for browser import/upload flows")}function wv(e){if(null==e?void 0:e.endpoint)return mv(e.endpoint);const t=Io();if(t)return mv(t);throw new pv("PROXY_API_ENDPOINT_REQUIRED","NDM proxy endpoint is unknown; pass options.endpoint or call initBuckyOS first")}async function bv(e,t){const n=void 0!==(null==e?void 0:e.sessionToken)?e.sessionToken:await Co(),r={...t,...(null==e?void 0:e.headers)??{}};return n&&!r.Authorization&&(r.Authorization=`Bearer ${n}`),r}async function _v(e){const t=(e.headers.get("content-type")??"").includes("application/json")?await e.json():await e.text(),n=t&&"object"==typeof t&&!Array.isArray(t)?t:null;throw new fv(e.status,null==n?void 0:n.error,(null==n?void 0:n.message)??("string"==typeof t&&t.length>0?t:`NDM proxy request failed with status ${e.status}`),t)}async function Av(e,t,n){var r;yv();const s=wv(n),i=(null==n?void 0:n.fetcher)??gv,o=await bv(n,{Accept:"application/json","Content-Type":"application/json"}),a=await i(`${s}${dv}/rpc/${e}`,{method:"POST",headers:o,body:JSON.stringify(t),credentials:(null==n?void 0:n.credentials)??"include"});if(!a.ok)return _v(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 e=await a.text();throw new fv(a.status,"invalid_data",e.length>0?e:"NDM proxy JSON RPC returned a non-JSON response",e)}return await a.json()}function vv(e,t){const n=e.get(t);if(null===n||""===n.trim())return null;const r=Number(n);return Number.isFinite(r)?r:null}async function Ev(e,t,n){yv();const r=wv(n),s=(null==n?void 0:n.fetcher)??gv,i=await bv(n,{Accept:"application/octet-stream","Content-Type":"application/json"}),o=await s(`${r}${dv}${e}`,{method:"POST",headers:i,body:JSON.stringify(t),credentials:(null==n?void 0:n.credentials)??"include"});return o.ok?{response:o,body:o.body,totalSize:vv(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:vv(o.headers,"Content-Length"),offset:vv(o.headers,"NDM-Offset")}:_v(o)}async function kv(e){const t=await e.response.arrayBuffer();return new Uint8Array(t)}class Sv{constructor(e){this.options=e}getObject(e,t){return Cv(e,{...this.options,...t})}openObject(e,t){return Ov(e,{...this.options,...t})}getDirChild(e,t){return xv(e,{...this.options,...t})}isObjectStored(e,t){return Nv(e,{...this.options,...t})}isObjectExist(e,t){return Pv(e,{...this.options,...t})}queryObjectById(e,t){return Dv(e,{...this.options,...t})}putObject(e,t){return Bv(e,{...this.options,...t})}removeObject(e,t){return Uv(e,{...this.options,...t})}haveChunk(e,t){return Lv(e,{...this.options,...t})}queryChunkState(e,t){return Mv(e,{...this.options,...t})}removeChunk(e,t){return Fv(e,{...this.options,...t})}addChunkBySameAs(e,t){return jv(e,{...this.options,...t})}applyEdge(e,t){return Gv(e,{...this.options,...t})}pin(e,t){return Hv(e,{...this.options,...t})}unpin(e,t){return Vv(e,{...this.options,...t})}unpinOwner(e,t){return qv(e,{...this.options,...t})}fsAcquire(e,t){return Wv(e,{...this.options,...t})}fsRelease(e,t){return zv(e,{...this.options,...t})}fsReleaseInode(e,t){return $v(e,{...this.options,...t})}fsAnchorState(e,t){return Kv(e,{...this.options,...t})}forcedGcUntil(e,t){return Qv(e,{...this.options,...t})}outboxCount(e){return Jv({...this.options,...e})}debugDumpExpandState(e,t){return Yv(e,{...this.options,...t})}anchorState(e,t){return Zv(e,{...this.options,...t})}}class Tv{constructor(e){this.options=e}openChunkReader(e,t){return Xv(e,{...this.options,...t})}getChunkData(e,t){return eE(e,{...this.options,...t})}getChunkPiece(e,t){return tE(e,{...this.options,...t})}openChunkListReader(e,t){return nE(e,{...this.options,...t})}openReader(e,t){return rE(e,{...this.options,...t})}}class Rv{constructor(e){this.options=e}putChunkByReader(e,t,n){return sE(e,t,{...this.options,...n})}putChunk(e,t,n){return iE(e,t,{...this.options,...n})}}class Iv{constructor(e){this.options=e,this.rpc=new Sv(e),this.reader=new Tv(e),this.writer=new Rv(e)}getObject(e,t){return this.rpc.getObject(e,t)}openObject(e,t){return this.rpc.openObject(e,t)}getDirChild(e,t){return this.rpc.getDirChild(e,t)}isObjectStored(e,t){return this.rpc.isObjectStored(e,t)}isObjectExist(e,t){return this.rpc.isObjectExist(e,t)}queryObjectById(e,t){return this.rpc.queryObjectById(e,t)}putObject(e,t){return this.rpc.putObject(e,t)}removeObject(e,t){return this.rpc.removeObject(e,t)}haveChunk(e,t){return this.rpc.haveChunk(e,t)}queryChunkState(e,t){return this.rpc.queryChunkState(e,t)}removeChunk(e,t){return this.rpc.removeChunk(e,t)}addChunkBySameAs(e,t){return this.rpc.addChunkBySameAs(e,t)}applyEdge(e,t){return this.rpc.applyEdge(e,t)}pin(e,t){return this.rpc.pin(e,t)}unpin(e,t){return this.rpc.unpin(e,t)}unpinOwner(e,t){return this.rpc.unpinOwner(e,t)}fsAcquire(e,t){return this.rpc.fsAcquire(e,t)}fsRelease(e,t){return this.rpc.fsRelease(e,t)}fsReleaseInode(e,t){return this.rpc.fsReleaseInode(e,t)}fsAnchorState(e,t){return this.rpc.fsAnchorState(e,t)}forcedGcUntil(e,t){return this.rpc.forcedGcUntil(e,t)}outboxCount(e){return this.rpc.outboxCount(e)}debugDumpExpandState(e,t){return this.rpc.debugDumpExpandState(e,t)}anchorState(e,t){return this.rpc.anchorState(e,t)}openChunkReader(e,t){return this.reader.openChunkReader(e,t)}getChunkData(e,t){return this.reader.getChunkData(e,t)}getChunkPiece(e,t){return this.reader.getChunkPiece(e,t)}openChunkListReader(e,t){return this.reader.openChunkListReader(e,t)}openReader(e,t){return this.reader.openReader(e,t)}putChunkByReader(e,t,n){return this.writer.putChunkByReader(e,t,n)}putChunk(e,t,n){return this.writer.putChunk(e,t,n)}withOptions(e){return new Iv({...this.options,...e})}}async function Cv(e,t){return Av("get_object",e,t)}async function Ov(e,t){return Av("open_object",e,t)}async function xv(e,t){return Av("get_dir_child",e,t)}async function Nv(e,t){return Av("is_object_stored",e,t)}async function Pv(e,t){return Av("is_object_exist",e,t)}async function Dv(e,t){return Av("query_object_by_id",e,t)}async function Bv(e,t){return Av("put_object",e,t)}async function Uv(e,t){return Av("remove_object",e,t)}async function Lv(e,t){return Av("have_chunk",e,t)}async function Mv(e,t){return Av("query_chunk_state",e,t)}async function Fv(e,t){return Av("remove_chunk",e,t)}async function jv(e,t){return Av("add_chunk_by_same_as",e,t)}async function Gv(e,t){return Av("apply_edge",e,t)}async function Hv(e,t){return Av("pin",e,t)}async function Vv(e,t){return Av("unpin",e,t)}async function qv(e,t){return Av("unpin_owner",e,t)}async function Wv(e,t){return Av("fs_acquire",e,t)}async function zv(e,t){return Av("fs_release",e,t)}async function $v(e,t){return Av("fs_release_inode",e,t)}async function Kv(e,t){return Av("fs_anchor_state",e,t)}async function Qv(e,t){return Av("forced_gc_until",e,t)}async function Jv(e){return Av("outbox_count",{},e)}async function Yv(e,t){return Av("debug_dump_expand_state",e,t)}async function Zv(e,t){return Av("anchor_state",e,t)}async function Xv(e,t){return Ev("/read/chunk/open",e,t)}async function eE(e,t){return kv(await Ev("/read/chunk/data",e,t))}async function tE(e,t){return kv(await Ev("/read/chunk/piece",e,t))}async function nE(e,t){return Ev("/read/chunklist/open",e,t)}async function rE(e,t){return Ev("/read/object/open",e,t)}async function sE(e,t,n){var r;yv();const s=wv(n),i=(null==n?void 0:n.fetcher)??gv,o=function(e){return e instanceof Uint8Array||e instanceof ArrayBuffer?e.byteLength:"undefined"!=typeof Blob&&e instanceof Blob?e.size:"string"==typeof e?(new TextEncoder).encode(e).byteLength:null}(t),a=(null==n?void 0:n.chunkSize)??o;if(null===a)throw new pv("PROXY_API_CHUNK_SIZE_REQUIRED","chunkSize is required when the request body length cannot be inferred");const c=await bv(n,{Accept:"application/json","Content-Type":"application/octet-stream","Content-Length":String(a),"NDM-Chunk-Size":String(a)}),l=await i(`${s}${function(e){return`${dv}/write/chunk/${encodeURIComponent(e)}`}(e)}`,{method:"PUT",headers:c,body:t,credentials:(null==n?void 0:n.credentials)??"include"});return l.ok?(await(null==(r=l.body)?void 0:r.cancel()),{chunkSize:vv(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}):_v(l)}async function iE(e,t,n){return sE(e,t,{...n,chunkSize:(null==n?void 0:n.chunkSize)??t.byteLength})}const oE=Object.freeze(Object.defineProperty({__proto__:null,NDM_PROXY_V1_PATH:dv,NdmProxyApiError:fv,NdmProxyClient:Iv,NdmProxyError:pv,NdmProxyReaderClient:Tv,NdmProxyRpcClient:Sv,NdmProxyWriterClient:Rv,addChunkBySameAs:jv,anchorState:Zv,applyEdge:Gv,createNdmProxyClient:function(e){return new Iv(e)},debugDumpExpandState:Yv,forcedGcUntil:Qv,fsAcquire:Wv,fsAnchorState:Kv,fsRelease:zv,fsReleaseInode:$v,getChunkData:eE,getChunkPiece:tE,getDirChild:xv,getObject:Cv,haveChunk:Lv,isObjectExist:Pv,isObjectStored:Nv,openChunkListReader:nE,openChunkReader:Xv,openObject:Ov,openReader:rE,outboxCount:Jv,pin:Hv,putChunk:iE,putChunkByReader:sE,putObject:Bv,queryChunkState:Mv,queryObjectById:Dv,removeChunk:Fv,removeObject:Uv,unpin:Vv,unpinOwner:qv},Symbol.toStringTag,{value:"Module"}));class aE extends Error{constructor(e,t="unavailable",n=!1){super(e),this.code=t,this.effectUnknown=n,this.name="ExecutorStreamError"}}function cE(e){const t=(new TextEncoder).encode(JSON.stringify(e));if(t.length>1048576)throw new Error("Executor control frame exceeds 1 MiB");const n=new Uint8Array(5+t.length);return n[0]=1,new DataView(n.buffer).setUint32(1,t.length),n.set(t,5),n}class lE{constructor(e,t,n){this.socket=e,this.target=t,this.runId=n,this.buffer=new Uint8Array,this.sequence=0,this.pending=new Map,this.closed=!1,e.binaryType="arraybuffer",e.onmessage=e=>{if(e.data instanceof ArrayBuffer)try{this.receive(new Uint8Array(e.data))}catch{this.fail(new aE("Invalid Command Stream frame","protocol"))}else this.fail(new aE("Expected binary Command Stream"))},e.onclose=()=>this.fail(new aE("Executor disconnected; query the persisted operation locator before taking further action","unavailable",!0)),e.onerror=()=>this.fail(new aE("Executor transport failed","unavailable",!0))}static async connect(e,t,n,r,s){if(e.executor_id!==t.executor_id||e.generation!==t.generation||e.profile_id!==t.profile_id||e.expires_at_ms<=Date.now())throw new aE("Route does not match the requested active executor","stale_target");const i=new URL(e.ws_url);if("wss:"!==i.protocol&&("ws:"!==i.protocol||!["localhost","127.0.0.1","[::1]"].includes(i.hostname)))throw new aE("Executor routes require WSS");if(i.username||i.password||i.hash)throw new aE("Invalid executor route URL");const o=new WebSocket(i);await new Promise(((t,n)=>{const r=setTimeout((()=>{o.close(),n(new aE("Route authentication timed out"))}),1e4);o.onopen=()=>o.send(JSON.stringify({ticket:e.ticket})),o.onmessage=e=>{try{if("string"!=typeof e.data||!0!==JSON.parse(e.data).ready)throw new Error;clearTimeout(r),t()}catch{clearTimeout(r),o.close(),n(new aE("Route authentication failed"))}},o.onerror=o.onclose=()=>{clearTimeout(r),n(new aE("Unable to connect executor route"))}}));const a=new lE(o,t,s);try{const e=await a.request("login",{v:1,token:n,profile:t.profile_id,client:{runtime_id:r,run_id:s}});if("login_ok"!==e.type||e.store_id!==t.store_id)throw new aE("Executor ledger changed","store_mismatch");return a}catch(c){throw a.close(),c}}receive(e){const t=new Uint8Array(this.buffer.length+e.length);for(t.set(this.buffer),t.set(e,this.buffer.length),this.buffer=t;this.buffer.length>=5;){const e=new DataView(this.buffer.buffer,this.buffer.byteOffset).getUint32(1);if(e>1048576||![1,2].includes(this.buffer[0]))throw new Error;if(this.buffer.length<e+5)return;const t=this.buffer[0],n=this.buffer.slice(5,e+5);if(this.buffer=this.buffer.slice(e+5),1!==t)continue;const r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n));if("closing"===r.type)return void this.fail(new aE("Executor stopped accepting requests"));const s=r.request_id&&this.pending.get(r.request_id);s&&(this.pending.delete(r.request_id),clearTimeout(s.timer),r.error?s.reject(new aE(r.error.message,r.error.code,r.error.effect_unknown)):s.resolve(r))}}fail(e){if(!this.closed){this.closed=!0;for(const t of this.pending.values())clearTimeout(t.timer),t.reject(e);this.pending.clear(),this.socket.close()}}close(){this.fail(new aE("Executor stream closed","unavailable",!0))}request(e,t={},n=4e4){if(this.closed)return Promise.reject(new aE("Executor stream is closed"));const r="q"+ ++this.sequence;return new Promise(((s,i)=>{const o=setTimeout((()=>{this.pending.delete(r),i(new aE("Executor response timed out; query operation before retrying","unavailable",!0))}),n);this.pending.set(r,{resolve:s,reject:i,timer:o});try{this.socket.send(cE({...t,type:e,request_id:r}))}catch{clearTimeout(o),this.pending.delete(r),i(new aE("Unable to send request","unavailable",!0))}}))}operation(e){if(e.executor_id!==this.target.executor_id||e.store_id!==this.target.store_id||e.profile_id!==this.target.profile_id)throw new aE("Operation locator belongs to another executor, profile or ledger","store_mismatch");return{store_id:e.store_id,op_id:e.op_id,run_id:e.run_id,call_id:e.call_id}}fresh(e){if(e.generation!==this.target.generation)throw new aE("Cannot dispatch an old operation to a new connection generation","stale_target");return this.operation(e)}async describe(e){const t=await this.request("describe",{workdir:e}),n=t.target;if("describe_ok"!==t.type||(null==n?void 0:n.executor_id)!==this.target.executor_id||(null==n?void 0:n.node_did)||(null==n?void 0:n.profile_id)!==this.target.profile_id||(null==n?void 0:n.store_id)!==this.target.store_id)throw new aE("Executor describe target changed","stale_target");return t}exec(e,t,n,r={},s=6e4){return this.request("exec",{...this.fresh(e),cmd:t,cwd:n,env_overrides:r,execution_timeout_ms:s})}read(e,t){return this.request("read",{...this.fresh(e),path:t,offset:0})}edit(e,t,n){return this.request("edit",{...this.fresh(e),path:t,edits:n})}async write(e,t,n,r="replace"){const s=this.fresh(e),i=(new TextEncoder).encode(e.op_id);if(0===i.length||i.length>128)throw new Error("Invalid operation ID");const o=Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",n))).map((e=>e.toString(16).padStart(2,"0"))).join(""),a=this.request("write",{...s,path:t,mode:r,content_length:n.length,content_hash:`sha256:${o}`});for(let c=0;c<n.length;c+=16384){const e=n.subarray(c,c+16384),t=new Uint8Array(16+i.length+e.length),r=new DataView(t.buffer);t[0]=2,r.setUint32(1,t.length-5),t[5]=4,r.setBigUint64(6,BigInt(c)),r.setUint16(14,i.length),t.set(i,16),t.set(e,16+i.length),this.socket.send(t)}return this.socket.send(cE({type:"upload_end",request_id:"end"+ ++this.sequence,op_id:e.op_id})),a}query(e,t,n=0,r=0){return this.operation(e),this.request("query",{store_id:e.store_id,op_id:e.op_id,channel:t,offset:n,max_bytes:262144,wait_ms:r})}cancel(e){return this.operation(e),this.request("cancel",{store_id:e.store_id,op_id:e.op_id})}}exports.ACCESS_DENIED_ERROR_CODE=Wn,exports.AGENT_DELEGATE_TASK_SCHEMA_ID="agent.delegate/v1",exports.AICC_AI_METHODS=Yr,exports.AICC_COMPUTE_TASK_SCHEMA_ID="aicc.compute/v1",exports.AICC_CORE_METHODS=Zr,exports.AICC_EXECUTION_MODES=ns,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=Xr,exports.AICC_METHODS=ts,exports.AICC_POLICY_REFUSAL_CODES=rs,exports.AICC_QUOTA_METHODS=es,exports.AICC_SERVICE_SERVICE_NAME="aicc",exports.AICC_SERVICE_SERVICE_PORT=4040,exports.AICC_SERVICE_UNIQUE_ID="aicc",exports.AIWORKSPACE_SERVICE_NAME=er,exports.ANONYMOUS_IDENTITY=Kn,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.AiWorkspaceClient=nr,exports.AiccClient=hs,exports.AiwsFailure=tr,exports.BNS_DNS_TXT_DEFAULT_TTL=600,exports.BNS_DNS_TXT_DOC_TYPE=r_,exports.BNS_EVM_DEFAULT_GAS_LIMIT=Xb,exports.BNS_EVM_DEFAULT_MAX_FEE_PER_GAS=e_,exports.BNS_EVM_DEFAULT_MAX_PRIORITY_FEE_PER_GAS=t_,exports.BNS_MAX_INLINE_DOCUMENT_BYTES=n_,exports.BNS_PUBLISH_DOCUMENT_ABI=i_,exports.BS_SERVICE_TASK_MANAGER="task-manager",exports.BS_SERVICE_VERIFY_HUB="verify-hub",exports.BnsEvmTxBuilder=f_,exports.BnsEvmTxError=l_,exports.BnsTxExecutor=class{constructor(e={}){this.localExecutionTail=Promise.resolve(),this.options=e,this.evmTxBuilder=e.bnsClient&&e.evmConfig?new f_(e.bnsClient,e.evmConfig,e.evmProvider):null}async resolveRoute(){const e=this.getRuntimeType(),t=m_(e)?await this.getLocalPrivateKey():null;return this.resolveRouteFor(e,t)}async resolveRouteFor(e,t){if(m_(e)&&this.options.evmConfig&&t)return"local";if(e===Ni.AppRuntime){const e=await this.getCurrentWalletUser();if(e&&!y_(e))return"wallet"}return"sn-proxy"}async execute(e){const t=this.getRuntimeType(),n=m_(t)?await this.getLocalPrivateKey():null,r=await this.resolveRouteFor(t,n);switch(r){case"local":return this.executeLocally(e,t,n);case"wallet":throw new p_("WALLET_EXECUTION_NOT_IMPLEMENTED",r,`BNS wallet execution is not implemented for operation ${e.type}`);case"sn-proxy":return this.executeWithSn(e)}}publishDnsTxt(e){return this.execute({type:"publish_dns_txt",request:e})}publishDocument(e){return this.execute({type:"publish_document",request:e})}getRuntimeType(){return(this.options.getRuntimeType??Ro)()}getCurrentWalletUser(){return Promise.resolve((this.options.getCurrentWalletUser??bo)())}async getLocalPrivateKey(){const e=this.options.localPrivateKey;return g_("function"==typeof e?await e():e)}async executeWithSn(e){const t=this.options.snClient;if(!t)throw new p_("SN_CLIENT_UNAVAILABLE","sn-proxy",`SN client is required for BNS operation ${e.type}`);const n="publish_dns_txt"===e.type?await t.publishDnsTxt(e.request):await t.publishDocument(e.request);return{route:"sn-proxy",operation:e.type,response:n}}async executeLocally(e,t,n){const r=this.options.bnsClient;if(!r)throw new p_("BNS_CLIENT_UNAVAILABLE","local",`BNS client is required for local operation ${e.type}`);const s=this.evmTxBuilder;if(!n||!s)throw new p_("LOCAL_SIGNING_UNAVAILABLE","local",`Local signing configuration is unavailable for operation ${e.type}`);return this.enqueueLocalExecution((async()=>{try{const t=await s.buildAndSign(e,n),i=await r.submitRawTx(t);return{route:"local",operation:e.type,response:i}}catch(t){throw s.resetNonce(),t}}))}enqueueLocalExecution(e){const t=this.localExecutionTail.then(e,e);return this.localExecutionTail=t.then((()=>{}),(()=>{})),t}},exports.BnsTxExecutorError=p_,exports.BuckyOSSDK=Oo,exports.CONTACT_CHANGED_EVENT_BOX="CONTACTS",exports.CONTACT_TAG_HOMESTATION_FOLLOWING=Fs,exports.CONTACT_TAG_ZONE_AGENT=Ms,exports.CONTACT_TAG_ZONE_USER=Ls,exports.DEFAULT_CHILD_CONTROL_POLICY={follow_pause:!0,follow_resume:!0,follow_cancel:!0},exports.DEFAULT_JUMP_BASE_URL=Yn,exports.DENY_REASONS=qn,exports.DOWNLOAD_TASK_SCHEMA_ID="download/v1",exports.EXTERNAL_PRINCIPAL_CLAIM=Di,exports.ExecutorClient=class{constructor(e,t=null,n={}){this.rpc=new Gn(e,t,null,n)}syncSessionToken(e){this.rpc.setSessionToken(e)}createDevice(e){return this.rpc.call("executor.device.create",e)}listDevices(){return this.rpc.call("executor.device.list",{})}issueAccess(e,t){return this.rpc.call("executor.device.issue",{executor_id:e,expires_at_ms:t})}revokeAccess(e){return this.rpc.call("executor.device.revoke",{executor_id:e})}deleteDevice(e){return this.rpc.call("executor.device.delete",{executor_id:e})}listOnline(){return this.rpc.call("executor.online.list",{})}async*watchOnline(e,t=5e3){if(t<250)throw new Error("Watch interval must be at least 250 ms");let n="";for(;!(null==e?void 0:e.aborted);){const{executors:r}=await this.listOnline(),s=JSON.stringify(r);s!==n&&(n=s,yield r),await new Promise((n=>{const r=()=>{clearTimeout(s),null==e||e.removeEventListener("abort",r),n()},s=setTimeout(r,t);null==e||e.addEventListener("abort",r,{once:!0}),(null==e?void 0:e.aborted)&&r()}))}}openRoute(e){return this.rpc.call("executor.stream.open",{executor_id:e.executor_id,generation:e.generation,profile_id:e.profile_id})}async connect(e,t,n,r){const s=await this.openRoute(e);return lE.connect(s,e,t,n,r)}},exports.ExecutorCommandStream=lE,exports.ExecutorStreamError=aE,exports.FRIEND_INTENT="buckyos.friend",exports.HUMAN_APPROVAL_SCHEMA_ID="human.approval/v1",exports.HUMAN_INPUT_TASK_SCHEMA_ID="human.input/v1",exports.JUMP_ACTION_PATHS=Zn,exports.KEventClient=mo,exports.KEventReader=uo,exports.MsgCenterClient=ii,exports.MsgQueueClient=Us,exports.NOTIFY_ACTION_ANSWER=Qs,exports.NOTIFY_ACTION_DISMISS=Js,exports.NOTIFY_CHOICE_CONTROL_ID=$s,exports.NOTIFY_DATA_VERSION=1,exports.NOTIFY_DELIVERED_INTENT="buckyos.notify.delivered",exports.NOTIFY_INTENT=Ws,exports.NOTIFY_LINK_PATH=Ys,exports.NOTIFY_SESSION_PREFIX=zs,exports.NOTIFY_TEXT_CONTROL_ID=Ks,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.RPCError=Fn,exports.RepoClient=wi,exports.RuntimeType=Ni,exports.SCHEDULER_DISPATCH_THUNK_TASK_SCHEMA_ID="scheduler.dispatch_thunk/v1",exports.StorageDomain=Or,exports.SystemConfigClient=Jr,exports.TASK_ERR_ALREADY_COMPLETED=fr,exports.TASK_ERR_CONTROL_ALREADY_PENDING=dr,exports.TASK_ERR_CONTROL_NOT_AVAILABLE=hr,exports.TASK_ERR_IDEMPOTENCY_CONFLICT=mr,exports.TASK_ERR_INPUT_SCHEMA_MISMATCH=pr,exports.TASK_ERR_INVALID_PHASE=ur,exports.TASK_ERR_NOT_FOUND=or,exports.TASK_ERR_PERMISSION_DENIED=ar,exports.TASK_ERR_RESULT_SCHEMA_MISMATCH=gr,exports.TASK_ERR_REVISION_CONFLICT=cr,exports.TASK_ERR_SCHEMA_NOT_FOUND=yr,exports.TASK_ERR_STALE_RUNNER_EPOCH=lr,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=wr,exports.TASK_POLICY_PRESET_COLLABORATIVE_TREE_V1="collaborative-tree/v1",exports.TOOL_EXEC_BASH_TASK_SCHEMA_ID="tool.exec_bash/v1",exports.TaskAction=Rr,exports.TaskControlAction=Tr,exports.TaskDataScope=Cr,exports.TaskEventType=xr,exports.TaskExecutorKind=Ar,exports.TaskGrantScope=Ir,exports.TaskManagerClient=Br,exports.TaskOutcome=Sr,exports.TaskPhase=vr,exports.TaskWaitReasonKind=kr,exports.USER_GROUP_REF_PREFIX=Vs,exports.USER_TYPE_GROUP_REF_PREFIX=Hs,exports.VerifyHubClient=ir,exports.WEB3_BRIDGE_HOST="web3.buckyos.ai",exports.WELL_KNOWN_CONTACT_TAGS=js,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=Kr,exports.WorkflowDefinitionStatus=jr,exports.WorkflowHumanActionKind=Vr,exports.WorkflowJoinMode=Mr,exports.WorkflowNodeRunState=Hr,exports.WorkflowOutputMode=Lr,exports.WorkflowRetryFallback=Fr,exports.WorkflowRunStatus=Gr,exports.WorkflowScheduledTaskFireStatus=zr,exports.WorkflowScheduledTaskMisfirePolicy=Wr,exports.WorkflowScheduledTaskStatus=qr,exports.WorkflowStepType=Ur,exports.ZONE_USER_TYPES=Pi,exports.accessDenialOf=function(e){return e instanceof Fn&&e.code===Wn?$n(e.data):null},exports.aiccMessageFirstText=function(e){var t;return null==(t=e.content.find((e=>"text"===e.type)))?void 0:t.text},exports.aiccMessageTextContent=function(e){return e.content.filter((e=>"text"===e.type)).map((e=>e.text)).join("\n")},exports.aiccRefusalOf=function(e){if(!(e instanceof Fn&&rs.includes(e.code)))return;const t=e.data;return{code:e.code,message:(null==t?void 0:t.message)??e.message,retriable:null==t?void 0:t.retriable,details:null==t?void 0:t.details}},exports.aiccTextMessage=function(e,t){return{role:e,content:[{type:"text",text:t}]}},exports.answerNotify=async function(e,t,n,r,s){const i=await e.notifyGet(n);if("notice"===i.kind)return r.dismiss?e.notifyDismiss(n):e.notifyAck(n);if(!i.task_id)throw new Fn(`notification ${n} has no task`);if(Zs(i.status))return i;const o=ci(r,i.prompt);if(o)throw new Fn(o);return await ui(t,i.task_id,r,s??i.to_user),e.notifyGet(n)},exports.appDidFromId=function(e){return Mn.DID.fromStr(vi(e)).toString()},exports.appIdFromDid=Ai,exports.baselineTaskControlProfile=function(e){return{pause:{kind:"Unavailable"},resume:{kind:"Unavailable"},cancel:{kind:"Interrupt"},updated_at:e}},exports.bns_client=Ma,exports.buildJumpUrl=function(e,t,n=Yn){const r=Zn[e];if(!r)throw new Error(`unregistered jump action: ${e}`);const s=new URL(n||Yn);if("https:"!==s.protocol&&"localhost"!==s.hostname)throw new Error("jump base must be https");const i=new URLSearchParams(t).toString();return`${s.origin}${r}${i?`#${i}`:""}`},exports.commitNotifyAnswer=ui,exports.contactTagApp=Gs,exports.contactTagKind=function(e){return e===Ls||e===Ms||qs(e)?"system":Gs(e)?"app":"user"},exports.createAppInstanceId=ki,exports.createSDKModule=function(e){const t=new Oo(e),n={initBuckyOS:t.initBuckyOS.bind(t),getBuckyOSConfig:t.getBuckyOSConfig.bind(t),getRuntimeType:t.getRuntimeType.bind(t),getAppId:t.getAppId.bind(t),getAppDid:t.getAppDid.bind(t),getAppInstanceId:t.getAppInstanceId.bind(t),getAppDataDir:t.getAppDataDir.bind(t),getKEventClient:t.getKEventClient.bind(t),createEventReader:t.createEventReader.bind(t),create_event_reader:t.create_event_reader.bind(t),subscribeKEvent:t.subscribeKEvent.bind(t),attachEvent:t.attachEvent.bind(t),removeEvent:t.removeEvent.bind(t),getAccountInfo:t.getAccountInfo.bind(t),loginByPassword:t.loginByPassword.bind(t),loginByBrowserSSO:t.loginByBrowserSSO.bind(t),loginByRuntimeSession:t.loginByRuntimeSession.bind(t),login:t.login.bind(t),logout:t.logout.bind(t),getAppSetting:t.getAppSetting.bind(t),setAppSetting:t.setAppSetting.bind(t),getCurrentWalletUser:t.getCurrentWalletUser.bind(t),getCurrentIdentity:t.getCurrentIdentity.bind(t),resolve_did:t.resolve_did.bind(t),walletSignWithActiveDid:t.walletSignWithActiveDid.bind(t),openExternalUrl:t.openExternalUrl.bind(t),getZoneHostName:t.getZoneHostName.bind(t),getZoneServiceURL:t.getZoneServiceURL.bind(t),getServiceRpcClient:t.getServiceRpcClient.bind(t),getVerifyHubClient:t.getVerifyHubClient.bind(t),getSystemConfigClient:t.getSystemConfigClient.bind(t),getTaskManagerClient:t.getTaskManagerClient.bind(t),getWorkflowClient:t.getWorkflowClient.bind(t),getAiccClient:t.getAiccClient.bind(t),getAiWorkspaceClient:t.getAiWorkspaceClient.bind(t),getMsgQueueClient:t.getMsgQueueClient.bind(t),getMsgCenterClient:t.getMsgCenterClient.bind(t),getRepoClient:t.getRepoClient.bind(t)};return{...n,buckyos:{kRPCClient:Gn,AuthClient:Vn,...n,hashPassword:Mn.hashPassword}}},exports.decisionRequirements=ms,exports.decodeBnsPublishDocumentCalldata=function(e){return o_.decodeFunctionData("publishDocument",e)},exports.encodeExecutorControl=cE,exports.getActiveRuntimeType=Ro,exports.getActiveSessionToken=Co,exports.getActiveZoneGatewayOrigin=Io,exports.getCurrentWalletUserFromHost=bo,exports.identityAllows=function(e,t){return"anonymous"!==e.kind&&(!e.restricted||(e.scopes??[]).includes(t))},exports.identityKey=Jn,exports.inputPrompt=function(e,t,n,r=!1){const s=[],i=n.length>0;return i&&s.push({kind:"choice",id:$s,options:n,multiple:!1,required:!r}),i&&!r||s.push({kind:"text_input",id:Ks,multiline:!0,required:!i}),t?{title:e,message:t,controls:s}:{title:e,controls:s}},exports.isAiccAiMethod=function(e){return ss.has(e)},exports.isExternalPrincipal=function(e){return"user"===(null==e?void 0:e.principal_kind)&&!0===e[Di]},exports.isNotifyClosed=Zs,exports.isTerminalTaskPhase=Er,exports.isUserGroupRefTag=qs,exports.mailboxAddress=function(e,t){if(!/^did:[^:]+:.+$/.test(e)||/[\s\x00-\x1f\x7f-\x9f/\\?#*|]/.test(e))throw new Fn("mailbox owner must be a bare DID");if(void 0===t)return e;if(!t||t.trim()!==t||[...t].length>200||"."===t||".."===t||/[\x00-\x1f\x7f-\x9f]/.test(t))throw new Fn("invalid mailbox session_id");return`${e}/${encodeURIComponent(t).replace(/[!'()*]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)).replace(/%3A/g,":").replace(/%40/g,"@")}`},exports.mailboxResource=function(e,t){const n=encodeURIComponent(e).replace(/[!'()*.]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)).replace(/%3A/g,":").replace(/%40/g,"@").replace(/%2F/g,"/");return`obj://msg-center/${t.toLowerCase()}/${n}`},exports.msgMachineData=li,exports.ndm_client=hv,exports.ndm_proxy=oE,exports.normalizeZoneHostname=Xn,exports.notifyAnswerToTaskResult=ai,exports.notifyCategoryFromSessionId=function(e){if(!e.startsWith(zs))return null;const t=e.slice(10);return"todo"===t||"agent"===t||"app"===t?t:null},exports.notifyCategorySessionId=function(e){return`${zs}${e}`},exports.notifyMessageData=function(e){const t=li(e,Ws);return t&&"string"==typeof t.notify_id?t:null},exports.notifyUrl=function(e,t){const n=`${Ys}?notify=${t}`,r=null==e?void 0:e.trim();return r?`https://${r}${n}`:n},exports.parseAccessDenial=$n,exports.parseAppId=vi,exports.parseAppInstanceId=Si,exports.parseCurrentIdentity=Qn,exports.parseSessionTokenClaims=Hi,exports.parseVideoPrompt=Es,exports.parseZoneUserType=function(e){const t="string"==typeof e?e.trim().toLowerCase():"";return Pi.includes(t)?t:null},exports.promptOptions=oi,exports.resolveDidFromHost=_o,exports.sn_client=SA,exports.taskMgrErrorCode=_r,exports.taskMgrTaskEventPath=br,exports.taskMgrTreeEventPath=function(e){return`/task_mgr/tree/${e}`},exports.validateAiccMessage=is,exports.validateDecisionAnswers=ws,exports.validateDecisionRequest=ys,exports.validateNotifyAnswer=ci,exports.validateVideoEdit=Os,exports.validateVideoGeneration=Cs,exports.validateVideoOutput=Is,exports.videoGenerationRequirement=xs,exports.waitNotify=async function(e,t,n,r={}){let s=await e.notifyGet(t),i=null,o=!1;r.kevent&&s.task_id&&!Zs(s.status)&&r.kevent.createEventReader([br(s.task_id)]).then((e=>{o?e.close().catch((()=>{})):i=e}),(()=>{}));try{let r=500;for(;;){if(Zs(s.status))return s;const o=Date.now();if(o>=n)return s;await hi(Math.min(r,n-o),i),r=Math.min(2*r,3e4),s=await e.notifyGet(t)}}finally{o=!0;const e=i;e&&await e.close().catch((()=>{}))}},exports.walletUserHasSnAccount=y_,exports.zoneActionUrl=function(e,t){const n=Xn(e),r=Zn[t];return n&&r?`https://${n}${r}`:null};
|
|
13
|
+
//# sourceMappingURL=executor_client-b3ff97ba.js.map
|