@0xmonaco/mcp-server 1.0.7 → 1.0.15

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 +2 -2
  2. package/package.json +3 -3
package/dist/bin.js CHANGED
@@ -133,7 +133,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
133
133
  `:`[${Y[V]}\r
134
134
  ]`;continue}if(X+=Y[V],Y[V]==="\\")G=!0;else if(W&&Y[V]==="]")W=!1;else if(!W&&Y[V]==="[")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 oN($,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===J$.ZodEnum)return{type:"object",required:$.keyType._def.values,properties:$.keyType._def.values.reduce((Y,X)=>({...Y,[X]:P$($.valueType._def,{...J,currentPath:[...J.currentPath,"properties",X]})??h4(J)}),{}),additionalProperties:J.rejectedAdditionalProperties};let Q={type:"object",additionalProperties:P$($.valueType._def,{...J,currentPath:[...J.currentPath,"additionalProperties"]})??J.allowedAdditionalProperties};if(J.target==="openApi3")return Q;if($.keyType?._def.typeName===J$.ZodString&&$.keyType._def.checks?.length){let{type:Y,...X}=iN($.keyType._def,J);return{...Q,propertyNames:X}}else if($.keyType?._def.typeName===J$.ZodEnum)return{...Q,propertyNames:{enum:$.keyType._def.values}};else if($.keyType?._def.typeName===J$.ZodBranded&&$.keyType._def.type._def.typeName===J$.ZodString&&$.keyType._def.type._def.checks?.length){let{type:Y,...X}=cN($.keyType._def,J);return{...Q,propertyNames:X}}return Q}function ek($,J){if(J.mapStrategy==="record")return oN($,J);let Q=P$($.keyType._def,{...J,currentPath:[...J.currentPath,"items","items","0"]})||h4(J),Y=P$($.valueType._def,{...J,currentPath:[...J.currentPath,"items","items","1"]})||h4(J);return{type:"array",maxItems:125,items:{type:"array",items:[Q,Y],minItems:2,maxItems:2}}}function $x($){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 Jx($){return $.target==="openAi"?void 0:{not:h4({...$,currentPath:[...$.currentPath,"not"]})}}function Qx($){return $.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var _D={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Yx($,J){if(J.target==="openApi3")return Xx($,J);let Q=$.options instanceof Map?Array.from($.options.values()):$.options;if(Q.every((Y)=>(Y._def.typeName in _D)&&(!Y._def.checks||!Y._def.checks.length))){let Y=Q.reduce((X,G)=>{let W=_D[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 Xx($,J)}var Xx=($,J)=>{let Q=($.options instanceof Map?Array.from($.options.values()):$.options).map((Y,X)=>P$(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 Gx($,J){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes($.innerType._def.typeName)&&(!$.innerType._def.checks||!$.innerType._def.checks.length)){if(J.target==="openApi3")return{type:_D[$.innerType._def.typeName],nullable:!0};return{type:[_D[$.innerType._def.typeName],"null"]}}if(J.target==="openApi3"){let Y=P$($.innerType._def,{...J,currentPath:[...J.currentPath]});if(Y&&"$ref"in Y)return{allOf:[Y],nullable:!0};return Y&&{...Y,nullable:!0}}let Q=P$($.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","0"]});return Q&&{anyOf:[Q,{type:"null"}]}}function Wx($,J){let Q={type:"number"};if(!$.checks)return Q;for(let Y of $.checks)switch(Y.kind){case"int":Q.type="integer",CL(Q,"type",Y.message,J);break;case"min":if(J.target==="jsonSchema7")if(Y.inclusive)a$(Q,"minimum",Y.value,Y.message,J);else a$(Q,"exclusiveMinimum",Y.value,Y.message,J);else{if(!Y.inclusive)Q.exclusiveMinimum=!0;a$(Q,"minimum",Y.value,Y.message,J)}break;case"max":if(J.target==="jsonSchema7")if(Y.inclusive)a$(Q,"maximum",Y.value,Y.message,J);else a$(Q,"exclusiveMaximum",Y.value,Y.message,J);else{if(!Y.inclusive)Q.exclusiveMaximum=!0;a$(Q,"maximum",Y.value,Y.message,J)}break;case"multipleOf":a$(Q,"multipleOf",Y.value,Y.message,J);break}return Q}function Dx($,J){let Q=J.target==="openAi",Y={type:"object",properties:{}},X=[],G=$.shape();for(let D in G){let V=G[D];if(V===void 0||V._def===void 0)continue;let K=R0$(V);if(K&&Q){if(V._def.typeName==="ZodOptional")V=V._def.innerType;if(!V.isNullable())V=V.nullable();K=!1}let O=P$(V._def,{...J,currentPath:[...J.currentPath,"properties",D],propertyPath:[...J.currentPath,"properties",D]});if(O===void 0)continue;if(Y.properties[D]=O,!K)X.push(D)}if(X.length)Y.required=X;let W=T0$($,J);if(W!==void 0)Y.additionalProperties=W;return Y}function T0$($,J){if($.catchall._def.typeName!=="ZodNever")return P$($.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 R0$($){try{return $.isOptional()}catch{return!0}}var Vx=($,J)=>{if(J.currentPath.toString()===J.propertyPath?.toString())return P$($.innerType._def,J);let Q=P$($.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","1"]});return Q?{anyOf:[{not:h4(J)},Q]}:h4(J)};var Kx=($,J)=>{if(J.pipeStrategy==="input")return P$($.in._def,J);else if(J.pipeStrategy==="output")return P$($.out._def,J);let Q=P$($.in._def,{...J,currentPath:[...J.currentPath,"allOf","0"]}),Y=P$($.out._def,{...J,currentPath:[...J.currentPath,"allOf",Q?"1":"0"]});return{allOf:[Q,Y].filter((X)=>X!==void 0)}};function Ux($,J){return P$($.type._def,J)}function Ox($,J){let Y={type:"array",uniqueItems:!0,items:P$($.valueType._def,{...J,currentPath:[...J.currentPath,"items"]})};if($.minSize)a$(Y,"minItems",$.minSize.value,$.minSize.message,J);if($.maxSize)a$(Y,"maxItems",$.maxSize.value,$.maxSize.message,J);return Y}function Nx($,J){if($.rest)return{type:"array",minItems:$.items.length,items:$.items.map((Q,Y)=>P$(Q._def,{...J,currentPath:[...J.currentPath,"items",`${Y}`]})).reduce((Q,Y)=>Y===void 0?Q:[...Q,Y],[]),additionalItems:P$($.rest._def,{...J,currentPath:[...J.currentPath,"additionalItems"]})};else return{type:"array",minItems:$.items.length,maxItems:$.items.length,items:$.items.map((Q,Y)=>P$(Q._def,{...J,currentPath:[...J.currentPath,"items",`${Y}`]})).reduce((Q,Y)=>Y===void 0?Q:[...Q,Y],[])}}function Mx($){return{not:h4($)}}function wx($){return h4($)}var Hx=($,J)=>{return P$($.innerType._def,J)};var Ax=($,J,Q)=>{switch(J){case J$.ZodString:return iN($,Q);case J$.ZodNumber:return Wx($,Q);case J$.ZodObject:return Dx($,Q);case J$.ZodBigInt:return pk($,Q);case J$.ZodBoolean:return nk();case J$.ZodDate:return PL($,Q);case J$.ZodUndefined:return Mx(Q);case J$.ZodNull:return Qx(Q);case J$.ZodArray:return dk($,Q);case J$.ZodUnion:case J$.ZodDiscriminatedUnion:return Yx($,Q);case J$.ZodIntersection:return tk($,Q);case J$.ZodTuple:return Nx($,Q);case J$.ZodRecord:return oN($,Q);case J$.ZodLiteral:return ak($,Q);case J$.ZodEnum:return rk($);case J$.ZodNativeEnum:return $x($);case J$.ZodNullable:return Gx($,Q);case J$.ZodOptional:return Vx($,Q);case J$.ZodMap:return ek($,Q);case J$.ZodSet:return Ox($,Q);case J$.ZodLazy:return()=>$.getter()._def;case J$.ZodPromise:return Ux($,Q);case J$.ZodNaN:case J$.ZodNever:return Jx(Q);case J$.ZodEffects:return ok($,Q);case J$.ZodAny:return h4(Q);case J$.ZodUnknown:return wx(Q);case J$.ZodDefault:return ik($,Q);case J$.ZodBranded:return cN($,Q);case J$.ZodReadonly:return Hx($,Q);case J$.ZodCatch:return ck($,Q);case J$.ZodPipeline:return Kx($,Q);case J$.ZodFunction:case J$.ZodVoid:case J$.ZodSymbol:return;default:return((Y)=>{return})(J)}};function P$($,J,Q=!1){let Y=J.seen.get($);if(J.override){let D=J.override?.($,J,Y,Q);if(D!==uk)return D}if(Y&&!Q){let D=C0$(Y,J);if(D!==void 0)return D}let X={def:$,path:J.currentPath,jsonSchema:void 0};J.seen.set($,X);let G=Ax($,$.typeName,J),W=typeof G==="function"?P$(G(),J):G;if(W)P0$($,J,W);if(J.postProcess){let D=J.postProcess(W,$,J);return X.jsonSchema=W,D}return X.jsonSchema=W,W}var C0$=($,J)=>{switch(J.$refStrategy){case"root":return{$ref:$.path.join("/")};case"relative":return{$ref:nN(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`),h4(J);return J.$refStrategy==="seen"?h4(J):void 0}}},P0$=($,J,Q)=>{if($.description){if(Q.description=$.description,J.markdownDescription)Q.markdownDescription=$.description}return Q};var xL=($,J)=>{let Q=lk(J),Y=typeof J==="object"&&J.definitions?Object.entries(J.definitions).reduce((V,[K,O])=>({...V,[K]:P$(O._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,K]},!0)??h4(Q)}),{}):void 0,X=typeof J==="string"?J:J?.nameStrategy==="title"?void 0:J?.name,G=P$($._def,X===void 0?Q:{...Q,currentPath:[...Q.basePath,Q.definitionPath,X]},!1)??h4(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 v0$($){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 fL($,J){if($0($))return cX($,{target:v0$(J?.target),io:J?.pipeStrategy??"input"});return xL($,{strictUnions:J?.strictUnions??!0,pipeStrategy:J?.pipeStrategy??"input"})}function bL($){let Q=q8($)?.method;if(!Q)throw Error("Schema is missing a method literal");let Y=o3(Q);if(typeof Y!=="string")throw Error("Schema method literal must be a string");return Y}function gL($,J){let Q=I8($,J);if(!Q.success)throw Q.error;return Q.data}var k0$=60000;class yL{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(TN,(J)=>{this._oncancel(J)}),this.setNotificationHandler(CN,(J)=>{this._onprogress(J)}),this.setRequestHandler(RN,(J)=>({})),this._taskStore=$?.taskStore,this._taskMessageQueue=$?.taskMessageQueue,this._taskStore)this.setRequestHandler(PN,async(J,Q)=>{let Y=await this._taskStore.getTask(J.params.taskId,Q.sessionId);if(!Y)throw new B$(E$.InvalidParams,"Failed to retrieve task: Task not found");return{...Y}}),this.setRequestHandler(kN,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,V=D.id,K=this._requestResolvers.get(V);if(K)if(this._requestResolvers.delete(V),W.type==="response")K(D);else{let O=D,N=new B$(O.error.code,O.error.message,O.error.data);K(N)}else{let O=W.type==="response"?"Response":"Error";this._onerror(Error(`${O} handler missing for request ${V}`))}continue}await this._transport?.send(W.message,{relatedRequestId:Q.requestId})}}let G=await this._taskStore.getTask(X,Q.sessionId);if(!G)throw new B$(E$.InvalidParams,`Task not found: ${X}`);if(!B8(G.status))return await this._waitForTaskUpdate(X,Q.signal),await Y();if(B8(G.status)){let W=await this._taskStore.getTaskResult(X,Q.sessionId);return this._clearTaskQueue(X),{...W,_meta:{...W._meta,[L8]:{taskId:X}}}}return await Y()};return await Y()}),this.setRequestHandler(xN,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 B$(E$.InvalidParams,`Failed to list tasks: ${Y instanceof Error?Y.message:String(Y)}`)}}),this.setRequestHandler(bN,async(J,Q)=>{try{let Y=await this._taskStore.getTask(J.params.taskId,Q.sessionId);if(!Y)throw new B$(E$.InvalidParams,`Task not found: ${J.params.taskId}`);if(B8(Y.status))throw new B$(E$.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 B$(E$.InvalidParams,`Task not found after cancellation: ${J.params.taskId}`);return{_meta:{},...X}}catch(Y){if(Y instanceof B$)throw Y;throw new B$(E$.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($),B$.fromError(E$.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),ID(X)||_k(X))this._onresponse(X);else if(AL(X))this._onrequest(X,G);else if(Sk(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=B$.fromError(E$.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?.[L8]?.taskId;if(Q===void 0){let K={jsonrpc:"2.0",id:$.id,error:{code:E$.MethodNotFound,message:"Method not found"}};if(X&&this._taskMessageQueue)this._enqueueTaskMessage(X,{type:"error",message:K,timestamp:Date.now()},Y?.sessionId).catch((O)=>this._onerror(Error(`Failed to enqueue error response: ${O}`)));else Y?.send(K).catch((O)=>this._onerror(Error(`Failed to send an error response: ${O}`)));return}let G=new AbortController;this._requestHandlerAbortControllers.set($.id,G);let W=Fk($.params)?$.params.task:void 0,D=this._taskStore?this.requestTaskStore($,Y?.sessionId):void 0,V={signal:G.signal,sessionId:Y?.sessionId,_meta:$.params?._meta,sendNotification:async(K)=>{if(G.signal.aborted)return;let O={relatedRequestId:$.id};if(X)O.relatedTask={taskId:X};await this.notification(K,O)},sendRequest:async(K,O,N)=>{if(G.signal.aborted)throw new B$(E$.ConnectionClosed,"Request was cancelled");let M={...N,relatedRequestId:$.id};if(X&&!M.relatedTask)M.relatedTask={taskId:X};let w=M.relatedTask?.taskId??X;if(w&&D)await D.updateTaskStatus(w,"input_required");return await this.request(K,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($,V)).then(async(K)=>{if(G.signal.aborted)return;let O={result:K,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(K)=>{if(G.signal.aborted)return;let O={jsonrpc:"2.0",id:$.id,error:{code:Number.isSafeInteger(K.code)?K.code:E$.InternalError,message:K.message??"Internal error",...K.data!==void 0&&{data:K.data}}};if(X&&this._taskMessageQueue)await this._enqueueTaskMessage(X,{type:"error",message:O,timestamp:Date.now()},Y?.sessionId);else await Y?.send(O)}).catch((K)=>this._onerror(Error(`Failed to send response: ${K}`))).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),ID($))Q($);else{let G=new B$($.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(ID($)&&$.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(ID($))Y($);else{let G=B$.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 B$?G:new B$(E$.InternalError,String(G))}}return}let X;try{let G=await this.request($,I5,Q);if(G.task)X=G.task.taskId,yield{type:"taskCreated",task:G.task};else throw new B$(E$.InternalError,"Task creation did not return a task");while(!0){let W=await this.getTask({taskId:X},Q);if(yield{type:"taskStatus",task:W},B8(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 B$(E$.InternalError,`Task ${X} failed`)};else if(W.status==="cancelled")yield{type:"error",error:new B$(E$.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((V)=>setTimeout(V,D)),Q?.signal?.throwIfAborted()}}catch(G){yield{type:"error",error:G instanceof B$?G:new B$(E$.InternalError,String(G))}}}request($,J,Q){let{relatedRequestId:Y,resumptionToken:X,onresumptiontoken:G,task:W,relatedTask:D}=Q??{};return new Promise((V,K)=>{let O=(Z)=>{K(Z)};if(!this._transport){O(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod($.method),W)this.assertTaskCapability($.method)}catch(Z){O(Z);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||{},[L8]:D}};let w=(Z)=>{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(Z)}},{relatedRequestId:Y,resumptionToken:X,onresumptiontoken:G}).catch((B)=>this._onerror(Error(`Failed to send cancellation: ${B}`)));let E=Z instanceof B$?Z:new B$(E$.RequestTimeout,String(Z));K(E)};this._responseHandlers.set(N,(Z)=>{if(Q?.signal?.aborted)return;if(Z instanceof Error)return K(Z);try{let E=I8(J,Z.result);if(!E.success)K(E.error);else V(E.data)}catch(E){K(E)}}),Q?.signal?.addEventListener("abort",()=>{w(Q?.signal?.reason)});let z=Q?.timeout??k0$,q=()=>w(B$.fromError(E$.RequestTimeout,"Request timed out",{timeout:z}));this._setupTimeout(N,z,Q?.maxTotalTimeout,q,Q?.resetTimeoutOnProgress??!1);let F=D?.taskId;if(F){let Z=(E)=>{let B=this._responseHandlers.get(N);if(B)B(E);else this._onerror(Error(`Response handler missing for side-channeled request ${N}`))};this._requestResolvers.set(N,Z),this._enqueueTaskMessage(F,{type:"request",message:M,timestamp:Date.now()}).catch((E)=>{this._cleanupTimeout(N),K(E)})}else this._transport.send(M,{relatedRequestId:Y,resumptionToken:X,onresumptiontoken:G}).catch((Z)=>{this._cleanupTimeout(N),K(Z)})})}async getTask($,J){return this.request({method:"tasks/get",params:$},vN,J)}async getTaskResult($,J,Q){return this.request({method:"tasks/result",params:$},J,Q)}async listTasks($,J){return this.request({method:"tasks/list",params:$},fN,J)}async cancelTask($,J){return this.request({method:"tasks/cancel",params:$},Ck,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||{},[L8]: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||{},[L8]: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||{},[L8]:J.relatedTask}}};await this._transport.send(G,J)}setRequestHandler($,J){let Q=bL($);this.assertRequestHandlerCapability(Q),this._requestHandlers.set(Q,(Y,X)=>{let G=gL($,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=bL($);this._notificationHandlers.set(Q,(Y)=>{let X=gL($,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"&&AL(Y.message)){let X=Y.message.id,G=this._requestResolvers.get(X);if(G)G(new B$(E$.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 B$(E$.InvalidRequest,"Request cancelled"));return}let G=setTimeout(Y,Q);J.addEventListener("abort",()=>{clearTimeout(G),X(new B$(E$.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 B$(E$.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=FD.parse({method:"notifications/tasks/status",params:W});if(await this.notification(D),B8(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 B$(E$.InvalidParams,`Task "${Y}" not found - it may have been cleaned up`);if(B8(W.status))throw new B$(E$.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 V=FD.parse({method:"notifications/tasks/status",params:D});if(await this.notification(V),B8(D.status))this._cleanupTaskProgressHandler(Y)}},listTasks:(Y)=>{return Q.listTasks(Y,J)}}}}function zx($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function Ix($,J){let Q={...$};for(let Y in J){let X=Y,G=J[X];if(G===void 0)continue;let W=Q[X];if(zx(W)&&zx(G))Q[X]={...W,...G};else Q[X]=G}return Q}var Jh=e1(kB(),1),Qh=e1($h(),1);function J7$(){let $=new Jh.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return Qh.default($),$}class dB{constructor($){this._ajv=$??J7$()}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 pB{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((K)=>K.type==="tool_result"),W=$.messages.length>1?$.messages[$.messages.length-2]:void 0,D=W?Array.isArray(W.content)?W.content:[W.content]:[],V=D.some((K)=>K.type==="tool_use");if(G){if(X.some((K)=>K.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!V)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(V){let K=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(K.size!==O.size||![...K].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:$},SD,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},L5,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 Xh($,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 Yh($,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 nB extends yL{constructor($,J){super(J);if(this._serverInfo=$,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ED.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 dB,this.setRequestHandler(qL,(Q)=>this._oninitialize(Q)),this.setNotificationHandler(ZL,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(_L,async(Q,Y)=>{let X=Y.sessionId||Y.requestInfo?.headers["mcp-session-id"]||void 0,{level:G}=Q.params,W=ED.safeParse(G);if(W.success)this._loggingLevels.set(X,W.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new pB(this)};return this._experimental}registerCapabilities($){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=Ix(this._capabilities,$)}setRequestHandler($,J){let Y=q8($)?.method;if(!Y)throw Error("Schema is missing a method literal");let X;if($0(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,V)=>{let K=I8(Z5,D);if(!K.success){let w=K.error instanceof Error?K.error.message:String(K.error);throw new B$(E$.InvalidParams,`Invalid tools/call request: ${w}`)}let{params:O}=K.data,N=await Promise.resolve(J(D,V));if(O.task){let w=I8(I5,N);if(!w.success){let z=w.error instanceof Error?w.error.message:String(w.error);throw new B$(E$.InvalidParams,`Invalid task creation result: ${z}`)}return w.data}let M=I8(dN,N);if(!M.success){let w=M.error instanceof Error?M.error.message:String(M.error);throw new B$(E$.InvalidParams,`Invalid tools/call result: ${w}`)}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($){Yh(this._clientCapabilities?.tasks?.requests,$,"Client")}assertTaskHandlerCapability($){if(!this._capabilities)return;Xh(this._capabilities.tasks?.requests,$,"Server")}async _oninitialize($){let J=$.params.protocolVersion;return this._clientCapabilities=$.params.capabilities,this._clientVersion=$.params.clientInfo,{protocolVersion:Zk.includes(J)?J:wL,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"},_N)}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((V)=>V.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((V)=>V.type==="tool_use");if(X){if(Y.some((V)=>V.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 V=new Set(W.filter((O)=>O.type==="tool_use").map((O)=>O.id)),K=new Set(Y.filter((O)=>O.type==="tool_result").map((O)=>O.toolUseId));if(V.size!==K.size||![...V].every((O)=>K.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:$},TL,J);return this.request({method:"sampling/createMessage",params:$},SD,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},L5,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},L5,J);if(X.action==="accept"&&X.content&&Y.requestedSchema)try{let W=this._jsonSchemaValidator.getValidator(Y.requestedSchema)(X.content);if(!W.valid)throw new B$(E$.InvalidParams,`Elicitation response content does not match requested schema: ${W.errorMessage}`)}catch(G){if(G instanceof B$)throw G;throw new B$(E$.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:$},RL,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 Wh=Symbol.for("mcp.completable");function cB($){return!!$&&typeof $==="object"&&Wh in $}function Dh($){return $[Wh]?.complete}var Gh;(function($){$.Completable="McpCompletable"})(Gh||(Gh={}));var Q7$=/^[A-Za-z0-9._-]{1,128}$/;function X7$($){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(!Q7$.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 Y7$($,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 iB($){let J=X7$($);return Y7$($,J.warnings),J.isValid}class oB{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 tB{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 nB($,J)}get experimental(){if(!this._experimental)this._experimental={tasks:new oB(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(C8(lN)),this.server.assertCanSetRequestHandler(C8(Z5)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(lN,()=>({tools:Object.entries(this._registeredTools).filter(([,$])=>$.enabled).map(([$,J])=>{let Q={name:$,title:J.title,description:J.description,inputSchema:(()=>{let Y=D5(J.inputSchema);return Y?fL(Y,{strictUnions:!0,pipeStrategy:"input"}):G7$})(),annotations:J.annotations,execution:J.execution,_meta:J._meta};if(J.outputSchema){let Y=D5(J.outputSchema);if(Y)Q.outputSchema=fL(Y,{strictUnions:!0,pipeStrategy:"output"})}return Q})})),this.server.setRequestHandler(Z5,async($,J)=>{try{let Q=this._registeredTools[$.params.name];if(!Q)throw new B$(E$.InvalidParams,`Tool ${$.params.name} not found`);if(!Q.enabled)throw new B$(E$.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 B$(E$.InternalError,`Tool ${$.params.name} has taskSupport '${X}' but was not registered with registerToolTask`);if(X==="required"&&!Y)throw new B$(E$.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 B$){if(Q.code===E$.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=D5($.inputSchema)??$.inputSchema,G=await c3(X,J);if(!G.success){let W="error"in G?G.error:"Unknown error",D=i3(W);throw new B$(E$.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 B$(E$.InvalidParams,`Output validation error: Tool ${Q} has an output schema but no structured content was provided`);let Y=D5($.outputSchema),X=await c3(Y,J.structuredContent);if(!X.success){let G="error"in X?X.error:"Unknown error",W=i3(G);throw new B$(E$.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,V=W.task,K=V.pollInterval??5000;while(V.status!=="completed"&&V.status!=="failed"&&V.status!=="cancelled"){await new Promise((N)=>setTimeout(N,K));let O=await Q.taskStore.getTask(D);if(!O)throw new B$(E$.InternalError,`Task ${D} not found during polling`);V=O}return await Q.taskStore.getTaskResult(D)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(C8(pN)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(pN,async($)=>{switch($.params.ref.type){case"ref/prompt":return bk($),this.handlePromptCompletion($,$.params.ref);case"ref/resource":return gk($),this.handleResourceCompletion($,$.params.ref);default:throw new B$(E$.InvalidParams,`Invalid completion reference: ${$.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion($,J){let Q=this._registeredPrompts[J.name];if(!Q)throw new B$(E$.InvalidParams,`Prompt ${J.name} not found`);if(!Q.enabled)throw new B$(E$.InvalidParams,`Prompt ${J.name} disabled`);if(!Q.argsSchema)return aD;let X=q8(Q.argsSchema)?.[$.params.argument.name];if(!cB(X))return aD;let G=Dh(X);if(!G)return aD;let W=await G($.params.argument.value,$.params.context);return Kh(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 aD;throw new B$(E$.InvalidParams,`Resource template ${$.params.ref.uri} not found`)}let Y=Q.resourceTemplate.completeCallback($.params.argument.name);if(!Y)return aD;let X=await Y($.params.argument.value,$.params.context);return Kh(X)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(C8(gN)),this.server.assertCanSetRequestHandler(C8(yN)),this.server.assertCanSetRequestHandler(C8(hN)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(gN,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(yN,async()=>{return{resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([J,Q])=>({name:J,uriTemplate:Q.resourceTemplate.uriTemplate.toString(),...Q.metadata}))}}),this.server.setRequestHandler(hN,async($,J)=>{let Q=new URL($.params.uri),Y=this._registeredResources[Q.toString()];if(Y){if(!Y.enabled)throw new B$(E$.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 B$(E$.InvalidParams,`Resource ${Q} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(C8(uN)),this.server.assertCanSetRequestHandler(C8(mN)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(uN,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,$])=>$.enabled).map(([$,J])=>{return{name:$,title:J.title,description:J.description,arguments:J.argsSchema?W7$(J.argsSchema):void 0}})})),this.server.setRequestHandler(mN,async($,J)=>{let Q=this._registeredPrompts[$.params.name];if(!Q)throw new B$(E$.InvalidParams,`Prompt ${$.params.name} not found`);if(!Q.enabled)throw new B$(E$.InvalidParams,`Prompt ${$.params.name} disabled`);if(Q.argsSchema){let Y=D5(Q.argsSchema),X=await c3(Y,$.params.arguments);if(!X.success){let D="error"in X?X.error:"Unknown error",V=i3(D);throw new B$(E$.InvalidParams,`Invalid arguments for prompt ${$.params.name}: ${V}`)}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:(V)=>{if(typeof V.name<"u"&&V.name!==$){if(delete this._registeredResourceTemplates[$],V.name)this._registeredResourceTemplates[V.name]=G}if(typeof V.title<"u")G.title=V.title;if(typeof V.template<"u")G.resourceTemplate=V.template;if(typeof V.metadata<"u")G.metadata=V.metadata;if(typeof V.callback<"u")G.readCallback=V.callback;if(typeof V.enabled<"u")G.enabled=V.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[$]=G;let W=Q.uriTemplate.variableNames;if(Array.isArray(W)&&W.some((V)=>!!Q.completeCallback(V)))this.setCompletionRequestHandler();return G}_createRegisteredPrompt($,J,Q,Y,X){let G={title:J,description:Q,argsSchema:Y===void 0?void 0:iX(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=iX(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 V=D instanceof A5?D._def?.innerType:D;return cB(V)}))this.setCompletionRequestHandler()}return G}_createRegisteredTool($,J,Q,Y,X,G,W,D,V){iB($);let K={title:J,description:Q,inputSchema:Vh(Y),outputSchema:Vh(X),annotations:G,execution:W,_meta:D,handler:V,enabled:!0,disable:()=>K.update({enabled:!1}),enable:()=>K.update({enabled:!0}),remove:()=>K.update({name:null}),update:(O)=>{if(typeof O.name<"u"&&O.name!==$){if(typeof O.name==="string")iB(O.name);if(delete this._registeredTools[$],O.name)this._registeredTools[O.name]=K}if(typeof O.title<"u")K.title=O.title;if(typeof O.description<"u")K.description=O.description;if(typeof O.paramsSchema<"u")K.inputSchema=iX(O.paramsSchema);if(typeof O.outputSchema<"u")K.outputSchema=iX(O.outputSchema);if(typeof O.callback<"u")K.handler=O.callback;if(typeof O.annotations<"u")K.annotations=O.annotations;if(typeof O._meta<"u")K._meta=O._meta;if(typeof O.enabled<"u")K.enabled=O.enabled;this.sendToolListChanged()}};return this._registeredTools[$]=K,this.setToolRequestHandlers(),this.sendToolListChanged(),K}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(rB(D)){if(Y=J.shift(),J.length>1&&typeof J[0]==="object"&&J[0]!==null&&!rB(J[0]))G=J.shift()}else if(typeof D==="object"&&D!==null){if(Object.values(D).some((V)=>typeof V==="object"&&V!==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:V}=J;return this._createRegisteredTool($,Y,X,G,W,D,{taskSupport:"forbidden"},V,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 G7$={type:"object",properties:{}};function Uh($){return $!==null&&typeof $==="object"&&"parse"in $&&typeof $.parse==="function"&&"safeParse"in $&&typeof $.safeParse==="function"}function Oh($){return"_def"in $||"_zod"in $||Uh($)}function rB($){if(typeof $!=="object"||$===null)return!1;if(Oh($))return!1;if(Object.keys($).length===0)return!0;return Object.values($).some(Uh)}function Vh($){if(!$)return;if(rB($))return iX($);if(!Oh($))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return $}function W7$($){let J=q8($);if(!J)return[];return Object.entries(J).map(([Q,Y])=>{let X=Gv(Y),G=Wv(Y);return{name:Q,description:X,required:!G}})}function C8($){let Q=q8($)?.method;if(!Q)throw Error("Schema is missing a method literal");let Y=o3(Q);if(typeof Y==="string")return Y;throw Error("Schema method literal must be a string")}function Kh($){return{completion:{values:$.slice(0,100),total:$.length,hasMore:$.length>100}}}var aD={completion:{values:[],hasMore:!1}};import Mh from"node:process";class aB{append($){this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){if(!this._buffer)return null;let $=this._buffer.indexOf(`
135
135
  `);if($===-1)return null;let J=this._buffer.toString("utf8",0,$).replace(/\r$/,"");return this._buffer=this._buffer.subarray($+1),D7$(J)}clear(){this._buffer=void 0}}function D7$($){return Tk.parse(JSON.parse($))}function Nh($){return JSON.stringify($)+`
136
- `}class sB{constructor($=Mh.stdin,J=Mh.stdout){this._stdin=$,this._stdout=J,this._readBuffer=new aB,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=Nh($);if(this._stdout.write(Q))J();else this._stdout.once("drain",J)})}}var PM={name:"@0xmonaco/mcp-server",version:"1.0.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":"1.0.7","@0xmonaco/types":"1.0.7","@modelcontextprotocol/sdk":"^1.29.0","node-fetch":"^3.3.2",viem:"^2.53.1",ws:"^8.21.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"latest","@types/ws":"^8.18.1"}};var K7$={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 P8($=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||K7$[G];return{privateKey:J,clientId:Q,network:G,seiRpcUrl:W}}function U7$($){return $.replace(/_([a-z])/g,(J,Q)=>Q.toUpperCase())}function f5($){if($===null||$===void 0)return $;if(typeof $!=="object")return $;if(Array.isArray($))return $.map((Q)=>f5(Q));let J={};for(let[Q,Y]of Object.entries($))J[U7$(Q)]=typeof Y==="object"&&Y!==null?f5(Y):Y;return J}W0();QV();W0();AF();w9();N9();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var LJ=BigInt(0),U6=BigInt(1),$u=BigInt(2),v7$=BigInt(8),k7$={zip215:!0};function x7$($){let J=GV($);return g0($,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...J})}function Ju($){let J=x7$($),{Fp:Q,n:Y,prehash:X,hash:G,randomBytes:W,nByteLength:D,h:V}=J,K=$u<<BigInt(D*8)-U6,O=Q.create,N=HQ(J.n,J.nBitLength);function M(_,C){let m=Q.sqr(_),V$=Q.sqr(C),K$=Q.add(Q.mul(J.a,m),V$),z$=Q.add(Q.ONE,Q.mul(J.d,Q.mul(m,V$)));return Q.eql(K$,z$)}if(!M(J.Gx,J.Gy))throw Error("bad curve params: generator point");let w=J.uvRatio||((_,C)=>{try{return{isValid:!0,value:Q.sqrt(_*Q.inv(C))}}catch(m){return{isValid:!1,value:LJ}}}),z=J.adjustScalarBytes||((_)=>_),q=J.domain||((_,C,m)=>{if(qJ("phflag",m),C.length||m)throw Error("Contexts/pre-hash are not supported");return _});function F(_,C,m=!1){let V$=m?U6:LJ;V6("coordinate "+_,C,V$,K)}function Z(_){if(!(_ instanceof L))throw Error("ExtendedPoint expected")}let E=u5((_,C)=>{let{ex:m,ey:V$,ez:K$}=_,z$=_.is0();if(C==null)C=z$?v7$:Q.inv(K$);let R$=O(m*C),Z$=O(V$*C),W4=O(K$*C);if(z$)return{x:LJ,y:U6};if(W4!==U6)throw Error("invZ was invalid");return{x:R$,y:Z$}}),B=u5((_)=>{let{a:C,d:m}=J;if(_.is0())throw Error("bad point: ZERO");let{ex:V$,ey:K$,ez:z$,et:R$}=_,Z$=O(V$*V$),W4=O(K$*K$),Z4=O(z$*z$),w4=O(Z4*Z4),p4=O(Z$*C),a4=O(Z4*O(p4+W4)),Y1=O(w4+O(m*O(Z$*W4)));if(a4!==Y1)throw Error("bad point: equation left != right (1)");let d1=O(V$*K$),s4=O(z$*R$);if(d1!==s4)throw Error("bad point: equation left != right (2)");return!0});class L{constructor(_,C,m,V$){F("x",_),F("y",C),F("z",m,!0),F("t",V$),this.ex=_,this.ey=C,this.ez=m,this.et=V$,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(_){if(_ instanceof L)throw Error("extended point not allowed");let{x:C,y:m}=_||{};return F("x",C),F("y",m),new L(C,m,U6,O(C*m))}static normalizeZ(_){let C=wQ(Q,_.map((m)=>m.ez));return _.map((m,V$)=>m.toAffine(C[V$])).map(L.fromAffine)}static msm(_,C){return mM(L,N,_,C)}_setWindowSize(_){x.setWindowSize(this,_)}assertValidity(){B(this)}equals(_){Z(_);let{ex:C,ey:m,ez:V$}=this,{ex:K$,ey:z$,ez:R$}=_,Z$=O(C*R$),W4=O(K$*V$),Z4=O(m*R$),w4=O(z$*V$);return Z$===W4&&Z4===w4}is0(){return this.equals(L.ZERO)}negate(){return new L(O(-this.ex),this.ey,this.ez,O(-this.et))}double(){let{a:_}=J,{ex:C,ey:m,ez:V$}=this,K$=O(C*C),z$=O(m*m),R$=O($u*O(V$*V$)),Z$=O(_*K$),W4=C+m,Z4=O(O(W4*W4)-K$-z$),w4=Z$+z$,p4=w4-R$,a4=Z$-z$,Y1=O(Z4*p4),d1=O(w4*a4),s4=O(Z4*a4),L6=O(p4*w4);return new L(Y1,d1,L6,s4)}add(_){Z(_);let{a:C,d:m}=J,{ex:V$,ey:K$,ez:z$,et:R$}=this,{ex:Z$,ey:W4,ez:Z4,et:w4}=_,p4=O(V$*Z$),a4=O(K$*W4),Y1=O(R$*m*w4),d1=O(z$*Z4),s4=O((V$+K$)*(Z$+W4)-p4-a4),L6=d1-Y1,p1=d1+Y1,dQ=O(a4-C*p4),C7=O(s4*L6),XY=O(p1*dQ),bK=O(s4*dQ),q0=O(L6*p1);return new L(C7,XY,q0,bK)}subtract(_){return this.add(_.negate())}wNAF(_){return x.wNAFCached(this,_,L.normalizeZ)}multiply(_){let C=_;V6("scalar",C,U6,Y);let{p:m,f:V$}=this.wNAF(C);return L.normalizeZ([m,V$])[0]}multiplyUnsafe(_,C=L.ZERO){let m=_;if(V6("scalar",m,LJ,Y),m===LJ)return T;if(this.is0()||m===U6)return this;return x.wNAFCachedUnsafe(this,m,L.normalizeZ,C)}isSmallOrder(){return this.multiplyUnsafe(V).is0()}isTorsionFree(){return x.unsafeLadder(this,Y).is0()}toAffine(_){return E(this,_)}clearCofactor(){let{h:_}=J;if(_===U6)return this;return this.multiplyUnsafe(_)}static fromHex(_,C=!1){let{d:m,a:V$}=J,K$=Q.BYTES;_=A4("pointHex",_,K$),qJ("zip215",C);let z$=_.slice(),R$=_[K$-1];z$[K$-1]=R$&-129;let Z$=K9(z$),W4=C?K:Q.ORDER;V6("pointHex.y",Z$,LJ,W4);let Z4=O(Z$*Z$),w4=O(Z4-U6),p4=O(m*Z4-V$),{isValid:a4,value:Y1}=w(w4,p4);if(!a4)throw Error("Point.fromHex: invalid y coordinate");let d1=(Y1&U6)===U6,s4=(R$&128)!==0;if(!C&&Y1===LJ&&s4)throw Error("Point.fromHex: x=0 and x_0=1");if(s4!==d1)Y1=O(-Y1);return L.fromAffine({x:Y1,y:Z$})}static fromPrivateKey(_){let{scalar:C}=R(_);return j.multiply(C)}toRawBytes(){let{x:_,y:C}=this.toAffine(),m=h5(C,Q.BYTES);return m[m.length-1]|=_&U6?128:0,m}toHex(){return f8(this.toRawBytes())}}L.BASE=new L(J.Gx,J.Gy,U6,O(J.Gx*J.Gy)),L.ZERO=new L(LJ,U6,U6,LJ);let{BASE:j,ZERO:T}=L,x=uM(L,D*8);function f(_){return G4(_,Y)}function u(_){return f(K9(_))}function R(_){let C=Q.BYTES;_=A4("private key",_,C);let m=A4("hashed private key",G(_),2*C),V$=z(m.slice(0,C)),K$=m.slice(C,2*C),z$=u(V$);return{head:V$,prefix:K$,scalar:z$}}function d(_){let{head:C,prefix:m,scalar:V$}=R(_),K$=j.multiply(V$),z$=K$.toRawBytes();return{head:C,prefix:m,scalar:V$,point:K$,pointBytes:z$}}function p(_){return d(_).pointBytes}function Y$(_=Uint8Array.of(),...C){let m=A1(...C);return u(G(q(m,A4("context",_),!!X)))}function c(_,C,m={}){if(_=A4("message",_),X)_=X(_);let{prefix:V$,scalar:K$,pointBytes:z$}=d(C),R$=Y$(m.context,V$,_),Z$=j.multiply(R$).toRawBytes(),W4=Y$(m.context,Z$,z$,_),Z4=f(R$+W4*K$);V6("signature.s",Z4,LJ,Y);let w4=A1(Z$,h5(Z4,Q.BYTES));return A4("result",w4,Q.BYTES*2)}let k=k7$;function n(_,C,m,V$=k){let{context:K$,zip215:z$}=V$,R$=Q.BYTES;if(_=A4("signature",_,2*R$),C=A4("message",C),m=A4("publicKey",m,R$),z$!==void 0)qJ("zip215",z$);if(X)C=X(C);let Z$=K9(_.slice(R$,2*R$)),W4,Z4,w4;try{W4=L.fromHex(m,z$),Z4=L.fromHex(_.slice(0,R$),z$),w4=j.multiplyUnsafe(Z$)}catch(Y1){return!1}if(!z$&&W4.isSmallOrder())return!1;let p4=Y$(K$,Z4.toRawBytes(),W4.toRawBytes(),C);return Z4.add(W4.multiplyUnsafe(p4)).subtract(w4).clearCofactor().equals(L.ZERO)}return j._setWindowSize(8),{CURVE:J,getPublicKey:p,sign:c,verify:n,ExtendedPoint:L,utils:{getExtendedPublicKey:d,randomPrivateKey:()=>W(Q.BYTES),precompute(_=8,C=L.BASE){return C._setWindowSize(_),C.multiply(BigInt(3)),C}}}}w9();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var zF=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Wu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),fL$=BigInt(0),h7$=BigInt(1),Du=BigInt(2),bL$=BigInt(3),u7$=BigInt(5),m7$=BigInt(8);function l7$($){let J=BigInt(10),Q=BigInt(20),Y=BigInt(40),X=BigInt(80),G=zF,D=$*$%G*$%G,V=u4(D,Du,G)*D%G,K=u4(V,h7$,G)*$%G,O=u4(K,u7$,G)*K%G,N=u4(O,J,G)*O%G,M=u4(N,Q,G)*N%G,w=u4(M,Y,G)*M%G,z=u4(w,X,G)*w%G,q=u4(z,X,G)*w%G,F=u4(q,J,G)*O%G;return{pow_p_5_8:u4(F,Du,G)*$%G,b2:D}}function d7$($){return $[0]&=248,$[31]&=127,$[31]|=64,$}function p7$($,J){let Q=zF,Y=G4(J*J*J,Q),X=G4(Y*Y*J,Q),G=l7$($*X).pow_p_5_8,W=G4($*Y*G,Q),D=G4(J*W*W,Q),V=W,K=G4(W*Wu,Q),O=D===$,N=D===G4(-$,Q),M=D===G4(-$*Wu,Q);if(O)W=V;if(N||M)W=K;if(ih(W,Q))W=G4(-W,Q);return{isValid:O||N,value:W}}var Vu=(()=>HQ(zF,void 0,!0))(),n7$=(()=>({a:Vu.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Vu,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:m7$,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:fh,randomBytes:g5,adjustScalarBytes:d7$,uvRatio:p7$}))(),lM=(()=>Ju(n7$))();QV();W0();function dM(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let $=lM.utils.randomPrivateKey();return{publicKey:lM.getPublicKey($),privateKey:$}}function pM($){return Y9($.publicKey)}function nM($){return Y9($.privateKey)}function Ku($,J){return{publicKey:sD($),privateKey:sD(J)}}function Uu($){return Y9(OQ($))}function Ou($,J,Q,Y){return`${$.toUpperCase()}
136
+ `}class sB{constructor($=Mh.stdin,J=Mh.stdout){this._stdin=$,this._stdout=J,this._readBuffer=new aB,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=Nh($);if(this._stdout.write(Q))J();else this._stdout.once("drain",J)})}}var PM={name:"@0xmonaco/mcp-server",version:"1.0.15",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":"1.0.15","@0xmonaco/types":"1.0.15","@modelcontextprotocol/sdk":"^1.29.0","node-fetch":"^3.3.2",viem:"^2.53.1",ws:"^8.21.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"latest","@types/ws":"^8.18.1"}};var K7$={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 P8($=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||K7$[G];return{privateKey:J,clientId:Q,network:G,seiRpcUrl:W}}function U7$($){return $.replace(/_([a-z])/g,(J,Q)=>Q.toUpperCase())}function f5($){if($===null||$===void 0)return $;if(typeof $!=="object")return $;if(Array.isArray($))return $.map((Q)=>f5(Q));let J={};for(let[Q,Y]of Object.entries($))J[U7$(Q)]=typeof Y==="object"&&Y!==null?f5(Y):Y;return J}W0();QV();W0();AF();w9();N9();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var LJ=BigInt(0),U6=BigInt(1),$u=BigInt(2),v7$=BigInt(8),k7$={zip215:!0};function x7$($){let J=GV($);return g0($,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...J})}function Ju($){let J=x7$($),{Fp:Q,n:Y,prehash:X,hash:G,randomBytes:W,nByteLength:D,h:V}=J,K=$u<<BigInt(D*8)-U6,O=Q.create,N=HQ(J.n,J.nBitLength);function M(_,C){let m=Q.sqr(_),V$=Q.sqr(C),K$=Q.add(Q.mul(J.a,m),V$),z$=Q.add(Q.ONE,Q.mul(J.d,Q.mul(m,V$)));return Q.eql(K$,z$)}if(!M(J.Gx,J.Gy))throw Error("bad curve params: generator point");let w=J.uvRatio||((_,C)=>{try{return{isValid:!0,value:Q.sqrt(_*Q.inv(C))}}catch(m){return{isValid:!1,value:LJ}}}),z=J.adjustScalarBytes||((_)=>_),q=J.domain||((_,C,m)=>{if(qJ("phflag",m),C.length||m)throw Error("Contexts/pre-hash are not supported");return _});function F(_,C,m=!1){let V$=m?U6:LJ;V6("coordinate "+_,C,V$,K)}function Z(_){if(!(_ instanceof L))throw Error("ExtendedPoint expected")}let E=u5((_,C)=>{let{ex:m,ey:V$,ez:K$}=_,z$=_.is0();if(C==null)C=z$?v7$:Q.inv(K$);let R$=O(m*C),Z$=O(V$*C),W4=O(K$*C);if(z$)return{x:LJ,y:U6};if(W4!==U6)throw Error("invZ was invalid");return{x:R$,y:Z$}}),B=u5((_)=>{let{a:C,d:m}=J;if(_.is0())throw Error("bad point: ZERO");let{ex:V$,ey:K$,ez:z$,et:R$}=_,Z$=O(V$*V$),W4=O(K$*K$),Z4=O(z$*z$),w4=O(Z4*Z4),p4=O(Z$*C),a4=O(Z4*O(p4+W4)),Y1=O(w4+O(m*O(Z$*W4)));if(a4!==Y1)throw Error("bad point: equation left != right (1)");let d1=O(V$*K$),s4=O(z$*R$);if(d1!==s4)throw Error("bad point: equation left != right (2)");return!0});class L{constructor(_,C,m,V$){F("x",_),F("y",C),F("z",m,!0),F("t",V$),this.ex=_,this.ey=C,this.ez=m,this.et=V$,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(_){if(_ instanceof L)throw Error("extended point not allowed");let{x:C,y:m}=_||{};return F("x",C),F("y",m),new L(C,m,U6,O(C*m))}static normalizeZ(_){let C=wQ(Q,_.map((m)=>m.ez));return _.map((m,V$)=>m.toAffine(C[V$])).map(L.fromAffine)}static msm(_,C){return mM(L,N,_,C)}_setWindowSize(_){x.setWindowSize(this,_)}assertValidity(){B(this)}equals(_){Z(_);let{ex:C,ey:m,ez:V$}=this,{ex:K$,ey:z$,ez:R$}=_,Z$=O(C*R$),W4=O(K$*V$),Z4=O(m*R$),w4=O(z$*V$);return Z$===W4&&Z4===w4}is0(){return this.equals(L.ZERO)}negate(){return new L(O(-this.ex),this.ey,this.ez,O(-this.et))}double(){let{a:_}=J,{ex:C,ey:m,ez:V$}=this,K$=O(C*C),z$=O(m*m),R$=O($u*O(V$*V$)),Z$=O(_*K$),W4=C+m,Z4=O(O(W4*W4)-K$-z$),w4=Z$+z$,p4=w4-R$,a4=Z$-z$,Y1=O(Z4*p4),d1=O(w4*a4),s4=O(Z4*a4),L6=O(p4*w4);return new L(Y1,d1,L6,s4)}add(_){Z(_);let{a:C,d:m}=J,{ex:V$,ey:K$,ez:z$,et:R$}=this,{ex:Z$,ey:W4,ez:Z4,et:w4}=_,p4=O(V$*Z$),a4=O(K$*W4),Y1=O(R$*m*w4),d1=O(z$*Z4),s4=O((V$+K$)*(Z$+W4)-p4-a4),L6=d1-Y1,p1=d1+Y1,dQ=O(a4-C*p4),C7=O(s4*L6),XY=O(p1*dQ),bK=O(s4*dQ),q0=O(L6*p1);return new L(C7,XY,q0,bK)}subtract(_){return this.add(_.negate())}wNAF(_){return x.wNAFCached(this,_,L.normalizeZ)}multiply(_){let C=_;V6("scalar",C,U6,Y);let{p:m,f:V$}=this.wNAF(C);return L.normalizeZ([m,V$])[0]}multiplyUnsafe(_,C=L.ZERO){let m=_;if(V6("scalar",m,LJ,Y),m===LJ)return T;if(this.is0()||m===U6)return this;return x.wNAFCachedUnsafe(this,m,L.normalizeZ,C)}isSmallOrder(){return this.multiplyUnsafe(V).is0()}isTorsionFree(){return x.unsafeLadder(this,Y).is0()}toAffine(_){return E(this,_)}clearCofactor(){let{h:_}=J;if(_===U6)return this;return this.multiplyUnsafe(_)}static fromHex(_,C=!1){let{d:m,a:V$}=J,K$=Q.BYTES;_=A4("pointHex",_,K$),qJ("zip215",C);let z$=_.slice(),R$=_[K$-1];z$[K$-1]=R$&-129;let Z$=K9(z$),W4=C?K:Q.ORDER;V6("pointHex.y",Z$,LJ,W4);let Z4=O(Z$*Z$),w4=O(Z4-U6),p4=O(m*Z4-V$),{isValid:a4,value:Y1}=w(w4,p4);if(!a4)throw Error("Point.fromHex: invalid y coordinate");let d1=(Y1&U6)===U6,s4=(R$&128)!==0;if(!C&&Y1===LJ&&s4)throw Error("Point.fromHex: x=0 and x_0=1");if(s4!==d1)Y1=O(-Y1);return L.fromAffine({x:Y1,y:Z$})}static fromPrivateKey(_){let{scalar:C}=R(_);return j.multiply(C)}toRawBytes(){let{x:_,y:C}=this.toAffine(),m=h5(C,Q.BYTES);return m[m.length-1]|=_&U6?128:0,m}toHex(){return f8(this.toRawBytes())}}L.BASE=new L(J.Gx,J.Gy,U6,O(J.Gx*J.Gy)),L.ZERO=new L(LJ,U6,U6,LJ);let{BASE:j,ZERO:T}=L,x=uM(L,D*8);function f(_){return G4(_,Y)}function u(_){return f(K9(_))}function R(_){let C=Q.BYTES;_=A4("private key",_,C);let m=A4("hashed private key",G(_),2*C),V$=z(m.slice(0,C)),K$=m.slice(C,2*C),z$=u(V$);return{head:V$,prefix:K$,scalar:z$}}function d(_){let{head:C,prefix:m,scalar:V$}=R(_),K$=j.multiply(V$),z$=K$.toRawBytes();return{head:C,prefix:m,scalar:V$,point:K$,pointBytes:z$}}function p(_){return d(_).pointBytes}function Y$(_=Uint8Array.of(),...C){let m=A1(...C);return u(G(q(m,A4("context",_),!!X)))}function c(_,C,m={}){if(_=A4("message",_),X)_=X(_);let{prefix:V$,scalar:K$,pointBytes:z$}=d(C),R$=Y$(m.context,V$,_),Z$=j.multiply(R$).toRawBytes(),W4=Y$(m.context,Z$,z$,_),Z4=f(R$+W4*K$);V6("signature.s",Z4,LJ,Y);let w4=A1(Z$,h5(Z4,Q.BYTES));return A4("result",w4,Q.BYTES*2)}let k=k7$;function n(_,C,m,V$=k){let{context:K$,zip215:z$}=V$,R$=Q.BYTES;if(_=A4("signature",_,2*R$),C=A4("message",C),m=A4("publicKey",m,R$),z$!==void 0)qJ("zip215",z$);if(X)C=X(C);let Z$=K9(_.slice(R$,2*R$)),W4,Z4,w4;try{W4=L.fromHex(m,z$),Z4=L.fromHex(_.slice(0,R$),z$),w4=j.multiplyUnsafe(Z$)}catch(Y1){return!1}if(!z$&&W4.isSmallOrder())return!1;let p4=Y$(K$,Z4.toRawBytes(),W4.toRawBytes(),C);return Z4.add(W4.multiplyUnsafe(p4)).subtract(w4).clearCofactor().equals(L.ZERO)}return j._setWindowSize(8),{CURVE:J,getPublicKey:p,sign:c,verify:n,ExtendedPoint:L,utils:{getExtendedPublicKey:d,randomPrivateKey:()=>W(Q.BYTES),precompute(_=8,C=L.BASE){return C._setWindowSize(_),C.multiply(BigInt(3)),C}}}}w9();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var zF=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Wu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),fL$=BigInt(0),h7$=BigInt(1),Du=BigInt(2),bL$=BigInt(3),u7$=BigInt(5),m7$=BigInt(8);function l7$($){let J=BigInt(10),Q=BigInt(20),Y=BigInt(40),X=BigInt(80),G=zF,D=$*$%G*$%G,V=u4(D,Du,G)*D%G,K=u4(V,h7$,G)*$%G,O=u4(K,u7$,G)*K%G,N=u4(O,J,G)*O%G,M=u4(N,Q,G)*N%G,w=u4(M,Y,G)*M%G,z=u4(w,X,G)*w%G,q=u4(z,X,G)*w%G,F=u4(q,J,G)*O%G;return{pow_p_5_8:u4(F,Du,G)*$%G,b2:D}}function d7$($){return $[0]&=248,$[31]&=127,$[31]|=64,$}function p7$($,J){let Q=zF,Y=G4(J*J*J,Q),X=G4(Y*Y*J,Q),G=l7$($*X).pow_p_5_8,W=G4($*Y*G,Q),D=G4(J*W*W,Q),V=W,K=G4(W*Wu,Q),O=D===$,N=D===G4(-$,Q),M=D===G4(-$*Wu,Q);if(O)W=V;if(N||M)W=K;if(ih(W,Q))W=G4(-W,Q);return{isValid:O||N,value:W}}var Vu=(()=>HQ(zF,void 0,!0))(),n7$=(()=>({a:Vu.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Vu,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:m7$,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:fh,randomBytes:g5,adjustScalarBytes:d7$,uvRatio:p7$}))(),lM=(()=>Ju(n7$))();QV();W0();function dM(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let $=lM.utils.randomPrivateKey();return{publicKey:lM.getPublicKey($),privateKey:$}}function pM($){return Y9($.publicKey)}function nM($){return Y9($.privateKey)}function Ku($,J){return{publicKey:sD($),privateKey:sD(J)}}function Uu($){return Y9(OQ($))}function Ou($,J,Q,Y){return`${$.toUpperCase()}
137
137
  ${J}
138
138
  ${Q}
139
139
  ${Y}`}function Nu($,J){return`WS-AUTH
@@ -141,7 +141,7 @@ ${$}
141
141
  ${J}`}function cM($,J){return Y9(lM.sign(b5(J),$))}var DV=[0.0001,0.001,0.01,0.1,1,10,100,1000,1e4];var c7$=1e4,i7$=15000,o7$=30000,r7$=["created","activated","cancelled","parent_cancelled","triggered","failed","oco_cancelled"],t7$=["STOP_LOSS","TAKE_PROFIT"],a7$=["MARK_PRICE"],s7$=["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],e7$=["POSITION","PARENT_ORDER"];function Mu($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function H9($,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 y0($,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 $W$($,J){let Q=$[J];if(typeof Q!=="boolean")throw Error(`Invalid conditional order event: ${J} must be a boolean`);return Q}function JW$($,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 g8($,J,Q){let Y=H9($,J);if(!Q.includes(Y))throw Error(`Invalid conditional order event: ${J} must be one of ${Q.join(", ")}`);return Y}function wu($,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 QW$($){if(!Mu($))throw Error("Invalid conditional order event: payload must be an object");if(!Mu($.data))throw Error("Invalid conditional order event: data must be an object");let J=f5($.data);return{eventType:g8($,"event_type",["conditional_order_update"]),userId:H9($,"user_id"),data:{conditionalOrderId:H9(J,"conditionalOrderId"),tradingPairId:H9(J,"tradingPairId"),marginAccountId:H9(J,"marginAccountId"),positionId:y0(J,"positionId"),parentOrderId:y0(J,"parentOrderId"),associationType:wu(J,"associationType",e7$),linkedGroupId:y0(J,"linkedGroupId"),conditionType:g8(J,"conditionType",t7$),triggerSource:g8(J,"triggerSource",a7$),triggerPrice:H9(J,"triggerPrice"),side:g8(J,"side",["BUY","SELL"]),positionSide:g8(J,"positionSide",["LONG","SHORT","NONE"]),orderType:g8(J,"orderType",["LIMIT","MARKET"]),limitPrice:y0(J,"limitPrice"),quantity:y0(J,"quantity"),slippageToleranceBps:JW$(J,"slippageToleranceBps"),reduceOnly:$W$(J,"reduceOnly"),timeInForce:wu(J,"timeInForce",["GTC","IOC"]),state:g8(J,"state",s7$),triggeredOrderId:y0(J,"triggeredOrderId"),triggeredAt:y0(J,"triggeredAt"),activatedAt:y0(J,"activatedAt"),cancelledAt:y0(J,"cancelledAt"),expiresAt:y0(J,"expiresAt"),failureReason:y0(J,"failureReason"),reason:g8(J,"reason",r7$),updatedAt:H9(J,"updatedAt")}}}function IF($,J={}){let Q=null,Y=J.session,X=0,G=null,W=null,D=J.autoReconnect??!0,V=J.maxReconnectAttempts??5,K=new Map,O=()=>{if(!Q)return"disconnected";switch(Q.readyState){case WebSocket.CONNECTING:return"connecting";case WebSocket.OPEN:return"connected";default:return"disconnected"}},N=()=>$,M=()=>{if(!Y||Q?.readyState!==WebSocket.OPEN)return;let k=Date.now(),n=cM(sD(Y.privateKey),Nu(Y.publicKey,k));Q.send(JSON.stringify({type:"Authenticate",public_key:Y.publicKey,timestamp:k,signature:n}))},w=()=>{if(W)clearInterval(W),W=null},z=()=>{w(),W=setInterval(()=>{if(Q?.readyState===WebSocket.OPEN)Q.send(JSON.stringify({type:"Ping"}))},i7$)},q=()=>{if(G)clearTimeout(G),G=null},F=()=>{if(!D||X>=V){console.error("WebSocket: Max reconnect attempts reached");return}X++;let k=Math.min(1000*2**X,o7$);G=setTimeout(()=>{L().catch((n)=>{console.warn("WebSocket: Failed to reconnect:",n)})},k)},Z=(k)=>{if(Q?.readyState===WebSocket.OPEN)Q.send(JSON.stringify(k))},E=()=>{let k=Array.from(K.keys());if(k.length>0)Z({type:"Subscribe",channels:k})},B=(k)=>{if(k.type!=="Event"||!k.channel)return;for(let[n,s]of K)if(k.channel===n||k.channel.startsWith(`${n}:`))for(let _ of s)_(k.data)},L=()=>{return new Promise((k,n)=>{if(Q?.readyState===WebSocket.CONNECTING||Q?.readyState===WebSocket.OPEN){k();return}try{let s=new WebSocket(N());Q=s;let _=setTimeout(()=>{if(Q!==s){k();return}if(s.readyState===WebSocket.CONNECTING)s.close(1000,"Connection timeout"),n(Error("WebSocket connection timeout"))},c7$);s.onopen=()=>{if(clearTimeout(_),Q!==s){k();return}X=0,z(),M(),E(),J.onStatusChange?.("connected"),k()},s.onmessage=(C)=>{if(Q!==s)return;try{let m=JSON.parse(C.data);if(m.type==="Pong")return;B(m)}catch(m){console.warn("WebSocket: Failed to parse message",m)}},s.onclose=(C)=>{if(clearTimeout(_),Q!==s){k();return}if(Q=null,w(),J.onStatusChange?.("disconnected"),D&&C.code!==1000)F()},s.onerror=()=>clearTimeout(_)}catch(s){J.onStatusChange?.("disconnected"),n(s)}})},j=()=>{D=!1,q(),w(),K.clear(),Q?.close(1000,"Client disconnect"),Q=null,J.onStatusChange?.("disconnected")},T=(k,n)=>{let s=!K.has(k);if(!K.has(k))K.set(k,new Set);if(K.get(k)?.add(n),s&&Q?.readyState===WebSocket.OPEN)Z({type:"Subscribe",channels:[k]});return()=>{let _=K.get(k);if(_){if(_.delete(n),_.size===0){if(K.delete(k),Q?.readyState===WebSocket.OPEN)Z({type:"Unsubscribe",channels:[k]})}}}};return{connect:L,disconnect:j,isConnected:()=>Q?.readyState===WebSocket.OPEN,getStatus:O,setSessionKeypair:(k)=>{if(Y=k??void 0,Y&&Q?.readyState===WebSocket.OPEN)M();else if(Y&&(!Q||Q.readyState===WebSocket.CLOSED))L().catch((n)=>{console.warn("WebSocket: Failed to connect after session update:",n)})},orders:(k,n,s)=>{let _=`orders:${k}:${n}`;return T(_,(C)=>{try{let m=C,V$={orderId:m.order_id,eventType:m.event_type,timestamp:m.timestamp,data:f5(m.data)};s(V$)}catch(m){console.error("WebSocket: Error processing order event",m)}})},orderbook:(k,n,s,_,C)=>{if(!k||!n||s===void 0||!_)throw Error(`orderbook subscription requires all params: tradingPairId="${k}", tradingMode="${n}", magnitude=${s} (valid: ${DV.join(", ")}), quotationMode="${_}" (valid: "BASE", "QUOTE")`);if(!DV.includes(s))throw Error(`Invalid magnitude: ${s}. Must be one of: ${DV.join(", ")}`);let m=`orderbook:${k}:${n}:${s}:${_.toLowerCase()}`;return T(m,(V$)=>{try{let K$=V$,z$=K$.data,R$={tradingPairId:K$.trading_pair_id,tradingMode:K$.trading_mode,bids:(z$?.bids||[]).map((Z$)=>({price:Z$.price,quantity:Z$.quantity,orderCount:Z$.order_count||0})),asks:(z$?.asks||[]).map((Z$)=>({price:Z$.price,quantity:Z$.quantity,orderCount:Z$.order_count||0})),bestBid:z$?.best_bid,bestAsk:z$?.best_ask,bidVolume:z$?.bid_volume||void 0,askVolume:z$?.ask_volume||void 0,priceChange:z$?.price_change?{side:z$.price_change.side,oldPrice:z$.price_change.old_price,newPrice:z$.price_change.new_price,levelRemoved:z$.price_change.level_removed||!1,levelAdded:z$.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};C(R$)}catch(K$){console.error("WebSocket: Error processing orderbook event",K$)}})},ohlcv:(k,n,s,_)=>{let C=`ohlcv:${k}:${n}:${s}`;return T(C,(m)=>{try{let V$=m,K$=V$.data,z$={tradingPairId:V$.trading_pair_id,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}};_(z$)}catch(V$){console.error("WebSocket: Error processing OHLCV event",V$)}})},trades:(k,n)=>{let s=`trades:${k}`;return T(s,(_)=>{try{let C=_,m=C.data,V$={eventType:"trade",tradingPairId:C.trading_pair_id,tradingMode:C.trading_mode.toUpperCase(),data:{tradeId:m.trade_id,price:m.price,quantity:m.quantity,makerSide:m.maker_side.toUpperCase(),executedAt:m.executed_at}};n(V$)}catch(C){console.error("WebSocket: Error processing trade event",C)}})},movements:(k)=>{return T("movements",(s)=>{try{let _=s,C=_.data,m={eventType:"movement",userId:_.user_id,data:{id:C.id,entryType:C.entry_type,transactionType:C.transaction_type,tokenAddress:C.token_address,amount:String(C.amount),amountRaw:C.amount_raw,balanceBefore:C.balance_before!=null?String(C.balance_before):void 0,balanceAfter:C.balance_after!=null?String(C.balance_after):void 0,lockedBefore:C.locked_before!=null?String(C.locked_before):void 0,lockedAfter:C.locked_after!=null?String(C.locked_after):void 0,referenceId:C.reference_id,referenceType:C.reference_type,description:C.description,txHash:C.tx_hash,createdAt:C.created_at,decimals:C.decimals}};k(m)}catch(_){console.error("WebSocket: Error processing movement event",_)}})},userOrders:(k)=>{return T("orders",(s)=>{try{let _=s,C={orderId:_.order_id,eventType:_.event_type,timestamp:_.timestamp,data:f5(_.data)};k(C)}catch(_){console.error("WebSocket: Error processing user order event",_)}})},balances:(k)=>{return T("balances",(s)=>{try{let _=s,C=_.data,m={eventType:"balance_update",userId:_.user_id,data:{tokenAddress:C.token_address,tokenSymbol:C.token_symbol,available:C.available,availableRaw:C.available_raw,locked:C.locked,lockedRaw:C.locked_raw,total:C.total,totalRaw:C.total_raw,reason:C.reason,referenceId:C.reference_id,updatedAt:C.updated_at}};k(m)}catch(_){console.error("WebSocket: Error processing balance event",_)}})},conditionalOrders:(k,n)=>{if(!k)throw Error("conditionalOrders subscription requires a handler");if(n!==void 0&&n.length===0)throw Error("conditionalOrders tradingPairId cannot be empty");let s=n?`conditional_orders:${n}`:"conditional_orders";return T(s,(_)=>{try{k(QW$(_))}catch(C){console.error("WebSocket: Error processing conditional order event",C)}})}}}var y8=e1(oM(),1),Sm=["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 m5($,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)=>m5(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(Sm.some((V)=>W.includes(V.toLowerCase())))Y[X]="[REDACTED]";else if(typeof G==="string"&&G.length>500)Y[X]=`${G.substring(0,500)}... [truncated]`;else Y[X]=m5(G,J,Q+1)}return Y}if(typeof $==="string"){if($.length>1000)return`${$.substring(0,1000)}... [truncated]`;return $}return $}class l5 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 b4 extends l5{code="INVALID_CONFIG";field;value;constructor($,J,Q,Y){let X=J?`Check the '${J}' configuration parameter. ${zW$(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(Sm.some((Y)=>J.includes(Y.toLowerCase())))$="[REDACTED]";else $=m5(this.value)}else $=m5(this.value);return{...super.toJSON(),field:this.field,value:$}}}function zW$($){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 VV extends l5{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 U1 extends l5{code="API_ERROR";endpoint;statusCode;responseBody;requestBody;requestId;retryAfter;constructor($,J){let{suggestion:Q,retryable:Y}=IW$(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:m5(this.responseBody),requestBody:m5(this.requestBody),requestId:this.requestId,retryAfter:this.retryAfter}}}function IW$($,J,Q){if(!$)return{suggestion:"Network request failed. Check your internet connection and try again.",retryable:!0};if($===y8.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($===y8.StatusCodes.FORBIDDEN)return{suggestion:"Access denied. Ensure your application has the required permissions and your client ID is valid.",retryable:!1};if($===y8.StatusCodes.NOT_FOUND)return{suggestion:"Resource not found. Check that the ID or identifier is correct and the resource exists.",retryable:!1};if($===y8.StatusCodes.CONFLICT)return{suggestion:"Resource conflict. The resource may have been modified. Refresh and try again.",retryable:!0};if($===y8.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($===y8.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($>=y8.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 AQ extends l5{code="CONTRACT_ERROR";revertReason;transactionHash;contractAddress;constructor($,J){let Q=qW$(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 qW$($){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 ZW$={local:"http://localhost:8080",development:"https://develop.apimonaco.xyz",staging:"https://staging.apimonaco.xyz",mainnet:"https://api.monaco.xyz"},LW$={local:"ws://localhost:8085/ws",development:"wss://develop.apimonaco.xyz/ws",staging:"wss://staging.apimonaco.xyz/ws",mainnet:"wss://api.monaco.xyz/ws"};function KV($){return ZW$[$]}function EF($){return LW$[$]}var uS=e1(oM(),1);var rM=256,tM;function aM($=11){if(!tM||rM+$>512){tM="",rM=0;for(let J=0;J<256;J++)tM+=(256+Math.random()*256|0).toString(16).substring(1)}return tM.substring(rM,rM+++$)}function _m($){let{batch:J,chain:Q,ccipRead:Y,dataSuffix:X,key:G="base",name:W="Base Client",type:D="base"}=$,V=$.experimental_blockTag??(typeof Q?.experimental_preconfirmationTime==="number"?"pending":void 0),K=Q?.blockTime??12000,O=Math.min(Math.max(Math.floor(K/2),500),4000),N=$.pollingInterval??O,M=$.cacheTime??N,w=$.account?g4($.account):void 0,{config:z,request:q,value:F}=$.transport({account:w,chain:Q,pollingInterval:N}),Z={...z,...F},E={account:w,batch:J,cacheTime:M,ccipRead:Y,chain:Q,dataSuffix:X,key:G,name:W,pollingInterval:N,request:q,transport:Z,type:D,uid:aM(),...V?{experimental_blockTag:V}:{}};function B(L){return(j)=>{let T=j(L);for(let f in E)delete T[f];let x={...L,...T};return Object.assign(x,{extend:B(x)})}}return Object.assign(E,{extend:B(E)})}BJ();_Q();U0();F9();d$();e$();p8();function XG($){if(!($ instanceof h))return!1;let J=$.walk((Q)=>Q instanceof QG);if(!(J instanceof QG))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}RV();g1();d$();d0();function Pw($){if($.length!==66)return null;if($.indexOf("[")!==0)return null;if($.indexOf("]")!==65)return null;let J=`0x${$.slice(1,65)}`;if(!Q1(J))return null;return J}function CV($){let J=new Uint8Array(32).fill(0);if(!$)return O4(J);let Q=$.split(".");for(let Y=Q.length-1;Y>=0;Y-=1){let X=Pw(Q[Y]),G=X?V0(X):C4(l0(Q[Y]),"bytes");J=C4(y1([J,G]),"bytes")}return O4(J)}g1();function il($){return`[${$.slice(2)}]`}g1();d$();d0();function ol($){let J=new Uint8Array(32).fill(0);if(!$)return O4(J);return Pw($)||C4(l0($))}function YG($){let J=$.replace(/^\.|\.$/gm,"");if(J.length===0)return new Uint8Array(1);let Q=new Uint8Array(l0(J).byteLength+2),Y=0,X=J.split(".");for(let G=0;G<X.length;G++){let W=l0(X[G]);if(W.byteLength>255)W=l0(il(ol(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 W$($,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)}_Q();U0();J1();e$();p8();_9();PV();var qD$=3;function i0($,{abi:J,address:Q,args:Y,docsPath:X,functionName:G,sender:W}){let D=$ instanceof RQ?$:$ instanceof h?$.walk((z)=>("data"in z))||$.walk():{},{code:V,data:K,details:O,message:N,shortMessage:M}=D,w=(()=>{if($ instanceof u0)return new yj({functionName:G,cause:$});if([qD$,PQ.code].includes(V)&&(K||O||N||M)||V===N0.code&&O==="execution reverted"&&K)return new QG({abi:J,data:typeof K==="object"?K.data:K,functionName:G,message:D instanceof S9?O:M??N,cause:$});return $})();return new TV(w,{abi:J,args:Y,contractAddress:Q,docsPath:X,functionName:G,sender:W})}f9();async function W1($,J){let{abi:Q,address:Y,args:X,functionName:G,...W}=J,D=n4({abi:Q,args:X,functionName:G});try{let{data:V}=await W$($,H0,"call")({...W,data:D,to:Y});return r1({abi:Q,args:X,functionName:G,data:V||"0x"})}catch(V){throw i0(V,{abi:Q,address:Y,args:X,docsPath:"/docs/contract/readContract",functionName:G})}}async function Cd($,J){let{blockNumber:Q,blockTag:Y,coinType:X,name:G,gatewayUrls:W,strict:D}=J,{chain:V}=$,K=(()=>{if(J.universalResolverAddress)return J.universalResolverAddress;if(!V)throw Error("client chain not configured. universalResolverAddress is required.");return O0({blockNumber:Q,chain:V,contract:"ensUniversalResolver"})})(),O=V?.ensTlds;if(O&&!O.some((M)=>G.endsWith(M)))return null;let N=(()=>{if(X!=null)return[CV(G),BigInt(X)];return[CV(G)]})();try{let M=n4({abi:_F,functionName:"addr",args:N}),w={address:K,abi:eM,functionName:"resolveWithGateways",args:[o1(YG(G)),M,W??[CQ]],blockNumber:Q,blockTag:Y},q=await W$($,W1,"readContract")(w);if(q[0]==="0x")return null;let F=r1({abi:_F,args:N,functionName:"addr",data:q[0]});if(F==="0x")return null;if(m0(F)==="0x00")return null;return F}catch(M){if(D)throw M;if(XG(M))return null;throw M}}e$();class ME extends h{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 b9 extends h{constructor({reason:$}){super(`ENS NFT avatar URI is invalid. ${$}`,{name:"EnsAvatarInvalidNftUriError"})}}class pV extends h{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 wE extends h{constructor({namespace:$}){super(`ENS NFT avatar namespace "${$}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}var uD$=/(?<protocol>https?:\/\/[^/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/,mD$=/^(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>\/.*)?$/,lD$=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,dD$=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function pD$($){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 Pd($,J){if(!$)return J;if($.endsWith("/"))return $.slice(0,-1);return $}function HE({uri:$,gatewayUrls:J}){let Q=lD$.test($);if(Q)return{uri:$,isOnChain:!0,isEncoded:Q};let Y=Pd(J?.ipfs,"https://ipfs.io"),X=Pd(J?.arweave,"https://arweave.net"),G=$.match(uD$),{protocol:W,subpath:D,target:V,subtarget:K=""}=G?.groups||{},O=W==="ipns:/"||D==="ipns/",N=W==="ipfs:/"||D==="ipfs/"||mD$.test($);if($.startsWith("http")&&!O&&!N){let w=$;if(J?.arweave)w=$.replace(/https:\/\/arweave.net/g,J?.arweave);return{uri:w,isOnChain:!1,isEncoded:!1}}if((O||N)&&V)return{uri:`${Y}/${O?"ipns":"ipfs"}/${V}${K}`,isOnChain:!1,isEncoded:!1};if(W==="ar:/"&&V)return{uri:`${X}/${V}${K||""}`,isOnChain:!1,isEncoded:!1};let M=$.replace(dD$,"");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 pV({uri:$})}function AE($){if(typeof $!=="object"||!("image"in $)&&!("image_url"in $)&&!("image_data"in $))throw new ME({data:$});return $.image||$.image_url||$.image_data}async function vd({gatewayUrls:$,uri:J}){try{let Q=await fetch(J).then((X)=>X.json());return await nw({gatewayUrls:$,uri:AE(Q)})}catch{throw new pV({uri:J})}}async function nw({gatewayUrls:$,uri:J}){let{uri:Q,isOnChain:Y}=HE({uri:J,gatewayUrls:$});if(Y)return Q;if(await pD$(Q))return Q;throw new pV({uri:J})}function kd($){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,V]=Y.split(":");if(!G||G.toLowerCase()!=="eip155")throw new b9({reason:"Only EIP-155 supported"});if(!W)throw new b9({reason:"Chain ID not found"});if(!V)throw new b9({reason:"Contract address not found"});if(!X)throw new b9({reason:"Token ID not found"});if(!D)throw new b9({reason:"ERC namespace not found"});return{chainID:Number.parseInt(W,10),namespace:D.toLowerCase(),contractAddress:V,tokenID:X}}async function xd($,{nft:J}){if(J.namespace==="erc721")return W1($,{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 W1($,{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 wE({namespace:J.namespace})}async function fd($,{gatewayUrls:J,record:Q}){if(/eip155:/i.test(Q))return nD$($,{gatewayUrls:J,record:Q});return nw({uri:Q,gatewayUrls:J})}async function nD$($,{gatewayUrls:J,record:Q}){let Y=kd(Q),X=await xd($,{nft:Y}),{uri:G,isOnChain:W,isEncoded:D}=HE({uri:X,gatewayUrls:J});if(W&&(G.includes("data:application/json;base64,")||G.startsWith("{"))){let K=D?atob(G.replace("data:application/json;base64,","")):G,O=JSON.parse(K);return nw({uri:AE(O),gatewayUrls:J})}let V=Y.tokenID;if(Y.namespace==="erc1155")V=V.replace("0x","").padStart(64,"0");return vd({gatewayUrls:J,uri:G.replace(/(?:0x)?{id}/,V)})}BJ();_Q();U0();F9();d$();RV();async function cw($,J){let{blockNumber:Q,blockTag:Y,key:X,name:G,gatewayUrls:W,strict:D}=J,{chain:V}=$,K=(()=>{if(J.universalResolverAddress)return J.universalResolverAddress;if(!V)throw Error("client chain not configured. universalResolverAddress is required.");return O0({blockNumber:Q,chain:V,contract:"ensUniversalResolver"})})(),O=V?.ensTlds;if(O&&!O.some((N)=>G.endsWith(N)))return null;try{let N={address:K,abi:eM,args:[o1(YG(G)),n4({abi:SF,functionName:"text",args:[CV(G),X]}),W??[CQ]],functionName:"resolveWithGateways",blockNumber:Q,blockTag:Y},w=await W$($,W1,"readContract")(N);if(w[0]==="0x")return null;let z=r1({abi:SF,functionName:"text",data:w[0]});return z===""?null:z}catch(N){if(D)throw N;if(XG(N))return null;throw N}}async function bd($,{blockNumber:J,blockTag:Q,assetGatewayUrls:Y,name:X,gatewayUrls:G,strict:W,universalResolverAddress:D}){let V=await W$($,cw,"getEnsText")({blockNumber:J,blockTag:Q,key:"avatar",name:X,universalResolverAddress:D,gatewayUrls:G,strict:W});if(!V)return null;try{return await fd($,{record:V,gatewayUrls:Y})}catch{return null}}BJ();F9();RV();async function gd($,J){let{address:Q,blockNumber:Y,blockTag:X,coinType:G=60n,gatewayUrls:W,strict:D}=J,{chain:V}=$,K=(()=>{if(J.universalResolverAddress)return J.universalResolverAddress;if(!V)throw Error("client chain not configured. universalResolverAddress is required.");return O0({blockNumber:Y,chain:V,contract:"ensUniversalResolver"})})();try{let O={address:K,abi:Rm,args:[Q,G,W??[CQ]],functionName:"reverseWithGateways",blockNumber:Y,blockTag:X},N=W$($,W1,"readContract"),[M]=await N(O);return M||null}catch(O){if(D)throw O;if(XG(O))return null;throw O}}F9();d$();async function yd($,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 O0({blockNumber:Q,chain:G,contract:"ensUniversalResolver"})})(),D=G?.ensTlds;if(D&&!D.some((K)=>X.endsWith(K)))throw Error(`${X} is not a valid ENS TLD (${D?.join(", ")}) for chain "${G.name}" (id: ${G.id}).`);let[V]=await W$($,W1,"readContract")({address:W,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"},{type:"uint256"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[o1(YG(X))],blockNumber:Q,blockTag:Y});return V}f9();d$();DE();vG();x9();async function iw($,J){let{account:Q=$.account,blockNumber:Y,blockTag:X="latest",blobs:G,data:W,gas:D,gasPrice:V,maxFeePerBlobGas:K,maxFeePerGas:O,maxPriorityFeePerGas:N,to:M,value:w,...z}=J,q=Q?g4(Q):void 0;try{w0(J);let Z=(typeof Y==="bigint"?N$(Y):void 0)||X,E=$.chain?.formatters?.transactionRequest?.format,L=(E||TJ)({...t8(z,{format:E}),account:q,blobs:G,data:W,gas:D,gasPrice:V,maxFeePerBlobGas:K,maxFeePerGas:O,maxPriorityFeePerGas:N,to:M,value:w},"createAccessList"),j=await $.request({method:"eth_createAccessList",params:[L,Z]});return{accessList:j.accessList,gasUsed:BigInt(j.gasUsed)}}catch(F){throw mw(F,{...J,account:q,chain:$.chain})}}function a8($,{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 hd($){let J=a8($,{method:"eth_newBlockFilter"}),Q=await $.request({method:"eth_newBlockFilter"});return{id:Q,request:J(Q),type:"block"}}J1();e$();class zE extends h{constructor($){super(`Filter type "${$}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}g1();d0();jV();BQ();zQ();d8();var ud="/docs/contract/encodeEventTopics";function RJ($){let{abi:J,eventName:Q,args:Y}=$,X=J[0];if(Q){let V=b6({abi:J,name:Q});if(!V)throw new Xw(Q,{docsPath:ud});X=V}if(X.type!=="event")throw new Xw(void 0,{docsPath:ud});let G=O1(X),W=l8(G),D=[];if(Y&&"inputs"in X){let V=X.inputs?.filter((O)=>("indexed"in O)&&O.indexed),K=Array.isArray(Y)?Y:Object.values(Y).length>0?V?.map((O)=>Y[O.name])??[]:[];if(K.length>0)D=V?.map((O,N)=>{if(Array.isArray(K[N]))return K[N].map((M,w)=>md({param:O,value:K[N][w]}));return typeof K[N]<"u"&&K[N]!==null?md({param:O,value:K[N]}):null})??[]}return[W,...D]}function md({param:$,value:J}){if($.type==="string"||$.type==="bytes")return C4(V0(J));if($.type==="tuple"||$.type.match(/^(.*)\[(\d+)?\]$/))throw new zE($.type);return M6([$],[J])}d$();async function ow($,J){let{address:Q,abi:Y,args:X,eventName:G,fromBlock:W,strict:D,toBlock:V}=J,K=a8($,{method:"eth_newFilter"}),O=G?RJ({abi:Y,args:X,eventName:G}):void 0,N=await $.request({method:"eth_newFilter",params:[{address:Q,fromBlock:typeof W==="bigint"?N$(W):W,toBlock:typeof V==="bigint"?N$(V):V,topics:O}]});return{abi:Y,args:X,eventName:G,id:N,request:K(N),strict:Boolean(D),type:"event"}}d$();async function rw($,{address:J,args:Q,event:Y,events:X,fromBlock:G,strict:W,toBlock:D}={}){let V=X??(Y?[Y]:void 0),K=a8($,{method:"eth_newFilter"}),O=[];if(V){if(O=[V.flatMap((w)=>RJ({abi:[w],eventName:w.name,args:Q}))],Y)O=O[0]}let N=await $.request({method:"eth_newFilter",params:[{address:J,fromBlock:typeof G==="bigint"?N$(G):G,toBlock:typeof D==="bigint"?N$(D):D,...O.length?{topics:O}:{}}]});return{abi:V,args:Q,eventName:Y?Y.name:void 0,fromBlock:G,id:N,request:K(N),strict:Boolean(W),toBlock:D,type:"event"}}async function tw($){let J=a8($,{method:"eth_newPendingTransactionFilter"}),Q=await $.request({method:"eth_newPendingTransactionFilter"});return{id:Q,request:J(Q),type:"transaction"}}U0();e$();Z9();d0();function ld($){let J=C4(`0x${$.substring(4)}`).substring(26);return q9(`0x${J}`)}D0();N6();d$();async function Xp({hash:$,signature:J}){let Q=Q1($)?$:o1($),{secp256k1:Y}=await Promise.resolve().then(() => ($X(),CE));return`0x${(()=>{if(typeof J==="object"&&"r"in J&&"s"in J){let{r:K,s:O,v:N,yParity:M}=J,w=Number(M??N),z=Qp(w);return new Y.Signature(f1(K),f1(O)).addRecoveryBit(z)}let W=Q1(J)?J:o1(J);if(X4(W)!==65)throw Error("invalid signature length");let D=I1(`0x${W.slice(130)}`),V=Qp(D);return Y.Signature.fromCompact(W.substring(2,130)).addRecoveryBit(V)})().recoverPublicKey(Q.substring(2)).toHex(!1)}`}function Qp($){if($===0||$===1)return $;if($===27)return 0;if($===28)return 1;throw Error("Invalid yParityOrV value")}async function rV({hash:$,signature:J}){return ld(await Xp({hash:$,signature:J}))}g1();d$();e$();Ow();g1();d$();function Yp($,J="hex"){let Q=Gp($),Y=n5(new Uint8Array(Q.length));if(Q.encode(Y),J==="hex")return O4(Y.bytes);return Y.bytes}function Gp($){if(Array.isArray($))return GV$($.map((J)=>Gp(J)));return WV$($)}function GV$($){let J=$.reduce((X,G)=>X+G.length,0),Q=Wp(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 WV$($){let J=typeof $==="string"?b1($):$,Q=Wp(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 Wp($){if($<256)return 1;if($<65536)return 2;if($<16777216)return 3;if($<4294967296)return 4;throw new h("Length is too large.")}d0();function Dp($){let{chainId:J,nonce:Q,to:Y}=$,X=$.contractAddress??$.address,G=C4(p0(["0x05",Yp([J?N$(J):"0x",X,Q?N$(Q):"0x"])]));if(Y==="bytes")return b1(G);return G}async function $H($){let{authorization:J,signature:Q}=$;return rV({hash:Dp(J),signature:Q??J})}d$();Cw();JG();e$();TQ();class PE extends h{constructor($,{account:J,docsPath:Q,chain:Y,data:X,gas:G,gasPrice:W,maxFeePerGas:D,maxPriorityFeePerGas:V,nonce:K,to:O,value:N}){let M=j9({from:J?.address,to:O,value:typeof N<"u"&&`${$G(N)} ${Y?.nativeCurrency?.symbol||"ETH"}`,data:X,gas:G,gasPrice:typeof W<"u"&&`${N1(W)} gwei`,maxFeePerGas:typeof D<"u"&&`${N1(D)} gwei`,maxPriorityFeePerGas:typeof V<"u"&&`${N1(V)} gwei`,nonce:K});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=$}}k9();dV();function Vp($,{docsPath:J,...Q}){let Y=(()=>{let X=r8($,Q);if(X instanceof o0)return $;return X})();return new PE(Y,{docsPath:J,...Q})}vG();pw();x9();JG();e$();class tV extends h{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class g9 extends h{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class vE extends h{constructor({maxPriorityFeePerGas:$}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${N1($)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}N6();e$();class aV extends h{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"})}}d$();N6();var kE={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function bG($,J){let Q={...$,blockHash:$.blockHash?$.blockHash:null,blockNumber:$.blockNumber?BigInt($.blockNumber):null,...$.blockTimestamp!=null&&{blockTimestamp:BigInt($.blockTimestamp)},chainId:$.chainId?I1($.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?I1($.nonce):void 0,to:$.to?$.to:null,transactionIndex:$.transactionIndex?Number($.transactionIndex):null,type:$.type?kE[$.type]:void 0,typeHex:$.type?$.type:void 0,value:$.value?BigInt($.value):void 0,v:$.v?BigInt($.v):void 0};if($.authorizationList)Q.authorizationList=DV$($.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 DV$($){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 JH($,J){let Q=($.transactions??[]).map((Y)=>{if(typeof Y==="string")return Y;return bG(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 Z1($,{blockHash:J,blockNumber:Q,blockTag:Y=$.experimental_blockTag??"latest",includeTransactions:X}={}){let G=X??!1,W=Q!==void 0?N$(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 aV({blockHash:J,blockNumber:Q});return($.chain?.formatters?.block?.format||JH)(D,"getBlock")}async function gG($){let J=await $.request({method:"eth_gasPrice"});return BigInt(J)}async function Kp($,J){return xE($,J)}async function xE($,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 W$($,Z1,"getBlock")({}),V=await G({block:D,client:$,request:X});if(V===null)throw Error();return V}if(typeof G<"u")return G;let W=await $.request({method:"eth_maxPriorityFeePerGas"});return f1(W)}catch{let[G,W]=await Promise.all([Q?Promise.resolve(Q):W$($,Z1,"getBlock")({}),W$($,gG,"getGasPrice")({})]);if(typeof G.baseFeePerGas!=="bigint")throw new g9;let D=W-G.baseFeePerGas;if(D<0n)return 0n;return D}}async function Up($,J){return QH($,J)}async function QH($,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 tV;let V=10**(W.toString().split(".")[1]?.length??0),K=(M)=>M*BigInt(Math.ceil(W*V))/BigInt(V),O=Q?Q:await W$($,Z1,"getBlock")({});if(typeof Y?.fees?.estimateFeesPerGas==="function"){let M=await Y.fees.estimateFeesPerGas({block:Q,client:$,multiply:K,request:X,type:G});if(M!==null)return M}if(G==="eip1559"){if(typeof O.baseFeePerGas!=="bigint")throw new g9;let M=typeof X?.maxPriorityFeePerGas==="bigint"?X.maxPriorityFeePerGas:await xE($,{block:O,chain:Y,request:X}),w=K(O.baseFeePerGas);return{maxFeePerGas:X?.maxFeePerGas??w+M,maxPriorityFeePerGas:M}}return{gasPrice:X?.gasPrice??K(await W$($,gG,"getGasPrice")({}))}}N6();d$();async function XH($,{address:J,blockTag:Q="latest",blockNumber:Y}){let X=await $.request({method:"eth_getTransactionCount",params:[J,typeof Y==="bigint"?N$(Y):Q]},{dedupe:Boolean(Y)});return I1(X)}g1();d$();function YH($){let{kzg:J}=$,Q=$.to??(typeof $.blobs[0]==="string"?"hex":"bytes"),Y=typeof $.blobs[0]==="string"?$.blobs.map((G)=>b1(G)):$.blobs,X=[];for(let G of Y)X.push(Uint8Array.from(J.blobToKzgCommitment(G)));return Q==="bytes"?X:X.map((G)=>O4(G))}g1();d$();function GH($){let{kzg:J}=$,Q=$.to??(typeof $.blobs[0]==="string"?"hex":"bytes"),Y=typeof $.blobs[0]==="string"?$.blobs.map((W)=>b1(W)):$.blobs,X=typeof $.commitments[0]==="string"?$.commitments.map((W)=>b1(W)):$.commitments,G=[];for(let W=0;W<Y.length;W++){let D=Y[W],V=X[W];G.push(Uint8Array.from(J.computeBlobKzgProof(D,V)))}return Q==="bytes"?G:G.map((W)=>O4(W))}d$();QV();var WH=OQ;g1();d$();function Op($,J){let Q=J||"hex",Y=WH(Q1($,{strict:!1})?V0($):$);if(Q==="bytes")return Y;return o1(Y)}function Np($){let{commitment:J,version:Q=1}=$,Y=$.to??(typeof J==="string"?"hex":"bytes"),X=Op(J,"bytes");return X.set([Q],0),Y==="bytes"?X:O4(X)}function Mp($){let{commitments:J,version:Q}=$,Y=$.to??(typeof J[0]==="string"?"hex":"bytes"),X=[];for(let G of J)X.push(Np({commitment:G,to:Y,version:Q}));return X}var wp=32,Hp=4096,Ap=131072,fE=761855;e$();class bE extends h{constructor({maxSize:$,size:J}){super("Blob size is too large.",{metaMessages:[`Max: ${$} bytes`,`Given: ${J} bytes`],name:"BlobSizeTooLargeError"})}}class gE extends h{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}Ow();D0();g1();d$();function zp($){let J=$.to??(typeof $.data==="string"?"hex":"bytes"),Q=typeof $.data==="string"?b1($.data):$.data,Y=X4(Q);if(!Y)throw new gE;if(Y>fE)throw new bE({maxSize:fE,size:Y});let X=[],G=!0,W=0;while(G){let D=n5(new Uint8Array(Ap)),V=0;while(V<Hp){let K=Q.slice(W,W+(wp-1));if(D.pushByte(0),D.pushBytes(K),K.length<31){D.pushByte(128),G=!1;break}V++,W+=31}X.push(D)}return J==="bytes"?X.map((D)=>D.bytes):X.map((D)=>O4(D.bytes))}function Ip($){let{data:J,kzg:Q,to:Y}=$,X=$.blobs??zp({data:J,to:Y}),G=$.commitments??YH({blobs:X,kzg:Q,to:Y}),W=$.proofs??GH({blobs:X,commitments:G,kzg:Q,to:Y}),D=[];for(let V=0;V<X.length;V++)D.push({blob:X[V],commitment:G[V],proof:W[V]});return D}IV();x9();TQ();function qp($){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 xj({transaction:$})}k9();TQ();dV();function Zp($,{docsPath:J,...Q}){let Y=(()=>{let X=r8($,Q);if(X instanceof o0)return $;return X})();return new fj(Y,{docsPath:J,...Q})}vG();x9();N6();async function yG($){let J=await $.request({method:"eth_chainId"},{dedupe:!0});return I1(J)}async function DH($,J){let{account:Q=$.account,accessList:Y,authorizationList:X,chain:G=$.chain,blobVersionedHashes:W,blobs:D,data:V,gas:K,gasPrice:O,maxFeePerBlobGas:N,maxFeePerGas:M,maxPriorityFeePerGas:w,nonce:z,nonceManager:q,to:F,type:Z,value:E,...B}=J,L=await(async()=>{if(!Q)return z;if(!q)return z;if(typeof z<"u")return z;let f=g4(Q),u=G?G.id:await W$($,yG,"getChainId")({});return await q.consume({address:f.address,chainId:u,client:$})})();w0(J);let j=G?.formatters?.transactionRequest?.format,x=(j||TJ)({...t8(B,{format:j}),account:Q?g4(Q):void 0,accessList:Y,authorizationList:X,blobs:D,blobVersionedHashes:W,data:V,gas:K,gasPrice:O,maxFeePerBlobGas:N,maxFeePerGas:M,maxPriorityFeePerGas:w,nonce:L,to:F,type:Z,value:E},"fillTransaction");try{let f=await $.request({method:"eth_fillTransaction",params:[x]}),R=(G?.formatters?.transaction?.format||bG)(f.tx);if(delete R.blockHash,delete R.blockNumber,delete R.r,delete R.s,delete R.transactionIndex,delete R.v,delete R.yParity,R.data=R.input,R.gas)R.gas=J.gas??R.gas;if(R.gasPrice)R.gasPrice=J.gasPrice??R.gasPrice;if(R.maxFeePerBlobGas)R.maxFeePerBlobGas=J.maxFeePerBlobGas??R.maxFeePerBlobGas;if(R.maxFeePerGas)R.maxFeePerGas=J.maxFeePerGas??R.maxFeePerGas;if(R.maxPriorityFeePerGas)R.maxPriorityFeePerGas=J.maxPriorityFeePerGas??R.maxPriorityFeePerGas;if(typeof R.nonce<"u")R.nonce=J.nonce??R.nonce;let d=await(async()=>{if(typeof G?.fees?.baseFeeMultiplier==="function"){let k=await W$($,Z1,"getBlock")({});return G.fees.baseFeeMultiplier({block:k,client:$,request:J})}return G?.fees?.baseFeeMultiplier??1.2})();if(d<1)throw new tV;let Y$=10**(d.toString().split(".")[1]?.length??0),c=(k)=>k*BigInt(Math.ceil(d*Y$))/BigInt(Y$);if(!R.feePayerSignature){if(R.maxFeePerGas&&!J.maxFeePerGas)R.maxFeePerGas=c(R.maxFeePerGas);if(R.gasPrice&&!J.gasPrice)R.gasPrice=c(R.gasPrice)}return{raw:f.raw,transaction:{from:x.from,...R},...f.capabilities?{capabilities:f.capabilities}:{}}}catch(f){throw Zp(f,{...J,chain:$.chain})}}var VV$=["blobVersionedHashes","chainId","fees","gas","nonce","type"],Lp=new Map,yE=new ZQ(128);async function VH($,J){let Q=J;Q.account??=$.account,Q.parameters??=VV$;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})(),V;async function K(){if(V)return V;if(typeof Q.chainId<"u")return Q.chainId;if(X)return X.id;return V=await W$($,yG,"getChainId")({}),V}let O=Y?g4(Y):Y,N=Q.nonce;if(W.includes("nonce")&&typeof N>"u"&&O&&G){let L=await K();N=await G.consume({address:O.address,chainId:L,client:$})}if(D?.fn&&D.runAt?.includes("beforeFillTransaction"))Q=await D.fn({...Q,chain:X},{phase:"beforeFillTransaction"}),N??=Q.nonce;let w=(()=>{if((W.includes("blobVersionedHashes")||W.includes("sidecars"))&&Q.kzg&&Q.blobs)return!1;if(yE.get($.uid)===!1)return!1;if(!["fees","gas"].some((j)=>W.includes(j)))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 W$($,DH,"fillTransaction")({...Q,nonce:N}).then((L)=>{let{chainId:j,from:T,gas:x,gasPrice:f,nonce:u,maxFeePerBlobGas:R,maxFeePerGas:d,maxPriorityFeePerGas:p,type:Y$,...c}=L.transaction;return yE.set($.uid,!0),{...Q,...T?{from:T}:{},...Y$&&!Q.type?{type:Y$}:{},...typeof j<"u"?{chainId:j}:{},...typeof x<"u"?{gas:x}:{},...typeof f<"u"?{gasPrice:f}:{},...typeof u<"u"?{nonce:u}:{},...typeof R<"u"&&Q.type!=="legacy"&&Q.type!=="eip2930"?{maxFeePerBlobGas:R}:{},...typeof d<"u"&&Q.type!=="legacy"&&Q.type!=="eip2930"?{maxFeePerGas:d}:{},...typeof p<"u"&&Q.type!=="legacy"&&Q.type!=="eip2930"?{maxPriorityFeePerGas:p}:{},..."nonceKey"in c&&typeof c.nonceKey<"u"?{nonceKey:c.nonceKey}:{},..."keyAuthorization"in c&&typeof c.keyAuthorization<"u"&&c.keyAuthorization!==null&&!("keyAuthorization"in Q)?{keyAuthorization:c.keyAuthorization}:{},..."feePayerSignature"in c&&typeof c.feePayerSignature<"u"&&c.feePayerSignature!==null?{feePayerSignature:c.feePayerSignature}:{},..."feeToken"in c&&typeof c.feeToken<"u"&&c.feeToken!==null&&!("feeToken"in Q)?{feeToken:c.feeToken}:{},...L.capabilities?{_capabilities:L.capabilities}:{}}}).catch((L)=>{let j=L;if(j.name!=="TransactionExecutionError")return Q;if(j.walk?.((f)=>{return f.name==="ExecutionRevertedError"}))throw L;if(j.walk?.((f)=>{let u=f;return u.name==="MethodNotFoundRpcError"||u.name==="MethodNotSupportedRpcError"||u.message?.includes("eth_fillTransaction is not available")}))yE.set($.uid,!1);return Q}):Q;N??=w.nonce,Q={...w,...O?{from:O?.address}:{},...typeof N<"u"?{nonce:N}:{}};let{blobs:z,gas:q,kzg:F,type:Z}=Q;if(D?.fn&&D.runAt?.includes("beforeFillParameters"))Q=await D.fn({...Q,chain:X},{phase:"beforeFillParameters"});let E;async function B(){if(E)return E;return E=await W$($,Z1,"getBlock")({blockTag:"latest"}),E}if(W.includes("nonce")&&typeof N>"u"&&O&&!G)Q.nonce=await W$($,XH,"getTransactionCount")({address:O.address,blockTag:"pending"});if((W.includes("blobVersionedHashes")||W.includes("sidecars"))&&z&&F){let L=YH({blobs:z,kzg:F});if(W.includes("blobVersionedHashes")){let j=Mp({commitments:L,to:"hex"});Q.blobVersionedHashes=j}if(W.includes("sidecars")){let j=GH({blobs:z,commitments:L,kzg:F}),T=Ip({blobs:z,commitments:L,proofs:j,to:"hex"});Q.sidecars=T}}if(W.includes("chainId"))Q.chainId=await K();if((W.includes("fees")||W.includes("type"))&&typeof Z>"u")try{Q.type=qp(Q)}catch{let L=Lp.get($.uid);if(typeof L>"u")L=typeof(await B())?.baseFeePerGas==="bigint",Lp.set($.uid,L);Q.type=L?"eip1559":"legacy"}if(W.includes("fees"))if(Q.type!=="legacy"&&Q.type!=="eip2930"){if(typeof Q.maxFeePerGas>"u"||typeof Q.maxPriorityFeePerGas>"u"){let L=await B(),{maxFeePerGas:j,maxPriorityFeePerGas:T}=await QH($,{block:L,chain:X,request:Q});if(typeof Q.maxPriorityFeePerGas>"u"&&Q.maxFeePerGas&&Q.maxFeePerGas<T)throw new vE({maxPriorityFeePerGas:T});Q.maxPriorityFeePerGas=T,Q.maxFeePerGas=j}}else{if(typeof Q.maxFeePerGas<"u"||typeof Q.maxPriorityFeePerGas<"u")throw new g9;if(typeof Q.gasPrice>"u"){let L=await B(),{gasPrice:j}=await QH($,{block:L,chain:X,request:Q,type:"legacy"});Q.gasPrice=j}}if(W.includes("gas")&&typeof q>"u")Q.gas=await W$($,hG,"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 w0(Q),delete Q.parameters,Q}async function hG($,J){let{account:Q=$.account,prepare:Y=!0}=J,X=Q?g4(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 $H({authorization:J.authorizationList[0]}).catch(()=>{throw new h("`to` is required. Could not infer from `authorizationList`")});return})(),{accessList:D,authorizationList:V,blobs:K,blobVersionedHashes:O,blockNumber:N,blockTag:M,data:w,gas:z,gasPrice:q,maxFeePerBlobGas:F,maxFeePerGas:Z,maxPriorityFeePerGas:E,nonce:B,value:L,stateOverride:j,...T}=Y?await VH($,{...J,parameters:G,to:W}):J;if(z&&J.gas!==z)return z;let f=(typeof N==="bigint"?N$(N):void 0)||M,u=kG(j);w0(J);let R=$.chain?.formatters?.transactionRequest?.format,p=(R||TJ)({...t8(T,{format:R}),account:X,accessList:D,authorizationList:V,blobs:K,blobVersionedHashes:O,data:w,gasPrice:q,maxFeePerBlobGas:F,maxFeePerGas:Z,maxPriorityFeePerGas:E,nonce:B,to:W,value:L},"estimateGas");return BigInt(await $.request({method:"eth_estimateGas",params:u?[p,f??$.experimental_blockTag??"latest",u]:f?[p,f]:[p]}))}catch(W){throw Vp(W,{...J,account:X,chain:$.chain})}}async function Bp($,J){let{abi:Q,address:Y,args:X,functionName:G,dataSuffix:W=typeof $.dataSuffix==="string"?$.dataSuffix:$.dataSuffix?.value,...D}=J,V=n4({abi:Q,args:X,functionName:G});try{return await W$($,hG,"estimateGas")({data:`${V}${W?W.replace("0x",""):""}`,to:Y,...D})}catch(K){let O=D.account?g4(D.account):void 0;throw i0(K,{abi:Q,address:Y,args:X,docsPath:"/docs/contract/estimateContractGas",functionName:G,sender:O?.address})}}BJ();_Q();U0();d$();f9();async function Fp($,{address:J,blockNumber:Q,blockTag:Y=$.experimental_blockTag??"latest"}){if($.batch?.multicall&&$.chain?.contracts?.multicall3){let W=$.chain.contracts.multicall3.address,D=n4({abi:h0,functionName:"getEthBalance",args:[J]}),{data:V}=await W$($,H0,"call")({to:W,data:D,blockNumber:Q,blockTag:Y});return r1({abi:h0,functionName:"getEthBalance",args:[J],data:V||"0x"})}let X=typeof Q==="bigint"?N$(Q):void 0,G=await $.request({method:"eth_getBalance",params:[J,X||Y]});return BigInt(G)}async function jp($){let J=await $.request({method:"eth_blobBaseFee"});return BigInt(J)}var KV$=new Map,UV$=new Map;function Ep($){let J=(X,G)=>({clear:()=>G.delete(X),get:()=>G.get(X),set:(W)=>G.set(X,W)}),Q=J($,KV$),Y=J($,UV$);return{clear:()=>{Q.clear(),Y.clear()},promise:Q,response:Y}}async function Sp($,{cacheKey:J,cacheTime:Q=Number.POSITIVE_INFINITY}){let Y=Ep(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 OV$=($)=>`blockNumber.${$}`;async function CJ($,{cacheTime:J=$.cacheTime}={}){let Q=await Sp(()=>$.request({method:"eth_blockNumber"}),{cacheKey:OV$($.uid),cacheTime:J});return BigInt(Q)}N6();d$();async function _p($,{blockHash:J,blockNumber:Q,blockTag:Y="latest"}={}){let X=Q!==void 0?N$(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 I1(G)}d$();async function y9($,{address:J,blockNumber:Q,blockTag:Y="latest"}){let X=Q!==void 0?N$(Q):void 0,G=await $.request({method:"eth_getCode",params:[J,X||Y]},{dedupe:Boolean(X)});if(G==="0x")return;return G}d8();xG();g1();function L1($,{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}:{}}}d0();jV();J1();eF();D0();jV();LV();zQ();var Tp="/docs/contract/decodeEventLog";function h9($){let{abi:J,data:Q,strict:Y,topics:X}=$,G=Y??!0,[W,...D]=X;if(!W)throw new gF({docsPath:Tp});let V=J.find((Z)=>Z.type==="event"&&W===l8(O1(Z)));if(!(V&&("name"in V))||V.type!=="event")throw new yF(W,{docsPath:Tp});let{name:K,inputs:O}=V,N=O?.some((Z)=>!(("name"in Z)&&Z.name)),M=N?[]:{},w=O.map((Z,E)=>[Z,E]).filter(([Z])=>("indexed"in Z)&&Z.indexed),z=[];for(let Z=0;Z<w.length;Z++){let[E,B]=w[Z],L=D[Z];if(!L){if(G)throw new A9({abiItem:V,param:E});z.push([E,B]);continue}M[N?B:E.name||B]=NV$({param:E,value:L})}let q=O.filter((Z)=>!(("indexed"in Z)&&Z.indexed)),F=G?q:[...z.map(([Z])=>Z),...q];if(F.length>0){if(Q&&Q!=="0x")try{let Z=FQ(F,Q);if(Z){let E=0;if(!G)for(let[B,L]of z)M[N?L:B.name||L]=Z[E++];if(N){for(let B=0;B<O.length;B++)if(M[B]===void 0&&E<Z.length)M[B]=Z[E++]}else for(let B=0;B<q.length;B++)M[q[B].name]=Z[E++]}}catch(Z){if(G){if(Z instanceof NV||Z instanceof qV)throw new h8({abiItem:V,data:Q,params:F,size:X4(Q)});throw Z}}else if(G)throw new h8({abiItem:V,data:"0x",params:F,size:0})}return{eventName:K,args:Object.values(M).length>0?M:void 0}}function NV$({param:$,value:J}){if($.type==="string"||$.type==="bytes"||$.type==="tuple"||$.type.match(/^(.*)\[(\d+)?\]$/))return J;return(FQ([$],J)||[])[0]}function uG($){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:l8(D)}));return Y.map((D)=>{let V=typeof D.blockNumber==="string"?L1(D):D,K=W.filter((M)=>V.topics[0]===M.selector);if(K.length===0)return null;let O,N;for(let M of K)try{O=h9({...V,abi:[M.abi],strict:!0}),N=M;break}catch{}if(!O&&!X){N=K[0];try{O=h9({data:V.data,topics:V.topics,abi:[N.abi],strict:!1})}catch{let M=N.abi.inputs?.some((w)=>!(("name"in w)&&w.name));return{...V,args:M?[]:{},eventName:N.abi.name}}}if(!O||!N)return null;if(G&&!G.includes(O.eventName))return null;if(!MV$({args:O.args,inputs:N.abi.inputs,matchArgs:Q}))return null;return{...O,...V}}).filter(Boolean)}function MV$($){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 r0(W,D);if(G.type==="string"||G.type==="bytes")return C4(V0(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((K)=>X(D,K,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((K)=>K.name===G);if(!D)return!1;return(Array.isArray(W)?W:[W]).some((K)=>X(D,K,J[G]))});return!1}d$();async function mG($,{address:J,blockHash:Q,fromBlock:Y,toBlock:X,event:G,events:W,args:D,strict:V}={}){let K=V??!1,O=W??(G?[G]:void 0),N=[];if(O){if(N=[O.flatMap((q)=>RJ({abi:[q],eventName:q.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"?N$(Y):Y,toBlock:typeof X==="bigint"?N$(X):X}]});let w=M.map((z)=>L1(z));if(!O)return w;return uG({abi:O,args:D,logs:w,strict:K})}async function KH($,J){let{abi:Q,address:Y,args:X,blockHash:G,eventName:W,fromBlock:D,toBlock:V,strict:K}=J,O=W?b6({abi:Q,name:W}):void 0,N=!O?Q.filter((M)=>M.type==="event"):void 0;return W$($,mG,"getLogs")({address:Y,args:X,blockHash:G,event:O,events:N,fromBlock:D,toBlock:V,strict:K})}Z9();D0();B9();async function Rp($,{address:J,blockNumber:Q,blockTag:Y="latest"}){let X=await y9($,{address:J,...Q!==void 0?{blockNumber:Q}:{blockTag:Y}});if(!X)return;if(X4(X)!==23)return;if(!X.startsWith("0xef0100"))return;return L9(K0(X,3,23))}e$();class hE extends h{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 Cp($,J){let{address:Q,factory:Y,factoryData:X}=J;try{let[G,W,D,V,K,O,N]=await W$($,W1,"readContract")({abi:wV$,address:Q,functionName:"eip712Domain",factory:Y,factoryData:X});return{domain:{name:W,version:D,chainId:Number(V),verifyingContract:K,salt:O},extensions:N,fields:G}}catch(G){let W=G;if(W.name==="ContractFunctionExecutionError"&&W.cause.name==="ContractFunctionZeroDataError")throw new hE({address:Q});throw W}}var wV$=[{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"}];d$();function Pp($){return{baseFeePerGas:$.baseFeePerGas.map((J)=>BigInt(J)),gasUsedRatio:$.gasUsedRatio,oldestBlock:BigInt($.oldestBlock),reward:$.reward?.map((J)=>J.map((Q)=>BigInt(Q)))}}async function vp($,{blockCount:J,blockNumber:Q,blockTag:Y="latest",rewardPercentiles:X}){let G=typeof Q==="bigint"?N$(Q):void 0,W=await $.request({method:"eth_feeHistory",params:[N$(J),G||Y,X]},{dedupe:Boolean(G)});return Pp(W)}async function JX($,{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)=>L1(G));if(!("abi"in J)||!J.abi)return X;return uG({abi:J.abi,logs:X,strict:Q})}async function kp($,{filter:J}){let Q=J.strict??!1,X=(await J.request({method:"eth_getFilterLogs",params:[J.id]})).map((G)=>L1(G));if(!J.abi)return X;return uG({abi:J.abi,logs:X,strict:Q})}d$();N6();function HV$($){return $.map((J)=>({...J,value:BigInt(J.value)}))}function xp($){return{...$,balance:$.balance?BigInt($.balance):void 0,nonce:$.nonce?I1($.nonce):void 0,storageProof:$.storageProof?HV$($.storageProof):void 0}}async function fp($,{address:J,blockNumber:Q,blockTag:Y,storageKeys:X}){let G=Y??"latest",W=Q!==void 0?N$(Q):void 0,D=await $.request({method:"eth_getProof",params:[J,X,W||G]});return xp(D)}d$();async function bp($,{address:J,blockNumber:Q,blockTag:Y="latest",slot:X}){let G=Q!==void 0?N$(Q):void 0;return await $.request({method:"eth_getStorageAt",params:[J,X,G||Y]})}TQ();d$();async function lG($,{blockHash:J,blockNumber:Q,blockTag:Y,hash:X,index:G,sender:W,nonce:D}){let V=Y||"latest",K=Q!==void 0?N$(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,N$(G)]},{dedupe:!0});else if((K||V)&&typeof G==="number")O=await $.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[K||V,N$(G)]},{dedupe:Boolean(K)});else if(W&&typeof D==="number")O=await $.request({method:"eth_getTransactionBySenderAndNonce",params:[W,N$(D)]},{dedupe:!0});if(!O)throw new EV({blockHash:J,blockNumber:Q,blockTag:V,hash:X,index:G});return($.chain?.formatters?.transaction?.format||bG)(O,"getTransaction")}async function gp($,{hash:J,transactionReceipt:Q}){let[Y,X]=await Promise.all([W$($,CJ,"getBlockNumber")({}),J?W$($,lG,"getTransaction")({hash:J}):void 0]),G=Q?.blockNumber||X?.blockNumber;if(!G)return 0n;return Y-G+1n}TQ();N6();var AV$={"0x0":"reverted","0x1":"success"};function UH($,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)=>L1(Y)):null,to:$.to?$.to:null,transactionIndex:$.transactionIndex?I1($.transactionIndex):null,status:$.status?AV$[$.status]:null,type:$.type?kE[$.type]||$.type:null};if($.blobGasPrice)Q.blobGasPrice=BigInt($.blobGasPrice);if($.blobGasUsed)Q.blobGasUsed=BigInt($.blobGasUsed);return Q}async function dG($,{hash:J}){let Q=await $.request({method:"eth_getTransactionReceipt",params:[J]},{dedupe:!0});if(!Q)throw new SV({hash:J});return($.chain?.formatters?.transactionReceipt?.format||UH)(Q,"getTransactionReceipt")}BJ();J1();e$();p8();_Q();U0();F9();async function yp($,J){let{account:Q,authorizationList:Y,allowFailure:X=!0,blockNumber:G,blockOverrides:W,blockTag:D,stateOverride:V}=J,K=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 O0({blockNumber:G,chain:$.chain,contract:"multicall3"});throw Error("client chain not configured. multicallAddress is required.")})(),w=[[]],z=0,q=0;for(let E=0;E<K.length;E++){let{abi:B,address:L,args:j,functionName:T}=K[E];try{let x=n4({abi:B,args:j,functionName:T});if(q+=(x.length-2)/2,O>0&&q>O&&w[z].length>0)z++,q=(x.length-2)/2,w[z]=[];w[z]=[...w[z],{allowFailure:!0,callData:x,target:L}]}catch(x){let f=i0(x,{abi:B,address:L,args:j,docsPath:"/docs/contract/multicall",functionName:T,sender:Q});if(!X)throw f;w[z]=[...w[z],{allowFailure:!0,callData:"0x",target:L}]}}let F=await Promise.allSettled(w.map((E)=>W$($,W1,"readContract")({...M===null?{code:PG}:{address:M},abi:h0,account:Q,args:[E],authorizationList:Y,blockNumber:G,blockOverrides:W,blockTag:D,functionName:"aggregate3",stateOverride:V}))),Z=[];for(let E=0;E<F.length;E++){let B=F[E];if(B.status==="rejected"){if(!X)throw B.reason;for(let j=0;j<w[E].length;j++)Z.push({status:"failure",error:B.reason,result:void 0});continue}let L=B.value;for(let j=0;j<L.length;j++){let{returnData:T,success:x}=L[j],{callData:f}=w[E][j],{abi:u,address:R,functionName:d,args:p}=K[Z.length];try{if(f==="0x")throw new u0;if(!x)throw new RQ({data:T});let Y$=r1({abi:u,args:p,data:T,functionName:d});Z.push(X?{result:Y$,status:"success"}:Y$)}catch(Y$){let c=i0(Y$,{abi:u,address:R,args:p,docsPath:"/docs/contract/multicall",functionName:d});if(!X)throw c;Z.push({error:c,result:void 0,status:"failure"})}}}if(Z.length!==K.length)throw new h("multicall results mismatch");return Z}YE();J1();p8();k9();_Q();U0();d$();dV();vG();pw();x9();async function sV($,J){let{blockNumber:Q,blockTag:Y=$.experimental_blockTag??"latest",blocks:X,returnFullTransactions:G,traceTransfers:W,validation:D}=J;try{let V=[];for(let M of X){let w=M.blockOverrides?hw(M.blockOverrides):void 0,z=M.calls.map((F)=>{let Z=F,E=Z.account?g4(Z.account):void 0,B=Z.abi?n4(Z):Z.data,L={...Z,account:E,data:Z.dataSuffix?y1([B||"0x",Z.dataSuffix]):B,from:Z.from??E?.address};return w0(L),TJ(L)}),q=M.stateOverrides?kG(M.stateOverrides):void 0;V.push({blockOverrides:w,calls:z,stateOverrides:q})}let O=(typeof Q==="bigint"?N$(Q):void 0)||Y;return(await $.request({method:"eth_simulateV1",params:[{blockStateCalls:V,returnFullTransactions:G,traceTransfers:W,validation:D},O]})).map((M,w)=>({...JH(M),calls:M.calls.map((z,q)=>{let{abi:F,args:Z,functionName:E,to:B}=X[w].calls[q],L=z.error?.data??z.returnData,j=BigInt(z.gasUsed),T=z.logs?.map((R)=>L1(R)),x=z.status==="0x1"?"success":"failure",f=F&&x==="success"&&L!=="0x"?r1({abi:F,data:L,functionName:E}):null,u=(()=>{if(x==="success")return;let R;if(L==="0x")R=new u0;else if(L)R=new RQ({data:L});if(!R)return;return i0(R,{abi:F??[],address:B??"0x",args:Z,functionName:E??"<unknown>"})})();return{data:L,gasUsed:j,logs:T,status:x,...x==="success"?{result:f}:{error:u}}})}))}catch(V){let K=V,O=r8(K,{});if(O instanceof o0)throw K;throw O}}a5();g6();Kw();c8();q1();function u9($,J={}){let{as:Q=typeof $==="string"?"Hex":"Bytes"}=J,Y=p5(Dd($));if(Q==="Bytes")return Y;return X1(Y)}q1();c8();class mE 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 zV$={checksum:new mE(8192)},OH=zV$.checksum;g6();c8();g6();q1();function hp($,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 lE({prefix:Y,cause:new pp});return}if(Q===!0||typeof X==="bigint"&&typeof G>"u"){if(Y!==3&&Y!==2)throw new lE({prefix:Y,cause:new dp});return}throw new lp({publicKey:$})}function up($){let J=(()=>{if(kV($))return mp($);if(Md($))return qV$($);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 hp(J),J}function qV$($){return mp(X1($))}function mp($){if($.length!==132&&$.length!==130&&$.length!==68)throw new np({publicKey:$});if($.length===130){let Y=BigInt(l4($,0,32)),X=BigInt(l4($,32,64));return{prefix:4,x:Y,y:X}}if($.length===132){let Y=Number(l4($,0,1)),X=BigInt(l4($,1,33)),G=BigInt(l4($,33,65));return{prefix:Y,x:X,y:G}}let J=Number(l4($,0,1)),Q=BigInt(l4($,1,33));return{prefix:J,x:Q}}function dE($,J={}){hp($);let{prefix:Q,x:Y,y:X}=$,{includePrefix:G=!0}=J;return c4(G?V4(Q,{size:1}):"0x",V4(Y,{size:32}),typeof X==="bigint"?V4(X,{size:32}):"0x")}class lp extends w${constructor({publicKey:$}){super(`Value \`${i8($)}\` 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 lE extends w${constructor({prefix:$,cause:J}){super(`Prefix "${$}" is invalid.`,{cause:J});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class dp extends w${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 pp extends w${constructor(){super("Prefix must be 4 for uncompressed public keys.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}class np extends w${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 ${m4(RG($))} bytes.`]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}}var ZV$=/^0x[a-fA-F0-9]{40}$/;function m9($,J={}){let{strict:Q=!0}=J;if(!ZV$.test($))throw new pE({address:$,cause:new op});if(Q){if($.toLowerCase()===$)return;if(NH($)!==$)throw new pE({address:$,cause:new rp})}}function NH($){if(OH.has($))return OH.get($);m9($,{strict:!1});let J=$.substring(2).toLowerCase(),Q=u9(Vd(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 OH.set($,X),X}function LV$($,J={}){let{checksum:Q=!1}=J;if(m9($),Q)return NH($);return $}function ip($,J={}){let Q=u9(`0x${dE($).slice(4)}`).substring(26);return LV$(`0x${Q}`,J)}function MH($,J={}){let{strict:Q=!0}=J??{};try{return m9($,{strict:Q}),!0}catch{return!1}}class pE extends w${constructor({address:$,cause:J}){super(`Address "${$}" is invalid.`,{cause:J});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class op extends w${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 rp extends w${constructor(){super("Address does not match its checksum counterpart.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}g6();function AH($){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 w$("Unable to normalize signature.");return X}function HH($,J){let Q=typeof $,Y=J.type;switch(Y){case"address":return MH($,{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 HH(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)=>HH(X,{...J,type:Y.replace(/(\[[0-9]{0,}\])$/,"")}));return!1}}}function nE($,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 nE(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 MH(Q[Y],{strict:!1});if(W.includes("address")&&W.includes("bytes"))return MH(Q[Y],{strict:!1});return!1})())return W}return}function zH($,J={}){let{prepare:Q=!0}=J,Y=(()=>{if(Array.isArray($))return Bw($);if(typeof $==="string")return Bw($);return $})();return{...Y,...Q?{hash:pG(Y)}:{}}}function eV($,J,Q){let{args:Y=[],prepare:X=!0}=Q??{},G=kV(J,{strict:!1}),W=$.filter((K)=>{if(G){if(K.type==="function"||K.type==="error")return cE(K)===l4(J,0,4);if(K.type==="event")return pG(K)===J;return!1}return"name"in K&&K.name===J});if(W.length===0)throw new l9({name:J});if(W.length===1)return{...W[0],...X?{hash:pG(W[0])}:{}};let D;for(let K of W){if(!("inputs"in K))continue;if(!Y||Y.length===0){if(!K.inputs||K.inputs.length===0)return{...K,...X?{hash:pG(K)}:{}};continue}if(!K.inputs)continue;if(K.inputs.length===0)continue;if(K.inputs.length!==Y.length)continue;if(Y.every((N,M)=>{let w="inputs"in K&&K.inputs[M];if(!w)return!1;return HH(N,w)})){if(D&&"inputs"in D&&D.inputs){let N=nE(K.inputs,D.inputs,Y);if(N)throw new tp({abiItem:K,type:N[0]},{abiItem:D,type:N[1]})}D=K}}let V=(()=>{if(D)return D;let[K,...O]=W;return{...K,overloads:O}})();if(!V)throw new l9({name:J});return{...V,...X?{hash:pG(V)}:{}}}function cE(...$){let J=(()=>{if(Array.isArray($[0])){let[Q,Y]=$;return eV(Q,Y)}return $[0]})();return l4(pG(J),0,4)}function FV$(...$){let J=(()=>{if(Array.isArray($[0])){let[Y,X]=$;return eV(Y,X)}return $[0]})(),Q=(()=>{if(typeof J==="string")return J;return EQ(J)})();return AH(Q)}function pG(...$){let J=(()=>{if(Array.isArray($[0])){let[Q,Y]=$;return eV(Q,Y)}return $[0]})();if(typeof J!=="string"&&"hash"in J&&J.hash)return J.hash;return u9(CG(FV$(J)))}class tp extends w${constructor($,J){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${$.type}\` in \`${AH(EQ($.abiItem))}\`, and`,`\`${J.type}\` in \`${AH(EQ(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 l9 extends w${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"})}}a5();c8();g6();q1();c8();g6();q1();var sp=/^(.*)\[([0-9]*)\]$/,ep=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,IH=/^(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)?$/,jl$=2n**(8n-1n)-1n,El$=2n**(16n-1n)-1n,Sl$=2n**(24n-1n)-1n,_l$=2n**(32n-1n)-1n,Tl$=2n**(40n-1n)-1n,Rl$=2n**(48n-1n)-1n,Cl$=2n**(56n-1n)-1n,Pl$=2n**(64n-1n)-1n,vl$=2n**(72n-1n)-1n,kl$=2n**(80n-1n)-1n,xl$=2n**(88n-1n)-1n,fl$=2n**(96n-1n)-1n,bl$=2n**(104n-1n)-1n,gl$=2n**(112n-1n)-1n,yl$=2n**(120n-1n)-1n,hl$=2n**(128n-1n)-1n,ul$=2n**(136n-1n)-1n,ml$=2n**(144n-1n)-1n,ll$=2n**(152n-1n)-1n,dl$=2n**(160n-1n)-1n,pl$=2n**(168n-1n)-1n,nl$=2n**(176n-1n)-1n,cl$=2n**(184n-1n)-1n,il$=2n**(192n-1n)-1n,ol$=2n**(200n-1n)-1n,rl$=2n**(208n-1n)-1n,tl$=2n**(216n-1n)-1n,al$=2n**(224n-1n)-1n,sl$=2n**(232n-1n)-1n,el$=2n**(240n-1n)-1n,$d$=2n**(248n-1n)-1n,Jd$=2n**(256n-1n)-1n,Qd$=-(2n**(8n-1n)),Xd$=-(2n**(16n-1n)),Yd$=-(2n**(24n-1n)),Gd$=-(2n**(32n-1n)),Wd$=-(2n**(40n-1n)),Dd$=-(2n**(48n-1n)),Vd$=-(2n**(56n-1n)),Kd$=-(2n**(64n-1n)),Ud$=-(2n**(72n-1n)),Od$=-(2n**(80n-1n)),Nd$=-(2n**(88n-1n)),Md$=-(2n**(96n-1n)),wd$=-(2n**(104n-1n)),Hd$=-(2n**(112n-1n)),Ad$=-(2n**(120n-1n)),zd$=-(2n**(128n-1n)),Id$=-(2n**(136n-1n)),qd$=-(2n**(144n-1n)),Zd$=-(2n**(152n-1n)),Ld$=-(2n**(160n-1n)),Bd$=-(2n**(168n-1n)),Fd$=-(2n**(176n-1n)),jd$=-(2n**(184n-1n)),Ed$=-(2n**(192n-1n)),Sd$=-(2n**(200n-1n)),_d$=-(2n**(208n-1n)),Td$=-(2n**(216n-1n)),Rd$=-(2n**(224n-1n)),Cd$=-(2n**(232n-1n)),Pd$=-(2n**(240n-1n)),vd$=-(2n**(248n-1n)),kd$=-(2n**(256n-1n)),xd$=2n**8n-1n,fd$=2n**16n-1n,bd$=2n**24n-1n,gd$=2n**32n-1n,yd$=2n**40n-1n,hd$=2n**48n-1n,ud$=2n**56n-1n,md$=2n**64n-1n,ld$=2n**72n-1n,dd$=2n**80n-1n,pd$=2n**88n-1n,nd$=2n**96n-1n,cd$=2n**104n-1n,id$=2n**112n-1n,od$=2n**120n-1n,rd$=2n**128n-1n,td$=2n**136n-1n,ad$=2n**144n-1n,sd$=2n**152n-1n,ed$=2n**160n-1n,$p$=2n**168n-1n,Jp$=2n**176n-1n,Qp$=2n**184n-1n,Xp$=2n**192n-1n,Yp$=2n**200n-1n,Gp$=2n**208n-1n,Wp$=2n**216n-1n,Dp$=2n**224n-1n,Vp$=2n**232n-1n,Kp$=2n**240n-1n,Up$=2n**248n-1n,iE=2n**256n-1n;function d9($,J,Q){let{checksumAddress:Y,staticPosition:X}=Q,G=tE(J.type);if(G){let[W,D]=G;return EV$($,{...J,type:D},{checksumAddress:Y,length:W,staticPosition:X})}if(J.type==="tuple")return RV$($,J,{checksumAddress:Y,staticPosition:X});if(J.type==="address")return jV$($,{checksum:Y});if(J.type==="bool")return SV$($);if(J.type.startsWith("bytes"))return _V$($,J,{staticPosition:X});if(J.type.startsWith("uint")||J.type.startsWith("int"))return TV$($,J);if(J.type==="string")return CV$($,{staticPosition:X});throw new JK(J.type)}var Jn=32,oE=32;function jV$($,J={}){let{checksum:Q=!1}=J,Y=$.readBytes(32);return[((G)=>Q?NH(G):G)(X1(Kd(Y,-20))),32]}function EV$($,J,Q){let{checksumAddress:Y,length:X,staticPosition:G}=Q;if(!X){let V=SJ($.readBytes(oE)),K=G+V,O=K+Jn;$.setPosition(K);let N=SJ($.readBytes(Jn)),M=$K(J),w=0,z=[];for(let q=0;q<N;++q){$.setPosition(O+(M?q*32:w));let[F,Z]=d9($,J,{checksumAddress:Y,staticPosition:O});w+=Z,z.push(F)}return $.setPosition(G+32),[z,32]}if($K(J)){let V=SJ($.readBytes(oE)),K=G+V,O=[];for(let N=0;N<X;++N){$.setPosition(K+N*32);let[M]=d9($,J,{checksumAddress:Y,staticPosition:K});O.push(M)}return $.setPosition(G+32),[O,32]}let W=0,D=[];for(let V=0;V<X;++V){let[K,O]=d9($,J,{checksumAddress:Y,staticPosition:G+W});W+=O,D.push(K)}return[D,W]}function SV$($){return[Od($.readBytes(32),{size:32}),32]}function _V$($,J,{staticPosition:Q}){let[Y,X]=J.type.split("bytes");if(!X){let W=SJ($.readBytes(32));$.setPosition(Q+W);let D=SJ($.readBytes(32));if(D===0)return $.setPosition(Q+32),["0x",32];let V=$.readBytes(D);return $.setPosition(Q+32),[X1(V),32]}return[X1($.readBytes(Number.parseInt(X,10),32)),32]}function TV$($,J){let Q=J.type.startsWith("int"),Y=Number.parseInt(J.type.split("int")[1]||"256",10),X=$.readBytes(32);return[Y>48?Ud(X,{signed:Q}):SJ(X,{signed:Q}),32]}function RV$($,J,Q){let{checksumAddress:Y,staticPosition:X}=Q,G=J.components.length===0||J.components.some(({name:V})=>!V),W=G?[]:{},D=0;if($K(J)){let V=SJ($.readBytes(oE)),K=X+V;for(let O=0;O<J.components.length;++O){let N=J.components[O];$.setPosition(K+D);let[M,w]=d9($,N,{checksumAddress:Y,staticPosition:K});D+=w,W[G?O:N?.name]=M}return $.setPosition(X+32),[W,32]}for(let V=0;V<J.components.length;++V){let K=J.components[V],[O,N]=d9($,K,{checksumAddress:Y,staticPosition:X});W[G?V:K?.name]=O,D+=N}return[W,D]}function CV$($,{staticPosition:J}){let Q=SJ($.readBytes(32)),Y=J+Q;$.setPosition(Y);let X=SJ($.readBytes(32));if(X===0)return $.setPosition(J+32),["",32];let G=$.readBytes(X,32),W=Nd(ej(G));return $.setPosition(J+32),[W,32]}function Qn({checksumAddress:$,parameters:J,values:Q}){let Y=[];for(let X=0;X<J.length;X++)Y.push(rE({checksumAddress:$,parameter:J[X],value:Q[X]}));return Y}function rE({checksumAddress:$=!1,parameter:J,value:Q}){let Y=J,X=tE(Y.type);if(X){let[G,W]=X;return vV$(Q,{checksumAddress:$,length:G,parameter:{...Y,type:W}})}if(Y.type==="tuple")return gV$(Q,{checksumAddress:$,parameter:Y});if(Y.type==="address")return PV$(Q,{checksum:$});if(Y.type==="bool")return xV$(Q);if(Y.type.startsWith("uint")||Y.type.startsWith("int")){let G=Y.type.startsWith("int"),[,,W="256"]=IH.exec(Y.type)??[];return fV$(Q,{signed:G,size:Number(W)})}if(Y.type.startsWith("bytes"))return kV$(Q,{type:Y.type});if(Y.type==="string")return bV$(Q);throw new JK(Y.type)}function qH($){let J=0;for(let G=0;G<$.length;G++){let{dynamic:W,encoded:D}=$[G];if(W)J+=32;else J+=m4(D)}let Q=[],Y=[],X=0;for(let G=0;G<$.length;G++){let{dynamic:W,encoded:D}=$[G];if(W)Q.push(V4(J+X,{size:32})),Y.push(D),X+=m4(D);else Q.push(D)}return c4(...Q,...Y)}function PV$($,J){let{checksum:Q=!1}=J;return m9($,{strict:Q}),{dynamic:!1,encoded:kQ($.toLowerCase())}}function vV$($,J){let{checksumAddress:Q,length:Y,parameter:X}=J,G=Y===null;if(!Array.isArray($))throw new sE($);if(!G&&$.length!==Y)throw new aE({expectedLength:Y,givenLength:$.length,type:`${X.type}[${Y}]`});let W=!1,D=[];for(let V=0;V<$.length;V++){let K=rE({checksumAddress:Q,parameter:X,value:$[V]});if(K.dynamic)W=!0;D.push(K)}if(G||W){let V=qH(D);if(G){let K=V4(D.length,{size:32});return{dynamic:!0,encoded:D.length>0?c4(K,V):K}}if(W)return{dynamic:!0,encoded:V}}return{dynamic:!1,encoded:c4(...D.map(({encoded:V})=>V))}}function kV$($,{type:J}){let[,Q]=J.split("bytes"),Y=m4($);if(!Q){let X=$;if(Y%32!==0)X=_J(X,Math.ceil(($.length-2)/2/32)*32);return{dynamic:!0,encoded:c4(kQ(V4(Y,{size:32})),X)}}if(Y!==Number.parseInt(Q,10))throw new ZH({expectedSize:Number.parseInt(Q,10),value:$});return{dynamic:!1,encoded:_J($)}}function xV$($){if(typeof $!=="boolean")throw new w$(`Invalid boolean value: "${$}" (type: ${typeof $}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:kQ(gw($))}}function fV$($,{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 yw({max:Y.toString(),min:X.toString(),signed:J,size:Q/8,value:$.toString()})}return{dynamic:!1,encoded:V4($,{size:32,signed:J})}}function bV$($){let J=CG($),Q=Math.ceil(m4(J)/32),Y=[];for(let X=0;X<Q;X++)Y.push(_J(l4(J,X*32,(X+1)*32)));return{dynamic:!0,encoded:c4(_J(V4(m4(J),{size:32})),...Y)}}function gV$($,J){let{checksumAddress:Q,parameter:Y}=J,X=!1,G=[];for(let W=0;W<Y.components.length;W++){let D=Y.components[W],V=Array.isArray($)?W:D.name,K=rE({checksumAddress:Q,parameter:D,value:$[V]});if(G.push(K),K.dynamic)X=!0}return{dynamic:X,encoded:X?qH(G):c4(...G.map(({encoded:W})=>W))}}function tE($){let J=$.match(/^(.*)\[(\d+)?\]$/);return J?[J[2]?Number(J[2]):null,J[1]]:void 0}function $K($){let{type:J}=$;if(J==="string")return!0;if(J==="bytes")return!0;if(J.endsWith("[]"))return!0;if(J==="tuple")return $.components?.some($K);let Q=tE($.type);if(Q&&$K({...$,type:Q[1]}))return!0;return!1}g6();var hV$={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 Yn({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition($){if($<0||$>this.bytes.length-1)throw new Xn({length:this.bytes.length,position:$})},decrementPosition($){if($<0)throw new eE({offset:$});let J=this.position-$;this.assertPosition(J),this.position=J},getReadCount($){return this.positionReadCount.get($||this.position)||0},incrementPosition($){if($<0)throw new eE({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 LH($,{recursiveReadLimit:J=8192}={}){let Q=Object.create(hV$);return Q.bytes=$,Q.dataView=new DataView($.buffer,$.byteOffset,$.byteLength),Q.positionReadCount=new Map,Q.recursiveReadLimit=J,Q}class eE extends w${constructor({offset:$}){super(`Offset \`${$}\` cannot be negative.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.NegativeOffsetError"})}}class Xn extends w${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 Yn extends w${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 nG($,J,Q={}){let{as:Y="Array",checksumAddress:X=!1}=Q,G=typeof J==="string"?TG(J):J,W=LH(G);if(M0(G)===0&&$.length>0)throw new Dn;if(M0(G)&&M0(G)<32)throw new Wn({data:typeof J==="string"?J:X1(J),parameters:$,size:M0(G)});let D=0,V=Y==="Array"?[]:{};for(let K=0;K<$.length;++K){let O=$[K];W.setPosition(D);let[N,M]=d9(W,O,{checksumAddress:X,staticPosition:0});if(D+=M,Y==="Array")V.push(N);else V[O.name??K]=N}return V}function QX($,J,Q){let{checksumAddress:Y=!1}=Q??{};if($.length!==J.length)throw new JS({expectedLength:$.length,givenLength:J.length});let X=Qn({checksumAddress:Y,parameters:$,values:J}),G=qH(X);if(G.length===0)return"0x";return G}function $S($,J){if($.length!==J.length)throw new JS({expectedLength:$.length,givenLength:J.length});let Q=[];for(let Y=0;Y<$.length;Y++){let X=$[Y],G=J[Y];Q.push($S.encode(X,G))}return c4(...Q)}(function($){function J(Q,Y,X=!1){if(Q==="address"){let V=Y;return m9(V),kQ(V.toLowerCase(),X?32:0)}if(Q==="string")return CG(Y);if(Q==="bytes")return Y;if(Q==="bool")return kQ(gw(Y),X?32:1);let G=Q.match(IH);if(G){let[V,K,O="256"]=G,N=Number.parseInt(O,10)/8;return V4(Y,{size:X?32:N,signed:K==="int"})}let W=Q.match(ep);if(W){let[V,K]=W;if(Number.parseInt(K,10)!==(Y.length-2)/2)throw new ZH({expectedSize:Number.parseInt(K,10),value:Y});return _J(Y,X?32:0)}let D=Q.match(sp);if(D&&Array.isArray(Y)){let[V,K]=D,O=[];for(let N=0;N<Y.length;N++)O.push(J(K,Y[N],!0));if(O.length===0)return"0x";return c4(...O)}throw new JK(Q)}$.encode=J})($S||($S={}));function XK($){if(Array.isArray($)&&typeof $[0]==="string")return Fw($);if(typeof $==="string")return Fw($);return $}class Wn extends w${constructor({data:$,parameters:J,size:Q}){super(`Data size of ${Q} bytes is too small for given parameters.`,{metaMessages:[`Params: (${jQ(J)})`,`Data: ${$} (${Q} bytes)`]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.DataSizeTooSmallError"})}}class Dn extends w${constructor(){super('Cannot decode zero data ("0x") with ABI parameters.');Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ZeroDataError"})}}class aE extends w${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 ZH extends w${constructor({expectedSize:$,value:J}){super(`Size of bytes "${J}" (bytes${m4(J)}) does not match expected size (bytes${$}).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class JS extends w${constructor({expectedLength:$,givenLength:J}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${$}`,`Given length (values): ${J}`].join(`
142
142
  `));Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class sE extends w${constructor($){super(`Value \`${$}\` is not a valid array.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidArrayError"})}}class JK extends w${constructor($){super(`Type \`${$}\` is not a valid ABI Type.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}q1();function Vn(...$){let[J,Q]=(()=>{if(Array.isArray($[0])){let[G,W]=$;return[uV$(G),W]}return $})(),{bytecode:Y,args:X}=Q;return c4(Y,J.inputs?.length&&X?.length?QX(J.inputs,X):"0x")}function Kn($){return zH($)}function uV$($){let J=$.find((Q)=>Q.type==="constructor");if(!J)throw new l9({name:"constructor"});return J}q1();function On(...$){let[J,Q=[]]=(()=>{if(Array.isArray($[0])){let[K,O,N]=$;return[Un(K,O,{args:N}),N]}let[D,V]=$;return[D,V]})(),{overloads:Y}=J,X=Y?Un([J,...Y],J.name,{args:Q}):J,G=lV$(X),W=Q.length>0?QX(X.inputs,Q):void 0;return W?c4(G,W):G}function p9($,J={}){return zH($,J)}function Un($,J,Q){let Y=eV($,J,Q);if(Y.type!=="function")throw new l9({name:J,type:"function"});return Y}function lV$($){return cE($)}var QS="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",z6="0x0000000000000000000000000000000000000000";e$();U0();var pV$="0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033";async function Nn($,J){let{blockNumber:Q,blockTag:Y,calls:X,stateOverrides:G,traceAssetChanges:W,traceTransfers:D,validation:V}=J,K=J.account?g4(J.account):void 0;if(W&&!K)throw new h("`account` is required when `traceAssetChanges` is true");let O=K?Vn(Kn("constructor(bytes, bytes)"),{bytecode:uw,args:[pV$,On(p9("function getBalance(address)"),[K.address])]}):void 0,N=W?await Promise.all(J.calls.map(async(_)=>{if(!_.data&&!_.abi)return;let{accessList:C}=await iw($,{account:K.address,..._,data:_.abi?n4(_):_.data});return C.map(({address:m,storageKeys:V$})=>V$.length>0?m:null)})).then((_)=>_.flat().filter(Boolean)):[],M=await sV($,{blockNumber:Q,blockTag:Y,blocks:[...W?[{calls:[{data:O}],stateOverrides:G},{calls:N.map((_,C)=>({abi:[p9("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[K.address],to:_,from:z6,nonce:C})),stateOverrides:[{address:z6,nonce:0}]}]:[],{calls:[...X,{to:z6}].map((_)=>({..._,from:K?.address})),stateOverrides:G},...W?[{calls:[{data:O}]},{calls:N.map((_,C)=>({abi:[p9("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[K.address],to:_,from:z6,nonce:C})),stateOverrides:[{address:z6,nonce:0}]},{calls:N.map((_,C)=>({to:_,abi:[p9("function decimals() returns (uint256)")],functionName:"decimals",from:z6,nonce:C})),stateOverrides:[{address:z6,nonce:0}]},{calls:N.map((_,C)=>({to:_,abi:[p9("function tokenURI(uint256) returns (string)")],functionName:"tokenURI",args:[0n],from:z6,nonce:C})),stateOverrides:[{address:z6,nonce:0}]},{calls:N.map((_,C)=>({to:_,abi:[p9("function symbol() returns (string)")],functionName:"symbol",from:z6,nonce:C})),stateOverrides:[{address:z6,nonce:0}]}]:[]],traceTransfers:D,validation:V}),w=W?M[2]:M[0],[z,q,,F,Z,E,B,L]=W?M:[],{calls:j,...T}=w,x=j.slice(0,-1)??[],f=z?.calls??[],u=q?.calls??[],R=[...f,...u].map((_)=>_.status==="success"?f1(_.data):null),d=F?.calls??[],p=Z?.calls??[],Y$=[...d,...p].map((_)=>_.status==="success"?f1(_.data):null),c=(E?.calls??[]).map((_)=>_.status==="success"?_.result:null),k=(L?.calls??[]).map((_)=>_.status==="success"?_.result:null),n=(B?.calls??[]).map((_)=>_.status==="success"?_.result:null),s=[];for(let[_,C]of Y$.entries()){let m=R[_];if(typeof C!=="bigint")continue;if(typeof m!=="bigint")continue;let V$=c[_-1],K$=k[_-1],z$=n[_-1],R$=(()=>{if(_===0)return{address:QS,decimals:18,symbol:"ETH"};return{address:N[_-1],decimals:z$||V$?Number(V$??1):void 0,symbol:K$??void 0}})();if(s.some((Z$)=>Z$.token.address===R$.address))continue;s.push({token:R$,value:{pre:m,post:C,diff:C-m}})}return{assetChanges:s,block:T,results:x}}_Q();U0();f9();async function Mn($,J){let{abi:Q,address:Y,args:X,functionName:G,dataSuffix:W=typeof $.dataSuffix==="string"?$.dataSuffix:$.dataSuffix?.value,...D}=J,V=D.account?g4(D.account):$.account,K=n4({abi:Q,args:X,functionName:G});try{let{data:O}=await W$($,H0,"call")({batch:!1,data:`${K}${W?W.replace("0x",""):""}`,to:Y,...D,account:V}),N=r1({abi:Q,args:X,functionName:G,data:O||"0x"}),M=Q.filter((w)=>("name"in w)&&w.name===J.functionName);return{result:N,request:{abi:M,address:Y,args:X,dataSuffix:W,functionName:G,...D,account:V}}}catch(O){throw i0(O,{abi:Q,address:Y,args:X,docsPath:"/docs/contract/simulateContract",functionName:G,sender:V?.address})}}async function XX($,{filter:J}){return J.request({method:"eth_uninstallFilter",params:[J.id]})}var YK={};F6(YK,{wrap:()=>oV$,validate:()=>rV$,unwrap:()=>wn,universalSignatureValidatorBytecode:()=>nV$,universalSignatureValidatorAbi:()=>cV$,magicBytes:()=>XS,from:()=>iV$,assert:()=>YS,InvalidWrappedSignatureError:()=>GS});g6();q1();var XS="0x6492649264926492649264926492649264926492649264926492649264926492",nV$="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572",cV$=[{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 YS($){if(l4($,-32)!==XS)throw new GS($)}function iV$($){if(typeof $==="string")return wn($);return $}function wn($){YS($);let[J,Q,Y]=nG(XK("address, bytes, bytes"),$);return{data:Q,signature:Y,to:J}}function oV$($){let{data:J,signature:Q,to:Y}=$;return c4(QX(XK("address, bytes, bytes"),[Y,J,Q]),XS)}function rV$($){try{return YS($),!0}catch{return!1}}class GS extends w${constructor($){super(`Value \`${$}\` is an invalid ERC-6492 wrapped signature.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc6492.InvalidWrappedSignatureError"})}}var GK={};F6(GK,{wrap:()=>UK$,validate:()=>OK$,unwrap:()=>Tn,suffixParameters:()=>OS,magicBytes:()=>US,from:()=>KK$,assert:()=>jH,InvalidWrappedSignatureError:()=>NS});q1();c8();g6();q1();function tV$($,J){let{as:Q}=J,Y=An($),X=LH(new Uint8Array(Y.length));if(Y.encode(X),Q==="Hex")return X1(X.bytes);return X.bytes}function Hn($,J={}){let{as:Q="Hex"}=J;return tV$($,{as:Q})}function An($){if(Array.isArray($))return aV$($.map((J)=>An(J)));return sV$($)}function aV$($){let J=$.reduce((X,G)=>X+G.length,0),Q=zn(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 sV$($){let J=typeof $==="string"?TG($):$,Q=zn(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 zn($){if($<=255)return 1;if($<=65535)return 2;if($<=16777215)return 3;if($<=4294967295)return 4;throw new w$("Length is too large.")}g6();q1();function WS($,J={}){let{recovered:Q}=J;if(typeof $.r>"u")throw new BH({signature:$});if(typeof $.s>"u")throw new BH({signature:$});if(Q&&typeof $.yParity>"u")throw new BH({signature:$});if($.r<0n||$.r>iE)throw new Ln({value:$.r});if($.s<0n||$.s>iE)throw new Bn({value:$.s});if(typeof $.yParity==="number"&&$.yParity!==0&&$.yParity!==1)throw new FH({value:$.yParity})}function $K$($){return In(X1($))}function In($){if($.length!==130&&$.length!==132)throw new Zn({signature:$});let J=BigInt(l4($,0,32)),Q=BigInt(l4($,32,64)),Y=(()=>{let X=Number(`0x${$.slice(130)}`);if(Number.isNaN(X))return;try{return KS(X)}catch{throw new FH({value:X})}})();if(typeof Y>"u")return{r:J,s:Q};return{r:J,s:Q,yParity:Y}}function DS($){if(typeof $.r>"u")return;if(typeof $.s>"u")return;return VS($)}function VS($){let J=(()=>{if(typeof $==="string")return In($);if($ instanceof Uint8Array)return $K$($);if(typeof $.r==="string")return QK$($);if($.v)return JK$($);return{r:$.r,s:$.s,...typeof $.yParity<"u"?{yParity:$.yParity}:{}}})();return WS(J),J}function JK$($){return{r:$.r,s:$.s,yParity:KS($.v)}}function QK$($){let J=(()=>{let Q=$.v?Number($.v):void 0,Y=$.yParity?Number($.yParity):void 0;if(typeof Q==="number"&&typeof Y!=="number")Y=KS(Q);if(typeof Y!=="number")throw new FH({value:$.yParity});return Y})();return{r:BigInt($.r),s:BigInt($.s),yParity:J}}function qn($){let{r:J,s:Q,yParity:Y}=$;return[Y?"0x01":"0x",J===0n?"0x":XE(V4(J)),Q===0n?"0x":XE(V4(Q))]}function KS($){if($===0||$===27)return 0;if($===1||$===28)return 1;if($>=35)return $%2===0?1:0;throw new Fn({value:$})}class Zn extends w${constructor({signature:$}){super(`Value \`${$}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${m4(RG($))} bytes.`]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class BH extends w${constructor({signature:$}){super(`Signature \`${i8($)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}}class Ln extends w${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 Bn extends w${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 FH extends w${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 Fn extends w${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 En($,J={}){if(typeof $.chainId==="string")return XK$($);return{...$,...J.signature}}function XK$($){let{address:J,chainId:Q,nonce:Y}=$,X=DS($);return{address:J,chainId:Number(Q),nonce:BigInt(Y),...X}}function Sn($){return YK$($,{presign:!0})}function YK$($,J={}){let{presign:Q}=J;return u9(c4("0x05",Hn(GK$(Q?{address:$.address,chainId:$.chainId,nonce:$.nonce}:$))))}function GK$($){let{address:J,chainId:Q,nonce:Y}=$,X=DS($);return[Q?V4(Q):"0x",J,Y?V4(Y):"0x",...X?qn(X):[]]}g6();q1();$X();q1();function _n($){return ip(DK$($))}function DK$($){let{payload:J,signature:Q}=$,{r:Y,s:X,yParity:G}=Q,D=new A6.Signature(BigInt(Y),BigInt(X)).addRecoveryBit(G).recoverPublicKey(RG(J).substring(2));return up(D)}var US="0x8010801080108010801080108010801080108010801080108010801080108010",OS=XK("(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data");function jH($){if(typeof $==="string"){if(l4($,-32)!==US)throw new NS($)}else WS($.authorization)}function KK$($){if(typeof $==="string")return Tn($);return $}function Tn($){jH($);let J=bw(l4($,-64,-32)),Q=l4($,-J-64,-64),Y=l4($,0,-J-64),[X,G,W]=nG(OS,Q);return{authorization:En({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 UK$($){let{data:J,signature:Q}=$;jH($);let Y=_n({payload:Sn($.authorization),signature:VS($.authorization)}),X=QX(OS,[{...$.authorization,delegation:$.authorization.address,chainId:BigInt($.authorization.chainId)},$.to??Y,J??"0x"]),G=V4(m4(X),{size:32});return c4(Q,X,G,US)}function OK$($){try{return jH($),!0}catch{return!1}}class NS extends w${constructor($){super(`Value \`${$}\` is an invalid ERC-8010 wrapped signature.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc8010.InvalidWrappedSignatureError"})}}BJ();p8();WE();U0();Z9();xG();Z9();xG();async function Rn({address:$,authorization:J,signature:Q}){return r0(L9($),await $H({authorization:J,signature:Q}))}N6();d$();$X();N6();g1();function Cn({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 A6.Signature(f1($),f1(J)).toCompactHex()}${G===0?"1b":"1c"}`;if(Q==="hex")return W;return b1(W)}f9();async function GX($,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 V=(()=>{let K=J.signature;if(Q1(K))return K;if(typeof K==="object"&&"r"in K&&"s"in K)return Cn(K);return O4(K)})();try{if(D==="eoa")try{if(r0(L9(Q),await rV({hash:X,signature:V})))return!0}catch{}if(GK.validate(V))return await NK$($,{...J,multicallAddress:W,signature:V});return await MK$($,{...J,verifierAddress:G,signature:V})}catch(K){if(D!=="eoa")try{if(r0(L9(Q),await rV({hash:X,signature:V})))return!0}catch{}if(K instanceof YX)return!1;throw K}}async function NK$($,J){let{address:Q,blockNumber:Y,blockTag:X,hash:G,multicallAddress:W}=J,{authorization:D,data:V,signature:K,to:O}=GK.unwrap(J.signature);if(await y9($,{address:Q,blockNumber:Y,blockTag:X})===p0(["0xef0100",D.address]))return await wK$($,{address:Q,blockNumber:Y,blockTag:X,hash:G,signature:K});let M={address:D.address,chainId:Number(D.chainId),nonce:Number(D.nonce),r:N$(D.r,{size:32}),s:N$(D.s,{size:32}),yParity:D.yParity};if(!await Rn({address:Q,authorization:M}))throw new YX;let z=await W$($,W1,"readContract")({...W?{address:W}:{code:PG},authorizationList:[M],abi:h0,blockNumber:Y,blockTag:"pending",functionName:"aggregate3",args:[[...V?[{allowFailure:!0,target:O??Q,callData:V}]:[],{allowFailure:!0,target:Q,callData:n4({abi:TF,functionName:"isValidSignature",args:[G,K]})}]]});if(z[z.length-1]?.returnData?.startsWith("0x1626ba7e"))return!0;throw new YX}async function MK$($,J){let{address:Q,factory:Y,factoryData:X,hash:G,signature:W,verifierAddress:D,...V}=J,K=await(async()=>{if(!Y&&!X)return W;if(YK.validate(W))return W;return YK.wrap({data:X,signature:W,to:Y})})(),O=D?{to:D,data:n4({abi:UV,functionName:"isValidSig",args:[Q,G,K]}),...V}:{data:xV({abi:UV,args:[Q,G,K],bytecode:Zd}),...V},{data:N}=await W$($,H0,"call")(O).catch((M)=>{if(M instanceof _V)throw new YX;throw M});if(iF(N??"0x0"))return!0;throw new YX}async function wK$($,J){let{address:Q,blockNumber:Y,blockTag:X,hash:G,signature:W}=J;if((await W$($,W1,"readContract")({address:Q,abi:TF,args:[G,W],blockNumber:Y,blockTag:X,functionName:"isValidSignature"}).catch((V)=>{if(V instanceof TV)throw new YX;throw V})).startsWith("0x1626ba7e"))return!0;throw new YX}class YX extends Error{}d0();var Pn=`\x19Ethereum Signed Message:
143
143
  `;D0();d$();function vn($){let J=(()=>{if(typeof $==="string")return d5($);if(typeof $.raw==="string")return $.raw;return O4($.raw)})(),Q=d5(`${Pn}${X4(J)}`);return y1([Q,J])}function EH($,J){return C4(vn($),J)}async function kn($,{address:J,message:Q,factory:Y,factoryData:X,signature:G,...W}){let D=EH(Q);return W$($,GX,"verifyHash")({address:J,factory:Y,factoryData:X,hash:D,signature:G,...W})}BQ();d$();d0();J1();z9();e$();class MS extends h{constructor({domain:$}){super(`Invalid domain "${D4($)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class wS extends h{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 HS extends h{constructor({type:$}){super(`Struct type "${$}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}LQ();D0();d$();Jj();function xn($){let{domain:J,message:Q,primaryType:Y,types:X}=$,G=(W,D)=>{for(let V of W){let{name:K,type:O}=V,N=D[K],M=O.match(Nw);if(M&&(typeof N==="number"||typeof N==="bigint")){let[q,F,Z]=M;N$(N,{signed:F==="int",size:Number.parseInt(Z,10)/8})}if(O==="address"&&typeof N==="string"&&!G1(N))throw new O6({address:N});let w=O.match(pm);if(w){let[q,F]=w;if(F&&X4(N)!==Number.parseInt(F,10))throw new mF({expectedSize:Number.parseInt(F,10),givenSize:X4(N)})}let z=X[O];if(z)HK$(O),G(z,N)}};if(X.EIP712Domain&&J){if(typeof J!=="object")throw new MS({domain:J});G(X.EIP712Domain,J)}if(Y!=="EIP712Domain")if(X[Y])G(X[Y],Q);else throw new wS({primaryType:Y,types:X})}function fn({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 HK$($){if($==="address"||$==="bool"||$==="string"||$.startsWith("bytes")||$.startsWith("uint")||$.startsWith("int"))throw new HS({type:$})}function bn($){let{domain:J={},message:Q,primaryType:Y}=$,X={EIP712Domain:fn({domain:J}),...$.types};xn({domain:J,message:Q,primaryType:Y,types:X});let G=["0x1901"];if(J)G.push(AK$({domain:J,types:X}));if(Y!=="EIP712Domain")G.push(gn({data:Q,primaryType:Y,types:X}));return C4(y1(G))}function AK$({domain:$,types:J}){return gn({data:$,primaryType:"EIP712Domain",types:J})}function gn({data:$,primaryType:J,types:Q}){let Y=yn({data:$,primaryType:J,types:Q});return C4(Y)}function yn({data:$,primaryType:J,types:Q}){let Y=[{type:"bytes32"}],X=[zK$({primaryType:J,types:Q})];for(let G of Q[J]){let[W,D]=un({types:Q,name:G.name,type:G.type,value:$[G.name]});Y.push(W),X.push(D)}return M6(Y,X)}function zK$({primaryType:$,types:J}){let Q=o1(IK$({primaryType:$,types:J}));return C4(Q)}function IK$({primaryType:$,types:J}){let Q="",Y=hn({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 hn({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])hn({primaryType:G.type,types:J},Q);return Q}function un({types:$,name:J,type:Q,value:Y}){if($[Q]!==void 0)return[{type:"bytes32"},C4(yn({data:Y,primaryType:Q,types:$}))];if(Q==="bytes")return[{type:"bytes32"},C4(Y)];if(Q==="string")return[{type:"bytes32"},C4(o1(Y))];if(Q.lastIndexOf("]")===Q.length-1){let X=Q.slice(0,Q.lastIndexOf("[")),G=Y.map((W)=>un({name:J,type:X,types:$,value:W}));return[{type:"bytes32"},C4(M6(G.map(([W])=>W),G.map(([,W])=>W)))]}return[{type:Q},Y]}async function mn($,J){let{address:Q,factory:Y,factoryData:X,signature:G,message:W,primaryType:D,types:V,domain:K,...O}=J,N=bn({message:W,primaryType:D,types:V,domain:K});return W$($,GX,"verifyHash")({address:Q,factory:Y,factoryData:X,hash:N,signature:G,...O})}TQ();var AS=new Map,ln=new Map,qK$=0;function y6($,J,Q){let Y=++qK$,X=()=>AS.get($)||[],G=()=>{let O=X();AS.set($,O.filter((N)=>N.id!==Y))},W=()=>{let O=X();if(!O.some((M)=>M.id===Y))return;let N=ln.get($);if(O.length===1&&N){let M=N();if(M instanceof Promise)M.catch(()=>{})}G()},D=X();if(AS.set($,[...D,{id:Y,fns:J}]),D&&D.length>0)return W;let V={};for(let O in J)V[O]=(...N)=>{let M=X();if(M.length===0)return;for(let w of M)w.fns[O]?.(...N)};let K=Q(V);if(typeof K==="function")ln.set($,K);return W}async function WK($){return new Promise((J)=>setTimeout(J,$))}function DK($,{delay:J=100,retryCount:Q=2,shouldRetry:Y=()=>!0}={}){return new Promise((X,G)=>{let W=async({count:D=0}={})=>{let V=async({error:K})=>{let O=typeof J==="function"?J({count:D,error:K}):J;if(O)await WK(O);W({count:D+1})};try{let K=await $();X(K)}catch(K){if(D<Q&&await Y({count:D,error:K}))return V({error:K});G(K)}};W()})}N6();function PJ($,{emitOnBegin:J,initialWaitTime:Q,interval:Y}){let X=!0,G=()=>X=!1;return(async()=>{let D;if(J)D=await $({unpoll:G});let V=await Q?.(D)??Y;await WK(V);let K=async()=>{if(!X)return;await $({unpoll:G}),await WK(Y),K()};K()})(),G}function SH($,{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})(),V;return D?(()=>{let N=D4(["watchBlockNumber",$.uid,J,Q,W]);return y6(N,{onBlockNumber:Y,onError:X},(M)=>PJ(async()=>{try{let w=await W$($,CJ,"getBlockNumber")({cacheTime:0});if(V!==void 0){if(w===V)return;if(w-V>1&&Q)for(let z=V+1n;z<w;z++)M.onBlockNumber(z,V),V=z}if(V===void 0||w>V)M.onBlockNumber(w,V),V=w}catch(w){M.onError?.(w)}},{emitOnBegin:J,interval:W}))})():(()=>{let N=D4(["watchBlockNumber",$.uid,J,Q]);return y6(N,{onBlockNumber:Y,onError:X},(M)=>{let w=!0,z=()=>w=!1;return(async()=>{try{let q=(()=>{if($.transport.type==="fallback"){let Z=$.transport.transports.find((E)=>E.config.type==="webSocket"||E.config.type==="ipc");if(!Z)return $.transport;return Z.value}return $.transport})(),{unsubscribe:F}=await q.subscribe({params:["newHeads"],onData(Z){if(!w)return;let E=f1(Z.result?.number);M.onBlockNumber(E,V),V=E},onError(Z){M.onError?.(Z)}});if(z=F,!w)z()}catch(q){X?.(q)}})(),()=>z()})})()}async function dn($,J){let{checkReplacement:Q=!0,confirmations:Y=1,hash:X,onReplaced:G,retryCount:W=6,retryDelay:D=({count:j})=>~~(1<<j)*200,timeout:V=180000}=J,K=D4(["waitForTransactionReceipt",$.uid,X]),O=(()=>{if(J.pollingInterval)return J.pollingInterval;if($.chain?.experimental_preconfirmationTime)return $.chain.experimental_preconfirmationTime;return $.pollingInterval})(),N,M,w,z=!1,q,F,{promise:Z,resolve:E,reject:B}=lw(),L=V?setTimeout(()=>{F?.(),q?.(),B(new gj({hash:X}))},V):void 0;return q=y6(K,{onReplaced:G,resolve:E,reject:B},async(j)=>{if(w=await W$($,dG,"getTransactionReceipt")({hash:X}).catch(()=>{return}),w&&Y<=1){clearTimeout(L),j.resolve(w),q?.();return}F=W$($,SH,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:O,async onBlockNumber(T){let x=(u)=>{clearTimeout(L),F?.(),u(),q?.()},f=T;if(z)return;try{if(w){if(Y>1&&(!w.blockNumber||f-w.blockNumber+1n<Y))return;x(()=>j.resolve(w));return}if(Q&&!N)z=!0,await DK(async()=>{if(N=await W$($,lG,"getTransaction")({hash:X}),N.blockNumber)f=N.blockNumber},{delay:D,retryCount:W}),z=!1;if(w=await W$($,dG,"getTransactionReceipt")({hash:X}),Y>1&&(!w.blockNumber||f-w.blockNumber+1n<Y))return;x(()=>j.resolve(w))}catch(u){if(u instanceof EV||u instanceof SV){if(!N){z=!1;return}try{M=N,z=!0;let R=await DK(()=>W$($,Z1,"getBlock")({blockNumber:f,includeTransactions:!0}),{delay:D,retryCount:W,shouldRetry:({error:Y$})=>Y$ instanceof aV});z=!1;let d=R.transactions.find(({from:Y$,nonce:c})=>Y$===M.from&&c===M.nonce);if(!d)return;if(w=await W$($,dG,"getTransactionReceipt")({hash:d.hash}),Y>1&&(!w.blockNumber||f-w.blockNumber+1n<Y))return;let p="replaced";if(d.to===M.to&&d.value===M.value&&d.input===M.input)p="repriced";else if(d.from===d.to&&d.value===0n)p="cancelled";x(()=>{j.onReplaced?.({reason:p,replacedTransaction:M,transaction:d,transactionReceipt:w}),j.resolve(w)})}catch(R){x(()=>j.reject(R))}}else x(()=>j.reject(u))}}})}),Z}function pn($,{blockTag:J=$.experimental_blockTag??"latest",emitMissed:Q=!1,emitOnBegin:Y=!1,onBlock:X,onError:G,includeTransactions:W,poll:D,pollingInterval:V=$.pollingInterval}){let K=(()=>{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 K?(()=>{let z=D4(["watchBlocks",$.uid,J,Q,Y,O,V]);return y6(z,{onBlock:X,onError:G},(q)=>PJ(async()=>{try{let F=await W$($,Z1,"getBlock")({blockTag:J,includeTransactions:O});if(F.number!==null&&N?.number!=null){if(F.number===N.number)return;if(F.number-N.number>1&&Q)for(let Z=N?.number+1n;Z<F.number;Z++){let E=await W$($,Z1,"getBlock")({blockNumber:Z,includeTransactions:O});q.onBlock(E,N),N=E}}if(N?.number==null||J==="pending"&&F?.number==null||F.number!==null&&F.number>N.number)q.onBlock(F,N),N=F}catch(F){q.onError?.(F)}},{emitOnBegin:Y,interval:V}))})():(()=>{let z=!0,q=!0,F=()=>z=!1;return(async()=>{try{if(Y)W$($,Z1,"getBlock")({blockTag:J,includeTransactions:O}).then((B)=>{if(!z)return;if(!q)return;X(B,void 0),q=!1}).catch(G);let Z=(()=>{if($.transport.type==="fallback"){let B=$.transport.transports.find((L)=>L.config.type==="webSocket"||L.config.type==="ipc");if(!B)return $.transport;return B.value}return $.transport})(),{unsubscribe:E}=await Z.subscribe({params:["newHeads"],async onData(B){if(!z)return;let L=await W$($,Z1,"getBlock")({blockNumber:B.result?.number,includeTransactions:O}).catch(()=>{});if(!z)return;X(L,N),q=!1,N=L},onError(B){G?.(B)}});if(F=E,!z)F()}catch(Z){G?.(Z)}})(),()=>F()})()}J1();PV();function nn($,J){let{abi:Q,address:Y,args:X,batch:G=!0,eventName:W,fromBlock:D,onError:V,onLogs:K,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 F=M??!1,Z=D4(["watchContractEvent",Y,X,G,$.uid,W,N,F,D]);return y6(Z,{onLogs:K,onError:V},(E)=>{let B;if(D!==void 0)B=D-1n;let L,j=!1,T=PJ(async()=>{if(!j){try{L=await W$($,ow,"createContractEventFilter")({abi:Q,address:Y,args:X,eventName:W,strict:F,fromBlock:D})}catch{}j=!0;return}try{let x;if(L)x=await W$($,JX,"getFilterChanges")({filter:L});else{let f=await W$($,CJ,"getBlockNumber")({});if(B&&B<f)x=await W$($,KH,"getContractEvents")({abi:Q,address:Y,args:X,eventName:W,fromBlock:B+1n,toBlock:f,strict:F});else x=[];B=f}if(x.length===0)return;if(G)E.onLogs(x);else for(let f of x)E.onLogs([f])}catch(x){if(L&&x instanceof N0)j=!1;E.onError?.(x)}},{emitOnBegin:!0,interval:N});return async()=>{if(L)await W$($,XX,"uninstallFilter")({filter:L});T()}})})():(()=>{let F=M??!1,Z=D4(["watchContractEvent",Y,X,G,$.uid,W,N,F]),E=!0,B=()=>E=!1;return y6(Z,{onLogs:K,onError:V},(L)=>{return(async()=>{try{let j=(()=>{if($.transport.type==="fallback"){let f=$.transport.transports.find((u)=>u.config.type==="webSocket"||u.config.type==="ipc");if(!f)return $.transport;return f.value}return $.transport})(),T=W?RJ({abi:Q,eventName:W,args:X}):[],{unsubscribe:x}=await j.subscribe({params:["logs",{address:Y,topics:T}],onData(f){if(!E)return;let u=f.result;try{let{eventName:R,args:d}=h9({abi:Q,data:u.data,topics:u.topics,strict:M}),p=L1(u,{args:d,eventName:R});L.onLogs([p])}catch(R){let d,p;if(R instanceof h8||R instanceof A9){if(M)return;d=R.abiItem.name,p=R.abiItem.inputs?.some((c)=>!(("name"in c)&&c.name))}let Y$=L1(u,{args:p?[]:{},eventName:d});L.onLogs([Y$])}},onError(f){L.onError?.(f)}});if(B=x,!E)B()}catch(j){V?.(j)}})(),()=>B()})})()}J1();PV();function cn($,{address:J,args:Q,batch:Y=!0,event:X,events:G,fromBlock:W,onError:D,onLogs:V,poll:K,pollingInterval:O=$.pollingInterval,strict:N}){let M=(()=>{if(typeof K<"u")return K;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})(),w=N??!1;return M?(()=>{let F=D4(["watchEvent",J,Q,Y,$.uid,X,O,W]);return y6(F,{onLogs:V,onError:D},(Z)=>{let E;if(W!==void 0)E=W-1n;let B,L=!1,j=PJ(async()=>{if(!L){try{B=await W$($,rw,"createEventFilter")({address:J,args:Q,event:X,events:G,strict:w,fromBlock:W})}catch{}L=!0;return}try{let T;if(B)T=await W$($,JX,"getFilterChanges")({filter:B});else{let x=await W$($,CJ,"getBlockNumber")({});if(E&&E!==x)T=await W$($,mG,"getLogs")({address:J,args:Q,event:X,events:G,fromBlock:E+1n,toBlock:x});else T=[];E=x}if(T.length===0)return;if(Y)Z.onLogs(T);else for(let x of T)Z.onLogs([x])}catch(T){if(B&&T instanceof N0)L=!1;Z.onError?.(T)}},{emitOnBegin:!0,interval:O});return async()=>{if(B)await W$($,XX,"uninstallFilter")({filter:B});j()}})})():(()=>{let F=!0,Z=()=>F=!1;return(async()=>{try{let E=(()=>{if($.transport.type==="fallback"){let T=$.transport.transports.find((x)=>x.config.type==="webSocket"||x.config.type==="ipc");if(!T)return $.transport;return T.value}return $.transport})(),B=G??(X?[X]:void 0),L=[];if(B){if(L=[B.flatMap((x)=>RJ({abi:[x],eventName:x.name,args:Q}))],X)L=L[0]}let{unsubscribe:j}=await E.subscribe({params:["logs",{address:J,topics:L}],onData(T){if(!F)return;let x=T.result;try{let{eventName:f,args:u}=h9({abi:B??[],data:x.data,topics:x.topics,strict:w}),R=L1(x,{args:u,eventName:f});V([R])}catch(f){let u,R;if(f instanceof h8||f instanceof A9){if(N)return;u=f.abiItem.name,R=f.abiItem.inputs?.some((p)=>!(("name"in p)&&p.name))}let d=L1(x,{args:R?[]:{},eventName:u});V([d])}},onError(T){D?.(T)}});if(Z=j,!F)Z()}catch(E){D?.(E)}})(),()=>Z()})()}function on($,{batch:J=!0,onError:Q,onTransactions:Y,poll:X,pollingInterval:G=$.pollingInterval}){return(typeof X<"u"?X:$.transport.type!=="webSocket"&&$.transport.type!=="ipc")?(()=>{let K=D4(["watchPendingTransactions",$.uid,J,G]);return y6(K,{onTransactions:Y,onError:Q},(O)=>{let N,M=PJ(async()=>{try{if(!N)try{N=await W$($,tw,"createPendingTransactionFilter")({});return}catch(z){throw M(),z}let w=await W$($,JX,"getFilterChanges")({filter:N});if(w.length===0)return;if(J)O.onTransactions(w);else for(let z of w)O.onTransactions([z])}catch(w){O.onError?.(w)}},{emitOnBegin:!0,interval:G});return async()=>{if(N)await W$($,XX,"uninstallFilter")({filter:N});M()}})})():(()=>{let K=!0,O=()=>K=!1;return(async()=>{try{let{unsubscribe:N}=await $.transport.subscribe({params:["newPendingTransactions"],onData(M){if(!K)return;let w=M.result;Y([w])},onError(M){Q?.(M)}});if(O=N,!K)O()}catch(N){Q?.(N)}})(),()=>O()})()}function rn($){let{scheme:J,statement:Q,...Y}=$.match(ZK$)?.groups??{},{chainId:X,expirationTime:G,issuedAt:W,notBefore:D,requestId:V,...K}=$.match(LK$)?.groups??{},O=$.split("Resources:")[1]?.split(`
144
- - `).slice(1);return{...Y,...K,...X?{chainId:Number(X)}:{},...G?{expirationTime:new Date(G)}:{},...W?{issuedAt:new Date(W)}:{},...D?{notBefore:new Date(D)}:{},...V?{requestId:V}:{},...O?{resources:O}:{},...J?{scheme:J}:{},...Q?{statement:Q}:{}}}var ZK$=/^(?:(?<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)?/,LK$=/(?: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>.+))?/;LQ();xG();function tn($){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(!G1(Y.address,{strict:!1}))return!1;if(J&&!r0(Y.address,J))return!1}catch{return!1}return!0}async function an($,J){let{address:Q,domain:Y,message:X,nonce:G,scheme:W,signature:D,time:V=new Date,...K}=J,O=rn(X);if(!O.address)return!1;if(!tn({address:Q,domain:Y,message:O,nonce:G,scheme:W,time:V}))return!1;let M=EH(X);return GX($,{address:O.address,hash:M,signature:D,...K})}async function sn($,{serializedTransaction:J}){return $.request({method:"eth_sendRawTransaction",params:[J]},{retryCount:0})}TQ();async function en($,{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||UH)(X);if(W.status==="reverted"&&Q)throw new bj({receipt:W});return W}function $c($){return{call:(J)=>H0($,J),createAccessList:(J)=>iw($,J),createBlockFilter:()=>hd($),createContractEventFilter:(J)=>ow($,J),createEventFilter:(J)=>rw($,J),createPendingTransactionFilter:()=>tw($),estimateContractGas:(J)=>Bp($,J),estimateGas:(J)=>hG($,J),getBalance:(J)=>Fp($,J),getBlobBaseFee:()=>jp($),getBlock:(J)=>Z1($,J),getBlockNumber:(J)=>CJ($,J),getBlockTransactionCount:(J)=>_p($,J),getBytecode:(J)=>y9($,J),getChainId:()=>yG($),getCode:(J)=>y9($,J),getContractEvents:(J)=>KH($,J),getDelegation:(J)=>Rp($,J),getEip712Domain:(J)=>Cp($,J),getEnsAddress:(J)=>Cd($,J),getEnsAvatar:(J)=>bd($,J),getEnsName:(J)=>gd($,J),getEnsResolver:(J)=>yd($,J),getEnsText:(J)=>cw($,J),getFeeHistory:(J)=>vp($,J),estimateFeesPerGas:(J)=>Up($,J),getFilterChanges:(J)=>JX($,J),getFilterLogs:(J)=>kp($,J),getGasPrice:()=>gG($),getLogs:(J)=>mG($,J),getProof:(J)=>fp($,J),estimateMaxPriorityFeePerGas:(J)=>Kp($,J),fillTransaction:(J)=>DH($,J),getStorageAt:(J)=>bp($,J),getTransaction:(J)=>lG($,J),getTransactionConfirmations:(J)=>gp($,J),getTransactionCount:(J)=>XH($,J),getTransactionReceipt:(J)=>dG($,J),multicall:(J)=>yp($,J),prepareTransactionRequest:(J)=>VH($,J),readContract:(J)=>W1($,J),sendRawTransaction:(J)=>sn($,J),sendRawTransactionSync:(J)=>en($,J),simulate:(J)=>sV($,J),simulateBlocks:(J)=>sV($,J),simulateCalls:(J)=>Nn($,J),simulateContract:(J)=>Mn($,J),verifyHash:(J)=>GX($,J),verifyMessage:(J)=>kn($,J),verifySiweMessage:(J)=>an($,J),verifyTypedData:(J)=>mn($,J),uninstallFilter:(J)=>XX($,J),waitForTransactionReceipt:(J)=>dn($,J),watchBlocks:(J)=>pn($,J),watchBlockNumber:(J)=>SH($,J),watchContractEvent:(J)=>nn($,J),watchEvent:(J)=>cn($,J),watchPendingTransactions:(J)=>on($,J)}}function zS($){let{key:J="public",name:Q="Public Client"}=$;return _m({...$,key:J,name:Q,type:"publicClient"}).extend($c)}_9();e$();class IS extends h{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}KE();_9();function Jc($,{errorInstance:J=Error("timed out"),timeout:Q,signal:Y}){return new Promise((X,G)=>{(async()=>{let W;try{let D=new AbortController;if(Q>0)W=setTimeout(()=>{if(Y)D.abort();else G(J)},Q);X(await $({signal:D?.signal||null}))}catch(D){if(D?.name==="AbortError")G(J);G(D)}finally{clearTimeout(W)}})()})}function BK$(){return{current:0,take(){return this.current++},reset(){this.current=0}}}var qS=BK$();function Qc($,J={}){let{url:Q,headers:Y}=FK$($);return{async request(X){let{body:G,fetchFn:W=J.fetchFn??fetch,onRequest:D=J.onRequest,onResponse:V=J.onResponse,timeout:K=J.timeout??1e4}=X,O={...J.fetchOptions??{},...X.fetchOptions??{}},{headers:N,method:M,signal:w}=O;try{let z=await Jc(async({signal:F})=>{let Z={...O,body:Array.isArray(G)?D4(G.map((j)=>({jsonrpc:"2.0",id:j.id??qS.take(),...j}))):D4({jsonrpc:"2.0",id:G.id??qS.take(),...G}),headers:{...Y,"Content-Type":"application/json",...N},method:M||"POST",signal:w||(K>0?F:null)},E=new Request(Q,Z),B=await D?.(E,Z)??{...Z,url:Q};return await W(B.url??Q,B)},{errorInstance:new vw({body:G,url:Q}),timeout:K,signal:!0});if(V)await V(z);let q;if(z.headers.get("Content-Type")?.startsWith("application/json"))q=await z.json();else{q=await z.text();try{q=JSON.parse(q||"{}")}catch(F){if(z.ok)throw F;q={error:q}}}if(!z.ok){if(typeof q.error?.code==="number"&&typeof q.error?.message==="string")return q;throw new c0({body:G,details:D4(q.error)||z.statusText,headers:z.headers,status:z.status,url:Q})}return q}catch(z){if(z instanceof c0)throw z;if(z instanceof vw)throw z;throw new c0({body:G,cause:z,url:Q})}}}}function FK$($){try{let J=new URL($),Q=(()=>{if(J.username){let Y=`${decodeURIComponent(J.username)}:${decodeURIComponent(J.password)}`;return J.username="",J.password="",{url:J.toString(),headers:{Authorization:`Basic ${btoa(Y)}`}}}return})();return{url:J.toString(),...Q}}catch{return{url:$}}}e$();_9();PV();IV();var _H=new ZQ(8192);function Xc($,{enabled:J=!0,id:Q}){if(!J||!Q)return $();if(_H.get(Q))return _H.get(Q);let Y=$().finally(()=>_H.delete(Q));return _H.set(Q,Y),Y}function Yc($,J={}){return async(Q,Y={})=>{let{dedupe:X=!1,methods:G,retryDelay:W=150,retryCount:D=3,uid:V}={...J,...Y},{method:K}=Q;if(G?.exclude?.includes(K))throw new n8(Error("method not supported"),{method:K});if(G?.include&&!G.include.includes(K))throw new n8(Error("method not supported"),{method:K});let O=X?EK$(`${V}.${D4(Q)}`):void 0;return Xc(()=>DK(async()=>{try{return await $(Q)}catch(N){let M=N;switch(M.code){case GG.code:throw new GG(M);case WG.code:throw new WG(M);case DG.code:throw new DG(M,{method:Q.method});case VG.code:throw new VG(M);case PQ.code:throw new PQ(M);case N0.code:throw new N0(M);case KG.code:throw new KG(M);case UG.code:throw new UG(M);case OG.code:throw new OG(M);case n8.code:throw new n8(M,{method:Q.method});case T9.code:throw new T9(M);case NG.code:throw new NG(M);case R9.code:throw new R9(M);case MG.code:throw new MG(M);case wG.code:throw new wG(M);case HG.code:throw new HG(M);case AG.code:throw new AG(M);case zG.code:throw new zG(M);case IG.code:throw new IG(M);case qG.code:throw new qG(M);case ZG.code:throw new ZG(M);case LG.code:throw new LG(M);case BG.code:throw new BG(M);case FG.code:throw new FG(M);case jG.code:throw new jG(M);case 5000:throw new R9(M);case EG.code:throw new EG(M);default:if(N instanceof h)throw N;throw new pj(M)}}},{delay:({count:N,error:M})=>{if(M&&M instanceof c0){let w=M?.headers?.get("Retry-After");if(w?.match(/\d/))return Number.parseInt(w,10)*1000}return~~(1<<N)*W},retryCount:D,shouldRetry:({error:N})=>jK$(N)}),{enabled:X,id:O})}}function jK$($){if("code"in $&&typeof $.code==="number"){if($.code===-1)return!0;if($.code===T9.code)return!0;if($.code===PQ.code)return!0;if($.code===429)return!0;return!1}if($ instanceof c0&&$.status){if($.status===403)return!0;if($.status===408)return!0;if($.status===413)return!0;if($.status===429)return!0;if($.status===500)return!0;if($.status===502)return!0;if($.status===503)return!0;if($.status===504)return!0;return!1}return!0}function EK$($,J=0){let Q=3735928559^J,Y=1103547991^J;for(let X=0;X<$.length;X++){let G=$.charCodeAt(X);Q=Math.imul(Q^G,2654435761),Y=Math.imul(Y^G,1597334677)}return Q=Math.imul(Q^Q>>>16,2246822507),Q^=Math.imul(Y^Y>>>16,3266489909),Y=Math.imul(Y^Y>>>16,2246822507),Y^=Math.imul(Q^Q>>>16,3266489909),(4294967296*(2097151&Y)+(Q>>>0)).toString(36)}function Gc({key:$,methods:J,name:Q,request:Y,retryCount:X=3,retryDelay:G=150,timeout:W,type:D},V){let K=aM();return{config:{key:$,methods:J,name:Q,request:Y,retryCount:X,retryDelay:G,timeout:W,type:D},request:Yc(Y,{methods:J,retryCount:X,retryDelay:G,uid:K}),value:V}}function ZS($,J={}){let{batch:Q,fetchFn:Y,fetchOptions:X,key:G="http",methods:W,name:D="HTTP JSON-RPC",onFetchRequest:V,onFetchResponse:K,retryDelay:O,raw:N}=J;return({chain:M,retryCount:w,timeout:z})=>{let{batchSize:q=1000,wait:F=0}=typeof Q==="object"?Q:{},Z=J.retryCount??w,E=z??J.timeout??1e4,B=$||M?.rpcUrls.default.http[0];if(!B)throw new IS;let L=Qc(B,{fetchFn:Y,fetchOptions:X,onRequest:V,onResponse:K,timeout:E});return Gc({key:G,methods:W,name:D,async request({method:j,params:T}){let x={method:j,params:T},{schedule:f}=dw({id:B,wait:F,shouldSplitBatch(p){return p.length>q},fn:(p)=>L.request({body:p}),sort:(p,Y$)=>p.id-Y$.id}),u=async(p)=>Q?f(p):[await L.request({body:p})],[{error:R,result:d}]=await u(x);if(N)return{error:R,result:d};if(R)throw new S9({body:x,error:R,url:B});return d},retryCount:Z,retryDelay:O,timeout:E,type:"http"},{fetchOptions:X,url:B})}}BJ();function TH($){let J={formatters:void 0,fees:void 0,serializers:void 0,...$};function Q(Y){return(X)=>{let G=typeof X==="function"?X(Y):X,W={...Y,...G};return Object.assign(W,{extend:Q(W)})}}return Object.assign(J,{extend:Q(J)})}var LS=TH({id:1329,name:"Sei Network",nativeCurrency:{name:"Sei",symbol:"SEI",decimals:18},rpcUrls:{default:{http:["https://evm-rpc.sei-apis.com/"],webSocket:["wss://evm-ws.sei-apis.com/"]}},blockExplorers:{default:{name:"Seiscan",url:"https://seiscan.io",apiUrl:"https://api.etherscan.io/v2/api"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11"}}});var BS=TH({id:1328,name:"Sei Testnet",nativeCurrency:{name:"Sei",symbol:"SEI",decimals:18},rpcUrls:{default:{http:["https://evm-rpc-testnet.sei-apis.com"],webSocket:["wss://evm-ws-testnet.sei-apis.com"]}},blockExplorers:{default:{name:"Seiscan",url:"https://testnet.seiscan.io",apiUrl:"https://api.etherscan.io/v2/api"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:98697651}},testnet:!0});W0();var RH=e1(oM(),1);class $4{apiUrl;sessionKeypair;serverKey;retryOptions;constructor($,J){this.apiUrl=$,this.retryOptions={maxRetries:J?.maxRetries??3,baseDelayMs:J?.baseDelayMs??1000}}setSessionKeypair($){this.sessionKeypair=$?Ku($.publicKey,$.privateKey):void 0}setServerKey($){this.serverKey=$}parseRequestBody($){if(!$)return;if(typeof $==="string")try{return JSON.parse($)}catch{return $}if($ instanceof FormData){let J={};return $.forEach((Q,Y)=>{J[Y]=Q instanceof File?`[File: ${Q.name}]`:Q}),J}if($ instanceof URLSearchParams){let J={};return $.forEach((Q,Y)=>{J[Y]=Q}),J}if($ instanceof Blob)return{type:"[Blob]",size:$.size,contentType:$.type};if($ instanceof ArrayBuffer||ArrayBuffer.isView($))return{type:"[ArrayBuffer]",size:$ instanceof ArrayBuffer?$.byteLength:$.byteLength};if(typeof ReadableStream<"u"&&$ instanceof ReadableStream)return{type:"[ReadableStream]",note:"Stream body not captured for logging"};return{type:"[Unknown]",bodyType:typeof $}}extractResponseMetadata($){if(!$)return{};let J=$.get("x-request-id")||$.get("request-id")||$.get("x-correlation-id")||void 0,Q=$.get("retry-after"),Y;if(Q!==null){let X=Number.parseInt(Q,10);Y=Number.isNaN(X)?void 0:X}return{requestId:J,retryAfter:Y}}async executeRequest($,J,Q,Y){let X;try{X=await fetch($,Q)}catch(V){throw new U1(`Network request failed for ${J}`,{endpoint:$,cause:V instanceof Error?V:Error(String(V)),requestBody:Y})}let G,W=X.headers?.get("content-type")||"unknown",D=X.clone?X.clone():X;try{G=await X.json()}catch(V){let K;try{K=await D.text()}catch{K="[Unable to read response body]"}if(!X.ok){let O=`API request failed: ${X.status}. Response is not JSON (Content-Type: ${W})`,{requestId:N,retryAfter:M}=this.extractResponseMetadata(X.headers);throw new U1(O,{endpoint:$,statusCode:X.status,responseBody:{rawResponse:K.substring(0,500),contentType:W,parseError:V instanceof Error?V.message:String(V)},cause:V instanceof Error?V:void 0,requestBody:Y,requestId:N,retryAfter:M})}if(K.trim()==="")return;throw new U1(`Expected JSON response but received ${W}`,{endpoint:$,statusCode:X.status,responseBody:{rawResponse:K.substring(0,500),contentType:W},cause:V instanceof Error?V:void 0,requestBody:Y})}if(!X.ok){let V=G!==null&&typeof G==="object"?G:void 0,K=(typeof V?.message==="string"?V.message:void 0)||(typeof V?.error==="string"?V.error:void 0)||`API request failed: ${X.status}`,{requestId:O,retryAfter:N}=this.extractResponseMetadata(X.headers);throw new U1(K,{endpoint:$,statusCode:X.status,responseBody:G,requestBody:Y,requestId:O,retryAfter:N})}return G}async makeAuthenticatedRequest($,J={}){if(!this.sessionKeypair)throw new U1("Session keypair not set. Authenticate (login) first.",{endpoint:`${this.apiUrl}${$}`,statusCode:RH.StatusCodes.UNAUTHORIZED});let Q=`${this.apiUrl}${$}`,Y=this.parseRequestBody(J.body),X=this.buildSignatureHeaders($,J);return this.executeRequest(Q,$,{...J,headers:{"Content-Type":"application/json",...X,...J.headers}},Y)}buildSignatureHeaders($,J){if(!this.sessionKeypair)throw new U1("Session keypair not set. Authenticate (login) first.",{endpoint:`${this.apiUrl}${$}`,statusCode:RH.StatusCodes.UNAUTHORIZED});let Q=(J.method??"GET").toUpperCase(),Y=Date.now(),X=typeof J.body==="string"?b5(J.body):new Uint8Array(0),G=Uu(X),W=Ou(Q,$,Y,G),D=cM(this.sessionKeypair.privateKey,W);return{"X-Monaco-PublicKey":Y9(this.sessionKeypair.publicKey),"X-Monaco-Timestamp":String(Y),"X-Monaco-Signature":D}}async makeBackendRequest($,J={}){if(!this.serverKey)throw new U1("Server key not set. Call setServerKey(sk_...) first.",{endpoint:`${this.apiUrl}${$}`,statusCode:RH.StatusCodes.UNAUTHORIZED});let Q=`${this.apiUrl}${$}`,Y=this.parseRequestBody(J.body);return this.executeRequest(Q,$,{...J,headers:{"Content-Type":"application/json","x-server-key":this.serverKey,...J.headers}},Y)}async makePublicRequest($,J={}){let Q=`${this.apiUrl}${$}`,Y=this.parseRequestBody(J.body);return this.executeRequest(Q,$,{...J,headers:{"Content-Type":"application/json",...J.headers}},Y)}}function t$($){return encodeURIComponent($)}function d4($,J){if(!J)return $;let Q=new URLSearchParams;for(let[X,G]of Object.entries(J))if(G!==void 0)Q.set(X,String(G));let Y=Q.toString();return Y?`${$}?${Y}`:$}var D$={orders:{create:()=>"/api/v1/orders",list:($)=>d4("/api/v1/orders",$),get:($)=>`/api/v1/orders/${t$($)}`,replace:($)=>`/api/v1/orders/${t$($)}`,cancel:()=>"/api/v1/orders/cancel",batchCancel:()=>"/api/v1/orders/batch-cancel",batchCancelAll:()=>"/api/v1/orders/batch-cancel-all",batchCancelAllByPair:($)=>`/api/v1/orders/batch-cancel-all/${t$($)}`,batchCreate:()=>"/api/v1/orders/batch-create",batchReplace:()=>"/api/v1/orders/batch-replace",listConditional:($)=>d4("/api/v1/orders/conditional",$),cancelConditional:($)=>`/api/v1/orders/conditional/${t$($)}`,getConditional:($)=>`/api/v1/orders/conditional/${t$($)}`},delegatedAgents:{list:()=>"/api/v1/delegated-agents",owners:()=>"/api/v1/delegated-agents/owners",byId:($)=>`/api/v1/delegated-agents/${t$($)}`,sessions:()=>"/api/v1/delegated-agents/sessions"},withdrawals:{initiate:()=>"/api/v1/withdrawals",byIndex:($)=>`/api/v1/withdrawals/${t$(String($))}`,list:($)=>d4("/api/v1/withdrawals",$)},market:{listTradingPairs:($)=>d4("/api/v1/market/pairs",$),getTradingPair:($)=>`/api/v1/market/pairs/${t$($)}`,getCandles:($,J,Q)=>d4(`/api/v1/market/pairs/charts/candlestick/${t$($)}/${t$(J)}`,Q),getMarketMetadata:($)=>`/api/v1/market/pairs/${t$($)}/metadata`,getPerpMarketConfig:($)=>`/api/v1/market/pairs/${t$($)}/perp/config`,getPerpMarketSummary:($)=>`/api/v1/market/pairs/${t$($)}/perp/summary`,getMarkPrice:($)=>`/api/v1/market/pairs/${t$($)}/mark-price`,getIndexPrice:($)=>`/api/v1/market/pairs/${t$($)}/index-price`,getFundingState:($)=>`/api/v1/market/pairs/${t$($)}/funding`,listFundingHistory:($,J)=>d4(`/api/v1/market/pairs/${t$($)}/funding/history`,J),getOpenInterest:($)=>`/api/v1/market/pairs/${t$($)}/open-interest`,getScreener:($)=>d4("/api/v1/market/screener",$),getMarketStats:()=>"/api/v1/market/stats"},orderbook:{get:($,J)=>d4(`/api/v1/orderbook/${t$($)}`,J)},trades:{publicByPair:($,J)=>d4(`/api/v1/trades/${t$($)}`,J),byId:($)=>`/api/v1/trades/by-id/${t$($)}`,user:($)=>d4("/api/v1/accounts/trades",$)},applications:{orders:($)=>d4("/api/v1/applications/orders",$),users:($)=>d4("/api/v1/applications/users",$),movements:($)=>d4("/api/v1/applications/movements",$),balances:($)=>d4("/api/v1/applications/balances",$),stats:($)=>d4("/api/v1/applications/stats",$)},subAccounts:{list:()=>"/api/v1/accounts/sub-accounts",createLimit:()=>"/api/v1/accounts/sub-accounts/limits",getLimits:($)=>`/api/v1/accounts/sub-accounts/${t$($)}/limits`,limit:($,J)=>`/api/v1/accounts/sub-accounts/${t$($)}/limits/${t$(J)}`},faucet:{mint:()=>"/api/v1/faucet/mint"},whitelist:{submit:()=>"/api/v1/whitelist"},positions:{list:($)=>d4("/api/v1/positions",$),get:($)=>`/api/v1/positions/${t$($)}`,close:($)=>`/api/v1/positions/${t$($)}/close`,batchCloseAll:()=>"/api/v1/positions/batch-close-all",risk:($)=>`/api/v1/positions/${t$($)}/risk`,addMargin:($)=>`/api/v1/positions/${t$($)}/margin/add`,reduceMargin:($)=>`/api/v1/positions/${t$($)}/margin/reduce`,attachTpSl:($)=>`/api/v1/positions/${t$($)}/tp-sl`,history:($)=>d4("/api/v1/positions/history",$),pnlHistory:($,J)=>d4(`/api/v1/positions/${t$($)}/pnl/history`,J)},marginAccounts:{list:($)=>d4("/api/v1/margin/accounts",$),parentSummary:($)=>d4("/api/v1/margin/parent-margin-account",$),summary:($,J)=>d4(`/api/v1/margin/accounts/${t$($)}`,J),availableCollateral:($)=>d4("/api/v1/margin/collateral/available",$),transferIn:($)=>`/api/v1/margin/accounts/${t$($)}/collateral/transfer-in`,transferInParent:()=>"/api/v1/margin/parent-margin-account/collateral/transfer-in",transferInRiskBucket:()=>"/api/v1/margin/risk-buckets/collateral/transfer-in",transferOut:($)=>`/api/v1/margin/accounts/${t$($)}/collateral/transfer-out`,transferOutParent:()=>"/api/v1/margin/parent-margin-account/collateral/transfer-out",movements:($,J)=>d4(`/api/v1/margin/accounts/${t$($)}/movements`,J),parentMovements:($)=>d4("/api/v1/margin/parent-margin-account/movements",$),simulateParentMarginOrderRisk:()=>"/api/v1/margin/parent-margin-account/simulate-order-risk",simulateOrderRisk:($)=>`/api/v1/margin/accounts/${t$($)}/simulate-order-risk`,simulateRiskBucketOrderRisk:()=>"/api/v1/margin/risk-buckets/simulate-order-risk"},streams:{orderbook:()=>"/api/v1/streaming/orderbook",trades:()=>"/api/v1/streaming/trades",perpMarketSummaries:()=>"/api/v1/streaming/perp-market-summaries",markPrices:()=>"/api/v1/streaming/mark-prices",privateTrades:()=>"/api/v1/streaming/private-trades",orders:()=>"/api/v1/streaming/orders",positions:()=>"/api/v1/streaming/positions",funding:()=>"/api/v1/streaming/funding",liquidationAlerts:()=>"/api/v1/streaming/liquidation-alerts"}};class CH extends $4{async getApplicationConfig(){let $=await this.makeAuthenticatedRequest("/api/v1/applications/config",{method:"GET"});return{id:$.id,name:$.name,allowedOrigins:$.allowedOrigins,webhookUrl:$.webhookUrl,vaultContractAddress:$.vaultContractAddress,clientId:$.clientId}}async listApplicationOrders($){return await this.makeBackendRequest(D$.applications.orders($))}async listApplicationUsers($){return await this.makeBackendRequest(D$.applications.users($))}async listApplicationMovements($){return await this.makeBackendRequest(D$.applications.movements($))}async listApplicationBalances($){return await this.makeBackendRequest(D$.applications.balances($))}async getApplicationStats($){return await this.makeBackendRequest(D$.applications.stats($))}}class FS extends $4{async upsertDelegatedAgent($){return this.makeAuthenticatedRequest(D$.delegatedAgents.list(),{method:"POST",body:JSON.stringify({agentAddress:$.agentAddress,name:$.name,expiresAt:$.expiresAt,allowedActions:$.allowedActions,allowedTradingPairIds:$.allowedTradingPairIds,allowedMarginAccountIds:$.allowedMarginAccountIds,allowedOrderTypes:$.allowedOrderTypes,allowedTimeInForce:$.allowedTimeInForce,maxLeverage:$.maxLeverage,maxOrderNotional:$.maxOrderNotional,maxOpenOrders:$.maxOpenOrders})})}async listDelegatedAgents(){return this.makeAuthenticatedRequest(D$.delegatedAgents.list())}async listDelegatedOwners(){return this.makeAuthenticatedRequest(D$.delegatedAgents.owners())}async revokeDelegatedAgent($){return this.makeAuthenticatedRequest(D$.delegatedAgents.byId($),{method:"DELETE"})}async createDelegatedSession($){return this.makeAuthenticatedRequest(D$.delegatedAgents.sessions(),{method:"POST",body:JSON.stringify({ownerUserId:$.ownerUserId,sessionPublicKey:$.sessionPublicKey})})}}class PH extends $4{async mint(){return await this.makeAuthenticatedRequest(D$.faucet.mint(),{method:"POST"})}}var jS=A.object({tradingPairId:A.string().trim().min(1,"Trading pair ID is required and cannot be empty"),side:A.enum(["BUY","SELL"],{message:"Order side is required and must be either 'BUY' or 'SELL'"}),price:A.string().trim().min(1,"Price is required and cannot be empty").refine(($)=>!Number.isNaN(Number($)),"Price must be a valid number").refine(($)=>Number($)>0,"Price must be greater than 0"),quantity:A.string().trim().min(1,"Quantity is required and cannot be empty").refine(($)=>!Number.isNaN(Number($)),"Quantity must be a valid number").refine(($)=>Number($)>0,"Quantity must be greater than 0"),orderType:A.enum(["LIMIT","MARKET"]).optional(),slippageToleranceBps:A.number().int().min(0,"Slippage tolerance must be between 0 and 1000 bps").max(1000,"Slippage tolerance must be between 0 and 1000 bps").optional()}).superRefine(($,J)=>{if($.slippageToleranceBps!==void 0&&$.orderType!=="MARKET")J.addIssue({code:A.ZodIssueCode.custom,message:"slippageToleranceBps is only valid when orderType is MARKET",path:["slippageToleranceBps"]})}),SK$=A.object({applicationName:A.string().nullable().optional(),applicationTakerFee:A.string(),applicationTakerFeeBps:A.number(),buyOrderLockAmount:A.string().nullable().optional(),makerTotalReceipt:A.string(),monacoMakerRebate:A.string(),monacoMakerRebateBps:A.number(),monacoTakerFee:A.string(),monacoTakerFeeBps:A.number(),notional:A.string(),takerTotalPayment:A.string(),totalTakerFees:A.string(),maxQuantity:A.string().nullable(),maxQuantityRaw:A.string().nullable(),slippageToleranceBps:A.number().nullable()}),ES=A.object({tradingPairId:A.string().trim().min(1,"Trading pair ID is required and cannot be empty")}),Wc=A.object({tierLevel:A.number().int(),minVolumeThreshold:A.string(),makerFeeBps:A.string(),takerFeeBps:A.string()}),_K$=A.object({currentTierLevel:A.number().int(),weightedVolume14d:A.string(),spotVolume14d:A.string(),perpVolume14d:A.string(),volumeToNextTier:A.string().nullable().optional(),nextTierLevel:A.number().int().nullable().optional(),feeSchedule:A.array(Wc)});var Dc=A.object({token:A.string(),available:A.string()}),TK$=A.object({balances:A.array(Dc)}),RK$=A.object({code:A.string(),createdAt:A.string()}),CK$=A.object({code:A.string()}),SS=A.object({token:A.string().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:A.string().trim().min(1,"amount is required").refine(($)=>/^\d+$/.test($)&&BigInt($)>0n,"amount must be a positive integer string")}),PK$=A.object({rewardsBalance:A.string(),tradingBalance:A.string()});var _S=["SUBMITTED","PARTIALLY_FILLED","FILLED","SETTLED_ON_CHAIN","SETTLED","CANCELLED","REJECTED","EXPIRED"];class Vc extends Error{issues;constructor($){let J=$.issues.map((Q)=>{let Y=Q.path.join(".");return`${Y?`${Y}: `:""}${Q.message}`});super(`Validation failed:
144
+ - `).slice(1);return{...Y,...K,...X?{chainId:Number(X)}:{},...G?{expirationTime:new Date(G)}:{},...W?{issuedAt:new Date(W)}:{},...D?{notBefore:new Date(D)}:{},...V?{requestId:V}:{},...O?{resources:O}:{},...J?{scheme:J}:{},...Q?{statement:Q}:{}}}var ZK$=/^(?:(?<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)?/,LK$=/(?: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>.+))?/;LQ();xG();function tn($){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(!G1(Y.address,{strict:!1}))return!1;if(J&&!r0(Y.address,J))return!1}catch{return!1}return!0}async function an($,J){let{address:Q,domain:Y,message:X,nonce:G,scheme:W,signature:D,time:V=new Date,...K}=J,O=rn(X);if(!O.address)return!1;if(!tn({address:Q,domain:Y,message:O,nonce:G,scheme:W,time:V}))return!1;let M=EH(X);return GX($,{address:O.address,hash:M,signature:D,...K})}async function sn($,{serializedTransaction:J}){return $.request({method:"eth_sendRawTransaction",params:[J]},{retryCount:0})}TQ();async function en($,{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||UH)(X);if(W.status==="reverted"&&Q)throw new bj({receipt:W});return W}function $c($){return{call:(J)=>H0($,J),createAccessList:(J)=>iw($,J),createBlockFilter:()=>hd($),createContractEventFilter:(J)=>ow($,J),createEventFilter:(J)=>rw($,J),createPendingTransactionFilter:()=>tw($),estimateContractGas:(J)=>Bp($,J),estimateGas:(J)=>hG($,J),getBalance:(J)=>Fp($,J),getBlobBaseFee:()=>jp($),getBlock:(J)=>Z1($,J),getBlockNumber:(J)=>CJ($,J),getBlockTransactionCount:(J)=>_p($,J),getBytecode:(J)=>y9($,J),getChainId:()=>yG($),getCode:(J)=>y9($,J),getContractEvents:(J)=>KH($,J),getDelegation:(J)=>Rp($,J),getEip712Domain:(J)=>Cp($,J),getEnsAddress:(J)=>Cd($,J),getEnsAvatar:(J)=>bd($,J),getEnsName:(J)=>gd($,J),getEnsResolver:(J)=>yd($,J),getEnsText:(J)=>cw($,J),getFeeHistory:(J)=>vp($,J),estimateFeesPerGas:(J)=>Up($,J),getFilterChanges:(J)=>JX($,J),getFilterLogs:(J)=>kp($,J),getGasPrice:()=>gG($),getLogs:(J)=>mG($,J),getProof:(J)=>fp($,J),estimateMaxPriorityFeePerGas:(J)=>Kp($,J),fillTransaction:(J)=>DH($,J),getStorageAt:(J)=>bp($,J),getTransaction:(J)=>lG($,J),getTransactionConfirmations:(J)=>gp($,J),getTransactionCount:(J)=>XH($,J),getTransactionReceipt:(J)=>dG($,J),multicall:(J)=>yp($,J),prepareTransactionRequest:(J)=>VH($,J),readContract:(J)=>W1($,J),sendRawTransaction:(J)=>sn($,J),sendRawTransactionSync:(J)=>en($,J),simulate:(J)=>sV($,J),simulateBlocks:(J)=>sV($,J),simulateCalls:(J)=>Nn($,J),simulateContract:(J)=>Mn($,J),verifyHash:(J)=>GX($,J),verifyMessage:(J)=>kn($,J),verifySiweMessage:(J)=>an($,J),verifyTypedData:(J)=>mn($,J),uninstallFilter:(J)=>XX($,J),waitForTransactionReceipt:(J)=>dn($,J),watchBlocks:(J)=>pn($,J),watchBlockNumber:(J)=>SH($,J),watchContractEvent:(J)=>nn($,J),watchEvent:(J)=>cn($,J),watchPendingTransactions:(J)=>on($,J)}}function zS($){let{key:J="public",name:Q="Public Client"}=$;return _m({...$,key:J,name:Q,type:"publicClient"}).extend($c)}_9();e$();class IS extends h{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}KE();_9();function Jc($,{errorInstance:J=Error("timed out"),timeout:Q,signal:Y}){return new Promise((X,G)=>{(async()=>{let W;try{let D=new AbortController;if(Q>0)W=setTimeout(()=>{if(Y)D.abort();else G(J)},Q);X(await $({signal:D?.signal||null}))}catch(D){if(D?.name==="AbortError")G(J);G(D)}finally{clearTimeout(W)}})()})}function BK$(){return{current:0,take(){return this.current++},reset(){this.current=0}}}var qS=BK$();function Qc($,J={}){let{url:Q,headers:Y}=FK$($);return{async request(X){let{body:G,fetchFn:W=J.fetchFn??fetch,onRequest:D=J.onRequest,onResponse:V=J.onResponse,timeout:K=J.timeout??1e4}=X,O={...J.fetchOptions??{},...X.fetchOptions??{}},{headers:N,method:M,signal:w}=O;try{let z=await Jc(async({signal:F})=>{let Z={...O,body:Array.isArray(G)?D4(G.map((j)=>({jsonrpc:"2.0",id:j.id??qS.take(),...j}))):D4({jsonrpc:"2.0",id:G.id??qS.take(),...G}),headers:{...Y,"Content-Type":"application/json",...N},method:M||"POST",signal:w||(K>0?F:null)},E=new Request(Q,Z),B=await D?.(E,Z)??{...Z,url:Q};return await W(B.url??Q,B)},{errorInstance:new vw({body:G,url:Q}),timeout:K,signal:!0});if(V)await V(z);let q;if(z.headers.get("Content-Type")?.startsWith("application/json"))q=await z.json();else{q=await z.text();try{q=JSON.parse(q||"{}")}catch(F){if(z.ok)throw F;q={error:q}}}if(!z.ok){if(typeof q.error?.code==="number"&&typeof q.error?.message==="string")return q;throw new c0({body:G,details:D4(q.error)||z.statusText,headers:z.headers,status:z.status,url:Q})}return q}catch(z){if(z instanceof c0)throw z;if(z instanceof vw)throw z;throw new c0({body:G,cause:z,url:Q})}}}}function FK$($){try{let J=new URL($),Q=(()=>{if(J.username){let Y=`${decodeURIComponent(J.username)}:${decodeURIComponent(J.password)}`;return J.username="",J.password="",{url:J.toString(),headers:{Authorization:`Basic ${btoa(Y)}`}}}return})();return{url:J.toString(),...Q}}catch{return{url:$}}}e$();_9();PV();IV();var _H=new ZQ(8192);function Xc($,{enabled:J=!0,id:Q}){if(!J||!Q)return $();if(_H.get(Q))return _H.get(Q);let Y=$().finally(()=>_H.delete(Q));return _H.set(Q,Y),Y}function Yc($,J={}){return async(Q,Y={})=>{let{dedupe:X=!1,methods:G,retryDelay:W=150,retryCount:D=3,uid:V}={...J,...Y},{method:K}=Q;if(G?.exclude?.includes(K))throw new n8(Error("method not supported"),{method:K});if(G?.include&&!G.include.includes(K))throw new n8(Error("method not supported"),{method:K});let O=X?EK$(`${V}.${D4(Q)}`):void 0;return Xc(()=>DK(async()=>{try{return await $(Q)}catch(N){let M=N;switch(M.code){case GG.code:throw new GG(M);case WG.code:throw new WG(M);case DG.code:throw new DG(M,{method:Q.method});case VG.code:throw new VG(M);case PQ.code:throw new PQ(M);case N0.code:throw new N0(M);case KG.code:throw new KG(M);case UG.code:throw new UG(M);case OG.code:throw new OG(M);case n8.code:throw new n8(M,{method:Q.method});case T9.code:throw new T9(M);case NG.code:throw new NG(M);case R9.code:throw new R9(M);case MG.code:throw new MG(M);case wG.code:throw new wG(M);case HG.code:throw new HG(M);case AG.code:throw new AG(M);case zG.code:throw new zG(M);case IG.code:throw new IG(M);case qG.code:throw new qG(M);case ZG.code:throw new ZG(M);case LG.code:throw new LG(M);case BG.code:throw new BG(M);case FG.code:throw new FG(M);case jG.code:throw new jG(M);case 5000:throw new R9(M);case EG.code:throw new EG(M);default:if(N instanceof h)throw N;throw new pj(M)}}},{delay:({count:N,error:M})=>{if(M&&M instanceof c0){let w=M?.headers?.get("Retry-After");if(w?.match(/\d/))return Number.parseInt(w,10)*1000}return~~(1<<N)*W},retryCount:D,shouldRetry:({error:N})=>jK$(N)}),{enabled:X,id:O})}}function jK$($){if("code"in $&&typeof $.code==="number"){if($.code===-1)return!0;if($.code===T9.code)return!0;if($.code===PQ.code)return!0;if($.code===429)return!0;return!1}if($ instanceof c0&&$.status){if($.status===403)return!0;if($.status===408)return!0;if($.status===413)return!0;if($.status===429)return!0;if($.status===500)return!0;if($.status===502)return!0;if($.status===503)return!0;if($.status===504)return!0;return!1}return!0}function EK$($,J=0){let Q=3735928559^J,Y=1103547991^J;for(let X=0;X<$.length;X++){let G=$.charCodeAt(X);Q=Math.imul(Q^G,2654435761),Y=Math.imul(Y^G,1597334677)}return Q=Math.imul(Q^Q>>>16,2246822507),Q^=Math.imul(Y^Y>>>16,3266489909),Y=Math.imul(Y^Y>>>16,2246822507),Y^=Math.imul(Q^Q>>>16,3266489909),(4294967296*(2097151&Y)+(Q>>>0)).toString(36)}function Gc({key:$,methods:J,name:Q,request:Y,retryCount:X=3,retryDelay:G=150,timeout:W,type:D},V){let K=aM();return{config:{key:$,methods:J,name:Q,request:Y,retryCount:X,retryDelay:G,timeout:W,type:D},request:Yc(Y,{methods:J,retryCount:X,retryDelay:G,uid:K}),value:V}}function ZS($,J={}){let{batch:Q,fetchFn:Y,fetchOptions:X,key:G="http",methods:W,name:D="HTTP JSON-RPC",onFetchRequest:V,onFetchResponse:K,retryDelay:O,raw:N}=J;return({chain:M,retryCount:w,timeout:z})=>{let{batchSize:q=1000,wait:F=0}=typeof Q==="object"?Q:{},Z=J.retryCount??w,E=z??J.timeout??1e4,B=$||M?.rpcUrls.default.http[0];if(!B)throw new IS;let L=Qc(B,{fetchFn:Y,fetchOptions:X,onRequest:V,onResponse:K,timeout:E});return Gc({key:G,methods:W,name:D,async request({method:j,params:T}){let x={method:j,params:T},{schedule:f}=dw({id:B,wait:F,shouldSplitBatch(p){return p.length>q},fn:(p)=>L.request({body:p}),sort:(p,Y$)=>p.id-Y$.id}),u=async(p)=>Q?f(p):[await L.request({body:p})],[{error:R,result:d}]=await u(x);if(N)return{error:R,result:d};if(R)throw new S9({body:x,error:R,url:B});return d},retryCount:Z,retryDelay:O,timeout:E,type:"http"},{fetchOptions:X,url:B})}}BJ();function TH($){let J={formatters:void 0,fees:void 0,serializers:void 0,...$};function Q(Y){return(X)=>{let G=typeof X==="function"?X(Y):X,W={...Y,...G};return Object.assign(W,{extend:Q(W)})}}return Object.assign(J,{extend:Q(J)})}var LS=TH({id:1329,name:"Sei Network",nativeCurrency:{name:"Sei",symbol:"SEI",decimals:18},rpcUrls:{default:{http:["https://evm-rpc.sei-apis.com/"],webSocket:["wss://evm-ws.sei-apis.com/"]}},blockExplorers:{default:{name:"Seiscan",url:"https://seiscan.io",apiUrl:"https://api.etherscan.io/v2/api"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11"}}});var BS=TH({id:1328,name:"Sei Testnet",nativeCurrency:{name:"Sei",symbol:"SEI",decimals:18},rpcUrls:{default:{http:["https://evm-rpc-testnet.sei-apis.com"],webSocket:["wss://evm-ws-testnet.sei-apis.com"]}},blockExplorers:{default:{name:"Seiscan",url:"https://testnet.seiscan.io",apiUrl:"https://api.etherscan.io/v2/api"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:98697651}},testnet:!0});W0();var RH=e1(oM(),1);class $4{apiUrl;sessionKeypair;serverKey;retryOptions;constructor($,J){this.apiUrl=$,this.retryOptions={maxRetries:J?.maxRetries??3,baseDelayMs:J?.baseDelayMs??1000}}setSessionKeypair($){this.sessionKeypair=$?Ku($.publicKey,$.privateKey):void 0}setServerKey($){this.serverKey=$}parseRequestBody($){if(!$)return;if(typeof $==="string")try{return JSON.parse($)}catch{return $}if($ instanceof FormData){let J={};return $.forEach((Q,Y)=>{J[Y]=Q instanceof File?`[File: ${Q.name}]`:Q}),J}if($ instanceof URLSearchParams){let J={};return $.forEach((Q,Y)=>{J[Y]=Q}),J}if($ instanceof Blob)return{type:"[Blob]",size:$.size,contentType:$.type};if($ instanceof ArrayBuffer||ArrayBuffer.isView($))return{type:"[ArrayBuffer]",size:$ instanceof ArrayBuffer?$.byteLength:$.byteLength};if(typeof ReadableStream<"u"&&$ instanceof ReadableStream)return{type:"[ReadableStream]",note:"Stream body not captured for logging"};return{type:"[Unknown]",bodyType:typeof $}}extractResponseMetadata($){if(!$)return{};let J=$.get("x-request-id")||$.get("request-id")||$.get("x-correlation-id")||void 0,Q=$.get("retry-after"),Y;if(Q!==null){let X=Number.parseInt(Q,10);Y=Number.isNaN(X)?void 0:X}return{requestId:J,retryAfter:Y}}async executeRequest($,J,Q,Y){let X;try{X=await fetch($,Q)}catch(V){throw new U1(`Network request failed for ${J}`,{endpoint:$,cause:V instanceof Error?V:Error(String(V)),requestBody:Y})}let G,W=X.headers?.get("content-type")||"unknown",D=X.clone?X.clone():X;try{G=await X.json()}catch(V){let K;try{K=await D.text()}catch{K="[Unable to read response body]"}if(!X.ok){let O=`API request failed: ${X.status}. Response is not JSON (Content-Type: ${W})`,{requestId:N,retryAfter:M}=this.extractResponseMetadata(X.headers);throw new U1(O,{endpoint:$,statusCode:X.status,responseBody:{rawResponse:K.substring(0,500),contentType:W,parseError:V instanceof Error?V.message:String(V)},cause:V instanceof Error?V:void 0,requestBody:Y,requestId:N,retryAfter:M})}if(K.trim()==="")return;throw new U1(`Expected JSON response but received ${W}`,{endpoint:$,statusCode:X.status,responseBody:{rawResponse:K.substring(0,500),contentType:W},cause:V instanceof Error?V:void 0,requestBody:Y})}if(!X.ok){let V=G!==null&&typeof G==="object"?G:void 0,K=(typeof V?.message==="string"?V.message:void 0)||(typeof V?.error==="string"?V.error:void 0)||`API request failed: ${X.status}`,{requestId:O,retryAfter:N}=this.extractResponseMetadata(X.headers);throw new U1(K,{endpoint:$,statusCode:X.status,responseBody:G,requestBody:Y,requestId:O,retryAfter:N})}return G}async makeAuthenticatedRequest($,J={}){if(!this.sessionKeypair)throw new U1("Session keypair not set. Authenticate (login) first.",{endpoint:`${this.apiUrl}${$}`,statusCode:RH.StatusCodes.UNAUTHORIZED});let Q=`${this.apiUrl}${$}`,Y=this.parseRequestBody(J.body),X=this.buildSignatureHeaders($,J);return this.executeRequest(Q,$,{...J,headers:{"Content-Type":"application/json",...X,...J.headers}},Y)}buildSignatureHeaders($,J){if(!this.sessionKeypair)throw new U1("Session keypair not set. Authenticate (login) first.",{endpoint:`${this.apiUrl}${$}`,statusCode:RH.StatusCodes.UNAUTHORIZED});let Q=(J.method??"GET").toUpperCase(),Y=Date.now(),X=typeof J.body==="string"?b5(J.body):new Uint8Array(0),G=Uu(X),W=Ou(Q,$,Y,G),D=cM(this.sessionKeypair.privateKey,W);return{"X-Monaco-PublicKey":Y9(this.sessionKeypair.publicKey),"X-Monaco-Timestamp":String(Y),"X-Monaco-Signature":D}}async makeBackendRequest($,J={}){if(!this.serverKey)throw new U1("Server key not set. Call setServerKey(sk_...) first.",{endpoint:`${this.apiUrl}${$}`,statusCode:RH.StatusCodes.UNAUTHORIZED});let Q=`${this.apiUrl}${$}`,Y=this.parseRequestBody(J.body);return this.executeRequest(Q,$,{...J,headers:{"Content-Type":"application/json","x-server-key":this.serverKey,...J.headers}},Y)}async makePublicRequest($,J={}){let Q=`${this.apiUrl}${$}`,Y=this.parseRequestBody(J.body);return this.executeRequest(Q,$,{...J,headers:{"Content-Type":"application/json",...J.headers}},Y)}}function t$($){return encodeURIComponent($)}function d4($,J){if(!J)return $;let Q=new URLSearchParams;for(let[X,G]of Object.entries(J))if(G!==void 0)Q.set(X,String(G));let Y=Q.toString();return Y?`${$}?${Y}`:$}var D$={orders:{create:()=>"/api/v1/orders",list:($)=>d4("/api/v1/orders",$),get:($)=>`/api/v1/orders/${t$($)}`,replace:($)=>`/api/v1/orders/${t$($)}`,cancel:()=>"/api/v1/orders/cancel",batchCancel:()=>"/api/v1/orders/batch-cancel",batchCancelAll:()=>"/api/v1/orders/batch-cancel-all",batchCancelAllByPair:($)=>`/api/v1/orders/batch-cancel-all/${t$($)}`,batchCreate:()=>"/api/v1/orders/batch-create",batchReplace:()=>"/api/v1/orders/batch-replace",listConditional:($)=>d4("/api/v1/orders/conditional",$),cancelConditional:($)=>`/api/v1/orders/conditional/${t$($)}`,getConditional:($)=>`/api/v1/orders/conditional/${t$($)}`},delegatedAgents:{list:()=>"/api/v1/delegated-agents",owners:()=>"/api/v1/delegated-agents/owners",byId:($)=>`/api/v1/delegated-agents/${t$($)}`,sessions:()=>"/api/v1/delegated-agents/sessions"},withdrawals:{initiate:()=>"/api/v1/withdrawals",byIndex:($)=>`/api/v1/withdrawals/${t$(String($))}`,list:($)=>d4("/api/v1/withdrawals",$)},market:{listTradingPairs:($)=>d4("/api/v1/market/pairs",$),getTradingPair:($)=>`/api/v1/market/pairs/${t$($)}`,getCandles:($,J,Q)=>d4(`/api/v1/market/pairs/charts/candlestick/${t$($)}/${t$(J)}`,Q),getMarketMetadata:($)=>`/api/v1/market/pairs/${t$($)}/metadata`,getPerpMarketConfig:($)=>`/api/v1/market/pairs/${t$($)}/perp/config`,getPerpMarketSummary:($)=>`/api/v1/market/pairs/${t$($)}/perp/summary`,getMarkPrice:($)=>`/api/v1/market/pairs/${t$($)}/mark-price`,getIndexPrice:($)=>`/api/v1/market/pairs/${t$($)}/index-price`,getFundingState:($)=>`/api/v1/market/pairs/${t$($)}/funding`,listFundingHistory:($,J)=>d4(`/api/v1/market/pairs/${t$($)}/funding/history`,J),getOpenInterest:($)=>`/api/v1/market/pairs/${t$($)}/open-interest`,getScreener:($)=>d4("/api/v1/market/screener",$),getMarketStats:()=>"/api/v1/market/stats"},orderbook:{get:($,J)=>d4(`/api/v1/orderbook/${t$($)}`,J)},trades:{publicByPair:($,J)=>d4(`/api/v1/trades/${t$($)}`,J),byId:($)=>`/api/v1/trades/by-id/${t$($)}`,user:($)=>d4("/api/v1/accounts/trades",$)},applications:{orders:($)=>d4("/api/v1/applications/orders",$),users:($)=>d4("/api/v1/applications/users",$),movements:($)=>d4("/api/v1/applications/movements",$),balances:($)=>d4("/api/v1/applications/balances",$),stats:($)=>d4("/api/v1/applications/stats",$)},subAccounts:{list:()=>"/api/v1/accounts/sub-accounts",createLimit:()=>"/api/v1/accounts/sub-accounts/limits",getLimits:($)=>`/api/v1/accounts/sub-accounts/${t$($)}/limits`,limit:($,J)=>`/api/v1/accounts/sub-accounts/${t$($)}/limits/${t$(J)}`},faucet:{mint:()=>"/api/v1/faucet/mint"},whitelist:{submit:()=>"/api/v1/whitelist"},positions:{list:($)=>d4("/api/v1/positions",$),get:($)=>`/api/v1/positions/${t$($)}`,close:($)=>`/api/v1/positions/${t$($)}/close`,batchCloseAll:()=>"/api/v1/positions/batch-close-all",risk:($)=>`/api/v1/positions/${t$($)}/risk`,addMargin:($)=>`/api/v1/positions/${t$($)}/margin/add`,reduceMargin:($)=>`/api/v1/positions/${t$($)}/margin/reduce`,attachTpSl:($)=>`/api/v1/positions/${t$($)}/tp-sl`,history:($)=>d4("/api/v1/positions/history",$),pnlHistory:($,J)=>d4(`/api/v1/positions/${t$($)}/pnl/history`,J)},marginAccounts:{list:($)=>d4("/api/v1/margin/accounts",$),parentSummary:($)=>d4("/api/v1/margin/parent-margin-account",$),summary:($,J)=>d4(`/api/v1/margin/accounts/${t$($)}`,J),availableCollateral:($)=>d4("/api/v1/margin/collateral/available",$),transferIn:($)=>`/api/v1/margin/accounts/${t$($)}/collateral/transfer-in`,transferInParent:()=>"/api/v1/margin/parent-margin-account/collateral/transfer-in",transferInRiskBucket:()=>"/api/v1/margin/risk-buckets/collateral/transfer-in",transferOut:($)=>`/api/v1/margin/accounts/${t$($)}/collateral/transfer-out`,transferOutParent:()=>"/api/v1/margin/parent-margin-account/collateral/transfer-out",movements:($,J)=>d4(`/api/v1/margin/accounts/${t$($)}/movements`,J),parentMovements:($)=>d4("/api/v1/margin/parent-margin-account/movements",$),simulateParentMarginOrderRisk:()=>"/api/v1/margin/parent-margin-account/simulate-order-risk",simulateOrderRisk:($)=>`/api/v1/margin/accounts/${t$($)}/simulate-order-risk`,simulateRiskBucketOrderRisk:()=>"/api/v1/margin/risk-buckets/simulate-order-risk"},streams:{orderbook:()=>"/api/v1/streaming/orderbook",trades:()=>"/api/v1/streaming/trades",perpMarketSummaries:()=>"/api/v1/streaming/perp-market-summaries",markPrices:()=>"/api/v1/streaming/mark-prices",privateTrades:()=>"/api/v1/streaming/private-trades",orders:()=>"/api/v1/streaming/orders",positions:()=>"/api/v1/streaming/positions",funding:()=>"/api/v1/streaming/funding",liquidationAlerts:()=>"/api/v1/streaming/liquidation-alerts"}};class CH extends $4{async getApplicationConfig(){let $=await this.makeAuthenticatedRequest("/api/v1/applications/config",{method:"GET"});return{id:$.id,name:$.name,allowedOrigins:$.allowedOrigins,webhookUrl:$.webhookUrl,vaultContractAddress:$.vaultContractAddress,clientId:$.clientId}}async listApplicationOrders($){return await this.makeBackendRequest(D$.applications.orders($))}async listApplicationUsers($){return await this.makeBackendRequest(D$.applications.users($))}async listApplicationMovements($){return await this.makeBackendRequest(D$.applications.movements($))}async listApplicationBalances($){return await this.makeBackendRequest(D$.applications.balances($))}async getApplicationStats($){return await this.makeBackendRequest(D$.applications.stats($))}}class FS extends $4{async upsertDelegatedAgent($){return this.makeAuthenticatedRequest(D$.delegatedAgents.list(),{method:"POST",body:JSON.stringify({agentAddress:$.agentAddress,name:$.name,expiresAt:$.expiresAt,allowedActions:$.allowedActions,allowedTradingPairIds:$.allowedTradingPairIds,allowedMarginAccountIds:$.allowedMarginAccountIds,allowedOrderTypes:$.allowedOrderTypes,allowedTimeInForce:$.allowedTimeInForce,maxLeverage:$.maxLeverage,maxOrderNotional:$.maxOrderNotional,maxOpenOrders:$.maxOpenOrders})})}async listDelegatedAgents(){return this.makeAuthenticatedRequest(D$.delegatedAgents.list())}async listDelegatedOwners(){return this.makeAuthenticatedRequest(D$.delegatedAgents.owners())}async revokeDelegatedAgent($){return this.makeAuthenticatedRequest(D$.delegatedAgents.byId($),{method:"DELETE"})}async createDelegatedSession($){return this.makeAuthenticatedRequest(D$.delegatedAgents.sessions(),{method:"POST",body:JSON.stringify({ownerUserId:$.ownerUserId,sessionPublicKey:$.sessionPublicKey})})}}class PH extends $4{async mint($){return await this.makeAuthenticatedRequest(D$.faucet.mint(),{method:"POST",...$?.turnstileToken!==void 0&&{body:JSON.stringify({turnstileToken:$.turnstileToken})}})}}var jS=A.object({tradingPairId:A.string().trim().min(1,"Trading pair ID is required and cannot be empty"),side:A.enum(["BUY","SELL"],{message:"Order side is required and must be either 'BUY' or 'SELL'"}),price:A.string().trim().min(1,"Price is required and cannot be empty").refine(($)=>!Number.isNaN(Number($)),"Price must be a valid number").refine(($)=>Number($)>0,"Price must be greater than 0"),quantity:A.string().trim().min(1,"Quantity is required and cannot be empty").refine(($)=>!Number.isNaN(Number($)),"Quantity must be a valid number").refine(($)=>Number($)>0,"Quantity must be greater than 0"),orderType:A.enum(["LIMIT","MARKET"]).optional(),slippageToleranceBps:A.number().int().min(0,"Slippage tolerance must be between 0 and 1000 bps").max(1000,"Slippage tolerance must be between 0 and 1000 bps").optional()}).superRefine(($,J)=>{if($.slippageToleranceBps!==void 0&&$.orderType!=="MARKET")J.addIssue({code:A.ZodIssueCode.custom,message:"slippageToleranceBps is only valid when orderType is MARKET",path:["slippageToleranceBps"]})}),SK$=A.object({applicationName:A.string().nullable().optional(),applicationTakerFee:A.string(),applicationTakerFeeBps:A.number(),buyOrderLockAmount:A.string().nullable().optional(),makerTotalReceipt:A.string(),monacoMakerRebate:A.string(),monacoMakerRebateBps:A.number(),monacoTakerFee:A.string(),monacoTakerFeeBps:A.number(),notional:A.string(),takerTotalPayment:A.string(),totalTakerFees:A.string(),maxQuantity:A.string().nullable(),maxQuantityRaw:A.string().nullable(),slippageToleranceBps:A.number().nullable()}),ES=A.object({tradingPairId:A.string().trim().min(1,"Trading pair ID is required and cannot be empty")}),Wc=A.object({tierLevel:A.number().int(),minVolumeThreshold:A.string(),makerFeeBps:A.string(),takerFeeBps:A.string()}),_K$=A.object({currentTierLevel:A.number().int(),weightedVolume14d:A.string(),spotVolume14d:A.string(),perpVolume14d:A.string(),volumeToNextTier:A.string().nullable().optional(),nextTierLevel:A.number().int().nullable().optional(),feeSchedule:A.array(Wc)});var Dc=A.object({token:A.string(),available:A.string()}),TK$=A.object({balances:A.array(Dc)}),RK$=A.object({code:A.string(),createdAt:A.string()}),CK$=A.object({code:A.string()}),SS=A.object({token:A.string().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:A.string().trim().min(1,"amount is required").refine(($)=>/^\d+$/.test($)&&BigInt($)>0n,"amount must be a positive integer string")}),PK$=A.object({rewardsBalance:A.string(),tradingBalance:A.string()});var _S=["SUBMITTED","PARTIALLY_FILLED","FILLED","SETTLED_ON_CHAIN","SETTLED","CANCELLED","REJECTED","EXPIRED"];class Vc extends Error{issues;constructor($){let J=$.issues.map((Q)=>{let Y=Q.path.join(".");return`${Y?`${Y}: `:""}${Q.message}`});super(`Validation failed:
145
145
  - ${J.join(`
146
146
  - `)}`);this.name="ValidationError",this.issues=$.issues}getErrors(){let $={};for(let J of this.issues){let Q=J.path.join(".");$[Q||"root"]=J.message}return $}}function q$($,J){let Q=$.safeParse(J);if(!Q.success)throw new Vc(Q.error);return Q.data}var VK=A.enum(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),kH=A.enum(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),TS=A.enum(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),KK=A.enum(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),Kc=A.enum(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),RS=A.enum(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),iG=A.enum(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),N4=A.string().trim().min(1,"Value cannot be empty").regex(/^\d+(\.\d+)?$/,"Value must be a positive decimal number (e.g., '1.5', '100')").refine(($)=>Number.parseFloat($)>0,{message:"Value must be greater than 0"}),S$=A.uuid({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),UK=A.iso.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),Uc=A.number().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),OK=A.number().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),vH=A.object({triggerPrice:N4,orderType:iG,limitPrice:N4.optional(),timeInForce:RS.optional(),slippageToleranceBps:OK.optional(),expiresAt:UK.optional()}).refine(($)=>$.orderType!=="LIMIT"||$.limitPrice!==void 0,{message:"limitPrice is required for LIMIT parent TP/SL",path:["limitPrice"]}).refine(($)=>$.orderType!=="MARKET"||$.limitPrice===void 0,{message:"limitPrice must not be provided for MARKET parent TP/SL",path:["limitPrice"]}).refine(($)=>$.orderType!=="MARKET"||$.timeInForce===void 0,{message:"timeInForce is only allowed for LIMIT parent TP/SL",path:["timeInForce"]}).refine(($)=>$.orderType!=="LIMIT"||$.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only allowed for MARKET parent TP/SL",path:["slippageToleranceBps"]}),cG=($)=>$?.takeProfit!==void 0||$?.stopLoss!==void 0,Oc=A.object({tradingPairId:S$,side:VK,quantity:N4,price:N4,options:A.object({tradingMode:kH.optional(),useMasterBalance:A.boolean().optional(),expirationDate:UK.optional(),timeInForce:Kc.optional(),marginAccountId:S$.optional(),marginMode:TS.optional(),riskBucketId:S$.optional(),riskBucketCollateral:N4.optional(),strategyKey:A.string().min(1).max(128).optional(),positionSide:KK.optional(),leverage:N4.optional(),reduceOnly:A.boolean().optional(),takeProfit:vH.optional(),stopLoss:vH.optional()}).optional()}).refine(($)=>$.options?.tradingMode!=="MARGIN"||$.options.positionSide!==void 0,{message:"positionSide is required for MARGIN orders",path:["options","positionSide"]}).refine(($)=>$.options?.tradingMode!=="MARGIN"||$.options.leverage!==void 0,{message:"leverage is required for MARGIN orders",path:["options","leverage"]}).refine(($)=>!cG($.options)||$.options?.tradingMode==="MARGIN",{message:"Parent TP/SL is only supported for MARGIN orders",path:["options","tradingMode"]}).refine(($)=>!cG($.options)||$.options?.positionSide!=="NONE",{message:"Parent TP/SL requires positionSide to be LONG or SHORT",path:["options","positionSide"]}).refine(($)=>!cG($.options)||$.options?.reduceOnly!==!0,{message:"Parent TP/SL cannot be attached to reduceOnly orders",path:["options","reduceOnly"]}).refine(($)=>$.options?.riskBucketCollateral===void 0||$.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine(($)=>$.options?.marginMode===void 0||$.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine(($)=>$.options?.marginMode!=="CROSS"||$.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine(($)=>$.options?.marginMode!=="CROSS"||$.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine(($)=>$.options?.marginMode!=="CROSS"||$.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine(($)=>$.options?.marginMode!=="CROSS"||$.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine(($)=>$.options?.riskBucketCollateral===void 0||$.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine(($)=>$.options?.riskBucketCollateral===void 0||$.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}),Nc=A.object({tradingPairId:S$,side:VK,quantity:N4,options:A.object({tradingMode:kH.optional(),slippageTolerance:Uc,marginAccountId:S$.optional(),marginMode:TS.optional(),riskBucketId:S$.optional(),riskBucketCollateral:N4.optional(),strategyKey:A.string().min(1).max(128).optional(),positionSide:KK.optional(),leverage:N4.optional(),reduceOnly:A.boolean().optional(),takeProfit:vH.optional(),stopLoss:vH.optional()}).optional()}).refine(($)=>$.options?.tradingMode!=="MARGIN"||$.options.positionSide!==void 0,{message:"positionSide is required for MARGIN orders",path:["options","positionSide"]}).refine(($)=>$.options?.tradingMode!=="MARGIN"||$.options.leverage!==void 0,{message:"leverage is required for MARGIN orders",path:["options","leverage"]}).refine(($)=>!cG($.options)||$.options?.tradingMode==="MARGIN",{message:"Parent TP/SL is only supported for MARGIN orders",path:["options","tradingMode"]}).refine(($)=>!cG($.options)||$.options?.positionSide!=="NONE",{message:"Parent TP/SL requires positionSide to be LONG or SHORT",path:["options","positionSide"]}).refine(($)=>!cG($.options)||$.options?.reduceOnly!==!0,{message:"Parent TP/SL cannot be attached to reduceOnly orders",path:["options","reduceOnly"]}).refine(($)=>$.options?.riskBucketCollateral===void 0||$.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine(($)=>$.options?.marginMode===void 0||$.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine(($)=>$.options?.marginMode!=="CROSS"||$.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine(($)=>$.options?.marginMode!=="CROSS"||$.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine(($)=>$.options?.marginMode!=="CROSS"||$.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine(($)=>$.options?.marginMode!=="CROSS"||$.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine(($)=>$.options?.riskBucketCollateral===void 0||$.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine(($)=>$.options?.riskBucketCollateral===void 0||$.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}),Mc=A.object({orderId:S$}),wc=A.object({orderId:S$,newOrder:A.object({price:N4.optional(),quantity:N4.optional(),useMasterBalance:A.boolean().optional()})}),Hc=A.object({status:A.enum(_S).optional(),tradingPairId:S$.optional(),tradingMode:kH.optional(),marginAccountId:S$.optional(),page:A.number().int().min(1,"Page must be at least 1").optional(),pageSize:A.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),PB4=A.enum(["STOP_LOSS","TAKE_PROFIT"],{message:'conditionType must be "STOP_LOSS" or "TAKE_PROFIT"'}),vB4=A.enum(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),vK$=A.enum(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),kB4=A.enum(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),CS=A.object({conditionalOrderId:S$}),Ac=A.object({marginAccountId:S$.optional(),tradingPairId:S$.optional(),state:vK$.optional(),page:A.number().int().min(1,"Page must be at least 1").optional(),pageSize:A.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),kK$=A.object({tradingPairId:S$,orderType:iG,side:VK,price:N4.optional(),quantity:N4,tradingMode:kH.optional(),slippageTolerance:Uc,useMasterBalance:A.boolean().optional(),expirationDate:UK.optional(),timeInForce:Kc.optional(),marginAccountId:S$.optional(),marginMode:TS.optional(),riskBucketId:S$.optional(),riskBucketCollateral:N4.optional(),strategyKey:A.string().min(1).max(128).optional(),positionSide:KK.optional(),leverage:N4.optional(),reduceOnly:A.boolean().optional()}).refine(($)=>$.orderType!=="LIMIT"||$.price!==void 0,{message:"Price is required for LIMIT orders",path:["price"]}).refine(($)=>$.orderType!=="MARKET"||$.price===void 0,{message:"Price must not be provided for MARKET orders",path:["price"]}).refine(($)=>$.riskBucketCollateral===void 0||$.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["tradingMode"]}).refine(($)=>$.marginMode===void 0||$.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["tradingMode"]}).refine(($)=>$.marginMode!=="CROSS"||$.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["marginAccountId"]}).refine(($)=>$.marginMode!=="CROSS"||$.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["riskBucketId"]}).refine(($)=>$.marginMode!=="CROSS"||$.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["riskBucketCollateral"]}).refine(($)=>$.marginMode!=="CROSS"||$.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["strategyKey"]}).refine(($)=>$.riskBucketCollateral===void 0||$.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["riskBucketId"]}).refine(($)=>$.riskBucketCollateral===void 0||$.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["reduceOnly"]}).refine(($)=>$.tradingMode!=="MARGIN"||$.positionSide!==void 0,{message:"positionSide is required for MARGIN orders",path:["positionSide"]}).refine(($)=>$.tradingMode!=="MARGIN"||$.leverage!==void 0,{message:"leverage is required for MARGIN orders",path:["leverage"]}),zc=A.object({orders:A.array(kK$).min(1,"At least one order is required")}),xK$=A.object({orderId:S$,price:N4.optional(),quantity:N4.optional(),useMasterBalance:A.boolean().optional()}).refine(($)=>$.price!==void 0||$.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),Ic=A.object({orders:A.array(xK$).min(1,"At least one order is required")});var PS=A.object({page:A.number().int().min(1,"Page must be at least 1").optional(),pageSize:A.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),qc=PS.extend({state:A.string().trim().min(1,"State cannot be empty").optional(),tradingPairId:S$.optional()}),Zc=A.object({marginAccountId:S$,tradingPairId:S$.optional()}),Lc=A.object({tradingPairId:S$.optional()}).optional(),Bc=A.object({asset:A.string().trim().min(1,"Asset cannot be empty").optional()}).optional(),fK$=A.object({asset:A.string().trim().min(1,"Asset cannot be empty"),amount:N4,tradingPairId:S$.optional(),strategyKey:A.string().trim().min(1,"Strategy key cannot be empty").optional()}),xH=A.object({asset:A.string().trim().min(1,"Asset cannot be empty"),amount:N4}),bK$=A.object({tradingPairId:S$,strategyKey:A.string().trim().min(1,"Strategy key cannot be empty").optional()}),gK$=A.array(S$).min(1,"selectedTradingPairIds is required for CROSS risk buckets"),Fc=bK$.extend({marginMode:A.literal("ISOLATED").optional(),selectedTradingPairIds:A.never().optional()}),jc=A.object({marginMode:A.literal("CROSS"),selectedTradingPairIds:gK$,strategyKey:A.never().optional()}),yK$=jc.extend({tradingPairId:A.never().optional()}),vS=A.object({marginAccountId:S$,request:fK$}),Ec=A.object({request:xH}),Sc=A.object({request:A.union([xH.merge(Fc).strict(),xH.merge(yK$).strict()])}),_c=A.object({request:xH}),Tc=PS.extend({marginAccountId:S$,movementType:A.string().trim().min(1,"Movement type cannot be empty").optional()}),Rc=PS.extend({movementType:A.string().trim().min(1,"Movement type cannot be empty").optional()}).optional(),kS=A.object({tradingPairId:S$,side:VK,positionSide:KK,orderType:iG,price:N4.optional(),quantity:N4,leverage:N4,reduceOnly:A.boolean().optional()}),Cc=kS.strict(),hK$=kS.merge(Fc).strict(),uK$=kS.merge(jc).strict().refine(($)=>$.selectedTradingPairIds.includes($.tradingPairId),{message:"tradingPairId must be included in selectedTradingPairIds for CROSS risk buckets",path:["selectedTradingPairIds"]}),mK$=A.union([hK$,uK$]),Pc=A.object({marginAccountId:S$,request:Cc}).refine(($)=>$.request.orderType!=="LIMIT"||$.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),vc=A.object({request:Cc}).refine(($)=>$.request.orderType!=="LIMIT"||$.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),kc=A.object({request:mK$}).refine(($)=>$.request.orderType!=="LIMIT"||$.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]});var xc=A.enum(["1m","5m","15m","30m","1h","4h","1d","1w","1M"],{message:'Interval must be one of: "1m", "5m", "15m", "30m", "1h", "4h", "1d", "1w", "1M"'}),lK$=31536000000,dK$=946684800000,fH=A.number().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min(dK$,{message:"Timestamp must be at least Jan 1, 2000 (946684800000 ms). Did you pass seconds instead of milliseconds?"}).max(Number.MAX_SAFE_INTEGER,{message:"Timestamp must not exceed JavaScript's maximum safe integer"}).refine(($)=>$<=Date.now()+lK$,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),uB4=A.object({tradingPairId:S$,interval:xc,startTime:fH,endTime:fH}).refine(($)=>$.startTime<$.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),mB4=A.string().min(1,"Trading pair symbol cannot be empty").regex(/^[A-Za-z0-9]{1,10}\/[A-Za-z0-9]{1,10}$/,{message:'Trading pair symbol must be in format "BASE/QUOTE" (e.g., "BTC/USDT", "ETH/USD")'}),pK$=A.number().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),fc=A.object({tradingPairId:S$,interval:xc,startTime:fH.optional(),endTime:fH.optional(),limit:pK$}).refine(($)=>{if($.startTime!==void 0&&$.endTime!==void 0)return $.startTime<$.endTime;return!0},{message:"startTime must be less than endTime",path:["endTime"]});var lB4=A.object({tradingPairId:S$}),dB4=A.object({query:A.string().min(1,"Search query cannot be empty").optional(),pageSize:A.number().int().min(1).max(100).optional(),page:A.number().int().min(1).optional()}),vJ=A.object({tradingPairId:S$});var gc=A.object({page:A.number().int().min(1,"Page must be at least 1").optional(),pageSize:A.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),nK$=A.enum(["OPEN","CLOSED","LIQUIDATING"],{message:'Position status must be "OPEN", "CLOSED", or "LIQUIDATING"'}),cK$=A.enum(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),n9=A.object({positionId:S$}),yc=gc.extend({marginAccountId:S$.optional(),tradingPairId:S$.optional(),status:nK$.optional()}),hc=n9,uc=n9.extend({request:A.object({closeType:cK$,limitPrice:N4.optional(),slippageToleranceBps:OK.optional(),quantity:N4.optional()})}).refine(($)=>$.request.closeType!=="LIMIT"||$.request.limitPrice!==void 0,{message:"limitPrice is required for LIMIT close requests",path:["request","limitPrice"]}).refine(($)=>$.request.closeType==="LIMIT"||$.request.limitPrice===void 0,{message:"limitPrice is only allowed for LIMIT close requests",path:["request","limitPrice"]}),mc=A.object({tradingPairId:S$.optional(),slippageToleranceBps:OK.optional()}),lc=n9,dc=n9.extend({request:A.object({amount:N4,asset:A.string().trim().min(1,"Asset cannot be empty")})}),pc=n9.extend({request:A.object({amount:N4})}),bc=A.object({triggerPrice:N4,orderType:iG,limitPrice:N4.optional(),quantity:N4.optional(),timeInForce:RS.optional(),slippageToleranceBps:OK.optional(),expiresAt:UK.optional()}).refine(($)=>$.orderType!=="LIMIT"||$.limitPrice!==void 0,{message:"limitPrice is required for LIMIT TP/SL legs",path:["limitPrice"]}).refine(($)=>$.orderType!=="MARKET"||$.limitPrice===void 0,{message:"limitPrice must not be provided for MARKET TP/SL legs",path:["limitPrice"]}).refine(($)=>$.orderType!=="MARKET"||$.timeInForce===void 0,{message:"timeInForce is only allowed for LIMIT TP/SL legs",path:["timeInForce"]}).refine(($)=>$.orderType!=="LIMIT"||$.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only allowed for MARKET TP/SL legs",path:["slippageToleranceBps"]}),nc=n9.extend({request:A.object({takeProfit:bc.optional(),stopLoss:bc.optional()}).refine(($)=>$.takeProfit!==void 0||$.stopLoss!==void 0,{message:"At least one of takeProfit or stopLoss is required"})}),cc=gc.extend({positionId:S$.optional(),marginAccountId:S$.optional(),tradingPairId:S$.optional(),reductionOnly:A.boolean().optional()}),iK$=A.enum(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),ic=n9.extend({params:A.object({interval:iK$,startTime:A.number().int().min(0,"startTime must be a non-negative millisecond timestamp").optional(),endTime:A.number().int().min(0,"endTime must be a non-negative millisecond timestamp").optional()}).refine(($)=>$.startTime===void 0||$.endTime===void 0||$.startTime<$.endTime,{message:"startTime must be less than endTime",path:["startTime"]})});var oK$=A.enum(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),rK$=A.enum(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),oc=A.object({page:A.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:A.number().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional(),entryType:oK$.optional(),transactionType:rK$.optional(),assetId:S$.optional()}),rc=A.object({page:A.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:A.number().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional(),tradingPairId:S$.optional()}),tc=A.object({page:A.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:A.number().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional(),tradingPairId:S$.optional(),positionId:S$.optional(),marginAccountId:S$.optional()});var eB4=A.string().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),xS=A.union([A.string().regex(/^\d+$/,"Must be a positive integer string").refine(($)=>BigInt($)>0n,{message:"Amount must be greater than 0"}),A.bigint().refine(($)=>$>0n,{message:"Amount must be greater than 0"})]),ac=A.object({assetId:S$,amount:xS,autoWait:A.boolean().optional()}),sc=A.object({assetId:S$,amount:xS,autoWait:A.boolean().optional(),target:A.enum(["spot","margin"]).optional()}),ec=A.object({assetId:S$,amount:xS,destination:A.string().regex(/^0x[a-fA-F0-9]{40}$/,"destination must be a 0x-prefixed 20-byte hex address"),autoWait:A.boolean().optional(),source:A.enum(["spot","margin"]).optional()}),$F4=A.object({assetId:S$});class bH extends $4{async simulateFees($){let J=q$(jS,$),Q=new URLSearchParams;if(Q.append("tradingPairId",J.tradingPairId),Q.append("side",J.side),Q.append("price",J.price),Q.append("quantity",J.quantity),J.orderType!==void 0)Q.append("orderType",J.orderType);if(J.slippageToleranceBps!==void 0)Q.append("slippageToleranceBps",String(J.slippageToleranceBps));let Y=`/api/v1/fees/simulate?${Q.toString()}`;return await this.makeAuthenticatedRequest(Y,{method:"GET"})}async getMyFeeTier($){let J=q$(ES,$),Q=new URLSearchParams;Q.append("tradingPairId",J.tradingPairId);let Y=`/api/v1/fees/tier?${Q.toString()}`;return await this.makeAuthenticatedRequest(Y,{method:"GET"})}}class gH extends $4{async listMarginAccounts($){if($)q$(qc,$);return await this.makeAuthenticatedRequest(D$.marginAccounts.list($?{page:$.page,pageSize:$.pageSize,state:$.state,tradingPairId:$.tradingPairId}:void 0))}async getMarginAccountSummary($,J){return q$(Zc,{marginAccountId:$,...J}),await this.makeAuthenticatedRequest(D$.marginAccounts.summary($,{tradingPairId:J?.tradingPairId}))}async getParentMarginAccountSummary($){return q$(Lc,$),await this.makeAuthenticatedRequest(D$.marginAccounts.parentSummary({tradingPairId:$?.tradingPairId}))}async getAvailableCollateral($){return q$(Bc,$),await this.makeAuthenticatedRequest(D$.marginAccounts.availableCollateral($))}async transferCollateralToMarginAccount($,J){return q$(vS,{marginAccountId:$,request:J}),await this.makeAuthenticatedRequest(D$.marginAccounts.transferIn($),{method:"POST",body:JSON.stringify({asset:J.asset,amount:J.amount,tradingPairId:J.tradingPairId,strategyKey:J.strategyKey})})}async transferCollateralToParentMarginAccount($){return q$(Ec,{request:$}),await this.makeAuthenticatedRequest(D$.marginAccounts.transferInParent(),{method:"POST",body:JSON.stringify({asset:$.asset,amount:$.amount})})}async transferCollateralToRiskBucket($){return q$(Sc,{request:$}),await this.makeAuthenticatedRequest(D$.marginAccounts.transferInRiskBucket(),{method:"POST",body:JSON.stringify({asset:$.asset,amount:$.amount,tradingPairId:$.tradingPairId,strategyKey:$.strategyKey,marginMode:$.marginMode,selectedTradingPairIds:$.selectedTradingPairIds})})}async transferCollateralFromMarginAccount($,J){return q$(vS,{marginAccountId:$,request:J}),await this.makeAuthenticatedRequest(D$.marginAccounts.transferOut($),{method:"POST",body:JSON.stringify({asset:J.asset,amount:J.amount,tradingPairId:J.tradingPairId,strategyKey:J.strategyKey})})}async transferCollateralFromParentMarginAccount($){return q$(_c,{request:$}),await this.makeAuthenticatedRequest(D$.marginAccounts.transferOutParent(),{method:"POST",body:JSON.stringify({asset:$.asset,amount:$.amount})})}async getMarginAccountMovements($,J){return q$(Tc,{marginAccountId:$,...J}),await this.makeAuthenticatedRequest(D$.marginAccounts.movements($,J))}async getParentMarginAccountMovements($){return q$(Rc,$),await this.makeAuthenticatedRequest(D$.marginAccounts.parentMovements($))}async simulateOrderRisk($,J){return q$(Pc,{marginAccountId:$,request:J}),await this.makeAuthenticatedRequest(D$.marginAccounts.simulateOrderRisk($),{method:"POST",body:JSON.stringify({tradingPairId:J.tradingPairId,side:J.side,positionSide:J.positionSide,orderType:J.orderType,price:J.price,quantity:J.quantity,leverage:J.leverage,reduceOnly:J.reduceOnly})})}async simulateParentMarginOrderRisk($){return q$(vc,{request:$}),await this.makeAuthenticatedRequest(D$.marginAccounts.simulateParentMarginOrderRisk(),{method:"POST",body:JSON.stringify({tradingPairId:$.tradingPairId,side:$.side,positionSide:$.positionSide,orderType:$.orderType,price:$.price,quantity:$.quantity,leverage:$.leverage,reduceOnly:$.reduceOnly})})}async simulateRiskBucketOrderRisk($){return q$(kc,{request:$}),await this.makeAuthenticatedRequest(D$.marginAccounts.simulateRiskBucketOrderRisk(),{method:"POST",body:JSON.stringify({tradingPairId:$.tradingPairId,strategyKey:$.strategyKey,marginMode:$.marginMode,selectedTradingPairIds:$.selectedTradingPairIds,side:$.side,positionSide:$.positionSide,orderType:$.orderType,price:$.price,quantity:$.quantity,leverage:$.leverage,reduceOnly:$.reduceOnly})})}}class yH extends $4{async getPaginatedTradingPairs($){let J=new URLSearchParams;if($?.page!==void 0)J.append("page",$.page.toString());if($?.pageSize!==void 0)J.append("pageSize",$.pageSize.toString());if($?.marketType)J.append("marketType",$.marketType);if($?.baseToken)J.append("baseToken",$.baseToken);if($?.quoteToken)J.append("quoteToken",$.quoteToken);if($?.isActive!==void 0)J.append("isActive",$.isActive.toString());if($?.category)J.append("category",$.category);let Q=J.toString(),Y=Q?`/api/v1/market/pairs?${Q}`:"/api/v1/market/pairs";return await this.makePublicRequest(Y)}async getTradingPair($){return q$(vJ,{tradingPairId:$}),(await this.makePublicRequest(D$.market.getTradingPair($))).tradingPair}async getTradingPairBySymbol($,J){return(await this.getPaginatedTradingPairs({pageSize:100,marketType:J})).tradingPairs.find((Y)=>Y.symbol===$)}async getCandlesticks($,J,Q){q$(fc,{tradingPairId:$,interval:J,startTime:Q?.startTime,endTime:Q?.endTime,limit:Q?.limit});let Y=new URLSearchParams;if(Q?.startTime!==void 0)Y.append("startTime",Q.startTime.toString());if(Q?.endTime!==void 0)Y.append("endTime",Q.endTime.toString());if(Q?.limit!==void 0)Y.append("limit",Q.limit.toString());let X=Y.toString(),G=X?`/api/v1/market/pairs/charts/candlestick/${encodeURIComponent($)}/${J}?${X}`:`/api/v1/market/pairs/charts/candlestick/${encodeURIComponent($)}/${J}`;return(await this.makePublicRequest(G)).data||[]}async getMarketMetadata($){return q$(vJ,{tradingPairId:$}),await this.makePublicRequest(D$.market.getMarketMetadata($))}async getPerpMarketConfig($){return q$(vJ,{tradingPairId:$}),await this.makePublicRequest(D$.market.getPerpMarketConfig($))}async getPerpMarketSummary($){return q$(vJ,{tradingPairId:$}),await this.makePublicRequest(D$.market.getPerpMarketSummary($))}async getMarkPrice($){return q$(vJ,{tradingPairId:$}),await this.makePublicRequest(D$.market.getMarkPrice($))}async getIndexPrice($){return q$(vJ,{tradingPairId:$}),await this.makePublicRequest(D$.market.getIndexPrice($))}async getFundingState($){return q$(vJ,{tradingPairId:$}),await this.makePublicRequest(D$.market.getFundingState($))}async listFundingHistory($,J){return q$(vJ,{tradingPairId:$}),await this.makePublicRequest(D$.market.listFundingHistory($,J))}async getOpenInterest($){return q$(vJ,{tradingPairId:$}),await this.makePublicRequest(D$.market.getOpenInterest($))}async getScreener($){return await this.makePublicRequest(D$.market.getScreener($))}async getMarketStats(){return await this.makePublicRequest(D$.market.getMarketStats())}}class hH extends $4{async getOrderbook($,J={}){let{depth:Q=10,tradingMode:Y,magnitude:X,denomination:G}=J,W=new URLSearchParams;if(W.set("levels",String(Q)),Y)W.set("tradingMode",Y);if(X!==void 0)W.set("magnitude",String(X));if(G)W.set("denomination",G.toLowerCase());let D=await this.makePublicRequest(`/api/v1/orderbook/${encodeURIComponent($)}?${W.toString()}`);return{tradingPairId:D.tradingPairId,tradingMode:D.tradingMode,bids:D.data.bids.map((V)=>({price:V.price,quantity:V.quantity,orderCount:V.orderCount})),asks:D.data.asks.map((V)=>({price:V.price,quantity:V.quantity,orderCount:V.orderCount})),bestBid:D.data.bestBid,bestAsk:D.data.bestAsk,bidVolume:D.data.bidVolume,askVolume:D.data.askVolume,baseDecimals:D.baseDecimals,quoteDecimals:D.quoteDecimals,timestamp:D.timestamp,sequence:D.sequenceNumber}}}class uH extends $4{async getMyTraderCode(){return await this.makeAuthenticatedRequest("/api/v1/pitpass/codes/me",{method:"GET"})}async getTraderCodeInfo($){let J=encodeURIComponent($.trim());return await this.makePublicRequest(`/api/v1/pitpass/codes/${J}`,{method:"GET"})}async getRewardsBalance(){return await this.makeAuthenticatedRequest("/api/v1/pitpass/rewards/balance",{method:"GET"})}async transferRewards($){let J=q$(SS,$);return await this.makeAuthenticatedRequest("/api/v1/pitpass/rewards/transfer",{method:"POST",body:JSON.stringify({token:J.token,amount:J.amount})})}}class mH extends $4{async listPositions($){if($)q$(yc,$);return await this.makeAuthenticatedRequest(D$.positions.list($))}async getPosition($){return q$(hc,{positionId:$}),await this.makeAuthenticatedRequest(D$.positions.get($))}async closePosition($,J){return q$(uc,{positionId:$,request:J}),await this.makeAuthenticatedRequest(D$.positions.close($),{method:"POST",body:JSON.stringify({closeType:J.closeType,limitPrice:J.limitPrice,slippageToleranceBps:J.slippageToleranceBps,quantity:J.quantity})})}async batchCloseAllPositions($){if($)q$(mc,$);return await this.makeAuthenticatedRequest(D$.positions.batchCloseAll(),{method:"POST",body:JSON.stringify({tradingPairId:$?.tradingPairId,slippageToleranceBps:$?.slippageToleranceBps})})}async getPositionRisk($){return q$(lc,{positionId:$}),await this.makeAuthenticatedRequest(D$.positions.risk($))}async addPositionMargin($,J){return q$(dc,{positionId:$,request:J}),await this.makeAuthenticatedRequest(D$.positions.addMargin($),{method:"POST",body:JSON.stringify({amount:J.amount,asset:J.asset})})}async reducePositionMargin($,J){return q$(pc,{positionId:$,request:J}),await this.makeAuthenticatedRequest(D$.positions.reduceMargin($),{method:"POST",body:JSON.stringify({amount:J.amount})})}async attachPositionTpSl($,J){return q$(nc,{positionId:$,request:J}),await this.makeAuthenticatedRequest(D$.positions.attachTpSl($),{method:"POST",body:JSON.stringify({takeProfit:J.takeProfit?{triggerPrice:J.takeProfit.triggerPrice,orderType:J.takeProfit.orderType,limitPrice:J.takeProfit.limitPrice,quantity:J.takeProfit.quantity,timeInForce:J.takeProfit.timeInForce,slippageToleranceBps:J.takeProfit.slippageToleranceBps,expiresAt:J.takeProfit.expiresAt}:void 0,stopLoss:J.stopLoss?{triggerPrice:J.stopLoss.triggerPrice,orderType:J.stopLoss.orderType,limitPrice:J.stopLoss.limitPrice,quantity:J.stopLoss.quantity,timeInForce:J.stopLoss.timeInForce,slippageToleranceBps:J.stopLoss.slippageToleranceBps,expiresAt:J.stopLoss.expiresAt}:void 0})})}async listPositionHistory($){if($)q$(cc,$);return await this.makeAuthenticatedRequest(D$.positions.history($))}async getPositionPnlHistory($,J){return q$(ic,{positionId:$,params:J}),await this.makeAuthenticatedRequest(D$.positions.pnlHistory($,J))}}class fS extends $4{async getProfile(){return await this.makeAuthenticatedRequest("/api/v1/accounts/me")}async getPaginatedUserMovements($){if($)q$(oc,$);let J=new URLSearchParams;if($?.page!==void 0)J.append("page",$.page.toString());if($?.pageSize!==void 0)J.append("pageSize",$.pageSize.toString());if($?.entryType!==void 0)J.append("entryType",$.entryType);if($?.transactionType!==void 0)J.append("transactionType",$.transactionType);if($?.assetId!==void 0)J.append("assetId",$.assetId);let Q=J.toString(),Y=Q?`/api/v1/accounts/movements?${Q}`:"/api/v1/accounts/movements";return await this.makeAuthenticatedRequest(Y)}async getUserBalances($){let J=new URLSearchParams;if($?.page!==void 0)J.append("page",$.page.toString());if($?.pageSize!==void 0)J.append("pageSize",$.pageSize.toString());let Q=J.toString(),Y=Q?`/api/v1/accounts/balances?${Q}`:"/api/v1/accounts/balances";return await this.makeAuthenticatedRequest(Y)}async getUserBalanceByAssetId($){if(!$||$.trim()==="")throw new U1("assetId is required and cannot be empty",{endpoint:"/api/v1/accounts/balances/{assetId}"});let J=`/api/v1/accounts/balances/${$}`;return await this.makeAuthenticatedRequest(J)}async getPortfolioStats($){let J=new URLSearchParams({period:$});return await this.makeAuthenticatedRequest(`/api/v1/accounts/me/portfolio?${J}`)}async getPortfolioChart($,J){let Q=new URLSearchParams({period:$,metric:J});return await this.makeAuthenticatedRequest(`/api/v1/accounts/me/portfolio/chart?${Q}`)}async getUserTrades($){if($)q$(rc,$);let J=new URLSearchParams;if($?.page!==void 0)J.append("page",$.page.toString());if($?.pageSize!==void 0)J.append("pageSize",$.pageSize.toString());if($?.tradingPairId!==void 0)J.append("tradingPairId",$.tradingPairId);let Q=J.toString(),Y=Q?`/api/v1/accounts/trades?${Q}`:"/api/v1/accounts/trades";return await this.makeAuthenticatedRequest(Y)}async listFundingPayments($){if($)q$(tc,$);let J=new URLSearchParams;if($?.page!==void 0)J.append("page",$.page.toString());if($?.pageSize!==void 0)J.append("pageSize",$.pageSize.toString());if($?.tradingPairId!==void 0)J.append("tradingPairId",$.tradingPairId);if($?.positionId!==void 0)J.append("positionId",$.positionId);if($?.marginAccountId!==void 0)J.append("marginAccountId",$.marginAccountId);let Q=J.toString(),Y=Q?`/api/v1/accounts/funding-payments?${Q}`:"/api/v1/accounts/funding-payments";return await this.makeAuthenticatedRequest(Y)}}class lH extends $4{async list(){return await this.makeAuthenticatedRequest(D$.subAccounts.list())}async createLimit($){return await this.makeAuthenticatedRequest(D$.subAccounts.createLimit(),{method:"POST",body:JSON.stringify($)})}async getLimits($){return await this.makeAuthenticatedRequest(D$.subAccounts.getLimits($))}async updateLimit($,J,Q){return await this.makeAuthenticatedRequest(D$.subAccounts.limit($,J),{method:"PUT",body:JSON.stringify(Q)})}async deleteLimit($,J){await this.makeAuthenticatedRequest(D$.subAccounts.limit($,J),{method:"DELETE"})}}function $i($){return{eventType:"trade",tradingPairId:$.tradingPairId,tradingMode:$.tradingMode.toUpperCase(),data:{tradeId:$.data.tradeId,price:$.data.price,quantity:$.data.quantity,makerSide:$.data.makerSide.toUpperCase(),executedAt:$.data.executedAt??""}}}class bS extends $4{async getTrades($,J={}){let{page:Q=1}=J,Y=J.pageSize!=null&&J.pageSize>0?Math.min(J.pageSize,100):25,X=new URLSearchParams;if(Q>1)X.set("page",String(Q));return X.set("pageSize",String(Y)),(await this.makePublicRequest(`/api/v1/trades/${encodeURIComponent($)}?${X.toString()}`)).trades.map($i)}async getTradeById($){let J=await this.makePublicRequest(D$.trades.byId($));return $i(J)}}function dH($){if(!$)return;return{triggerPrice:$.triggerPrice,orderType:$.orderType,limitPrice:$.limitPrice,timeInForce:$.timeInForce,slippageToleranceBps:$.slippageToleranceBps,expiresAt:$.expiresAt}}class pH extends $4{async placeLimitOrder($,J,Q,Y,X){q$(Oc,{tradingPairId:$,side:J,quantity:Q,price:Y,options:X});let G={tradingPairId:$,orderType:"LIMIT",side:J,price:Y,quantity:Q,tradingMode:X?.tradingMode||"SPOT",useMasterBalance:X?.useMasterBalance,expirationDate:X?.expirationDate,timeInForce:X?.timeInForce,marginAccountId:X?.marginAccountId,marginMode:X?.marginMode,riskBucketId:X?.riskBucketId,riskBucketCollateral:X?.riskBucketCollateral,strategyKey:X?.strategyKey,positionSide:X?.positionSide,leverage:X?.leverage,reduceOnly:X?.reduceOnly,takeProfit:dH(X?.takeProfit),stopLoss:dH(X?.stopLoss)};return await this.makeAuthenticatedRequest(D$.orders.create(),{method:"POST",body:JSON.stringify(G)})}async placeMarketOrder($,J,Q,Y){q$(Nc,{tradingPairId:$,side:J,quantity:Q,options:Y});let X={tradingPairId:$,orderType:"MARKET",side:J,slippageToleranceBps:Y?.slippageTolerance!==void 0?Math.round(Y.slippageTolerance*1e4):void 0,price:null,quantity:Q,tradingMode:Y?.tradingMode||"SPOT",marginAccountId:Y?.marginAccountId,marginMode:Y?.marginMode,riskBucketId:Y?.riskBucketId,riskBucketCollateral:Y?.riskBucketCollateral,strategyKey:Y?.strategyKey,positionSide:Y?.positionSide,leverage:Y?.leverage,reduceOnly:Y?.reduceOnly,takeProfit:dH(Y?.takeProfit),stopLoss:dH(Y?.stopLoss)};return await this.makeAuthenticatedRequest(D$.orders.create(),{method:"POST",body:JSON.stringify(X)})}async cancelOrder($){q$(Mc,{orderId:$});let J={orderId:$};return await this.makeAuthenticatedRequest(D$.orders.cancel(),{method:"POST",body:JSON.stringify(J)})}async cancelConditionalOrder($){return q$(CS,{conditionalOrderId:$}),await this.makeAuthenticatedRequest(D$.orders.cancelConditional($),{method:"DELETE"})}async getConditionalOrder($){return q$(CS,{conditionalOrderId:$}),await this.makeAuthenticatedRequest(D$.orders.getConditional($),{method:"GET"})}async listConditionalOrders($){if($)q$(Ac,$);let{page:J=1,pageSize:Q=20,marginAccountId:Y,tradingPairId:X,state:G}=$||{};return await this.makeAuthenticatedRequest(D$.orders.listConditional({page:J,pageSize:Math.min(Math.max(Q,1),100),marginAccountId:Y,tradingPairId:X,state:G}),{method:"GET"})}async batchCancel($){if(!$||$.length===0)throw Error("orderIds is required and must not be empty");return this.makeAuthenticatedRequest(D$.orders.batchCancel(),{method:"POST",body:JSON.stringify({orderIds:$})})}async batchCancelAll($){let J=$?D$.orders.batchCancelAllByPair($):D$.orders.batchCancelAll();return this.makeAuthenticatedRequest(J,{method:"POST"})}async replaceOrder($,J){q$(wc,{orderId:$,newOrder:J});let Q={useMasterBalance:J.useMasterBalance??!1};if(J.price!==void 0)Q.price=J.price;if(J.quantity!==void 0)Q.quantity=J.quantity;return await this.makeAuthenticatedRequest(D$.orders.replace($),{method:"PUT",body:JSON.stringify(Q)})}async batchCreate($){q$(zc,{orders:$});let J={orders:$.map((Q)=>({tradingPairId:Q.tradingPairId,orderType:Q.orderType,side:Q.side,price:Q.price,quantity:Q.quantity,tradingMode:Q.tradingMode||"SPOT",slippageToleranceBps:Q.slippageTolerance!==void 0?Math.round(Q.slippageTolerance*1e4):void 0,useMasterBalance:Q.useMasterBalance,expirationDate:Q.expirationDate,timeInForce:Q.timeInForce,marginAccountId:Q.marginAccountId,marginMode:Q.marginMode,riskBucketId:Q.riskBucketId,riskBucketCollateral:Q.riskBucketCollateral,strategyKey:Q.strategyKey,positionSide:Q.positionSide,leverage:Q.leverage,reduceOnly:Q.reduceOnly}))};return this.makeAuthenticatedRequest(D$.orders.batchCreate(),{method:"POST",body:JSON.stringify(J)})}async batchReplace($){q$(Ic,{orders:$});let J={orders:$.map((Q)=>({orderId:Q.orderId,price:Q.price,quantity:Q.quantity,useMasterBalance:Q.useMasterBalance}))};return this.makeAuthenticatedRequest(D$.orders.batchReplace(),{method:"POST",body:JSON.stringify(J)})}async getPaginatedOrders($){if($)q$(Hc,$);let{page:J=1,pageSize:Q=10,status:Y,tradingPairId:X,tradingMode:G,marginAccountId:W}=$||{},D=J>0?J:1,V=Q>0?Q:10,K=Math.min(V,100),O=new URLSearchParams;if(O.append("page",D.toString()),O.append("pageSize",K.toString()),Y)O.append("status",Y);if(X)O.append("tradingPairId",X);if(G)O.append("tradingMode",G);if(W)O.append("marginAccountId",W);let N=`/api/v1/orders?${O.toString()}`;return await this.makeAuthenticatedRequest(N,{method:"GET"})}async getOrder($){return{order:await this.makeAuthenticatedRequest(D$.orders.get($),{method:"GET"}),status:"SUCCESS"}}}var gS=[{inputs:[],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"AccessControlBadConfirmation",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"bytes32",name:"neededRole",type:"bytes32"}],name:"AccessControlUnauthorizedAccount",type:"error"},{inputs:[{internalType:"address",name:"target",type:"address"}],name:"AddressEmptyCode",type:"error"},{inputs:[],name:"ECDSAInvalidSignature",type:"error"},{inputs:[{internalType:"uint256",name:"length",type:"uint256"}],name:"ECDSAInvalidSignatureLength",type:"error"},{inputs:[{internalType:"bytes32",name:"s",type:"bytes32"}],name:"ECDSAInvalidSignatureS",type:"error"},{inputs:[{internalType:"address",name:"implementation",type:"address"}],name:"ERC1967InvalidImplementation",type:"error"},{inputs:[],name:"ERC1967NonPayable",type:"error"},{inputs:[],name:"EnforcedPause",type:"error"},{inputs:[],name:"ExpectedPause",type:"error"},{inputs:[],name:"FailedCall",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"ERC20InsufficientBalance",type:"error"},{inputs:[],name:"InsufficientBalance",type:"error"},{inputs:[],name:"InvalidAddress",type:"error"},{inputs:[],name:"InvalidInitialization",type:"error"},{inputs:[],name:"InvalidSeed",type:"error"},{inputs:[],name:"InvalidSignature",type:"error"},{inputs:[],name:"InvalidTimestamp",type:"error"},{inputs:[],name:"NonceAlreadyUsed",type:"error"},{inputs:[],name:"NotInitializing",type:"error"},{inputs:[],name:"ReentrancyGuardReentrantCall",type:"error"},{inputs:[],name:"TransferFailed",type:"error"},{inputs:[],name:"UUPSUnauthorizedCallContext",type:"error"},{inputs:[{internalType:"bytes32",name:"slot",type:"bytes32"}],name:"UUPSUnsupportedProxiableUUID",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Deposit",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"newFeeCollector",type:"address"}],name:"FeeCollectorChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint64",name:"version",type:"uint64"}],name:"Initialized",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Paused",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"previousAdminRole",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"newAdminRole",type:"bytes32"}],name:"RoleAdminChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:!0,internalType:"address",name:"account",type:"address"},{indexed:!0,internalType:"address",name:"sender",type:"address"}],name:"RoleGranted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:!0,internalType:"address",name:"account",type:"address"},{indexed:!0,internalType:"address",name:"sender",type:"address"}],name:"RoleRevoked",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"newSettlementContract",type:"address"}],name:"SettlementContractChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"maker",type:"address"},{indexed:!0,internalType:"address",name:"taker",type:"address"},{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"uint256",name:"fee",type:"uint256"}],name:"SettlementTransfer",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Unpaused",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"implementation",type:"address"}],name:"Upgraded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdrawal",type:"event"},{inputs:[],name:"DEBUGGER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"DEFAULT_ADMIN_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"FEE_MANAGER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"PAUSER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"SETTLEMENT_MANAGER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"UPGRADER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"UPGRADE_INTERFACE_VERSION",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"token",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"seed",type:"bytes"}],name:"decodeSeed",outputs:[{internalType:"address",name:"",type:"address"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"destination",type:"address"},{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"token",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"depositERC20",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"destination",type:"address"},{internalType:"string",name:"applicationId",type:"string"}],name:"depositNative",outputs:[],stateMutability:"payable",type:"function"},{inputs:[],name:"feeCollector",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getChainID",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"}],name:"getRoleAdmin",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"account",type:"address"}],name:"grantRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"account",type:"address"}],name:"hasRole",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"_admin",type:"address"}],name:"initialize",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"pause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"paused",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"proxiableUUID",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"callerConfirmation",type:"address"}],name:"renounceRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"account",type:"address"}],name:"revokeRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_newFeeCollector",type:"address"}],name:"setFeeCollector",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_settlementContract",type:"address"}],name:"setSettlementContract",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"settlementContract",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"maker",type:"address"},{internalType:"address",name:"taker",type:"address"},{internalType:"address",name:"token",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"fee",type:"uint256"}],name:"transferOnSettlement",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"unpause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newImplementation",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],name:"upgradeToAndCall",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes",name:"seed",type:"bytes"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"withdraw",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes",name:"seed",type:"bytes"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"withdrawNative",outputs:[],stateMutability:"nonpayable",type:"function"}];var yS={vault:gS};var tK$=5000,aK$=300000,sK$=($)=>new Promise((J)=>setTimeout(J,$));function Ji($,J){return J==="margin"?JSON.stringify({clientId:$,depositTarget:"MARGIN"}):$}class nH extends $4{publicClient;chain;applicationsAPI;profileAPI;walletClient;constructor($,J,Q,Y,X,G){super(G);this.publicClient=$,this.chain=Q,this.walletClient=J,this.applicationsAPI=Y,this.profileAPI=X}setWalletClient($){this.walletClient=$}async getVaultAddress(){return(await this.applicationsAPI.getApplicationConfig()).vaultContractAddress}async getClientId(){return(await this.applicationsAPI.getApplicationConfig()).clientId}async resolveAsset($){let J;try{J=(await this.profileAPI.getUserBalanceByAssetId($)).token}catch(Y){if(Y instanceof U1){if(Y.statusCode===404)throw new AQ(`Asset ID '${$}' does not exist`,{revertReason:"ASSET_NOT_FOUND",cause:Y});throw new AQ(`Failed to resolve asset ID '${$}': ${Y.retryable?"Network error occurred":"API request failed"}`,{revertReason:Y.retryable?"NETWORK_ERROR":"API_ERROR",cause:Y})}throw new AQ(`Failed to resolve asset ID '${$}': Unexpected error`,{revertReason:"UNKNOWN_ERROR",cause:Y instanceof Error?Y:void 0})}return{tokenAddress:J,isNativeToken:J===z6}}async approve($,J,Q=!0){if(!this.walletClient)throw new b4("Wallet client not set. Connect a wallet first.","walletClient");q$(ac,{assetId:$,amount:J,autoWait:Q});let Y=await this.getVaultAddress(),{tokenAddress:X}=await this.resolveAsset($),G=this.walletClient.account;if(!G)throw new b4("No account available in wallet client","account");let W=G.getNonce?await G.getNonce():0n,D=await this.walletClient.writeContract({address:X,abi:$w,functionName:"approve",args:[Y,J],chain:this.chain,account:G}),V={nonce:W,hash:D,status:"pending"};return await this.waitForTransaction(V,Q)}async deposit($,J,Q=!0,Y="spot"){if(!this.walletClient)throw new b4("Wallet client not set. Connect a wallet first.","walletClient");q$(sc,{assetId:$,amount:J,autoWait:Q,target:Y});let X=await this.getVaultAddress(),G=await this.getClientId(),W=Ji(G,Y),{tokenAddress:D,isNativeToken:V}=await this.resolveAsset($);if(!V){if(await this.needsApproval($,J))throw new AQ(`Approval required before deposit. Please invoke approve() first for asset ${$} (token address: ${D}).`,{revertReason:"APPROVAL_REQUIRED"})}let K=this.walletClient.account;if(!K)throw new b4("No account available in wallet client","account");let O;if(V)O=await this.walletClient.writeContract({address:X,abi:yS.vault,functionName:"depositNative",args:[K.address,W],account:K,chain:this.chain,value:J});else O=await this.walletClient.writeContract({address:X,abi:yS.vault,functionName:"depositERC20",args:[K.address,W,D,J],account:K,chain:this.chain});let N=K.getNonce?await K.getNonce():0n,M={hash:O,status:"pending",nonce:N};return await this.waitForTransaction(M,Q)}async pollWithdrawalCalldata($,J){let Q=J?.pollIntervalMs??tK$,Y=J?.timeoutMs??aK$,X=Date.now()+Y;for(;;){try{let{vaultAddress:G,calldata:W}=await this.makePublicRequest(`/api/v1/withdrawals/${$}`);if(W&&W!=="0x")return{vaultAddress:G,calldata:W}}catch(G){if(!(G instanceof U1&&(G.statusCode===404||G.statusCode===409)))throw G}if(Date.now()+Q>X)return null;await sK$(Q)}}async withdraw($,J,Q=!0,Y,X){if(!this.walletClient)throw new b4("Wallet client not set. Connect a wallet first.","walletClient");let G=this.walletClient.account;if(!G)throw new b4("No account available in wallet client","account");let W=G.address.toLowerCase(),D=typeof Y==="string"?Y:"spot",V=typeof Y==="string"?X:Y;q$(ec,{assetId:$,amount:J,destination:W,autoWait:Q,source:D});let{withdrawalIndex:K}=await this.makeAuthenticatedRequest("/api/v1/withdrawals",{method:"POST",body:JSON.stringify({assetId:$,amount:J.toString(),destination:W,source:D})});if(!Q)return{withdrawalIndex:K,status:"awaiting_proof"};let O=await this.pollWithdrawalCalldata(K,V);if(!O)return{withdrawalIndex:K,status:"awaiting_proof"};let{vaultAddress:N,calldata:M}=O,w;try{w=await this.walletClient.sendTransaction({to:N,data:M,account:G,chain:this.chain})}catch(Z){throw new AQ(`Failed to submit executeWithdrawal for withdrawal ${K}: ${Z instanceof Error?Z.message:"unknown error"}`,{cause:Z instanceof Error?Z:void 0})}let z=G.getNonce?await G.getNonce():0n,q={hash:w,status:"pending",nonce:z};return{...await this.waitForTransaction(q,Q),withdrawalIndex:K}}async retryWithdrawal($,J=!0,Q){if(!this.walletClient)throw new b4("Wallet client not set. Connect a wallet first.","walletClient");let Y=this.walletClient.account;if(!Y)throw new b4("No account available in wallet client","account");let X=await this.pollWithdrawalCalldata($,Q);if(!X)return{withdrawalIndex:$,status:"awaiting_proof"};let{vaultAddress:G,calldata:W}=X,D;try{D=await this.walletClient.sendTransaction({to:G,data:W,account:Y,chain:this.chain})}catch(N){throw new AQ(`Failed to resubmit executeWithdrawal for withdrawal ${$}: ${N instanceof Error?N.message:"unknown error"}`,{cause:N instanceof Error?N:void 0})}let V=Y.getNonce?await Y.getNonce():0n,K={hash:D,status:"pending",nonce:V};return{...await this.waitForTransaction(K,J),withdrawalIndex:$}}async getBalance($){throw new U1("getBalance() is deprecated and no longer supported. Please use profileAPI.getUserBalances() or profileAPI.getUserBalanceByAssetId() instead for balance data.",{statusCode:410})}async getAllowance($){if(!this.walletClient)throw new b4("Wallet client not set. Connect a wallet first.","walletClient");let J=await this.getVaultAddress(),Y=(await this.walletClient.getAddresses())[0];if(!Y)throw new b4("No account found in wallet client.","walletClient");let{tokenAddress:X}=await this.resolveAsset($);return await this.publicClient.readContract({address:X,abi:$w,functionName:"allowance",args:[Y,J]})}async needsApproval($,J){return await this.getAllowance($)<J}async waitForTransaction($,J=!0,Q={}){if(!J)return $;let{confirmations:Y=1,timeout:X=60000}=Q;try{let G=await this.publicClient.waitForTransactionReceipt({hash:$.hash,confirmations:Y,timeout:X});return{...$,status:G.status==="success"?"confirmed":"failed",receipt:G}}catch{return{...$,status:"failed"}}}}class cH extends $4{async submit($){return await this.makePublicRequest(D$.whitelist.submit(),{method:"POST",body:JSON.stringify($)})}}class hS extends $4{async initiateWithdrawal($){return this.makeAuthenticatedRequest(D$.withdrawals.initiate(),{method:"POST",body:JSON.stringify({assetId:$.assetId,amount:$.amount,destination:$.destination,source:$.source??"spot"})})}async getWithdrawal($){return this.makePublicRequest(D$.withdrawals.byIndex($))}async listPendingWithdrawals($){return this.makeAuthenticatedRequest(D$.withdrawals.list({page:$?.page,pageSize:$?.pageSize}))}}class iH extends $4{chain;walletClient;constructor($,J,Q){super(Q);this.chain=J,this.walletClient=$}setWalletClient($){this.walletClient=$}async authenticate($,J){if(!this.walletClient)throw new b4("Wallet client not set. Connect a wallet first.","walletClient");let Q=this.walletClient.account;if(!Q)throw new b4("No account available in wallet client","account");let Y=dM(),X={publicKey:pM(Y),privateKey:nM(Y)},G=await this.createChallenge(Q.address,$,X.publicKey),W=await this.signChallenge(G.message);return await this.verifySignature(Q.address,W,G.nonce,$,X,J)}async signChallenge($){if(!this.walletClient)throw new b4("Wallet client not set. Connect a wallet first.","walletClient");let J=this.walletClient.account;if(!J)throw new b4("No account available in wallet client","account");return await this.walletClient.signMessage({account:J,message:$})}async createChallenge($,J,Q){let Y=await this.makePublicRequest("/api/v1/auth/challenge",{method:"POST",body:JSON.stringify({address:$,clientId:J,chainId:this.chain.id,sessionPublicKey:Q})});return{nonce:Y.nonce,message:Y.message,expiresAt:Y.expiresAt}}async verifySignature($,J,Q,Y,X,G){let W=await this.makePublicRequest("/api/v1/auth/verify",{method:"POST",body:JSON.stringify({address:$,signature:J,nonce:Q,clientId:Y,chainId:this.chain.id,sessionPublicKey:X.publicKey,...G?{referralCode:G}:{}})});return{sessionPublicKey:X.publicKey,sessionPrivateKey:X.privateKey,expiresAt:W.expiresAt,user:{id:W.user.id,address:W.user.address,username:W.user.username}}}async refreshSession(){return{expiresAt:(await this.makeAuthenticatedRequest("/api/v1/auth/refresh",{method:"POST"})).expiresAt}}async revokeSession(){await this.makeAuthenticatedRequest("/api/v1/auth/revoke",{method:"POST"})}}function Qi($,J){try{new URL($)}catch(Q){throw new b4(`${J} must be a valid URL, got: ${$}`,J)}return $}class mS{auth;delegatedAgents;applications;fees;pitpass;vault;withdrawals;trading;market;marginAccounts;positions;subAccounts;faucet;whitelist;profile;orderbook;trades;ws;walletClient;publicClient;authState;network;chain;propagateSession($){this.auth.setSessionKeypair($),this.delegatedAgents.setSessionKeypair($),this.applications.setSessionKeypair($),this.fees.setSessionKeypair($),this.pitpass.setSessionKeypair($),this.vault.setSessionKeypair($),this.withdrawals.setSessionKeypair($),this.trading.setSessionKeypair($),this.market.setSessionKeypair($),this.marginAccounts.setSessionKeypair($),this.positions.setSessionKeypair($),this.subAccounts.setSessionKeypair($),this.faucet.setSessionKeypair($),this.whitelist.setSessionKeypair($),this.profile.setSessionKeypair($),this.orderbook.setSessionKeypair($),this.trades.setSessionKeypair($),this.ws.setSessionKeypair($)}setServerKey($){this.auth.setServerKey($),this.delegatedAgents.setServerKey($),this.applications.setServerKey($),this.fees.setServerKey($),this.pitpass.setServerKey($),this.vault.setServerKey($),this.withdrawals.setServerKey($),this.trading.setServerKey($),this.market.setServerKey($),this.marginAccounts.setServerKey($),this.positions.setServerKey($),this.subAccounts.setServerKey($),this.faucet.setServerKey($),this.whitelist.setServerKey($),this.profile.setServerKey($),this.orderbook.setServerKey($),this.trades.setServerKey($)}sessionFromAuthState($){return{publicKey:$.sessionPublicKey,privateKey:$.sessionPrivateKey}}constructor($){let J=["mainnet","development","staging","local"];if(!$.network||!J.includes($.network))throw new b4(`network must be one of: ${J.join(", ")}. Got: ${$.network}`,"network");if(this.network=$.network,!$.seiRpcUrl)throw new b4("seiRpcUrl is required","seiRpcUrl");try{new URL($.seiRpcUrl)}catch(W){throw new b4(`seiRpcUrl must be a valid URL, got: ${$.seiRpcUrl}`,"seiRpcUrl")}let Q=$.wsUrl?Qi($.wsUrl,"wsUrl"):EF(this.network),Y=this.network==="mainnet"?LS:BS;this.chain=Y;let X=ZS($.seiRpcUrl);this.publicClient=zS({chain:Y,transport:X});let G=$.apiUrl?Qi($.apiUrl,"apiUrl"):KV(this.network);if($.walletClient){if($.walletClient.chain?.id!==Y.id)throw new b4(`Wallet client chain mismatch. Expected ${Y.id}, got ${$.walletClient.chain?.id}`,"walletClient");this.walletClient=$.walletClient}this.applications=new CH(G),this.market=new yH(G),this.marginAccounts=new gH(G),this.positions=new mH(G),this.subAccounts=new lH(G),this.faucet=new PH(G),this.whitelist=new cH(G),this.auth=new iH(this.walletClient,this.chain,G),this.delegatedAgents=new FS(G),this.fees=new bH(G),this.pitpass=new uH(G),this.profile=new fS(G),this.vault=new nH(this.publicClient,this.walletClient,this.chain,this.applications,this.profile,G),this.withdrawals=new hS(G),this.trading=new pH(G),this.orderbook=new hH(G),this.trades=new bS(G),this.ws=IF(Q),this.ws.connect().catch(console.error)}async login($,J){if(this.authState=await this.auth.authenticate($),this.propagateSession(this.sessionFromAuthState(this.authState)),J?.connectWebSocket)await this.ws.connect();return this.authState}async loginAsDelegatedOwner($){if(!this.authState)throw new U1("No active agent session to create delegated session",{endpoint:"delegated-agents/sessions",statusCode:uS.StatusCodes.UNAUTHORIZED});let J=dM(),Q={publicKey:pM(J),privateKey:nM(J)},Y=await this.delegatedAgents.createDelegatedSession({ownerUserId:$,sessionPublicKey:Q.publicKey});return this.authState={sessionPublicKey:Q.publicKey,sessionPrivateKey:Q.privateKey,expiresAt:Y.expiresAt,user:{id:Y.ownerUserId,address:Y.agentAddress}},this.propagateSession(this.sessionFromAuthState(this.authState)),this.authState}getAuthState(){return this.authState}setAuthState($){this.authState=$,this.propagateSession(this.sessionFromAuthState($))}async logout(){if(this.authState)try{await this.auth.revokeSession()}catch($){console.warn("Failed to revoke session on logout:",$)}this.authState=void 0,this.propagateSession(void 0),this.ws.disconnect()}async refreshAuth(){if(!this.authState)throw new U1("No active session to refresh",{endpoint:"auth/refresh",statusCode:uS.StatusCodes.UNAUTHORIZED});try{let $=await this.auth.refreshSession();return this.authState={...this.authState,expiresAt:$.expiresAt},this.authState}catch($){throw this.authState=void 0,this.propagateSession(void 0),$}}isAuthenticated(){return!!this.authState}isConnected(){return!!this.walletClient&&!!this.publicClient}setWalletClient($){if($.chain?.id!==this.chain.id)throw new b4(`Wallet client chain mismatch. Expected ${this.chain.id}, got ${$.chain?.id}`,"walletClient");this.walletClient=$,this.auth.setWalletClient($),this.vault.setWalletClient($)}getAccountAddress(){if(!this.walletClient)throw new VV("Wallet client not set","walletClient");if(this.walletClient.account)return this.walletClient.account.address;throw new VV("No account available","account")}getNetwork(){return this.network}getChainId(){return this.chain.id}async waitForTransaction($,J,Q){return this.publicClient.waitForTransactionReceipt({hash:$,confirmations:J,timeout:Q})}}function lS($){return new mS($)}function K4($){if(typeof $==="string")return{address:$,type:"json-rpc"};return $}var oH=256,rH;function tH($=11){if(!rH||oH+$>512){rH="",oH=0;for(let J=0;J<256;J++)rH+=(256+Math.random()*256|0).toString(16).substring(1)}return rH.substring(oH,oH+++$)}function Xi($){let{batch:J,chain:Q,ccipRead:Y,dataSuffix:X,key:G="base",name:W="Base Client",type:D="base"}=$,V=$.experimental_blockTag??(typeof Q?.experimental_preconfirmationTime==="number"?"pending":void 0),K=Q?.blockTime??12000,O=Math.min(Math.max(Math.floor(K/2),500),4000),N=$.pollingInterval??O,M=$.cacheTime??N,w=$.account?K4($.account):void 0,{config:z,request:q,value:F}=$.transport({account:w,chain:Q,pollingInterval:N}),Z={...z,...F},E={account:w,batch:J,cacheTime:M,ccipRead:Y,chain:Q,dataSuffix:X,key:G,name:W,pollingInterval:N,request:q,transport:Z,type:D,uid:tH(),...V?{experimental_blockTag:V}:{}};function B(L){return(j)=>{let T=j(L);for(let f in E)delete T[f];let x={...L,...T};return Object.assign(x,{extend:B(x)})}}return Object.assign(E,{extend:B(E)})}var Yi={gwei:9,wei:18},Gi={ether:-9,wei:9};function aH($,J){let Q=$.toString(),Y=Q.startsWith("-");if(Y)Q=Q.slice(1);Q=Q.padStart(J,"0");let[X,G]=[Q.slice(0,Q.length-J),Q.slice(Q.length-J)];return G=G.replace(/(0+)$/,""),`${Y?"-":""}${X||"0"}${G?`.${G}`:""}`}function I6($,J="wei"){return aH($,Gi[J])}var dS="2.53.1";var pS={getDocsUrl:({docsBaseUrl:$,docsPath:J="",docsSlug:Q})=>J?`${$??"https://viem.sh"}${J}${Q?`#${Q}`:""}`:void 0,version:`viem@${dS}`};class l extends Error{constructor($,J={}){let Q=(()=>{if(J.cause instanceof l)return J.cause.details;if(J.cause?.message)return J.cause.message;return J.details})(),Y=(()=>{if(J.cause instanceof l)return J.cause.docsPath||J.docsPath;return J.docsPath})(),X=pS.getDocsUrl?.({...J,docsPath:Y}),G=[$||"An error occurred.","",...J.metaMessages?[...J.metaMessages,""]:[],...X?[`Docs: ${X}`]:[],...Q?[`Details: ${Q}`]:[],...pS.version?[`Version: ${pS.version}`]:[]].join(`
147
147
  `);super(G,J.cause?{cause:J.cause}:void 0);Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=Q,this.docsPath=Y,this.metaMessages=J.metaMessages,this.name=J.name??this.name,this.shortMessage=$,this.version=dS}walk($){return Wi(this,$)}}function Wi($,J){if(J?.($))return $;if($&&typeof $==="object"&&"cause"in $&&$.cause!==void 0)return Wi($.cause,J);return J?null:$}class NK extends l{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class c9 extends l{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class nS extends l{constructor({maxPriorityFeePerGas:$}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${I6($)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}class WX extends l{constructor({cause:$,message:J}={}){let Q=J?.replace("execution reverted: ","")?.replace("execution reverted","");super(`Execution reverted ${Q?`with reason: ${Q}`:"for an unknown reason"}.`,{cause:$,name:"ExecutionRevertedError"})}}Object.defineProperty(WX,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(WX,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted|gas required exceeds allowance/});class a0 extends l{constructor({cause:$,maxFeePerGas:J}={}){super(`The fee cap (\`maxFeePerGas\`${J?` = ${I6(J)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:$,name:"FeeCapTooHighError"})}}Object.defineProperty(a0,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});class MK extends l{constructor({cause:$,maxFeePerGas:J}={}){super(`The fee cap (\`maxFeePerGas\`${J?` = ${I6(J)}`:""} gwei) cannot be lower than the block base fee.`,{cause:$,name:"FeeCapTooLowError"})}}Object.defineProperty(MK,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/});class wK extends l{constructor({cause:$,nonce:J}={}){super(`Nonce provided for the transaction ${J?`(${J}) `:""}is higher than the next one expected.`,{cause:$,name:"NonceTooHighError"})}}Object.defineProperty(wK,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});class HK extends l{constructor({cause:$,nonce:J}={}){super([`Nonce provided for the transaction ${J?`(${J}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0xmonaco/mcp-server",
3
- "version": "1.0.7",
3
+ "version": "1.0.15",
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": "1.0.7",
29
- "@0xmonaco/types": "1.0.7",
28
+ "@0xmonaco/core": "1.0.15",
29
+ "@0xmonaco/types": "1.0.15",
30
30
  "@modelcontextprotocol/sdk": "^1.29.0",
31
31
  "node-fetch": "^3.3.2",
32
32
  "viem": "^2.53.1",