@0xmonaco/mcp-server 0.8.5 → 0.8.7

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.
Files changed (2) hide show
  1. package/dist/bin.js +1 -1
  2. package/package.json +3 -3
package/dist/bin.js CHANGED
@@ -134,7 +134,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
134
134
  `:`[${Y[U]}\r
135
135
  ]`;continue}if(X+=Y[U],Y[U]==="\\")G=!0;else if(W&&Y[U]==="]")W=!1;else if(!W&&Y[U]==="[")W=!0}try{new RegExp(X)}catch{return console.warn(`Could not convert regex pattern at ${J.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),$.source}return X}function nO($,J){if(J.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(J.target==="openApi3"&&$.keyType?._def.typeName===$$.ZodEnum)return{type:"object",required:$.keyType._def.values,properties:$.keyType._def.values.reduce((Y,X)=>({...Y,[X]:j$($.valueType._def,{...J,currentPath:[...J.currentPath,"properties",X]})??v4(J)}),{}),additionalProperties:J.rejectedAdditionalProperties};let Q={type:"object",additionalProperties:j$($.valueType._def,{...J,currentPath:[...J.currentPath,"additionalProperties"]})??J.allowedAdditionalProperties};if(J.target==="openApi3")return Q;if($.keyType?._def.typeName===$$.ZodString&&$.keyType._def.checks?.length){let{type:Y,...X}=lO($.keyType._def,J);return{...Q,propertyNames:X}}else if($.keyType?._def.typeName===$$.ZodEnum)return{...Q,propertyNames:{enum:$.keyType._def.values}};else if($.keyType?._def.typeName===$$.ZodBranded&&$.keyType._def.type._def.typeName===$$.ZodString&&$.keyType._def.type._def.checks?.length){let{type:Y,...X}=mO($.keyType._def,J);return{...Q,propertyNames:X}}return Q}function yP($,J){if(J.mapStrategy==="record")return nO($,J);let Q=j$($.keyType._def,{...J,currentPath:[...J.currentPath,"items","items","0"]})||v4(J),Y=j$($.valueType._def,{...J,currentPath:[...J.currentPath,"items","items","1"]})||v4(J);return{type:"array",maxItems:125,items:{type:"array",items:[Q,Y],minItems:2,maxItems:2}}}function hP($){let J=$.values,Y=Object.keys($.values).filter((G)=>{return typeof J[J[G]]!=="number"}).map((G)=>J[G]),X=Array.from(new Set(Y.map((G)=>typeof G)));return{type:X.length===1?X[0]==="string"?"string":"number":["string","number"],enum:Y}}function uP($){return $.target==="openAi"?void 0:{not:v4({...$,currentPath:[...$.currentPath,"not"]})}}function mP($){return $.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var i7={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function nP($,J){if(J.target==="openApi3")return lP($,J);let Q=$.options instanceof Map?Array.from($.options.values()):$.options;if(Q.every((Y)=>(Y._def.typeName in i7)&&(!Y._def.checks||!Y._def.checks.length))){let Y=Q.reduce((X,G)=>{let W=i7[G._def.typeName];return W&&!X.includes(W)?[...X,W]:X},[]);return{type:Y.length>1?Y:Y[0]}}else if(Q.every((Y)=>Y._def.typeName==="ZodLiteral"&&!Y.description)){let Y=Q.reduce((X,G)=>{let W=typeof G._def.value;switch(W){case"string":case"number":case"boolean":return[...X,W];case"bigint":return[...X,"integer"];case"object":if(G._def.value===null)return[...X,"null"];case"symbol":case"undefined":case"function":default:return X}},[]);if(Y.length===Q.length){let X=Y.filter((G,W,D)=>D.indexOf(G)===W);return{type:X.length>1?X:X[0],enum:Q.reduce((G,W)=>{return G.includes(W._def.value)?G:[...G,W._def.value]},[])}}}else if(Q.every((Y)=>Y._def.typeName==="ZodEnum"))return{type:"string",enum:Q.reduce((Y,X)=>[...Y,...X._def.values.filter((G)=>!Y.includes(G))],[])};return lP($,J)}var lP=($,J)=>{let Q=($.options instanceof Map?Array.from($.options.values()):$.options).map((Y,X)=>j$(Y._def,{...J,currentPath:[...J.currentPath,"anyOf",`${X}`]})).filter((Y)=>!!Y&&(!J.strictUnions||typeof Y==="object"&&Object.keys(Y).length>0));return Q.length?{anyOf:Q}:void 0};function iP($,J){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes($.innerType._def.typeName)&&(!$.innerType._def.checks||!$.innerType._def.checks.length)){if(J.target==="openApi3")return{type:i7[$.innerType._def.typeName],nullable:!0};return{type:[i7[$.innerType._def.typeName],"null"]}}if(J.target==="openApi3"){let Y=j$($.innerType._def,{...J,currentPath:[...J.currentPath]});if(Y&&"$ref"in Y)return{allOf:[Y],nullable:!0};return Y&&{...Y,nullable:!0}}let Q=j$($.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","0"]});return Q&&{anyOf:[Q,{type:"null"}]}}function dP($,J){let Q={type:"number"};if(!$.checks)return Q;for(let Y of $.checks)switch(Y.kind){case"int":Q.type="integer",xI(Q,"type",Y.message,J);break;case"min":if(J.target==="jsonSchema7")if(Y.inclusive)o$(Q,"minimum",Y.value,Y.message,J);else o$(Q,"exclusiveMinimum",Y.value,Y.message,J);else{if(!Y.inclusive)Q.exclusiveMinimum=!0;o$(Q,"minimum",Y.value,Y.message,J)}break;case"max":if(J.target==="jsonSchema7")if(Y.inclusive)o$(Q,"maximum",Y.value,Y.message,J);else o$(Q,"exclusiveMaximum",Y.value,Y.message,J);else{if(!Y.inclusive)Q.exclusiveMaximum=!0;o$(Q,"maximum",Y.value,Y.message,J)}break;case"multipleOf":o$(Q,"multipleOf",Y.value,Y.message,J);break}return Q}function pP($,J){let Q=J.target==="openAi",Y={type:"object",properties:{}},X=[],G=$.shape();for(let D in G){let U=G[D];if(U===void 0||U._def===void 0)continue;let V=Qs(U);if(V&&Q){if(U._def.typeName==="ZodOptional")U=U._def.innerType;if(!U.isNullable())U=U.nullable();V=!1}let O=j$(U._def,{...J,currentPath:[...J.currentPath,"properties",D],propertyPath:[...J.currentPath,"properties",D]});if(O===void 0)continue;if(Y.properties[D]=O,!V)X.push(D)}if(X.length)Y.required=X;let W=Js($,J);if(W!==void 0)Y.additionalProperties=W;return Y}function Js($,J){if($.catchall._def.typeName!=="ZodNever")return j$($.catchall._def,{...J,currentPath:[...J.currentPath,"additionalProperties"]});switch($.unknownKeys){case"passthrough":return J.allowedAdditionalProperties;case"strict":return J.rejectedAdditionalProperties;case"strip":return J.removeAdditionalStrategy==="strict"?J.allowedAdditionalProperties:J.rejectedAdditionalProperties}}function Qs($){try{return $.isOptional()}catch{return!0}}var cP=($,J)=>{if(J.currentPath.toString()===J.propertyPath?.toString())return j$($.innerType._def,J);let Q=j$($.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","1"]});return Q?{anyOf:[{not:v4(J)},Q]}:v4(J)};var oP=($,J)=>{if(J.pipeStrategy==="input")return j$($.in._def,J);else if(J.pipeStrategy==="output")return j$($.out._def,J);let Q=j$($.in._def,{...J,currentPath:[...J.currentPath,"allOf","0"]}),Y=j$($.out._def,{...J,currentPath:[...J.currentPath,"allOf",Q?"1":"0"]});return{allOf:[Q,Y].filter((X)=>X!==void 0)}};function rP($,J){return j$($.type._def,J)}function tP($,J){let Y={type:"array",uniqueItems:!0,items:j$($.valueType._def,{...J,currentPath:[...J.currentPath,"items"]})};if($.minSize)o$(Y,"minItems",$.minSize.value,$.minSize.message,J);if($.maxSize)o$(Y,"maxItems",$.maxSize.value,$.maxSize.message,J);return Y}function aP($,J){if($.rest)return{type:"array",minItems:$.items.length,items:$.items.map((Q,Y)=>j$(Q._def,{...J,currentPath:[...J.currentPath,"items",`${Y}`]})).reduce((Q,Y)=>Y===void 0?Q:[...Q,Y],[]),additionalItems:j$($.rest._def,{...J,currentPath:[...J.currentPath,"additionalItems"]})};else return{type:"array",minItems:$.items.length,maxItems:$.items.length,items:$.items.map((Q,Y)=>j$(Q._def,{...J,currentPath:[...J.currentPath,"items",`${Y}`]})).reduce((Q,Y)=>Y===void 0?Q:[...Q,Y],[])}}function sP($){return{not:v4($)}}function eP($){return v4($)}var $R=($,J)=>{return j$($.innerType._def,J)};var JR=($,J,Q)=>{switch(J){case $$.ZodString:return lO($,Q);case $$.ZodNumber:return dP($,Q);case $$.ZodObject:return pP($,Q);case $$.ZodBigInt:return PP($,Q);case $$.ZodBoolean:return RP();case $$.ZodDate:return fI($,Q);case $$.ZodUndefined:return sP(Q);case $$.ZodNull:return mP(Q);case $$.ZodArray:return vP($,Q);case $$.ZodUnion:case $$.ZodDiscriminatedUnion:return nP($,Q);case $$.ZodIntersection:return fP($,Q);case $$.ZodTuple:return aP($,Q);case $$.ZodRecord:return nO($,Q);case $$.ZodLiteral:return bP($,Q);case $$.ZodEnum:return xP($);case $$.ZodNativeEnum:return hP($);case $$.ZodNullable:return iP($,Q);case $$.ZodOptional:return cP($,Q);case $$.ZodMap:return yP($,Q);case $$.ZodSet:return tP($,Q);case $$.ZodLazy:return()=>$.getter()._def;case $$.ZodPromise:return rP($,Q);case $$.ZodNaN:case $$.ZodNever:return uP(Q);case $$.ZodEffects:return kP($,Q);case $$.ZodAny:return v4(Q);case $$.ZodUnknown:return eP(Q);case $$.ZodDefault:return CP($,Q);case $$.ZodBranded:return mO($,Q);case $$.ZodReadonly:return $R($,Q);case $$.ZodCatch:return TP($,Q);case $$.ZodPipeline:return oP($,Q);case $$.ZodFunction:case $$.ZodVoid:case $$.ZodSymbol:return;default:return((Y)=>{return})(J)}};function j$($,J,Q=!1){let Y=J.seen.get($);if(J.override){let D=J.override?.($,J,Y,Q);if(D!==_P)return D}if(Y&&!Q){let D=Xs(Y,J);if(D!==void 0)return D}let X={def:$,path:J.currentPath,jsonSchema:void 0};J.seen.set($,X);let G=JR($,$.typeName,J),W=typeof G==="function"?j$(G(),J):G;if(W)Ys($,J,W);if(J.postProcess){let D=J.postProcess(W,$,J);return X.jsonSchema=W,D}return X.jsonSchema=W,W}var Xs=($,J)=>{switch(J.$refStrategy){case"root":return{$ref:$.path.join("/")};case"relative":return{$ref:uO(J.currentPath,$.path)};case"none":case"seen":{if($.path.length<J.currentPath.length&&$.path.every((Q,Y)=>J.currentPath[Y]===Q))return console.warn(`Recursive reference detected at ${J.currentPath.join("/")}! Defaulting to any`),v4(J);return J.$refStrategy==="seen"?v4(J):void 0}}},Ys=($,J,Q)=>{if($.description){if(Q.description=$.description,J.markdownDescription)Q.markdownDescription=$.description}return Q};var yI=($,J)=>{let Q=EP(J),Y=typeof J==="object"&&J.definitions?Object.entries(J.definitions).reduce((U,[V,O])=>({...U,[V]:j$(O._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,V]},!0)??v4(Q)}),{}):void 0,X=typeof J==="string"?J:J?.nameStrategy==="title"?void 0:J?.name,G=j$($._def,X===void 0?Q:{...Q,currentPath:[...Q.basePath,Q.definitionPath,X]},!1)??v4(Q),W=typeof J==="object"&&J.name!==void 0&&J.nameStrategy==="title"?J.name:void 0;if(W!==void 0)G.title=W;if(Q.flags.hasReferencedOpenAiAnyType){if(!Y)Y={};if(!Y[Q.openAiAnyTypeName])Y[Q.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:Q.$refStrategy==="relative"?"1":[...Q.basePath,Q.definitionPath,Q.openAiAnyTypeName].join("/")}}}let D=X===void 0?Y?{...G,[Q.definitionPath]:Y}:G:{$ref:[...Q.$refStrategy==="relative"?[]:Q.basePath,Q.definitionPath,X].join("/"),[Q.definitionPath]:{...Y,[X]:G}};if(Q.target==="jsonSchema7")D.$schema="http://json-schema.org/draft-07/schema#";else if(Q.target==="jsonSchema2019-09"||Q.target==="openAi")D.$schema="https://json-schema.org/draft/2019-09/schema#";if(Q.target==="openAi"&&(("anyOf"in D)||("oneOf"in D)||("allOf"in D)||("type"in D)&&Array.isArray(D.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return D};function Gs($){if(!$)return"draft-7";if($==="jsonSchema7"||$==="draft-7")return"draft-7";if($==="jsonSchema2019-09"||$==="draft-2020-12")return"draft-2020-12";return"draft-7"}function hI($,J){if(C1($))return sX($,{target:Gs(J?.target),io:J?.pipeStrategy??"input"});return yI($,{strictUnions:J?.strictUnions??!0,pipeStrategy:J?.pipeStrategy??"input"})}function uI($){let Q=CQ($)?.method;if(!Q)throw Error("Schema is missing a method literal");let Y=nV(Q);if(typeof Y!=="string")throw Error("Schema method literal must be a string");return Y}function mI($,J){let Q=TQ($,J);if(!Q.success)throw Q.error;return Q.data}var Ws=60000;class lI{constructor($){if(this._options=$,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(ZO,(J)=>{this._oncancel(J)}),this.setNotificationHandler(_O,(J)=>{this._onprogress(J)}),this.setRequestHandler(FO,(J)=>({})),this._taskStore=$?.taskStore,this._taskMessageQueue=$?.taskMessageQueue,this._taskStore)this.setRequestHandler(SO,async(J,Q)=>{let Y=await this._taskStore.getTask(J.params.taskId,Q.sessionId);if(!Y)throw new z$(q$.InvalidParams,"Failed to retrieve task: Task not found");return{...Y}}),this.setRequestHandler(vO,async(J,Q)=>{let Y=async()=>{let X=J.params.taskId;if(this._taskMessageQueue){let W;while(W=await this._taskMessageQueue.dequeue(X,Q.sessionId)){if(W.type==="response"||W.type==="error"){let D=W.message,U=D.id,V=this._requestResolvers.get(U);if(V)if(this._requestResolvers.delete(U),W.type==="response")V(D);else{let O=D,N=new z$(O.error.code,O.error.message,O.error.data);V(N)}else{let O=W.type==="response"?"Response":"Error";this._onerror(Error(`${O} handler missing for request ${U}`))}continue}await this._transport?.send(W.message,{relatedRequestId:Q.requestId})}}let G=await this._taskStore.getTask(X,Q.sessionId);if(!G)throw new z$(q$.InvalidParams,`Task not found: ${X}`);if(!fQ(G.status))return await this._waitForTaskUpdate(X,Q.signal),await Y();if(fQ(G.status)){let W=await this._taskStore.getTaskResult(X,Q.sessionId);return this._clearTaskQueue(X),{...W,_meta:{...W._meta,[xQ]:{taskId:X}}}}return await Y()};return await Y()}),this.setRequestHandler(PO,async(J,Q)=>{try{let{tasks:Y,nextCursor:X}=await this._taskStore.listTasks(J.params?.cursor,Q.sessionId);return{tasks:Y,nextCursor:X,_meta:{}}}catch(Y){throw new z$(q$.InvalidParams,`Failed to list tasks: ${Y instanceof Error?Y.message:String(Y)}`)}}),this.setRequestHandler(TO,async(J,Q)=>{try{let Y=await this._taskStore.getTask(J.params.taskId,Q.sessionId);if(!Y)throw new z$(q$.InvalidParams,`Task not found: ${J.params.taskId}`);if(fQ(Y.status))throw new z$(q$.InvalidParams,`Cannot cancel task in terminal status: ${Y.status}`);await this._taskStore.updateTaskStatus(J.params.taskId,"cancelled","Client cancelled task execution.",Q.sessionId),this._clearTaskQueue(J.params.taskId);let X=await this._taskStore.getTask(J.params.taskId,Q.sessionId);if(!X)throw new z$(q$.InvalidParams,`Task not found after cancellation: ${J.params.taskId}`);return{_meta:{},...X}}catch(Y){if(Y instanceof z$)throw Y;throw new z$(q$.InvalidRequest,`Failed to cancel task: ${Y instanceof Error?Y.message:String(Y)}`)}})}async _oncancel($){if(!$.params.requestId)return;this._requestHandlerAbortControllers.get($.params.requestId)?.abort($.params.reason)}_setupTimeout($,J,Q,Y,X=!1){this._timeoutInfo.set($,{timeoutId:setTimeout(Y,J),startTime:Date.now(),timeout:J,maxTotalTimeout:Q,resetTimeoutOnProgress:X,onTimeout:Y})}_resetTimeout($){let J=this._timeoutInfo.get($);if(!J)return!1;let Q=Date.now()-J.startTime;if(J.maxTotalTimeout&&Q>=J.maxTotalTimeout)throw this._timeoutInfo.delete($),z$.fromError(q$.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:J.maxTotalTimeout,totalElapsed:Q});return clearTimeout(J.timeoutId),J.timeoutId=setTimeout(J.onTimeout,J.timeout),!0}_cleanupTimeout($){let J=this._timeoutInfo.get($);if(J)clearTimeout(J.timeoutId),this._timeoutInfo.delete($)}async connect($){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=$;let J=this.transport?.onclose;this._transport.onclose=()=>{J?.(),this._onclose()};let Q=this.transport?.onerror;this._transport.onerror=(X)=>{Q?.(X),this._onerror(X)};let Y=this._transport?.onmessage;this._transport.onmessage=(X,G)=>{if(Y?.(X,G),f7(X)||NP(X))this._onresponse(X);else if(LI(X))this._onrequest(X,G);else if(OP(X))this._onnotification(X);else this._onerror(Error(`Unknown message type: ${JSON.stringify(X)}`))},await this._transport.start()}_onclose(){let $=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let Q of this._timeoutInfo.values())clearTimeout(Q.timeoutId);this._timeoutInfo.clear();for(let Q of this._requestHandlerAbortControllers.values())Q.abort();this._requestHandlerAbortControllers.clear();let J=z$.fromError(q$.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let Q of $.values())Q(J)}_onerror($){this.onerror?.($)}_onnotification($){let J=this._notificationHandlers.get($.method)??this.fallbackNotificationHandler;if(J===void 0)return;Promise.resolve().then(()=>J($)).catch((Q)=>this._onerror(Error(`Uncaught error in notification handler: ${Q}`)))}_onrequest($,J){let Q=this._requestHandlers.get($.method)??this.fallbackRequestHandler,Y=this._transport,X=$.params?._meta?.[xQ]?.taskId;if(Q===void 0){let V={jsonrpc:"2.0",id:$.id,error:{code:q$.MethodNotFound,message:"Method not found"}};if(X&&this._taskMessageQueue)this._enqueueTaskMessage(X,{type:"error",message:V,timestamp:Date.now()},Y?.sessionId).catch((O)=>this._onerror(Error(`Failed to enqueue error response: ${O}`)));else Y?.send(V).catch((O)=>this._onerror(Error(`Failed to send an error response: ${O}`)));return}let G=new AbortController;this._requestHandlerAbortControllers.set($.id,G);let W=UP($.params)?$.params.task:void 0,D=this._taskStore?this.requestTaskStore($,Y?.sessionId):void 0,U={signal:G.signal,sessionId:Y?.sessionId,_meta:$.params?._meta,sendNotification:async(V)=>{if(G.signal.aborted)return;let O={relatedRequestId:$.id};if(X)O.relatedTask={taskId:X};await this.notification(V,O)},sendRequest:async(V,O,N)=>{if(G.signal.aborted)throw new z$(q$.ConnectionClosed,"Request was cancelled");let M={...N,relatedRequestId:$.id};if(X&&!M.relatedTask)M.relatedTask={taskId:X};let H=M.relatedTask?.taskId??X;if(H&&D)await D.updateTaskStatus(H,"input_required");return await this.request(V,O,M)},authInfo:J?.authInfo,requestId:$.id,requestInfo:J?.requestInfo,taskId:X,taskStore:D,taskRequestedTtl:W?.ttl,closeSSEStream:J?.closeSSEStream,closeStandaloneSSEStream:J?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(W)this.assertTaskHandlerCapability($.method)}).then(()=>Q($,U)).then(async(V)=>{if(G.signal.aborted)return;let O={result:V,jsonrpc:"2.0",id:$.id};if(X&&this._taskMessageQueue)await this._enqueueTaskMessage(X,{type:"response",message:O,timestamp:Date.now()},Y?.sessionId);else await Y?.send(O)},async(V)=>{if(G.signal.aborted)return;let O={jsonrpc:"2.0",id:$.id,error:{code:Number.isSafeInteger(V.code)?V.code:q$.InternalError,message:V.message??"Internal error",...V.data!==void 0&&{data:V.data}}};if(X&&this._taskMessageQueue)await this._enqueueTaskMessage(X,{type:"error",message:O,timestamp:Date.now()},Y?.sessionId);else await Y?.send(O)}).catch((V)=>this._onerror(Error(`Failed to send response: ${V}`))).finally(()=>{if(this._requestHandlerAbortControllers.get($.id)===G)this._requestHandlerAbortControllers.delete($.id)})}_onprogress($){let{progressToken:J,...Q}=$.params,Y=Number(J),X=this._progressHandlers.get(Y);if(!X){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify($)}`));return}let G=this._responseHandlers.get(Y),W=this._timeoutInfo.get(Y);if(W&&G&&W.resetTimeoutOnProgress)try{this._resetTimeout(Y)}catch(D){this._responseHandlers.delete(Y),this._progressHandlers.delete(Y),this._cleanupTimeout(Y),G(D);return}X(Q)}_onresponse($){let J=Number($.id),Q=this._requestResolvers.get(J);if(Q){if(this._requestResolvers.delete(J),f7($))Q($);else{let G=new z$($.error.code,$.error.message,$.error.data);Q(G)}return}let Y=this._responseHandlers.get(J);if(Y===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify($)}`));return}this._responseHandlers.delete(J),this._cleanupTimeout(J);let X=!1;if(f7($)&&$.result&&typeof $.result==="object"){let G=$.result;if(G.task&&typeof G.task==="object"){let W=G.task;if(typeof W.taskId==="string")X=!0,this._taskProgressTokens.set(W.taskId,J)}}if(!X)this._progressHandlers.delete(J);if(f7($))Y($);else{let G=z$.fromError($.error.code,$.error.message,$.error.data);Y(G)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream($,J,Q){let{task:Y}=Q??{};if(!Y){try{yield{type:"result",result:await this.request($,J,Q)}}catch(G){yield{type:"error",error:G instanceof z$?G:new z$(q$.InternalError,String(G))}}return}let X;try{let G=await this.request($,WY,Q);if(G.task)X=G.task.taskId,yield{type:"taskCreated",task:G.task};else throw new z$(q$.InternalError,"Task creation did not return a task");while(!0){let W=await this.getTask({taskId:X},Q);if(yield{type:"taskStatus",task:W},fQ(W.status)){if(W.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:X},J,Q)};else if(W.status==="failed")yield{type:"error",error:new z$(q$.InternalError,`Task ${X} failed`)};else if(W.status==="cancelled")yield{type:"error",error:new z$(q$.InternalError,`Task ${X} was cancelled`)};return}if(W.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:X},J,Q)};return}let D=W.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((U)=>setTimeout(U,D)),Q?.signal?.throwIfAborted()}}catch(G){yield{type:"error",error:G instanceof z$?G:new z$(q$.InternalError,String(G))}}}request($,J,Q){let{relatedRequestId:Y,resumptionToken:X,onresumptiontoken:G,task:W,relatedTask:D}=Q??{};return new Promise((U,V)=>{let O=(L)=>{V(L)};if(!this._transport){O(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod($.method),W)this.assertTaskCapability($.method)}catch(L){O(L);return}Q?.signal?.throwIfAborted();let N=this._requestMessageId++,M={...$,jsonrpc:"2.0",id:N};if(Q?.onprogress)this._progressHandlers.set(N,Q.onprogress),M.params={...$.params,_meta:{...$.params?._meta||{},progressToken:N}};if(W)M.params={...M.params,task:W};if(D)M.params={...M.params,_meta:{...M.params?._meta||{},[xQ]:D}};let H=(L)=>{this._responseHandlers.delete(N),this._progressHandlers.delete(N),this._cleanupTimeout(N),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:N,reason:String(L)}},{relatedRequestId:Y,resumptionToken:X,onresumptiontoken:G}).catch((B)=>this._onerror(Error(`Failed to send cancellation: ${B}`)));let S=L instanceof z$?L:new z$(q$.RequestTimeout,String(L));V(S)};this._responseHandlers.set(N,(L)=>{if(Q?.signal?.aborted)return;if(L instanceof Error)return V(L);try{let S=TQ(J,L.result);if(!S.success)V(S.error);else U(S.data)}catch(S){V(S)}}),Q?.signal?.addEventListener("abort",()=>{H(Q?.signal?.reason)});let w=Q?.timeout??Ws,I=()=>H(z$.fromError(q$.RequestTimeout,"Request timed out",{timeout:w}));this._setupTimeout(N,w,Q?.maxTotalTimeout,I,Q?.resetTimeoutOnProgress??!1);let j=D?.taskId;if(j){let L=(S)=>{let B=this._responseHandlers.get(N);if(B)B(S);else this._onerror(Error(`Response handler missing for side-channeled request ${N}`))};this._requestResolvers.set(N,L),this._enqueueTaskMessage(j,{type:"request",message:M,timestamp:Date.now()}).catch((S)=>{this._cleanupTimeout(N),V(S)})}else this._transport.send(M,{relatedRequestId:Y,resumptionToken:X,onresumptiontoken:G}).catch((L)=>{this._cleanupTimeout(N),V(L)})})}async getTask($,J){return this.request({method:"tasks/get",params:$},EO,J)}async getTaskResult($,J,Q){return this.request({method:"tasks/result",params:$},J,Q)}async listTasks($,J){return this.request({method:"tasks/list",params:$},RO,J)}async cancelTask($,J){return this.request({method:"tasks/cancel",params:$},HP,J)}async notification($,J){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability($.method);let Q=J?.relatedTask?.taskId;if(Q){let W={...$,jsonrpc:"2.0",params:{...$.params,_meta:{...$.params?._meta||{},[xQ]:J.relatedTask}}};await this._enqueueTaskMessage(Q,{type:"notification",message:W,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes($.method)&&!$.params&&!J?.relatedRequestId&&!J?.relatedTask){if(this._pendingDebouncedNotifications.has($.method))return;this._pendingDebouncedNotifications.add($.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete($.method),!this._transport)return;let W={...$,jsonrpc:"2.0"};if(J?.relatedTask)W={...W,params:{...W.params,_meta:{...W.params?._meta||{},[xQ]:J.relatedTask}}};this._transport?.send(W,J).catch((D)=>this._onerror(D))});return}let G={...$,jsonrpc:"2.0"};if(J?.relatedTask)G={...G,params:{...G.params,_meta:{...G.params?._meta||{},[xQ]:J.relatedTask}}};await this._transport.send(G,J)}setRequestHandler($,J){let Q=uI($);this.assertRequestHandlerCapability(Q),this._requestHandlers.set(Q,(Y,X)=>{let G=mI($,Y);return Promise.resolve(J(G,X))})}removeRequestHandler($){this._requestHandlers.delete($)}assertCanSetRequestHandler($){if(this._requestHandlers.has($))throw Error(`A request handler for ${$} already exists, which would be overridden`)}setNotificationHandler($,J){let Q=uI($);this._notificationHandlers.set(Q,(Y)=>{let X=mI($,Y);return Promise.resolve(J(X))})}removeNotificationHandler($){this._notificationHandlers.delete($)}_cleanupTaskProgressHandler($){let J=this._taskProgressTokens.get($);if(J!==void 0)this._progressHandlers.delete(J),this._taskProgressTokens.delete($)}async _enqueueTaskMessage($,J,Q){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let Y=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue($,J,Q,Y)}async _clearTaskQueue($,J){if(this._taskMessageQueue){let Q=await this._taskMessageQueue.dequeueAll($,J);for(let Y of Q)if(Y.type==="request"&&LI(Y.message)){let X=Y.message.id,G=this._requestResolvers.get(X);if(G)G(new z$(q$.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(X);else this._onerror(Error(`Resolver missing for request ${X} during task ${$} cleanup`))}}}async _waitForTaskUpdate($,J){let Q=this._options?.defaultTaskPollInterval??1000;try{let Y=await this._taskStore?.getTask($);if(Y?.pollInterval)Q=Y.pollInterval}catch{}return new Promise((Y,X)=>{if(J.aborted){X(new z$(q$.InvalidRequest,"Request cancelled"));return}let G=setTimeout(Y,Q);J.addEventListener("abort",()=>{clearTimeout(G),X(new z$(q$.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore($,J){let Q=this._taskStore;if(!Q)throw Error("No task store configured");return{createTask:async(Y)=>{if(!$)throw Error("No request provided");return await Q.createTask(Y,$.id,{method:$.method,params:$.params},J)},getTask:async(Y)=>{let X=await Q.getTask(Y,J);if(!X)throw new z$(q$.InvalidParams,"Failed to retrieve task: Task not found");return X},storeTaskResult:async(Y,X,G)=>{await Q.storeTaskResult(Y,X,G,J);let W=await Q.getTask(Y,J);if(W){let D=u7.parse({method:"notifications/tasks/status",params:W});if(await this.notification(D),fQ(W.status))this._cleanupTaskProgressHandler(Y)}},getTaskResult:(Y)=>{return Q.getTaskResult(Y,J)},updateTaskStatus:async(Y,X,G)=>{let W=await Q.getTask(Y,J);if(!W)throw new z$(q$.InvalidParams,`Task "${Y}" not found - it may have been cleaned up`);if(fQ(W.status))throw new z$(q$.InvalidParams,`Cannot update task "${Y}" from terminal status "${W.status}" to "${X}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await Q.updateTaskStatus(Y,X,G,J);let D=await Q.getTask(Y,J);if(D){let U=u7.parse({method:"notifications/tasks/status",params:D});if(await this.notification(U),fQ(D.status))this._cleanupTaskProgressHandler(Y)}},listTasks:(Y)=>{return Q.listTasks(Y,J)}}}}function QR($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function XR($,J){let Q={...$};for(let Y in J){let X=Y,G=J[X];if(G===void 0)continue;let W=Q[X];if(QR(W)&&QR(G))Q[X]={...W,...G};else Q[X]=G}return Q}var hx=P6(gL(),1),ux=P6(yx(),1);function vQ$(){let $=new hx.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return ux.default($),$}class cL{constructor($){this._ajv=$??vQ$()}getValidator($){let J="$id"in $&&typeof $.$id==="string"?this._ajv.getSchema($.$id)??this._ajv.compile($):this._ajv.compile($);return(Q)=>{if(J(Q))return{valid:!0,data:Q,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(J.errors)}}}}class oL{constructor($){this._server=$}requestStream($,J,Q){return this._server.requestStream($,J,Q)}createMessageStream($,J){let Q=this._server.getClientCapabilities();if(($.tools||$.toolChoice)&&!Q?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if($.messages.length>0){let Y=$.messages[$.messages.length-1],X=Array.isArray(Y.content)?Y.content:[Y.content],G=X.some((V)=>V.type==="tool_result"),W=$.messages.length>1?$.messages[$.messages.length-2]:void 0,D=W?Array.isArray(W.content)?W.content:[W.content]:[],U=D.some((V)=>V.type==="tool_use");if(G){if(X.some((V)=>V.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!U)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(U){let V=new Set(D.filter((N)=>N.type==="tool_use").map((N)=>N.id)),O=new Set(X.filter((N)=>N.type==="tool_result").map((N)=>N.toolUseId));if(V.size!==O.size||![...V].every((N)=>O.has(N)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:$},n7,J)}elicitInputStream($,J){let Q=this._server.getClientCapabilities(),Y=$.mode??"form";switch(Y){case"url":{if(!Q?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!Q?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let X=Y==="form"&&$.mode===void 0?{...$,mode:"form"}:$;return this.requestStream({method:"elicitation/create",params:X},KY,J)}async getTask($,J){return this._server.getTask({taskId:$},J)}async getTaskResult($,J,Q){return this._server.getTaskResult({taskId:$},J,Q)}async listTasks($,J){return this._server.listTasks($?{cursor:$}:void 0,J)}async cancelTask($,J){return this._server.cancelTask({taskId:$},J)}}function mx($,J,Q){if(!$)throw Error(`${Q} does not support task creation (required for ${J})`);switch(J){case"tools/call":if(!$.tools?.call)throw Error(`${Q} does not support task creation for tools/call (required for ${J})`);break;default:break}}function lx($,J,Q){if(!$)throw Error(`${Q} does not support task creation (required for ${J})`);switch(J){case"sampling/createMessage":if(!$.sampling?.createMessage)throw Error(`${Q} does not support task creation for sampling/createMessage (required for ${J})`);break;case"elicitation/create":if(!$.elicitation?.create)throw Error(`${Q} does not support task creation for elicitation/create (required for ${J})`);break;default:break}}class rL extends lI{constructor($,J){super(J);if(this._serverInfo=$,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(l7.options.map((Q,Y)=>[Q,Y])),this.isMessageIgnored=(Q,Y)=>{let X=this._loggingLevels.get(Y);return X?this.LOG_LEVEL_SEVERITY.get(Q)<this.LOG_LEVEL_SEVERITY.get(X):!1},this._capabilities=J?.capabilities??{},this._instructions=J?.instructions,this._jsonSchemaValidator=J?.jsonSchemaValidator??new cL,this.setRequestHandler(ZI,(Q)=>this._oninitialize(Q)),this.setNotificationHandler(FI,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(TI,async(Q,Y)=>{let X=Y.sessionId||Y.requestInfo?.headers["mcp-session-id"]||void 0,{level:G}=Q.params,W=l7.safeParse(G);if(W.success)this._loggingLevels.set(X,W.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new oL(this)};return this._experimental}registerCapabilities($){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=XR(this._capabilities,$)}setRequestHandler($,J){let Y=CQ($)?.method;if(!Y)throw Error("Schema is missing a method literal");let X;if(C1(Y)){let W=Y;X=W._zod?.def?.value??W.value}else{let W=Y;X=W._def?.value??W.value}if(typeof X!=="string")throw Error("Schema method literal must be a string");if(X==="tools/call"){let W=async(D,U)=>{let V=TQ(UY,D);if(!V.success){let H=V.error instanceof Error?V.error.message:String(V.error);throw new z$(q$.InvalidParams,`Invalid tools/call request: ${H}`)}let{params:O}=V.data,N=await Promise.resolve(J(D,U));if(O.task){let H=TQ(WY,N);if(!H.success){let w=H.error instanceof Error?H.error.message:String(H.error);throw new z$(q$.InvalidParams,`Invalid task creation result: ${w}`)}return H.data}let M=TQ(yO,N);if(!M.success){let H=M.error instanceof Error?M.error.message:String(M.error);throw new z$(q$.InvalidParams,`Invalid tools/call result: ${H}`)}return M.data};return super.setRequestHandler($,W)}return super.setRequestHandler($,J)}assertCapabilityForMethod($){switch($){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${$})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${$})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${$})`);break;case"ping":break}}assertNotificationCapability($){switch($){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${$})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${$})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${$})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${$})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${$})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability($){if(!this._capabilities)return;switch($){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${$})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${$})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${$})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${$})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${$})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${$})`);break;case"ping":case"initialize":break}}assertTaskCapability($){lx(this._clientCapabilities?.tasks?.requests,$,"Client")}assertTaskHandlerCapability($){if(!this._capabilities)return;mx(this._capabilities.tasks?.requests,$,"Server")}async _oninitialize($){let J=$.params.protocolVersion;return this._clientCapabilities=$.params.capabilities,this._clientVersion=$.params.clientInfo,{protocolVersion:GP.includes(J)?J:AI,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},jO)}async createMessage($,J){if($.tools||$.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if($.messages.length>0){let Q=$.messages[$.messages.length-1],Y=Array.isArray(Q.content)?Q.content:[Q.content],X=Y.some((U)=>U.type==="tool_result"),G=$.messages.length>1?$.messages[$.messages.length-2]:void 0,W=G?Array.isArray(G.content)?G.content:[G.content]:[],D=W.some((U)=>U.type==="tool_use");if(X){if(Y.some((U)=>U.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!D)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(D){let U=new Set(W.filter((O)=>O.type==="tool_use").map((O)=>O.id)),V=new Set(Y.filter((O)=>O.type==="tool_result").map((O)=>O.toolUseId));if(U.size!==V.size||![...U].every((O)=>V.has(O)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if($.tools)return this.request({method:"sampling/createMessage",params:$},CI,J);return this.request({method:"sampling/createMessage",params:$},n7,J)}async elicitInput($,J){switch($.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let Y=$;return this.request({method:"elicitation/create",params:Y},KY,J)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let Y=$.mode==="form"?$:{...$,mode:"form"},X=await this.request({method:"elicitation/create",params:Y},KY,J);if(X.action==="accept"&&X.content&&Y.requestedSchema)try{let W=this._jsonSchemaValidator.getValidator(Y.requestedSchema)(X.content);if(!W.valid)throw new z$(q$.InvalidParams,`Elicitation response content does not match requested schema: ${W.errorMessage}`)}catch(G){if(G instanceof z$)throw G;throw new z$(q$.InternalError,`Error validating elicitation response: ${G instanceof Error?G.message:String(G)}`)}return X}}}createElicitationCompletionNotifier($,J){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:$}},J)}async listRoots($,J){return this.request({method:"roots/list",params:$},kI,J)}async sendLoggingMessage($,J){if(this._capabilities.logging){if(!this.isMessageIgnored($.level,J))return this.notification({method:"notifications/message",params:$})}}async sendResourceUpdated($){return this.notification({method:"notifications/resources/updated",params:$})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var ix=Symbol.for("mcp.completable");function tL($){return!!$&&typeof $==="object"&&ix in $}function dx($){return $[ix]?.complete}var nx;(function($){$.Completable="McpCompletable"})(nx||(nx={}));var PQ$=/^[A-Za-z0-9._-]{1,128}$/;function RQ$($){let J=[];if($.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if($.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${$.length})`]};if($.includes(" "))J.push("Tool name contains spaces, which may cause parsing issues");if($.includes(","))J.push("Tool name contains commas, which may cause parsing issues");if($.startsWith("-")||$.endsWith("-"))J.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if($.startsWith(".")||$.endsWith("."))J.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!PQ$.test($)){let Q=$.split("").filter((Y)=>!/[A-Za-z0-9._-]/.test(Y)).filter((Y,X,G)=>G.indexOf(Y)===X);return J.push(`Tool name contains invalid characters: ${Q.map((Y)=>`"${Y}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:J}}return{isValid:!0,warnings:J}}function TQ$($,J){if(J.length>0){console.warn(`Tool name validation warning for "${$}":`);for(let Q of J)console.warn(` - ${Q}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function aL($){let J=RQ$($);return TQ$($,J.warnings),J.isValid}class sL{constructor($){this._mcpServer=$}registerToolTask($,J,Q){let Y={taskSupport:"required",...J.execution};if(Y.taskSupport==="forbidden")throw Error(`Cannot register task-based tool '${$}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool($,J.title,J.description,J.inputSchema,J.outputSchema,J.annotations,Y,J._meta,Q)}}class $2{constructor($,J){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new rL($,J)}get experimental(){if(!this._experimental)this._experimental={tasks:new sL(this)};return this._experimental}async connect($){return await this.server.connect($)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized)return;this.server.assertCanSetRequestHandler(nQ(gO)),this.server.assertCanSetRequestHandler(nQ(UY)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(gO,()=>({tools:Object.entries(this._registeredTools).filter(([,$])=>$.enabled).map(([$,J])=>{let Q={name:$,title:J.title,description:J.description,inputSchema:(()=>{let Y=r9(J.inputSchema);return Y?hI(Y,{strictUnions:!0,pipeStrategy:"input"}):CQ$})(),annotations:J.annotations,execution:J.execution,_meta:J._meta};if(J.outputSchema){let Y=r9(J.outputSchema);if(Y)Q.outputSchema=hI(Y,{strictUnions:!0,pipeStrategy:"output"})}return Q})})),this.server.setRequestHandler(UY,async($,J)=>{try{let Q=this._registeredTools[$.params.name];if(!Q)throw new z$(q$.InvalidParams,`Tool ${$.params.name} not found`);if(!Q.enabled)throw new z$(q$.InvalidParams,`Tool ${$.params.name} disabled`);let Y=!!$.params.task,X=Q.execution?.taskSupport,G="createTask"in Q.handler;if((X==="required"||X==="optional")&&!G)throw new z$(q$.InternalError,`Tool ${$.params.name} has taskSupport '${X}' but was not registered with registerToolTask`);if(X==="required"&&!Y)throw new z$(q$.MethodNotFound,`Tool ${$.params.name} requires task augmentation (taskSupport: 'required')`);if(X==="optional"&&!Y&&G)return await this.handleAutomaticTaskPolling(Q,$,J);let W=await this.validateToolInput(Q,$.params.arguments,$.params.name),D=await this.executeToolHandler(Q,W,J);if(Y)return D;return await this.validateToolOutput(Q,D,$.params.name),D}catch(Q){if(Q instanceof z$){if(Q.code===q$.UrlElicitationRequired)throw Q}return this.createToolError(Q instanceof Error?Q.message:String(Q))}}),this._toolHandlersInitialized=!0}createToolError($){return{content:[{type:"text",text:$}],isError:!0}}async validateToolInput($,J,Q){if(!$.inputSchema)return;let X=r9($.inputSchema)??$.inputSchema,G=await mV(X,J);if(!G.success){let W="error"in G?G.error:"Unknown error",D=lV(W);throw new z$(q$.InvalidParams,`Input validation error: Invalid arguments for tool ${Q}: ${D}`)}return G.data}async validateToolOutput($,J,Q){if(!$.outputSchema)return;if(!("content"in J))return;if(J.isError)return;if(!J.structuredContent)throw new z$(q$.InvalidParams,`Output validation error: Tool ${Q} has an output schema but no structured content was provided`);let Y=r9($.outputSchema),X=await mV(Y,J.structuredContent);if(!X.success){let G="error"in X?X.error:"Unknown error",W=lV(G);throw new z$(q$.InvalidParams,`Output validation error: Invalid structured content for tool ${Q}: ${W}`)}}async executeToolHandler($,J,Q){let Y=$.handler;if("createTask"in Y){if(!Q.taskStore)throw Error("No task store provided.");let G={...Q,taskStore:Q.taskStore};if($.inputSchema)return await Promise.resolve(Y.createTask(J,G));else return await Promise.resolve(Y.createTask(G))}if($.inputSchema)return await Promise.resolve(Y(J,Q));else return await Promise.resolve(Y(Q))}async handleAutomaticTaskPolling($,J,Q){if(!Q.taskStore)throw Error("No task store provided for task-capable tool.");let Y=await this.validateToolInput($,J.params.arguments,J.params.name),X=$.handler,G={...Q,taskStore:Q.taskStore},W=Y?await Promise.resolve(X.createTask(Y,G)):await Promise.resolve(X.createTask(G)),D=W.task.taskId,U=W.task,V=U.pollInterval??5000;while(U.status!=="completed"&&U.status!=="failed"&&U.status!=="cancelled"){await new Promise((N)=>setTimeout(N,V));let O=await Q.taskStore.getTask(D);if(!O)throw new z$(q$.InternalError,`Task ${D} not found during polling`);U=O}return await Q.taskStore.getTaskResult(D)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(nQ(hO)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(hO,async($)=>{switch($.params.ref.type){case"ref/prompt":return BP($),this.handlePromptCompletion($,$.params.ref);case"ref/resource":return jP($),this.handleResourceCompletion($,$.params.ref);default:throw new z$(q$.InvalidParams,`Invalid completion reference: ${$.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion($,J){let Q=this._registeredPrompts[J.name];if(!Q)throw new z$(q$.InvalidParams,`Prompt ${J.name} not found`);if(!Q.enabled)throw new z$(q$.InvalidParams,`Prompt ${J.name} disabled`);if(!Q.argsSchema)return MW;let X=CQ(Q.argsSchema)?.[$.params.argument.name];if(!tL(X))return MW;let G=dx(X);if(!G)return MW;let W=await G($.params.argument.value,$.params.context);return cx(W)}async handleResourceCompletion($,J){let Q=Object.values(this._registeredResourceTemplates).find((G)=>G.resourceTemplate.uriTemplate.toString()===J.uri);if(!Q){if(this._registeredResources[J.uri])return MW;throw new z$(q$.InvalidParams,`Resource template ${$.params.ref.uri} not found`)}let Y=Q.resourceTemplate.completeCallback($.params.argument.name);if(!Y)return MW;let X=await Y($.params.argument.value,$.params.context);return cx(X)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(nQ(CO)),this.server.assertCanSetRequestHandler(nQ(kO)),this.server.assertCanSetRequestHandler(nQ(xO)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(CO,async($,J)=>{let Q=Object.entries(this._registeredResources).filter(([X,G])=>G.enabled).map(([X,G])=>({uri:X,name:G.name,...G.metadata})),Y=[];for(let X of Object.values(this._registeredResourceTemplates)){if(!X.resourceTemplate.listCallback)continue;let G=await X.resourceTemplate.listCallback(J);for(let W of G.resources)Y.push({...X.metadata,...W})}return{resources:[...Q,...Y]}}),this.server.setRequestHandler(kO,async()=>{return{resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([J,Q])=>({name:J,uriTemplate:Q.resourceTemplate.uriTemplate.toString(),...Q.metadata}))}}),this.server.setRequestHandler(xO,async($,J)=>{let Q=new URL($.params.uri),Y=this._registeredResources[Q.toString()];if(Y){if(!Y.enabled)throw new z$(q$.InvalidParams,`Resource ${Q} disabled`);return Y.readCallback(Q,J)}for(let X of Object.values(this._registeredResourceTemplates)){let G=X.resourceTemplate.uriTemplate.match(Q.toString());if(G)return X.readCallback(Q,G,J)}throw new z$(q$.InvalidParams,`Resource ${Q} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(nQ(fO)),this.server.assertCanSetRequestHandler(nQ(bO)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(fO,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,$])=>$.enabled).map(([$,J])=>{return{name:$,title:J.title,description:J.description,arguments:J.argsSchema?kQ$(J.argsSchema):void 0}})})),this.server.setRequestHandler(bO,async($,J)=>{let Q=this._registeredPrompts[$.params.name];if(!Q)throw new z$(q$.InvalidParams,`Prompt ${$.params.name} not found`);if(!Q.enabled)throw new z$(q$.InvalidParams,`Prompt ${$.params.name} disabled`);if(Q.argsSchema){let Y=r9(Q.argsSchema),X=await mV(Y,$.params.arguments);if(!X.success){let D="error"in X?X.error:"Unknown error",U=lV(D);throw new z$(q$.InvalidParams,`Invalid arguments for prompt ${$.params.name}: ${U}`)}let G=X.data,W=Q.callback;return await Promise.resolve(W(G,J))}else{let Y=Q.callback;return await Promise.resolve(Y(J))}}),this._promptHandlersInitialized=!0}resource($,J,...Q){let Y;if(typeof Q[0]==="object")Y=Q.shift();let X=Q[0];if(typeof J==="string"){if(this._registeredResources[J])throw Error(`Resource ${J} is already registered`);let G=this._createRegisteredResource($,void 0,J,Y,X);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),G}else{if(this._registeredResourceTemplates[$])throw Error(`Resource template ${$} is already registered`);let G=this._createRegisteredResourceTemplate($,void 0,J,Y,X);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),G}}registerResource($,J,Q,Y){if(typeof J==="string"){if(this._registeredResources[J])throw Error(`Resource ${J} is already registered`);let X=this._createRegisteredResource($,Q.title,J,Q,Y);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),X}else{if(this._registeredResourceTemplates[$])throw Error(`Resource template ${$} is already registered`);let X=this._createRegisteredResourceTemplate($,Q.title,J,Q,Y);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),X}}_createRegisteredResource($,J,Q,Y,X){let G={name:$,title:J,metadata:Y,readCallback:X,enabled:!0,disable:()=>G.update({enabled:!1}),enable:()=>G.update({enabled:!0}),remove:()=>G.update({uri:null}),update:(W)=>{if(typeof W.uri<"u"&&W.uri!==Q){if(delete this._registeredResources[Q],W.uri)this._registeredResources[W.uri]=G}if(typeof W.name<"u")G.name=W.name;if(typeof W.title<"u")G.title=W.title;if(typeof W.metadata<"u")G.metadata=W.metadata;if(typeof W.callback<"u")G.readCallback=W.callback;if(typeof W.enabled<"u")G.enabled=W.enabled;this.sendResourceListChanged()}};return this._registeredResources[Q]=G,G}_createRegisteredResourceTemplate($,J,Q,Y,X){let G={resourceTemplate:Q,title:J,metadata:Y,readCallback:X,enabled:!0,disable:()=>G.update({enabled:!1}),enable:()=>G.update({enabled:!0}),remove:()=>G.update({name:null}),update:(U)=>{if(typeof U.name<"u"&&U.name!==$){if(delete this._registeredResourceTemplates[$],U.name)this._registeredResourceTemplates[U.name]=G}if(typeof U.title<"u")G.title=U.title;if(typeof U.template<"u")G.resourceTemplate=U.template;if(typeof U.metadata<"u")G.metadata=U.metadata;if(typeof U.callback<"u")G.readCallback=U.callback;if(typeof U.enabled<"u")G.enabled=U.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[$]=G;let W=Q.uriTemplate.variableNames;if(Array.isArray(W)&&W.some((U)=>!!Q.completeCallback(U)))this.setCompletionRequestHandler();return G}_createRegisteredPrompt($,J,Q,Y,X){let G={title:J,description:Q,argsSchema:Y===void 0?void 0:eX(Y),callback:X,enabled:!0,disable:()=>G.update({enabled:!1}),enable:()=>G.update({enabled:!0}),remove:()=>G.update({name:null}),update:(W)=>{if(typeof W.name<"u"&&W.name!==$){if(delete this._registeredPrompts[$],W.name)this._registeredPrompts[W.name]=G}if(typeof W.title<"u")G.title=W.title;if(typeof W.description<"u")G.description=W.description;if(typeof W.argsSchema<"u")G.argsSchema=eX(W.argsSchema);if(typeof W.callback<"u")G.callback=W.callback;if(typeof W.enabled<"u")G.enabled=W.enabled;this.sendPromptListChanged()}};if(this._registeredPrompts[$]=G,Y){if(Object.values(Y).some((D)=>{let U=D instanceof YY?D._def?.innerType:D;return tL(U)}))this.setCompletionRequestHandler()}return G}_createRegisteredTool($,J,Q,Y,X,G,W,D,U){aL($);let V={title:J,description:Q,inputSchema:px(Y),outputSchema:px(X),annotations:G,execution:W,_meta:D,handler:U,enabled:!0,disable:()=>V.update({enabled:!1}),enable:()=>V.update({enabled:!0}),remove:()=>V.update({name:null}),update:(O)=>{if(typeof O.name<"u"&&O.name!==$){if(typeof O.name==="string")aL(O.name);if(delete this._registeredTools[$],O.name)this._registeredTools[O.name]=V}if(typeof O.title<"u")V.title=O.title;if(typeof O.description<"u")V.description=O.description;if(typeof O.paramsSchema<"u")V.inputSchema=eX(O.paramsSchema);if(typeof O.outputSchema<"u")V.outputSchema=eX(O.outputSchema);if(typeof O.callback<"u")V.handler=O.callback;if(typeof O.annotations<"u")V.annotations=O.annotations;if(typeof O._meta<"u")V._meta=O._meta;if(typeof O.enabled<"u")V.enabled=O.enabled;this.sendToolListChanged()}};return this._registeredTools[$]=V,this.setToolRequestHandlers(),this.sendToolListChanged(),V}tool($,...J){if(this._registeredTools[$])throw Error(`Tool ${$} is already registered`);let Q,Y,X,G;if(typeof J[0]==="string")Q=J.shift();if(J.length>1){let D=J[0];if(eL(D)){if(Y=J.shift(),J.length>1&&typeof J[0]==="object"&&J[0]!==null&&!eL(J[0]))G=J.shift()}else if(typeof D==="object"&&D!==null){if(Object.values(D).some((U)=>typeof U==="object"&&U!==null))throw Error(`Tool ${$} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);G=J.shift()}}let W=J[0];return this._createRegisteredTool($,void 0,Q,Y,X,G,{taskSupport:"forbidden"},void 0,W)}registerTool($,J,Q){if(this._registeredTools[$])throw Error(`Tool ${$} is already registered`);let{title:Y,description:X,inputSchema:G,outputSchema:W,annotations:D,_meta:U}=J;return this._createRegisteredTool($,Y,X,G,W,D,{taskSupport:"forbidden"},U,Q)}prompt($,...J){if(this._registeredPrompts[$])throw Error(`Prompt ${$} is already registered`);let Q;if(typeof J[0]==="string")Q=J.shift();let Y;if(J.length>1)Y=J.shift();let X=J[0],G=this._createRegisteredPrompt($,void 0,Q,Y,X);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),G}registerPrompt($,J,Q){if(this._registeredPrompts[$])throw Error(`Prompt ${$} is already registered`);let{title:Y,description:X,argsSchema:G}=J,W=this._createRegisteredPrompt($,Y,X,G,Q);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),W}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage($,J){return this.server.sendLoggingMessage($,J)}sendResourceListChanged(){if(this.isConnected())this.server.sendResourceListChanged()}sendToolListChanged(){if(this.isConnected())this.server.sendToolListChanged()}sendPromptListChanged(){if(this.isConnected())this.server.sendPromptListChanged()}}var CQ$={type:"object",properties:{}};function ox($){return $!==null&&typeof $==="object"&&"parse"in $&&typeof $.parse==="function"&&"safeParse"in $&&typeof $.safeParse==="function"}function rx($){return"_def"in $||"_zod"in $||ox($)}function eL($){if(typeof $!=="object"||$===null)return!1;if(rx($))return!1;if(Object.keys($).length===0)return!0;return Object.values($).some(ox)}function px($){if(!$)return;if(eL($))return eX($);if(!rx($))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return $}function kQ$($){let J=CQ($);if(!J)return[];return Object.entries(J).map(([Q,Y])=>{let X=iE(Y),G=dE(Y);return{name:Q,description:X,required:!G}})}function nQ($){let Q=CQ($)?.method;if(!Q)throw Error("Schema is missing a method literal");let Y=nV(Q);if(typeof Y==="string")return Y;throw Error("Schema method literal must be a string")}function cx($){return{completion:{values:$.slice(0,100),total:$.length,hasMore:$.length>100}}}var MW={completion:{values:[],hasMore:!1}};import ax from"node:process";class J2{append($){this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){if(!this._buffer)return null;let $=this._buffer.indexOf(`
136
136
  `);if($===-1)return null;let J=this._buffer.toString("utf8",0,$).replace(/\r$/,"");return this._buffer=this._buffer.subarray($+1),xQ$(J)}clear(){this._buffer=void 0}}function xQ$($){return zP.parse(JSON.parse($))}function tx($){return JSON.stringify($)+`
137
- `}class Q2{constructor($=ax.stdin,J=ax.stdout){this._stdin=$,this._stdout=J,this._readBuffer=new J2,this._started=!1,this._ondata=(Q)=>{this._readBuffer.append(Q),this.processReadBuffer()},this._onerror=(Q)=>{this.onerror?.(Q)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let $=this._readBuffer.readMessage();if($===null)break;this.onmessage?.($)}catch($){this.onerror?.($)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send($){return new Promise((J)=>{let Q=tx($);if(this._stdout.write(Q))J();else this._stdout.once("drain",J)})}}var S3={name:"@0xmonaco/mcp-server",version:"0.8.5",type:"module",repository:{type:"git",url:"https://github.com/Monaco-Research/monaco-sdk.git",directory:"packages/mcp-server"},description:"MCP server for the Monaco SDK",engines:{node:">=18"},bin:"./dist/bin.js",files:["dist"],scripts:{build:"bun build src/bin.ts --outdir dist --target node --format esm --minify",dev:"bun --watch src/bin.ts",start:"bun dist/bin.js",clean:"rm -rf dist",lint:"biome lint .",test:"bun test"},author:"@codebycarson",dependencies:{"@0xmonaco/core":"0.8.5","@0xmonaco/types":"0.8.5","@modelcontextprotocol/sdk":"^1.26.0","node-fetch":"^3.3.2",viem:"^2.45.2",ws:"^8.19.0",zod:"^4.0.0"},devDependencies:{"@types/bun":"latest","@types/ws":"^8.18.1"}};var bQ$={mainnet:"https://evm-rpc.sei-apis.com",development:"https://evm-rpc-testnet.sei-apis.com",staging:"https://evm-rpc-testnet.sei-apis.com",local:"http://localhost:8545"};function iQ($=process.env){let J=$.MONACO_PRIVATE_KEY||null;if(J&&!J.startsWith("0x"))throw Error("MONACO_PRIVATE_KEY must start with '0x'.");let Q=$.MONACO_CLIENT_ID||null;if(J&&!Q)throw Error("MONACO_CLIENT_ID is required when MONACO_PRIVATE_KEY is set.");let Y=["mainnet","development","staging","local"],X=$.MONACO_NETWORK||"mainnet";if(!Y.includes(X))throw Error(`MONACO_NETWORK must be one of: ${Y.join(", ")}. Got: "${X}".`);let G=X,W=$.MONACO_RPC_URL||bQ$[G];return{privateKey:J,clientId:Q,network:G,seiRpcUrl:W}}function gQ$($){return $.replace(/_([a-z])/g,(J,Q)=>Q.toUpperCase())}function ZY($){if($===null||$===void 0)return $;if(typeof $!=="object")return $;if(Array.isArray($))return $.map((Q)=>ZY(Q));let J={};for(let[Q,Y]of Object.entries($))J[gQ$(Q)]=typeof Y==="object"&&Y!==null?ZY(Y):Y;return J}var HW=[0.0001,0.001,0.01,0.1,1,10,100,1000,1e4];var yQ$=1e4,hQ$=15000,uQ$=30000,mQ$=["created","activated","cancelled","parent_cancelled","triggered","failed","oco_cancelled"],lQ$=["STOP_LOSS","TAKE_PROFIT"],nQ$=["MARK_PRICE"],iQ$=["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],dQ$=["POSITION","PARENT_ORDER"];function sx($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function U8($,J){let Q=$[J];if(typeof Q!=="string"||Q.length===0)throw Error(`Invalid conditional order event: ${J} must be a non-empty string`);return Q}function V0($,J){let Q=$[J];if(Q===void 0||Q===null)return;if(typeof Q!=="string")throw Error(`Invalid conditional order event: ${J} must be a string`);return Q}function pQ$($,J){let Q=$[J];if(typeof Q!=="boolean")throw Error(`Invalid conditional order event: ${J} must be a boolean`);return Q}function cQ$($,J){let Q=$[J];if(Q===void 0||Q===null)return;if(typeof Q!=="number"||!Number.isFinite(Q))throw Error(`Invalid conditional order event: ${J} must be a finite number`);return Q}function dQ($,J,Q){let Y=U8($,J);if(!Q.includes(Y))throw Error(`Invalid conditional order event: ${J} must be one of ${Q.join(", ")}`);return Y}function ex($,J,Q){let Y=$[J];if(Y===void 0||Y===null)return;if(typeof Y!=="string"||!Q.includes(Y))throw Error(`Invalid conditional order event: ${J} must be one of ${Q.join(", ")}`);return Y}function oQ$($){if(!sx($))throw Error("Invalid conditional order event: payload must be an object");if(!sx($.data))throw Error("Invalid conditional order event: data must be an object");let J=ZY($.data);return{eventType:dQ($,"event_type",["conditional_order_update"]),userId:U8($,"user_id"),data:{conditionalOrderId:U8(J,"conditionalOrderId"),tradingPairId:U8(J,"tradingPairId"),marginAccountId:U8(J,"marginAccountId"),positionId:V0(J,"positionId"),parentOrderId:V0(J,"parentOrderId"),associationType:ex(J,"associationType",dQ$),linkedGroupId:V0(J,"linkedGroupId"),conditionType:dQ(J,"conditionType",lQ$),triggerSource:dQ(J,"triggerSource",nQ$),triggerPrice:U8(J,"triggerPrice"),side:dQ(J,"side",["BUY","SELL"]),positionSide:dQ(J,"positionSide",["LONG","SHORT","NONE"]),orderType:dQ(J,"orderType",["LIMIT","MARKET"]),limitPrice:V0(J,"limitPrice"),quantity:V0(J,"quantity"),slippageToleranceBps:cQ$(J,"slippageToleranceBps"),reduceOnly:pQ$(J,"reduceOnly"),timeInForce:ex(J,"timeInForce",["GTC","IOC"]),state:dQ(J,"state",iQ$),triggeredOrderId:V0(J,"triggeredOrderId"),triggeredAt:V0(J,"triggeredAt"),activatedAt:V0(J,"activatedAt"),cancelledAt:V0(J,"cancelledAt"),expiresAt:V0(J,"expiresAt"),failureReason:V0(J,"failureReason"),reason:dQ(J,"reason",mQ$),updatedAt:U8(J,"updatedAt")}}}function X2($,J={}){let Q=null,Y=J.token,X=0,G=null,W=null,D=J.autoReconnect??!0,U=J.maxReconnectAttempts??5,V=new Map,O=()=>{if(!Q)return"disconnected";switch(Q.readyState){case WebSocket.CONNECTING:return"connecting";case WebSocket.OPEN:return"connected";default:return"disconnected"}},N=()=>{let y=new URL($);if(Y)y.searchParams.set("token",Y);return y.toString()},M=()=>{if(W)clearInterval(W),W=null},H=()=>{M(),W=setInterval(()=>{if(Q?.readyState===WebSocket.OPEN)Q.send(JSON.stringify({type:"Ping"}))},hQ$)},w=()=>{if(G)clearTimeout(G),G=null},I=()=>{if(!D||X>=U){console.error("WebSocket: Max reconnect attempts reached");return}X++;let y=Math.min(1000*2**X,uQ$);G=setTimeout(()=>{B().catch((T)=>{console.warn("WebSocket: Failed to reconnect:",T)})},y)},j=(y)=>{if(Q?.readyState===WebSocket.OPEN)Q.send(JSON.stringify(y))},L=()=>{let y=Array.from(V.keys());if(y.length>0)j({type:"Subscribe",channels:y})},S=(y)=>{if(y.type!=="Event"||!y.channel)return;for(let[T,m]of V)if(y.channel===T||y.channel.startsWith(`${T}:`))for(let c of m)c(y.data)},B=()=>{return new Promise((y,T)=>{if(Q?.readyState===WebSocket.CONNECTING||Q?.readyState===WebSocket.OPEN){y();return}try{let m=new WebSocket(N());Q=m;let c=setTimeout(()=>{if(Q!==m){y();return}if(m.readyState===WebSocket.CONNECTING)m.close(1000,"Connection timeout"),T(Error("WebSocket connection timeout"))},yQ$);m.onopen=()=>{if(clearTimeout(c),Q!==m){y();return}X=0,H(),L(),J.onStatusChange?.("connected"),y()},m.onmessage=(g)=>{if(Q!==m)return;try{let t=JSON.parse(g.data);if(t.type==="Pong")return;S(t)}catch(t){console.warn("WebSocket: Failed to parse message",t)}},m.onclose=(g)=>{if(clearTimeout(c),Q!==m){y();return}if(Q=null,M(),J.onStatusChange?.("disconnected"),D&&g.code!==1000)I()},m.onerror=()=>clearTimeout(c)}catch(m){J.onStatusChange?.("disconnected"),T(m)}})},Z=()=>{D=!1,w(),M(),V.clear(),Q?.close(1000,"Client disconnect"),Q=null,J.onStatusChange?.("disconnected")},_=(y,T)=>{let m=!V.has(y);if(!V.has(y))V.set(y,new Set);if(V.get(y)?.add(T),m&&Q?.readyState===WebSocket.OPEN)j({type:"Subscribe",channels:[y]});return()=>{let c=V.get(y);if(c){if(c.delete(T),c.size===0){if(V.delete(y),Q?.readyState===WebSocket.OPEN)j({type:"Unsubscribe",channels:[y]})}}}};return{connect:B,disconnect:Z,isConnected:()=>Q?.readyState===WebSocket.OPEN,getStatus:O,setToken:(y)=>{Y=y||void 0,w();let T=Q;if(T?.readyState===WebSocket.OPEN||T?.readyState===WebSocket.CONNECTING||T?.readyState===WebSocket.CLOSING)T.close(1000,y?"Token updated, reconnecting.":"Token cleared."),Q=null;if(!y)return;B().catch((m)=>{console.warn("WebSocket: Failed to reconnect after token update:",m)})},orders:(y,T,m)=>{let c=`orders:${y}:${T}`;return _(c,(g)=>{try{let t=g,V$={orderId:t.order_id,eventType:t.event_type,timestamp:t.timestamp,data:ZY(t.data)};m(V$)}catch(t){console.error("WebSocket: Error processing order event",t)}})},orderbook:(y,T,m,c,g)=>{if(!y||!T||m===void 0||!c)throw Error(`orderbook subscription requires all params: tradingPairId="${y}", tradingMode="${T}", magnitude=${m} (valid: ${HW.join(", ")}), quotationMode="${c}" (valid: "BASE", "QUOTE")`);if(!HW.includes(m))throw Error(`Invalid magnitude: ${m}. Must be one of: ${HW.join(", ")}`);let t=`orderbook:${y}:${T}:${m}:${c.toLowerCase()}`;return _(t,(V$)=>{try{let k$=V$,T$=k$.data,A6={tradingPairId:k$.symbol,tradingMode:k$.trading_mode,bids:(T$?.bids||[]).map(($4)=>({price:$4.price,quantity:$4.quantity,orderCount:$4.order_count||0})),asks:(T$?.asks||[]).map(($4)=>({price:$4.price,quantity:$4.quantity,orderCount:$4.order_count||0})),bestBid:T$?.best_bid,bestAsk:T$?.best_ask,bidVolume:T$?.bid_volume||void 0,askVolume:T$?.ask_volume||void 0,priceChange:T$?.price_change?{side:T$.price_change.side,oldPrice:T$.price_change.old_price,newPrice:T$.price_change.new_price,levelRemoved:T$.price_change.level_removed||!1,levelAdded:T$.price_change.level_added||!1}:void 0,baseDecimals:k$.base_decimals||0,quoteDecimals:k$.quote_decimals||0,timestamp:k$.timestamp||new Date().toISOString(),sequence:k$.sequence_number||0};g(A6)}catch(k$){console.error("WebSocket: Error processing orderbook event",k$)}})},ohlcv:(y,T,m,c)=>{let g=`ohlcv:${y}:${T}:${m}`;return _(g,(t)=>{try{let V$=t,k$=V$.data,T$={tradingPairId:V$.symbol,tradingMode:V$.trading_mode,interval:V$.interval,candlestick:{T:k$.period_start||0,t:k$.period_end||0,o:k$.open||"0",h:k$.high||"0",l:k$.low||"0",c:k$.close||"0",v:k$.volume||"0",s:V$.symbol,i:V$.interval,n:k$.trades_count||0}};c(T$)}catch(V$){console.error("WebSocket: Error processing OHLCV event",V$)}})},trades:(y,T)=>{let m=`trades:${y}`;return _(m,(c)=>{try{let g=c,t=g.data,V$={eventType:"trade",tradingPairId:g.trading_pair_id,tradingMode:g.trading_mode.toUpperCase(),data:{tradeId:t.trade_id,price:t.price,quantity:t.quantity,makerSide:t.maker_side.toUpperCase(),executedAt:t.executed_at}};T(V$)}catch(g){console.error("WebSocket: Error processing trade event",g)}})},movements:(y)=>{return _("movements",(m)=>{try{let c=m,g=c.data,t={eventType:"movement",userId:c.user_id,data:{id:g.id,entryType:g.entry_type,transactionType:g.transaction_type,tokenAddress:g.token_address,amount:String(g.amount),amountRaw:g.amount_raw,balanceBefore:g.balance_before!=null?String(g.balance_before):void 0,balanceAfter:g.balance_after!=null?String(g.balance_after):void 0,lockedBefore:g.locked_before!=null?String(g.locked_before):void 0,lockedAfter:g.locked_after!=null?String(g.locked_after):void 0,referenceId:g.reference_id,referenceType:g.reference_type,description:g.description,txHash:g.tx_hash,createdAt:g.created_at,decimals:g.decimals}};y(t)}catch(c){console.error("WebSocket: Error processing movement event",c)}})},userOrders:(y)=>{return _("orders",(m)=>{try{let c=m,g={orderId:c.order_id,eventType:c.event_type,timestamp:c.timestamp,data:ZY(c.data)};y(g)}catch(c){console.error("WebSocket: Error processing user order event",c)}})},balances:(y)=>{return _("balances",(m)=>{try{let c=m,g=c.data,t={eventType:"balance_update",userId:c.user_id,data:{tokenAddress:g.token_address,tokenSymbol:g.token_symbol,available:g.available,availableRaw:g.available_raw,locked:g.locked,lockedRaw:g.locked_raw,total:g.total,totalRaw:g.total_raw,reason:g.reason,referenceId:g.reference_id,updatedAt:g.updated_at}};y(t)}catch(c){console.error("WebSocket: Error processing balance event",c)}})},conditionalOrders:(y,T)=>{if(!y)throw Error("conditionalOrders subscription requires a handler");if(T!==void 0&&T.length===0)throw Error("conditionalOrders tradingPairId cannot be empty");let m=T?`conditional_orders:${T}`:"conditional_orders";return _(m,(c)=>{try{y(oQ$(c))}catch(g){console.error("WebSocket: Error processing conditional order event",g)}})}}}var pQ=P6(v3(),1),Nb=["token","accessToken","access_token","refreshToken","refresh_token","authToken","auth_token","bearerToken","bearer_token","jwtToken","jwt_token","apiKey","api_key","apikey","clientSecret","client_secret","clientId","client_id","secret","password","authorization","bearer","auth","credentials","credential","email","phone","phoneNumber","phone_number","ssn","socialSecurity","social_security","address","passport","passportNumber","passport_number","driversLicense","drivers_license","cardNumber","card_number","creditCard","credit_card","cvv","pin","signature","privateKey","private_key","publicKey","public_key","mnemonic","seed","salt","hash","certificate","cert","fingerprint","cookie","session","sessionId","session_id","sessionToken","session_token","ipAddress","ip_address","deviceId","device_id","userId","user_id","accountId","account_id"];function FY($,J=5,Q=0){if(Q>=J)return"[Max depth reached]";if($===null||$===void 0)return $;if(Array.isArray($)){let X=$.slice(0,10).map((G)=>FY(G,J,Q+1));if($.length>10)X.push(`[... ${$.length-10} more items]`);return X}if(typeof $==="object"){let Y={};for(let[X,G]of Object.entries($)){let W=X.toLowerCase();if(Nb.some((U)=>W.includes(U.toLowerCase())))Y[X]="[REDACTED]";else if(typeof G==="string"&&G.length>500)Y[X]=`${G.substring(0,500)}... [truncated]`;else Y[X]=FY(G,J,Q+1)}return Y}if(typeof $==="string"){if($.length>1000)return`${$.substring(0,1000)}... [truncated]`;return $}return $}class _Y extends Error{cause;suggestion;retryable=!1;timestamp;constructor($,J){super($);if(this.name=this.constructor.name,this.timestamp=Date.now(),J?.cause)this.cause=J.cause;if(J?.suggestion)this.suggestion=J.suggestion;if(J?.retryable!==void 0)this.retryable=J.retryable}toJSON(){return{name:this.name,code:this.code,message:this.message,suggestion:this.suggestion,retryable:this.retryable,timestamp:this.timestamp,cause:this.cause instanceof Error?this.cause.message:this.cause}}}class P4 extends _Y{code="INVALID_CONFIG";field;value;constructor($,J,Q,Y){let X=J?`Check the '${J}' configuration parameter. ${KX$(J)}`:"Review your SDK configuration and ensure all required fields are provided correctly.";super($,{cause:Y,suggestion:X,retryable:!1});this.field=J,this.value=Q}toJSON(){let $;if(this.field){let J=this.field.toLowerCase();if(Nb.some((Y)=>J.includes(Y.toLowerCase())))$="[REDACTED]";else $=FY(this.value)}else $=FY(this.value);return{...super.toJSON(),field:this.field,value:$}}}function KX$($){switch($.toLowerCase()){case"walletclient":return"Ensure you're creating the wallet client with a valid account and chain configuration.";case"seirpcurl":return"Use 'https://evm-rpc-testnet.sei-apis.com' for testnet or 'https://evm-rpc.sei-apis.com' for mainnet.";case"wsurl":return"Use 'wss://development.apimonaco.xyz/ws' for testnet or 'wss://api.monaco.xyz/ws' for mainnet.";case"network":return"Valid networks are: 'mainnet', 'development', 'staging', 'local'.";default:return"Refer to the SDK documentation for correct configuration format."}}class qW extends _Y{code="INVALID_STATE";currentState;expectedState;constructor($,J,Q,Y){let X=Q?`${J?`Current state is '${J}', `:""}Expected state is '${Q}'. Ensure operations are performed in the correct order.`:"Check that prerequisites are met before calling this method.";super($,{cause:Y,suggestion:X,retryable:!1});this.currentState=J,this.expectedState=Q}toJSON(){return{...super.toJSON(),currentState:this.currentState,expectedState:this.expectedState}}}class y6 extends _Y{code="API_ERROR";endpoint;statusCode;responseBody;requestBody;requestId;retryAfter;constructor($,J){let{suggestion:Q,retryable:Y}=VX$(J?.statusCode,$,J?.responseBody);super($,{cause:J?.cause,suggestion:Q,retryable:Y});this.endpoint=J?.endpoint,this.statusCode=J?.statusCode,this.responseBody=J?.responseBody,this.requestBody=J?.requestBody,this.requestId=J?.requestId,this.retryAfter=J?.retryAfter}toJSON(){return{...super.toJSON(),endpoint:this.endpoint,statusCode:this.statusCode,responseBody:FY(this.responseBody),requestBody:FY(this.requestBody),requestId:this.requestId,retryAfter:this.retryAfter}}}function VX$($,J,Q){if(!$)return{suggestion:"Network request failed. Check your internet connection and try again.",retryable:!0};if($===pQ.StatusCodes.UNAUTHORIZED){if(J?.toLowerCase().includes("expired"))return{suggestion:"Access token has expired. Call sdk.refreshAuth() to get a new token, or call sdk.login() to re-authenticate.",retryable:!1};return{suggestion:"Authentication required. Call sdk.login(clientId) to authenticate before making this request.",retryable:!1}}if($===pQ.StatusCodes.FORBIDDEN)return{suggestion:"Access denied. Ensure your application has the required permissions and your client ID is valid.",retryable:!1};if($===pQ.StatusCodes.NOT_FOUND)return{suggestion:"Resource not found. Check that the ID or identifier is correct and the resource exists.",retryable:!1};if($===pQ.StatusCodes.CONFLICT)return{suggestion:"Resource conflict. The resource may have been modified. Refresh and try again.",retryable:!0};if($===pQ.StatusCodes.BAD_REQUEST){if(J?.toLowerCase().includes("insufficient balance"))return{suggestion:"Insufficient balance. Deposit more funds using sdk.vault.deposit() or reduce the order size.",retryable:!1};if(J?.toLowerCase().includes("invalid"))return{suggestion:"Invalid request parameters. Check the API documentation for correct parameter format and values.",retryable:!1};return{suggestion:"Bad request. Verify that all required parameters are provided and correctly formatted.",retryable:!1}}if($===pQ.StatusCodes.TOO_MANY_REQUESTS){let Y;if(typeof Q==="object"&&Q!==null&&"retry_after"in Q&&Q.retry_after){let X=Q.retry_after;Y=` Wait ${String(X)} seconds before retrying.`}else Y=" Wait a moment before retrying.";return{suggestion:`Rate limit exceeded.${Y} Consider implementing exponential backoff for retries.`,retryable:!0}}if($>=pQ.StatusCodes.INTERNAL_SERVER_ERROR&&$<600)return{suggestion:"Server error occurred. This is likely a temporary issue. Try again in a few moments.",retryable:!0};return{suggestion:void 0,retryable:!1}}class EJ extends _Y{code="CONTRACT_ERROR";revertReason;transactionHash;contractAddress;constructor($,J){let Q=OX$(J?.revertReason);super($,{cause:J?.cause,suggestion:Q,retryable:!1});this.revertReason=J?.revertReason,this.transactionHash=J?.transactionHash,this.contractAddress=J?.contractAddress}toJSON(){return{...super.toJSON(),revertReason:this.revertReason,transactionHash:this.transactionHash,contractAddress:this.contractAddress}}}function OX$($){if(!$)return"Smart contract execution failed. Check transaction parameters and try again.";let J=$.toLowerCase();if(J.includes("insufficient allowance"))return"Token allowance is insufficient. Call sdk.vault.approve() to increase the token allowance for the vault contract.";if(J.includes("insufficient balance"))return"Wallet balance is insufficient for this transaction. Ensure you have enough tokens and native currency for gas fees.";if(J.includes("nonce"))return"Transaction nonce error. This may be due to a pending transaction. Wait for pending transactions to complete or reset your account nonce.";if(J.includes("gas"))return"Transaction ran out of gas. Try increasing the gas limit for this transaction.";return}var NX$={local:"http://localhost:8080",development:"https://develop.apimonaco.xyz",staging:"https://staging.apimonaco.xyz",mainnet:"https://api.monaco.xyz"},zX$={local:"ws://localhost:8085/ws",development:"wss://develop.apimonaco.xyz/ws",staging:"wss://staging.apimonaco.xyz/ws",mainnet:"wss://api.monaco.xyz/ws"};function wW($){return NX$[$]}function V2($){return zX$[$]}var Bl=P6(v3(),1);var P3=256,R3;function T3($=11){if(!R3||P3+$>512){R3="",P3=0;for(let J=0;J<256;J++)R3+=(256+Math.random()*256|0).toString(16).substring(1)}return R3.substring(P3,P3+++$)}function C3($){let{batch:J,chain:Q,ccipRead:Y,dataSuffix:X,key:G="base",name:W="Base Client",type:D="base"}=$,U=$.experimental_blockTag??(typeof Q?.experimental_preconfirmationTime==="number"?"pending":void 0),V=Q?.blockTime??12000,O=Math.min(Math.max(Math.floor(V/2),500),4000),N=$.pollingInterval??O,M=$.cacheTime??N,H=$.account?E$($.account):void 0,{config:w,request:I,value:j}=$.transport({account:H,chain:Q,pollingInterval:N}),L={...w,...j},S={account:H,batch:J,cacheTime:M,ccipRead:Y,chain:Q,dataSuffix:X,key:G,name:W,pollingInterval:N,request:I,transport:L,type:D,uid:T3(),...U?{experimental_blockTag:U}:{}};function B(Z){return(_)=>{let P=_(Z);for(let h in S)delete P[h];let x={...Z,...P};return Object.assign(x,{extend:B(x)})}}return Object.assign(S,{extend:B(S)})}u0();mJ();W1();w8();A$();b$();$X();function yY($){if(!($ instanceof R))return!1;let J=$.walk((Q)=>Q instanceof gY);if(!(J instanceof gY))return!1;if(J.data?.errorName==="HttpError")return!0;if(J.data?.errorName==="ResolverError")return!0;if(J.data?.errorName==="ResolverNotContract")return!0;if(J.data?.errorName==="ResolverNotFound")return!0;if(J.data?.errorName==="ReverseAddressMismatch")return!0;if(J.data?.errorName==="UnsupportedResolverProfile")return!0;return!1}hW();J6();A$();y1();function AN($){if($.length!==66)return null;if($.indexOf("[")!==0)return null;if($.indexOf("]")!==65)return null;let J=`0x${$.slice(1,65)}`;if(!C4(J))return null;return J}function uW($){let J=new Uint8Array(32).fill(0);if(!$)return e$(J);let Q=$.split(".");for(let Y=Q.length-1;Y>=0;Y-=1){let X=AN(Q[Y]),G=X?g1(X):V4(z0(Q[Y]),"bytes");J=V4(Z4([J,G]),"bytes")}return e$(J)}J6();function ng($){return`[${$.slice(2)}]`}J6();A$();y1();function ig($){let J=new Uint8Array(32).fill(0);if(!$)return e$(J);return AN($)||V4(z0($))}function hY($){let J=$.replace(/^\.|\.$/gm,"");if(J.length===0)return new Uint8Array(1);let Q=new Uint8Array(z0(J).byteLength+2),Y=0,X=J.split(".");for(let G=0;G<X.length;G++){let W=z0(X[G]);if(W.byteLength>255)W=z0(ng(ig(X[G])));Q[Y]=W.length,Q.set(W,Y+1),Y+=W.length+1}if(Q.byteLength!==Y+1)return Q.slice(0,Y+1);return Q}function d($,J,Q){let Y=$[J.name];if(typeof Y==="function")return Y;let X=$[Q];if(typeof X==="function")return X;return(G)=>J($,G)}mJ();W1();l4();b$();$X();B8();G5();var q8$=3;function B1($,{abi:J,address:Q,args:Y,docsPath:X,functionName:G,sender:W}){let D=$ instanceof lJ?$:$ instanceof R?$.walk((w)=>("data"in w))||$.walk():{},{code:U,data:V,details:O,message:N,shortMessage:M}=D,H=(()=>{if($ instanceof N0)return new EB({functionName:G,cause:$});if([q8$,iJ.code].includes(U)&&(V||O||N||M)||U===l1.code&&O==="execution reverted"&&V)return new gY({abi:J,data:typeof V==="object"?V.data:V,functionName:G,message:D instanceof L8?O:M??N,cause:$});return $})();return new yW(H,{abi:J,args:Y,contractAddress:Q,docsPath:X,functionName:G,sender:W})}P8();async function p4($,J){let{abi:Q,address:Y,args:X,functionName:G,...W}=J,D=L4({abi:Q,args:X,functionName:G});try{let{data:U}=await d($,d1,"call")({...W,data:D,to:Y});return Z6({abi:Q,args:X,functionName:G,data:U||"0x"})}catch(U){throw B1(U,{abi:Q,address:Y,args:X,docsPath:"/docs/contract/readContract",functionName:G})}}async function Ry($,J){let{blockNumber:Q,blockTag:Y,coinType:X,name:G,gatewayUrls:W,strict:D}=J,{chain:U}=$,V=(()=>{if(J.universalResolverAddress)return J.universalResolverAddress;if(!U)throw Error("client chain not configured. universalResolverAddress is required.");return u1({blockNumber:Q,chain:U,contract:"ensUniversalResolver"})})(),O=U?.ensTlds;if(O&&!O.some((M)=>G.endsWith(M)))return null;let N=(()=>{if(X!=null)return[uW(G),BigInt(X)];return[uW(G)]})();try{let M=L4({abi:N2,functionName:"addr",args:N}),H={address:V,abi:x3,functionName:"resolveWithGateways",args:[x4(hY(G)),M,W??[nJ]],blockNumber:Q,blockTag:Y},I=await d($,p4,"readContract")(H);if(I[0]==="0x")return null;let j=Z6({abi:N2,args:N,functionName:"addr",data:I[0]});if(j==="0x")return null;if(e4(j)==="0x00")return null;return j}catch(M){if(D)throw M;if(yY(M))return null;throw M}}b$();class Kj extends R{constructor({data:$}){super("Unable to extract image from metadata. The metadata may be malformed or invalid.",{metaMessages:["- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.","",`Provided data: ${JSON.stringify($)}`],name:"EnsAvatarInvalidMetadataError"})}}class R8 extends R{constructor({reason:$}){super(`ENS NFT avatar URI is invalid. ${$}`,{name:"EnsAvatarInvalidNftUriError"})}}class $D extends R{constructor({uri:$}){super(`Unable to resolve ENS avatar URI "${$}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}}class Vj extends R{constructor({namespace:$}){super(`ENS NFT avatar namespace "${$}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}var h8$=/(?<protocol>https?:\/\/[^/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/,u8$=/^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?<target>[\w\-.]+))?(?<subtarget>\/.*)?$/,m8$=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,l8$=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function n8$($){try{let J=await fetch($,{method:"HEAD"});if(J.status===200)return J.headers.get("content-type")?.startsWith("image/");return!1}catch(J){if(typeof J==="object"&&typeof J.response<"u")return!1;if(!Object.hasOwn(globalThis,"Image"))return!1;return new Promise((Q)=>{let Y=new Image;Y.onload=()=>{Q(!0)},Y.onerror=()=>{Q(!1)},Y.src=$})}}function Ty($,J){if(!$)return J;if($.endsWith("/"))return $.slice(0,-1);return $}function Oj({uri:$,gatewayUrls:J}){let Q=m8$.test($);if(Q)return{uri:$,isOnChain:!0,isEncoded:Q};let Y=Ty(J?.ipfs,"https://ipfs.io"),X=Ty(J?.arweave,"https://arweave.net"),G=$.match(h8$),{protocol:W,subpath:D,target:U,subtarget:V=""}=G?.groups||{},O=W==="ipns:/"||D==="ipns/",N=W==="ipfs:/"||D==="ipfs/"||u8$.test($);if($.startsWith("http")&&!O&&!N){let H=$;if(J?.arweave)H=$.replace(/https:\/\/arweave.net/g,J?.arweave);return{uri:H,isOnChain:!1,isEncoded:!1}}if((O||N)&&U)return{uri:`${Y}/${O?"ipns":"ipfs"}/${U}${V}`,isOnChain:!1,isEncoded:!1};if(W==="ar:/"&&U)return{uri:`${X}/${U}${V||""}`,isOnChain:!1,isEncoded:!1};let M=$.replace(l8$,"");if(M.startsWith("<svg"))M=`data:image/svg+xml;base64,${btoa(M)}`;if(M.startsWith("data:")||M.startsWith("{"))return{uri:M,isOnChain:!0,isEncoded:!1};throw new $D({uri:$})}function Nj($){if(typeof $!=="object"||!("image"in $)&&!("image_url"in $)&&!("image_data"in $))throw new Kj({data:$});return $.image||$.image_url||$.image_data}async function Cy({gatewayUrls:$,uri:J}){try{let Q=await fetch(J).then((X)=>X.json());return await kN({gatewayUrls:$,uri:Nj(Q)})}catch{throw new $D({uri:J})}}async function kN({gatewayUrls:$,uri:J}){let{uri:Q,isOnChain:Y}=Oj({uri:J,gatewayUrls:$});if(Y)return Q;if(await n8$(Q))return Q;throw new $D({uri:J})}function ky($){let J=$;if(J.startsWith("did:nft:"))J=J.replace("did:nft:","").replace(/_/g,"/");let[Q,Y,X]=J.split("/"),[G,W]=Q.split(":"),[D,U]=Y.split(":");if(!G||G.toLowerCase()!=="eip155")throw new R8({reason:"Only EIP-155 supported"});if(!W)throw new R8({reason:"Chain ID not found"});if(!U)throw new R8({reason:"Contract address not found"});if(!X)throw new R8({reason:"Token ID not found"});if(!D)throw new R8({reason:"ERC namespace not found"});return{chainID:Number.parseInt(W,10),namespace:D.toLowerCase(),contractAddress:U,tokenID:X}}async function xy($,{nft:J}){if(J.namespace==="erc721")return p4($,{address:J.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(J.tokenID)]});if(J.namespace==="erc1155")return p4($,{address:J.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(J.tokenID)]});throw new Vj({namespace:J.namespace})}async function fy($,{gatewayUrls:J,record:Q}){if(/eip155:/i.test(Q))return i8$($,{gatewayUrls:J,record:Q});return kN({uri:Q,gatewayUrls:J})}async function i8$($,{gatewayUrls:J,record:Q}){let Y=ky(Q),X=await xy($,{nft:Y}),{uri:G,isOnChain:W,isEncoded:D}=Oj({uri:X,gatewayUrls:J});if(W&&(G.includes("data:application/json;base64,")||G.startsWith("{"))){let V=D?atob(G.replace("data:application/json;base64,","")):G,O=JSON.parse(V);return kN({uri:Nj(O),gatewayUrls:J})}let U=Y.tokenID;if(Y.namespace==="erc1155")U=U.replace("0x","").padStart(64,"0");return Cy({gatewayUrls:J,uri:G.replace(/(?:0x)?{id}/,U)})}u0();mJ();W1();w8();A$();hW();async function xN($,J){let{blockNumber:Q,blockTag:Y,key:X,name:G,gatewayUrls:W,strict:D}=J,{chain:U}=$,V=(()=>{if(J.universalResolverAddress)return J.universalResolverAddress;if(!U)throw Error("client chain not configured. universalResolverAddress is required.");return u1({blockNumber:Q,chain:U,contract:"ensUniversalResolver"})})(),O=U?.ensTlds;if(O&&!O.some((N)=>G.endsWith(N)))return null;try{let N={address:V,abi:x3,args:[x4(hY(G)),L4({abi:O2,functionName:"text",args:[uW(G),X]}),W??[nJ]],functionName:"resolveWithGateways",blockNumber:Q,blockTag:Y},H=await d($,p4,"readContract")(N);if(H[0]==="0x")return null;let w=Z6({abi:O2,functionName:"text",data:H[0]});return w===""?null:w}catch(N){if(D)throw N;if(yY(N))return null;throw N}}async function by($,{blockNumber:J,blockTag:Q,assetGatewayUrls:Y,name:X,gatewayUrls:G,strict:W,universalResolverAddress:D}){let U=await d($,xN,"getEnsText")({blockNumber:J,blockTag:Q,key:"avatar",name:X,universalResolverAddress:D,gatewayUrls:G,strict:W});if(!U)return null;try{return await fy($,{record:U,gatewayUrls:Y})}catch{return null}}u0();w8();hW();async function gy($,J){let{address:Q,blockNumber:Y,blockTag:X,coinType:G=60n,gatewayUrls:W,strict:D}=J,{chain:U}=$,V=(()=>{if(J.universalResolverAddress)return J.universalResolverAddress;if(!U)throw Error("client chain not configured. universalResolverAddress is required.");return u1({blockNumber:Y,chain:U,contract:"ensUniversalResolver"})})();try{let O={address:V,abi:Mb,args:[Q,G,W??[nJ]],functionName:"reverseWithGateways",blockNumber:Y,blockTag:X},N=d($,p4,"readContract"),[M]=await N(O);return M||null}catch(O){if(D)throw O;if(yY(O))return null;throw O}}w8();A$();async function yy($,J){let{blockNumber:Q,blockTag:Y,name:X}=J,{chain:G}=$,W=(()=>{if(J.universalResolverAddress)return J.universalResolverAddress;if(!G)throw Error("client chain not configured. universalResolverAddress is required.");return u1({blockNumber:Q,chain:G,contract:"ensUniversalResolver"})})(),D=G?.ensTlds;if(D&&!D.some((V)=>X.endsWith(V)))throw Error(`${X} is not a valid ENS TLD (${D?.join(", ")}) for chain "${G.name}" (id: ${G.id}).`);let[U]=await d($,p4,"readContract")({address:W,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"},{type:"uint256"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[x4(hY(X))],blockNumber:Q,blockTag:Y});return U}P8();A$();Qj();sJ();t0();async function fN($,J){let{account:Q=$.account,blockNumber:Y,blockTag:X="latest",blobs:G,data:W,gas:D,gasPrice:U,maxFeePerBlobGas:V,maxFeePerGas:O,maxPriorityFeePerGas:N,to:M,value:H,...w}=J,I=Q?E$(Q):void 0;try{X6(J);let L=(typeof Y==="bigint"?u(Y):void 0)||X,S=$.chain?.formatters?.transactionRequest?.format,Z=(S||F6)({...i1(w,{format:S}),account:I,blobs:G,data:W,gas:D,gasPrice:U,maxFeePerBlobGas:V,maxFeePerGas:O,maxPriorityFeePerGas:N,to:M,value:H},"createAccessList"),_=await $.request({method:"eth_createAccessList",params:[Z,L]});return{accessList:_.accessList,gasUsed:BigInt(_.gasUsed)}}catch(j){throw RN(j,{...J,account:I,chain:$.chain})}}function KX($,{method:J}){let Q={};if($.transport.type==="fallback")$.transport.onResponse?.(({method:Y,response:X,status:G,transport:W})=>{if(G==="success"&&J===Y)Q[X]=W.request});return(Y)=>Q[Y]||$.request}async function hy($){let J=KX($,{method:"eth_newBlockFilter"}),Q=await $.request({method:"eth_newBlockFilter"});return{id:Q,request:J(Q),type:"block"}}l4();b$();class zj extends R{constructor($){super(`Filter type "${$}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}J6();y1();CW();gJ();vJ();eQ();var uy="/docs/contract/encodeEventTopics";function a0($){let{abi:J,eventName:Q,args:Y}=$,X=J[0];if(Q){let U=G1({abi:J,name:Q});if(!U)throw new y3(Q,{docsPath:uy});X=U}if(X.type!=="event")throw new y3(void 0,{docsPath:uy});let G=o4(X),W=sQ(G),D=[];if(Y&&"inputs"in X){let U=X.inputs?.filter((O)=>("indexed"in O)&&O.indexed),V=Array.isArray(Y)?Y:Object.values(Y).length>0?U?.map((O)=>Y[O.name])??[]:[];if(V.length>0)D=U?.map((O,N)=>{if(Array.isArray(V[N]))return V[N].map((M,H)=>my({param:O,value:V[N][H]}));return typeof V[N]<"u"&&V[N]!==null?my({param:O,value:V[N]}):null})??[]}return[W,...D]}function my({param:$,value:J}){if($.type==="string"||$.type==="bytes")return V4(g1(J));if($.type==="tuple"||$.type.match(/^(.*)\[(\d+)?\]$/))throw new zj($.type);return h6([$],[J])}A$();async function bN($,J){let{address:Q,abi:Y,args:X,eventName:G,fromBlock:W,strict:D,toBlock:U}=J,V=KX($,{method:"eth_newFilter"}),O=G?a0({abi:Y,args:X,eventName:G}):void 0,N=await $.request({method:"eth_newFilter",params:[{address:Q,fromBlock:typeof W==="bigint"?u(W):W,toBlock:typeof U==="bigint"?u(U):U,topics:O}]});return{abi:Y,args:X,eventName:G,id:N,request:V(N),strict:Boolean(D),type:"event"}}A$();async function gN($,{address:J,args:Q,event:Y,events:X,fromBlock:G,strict:W,toBlock:D}={}){let U=X??(Y?[Y]:void 0),V=KX($,{method:"eth_newFilter"}),O=[];if(U){if(O=[U.flatMap((H)=>a0({abi:[H],eventName:H.name,args:Q}))],Y)O=O[0]}let N=await $.request({method:"eth_newFilter",params:[{address:J,fromBlock:typeof G==="bigint"?u(G):G,toBlock:typeof D==="bigint"?u(D):D,...O.length?{topics:O}:{}}]});return{abi:U,args:Q,eventName:Y?Y.name:void 0,fromBlock:G,id:N,request:V(N),strict:Boolean(W),toBlock:D,type:"event"}}async function yN($){let J=KX($,{method:"eth_newPendingTransactionFilter"}),Q=await $.request({method:"eth_newPendingTransactionFilter"});return{id:Q,request:J(Q),type:"transaction"}}W1();b$();xJ();y1();function hN($){let J=V4(`0x${$.substring(4)}`).substring(26);return kJ(`0x${J}`)}A1();$6();A$();async function Fh({hash:$,signature:J}){let Q=C4($)?$:x4($),{secp256k1:Y}=await Promise.resolve().then(() => (B5(),jh));return`0x${(()=>{if(typeof J==="object"&&"r"in J&&"s"in J){let{r:V,s:O,v:N,yParity:M}=J,H=Number(M??N),w=Zh(H);return new Y.Signature(y4(V),y4(O)).addRecoveryBit(w)}let W=C4(J)?J:x4(J);if(p$(W)!==65)throw Error("invalid signature length");let D=k4(`0x${W.slice(130)}`),U=Zh(D);return Y.Signature.fromCompact(W.substring(2,130)).addRecoveryBit(U)})().recoverPublicKey(Q.substring(2)).toHex(!1)}`}function Zh($){if($===0||$===1)return $;if($===27)return 0;if($===28)return 1;throw Error("Invalid yParityOrV value")}async function UD({hash:$,signature:J}){return hN(await Fh({hash:$,signature:J}))}J6();A$();b$();a3();J6();A$();function JQ($,J="hex"){let Q=_h($),Y=SY(new Uint8Array(Q.length));if(Q.encode(Y),J==="hex")return e$(Y.bytes);return Y.bytes}function _h($){if(Array.isArray($))return A9$($.map((J)=>_h(J)));return I9$($)}function A9$($){let J=$.reduce((X,G)=>X+G.length,0),Q=Sh(J);return{length:(()=>{if(J<=55)return 1+J;return 1+Q+J})(),encode(X){if(J<=55)X.pushByte(192+J);else if(X.pushByte(247+Q),Q===1)X.pushUint8(J);else if(Q===2)X.pushUint16(J);else if(Q===3)X.pushUint24(J);else X.pushUint32(J);for(let{encode:G}of $)G(X)}}}function I9$($){let J=typeof $==="string"?r4($):$,Q=Sh(J.length);return{length:(()=>{if(J.length===1&&J[0]<128)return 1;if(J.length<=55)return 1+J.length;return 1+Q+J.length})(),encode(X){if(J.length===1&&J[0]<128)X.pushBytes(J);else if(J.length<=55)X.pushByte(128+J.length),X.pushBytes(J);else{if(X.pushByte(183+Q),Q===1)X.pushUint8(J.length);else if(Q===2)X.pushUint16(J.length);else if(Q===3)X.pushUint24(J.length);else X.pushUint32(J.length);X.pushBytes(J)}}}}function Sh($){if($<256)return 1;if($<65536)return 2;if($<16777216)return 3;if($<4294967296)return 4;throw new R("Length is too large.")}y1();function dN($){let{chainId:J,nonce:Q,to:Y}=$,X=$.contractAddress??$.address,G=V4(j6(["0x05",JQ([J?u(J):"0x",X,Q?u(Q):"0x"])]));if(Y==="bytes")return r4(G);return G}async function MX($){let{authorization:J,signature:Q}=$;return UD({hash:dN(J),signature:Q??J})}A$();wN();bY();b$();m1();class gj extends R{constructor($,{account:J,docsPath:Q,chain:Y,data:X,gas:G,gasPrice:W,maxFeePerGas:D,maxPriorityFeePerGas:U,nonce:V,to:O,value:N}){let M=A8({from:J?.address,to:O,value:typeof N<"u"&&`${fY(N)} ${Y?.nativeCurrency?.symbol||"ETH"}`,data:X,gas:G,gasPrice:typeof W<"u"&&`${t4(W)} gwei`,maxFeePerGas:typeof D<"u"&&`${t4(D)} gwei`,maxPriorityFeePerGas:typeof U<"u"&&`${t4(U)} gwei`,nonce:V});super($.shortMessage,{cause:$,docsPath:Q,metaMessages:[...$.metaMessages?[...$.metaMessages," "]:[],"Estimate Gas Arguments:",M].filter(Boolean),name:"EstimateGasExecutionError"});Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=$}}DX();eW();function Eh($,{docsPath:J,...Q}){let Y=(()=>{let X=UX($,Q);if(X instanceof A0)return $;return X})();return new gj(Y,{docsPath:J,...Q})}sJ();CN();t0();bY();b$();class KD extends R{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class k8 extends R{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class yj extends R{constructor({maxPriorityFeePerGas:$}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${t4($)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}$6();b$();class VD extends R{constructor({blockHash:$,blockNumber:J}){let Q="Block";if($)Q=`Block at hash "${$}"`;if(J)Q=`Block at number "${J}"`;super(`${Q} could not be found.`,{name:"BlockNotFoundError"})}}A$();$6();var hj={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function j5($,J){let Q={...$,blockHash:$.blockHash?$.blockHash:null,blockNumber:$.blockNumber?BigInt($.blockNumber):null,...$.blockTimestamp!=null&&{blockTimestamp:BigInt($.blockTimestamp)},chainId:$.chainId?k4($.chainId):void 0,gas:$.gas?BigInt($.gas):void 0,gasPrice:$.gasPrice?BigInt($.gasPrice):void 0,maxFeePerBlobGas:$.maxFeePerBlobGas?BigInt($.maxFeePerBlobGas):void 0,maxFeePerGas:$.maxFeePerGas?BigInt($.maxFeePerGas):void 0,maxPriorityFeePerGas:$.maxPriorityFeePerGas?BigInt($.maxPriorityFeePerGas):void 0,nonce:$.nonce?k4($.nonce):void 0,to:$.to?$.to:null,transactionIndex:$.transactionIndex?Number($.transactionIndex):null,type:$.type?hj[$.type]:void 0,typeHex:$.type?$.type:void 0,value:$.value?BigInt($.value):void 0,v:$.v?BigInt($.v):void 0};if($.authorizationList)Q.authorizationList=L9$($.authorizationList);if(Q.yParity=(()=>{if($.yParity)return Number($.yParity);if(typeof Q.v==="bigint"){if(Q.v===0n||Q.v===27n)return 0;if(Q.v===1n||Q.v===28n)return 1;if(Q.v>=35n)return Q.v%2n===0n?1:0}return})(),Q.type==="legacy")delete Q.accessList,delete Q.maxFeePerBlobGas,delete Q.maxFeePerGas,delete Q.maxPriorityFeePerGas,delete Q.yParity;if(Q.type==="eip2930")delete Q.maxFeePerBlobGas,delete Q.maxFeePerGas,delete Q.maxPriorityFeePerGas;if(Q.type==="eip1559")delete Q.maxFeePerBlobGas;return Q}function L9$($){return $.map((J)=>({address:J.address,chainId:Number(J.chainId),nonce:Number(J.nonce),r:J.r,s:J.s,yParity:Number(J.yParity)}))}function pN($,J){let Q=($.transactions??[]).map((Y)=>{if(typeof Y==="string")return Y;return j5(Y)});return{...$,baseFeePerGas:$.baseFeePerGas?BigInt($.baseFeePerGas):null,blobGasUsed:$.blobGasUsed?BigInt($.blobGasUsed):void 0,difficulty:$.difficulty?BigInt($.difficulty):void 0,excessBlobGas:$.excessBlobGas?BigInt($.excessBlobGas):void 0,gasLimit:$.gasLimit?BigInt($.gasLimit):void 0,gasUsed:$.gasUsed?BigInt($.gasUsed):void 0,hash:$.hash?$.hash:null,logsBloom:$.logsBloom?$.logsBloom:null,nonce:$.nonce?$.nonce:null,number:$.number?BigInt($.number):null,size:$.size?BigInt($.size):void 0,timestamp:$.timestamp?BigInt($.timestamp):void 0,transactions:Q,totalDifficulty:$.totalDifficulty?BigInt($.totalDifficulty):null}}async function Y6($,{blockHash:J,blockNumber:Q,blockTag:Y=$.experimental_blockTag??"latest",includeTransactions:X}={}){let G=X??!1,W=Q!==void 0?u(Q):void 0,D=null;if(J)D=await $.request({method:"eth_getBlockByHash",params:[J,G]},{dedupe:!0});else D=await $.request({method:"eth_getBlockByNumber",params:[W||Y,G]},{dedupe:Boolean(W)});if(!D)throw new VD({blockHash:J,blockNumber:Q});return($.chain?.formatters?.block?.format||pN)(D,"getBlock")}async function Z5($){let J=await $.request({method:"eth_gasPrice"});return BigInt(J)}async function vh($,J){return uj($,J)}async function uj($,J){let{block:Q,chain:Y=$.chain,request:X}=J||{};try{let G=Y?.fees?.maxPriorityFeePerGas??Y?.fees?.defaultPriorityFee;if(typeof G==="function"){let D=Q||await d($,Y6,"getBlock")({}),U=await G({block:D,client:$,request:X});if(U===null)throw Error();return U}if(typeof G<"u")return G;let W=await $.request({method:"eth_maxPriorityFeePerGas"});return y4(W)}catch{let[G,W]=await Promise.all([Q?Promise.resolve(Q):d($,Y6,"getBlock")({}),d($,Z5,"getGasPrice")({})]);if(typeof G.baseFeePerGas!=="bigint")throw new k8;let D=W-G.baseFeePerGas;if(D<0n)return 0n;return D}}async function Ph($,J){return cN($,J)}async function cN($,J){let{block:Q,chain:Y=$.chain,request:X,type:G="eip1559"}=J||{},W=await(async()=>{if(typeof Y?.fees?.baseFeeMultiplier==="function")return Y.fees.baseFeeMultiplier({block:Q,client:$,request:X});return Y?.fees?.baseFeeMultiplier??1.2})();if(W<1)throw new KD;let U=10**(W.toString().split(".")[1]?.length??0),V=(M)=>M*BigInt(Math.ceil(W*U))/BigInt(U),O=Q?Q:await d($,Y6,"getBlock")({});if(typeof Y?.fees?.estimateFeesPerGas==="function"){let M=await Y.fees.estimateFeesPerGas({block:Q,client:$,multiply:V,request:X,type:G});if(M!==null)return M}if(G==="eip1559"){if(typeof O.baseFeePerGas!=="bigint")throw new k8;let M=typeof X?.maxPriorityFeePerGas==="bigint"?X.maxPriorityFeePerGas:await uj($,{block:O,chain:Y,request:X}),H=V(O.baseFeePerGas);return{maxFeePerGas:X?.maxFeePerGas??H+M,maxPriorityFeePerGas:M}}return{gasPrice:X?.gasPrice??V(await d($,Z5,"getGasPrice")({}))}}$6();A$();async function F5($,{address:J,blockTag:Q="latest",blockNumber:Y}){let X=await $.request({method:"eth_getTransactionCount",params:[J,typeof Y==="bigint"?u(Y):Q]},{dedupe:Boolean(Y)});return k4(X)}J6();A$();function _5($){let{kzg:J}=$,Q=$.to??(typeof $.blobs[0]==="string"?"hex":"bytes"),Y=typeof $.blobs[0]==="string"?$.blobs.map((G)=>r4(G)):$.blobs,X=[];for(let G of Y)X.push(Uint8Array.from(J.blobToKzgCommitment(G)));return Q==="bytes"?X:X.map((G)=>e$(G))}J6();A$();function S5($){let{kzg:J}=$,Q=$.to??(typeof $.blobs[0]==="string"?"hex":"bytes"),Y=typeof $.blobs[0]==="string"?$.blobs.map((W)=>r4(W)):$.blobs,X=typeof $.commitments[0]==="string"?$.commitments.map((W)=>r4(W)):$.commitments,G=[];for(let W=0;W<Y.length;W++){let D=Y[W],U=X[W];G.push(Uint8Array.from(J.computeBlobKzgProof(D,U)))}return Q==="bytes"?G:G.map((W)=>e$(W))}A$();qj();var Rh=T8;J6();A$();function Th($,J){let Q=J||"hex",Y=Rh(C4($,{strict:!1})?g1($):$);if(Q==="bytes")return Y;return x4(Y)}function Ch($){let{commitment:J,version:Q=1}=$,Y=$.to??(typeof J==="string"?"hex":"bytes"),X=Th(J,"bytes");return X.set([Q],0),Y==="bytes"?X:e$(X)}function oN($){let{commitments:J,version:Q}=$,Y=$.to??(typeof J[0]==="string"?"hex":"bytes"),X=[];for(let G of J)X.push(Ch({commitment:G,to:Y,version:Q}));return X}var kh=32,xh=4096,fh=131072,mj=761855;var rN=1;b$();class lj extends R{constructor({maxSize:$,size:J}){super("Blob size is too large.",{metaMessages:[`Max: ${$} bytes`,`Given: ${J} bytes`],name:"BlobSizeTooLargeError"})}}class OD extends R{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class nj extends R{constructor({hash:$,size:J}){super(`Versioned hash "${$}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${J}`],name:"InvalidVersionedHashSizeError"})}}class ij extends R{constructor({hash:$,version:J}){super(`Versioned hash "${$}" version is invalid.`,{metaMessages:[`Expected: ${rN}`,`Received: ${J}`],name:"InvalidVersionedHashVersionError"})}}a3();A1();J6();A$();function bh($){let J=$.to??(typeof $.data==="string"?"hex":"bytes"),Q=typeof $.data==="string"?r4($.data):$.data,Y=p$(Q);if(!Y)throw new OD;if(Y>mj)throw new lj({maxSize:mj,size:Y});let X=[],G=!0,W=0;while(G){let D=SY(new Uint8Array(fh)),U=0;while(U<xh){let V=Q.slice(W,W+(kh-1));if(D.pushByte(0),D.pushBytes(V),V.length<31){D.pushByte(128),G=!1;break}U++,W+=31}X.push(D)}return J==="bytes"?X.map((D)=>D.bytes):X.map((D)=>e$(D.bytes))}function tN($){let{data:J,kzg:Q,to:Y}=$,X=$.blobs??bh({data:J,to:Y}),G=$.commitments??_5({blobs:X,kzg:Q,to:Y}),W=$.proofs??S5({blobs:X,commitments:G,kzg:Q,to:Y}),D=[];for(let U=0;U<X.length;U++)D.push({blob:X[U],commitment:G[U],proof:W[U]});return D}H8();t0();m1();function aN($){if($.type)return $.type;if(typeof $.authorizationList<"u")return"eip7702";if(typeof $.blobs<"u"||typeof $.blobVersionedHashes<"u"||typeof $.maxFeePerBlobGas<"u"||typeof $.sidecars<"u")return"eip4844";if(typeof $.maxFeePerGas<"u"||typeof $.maxPriorityFeePerGas<"u")return"eip1559";if(typeof $.gasPrice<"u"){if(typeof $.accessList<"u")return"eip2930";return"legacy"}throw new ZB({transaction:$})}DX();m1();eW();function HX($,{docsPath:J,...Q}){let Y=(()=>{let X=UX($,Q);if(X instanceof A0)return $;return X})();return new _B(Y,{docsPath:J,...Q})}sJ();t0();$6();async function S6($){let J=await $.request({method:"eth_chainId"},{dedupe:!0});return k4(J)}async function E5($,J){let{account:Q=$.account,accessList:Y,authorizationList:X,chain:G=$.chain,blobVersionedHashes:W,blobs:D,data:U,gas:V,gasPrice:O,maxFeePerBlobGas:N,maxFeePerGas:M,maxPriorityFeePerGas:H,nonce:w,nonceManager:I,to:j,type:L,value:S,...B}=J,Z=await(async()=>{if(!Q)return w;if(!I)return w;if(typeof w<"u")return w;let h=E$(Q),p=G?G.id:await d($,S6,"getChainId")({});return await I.consume({address:h.address,chainId:p,client:$})})();X6(J);let _=G?.formatters?.transactionRequest?.format,x=(_||F6)({...i1(B,{format:_}),account:Q?E$(Q):void 0,accessList:Y,authorizationList:X,blobs:D,blobVersionedHashes:W,data:U,gas:V,gasPrice:O,maxFeePerBlobGas:N,maxFeePerGas:M,maxPriorityFeePerGas:H,nonce:Z,to:j,type:L,value:S},"fillTransaction");try{let h=await $.request({method:"eth_fillTransaction",params:[x]}),b=(G?.formatters?.transaction?.format||j5)(h.tx);if(delete b.blockHash,delete b.blockNumber,delete b.r,delete b.s,delete b.transactionIndex,delete b.v,delete b.yParity,b.data=b.input,b.gas)b.gas=J.gas??b.gas;if(b.gasPrice)b.gasPrice=J.gasPrice??b.gasPrice;if(b.maxFeePerBlobGas)b.maxFeePerBlobGas=J.maxFeePerBlobGas??b.maxFeePerBlobGas;if(b.maxFeePerGas)b.maxFeePerGas=J.maxFeePerGas??b.maxFeePerGas;if(b.maxPriorityFeePerGas)b.maxPriorityFeePerGas=J.maxPriorityFeePerGas??b.maxPriorityFeePerGas;if(typeof b.nonce<"u")b.nonce=J.nonce??b.nonce;let Q$=await(async()=>{if(typeof G?.fees?.baseFeeMultiplier==="function"){let T=await d($,Y6,"getBlock")({});return G.fees.baseFeeMultiplier({block:T,client:$,request:J})}return G?.fees?.baseFeeMultiplier??1.2})();if(Q$<1)throw new KD;let K$=10**(Q$.toString().split(".")[1]?.length??0),y=(T)=>T*BigInt(Math.ceil(Q$*K$))/BigInt(K$);if(!b.feePayerSignature){if(b.maxFeePerGas&&!J.maxFeePerGas)b.maxFeePerGas=y(b.maxFeePerGas);if(b.gasPrice&&!J.gasPrice)b.gasPrice=y(b.gasPrice)}return{raw:h.raw,transaction:{from:x.from,...b},...h.capabilities?{capabilities:h.capabilities}:{}}}catch(h){throw HX(h,{...J,chain:$.chain})}}var ND=["blobVersionedHashes","chainId","fees","gas","nonce","type"],gh=new Map,dj=new I1(128);async function s0($,J){let Q=J;Q.account??=$.account,Q.parameters??=ND;let{account:Y,chain:X=$.chain,nonceManager:G,parameters:W}=Q,D=(()=>{if(typeof X?.prepareTransactionRequest==="function")return{fn:X.prepareTransactionRequest,runAt:["beforeFillTransaction"]};if(Array.isArray(X?.prepareTransactionRequest))return{fn:X.prepareTransactionRequest[0],runAt:X.prepareTransactionRequest[1].runAt};return})(),U;async function V(){if(U)return U;if(typeof Q.chainId<"u")return Q.chainId;if(X)return X.id;return U=await d($,S6,"getChainId")({}),U}let O=Y?E$(Y):Y,N=Q.nonce;if(W.includes("nonce")&&typeof N>"u"&&O&&G){let Z=await V();N=await G.consume({address:O.address,chainId:Z,client:$})}if(D?.fn&&D.runAt?.includes("beforeFillTransaction"))Q=await D.fn({...Q,chain:X},{phase:"beforeFillTransaction"}),N??=Q.nonce;let H=(()=>{if((W.includes("blobVersionedHashes")||W.includes("sidecars"))&&Q.kzg&&Q.blobs)return!1;if(dj.get($.uid)===!1)return!1;if(!["fees","gas"].some((_)=>W.includes(_)))return!1;if(W.includes("chainId")&&typeof Q.chainId!=="number")return!0;if(W.includes("nonce")&&typeof N!=="number")return!0;if(W.includes("fees")&&typeof Q.gasPrice!=="bigint"&&(typeof Q.maxFeePerGas!=="bigint"||typeof Q.maxPriorityFeePerGas!=="bigint"))return!0;if(W.includes("gas")&&typeof Q.gas!=="bigint")return!0;return!1})()?await d($,E5,"fillTransaction")({...Q,nonce:N}).then((Z)=>{let{chainId:_,from:P,gas:x,gasPrice:h,nonce:p,maxFeePerBlobGas:b,maxFeePerGas:Q$,maxPriorityFeePerGas:s,type:K$,...y}=Z.transaction;return dj.set($.uid,!0),{...Q,...P?{from:P}:{},...K$&&!Q.type?{type:K$}:{},...typeof _<"u"?{chainId:_}:{},...typeof x<"u"?{gas:x}:{},...typeof h<"u"?{gasPrice:h}:{},...typeof p<"u"?{nonce:p}:{},...typeof b<"u"&&Q.type!=="legacy"&&Q.type!=="eip2930"?{maxFeePerBlobGas:b}:{},...typeof Q$<"u"&&Q.type!=="legacy"&&Q.type!=="eip2930"?{maxFeePerGas:Q$}:{},...typeof s<"u"&&Q.type!=="legacy"&&Q.type!=="eip2930"?{maxPriorityFeePerGas:s}:{},..."nonceKey"in y&&typeof y.nonceKey<"u"?{nonceKey:y.nonceKey}:{},..."keyAuthorization"in y&&typeof y.keyAuthorization<"u"&&y.keyAuthorization!==null&&!("keyAuthorization"in Q)?{keyAuthorization:y.keyAuthorization}:{},..."feePayerSignature"in y&&typeof y.feePayerSignature<"u"&&y.feePayerSignature!==null?{feePayerSignature:y.feePayerSignature}:{},..."feeToken"in y&&typeof y.feeToken<"u"&&y.feeToken!==null&&!("feeToken"in Q)?{feeToken:y.feeToken}:{},...Z.capabilities?{_capabilities:Z.capabilities}:{}}}).catch((Z)=>{let _=Z;if(_.name!=="TransactionExecutionError")return Q;if(_.walk?.((h)=>{return h.name==="ExecutionRevertedError"}))throw Z;if(_.walk?.((h)=>{let p=h;return p.name==="MethodNotFoundRpcError"||p.name==="MethodNotSupportedRpcError"||p.message?.includes("eth_fillTransaction is not available")}))dj.set($.uid,!1);return Q}):Q;N??=H.nonce,Q={...H,...O?{from:O?.address}:{},...typeof N<"u"?{nonce:N}:{}};let{blobs:w,gas:I,kzg:j,type:L}=Q;if(D?.fn&&D.runAt?.includes("beforeFillParameters"))Q=await D.fn({...Q,chain:X},{phase:"beforeFillParameters"});let S;async function B(){if(S)return S;return S=await d($,Y6,"getBlock")({blockTag:"latest"}),S}if(W.includes("nonce")&&typeof N>"u"&&O&&!G)Q.nonce=await d($,F5,"getTransactionCount")({address:O.address,blockTag:"pending"});if((W.includes("blobVersionedHashes")||W.includes("sidecars"))&&w&&j){let Z=_5({blobs:w,kzg:j});if(W.includes("blobVersionedHashes")){let _=oN({commitments:Z,to:"hex"});Q.blobVersionedHashes=_}if(W.includes("sidecars")){let _=S5({blobs:w,commitments:Z,kzg:j}),P=tN({blobs:w,commitments:Z,proofs:_,to:"hex"});Q.sidecars=P}}if(W.includes("chainId"))Q.chainId=await V();if((W.includes("fees")||W.includes("type"))&&typeof L>"u")try{Q.type=aN(Q)}catch{let Z=gh.get($.uid);if(typeof Z>"u")Z=typeof(await B())?.baseFeePerGas==="bigint",gh.set($.uid,Z);Q.type=Z?"eip1559":"legacy"}if(W.includes("fees"))if(Q.type!=="legacy"&&Q.type!=="eip2930"){if(typeof Q.maxFeePerGas>"u"||typeof Q.maxPriorityFeePerGas>"u"){let Z=await B(),{maxFeePerGas:_,maxPriorityFeePerGas:P}=await cN($,{block:Z,chain:X,request:Q});if(typeof Q.maxPriorityFeePerGas>"u"&&Q.maxFeePerGas&&Q.maxFeePerGas<P)throw new yj({maxPriorityFeePerGas:P});Q.maxPriorityFeePerGas=P,Q.maxFeePerGas=_}}else{if(typeof Q.maxFeePerGas<"u"||typeof Q.maxPriorityFeePerGas<"u")throw new k8;if(typeof Q.gasPrice>"u"){let Z=await B(),{gasPrice:_}=await cN($,{block:Z,chain:X,request:Q,type:"legacy"});Q.gasPrice=_}}if(W.includes("gas")&&typeof I>"u")Q.gas=await d($,v5,"estimateGas")({...Q,account:O,prepare:O?.type==="local"?[]:["blobVersionedHashes"]});if(D?.fn&&D.runAt?.includes("afterFillParameters"))Q=await D.fn({...Q,chain:X},{phase:"afterFillParameters"});return X6(Q),delete Q.parameters,Q}async function v5($,J){let{account:Q=$.account,prepare:Y=!0}=J,X=Q?E$(Q):void 0,G=(()=>{if(Array.isArray(Y))return Y;if(X?.type!=="local")return["blobVersionedHashes"];return})();try{let W=await(async()=>{if(J.to)return J.to;if(J.authorizationList&&J.authorizationList.length>0)return await MX({authorization:J.authorizationList[0]}).catch(()=>{throw new R("`to` is required. Could not infer from `authorizationList`")});return})(),{accessList:D,authorizationList:U,blobs:V,blobVersionedHashes:O,blockNumber:N,blockTag:M,data:H,gas:w,gasPrice:I,maxFeePerBlobGas:j,maxFeePerGas:L,maxPriorityFeePerGas:S,nonce:B,value:Z,stateOverride:_,...P}=Y?await s0($,{...J,parameters:G,to:W}):J;if(w&&J.gas!==w)return w;let h=(typeof N==="bigint"?u(N):void 0)||M,p=w5(_);X6(J);let b=$.chain?.formatters?.transactionRequest?.format,s=(b||F6)({...i1(P,{format:b}),account:X,accessList:D,authorizationList:U,blobs:V,blobVersionedHashes:O,data:H,gasPrice:I,maxFeePerBlobGas:j,maxFeePerGas:L,maxPriorityFeePerGas:S,nonce:B,to:W,value:Z},"estimateGas");return BigInt(await $.request({method:"eth_estimateGas",params:p?[s,h??$.experimental_blockTag??"latest",p]:h?[s,h]:[s]}))}catch(W){throw Eh(W,{...J,account:X,chain:$.chain})}}async function yh($,J){let{abi:Q,address:Y,args:X,functionName:G,dataSuffix:W=typeof $.dataSuffix==="string"?$.dataSuffix:$.dataSuffix?.value,...D}=J,U=L4({abi:Q,args:X,functionName:G});try{return await d($,v5,"estimateGas")({data:`${U}${W?W.replace("0x",""):""}`,to:Y,...D})}catch(V){let O=D.account?E$(D.account):void 0;throw B1(V,{abi:Q,address:Y,args:X,docsPath:"/docs/contract/estimateContractGas",functionName:G,sender:O?.address})}}u0();mJ();W1();A$();P8();async function hh($,{address:J,blockNumber:Q,blockTag:Y=$.experimental_blockTag??"latest"}){if($.batch?.multicall&&$.chain?.contracts?.multicall3){let W=$.chain.contracts.multicall3.address,D=L4({abi:O0,functionName:"getEthBalance",args:[J]}),{data:U}=await d($,d1,"call")({to:W,data:D,blockNumber:Q,blockTag:Y});return Z6({abi:O0,functionName:"getEthBalance",args:[J],data:U||"0x"})}let X=typeof Q==="bigint"?u(Q):void 0,G=await $.request({method:"eth_getBalance",params:[J,X||Y]});return BigInt(G)}async function uh($){let J=await $.request({method:"eth_blobBaseFee"});return BigInt(J)}var B9$=new Map,j9$=new Map;function mh($){let J=(X,G)=>({clear:()=>G.delete(X),get:()=>G.get(X),set:(W)=>G.set(X,W)}),Q=J($,B9$),Y=J($,j9$);return{clear:()=>{Q.clear(),Y.clear()},promise:Q,response:Y}}async function lh($,{cacheKey:J,cacheTime:Q=Number.POSITIVE_INFINITY}){let Y=mh(J),X=Y.response.get();if(X&&Q>0){if(Date.now()-X.created.getTime()<Q)return X.data}let G=Y.promise.get();if(!G)G=$(),Y.promise.set(G);try{let W=await G;return Y.response.set({created:new Date,data:W}),W}finally{Y.promise.clear()}}var Z9$=($)=>`blockNumber.${$}`;async function e0($,{cacheTime:J=$.cacheTime}={}){let Q=await lh(()=>$.request({method:"eth_blockNumber"}),{cacheKey:Z9$($.uid),cacheTime:J});return BigInt(Q)}$6();A$();async function nh($,{blockHash:J,blockNumber:Q,blockTag:Y="latest"}={}){let X=Q!==void 0?u(Q):void 0,G;if(J)G=await $.request({method:"eth_getBlockTransactionCountByHash",params:[J]},{dedupe:!0});else G=await $.request({method:"eth_getBlockTransactionCountByNumber",params:[X||Y]},{dedupe:Boolean(X)});return k4(G)}A$();async function x8($,{address:J,blockNumber:Q,blockTag:Y="latest"}){let X=Q!==void 0?u(Q):void 0,G=await $.request({method:"eth_getCode",params:[J,X||Y]},{dedupe:Boolean(X)});if(G==="0x")return;return G}eQ();v8();J6();function G6($,{args:J,eventName:Q}={}){return{...$,blockHash:$.blockHash?$.blockHash:null,blockNumber:$.blockNumber?BigInt($.blockNumber):null,blockTimestamp:$.blockTimestamp?BigInt($.blockTimestamp):$.blockTimestamp===null?null:void 0,logIndex:$.logIndex?Number($.logIndex):null,transactionHash:$.transactionHash?$.transactionHash:null,transactionIndex:$.transactionIndex?Number($.transactionIndex):null,...Q?{args:J,eventName:Q}:{}}}y1();CW();l4();u2();A1();CW();vW();vJ();var ih="/docs/contract/decodeEventLog";function f8($){let{abi:J,data:Q,strict:Y,topics:X}=$,G=Y??!0,[W,...D]=X;if(!W)throw new j2({docsPath:ih});let U=J.find((L)=>L.type==="event"&&W===sQ(o4(L)));if(!(U&&("name"in U))||U.type!=="event")throw new Z2(W,{docsPath:ih});let{name:V,inputs:O}=U,N=O?.some((L)=>!(("name"in L)&&L.name)),M=N?[]:{},H=O.map((L,S)=>[L,S]).filter(([L])=>("indexed"in L)&&L.indexed),w=[];for(let L=0;L<H.length;L++){let[S,B]=H[L],Z=D[L];if(!Z){if(G)throw new K8({abiItem:U,param:S});w.push([S,B]);continue}M[N?B:S.name||B]=F9$({param:S,value:Z})}let I=O.filter((L)=>!(("indexed"in L)&&L.indexed)),j=G?I:[...w.map(([L])=>L),...I];if(j.length>0){if(Q&&Q!=="0x")try{let L=yJ(j,Q);if(L){let S=0;if(!G)for(let[B,Z]of w)M[N?Z:B.name||Z]=L[S++];if(N){for(let B=0;B<O.length;B++)if(M[B]===void 0&&S<L.length)M[B]=L[S++]}else for(let B=0;B<I.length;B++)M[I[B].name]=L[S++]}}catch(L){if(G){if(L instanceof LW||L instanceof SW)throw new cQ({abiItem:U,data:Q,params:j,size:p$(Q)});throw L}}else if(G)throw new cQ({abiItem:U,data:"0x",params:j,size:0})}return{eventName:V,args:Object.values(M).length>0?M:void 0}}function F9$({param:$,value:J}){if($.type==="string"||$.type==="bytes"||$.type==="tuple"||$.type.match(/^(.*)\[(\d+)?\]$/))return J;return(yJ([$],J)||[])[0]}function P5($){let{abi:J,args:Q,logs:Y,strict:X=!0}=$,G=(()=>{if(!$.eventName)return;if(Array.isArray($.eventName))return $.eventName;return[$.eventName]})(),W=J.filter((D)=>D.type==="event").map((D)=>({abi:D,selector:sQ(D)}));return Y.map((D)=>{let U=typeof D.blockNumber==="string"?G6(D):D,V=W.filter((M)=>U.topics[0]===M.selector);if(V.length===0)return null;let O,N;for(let M of V)try{O=f8({...U,abi:[M.abi],strict:!0}),N=M;break}catch{}if(!O&&!X){N=V[0];try{O=f8({data:U.data,topics:U.topics,abi:[N.abi],strict:!1})}catch{let M=N.abi.inputs?.some((H)=>!(("name"in H)&&H.name));return{...U,args:M?[]:{},eventName:N.abi.name}}}if(!O||!N)return null;if(G&&!G.includes(O.eventName))return null;if(!_9$({args:O.args,inputs:N.abi.inputs,matchArgs:Q}))return null;return{...O,...U}}).filter(Boolean)}function _9$($){let{args:J,inputs:Q,matchArgs:Y}=$;if(!Y)return!0;if(!J)return!1;function X(G,W,D){try{if(G.type==="address")return Z1(W,D);if(G.type==="string"||G.type==="bytes")return V4(g1(W))===D;return W===D}catch{return!1}}if(Array.isArray(J)&&Array.isArray(Y))return Y.every((G,W)=>{if(G===null||G===void 0)return!0;let D=Q[W];if(!D)return!1;return(Array.isArray(G)?G:[G]).some((V)=>X(D,V,J[W]))});if(typeof J==="object"&&!Array.isArray(J)&&typeof Y==="object"&&!Array.isArray(Y))return Object.entries(Y).every(([G,W])=>{if(W===null||W===void 0)return!0;let D=Q.find((V)=>V.name===G);if(!D)return!1;return(Array.isArray(W)?W:[W]).some((V)=>X(D,V,J[G]))});return!1}A$();async function R5($,{address:J,blockHash:Q,fromBlock:Y,toBlock:X,event:G,events:W,args:D,strict:U}={}){let V=U??!1,O=W??(G?[G]:void 0),N=[];if(O){if(N=[O.flatMap((I)=>a0({abi:[I],eventName:I.name,args:W?void 0:D}))],G)N=N[0]}let M;if(Q)M=await $.request({method:"eth_getLogs",params:[{address:J,topics:N,blockHash:Q}]});else M=await $.request({method:"eth_getLogs",params:[{address:J,topics:N,fromBlock:typeof Y==="bigint"?u(Y):Y,toBlock:typeof X==="bigint"?u(X):X}]});let H=M.map((w)=>G6(w));if(!O)return H;return P5({abi:O,args:D,logs:H,strict:V})}async function sN($,J){let{abi:Q,address:Y,args:X,blockHash:G,eventName:W,fromBlock:D,toBlock:U,strict:V}=J,O=W?G1({abi:Q,name:W}):void 0,N=!O?Q.filter((M)=>M.type==="event"):void 0;return d($,R5,"getLogs")({address:Y,args:X,blockHash:G,event:O,events:N,fromBlock:D,toBlock:U,strict:V})}xJ();A1();bJ();async function dh($,{address:J,blockNumber:Q,blockTag:Y="latest"}){let X=await x8($,{address:J,...Q!==void 0?{blockNumber:Q}:{blockTag:Y}});if(!X)return;if(p$(X)!==23)return;if(!X.startsWith("0xef0100"))return;return fJ(X1(X,3,23))}b$();class pj extends R{constructor({address:$}){super(`No EIP-712 domain found on contract "${$}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${$}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}}async function ph($,J){let{address:Q,factory:Y,factoryData:X}=J;try{let[G,W,D,U,V,O,N]=await d($,p4,"readContract")({abi:S9$,address:Q,functionName:"eip712Domain",factory:Y,factoryData:X});return{domain:{name:W,version:D,chainId:Number(U),verifyingContract:V,salt:O},extensions:N,fields:G}}catch(G){let W=G;if(W.name==="ContractFunctionExecutionError"&&W.cause.name==="ContractFunctionZeroDataError")throw new pj({address:Q});throw W}}var S9$=[{inputs:[],name:"eip712Domain",outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"}];A$();function ch($){return{baseFeePerGas:$.baseFeePerGas.map((J)=>BigInt(J)),gasUsedRatio:$.gasUsedRatio,oldestBlock:BigInt($.oldestBlock),reward:$.reward?.map((J)=>J.map((Q)=>BigInt(Q)))}}async function oh($,{blockCount:J,blockNumber:Q,blockTag:Y="latest",rewardPercentiles:X}){let G=typeof Q==="bigint"?u(Q):void 0,W=await $.request({method:"eth_feeHistory",params:[u(J),G||Y,X]},{dedupe:Boolean(G)});return ch(W)}async function qX($,{filter:J}){let Q="strict"in J&&J.strict,Y=await J.request({method:"eth_getFilterChanges",params:[J.id]});if(typeof Y[0]==="string")return Y;let X=Y.map((G)=>G6(G));if(!("abi"in J)||!J.abi)return X;return P5({abi:J.abi,logs:X,strict:Q})}async function rh($,{filter:J}){let Q=J.strict??!1,X=(await J.request({method:"eth_getFilterLogs",params:[J.id]})).map((G)=>G6(G));if(!J.abi)return X;return P5({abi:J.abi,logs:X,strict:Q})}A$();$6();function E9$($){return $.map((J)=>({...J,value:BigInt(J.value)}))}function th($){return{...$,balance:$.balance?BigInt($.balance):void 0,nonce:$.nonce?k4($.nonce):void 0,storageProof:$.storageProof?E9$($.storageProof):void 0}}async function ah($,{address:J,blockNumber:Q,blockTag:Y,storageKeys:X}){let G=Y??"latest",W=Q!==void 0?u(Q):void 0,D=await $.request({method:"eth_getProof",params:[J,X,W||G]});return th(D)}A$();async function sh($,{address:J,blockNumber:Q,blockTag:Y="latest",slot:X}){let G=Q!==void 0?u(Q):void 0;return await $.request({method:"eth_getStorageAt",params:[J,X,G||Y]})}m1();A$();async function T5($,{blockHash:J,blockNumber:Q,blockTag:Y,hash:X,index:G,sender:W,nonce:D}){let U=Y||"latest",V=Q!==void 0?u(Q):void 0,O=null;if(X)O=await $.request({method:"eth_getTransactionByHash",params:[X]},{dedupe:!0});else if(J)O=await $.request({method:"eth_getTransactionByBlockHashAndIndex",params:[J,u(G)]},{dedupe:!0});else if((V||U)&&typeof G==="number")O=await $.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[V||U,u(G)]},{dedupe:Boolean(V)});else if(W&&typeof D==="number")O=await $.request({method:"eth_getTransactionBySenderAndNonce",params:[W,u(D)]},{dedupe:!0});if(!O)throw new xW({blockHash:J,blockNumber:Q,blockTag:U,hash:X,index:G});return($.chain?.formatters?.transaction?.format||j5)(O,"getTransaction")}async function eh($,{hash:J,transactionReceipt:Q}){let[Y,X]=await Promise.all([d($,e0,"getBlockNumber")({}),J?d($,T5,"getTransaction")({hash:J}):void 0]),G=Q?.blockNumber||X?.blockNumber;if(!G)return 0n;return Y-G+1n}m1();$6();var cj={"0x0":"reverted","0x1":"success"};function eN($,J){let Q={...$,blockNumber:$.blockNumber?BigInt($.blockNumber):null,contractAddress:$.contractAddress?$.contractAddress:null,cumulativeGasUsed:$.cumulativeGasUsed?BigInt($.cumulativeGasUsed):null,effectiveGasPrice:$.effectiveGasPrice?BigInt($.effectiveGasPrice):null,gasUsed:$.gasUsed?BigInt($.gasUsed):null,logs:$.logs?$.logs.map((Y)=>G6(Y)):null,to:$.to?$.to:null,transactionIndex:$.transactionIndex?k4($.transactionIndex):null,status:$.status?cj[$.status]:null,type:$.type?hj[$.type]||$.type:null};if($.blobGasPrice)Q.blobGasPrice=BigInt($.blobGasPrice);if($.blobGasUsed)Q.blobGasUsed=BigInt($.blobGasUsed);return Q}async function C5($,{hash:J}){let Q=await $.request({method:"eth_getTransactionReceipt",params:[J]},{dedupe:!0});if(!Q)throw new fW({hash:J});return($.chain?.formatters?.transactionReceipt?.format||eN)(Q,"getTransactionReceipt")}u0();l4();b$();$X();mJ();W1();w8();async function $u($,J){let{account:Q,authorizationList:Y,allowFailure:X=!0,blockNumber:G,blockOverrides:W,blockTag:D,stateOverride:U}=J,V=J.contracts,{batchSize:O=J.batchSize??1024,deployless:N=J.deployless??!1}=typeof $.batch?.multicall==="object"?$.batch.multicall:{},M=(()=>{if(J.multicallAddress)return J.multicallAddress;if(N)return null;if($.chain)return u1({blockNumber:G,chain:$.chain,contract:"multicall3"});throw Error("client chain not configured. multicallAddress is required.")})(),H=[[]],w=0,I=0;for(let S=0;S<V.length;S++){let{abi:B,address:Z,args:_,functionName:P}=V[S];try{let x=L4({abi:B,args:_,functionName:P});if(I+=(x.length-2)/2,O>0&&I>O&&H[w].length>0)w++,I=(x.length-2)/2,H[w]=[];H[w]=[...H[w],{allowFailure:!0,callData:x,target:Z}]}catch(x){let h=B1(x,{abi:B,address:Z,args:_,docsPath:"/docs/contract/multicall",functionName:P,sender:Q});if(!X)throw h;H[w]=[...H[w],{allowFailure:!0,callData:"0x",target:Z}]}}let j=await Promise.allSettled(H.map((S)=>d($,p4,"readContract")({...M===null?{code:H5}:{address:M},abi:O0,account:Q,args:[S],authorizationList:Y,blockNumber:G,blockOverrides:W,blockTag:D,functionName:"aggregate3",stateOverride:U}))),L=[];for(let S=0;S<j.length;S++){let B=j[S];if(B.status==="rejected"){if(!X)throw B.reason;for(let _=0;_<H[S].length;_++)L.push({status:"failure",error:B.reason,result:void 0});continue}let Z=B.value;for(let _=0;_<Z.length;_++){let{returnData:P,success:x}=Z[_],{callData:h}=H[S][_],{abi:p,address:b,functionName:Q$,args:s}=V[L.length];try{if(h==="0x")throw new N0;if(!x)throw new lJ({data:P});let K$=Z6({abi:p,args:s,data:P,functionName:Q$});L.push(X?{result:K$,status:"success"}:K$)}catch(K$){let y=B1(K$,{abi:p,address:b,args:s,docsPath:"/docs/contract/multicall",functionName:Q$});if(!X)throw y;L.push({error:y,result:void 0,status:"failure"})}}}if(L.length!==V.length)throw new R("multicall results mismatch");return L}$j();l4();$X();DX();mJ();W1();A$();eW();sJ();CN();t0();async function zD($,J){let{blockNumber:Q,blockTag:Y=$.experimental_blockTag??"latest",blocks:X,returnFullTransactions:G,traceTransfers:W,validation:D}=J;try{let U=[];for(let M of X){let H=M.blockOverrides?EN(M.blockOverrides):void 0,w=M.calls.map((j)=>{let L=j,S=L.account?E$(L.account):void 0,B=L.abi?L4(L):L.data,Z={...L,account:S,data:L.dataSuffix?Z4([B||"0x",L.dataSuffix]):B,from:L.from??S?.address};return X6(Z),F6(Z)}),I=M.stateOverrides?w5(M.stateOverrides):void 0;U.push({blockOverrides:H,calls:w,stateOverrides:I})}let O=(typeof Q==="bigint"?u(Q):void 0)||Y;return(await $.request({method:"eth_simulateV1",params:[{blockStateCalls:U,returnFullTransactions:G,traceTransfers:W,validation:D},O]})).map((M,H)=>({...pN(M),calls:M.calls.map((w,I)=>{let{abi:j,args:L,functionName:S,to:B}=X[H].calls[I],Z=w.error?.data??w.returnData,_=BigInt(w.gasUsed),P=w.logs?.map((b)=>G6(b)),x=w.status==="0x1"?"success":"failure",h=j&&x==="success"&&Z!=="0x"?Z6({abi:j,data:Z,functionName:S}):null,p=(()=>{if(x==="success")return;let b;if(Z==="0x")b=new N0;else if(Z)b=new lJ({data:Z});if(!b)return;return B1(b,{abi:j??[],address:B??"0x",args:L,functionName:S??"<unknown>"})})();return{data:Z,gasUsed:_,logs:P,status:x,...x==="success"?{result:h}:{error:p}}})}))}catch(U){let V=U,O=UX(V,{});if(O instanceof A0)throw V;throw O}}TW();U1();b2();YX();Q6();function b8($,J={}){let{as:Q=typeof $==="string"?"Hex":"Bytes"}=J,Y=r3(Ky($));if(Q==="Bytes")return Y;return n4(Y)}Q6();YX();class rj extends Map{constructor($){super();Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=$}get($){let J=super.get($);if(super.has($)&&J!==void 0)this.delete($),super.set($,J);return J}set($,J){if(super.set($,J),this.maxSize&&this.size>this.maxSize){let Q=this.keys().next().value;if(Q)this.delete(Q)}return this}}var v9$={checksum:new rj(8192)},$z=v9$.checksum;U1();YX();U1();Q6();function Ju($,J={}){let{compressed:Q}=J,{prefix:Y,x:X,y:G}=$;if(Q===!1||typeof X==="bigint"&&typeof G==="bigint"){if(Y!==4)throw new tj({prefix:Y,cause:new Wu});return}if(Q===!0||typeof X==="bigint"&&typeof G>"u"){if(Y!==3&&Y!==2)throw new tj({prefix:Y,cause:new Gu});return}throw new Yu({publicKey:$})}function Qu($){let J=(()=>{if(iW($))return Xu($);if(Hy($))return R9$($);let{prefix:Q,x:Y,y:X}=$;if(typeof Y==="bigint"&&typeof X==="bigint")return{prefix:Q??4,x:Y,y:X};return{prefix:Q,x:Y}})();return Ju(J),J}function R9$($){return Xu(n4($))}function Xu($){if($.length!==132&&$.length!==130&&$.length!==68)throw new Du({publicKey:$});if($.length===130){let Y=BigInt(T4($,0,32)),X=BigInt(T4($,32,64));return{prefix:4,x:Y,y:X}}if($.length===132){let Y=Number(T4($,0,1)),X=BigInt(T4($,1,33)),G=BigInt(T4($,33,65));return{prefix:Y,x:X,y:G}}let J=Number(T4($,0,1)),Q=BigInt(T4($,1,33));return{prefix:J,x:Q}}function aj($,J={}){Ju($);let{prefix:Q,x:Y,y:X}=$,{includePrefix:G=!0}=J;return f4(G?J4(Q,{size:1}):"0x",J4(Y,{size:32}),typeof X==="bigint"?J4(X,{size:32}):"0x")}class Yu extends D${constructor({publicKey:$}){super(`Value \`${GX($)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}}class tj extends D${constructor({prefix:$,cause:J}){super(`Prefix "${$}" is invalid.`,{cause:J});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class Gu extends D${constructor(){super("Prefix must be 2 or 3 for compressed public keys.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}}class Wu extends D${constructor(){super("Prefix must be 4 for uncompressed public keys.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}class Du extends D${constructor({publicKey:$}){super(`Value \`${$}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${R4(z5($))} bytes.`]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}}var T9$=/^0x[a-fA-F0-9]{40}$/;function g8($,J={}){let{strict:Q=!0}=J;if(!T9$.test($))throw new sj({address:$,cause:new Vu});if(Q){if($.toLowerCase()===$)return;if(Jz($)!==$)throw new sj({address:$,cause:new Ou})}}function Jz($){if($z.has($))return $z.get($);g8($,{strict:!1});let J=$.substring(2).toLowerCase(),Q=b8(Vy(J),{as:"Bytes"}),Y=J.split("");for(let G=0;G<40;G+=2){if(Q[G>>1]>>4>=8&&Y[G])Y[G]=Y[G].toUpperCase();if((Q[G>>1]&15)>=8&&Y[G+1])Y[G+1]=Y[G+1].toUpperCase()}let X=`0x${Y.join("")}`;return $z.set($,X),X}function C9$($,J={}){let{checksum:Q=!1}=J;if(g8($),Q)return Jz($);return $}function Ku($,J={}){let Q=b8(`0x${aj($).slice(4)}`).substring(26);return C9$(`0x${Q}`,J)}function Qz($,J={}){let{strict:Q=!0}=J??{};try{return g8($,{strict:Q}),!0}catch{return!1}}class sj extends D${constructor({address:$,cause:J}){super(`Address "${$}" is invalid.`,{cause:J});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class Vu extends D${constructor(){super("Address is not a 20 byte (40 hexadecimal character) value.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class Ou extends D${constructor(){super("Address does not match its checksum counterpart.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}U1();function Gz($){let J=!0,Q="",Y=0,X="",G=!1;for(let W=0;W<$.length;W++){let D=$[W];if(["(",")",","].includes(D))J=!0;if(D==="(")Y++;if(D===")")Y--;if(!J)continue;if(Y===0){if(D===" "&&["event","function","error",""].includes(X))X="";else if(X+=D,D===")"){G=!0;break}continue}if(D===" "){if($[W-1]!==","&&Q!==","&&Q!==",(")Q="",J=!1;continue}X+=D,Q+=D}if(!G)throw new D$("Unable to normalize signature.");return X}function Yz($,J){let Q=typeof $,Y=J.type;switch(Y){case"address":return Qz($,{strict:!1});case"bool":return Q==="boolean";case"function":return Q==="string";case"string":return Q==="string";default:{if(Y==="tuple"&&"components"in J)return Object.values(J.components).every((X,G)=>{return Yz(Object.values($)[G],X)});if(/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(Y))return Q==="number"||Q==="bigint";if(/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(Y))return Q==="string"||$ instanceof Uint8Array;if(/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(Y))return Array.isArray($)&&$.every((X)=>Yz(X,{...J,type:Y.replace(/(\[[0-9]{0,}\])$/,"")}));return!1}}}function ej($,J,Q){for(let Y in $){let X=$[Y],G=J[Y];if(X.type==="tuple"&&G.type==="tuple"&&"components"in X&&"components"in G)return ej(X.components,G.components,Q[Y]);let W=[X.type,G.type];if((()=>{if(W.includes("address")&&W.includes("bytes20"))return!0;if(W.includes("address")&&W.includes("string"))return Qz(Q[Y],{strict:!1});if(W.includes("address")&&W.includes("bytes"))return Qz(Q[Y],{strict:!1});return!1})())return W}return}function Wz($,J={}){let{prepare:Q=!0}=J,Y=(()=>{if(Array.isArray($))return KN($);if(typeof $==="string")return KN($);return $})();return{...Y,...Q?{hash:k5(Y)}:{}}}function MD($,J,Q){let{args:Y=[],prepare:X=!0}=Q??{},G=iW(J,{strict:!1}),W=$.filter((V)=>{if(G){if(V.type==="function"||V.type==="error")return $Z(V)===T4(J,0,4);if(V.type==="event")return k5(V)===J;return!1}return"name"in V&&V.name===J});if(W.length===0)throw new y8({name:J});if(W.length===1)return{...W[0],...X?{hash:k5(W[0])}:{}};let D;for(let V of W){if(!("inputs"in V))continue;if(!Y||Y.length===0){if(!V.inputs||V.inputs.length===0)return{...V,...X?{hash:k5(V)}:{}};continue}if(!V.inputs)continue;if(V.inputs.length===0)continue;if(V.inputs.length!==Y.length)continue;if(Y.every((N,M)=>{let H="inputs"in V&&V.inputs[M];if(!H)return!1;return Yz(N,H)})){if(D&&"inputs"in D&&D.inputs){let N=ej(V.inputs,D.inputs,Y);if(N)throw new Nu({abiItem:V,type:N[0]},{abiItem:D,type:N[1]})}D=V}}let U=(()=>{if(D)return D;let[V,...O]=W;return{...V,overloads:O}})();if(!U)throw new y8({name:J});return{...U,...X?{hash:k5(U)}:{}}}function $Z(...$){let J=(()=>{if(Array.isArray($[0])){let[Q,Y]=$;return MD(Q,Y)}return $[0]})();return T4(k5(J),0,4)}function x9$(...$){let J=(()=>{if(Array.isArray($[0])){let[Y,X]=$;return MD(Y,X)}return $[0]})(),Q=(()=>{if(typeof J==="string")return J;return q8(J)})();return Gz(Q)}function k5(...$){let J=(()=>{if(Array.isArray($[0])){let[Q,Y]=$;return MD(Q,Y)}return $[0]})();if(typeof J!=="string"&&"hash"in J&&J.hash)return J.hash;return b8(M5(x9$(J)))}class Nu extends D${constructor($,J){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${$.type}\` in \`${Gz(q8($.abiItem))}\`, and`,`\`${J.type}\` in \`${Gz(q8(J.abiItem))}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.AmbiguityError"})}}class y8 extends D${constructor({name:$,data:J,type:Q="item"}){let Y=(()=>{if($)return` with name "${$}"`;if(J)return` with data "${J}"`;return""})();super(`ABI ${Q}${Y} not found.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}}TW();YX();U1();Q6();YX();U1();Q6();var Mu=/^(.*)\[([0-9]*)\]$/,Hu=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Dz=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,Gx$=2n**(8n-1n)-1n,Wx$=2n**(16n-1n)-1n,Dx$=2n**(24n-1n)-1n,Ux$=2n**(32n-1n)-1n,Kx$=2n**(40n-1n)-1n,Vx$=2n**(48n-1n)-1n,Ox$=2n**(56n-1n)-1n,Nx$=2n**(64n-1n)-1n,zx$=2n**(72n-1n)-1n,Mx$=2n**(80n-1n)-1n,Hx$=2n**(88n-1n)-1n,qx$=2n**(96n-1n)-1n,wx$=2n**(104n-1n)-1n,Ax$=2n**(112n-1n)-1n,Ix$=2n**(120n-1n)-1n,Lx$=2n**(128n-1n)-1n,Bx$=2n**(136n-1n)-1n,jx$=2n**(144n-1n)-1n,Zx$=2n**(152n-1n)-1n,Fx$=2n**(160n-1n)-1n,_x$=2n**(168n-1n)-1n,Sx$=2n**(176n-1n)-1n,Ex$=2n**(184n-1n)-1n,vx$=2n**(192n-1n)-1n,Px$=2n**(200n-1n)-1n,Rx$=2n**(208n-1n)-1n,Tx$=2n**(216n-1n)-1n,Cx$=2n**(224n-1n)-1n,kx$=2n**(232n-1n)-1n,xx$=2n**(240n-1n)-1n,fx$=2n**(248n-1n)-1n,bx$=2n**(256n-1n)-1n,gx$=-(2n**(8n-1n)),yx$=-(2n**(16n-1n)),hx$=-(2n**(24n-1n)),ux$=-(2n**(32n-1n)),mx$=-(2n**(40n-1n)),lx$=-(2n**(48n-1n)),nx$=-(2n**(56n-1n)),ix$=-(2n**(64n-1n)),dx$=-(2n**(72n-1n)),px$=-(2n**(80n-1n)),cx$=-(2n**(88n-1n)),ox$=-(2n**(96n-1n)),rx$=-(2n**(104n-1n)),tx$=-(2n**(112n-1n)),ax$=-(2n**(120n-1n)),sx$=-(2n**(128n-1n)),ex$=-(2n**(136n-1n)),$f$=-(2n**(144n-1n)),Jf$=-(2n**(152n-1n)),Qf$=-(2n**(160n-1n)),Xf$=-(2n**(168n-1n)),Yf$=-(2n**(176n-1n)),Gf$=-(2n**(184n-1n)),Wf$=-(2n**(192n-1n)),Df$=-(2n**(200n-1n)),Uf$=-(2n**(208n-1n)),Kf$=-(2n**(216n-1n)),Vf$=-(2n**(224n-1n)),Of$=-(2n**(232n-1n)),Nf$=-(2n**(240n-1n)),zf$=-(2n**(248n-1n)),Mf$=-(2n**(256n-1n)),Hf$=2n**8n-1n,qf$=2n**16n-1n,wf$=2n**24n-1n,Af$=2n**32n-1n,If$=2n**40n-1n,Lf$=2n**48n-1n,Bf$=2n**56n-1n,jf$=2n**64n-1n,Zf$=2n**72n-1n,Ff$=2n**80n-1n,_f$=2n**88n-1n,Sf$=2n**96n-1n,Ef$=2n**104n-1n,vf$=2n**112n-1n,Pf$=2n**120n-1n,Rf$=2n**128n-1n,Tf$=2n**136n-1n,Cf$=2n**144n-1n,kf$=2n**152n-1n,xf$=2n**160n-1n,ff$=2n**168n-1n,bf$=2n**176n-1n,gf$=2n**184n-1n,yf$=2n**192n-1n,hf$=2n**200n-1n,uf$=2n**208n-1n,mf$=2n**216n-1n,lf$=2n**224n-1n,nf$=2n**232n-1n,if$=2n**240n-1n,df$=2n**248n-1n,JZ=2n**256n-1n;function h8($,J,Q){let{checksumAddress:Y,staticPosition:X}=Q,G=YZ(J.type);if(G){let[W,D]=G;return b9$($,{...J,type:D},{checksumAddress:Y,length:W,staticPosition:X})}if(J.type==="tuple")return u9$($,J,{checksumAddress:Y,staticPosition:X});if(J.type==="address")return f9$($,{checksum:Y});if(J.type==="bool")return g9$($);if(J.type.startsWith("bytes"))return y9$($,J,{staticPosition:X});if(J.type.startsWith("uint")||J.type.startsWith("int"))return h9$($,J);if(J.type==="string")return m9$($,{staticPosition:X});throw new qD(J.type)}var wu=32,QZ=32;function f9$($,J={}){let{checksum:Q=!1}=J,Y=$.readBytes(32);return[((G)=>Q?Jz(G):G)(n4(Oy(Y,-20))),32]}function b9$($,J,Q){let{checksumAddress:Y,length:X,staticPosition:G}=Q;if(!X){let U=o0($.readBytes(QZ)),V=G+U,O=V+wu;$.setPosition(V);let N=o0($.readBytes(wu)),M=HD(J),H=0,w=[];for(let I=0;I<N;++I){$.setPosition(O+(M?I*32:H));let[j,L]=h8($,J,{checksumAddress:Y,staticPosition:O});H+=L,w.push(j)}return $.setPosition(G+32),[w,32]}if(HD(J)){let U=o0($.readBytes(QZ)),V=G+U,O=[];for(let N=0;N<X;++N){$.setPosition(V+N*32);let[M]=h8($,J,{checksumAddress:Y,staticPosition:V});O.push(M)}return $.setPosition(G+32),[O,32]}let W=0,D=[];for(let U=0;U<X;++U){let[V,O]=h8($,J,{checksumAddress:Y,staticPosition:G+W});W+=O,D.push(V)}return[D,W]}function g9$($){return[zy($.readBytes(32),{size:32}),32]}function y9$($,J,{staticPosition:Q}){let[Y,X]=J.type.split("bytes");if(!X){let W=o0($.readBytes(32));$.setPosition(Q+W);let D=o0($.readBytes(32));if(D===0)return $.setPosition(Q+32),["0x",32];let U=$.readBytes(D);return $.setPosition(Q+32),[n4(U),32]}return[n4($.readBytes(Number.parseInt(X,10),32)),32]}function h9$($,J){let Q=J.type.startsWith("int"),Y=Number.parseInt(J.type.split("int")[1]||"256",10),X=$.readBytes(32);return[Y>48?Ny(X,{signed:Q}):o0(X,{signed:Q}),32]}function u9$($,J,Q){let{checksumAddress:Y,staticPosition:X}=Q,G=J.components.length===0||J.components.some(({name:U})=>!U),W=G?[]:{},D=0;if(HD(J)){let U=o0($.readBytes(QZ)),V=X+U;for(let O=0;O<J.components.length;++O){let N=J.components[O];$.setPosition(V+D);let[M,H]=h8($,N,{checksumAddress:Y,staticPosition:V});D+=H,W[G?O:N?.name]=M}return $.setPosition(X+32),[W,32]}for(let U=0;U<J.components.length;++U){let V=J.components[U],[O,N]=h8($,V,{checksumAddress:Y,staticPosition:X});W[G?U:V?.name]=O,D+=N}return[W,D]}function m9$($,{staticPosition:J}){let Q=o0($.readBytes(32)),Y=J+Q;$.setPosition(Y);let X=o0($.readBytes(32));if(X===0)return $.setPosition(J+32),["",32];let G=$.readBytes(X,32),W=My(rB(G));return $.setPosition(J+32),[W,32]}function Au({checksumAddress:$,parameters:J,values:Q}){let Y=[];for(let X=0;X<J.length;X++)Y.push(XZ({checksumAddress:$,parameter:J[X],value:Q[X]}));return Y}function XZ({checksumAddress:$=!1,parameter:J,value:Q}){let Y=J,X=YZ(Y.type);if(X){let[G,W]=X;return n9$(Q,{checksumAddress:$,length:G,parameter:{...Y,type:W}})}if(Y.type==="tuple")return o9$(Q,{checksumAddress:$,parameter:Y});if(Y.type==="address")return l9$(Q,{checksum:$});if(Y.type==="bool")return d9$(Q);if(Y.type.startsWith("uint")||Y.type.startsWith("int")){let G=Y.type.startsWith("int"),[,,W="256"]=Dz.exec(Y.type)??[];return p9$(Q,{signed:G,size:Number(W)})}if(Y.type.startsWith("bytes"))return i9$(Q,{type:Y.type});if(Y.type==="string")return c9$(Q);throw new qD(Y.type)}function Uz($){let J=0;for(let G=0;G<$.length;G++){let{dynamic:W,encoded:D}=$[G];if(W)J+=32;else J+=R4(D)}let Q=[],Y=[],X=0;for(let G=0;G<$.length;G++){let{dynamic:W,encoded:D}=$[G];if(W)Q.push(J4(J+X,{size:32})),Y.push(D),X+=R4(D);else Q.push(D)}return f4(...Q,...Y)}function l9$($,J){let{checksum:Q=!1}=J;return g8($,{strict:Q}),{dynamic:!1,encoded:tJ($.toLowerCase())}}function n9$($,J){let{checksumAddress:Q,length:Y,parameter:X}=J,G=Y===null;if(!Array.isArray($))throw new WZ($);if(!G&&$.length!==Y)throw new GZ({expectedLength:Y,givenLength:$.length,type:`${X.type}[${Y}]`});let W=!1,D=[];for(let U=0;U<$.length;U++){let V=XZ({checksumAddress:Q,parameter:X,value:$[U]});if(V.dynamic)W=!0;D.push(V)}if(G||W){let U=Uz(D);if(G){let V=J4(D.length,{size:32});return{dynamic:!0,encoded:D.length>0?f4(V,U):V}}if(W)return{dynamic:!0,encoded:U}}return{dynamic:!1,encoded:f4(...D.map(({encoded:U})=>U))}}function i9$($,{type:J}){let[,Q]=J.split("bytes"),Y=R4($);if(!Q){let X=$;if(Y%32!==0)X=r0(X,Math.ceil(($.length-2)/2/32)*32);return{dynamic:!0,encoded:f4(tJ(J4(Y,{size:32})),X)}}if(Y!==Number.parseInt(Q,10))throw new Kz({expectedSize:Number.parseInt(Q,10),value:$});return{dynamic:!1,encoded:r0($)}}function d9$($){if(typeof $!=="boolean")throw new D$(`Invalid boolean value: "${$}" (type: ${typeof $}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:tJ(_N($))}}function p9$($,{signed:J,size:Q}){if(typeof Q==="number"){let Y=2n**(BigInt(Q)-(J?1n:0n))-1n,X=J?-Y-1n:0n;if($>Y||$<X)throw new SN({max:Y.toString(),min:X.toString(),signed:J,size:Q/8,value:$.toString()})}return{dynamic:!1,encoded:J4($,{size:32,signed:J})}}function c9$($){let J=M5($),Q=Math.ceil(R4(J)/32),Y=[];for(let X=0;X<Q;X++)Y.push(r0(T4(J,X*32,(X+1)*32)));return{dynamic:!0,encoded:f4(r0(J4(R4(J),{size:32})),...Y)}}function o9$($,J){let{checksumAddress:Q,parameter:Y}=J,X=!1,G=[];for(let W=0;W<Y.components.length;W++){let D=Y.components[W],U=Array.isArray($)?W:D.name,V=XZ({checksumAddress:Q,parameter:D,value:$[U]});if(G.push(V),V.dynamic)X=!0}return{dynamic:X,encoded:X?Uz(G):f4(...G.map(({encoded:W})=>W))}}function YZ($){let J=$.match(/^(.*)\[(\d+)?\]$/);return J?[J[2]?Number(J[2]):null,J[1]]:void 0}function HD($){let{type:J}=$;if(J==="string")return!0;if(J==="bytes")return!0;if(J.endsWith("[]"))return!0;if(J==="tuple")return $.components?.some(HD);let Q=YZ($.type);if(Q&&HD({...$,type:Q[1]}))return!0;return!1}U1();var t9$={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new Lu({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition($){if($<0||$>this.bytes.length-1)throw new Iu({length:this.bytes.length,position:$})},decrementPosition($){if($<0)throw new DZ({offset:$});let J=this.position-$;this.assertPosition(J),this.position=J},getReadCount($){return this.positionReadCount.get($||this.position)||0},incrementPosition($){if($<0)throw new DZ({offset:$});let J=this.position+$;this.assertPosition(J),this.position=J},inspectByte($){let J=$??this.position;return this.assertPosition(J),this.bytes[J]},inspectBytes($,J){let Q=J??this.position;return this.assertPosition(Q+$-1),this.bytes.subarray(Q,Q+$)},inspectUint8($){let J=$??this.position;return this.assertPosition(J),this.bytes[J]},inspectUint16($){let J=$??this.position;return this.assertPosition(J+1),this.dataView.getUint16(J)},inspectUint24($){let J=$??this.position;return this.assertPosition(J+2),(this.dataView.getUint16(J)<<8)+this.dataView.getUint8(J+2)},inspectUint32($){let J=$??this.position;return this.assertPosition(J+3),this.dataView.getUint32(J)},pushByte($){this.assertPosition(this.position),this.bytes[this.position]=$,this.position++},pushBytes($){this.assertPosition(this.position+$.length-1),this.bytes.set($,this.position),this.position+=$.length},pushUint8($){this.assertPosition(this.position),this.bytes[this.position]=$,this.position++},pushUint16($){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,$),this.position+=2},pushUint24($){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,$>>8),this.dataView.setUint8(this.position+2,$&255),this.position+=3},pushUint32($){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,$),this.position+=4},readByte(){this.assertReadLimit(),this._touch();let $=this.inspectByte();return this.position++,$},readBytes($,J){this.assertReadLimit(),this._touch();let Q=this.inspectBytes($);return this.position+=J??$,Q},readUint8(){this.assertReadLimit(),this._touch();let $=this.inspectUint8();return this.position+=1,$},readUint16(){this.assertReadLimit(),this._touch();let $=this.inspectUint16();return this.position+=2,$},readUint24(){this.assertReadLimit(),this._touch();let $=this.inspectUint24();return this.position+=3,$},readUint32(){this.assertReadLimit(),this._touch();let $=this.inspectUint32();return this.position+=4,$},get remaining(){return this.bytes.length-this.position},setPosition($){let J=this.position;return this.assertPosition($),this.position=$,()=>this.position=J},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;let $=this.getReadCount();if(this.positionReadCount.set(this.position,$+1),$>0)this.recursiveReadCount++}};function Vz($,{recursiveReadLimit:J=8192}={}){let Q=Object.create(t9$);return Q.bytes=$,Q.dataView=new DataView($.buffer,$.byteOffset,$.byteLength),Q.positionReadCount=new Map,Q.recursiveReadLimit=J,Q}class DZ extends D${constructor({offset:$}){super(`Offset \`${$}\` cannot be negative.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.NegativeOffsetError"})}}class Iu extends D${constructor({length:$,position:J}){super(`Position \`${J}\` is out of bounds (\`0 < position < ${$}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.PositionOutOfBoundsError"})}}class Lu extends D${constructor({count:$,limit:J}){super(`Recursive read limit of \`${J}\` exceeded (recursive read count: \`${$}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.RecursiveReadLimitExceededError"})}}function x5($,J,Q={}){let{as:Y="Array",checksumAddress:X=!1}=Q,G=typeof J==="string"?N5(J):J,W=Vz(G);if(n1(G)===0&&$.length>0)throw new Zu;if(n1(G)&&n1(G)<32)throw new ju({data:typeof J==="string"?J:n4(J),parameters:$,size:n1(G)});let D=0,U=Y==="Array"?[]:{};for(let V=0;V<$.length;++V){let O=$[V];W.setPosition(D);let[N,M]=h8(W,O,{checksumAddress:X,staticPosition:0});if(D+=M,Y==="Array")U.push(N);else U[O.name??V]=N}return U}function wX($,J,Q){let{checksumAddress:Y=!1}=Q??{};if($.length!==J.length)throw new KZ({expectedLength:$.length,givenLength:J.length});let X=Au({checksumAddress:Y,parameters:$,values:J}),G=Uz(X);if(G.length===0)return"0x";return G}function UZ($,J){if($.length!==J.length)throw new KZ({expectedLength:$.length,givenLength:J.length});let Q=[];for(let Y=0;Y<$.length;Y++){let X=$[Y],G=J[Y];Q.push(UZ.encode(X,G))}return f4(...Q)}(function($){function J(Q,Y,X=!1){if(Q==="address"){let U=Y;return g8(U),tJ(U.toLowerCase(),X?32:0)}if(Q==="string")return M5(Y);if(Q==="bytes")return Y;if(Q==="bool")return tJ(_N(Y),X?32:1);let G=Q.match(Dz);if(G){let[U,V,O="256"]=G,N=Number.parseInt(O,10)/8;return J4(Y,{size:X?32:N,signed:V==="int"})}let W=Q.match(Hu);if(W){let[U,V]=W;if(Number.parseInt(V,10)!==(Y.length-2)/2)throw new Kz({expectedSize:Number.parseInt(V,10),value:Y});return r0(Y,X?32:0)}let D=Q.match(Mu);if(D&&Array.isArray(Y)){let[U,V]=D,O=[];for(let N=0;N<Y.length;N++)O.push(J(V,Y[N],!0));if(O.length===0)return"0x";return f4(...O)}throw new qD(Q)}$.encode=J})(UZ||(UZ={}));function AD($){if(Array.isArray($)&&typeof $[0]==="string")return VN($);if(typeof $==="string")return VN($);return $}class ju extends D${constructor({data:$,parameters:J,size:Q}){super(`Data size of ${Q} bytes is too small for given parameters.`,{metaMessages:[`Params: (${hJ(J)})`,`Data: ${$} (${Q} bytes)`]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.DataSizeTooSmallError"})}}class Zu extends D${constructor(){super('Cannot decode zero data ("0x") with ABI parameters.');Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ZeroDataError"})}}class GZ extends D${constructor({expectedLength:$,givenLength:J,type:Q}){super(`Array length mismatch for type \`${Q}\`. Expected: \`${$}\`. Given: \`${J}\`.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ArrayLengthMismatchError"})}}class Kz extends D${constructor({expectedSize:$,value:J}){super(`Size of bytes "${J}" (bytes${R4(J)}) does not match expected size (bytes${$}).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class KZ extends D${constructor({expectedLength:$,givenLength:J}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${$}`,`Given length (values): ${J}`].join(`
137
+ `}class Q2{constructor($=ax.stdin,J=ax.stdout){this._stdin=$,this._stdout=J,this._readBuffer=new J2,this._started=!1,this._ondata=(Q)=>{this._readBuffer.append(Q),this.processReadBuffer()},this._onerror=(Q)=>{this.onerror?.(Q)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let $=this._readBuffer.readMessage();if($===null)break;this.onmessage?.($)}catch($){this.onerror?.($)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send($){return new Promise((J)=>{let Q=tx($);if(this._stdout.write(Q))J();else this._stdout.once("drain",J)})}}var S3={name:"@0xmonaco/mcp-server",version:"0.8.7",type:"module",repository:{type:"git",url:"https://github.com/Monaco-Research/monaco-sdk.git",directory:"packages/mcp-server"},description:"MCP server for the Monaco SDK",engines:{node:">=18"},bin:"./dist/bin.js",files:["dist"],scripts:{build:"bun build src/bin.ts --outdir dist --target node --format esm --minify",dev:"bun --watch src/bin.ts",start:"bun dist/bin.js",clean:"rm -rf dist",lint:"biome lint .",test:"bun test"},author:"@codebycarson",dependencies:{"@0xmonaco/core":"0.8.7","@0xmonaco/types":"0.8.7","@modelcontextprotocol/sdk":"^1.26.0","node-fetch":"^3.3.2",viem:"^2.45.2",ws:"^8.19.0",zod:"^4.0.0"},devDependencies:{"@types/bun":"latest","@types/ws":"^8.18.1"}};var bQ$={mainnet:"https://evm-rpc.sei-apis.com",development:"https://evm-rpc-testnet.sei-apis.com",staging:"https://evm-rpc-testnet.sei-apis.com",local:"http://localhost:8545"};function iQ($=process.env){let J=$.MONACO_PRIVATE_KEY||null;if(J&&!J.startsWith("0x"))throw Error("MONACO_PRIVATE_KEY must start with '0x'.");let Q=$.MONACO_CLIENT_ID||null;if(J&&!Q)throw Error("MONACO_CLIENT_ID is required when MONACO_PRIVATE_KEY is set.");let Y=["mainnet","development","staging","local"],X=$.MONACO_NETWORK||"mainnet";if(!Y.includes(X))throw Error(`MONACO_NETWORK must be one of: ${Y.join(", ")}. Got: "${X}".`);let G=X,W=$.MONACO_RPC_URL||bQ$[G];return{privateKey:J,clientId:Q,network:G,seiRpcUrl:W}}function gQ$($){return $.replace(/_([a-z])/g,(J,Q)=>Q.toUpperCase())}function ZY($){if($===null||$===void 0)return $;if(typeof $!=="object")return $;if(Array.isArray($))return $.map((Q)=>ZY(Q));let J={};for(let[Q,Y]of Object.entries($))J[gQ$(Q)]=typeof Y==="object"&&Y!==null?ZY(Y):Y;return J}var HW=[0.0001,0.001,0.01,0.1,1,10,100,1000,1e4];var yQ$=1e4,hQ$=15000,uQ$=30000,mQ$=["created","activated","cancelled","parent_cancelled","triggered","failed","oco_cancelled"],lQ$=["STOP_LOSS","TAKE_PROFIT"],nQ$=["MARK_PRICE"],iQ$=["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],dQ$=["POSITION","PARENT_ORDER"];function sx($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function U8($,J){let Q=$[J];if(typeof Q!=="string"||Q.length===0)throw Error(`Invalid conditional order event: ${J} must be a non-empty string`);return Q}function V0($,J){let Q=$[J];if(Q===void 0||Q===null)return;if(typeof Q!=="string")throw Error(`Invalid conditional order event: ${J} must be a string`);return Q}function pQ$($,J){let Q=$[J];if(typeof Q!=="boolean")throw Error(`Invalid conditional order event: ${J} must be a boolean`);return Q}function cQ$($,J){let Q=$[J];if(Q===void 0||Q===null)return;if(typeof Q!=="number"||!Number.isFinite(Q))throw Error(`Invalid conditional order event: ${J} must be a finite number`);return Q}function dQ($,J,Q){let Y=U8($,J);if(!Q.includes(Y))throw Error(`Invalid conditional order event: ${J} must be one of ${Q.join(", ")}`);return Y}function ex($,J,Q){let Y=$[J];if(Y===void 0||Y===null)return;if(typeof Y!=="string"||!Q.includes(Y))throw Error(`Invalid conditional order event: ${J} must be one of ${Q.join(", ")}`);return Y}function oQ$($){if(!sx($))throw Error("Invalid conditional order event: payload must be an object");if(!sx($.data))throw Error("Invalid conditional order event: data must be an object");let J=ZY($.data);return{eventType:dQ($,"event_type",["conditional_order_update"]),userId:U8($,"user_id"),data:{conditionalOrderId:U8(J,"conditionalOrderId"),tradingPairId:U8(J,"tradingPairId"),marginAccountId:U8(J,"marginAccountId"),positionId:V0(J,"positionId"),parentOrderId:V0(J,"parentOrderId"),associationType:ex(J,"associationType",dQ$),linkedGroupId:V0(J,"linkedGroupId"),conditionType:dQ(J,"conditionType",lQ$),triggerSource:dQ(J,"triggerSource",nQ$),triggerPrice:U8(J,"triggerPrice"),side:dQ(J,"side",["BUY","SELL"]),positionSide:dQ(J,"positionSide",["LONG","SHORT","NONE"]),orderType:dQ(J,"orderType",["LIMIT","MARKET"]),limitPrice:V0(J,"limitPrice"),quantity:V0(J,"quantity"),slippageToleranceBps:cQ$(J,"slippageToleranceBps"),reduceOnly:pQ$(J,"reduceOnly"),timeInForce:ex(J,"timeInForce",["GTC","IOC"]),state:dQ(J,"state",iQ$),triggeredOrderId:V0(J,"triggeredOrderId"),triggeredAt:V0(J,"triggeredAt"),activatedAt:V0(J,"activatedAt"),cancelledAt:V0(J,"cancelledAt"),expiresAt:V0(J,"expiresAt"),failureReason:V0(J,"failureReason"),reason:dQ(J,"reason",mQ$),updatedAt:U8(J,"updatedAt")}}}function X2($,J={}){let Q=null,Y=J.token,X=0,G=null,W=null,D=J.autoReconnect??!0,U=J.maxReconnectAttempts??5,V=new Map,O=()=>{if(!Q)return"disconnected";switch(Q.readyState){case WebSocket.CONNECTING:return"connecting";case WebSocket.OPEN:return"connected";default:return"disconnected"}},N=()=>{let y=new URL($);if(Y)y.searchParams.set("token",Y);return y.toString()},M=()=>{if(W)clearInterval(W),W=null},H=()=>{M(),W=setInterval(()=>{if(Q?.readyState===WebSocket.OPEN)Q.send(JSON.stringify({type:"Ping"}))},hQ$)},w=()=>{if(G)clearTimeout(G),G=null},I=()=>{if(!D||X>=U){console.error("WebSocket: Max reconnect attempts reached");return}X++;let y=Math.min(1000*2**X,uQ$);G=setTimeout(()=>{B().catch((T)=>{console.warn("WebSocket: Failed to reconnect:",T)})},y)},j=(y)=>{if(Q?.readyState===WebSocket.OPEN)Q.send(JSON.stringify(y))},L=()=>{let y=Array.from(V.keys());if(y.length>0)j({type:"Subscribe",channels:y})},S=(y)=>{if(y.type!=="Event"||!y.channel)return;for(let[T,m]of V)if(y.channel===T||y.channel.startsWith(`${T}:`))for(let c of m)c(y.data)},B=()=>{return new Promise((y,T)=>{if(Q?.readyState===WebSocket.CONNECTING||Q?.readyState===WebSocket.OPEN){y();return}try{let m=new WebSocket(N());Q=m;let c=setTimeout(()=>{if(Q!==m){y();return}if(m.readyState===WebSocket.CONNECTING)m.close(1000,"Connection timeout"),T(Error("WebSocket connection timeout"))},yQ$);m.onopen=()=>{if(clearTimeout(c),Q!==m){y();return}X=0,H(),L(),J.onStatusChange?.("connected"),y()},m.onmessage=(g)=>{if(Q!==m)return;try{let t=JSON.parse(g.data);if(t.type==="Pong")return;S(t)}catch(t){console.warn("WebSocket: Failed to parse message",t)}},m.onclose=(g)=>{if(clearTimeout(c),Q!==m){y();return}if(Q=null,M(),J.onStatusChange?.("disconnected"),D&&g.code!==1000)I()},m.onerror=()=>clearTimeout(c)}catch(m){J.onStatusChange?.("disconnected"),T(m)}})},Z=()=>{D=!1,w(),M(),V.clear(),Q?.close(1000,"Client disconnect"),Q=null,J.onStatusChange?.("disconnected")},_=(y,T)=>{let m=!V.has(y);if(!V.has(y))V.set(y,new Set);if(V.get(y)?.add(T),m&&Q?.readyState===WebSocket.OPEN)j({type:"Subscribe",channels:[y]});return()=>{let c=V.get(y);if(c){if(c.delete(T),c.size===0){if(V.delete(y),Q?.readyState===WebSocket.OPEN)j({type:"Unsubscribe",channels:[y]})}}}};return{connect:B,disconnect:Z,isConnected:()=>Q?.readyState===WebSocket.OPEN,getStatus:O,setToken:(y)=>{Y=y||void 0,w();let T=Q;if(T?.readyState===WebSocket.OPEN||T?.readyState===WebSocket.CONNECTING||T?.readyState===WebSocket.CLOSING)T.close(1000,y?"Token updated, reconnecting.":"Token cleared."),Q=null;if(!y)return;B().catch((m)=>{console.warn("WebSocket: Failed to reconnect after token update:",m)})},orders:(y,T,m)=>{let c=`orders:${y}:${T}`;return _(c,(g)=>{try{let t=g,V$={orderId:t.order_id,eventType:t.event_type,timestamp:t.timestamp,data:ZY(t.data)};m(V$)}catch(t){console.error("WebSocket: Error processing order event",t)}})},orderbook:(y,T,m,c,g)=>{if(!y||!T||m===void 0||!c)throw Error(`orderbook subscription requires all params: tradingPairId="${y}", tradingMode="${T}", magnitude=${m} (valid: ${HW.join(", ")}), quotationMode="${c}" (valid: "BASE", "QUOTE")`);if(!HW.includes(m))throw Error(`Invalid magnitude: ${m}. Must be one of: ${HW.join(", ")}`);let t=`orderbook:${y}:${T}:${m}:${c.toLowerCase()}`;return _(t,(V$)=>{try{let k$=V$,T$=k$.data,A6={tradingPairId:k$.symbol,tradingMode:k$.trading_mode,bids:(T$?.bids||[]).map(($4)=>({price:$4.price,quantity:$4.quantity,orderCount:$4.order_count||0})),asks:(T$?.asks||[]).map(($4)=>({price:$4.price,quantity:$4.quantity,orderCount:$4.order_count||0})),bestBid:T$?.best_bid,bestAsk:T$?.best_ask,bidVolume:T$?.bid_volume||void 0,askVolume:T$?.ask_volume||void 0,priceChange:T$?.price_change?{side:T$.price_change.side,oldPrice:T$.price_change.old_price,newPrice:T$.price_change.new_price,levelRemoved:T$.price_change.level_removed||!1,levelAdded:T$.price_change.level_added||!1}:void 0,baseDecimals:k$.base_decimals||0,quoteDecimals:k$.quote_decimals||0,timestamp:k$.timestamp||new Date().toISOString(),sequence:k$.sequence_number||0};g(A6)}catch(k$){console.error("WebSocket: Error processing orderbook event",k$)}})},ohlcv:(y,T,m,c)=>{let g=`ohlcv:${y}:${T}:${m}`;return _(g,(t)=>{try{let V$=t,k$=V$.data,T$={tradingPairId:V$.symbol,tradingMode:V$.trading_mode,interval:V$.interval,candlestick:{T:k$.period_start||0,t:k$.period_end||0,o:k$.open||"0",h:k$.high||"0",l:k$.low||"0",c:k$.close||"0",v:k$.volume||"0",s:V$.symbol,i:V$.interval,n:k$.trades_count||0}};c(T$)}catch(V$){console.error("WebSocket: Error processing OHLCV event",V$)}})},trades:(y,T)=>{let m=`trades:${y}`;return _(m,(c)=>{try{let g=c,t=g.data,V$={eventType:"trade",tradingPairId:g.trading_pair_id,tradingMode:g.trading_mode.toUpperCase(),data:{tradeId:t.trade_id,price:t.price,quantity:t.quantity,makerSide:t.maker_side.toUpperCase(),executedAt:t.executed_at}};T(V$)}catch(g){console.error("WebSocket: Error processing trade event",g)}})},movements:(y)=>{return _("movements",(m)=>{try{let c=m,g=c.data,t={eventType:"movement",userId:c.user_id,data:{id:g.id,entryType:g.entry_type,transactionType:g.transaction_type,tokenAddress:g.token_address,amount:String(g.amount),amountRaw:g.amount_raw,balanceBefore:g.balance_before!=null?String(g.balance_before):void 0,balanceAfter:g.balance_after!=null?String(g.balance_after):void 0,lockedBefore:g.locked_before!=null?String(g.locked_before):void 0,lockedAfter:g.locked_after!=null?String(g.locked_after):void 0,referenceId:g.reference_id,referenceType:g.reference_type,description:g.description,txHash:g.tx_hash,createdAt:g.created_at,decimals:g.decimals}};y(t)}catch(c){console.error("WebSocket: Error processing movement event",c)}})},userOrders:(y)=>{return _("orders",(m)=>{try{let c=m,g={orderId:c.order_id,eventType:c.event_type,timestamp:c.timestamp,data:ZY(c.data)};y(g)}catch(c){console.error("WebSocket: Error processing user order event",c)}})},balances:(y)=>{return _("balances",(m)=>{try{let c=m,g=c.data,t={eventType:"balance_update",userId:c.user_id,data:{tokenAddress:g.token_address,tokenSymbol:g.token_symbol,available:g.available,availableRaw:g.available_raw,locked:g.locked,lockedRaw:g.locked_raw,total:g.total,totalRaw:g.total_raw,reason:g.reason,referenceId:g.reference_id,updatedAt:g.updated_at}};y(t)}catch(c){console.error("WebSocket: Error processing balance event",c)}})},conditionalOrders:(y,T)=>{if(!y)throw Error("conditionalOrders subscription requires a handler");if(T!==void 0&&T.length===0)throw Error("conditionalOrders tradingPairId cannot be empty");let m=T?`conditional_orders:${T}`:"conditional_orders";return _(m,(c)=>{try{y(oQ$(c))}catch(g){console.error("WebSocket: Error processing conditional order event",g)}})}}}var pQ=P6(v3(),1),Nb=["token","accessToken","access_token","refreshToken","refresh_token","authToken","auth_token","bearerToken","bearer_token","jwtToken","jwt_token","apiKey","api_key","apikey","clientSecret","client_secret","clientId","client_id","secret","password","authorization","bearer","auth","credentials","credential","email","phone","phoneNumber","phone_number","ssn","socialSecurity","social_security","address","passport","passportNumber","passport_number","driversLicense","drivers_license","cardNumber","card_number","creditCard","credit_card","cvv","pin","signature","privateKey","private_key","publicKey","public_key","mnemonic","seed","salt","hash","certificate","cert","fingerprint","cookie","session","sessionId","session_id","sessionToken","session_token","ipAddress","ip_address","deviceId","device_id","userId","user_id","accountId","account_id"];function FY($,J=5,Q=0){if(Q>=J)return"[Max depth reached]";if($===null||$===void 0)return $;if(Array.isArray($)){let X=$.slice(0,10).map((G)=>FY(G,J,Q+1));if($.length>10)X.push(`[... ${$.length-10} more items]`);return X}if(typeof $==="object"){let Y={};for(let[X,G]of Object.entries($)){let W=X.toLowerCase();if(Nb.some((U)=>W.includes(U.toLowerCase())))Y[X]="[REDACTED]";else if(typeof G==="string"&&G.length>500)Y[X]=`${G.substring(0,500)}... [truncated]`;else Y[X]=FY(G,J,Q+1)}return Y}if(typeof $==="string"){if($.length>1000)return`${$.substring(0,1000)}... [truncated]`;return $}return $}class _Y extends Error{cause;suggestion;retryable=!1;timestamp;constructor($,J){super($);if(this.name=this.constructor.name,this.timestamp=Date.now(),J?.cause)this.cause=J.cause;if(J?.suggestion)this.suggestion=J.suggestion;if(J?.retryable!==void 0)this.retryable=J.retryable}toJSON(){return{name:this.name,code:this.code,message:this.message,suggestion:this.suggestion,retryable:this.retryable,timestamp:this.timestamp,cause:this.cause instanceof Error?this.cause.message:this.cause}}}class P4 extends _Y{code="INVALID_CONFIG";field;value;constructor($,J,Q,Y){let X=J?`Check the '${J}' configuration parameter. ${KX$(J)}`:"Review your SDK configuration and ensure all required fields are provided correctly.";super($,{cause:Y,suggestion:X,retryable:!1});this.field=J,this.value=Q}toJSON(){let $;if(this.field){let J=this.field.toLowerCase();if(Nb.some((Y)=>J.includes(Y.toLowerCase())))$="[REDACTED]";else $=FY(this.value)}else $=FY(this.value);return{...super.toJSON(),field:this.field,value:$}}}function KX$($){switch($.toLowerCase()){case"walletclient":return"Ensure you're creating the wallet client with a valid account and chain configuration.";case"seirpcurl":return"Use 'https://evm-rpc-testnet.sei-apis.com' for testnet or 'https://evm-rpc.sei-apis.com' for mainnet.";case"wsurl":return"Use 'wss://development.apimonaco.xyz/ws' for testnet or 'wss://api.monaco.xyz/ws' for mainnet.";case"network":return"Valid networks are: 'mainnet', 'development', 'staging', 'local'.";default:return"Refer to the SDK documentation for correct configuration format."}}class qW extends _Y{code="INVALID_STATE";currentState;expectedState;constructor($,J,Q,Y){let X=Q?`${J?`Current state is '${J}', `:""}Expected state is '${Q}'. Ensure operations are performed in the correct order.`:"Check that prerequisites are met before calling this method.";super($,{cause:Y,suggestion:X,retryable:!1});this.currentState=J,this.expectedState=Q}toJSON(){return{...super.toJSON(),currentState:this.currentState,expectedState:this.expectedState}}}class y6 extends _Y{code="API_ERROR";endpoint;statusCode;responseBody;requestBody;requestId;retryAfter;constructor($,J){let{suggestion:Q,retryable:Y}=VX$(J?.statusCode,$,J?.responseBody);super($,{cause:J?.cause,suggestion:Q,retryable:Y});this.endpoint=J?.endpoint,this.statusCode=J?.statusCode,this.responseBody=J?.responseBody,this.requestBody=J?.requestBody,this.requestId=J?.requestId,this.retryAfter=J?.retryAfter}toJSON(){return{...super.toJSON(),endpoint:this.endpoint,statusCode:this.statusCode,responseBody:FY(this.responseBody),requestBody:FY(this.requestBody),requestId:this.requestId,retryAfter:this.retryAfter}}}function VX$($,J,Q){if(!$)return{suggestion:"Network request failed. Check your internet connection and try again.",retryable:!0};if($===pQ.StatusCodes.UNAUTHORIZED){if(J?.toLowerCase().includes("expired"))return{suggestion:"Access token has expired. Call sdk.refreshAuth() to get a new token, or call sdk.login() to re-authenticate.",retryable:!1};return{suggestion:"Authentication required. Call sdk.login(clientId) to authenticate before making this request.",retryable:!1}}if($===pQ.StatusCodes.FORBIDDEN)return{suggestion:"Access denied. Ensure your application has the required permissions and your client ID is valid.",retryable:!1};if($===pQ.StatusCodes.NOT_FOUND)return{suggestion:"Resource not found. Check that the ID or identifier is correct and the resource exists.",retryable:!1};if($===pQ.StatusCodes.CONFLICT)return{suggestion:"Resource conflict. The resource may have been modified. Refresh and try again.",retryable:!0};if($===pQ.StatusCodes.BAD_REQUEST){if(J?.toLowerCase().includes("insufficient balance"))return{suggestion:"Insufficient balance. Deposit more funds using sdk.vault.deposit() or reduce the order size.",retryable:!1};if(J?.toLowerCase().includes("invalid"))return{suggestion:"Invalid request parameters. Check the API documentation for correct parameter format and values.",retryable:!1};return{suggestion:"Bad request. Verify that all required parameters are provided and correctly formatted.",retryable:!1}}if($===pQ.StatusCodes.TOO_MANY_REQUESTS){let Y;if(typeof Q==="object"&&Q!==null&&"retry_after"in Q&&Q.retry_after){let X=Q.retry_after;Y=` Wait ${String(X)} seconds before retrying.`}else Y=" Wait a moment before retrying.";return{suggestion:`Rate limit exceeded.${Y} Consider implementing exponential backoff for retries.`,retryable:!0}}if($>=pQ.StatusCodes.INTERNAL_SERVER_ERROR&&$<600)return{suggestion:"Server error occurred. This is likely a temporary issue. Try again in a few moments.",retryable:!0};return{suggestion:void 0,retryable:!1}}class EJ extends _Y{code="CONTRACT_ERROR";revertReason;transactionHash;contractAddress;constructor($,J){let Q=OX$(J?.revertReason);super($,{cause:J?.cause,suggestion:Q,retryable:!1});this.revertReason=J?.revertReason,this.transactionHash=J?.transactionHash,this.contractAddress=J?.contractAddress}toJSON(){return{...super.toJSON(),revertReason:this.revertReason,transactionHash:this.transactionHash,contractAddress:this.contractAddress}}}function OX$($){if(!$)return"Smart contract execution failed. Check transaction parameters and try again.";let J=$.toLowerCase();if(J.includes("insufficient allowance"))return"Token allowance is insufficient. Call sdk.vault.approve() to increase the token allowance for the vault contract.";if(J.includes("insufficient balance"))return"Wallet balance is insufficient for this transaction. Ensure you have enough tokens and native currency for gas fees.";if(J.includes("nonce"))return"Transaction nonce error. This may be due to a pending transaction. Wait for pending transactions to complete or reset your account nonce.";if(J.includes("gas"))return"Transaction ran out of gas. Try increasing the gas limit for this transaction.";return}var NX$={local:"http://localhost:8080",development:"https://develop.apimonaco.xyz",staging:"https://staging.apimonaco.xyz",mainnet:"https://api.monaco.xyz"},zX$={local:"ws://localhost:8085/ws",development:"wss://develop.apimonaco.xyz/ws",staging:"wss://staging.apimonaco.xyz/ws",mainnet:"wss://api.monaco.xyz/ws"};function wW($){return NX$[$]}function V2($){return zX$[$]}var Bl=P6(v3(),1);var P3=256,R3;function T3($=11){if(!R3||P3+$>512){R3="",P3=0;for(let J=0;J<256;J++)R3+=(256+Math.random()*256|0).toString(16).substring(1)}return R3.substring(P3,P3+++$)}function C3($){let{batch:J,chain:Q,ccipRead:Y,dataSuffix:X,key:G="base",name:W="Base Client",type:D="base"}=$,U=$.experimental_blockTag??(typeof Q?.experimental_preconfirmationTime==="number"?"pending":void 0),V=Q?.blockTime??12000,O=Math.min(Math.max(Math.floor(V/2),500),4000),N=$.pollingInterval??O,M=$.cacheTime??N,H=$.account?E$($.account):void 0,{config:w,request:I,value:j}=$.transport({account:H,chain:Q,pollingInterval:N}),L={...w,...j},S={account:H,batch:J,cacheTime:M,ccipRead:Y,chain:Q,dataSuffix:X,key:G,name:W,pollingInterval:N,request:I,transport:L,type:D,uid:T3(),...U?{experimental_blockTag:U}:{}};function B(Z){return(_)=>{let P=_(Z);for(let h in S)delete P[h];let x={...Z,...P};return Object.assign(x,{extend:B(x)})}}return Object.assign(S,{extend:B(S)})}u0();mJ();W1();w8();A$();b$();$X();function yY($){if(!($ instanceof R))return!1;let J=$.walk((Q)=>Q instanceof gY);if(!(J instanceof gY))return!1;if(J.data?.errorName==="HttpError")return!0;if(J.data?.errorName==="ResolverError")return!0;if(J.data?.errorName==="ResolverNotContract")return!0;if(J.data?.errorName==="ResolverNotFound")return!0;if(J.data?.errorName==="ReverseAddressMismatch")return!0;if(J.data?.errorName==="UnsupportedResolverProfile")return!0;return!1}hW();J6();A$();y1();function AN($){if($.length!==66)return null;if($.indexOf("[")!==0)return null;if($.indexOf("]")!==65)return null;let J=`0x${$.slice(1,65)}`;if(!C4(J))return null;return J}function uW($){let J=new Uint8Array(32).fill(0);if(!$)return e$(J);let Q=$.split(".");for(let Y=Q.length-1;Y>=0;Y-=1){let X=AN(Q[Y]),G=X?g1(X):V4(z0(Q[Y]),"bytes");J=V4(Z4([J,G]),"bytes")}return e$(J)}J6();function ng($){return`[${$.slice(2)}]`}J6();A$();y1();function ig($){let J=new Uint8Array(32).fill(0);if(!$)return e$(J);return AN($)||V4(z0($))}function hY($){let J=$.replace(/^\.|\.$/gm,"");if(J.length===0)return new Uint8Array(1);let Q=new Uint8Array(z0(J).byteLength+2),Y=0,X=J.split(".");for(let G=0;G<X.length;G++){let W=z0(X[G]);if(W.byteLength>255)W=z0(ng(ig(X[G])));Q[Y]=W.length,Q.set(W,Y+1),Y+=W.length+1}if(Q.byteLength!==Y+1)return Q.slice(0,Y+1);return Q}function d($,J,Q){let Y=$[J.name];if(typeof Y==="function")return Y;let X=$[Q];if(typeof X==="function")return X;return(G)=>J($,G)}mJ();W1();l4();b$();$X();B8();G5();var q8$=3;function B1($,{abi:J,address:Q,args:Y,docsPath:X,functionName:G,sender:W}){let D=$ instanceof lJ?$:$ instanceof R?$.walk((w)=>("data"in w))||$.walk():{},{code:U,data:V,details:O,message:N,shortMessage:M}=D,H=(()=>{if($ instanceof N0)return new EB({functionName:G,cause:$});if([q8$,iJ.code].includes(U)&&(V||O||N||M)||U===l1.code&&O==="execution reverted"&&V)return new gY({abi:J,data:typeof V==="object"?V.data:V,functionName:G,message:D instanceof L8?O:M??N,cause:$});return $})();return new yW(H,{abi:J,args:Y,contractAddress:Q,docsPath:X,functionName:G,sender:W})}P8();async function p4($,J){let{abi:Q,address:Y,args:X,functionName:G,...W}=J,D=L4({abi:Q,args:X,functionName:G});try{let{data:U}=await d($,d1,"call")({...W,data:D,to:Y});return Z6({abi:Q,args:X,functionName:G,data:U||"0x"})}catch(U){throw B1(U,{abi:Q,address:Y,args:X,docsPath:"/docs/contract/readContract",functionName:G})}}async function Ry($,J){let{blockNumber:Q,blockTag:Y,coinType:X,name:G,gatewayUrls:W,strict:D}=J,{chain:U}=$,V=(()=>{if(J.universalResolverAddress)return J.universalResolverAddress;if(!U)throw Error("client chain not configured. universalResolverAddress is required.");return u1({blockNumber:Q,chain:U,contract:"ensUniversalResolver"})})(),O=U?.ensTlds;if(O&&!O.some((M)=>G.endsWith(M)))return null;let N=(()=>{if(X!=null)return[uW(G),BigInt(X)];return[uW(G)]})();try{let M=L4({abi:N2,functionName:"addr",args:N}),H={address:V,abi:x3,functionName:"resolveWithGateways",args:[x4(hY(G)),M,W??[nJ]],blockNumber:Q,blockTag:Y},I=await d($,p4,"readContract")(H);if(I[0]==="0x")return null;let j=Z6({abi:N2,args:N,functionName:"addr",data:I[0]});if(j==="0x")return null;if(e4(j)==="0x00")return null;return j}catch(M){if(D)throw M;if(yY(M))return null;throw M}}b$();class Kj extends R{constructor({data:$}){super("Unable to extract image from metadata. The metadata may be malformed or invalid.",{metaMessages:["- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.","",`Provided data: ${JSON.stringify($)}`],name:"EnsAvatarInvalidMetadataError"})}}class R8 extends R{constructor({reason:$}){super(`ENS NFT avatar URI is invalid. ${$}`,{name:"EnsAvatarInvalidNftUriError"})}}class $D extends R{constructor({uri:$}){super(`Unable to resolve ENS avatar URI "${$}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}}class Vj extends R{constructor({namespace:$}){super(`ENS NFT avatar namespace "${$}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}var h8$=/(?<protocol>https?:\/\/[^/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/,u8$=/^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?<target>[\w\-.]+))?(?<subtarget>\/.*)?$/,m8$=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,l8$=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function n8$($){try{let J=await fetch($,{method:"HEAD"});if(J.status===200)return J.headers.get("content-type")?.startsWith("image/");return!1}catch(J){if(typeof J==="object"&&typeof J.response<"u")return!1;if(!Object.hasOwn(globalThis,"Image"))return!1;return new Promise((Q)=>{let Y=new Image;Y.onload=()=>{Q(!0)},Y.onerror=()=>{Q(!1)},Y.src=$})}}function Ty($,J){if(!$)return J;if($.endsWith("/"))return $.slice(0,-1);return $}function Oj({uri:$,gatewayUrls:J}){let Q=m8$.test($);if(Q)return{uri:$,isOnChain:!0,isEncoded:Q};let Y=Ty(J?.ipfs,"https://ipfs.io"),X=Ty(J?.arweave,"https://arweave.net"),G=$.match(h8$),{protocol:W,subpath:D,target:U,subtarget:V=""}=G?.groups||{},O=W==="ipns:/"||D==="ipns/",N=W==="ipfs:/"||D==="ipfs/"||u8$.test($);if($.startsWith("http")&&!O&&!N){let H=$;if(J?.arweave)H=$.replace(/https:\/\/arweave.net/g,J?.arweave);return{uri:H,isOnChain:!1,isEncoded:!1}}if((O||N)&&U)return{uri:`${Y}/${O?"ipns":"ipfs"}/${U}${V}`,isOnChain:!1,isEncoded:!1};if(W==="ar:/"&&U)return{uri:`${X}/${U}${V||""}`,isOnChain:!1,isEncoded:!1};let M=$.replace(l8$,"");if(M.startsWith("<svg"))M=`data:image/svg+xml;base64,${btoa(M)}`;if(M.startsWith("data:")||M.startsWith("{"))return{uri:M,isOnChain:!0,isEncoded:!1};throw new $D({uri:$})}function Nj($){if(typeof $!=="object"||!("image"in $)&&!("image_url"in $)&&!("image_data"in $))throw new Kj({data:$});return $.image||$.image_url||$.image_data}async function Cy({gatewayUrls:$,uri:J}){try{let Q=await fetch(J).then((X)=>X.json());return await kN({gatewayUrls:$,uri:Nj(Q)})}catch{throw new $D({uri:J})}}async function kN({gatewayUrls:$,uri:J}){let{uri:Q,isOnChain:Y}=Oj({uri:J,gatewayUrls:$});if(Y)return Q;if(await n8$(Q))return Q;throw new $D({uri:J})}function ky($){let J=$;if(J.startsWith("did:nft:"))J=J.replace("did:nft:","").replace(/_/g,"/");let[Q,Y,X]=J.split("/"),[G,W]=Q.split(":"),[D,U]=Y.split(":");if(!G||G.toLowerCase()!=="eip155")throw new R8({reason:"Only EIP-155 supported"});if(!W)throw new R8({reason:"Chain ID not found"});if(!U)throw new R8({reason:"Contract address not found"});if(!X)throw new R8({reason:"Token ID not found"});if(!D)throw new R8({reason:"ERC namespace not found"});return{chainID:Number.parseInt(W,10),namespace:D.toLowerCase(),contractAddress:U,tokenID:X}}async function xy($,{nft:J}){if(J.namespace==="erc721")return p4($,{address:J.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(J.tokenID)]});if(J.namespace==="erc1155")return p4($,{address:J.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(J.tokenID)]});throw new Vj({namespace:J.namespace})}async function fy($,{gatewayUrls:J,record:Q}){if(/eip155:/i.test(Q))return i8$($,{gatewayUrls:J,record:Q});return kN({uri:Q,gatewayUrls:J})}async function i8$($,{gatewayUrls:J,record:Q}){let Y=ky(Q),X=await xy($,{nft:Y}),{uri:G,isOnChain:W,isEncoded:D}=Oj({uri:X,gatewayUrls:J});if(W&&(G.includes("data:application/json;base64,")||G.startsWith("{"))){let V=D?atob(G.replace("data:application/json;base64,","")):G,O=JSON.parse(V);return kN({uri:Nj(O),gatewayUrls:J})}let U=Y.tokenID;if(Y.namespace==="erc1155")U=U.replace("0x","").padStart(64,"0");return Cy({gatewayUrls:J,uri:G.replace(/(?:0x)?{id}/,U)})}u0();mJ();W1();w8();A$();hW();async function xN($,J){let{blockNumber:Q,blockTag:Y,key:X,name:G,gatewayUrls:W,strict:D}=J,{chain:U}=$,V=(()=>{if(J.universalResolverAddress)return J.universalResolverAddress;if(!U)throw Error("client chain not configured. universalResolverAddress is required.");return u1({blockNumber:Q,chain:U,contract:"ensUniversalResolver"})})(),O=U?.ensTlds;if(O&&!O.some((N)=>G.endsWith(N)))return null;try{let N={address:V,abi:x3,args:[x4(hY(G)),L4({abi:O2,functionName:"text",args:[uW(G),X]}),W??[nJ]],functionName:"resolveWithGateways",blockNumber:Q,blockTag:Y},H=await d($,p4,"readContract")(N);if(H[0]==="0x")return null;let w=Z6({abi:O2,functionName:"text",data:H[0]});return w===""?null:w}catch(N){if(D)throw N;if(yY(N))return null;throw N}}async function by($,{blockNumber:J,blockTag:Q,assetGatewayUrls:Y,name:X,gatewayUrls:G,strict:W,universalResolverAddress:D}){let U=await d($,xN,"getEnsText")({blockNumber:J,blockTag:Q,key:"avatar",name:X,universalResolverAddress:D,gatewayUrls:G,strict:W});if(!U)return null;try{return await fy($,{record:U,gatewayUrls:Y})}catch{return null}}u0();w8();hW();async function gy($,J){let{address:Q,blockNumber:Y,blockTag:X,coinType:G=60n,gatewayUrls:W,strict:D}=J,{chain:U}=$,V=(()=>{if(J.universalResolverAddress)return J.universalResolverAddress;if(!U)throw Error("client chain not configured. universalResolverAddress is required.");return u1({blockNumber:Y,chain:U,contract:"ensUniversalResolver"})})();try{let O={address:V,abi:Mb,args:[Q,G,W??[nJ]],functionName:"reverseWithGateways",blockNumber:Y,blockTag:X},N=d($,p4,"readContract"),[M]=await N(O);return M||null}catch(O){if(D)throw O;if(yY(O))return null;throw O}}w8();A$();async function yy($,J){let{blockNumber:Q,blockTag:Y,name:X}=J,{chain:G}=$,W=(()=>{if(J.universalResolverAddress)return J.universalResolverAddress;if(!G)throw Error("client chain not configured. universalResolverAddress is required.");return u1({blockNumber:Q,chain:G,contract:"ensUniversalResolver"})})(),D=G?.ensTlds;if(D&&!D.some((V)=>X.endsWith(V)))throw Error(`${X} is not a valid ENS TLD (${D?.join(", ")}) for chain "${G.name}" (id: ${G.id}).`);let[U]=await d($,p4,"readContract")({address:W,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"},{type:"uint256"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[x4(hY(X))],blockNumber:Q,blockTag:Y});return U}P8();A$();Qj();sJ();t0();async function fN($,J){let{account:Q=$.account,blockNumber:Y,blockTag:X="latest",blobs:G,data:W,gas:D,gasPrice:U,maxFeePerBlobGas:V,maxFeePerGas:O,maxPriorityFeePerGas:N,to:M,value:H,...w}=J,I=Q?E$(Q):void 0;try{X6(J);let L=(typeof Y==="bigint"?u(Y):void 0)||X,S=$.chain?.formatters?.transactionRequest?.format,Z=(S||F6)({...i1(w,{format:S}),account:I,blobs:G,data:W,gas:D,gasPrice:U,maxFeePerBlobGas:V,maxFeePerGas:O,maxPriorityFeePerGas:N,to:M,value:H},"createAccessList"),_=await $.request({method:"eth_createAccessList",params:[Z,L]});return{accessList:_.accessList,gasUsed:BigInt(_.gasUsed)}}catch(j){throw RN(j,{...J,account:I,chain:$.chain})}}function KX($,{method:J}){let Q={};if($.transport.type==="fallback")$.transport.onResponse?.(({method:Y,response:X,status:G,transport:W})=>{if(G==="success"&&J===Y)Q[X]=W.request});return(Y)=>Q[Y]||$.request}async function hy($){let J=KX($,{method:"eth_newBlockFilter"}),Q=await $.request({method:"eth_newBlockFilter"});return{id:Q,request:J(Q),type:"block"}}l4();b$();class zj extends R{constructor($){super(`Filter type "${$}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}J6();y1();CW();gJ();vJ();eQ();var uy="/docs/contract/encodeEventTopics";function a0($){let{abi:J,eventName:Q,args:Y}=$,X=J[0];if(Q){let U=G1({abi:J,name:Q});if(!U)throw new y3(Q,{docsPath:uy});X=U}if(X.type!=="event")throw new y3(void 0,{docsPath:uy});let G=o4(X),W=sQ(G),D=[];if(Y&&"inputs"in X){let U=X.inputs?.filter((O)=>("indexed"in O)&&O.indexed),V=Array.isArray(Y)?Y:Object.values(Y).length>0?U?.map((O)=>Y[O.name])??[]:[];if(V.length>0)D=U?.map((O,N)=>{if(Array.isArray(V[N]))return V[N].map((M,H)=>my({param:O,value:V[N][H]}));return typeof V[N]<"u"&&V[N]!==null?my({param:O,value:V[N]}):null})??[]}return[W,...D]}function my({param:$,value:J}){if($.type==="string"||$.type==="bytes")return V4(g1(J));if($.type==="tuple"||$.type.match(/^(.*)\[(\d+)?\]$/))throw new zj($.type);return h6([$],[J])}A$();async function bN($,J){let{address:Q,abi:Y,args:X,eventName:G,fromBlock:W,strict:D,toBlock:U}=J,V=KX($,{method:"eth_newFilter"}),O=G?a0({abi:Y,args:X,eventName:G}):void 0,N=await $.request({method:"eth_newFilter",params:[{address:Q,fromBlock:typeof W==="bigint"?u(W):W,toBlock:typeof U==="bigint"?u(U):U,topics:O}]});return{abi:Y,args:X,eventName:G,id:N,request:V(N),strict:Boolean(D),type:"event"}}A$();async function gN($,{address:J,args:Q,event:Y,events:X,fromBlock:G,strict:W,toBlock:D}={}){let U=X??(Y?[Y]:void 0),V=KX($,{method:"eth_newFilter"}),O=[];if(U){if(O=[U.flatMap((H)=>a0({abi:[H],eventName:H.name,args:Q}))],Y)O=O[0]}let N=await $.request({method:"eth_newFilter",params:[{address:J,fromBlock:typeof G==="bigint"?u(G):G,toBlock:typeof D==="bigint"?u(D):D,...O.length?{topics:O}:{}}]});return{abi:U,args:Q,eventName:Y?Y.name:void 0,fromBlock:G,id:N,request:V(N),strict:Boolean(W),toBlock:D,type:"event"}}async function yN($){let J=KX($,{method:"eth_newPendingTransactionFilter"}),Q=await $.request({method:"eth_newPendingTransactionFilter"});return{id:Q,request:J(Q),type:"transaction"}}W1();b$();xJ();y1();function hN($){let J=V4(`0x${$.substring(4)}`).substring(26);return kJ(`0x${J}`)}A1();$6();A$();async function Fh({hash:$,signature:J}){let Q=C4($)?$:x4($),{secp256k1:Y}=await Promise.resolve().then(() => (B5(),jh));return`0x${(()=>{if(typeof J==="object"&&"r"in J&&"s"in J){let{r:V,s:O,v:N,yParity:M}=J,H=Number(M??N),w=Zh(H);return new Y.Signature(y4(V),y4(O)).addRecoveryBit(w)}let W=C4(J)?J:x4(J);if(p$(W)!==65)throw Error("invalid signature length");let D=k4(`0x${W.slice(130)}`),U=Zh(D);return Y.Signature.fromCompact(W.substring(2,130)).addRecoveryBit(U)})().recoverPublicKey(Q.substring(2)).toHex(!1)}`}function Zh($){if($===0||$===1)return $;if($===27)return 0;if($===28)return 1;throw Error("Invalid yParityOrV value")}async function UD({hash:$,signature:J}){return hN(await Fh({hash:$,signature:J}))}J6();A$();b$();a3();J6();A$();function JQ($,J="hex"){let Q=_h($),Y=SY(new Uint8Array(Q.length));if(Q.encode(Y),J==="hex")return e$(Y.bytes);return Y.bytes}function _h($){if(Array.isArray($))return A9$($.map((J)=>_h(J)));return I9$($)}function A9$($){let J=$.reduce((X,G)=>X+G.length,0),Q=Sh(J);return{length:(()=>{if(J<=55)return 1+J;return 1+Q+J})(),encode(X){if(J<=55)X.pushByte(192+J);else if(X.pushByte(247+Q),Q===1)X.pushUint8(J);else if(Q===2)X.pushUint16(J);else if(Q===3)X.pushUint24(J);else X.pushUint32(J);for(let{encode:G}of $)G(X)}}}function I9$($){let J=typeof $==="string"?r4($):$,Q=Sh(J.length);return{length:(()=>{if(J.length===1&&J[0]<128)return 1;if(J.length<=55)return 1+J.length;return 1+Q+J.length})(),encode(X){if(J.length===1&&J[0]<128)X.pushBytes(J);else if(J.length<=55)X.pushByte(128+J.length),X.pushBytes(J);else{if(X.pushByte(183+Q),Q===1)X.pushUint8(J.length);else if(Q===2)X.pushUint16(J.length);else if(Q===3)X.pushUint24(J.length);else X.pushUint32(J.length);X.pushBytes(J)}}}}function Sh($){if($<256)return 1;if($<65536)return 2;if($<16777216)return 3;if($<4294967296)return 4;throw new R("Length is too large.")}y1();function dN($){let{chainId:J,nonce:Q,to:Y}=$,X=$.contractAddress??$.address,G=V4(j6(["0x05",JQ([J?u(J):"0x",X,Q?u(Q):"0x"])]));if(Y==="bytes")return r4(G);return G}async function MX($){let{authorization:J,signature:Q}=$;return UD({hash:dN(J),signature:Q??J})}A$();wN();bY();b$();m1();class gj extends R{constructor($,{account:J,docsPath:Q,chain:Y,data:X,gas:G,gasPrice:W,maxFeePerGas:D,maxPriorityFeePerGas:U,nonce:V,to:O,value:N}){let M=A8({from:J?.address,to:O,value:typeof N<"u"&&`${fY(N)} ${Y?.nativeCurrency?.symbol||"ETH"}`,data:X,gas:G,gasPrice:typeof W<"u"&&`${t4(W)} gwei`,maxFeePerGas:typeof D<"u"&&`${t4(D)} gwei`,maxPriorityFeePerGas:typeof U<"u"&&`${t4(U)} gwei`,nonce:V});super($.shortMessage,{cause:$,docsPath:Q,metaMessages:[...$.metaMessages?[...$.metaMessages," "]:[],"Estimate Gas Arguments:",M].filter(Boolean),name:"EstimateGasExecutionError"});Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=$}}DX();eW();function Eh($,{docsPath:J,...Q}){let Y=(()=>{let X=UX($,Q);if(X instanceof A0)return $;return X})();return new gj(Y,{docsPath:J,...Q})}sJ();CN();t0();bY();b$();class KD extends R{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class k8 extends R{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class yj extends R{constructor({maxPriorityFeePerGas:$}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${t4($)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}$6();b$();class VD extends R{constructor({blockHash:$,blockNumber:J}){let Q="Block";if($)Q=`Block at hash "${$}"`;if(J)Q=`Block at number "${J}"`;super(`${Q} could not be found.`,{name:"BlockNotFoundError"})}}A$();$6();var hj={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function j5($,J){let Q={...$,blockHash:$.blockHash?$.blockHash:null,blockNumber:$.blockNumber?BigInt($.blockNumber):null,...$.blockTimestamp!=null&&{blockTimestamp:BigInt($.blockTimestamp)},chainId:$.chainId?k4($.chainId):void 0,gas:$.gas?BigInt($.gas):void 0,gasPrice:$.gasPrice?BigInt($.gasPrice):void 0,maxFeePerBlobGas:$.maxFeePerBlobGas?BigInt($.maxFeePerBlobGas):void 0,maxFeePerGas:$.maxFeePerGas?BigInt($.maxFeePerGas):void 0,maxPriorityFeePerGas:$.maxPriorityFeePerGas?BigInt($.maxPriorityFeePerGas):void 0,nonce:$.nonce?k4($.nonce):void 0,to:$.to?$.to:null,transactionIndex:$.transactionIndex?Number($.transactionIndex):null,type:$.type?hj[$.type]:void 0,typeHex:$.type?$.type:void 0,value:$.value?BigInt($.value):void 0,v:$.v?BigInt($.v):void 0};if($.authorizationList)Q.authorizationList=L9$($.authorizationList);if(Q.yParity=(()=>{if($.yParity)return Number($.yParity);if(typeof Q.v==="bigint"){if(Q.v===0n||Q.v===27n)return 0;if(Q.v===1n||Q.v===28n)return 1;if(Q.v>=35n)return Q.v%2n===0n?1:0}return})(),Q.type==="legacy")delete Q.accessList,delete Q.maxFeePerBlobGas,delete Q.maxFeePerGas,delete Q.maxPriorityFeePerGas,delete Q.yParity;if(Q.type==="eip2930")delete Q.maxFeePerBlobGas,delete Q.maxFeePerGas,delete Q.maxPriorityFeePerGas;if(Q.type==="eip1559")delete Q.maxFeePerBlobGas;return Q}function L9$($){return $.map((J)=>({address:J.address,chainId:Number(J.chainId),nonce:Number(J.nonce),r:J.r,s:J.s,yParity:Number(J.yParity)}))}function pN($,J){let Q=($.transactions??[]).map((Y)=>{if(typeof Y==="string")return Y;return j5(Y)});return{...$,baseFeePerGas:$.baseFeePerGas?BigInt($.baseFeePerGas):null,blobGasUsed:$.blobGasUsed?BigInt($.blobGasUsed):void 0,difficulty:$.difficulty?BigInt($.difficulty):void 0,excessBlobGas:$.excessBlobGas?BigInt($.excessBlobGas):void 0,gasLimit:$.gasLimit?BigInt($.gasLimit):void 0,gasUsed:$.gasUsed?BigInt($.gasUsed):void 0,hash:$.hash?$.hash:null,logsBloom:$.logsBloom?$.logsBloom:null,nonce:$.nonce?$.nonce:null,number:$.number?BigInt($.number):null,size:$.size?BigInt($.size):void 0,timestamp:$.timestamp?BigInt($.timestamp):void 0,transactions:Q,totalDifficulty:$.totalDifficulty?BigInt($.totalDifficulty):null}}async function Y6($,{blockHash:J,blockNumber:Q,blockTag:Y=$.experimental_blockTag??"latest",includeTransactions:X}={}){let G=X??!1,W=Q!==void 0?u(Q):void 0,D=null;if(J)D=await $.request({method:"eth_getBlockByHash",params:[J,G]},{dedupe:!0});else D=await $.request({method:"eth_getBlockByNumber",params:[W||Y,G]},{dedupe:Boolean(W)});if(!D)throw new VD({blockHash:J,blockNumber:Q});return($.chain?.formatters?.block?.format||pN)(D,"getBlock")}async function Z5($){let J=await $.request({method:"eth_gasPrice"});return BigInt(J)}async function vh($,J){return uj($,J)}async function uj($,J){let{block:Q,chain:Y=$.chain,request:X}=J||{};try{let G=Y?.fees?.maxPriorityFeePerGas??Y?.fees?.defaultPriorityFee;if(typeof G==="function"){let D=Q||await d($,Y6,"getBlock")({}),U=await G({block:D,client:$,request:X});if(U===null)throw Error();return U}if(typeof G<"u")return G;let W=await $.request({method:"eth_maxPriorityFeePerGas"});return y4(W)}catch{let[G,W]=await Promise.all([Q?Promise.resolve(Q):d($,Y6,"getBlock")({}),d($,Z5,"getGasPrice")({})]);if(typeof G.baseFeePerGas!=="bigint")throw new k8;let D=W-G.baseFeePerGas;if(D<0n)return 0n;return D}}async function Ph($,J){return cN($,J)}async function cN($,J){let{block:Q,chain:Y=$.chain,request:X,type:G="eip1559"}=J||{},W=await(async()=>{if(typeof Y?.fees?.baseFeeMultiplier==="function")return Y.fees.baseFeeMultiplier({block:Q,client:$,request:X});return Y?.fees?.baseFeeMultiplier??1.2})();if(W<1)throw new KD;let U=10**(W.toString().split(".")[1]?.length??0),V=(M)=>M*BigInt(Math.ceil(W*U))/BigInt(U),O=Q?Q:await d($,Y6,"getBlock")({});if(typeof Y?.fees?.estimateFeesPerGas==="function"){let M=await Y.fees.estimateFeesPerGas({block:Q,client:$,multiply:V,request:X,type:G});if(M!==null)return M}if(G==="eip1559"){if(typeof O.baseFeePerGas!=="bigint")throw new k8;let M=typeof X?.maxPriorityFeePerGas==="bigint"?X.maxPriorityFeePerGas:await uj($,{block:O,chain:Y,request:X}),H=V(O.baseFeePerGas);return{maxFeePerGas:X?.maxFeePerGas??H+M,maxPriorityFeePerGas:M}}return{gasPrice:X?.gasPrice??V(await d($,Z5,"getGasPrice")({}))}}$6();A$();async function F5($,{address:J,blockTag:Q="latest",blockNumber:Y}){let X=await $.request({method:"eth_getTransactionCount",params:[J,typeof Y==="bigint"?u(Y):Q]},{dedupe:Boolean(Y)});return k4(X)}J6();A$();function _5($){let{kzg:J}=$,Q=$.to??(typeof $.blobs[0]==="string"?"hex":"bytes"),Y=typeof $.blobs[0]==="string"?$.blobs.map((G)=>r4(G)):$.blobs,X=[];for(let G of Y)X.push(Uint8Array.from(J.blobToKzgCommitment(G)));return Q==="bytes"?X:X.map((G)=>e$(G))}J6();A$();function S5($){let{kzg:J}=$,Q=$.to??(typeof $.blobs[0]==="string"?"hex":"bytes"),Y=typeof $.blobs[0]==="string"?$.blobs.map((W)=>r4(W)):$.blobs,X=typeof $.commitments[0]==="string"?$.commitments.map((W)=>r4(W)):$.commitments,G=[];for(let W=0;W<Y.length;W++){let D=Y[W],U=X[W];G.push(Uint8Array.from(J.computeBlobKzgProof(D,U)))}return Q==="bytes"?G:G.map((W)=>e$(W))}A$();qj();var Rh=T8;J6();A$();function Th($,J){let Q=J||"hex",Y=Rh(C4($,{strict:!1})?g1($):$);if(Q==="bytes")return Y;return x4(Y)}function Ch($){let{commitment:J,version:Q=1}=$,Y=$.to??(typeof J==="string"?"hex":"bytes"),X=Th(J,"bytes");return X.set([Q],0),Y==="bytes"?X:e$(X)}function oN($){let{commitments:J,version:Q}=$,Y=$.to??(typeof J[0]==="string"?"hex":"bytes"),X=[];for(let G of J)X.push(Ch({commitment:G,to:Y,version:Q}));return X}var kh=32,xh=4096,fh=131072,mj=761855;var rN=1;b$();class lj extends R{constructor({maxSize:$,size:J}){super("Blob size is too large.",{metaMessages:[`Max: ${$} bytes`,`Given: ${J} bytes`],name:"BlobSizeTooLargeError"})}}class OD extends R{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class nj extends R{constructor({hash:$,size:J}){super(`Versioned hash "${$}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${J}`],name:"InvalidVersionedHashSizeError"})}}class ij extends R{constructor({hash:$,version:J}){super(`Versioned hash "${$}" version is invalid.`,{metaMessages:[`Expected: ${rN}`,`Received: ${J}`],name:"InvalidVersionedHashVersionError"})}}a3();A1();J6();A$();function bh($){let J=$.to??(typeof $.data==="string"?"hex":"bytes"),Q=typeof $.data==="string"?r4($.data):$.data,Y=p$(Q);if(!Y)throw new OD;if(Y>mj)throw new lj({maxSize:mj,size:Y});let X=[],G=!0,W=0;while(G){let D=SY(new Uint8Array(fh)),U=0;while(U<xh){let V=Q.slice(W,W+(kh-1));if(D.pushByte(0),D.pushBytes(V),V.length<31){D.pushByte(128),G=!1;break}U++,W+=31}X.push(D)}return J==="bytes"?X.map((D)=>D.bytes):X.map((D)=>e$(D.bytes))}function tN($){let{data:J,kzg:Q,to:Y}=$,X=$.blobs??bh({data:J,to:Y}),G=$.commitments??_5({blobs:X,kzg:Q,to:Y}),W=$.proofs??S5({blobs:X,commitments:G,kzg:Q,to:Y}),D=[];for(let U=0;U<X.length;U++)D.push({blob:X[U],commitment:G[U],proof:W[U]});return D}H8();t0();m1();function aN($){if($.type)return $.type;if(typeof $.authorizationList<"u")return"eip7702";if(typeof $.blobs<"u"||typeof $.blobVersionedHashes<"u"||typeof $.maxFeePerBlobGas<"u"||typeof $.sidecars<"u")return"eip4844";if(typeof $.maxFeePerGas<"u"||typeof $.maxPriorityFeePerGas<"u")return"eip1559";if(typeof $.gasPrice<"u"){if(typeof $.accessList<"u")return"eip2930";return"legacy"}throw new ZB({transaction:$})}DX();m1();eW();function HX($,{docsPath:J,...Q}){let Y=(()=>{let X=UX($,Q);if(X instanceof A0)return $;return X})();return new _B(Y,{docsPath:J,...Q})}sJ();t0();$6();async function S6($){let J=await $.request({method:"eth_chainId"},{dedupe:!0});return k4(J)}async function E5($,J){let{account:Q=$.account,accessList:Y,authorizationList:X,chain:G=$.chain,blobVersionedHashes:W,blobs:D,data:U,gas:V,gasPrice:O,maxFeePerBlobGas:N,maxFeePerGas:M,maxPriorityFeePerGas:H,nonce:w,nonceManager:I,to:j,type:L,value:S,...B}=J,Z=await(async()=>{if(!Q)return w;if(!I)return w;if(typeof w<"u")return w;let h=E$(Q),p=G?G.id:await d($,S6,"getChainId")({});return await I.consume({address:h.address,chainId:p,client:$})})();X6(J);let _=G?.formatters?.transactionRequest?.format,x=(_||F6)({...i1(B,{format:_}),account:Q?E$(Q):void 0,accessList:Y,authorizationList:X,blobs:D,blobVersionedHashes:W,data:U,gas:V,gasPrice:O,maxFeePerBlobGas:N,maxFeePerGas:M,maxPriorityFeePerGas:H,nonce:Z,to:j,type:L,value:S},"fillTransaction");try{let h=await $.request({method:"eth_fillTransaction",params:[x]}),b=(G?.formatters?.transaction?.format||j5)(h.tx);if(delete b.blockHash,delete b.blockNumber,delete b.r,delete b.s,delete b.transactionIndex,delete b.v,delete b.yParity,b.data=b.input,b.gas)b.gas=J.gas??b.gas;if(b.gasPrice)b.gasPrice=J.gasPrice??b.gasPrice;if(b.maxFeePerBlobGas)b.maxFeePerBlobGas=J.maxFeePerBlobGas??b.maxFeePerBlobGas;if(b.maxFeePerGas)b.maxFeePerGas=J.maxFeePerGas??b.maxFeePerGas;if(b.maxPriorityFeePerGas)b.maxPriorityFeePerGas=J.maxPriorityFeePerGas??b.maxPriorityFeePerGas;if(typeof b.nonce<"u")b.nonce=J.nonce??b.nonce;let Q$=await(async()=>{if(typeof G?.fees?.baseFeeMultiplier==="function"){let T=await d($,Y6,"getBlock")({});return G.fees.baseFeeMultiplier({block:T,client:$,request:J})}return G?.fees?.baseFeeMultiplier??1.2})();if(Q$<1)throw new KD;let K$=10**(Q$.toString().split(".")[1]?.length??0),y=(T)=>T*BigInt(Math.ceil(Q$*K$))/BigInt(K$);if(!b.feePayerSignature){if(b.maxFeePerGas&&!J.maxFeePerGas)b.maxFeePerGas=y(b.maxFeePerGas);if(b.gasPrice&&!J.gasPrice)b.gasPrice=y(b.gasPrice)}return{raw:h.raw,transaction:{from:x.from,...b},...h.capabilities?{capabilities:h.capabilities}:{}}}catch(h){throw HX(h,{...J,chain:$.chain})}}var ND=["blobVersionedHashes","chainId","fees","gas","nonce","type"],gh=new Map,dj=new I1(128);async function s0($,J){let Q=J;Q.account??=$.account,Q.parameters??=ND;let{account:Y,chain:X=$.chain,nonceManager:G,parameters:W}=Q,D=(()=>{if(typeof X?.prepareTransactionRequest==="function")return{fn:X.prepareTransactionRequest,runAt:["beforeFillTransaction"]};if(Array.isArray(X?.prepareTransactionRequest))return{fn:X.prepareTransactionRequest[0],runAt:X.prepareTransactionRequest[1].runAt};return})(),U;async function V(){if(U)return U;if(typeof Q.chainId<"u")return Q.chainId;if(X)return X.id;return U=await d($,S6,"getChainId")({}),U}let O=Y?E$(Y):Y,N=Q.nonce;if(W.includes("nonce")&&typeof N>"u"&&O&&G){let Z=await V();N=await G.consume({address:O.address,chainId:Z,client:$})}if(D?.fn&&D.runAt?.includes("beforeFillTransaction"))Q=await D.fn({...Q,chain:X},{phase:"beforeFillTransaction"}),N??=Q.nonce;let H=(()=>{if((W.includes("blobVersionedHashes")||W.includes("sidecars"))&&Q.kzg&&Q.blobs)return!1;if(dj.get($.uid)===!1)return!1;if(!["fees","gas"].some((_)=>W.includes(_)))return!1;if(W.includes("chainId")&&typeof Q.chainId!=="number")return!0;if(W.includes("nonce")&&typeof N!=="number")return!0;if(W.includes("fees")&&typeof Q.gasPrice!=="bigint"&&(typeof Q.maxFeePerGas!=="bigint"||typeof Q.maxPriorityFeePerGas!=="bigint"))return!0;if(W.includes("gas")&&typeof Q.gas!=="bigint")return!0;return!1})()?await d($,E5,"fillTransaction")({...Q,nonce:N}).then((Z)=>{let{chainId:_,from:P,gas:x,gasPrice:h,nonce:p,maxFeePerBlobGas:b,maxFeePerGas:Q$,maxPriorityFeePerGas:s,type:K$,...y}=Z.transaction;return dj.set($.uid,!0),{...Q,...P?{from:P}:{},...K$&&!Q.type?{type:K$}:{},...typeof _<"u"?{chainId:_}:{},...typeof x<"u"?{gas:x}:{},...typeof h<"u"?{gasPrice:h}:{},...typeof p<"u"?{nonce:p}:{},...typeof b<"u"&&Q.type!=="legacy"&&Q.type!=="eip2930"?{maxFeePerBlobGas:b}:{},...typeof Q$<"u"&&Q.type!=="legacy"&&Q.type!=="eip2930"?{maxFeePerGas:Q$}:{},...typeof s<"u"&&Q.type!=="legacy"&&Q.type!=="eip2930"?{maxPriorityFeePerGas:s}:{},..."nonceKey"in y&&typeof y.nonceKey<"u"?{nonceKey:y.nonceKey}:{},..."keyAuthorization"in y&&typeof y.keyAuthorization<"u"&&y.keyAuthorization!==null&&!("keyAuthorization"in Q)?{keyAuthorization:y.keyAuthorization}:{},..."feePayerSignature"in y&&typeof y.feePayerSignature<"u"&&y.feePayerSignature!==null?{feePayerSignature:y.feePayerSignature}:{},..."feeToken"in y&&typeof y.feeToken<"u"&&y.feeToken!==null&&!("feeToken"in Q)?{feeToken:y.feeToken}:{},...Z.capabilities?{_capabilities:Z.capabilities}:{}}}).catch((Z)=>{let _=Z;if(_.name!=="TransactionExecutionError")return Q;if(_.walk?.((h)=>{return h.name==="ExecutionRevertedError"}))throw Z;if(_.walk?.((h)=>{let p=h;return p.name==="MethodNotFoundRpcError"||p.name==="MethodNotSupportedRpcError"||p.message?.includes("eth_fillTransaction is not available")}))dj.set($.uid,!1);return Q}):Q;N??=H.nonce,Q={...H,...O?{from:O?.address}:{},...typeof N<"u"?{nonce:N}:{}};let{blobs:w,gas:I,kzg:j,type:L}=Q;if(D?.fn&&D.runAt?.includes("beforeFillParameters"))Q=await D.fn({...Q,chain:X},{phase:"beforeFillParameters"});let S;async function B(){if(S)return S;return S=await d($,Y6,"getBlock")({blockTag:"latest"}),S}if(W.includes("nonce")&&typeof N>"u"&&O&&!G)Q.nonce=await d($,F5,"getTransactionCount")({address:O.address,blockTag:"pending"});if((W.includes("blobVersionedHashes")||W.includes("sidecars"))&&w&&j){let Z=_5({blobs:w,kzg:j});if(W.includes("blobVersionedHashes")){let _=oN({commitments:Z,to:"hex"});Q.blobVersionedHashes=_}if(W.includes("sidecars")){let _=S5({blobs:w,commitments:Z,kzg:j}),P=tN({blobs:w,commitments:Z,proofs:_,to:"hex"});Q.sidecars=P}}if(W.includes("chainId"))Q.chainId=await V();if((W.includes("fees")||W.includes("type"))&&typeof L>"u")try{Q.type=aN(Q)}catch{let Z=gh.get($.uid);if(typeof Z>"u")Z=typeof(await B())?.baseFeePerGas==="bigint",gh.set($.uid,Z);Q.type=Z?"eip1559":"legacy"}if(W.includes("fees"))if(Q.type!=="legacy"&&Q.type!=="eip2930"){if(typeof Q.maxFeePerGas>"u"||typeof Q.maxPriorityFeePerGas>"u"){let Z=await B(),{maxFeePerGas:_,maxPriorityFeePerGas:P}=await cN($,{block:Z,chain:X,request:Q});if(typeof Q.maxPriorityFeePerGas>"u"&&Q.maxFeePerGas&&Q.maxFeePerGas<P)throw new yj({maxPriorityFeePerGas:P});Q.maxPriorityFeePerGas=P,Q.maxFeePerGas=_}}else{if(typeof Q.maxFeePerGas<"u"||typeof Q.maxPriorityFeePerGas<"u")throw new k8;if(typeof Q.gasPrice>"u"){let Z=await B(),{gasPrice:_}=await cN($,{block:Z,chain:X,request:Q,type:"legacy"});Q.gasPrice=_}}if(W.includes("gas")&&typeof I>"u")Q.gas=await d($,v5,"estimateGas")({...Q,account:O,prepare:O?.type==="local"?[]:["blobVersionedHashes"]});if(D?.fn&&D.runAt?.includes("afterFillParameters"))Q=await D.fn({...Q,chain:X},{phase:"afterFillParameters"});return X6(Q),delete Q.parameters,Q}async function v5($,J){let{account:Q=$.account,prepare:Y=!0}=J,X=Q?E$(Q):void 0,G=(()=>{if(Array.isArray(Y))return Y;if(X?.type!=="local")return["blobVersionedHashes"];return})();try{let W=await(async()=>{if(J.to)return J.to;if(J.authorizationList&&J.authorizationList.length>0)return await MX({authorization:J.authorizationList[0]}).catch(()=>{throw new R("`to` is required. Could not infer from `authorizationList`")});return})(),{accessList:D,authorizationList:U,blobs:V,blobVersionedHashes:O,blockNumber:N,blockTag:M,data:H,gas:w,gasPrice:I,maxFeePerBlobGas:j,maxFeePerGas:L,maxPriorityFeePerGas:S,nonce:B,value:Z,stateOverride:_,...P}=Y?await s0($,{...J,parameters:G,to:W}):J;if(w&&J.gas!==w)return w;let h=(typeof N==="bigint"?u(N):void 0)||M,p=w5(_);X6(J);let b=$.chain?.formatters?.transactionRequest?.format,s=(b||F6)({...i1(P,{format:b}),account:X,accessList:D,authorizationList:U,blobs:V,blobVersionedHashes:O,data:H,gasPrice:I,maxFeePerBlobGas:j,maxFeePerGas:L,maxPriorityFeePerGas:S,nonce:B,to:W,value:Z},"estimateGas");return BigInt(await $.request({method:"eth_estimateGas",params:p?[s,h??$.experimental_blockTag??"latest",p]:h?[s,h]:[s]}))}catch(W){throw Eh(W,{...J,account:X,chain:$.chain})}}async function yh($,J){let{abi:Q,address:Y,args:X,functionName:G,dataSuffix:W=typeof $.dataSuffix==="string"?$.dataSuffix:$.dataSuffix?.value,...D}=J,U=L4({abi:Q,args:X,functionName:G});try{return await d($,v5,"estimateGas")({data:`${U}${W?W.replace("0x",""):""}`,to:Y,...D})}catch(V){let O=D.account?E$(D.account):void 0;throw B1(V,{abi:Q,address:Y,args:X,docsPath:"/docs/contract/estimateContractGas",functionName:G,sender:O?.address})}}u0();mJ();W1();A$();P8();async function hh($,{address:J,blockNumber:Q,blockTag:Y=$.experimental_blockTag??"latest"}){if($.batch?.multicall&&$.chain?.contracts?.multicall3){let W=$.chain.contracts.multicall3.address,D=L4({abi:O0,functionName:"getEthBalance",args:[J]}),{data:U}=await d($,d1,"call")({to:W,data:D,blockNumber:Q,blockTag:Y});return Z6({abi:O0,functionName:"getEthBalance",args:[J],data:U||"0x"})}let X=typeof Q==="bigint"?u(Q):void 0,G=await $.request({method:"eth_getBalance",params:[J,X||Y]});return BigInt(G)}async function uh($){let J=await $.request({method:"eth_blobBaseFee"});return BigInt(J)}var B9$=new Map,j9$=new Map;function mh($){let J=(X,G)=>({clear:()=>G.delete(X),get:()=>G.get(X),set:(W)=>G.set(X,W)}),Q=J($,B9$),Y=J($,j9$);return{clear:()=>{Q.clear(),Y.clear()},promise:Q,response:Y}}async function lh($,{cacheKey:J,cacheTime:Q=Number.POSITIVE_INFINITY}){let Y=mh(J),X=Y.response.get();if(X&&Q>0){if(Date.now()-X.created.getTime()<Q)return X.data}let G=Y.promise.get();if(!G)G=$(),Y.promise.set(G);try{let W=await G;return Y.response.set({created:new Date,data:W}),W}finally{Y.promise.clear()}}var Z9$=($)=>`blockNumber.${$}`;async function e0($,{cacheTime:J=$.cacheTime}={}){let Q=await lh(()=>$.request({method:"eth_blockNumber"}),{cacheKey:Z9$($.uid),cacheTime:J});return BigInt(Q)}$6();A$();async function nh($,{blockHash:J,blockNumber:Q,blockTag:Y="latest"}={}){let X=Q!==void 0?u(Q):void 0,G;if(J)G=await $.request({method:"eth_getBlockTransactionCountByHash",params:[J]},{dedupe:!0});else G=await $.request({method:"eth_getBlockTransactionCountByNumber",params:[X||Y]},{dedupe:Boolean(X)});return k4(G)}A$();async function x8($,{address:J,blockNumber:Q,blockTag:Y="latest"}){let X=Q!==void 0?u(Q):void 0,G=await $.request({method:"eth_getCode",params:[J,X||Y]},{dedupe:Boolean(X)});if(G==="0x")return;return G}eQ();v8();J6();function G6($,{args:J,eventName:Q}={}){return{...$,blockHash:$.blockHash?$.blockHash:null,blockNumber:$.blockNumber?BigInt($.blockNumber):null,blockTimestamp:$.blockTimestamp?BigInt($.blockTimestamp):$.blockTimestamp===null?null:void 0,logIndex:$.logIndex?Number($.logIndex):null,transactionHash:$.transactionHash?$.transactionHash:null,transactionIndex:$.transactionIndex?Number($.transactionIndex):null,...Q?{args:J,eventName:Q}:{}}}y1();CW();l4();u2();A1();CW();vW();vJ();var ih="/docs/contract/decodeEventLog";function f8($){let{abi:J,data:Q,strict:Y,topics:X}=$,G=Y??!0,[W,...D]=X;if(!W)throw new j2({docsPath:ih});let U=J.find((L)=>L.type==="event"&&W===sQ(o4(L)));if(!(U&&("name"in U))||U.type!=="event")throw new Z2(W,{docsPath:ih});let{name:V,inputs:O}=U,N=O?.some((L)=>!(("name"in L)&&L.name)),M=N?[]:{},H=O.map((L,S)=>[L,S]).filter(([L])=>("indexed"in L)&&L.indexed),w=[];for(let L=0;L<H.length;L++){let[S,B]=H[L],Z=D[L];if(!Z){if(G)throw new K8({abiItem:U,param:S});w.push([S,B]);continue}M[N?B:S.name||B]=F9$({param:S,value:Z})}let I=O.filter((L)=>!(("indexed"in L)&&L.indexed)),j=G?I:[...w.map(([L])=>L),...I];if(j.length>0){if(Q&&Q!=="0x")try{let L=yJ(j,Q);if(L){let S=0;if(!G)for(let[B,Z]of w)M[N?Z:B.name||Z]=L[S++];if(N){for(let B=0;B<O.length;B++)if(M[B]===void 0&&S<L.length)M[B]=L[S++]}else for(let B=0;B<I.length;B++)M[I[B].name]=L[S++]}}catch(L){if(G){if(L instanceof LW||L instanceof SW)throw new cQ({abiItem:U,data:Q,params:j,size:p$(Q)});throw L}}else if(G)throw new cQ({abiItem:U,data:"0x",params:j,size:0})}return{eventName:V,args:Object.values(M).length>0?M:void 0}}function F9$({param:$,value:J}){if($.type==="string"||$.type==="bytes"||$.type==="tuple"||$.type.match(/^(.*)\[(\d+)?\]$/))return J;return(yJ([$],J)||[])[0]}function P5($){let{abi:J,args:Q,logs:Y,strict:X=!0}=$,G=(()=>{if(!$.eventName)return;if(Array.isArray($.eventName))return $.eventName;return[$.eventName]})(),W=J.filter((D)=>D.type==="event").map((D)=>({abi:D,selector:sQ(D)}));return Y.map((D)=>{let U=typeof D.blockNumber==="string"?G6(D):D,V=W.filter((M)=>U.topics[0]===M.selector);if(V.length===0)return null;let O,N;for(let M of V)try{O=f8({...U,abi:[M.abi],strict:!0}),N=M;break}catch{}if(!O&&!X){N=V[0];try{O=f8({data:U.data,topics:U.topics,abi:[N.abi],strict:!1})}catch{let M=N.abi.inputs?.some((H)=>!(("name"in H)&&H.name));return{...U,args:M?[]:{},eventName:N.abi.name}}}if(!O||!N)return null;if(G&&!G.includes(O.eventName))return null;if(!_9$({args:O.args,inputs:N.abi.inputs,matchArgs:Q}))return null;return{...O,...U}}).filter(Boolean)}function _9$($){let{args:J,inputs:Q,matchArgs:Y}=$;if(!Y)return!0;if(!J)return!1;function X(G,W,D){try{if(G.type==="address")return Z1(W,D);if(G.type==="string"||G.type==="bytes")return V4(g1(W))===D;return W===D}catch{return!1}}if(Array.isArray(J)&&Array.isArray(Y))return Y.every((G,W)=>{if(G===null||G===void 0)return!0;let D=Q[W];if(!D)return!1;return(Array.isArray(G)?G:[G]).some((V)=>X(D,V,J[W]))});if(typeof J==="object"&&!Array.isArray(J)&&typeof Y==="object"&&!Array.isArray(Y))return Object.entries(Y).every(([G,W])=>{if(W===null||W===void 0)return!0;let D=Q.find((V)=>V.name===G);if(!D)return!1;return(Array.isArray(W)?W:[W]).some((V)=>X(D,V,J[G]))});return!1}A$();async function R5($,{address:J,blockHash:Q,fromBlock:Y,toBlock:X,event:G,events:W,args:D,strict:U}={}){let V=U??!1,O=W??(G?[G]:void 0),N=[];if(O){if(N=[O.flatMap((I)=>a0({abi:[I],eventName:I.name,args:W?void 0:D}))],G)N=N[0]}let M;if(Q)M=await $.request({method:"eth_getLogs",params:[{address:J,topics:N,blockHash:Q}]});else M=await $.request({method:"eth_getLogs",params:[{address:J,topics:N,fromBlock:typeof Y==="bigint"?u(Y):Y,toBlock:typeof X==="bigint"?u(X):X}]});let H=M.map((w)=>G6(w));if(!O)return H;return P5({abi:O,args:D,logs:H,strict:V})}async function sN($,J){let{abi:Q,address:Y,args:X,blockHash:G,eventName:W,fromBlock:D,toBlock:U,strict:V}=J,O=W?G1({abi:Q,name:W}):void 0,N=!O?Q.filter((M)=>M.type==="event"):void 0;return d($,R5,"getLogs")({address:Y,args:X,blockHash:G,event:O,events:N,fromBlock:D,toBlock:U,strict:V})}xJ();A1();bJ();async function dh($,{address:J,blockNumber:Q,blockTag:Y="latest"}){let X=await x8($,{address:J,...Q!==void 0?{blockNumber:Q}:{blockTag:Y}});if(!X)return;if(p$(X)!==23)return;if(!X.startsWith("0xef0100"))return;return fJ(X1(X,3,23))}b$();class pj extends R{constructor({address:$}){super(`No EIP-712 domain found on contract "${$}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${$}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}}async function ph($,J){let{address:Q,factory:Y,factoryData:X}=J;try{let[G,W,D,U,V,O,N]=await d($,p4,"readContract")({abi:S9$,address:Q,functionName:"eip712Domain",factory:Y,factoryData:X});return{domain:{name:W,version:D,chainId:Number(U),verifyingContract:V,salt:O},extensions:N,fields:G}}catch(G){let W=G;if(W.name==="ContractFunctionExecutionError"&&W.cause.name==="ContractFunctionZeroDataError")throw new pj({address:Q});throw W}}var S9$=[{inputs:[],name:"eip712Domain",outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"}];A$();function ch($){return{baseFeePerGas:$.baseFeePerGas.map((J)=>BigInt(J)),gasUsedRatio:$.gasUsedRatio,oldestBlock:BigInt($.oldestBlock),reward:$.reward?.map((J)=>J.map((Q)=>BigInt(Q)))}}async function oh($,{blockCount:J,blockNumber:Q,blockTag:Y="latest",rewardPercentiles:X}){let G=typeof Q==="bigint"?u(Q):void 0,W=await $.request({method:"eth_feeHistory",params:[u(J),G||Y,X]},{dedupe:Boolean(G)});return ch(W)}async function qX($,{filter:J}){let Q="strict"in J&&J.strict,Y=await J.request({method:"eth_getFilterChanges",params:[J.id]});if(typeof Y[0]==="string")return Y;let X=Y.map((G)=>G6(G));if(!("abi"in J)||!J.abi)return X;return P5({abi:J.abi,logs:X,strict:Q})}async function rh($,{filter:J}){let Q=J.strict??!1,X=(await J.request({method:"eth_getFilterLogs",params:[J.id]})).map((G)=>G6(G));if(!J.abi)return X;return P5({abi:J.abi,logs:X,strict:Q})}A$();$6();function E9$($){return $.map((J)=>({...J,value:BigInt(J.value)}))}function th($){return{...$,balance:$.balance?BigInt($.balance):void 0,nonce:$.nonce?k4($.nonce):void 0,storageProof:$.storageProof?E9$($.storageProof):void 0}}async function ah($,{address:J,blockNumber:Q,blockTag:Y,storageKeys:X}){let G=Y??"latest",W=Q!==void 0?u(Q):void 0,D=await $.request({method:"eth_getProof",params:[J,X,W||G]});return th(D)}A$();async function sh($,{address:J,blockNumber:Q,blockTag:Y="latest",slot:X}){let G=Q!==void 0?u(Q):void 0;return await $.request({method:"eth_getStorageAt",params:[J,X,G||Y]})}m1();A$();async function T5($,{blockHash:J,blockNumber:Q,blockTag:Y,hash:X,index:G,sender:W,nonce:D}){let U=Y||"latest",V=Q!==void 0?u(Q):void 0,O=null;if(X)O=await $.request({method:"eth_getTransactionByHash",params:[X]},{dedupe:!0});else if(J)O=await $.request({method:"eth_getTransactionByBlockHashAndIndex",params:[J,u(G)]},{dedupe:!0});else if((V||U)&&typeof G==="number")O=await $.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[V||U,u(G)]},{dedupe:Boolean(V)});else if(W&&typeof D==="number")O=await $.request({method:"eth_getTransactionBySenderAndNonce",params:[W,u(D)]},{dedupe:!0});if(!O)throw new xW({blockHash:J,blockNumber:Q,blockTag:U,hash:X,index:G});return($.chain?.formatters?.transaction?.format||j5)(O,"getTransaction")}async function eh($,{hash:J,transactionReceipt:Q}){let[Y,X]=await Promise.all([d($,e0,"getBlockNumber")({}),J?d($,T5,"getTransaction")({hash:J}):void 0]),G=Q?.blockNumber||X?.blockNumber;if(!G)return 0n;return Y-G+1n}m1();$6();var cj={"0x0":"reverted","0x1":"success"};function eN($,J){let Q={...$,blockNumber:$.blockNumber?BigInt($.blockNumber):null,contractAddress:$.contractAddress?$.contractAddress:null,cumulativeGasUsed:$.cumulativeGasUsed?BigInt($.cumulativeGasUsed):null,effectiveGasPrice:$.effectiveGasPrice?BigInt($.effectiveGasPrice):null,gasUsed:$.gasUsed?BigInt($.gasUsed):null,logs:$.logs?$.logs.map((Y)=>G6(Y)):null,to:$.to?$.to:null,transactionIndex:$.transactionIndex?k4($.transactionIndex):null,status:$.status?cj[$.status]:null,type:$.type?hj[$.type]||$.type:null};if($.blobGasPrice)Q.blobGasPrice=BigInt($.blobGasPrice);if($.blobGasUsed)Q.blobGasUsed=BigInt($.blobGasUsed);return Q}async function C5($,{hash:J}){let Q=await $.request({method:"eth_getTransactionReceipt",params:[J]},{dedupe:!0});if(!Q)throw new fW({hash:J});return($.chain?.formatters?.transactionReceipt?.format||eN)(Q,"getTransactionReceipt")}u0();l4();b$();$X();mJ();W1();w8();async function $u($,J){let{account:Q,authorizationList:Y,allowFailure:X=!0,blockNumber:G,blockOverrides:W,blockTag:D,stateOverride:U}=J,V=J.contracts,{batchSize:O=J.batchSize??1024,deployless:N=J.deployless??!1}=typeof $.batch?.multicall==="object"?$.batch.multicall:{},M=(()=>{if(J.multicallAddress)return J.multicallAddress;if(N)return null;if($.chain)return u1({blockNumber:G,chain:$.chain,contract:"multicall3"});throw Error("client chain not configured. multicallAddress is required.")})(),H=[[]],w=0,I=0;for(let S=0;S<V.length;S++){let{abi:B,address:Z,args:_,functionName:P}=V[S];try{let x=L4({abi:B,args:_,functionName:P});if(I+=(x.length-2)/2,O>0&&I>O&&H[w].length>0)w++,I=(x.length-2)/2,H[w]=[];H[w]=[...H[w],{allowFailure:!0,callData:x,target:Z}]}catch(x){let h=B1(x,{abi:B,address:Z,args:_,docsPath:"/docs/contract/multicall",functionName:P,sender:Q});if(!X)throw h;H[w]=[...H[w],{allowFailure:!0,callData:"0x",target:Z}]}}let j=await Promise.allSettled(H.map((S)=>d($,p4,"readContract")({...M===null?{code:H5}:{address:M},abi:O0,account:Q,args:[S],authorizationList:Y,blockNumber:G,blockOverrides:W,blockTag:D,functionName:"aggregate3",stateOverride:U}))),L=[];for(let S=0;S<j.length;S++){let B=j[S];if(B.status==="rejected"){if(!X)throw B.reason;for(let _=0;_<H[S].length;_++)L.push({status:"failure",error:B.reason,result:void 0});continue}let Z=B.value;for(let _=0;_<Z.length;_++){let{returnData:P,success:x}=Z[_],{callData:h}=H[S][_],{abi:p,address:b,functionName:Q$,args:s}=V[L.length];try{if(h==="0x")throw new N0;if(!x)throw new lJ({data:P});let K$=Z6({abi:p,args:s,data:P,functionName:Q$});L.push(X?{result:K$,status:"success"}:K$)}catch(K$){let y=B1(K$,{abi:p,address:b,args:s,docsPath:"/docs/contract/multicall",functionName:Q$});if(!X)throw y;L.push({error:y,result:void 0,status:"failure"})}}}if(L.length!==V.length)throw new R("multicall results mismatch");return L}$j();l4();$X();DX();mJ();W1();A$();eW();sJ();CN();t0();async function zD($,J){let{blockNumber:Q,blockTag:Y=$.experimental_blockTag??"latest",blocks:X,returnFullTransactions:G,traceTransfers:W,validation:D}=J;try{let U=[];for(let M of X){let H=M.blockOverrides?EN(M.blockOverrides):void 0,w=M.calls.map((j)=>{let L=j,S=L.account?E$(L.account):void 0,B=L.abi?L4(L):L.data,Z={...L,account:S,data:L.dataSuffix?Z4([B||"0x",L.dataSuffix]):B,from:L.from??S?.address};return X6(Z),F6(Z)}),I=M.stateOverrides?w5(M.stateOverrides):void 0;U.push({blockOverrides:H,calls:w,stateOverrides:I})}let O=(typeof Q==="bigint"?u(Q):void 0)||Y;return(await $.request({method:"eth_simulateV1",params:[{blockStateCalls:U,returnFullTransactions:G,traceTransfers:W,validation:D},O]})).map((M,H)=>({...pN(M),calls:M.calls.map((w,I)=>{let{abi:j,args:L,functionName:S,to:B}=X[H].calls[I],Z=w.error?.data??w.returnData,_=BigInt(w.gasUsed),P=w.logs?.map((b)=>G6(b)),x=w.status==="0x1"?"success":"failure",h=j&&x==="success"&&Z!=="0x"?Z6({abi:j,data:Z,functionName:S}):null,p=(()=>{if(x==="success")return;let b;if(Z==="0x")b=new N0;else if(Z)b=new lJ({data:Z});if(!b)return;return B1(b,{abi:j??[],address:B??"0x",args:L,functionName:S??"<unknown>"})})();return{data:Z,gasUsed:_,logs:P,status:x,...x==="success"?{result:h}:{error:p}}})}))}catch(U){let V=U,O=UX(V,{});if(O instanceof A0)throw V;throw O}}TW();U1();b2();YX();Q6();function b8($,J={}){let{as:Q=typeof $==="string"?"Hex":"Bytes"}=J,Y=r3(Ky($));if(Q==="Bytes")return Y;return n4(Y)}Q6();YX();class rj extends Map{constructor($){super();Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=$}get($){let J=super.get($);if(super.has($)&&J!==void 0)this.delete($),super.set($,J);return J}set($,J){if(super.set($,J),this.maxSize&&this.size>this.maxSize){let Q=this.keys().next().value;if(Q)this.delete(Q)}return this}}var v9$={checksum:new rj(8192)},$z=v9$.checksum;U1();YX();U1();Q6();function Ju($,J={}){let{compressed:Q}=J,{prefix:Y,x:X,y:G}=$;if(Q===!1||typeof X==="bigint"&&typeof G==="bigint"){if(Y!==4)throw new tj({prefix:Y,cause:new Wu});return}if(Q===!0||typeof X==="bigint"&&typeof G>"u"){if(Y!==3&&Y!==2)throw new tj({prefix:Y,cause:new Gu});return}throw new Yu({publicKey:$})}function Qu($){let J=(()=>{if(iW($))return Xu($);if(Hy($))return R9$($);let{prefix:Q,x:Y,y:X}=$;if(typeof Y==="bigint"&&typeof X==="bigint")return{prefix:Q??4,x:Y,y:X};return{prefix:Q,x:Y}})();return Ju(J),J}function R9$($){return Xu(n4($))}function Xu($){if($.length!==132&&$.length!==130&&$.length!==68)throw new Du({publicKey:$});if($.length===130){let Y=BigInt(T4($,0,32)),X=BigInt(T4($,32,64));return{prefix:4,x:Y,y:X}}if($.length===132){let Y=Number(T4($,0,1)),X=BigInt(T4($,1,33)),G=BigInt(T4($,33,65));return{prefix:Y,x:X,y:G}}let J=Number(T4($,0,1)),Q=BigInt(T4($,1,33));return{prefix:J,x:Q}}function aj($,J={}){Ju($);let{prefix:Q,x:Y,y:X}=$,{includePrefix:G=!0}=J;return f4(G?J4(Q,{size:1}):"0x",J4(Y,{size:32}),typeof X==="bigint"?J4(X,{size:32}):"0x")}class Yu extends D${constructor({publicKey:$}){super(`Value \`${GX($)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}}class tj extends D${constructor({prefix:$,cause:J}){super(`Prefix "${$}" is invalid.`,{cause:J});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class Gu extends D${constructor(){super("Prefix must be 2 or 3 for compressed public keys.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}}class Wu extends D${constructor(){super("Prefix must be 4 for uncompressed public keys.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}class Du extends D${constructor({publicKey:$}){super(`Value \`${$}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${R4(z5($))} bytes.`]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}}var T9$=/^0x[a-fA-F0-9]{40}$/;function g8($,J={}){let{strict:Q=!0}=J;if(!T9$.test($))throw new sj({address:$,cause:new Vu});if(Q){if($.toLowerCase()===$)return;if(Jz($)!==$)throw new sj({address:$,cause:new Ou})}}function Jz($){if($z.has($))return $z.get($);g8($,{strict:!1});let J=$.substring(2).toLowerCase(),Q=b8(Vy(J),{as:"Bytes"}),Y=J.split("");for(let G=0;G<40;G+=2){if(Q[G>>1]>>4>=8&&Y[G])Y[G]=Y[G].toUpperCase();if((Q[G>>1]&15)>=8&&Y[G+1])Y[G+1]=Y[G+1].toUpperCase()}let X=`0x${Y.join("")}`;return $z.set($,X),X}function C9$($,J={}){let{checksum:Q=!1}=J;if(g8($),Q)return Jz($);return $}function Ku($,J={}){let Q=b8(`0x${aj($).slice(4)}`).substring(26);return C9$(`0x${Q}`,J)}function Qz($,J={}){let{strict:Q=!0}=J??{};try{return g8($,{strict:Q}),!0}catch{return!1}}class sj extends D${constructor({address:$,cause:J}){super(`Address "${$}" is invalid.`,{cause:J});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class Vu extends D${constructor(){super("Address is not a 20 byte (40 hexadecimal character) value.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class Ou extends D${constructor(){super("Address does not match its checksum counterpart.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}U1();function Gz($){let J=!0,Q="",Y=0,X="",G=!1;for(let W=0;W<$.length;W++){let D=$[W];if(["(",")",","].includes(D))J=!0;if(D==="(")Y++;if(D===")")Y--;if(!J)continue;if(Y===0){if(D===" "&&["event","function","error",""].includes(X))X="";else if(X+=D,D===")"){G=!0;break}continue}if(D===" "){if($[W-1]!==","&&Q!==","&&Q!==",(")Q="",J=!1;continue}X+=D,Q+=D}if(!G)throw new D$("Unable to normalize signature.");return X}function Yz($,J){let Q=typeof $,Y=J.type;switch(Y){case"address":return Qz($,{strict:!1});case"bool":return Q==="boolean";case"function":return Q==="string";case"string":return Q==="string";default:{if(Y==="tuple"&&"components"in J)return Object.values(J.components).every((X,G)=>{return Yz(Object.values($)[G],X)});if(/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(Y))return Q==="number"||Q==="bigint";if(/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(Y))return Q==="string"||$ instanceof Uint8Array;if(/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(Y))return Array.isArray($)&&$.every((X)=>Yz(X,{...J,type:Y.replace(/(\[[0-9]{0,}\])$/,"")}));return!1}}}function ej($,J,Q){for(let Y in $){let X=$[Y],G=J[Y];if(X.type==="tuple"&&G.type==="tuple"&&"components"in X&&"components"in G)return ej(X.components,G.components,Q[Y]);let W=[X.type,G.type];if((()=>{if(W.includes("address")&&W.includes("bytes20"))return!0;if(W.includes("address")&&W.includes("string"))return Qz(Q[Y],{strict:!1});if(W.includes("address")&&W.includes("bytes"))return Qz(Q[Y],{strict:!1});return!1})())return W}return}function Wz($,J={}){let{prepare:Q=!0}=J,Y=(()=>{if(Array.isArray($))return KN($);if(typeof $==="string")return KN($);return $})();return{...Y,...Q?{hash:k5(Y)}:{}}}function MD($,J,Q){let{args:Y=[],prepare:X=!0}=Q??{},G=iW(J,{strict:!1}),W=$.filter((V)=>{if(G){if(V.type==="function"||V.type==="error")return $Z(V)===T4(J,0,4);if(V.type==="event")return k5(V)===J;return!1}return"name"in V&&V.name===J});if(W.length===0)throw new y8({name:J});if(W.length===1)return{...W[0],...X?{hash:k5(W[0])}:{}};let D;for(let V of W){if(!("inputs"in V))continue;if(!Y||Y.length===0){if(!V.inputs||V.inputs.length===0)return{...V,...X?{hash:k5(V)}:{}};continue}if(!V.inputs)continue;if(V.inputs.length===0)continue;if(V.inputs.length!==Y.length)continue;if(Y.every((N,M)=>{let H="inputs"in V&&V.inputs[M];if(!H)return!1;return Yz(N,H)})){if(D&&"inputs"in D&&D.inputs){let N=ej(V.inputs,D.inputs,Y);if(N)throw new Nu({abiItem:V,type:N[0]},{abiItem:D,type:N[1]})}D=V}}let U=(()=>{if(D)return D;let[V,...O]=W;return{...V,overloads:O}})();if(!U)throw new y8({name:J});return{...U,...X?{hash:k5(U)}:{}}}function $Z(...$){let J=(()=>{if(Array.isArray($[0])){let[Q,Y]=$;return MD(Q,Y)}return $[0]})();return T4(k5(J),0,4)}function x9$(...$){let J=(()=>{if(Array.isArray($[0])){let[Y,X]=$;return MD(Y,X)}return $[0]})(),Q=(()=>{if(typeof J==="string")return J;return q8(J)})();return Gz(Q)}function k5(...$){let J=(()=>{if(Array.isArray($[0])){let[Q,Y]=$;return MD(Q,Y)}return $[0]})();if(typeof J!=="string"&&"hash"in J&&J.hash)return J.hash;return b8(M5(x9$(J)))}class Nu extends D${constructor($,J){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${$.type}\` in \`${Gz(q8($.abiItem))}\`, and`,`\`${J.type}\` in \`${Gz(q8(J.abiItem))}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.AmbiguityError"})}}class y8 extends D${constructor({name:$,data:J,type:Q="item"}){let Y=(()=>{if($)return` with name "${$}"`;if(J)return` with data "${J}"`;return""})();super(`ABI ${Q}${Y} not found.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}}TW();YX();U1();Q6();YX();U1();Q6();var Mu=/^(.*)\[([0-9]*)\]$/,Hu=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Dz=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,Gx$=2n**(8n-1n)-1n,Wx$=2n**(16n-1n)-1n,Dx$=2n**(24n-1n)-1n,Ux$=2n**(32n-1n)-1n,Kx$=2n**(40n-1n)-1n,Vx$=2n**(48n-1n)-1n,Ox$=2n**(56n-1n)-1n,Nx$=2n**(64n-1n)-1n,zx$=2n**(72n-1n)-1n,Mx$=2n**(80n-1n)-1n,Hx$=2n**(88n-1n)-1n,qx$=2n**(96n-1n)-1n,wx$=2n**(104n-1n)-1n,Ax$=2n**(112n-1n)-1n,Ix$=2n**(120n-1n)-1n,Lx$=2n**(128n-1n)-1n,Bx$=2n**(136n-1n)-1n,jx$=2n**(144n-1n)-1n,Zx$=2n**(152n-1n)-1n,Fx$=2n**(160n-1n)-1n,_x$=2n**(168n-1n)-1n,Sx$=2n**(176n-1n)-1n,Ex$=2n**(184n-1n)-1n,vx$=2n**(192n-1n)-1n,Px$=2n**(200n-1n)-1n,Rx$=2n**(208n-1n)-1n,Tx$=2n**(216n-1n)-1n,Cx$=2n**(224n-1n)-1n,kx$=2n**(232n-1n)-1n,xx$=2n**(240n-1n)-1n,fx$=2n**(248n-1n)-1n,bx$=2n**(256n-1n)-1n,gx$=-(2n**(8n-1n)),yx$=-(2n**(16n-1n)),hx$=-(2n**(24n-1n)),ux$=-(2n**(32n-1n)),mx$=-(2n**(40n-1n)),lx$=-(2n**(48n-1n)),nx$=-(2n**(56n-1n)),ix$=-(2n**(64n-1n)),dx$=-(2n**(72n-1n)),px$=-(2n**(80n-1n)),cx$=-(2n**(88n-1n)),ox$=-(2n**(96n-1n)),rx$=-(2n**(104n-1n)),tx$=-(2n**(112n-1n)),ax$=-(2n**(120n-1n)),sx$=-(2n**(128n-1n)),ex$=-(2n**(136n-1n)),$f$=-(2n**(144n-1n)),Jf$=-(2n**(152n-1n)),Qf$=-(2n**(160n-1n)),Xf$=-(2n**(168n-1n)),Yf$=-(2n**(176n-1n)),Gf$=-(2n**(184n-1n)),Wf$=-(2n**(192n-1n)),Df$=-(2n**(200n-1n)),Uf$=-(2n**(208n-1n)),Kf$=-(2n**(216n-1n)),Vf$=-(2n**(224n-1n)),Of$=-(2n**(232n-1n)),Nf$=-(2n**(240n-1n)),zf$=-(2n**(248n-1n)),Mf$=-(2n**(256n-1n)),Hf$=2n**8n-1n,qf$=2n**16n-1n,wf$=2n**24n-1n,Af$=2n**32n-1n,If$=2n**40n-1n,Lf$=2n**48n-1n,Bf$=2n**56n-1n,jf$=2n**64n-1n,Zf$=2n**72n-1n,Ff$=2n**80n-1n,_f$=2n**88n-1n,Sf$=2n**96n-1n,Ef$=2n**104n-1n,vf$=2n**112n-1n,Pf$=2n**120n-1n,Rf$=2n**128n-1n,Tf$=2n**136n-1n,Cf$=2n**144n-1n,kf$=2n**152n-1n,xf$=2n**160n-1n,ff$=2n**168n-1n,bf$=2n**176n-1n,gf$=2n**184n-1n,yf$=2n**192n-1n,hf$=2n**200n-1n,uf$=2n**208n-1n,mf$=2n**216n-1n,lf$=2n**224n-1n,nf$=2n**232n-1n,if$=2n**240n-1n,df$=2n**248n-1n,JZ=2n**256n-1n;function h8($,J,Q){let{checksumAddress:Y,staticPosition:X}=Q,G=YZ(J.type);if(G){let[W,D]=G;return b9$($,{...J,type:D},{checksumAddress:Y,length:W,staticPosition:X})}if(J.type==="tuple")return u9$($,J,{checksumAddress:Y,staticPosition:X});if(J.type==="address")return f9$($,{checksum:Y});if(J.type==="bool")return g9$($);if(J.type.startsWith("bytes"))return y9$($,J,{staticPosition:X});if(J.type.startsWith("uint")||J.type.startsWith("int"))return h9$($,J);if(J.type==="string")return m9$($,{staticPosition:X});throw new qD(J.type)}var wu=32,QZ=32;function f9$($,J={}){let{checksum:Q=!1}=J,Y=$.readBytes(32);return[((G)=>Q?Jz(G):G)(n4(Oy(Y,-20))),32]}function b9$($,J,Q){let{checksumAddress:Y,length:X,staticPosition:G}=Q;if(!X){let U=o0($.readBytes(QZ)),V=G+U,O=V+wu;$.setPosition(V);let N=o0($.readBytes(wu)),M=HD(J),H=0,w=[];for(let I=0;I<N;++I){$.setPosition(O+(M?I*32:H));let[j,L]=h8($,J,{checksumAddress:Y,staticPosition:O});H+=L,w.push(j)}return $.setPosition(G+32),[w,32]}if(HD(J)){let U=o0($.readBytes(QZ)),V=G+U,O=[];for(let N=0;N<X;++N){$.setPosition(V+N*32);let[M]=h8($,J,{checksumAddress:Y,staticPosition:V});O.push(M)}return $.setPosition(G+32),[O,32]}let W=0,D=[];for(let U=0;U<X;++U){let[V,O]=h8($,J,{checksumAddress:Y,staticPosition:G+W});W+=O,D.push(V)}return[D,W]}function g9$($){return[zy($.readBytes(32),{size:32}),32]}function y9$($,J,{staticPosition:Q}){let[Y,X]=J.type.split("bytes");if(!X){let W=o0($.readBytes(32));$.setPosition(Q+W);let D=o0($.readBytes(32));if(D===0)return $.setPosition(Q+32),["0x",32];let U=$.readBytes(D);return $.setPosition(Q+32),[n4(U),32]}return[n4($.readBytes(Number.parseInt(X,10),32)),32]}function h9$($,J){let Q=J.type.startsWith("int"),Y=Number.parseInt(J.type.split("int")[1]||"256",10),X=$.readBytes(32);return[Y>48?Ny(X,{signed:Q}):o0(X,{signed:Q}),32]}function u9$($,J,Q){let{checksumAddress:Y,staticPosition:X}=Q,G=J.components.length===0||J.components.some(({name:U})=>!U),W=G?[]:{},D=0;if(HD(J)){let U=o0($.readBytes(QZ)),V=X+U;for(let O=0;O<J.components.length;++O){let N=J.components[O];$.setPosition(V+D);let[M,H]=h8($,N,{checksumAddress:Y,staticPosition:V});D+=H,W[G?O:N?.name]=M}return $.setPosition(X+32),[W,32]}for(let U=0;U<J.components.length;++U){let V=J.components[U],[O,N]=h8($,V,{checksumAddress:Y,staticPosition:X});W[G?U:V?.name]=O,D+=N}return[W,D]}function m9$($,{staticPosition:J}){let Q=o0($.readBytes(32)),Y=J+Q;$.setPosition(Y);let X=o0($.readBytes(32));if(X===0)return $.setPosition(J+32),["",32];let G=$.readBytes(X,32),W=My(rB(G));return $.setPosition(J+32),[W,32]}function Au({checksumAddress:$,parameters:J,values:Q}){let Y=[];for(let X=0;X<J.length;X++)Y.push(XZ({checksumAddress:$,parameter:J[X],value:Q[X]}));return Y}function XZ({checksumAddress:$=!1,parameter:J,value:Q}){let Y=J,X=YZ(Y.type);if(X){let[G,W]=X;return n9$(Q,{checksumAddress:$,length:G,parameter:{...Y,type:W}})}if(Y.type==="tuple")return o9$(Q,{checksumAddress:$,parameter:Y});if(Y.type==="address")return l9$(Q,{checksum:$});if(Y.type==="bool")return d9$(Q);if(Y.type.startsWith("uint")||Y.type.startsWith("int")){let G=Y.type.startsWith("int"),[,,W="256"]=Dz.exec(Y.type)??[];return p9$(Q,{signed:G,size:Number(W)})}if(Y.type.startsWith("bytes"))return i9$(Q,{type:Y.type});if(Y.type==="string")return c9$(Q);throw new qD(Y.type)}function Uz($){let J=0;for(let G=0;G<$.length;G++){let{dynamic:W,encoded:D}=$[G];if(W)J+=32;else J+=R4(D)}let Q=[],Y=[],X=0;for(let G=0;G<$.length;G++){let{dynamic:W,encoded:D}=$[G];if(W)Q.push(J4(J+X,{size:32})),Y.push(D),X+=R4(D);else Q.push(D)}return f4(...Q,...Y)}function l9$($,J){let{checksum:Q=!1}=J;return g8($,{strict:Q}),{dynamic:!1,encoded:tJ($.toLowerCase())}}function n9$($,J){let{checksumAddress:Q,length:Y,parameter:X}=J,G=Y===null;if(!Array.isArray($))throw new WZ($);if(!G&&$.length!==Y)throw new GZ({expectedLength:Y,givenLength:$.length,type:`${X.type}[${Y}]`});let W=!1,D=[];for(let U=0;U<$.length;U++){let V=XZ({checksumAddress:Q,parameter:X,value:$[U]});if(V.dynamic)W=!0;D.push(V)}if(G||W){let U=Uz(D);if(G){let V=J4(D.length,{size:32});return{dynamic:!0,encoded:D.length>0?f4(V,U):V}}if(W)return{dynamic:!0,encoded:U}}return{dynamic:!1,encoded:f4(...D.map(({encoded:U})=>U))}}function i9$($,{type:J}){let[,Q]=J.split("bytes"),Y=R4($);if(!Q){let X=$;if(Y%32!==0)X=r0(X,Math.ceil(($.length-2)/2/32)*32);return{dynamic:!0,encoded:f4(tJ(J4(Y,{size:32})),X)}}if(Y!==Number.parseInt(Q,10))throw new Kz({expectedSize:Number.parseInt(Q,10),value:$});return{dynamic:!1,encoded:r0($)}}function d9$($){if(typeof $!=="boolean")throw new D$(`Invalid boolean value: "${$}" (type: ${typeof $}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:tJ(_N($))}}function p9$($,{signed:J,size:Q}){if(typeof Q==="number"){let Y=2n**(BigInt(Q)-(J?1n:0n))-1n,X=J?-Y-1n:0n;if($>Y||$<X)throw new SN({max:Y.toString(),min:X.toString(),signed:J,size:Q/8,value:$.toString()})}return{dynamic:!1,encoded:J4($,{size:32,signed:J})}}function c9$($){let J=M5($),Q=Math.ceil(R4(J)/32),Y=[];for(let X=0;X<Q;X++)Y.push(r0(T4(J,X*32,(X+1)*32)));return{dynamic:!0,encoded:f4(r0(J4(R4(J),{size:32})),...Y)}}function o9$($,J){let{checksumAddress:Q,parameter:Y}=J,X=!1,G=[];for(let W=0;W<Y.components.length;W++){let D=Y.components[W],U=Array.isArray($)?W:D.name,V=XZ({checksumAddress:Q,parameter:D,value:$[U]});if(G.push(V),V.dynamic)X=!0}return{dynamic:X,encoded:X?Uz(G):f4(...G.map(({encoded:W})=>W))}}function YZ($){let J=$.match(/^(.*)\[(\d+)?\]$/);return J?[J[2]?Number(J[2]):null,J[1]]:void 0}function HD($){let{type:J}=$;if(J==="string")return!0;if(J==="bytes")return!0;if(J.endsWith("[]"))return!0;if(J==="tuple")return $.components?.some(HD);let Q=YZ($.type);if(Q&&HD({...$,type:Q[1]}))return!0;return!1}U1();var t9$={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new Lu({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition($){if($<0||$>this.bytes.length-1)throw new Iu({length:this.bytes.length,position:$})},decrementPosition($){if($<0)throw new DZ({offset:$});let J=this.position-$;this.assertPosition(J),this.position=J},getReadCount($){return this.positionReadCount.get($||this.position)||0},incrementPosition($){if($<0)throw new DZ({offset:$});let J=this.position+$;this.assertPosition(J),this.position=J},inspectByte($){let J=$??this.position;return this.assertPosition(J),this.bytes[J]},inspectBytes($,J){let Q=J??this.position;return this.assertPosition(Q+$-1),this.bytes.subarray(Q,Q+$)},inspectUint8($){let J=$??this.position;return this.assertPosition(J),this.bytes[J]},inspectUint16($){let J=$??this.position;return this.assertPosition(J+1),this.dataView.getUint16(J)},inspectUint24($){let J=$??this.position;return this.assertPosition(J+2),(this.dataView.getUint16(J)<<8)+this.dataView.getUint8(J+2)},inspectUint32($){let J=$??this.position;return this.assertPosition(J+3),this.dataView.getUint32(J)},pushByte($){this.assertPosition(this.position),this.bytes[this.position]=$,this.position++},pushBytes($){this.assertPosition(this.position+$.length-1),this.bytes.set($,this.position),this.position+=$.length},pushUint8($){this.assertPosition(this.position),this.bytes[this.position]=$,this.position++},pushUint16($){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,$),this.position+=2},pushUint24($){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,$>>8),this.dataView.setUint8(this.position+2,$&255),this.position+=3},pushUint32($){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,$),this.position+=4},readByte(){this.assertReadLimit(),this._touch();let $=this.inspectByte();return this.position++,$},readBytes($,J){this.assertReadLimit(),this._touch();let Q=this.inspectBytes($);return this.position+=J??$,Q},readUint8(){this.assertReadLimit(),this._touch();let $=this.inspectUint8();return this.position+=1,$},readUint16(){this.assertReadLimit(),this._touch();let $=this.inspectUint16();return this.position+=2,$},readUint24(){this.assertReadLimit(),this._touch();let $=this.inspectUint24();return this.position+=3,$},readUint32(){this.assertReadLimit(),this._touch();let $=this.inspectUint32();return this.position+=4,$},get remaining(){return this.bytes.length-this.position},setPosition($){let J=this.position;return this.assertPosition($),this.position=$,()=>this.position=J},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;let $=this.getReadCount();if(this.positionReadCount.set(this.position,$+1),$>0)this.recursiveReadCount++}};function Vz($,{recursiveReadLimit:J=8192}={}){let Q=Object.create(t9$);return Q.bytes=$,Q.dataView=new DataView($.buffer,$.byteOffset,$.byteLength),Q.positionReadCount=new Map,Q.recursiveReadLimit=J,Q}class DZ extends D${constructor({offset:$}){super(`Offset \`${$}\` cannot be negative.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.NegativeOffsetError"})}}class Iu extends D${constructor({length:$,position:J}){super(`Position \`${J}\` is out of bounds (\`0 < position < ${$}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.PositionOutOfBoundsError"})}}class Lu extends D${constructor({count:$,limit:J}){super(`Recursive read limit of \`${J}\` exceeded (recursive read count: \`${$}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.RecursiveReadLimitExceededError"})}}function x5($,J,Q={}){let{as:Y="Array",checksumAddress:X=!1}=Q,G=typeof J==="string"?N5(J):J,W=Vz(G);if(n1(G)===0&&$.length>0)throw new Zu;if(n1(G)&&n1(G)<32)throw new ju({data:typeof J==="string"?J:n4(J),parameters:$,size:n1(G)});let D=0,U=Y==="Array"?[]:{};for(let V=0;V<$.length;++V){let O=$[V];W.setPosition(D);let[N,M]=h8(W,O,{checksumAddress:X,staticPosition:0});if(D+=M,Y==="Array")U.push(N);else U[O.name??V]=N}return U}function wX($,J,Q){let{checksumAddress:Y=!1}=Q??{};if($.length!==J.length)throw new KZ({expectedLength:$.length,givenLength:J.length});let X=Au({checksumAddress:Y,parameters:$,values:J}),G=Uz(X);if(G.length===0)return"0x";return G}function UZ($,J){if($.length!==J.length)throw new KZ({expectedLength:$.length,givenLength:J.length});let Q=[];for(let Y=0;Y<$.length;Y++){let X=$[Y],G=J[Y];Q.push(UZ.encode(X,G))}return f4(...Q)}(function($){function J(Q,Y,X=!1){if(Q==="address"){let U=Y;return g8(U),tJ(U.toLowerCase(),X?32:0)}if(Q==="string")return M5(Y);if(Q==="bytes")return Y;if(Q==="bool")return tJ(_N(Y),X?32:1);let G=Q.match(Dz);if(G){let[U,V,O="256"]=G,N=Number.parseInt(O,10)/8;return J4(Y,{size:X?32:N,signed:V==="int"})}let W=Q.match(Hu);if(W){let[U,V]=W;if(Number.parseInt(V,10)!==(Y.length-2)/2)throw new Kz({expectedSize:Number.parseInt(V,10),value:Y});return r0(Y,X?32:0)}let D=Q.match(Mu);if(D&&Array.isArray(Y)){let[U,V]=D,O=[];for(let N=0;N<Y.length;N++)O.push(J(V,Y[N],!0));if(O.length===0)return"0x";return f4(...O)}throw new qD(Q)}$.encode=J})(UZ||(UZ={}));function AD($){if(Array.isArray($)&&typeof $[0]==="string")return VN($);if(typeof $==="string")return VN($);return $}class ju extends D${constructor({data:$,parameters:J,size:Q}){super(`Data size of ${Q} bytes is too small for given parameters.`,{metaMessages:[`Params: (${hJ(J)})`,`Data: ${$} (${Q} bytes)`]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.DataSizeTooSmallError"})}}class Zu extends D${constructor(){super('Cannot decode zero data ("0x") with ABI parameters.');Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ZeroDataError"})}}class GZ extends D${constructor({expectedLength:$,givenLength:J,type:Q}){super(`Array length mismatch for type \`${Q}\`. Expected: \`${$}\`. Given: \`${J}\`.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ArrayLengthMismatchError"})}}class Kz extends D${constructor({expectedSize:$,value:J}){super(`Size of bytes "${J}" (bytes${R4(J)}) does not match expected size (bytes${$}).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class KZ extends D${constructor({expectedLength:$,givenLength:J}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${$}`,`Given length (values): ${J}`].join(`
138
138
  `));Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class WZ extends D${constructor($){super(`Value \`${$}\` is not a valid array.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidArrayError"})}}class qD extends D${constructor($){super(`Type \`${$}\` is not a valid ABI Type.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}Q6();function Fu(...$){let[J,Q]=(()=>{if(Array.isArray($[0])){let[G,W]=$;return[a9$(G),W]}return $})(),{bytecode:Y,args:X}=Q;return f4(Y,J.inputs?.length&&X?.length?wX(J.inputs,X):"0x")}function _u($){return Wz($)}function a9$($){let J=$.find((Q)=>Q.type==="constructor");if(!J)throw new y8({name:"constructor"});return J}Q6();function Eu(...$){let[J,Q=[]]=(()=>{if(Array.isArray($[0])){let[V,O,N]=$;return[Su(V,O,{args:N}),N]}let[D,U]=$;return[D,U]})(),{overloads:Y}=J,X=Y?Su([J,...Y],J.name,{args:Q}):J,G=e9$(X),W=Q.length>0?wX(X.inputs,Q):void 0;return W?f4(G,W):G}function u8($,J={}){return Wz($,J)}function Su($,J,Q){let Y=MD($,J,Q);if(Y.type!=="function")throw new y8({name:J,type:"function"});return Y}function e9$($){return $Z($)}var VZ="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",i6="0x0000000000000000000000000000000000000000";b$();W1();var JY$="0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033";async function vu($,J){let{blockNumber:Q,blockTag:Y,calls:X,stateOverrides:G,traceAssetChanges:W,traceTransfers:D,validation:U}=J,V=J.account?E$(J.account):void 0;if(W&&!V)throw new R("`account` is required when `traceAssetChanges` is true");let O=V?Fu(_u("constructor(bytes, bytes)"),{bytecode:vN,args:[JY$,Eu(u8("function getBalance(address)"),[V.address])]}):void 0,N=W?await Promise.all(J.calls.map(async(g)=>{if(!g.data&&!g.abi)return;let{accessList:t}=await fN($,{account:V.address,...g,data:g.abi?L4(g):g.data});return t.map(({address:V$,storageKeys:k$})=>k$.length>0?V$:null)})).then((g)=>g.flat().filter(Boolean)):[],M=await zD($,{blockNumber:Q,blockTag:Y,blocks:[...W?[{calls:[{data:O}],stateOverrides:G},{calls:N.map((g,t)=>({abi:[u8("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[V.address],to:g,from:i6,nonce:t})),stateOverrides:[{address:i6,nonce:0}]}]:[],{calls:[...X,{to:i6}].map((g)=>({...g,from:V?.address})),stateOverrides:G},...W?[{calls:[{data:O}]},{calls:N.map((g,t)=>({abi:[u8("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[V.address],to:g,from:i6,nonce:t})),stateOverrides:[{address:i6,nonce:0}]},{calls:N.map((g,t)=>({to:g,abi:[u8("function decimals() returns (uint256)")],functionName:"decimals",from:i6,nonce:t})),stateOverrides:[{address:i6,nonce:0}]},{calls:N.map((g,t)=>({to:g,abi:[u8("function tokenURI(uint256) returns (string)")],functionName:"tokenURI",args:[0n],from:i6,nonce:t})),stateOverrides:[{address:i6,nonce:0}]},{calls:N.map((g,t)=>({to:g,abi:[u8("function symbol() returns (string)")],functionName:"symbol",from:i6,nonce:t})),stateOverrides:[{address:i6,nonce:0}]}]:[]],traceTransfers:D,validation:U}),H=W?M[2]:M[0],[w,I,,j,L,S,B,Z]=W?M:[],{calls:_,...P}=H,x=_.slice(0,-1)??[],h=w?.calls??[],p=I?.calls??[],b=[...h,...p].map((g)=>g.status==="success"?y4(g.data):null),Q$=j?.calls??[],s=L?.calls??[],K$=[...Q$,...s].map((g)=>g.status==="success"?y4(g.data):null),y=(S?.calls??[]).map((g)=>g.status==="success"?g.result:null),T=(Z?.calls??[]).map((g)=>g.status==="success"?g.result:null),m=(B?.calls??[]).map((g)=>g.status==="success"?g.result:null),c=[];for(let[g,t]of K$.entries()){let V$=b[g];if(typeof t!=="bigint")continue;if(typeof V$!=="bigint")continue;let k$=y[g-1],T$=T[g-1],A6=m[g-1],$4=(()=>{if(g===0)return{address:VZ,decimals:18,symbol:"ETH"};return{address:N[g-1],decimals:A6||k$?Number(k$??1):void 0,symbol:T$??void 0}})();if(c.some((W4)=>W4.token.address===$4.address))continue;c.push({token:$4,value:{pre:V$,post:t,diff:t-V$}})}return{assetChanges:c,block:P,results:x}}mJ();W1();P8();async function Pu($,J){let{abi:Q,address:Y,args:X,functionName:G,dataSuffix:W=typeof $.dataSuffix==="string"?$.dataSuffix:$.dataSuffix?.value,...D}=J,U=D.account?E$(D.account):$.account,V=L4({abi:Q,args:X,functionName:G});try{let{data:O}=await d($,d1,"call")({batch:!1,data:`${V}${W?W.replace("0x",""):""}`,to:Y,...D,account:U}),N=Z6({abi:Q,args:X,functionName:G,data:O||"0x"}),M=Q.filter((H)=>("name"in H)&&H.name===J.functionName);return{result:N,request:{abi:M,address:Y,args:X,dataSuffix:W,functionName:G,...D,account:U}}}catch(O){throw B1(O,{abi:Q,address:Y,args:X,docsPath:"/docs/contract/simulateContract",functionName:G,sender:U?.address})}}async function AX($,{filter:J}){return J.request({method:"eth_uninstallFilter",params:[J.id]})}var ID={};p6(ID,{wrap:()=>GY$,validate:()=>WY$,unwrap:()=>Ru,universalSignatureValidatorBytecode:()=>QY$,universalSignatureValidatorAbi:()=>XY$,magicBytes:()=>OZ,from:()=>YY$,assert:()=>NZ,InvalidWrappedSignatureError:()=>zZ});U1();Q6();var OZ="0x6492649264926492649264926492649264926492649264926492649264926492",QY$="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572",XY$=[{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function",name:"isValidSig"}];function NZ($){if(T4($,-32)!==OZ)throw new zZ($)}function YY$($){if(typeof $==="string")return Ru($);return $}function Ru($){NZ($);let[J,Q,Y]=x5(AD("address, bytes, bytes"),$);return{data:Q,signature:Y,to:J}}function GY$($){let{data:J,signature:Q,to:Y}=$;return f4(wX(AD("address, bytes, bytes"),[Y,J,Q]),OZ)}function WY$($){try{return NZ($),!0}catch{return!1}}class zZ extends D${constructor($){super(`Value \`${$}\` is an invalid ERC-6492 wrapped signature.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc6492.InvalidWrappedSignatureError"})}}var LD={};p6(LD,{wrap:()=>BY$,validate:()=>jY$,unwrap:()=>iu,suffixParameters:()=>IZ,magicBytes:()=>AZ,from:()=>LY$,assert:()=>zz,InvalidWrappedSignatureError:()=>LZ});Q6();YX();U1();Q6();function DY$($,J){let{as:Q}=J,Y=Cu($),X=Vz(new Uint8Array(Y.length));if(Y.encode(X),Q==="Hex")return n4(X.bytes);return X.bytes}function Tu($,J={}){let{as:Q="Hex"}=J;return DY$($,{as:Q})}function Cu($){if(Array.isArray($))return UY$($.map((J)=>Cu(J)));return KY$($)}function UY$($){let J=$.reduce((X,G)=>X+G.length,0),Q=ku(J);return{length:(()=>{if(J<=55)return 1+J;return 1+Q+J})(),encode(X){if(J<=55)X.pushByte(192+J);else if(X.pushByte(247+Q),Q===1)X.pushUint8(J);else if(Q===2)X.pushUint16(J);else if(Q===3)X.pushUint24(J);else X.pushUint32(J);for(let{encode:G}of $)G(X)}}}function KY$($){let J=typeof $==="string"?N5($):$,Q=ku(J.length);return{length:(()=>{if(J.length===1&&J[0]<128)return 1;if(J.length<=55)return 1+J.length;return 1+Q+J.length})(),encode(X){if(J.length===1&&J[0]<128)X.pushBytes(J);else if(J.length<=55)X.pushByte(128+J.length),X.pushBytes(J);else{if(X.pushByte(183+Q),Q===1)X.pushUint8(J.length);else if(Q===2)X.pushUint16(J.length);else if(Q===3)X.pushUint24(J.length);else X.pushUint32(J.length);X.pushBytes(J)}}}}function ku($){if($<=255)return 1;if($<=65535)return 2;if($<=16777215)return 3;if($<=4294967295)return 4;throw new D$("Length is too large.")}U1();Q6();function MZ($,J={}){let{recovered:Q}=J;if(typeof $.r>"u")throw new Oz({signature:$});if(typeof $.s>"u")throw new Oz({signature:$});if(Q&&typeof $.yParity>"u")throw new Oz({signature:$});if($.r<0n||$.r>JZ)throw new gu({value:$.r});if($.s<0n||$.s>JZ)throw new yu({value:$.s});if(typeof $.yParity==="number"&&$.yParity!==0&&$.yParity!==1)throw new Nz({value:$.yParity})}function OY$($){return xu(n4($))}function xu($){if($.length!==130&&$.length!==132)throw new bu({signature:$});let J=BigInt(T4($,0,32)),Q=BigInt(T4($,32,64)),Y=(()=>{let X=Number(`0x${$.slice(130)}`);if(Number.isNaN(X))return;try{return wZ(X)}catch{throw new Nz({value:X})}})();if(typeof Y>"u")return{r:J,s:Q};return{r:J,s:Q,yParity:Y}}function HZ($){if(typeof $.r>"u")return;if(typeof $.s>"u")return;return qZ($)}function qZ($){let J=(()=>{if(typeof $==="string")return xu($);if($ instanceof Uint8Array)return OY$($);if(typeof $.r==="string")return zY$($);if($.v)return NY$($);return{r:$.r,s:$.s,...typeof $.yParity<"u"?{yParity:$.yParity}:{}}})();return MZ(J),J}function NY$($){return{r:$.r,s:$.s,yParity:wZ($.v)}}function zY$($){let J=(()=>{let Q=$.v?Number($.v):void 0,Y=$.yParity?Number($.yParity):void 0;if(typeof Q==="number"&&typeof Y!=="number")Y=wZ(Q);if(typeof Y!=="number")throw new Nz({value:$.yParity});return Y})();return{r:BigInt($.r),s:BigInt($.s),yParity:J}}function fu($){let{r:J,s:Q,yParity:Y}=$;return[Y?"0x01":"0x",J===0n?"0x":eB(J4(J)),Q===0n?"0x":eB(J4(Q))]}function wZ($){if($===0||$===27)return 0;if($===1||$===28)return 1;if($>=35)return $%2===0?1:0;throw new hu({value:$})}class bu extends D${constructor({signature:$}){super(`Value \`${$}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${R4(z5($))} bytes.`]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class Oz extends D${constructor({signature:$}){super(`Signature \`${GX($)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}}class gu extends D${constructor({value:$}){super(`Value \`${$}\` is an invalid r value. r must be a positive integer less than 2^256.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidRError"})}}class yu extends D${constructor({value:$}){super(`Value \`${$}\` is an invalid s value. s must be a positive integer less than 2^256.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSError"})}}class Nz extends D${constructor({value:$}){super(`Value \`${$}\` is an invalid y-parity value. Y-parity must be 0 or 1.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}}class hu extends D${constructor({value:$}){super(`Value \`${$}\` is an invalid v value. v must be 27, 28 or >=35.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}function mu($,J={}){if(typeof $.chainId==="string")return MY$($);return{...$,...J.signature}}function MY$($){let{address:J,chainId:Q,nonce:Y}=$,X=HZ($);return{address:J,chainId:Number(Q),nonce:BigInt(Y),...X}}function lu($){return HY$($,{presign:!0})}function HY$($,J={}){let{presign:Q}=J;return b8(f4("0x05",Tu(qY$(Q?{address:$.address,chainId:$.chainId,nonce:$.nonce}:$))))}function qY$($){let{address:J,chainId:Q,nonce:Y}=$,X=HZ($);return[Q?J4(Q):"0x",J,Y?J4(Y):"0x",...X?fu(X):[]]}U1();Q6();B5();Q6();function nu($){return Ku(AY$($))}function AY$($){let{payload:J,signature:Q}=$,{r:Y,s:X,yParity:G}=Q,D=new _1.Signature(BigInt(Y),BigInt(X)).addRecoveryBit(G).recoverPublicKey(z5(J).substring(2));return Qu(D)}var AZ="0x8010801080108010801080108010801080108010801080108010801080108010",IZ=AD("(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data");function zz($){if(typeof $==="string"){if(T4($,-32)!==AZ)throw new LZ($)}else MZ($.authorization)}function LY$($){if(typeof $==="string")return iu($);return $}function iu($){zz($);let J=FN(T4($,-64,-32)),Q=T4($,-J-64,-64),Y=T4($,0,-J-64),[X,G,W]=x5(IZ,Q);return{authorization:mu({address:X.delegation,chainId:Number(X.chainId),nonce:X.nonce,yParity:X.yParity,r:X.r,s:X.s}),signature:Y,...W&&W!=="0x"?{data:W,to:G}:{}}}function BY$($){let{data:J,signature:Q}=$;zz($);let Y=nu({payload:lu($.authorization),signature:qZ($.authorization)}),X=wX(IZ,[{...$.authorization,delegation:$.authorization.address,chainId:BigInt($.authorization.chainId)},$.to??Y,J??"0x"]),G=J4(R4(X),{size:32});return f4(Q,X,G,AZ)}function jY$($){try{return zz($),!0}catch{return!1}}class LZ extends D${constructor($){super(`Value \`${$}\` is an invalid ERC-8010 wrapped signature.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc8010.InvalidWrappedSignatureError"})}}u0();$X();PN();W1();xJ();v8();xJ();v8();async function du({address:$,authorization:J,signature:Q}){return Z1(fJ($),await MX({authorization:J,signature:Q}))}$6();A$();B5();$6();J6();function Mz({r:$,s:J,to:Q="hex",v:Y,yParity:X}){let G=(()=>{if(X===0||X===1)return X;if(Y&&(Y===27n||Y===28n||Y>=35n))return Y%2n===0n?1:0;throw Error("Invalid `v` or `yParity` value")})(),W=`0x${new _1.Signature(y4($),y4(J)).toCompactHex()}${G===0?"1b":"1c"}`;if(Q==="hex")return W;return r4(W)}P8();async function LX($,J){let{address:Q,chain:Y=$.chain,hash:X,erc6492VerifierAddress:G=J.universalSignatureVerifierAddress??Y?.contracts?.erc6492Verifier?.address,multicallAddress:W=J.multicallAddress??Y?.contracts?.multicall3?.address,mode:D="auto"}=J;if(Y?.verifyHash)return await Y.verifyHash($,J);let U=(()=>{let V=J.signature;if(C4(V))return V;if(typeof V==="object"&&"r"in V&&"s"in V)return Mz(V);return e$(V)})();try{if(D==="eoa")try{if(Z1(fJ(Q),await UD({hash:X,signature:U})))return!0}catch{}if(LD.validate(U))return await ZY$($,{...J,multicallAddress:W,signature:U});return await FY$($,{...J,verifierAddress:G,signature:U})}catch(V){if(D!=="eoa")try{if(Z1(fJ(Q),await UD({hash:X,signature:U})))return!0}catch{}if(V instanceof IX)return!1;throw V}}async function ZY$($,J){let{address:Q,blockNumber:Y,blockTag:X,hash:G,multicallAddress:W}=J,{authorization:D,data:U,signature:V,to:O}=LD.unwrap(J.signature);if(await x8($,{address:Q,blockNumber:Y,blockTag:X})===j6(["0xef0100",D.address]))return await _Y$($,{address:Q,blockNumber:Y,blockTag:X,hash:G,signature:V});let M={address:D.address,chainId:Number(D.chainId),nonce:Number(D.nonce),r:u(D.r,{size:32}),s:u(D.s,{size:32}),yParity:D.yParity};if(!await du({address:Q,authorization:M}))throw new IX;let w=await d($,p4,"readContract")({...W?{address:W}:{code:H5},authorizationList:[M],abi:O0,blockNumber:Y,blockTag:"pending",functionName:"aggregate3",args:[[...U?[{allowFailure:!0,target:O??Q,callData:U}]:[],{allowFailure:!0,target:Q,callData:L4({abi:z2,functionName:"isValidSignature",args:[G,V]})}]]});if(w[w.length-1]?.returnData?.startsWith("0x1626ba7e"))return!0;throw new IX}async function FY$($,J){let{address:Q,factory:Y,factoryData:X,hash:G,signature:W,verifierAddress:D,...U}=J,V=await(async()=>{if(!Y&&!X)return W;if(ID.validate(W))return W;return ID.wrap({data:X,signature:W,to:Y})})(),O=D?{to:D,data:L4({abi:AW,functionName:"isValidSig",args:[Q,G,V]}),...U}:{data:E8({abi:AW,args:[Q,G,V],bytecode:jy}),...U},{data:N}=await d($,d1,"call")(O).catch((M)=>{if(M instanceof gW)throw new IX;throw M});if(C2(N??"0x0"))return!0;throw new IX}async function _Y$($,J){let{address:Q,blockNumber:Y,blockTag:X,hash:G,signature:W}=J;if((await d($,p4,"readContract")({address:Q,abi:z2,args:[G,W],blockNumber:Y,blockTag:X,functionName:"isValidSignature"}).catch((U)=>{if(U instanceof yW)throw new IX;throw U})).startsWith("0x1626ba7e"))return!0;throw new IX}class IX extends Error{}y1();var pu=`\x19Ethereum Signed Message:
139
139
  `;A1();A$();function cu($){let J=(()=>{if(typeof $==="string")return rQ($);if(typeof $.raw==="string")return $.raw;return e$($.raw)})(),Q=rQ(`${pu}${p$(J)}`);return Z4([Q,J])}function f5($,J){return V4(cu($),J)}async function ou($,{address:J,message:Q,factory:Y,factoryData:X,signature:G,...W}){let D=f5(Q);return d($,LX,"verifyHash")({address:J,factory:Y,factoryData:X,hash:D,signature:G,...W})}gJ();A$();y1();l4();l0();b$();class BZ extends R{constructor({domain:$}){super(`Invalid domain "${c$($)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class jZ extends R{constructor({primaryType:$,types:J}){super(`Invalid primary type \`${$}\` must be one of \`${JSON.stringify(Object.keys(J))}\`.`,{docsPath:"/api/glossary/Errors#typeddatainvalidprimarytypeerror",metaMessages:["Check that the primary type is a key in `types`."]})}}class ZZ extends R{constructor({type:$}){super(`Struct type "${$}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}h1();A1();A$();l2();function ru($){let{domain:J,message:Q,primaryType:Y,types:X}=$,G=(U,V)=>{let O={...V};for(let N of U){let{name:M,type:H}=N;if(H==="address")O[M]=O[M].toLowerCase()}return O},W=(()=>{if(!X.EIP712Domain)return{};if(!J)return{};return G(X.EIP712Domain,J)})(),D=(()=>{if(Y==="EIP712Domain")return;return G(X[Y],Q)})();return c$({domain:W,message:D,primaryType:Y,types:X})}function Hz($){let{domain:J,message:Q,primaryType:Y,types:X}=$,G=(W,D)=>{for(let U of W){let{name:V,type:O}=U,N=D[V],M=O.match(e3);if(M&&(typeof N==="number"||typeof N==="bigint")){let[I,j,L]=M;u(N,{signed:j==="int",size:Number.parseInt(L,10)/8})}if(O==="address"&&typeof N==="string"&&!X4(N))throw new _4({address:N});let H=O.match(ub);if(H){let[I,j]=H;if(j&&p$(N)!==Number.parseInt(j,10))throw new S2({expectedSize:Number.parseInt(j,10),givenSize:p$(N)})}let w=X[O];if(w)SY$(O),G(w,N)}};if(X.EIP712Domain&&J){if(typeof J!=="object")throw new BZ({domain:J});G(X.EIP712Domain,J)}if(Y!=="EIP712Domain")if(X[Y])G(X[Y],Q);else throw new jZ({primaryType:Y,types:X})}function qz({domain:$}){return[typeof $?.name==="string"&&{name:"name",type:"string"},$?.version&&{name:"version",type:"string"},(typeof $?.chainId==="number"||typeof $?.chainId==="bigint")&&{name:"chainId",type:"uint256"},$?.verifyingContract&&{name:"verifyingContract",type:"address"},$?.salt&&{name:"salt",type:"bytes32"}].filter(Boolean)}function SY$($){if($==="address"||$==="bool"||$==="string"||$.startsWith("bytes")||$.startsWith("uint")||$.startsWith("int"))throw new ZZ({type:$})}function wz($){let{domain:J={},message:Q,primaryType:Y}=$,X={EIP712Domain:qz({domain:J}),...$.types};Hz({domain:J,message:Q,primaryType:Y,types:X});let G=["0x1901"];if(J)G.push(EY$({domain:J,types:X}));if(Y!=="EIP712Domain")G.push(tu({data:Q,primaryType:Y,types:X}));return V4(Z4(G))}function EY$({domain:$,types:J}){return tu({data:$,primaryType:"EIP712Domain",types:J})}function tu({data:$,primaryType:J,types:Q}){let Y=au({data:$,primaryType:J,types:Q});return V4(Y)}function au({data:$,primaryType:J,types:Q}){let Y=[{type:"bytes32"}],X=[vY$({primaryType:J,types:Q})];for(let G of Q[J]){let[W,D]=eu({types:Q,name:G.name,type:G.type,value:$[G.name]});Y.push(W),X.push(D)}return h6(Y,X)}function vY$({primaryType:$,types:J}){let Q=x4(PY$({primaryType:$,types:J}));return V4(Q)}function PY$({primaryType:$,types:J}){let Q="",Y=su({primaryType:$,types:J});Y.delete($);let X=[$,...Array.from(Y).sort()];for(let G of X)Q+=`${G}(${J[G].map(({name:W,type:D})=>`${D} ${W}`).join(",")})`;return Q}function su({primaryType:$,types:J},Q=new Set){let X=$.match(/^\w*/u)?.[0];if(Q.has(X)||J[X]===void 0)return Q;Q.add(X);for(let G of J[X])su({primaryType:G.type,types:J},Q);return Q}function eu({types:$,name:J,type:Q,value:Y}){if($[Q]!==void 0)return[{type:"bytes32"},V4(au({data:Y,primaryType:Q,types:$}))];if(Q==="bytes")return[{type:"bytes32"},V4(Y)];if(Q==="string")return[{type:"bytes32"},V4(x4(Y))];if(Q.lastIndexOf("]")===Q.length-1){let X=Q.slice(0,Q.lastIndexOf("[")),G=Y.map((W)=>eu({name:J,type:X,types:$,value:W}));return[{type:"bytes32"},V4(h6(G.map(([W])=>W),G.map(([,W])=>W)))]}return[{type:Q},Y]}async function $m($,J){let{address:Q,factory:Y,factoryData:X,signature:G,message:W,primaryType:D,types:U,domain:V,...O}=J,N=wz({message:W,primaryType:D,types:U,domain:V});return d($,LX,"verifyHash")({address:Q,factory:Y,factoryData:X,hash:N,signature:G,...O})}m1();var FZ=new Map,Jm=new Map,RY$=0;function E6($,J,Q){let Y=++RY$,X=()=>FZ.get($)||[],G=()=>{let O=X();FZ.set($,O.filter((N)=>N.id!==Y))},W=()=>{let O=X();if(!O.some((M)=>M.id===Y))return;let N=Jm.get($);if(O.length===1&&N){let M=N();if(M instanceof Promise)M.catch(()=>{})}G()},D=X();if(FZ.set($,[...D,{id:Y,fns:J}]),D&&D.length>0)return W;let U={};for(let O in J)U[O]=(...N)=>{let M=X();if(M.length===0)return;for(let H of M)H.fns[O]?.(...N)};let V=Q(U);if(typeof V==="function")Jm.set($,V);return W}async function BD($){return new Promise((J)=>setTimeout(J,$))}function m8($,{delay:J=100,retryCount:Q=2,shouldRetry:Y=()=>!0}={}){return new Promise((X,G)=>{let W=async({count:D=0}={})=>{let U=async({error:V})=>{let O=typeof J==="function"?J({count:D,error:V}):J;if(O)await BD(O);W({count:D+1})};try{let V=await $();X(V)}catch(V){if(D<Q&&await Y({count:D,error:V}))return U({error:V});G(V)}};W()})}$6();function p1($,{emitOnBegin:J,initialWaitTime:Q,interval:Y}){let X=!0,G=()=>X=!1;return(async()=>{let D;if(J)D=await $({unpoll:G});let U=await Q?.(D)??Y;await BD(U);let V=async()=>{if(!X)return;await $({unpoll:G}),await BD(Y),V()};V()})(),G}function Az($,{emitOnBegin:J=!1,emitMissed:Q=!1,onBlockNumber:Y,onError:X,poll:G,pollingInterval:W=$.pollingInterval}){let D=(()=>{if(typeof G<"u")return G;if($.transport.type==="webSocket"||$.transport.type==="ipc")return!1;if($.transport.type==="fallback"&&($.transport.transports[0].config.type==="webSocket"||$.transport.transports[0].config.type==="ipc"))return!1;return!0})(),U;return D?(()=>{let N=c$(["watchBlockNumber",$.uid,J,Q,W]);return E6(N,{onBlockNumber:Y,onError:X},(M)=>p1(async()=>{try{let H=await d($,e0,"getBlockNumber")({cacheTime:0});if(U!==void 0){if(H===U)return;if(H-U>1&&Q)for(let w=U+1n;w<H;w++)M.onBlockNumber(w,U),U=w}if(U===void 0||H>U)M.onBlockNumber(H,U),U=H}catch(H){M.onError?.(H)}},{emitOnBegin:J,interval:W}))})():(()=>{let N=c$(["watchBlockNumber",$.uid,J,Q]);return E6(N,{onBlockNumber:Y,onError:X},(M)=>{let H=!0,w=()=>H=!1;return(async()=>{try{let I=(()=>{if($.transport.type==="fallback"){let L=$.transport.transports.find((S)=>S.config.type==="webSocket"||S.config.type==="ipc");if(!L)return $.transport;return L.value}return $.transport})(),{unsubscribe:j}=await I.subscribe({params:["newHeads"],onData(L){if(!H)return;let S=y4(L.result?.number);M.onBlockNumber(S,U),U=S},onError(L){M.onError?.(L)}});if(w=j,!H)w()}catch(I){X?.(I)}})(),()=>w()})})()}async function Iz($,J){let{checkReplacement:Q=!0,confirmations:Y=1,hash:X,onReplaced:G,retryCount:W=6,retryDelay:D=({count:_})=>~~(1<<_)*200,timeout:U=180000}=J,V=c$(["waitForTransactionReceipt",$.uid,X]),O=(()=>{if(J.pollingInterval)return J.pollingInterval;if($.chain?.experimental_preconfirmationTime)return $.chain.experimental_preconfirmationTime;return $.pollingInterval})(),N,M,H,w=!1,I,j,{promise:L,resolve:S,reject:B}=q5(),Z=U?setTimeout(()=>{j?.(),I?.(),B(new SB({hash:X}))},U):void 0;return I=E6(V,{onReplaced:G,resolve:S,reject:B},async(_)=>{if(H=await d($,C5,"getTransactionReceipt")({hash:X}).catch(()=>{return}),H&&Y<=1){clearTimeout(Z),_.resolve(H),I?.();return}j=d($,Az,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:O,async onBlockNumber(P){let x=(p)=>{clearTimeout(Z),j?.(),p(),I?.()},h=P;if(w)return;try{if(H){if(Y>1&&(!H.blockNumber||h-H.blockNumber+1n<Y))return;x(()=>_.resolve(H));return}if(Q&&!N)w=!0,await m8(async()=>{if(N=await d($,T5,"getTransaction")({hash:X}),N.blockNumber)h=N.blockNumber},{delay:D,retryCount:W}),w=!1;if(H=await d($,C5,"getTransactionReceipt")({hash:X}),Y>1&&(!H.blockNumber||h-H.blockNumber+1n<Y))return;x(()=>_.resolve(H))}catch(p){if(p instanceof xW||p instanceof fW){if(!N){w=!1;return}try{M=N,w=!0;let b=await m8(()=>d($,Y6,"getBlock")({blockNumber:h,includeTransactions:!0}),{delay:D,retryCount:W,shouldRetry:({error:K$})=>K$ instanceof VD});w=!1;let Q$=b.transactions.find(({from:K$,nonce:y})=>K$===M.from&&y===M.nonce);if(!Q$)return;if(H=await d($,C5,"getTransactionReceipt")({hash:Q$.hash}),Y>1&&(!H.blockNumber||h-H.blockNumber+1n<Y))return;let s="replaced";if(Q$.to===M.to&&Q$.value===M.value&&Q$.input===M.input)s="repriced";else if(Q$.from===Q$.to&&Q$.value===0n)s="cancelled";x(()=>{_.onReplaced?.({reason:s,replacedTransaction:M,transaction:Q$,transactionReceipt:H}),_.resolve(H)})}catch(b){x(()=>_.reject(b))}}else x(()=>_.reject(p))}}})}),L}function Qm($,{blockTag:J=$.experimental_blockTag??"latest",emitMissed:Q=!1,emitOnBegin:Y=!1,onBlock:X,onError:G,includeTransactions:W,poll:D,pollingInterval:U=$.pollingInterval}){let V=(()=>{if(typeof D<"u")return D;if($.transport.type==="webSocket"||$.transport.type==="ipc")return!1;if($.transport.type==="fallback"&&($.transport.transports[0].config.type==="webSocket"||$.transport.transports[0].config.type==="ipc"))return!1;return!0})(),O=W??!1,N;return V?(()=>{let w=c$(["watchBlocks",$.uid,J,Q,Y,O,U]);return E6(w,{onBlock:X,onError:G},(I)=>p1(async()=>{try{let j=await d($,Y6,"getBlock")({blockTag:J,includeTransactions:O});if(j.number!==null&&N?.number!=null){if(j.number===N.number)return;if(j.number-N.number>1&&Q)for(let L=N?.number+1n;L<j.number;L++){let S=await d($,Y6,"getBlock")({blockNumber:L,includeTransactions:O});I.onBlock(S,N),N=S}}if(N?.number==null||J==="pending"&&j?.number==null||j.number!==null&&j.number>N.number)I.onBlock(j,N),N=j}catch(j){I.onError?.(j)}},{emitOnBegin:Y,interval:U}))})():(()=>{let w=!0,I=!0,j=()=>w=!1;return(async()=>{try{if(Y)d($,Y6,"getBlock")({blockTag:J,includeTransactions:O}).then((B)=>{if(!w)return;if(!I)return;X(B,void 0),I=!1}).catch(G);let L=(()=>{if($.transport.type==="fallback"){let B=$.transport.transports.find((Z)=>Z.config.type==="webSocket"||Z.config.type==="ipc");if(!B)return $.transport;return B.value}return $.transport})(),{unsubscribe:S}=await L.subscribe({params:["newHeads"],async onData(B){if(!w)return;let Z=await d($,Y6,"getBlock")({blockNumber:B.result?.number,includeTransactions:O}).catch(()=>{});if(!w)return;X(Z,N),I=!1,N=Z},onError(B){G?.(B)}});if(j=S,!w)j()}catch(L){G?.(L)}})(),()=>j()})()}l4();G5();function Xm($,J){let{abi:Q,address:Y,args:X,batch:G=!0,eventName:W,fromBlock:D,onError:U,onLogs:V,poll:O,pollingInterval:N=$.pollingInterval,strict:M}=J;return(()=>{if(typeof O<"u")return O;if(typeof D==="bigint")return!0;if($.transport.type==="webSocket"||$.transport.type==="ipc")return!1;if($.transport.type==="fallback"&&($.transport.transports[0].config.type==="webSocket"||$.transport.transports[0].config.type==="ipc"))return!1;return!0})()?(()=>{let j=M??!1,L=c$(["watchContractEvent",Y,X,G,$.uid,W,N,j,D]);return E6(L,{onLogs:V,onError:U},(S)=>{let B;if(D!==void 0)B=D-1n;let Z,_=!1,P=p1(async()=>{if(!_){try{Z=await d($,bN,"createContractEventFilter")({abi:Q,address:Y,args:X,eventName:W,strict:j,fromBlock:D})}catch{}_=!0;return}try{let x;if(Z)x=await d($,qX,"getFilterChanges")({filter:Z});else{let h=await d($,e0,"getBlockNumber")({});if(B&&B<h)x=await d($,sN,"getContractEvents")({abi:Q,address:Y,args:X,eventName:W,fromBlock:B+1n,toBlock:h,strict:j});else x=[];B=h}if(x.length===0)return;if(G)S.onLogs(x);else for(let h of x)S.onLogs([h])}catch(x){if(Z&&x instanceof l1)_=!1;S.onError?.(x)}},{emitOnBegin:!0,interval:N});return async()=>{if(Z)await d($,AX,"uninstallFilter")({filter:Z});P()}})})():(()=>{let j=M??!1,L=c$(["watchContractEvent",Y,X,G,$.uid,W,N,j]),S=!0,B=()=>S=!1;return E6(L,{onLogs:V,onError:U},(Z)=>{return(async()=>{try{let _=(()=>{if($.transport.type==="fallback"){let h=$.transport.transports.find((p)=>p.config.type==="webSocket"||p.config.type==="ipc");if(!h)return $.transport;return h.value}return $.transport})(),P=W?a0({abi:Q,eventName:W,args:X}):[],{unsubscribe:x}=await _.subscribe({params:["logs",{address:Y,topics:P}],onData(h){if(!S)return;let p=h.result;try{let{eventName:b,args:Q$}=f8({abi:Q,data:p.data,topics:p.topics,strict:M}),s=G6(p,{args:Q$,eventName:b});Z.onLogs([s])}catch(b){let Q$,s;if(b instanceof cQ||b instanceof K8){if(M)return;Q$=b.abiItem.name,s=b.abiItem.inputs?.some((y)=>!(("name"in y)&&y.name))}let K$=G6(p,{args:s?[]:{},eventName:Q$});Z.onLogs([K$])}},onError(h){Z.onError?.(h)}});if(B=x,!S)B()}catch(_){U?.(_)}})(),()=>B()})})()}l4();G5();function Ym($,{address:J,args:Q,batch:Y=!0,event:X,events:G,fromBlock:W,onError:D,onLogs:U,poll:V,pollingInterval:O=$.pollingInterval,strict:N}){let M=(()=>{if(typeof V<"u")return V;if(typeof W==="bigint")return!0;if($.transport.type==="webSocket"||$.transport.type==="ipc")return!1;if($.transport.type==="fallback"&&($.transport.transports[0].config.type==="webSocket"||$.transport.transports[0].config.type==="ipc"))return!1;return!0})(),H=N??!1;return M?(()=>{let j=c$(["watchEvent",J,Q,Y,$.uid,X,O,W]);return E6(j,{onLogs:U,onError:D},(L)=>{let S;if(W!==void 0)S=W-1n;let B,Z=!1,_=p1(async()=>{if(!Z){try{B=await d($,gN,"createEventFilter")({address:J,args:Q,event:X,events:G,strict:H,fromBlock:W})}catch{}Z=!0;return}try{let P;if(B)P=await d($,qX,"getFilterChanges")({filter:B});else{let x=await d($,e0,"getBlockNumber")({});if(S&&S!==x)P=await d($,R5,"getLogs")({address:J,args:Q,event:X,events:G,fromBlock:S+1n,toBlock:x});else P=[];S=x}if(P.length===0)return;if(Y)L.onLogs(P);else for(let x of P)L.onLogs([x])}catch(P){if(B&&P instanceof l1)Z=!1;L.onError?.(P)}},{emitOnBegin:!0,interval:O});return async()=>{if(B)await d($,AX,"uninstallFilter")({filter:B});_()}})})():(()=>{let j=!0,L=()=>j=!1;return(async()=>{try{let S=(()=>{if($.transport.type==="fallback"){let P=$.transport.transports.find((x)=>x.config.type==="webSocket"||x.config.type==="ipc");if(!P)return $.transport;return P.value}return $.transport})(),B=G??(X?[X]:void 0),Z=[];if(B){if(Z=[B.flatMap((x)=>a0({abi:[x],eventName:x.name,args:Q}))],X)Z=Z[0]}let{unsubscribe:_}=await S.subscribe({params:["logs",{address:J,topics:Z}],onData(P){if(!j)return;let x=P.result;try{let{eventName:h,args:p}=f8({abi:B??[],data:x.data,topics:x.topics,strict:H}),b=G6(x,{args:p,eventName:h});U([b])}catch(h){let p,b;if(h instanceof cQ||h instanceof K8){if(N)return;p=h.abiItem.name,b=h.abiItem.inputs?.some((s)=>!(("name"in s)&&s.name))}let Q$=G6(x,{args:b?[]:{},eventName:p});U([Q$])}},onError(P){D?.(P)}});if(L=_,!j)L()}catch(S){D?.(S)}})(),()=>L()})()}function Gm($,{batch:J=!0,onError:Q,onTransactions:Y,poll:X,pollingInterval:G=$.pollingInterval}){return(typeof X<"u"?X:$.transport.type!=="webSocket"&&$.transport.type!=="ipc")?(()=>{let V=c$(["watchPendingTransactions",$.uid,J,G]);return E6(V,{onTransactions:Y,onError:Q},(O)=>{let N,M=p1(async()=>{try{if(!N)try{N=await d($,yN,"createPendingTransactionFilter")({});return}catch(w){throw M(),w}let H=await d($,qX,"getFilterChanges")({filter:N});if(H.length===0)return;if(J)O.onTransactions(H);else for(let w of H)O.onTransactions([w])}catch(H){O.onError?.(H)}},{emitOnBegin:!0,interval:G});return async()=>{if(N)await d($,AX,"uninstallFilter")({filter:N});M()}})})():(()=>{let V=!0,O=()=>V=!1;return(async()=>{try{let{unsubscribe:N}=await $.transport.subscribe({params:["newPendingTransactions"],onData(M){if(!V)return;let H=M.result;Y([H])},onError(M){Q?.(M)}});if(O=N,!V)O()}catch(N){Q?.(N)}})(),()=>O()})()}function Wm($){let{scheme:J,statement:Q,...Y}=$.match(TY$)?.groups??{},{chainId:X,expirationTime:G,issuedAt:W,notBefore:D,requestId:U,...V}=$.match(CY$)?.groups??{},O=$.split("Resources:")[1]?.split(`
140
140
  - `).slice(1);return{...Y,...V,...X?{chainId:Number(X)}:{},...G?{expirationTime:new Date(G)}:{},...W?{issuedAt:new Date(W)}:{},...D?{notBefore:new Date(D)}:{},...U?{requestId:U}:{},...O?{resources:O}:{},...J?{scheme:J}:{},...Q?{statement:Q}:{}}}var TY$=/^(?:(?<scheme>[a-zA-Z][a-zA-Z0-9+-.]*):\/\/)?(?<domain>[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\n)(?<address>0x[a-fA-F0-9]{40})\n\n(?:(?<statement>.*)\n\n)?/,CY$=/(?:URI: (?<uri>.+))\n(?:Version: (?<version>.+))\n(?:Chain ID: (?<chainId>\d+))\n(?:Nonce: (?<nonce>[a-zA-Z0-9]+))\n(?:Issued At: (?<issuedAt>.+))(?:\nExpiration Time: (?<expirationTime>.+))?(?:\nNot Before: (?<notBefore>.+))?(?:\nRequest ID: (?<requestId>.+))?/;h1();v8();function Dm($){let{address:J,domain:Q,message:Y,nonce:X,scheme:G,time:W=new Date}=$;if(Q&&Y.domain!==Q)return!1;if(X&&Y.nonce!==X)return!1;if(G&&Y.scheme!==G)return!1;if(Y.expirationTime&&W>=Y.expirationTime)return!1;if(Y.notBefore&&W<Y.notBefore)return!1;try{if(!Y.address)return!1;if(!X4(Y.address,{strict:!1}))return!1;if(J&&!Z1(Y.address,J))return!1}catch{return!1}return!0}async function Um($,J){let{address:Q,domain:Y,message:X,nonce:G,scheme:W,signature:D,time:U=new Date,...V}=J,O=Wm(X);if(!O.address)return!1;if(!Dm({address:Q,domain:Y,message:O,nonce:G,scheme:W,time:U}))return!1;let M=f5(X);return LX($,{address:O.address,hash:M,signature:D,...V})}async function b5($,{serializedTransaction:J}){return $.request({method:"eth_sendRawTransaction",params:[J]},{retryCount:0})}m1();async function g5($,{serializedTransaction:J,throwOnReceiptRevert:Q,timeout:Y}){let X=await $.request({method:"eth_sendRawTransactionSync",params:Y?[J,Y]:[J]},{retryCount:0}),W=($.chain?.formatters?.transactionReceipt?.format||eN)(X);if(W.status==="reverted"&&Q)throw new bW({receipt:W});return W}function Km($){return{call:(J)=>d1($,J),createAccessList:(J)=>fN($,J),createBlockFilter:()=>hy($),createContractEventFilter:(J)=>bN($,J),createEventFilter:(J)=>gN($,J),createPendingTransactionFilter:()=>yN($),estimateContractGas:(J)=>yh($,J),estimateGas:(J)=>v5($,J),getBalance:(J)=>hh($,J),getBlobBaseFee:()=>uh($),getBlock:(J)=>Y6($,J),getBlockNumber:(J)=>e0($,J),getBlockTransactionCount:(J)=>nh($,J),getBytecode:(J)=>x8($,J),getChainId:()=>S6($),getCode:(J)=>x8($,J),getContractEvents:(J)=>sN($,J),getDelegation:(J)=>dh($,J),getEip712Domain:(J)=>ph($,J),getEnsAddress:(J)=>Ry($,J),getEnsAvatar:(J)=>by($,J),getEnsName:(J)=>gy($,J),getEnsResolver:(J)=>yy($,J),getEnsText:(J)=>xN($,J),getFeeHistory:(J)=>oh($,J),estimateFeesPerGas:(J)=>Ph($,J),getFilterChanges:(J)=>qX($,J),getFilterLogs:(J)=>rh($,J),getGasPrice:()=>Z5($),getLogs:(J)=>R5($,J),getProof:(J)=>ah($,J),estimateMaxPriorityFeePerGas:(J)=>vh($,J),fillTransaction:(J)=>E5($,J),getStorageAt:(J)=>sh($,J),getTransaction:(J)=>T5($,J),getTransactionConfirmations:(J)=>eh($,J),getTransactionCount:(J)=>F5($,J),getTransactionReceipt:(J)=>C5($,J),multicall:(J)=>$u($,J),prepareTransactionRequest:(J)=>s0($,J),readContract:(J)=>p4($,J),sendRawTransaction:(J)=>b5($,J),sendRawTransactionSync:(J)=>g5($,J),simulate:(J)=>zD($,J),simulateBlocks:(J)=>zD($,J),simulateCalls:(J)=>vu($,J),simulateContract:(J)=>Pu($,J),verifyHash:(J)=>LX($,J),verifyMessage:(J)=>ou($,J),verifySiweMessage:(J)=>Um($,J),verifyTypedData:(J)=>$m($,J),uninstallFilter:(J)=>AX($,J),waitForTransactionReceipt:(J)=>Iz($,J),watchBlocks:(J)=>Qm($,J),watchBlockNumber:(J)=>Az($,J),watchContractEvent:(J)=>Xm($,J),watchEvent:(J)=>Ym($,J),watchPendingTransactions:(J)=>Gm($,J)}}function _Z($){let{key:J="public",name:Q="Public Client"}=$;return C3({...$,key:J,name:Q,type:"publicClient"}).extend(Km)}A$();async function Vm($,{chain:J}){let{id:Q,name:Y,nativeCurrency:X,rpcUrls:G,blockExplorers:W}=J;await $.request({method:"wallet_addEthereumChain",params:[{chainId:u(Q),chainName:Y,nativeCurrency:X,rpcUrls:G.default.http,blockExplorerUrls:W?Object.values(W).map(({url:D})=>D):void 0}]},{dedupe:!0,retryCount:0})}PN();b$();class w6 extends R{constructor({docsPath:$}={}){super(["Could not find an Account to execute with this Action.","Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."].join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0xmonaco/mcp-server",
3
- "version": "0.8.5",
3
+ "version": "0.8.7",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -25,8 +25,8 @@
25
25
  },
26
26
  "author": "@codebycarson",
27
27
  "dependencies": {
28
- "@0xmonaco/core": "0.8.5",
29
- "@0xmonaco/types": "0.8.5",
28
+ "@0xmonaco/core": "0.8.7",
29
+ "@0xmonaco/types": "0.8.7",
30
30
  "@modelcontextprotocol/sdk": "^1.26.0",
31
31
  "node-fetch": "^3.3.2",
32
32
  "viem": "^2.45.2",